text
stringlengths
2
1.04M
meta
dict
from urllib3 import HTTPConnectionPool, HTTPSConnectionPool from urllib3.poolmanager import proxy_from_url from urllib3.exceptions import ( MaxRetryError, ProxyError, ReadTimeoutError, SSLError, ProtocolError, ) from urllib3.response import httplib from urllib3.util.ssl_ import HAS_SNI from urllib3.util.timeout import Timeout from urllib3.util.retry import Retry from urllib3._collections import HTTPHeaderDict from dummyserver.testcase import SocketDummyServerTestCase from dummyserver.server import ( DEFAULT_CERTS, DEFAULT_CA, get_unreachable_address) from .. import onlyPy3, LogRecorder from nose.plugins.skip import SkipTest try: from mimetools import Message as MimeToolMessage except ImportError: class MimeToolMessage(object): pass from threading import Event import socket import ssl class TestCookies(SocketDummyServerTestCase): def test_multi_setcookie(self): def multicookie_response_handler(listener): sock = listener.accept()[0] buf = b'' while not buf.endswith(b'\r\n\r\n'): buf += sock.recv(65536) sock.send(b'HTTP/1.1 200 OK\r\n' b'Set-Cookie: foo=1\r\n' b'Set-Cookie: bar=1\r\n' b'\r\n') sock.close() self._start_server(multicookie_response_handler) pool = HTTPConnectionPool(self.host, self.port) r = pool.request('GET', '/', retries=0) self.assertEqual(r.headers, {'set-cookie': 'foo=1, bar=1'}) self.assertEqual(r.headers.getlist('set-cookie'), ['foo=1', 'bar=1']) class TestSNI(SocketDummyServerTestCase): def test_hostname_in_first_request_packet(self): if not HAS_SNI: raise SkipTest('SNI-support not available') done_receiving = Event() self.buf = b'' def socket_handler(listener): sock = listener.accept()[0] self.buf = sock.recv(65536) # We only accept one packet done_receiving.set() # let the test know it can proceed sock.close() self._start_server(socket_handler) pool = HTTPSConnectionPool(self.host, self.port) try: pool.request('GET', '/', retries=0) except SSLError: # We are violating the protocol pass done_receiving.wait() self.assertTrue(self.host.encode() in self.buf, "missing hostname in SSL handshake") class TestSocketClosing(SocketDummyServerTestCase): def test_recovery_when_server_closes_connection(self): # Does the pool work seamlessly if an open connection in the # connection pool gets hung up on by the server, then reaches # the front of the queue again? done_closing = Event() def socket_handler(listener): for i in 0, 1: sock = listener.accept()[0] buf = b'' while not buf.endswith(b'\r\n\r\n'): buf = sock.recv(65536) body = 'Response %d' % i sock.send(('HTTP/1.1 200 OK\r\n' 'Content-Type: text/plain\r\n' 'Content-Length: %d\r\n' '\r\n' '%s' % (len(body), body)).encode('utf-8')) sock.close() # simulate a server timing out, closing socket done_closing.set() # let the test know it can proceed self._start_server(socket_handler) pool = HTTPConnectionPool(self.host, self.port) response = pool.request('GET', '/', retries=0) self.assertEqual(response.status, 200) self.assertEqual(response.data, b'Response 0') done_closing.wait() # wait until the socket in our pool gets closed response = pool.request('GET', '/', retries=0) self.assertEqual(response.status, 200) self.assertEqual(response.data, b'Response 1') def test_connection_refused(self): # Does the pool retry if there is no listener on the port? host, port = get_unreachable_address() http = HTTPConnectionPool(host, port, maxsize=3, block=True) self.assertRaises(MaxRetryError, http.request, 'GET', '/', retries=0, release_conn=False) self.assertEqual(http.pool.qsize(), http.pool.maxsize) def test_connection_read_timeout(self): timed_out = Event() def socket_handler(listener): sock = listener.accept()[0] while not sock.recv(65536).endswith(b'\r\n\r\n'): pass timed_out.wait() sock.close() self._start_server(socket_handler) http = HTTPConnectionPool(self.host, self.port, timeout=0.001, retries=False, maxsize=3, block=True) try: self.assertRaises(ReadTimeoutError, http.request, 'GET', '/', release_conn=False) finally: timed_out.set() self.assertEqual(http.pool.qsize(), http.pool.maxsize) def test_https_connection_read_timeout(self): """ Handshake timeouts should fail with a Timeout""" timed_out = Event() def socket_handler(listener): sock = listener.accept()[0] while not sock.recv(65536): pass timed_out.wait() sock.close() self._start_server(socket_handler) pool = HTTPSConnectionPool(self.host, self.port, timeout=0.001, retries=False) try: self.assertRaises(ReadTimeoutError, pool.request, 'GET', '/') finally: timed_out.set() def test_timeout_errors_cause_retries(self): def socket_handler(listener): sock_timeout = listener.accept()[0] # Wait for a second request before closing the first socket. sock = listener.accept()[0] sock_timeout.close() # Second request. buf = b'' while not buf.endswith(b'\r\n\r\n'): buf += sock.recv(65536) # Now respond immediately. body = 'Response 2' sock.send(('HTTP/1.1 200 OK\r\n' 'Content-Type: text/plain\r\n' 'Content-Length: %d\r\n' '\r\n' '%s' % (len(body), body)).encode('utf-8')) sock.close() # In situations where the main thread throws an exception, the server # thread can hang on an accept() call. This ensures everything times # out within 1 second. This should be long enough for any socket # operations in the test suite to complete default_timeout = socket.getdefaulttimeout() socket.setdefaulttimeout(1) try: self._start_server(socket_handler) t = Timeout(connect=0.001, read=0.001) pool = HTTPConnectionPool(self.host, self.port, timeout=t) response = pool.request('GET', '/', retries=1) self.assertEqual(response.status, 200) self.assertEqual(response.data, b'Response 2') finally: socket.setdefaulttimeout(default_timeout) def test_delayed_body_read_timeout(self): timed_out = Event() def socket_handler(listener): sock = listener.accept()[0] buf = b'' body = 'Hi' while not buf.endswith(b'\r\n\r\n'): buf = sock.recv(65536) sock.send(('HTTP/1.1 200 OK\r\n' 'Content-Type: text/plain\r\n' 'Content-Length: %d\r\n' '\r\n' % len(body)).encode('utf-8')) timed_out.wait() sock.send(body.encode('utf-8')) sock.close() self._start_server(socket_handler) pool = HTTPConnectionPool(self.host, self.port) response = pool.urlopen('GET', '/', retries=0, preload_content=False, timeout=Timeout(connect=1, read=0.001)) try: self.assertRaises(ReadTimeoutError, response.read) finally: timed_out.set() def test_incomplete_response(self): body = 'Response' partial_body = body[:2] def socket_handler(listener): sock = listener.accept()[0] # Consume request buf = b'' while not buf.endswith(b'\r\n\r\n'): buf = sock.recv(65536) # Send partial response and close socket. sock.send(( 'HTTP/1.1 200 OK\r\n' 'Content-Type: text/plain\r\n' 'Content-Length: %d\r\n' '\r\n' '%s' % (len(body), partial_body)).encode('utf-8') ) sock.close() self._start_server(socket_handler) pool = HTTPConnectionPool(self.host, self.port) response = pool.request('GET', '/', retries=0, preload_content=False) self.assertRaises(ProtocolError, response.read) def test_retry_weird_http_version(self): """ Retry class should handle httplib.BadStatusLine errors properly """ def socket_handler(listener): sock = listener.accept()[0] # First request. # Pause before responding so the first request times out. buf = b'' while not buf.endswith(b'\r\n\r\n'): buf += sock.recv(65536) # send unknown http protocol body = "bad http 0.5 response" sock.send(('HTTP/0.5 200 OK\r\n' 'Content-Type: text/plain\r\n' 'Content-Length: %d\r\n' '\r\n' '%s' % (len(body), body)).encode('utf-8')) sock.close() # Second request. sock = listener.accept()[0] buf = b'' while not buf.endswith(b'\r\n\r\n'): buf += sock.recv(65536) # Now respond immediately. sock.send(('HTTP/1.1 200 OK\r\n' 'Content-Type: text/plain\r\n' 'Content-Length: %d\r\n' '\r\n' 'foo' % (len('foo'))).encode('utf-8')) sock.close() # Close the socket. self._start_server(socket_handler) pool = HTTPConnectionPool(self.host, self.port) retry = Retry(read=1) response = pool.request('GET', '/', retries=retry) self.assertEqual(response.status, 200) self.assertEqual(response.data, b'foo') def test_connection_cleanup_on_read_timeout(self): timed_out = Event() def socket_handler(listener): sock = listener.accept()[0] buf = b'' body = 'Hi' while not buf.endswith(b'\r\n\r\n'): buf = sock.recv(65536) sock.send(('HTTP/1.1 200 OK\r\n' 'Content-Type: text/plain\r\n' 'Content-Length: %d\r\n' '\r\n' % len(body)).encode('utf-8')) timed_out.wait() sock.close() self._start_server(socket_handler) with HTTPConnectionPool(self.host, self.port) as pool: poolsize = pool.pool.qsize() response = pool.urlopen('GET', '/', retries=0, preload_content=False, timeout=Timeout(connect=1, read=0.001)) try: self.assertRaises(ReadTimeoutError, response.read) self.assertEqual(poolsize, pool.pool.qsize()) finally: timed_out.set() def test_connection_cleanup_on_protocol_error_during_read(self): body = 'Response' partial_body = body[:2] def socket_handler(listener): sock = listener.accept()[0] # Consume request buf = b'' while not buf.endswith(b'\r\n\r\n'): buf = sock.recv(65536) # Send partial response and close socket. sock.send(( 'HTTP/1.1 200 OK\r\n' 'Content-Type: text/plain\r\n' 'Content-Length: %d\r\n' '\r\n' '%s' % (len(body), partial_body)).encode('utf-8') ) sock.close() self._start_server(socket_handler) with HTTPConnectionPool(self.host, self.port) as pool: poolsize = pool.pool.qsize() response = pool.request('GET', '/', retries=0, preload_content=False) self.assertRaises(ProtocolError, response.read) self.assertEqual(poolsize, pool.pool.qsize()) class TestProxyManager(SocketDummyServerTestCase): def test_simple(self): def echo_socket_handler(listener): sock = listener.accept()[0] buf = b'' while not buf.endswith(b'\r\n\r\n'): buf += sock.recv(65536) sock.send(('HTTP/1.1 200 OK\r\n' 'Content-Type: text/plain\r\n' 'Content-Length: %d\r\n' '\r\n' '%s' % (len(buf), buf.decode('utf-8'))).encode('utf-8')) sock.close() self._start_server(echo_socket_handler) base_url = 'http://%s:%d' % (self.host, self.port) proxy = proxy_from_url(base_url) r = proxy.request('GET', 'http://google.com/') self.assertEqual(r.status, 200) # FIXME: The order of the headers is not predictable right now. We # should fix that someday (maybe when we migrate to # OrderedDict/MultiDict). self.assertEqual(sorted(r.data.split(b'\r\n')), sorted([ b'GET http://google.com/ HTTP/1.1', b'Host: google.com', b'Accept-Encoding: identity', b'Accept: */*', b'', b'', ])) def test_headers(self): def echo_socket_handler(listener): sock = listener.accept()[0] buf = b'' while not buf.endswith(b'\r\n\r\n'): buf += sock.recv(65536) sock.send(('HTTP/1.1 200 OK\r\n' 'Content-Type: text/plain\r\n' 'Content-Length: %d\r\n' '\r\n' '%s' % (len(buf), buf.decode('utf-8'))).encode('utf-8')) sock.close() self._start_server(echo_socket_handler) base_url = 'http://%s:%d' % (self.host, self.port) # Define some proxy headers. proxy_headers = HTTPHeaderDict({'For The Proxy': 'YEAH!'}) proxy = proxy_from_url(base_url, proxy_headers=proxy_headers) conn = proxy.connection_from_url('http://www.google.com/') r = conn.urlopen('GET', 'http://www.google.com/', assert_same_host=False) self.assertEqual(r.status, 200) # FIXME: The order of the headers is not predictable right now. We # should fix that someday (maybe when we migrate to # OrderedDict/MultiDict). self.assertTrue(b'For The Proxy: YEAH!\r\n' in r.data) def test_retries(self): def echo_socket_handler(listener): sock = listener.accept()[0] # First request, which should fail sock.close() # Second request sock = listener.accept()[0] buf = b'' while not buf.endswith(b'\r\n\r\n'): buf += sock.recv(65536) sock.send(('HTTP/1.1 200 OK\r\n' 'Content-Type: text/plain\r\n' 'Content-Length: %d\r\n' '\r\n' '%s' % (len(buf), buf.decode('utf-8'))).encode('utf-8')) sock.close() self._start_server(echo_socket_handler) base_url = 'http://%s:%d' % (self.host, self.port) proxy = proxy_from_url(base_url) conn = proxy.connection_from_url('http://www.google.com') r = conn.urlopen('GET', 'http://www.google.com', assert_same_host=False, retries=1) self.assertEqual(r.status, 200) self.assertRaises(ProxyError, conn.urlopen, 'GET', 'http://www.google.com', assert_same_host=False, retries=False) def test_connect_reconn(self): def proxy_ssl_one(listener): sock = listener.accept()[0] buf = b'' while not buf.endswith(b'\r\n\r\n'): buf += sock.recv(65536) s = buf.decode('utf-8') if not s.startswith('CONNECT '): sock.send(('HTTP/1.1 405 Method not allowed\r\n' 'Allow: CONNECT\r\n\r\n').encode('utf-8')) sock.close() return if not s.startswith('CONNECT %s:443' % (self.host,)): sock.send(('HTTP/1.1 403 Forbidden\r\n\r\n').encode('utf-8')) sock.close() return sock.send(('HTTP/1.1 200 Connection Established\r\n\r\n').encode('utf-8')) ssl_sock = ssl.wrap_socket(sock, server_side=True, keyfile=DEFAULT_CERTS['keyfile'], certfile=DEFAULT_CERTS['certfile'], ca_certs=DEFAULT_CA) buf = b'' while not buf.endswith(b'\r\n\r\n'): buf += ssl_sock.recv(65536) ssl_sock.send(('HTTP/1.1 200 OK\r\n' 'Content-Type: text/plain\r\n' 'Content-Length: 2\r\n' 'Connection: close\r\n' '\r\n' 'Hi').encode('utf-8')) ssl_sock.close() def echo_socket_handler(listener): proxy_ssl_one(listener) proxy_ssl_one(listener) self._start_server(echo_socket_handler) base_url = 'http://%s:%d' % (self.host, self.port) proxy = proxy_from_url(base_url) url = 'https://{0}'.format(self.host) conn = proxy.connection_from_url(url) r = conn.urlopen('GET', url, retries=0) self.assertEqual(r.status, 200) r = conn.urlopen('GET', url, retries=0) self.assertEqual(r.status, 200) class TestSSL(SocketDummyServerTestCase): def test_ssl_failure_midway_through_conn(self): def socket_handler(listener): sock = listener.accept()[0] sock2 = sock.dup() ssl_sock = ssl.wrap_socket(sock, server_side=True, keyfile=DEFAULT_CERTS['keyfile'], certfile=DEFAULT_CERTS['certfile'], ca_certs=DEFAULT_CA) buf = b'' while not buf.endswith(b'\r\n\r\n'): buf += ssl_sock.recv(65536) # Deliberately send from the non-SSL socket. sock2.send(( 'HTTP/1.1 200 OK\r\n' 'Content-Type: text/plain\r\n' 'Content-Length: 2\r\n' '\r\n' 'Hi').encode('utf-8')) sock2.close() ssl_sock.close() self._start_server(socket_handler) pool = HTTPSConnectionPool(self.host, self.port) self.assertRaises(SSLError, pool.request, 'GET', '/', retries=0) def test_ssl_read_timeout(self): timed_out = Event() def socket_handler(listener): sock = listener.accept()[0] ssl_sock = ssl.wrap_socket(sock, server_side=True, keyfile=DEFAULT_CERTS['keyfile'], certfile=DEFAULT_CERTS['certfile'], ca_certs=DEFAULT_CA) buf = b'' while not buf.endswith(b'\r\n\r\n'): buf += ssl_sock.recv(65536) # Send incomplete message (note Content-Length) ssl_sock.send(( 'HTTP/1.1 200 OK\r\n' 'Content-Type: text/plain\r\n' 'Content-Length: 10\r\n' '\r\n' 'Hi-').encode('utf-8')) timed_out.wait() sock.close() ssl_sock.close() self._start_server(socket_handler) pool = HTTPSConnectionPool(self.host, self.port) response = pool.urlopen('GET', '/', retries=0, preload_content=False, timeout=Timeout(connect=1, read=0.001)) try: self.assertRaises(ReadTimeoutError, response.read) finally: timed_out.set() def test_ssl_failed_fingerprint_verification(self): def socket_handler(listener): for i in range(2): sock = listener.accept()[0] ssl_sock = ssl.wrap_socket(sock, server_side=True, keyfile=DEFAULT_CERTS['keyfile'], certfile=DEFAULT_CERTS['certfile'], ca_certs=DEFAULT_CA) ssl_sock.send(b'HTTP/1.1 200 OK\r\n' b'Content-Type: text/plain\r\n' b'Content-Length: 5\r\n\r\n' b'Hello') ssl_sock.close() sock.close() self._start_server(socket_handler) # GitHub's fingerprint. Valid, but not matching. fingerprint = ('A0:C4:A7:46:00:ED:A7:2D:C0:BE:CB' ':9A:8C:B6:07:CA:58:EE:74:5E') def request(): try: pool = HTTPSConnectionPool(self.host, self.port, assert_fingerprint=fingerprint) response = pool.urlopen('GET', '/', preload_content=False, timeout=Timeout(connect=1, read=0.001)) response.read() finally: pool.close() self.assertRaises(SSLError, request) # Should not hang, see https://github.com/shazow/urllib3/issues/529 self.assertRaises(SSLError, request) def consume_socket(sock, chunks=65536): while not sock.recv(chunks).endswith(b'\r\n\r\n'): pass def create_response_handler(response, num=1): def socket_handler(listener): for _ in range(num): sock = listener.accept()[0] consume_socket(sock) sock.send(response) sock.close() return socket_handler class TestErrorWrapping(SocketDummyServerTestCase): def test_bad_statusline(self): handler = create_response_handler( b'HTTP/1.1 Omg What Is This?\r\n' b'Content-Length: 0\r\n' b'\r\n' ) self._start_server(handler) pool = HTTPConnectionPool(self.host, self.port, retries=False) self.assertRaises(ProtocolError, pool.request, 'GET', '/') def test_unknown_protocol(self): handler = create_response_handler( b'HTTP/1000 200 OK\r\n' b'Content-Length: 0\r\n' b'\r\n' ) self._start_server(handler) pool = HTTPConnectionPool(self.host, self.port, retries=False) self.assertRaises(ProtocolError, pool.request, 'GET', '/') class TestHeaders(SocketDummyServerTestCase): @onlyPy3 def test_httplib_headers_case_insensitive(self): handler = create_response_handler( b'HTTP/1.1 200 OK\r\n' b'Content-Length: 0\r\n' b'Content-type: text/plain\r\n' b'\r\n' ) self._start_server(handler) pool = HTTPConnectionPool(self.host, self.port, retries=False) HEADERS = {'Content-Length': '0', 'Content-type': 'text/plain'} r = pool.request('GET', '/') self.assertEqual(HEADERS, dict(r.headers.items())) # to preserve case sensitivity def test_headers_are_sent_with_the_original_case(self): headers = {'foo': 'bar', 'bAz': 'quux'} parsed_headers = {} def socket_handler(listener): sock = listener.accept()[0] buf = b'' while not buf.endswith(b'\r\n\r\n'): buf += sock.recv(65536) headers_list = [header for header in buf.split(b'\r\n')[1:] if header] for header in headers_list: (key, value) = header.split(b': ') parsed_headers[key.decode()] = value.decode() # Send incomplete message (note Content-Length) sock.send(( 'HTTP/1.1 204 No Content\r\n' 'Content-Length: 0\r\n' '\r\n').encode('utf-8')) sock.close() self._start_server(socket_handler) expected_headers = {'Accept-Encoding': 'identity', 'Host': '{0}:{1}'.format(self.host, self.port)} expected_headers.update(headers) pool = HTTPConnectionPool(self.host, self.port, retries=False) pool.request('GET', '/', headers=HTTPHeaderDict(headers)) self.assertEqual(expected_headers, parsed_headers) class TestBrokenHeaders(SocketDummyServerTestCase): def setUp(self): if issubclass(httplib.HTTPMessage, MimeToolMessage): raise SkipTest('Header parsing errors not available') super(TestBrokenHeaders, self).setUp() def _test_broken_header_parsing(self, headers): handler = create_response_handler(( b'HTTP/1.1 200 OK\r\n' b'Content-Length: 0\r\n' b'Content-type: text/plain\r\n' ) + b'\r\n'.join(headers) + b'\r\n' ) self._start_server(handler) pool = HTTPConnectionPool(self.host, self.port, retries=False) with LogRecorder() as logs: pool.request('GET', '/') for record in logs: if 'Failed to parse headers' in record.msg and \ pool._absolute_url('/') == record.args[0]: return self.fail('Missing log about unparsed headers') def test_header_without_name(self): self._test_broken_header_parsing([ b': Value\r\n', b'Another: Header\r\n', ]) def test_header_without_name_or_value(self): self._test_broken_header_parsing([ b':\r\n', b'Another: Header\r\n', ]) def test_header_without_colon_or_value(self): self._test_broken_header_parsing([ b'Broken Header', b'Another: Header', ]) class TestHEAD(SocketDummyServerTestCase): def test_chunked_head_response_does_not_hang(self): handler = create_response_handler( b'HTTP/1.1 200 OK\r\n' b'Transfer-Encoding: chunked\r\n' b'Content-type: text/plain\r\n' b'\r\n' ) self._start_server(handler) pool = HTTPConnectionPool(self.host, self.port, retries=False) r = pool.request('HEAD', '/', timeout=1, preload_content=False) # stream will use the read_chunked method here. self.assertEqual([], list(r.stream())) def test_empty_head_response_does_not_hang(self): handler = create_response_handler( b'HTTP/1.1 200 OK\r\n' b'Content-Length: 256\r\n' b'Content-type: text/plain\r\n' b'\r\n' ) self._start_server(handler) pool = HTTPConnectionPool(self.host, self.port, retries=False) r = pool.request('HEAD', '/', timeout=1, preload_content=False) # stream will use the read method here. self.assertEqual([], list(r.stream()))
{ "content_hash": "f0446a81f5cd2d794e793ee19865ecec", "timestamp": "", "source": "github", "line_count": 792, "max_line_length": 108, "avg_line_length": 35.39646464646464, "alnum_prop": 0.5239708924876935, "repo_name": "luca3m/urllib3", "id": "5af00e0bf5d3e3c89c7eab3d4f2531c1853b9922", "size": "28156", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "test/with_dummyserver/test_socketlevel.py", "mode": "33188", "license": "mit", "language": [ { "name": "Makefile", "bytes": "906" }, { "name": "Python", "bytes": "416214" }, { "name": "Shell", "bytes": "1036" } ], "symlink_target": "" }
/* As a special exception, if you link this library with files compiled with GCC to produce an executable, this does not cause the resulting executable to be covered by the GNU General Public License. This exception does not however invalidate any other reasons why the executable file might be covered by the GNU General Public License. */ #include "objc/thr.h" #include "objc/runtime.h" #include <pthread.h> /* Key structure for maintaining thread specific storage */ static pthread_key_t _objc_thread_storage; static pthread_attr_t _objc_thread_attribs; /* Backend initialization functions */ /* Initialize the threads subsystem. */ int __objc_init_thread_system(void) { /* Initialize the thread storage key */ if (pthread_key_create(&_objc_thread_storage, NULL) == 0) { /* * The normal default detach state for threads is PTHREAD_CREATE_JOINABLE * which causes threads to not die when you think they should. */ if (pthread_attr_init(&_objc_thread_attribs) == 0) { if (pthread_attr_setdetachstate(&_objc_thread_attribs, PTHREAD_CREATE_DETACHED) == 0) return 0; } } return -1; } /* Close the threads subsystem. */ int __objc_close_thread_system(void) { if (pthread_key_delete(_objc_thread_storage) == 0) { if (pthread_attr_destroy(&_objc_thread_attribs) == 0) return 0; } return -1; } /* Backend thread functions */ /* Create a new thread of execution. */ objc_thread_t __objc_thread_detach(void (*func)(void *arg), void *arg) { objc_thread_t thread_id; pthread_t new_thread_handle; if (!(pthread_create(&new_thread_handle, &_objc_thread_attribs, (void *)func, arg))) thread_id = *(objc_thread_t *)&new_thread_handle; else thread_id = NULL; return thread_id; } /* Set the current thread's priority. * * Be aware that the default schedpolicy often disallows thread priorities. */ int __objc_thread_set_priority(int priority) { pthread_t thread_id = pthread_self(); int policy; struct sched_param params; int priority_min, priority_max; if (pthread_getschedparam(thread_id, &policy, &params) == 0) { if ((priority_max = sched_get_priority_max(policy)) != 0) return -1; if ((priority_min = sched_get_priority_min(policy)) != 0) return -1; if (priority > priority_max) priority = priority_max; else if (priority < priority_min) priority = priority_min; params.sched_priority = priority; /* * The solaris 7 and several other man pages incorrectly state that * this should be a pointer to policy but pthread.h is universally * at odds with this. */ if (pthread_setschedparam(thread_id, policy, &params) == 0) return 0; } return -1; } /* Return the current thread's priority. */ int __objc_thread_get_priority(void) { int policy; struct sched_param params; if (pthread_getschedparam(pthread_self(), &policy, &params) == 0) return params.sched_priority; else return -1; } /* Yield our process time to another thread. */ void __objc_thread_yield(void) { sched_yield(); } /* Terminate the current thread. */ int __objc_thread_exit(void) { /* exit the thread */ pthread_exit(&__objc_thread_exit_status); /* Failed if we reached here */ return -1; } /* Returns an integer value which uniquely describes a thread. */ objc_thread_t __objc_thread_id(void) { pthread_t self = pthread_self(); return *(objc_thread_t *)&self; } /* Sets the thread's local storage pointer. */ int __objc_thread_set_data(void *value) { if (pthread_setspecific(_objc_thread_storage, value) == 0) return 0; else return -1; } /* Returns the thread's local storage pointer. */ void * __objc_thread_get_data(void) { return pthread_getspecific(_objc_thread_storage); } /* Backend mutex functions */ /* Allocate a mutex. */ int __objc_mutex_allocate(objc_mutex_t mutex) { mutex->backend = objc_malloc(sizeof(pthread_mutex_t)); if (pthread_mutex_init((pthread_mutex_t *)mutex->backend, NULL)) { objc_free(mutex->backend); mutex->backend = NULL; return -1; } return 0; } /* Deallocate a mutex. */ int __objc_mutex_deallocate(objc_mutex_t mutex) { int count = 1; /* * Posix Threads specifically require that the thread be unlocked for * pthread_mutex_destroy to work. */ while (count) { if ((count = pthread_mutex_unlock((pthread_mutex_t*)mutex->backend)) < 0) return -1; } if (pthread_mutex_destroy((pthread_mutex_t *)mutex->backend)) return -1; objc_free(mutex->backend); mutex->backend = NULL; return 0; } /* Grab a lock on a mutex. */ int __objc_mutex_lock(objc_mutex_t mutex) { if (pthread_mutex_lock((pthread_mutex_t *)mutex->backend) == 0) return 0; else return -1; } /* Try to grab a lock on a mutex. */ int __objc_mutex_trylock(objc_mutex_t mutex) { if (pthread_mutex_trylock((pthread_mutex_t *)mutex->backend) == 0) return 0; else return -1; } /* Unlock the mutex */ int __objc_mutex_unlock(objc_mutex_t mutex) { if (pthread_mutex_unlock((pthread_mutex_t *)mutex->backend) == 0) return 0; else return -1; } /* Backend condition mutex functions */ /* Allocate a condition. */ int __objc_condition_allocate(objc_condition_t condition) { condition->backend = objc_malloc(sizeof(pthread_cond_t)); if (pthread_cond_init((pthread_cond_t *)condition->backend, NULL)) { objc_free(condition->backend); condition->backend = NULL; return -1; } return 0; } /* Deallocate a condition. */ int __objc_condition_deallocate(objc_condition_t condition) { if (pthread_cond_destroy((pthread_cond_t *)condition->backend)) return -1; objc_free(condition->backend); condition->backend = NULL; return 0; } /* Wait on the condition */ int __objc_condition_wait(objc_condition_t condition, objc_mutex_t mutex) { if (pthread_cond_wait((pthread_cond_t *)condition->backend, (pthread_mutex_t *)mutex->backend) == 0) return 0; else return -1; } /* Wake up all threads waiting on this condition. */ int __objc_condition_broadcast(objc_condition_t condition) { if (pthread_cond_broadcast((pthread_cond_t *)condition->backend) == 0) return 0; else return -1; } /* Wake up one thread waiting on this condition. */ int __objc_condition_signal(objc_condition_t condition) { if (pthread_cond_signal((pthread_cond_t *)condition->backend) == 0) return 0; else return -1; }
{ "content_hash": "7f2482ac15012de9268b36050e48971f", "timestamp": "", "source": "github", "line_count": 298, "max_line_length": 79, "avg_line_length": 22.33221476510067, "alnum_prop": 0.6462809917355372, "repo_name": "shaotuanchen/sunflower_exp", "id": "f7010833df8f3d0ddf6e511bedd4e0af0219eef8", "size": "7675", "binary": false, "copies": "11", "ref": "refs/heads/master", "path": "tools/source/gcc-4.2.4/libobjc/thr-posix.c", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "459993" }, { "name": "Awk", "bytes": "6562" }, { "name": "Batchfile", "bytes": "9028" }, { "name": "C", "bytes": "50326113" }, { "name": "C++", "bytes": "2040239" }, { "name": "CSS", "bytes": "2355" }, { "name": "Clarion", "bytes": "2484" }, { "name": "Coq", "bytes": "61440" }, { "name": "DIGITAL Command Language", "bytes": "69150" }, { "name": "Emacs Lisp", "bytes": "186910" }, { "name": "Fortran", "bytes": "5364" }, { "name": "HTML", "bytes": "2171356" }, { "name": "JavaScript", "bytes": "27164" }, { "name": "Logos", "bytes": "159114" }, { "name": "M", "bytes": "109006" }, { "name": "M4", "bytes": "100614" }, { "name": "Makefile", "bytes": "5409865" }, { "name": "Mercury", "bytes": "702" }, { "name": "Module Management System", "bytes": "56956" }, { "name": "OCaml", "bytes": "253115" }, { "name": "Objective-C", "bytes": "57800" }, { "name": "Papyrus", "bytes": "3298" }, { "name": "Perl", "bytes": "70992" }, { "name": "Perl 6", "bytes": "693" }, { "name": "PostScript", "bytes": "3440120" }, { "name": "Python", "bytes": "40729" }, { "name": "Redcode", "bytes": "1140" }, { "name": "Roff", "bytes": "3794721" }, { "name": "SAS", "bytes": "56770" }, { "name": "SRecode Template", "bytes": "540157" }, { "name": "Shell", "bytes": "1560436" }, { "name": "Smalltalk", "bytes": "10124" }, { "name": "Standard ML", "bytes": "1212" }, { "name": "TeX", "bytes": "385584" }, { "name": "WebAssembly", "bytes": "52904" }, { "name": "Yacc", "bytes": "510934" } ], "symlink_target": "" }
/* * Localized default methods for the jQuery validation plugin. * Locale: FI */ $.extend($.validator.methods, { date: function(value, element) { return this.optional(element) || /^\d{1,2}\.\d{1,2}\.\d{4}$/.test(value); }, number: function(value, element) { return this.optional(element) || /^-?(?:\d+)(?:,\d+)?$/.test(value); } });
{ "content_hash": "27484c6aacae163a2b18b1bf5e5dbd3d", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 75, "avg_line_length": 29.666666666666668, "alnum_prop": 0.5870786516853933, "repo_name": "vuonghuynhthanhtu/administrator.lacasa.com", "id": "f1b07faf1a5c3e83d92564b7d3e89c69353e2855", "size": "356", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "application/libraries/javascript/js/jquery-validation-1.13.1/src/localization/methods_fi.js", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "1112980" }, { "name": "CoffeeScript", "bytes": "32734" }, { "name": "HTML", "bytes": "9059672" }, { "name": "JavaScript", "bytes": "5034387" }, { "name": "PHP", "bytes": "3633847" }, { "name": "Python", "bytes": "3336" }, { "name": "Ruby", "bytes": "592" }, { "name": "Shell", "bytes": "198" } ], "symlink_target": "" }
package com.shejiaomao.weibo.service.listener; import com.shejiaomao.maobo.R; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.Spinner; import android.widget.TextView; import com.cattong.commons.ServiceProvider; import com.shejiaomao.weibo.activity.AddAccountActivity; public class AddAccountCustomKeyClickListener implements OnClickListener { private AddAccountActivity context; private LinearLayout llXAuthForm; private LinearLayout llOAuthIntro; private EditText etUsername; private EditText etPassword; private TextView tvOAuthIntro; private CheckBox cbUseProxy; private EditText etRestProxy; private EditText etSearchProxy; private CheckBox cbFollowOffical; private CheckBox cbMakeDefault; private Spinner spConfigApp; private Button btnAuthorize; public AddAccountCustomKeyClickListener(AddAccountActivity context) { this.context = context; llXAuthForm = (LinearLayout) context.findViewById(R.id.llXAuthForm); etUsername = (EditText) context.findViewById(R.id.etUsername); etPassword = (EditText) context.findViewById(R.id.etPassword); llOAuthIntro = (LinearLayout) context.findViewById(R.id.llOAuthIntro); tvOAuthIntro = (TextView) context.findViewById(R.id.tvOAuthIntro); cbUseProxy = (CheckBox) context.findViewById(R.id.cbUseApiProxy); etRestProxy = (EditText) context.findViewById(R.id.etRestProxy); etSearchProxy = (EditText) context.findViewById(R.id.etSearchProxy); cbFollowOffical = (CheckBox) context.findViewById(R.id.cbFollowOffical); cbMakeDefault = (CheckBox) context.findViewById(R.id.cbDefault); spConfigApp = (Spinner)context.findViewById(R.id.spConfigApp); btnAuthorize = (Button) context.findViewById(R.id.btnAuthorize); } @Override public void onClick(View v) { ServiceProvider sp = context.getSp(); if (true) { showOAuthForm(sp); } else { showForm(sp); context.resetAuthConfigApp(); } } private void showForm(final ServiceProvider sp) { switch (sp) { case Sina: case Tencent: showOAuthForm(sp); break; case Twitter: showOAuthForm(sp); cbUseProxy.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { showXAuthForm(sp); } else { showOAuthForm(sp); } } }); break; case RenRen: case KaiXin: case QQZone: showOAuthForm(sp); break; default: showXAuthForm(sp); break; } } private void showXAuthForm(ServiceProvider sp) { llOAuthIntro.setVisibility(View.GONE); llXAuthForm.setVisibility(View.VISIBLE); etUsername.setText(""); etPassword.setText(""); if (sp == ServiceProvider.Twitter) { cbUseProxy.setVisibility(View.VISIBLE); etRestProxy.setVisibility(View.VISIBLE); etRestProxy.setText(""); etSearchProxy.setVisibility(View.GONE); } else { cbUseProxy.setVisibility(View.GONE); etRestProxy.setVisibility(View.GONE); etSearchProxy.setVisibility(View.GONE); } // boolean isEnabled = false; // if (sp == ServiceProvider.Twitter && cbUseProxy.isChecked()) { // isEnabled = isEnabled && etRestProxy.getText().length() > 0; // } btnAuthorize.setEnabled(false); } private void showOAuthForm(ServiceProvider sp) { llXAuthForm.setVisibility(View.GONE); llOAuthIntro.setVisibility(View.VISIBLE); if (sp == ServiceProvider.Twitter) { cbUseProxy.setVisibility(View.VISIBLE); } else { cbUseProxy.setVisibility(View.GONE); } if (sp.getSpCategory().equals(ServiceProvider.CATEGORY_SNS)) { cbFollowOffical.setVisibility(View.GONE); cbMakeDefault.setVisibility(View.GONE); } else { cbFollowOffical.setVisibility(View.VISIBLE); cbMakeDefault.setVisibility(View.VISIBLE); } etRestProxy.setVisibility(View.GONE); etSearchProxy.setVisibility(View.GONE); tvOAuthIntro.setText(R.string.hint_accounts_oauth_intro_tencent); if (sp.isSns()) { tvOAuthIntro.append("\n\n"); tvOAuthIntro.append(context.getText(R.string.hint_accounts_sns)); } btnAuthorize.setEnabled(true); } }
{ "content_hash": "9542d7db09305c6970a00c60fc1a328d", "timestamp": "", "source": "github", "line_count": 151, "max_line_length": 87, "avg_line_length": 29.503311258278146, "alnum_prop": 0.7241301907968575, "repo_name": "0359xiaodong/YiBo", "id": "3382c31ed4445418b519d84da30a4047fc0d8309", "size": "4455", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "YiBo/src/com/shejiaomao/weibo/service/listener/AddAccountCustomKeyClickListener.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package com.notonthehighstreet.ratel.internal.model; import com.fasterxml.jackson.annotation.JsonProperty; import java.math.BigDecimal; /** * Honeybadger API class. Contains information about system memory. */ public class Memory { private final BigDecimal total; private final BigDecimal free; @JsonProperty("free_total") private final BigDecimal freeTotal; Memory() { final long max = Runtime.getRuntime().maxMemory(); if (max == Long.MAX_VALUE) { free = toMB(Runtime.getRuntime().freeMemory()); } else { free = toMB(max - Runtime.getRuntime().totalMemory() + Runtime.getRuntime().freeMemory()); } freeTotal = null; total = toMB(Runtime.getRuntime().maxMemory()); } public BigDecimal getTotal() { return total; } public BigDecimal getFree() { return free; } public BigDecimal getFreeTotal() { return freeTotal; } private BigDecimal toMB(final long bytes) { return new BigDecimal(bytes).divide(new BigDecimal(1024 * 1024)); } }
{ "content_hash": "995e78d80ddd51a87cc0928072b9a25e", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 102, "avg_line_length": 24.488888888888887, "alnum_prop": 0.6397459165154264, "repo_name": "notonthehighstreet/ratel", "id": "da7dfd66facc7d34120493634118efa4bafcc8f3", "size": "2270", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/notonthehighstreet/ratel/internal/model/Memory.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "54319" } ], "symlink_target": "" }
using base::ASCIIToUTF16; using base::UTF16ToASCII; using base::WideToUTF16; namespace autofill { // Default JavaScript code used to submit the forms. const char kDocumentClickHandlerSubmitJS[] = "document.onclick = function() {" " document.getElementById('testform').submit();" "};"; // TODO(bondd): PdmChangeWaiter in autofill_uitest_util.cc is a replacement for // this class. Remove this class and use helper functions in that file instead. class WindowedPersonalDataManagerObserver : public PersonalDataManagerObserver, public infobars::InfoBarManager::Observer { public: explicit WindowedPersonalDataManagerObserver(Browser* browser) : alerted_(false), has_run_message_loop_(false), browser_(browser), infobar_service_(InfoBarService::FromWebContents( browser_->tab_strip_model()->GetActiveWebContents())) { PersonalDataManagerFactory::GetForProfile(browser_->profile())-> AddObserver(this); infobar_service_->AddObserver(this); } ~WindowedPersonalDataManagerObserver() override { infobar_service_->RemoveObserver(this); if (infobar_service_->infobar_count() > 0) { infobar_service_->RemoveInfoBar(infobar_service_->infobar_at(0)); } } void Wait() { if (!alerted_) { has_run_message_loop_ = true; content::RunMessageLoop(); } PersonalDataManagerFactory::GetForProfile(browser_->profile())-> RemoveObserver(this); } // PersonalDataManagerObserver: void OnPersonalDataChanged() override { if (has_run_message_loop_) { base::MessageLoopForUI::current()->Quit(); has_run_message_loop_ = false; } alerted_ = true; } void OnInsufficientFormData() override { OnPersonalDataChanged(); } // infobars::InfoBarManager::Observer: void OnInfoBarAdded(infobars::InfoBar* infobar) override { ConfirmInfoBarDelegate* infobar_delegate = infobar_service_->infobar_at(0)->delegate()->AsConfirmInfoBarDelegate(); ASSERT_TRUE(infobar_delegate); infobar_delegate->Accept(); } private: bool alerted_; bool has_run_message_loop_; Browser* browser_; InfoBarService* infobar_service_; }; class AutofillTest : public InProcessBrowserTest { protected: AutofillTest() {} void SetUpOnMainThread() override { // Don't want Keychain coming up on Mac. test::DisableSystemServices(browser()->profile()->GetPrefs()); } void TearDownOnMainThread() override { // Make sure to close any showing popups prior to tearing down the UI. content::WebContents* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); AutofillManager* autofill_manager = ContentAutofillDriverFactory::FromWebContents(web_contents) ->DriverForFrame(web_contents->GetMainFrame()) ->autofill_manager(); autofill_manager->client()->HideAutofillPopup(); } PersonalDataManager* personal_data_manager() { return PersonalDataManagerFactory::GetForProfile(browser()->profile()); } void SetProfiles(std::vector<AutofillProfile>* profiles) { WindowedPersonalDataManagerObserver observer(browser()); personal_data_manager()->SetProfiles(profiles); observer.Wait(); } void SetProfile(const AutofillProfile& profile) { std::vector<AutofillProfile> profiles; profiles.push_back(profile); SetProfiles(&profiles); } void SetCards(std::vector<CreditCard>* cards) { WindowedPersonalDataManagerObserver observer(browser()); personal_data_manager()->SetCreditCards(cards); observer.Wait(); } void SetCard(const CreditCard& card) { std::vector<CreditCard> cards; cards.push_back(card); SetCards(&cards); } typedef std::map<std::string, std::string> FormMap; // Helper function to obtain the Javascript required to update a form. std::string GetJSToFillForm(const FormMap& data) { std::string js; for (const auto& entry : data) { js += "document.getElementById('" + entry.first + "').value = '" + entry.second + "';"; } return js; } // Navigate to the form, input values into the fields, and submit the form. // The function returns after the PersonalDataManager is updated. void FillFormAndSubmit(const std::string& filename, const FormMap& data) { FillFormAndSubmitWithHandler(filename, data, kDocumentClickHandlerSubmitJS, true, true); } // Helper where the actual submit JS code can be specified, as well as whether // the test should |simulate_click| on the document. void FillFormAndSubmitWithHandler(const std::string& filename, const FormMap& data, const std::string& submit_js, bool simulate_click, bool expect_personal_data_change) { GURL url = test_server()->GetURL("files/autofill/" + filename); chrome::NavigateParams params(browser(), url, ui::PAGE_TRANSITION_LINK); params.disposition = NEW_FOREGROUND_TAB; ui_test_utils::NavigateToURL(&params); scoped_ptr<WindowedPersonalDataManagerObserver> observer; if (expect_personal_data_change) observer.reset(new WindowedPersonalDataManagerObserver(browser())); std::string js = GetJSToFillForm(data) + submit_js; ASSERT_TRUE(content::ExecuteScript(render_view_host(), js)); if (simulate_click) { // Simulate a mouse click to submit the form because form submissions not // triggered by user gestures are ignored. content::SimulateMouseClick( browser()->tab_strip_model()->GetActiveWebContents(), 0, blink::WebMouseEvent::ButtonLeft); } // We may not always be expecting changes in Personal data. if (observer.get()) observer->Wait(); else base::RunLoop().RunUntilIdle(); } void SubmitCreditCard(const char* name, const char* number, const char* exp_month, const char* exp_year) { FormMap data; data["CREDIT_CARD_NAME"] = name; data["CREDIT_CARD_NUMBER"] = number; data["CREDIT_CARD_EXP_MONTH"] = exp_month; data["CREDIT_CARD_EXP_4_DIGIT_YEAR"] = exp_year; FillFormAndSubmit("autofill_creditcard_form.html", data); } // Aggregate profiles from forms into Autofill preferences. Returns the number // of parsed profiles. int AggregateProfilesIntoAutofillPrefs(const std::string& filename) { CHECK(test_server()->Start()); std::string data; base::FilePath data_file = ui_test_utils::GetTestFilePath(base::FilePath().AppendASCII("autofill"), base::FilePath().AppendASCII(filename)); CHECK(base::ReadFileToString(data_file, &data)); std::vector<std::string> lines; base::SplitString(data, '\n', &lines); int parsed_profiles = 0; for (size_t i = 0; i < lines.size(); ++i) { if (StartsWithASCII(lines[i], "#", false)) continue; std::vector<std::string> fields; base::SplitString(lines[i], '|', &fields); if (fields.empty()) continue; // Blank line. ++parsed_profiles; CHECK_EQ(12u, fields.size()); FormMap data; data["NAME_FIRST"] = fields[0]; data["NAME_MIDDLE"] = fields[1]; data["NAME_LAST"] = fields[2]; data["EMAIL_ADDRESS"] = fields[3]; data["COMPANY_NAME"] = fields[4]; data["ADDRESS_HOME_LINE1"] = fields[5]; data["ADDRESS_HOME_LINE2"] = fields[6]; data["ADDRESS_HOME_CITY"] = fields[7]; data["ADDRESS_HOME_STATE"] = fields[8]; data["ADDRESS_HOME_ZIP"] = fields[9]; data["ADDRESS_HOME_COUNTRY"] = fields[10]; data["PHONE_HOME_WHOLE_NUMBER"] = fields[11]; FillFormAndSubmit("duplicate_profiles_test.html", data); } return parsed_profiles; } void ExpectFieldValue(const std::string& field_name, const std::string& expected_value) { std::string value; ASSERT_TRUE(content::ExecuteScriptAndExtractString( browser()->tab_strip_model()->GetActiveWebContents(), "window.domAutomationController.send(" " document.getElementById('" + field_name + "').value);", &value)); EXPECT_EQ(expected_value, value); } content::RenderViewHost* render_view_host() { return browser()->tab_strip_model()->GetActiveWebContents()-> GetRenderViewHost(); } void ExpectFilledTestForm() { ExpectFieldValue("firstname", "Milton"); ExpectFieldValue("lastname", "Waddams"); ExpectFieldValue("address1", "4120 Freidrich Lane"); ExpectFieldValue("address2", "Basement"); ExpectFieldValue("city", "Austin"); ExpectFieldValue("state", "TX"); ExpectFieldValue("zip", "78744"); ExpectFieldValue("country", "US"); ExpectFieldValue("phone", "5125551234"); } private: net::TestURLFetcherFactory url_fetcher_factory_; }; // Test filling profiles with unicode strings and crazy characters. // TODO(isherman): rewrite as unit test under PersonalDataManagerTest. IN_PROC_BROWSER_TEST_F(AutofillTest, FillProfileCrazyCharacters) { std::vector<AutofillProfile> profiles; AutofillProfile profile1; profile1.SetRawInfo(NAME_FIRST, WideToUTF16(L"\u0623\u0648\u0628\u0627\u0645\u0627 " L"\u064a\u0639\u062a\u0630\u0631 " L"\u0647\u0627\u062a\u0641\u064a\u0627 " L"\u0644\u0645\u0648\u0638\u0641\u0629 " L"\u0633\u0648\u062f\u0627\u0621 " L"\u0627\u0633\u062a\u0642\u0627\u0644\u062a " L"\u0628\u0633\u0628\u0628 " L"\u062a\u0635\u0631\u064a\u062d\u0627\u062a " L"\u0645\u062c\u062a\u0632\u0623\u0629")); profile1.SetRawInfo(NAME_MIDDLE, WideToUTF16(L"BANK\xcBERF\xc4LLE")); profile1.SetRawInfo(EMAIL_ADDRESS, WideToUTF16(L"\uacbd\uc81c \ub274\uc2a4 " L"\ub354\ubcf4\[email protected]")); profile1.SetRawInfo(ADDRESS_HOME_LINE1, WideToUTF16(L"\uad6d\uc815\uc6d0\xb7\uac80\ucc30, " L"\ub178\ubb34\ud604\uc815\ubd80 " L"\ub300\ubd81\uc811\ucd09 \ub2f4\ub2f9 " L"\uc778\uc0ac\ub4e4 \uc870\uc0ac")); profile1.SetRawInfo(ADDRESS_HOME_CITY, WideToUTF16(L"\u653f\u5e9c\u4e0d\u6392\u9664\u7acb\u6cd5" L"\u898f\u7ba1\u5c0e\u904a")); profile1.SetRawInfo(ADDRESS_HOME_ZIP, WideToUTF16(L"YOHO_54676")); profile1.SetRawInfo(PHONE_HOME_WHOLE_NUMBER, WideToUTF16(L"861088828000")); profile1.SetInfo( AutofillType(ADDRESS_HOME_COUNTRY), WideToUTF16(L"India"), "en-US"); profiles.push_back(profile1); AutofillProfile profile2; profile2.SetRawInfo(NAME_FIRST, WideToUTF16(L"\u4e0a\u6d77\u5e02\u91d1\u5c71\u533a " L"\u677e\u9690\u9547\u4ead\u67ab\u516c" L"\u8def1915\u53f7")); profile2.SetRawInfo(NAME_LAST, WideToUTF16(L"aguantó")); profile2.SetRawInfo(ADDRESS_HOME_ZIP, WideToUTF16(L"HOME 94043")); profiles.push_back(profile2); AutofillProfile profile3; profile3.SetRawInfo(EMAIL_ADDRESS, WideToUTF16(L"[email protected]")); profile3.SetRawInfo(COMPANY_NAME, WideToUTF16(L"Company X")); profiles.push_back(profile3); AutofillProfile profile4; profile4.SetRawInfo(NAME_FIRST, WideToUTF16(L"Joe 3254")); profile4.SetRawInfo(NAME_LAST, WideToUTF16(L"\u8bb0\u8d262\u5e74\u591a")); profile4.SetRawInfo(ADDRESS_HOME_ZIP, WideToUTF16(L"\uff08\u90ae\u7f16\uff1a201504\uff09")); profile4.SetRawInfo(EMAIL_ADDRESS, WideToUTF16(L"télé[email protected]")); profile4.SetRawInfo(COMPANY_NAME, WideToUTF16(L"\u0907\u0932\u0947\u0915\u093f\u091f\u094d" L"\u0930\u0928\u093f\u0915\u094d\u0938, " L"\u0905\u092a\u094b\u0932\u094b " L"\u091f\u093e\u092f\u0930\u094d\u0938 " L"\u0906\u0926\u093f")); profiles.push_back(profile4); AutofillProfile profile5; profile5.SetRawInfo(NAME_FIRST, WideToUTF16(L"Larry")); profile5.SetRawInfo(NAME_LAST, WideToUTF16(L"\u0938\u094d\u091f\u093e\u0902\u092a " L"\u0921\u094d\u092f\u0942\u091f\u0940")); profile5.SetRawInfo(ADDRESS_HOME_ZIP, WideToUTF16(L"111111111111110000GOOGLE")); profile5.SetRawInfo(EMAIL_ADDRESS, WideToUTF16(L"[email protected]")); profile5.SetRawInfo(COMPANY_NAME, WideToUTF16(L"Google")); profiles.push_back(profile5); AutofillProfile profile6; profile6.SetRawInfo(NAME_FIRST, WideToUTF16(L"\u4e0a\u6d77\u5e02\u91d1\u5c71\u533a " L"\u677e\u9690\u9547\u4ead\u67ab\u516c" L"\u8def1915\u53f7")); profile6.SetRawInfo(NAME_LAST, WideToUTF16(L"\u0646\u062c\u0627\u0645\u064a\u0646\u0627 " L"\u062f\u0639\u0645\u0647\u0627 " L"\u0644\u0644\u0631\u0626\u064a\u0633 " L"\u0627\u0644\u0633\u0648\u062f\u0627\u0646" L"\u064a \u0639\u0645\u0631 " L"\u0627\u0644\u0628\u0634\u064a\u0631")); profile6.SetRawInfo(ADDRESS_HOME_ZIP, WideToUTF16(L"HOME 94043")); profiles.push_back(profile6); AutofillProfile profile7; profile7.SetRawInfo(NAME_FIRST, WideToUTF16(L"&$%$$$ TESTO *&*&^&^& MOKO")); profile7.SetRawInfo(NAME_MIDDLE, WideToUTF16(L"WOHOOOO$$$$$$$$****")); profile7.SetRawInfo(EMAIL_ADDRESS, WideToUTF16(L"[email protected]")); profile7.SetRawInfo(ADDRESS_HOME_LINE1, WideToUTF16(L"34544, anderson ST.(120230)")); profile7.SetRawInfo(ADDRESS_HOME_CITY, WideToUTF16(L"Sunnyvale")); profile7.SetRawInfo(ADDRESS_HOME_STATE, WideToUTF16(L"CA")); profile7.SetRawInfo(ADDRESS_HOME_ZIP, WideToUTF16(L"94086")); profile7.SetRawInfo(PHONE_HOME_WHOLE_NUMBER, WideToUTF16(L"15466784565")); profile7.SetInfo( AutofillType(ADDRESS_HOME_COUNTRY), WideToUTF16(L"United States"), "en-US"); profiles.push_back(profile7); SetProfiles(&profiles); ASSERT_EQ(profiles.size(), personal_data_manager()->GetProfiles().size()); for (size_t i = 0; i < profiles.size(); ++i) { EXPECT_TRUE(std::find(profiles.begin(), profiles.end(), *personal_data_manager()->GetProfiles()[i]) != profiles.end()); } std::vector<CreditCard> cards; CreditCard card1; card1.SetRawInfo(CREDIT_CARD_NAME, WideToUTF16(L"\u751f\u6d3b\u5f88\u6709\u89c4\u5f8b " L"\u4ee5\u73a9\u4e3a\u4e3b")); card1.SetRawInfo(CREDIT_CARD_NUMBER, WideToUTF16(L"6011111111111117")); card1.SetRawInfo(CREDIT_CARD_EXP_MONTH, WideToUTF16(L"12")); card1.SetRawInfo(CREDIT_CARD_EXP_4_DIGIT_YEAR, WideToUTF16(L"2011")); cards.push_back(card1); CreditCard card2; card2.SetRawInfo(CREDIT_CARD_NAME, WideToUTF16(L"John Williams")); card2.SetRawInfo(CREDIT_CARD_NUMBER, WideToUTF16(L"WokoAwesome12345")); card2.SetRawInfo(CREDIT_CARD_EXP_MONTH, WideToUTF16(L"10")); card2.SetRawInfo(CREDIT_CARD_EXP_4_DIGIT_YEAR, WideToUTF16(L"2015")); cards.push_back(card2); CreditCard card3; card3.SetRawInfo(CREDIT_CARD_NAME, WideToUTF16(L"\u0623\u062d\u0645\u062f\u064a " L"\u0646\u062c\u0627\u062f " L"\u0644\u0645\u062d\u0627\u0648\u0644\u0647 " L"\u0627\u063a\u062a\u064a\u0627\u0644 " L"\u0641\u064a \u0645\u062f\u064a\u0646\u0629 " L"\u0647\u0645\u062f\u0627\u0646 ")); card3.SetRawInfo(CREDIT_CARD_NUMBER, WideToUTF16(L"\u092a\u0941\u0928\u0930\u094d\u091c\u0940" L"\u0935\u093f\u0924 \u0939\u094b\u0917\u093e " L"\u0928\u093e\u0932\u0902\u0926\u093e")); card3.SetRawInfo(CREDIT_CARD_EXP_MONTH, WideToUTF16(L"10")); card3.SetRawInfo(CREDIT_CARD_EXP_4_DIGIT_YEAR, WideToUTF16(L"2015")); cards.push_back(card3); CreditCard card4; card4.SetRawInfo(CREDIT_CARD_NAME, WideToUTF16(L"\u039d\u03ad\u03b5\u03c2 " L"\u03c3\u03c5\u03b3\u03c7\u03c9\u03bd\u03b5" L"\u03cd\u03c3\u03b5\u03b9\u03c2 " L"\u03ba\u03b1\u03b9 " L"\u03ba\u03b1\u03c4\u03b1\u03c1\u03b3\u03ae" L"\u03c3\u03b5\u03b9\u03c2")); card4.SetRawInfo(CREDIT_CARD_NUMBER, WideToUTF16(L"00000000000000000000000")); card4.SetRawInfo(CREDIT_CARD_EXP_MONTH, WideToUTF16(L"01")); card4.SetRawInfo(CREDIT_CARD_EXP_4_DIGIT_YEAR, WideToUTF16(L"2016")); cards.push_back(card4); SetCards(&cards); ASSERT_EQ(cards.size(), personal_data_manager()->GetCreditCards().size()); for (size_t i = 0; i < cards.size(); ++i) { EXPECT_TRUE(std::find(cards.begin(), cards.end(), *personal_data_manager()->GetCreditCards()[i]) != cards.end()); } } // Test filling in invalid values for profiles are saved as-is. Phone // information entered into the prefs UI is not validated or rejected except for // duplicates. // TODO(isherman): rewrite as WebUI test? IN_PROC_BROWSER_TEST_F(AutofillTest, Invalid) { // First try profiles with invalid ZIP input. AutofillProfile without_invalid; without_invalid.SetRawInfo(NAME_FIRST, ASCIIToUTF16("Will")); without_invalid.SetRawInfo(ADDRESS_HOME_CITY, ASCIIToUTF16("Sunnyvale")); without_invalid.SetRawInfo(ADDRESS_HOME_STATE, ASCIIToUTF16("CA")); without_invalid.SetRawInfo(ADDRESS_HOME_ZIP, ASCIIToUTF16("my_zip")); without_invalid.SetInfo( AutofillType(ADDRESS_HOME_COUNTRY), ASCIIToUTF16("United States"), "en-US"); AutofillProfile with_invalid = without_invalid; with_invalid.SetRawInfo(PHONE_HOME_WHOLE_NUMBER, ASCIIToUTF16("Invalid_Phone_Number")); SetProfile(with_invalid); ASSERT_EQ(1u, personal_data_manager()->GetProfiles().size()); AutofillProfile profile = *personal_data_manager()->GetProfiles()[0]; ASSERT_NE(without_invalid.GetRawInfo(PHONE_HOME_WHOLE_NUMBER), profile.GetRawInfo(PHONE_HOME_WHOLE_NUMBER)); } // Test invalid credit card numbers typed in prefs should be saved as-is. // TODO(isherman): rewrite as WebUI test? IN_PROC_BROWSER_TEST_F(AutofillTest, PrefsStringSavedAsIs) { CreditCard card; card.SetRawInfo(CREDIT_CARD_NUMBER, ASCIIToUTF16("Not_0123-5Checked")); SetCard(card); ASSERT_EQ(1u, personal_data_manager()->GetCreditCards().size()); ASSERT_EQ(card, *personal_data_manager()->GetCreditCards()[0]); } // Test credit card info with an invalid number is not aggregated. // When filling out a form with an invalid credit card number (one that does not // pass the Luhn test) the credit card info should not be saved into Autofill // preferences. IN_PROC_BROWSER_TEST_F(AutofillTest, InvalidCreditCardNumberIsNotAggregated) { #if defined(OS_WIN) && defined(USE_ASH) // Disable this test in Metro+Ash for now (http://crbug.com/262796). if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kAshBrowserTests)) return; #endif ASSERT_TRUE(test_server()->Start()); std::string card("4408 0412 3456 7890"); ASSERT_FALSE(autofill::IsValidCreditCardNumber(ASCIIToUTF16(card))); SubmitCreditCard("Bob Smith", card.c_str(), "12", "2014"); InfoBarService* infobar_service = InfoBarService::FromWebContents( browser()->tab_strip_model()->GetActiveWebContents()); ASSERT_EQ(0u, infobar_service->infobar_count()); } // Test whitespaces and separator chars are stripped for valid CC numbers. // The credit card numbers used in this test pass the Luhn test. For reference: // http://www.merriampark.com/anatomycc.htm IN_PROC_BROWSER_TEST_F(AutofillTest, WhitespacesAndSeparatorCharsStrippedForValidCCNums) { #if defined(OS_WIN) && defined(USE_ASH) // Disable this test in Metro+Ash for now (http://crbug.com/262796). if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kAshBrowserTests)) return; #endif ASSERT_TRUE(test_server()->Start()); SubmitCreditCard("Bob Smith", "4408 0412 3456 7893", "12", "2014"); SubmitCreditCard("Jane Doe", "4417-1234-5678-9113", "10", "2013"); ASSERT_EQ(2u, personal_data_manager()->GetCreditCards().size()); base::string16 cc1 = personal_data_manager()->GetCreditCards()[0]->GetRawInfo( CREDIT_CARD_NUMBER); ASSERT_TRUE(autofill::IsValidCreditCardNumber(cc1)); base::string16 cc2 = personal_data_manager()->GetCreditCards()[1]->GetRawInfo( CREDIT_CARD_NUMBER); ASSERT_TRUE(autofill::IsValidCreditCardNumber(cc2)); } // Test that Autofill aggregates a minimum valid profile. // The minimum required address fields must be specified: First Name, Last Name, // Address Line 1, City, Zip Code, and State. IN_PROC_BROWSER_TEST_F(AutofillTest, AggregatesMinValidProfile) { ASSERT_TRUE(test_server()->Start()); FormMap data; data["NAME_FIRST"] = "Bob"; data["NAME_LAST"] = "Smith"; data["ADDRESS_HOME_LINE1"] = "1234 H St."; data["ADDRESS_HOME_CITY"] = "Mountain View"; data["ADDRESS_HOME_STATE"] = "CA"; data["ADDRESS_HOME_ZIP"] = "94043"; FillFormAndSubmit("duplicate_profiles_test.html", data); ASSERT_EQ(1u, personal_data_manager()->GetProfiles().size()); } // Different Javascript to submit the form. IN_PROC_BROWSER_TEST_F(AutofillTest, AggregatesMinValidProfileDifferentJS) { ASSERT_TRUE(test_server()->Start()); FormMap data; data["NAME_FIRST"] = "Bob"; data["NAME_LAST"] = "Smith"; data["ADDRESS_HOME_LINE1"] = "1234 H St."; data["ADDRESS_HOME_CITY"] = "Mountain View"; data["ADDRESS_HOME_STATE"] = "CA"; data["ADDRESS_HOME_ZIP"] = "94043"; std::string submit("document.forms[0].submit();"); FillFormAndSubmitWithHandler("duplicate_profiles_test.html", data, submit, false, true); ASSERT_EQ(1u, personal_data_manager()->GetProfiles().size()); } // Form submitted via JavaScript, with an event handler on the submit event // which prevents submission of the form. Will not update the user's personal // data. IN_PROC_BROWSER_TEST_F(AutofillTest, ProfilesNotAggregatedWithSubmitHandler) { ASSERT_TRUE(test_server()->Start()); FormMap data; data["NAME_FIRST"] = "Bob"; data["NAME_LAST"] = "Smith"; data["ADDRESS_HOME_LINE1"] = "1234 H St."; data["ADDRESS_HOME_CITY"] = "Mountain View"; data["ADDRESS_HOME_STATE"] = "CA"; data["ADDRESS_HOME_ZIP"] = "94043"; std::string submit( "var preventFunction = function(event) { event.preventDefault(); };" "document.forms[0].addEventListener('submit', preventFunction);" "document.querySelector('input[type=submit]').click();"); FillFormAndSubmitWithHandler("duplicate_profiles_test.html", data, submit, false, false); // The AutofillManager will NOT update the user's profile. EXPECT_EQ(0u, personal_data_manager()->GetProfiles().size()); // We remove the submit handler and resubmit the form. This time the profile // will be updated. This is to guard against the underlying mechanics changing // and to try to avoid flakiness if this happens. We submit slightly different // data to make sure the expected data is saved. data["NAME_FIRST"] = "John"; data["NAME_LAST"] = "Doe"; std::string change_and_resubmit = GetJSToFillForm(data) + "document.forms[0].removeEventListener('submit', preventFunction);" "document.querySelector('input[type=submit]').click();"; WindowedPersonalDataManagerObserver observer(browser()); ASSERT_TRUE(content::ExecuteScript(render_view_host(), change_and_resubmit)); observer.Wait(); // The AutofillManager will update the user's profile this time. ASSERT_EQ(1u, personal_data_manager()->GetProfiles().size()); EXPECT_EQ(ASCIIToUTF16("John"), personal_data_manager()->GetProfiles()[0]->GetRawInfo(NAME_FIRST)); EXPECT_EQ(ASCIIToUTF16("Doe"), personal_data_manager()->GetProfiles()[0]->GetRawInfo(NAME_LAST)); } // Test Autofill does not aggregate profiles with no address info. // The minimum required address fields must be specified: First Name, Last Name, // Address Line 1, City, Zip Code, and State. IN_PROC_BROWSER_TEST_F(AutofillTest, ProfilesNotAggregatedWithNoAddress) { ASSERT_TRUE(test_server()->Start()); FormMap data; data["NAME_FIRST"] = "Bob"; data["NAME_LAST"] = "Smith"; data["EMAIL_ADDRESS"] = "[email protected]"; data["COMPANY_NAME"] = "Mountain View"; data["ADDRESS_HOME_CITY"] = "Mountain View"; data["PHONE_HOME_WHOLE_NUMBER"] = "650-555-4567"; FillFormAndSubmit("duplicate_profiles_test.html", data); ASSERT_TRUE(personal_data_manager()->GetProfiles().empty()); } // Test Autofill does not aggregate profiles with an invalid email. IN_PROC_BROWSER_TEST_F(AutofillTest, ProfilesNotAggregatedWithInvalidEmail) { ASSERT_TRUE(test_server()->Start()); FormMap data; data["NAME_FIRST"] = "Bob"; data["NAME_LAST"] = "Smith"; data["EMAIL_ADDRESS"] = "garbage"; data["ADDRESS_HOME_LINE1"] = "1234 H St."; data["ADDRESS_HOME_CITY"] = "San Jose"; data["ADDRESS_HOME_STATE"] = "CA"; data["ADDRESS_HOME_ZIP"] = "95110"; data["COMPANY_NAME"] = "Company X"; data["PHONE_HOME_WHOLE_NUMBER"] = "408-871-4567"; FillFormAndSubmit("duplicate_profiles_test.html", data); ASSERT_TRUE(personal_data_manager()->GetProfiles().empty()); } // Test profile is saved if phone number is valid in selected country. // The data file contains two profiles with valid phone numbers and two // profiles with invalid phone numbers from their respective country. IN_PROC_BROWSER_TEST_F(AutofillTest, ProfileSavedWithValidCountryPhone) { ASSERT_TRUE(test_server()->Start()); std::vector<FormMap> profiles; FormMap data1; data1["NAME_FIRST"] = "Bob"; data1["NAME_LAST"] = "Smith"; data1["ADDRESS_HOME_LINE1"] = "123 Cherry Ave"; data1["ADDRESS_HOME_CITY"] = "Mountain View"; data1["ADDRESS_HOME_STATE"] = "CA"; data1["ADDRESS_HOME_ZIP"] = "94043"; data1["ADDRESS_HOME_COUNTRY"] = "United States"; data1["PHONE_HOME_WHOLE_NUMBER"] = "408-871-4567"; profiles.push_back(data1); FormMap data2; data2["NAME_FIRST"] = "John"; data2["NAME_LAST"] = "Doe"; data2["ADDRESS_HOME_LINE1"] = "987 H St"; data2["ADDRESS_HOME_CITY"] = "San Jose"; data2["ADDRESS_HOME_STATE"] = "CA"; data2["ADDRESS_HOME_ZIP"] = "95510"; data2["ADDRESS_HOME_COUNTRY"] = "United States"; data2["PHONE_HOME_WHOLE_NUMBER"] = "408-123-456"; profiles.push_back(data2); FormMap data3; data3["NAME_FIRST"] = "Jane"; data3["NAME_LAST"] = "Doe"; data3["ADDRESS_HOME_LINE1"] = "1523 Garcia St"; data3["ADDRESS_HOME_CITY"] = "Mountain View"; data3["ADDRESS_HOME_STATE"] = "CA"; data3["ADDRESS_HOME_ZIP"] = "94043"; data3["ADDRESS_HOME_COUNTRY"] = "Germany"; data3["PHONE_HOME_WHOLE_NUMBER"] = "+49 40-80-81-79-000"; profiles.push_back(data3); FormMap data4; data4["NAME_FIRST"] = "Bonnie"; data4["NAME_LAST"] = "Smith"; data4["ADDRESS_HOME_LINE1"] = "6723 Roadway Rd"; data4["ADDRESS_HOME_CITY"] = "San Jose"; data4["ADDRESS_HOME_STATE"] = "CA"; data4["ADDRESS_HOME_ZIP"] = "95510"; data4["ADDRESS_HOME_COUNTRY"] = "Germany"; data4["PHONE_HOME_WHOLE_NUMBER"] = "+21 08450 777 777"; profiles.push_back(data4); for (size_t i = 0; i < profiles.size(); ++i) FillFormAndSubmit("autofill_test_form.html", profiles[i]); ASSERT_EQ(2u, personal_data_manager()->GetProfiles().size()); int us_address_index = personal_data_manager()->GetProfiles()[0]->GetRawInfo( ADDRESS_HOME_LINE1) == ASCIIToUTF16("123 Cherry Ave") ? 0 : 1; EXPECT_EQ( ASCIIToUTF16("408-871-4567"), personal_data_manager()->GetProfiles()[us_address_index]->GetRawInfo( PHONE_HOME_WHOLE_NUMBER)); ASSERT_EQ( ASCIIToUTF16("+49 40-80-81-79-000"), personal_data_manager()->GetProfiles()[1 - us_address_index]->GetRawInfo( PHONE_HOME_WHOLE_NUMBER)); } // Prepend country codes when formatting phone numbers, but only if the user // provided one in the first place. IN_PROC_BROWSER_TEST_F(AutofillTest, AppendCountryCodeForAggregatedPhones) { ASSERT_TRUE(test_server()->Start()); FormMap data; data["NAME_FIRST"] = "Bob"; data["NAME_LAST"] = "Smith"; data["ADDRESS_HOME_LINE1"] = "1234 H St."; data["ADDRESS_HOME_CITY"] = "San Jose"; data["ADDRESS_HOME_STATE"] = "CA"; data["ADDRESS_HOME_ZIP"] = "95110"; data["ADDRESS_HOME_COUNTRY"] = "Germany"; data["PHONE_HOME_WHOLE_NUMBER"] = "+4908450777777"; FillFormAndSubmit("autofill_test_form.html", data); data["ADDRESS_HOME_LINE1"] = "4321 H St."; data["PHONE_HOME_WHOLE_NUMBER"] = "08450777777"; FillFormAndSubmit("autofill_test_form.html", data); ASSERT_EQ(2u, personal_data_manager()->GetProfiles().size()); int second_address_index = personal_data_manager()->GetProfiles()[0]->GetRawInfo( ADDRESS_HOME_LINE1) == ASCIIToUTF16("4321 H St.") ? 0 : 1; EXPECT_EQ(ASCIIToUTF16("+49 8450 777777"), personal_data_manager() ->GetProfiles()[1 - second_address_index] ->GetRawInfo(PHONE_HOME_WHOLE_NUMBER)); EXPECT_EQ( ASCIIToUTF16("08450 777777"), personal_data_manager()->GetProfiles()[second_address_index]->GetRawInfo( PHONE_HOME_WHOLE_NUMBER)); } // Test that Autofill uses '+' sign for international numbers. // This applies to the following cases: // The phone number has a leading '+'. // The phone number does not have a leading '+'. // The phone number has a leading international direct dialing (IDD) code. // This does not apply to US numbers. For US numbers, '+' is removed. IN_PROC_BROWSER_TEST_F(AutofillTest, UsePlusSignForInternationalNumber) { ASSERT_TRUE(test_server()->Start()); std::vector<FormMap> profiles; FormMap data1; data1["NAME_FIRST"] = "Bonnie"; data1["NAME_LAST"] = "Smith"; data1["ADDRESS_HOME_LINE1"] = "6723 Roadway Rd"; data1["ADDRESS_HOME_CITY"] = "Reading"; data1["ADDRESS_HOME_STATE"] = "Berkshire"; data1["ADDRESS_HOME_ZIP"] = "RG12 3BR"; data1["ADDRESS_HOME_COUNTRY"] = "United Kingdom"; data1["PHONE_HOME_WHOLE_NUMBER"] = "+44 7624-123456"; profiles.push_back(data1); FormMap data2; data2["NAME_FIRST"] = "John"; data2["NAME_LAST"] = "Doe"; data2["ADDRESS_HOME_LINE1"] = "987 H St"; data2["ADDRESS_HOME_CITY"] = "Reading"; data2["ADDRESS_HOME_STATE"] = "BerkShire"; data2["ADDRESS_HOME_ZIP"] = "RG12 3BR"; data2["ADDRESS_HOME_COUNTRY"] = "United Kingdom"; data2["PHONE_HOME_WHOLE_NUMBER"] = "44 7624 123456"; profiles.push_back(data2); FormMap data3; data3["NAME_FIRST"] = "Jane"; data3["NAME_LAST"] = "Doe"; data3["ADDRESS_HOME_LINE1"] = "1523 Garcia St"; data3["ADDRESS_HOME_CITY"] = "Reading"; data3["ADDRESS_HOME_STATE"] = "BerkShire"; data3["ADDRESS_HOME_ZIP"] = "RG12 3BR"; data3["ADDRESS_HOME_COUNTRY"] = "United Kingdom"; data3["PHONE_HOME_WHOLE_NUMBER"] = "0044 7624 123456"; profiles.push_back(data3); FormMap data4; data4["NAME_FIRST"] = "Bob"; data4["NAME_LAST"] = "Smith"; data4["ADDRESS_HOME_LINE1"] = "123 Cherry Ave"; data4["ADDRESS_HOME_CITY"] = "Mountain View"; data4["ADDRESS_HOME_STATE"] = "CA"; data4["ADDRESS_HOME_ZIP"] = "94043"; data4["ADDRESS_HOME_COUNTRY"] = "United States"; data4["PHONE_HOME_WHOLE_NUMBER"] = "+1 (408) 871-4567"; profiles.push_back(data4); for (size_t i = 0; i < profiles.size(); ++i) FillFormAndSubmit("autofill_test_form.html", profiles[i]); ASSERT_EQ(4u, personal_data_manager()->GetProfiles().size()); for (size_t i = 0; i < personal_data_manager()->GetProfiles().size(); ++i) { AutofillProfile* profile = personal_data_manager()->GetProfiles()[i]; std::string expectation; std::string name = UTF16ToASCII(profile->GetRawInfo(NAME_FIRST)); if (name == "Bonnie") expectation = "+447624123456"; else if (name == "John") expectation = "+447624123456"; else if (name == "Jane") expectation = "+447624123456"; else if (name == "Bob") expectation = "14088714567"; EXPECT_EQ(ASCIIToUTF16(expectation), profile->GetInfo(AutofillType(PHONE_HOME_WHOLE_NUMBER), "")); } } // Test CC info not offered to be saved when autocomplete=off for CC field. // If the credit card number field has autocomplete turned off, then the credit // card infobar should not offer to save the credit card info. The credit card // number must be a valid Luhn number. IN_PROC_BROWSER_TEST_F(AutofillTest, CCInfoNotStoredWhenAutocompleteOff) { #if defined(OS_WIN) && defined(USE_ASH) // Disable this test in Metro+Ash for now (http://crbug.com/262796). if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kAshBrowserTests)) return; #endif ASSERT_TRUE(test_server()->Start()); FormMap data; data["CREDIT_CARD_NAME"] = "Bob Smith"; data["CREDIT_CARD_NUMBER"] = "4408041234567893"; data["CREDIT_CARD_EXP_MONTH"] = "12"; data["CREDIT_CARD_EXP_4_DIGIT_YEAR"] = "2014"; FillFormAndSubmit("cc_autocomplete_off_test.html", data); InfoBarService* infobar_service = InfoBarService::FromWebContents( browser()->tab_strip_model()->GetActiveWebContents()); ASSERT_EQ(0u, infobar_service->infobar_count()); } // Test profile not aggregated if email found in non-email field. IN_PROC_BROWSER_TEST_F(AutofillTest, ProfileWithEmailInOtherFieldNotSaved) { ASSERT_TRUE(test_server()->Start()); FormMap data; data["NAME_FIRST"] = "Bob"; data["NAME_LAST"] = "Smith"; data["ADDRESS_HOME_LINE1"] = "[email protected]"; data["ADDRESS_HOME_CITY"] = "San Jose"; data["ADDRESS_HOME_STATE"] = "CA"; data["ADDRESS_HOME_ZIP"] = "95110"; data["COMPANY_NAME"] = "Company X"; data["PHONE_HOME_WHOLE_NUMBER"] = "408-871-4567"; FillFormAndSubmit("duplicate_profiles_test.html", data); ASSERT_EQ(0u, personal_data_manager()->GetProfiles().size()); } // Test that profiles merge for aggregated data with same address. // The criterion for when two profiles are expected to be merged is when their // 'Address Line 1' and 'City' data match. When two profiles are merged, any // remaining address fields are expected to be overwritten. Any non-address // fields should accumulate multi-valued data. // DISABLED: http://crbug.com/281541 IN_PROC_BROWSER_TEST_F(AutofillTest, DISABLED_MergeAggregatedProfilesWithSameAddress) { AggregateProfilesIntoAutofillPrefs("dataset_same_address.txt"); ASSERT_EQ(3u, personal_data_manager()->GetProfiles().size()); } // Test profiles are not merged without minimum address values. // Mininum address values needed during aggregation are: address line 1, city, // state, and zip code. // Profiles are merged when data for address line 1 and city match. // DISABLED: http://crbug.com/281541 IN_PROC_BROWSER_TEST_F(AutofillTest, DISABLED_ProfilesNotMergedWhenNoMinAddressData) { AggregateProfilesIntoAutofillPrefs("dataset_no_address.txt"); ASSERT_EQ(0u, personal_data_manager()->GetProfiles().size()); } // Test Autofill ability to merge duplicate profiles and throw away junk. // TODO(isherman): this looks redundant, consider removing. // DISABLED: http://crbug.com/281541 IN_PROC_BROWSER_TEST_F(AutofillTest, DISABLED_MergeAggregatedDuplicatedProfiles) { int num_of_profiles = AggregateProfilesIntoAutofillPrefs("dataset_duplicated_profiles.txt"); ASSERT_GT(num_of_profiles, static_cast<int>(personal_data_manager()->GetProfiles().size())); } } // namespace autofill
{ "content_hash": "e49ea15c6f9bc8666c9b886ace49a90d", "timestamp": "", "source": "github", "line_count": 892, "max_line_length": 80, "avg_line_length": 40.74551569506726, "alnum_prop": 0.6558811390837804, "repo_name": "mou4e/zirconium", "id": "c280cb8e5bcb9902da1405474d2966b6b5514bc5", "size": "38659", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "chrome/browser/autofill/autofill_browsertest.cc", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "AppleScript", "bytes": "6973" }, { "name": "Arduino", "bytes": "464" }, { "name": "Assembly", "bytes": "23829" }, { "name": "C", "bytes": "4115478" }, { "name": "C++", "bytes": "233013312" }, { "name": "CSS", "bytes": "931463" }, { "name": "Emacs Lisp", "bytes": "988" }, { "name": "HTML", "bytes": "28131619" }, { "name": "Java", "bytes": "9810569" }, { "name": "JavaScript", "bytes": "19670133" }, { "name": "Makefile", "bytes": "68017" }, { "name": "Objective-C", "bytes": "1475873" }, { "name": "Objective-C++", "bytes": "8640851" }, { "name": "PHP", "bytes": "97817" }, { "name": "PLpgSQL", "bytes": "171186" }, { "name": "Perl", "bytes": "63937" }, { "name": "Protocol Buffer", "bytes": "456460" }, { "name": "Python", "bytes": "7958623" }, { "name": "Shell", "bytes": "477153" }, { "name": "Standard ML", "bytes": "4965" }, { "name": "XSLT", "bytes": "418" }, { "name": "nesC", "bytes": "18347" } ], "symlink_target": "" }
package com.google.android.exoplayer.text.subrip; import com.google.android.exoplayer.text.Cue; import com.google.android.exoplayer.text.Subtitle; import com.google.android.exoplayer.util.Assertions; import com.google.android.exoplayer.util.Util; import java.util.Collections; import java.util.List; /** * A representation of a SubRip subtitle. */ /* package */ final class SubripSubtitle implements Subtitle { private final Cue[] cues; private final long[] cueTimesUs; /** * @param cues The cues in the subtitle. Null entries may be used to represent empty cues. * @param cueTimesUs The cue times, in microseconds. */ public SubripSubtitle(Cue[] cues, long[] cueTimesUs) { this.cues = cues; this.cueTimesUs = cueTimesUs; } @Override public int getNextEventTimeIndex(long timeUs) { int index = Util.binarySearchCeil(cueTimesUs, timeUs, false, false); return index < cueTimesUs.length ? index : -1; } @Override public int getEventTimeCount() { return cueTimesUs.length; } @Override public long getEventTime(int index) { Assertions.checkArgument(index >= 0); Assertions.checkArgument(index < cueTimesUs.length); return cueTimesUs[index]; } @Override public long getLastEventTime() { if (getEventTimeCount() == 0) { return -1; } return cueTimesUs[cueTimesUs.length - 1]; } @Override public List<Cue> getCues(long timeUs) { int index = Util.binarySearchFloor(cueTimesUs, timeUs, true, false); if (index == -1 || cues[index] == null) { // timeUs is earlier than the start of the first cue, or we have an empty cue. return Collections.<Cue>emptyList(); } else { return Collections.singletonList(cues[index]); } } }
{ "content_hash": "f96f306106637083964102bf19802798", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 92, "avg_line_length": 27, "alnum_prop": 0.6962962962962963, "repo_name": "reid-mcpherson/ExoPlayerDebug", "id": "e8e583f822997c16e81e5ea7fa4f922f50cce8ed", "size": "2374", "binary": false, "copies": "5", "ref": "refs/heads/development", "path": "library/src/main/java/com/google/android/exoplayer/text/subrip/SubripSubtitle.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "36486" }, { "name": "Java", "bytes": "2702509" }, { "name": "Makefile", "bytes": "11443" }, { "name": "Shell", "bytes": "5498" } ], "symlink_target": "" }
package de.hub.clickwatch.specificmodels.brn.device_wifi_wifidevice_cst_stats; import org.eclipse.emf.ecore.EObject; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Mac duration</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * <ul> * <li>{@link de.hub.clickwatch.specificmodels.brn.device_wifi_wifidevice_cst_stats.Mac_duration#getEContainer_mac_duration <em>EContainer mac duration</em>}</li> * <li>{@link de.hub.clickwatch.specificmodels.brn.device_wifi_wifidevice_cst_stats.Mac_duration#getBusy <em>Busy</em>}</li> * <li>{@link de.hub.clickwatch.specificmodels.brn.device_wifi_wifidevice_cst_stats.Mac_duration#getRx <em>Rx</em>}</li> * <li>{@link de.hub.clickwatch.specificmodels.brn.device_wifi_wifidevice_cst_stats.Mac_duration#getTx <em>Tx</em>}</li> * <li>{@link de.hub.clickwatch.specificmodels.brn.device_wifi_wifidevice_cst_stats.Mac_duration#getNoerr_rx <em>Noerr rx</em>}</li> * <li>{@link de.hub.clickwatch.specificmodels.brn.device_wifi_wifidevice_cst_stats.Mac_duration#getCrc_rx <em>Crc rx</em>}</li> * <li>{@link de.hub.clickwatch.specificmodels.brn.device_wifi_wifidevice_cst_stats.Mac_duration#getPhy_rx <em>Phy rx</em>}</li> * <li>{@link de.hub.clickwatch.specificmodels.brn.device_wifi_wifidevice_cst_stats.Mac_duration#getUnknown_err_rx <em>Unknown err rx</em>}</li> * <li>{@link de.hub.clickwatch.specificmodels.brn.device_wifi_wifidevice_cst_stats.Mac_duration#getUnit <em>Unit</em>}</li> * </ul> * </p> * * @see de.hub.clickwatch.specificmodels.brn.device_wifi_wifidevice_cst_stats.Device_wifi_wifidevice_cst_statsPackage#getMac_duration() * @model annotation="http://de.hub.clickwatch.specificmodels target_id='Stats|Handler/channelstats|channelstats:Channelstats|EObject/mac_duration|mac_duration:Mac_duration|EObject'" * @generated */ public interface Mac_duration extends EObject { /** * Returns the value of the '<em><b>EContainer mac duration</b></em>' container reference. * It is bidirectional and its opposite is '{@link de.hub.clickwatch.specificmodels.brn.device_wifi_wifidevice_cst_stats.Channelstats#getMac_duration <em>Mac duration</em>}'. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>EContainer mac duration</em>' container reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>EContainer mac duration</em>' container reference. * @see #setEContainer_mac_duration(Channelstats) * @see de.hub.clickwatch.specificmodels.brn.device_wifi_wifidevice_cst_stats.Device_wifi_wifidevice_cst_statsPackage#getMac_duration_EContainer_mac_duration() * @see de.hub.clickwatch.specificmodels.brn.device_wifi_wifidevice_cst_stats.Channelstats#getMac_duration * @model opposite="mac_duration" transient="false" * @generated */ Channelstats getEContainer_mac_duration(); /** * Sets the value of the '{@link de.hub.clickwatch.specificmodels.brn.device_wifi_wifidevice_cst_stats.Mac_duration#getEContainer_mac_duration <em>EContainer mac duration</em>}' container reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>EContainer mac duration</em>' container reference. * @see #getEContainer_mac_duration() * @generated */ void setEContainer_mac_duration(Channelstats value); /** * Returns the value of the '<em><b>Busy</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Busy</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Busy</em>' attribute. * @see #setBusy(int) * @see de.hub.clickwatch.specificmodels.brn.device_wifi_wifidevice_cst_stats.Device_wifi_wifidevice_cst_statsPackage#getMac_duration_Busy() * @model annotation="http://de.hub.clickwatch.specificmodels target_id='Stats|Handler/channelstats|channelstats:Channelstats|EObject/mac_duration|mac_duration:Mac_duration|EObject/busy|busy:'" * @generated */ int getBusy(); /** * Sets the value of the '{@link de.hub.clickwatch.specificmodels.brn.device_wifi_wifidevice_cst_stats.Mac_duration#getBusy <em>Busy</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Busy</em>' attribute. * @see #getBusy() * @generated */ void setBusy(int value); /** * Returns the value of the '<em><b>Rx</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Rx</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Rx</em>' attribute. * @see #setRx(int) * @see de.hub.clickwatch.specificmodels.brn.device_wifi_wifidevice_cst_stats.Device_wifi_wifidevice_cst_statsPackage#getMac_duration_Rx() * @model annotation="http://de.hub.clickwatch.specificmodels target_id='Stats|Handler/channelstats|channelstats:Channelstats|EObject/mac_duration|mac_duration:Mac_duration|EObject/rx|rx:'" * @generated */ int getRx(); /** * Sets the value of the '{@link de.hub.clickwatch.specificmodels.brn.device_wifi_wifidevice_cst_stats.Mac_duration#getRx <em>Rx</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Rx</em>' attribute. * @see #getRx() * @generated */ void setRx(int value); /** * Returns the value of the '<em><b>Tx</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Tx</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Tx</em>' attribute. * @see #setTx(int) * @see de.hub.clickwatch.specificmodels.brn.device_wifi_wifidevice_cst_stats.Device_wifi_wifidevice_cst_statsPackage#getMac_duration_Tx() * @model annotation="http://de.hub.clickwatch.specificmodels target_id='Stats|Handler/channelstats|channelstats:Channelstats|EObject/mac_duration|mac_duration:Mac_duration|EObject/tx|tx:'" * @generated */ int getTx(); /** * Sets the value of the '{@link de.hub.clickwatch.specificmodels.brn.device_wifi_wifidevice_cst_stats.Mac_duration#getTx <em>Tx</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Tx</em>' attribute. * @see #getTx() * @generated */ void setTx(int value); /** * Returns the value of the '<em><b>Noerr rx</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Noerr rx</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Noerr rx</em>' attribute. * @see #setNoerr_rx(int) * @see de.hub.clickwatch.specificmodels.brn.device_wifi_wifidevice_cst_stats.Device_wifi_wifidevice_cst_statsPackage#getMac_duration_Noerr_rx() * @model annotation="http://de.hub.clickwatch.specificmodels target_id='Stats|Handler/channelstats|channelstats:Channelstats|EObject/mac_duration|mac_duration:Mac_duration|EObject/noerr_rx|noerr_rx:'" * @generated */ int getNoerr_rx(); /** * Sets the value of the '{@link de.hub.clickwatch.specificmodels.brn.device_wifi_wifidevice_cst_stats.Mac_duration#getNoerr_rx <em>Noerr rx</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Noerr rx</em>' attribute. * @see #getNoerr_rx() * @generated */ void setNoerr_rx(int value); /** * Returns the value of the '<em><b>Crc rx</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Crc rx</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Crc rx</em>' attribute. * @see #setCrc_rx(int) * @see de.hub.clickwatch.specificmodels.brn.device_wifi_wifidevice_cst_stats.Device_wifi_wifidevice_cst_statsPackage#getMac_duration_Crc_rx() * @model annotation="http://de.hub.clickwatch.specificmodels target_id='Stats|Handler/channelstats|channelstats:Channelstats|EObject/mac_duration|mac_duration:Mac_duration|EObject/crc_rx|crc_rx:'" * @generated */ int getCrc_rx(); /** * Sets the value of the '{@link de.hub.clickwatch.specificmodels.brn.device_wifi_wifidevice_cst_stats.Mac_duration#getCrc_rx <em>Crc rx</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Crc rx</em>' attribute. * @see #getCrc_rx() * @generated */ void setCrc_rx(int value); /** * Returns the value of the '<em><b>Phy rx</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Phy rx</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Phy rx</em>' attribute. * @see #setPhy_rx(int) * @see de.hub.clickwatch.specificmodels.brn.device_wifi_wifidevice_cst_stats.Device_wifi_wifidevice_cst_statsPackage#getMac_duration_Phy_rx() * @model annotation="http://de.hub.clickwatch.specificmodels target_id='Stats|Handler/channelstats|channelstats:Channelstats|EObject/mac_duration|mac_duration:Mac_duration|EObject/phy_rx|phy_rx:'" * @generated */ int getPhy_rx(); /** * Sets the value of the '{@link de.hub.clickwatch.specificmodels.brn.device_wifi_wifidevice_cst_stats.Mac_duration#getPhy_rx <em>Phy rx</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Phy rx</em>' attribute. * @see #getPhy_rx() * @generated */ void setPhy_rx(int value); /** * Returns the value of the '<em><b>Unknown err rx</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Unknown err rx</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Unknown err rx</em>' attribute. * @see #setUnknown_err_rx(int) * @see de.hub.clickwatch.specificmodels.brn.device_wifi_wifidevice_cst_stats.Device_wifi_wifidevice_cst_statsPackage#getMac_duration_Unknown_err_rx() * @model annotation="http://de.hub.clickwatch.specificmodels target_id='Stats|Handler/channelstats|channelstats:Channelstats|EObject/mac_duration|mac_duration:Mac_duration|EObject/unknown_err_rx|unknown_err_rx:'" * @generated */ int getUnknown_err_rx(); /** * Sets the value of the '{@link de.hub.clickwatch.specificmodels.brn.device_wifi_wifidevice_cst_stats.Mac_duration#getUnknown_err_rx <em>Unknown err rx</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Unknown err rx</em>' attribute. * @see #getUnknown_err_rx() * @generated */ void setUnknown_err_rx(int value); /** * Returns the value of the '<em><b>Unit</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Unit</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Unit</em>' attribute. * @see #setUnit(String) * @see de.hub.clickwatch.specificmodels.brn.device_wifi_wifidevice_cst_stats.Device_wifi_wifidevice_cst_statsPackage#getMac_duration_Unit() * @model annotation="http://de.hub.clickwatch.specificmodels target_id='Stats|Handler/channelstats|channelstats:Channelstats|EObject/mac_duration|mac_duration:Mac_duration|EObject/unit|unit:'" * @generated */ String getUnit(); /** * Sets the value of the '{@link de.hub.clickwatch.specificmodels.brn.device_wifi_wifidevice_cst_stats.Mac_duration#getUnit <em>Unit</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Unit</em>' attribute. * @see #getUnit() * @generated */ void setUnit(String value); } // Mac_duration
{ "content_hash": "4e01c12814882ea5358c74b2f22b291a", "timestamp": "", "source": "github", "line_count": 267, "max_line_length": 217, "avg_line_length": 47.659176029962545, "alnum_prop": 0.6521807465618861, "repo_name": "markus1978/clickwatch", "id": "435a8a95bcac0e9a314272080e9ab45805575cdb", "size": "12774", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "analysis/de.hub.clickwatch.specificmodels.brn/src/de/hub/clickwatch/specificmodels/brn/device_wifi_wifidevice_cst_stats/Mac_duration.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "10246972" }, { "name": "Matlab", "bytes": "7054" }, { "name": "Shell", "bytes": "256" }, { "name": "XML", "bytes": "14136" } ], "symlink_target": "" }
package io.scalajs.nodejs package fs import io.scalajs.RawOptions import io.scalajs.nodejs.buffer.Buffer import io.scalajs.nodejs.events.IEventEmitter import io.scalajs.nodejs.url.URL import scala.scalajs.js import scala.scalajs.js.annotation.JSImport import scala.scalajs.js.typedarray.Uint8Array import scala.scalajs.js.| /** * File I/O is provided by simple wrappers around standard POSIX functions. To use this module do require('fs'). * All the methods have asynchronous and synchronous forms. * * The asynchronous form always takes a completion callback as its last argument. The arguments passed to the * completion callback depend on the method, but the first argument is always reserved for an exception. If the * operation was completed successfully, then the first argument will be null or undefined. * * When using the synchronous form any exceptions are immediately thrown. You can use try/catch to handle exceptions * or allow them to bubble up. * @author [email protected] */ @js.native trait Fs extends IEventEmitter with FSConstants { /** * Returns an object containing commonly used constants for file system operations * @return an [[FSConstants object]] containing commonly used constants for file system operations */ def constants: FSConstants = js.native ///////////////////////////////////////////////////////////////////////////////// // Methods ///////////////////////////////////////////////////////////////////////////////// /** * Tests a user's permissions for the file specified by path. mode is an optional integer that specifies * the accessibility checks to be performed. The following constants define the possible values of mode. * It is possible to create a mask consisting of the bitwise OR of two or more values. * <ul> * <li>fs.F_OK - File is visible to the calling process. This is useful for determining if a file exists, * but says nothing about rwx permissions. Default if no mode is specified.</li> * <li>[[FSConstants.R_OK]] - File can be read by the calling process.</li> * <li>[[FSConstants.W_OK]] - File can be written by the calling process.</li> * <li>[[FSConstants.X_OK]] - File can be executed by the calling process. This has no effect on Windows (will behave like [[F_OK]]).</li> * </ul> * @param path the path (Buffer | String) * @param mode the optional mode * @param callback is a callback function that is invoked with a possible error argument. If any of the accessibility * checks fail, the error argument will be populated. * @example fs.access(path[, mode], callback) */ def access(path: Buffer | String | URL, mode: FileMode, callback: FsCallback0): Unit = js.native /** * Tests a user's permissions for the file specified by path. mode is an optional integer that specifies * the accessibility checks to be performed. The following constants define the possible values of mode. * It is possible to create a mask consisting of the bitwise OR of two or more values. * <ul> * <li>fs.F_OK - File is visible to the calling process. This is useful for determining if a file exists, * but says nothing about rwx permissions. Default if no mode is specified.</li> * <li>[[FSConstants.R_OK]] - File can be read by the calling process.</li> * <li>[[FSConstants.W_OK]] - File can be written by the calling process.</li> * <li>[[FSConstants.X_OK]] - File can be executed by the calling process. This has no effect on Windows (will behave like [[F_OK]]).</li> * </ul> * @param path the path (Buffer | String) * @param callback is a callback function that is invoked with a possible error argument. If any of the accessibility * checks fail, the error argument will be populated. * @example fs.access(path[, mode], callback) */ def access(path: Buffer | String | URL, callback: FsCallback0): Unit = js.native /** * Synchronous version of fs.access(). This throws if any accessibility checks fail, and does nothing otherwise. * @param path the path (Buffer | String) * @param mode the optional mode * @example fs.accessSync(path[, mode]) */ def accessSync(path: Buffer | String | URL, mode: FileMode = js.native): Unit = js.native /** * Asynchronously append data to a file, creating the file if it does not yet exist. data can be a string or a buffer. * @param file the filename or file descriptor (Buffer | String | Number) * @param data the data to append (Buffer | String) * @param options the [[FileAppendOptions optional append settings]] * @param callback the callback function * @example fs.appendFile(file, data[, options], callback) */ def appendFile(file: Buffer | FileDescriptor | String, data: Buffer | String, options: FileAppendOptions | RawOptions, callback: FsCallback0): Unit = js.native /** * Asynchronously append data to a file, creating the file if it does not yet exist. data can be a string or a buffer. * @param file the filename or file descriptor (Buffer | String | Number) * @param data the data to append (Buffer | String) * @param callback the callback function * @example fs.appendFile(file, data[, options], callback) */ def appendFile(file: Buffer | FileDescriptor | String, data: Buffer | String, callback: FsCallback0): Unit = js.native /** * The synchronous version of fs.appendFile(). * @param file the filename or file descriptor (Buffer | String | Number) * @param data the data to append (Buffer | String) * @param options the [[FileAppendOptions optional append settings]] * @return undefined. */ def appendFileSync(file: Buffer | FileDescriptor | String, data: Buffer | String, options: FileAppendOptions | RawOptions = js.native): Unit = js.native /** * Asynchronous chmod(2). No arguments other than a possible exception are given to the completion callback. * @param path the file or directory path (Buffer | String) * @param mode the file or directory mode * @param callback the completion callback. */ def chmod(path: Buffer | String | URL, mode: FileMode, callback: FsCallback0): Unit = js.native /** * Synchronous chmod(2). * @param path the file or directory path (Buffer | String) * @param mode the file or directory mode * @return undefined. */ def chmodSync(path: Buffer | String | URL, mode: FileMode): Unit = js.native /** * Asynchronous chown(2). No arguments other than a possible exception are given to the completion callback. * @param path the file or directory path (Buffer | String) * @param uid the user ID * @param gid the group ID * @param callback the completion callback. */ def chown(path: Buffer | String | URL, uid: UID, gid: GID, callback: FsCallback0): Unit = js.native /** * Synchronous chown(2). * @param path the file or directory path (Buffer | String) * @param uid the user ID * @param gid the group ID * @return undefined. */ def chownSync(path: Buffer | String | URL, uid: UID, gid: GID): Unit = js.native /** * Asynchronous close(2). No arguments other than a possible exception are given to the completion callback. * @example fs.close(fd, callback) */ def close(fd: FileDescriptor, callback: FsCallback0): Unit = js.native /** * Synchronous close(2). * @return undefined. * @example fs.closeSync(fd) */ def closeSync(fd: FileDescriptor): Unit = js.native /** * Asynchronously copies src to dest. By default, dest is overwritten if it already exists. No arguments other * than a possible exception are given to the callback function. Node.js makes no guarantees about the atomicity * of the copy operation. If an error occurs after the destination file has been opened for writing, Node.js will * attempt to remove the destination. * * flags is an optional integer that specifies the behavior of the copy operation. The only supported flag is * fs.constants.COPYFILE_EXCL, which causes the copy operation to fail if dest already exists. * @param src the source filename to copy * @param dest the destination filename of the copy operation * @param flags the modifiers for copy operation. Default: 0 * @param callback the callback function * @example {{{ fs.copyFile(src, dest[, flags], callback) }}} */ def copyFile(src: Buffer | String | URL, dest: Buffer | String | URL, flags: Flags, callback: js.Function): Unit = js.native /** * Asynchronously copies src to dest. By default, dest is overwritten if it already exists. No arguments other * than a possible exception are given to the callback function. Node.js makes no guarantees about the atomicity * of the copy operation. If an error occurs after the destination file has been opened for writing, Node.js will * attempt to remove the destination. * * flags is an optional integer that specifies the behavior of the copy operation. The only supported flag is * fs.constants.COPYFILE_EXCL, which causes the copy operation to fail if dest already exists. * @param src the source filename to copy * @param dest the destination filename of the copy operation * @param callback the callback function * @example {{{ fs.copyFile(src, dest[, flags], callback) }}} */ def copyFile(src: Buffer | String | URL, dest: Buffer | String | URL, callback: js.Function): Unit = js.native /** * Synchronously copies src to dest. By default, dest is overwritten if it already exists. * * Node.js makes no guarantees about the atomicity of the copy operation. If an error occurs after the destination * file has been opened for writing, Node.js will attempt to remove the destination. * * flags is an optional integer that specifies the behavior of the copy operation. The only supported flag is * fs.constants.COPYFILE_EXCL, which causes the copy operation to fail if dest already exists. * @param src the source filename to copy * @param dest the destination filename of the copy operation * @param flags the modifiers for copy operation. Default: 0 * @example {{{ fs.copyFileSync(src, dest[, flags]) }}} */ def copyFileSync(src: Buffer | String | URL, dest: Buffer | String | URL, flags: Flags): Unit = js.native /** * Returns a new ReadStream object. (See Readable Stream). Be aware that, unlike the default value * set for highWaterMark on a readable stream (16 kb), the stream returned by this method has a * default value of 64 kb for the same parameter. * @param path the path (Buffer | String) * @param options the optional stream options * @example fs.createReadStream(path[, options]) */ def createReadStream(path: Buffer | String | URL, options: FileInputOptions | RawOptions = js.native): ReadStream = js.native /** * Returns a new WriteStream object. * @param path the path (Buffer | String) * @param options the optional stream options * @example fs.createWriteStream(path[, options]) */ def createWriteStream(path: Buffer | String | URL, options: FileOutputOptions | RawOptions = js.native): WriteStream = js.native /** * Test whether or not the given path exists by checking with the file system. Then call the callback argument with * either true or false. * @example fs.exists('/etc/passwd', (exists) => { ... }) */ @deprecated("Use fs.stat() or fs.access() instead.", since = "1.0.0") def exists(path: Buffer | String | URL, callback: js.Function1[Boolean, Any]): Unit = js.native /** * fs.exists() should not be used to check if a file exists before calling fs.open(). Doing so introduces a race * condition since other processes may change the file's state between the two calls. Instead, user code should * call fs.open() directly and handle the error raised if the file is non-existent. * @example fs.existsSync(path) */ def existsSync(path: Buffer | String | URL): Boolean = js.native /** * Asynchronous fchmod(2). No arguments other than a possible exception are given to the completion callback. * @example fs.fchmod(fd, mode, callback) */ def fchmod(fd: FileDescriptor, mode: FileMode, callback: FsCallback0): Unit = js.native /** * Synchronous fchmod(2). * @return undefined. * @example fs.fchmodSync(fd, mode) */ def fchmodSync(fd: FileDescriptor, mode: FileMode): Unit = js.native /** * Asynchronous fchown(2). No arguments other than a possible exception are given to the completion callback. * @param path the file or directory path (Buffer | String) * @param uid the user ID * @param gid the group ID * @param callback the completion callback. */ def fchown(path: Buffer | String, uid: UID, gid: GID, callback: FsCallback0): Unit = js.native /** * Synchronous fchown(2). * @param path the file or directory path (Buffer | String) * @param uid the user ID * @param gid the group ID * @return undefined. * */ def fchownSync(path: Buffer | String, uid: UID, gid: GID): Unit = js.native /** * Asynchronous fdatasync(2). No arguments other than a possible exception are given to the completion callback. * @example fs.fdatasync(fd, callback) */ def fdatasync(fd: FileDescriptor, callback: FsCallback0): Unit = js.native /** * Synchronous fdatasync(2). * @return undefined. * @example fs.fdatasyncSync(fd) */ def fdatasyncSync(fd: FileDescriptor): Unit = js.native /** * Asynchronous fstat(2). The callback gets two arguments (err, stats) where stats is an fs.Stats object. * fstat() is identical to stat(), except that the file to be stat-ed is specified by the file descriptor fd. * @param fd the file descriptor * @param callback the completion callback. */ def fstat(fd: FileDescriptor, callback: FsCallback1[Stats]): Unit = js.native /** * Synchronous fstat(2). * @param fd the file descriptor * @return an instance of [[fs.Stats]]. */ def fstatSync(fd: FileDescriptor): Stats = js.native /** * Asynchronous fsync(2). No arguments other than a possible exception are given to the completion callback. * @param fd the file descriptor * @param callback the completion callback. */ def fsync(fd: FileDescriptor, callback: FsCallback0): Unit = js.native /** * Synchronous fsync(2). * @return undefined. * @param fd the file descriptor */ def fsyncSync(fd: FileDescriptor): Unit = js.native /** * Asynchronous ftruncate(2). No arguments other than a possible exception are given to the completion callback. * If the file referred to by the file descriptor was larger than length bytes, only the first length bytes will be * retained in the file. * @param fd the file descriptor * @param length the desired length * @param callback the completion callback. */ def ftruncate(fd: FileDescriptor, length: Double, callback: FsCallback0): Unit = js.native /** * Synchronous ftruncate(2). * @param fd the file descriptor * @param length the desired length * @return undefined. */ def ftruncateSync(fd: FileDescriptor, length: Double): Unit = js.native /** * Change the file timestamps of a file referenced by the supplied file descriptor. * @example fs.futimes(fd, atime, mtime, callback) */ def futimes(fd: FileDescriptor, atime: Integer, mtime: Integer, callback: js.Function): Unit = js.native /** * Synchronous version of fs.futimes(). * @return undefined. * @example fs.futimesSync(fd, atime, mtime) */ def futimesSync(fd: FileDescriptor, atime: Integer, mtime: Integer): Unit = js.native /** * Asynchronous lchmod(2). No arguments other than a possible exception are given to the completion callback. * @example fs.lchmod(path, mode, callback) */ def lchmod(path: Buffer | String, mode: FileMode, callback: FsCallback0): Unit = js.native /** * Synchronous lchmod(2). * @param path the path (Buffer | String) * @param mode the mode (Integer) * @return undefined. * @example fs.lchmodSync(path, mode) */ def lchmodSync(path: Buffer | String, mode: FileMode): Unit = js.native /** * Asynchronous lchown(2). No arguments other than a possible exception are given to the completion callback. * @param path the path (Buffer | String) * @param uid the user ID * @param gid the group ID * @param callback the completion callback. * @example fs.lchown(path, uid, gid, callback) */ def lchown(path: Buffer | String, uid: UID, gid: GID, callback: FsCallback0): Unit = js.native /** * Synchronous chown(2). * @param path the path (Buffer | String) * @param uid the user ID * @param gid the group ID * @return undefined. */ def lchownSync(path: Buffer | String, uid: UID, gid: GID): Unit = js.native /** * Asynchronous link(2). No arguments other than a possible exception are given to the completion callback. * @param existingPath the existing path * @param newPath the new path * @param callback the completion callback. * @example fs.link(srcpath, dstpath, callback) */ def link(existingPath: Buffer | String | URL, newPath: Buffer | String, callback: FsCallback0): Unit = js.native /** * Synchronous link(2). * @param existingPath the existing path * @param newPath the new path * @return undefined. */ def linkSync(existingPath: Buffer | String | URL, newPath: Buffer | String): Unit = js.native /** * Asynchronous lstat(2). * lstat() is identical to stat(), except that if path is a symbolic link, then the link itself is stat-ed, * not the file that it refers to. * @param path the path (Buffer | String) * @param callback The callback gets two arguments (err, stats) where stats is a fs.Stats object. */ def lstat(path: Buffer | String | URL, callback: FsCallback1[Stats]): Unit = js.native /** * Synchronous lstat(2). * @param path the path (Buffer | String) * @return an instance of [[fs.Stats]]. */ def lstatSync(path: Buffer | String | URL): Stats = js.native /** * Asynchronous mkdir(2). No arguments other than a possible exception are given to the completion callback. * mode defaults to 0o777. * @example fs.mkdir(path[, mode], callback) */ def mkdir(path: Buffer | String | URL, mode: FileMode, callback: FsCallback0): Unit = js.native /** * Asynchronous mkdir(2). No arguments other than a possible exception are given to the completion callback. * mode defaults to 0o777. * @example fs.mkdir(path[, mode], callback) */ def mkdir(path: Buffer | String | URL, callback: FsCallback0): Unit = js.native /** * Synchronous mkdir(2). * @param path the path * @param mode the mode */ def mkdirSync(path: Buffer | String, mode: FileMode = js.native): Unit = js.native /** * Creates a unique temporary directory. * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. * The created folder path is passed as a string to the callback's second parameter. * The optional options argument can be a string specifying an encoding, or an object with an * encoding property specifying the character encoding to use. * @param prefix the prefix * @param options the optional encoding setting * @param callback the callback * @example fs.mkdtemp(prefix[, options], callback) */ def mkdtemp(prefix: String, options: String | FileEncodingOptions | RawOptions, callback: FsCallback1[String]): Unit = js.native /** * Creates a unique temporary directory. * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. * The created folder path is passed as a string to the callback's second parameter. * The optional options argument can be a string specifying an encoding, or an object with an * encoding property specifying the character encoding to use. * @param prefix the prefix * @param callback the callback * @example fs.mkdtemp(prefix[, options], callback) */ def mkdtemp(prefix: String, callback: FsCallback1[String]): Unit = js.native /** * The synchronous version of fs.mkdtemp(). Returns the created folder path. * The optional options argument can be a string specifying an encoding, or an object with * an encoding property specifying the character encoding to use. * @param prefix the prefix * @param options the optional encoding setting */ def mkdtempSync(prefix: String, options: String | FileEncodingOptions | RawOptions = js.native): String = js.native /** * Asynchronous file open. See open(2). * @param path the path (Buffer | String) * @param flags flags can be: * <ul> * <li>'r' - Open file for reading. An exception occurs if the file does not exist.</li> * <li>'r+' - Open file for reading and writing. An exception occurs if the file does not exist.</li> * <li>'rs+' - Open file for reading and writing in synchronous mode. * Instructs the operating system to bypass the local file system cache. * This is primarily useful for opening files on NFS mounts as it allows you to skip * the potentially stale local cache. It has a very real impact on I/O performance * so don't use this flag unless you need it. * Note that this doesn't turn fs.open() into a synchronous blocking call. * If that's what you want then you should be using fs.openSync()</li> * <li>'w' - Open file for writing. The file is created (if it does not exist) or truncated (if it exists).</li> * <li>'wx' - Like 'w' but fails if path exists.</li> * <li>'w+' - Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists).</li> * <li>'wx+' - Like 'w+' but fails if path exists.</li> * <li>'a' - Open file for appending. The file is created if it does not exist.</li> * <li>'ax' - Like 'a' but fails if path exists.</li> * <li>'a+' - Open file for reading and appending. The file is created if it does not exist.</li> * <li>'ax+' - Like 'a+' but fails if path exists.</li> * </ul> * @param mode sets the file mode (permission and sticky bits), but only if the file was created. * It defaults to 0666, readable and writable. * @param callback the callback gets two arguments (err, fd) * @example fs.open(path, flags[, mode], callback) */ def open(path: Buffer | String | URL, flags: Flags, mode: FileMode, callback: FsCallback1[FileDescriptor]): Unit = js.native /** * Asynchronous file open. See open(2). * @param path the path (Buffer | String) * @param flags flags can be: * <ul> * <li>'r' - Open file for reading. An exception occurs if the file does not exist.</li> * <li>'r+' - Open file for reading and writing. An exception occurs if the file does not exist.</li> * <li>'rs+' - Open file for reading and writing in synchronous mode. * Instructs the operating system to bypass the local file system cache. * This is primarily useful for opening files on NFS mounts as it allows you to skip * the potentially stale local cache. It has a very real impact on I/O performance * so don't use this flag unless you need it. * Note that this doesn't turn fs.open() into a synchronous blocking call. * If that's what you want then you should be using fs.openSync()</li> * <li>'w' - Open file for writing. The file is created (if it does not exist) or truncated (if it exists).</li> * <li>'wx' - Like 'w' but fails if path exists.</li> * <li>'w+' - Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists).</li> * <li>'wx+' - Like 'w+' but fails if path exists.</li> * <li>'a' - Open file for appending. The file is created if it does not exist.</li> * <li>'ax' - Like 'a' but fails if path exists.</li> * <li>'a+' - Open file for reading and appending. The file is created if it does not exist.</li> * <li>'ax+' - Like 'a+' but fails if path exists.</li> * </ul> * @param callback the callback gets two arguments (err, fd) * @example fs.open(path, flags[, mode], callback) */ def open(path: Buffer | String | URL, flags: Flags, callback: FsCallback1[FileDescriptor]): Unit = js.native /** * Synchronous version of fs.open(). * @param path the path (Buffer | String) * @param flags the flags * @param mode the file mode * @return an integer representing the file descriptor. * @example fs.openSync(path, flags[, mode]) */ def openSync(path: Buffer | String | URL, flags: Flags, mode: FileMode = js.native): FileDescriptor = js.native /** * Read data from the file specified by fd. * @param fd is the file descriptor * @param buffer is the buffer that the data will be written to. * @param offset is the offset in the buffer to start writing at. * @param length is an integer specifying the number of bytes to read. * @param position is an integer specifying where to begin reading from in the file. If position is null, * data will be read from the current file position. * @param callback the callback is given the three arguments, (err, bytesRead, buffer). */ def read(fd: FileDescriptor, buffer: Buffer, offset: Int, length: Int, position: Int, callback: FsCallback2[Int, Buffer]): Unit = js.native /** * Synchronous version of fs.read(). * @param fd is the file descriptor * @param buffer is the buffer that the data will be written to. * @param offset is the offset in the buffer to start writing at. * @param length is an integer specifying the number of bytes to read. * @param position is an integer specifying where to begin reading from in the file. If position is null, * data will be read from the current file position. * @return the number of bytesRead. */ def readSync(fd: FileDescriptor, buffer: Buffer, offset: Int, length: Int, position: Int): Int = js.native /** * Asynchronous readdir(3). Reads the contents of a directory. * @param path the path (Buffer | String) * @param options the optional options argument can be a string specifying an encoding, * or an object with an encoding property specifying the character encoding * to use for the filenames passed to the callback. If the encoding is set * to 'buffer', the filenames returned will be passed as Buffer objects. * @param callback the callback gets two arguments (err, files) where files is an array * of the names of the files in the directory excluding '.' and '..'. * @example fs.readdir(path[, options], callback) */ def readdir(path: Buffer | String | URL, options: String | FileEncodingOptions | RawOptions, callback: FsCallback1[js.Array[String]]): Unit = js.native /** * Asynchronous readdir(3). Reads the contents of a directory. * @param path the path (Buffer | String) * @param callback the callback gets two arguments (err, files) where files is an array * of the names of the files in the directory excluding '.' and '..'. * @example fs.readdir(path[, options], callback) */ def readdir(path: Buffer | String | URL, callback: FsCallback1[js.Array[String]]): Unit = js.native /** * Synchronous readdir(3). * @param path the path (Buffer | String) * @param options the optional options argument can be a string specifying an encoding, * or an object with an encoding property specifying the character encoding * to use for the filenames passed to the callback. If the encoding is set * to 'buffer', the filenames returned will be passed as Buffer objects. * @return an array of filenames excluding '.' and '..'. */ def readdirSync(path: Buffer | String | URL, options: String | FileEncodingOptions | RawOptions = js.native): js.Array[String] = js.native /** * Asynchronously reads the entire contents of a file. * @param file filename or file descriptor * @param options the optional settings * @param callback The callback is passed two arguments (err, data), where data is the contents of the file. * If no encoding is specified, then the raw buffer is returned. * @example fs.readFile(file[, options], callback) */ def readFile(file: Buffer | FileDescriptor | String | URL, options: String | FileInputOptions | RawOptions | String, callback: FsCallback1[js.Any]): Unit = js.native /** * Asynchronously reads the entire contents of a file. * @param file filename or file descriptor * @param encoding the encoding (default = null) * @param callback The callback is passed two arguments (err, data), where data is the contents of the file. * If no encoding is specified, then the raw buffer is returned. * @example fs.readFile(file[, options], callback) */ def readFile(file: Buffer | FileDescriptor | String | URL, encoding: String, callback: FsCallback1[String]): Unit = js.native /** * Asynchronously reads the entire contents of a file. * @param file filename or file descriptor * @param callback The callback is passed two arguments (err, data), where data is the contents of the file. * If no encoding is specified, then the raw buffer is returned. * @example fs.readFile(file[, options], callback) */ def readFile(file: Buffer | FileDescriptor | String | URL, callback: FsCallback1[Buffer]): Unit = js.native /** * Synchronous version of fs.readFile. Returns the contents of the file. * @param file filename or file descriptor <String> | <Buffer> | <Integer> * @param encoding the optional encoding <Object> | <String> * @return the contents of the file. If the encoding option is specified then this function returns a string. * Otherwise it returns a buffer. * @example fs.readFileSync(file[, options]) */ def readFileSync(file: Buffer | FileDescriptor | String | URL, encoding: String): String = js.native /** * Synchronous version of fs.readFile. Returns the contents of the file. * @param file filename or file descriptor <String> | <Buffer> | <Integer> * @param options the optional encoding <Object> | <String> * @return the contents of the file. If the encoding option is specified then this function returns a string. * Otherwise it returns a buffer. * @example fs.readFileSync(file[, options]) */ def readFileSync(file: Buffer | FileDescriptor | String | URL, options: FileInputOptions | RawOptions = js.native): js.Any = js.native /** * Synchronous version of fs.readFile. * @param file filename or file descriptor <String> | <Buffer> | <Integer> * @return the contents of the file. If the encoding option is specified then this function returns a string. * Otherwise it returns a buffer. * @example fs.readFileSync(file[, options]) */ def readFileSync(file: Buffer | FileDescriptor | String | URL): Buffer = js.native /** * Asynchronous readlink(2). * If the encoding is set to 'buffer', the link path returned will be passed as a Buffer object. * @param path the path (Buffer | String) * @param options the optional options argument can be a string specifying an encoding, or an object * with an encoding property specifying the character encoding to use for the link path * passed to the callback. * @param callback the callback gets two arguments (err, linkString). * @example fs.readlink(path[, options], callback) */ def readlink(path: Buffer | String | URL, options: String | FileEncodingOptions | RawOptions, callback: FsCallback1[String]): Unit = js.native /** * Synchronous readlink(2). * @param path the path (Buffer | String) * @param options the optional options argument can be a string specifying an encoding, * or an object with an encoding property specifying the character encoding * to use for the link path passed to the callback. If the encoding is set * to 'buffer', the link path returned will be passed as a Buffer object. * @return the symbolic link's string value. */ def readlinkSync(path: Buffer | String | URL, options: String | FileEncodingOptions | RawOptions = js.native): String = js.native /** * Asynchronous realpath(2). * May use process.cwd to resolve relative paths. * @param path the path * @param options The optional options argument can be a string specifying an encoding, or an object with * an encoding property specifying the character encoding to use for the path passed to the callback. * @param callback The callback gets two arguments (err, resolvedPath). * If the encoding is set to 'buffer', * the path returned will be passed as a Buffer object. * @example fs.realpath(path[, options], callback) */ def realpath(path: Buffer | String | URL, options: FileEncodingOptions | String | RawOptions, callback: FsCallback1[String]): Unit = js.native /** * Asynchronous realpath(2). The callback gets two arguments (err, resolvedPath). * May use process.cwd to resolve relative paths. * * The optional options argument can be a string specifying an encoding, or an object with an encoding property * specifying the character encoding to use for the path passed to the callback. If the encoding is set to 'buffer', * the path returned will be passed as a Buffer object. * @example fs.realpath(path[, options], callback) */ def realpath(path: Buffer | String | URL, callback: FsCallback1[String]): Unit = js.native /** * Synchronous realpath(3). * Only paths that can be converted to UTF8 strings are supported. * The optional options argument can be a string specifying an encoding, or an object with an * encoding property specifying the character encoding to use for the returned value. If the * encoding is set to 'buffer', the path returned will be passed as a Buffer object. * @return the resolved path. * @example fs.realpathSync(path[, options]) */ def realpathSync(path: Buffer | String | URL, options: FileEncodingOptions | String | RawOptions = js.native): String = js.native /** * Asynchronous rename(2). No arguments other than a possible exception are given to the completion callback. * @example fs.rename(oldPath, newPath, callback) */ def rename(oldPath: Buffer | String | URL, newPath: Buffer | String | URL, callback: FsCallback0): Unit = js.native /** * Synchronous rename(2). * @return undefined. * @example fs.renameSync(oldPath, newPath) */ def renameSync(oldPath: Buffer | String | URL, newPath: Buffer | String | URL): Unit = js.native /** * Asynchronous rmdir(2). No arguments other than a possible exception are given to the completion callback. * @example fs.rmdir(path, callback) */ def rmdir(path: Buffer | String | URL, callback: FsCallback0): Unit = js.native /** * Synchronous rmdir(2). * @return undefined. * @example fs.rmdirSync(path) */ def rmdirSync(path: Buffer | String | URL): Unit = js.native /** * Asynchronous stat(2). The callback gets two arguments (err, stats) where stats is a [[fs.Stats]] object. * See the fs.Stats section for more information. * @example fs.stat(path, callback) */ def stat(path: Buffer | String | URL, callback: FsCallback1[Stats]): Stats = js.native /** * Synchronous stat(2). Returns an instance of [[fs.Stats]]. * @example fs.statSync(path) */ def statSync(path: Buffer | String | URL): Stats = js.native /** * Asynchronous symlink(2). No arguments other than a possible exception are given to the completion callback. * The type argument can be set to 'dir', 'file', or 'junction' (default is 'file') and is only available on Windows * (ignored on other platforms). Note that Windows junction points require the destination path to be absolute. * When using 'junction', the target argument will automatically be normalized to absolute path. * @example fs.symlink(target, path[, type], callback) */ def symlink(target: Buffer | String | URL, path: Buffer | String | URL, `type`: String, callback: FsCallback0): Unit = js.native /** * Asynchronous symlink(2). No arguments other than a possible exception are given to the completion callback. * The type argument can be set to 'dir', 'file', or 'junction' (default is 'file') and is only available on Windows * (ignored on other platforms). Note that Windows junction points require the destination path to be absolute. * When using 'junction', the target argument will automatically be normalized to absolute path. * @example fs.symlink(target, path[, type], callback) */ def symlink(target: Buffer | String | URL, path: Buffer | String | URL, callback: FsCallback0): Unit = js.native /** * Synchronous symlink(2). * @return undefined. * @example fs.symlinkSync(target, path[, type]) */ def symlinkSync(target: Buffer | String | URL, path: Buffer | String | URL, `type`: String = js.native): Unit = js.native /** * Asynchronous truncate(2). No arguments other than a possible exception are given to the completion callback. * A file descriptor can also be passed as the first argument. In this case, fs.ftruncate() is called. * @param path the path <String> | <Buffer> * @param length the length * @param callback the completion callback. * @example fs.truncate(path, length, callback) */ def truncate(path: Buffer | FileDescriptor | String, length: Int, callback: FsCallback0): Unit = js.native /** * Synchronous truncate(2). * In this case, fs.ftruncateSync() is called. * @param path the path or file descriptor - <String> | <Buffer> | <Integer> * @param length the length * @return undefined. * @example fs.truncateSync(path, length) */ def truncateSync(path: Buffer | FileDescriptor | String, length: Int): Unit = js.native /** * Asynchronous unlink(2). No arguments other than a possible exception are given to the completion callback. * @example fs.unlink(path, callback) */ def unlink(path: Buffer | String | URL, callback: FsCallback0): Unit = js.native /** * Synchronous unlink(2). * @return undefined. * @example fs.unlinkSync(path) */ def unlinkSync(path: Buffer | String | URL): Unit = js.native /** * Stop watching for changes on filename. If listener is specified, only that particular listener is removed. * Otherwise, all listeners are removed and you have effectively stopped watching filename. * * Calling fs.unwatchFile() with a filename that is not being watched is a no-op, not an error. * * Note: fs.watch() is more efficient than fs.watchFile() and fs.unwatchFile(). fs.watch() should be used instead of * fs.watchFile() and fs.unwatchFile() when possible. * @example fs.unwatchFile(filename[, listener]) */ def unwatchFile(filename: Buffer | String, listener: FsCallback0 = js.native): Unit = js.native /** * Change file timestamps of the file referenced by the supplied path. * * Note: the arguments atime and mtime of the following related functions does follow the below rules: * * If the value is a numberable string like '123456789', the value would get converted to corresponding number. * If the value is NaN or Infinity, the value would get converted to Date.now(). * @example fs.utimes(path, atime, mtime, callback) */ def utimes(path: Buffer | String | URL, atime: Int, mtime: Int, callback: FsCallback0): Unit = js.native /** * Synchronous version of fs.utimes(). * @return undefined. * @example fs.utimesSync(path, atime, mtime) */ def utimesSync(path: Buffer | String | URL, atime: Int, mtime: Int): Unit = js.native /** * Watch for changes on filename, where filename is either a file or a directory. * The returned object is a [[fs.FSWatcher]]. * * The second argument is optional. If options is provided as a string, it specifies the encoding. * Otherwise options should be passed as an object. * * The listener callback gets two arguments (event, filename). event is either 'rename' or 'change', and filename * is the name of the file which triggered the event. * @param filename the filename (Buffer | String) * @param options the [[FSWatcherOptions optional settings]] * @param listener the callback function * @return a [[FSWatcher]] * @example fs.watch(filename[, options][, listener]) */ def watch(filename: Buffer | String | URL, options: FSWatcherOptions | RawOptions, listener: js.Function2[EventType, String, Any]): FSWatcher = js.native /** * Watch for changes on filename, where filename is either a file or a directory. * The returned object is a [[fs.FSWatcher]]. * * The second argument is optional. If options is provided as a string, it specifies the encoding. * Otherwise options should be passed as an object. * * The listener callback gets two arguments (event, filename). event is either 'rename' or 'change', and filename * is the name of the file which triggered the event. * @param filename the filename (Buffer | String) * @param listener the listener callback gets two arguments (eventType, filename). * eventType is either 'rename' or 'change', * and filename is the name of the file which triggered the event. * @return a [[FSWatcher]] * @example fs.watch(filename[, options][, listener]) */ def watch(filename: Buffer | String | URL, listener: js.Function2[EventType, String, Any]): FSWatcher = js.native /** * Watch for changes on filename, where filename is either a file or a directory. * The returned object is a [[fs.FSWatcher]]. * * The second argument is optional. If options is provided as a string, it specifies the encoding. * Otherwise options should be passed as an object. * * The listener callback gets two arguments (event, filename). event is either 'rename' or 'change', and filename * is the name of the file which triggered the event. * @param filename the filename (Buffer | String) * @param options the [[FSWatcherOptions optional settings]] * @return a [[FSWatcher]] * @example fs.watch(filename[, options][, listener]) */ def watch(filename: Buffer | String | URL, options: FSWatcherOptions | RawOptions = js.native): FSWatcher = js.native /** * Watch for changes on filename. The callback listener will be called each time the file is accessed. * * The options argument may be omitted. If provided, it should be an object. The options object may contain * a boolean named persistent that indicates whether the process should continue to run as long as files are * being watched. The options object may specify an interval property indicating how often the target should * be polled in milliseconds. The default is { persistent: true, interval: 5007 }. * @param filename the filename (Buffer | String) * @param options the [[FSWatcherOptions optional settings]] * @param listener the callback */ def watchFile(filename: Buffer | String | URL, options: FileWatcherOptions | RawOptions, listener: FsCallback2[Stats, Stats]): Unit = js.native /** * Watch for changes on filename. The callback listener will be called each time the file is accessed. * * The options argument may be omitted. If provided, it should be an object. The options object may contain * a boolean named persistent that indicates whether the process should continue to run as long as files are * being watched. The options object may specify an interval property indicating how often the target should * be polled in milliseconds. The default is { persistent: true, interval: 5007 }. * @param filename the filename (Buffer | String) * @param listener the callback */ def watchFile(filename: Buffer | String, listener: FsCallback2[Stats, Stats]): Unit = js.native /** * Write buffer to the file specified by fd. * <p><b>Note</b>: that it is unsafe to use fs.write multiple times on the same file without waiting for the callback. * For this scenario, fs.createWriteStream is strongly recommended.</p> * <p>On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the * position argument and always appends the data to the end of the file.</p> * @param fd the file descriptor * @param buffer the buffer containing the data to write * @param offset determines the part of the buffer to be written, and length is an integer specifying * the number of bytes to write. * @param length the optional length of the data to write * @param position refers to the offset from the beginning of the file where this data should be written. * If typeof position !== 'number', the data will be written at the current position. See pwrite(2). * @param callback will be given three arguments (err, written, buffer) where written specifies how many * bytes were written from buffer. * @example {{{ fs.write(fd, buffer[, offset[, length[, position]]], callback) }}} **/ def write(fd: FileDescriptor, buffer: Buffer | Uint8Array, offset: Integer = js.native, length: Integer = js.native, position: Integer = js.native, callback: FsCallback2[Int, Buffer]): Unit = js.native /** * Write buffer to the file specified by fd. * <p><b>Note</b>: that it is unsafe to use fs.write multiple times on the same file without waiting for the callback. * For this scenario, fs.createWriteStream is strongly recommended.</p> * <p>On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the * position argument and always appends the data to the end of the file.</p> * @param fd the file descriptor * @param buffer the buffer containing the data to write * If typeof position !== 'number', the data will be written at the current position. See pwrite(2). * @param callback will be given three arguments (err, written, buffer) where written specifies how many * bytes were written from buffer. * @example {{{ fs.write(fd, buffer[, offset[, length[, position]]], callback) }}} **/ def write(fd: FileDescriptor, buffer: Buffer | Uint8Array, callback: FsCallback2[Int, Buffer]): Unit = js.native /** * Write string to the file specified by fd. If string is not a string, then the value will be coerced to one. * Unlike when writing buffer, the entire string must be written. No substring may be specified. * This is because the byte offset of the resulting data may not be the same as the string offset. * Note that it is unsafe to use fs.write multiple times on the same file without waiting for the callback. * For this scenario, fs.createWriteStream is strongly recommended. * On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the * position argument and always appends the data to the end of the file. * @param fd the file descriptor * @param string the data to write * @param position refers to the offset from the beginning of the file where this data should be written. * If typeof position !== 'number' the data will be written at the current position. See pwrite(2). * @param encoding is the expected string encoding. * @param callback will receive the arguments (err, written, string) where written specifies how many bytes * the passed string required to be written. Note that bytes written is not the same as * string characters. See Buffer.byteLength. * @example {{{ fs.write(fd, string[, position[, encoding]], callback) }}} */ def write(fd: FileDescriptor, string: String, position: Int, encoding: String, callback: FsCallback2[Int, String]): Unit = js.native /** * Write string to the file specified by fd. If string is not a string, then the value will be coerced to one. * Unlike when writing buffer, the entire string must be written. No substring may be specified. * This is because the byte offset of the resulting data may not be the same as the string offset. * Note that it is unsafe to use fs.write multiple times on the same file without waiting for the callback. * For this scenario, fs.createWriteStream is strongly recommended. * On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the * position argument and always appends the data to the end of the file. * @param fd the file descriptor * @param string the data to write * @param encoding is the expected string encoding. * @param callback will receive the arguments (err, written, string) where written specifies how many bytes * the passed string required to be written. Note that bytes written is not the same as * string characters. See Buffer.byteLength. * @example {{{ fs.write(fd, string[, position[, encoding]], callback) }}} */ def write(fd: FileDescriptor, string: String, encoding: String, callback: FsCallback2[Int, String]): Unit = js.native /** * Write string to the file specified by fd. If string is not a string, then the value will be coerced to one. * Unlike when writing buffer, the entire string must be written. No substring may be specified. * This is because the byte offset of the resulting data may not be the same as the string offset. * Note that it is unsafe to use fs.write multiple times on the same file without waiting for the callback. * For this scenario, fs.createWriteStream is strongly recommended. * On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the * position argument and always appends the data to the end of the file. * @param fd the file descriptor * @param string the data to write * @param callback will receive the arguments (err, written, string) where written specifies how many bytes * the passed string required to be written. Note that bytes written is not the same as * string characters. See Buffer.byteLength. * @example {{{ fs.write(fd, string[, position[, encoding]], callback) }}} */ def write(fd: FileDescriptor, string: String, callback: FsCallback2[Int, String]): Unit = js.native /** * Asynchronously writes data to a file, replacing the file if it already exists. data can be a string or a buffer. * The encoding option is ignored if data is a buffer. It defaults to 'utf8' * @example fs.writeFile(file, data[, options], callback) */ def writeFile(file: String, data: Buffer | String, options: FileOutputOptions | RawOptions, callback: FsCallback0): Unit = js.native /** * Asynchronously writes data to a file, replacing the file if it already exists. data can be a string or a buffer. * The encoding option is ignored if data is a buffer. It defaults to 'utf8' * @example fs.writeFile(file, data[, options], callback) */ def writeFile(file: String, data: Buffer | String, callback: FsCallback0): Unit = js.native /** * The synchronous version of fs.writeFile(). * @return undefined. * @example fs.writeFileSync(file, data[, options]) */ def writeFileSync(file: String, data: Buffer | String, options: FileOutputOptions | RawOptions = js.native): Unit = js.native /** * Write buffer to the file specified by fd. * @param fd the given file descriptor * @param buffer the given [[Buffer buffer]] * @param offset determines the part of the buffer to be written, and length is an integer specifying * the number of bytes to write. * @param length the optional length of the data to write * @param position refers to the offset from the beginning of the file where this data should be written. * @example {{{ fs.writeSync(fd, buffer[, offset[, length[, position]]]) }}} */ def writeSync(fd: FileDescriptor, buffer: Buffer | Uint8Array, offset: Int = js.native, length: Int = js.native, position: Int = js.native): Unit = js.native /** * Write buffer to the file specified by fd. * @param fd the given file descriptor * @param buffer the given [[Buffer buffer]] * @example {{{ fs.writeSync(fd, buffer[, offset[, length[, position]]]) }}} */ def writeSync(fd: FileDescriptor, buffer: Buffer | Uint8Array): Unit = js.native /** * Write string to the file specified by fd. * @param fd the given file descriptor * @param data the given string * @param position refers to the offset from the beginning of the file where this data should be written. * @param encoding is the expected string encoding. * @example {{{ fs.writeSync(fd, string[, position[, encoding]]) }}} */ def writeSync(fd: FileDescriptor, data: String, position: Int, encoding: String): Unit = js.native /** * Write string to the file specified by fd. * @param fd the given file descriptor * @param data the given string * @param position refers to the offset from the beginning of the file where this data should be written. * @example {{{ fs.writeSync(fd, string[, position[, encoding]]) }}} */ def writeSync(fd: FileDescriptor, data: String, position: Int): Unit = js.native /** * Write string to the file specified by fd. * @param fd the given file descriptor * @param data the given string * @param encoding is the expected string encoding. * @example {{{ fs.writeSync(fd, string[, position[, encoding]]) }}} */ def writeSync(fd: FileDescriptor, data: String, encoding: String): Unit = js.native /** * Write string to the file specified by fd. * @param fd the given file descriptor * @param data the given string * @example {{{ fs.writeSync(fd, string[, position[, encoding]]) }}} */ def writeSync(fd: FileDescriptor, data: String): Unit = js.native } /** * File System Singleton * @author [email protected] */ @js.native @JSImport("fs", JSImport.Namespace) object Fs extends Fs /** * File Append Options * @author [email protected] */ class FileAppendOptions(val encoding: js.UndefOr[String] = js.undefined, val mode: js.UndefOr[FileMode] = js.undefined, val flag: js.UndefOr[String] = js.undefined) extends js.Object /** * File Encoding Options * @author [email protected] */ class FileEncodingOptions(val encoding: js.UndefOr[String] = js.undefined) extends js.Object /** * File Input Options * @author [email protected] */ class FileInputOptions(val flags: js.UndefOr[String] = js.undefined, val encoding: js.UndefOr[String] = js.undefined, val fd: js.UndefOr[FileDescriptor] = js.undefined, val mode: js.UndefOr[Int] = js.undefined, val autoClose: js.UndefOr[Boolean] = js.undefined, val start: js.UndefOr[Int] = js.undefined, val end: js.UndefOr[Int] = js.undefined) extends js.Object /** * File Input Options * @author [email protected] */ class FileOutputOptions(val flags: js.UndefOr[String] = js.undefined, val defaultEncoding: js.UndefOr[String] = js.undefined, val fd: js.UndefOr[FileDescriptor] = js.undefined, val mode: js.UndefOr[Int] = js.undefined, val autoClose: js.UndefOr[Boolean] = js.undefined, val start: js.UndefOr[Int] = js.undefined) extends js.Object /** * File Watcher Options * @param persistent <Boolean> * @param interval <Integer> */ class FileWatcherOptions(val persistent: js.UndefOr[Boolean] = js.undefined, val interval: js.UndefOr[Int] = js.undefined) extends js.Object
{ "content_hash": "4deb0d5dca1f67dbe01117814a3845df", "timestamp": "", "source": "github", "line_count": 1184, "max_line_length": 159, "avg_line_length": 49.56925675675676, "alnum_prop": 0.6610666212301926, "repo_name": "ldaniels528/scalajs-nodejs", "id": "dbb8064dd4b9c207cfba70edcc9c553cc3e19c7a", "size": "58690", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "app/current/src/main/scala/io/scalajs/nodejs/fs/Fs.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "JavaScript", "bytes": "454" }, { "name": "Scala", "bytes": "1483505" } ], "symlink_target": "" }
require "helper/spec" describe Spurious::Server::State::Init do it "Pulls down the docker images down and sends response back to client" do connection_double = double('Spurious::Server::App') config_stub = { :foo => { :image => 'foo/bar', :name => 'foo-bar' } } config = double('Spurious::Server::Config', :app => config_stub, :length => 0) state = Spurious::Server::State::Init.new(connection_double, config) allow(Docker::Image).to receive(:create).once.with('fromImage' => 'foo/bar').and_return(true) allow(Docker::Container).to receive(:create).once.with('name' => 'foo-bar', 'Image' => 'foo/bar').and_return(true) allow(EM).to receive(:add_timer).twice state.execute! end end
{ "content_hash": "7eb9b6dc9b21297c9f9f8c150e94a913", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 118, "avg_line_length": 29.115384615384617, "alnum_prop": 0.6327608982826949, "repo_name": "spurious-io/server", "id": "f3c75fb9bfa61d6d013d0c935c459fef09e0938e", "size": "757", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/state_init_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "24586" } ], "symlink_target": "" }
#import <MetaWear/MBLConstants.h> #import <MetaWear/MBLModule.h> /** Interface to external haptic or buzzers */ @interface MBLHapticBuzzer : MBLModule /** Turn on Haptic Driver. @param dcycle Duty cycle (0-248), relative strength of buzz @param pwidth Duration of buzz in mSec @param completion Callback when the buzz is complete */ - (void)startHapticWithDutyCycle:(uint8_t)dcycle pulseWidth:(uint16_t)pwidth completion:(MBLVoidHandler)completion; /** Turn on Buzzer Driver. @param pwidth Duration of buzz in mSec @param completion Callback when the buzz is complete */ - (void)startBuzzerWithPulseWidth:(uint16_t)pwidth completion:(MBLVoidHandler)completion; @end
{ "content_hash": "4d982b1ae5f646670640375a7c096e43", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 115, "avg_line_length": 26.26923076923077, "alnum_prop": 0.7701317715959004, "repo_name": "iic-ninjas/metawear-ball", "id": "28b45dff9327e87c799c98953c160e9d91708600", "size": "2604", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "MetaWear.framework/Versions/A/Headers/MBLHapticBuzzer.h", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "200691" } ], "symlink_target": "" }
#region License #endregion using System; namespace Example { public class WeakReferenceExamples { } }
{ "content_hash": "b3f3cfc6f4d3af3261cfde4b9fc3f6b1", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 35, "avg_line_length": 11.5, "alnum_prop": 0.7043478260869566, "repo_name": "BclEx/AdamsyncEx", "id": "2f3d4aa8acbce09b283a66db2ad7fb7631cb1364", "size": "1214", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/DocsExamples/WeakReferenceExamples.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "27776" }, { "name": "C#", "bytes": "2433052" }, { "name": "JavaScript", "bytes": "27776" }, { "name": "PowerShell", "bytes": "31915" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StudentsAndWorkers.Models { public class Student : Human { public int Grade { get; set; } public Student(string firstName, string lastName, int grade) : base(firstName, lastName) { this.Grade = grade; } } }
{ "content_hash": "4ce1dde0c1e4e97b2402333076fa2e62", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 62, "avg_line_length": 18.57894736842105, "alnum_prop": 0.7252124645892352, "repo_name": "SHAMMY1/Telerik-Academy", "id": "0a4b6ed5f6c7922976ea1369ff5319e0ed72ecba", "size": "355", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Homeworks/CSharpOOP/04.OOPPrinciplesOne/OOPPrinciplesOneHomework/StudentsAndWorkers/Models/Student.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "504470" } ], "symlink_target": "" }
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("04. Numbers in Reversed Order")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("04. Numbers in Reversed Order")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("ec1b54f1-28cf-475e-9f01-83311347b3ec")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
{ "content_hash": "d4d61b21c1cfb91f83f170047b361117", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 84, "avg_line_length": 39.75, "alnum_prop": 0.7442348008385744, "repo_name": "NikiStanchev/SoftUni", "id": "5c1f93d378c666e0fa2d95fb0628d00cd0e1f41d", "size": "1434", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Programming Fundamentals/Methods and Debugging - Exercises/04. Numbers in Reversed Order/Properties/AssemblyInfo.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "950061" }, { "name": "CSS", "bytes": "82538" }, { "name": "HTML", "bytes": "295262" }, { "name": "JavaScript", "bytes": "733396" }, { "name": "TypeScript", "bytes": "195372" } ], "symlink_target": "" }
// +build linux package mount import ( "os" "path/filepath" "strings" "github.com/golang/glog" "k8s.io/kubernetes/pkg/util/exec" ) // NsenterMounter is part of experimental support for running the kubelet // in a container. Currently, all docker containers receive their own mount // namespaces. NsenterMounter works by executing nsenter to run commands in // the host's mount namespace. // // NsenterMounter requires: // // 1. Docker >= 1.6 due to the dependency on the slave propagation mode // of the bind-mount of the kubelet root directory in the container. // Docker 1.5 used a private propagation mode for bind-mounts, so mounts // performed in the host's mount namespace do not propagate out to the // bind-mount in this docker version. // 2. The host's root filesystem must be available at /rootfs // 3. The nsenter binary must be on the Kubelet process' PATH in the container's // filesystem. // 4. The Kubelet process must have CAP_SYS_ADMIN (required by nsenter); at // the present, this effectively means that the kubelet is running in a // privileged container. // 5. The volume path used by the Kubelet must be the same inside and outside // the container and be writable by the container (to initialize volume) // contents. TODO: remove this requirement. // 6. The host image must have mount, stat, and umount binaries in /bin, // /usr/sbin, or /usr/bin // // For more information about mount propagation modes, see: // https://www.kernel.org/doc/Documentation/filesystems/sharedsubtree.txt type NsenterMounter struct { // a map of commands to their paths on the host filesystem paths map[string]string } func NewNsenterMounter() *NsenterMounter { m := &NsenterMounter{ paths: map[string]string{ "mount": "", "stat": "", "umount": "", }, } // search for the mount command in other locations besides /usr/bin for binary := range m.paths { // default to root m.paths[binary] = filepath.Join("/", binary) for _, path := range []string{"/bin", "/usr/sbin", "/usr/bin"} { binPath := filepath.Join(path, binary) if _, err := os.Stat(filepath.Join(hostRootFsPath, binPath)); err != nil { continue } m.paths[binary] = binPath break } // TODO: error, so that the kubelet can stop if the mounts don't exist } return m } // NsenterMounter implements mount.Interface var _ = Interface(&NsenterMounter{}) const ( hostRootFsPath = "/rootfs" hostProcMountsPath = "/rootfs/proc/mounts" nsenterPath = "nsenter" ) // Mount runs mount(8) in the host's root mount namespace. Aside from this // aspect, Mount has the same semantics as the mounter returned by mount.New() func (n *NsenterMounter) Mount(source string, target string, fstype string, options []string) error { bind, bindRemountOpts := isBind(options) if bind { err := n.doNsenterMount(source, target, fstype, []string{"bind"}) if err != nil { return err } return n.doNsenterMount(source, target, fstype, bindRemountOpts) } return n.doNsenterMount(source, target, fstype, options) } // doNsenterMount nsenters the host's mount namespace and performs the // requested mount. func (n *NsenterMounter) doNsenterMount(source, target, fstype string, options []string) error { glog.V(5).Infof("nsenter Mounting %s %s %s %v", source, target, fstype, options) args := n.makeNsenterArgs(source, target, fstype, options) glog.V(5).Infof("Mount command: %v %v", nsenterPath, args) exec := exec.New() outputBytes, err := exec.Command(nsenterPath, args...).CombinedOutput() if len(outputBytes) != 0 { glog.V(5).Infof("Output from mount command: %v", string(outputBytes)) } return err } // makeNsenterArgs makes a list of argument to nsenter in order to do the // requested mount. func (n *NsenterMounter) makeNsenterArgs(source, target, fstype string, options []string) []string { nsenterArgs := []string{ "--mount=/rootfs/proc/1/ns/mnt", "--", n.absHostPath("mount"), } args := makeMountArgs(source, target, fstype, options) return append(nsenterArgs, args...) } // Unmount runs umount(8) in the host's mount namespace. func (n *NsenterMounter) Unmount(target string) error { args := []string{ "--mount=/rootfs/proc/1/ns/mnt", "--", n.absHostPath("umount"), target, } glog.V(5).Infof("Unmount command: %v %v", nsenterPath, args) exec := exec.New() outputBytes, err := exec.Command(nsenterPath, args...).CombinedOutput() if len(outputBytes) != 0 { glog.V(5).Infof("Output from mount command: %v", string(outputBytes)) } return err } // List returns a list of all mounted filesystems in the host's mount namespace. func (*NsenterMounter) List() ([]MountPoint, error) { return listProcMounts(hostProcMountsPath) } // IsLikelyNotMountPoint determines whether a path is a mountpoint by calling stat // in the host's root mount namespace. func (n *NsenterMounter) IsLikelyNotMountPoint(file string) (bool, error) { file, err := filepath.Abs(file) if err != nil { return true, err } args := []string{"--mount=/rootfs/proc/1/ns/mnt", "--", n.absHostPath("stat"), "-c%m", file} glog.V(5).Infof("stat command: %v %v", nsenterPath, args) exec := exec.New() out, err := exec.Command(nsenterPath, args...).CombinedOutput() if err != nil { glog.Errorf("Failed to nsenter mount, return file(%s) doesn't exist: %v", file, err) // If the command itself is correct, then if we encountered error // then most likely this means that the directory does not exist. return true, os.ErrNotExist } strOut := strings.TrimSuffix(string(out), "\n") glog.V(5).Infof("IsLikelyNotMountPoint stat output: %v", strOut) if strOut == file { return false, nil } return true, nil } func (n *NsenterMounter) absHostPath(command string) string { path, ok := n.paths[command] if !ok { return command } return path }
{ "content_hash": "de5f3921b9874198cb5d70ae58b93fe5", "timestamp": "", "source": "github", "line_count": 186, "max_line_length": 101, "avg_line_length": 31.49462365591398, "alnum_prop": 0.697678388528508, "repo_name": "we87/kubernetes", "id": "d0c2af02eb84955d89e0a4a30e307655cf7d6512", "size": "6447", "binary": false, "copies": "1", "ref": "refs/heads/we87", "path": "pkg/util/mount/nsenter_mount.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "15696136" }, { "name": "HTML", "bytes": "1193991" }, { "name": "Makefile", "bytes": "19444" }, { "name": "Nginx", "bytes": "1013" }, { "name": "Python", "bytes": "68188" }, { "name": "SaltStack", "bytes": "38614" }, { "name": "Shell", "bytes": "1070755" } ], "symlink_target": "" }
package com.opengamma.master; import java.util.Map; import org.joda.beans.Bean; import org.joda.beans.BeanBuilder; import org.joda.beans.BeanDefinition; import org.joda.beans.JodaBeanUtils; import org.joda.beans.MetaProperty; import org.joda.beans.Property; import org.joda.beans.PropertyDefinition; import org.joda.beans.impl.direct.DirectBean; import org.joda.beans.impl.direct.DirectMetaBean; import org.joda.beans.impl.direct.DirectMetaProperty; import org.joda.beans.impl.direct.DirectMetaPropertyMap; import org.threeten.bp.Instant; import com.opengamma.id.ObjectId; import com.opengamma.id.ObjectIdentifiable; import com.opengamma.util.ArgumentChecker; import com.opengamma.util.PublicSPI; import com.opengamma.util.paging.PagingRequest; /** * Request for the history of a document. * <p> * A full master implements historical storage of data. * History can be stored in two dimensions and this request provides searching. * <p> * The first historic dimension is the classic series of versions. * Each new version is stored in such a manor that previous versions can be accessed. * <p> * The second historic dimension is corrections. * A correction occurs when it is realized that the original data stored was incorrect. * A simple master might simply replace the original version with the corrected value. * A full implementation will store the correction in such a manner that it is still possible * to obtain the value before the correction was made. * <p> * For example, a document added on Monday and updated on Thursday has two versions. * If it is realized on Friday that the version stored on Monday was incorrect, then a * correction may be applied. There are now two versions, the first of which has one correction. * This may continue, with multiple corrections allowed for each version. * <p> * Versions and corrections are represented by instants in the search. */ @PublicSPI @BeanDefinition public abstract class AbstractHistoryRequest extends DirectBean implements PagedRequest { /** * The request for paging. * By default all matching items will be returned. */ @PropertyDefinition private PagingRequest _pagingRequest = PagingRequest.ALL; /** * The object identifier to match. */ @PropertyDefinition private ObjectId _objectId; /** * The instant to retrieve versions on or after (inclusive). * If this instant equals the {@code versionsToInstant} the search is at a single instant. * A null value will retrieve values starting from the earliest version. */ @PropertyDefinition private Instant _versionsFromInstant; /** * The instant to retrieve versions before (exclusive). * If this instant equals the {@code versionsFromInstant} the search is at a single instant. * A null value will retrieve values up to the latest version. * This should be equal to or later than the {@code versionsFromInstant}. */ @PropertyDefinition private Instant _versionsToInstant; /** * The instant to retrieve corrections on or after (inclusive). * If this instant equals the {@code correctionsToInstant} the search is at a single instant. * A null value will retrieve values starting from the earliest version prior to corrections. * This should be equal to or later than the {@code versionsFromInstant}. */ @PropertyDefinition private Instant _correctionsFromInstant; /** * The instant to retrieve corrections before (exclusive). * If this instant equals the {@code correctionsFromInstant} the search is at a single instant. * A null value will retrieve values up to the latest correction. * This should be equal to or later than the {@code correctionsFromInstant}. */ @PropertyDefinition private Instant _correctionsToInstant; /** * Creates an instance. * The object identifier must be added before searching. */ public AbstractHistoryRequest() { } /** * Creates an instance with object identifier. * This will retrieve all versions and corrections unless the relevant fields are set. * * @param objectId the object identifier, not null */ public AbstractHistoryRequest(final ObjectIdentifiable objectId) { this(objectId, null, null); } /** * Creates an instance with object identifier and optional version and correction. * * @param objectId the object identifier, not null * @param versionInstant the version instant to retrieve, null for all versions * @param correctedToInstant the instant that the data should be corrected to, null for all corrections */ public AbstractHistoryRequest(final ObjectIdentifiable objectId, Instant versionInstant, Instant correctedToInstant) { ArgumentChecker.notNull(objectId, "objectId"); setObjectId(objectId.getObjectId()); setVersionsFromInstant(versionInstant); setVersionsToInstant(versionInstant); setCorrectionsFromInstant(correctedToInstant); setCorrectionsToInstant(correctedToInstant); } //------------------------- AUTOGENERATED START ------------------------- ///CLOVER:OFF /** * The meta-bean for {@code AbstractHistoryRequest}. * @return the meta-bean, not null */ public static AbstractHistoryRequest.Meta meta() { return AbstractHistoryRequest.Meta.INSTANCE; } static { JodaBeanUtils.registerMetaBean(AbstractHistoryRequest.Meta.INSTANCE); } @Override public AbstractHistoryRequest.Meta metaBean() { return AbstractHistoryRequest.Meta.INSTANCE; } //----------------------------------------------------------------------- /** * Gets the request for paging. * By default all matching items will be returned. * @return the value of the property */ public PagingRequest getPagingRequest() { return _pagingRequest; } /** * Sets the request for paging. * By default all matching items will be returned. * @param pagingRequest the new value of the property */ public void setPagingRequest(PagingRequest pagingRequest) { this._pagingRequest = pagingRequest; } /** * Gets the the {@code pagingRequest} property. * By default all matching items will be returned. * @return the property, not null */ public final Property<PagingRequest> pagingRequest() { return metaBean().pagingRequest().createProperty(this); } //----------------------------------------------------------------------- /** * Gets the object identifier to match. * @return the value of the property */ public ObjectId getObjectId() { return _objectId; } /** * Sets the object identifier to match. * @param objectId the new value of the property */ public void setObjectId(ObjectId objectId) { this._objectId = objectId; } /** * Gets the the {@code objectId} property. * @return the property, not null */ public final Property<ObjectId> objectId() { return metaBean().objectId().createProperty(this); } //----------------------------------------------------------------------- /** * Gets the instant to retrieve versions on or after (inclusive). * If this instant equals the {@code versionsToInstant} the search is at a single instant. * A null value will retrieve values starting from the earliest version. * @return the value of the property */ public Instant getVersionsFromInstant() { return _versionsFromInstant; } /** * Sets the instant to retrieve versions on or after (inclusive). * If this instant equals the {@code versionsToInstant} the search is at a single instant. * A null value will retrieve values starting from the earliest version. * @param versionsFromInstant the new value of the property */ public void setVersionsFromInstant(Instant versionsFromInstant) { this._versionsFromInstant = versionsFromInstant; } /** * Gets the the {@code versionsFromInstant} property. * If this instant equals the {@code versionsToInstant} the search is at a single instant. * A null value will retrieve values starting from the earliest version. * @return the property, not null */ public final Property<Instant> versionsFromInstant() { return metaBean().versionsFromInstant().createProperty(this); } //----------------------------------------------------------------------- /** * Gets the instant to retrieve versions before (exclusive). * If this instant equals the {@code versionsFromInstant} the search is at a single instant. * A null value will retrieve values up to the latest version. * This should be equal to or later than the {@code versionsFromInstant}. * @return the value of the property */ public Instant getVersionsToInstant() { return _versionsToInstant; } /** * Sets the instant to retrieve versions before (exclusive). * If this instant equals the {@code versionsFromInstant} the search is at a single instant. * A null value will retrieve values up to the latest version. * This should be equal to or later than the {@code versionsFromInstant}. * @param versionsToInstant the new value of the property */ public void setVersionsToInstant(Instant versionsToInstant) { this._versionsToInstant = versionsToInstant; } /** * Gets the the {@code versionsToInstant} property. * If this instant equals the {@code versionsFromInstant} the search is at a single instant. * A null value will retrieve values up to the latest version. * This should be equal to or later than the {@code versionsFromInstant}. * @return the property, not null */ public final Property<Instant> versionsToInstant() { return metaBean().versionsToInstant().createProperty(this); } //----------------------------------------------------------------------- /** * Gets the instant to retrieve corrections on or after (inclusive). * If this instant equals the {@code correctionsToInstant} the search is at a single instant. * A null value will retrieve values starting from the earliest version prior to corrections. * This should be equal to or later than the {@code versionsFromInstant}. * @return the value of the property */ public Instant getCorrectionsFromInstant() { return _correctionsFromInstant; } /** * Sets the instant to retrieve corrections on or after (inclusive). * If this instant equals the {@code correctionsToInstant} the search is at a single instant. * A null value will retrieve values starting from the earliest version prior to corrections. * This should be equal to or later than the {@code versionsFromInstant}. * @param correctionsFromInstant the new value of the property */ public void setCorrectionsFromInstant(Instant correctionsFromInstant) { this._correctionsFromInstant = correctionsFromInstant; } /** * Gets the the {@code correctionsFromInstant} property. * If this instant equals the {@code correctionsToInstant} the search is at a single instant. * A null value will retrieve values starting from the earliest version prior to corrections. * This should be equal to or later than the {@code versionsFromInstant}. * @return the property, not null */ public final Property<Instant> correctionsFromInstant() { return metaBean().correctionsFromInstant().createProperty(this); } //----------------------------------------------------------------------- /** * Gets the instant to retrieve corrections before (exclusive). * If this instant equals the {@code correctionsFromInstant} the search is at a single instant. * A null value will retrieve values up to the latest correction. * This should be equal to or later than the {@code correctionsFromInstant}. * @return the value of the property */ public Instant getCorrectionsToInstant() { return _correctionsToInstant; } /** * Sets the instant to retrieve corrections before (exclusive). * If this instant equals the {@code correctionsFromInstant} the search is at a single instant. * A null value will retrieve values up to the latest correction. * This should be equal to or later than the {@code correctionsFromInstant}. * @param correctionsToInstant the new value of the property */ public void setCorrectionsToInstant(Instant correctionsToInstant) { this._correctionsToInstant = correctionsToInstant; } /** * Gets the the {@code correctionsToInstant} property. * If this instant equals the {@code correctionsFromInstant} the search is at a single instant. * A null value will retrieve values up to the latest correction. * This should be equal to or later than the {@code correctionsFromInstant}. * @return the property, not null */ public final Property<Instant> correctionsToInstant() { return metaBean().correctionsToInstant().createProperty(this); } //----------------------------------------------------------------------- @Override public AbstractHistoryRequest clone() { return JodaBeanUtils.cloneAlways(this); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj != null && obj.getClass() == this.getClass()) { AbstractHistoryRequest other = (AbstractHistoryRequest) obj; return JodaBeanUtils.equal(getPagingRequest(), other.getPagingRequest()) && JodaBeanUtils.equal(getObjectId(), other.getObjectId()) && JodaBeanUtils.equal(getVersionsFromInstant(), other.getVersionsFromInstant()) && JodaBeanUtils.equal(getVersionsToInstant(), other.getVersionsToInstant()) && JodaBeanUtils.equal(getCorrectionsFromInstant(), other.getCorrectionsFromInstant()) && JodaBeanUtils.equal(getCorrectionsToInstant(), other.getCorrectionsToInstant()); } return false; } @Override public int hashCode() { int hash = getClass().hashCode(); hash = hash * 31 + JodaBeanUtils.hashCode(getPagingRequest()); hash = hash * 31 + JodaBeanUtils.hashCode(getObjectId()); hash = hash * 31 + JodaBeanUtils.hashCode(getVersionsFromInstant()); hash = hash * 31 + JodaBeanUtils.hashCode(getVersionsToInstant()); hash = hash * 31 + JodaBeanUtils.hashCode(getCorrectionsFromInstant()); hash = hash * 31 + JodaBeanUtils.hashCode(getCorrectionsToInstant()); return hash; } @Override public String toString() { StringBuilder buf = new StringBuilder(224); buf.append("AbstractHistoryRequest{"); int len = buf.length(); toString(buf); if (buf.length() > len) { buf.setLength(buf.length() - 2); } buf.append('}'); return buf.toString(); } protected void toString(StringBuilder buf) { buf.append("pagingRequest").append('=').append(JodaBeanUtils.toString(getPagingRequest())).append(',').append(' '); buf.append("objectId").append('=').append(JodaBeanUtils.toString(getObjectId())).append(',').append(' '); buf.append("versionsFromInstant").append('=').append(JodaBeanUtils.toString(getVersionsFromInstant())).append(',').append(' '); buf.append("versionsToInstant").append('=').append(JodaBeanUtils.toString(getVersionsToInstant())).append(',').append(' '); buf.append("correctionsFromInstant").append('=').append(JodaBeanUtils.toString(getCorrectionsFromInstant())).append(',').append(' '); buf.append("correctionsToInstant").append('=').append(JodaBeanUtils.toString(getCorrectionsToInstant())).append(',').append(' '); } //----------------------------------------------------------------------- /** * The meta-bean for {@code AbstractHistoryRequest}. */ public static class Meta extends DirectMetaBean { /** * The singleton instance of the meta-bean. */ static final Meta INSTANCE = new Meta(); /** * The meta-property for the {@code pagingRequest} property. */ private final MetaProperty<PagingRequest> _pagingRequest = DirectMetaProperty.ofReadWrite( this, "pagingRequest", AbstractHistoryRequest.class, PagingRequest.class); /** * The meta-property for the {@code objectId} property. */ private final MetaProperty<ObjectId> _objectId = DirectMetaProperty.ofReadWrite( this, "objectId", AbstractHistoryRequest.class, ObjectId.class); /** * The meta-property for the {@code versionsFromInstant} property. */ private final MetaProperty<Instant> _versionsFromInstant = DirectMetaProperty.ofReadWrite( this, "versionsFromInstant", AbstractHistoryRequest.class, Instant.class); /** * The meta-property for the {@code versionsToInstant} property. */ private final MetaProperty<Instant> _versionsToInstant = DirectMetaProperty.ofReadWrite( this, "versionsToInstant", AbstractHistoryRequest.class, Instant.class); /** * The meta-property for the {@code correctionsFromInstant} property. */ private final MetaProperty<Instant> _correctionsFromInstant = DirectMetaProperty.ofReadWrite( this, "correctionsFromInstant", AbstractHistoryRequest.class, Instant.class); /** * The meta-property for the {@code correctionsToInstant} property. */ private final MetaProperty<Instant> _correctionsToInstant = DirectMetaProperty.ofReadWrite( this, "correctionsToInstant", AbstractHistoryRequest.class, Instant.class); /** * The meta-properties. */ private final Map<String, MetaProperty<?>> _metaPropertyMap$ = new DirectMetaPropertyMap( this, null, "pagingRequest", "objectId", "versionsFromInstant", "versionsToInstant", "correctionsFromInstant", "correctionsToInstant"); /** * Restricted constructor. */ protected Meta() { } @Override protected MetaProperty<?> metaPropertyGet(String propertyName) { switch (propertyName.hashCode()) { case -2092032669: // pagingRequest return _pagingRequest; case 90495162: // objectId return _objectId; case 825630012: // versionsFromInstant return _versionsFromInstant; case 288644747: // versionsToInstant return _versionsToInstant; case -1002076478: // correctionsFromInstant return _correctionsFromInstant; case -1241747055: // correctionsToInstant return _correctionsToInstant; } return super.metaPropertyGet(propertyName); } @Override public BeanBuilder<? extends AbstractHistoryRequest> builder() { throw new UnsupportedOperationException("AbstractHistoryRequest is an abstract class"); } @Override public Class<? extends AbstractHistoryRequest> beanType() { return AbstractHistoryRequest.class; } @Override public Map<String, MetaProperty<?>> metaPropertyMap() { return _metaPropertyMap$; } //----------------------------------------------------------------------- /** * The meta-property for the {@code pagingRequest} property. * @return the meta-property, not null */ public final MetaProperty<PagingRequest> pagingRequest() { return _pagingRequest; } /** * The meta-property for the {@code objectId} property. * @return the meta-property, not null */ public final MetaProperty<ObjectId> objectId() { return _objectId; } /** * The meta-property for the {@code versionsFromInstant} property. * @return the meta-property, not null */ public final MetaProperty<Instant> versionsFromInstant() { return _versionsFromInstant; } /** * The meta-property for the {@code versionsToInstant} property. * @return the meta-property, not null */ public final MetaProperty<Instant> versionsToInstant() { return _versionsToInstant; } /** * The meta-property for the {@code correctionsFromInstant} property. * @return the meta-property, not null */ public final MetaProperty<Instant> correctionsFromInstant() { return _correctionsFromInstant; } /** * The meta-property for the {@code correctionsToInstant} property. * @return the meta-property, not null */ public final MetaProperty<Instant> correctionsToInstant() { return _correctionsToInstant; } //----------------------------------------------------------------------- @Override protected Object propertyGet(Bean bean, String propertyName, boolean quiet) { switch (propertyName.hashCode()) { case -2092032669: // pagingRequest return ((AbstractHistoryRequest) bean).getPagingRequest(); case 90495162: // objectId return ((AbstractHistoryRequest) bean).getObjectId(); case 825630012: // versionsFromInstant return ((AbstractHistoryRequest) bean).getVersionsFromInstant(); case 288644747: // versionsToInstant return ((AbstractHistoryRequest) bean).getVersionsToInstant(); case -1002076478: // correctionsFromInstant return ((AbstractHistoryRequest) bean).getCorrectionsFromInstant(); case -1241747055: // correctionsToInstant return ((AbstractHistoryRequest) bean).getCorrectionsToInstant(); } return super.propertyGet(bean, propertyName, quiet); } @Override protected void propertySet(Bean bean, String propertyName, Object newValue, boolean quiet) { switch (propertyName.hashCode()) { case -2092032669: // pagingRequest ((AbstractHistoryRequest) bean).setPagingRequest((PagingRequest) newValue); return; case 90495162: // objectId ((AbstractHistoryRequest) bean).setObjectId((ObjectId) newValue); return; case 825630012: // versionsFromInstant ((AbstractHistoryRequest) bean).setVersionsFromInstant((Instant) newValue); return; case 288644747: // versionsToInstant ((AbstractHistoryRequest) bean).setVersionsToInstant((Instant) newValue); return; case -1002076478: // correctionsFromInstant ((AbstractHistoryRequest) bean).setCorrectionsFromInstant((Instant) newValue); return; case -1241747055: // correctionsToInstant ((AbstractHistoryRequest) bean).setCorrectionsToInstant((Instant) newValue); return; } super.propertySet(bean, propertyName, newValue, quiet); } } ///CLOVER:ON //-------------------------- AUTOGENERATED END -------------------------- }
{ "content_hash": "0cb0a532ae7ee7c5bfe1adf7097d17c2", "timestamp": "", "source": "github", "line_count": 579, "max_line_length": 137, "avg_line_length": 38.77892918825561, "alnum_prop": 0.6817351801540997, "repo_name": "jeorme/OG-Platform", "id": "6f06c1622c15a10ace17d59c8936ad62b9ffc4f1", "size": "22590", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "projects/OG-Master/src/main/java/com/opengamma/master/AbstractHistoryRequest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "4064" }, { "name": "CSS", "bytes": "212432" }, { "name": "GAP", "bytes": "1490" }, { "name": "Groovy", "bytes": "11518" }, { "name": "HTML", "bytes": "284313" }, { "name": "Java", "bytes": "81033606" }, { "name": "JavaScript", "bytes": "1528695" }, { "name": "PLSQL", "bytes": "105" }, { "name": "PLpgSQL", "bytes": "13175" }, { "name": "Protocol Buffer", "bytes": "53119" }, { "name": "SQLPL", "bytes": "1004" }, { "name": "Shell", "bytes": "10958" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace CLK.AspNet.Identity.WebSite { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } } }
{ "content_hash": "cf1412bc5c0a1f8325b27c3b5462bf72", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 98, "avg_line_length": 32.25, "alnum_prop": 0.7222222222222222, "repo_name": "Clark159/CLK.AspNet.Identity", "id": "ac8b4d0e99d947010187ba83124a1b2e402ab0e4", "size": "776", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/CLK.AspNet.Identity.WebSite/Global.asax.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "118" }, { "name": "Batchfile", "bytes": "912" }, { "name": "C#", "bytes": "238810" }, { "name": "CSS", "bytes": "513" }, { "name": "HTML", "bytes": "5179" }, { "name": "JavaScript", "bytes": "20079" } ], "symlink_target": "" }
verify.getSemanticDiagnostics(`[ { "message": "'interface declarations' can only be used in a .ts file.", "start": 10, "length": 1, "category": "error", "code": 8006 } ]`);
{ "content_hash": "e13b9572ff39fd1e14194b5eae75019a", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 74, "avg_line_length": 21.77777777777778, "alnum_prop": 0.576530612244898, "repo_name": "freedot/tstolua", "id": "846ca3ea4926ee0d177c60cfa902b6e6188d41e0", "size": "307", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/cases/fourslash/getJavaScriptSemanticDiagnostics6.ts", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1125" }, { "name": "HTML", "bytes": "4659" }, { "name": "JavaScript", "bytes": "85" }, { "name": "Lua", "bytes": "68588" }, { "name": "PowerShell", "bytes": "2780" }, { "name": "TypeScript", "bytes": "22883724" } ], "symlink_target": "" }
<?php require __DIR__.'/autoload.php'; return function (array $context): void { echo 'Hello World ', $context['SOME_VAR']; };
{ "content_hash": "159038ec9abd5cc5445968c019252909", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 46, "avg_line_length": 14.88888888888889, "alnum_prop": 0.6119402985074627, "repo_name": "symfony/symfony", "id": "512e2dc5a3e13c6ba82fa1d43c9065313302cfa3", "size": "363", "binary": false, "copies": "12", "ref": "refs/heads/6.3", "path": "src/Symfony/Component/Runtime/Tests/phpt/hello.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "49777" }, { "name": "HTML", "bytes": "16735" }, { "name": "Hack", "bytes": "26" }, { "name": "JavaScript", "bytes": "29581" }, { "name": "Makefile", "bytes": "444" }, { "name": "PHP", "bytes": "67196392" }, { "name": "Shell", "bytes": "9506" }, { "name": "Twig", "bytes": "572335" } ], "symlink_target": "" }
from rllab.baselines.linear_feature_baseline import LinearFeatureBaseline from rllab.envs.normalized_env import normalize from rllab.misc.instrument import stub, run_experiment_lite from sandbox.snn4hrl.algos.trpo_snn import TRPO_snn from sandbox.snn4hrl.bonus_evaluators.grid_bonus_evaluator import GridBonusEvaluator from sandbox.snn4hrl.envs.mujoco.swimmer_env import SwimmerEnv from sandbox.snn4hrl.policies.snn_mlp_policy import GaussianMLPPolicy_snn from sandbox.snn4hrl.regressors.latent_regressor import Latent_regressor stub(globals()) # SNN policy settings latent_dim = 6 # dim of the latent variables in the SNN # Bonus evaluator settings mesh_density = 5 # for the discretization of the x-y space snn_H_bonus = 0.05 # coef of the MI bonus # extra arguments, not used in the paper switch_lat_every = 0 # switch latents during the pre-training virtual_reset = False # Latent regressor (to avoid using the GridBonus evaluator and its discretization) noisify_coef = 0 # noise injected int the state while fitting/predicting latents reward_regressor_mi = 0 # bonus associated to the MI computed with the regressor # choose your environment. For later hierarchization, choose ego_obs=True env = normalize(SwimmerEnv(ego_obs=True)) policy = GaussianMLPPolicy_snn( env_spec=env.spec, latent_dim=latent_dim, latent_name='categorical', bilinear_integration=True, # concatenate also the outer product hidden_sizes=(64, 64), min_std=1e-6, ) baseline = LinearFeatureBaseline(env_spec=env.spec) if latent_dim: latent_regressor = Latent_regressor( env_spec=env.spec, policy=policy, predict_all=True, # use all the predictions and not only the last obs_regressed='all', # [-3] is the x-position of the com, otherwise put 'all' act_regressed=[], # use [] for nothing or 'all' for all. noisify_traj_coef=noisify_coef, regressor_args={ 'hidden_sizes': (32, 32), 'name': 'latent_reg', 'use_trust_region': False, } ) else: latent_regressor = None bonus_evaluators = [GridBonusEvaluator(mesh_density=mesh_density, snn_H_bonus=snn_H_bonus, virtual_reset=virtual_reset, switch_lat_every=switch_lat_every, )] reward_coef_bonus = [1] algo = TRPO_snn( env=env, policy=policy, baseline=baseline, self_normalize=True, log_individual_latents=True, log_deterministic=True, latent_regressor=latent_regressor, reward_regressor_mi=reward_regressor_mi, bonus_evaluator=bonus_evaluators, reward_coef_bonus=reward_coef_bonus, switch_lat_every=switch_lat_every, batch_size=50000, whole_paths=True, max_path_length=500, n_itr=500, discount=0.99, step_size=0.01, ) for s in range(10, 110, 10): # [10, 20, 30, 40, 50]: exp_prefix = 'egoSwimmer-snn' exp_name = exp_prefix + '_{}MI_{}grid_{}latCat_bil_{:04d}'.format( ''.join(str(snn_H_bonus).split('.')), mesh_density, latent_dim, s) run_experiment_lite( stub_method_call=algo.train(), use_cloudpickle=False, mode='local', pre_commands=['pip install --upgrade pip', 'pip install --upgrade theano', ], # Number of parallel workers for sampling n_parallel=4, # Only keep the snapshot parameters for the last iteration snapshot_mode="last", # Specifies the seed for the experiment. If this is not provided, a random seed # will be used seed=s, # plot=True, # Save to data/ec2/exp_prefix/exp_name/ exp_prefix=exp_prefix, exp_name=exp_name, sync_s3_pkl=True, # for sync the pkl file also during the training sync_s3_png=True, terminate_machine=True, # dangerous to have False! )
{ "content_hash": "a3253ebcbae04e8fe21244ea604e3959", "timestamp": "", "source": "github", "line_count": 110, "max_line_length": 90, "avg_line_length": 36.18181818181818, "alnum_prop": 0.6540201005025126, "repo_name": "florensacc/snn4hrl", "id": "02393c428a90678d5a11a5606e7c8b314fee3fb3", "size": "3980", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "runs/train_snn.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "268571" } ], "symlink_target": "" }
{template 'common/header'} <div class="new-keyword" id="js-user-group-post" ng-controller="UserGroupPost" ng-cloak> <ol class="breadcrumb we7-breadcrumb"> <a href="{php echo url('user/group/display')}"><i class="wi wi-back-circle"></i> </a> <li><a href="{php echo url('user/group/display')}">用户组管理</a></li> <li>添加用户组</li> </ol> <form class="we7-form user-group-edit" method="post" action=""> <div class="form-group"> <label for="" class="control-label col-sm-2">用户权限组名</label> <div class="form-controls col-sm-8"> <input type="text" name="name" class="form-control" ng-model="groupInfo.name"> </div> </div> <div class="form-group"> <label for="" class="control-label col-sm-2">创建公众号数量</label> <div class="form-controls col-sm-8"> <input type="text" name="maxaccount" class="form-control" ng-model="groupInfo.maxaccount"> <span class="help-block">限制公众号的数量,为0则不允许添加。</span> </div> </div> <div class="form-group"> <label for="" class="control-label col-sm-2">创建小程序数量</label> <div class="form-controls col-sm-8"> <input type="text" name="maxwxapp" class="form-control" ng-model="groupInfo.maxwxapp"> <span class="help-block">限制小程序的数量,为0则不允许添加。</span> </div> </div> <div class="form-group"> <label for="" class="control-label col-sm-2">创建PC数量</label> <div class="form-controls col-sm-8"> <input type="text" name="maxwebapp" class="form-control" ng-model="groupInfo.maxwebapp"> <span class="help-block">限制PC的数量,为0则不允许添加。</span> </div> </div> <div class="form-group"> <label for="" class="control-label col-sm-2">创建APP数量</label> <div class="form-controls col-sm-8"> <input type="text" name="maxphoneapp" class="form-control" ng-model="groupInfo.maxphoneapp"> <span class="help-block">限制APP的数量,为0则不允许添加。</span> </div> </div> <div class="form-group"> <label for="" class="control-label col-sm-2">有效期</label> <div class="form-controls col-sm-8"> <div class="input-group"> <input type="text" name="timelimit" class="form-control" ng-model="groupInfo.timelimit"> <span class="input-group-addon font-default">天</span> </div> <span class="help-block">设置用户组的有效期限。0为不限制期限。到期后,该用户下的所有公众号只能使用 "基础服务"</span> </div> </div> <div class="panel we7-panel"> <div class="panel-heading"> 选择应用权限套餐组 <a href="{php echo url('module/group/post')}" class="color-default pull-right">新建应用权限套餐组</a> </div> <div class="panel-body user-permission"> <div ng-repeat="pack in packages"> <div class="permission-heading"> <input id="checkbox-{{pack.id}}" type="checkbox" name='package[]' value="{{pack.id}}" ng-checked="pack.checked"> <label for="checkbox-{{pack.id}}" ng-bind="pack.name"></label> <div class="pull-right permission-edit"> <a href="javascript:;" class="color-default js-unfold" data-toggle="collapse" data-target="#demo-{{pack.id}}" ng-click="changeText($event)">展开</a> </div> </div> <div class="collapse" id="demo-{{pack.id}}"> <table class="table we7-table table-hover"> <col width="90px" /> <col /> <tr class="permission-apply"> <td class="vertical-middle">公众号应用</td> <td> <ul> <li ng-repeat="module in pack.modules" class="col-sm-2 text-over text-left"> <div ng-if="module.name != 'all'"> <img ng-src="{{ module.logo }}" alt=""> {{ module.title }} </div> </li> </ul> </td> </tr> <tr class="permission-apply"> <td class="vertical-middle">小程序应用</td> <td> <ul> <li ng-repeat="wxapp in pack.wxapp"> <span class="label label-info" ng-bind="wxapp.title"></span> </li> </ul> </td> </tr> <tr class="permission-apply"> <td class="vertical-middle">PC应用</td> <td> <ul> <li ng-repeat="pc in pack.pc"> <span class="label label-info" ng-bind="pc.title"></span> </li> </ul> </td> </tr> <tr class="permission-template"> <td class="vertical-middle">模板</td> <td><ul><li ng-repeat="tpl in pack.templates"><span class="label label-info" ng-bind="tpl.title"></span></li></ul></td> </tr> </table> </div> </div> {if permission_check_account_user('see_account_manage_module_tpl_all_permission')} <div> <div class="permission-heading"> <input id="checkbox-0" type="checkbox" value="-1" name='package[]' ng-checked="groupInfo.check_all"> <label for="checkbox-0">所有服务</label> <div class="pull-right permission-edit"> <a href="javascript:;" class="color-default js-unfold" data-toggle="collapse" data-target="#demo-0" ng-click="changeText($event)">展开</a> </div> </div> <div class="collapse" id="demo-0"> <table class="table we7-table table-hover"> <col width="90px" /> <col /> <tr class="permission-apply"> <td class="vertical-middle">应用</td> <td><ul><li><span class="label label-danger">系统所有模块</span></li></ul></td> </tr> <tr class="permission-template"> <td class="vertical-middle">模板</td> <td><ul><li><span class="label label-danger">系统所有模板</span></li></ul></td> </tr> </table> </div> </div> {/if} </div> </div> <input type="submit" name="submit" value="保存" class="btn btn-primary" ng-style="{'padding': '6px 50px'}" /> <input type="hidden" name="token" value="{$_W['token']}"> </form> </div> <script> angular.module('userGroup').value('config', { groupInfo: {php echo !empty($group_info) ? json_encode($group_info) : 'null'}, packages: {php echo !empty($packages) ? json_encode($packages) : 'null'}, }); angular.bootstrap($('#js-user-group-post'), ['userGroup']); </script> {template 'common/footer'}
{ "content_hash": "708023882d56d84511f72ac108e38540", "timestamp": "", "source": "github", "line_count": 150, "max_line_length": 153, "avg_line_length": 39.333333333333336, "alnum_prop": 0.5952542372881356, "repo_name": "justzheng/test1", "id": "69a303c6b1b9bc003fe0e37435a5c594263e4bdb", "size": "6304", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "web/themes/default/user/group-post.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "309180" }, { "name": "HTML", "bytes": "3403511" }, { "name": "JavaScript", "bytes": "2372527" }, { "name": "PHP", "bytes": "8422588" } ], "symlink_target": "" }
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/sync/driver/data_type_manager_impl.h" #include <algorithm> #include <functional> #include <string> #include <utility> #include "base/bind.h" #include "base/bind_helpers.h" #include "base/callback.h" #include "base/containers/queue.h" #include "base/logging.h" #include "base/metrics/histogram_functions.h" #include "base/metrics/histogram_macros.h" #include "base/sequenced_task_runner.h" #include "base/strings/stringprintf.h" #include "base/threading/sequenced_task_runner_handle.h" #include "base/trace_event/trace_event.h" #include "components/sync/driver/configure_context.h" #include "components/sync/driver/data_type_encryption_handler.h" #include "components/sync/driver/data_type_manager_observer.h" #include "components/sync/driver/data_type_status_table.h" #include "components/sync/engine/data_type_debug_info_listener.h" namespace syncer { namespace { DataTypeStatusTable::TypeErrorMap GenerateCryptoErrorsForTypes( ModelTypeSet encrypted_types) { DataTypeStatusTable::TypeErrorMap crypto_errors; for (ModelType type : encrypted_types) { crypto_errors[type] = SyncError(FROM_HERE, SyncError::CRYPTO_ERROR, "", type); } return crypto_errors; } ConfigureReason GetReasonForProgrammaticReconfigure( ConfigureReason original_reason) { // This reconfiguration can happen within the first configure cycle and in // this case we want to stick to the original reason -- doing the first sync // cycle. return (original_reason == ConfigureReason::CONFIGURE_REASON_NEW_CLIENT) ? ConfigureReason::CONFIGURE_REASON_NEW_CLIENT : ConfigureReason::CONFIGURE_REASON_PROGRAMMATIC; } } // namespace DataTypeManagerImpl::AssociationTypesInfo::AssociationTypesInfo() {} DataTypeManagerImpl::AssociationTypesInfo::AssociationTypesInfo( const AssociationTypesInfo& other) = default; DataTypeManagerImpl::AssociationTypesInfo::~AssociationTypesInfo() {} DataTypeManagerImpl::DataTypeManagerImpl( ModelTypeSet initial_types, const WeakHandle<DataTypeDebugInfoListener>& debug_info_listener, const DataTypeController::TypeMap* controllers, const DataTypeEncryptionHandler* encryption_handler, ModelTypeConfigurer* configurer, DataTypeManagerObserver* observer) : downloaded_types_(initial_types), configurer_(configurer), controllers_(controllers), state_(DataTypeManager::STOPPED), needs_reconfigure_(false), debug_info_listener_(debug_info_listener), model_association_manager_(controllers, this), observer_(observer), encryption_handler_(encryption_handler), download_started_(false) { DCHECK(configurer_); DCHECK(observer_); // Check if any of the controllers are already in a FAILED state, and if so, // mark them accordingly in the status table. DataTypeStatusTable::TypeErrorMap existing_errors; for (const auto& kv : *controllers_) { ModelType type = kv.first; const DataTypeController* controller = kv.second.get(); DataTypeController::State state = controller->state(); DCHECK(state == DataTypeController::NOT_RUNNING || state == DataTypeController::STOPPING || state == DataTypeController::FAILED); if (state == DataTypeController::FAILED) { existing_errors[type] = SyncError(FROM_HERE, SyncError::DATATYPE_ERROR, "Preexisting controller error on Sync startup", type); } } data_type_status_table_.UpdateFailedDataTypes(existing_errors); } DataTypeManagerImpl::~DataTypeManagerImpl() {} void DataTypeManagerImpl::Configure(ModelTypeSet desired_types, const ConfigureContext& context) { desired_types.PutAll(ControlTypes()); ModelTypeSet allowed_types = ControlTypes(); // Add types with controllers. for (const auto& kv : *controllers_) { allowed_types.Put(kv.first); } ConfigureImpl(Intersection(desired_types, allowed_types), context); } void DataTypeManagerImpl::DataTypePreconditionChanged(ModelType type) { if (!UpdatePreconditionError(type)) { // Nothing changed. return; } switch (controllers_->find(type)->second->GetPreconditionState()) { case DataTypeController::PreconditionState::kPreconditionsMet: if (last_requested_types_.Has(type)) { // Only reconfigure if the type is both ready and desired. This will // internally also update ready state of all other requested types. ForceReconfiguration(); } break; case DataTypeController::PreconditionState::kMustStopAndClearData: model_association_manager_.StopDatatype( type, DISABLE_SYNC, SyncError(FROM_HERE, syncer::SyncError::DATATYPE_POLICY_ERROR, "Datatype preconditions not met.", type)); break; case DataTypeController::PreconditionState::kMustStopAndKeepData: model_association_manager_.StopDatatype( type, STOP_SYNC, SyncError(FROM_HERE, syncer::SyncError::UNREADY_ERROR, "Data type is unready.", type)); break; } } void DataTypeManagerImpl::ForceReconfiguration() { needs_reconfigure_ = true; last_requested_context_.reason = GetReasonForProgrammaticReconfigure(last_requested_context_.reason); ProcessReconfigure(); } void DataTypeManagerImpl::ResetDataTypeErrors() { data_type_status_table_.Reset(); } void DataTypeManagerImpl::PurgeForMigration(ModelTypeSet undesired_types) { ModelTypeSet remainder = Difference(last_requested_types_, undesired_types); last_requested_context_.reason = CONFIGURE_REASON_MIGRATION; ConfigureImpl(remainder, last_requested_context_); } void DataTypeManagerImpl::ConfigureImpl(ModelTypeSet desired_types, const ConfigureContext& context) { DCHECK_NE(context.reason, CONFIGURE_REASON_UNKNOWN); DVLOG(1) << "Configuring for " << ModelTypeSetToString(desired_types) << " with reason " << context.reason; if (state_ == STOPPING) { // You can not set a configuration while stopping. LOG(ERROR) << "Configuration set while stopping."; return; } if (state_ != STOPPED) { DCHECK_EQ(context.authenticated_account_id, last_requested_context_.authenticated_account_id); DCHECK_EQ(context.cache_guid, last_requested_context_.cache_guid); } // TODO(zea): consider not performing a full configuration once there's a // reliable way to determine if the requested set of enabled types matches the // current set. last_requested_types_ = desired_types; last_requested_context_ = context; // Only proceed if we're in a steady state or retrying. if (state_ != STOPPED && state_ != CONFIGURED && state_ != RETRYING) { DVLOG(1) << "Received configure request while configuration in flight. " << "Postponing until current configuration complete."; needs_reconfigure_ = true; return; } Restart(); } void DataTypeManagerImpl::RegisterTypesWithBackend() { for (ModelType type : last_enabled_types_) { const auto& dtc_iter = controllers_->find(type); if (dtc_iter == controllers_->end()) continue; DataTypeController* dtc = dtc_iter->second.get(); if (dtc->state() == DataTypeController::MODEL_LOADED) { // Only call RegisterWithBackend for types that completed LoadModels // successfully. Such types shouldn't be in an error state at the same // time. DCHECK(!data_type_status_table_.GetFailedTypes().Has(dtc->type())); switch (dtc->RegisterWithBackend(configurer_)) { case DataTypeController::REGISTRATION_IGNORED: break; case DataTypeController::TYPE_ALREADY_DOWNLOADED: downloaded_types_.Put(type); break; case DataTypeController::TYPE_NOT_YET_DOWNLOADED: downloaded_types_.Remove(type); break; } if (force_redownload_types_.Has(type)) { downloaded_types_.Remove(type); } } } } // static ModelTypeSet DataTypeManagerImpl::GetDataTypesInState( DataTypeConfigState state, const DataTypeConfigStateMap& state_map) { ModelTypeSet types; for (const auto& kv : state_map) { if (kv.second == state) types.Put(kv.first); } return types; } // static void DataTypeManagerImpl::SetDataTypesState(DataTypeConfigState state, ModelTypeSet types, DataTypeConfigStateMap* state_map) { for (ModelType type : types) { (*state_map)[type] = state; } } DataTypeManagerImpl::DataTypeConfigStateMap DataTypeManagerImpl::BuildDataTypeConfigStateMap( const ModelTypeSet& types_being_configured) const { // 1. Get the failed types (due to fatal, crypto, and unready errors). // 2. Add the difference between last_requested_types_ and the failed types // as CONFIGURE_INACTIVE. // 3. Flip |types_being_configured| to CONFIGURE_ACTIVE. // 4. Set non-enabled user types as DISABLED. // 5. Set the fatal, crypto, and unready types to their respective states. ModelTypeSet fatal_types = data_type_status_table_.GetFatalErrorTypes(); ModelTypeSet crypto_types = data_type_status_table_.GetCryptoErrorTypes(); ModelTypeSet unready_types = data_type_status_table_.GetUnreadyErrorTypes(); // Types with persistence errors are only purged/resynced when they're // actively being configured. ModelTypeSet clean_types = data_type_status_table_.GetPersistenceErrorTypes(); clean_types.RetainAll(types_being_configured); // Types with unready errors do not count as unready if they've been disabled. unready_types.RetainAll(last_requested_types_); ModelTypeSet enabled_types = GetEnabledTypes(); ModelTypeSet disabled_types = Difference(Union(UserTypes(), ControlTypes()), enabled_types); ModelTypeSet to_configure = Intersection(enabled_types, types_being_configured); DVLOG(1) << "Enabling: " << ModelTypeSetToString(enabled_types); DVLOG(1) << "Configuring: " << ModelTypeSetToString(to_configure); DVLOG(1) << "Disabling: " << ModelTypeSetToString(disabled_types); DataTypeConfigStateMap config_state_map; SetDataTypesState(CONFIGURE_INACTIVE, enabled_types, &config_state_map); SetDataTypesState(CONFIGURE_ACTIVE, to_configure, &config_state_map); SetDataTypesState(CONFIGURE_CLEAN, clean_types, &config_state_map); SetDataTypesState(DISABLED, disabled_types, &config_state_map); SetDataTypesState(FATAL, fatal_types, &config_state_map); SetDataTypesState(CRYPTO, crypto_types, &config_state_map); SetDataTypesState(UNREADY, unready_types, &config_state_map); return config_state_map; } void DataTypeManagerImpl::Restart() { DVLOG(1) << "Restarting..."; const ConfigureReason reason = last_requested_context_.reason; // Only record the type histograms for user-triggered configurations or // restarts. if (reason == CONFIGURE_REASON_RECONFIGURATION || reason == CONFIGURE_REASON_NEW_CLIENT || reason == CONFIGURE_REASON_NEWLY_ENABLED_DATA_TYPE) { for (ModelType type : last_requested_types_) { // TODO(wychen): enum uma should be strongly typed. crbug.com/661401 UMA_HISTOGRAM_ENUMERATION("Sync.ConfigureDataTypes", ModelTypeHistogramValue(type)); } } // Check for new or resolved data type crypto errors. if (encryption_handler_->HasCryptoError()) { ModelTypeSet encrypted_types = encryption_handler_->GetEncryptedDataTypes(); encrypted_types.RetainAll(last_requested_types_); encrypted_types.RemoveAll(data_type_status_table_.GetCryptoErrorTypes()); DataTypeStatusTable::TypeErrorMap crypto_errors = GenerateCryptoErrorsForTypes(encrypted_types); data_type_status_table_.UpdateFailedDataTypes(crypto_errors); } else { data_type_status_table_.ResetCryptoErrors(); } UpdatePreconditionErrors(last_requested_types_); last_enabled_types_ = GetEnabledTypes(); last_restart_time_ = base::Time::Now(); configuration_stats_.clear(); DCHECK(state_ == STOPPED || state_ == CONFIGURED || state_ == RETRYING); const State old_state = state_; state_ = CONFIGURING; // Starting from a "steady state" (stopped or configured) state // should send a start notification. // Note: NotifyStart() must be called with the updated (non-idle) state, // otherwise logic listening for the configuration start might not be aware // of the fact that the DTM is in a configuration state. if (old_state == STOPPED || old_state == CONFIGURED) NotifyStart(); download_types_queue_ = PrioritizeTypes(last_enabled_types_); association_types_queue_ = base::queue<AssociationTypesInfo>(); download_started_ = false; model_association_manager_.Initialize( /*desired_types=*/last_enabled_types_, /*preferred_types=*/last_requested_types_, last_requested_context_); } void DataTypeManagerImpl::OnAllDataTypesReadyForConfigure() { DCHECK(!download_started_); download_started_ = true; // TODO(pavely): By now some of datatypes in |download_types_queue_| could // have failed loading and should be excluded from configuration. I need to // adjust |download_types_queue_| for such types. RegisterTypesWithBackend(); StartNextDownload(ModelTypeSet()); } ModelTypeSet DataTypeManagerImpl::GetPriorityTypes() const { ModelTypeSet high_priority_types; high_priority_types.PutAll(ControlTypes()); high_priority_types.PutAll(PriorityUserTypes()); return high_priority_types; } TypeSetPriorityList DataTypeManagerImpl::PrioritizeTypes( const ModelTypeSet& types) { ModelTypeSet high_priority_types = GetPriorityTypes(); high_priority_types.RetainAll(types); ModelTypeSet low_priority_types = Difference(types, high_priority_types); TypeSetPriorityList result; if (!high_priority_types.Empty()) result.push(high_priority_types); if (!low_priority_types.Empty()) result.push(low_priority_types); // Could be empty in case of purging for migration, sync nothing, etc. // Configure empty set to purge data from backend. if (result.empty()) result.push(ModelTypeSet()); return result; } void DataTypeManagerImpl::UpdatePreconditionErrors( const ModelTypeSet& desired_types) { for (ModelType type : desired_types) { UpdatePreconditionError(type); } } bool DataTypeManagerImpl::UpdatePreconditionError(ModelType type) { const auto& iter = controllers_->find(type); if (iter == controllers_->end()) return false; switch (iter->second->GetPreconditionState()) { case DataTypeController::PreconditionState::kPreconditionsMet: { const bool data_type_policy_error_changed = data_type_status_table_.ResetDataTypePolicyErrorFor(type); const bool unready_status_changed = data_type_status_table_.ResetUnreadyErrorFor(type); if (!data_type_policy_error_changed && !unready_status_changed) { // Nothing changed. return false; } // If preconditions are newly met, the datatype should be immediately // redownloaded as part of the datatype configuration (most relevant for // the UNREADY_ERROR case which usually won't clear sync metadata). force_redownload_types_.Put(type); return true; } case DataTypeController::PreconditionState::kMustStopAndClearData: { return data_type_status_table_.UpdateFailedDataType( type, SyncError(FROM_HERE, SyncError::DATATYPE_POLICY_ERROR, "Datatype preconditions not met.", type)); } case DataTypeController::PreconditionState::kMustStopAndKeepData: { return data_type_status_table_.UpdateFailedDataType( type, SyncError(FROM_HERE, SyncError::UNREADY_ERROR, "Datatype not ready at config time.", type)); } } NOTREACHED(); return false; } void DataTypeManagerImpl::ProcessReconfigure() { // This may have been called asynchronously; no-op if it is no longer needed. if (!needs_reconfigure_) { return; } // Wait for current download and association to finish. if (!download_types_queue_.empty() || model_association_manager_.state() == ModelAssociationManager::ASSOCIATING) { return; } association_types_queue_ = base::queue<AssociationTypesInfo>(); // An attempt was made to reconfigure while we were already configuring. // This can be because a passphrase was accepted or the user changed the // set of desired types. Either way, |last_requested_types_| will contain // the most recent set of desired types, so we just call configure. // Note: we do this whether or not GetControllersNeedingStart is true, // because we may need to stop datatypes. DVLOG(1) << "Reconfiguring due to previous configure attempt occurring while" << " busy."; // Note: ConfigureImpl is called directly, rather than posted, in order to // ensure that any purging/unapplying/journaling happens while the set of // failed types is still up to date. If stack unwinding were to be done // via PostTask, the failed data types may be reset before the purging was // performed. state_ = RETRYING; needs_reconfigure_ = false; ConfigureImpl(last_requested_types_, last_requested_context_); } void DataTypeManagerImpl::DownloadReady( ModelTypeSet types_to_download, ModelTypeSet first_sync_types, ModelTypeSet failed_configuration_types) { DCHECK_EQ(CONFIGURING, state_); // Persistence errors are reset after each backend configuration attempt // during which they would have been purged. data_type_status_table_.ResetPersistenceErrorsFrom(types_to_download); if (!failed_configuration_types.Empty()) { DataTypeStatusTable::TypeErrorMap errors; for (ModelType type : failed_configuration_types) { SyncError error(FROM_HERE, SyncError::DATATYPE_ERROR, "Backend failed to download type.", type); errors[type] = error; } data_type_status_table_.UpdateFailedDataTypes(errors); needs_reconfigure_ = true; } if (needs_reconfigure_) { download_types_queue_ = TypeSetPriorityList(); ProcessReconfigure(); return; } DCHECK(!download_types_queue_.empty()); download_types_queue_.pop(); // Those types that were already downloaded (non first sync/error types) // should already be associating. Just kick off association of the newly // downloaded types if necessary. if (!association_types_queue_.empty()) { association_types_queue_.back().first_sync_types = first_sync_types; association_types_queue_.back().download_ready_time = base::Time::Now(); StartNextAssociation(UNREADY_AT_CONFIG); } else if (download_types_queue_.empty() && model_association_manager_.state() != ModelAssociationManager::ASSOCIATING) { // There's nothing more to download or associate (implying either there were // no types to associate or they associated as part of |ready_types|). // If the model association manager is also finished, then we're done // configuring. state_ = CONFIGURED; ConfigureResult result(OK, last_requested_types_); NotifyDone(result); return; } StartNextDownload(types_to_download); } void DataTypeManagerImpl::StartNextDownload( ModelTypeSet high_priority_types_before) { if (download_types_queue_.empty()) return; ModelTypeConfigurer::ConfigureParams config_params; ModelTypeSet ready_types = PrepareConfigureParams(&config_params); // The engine's state was initially derived from the types detected to have // been downloaded in the database. Afterwards it is modified only by this // function. We expect |downloaded_types_| to remain consistent because // configuration requests are never aborted; they are retried until they // succeed or the engine is shut down. // // Only one configure is allowed at a time. This is guaranteed by our callers. // The sync engine requests one configure as it is initializing and waits for // it to complete. After engine initialization, all configurations pass // through the DataTypeManager, and we are careful to never send a new // configure request until the current request succeeds. configurer_->ConfigureDataTypes(std::move(config_params)); AssociationTypesInfo association_info; association_info.types = download_types_queue_.front(); association_info.ready_types = ready_types; association_info.download_start_time = base::Time::Now(); association_info.high_priority_types_before = high_priority_types_before; association_types_queue_.push(association_info); // Start associating those types that are already downloaded (does nothing // if model associator is busy). StartNextAssociation(READY_AT_CONFIG); } ModelTypeSet DataTypeManagerImpl::PrepareConfigureParams( ModelTypeConfigurer::ConfigureParams* params) { // Divide up the types into their corresponding actions: // - Types which are newly enabled are downloaded. // - Types which have encountered a fatal error (fatal_types) are deleted // from the directory and journaled in the delete journal. // - Types which have encountered a cryptographer error (crypto_types) are // unapplied (local state is purged but sync state is not). // - All other types not in the routing info (types just disabled) are deleted // from the directory. // - Everything else (enabled types and already disabled types) is not // touched. const DataTypeConfigStateMap config_state_map = BuildDataTypeConfigStateMap(download_types_queue_.front()); const ModelTypeSet fatal_types = GetDataTypesInState(FATAL, config_state_map); const ModelTypeSet crypto_types = GetDataTypesInState(CRYPTO, config_state_map); const ModelTypeSet unready_types = GetDataTypesInState(UNREADY, config_state_map); const ModelTypeSet active_types = GetDataTypesInState(CONFIGURE_ACTIVE, config_state_map); const ModelTypeSet clean_types = GetDataTypesInState(CONFIGURE_CLEAN, config_state_map); const ModelTypeSet inactive_types = GetDataTypesInState(CONFIGURE_INACTIVE, config_state_map); ModelTypeSet enabled_types = Union(active_types, clean_types); ModelTypeSet disabled_types = GetDataTypesInState(DISABLED, config_state_map); disabled_types.PutAll(fatal_types); disabled_types.PutAll(crypto_types); disabled_types.PutAll(unready_types); DCHECK(Intersection(enabled_types, disabled_types).Empty()); // The sync engine's enabled types will be updated by adding |enabled_types| // to the list then removing |disabled_types|. Any types which are not in // either of those sets will remain untouched. Types which were not in // |downloaded_types_| previously are not fully downloaded, so we must ask the // engine to download them. Any newly supported datatypes won't have been in // |downloaded_types_|, so they will also be downloaded if they are enabled. ModelTypeSet types_to_download = Difference(enabled_types, downloaded_types_); downloaded_types_.PutAll(enabled_types); downloaded_types_.RemoveAll(disabled_types); types_to_download.PutAll(clean_types); types_to_download.RemoveAll(ProxyTypes()); types_to_download.RemoveAll(CommitOnlyTypes()); if (!types_to_download.Empty()) types_to_download.Put(NIGORI); force_redownload_types_.RemoveAll(types_to_download); // TODO(sync): crbug.com/137550. // It's dangerous to configure types that have progress markers. Types with // progress markers can trigger a MIGRATION_DONE response. We are not // prepared to handle a migration during a configure, so we must ensure that // all our types_to_download actually contain no data before we sync them. // // One common way to end up in this situation used to be types which // downloaded some or all of their data but have not applied it yet. We avoid // problems with those types by purging the data of any such partially synced // types soon after we load the directory. // // Another possible scenario is that we have newly supported or newly enabled // data types being downloaded here but the nigori type, which is always // included in any GetUpdates request, requires migration. The server has // code to detect this scenario based on the configure reason, the fact that // the nigori type is the only requested type which requires migration, and // that the requested types list includes at least one non-nigori type. It // will not send a MIGRATION_DONE response in that case. We still need to be // careful to not send progress markers for non-nigori types, though. If a // non-nigori type in the request requires migration, a MIGRATION_DONE // response will be sent. ModelTypeSet types_to_purge; // If we're using transport-only mode, don't clear any old data. The reason is // that if a user temporarily disables Sync, we don't want to wipe (and later // redownload) all their data, just because Sync restarted in transport-only // mode. if (last_requested_context_.sync_mode == SyncMode::kFull) { types_to_purge = Difference(ModelTypeSet::All(), downloaded_types_); // Include clean_types in types_to_purge, they are part of // |downloaded_types_|, but still need to be cleared. DCHECK(downloaded_types_.HasAll(clean_types)); types_to_purge.PutAll(clean_types); types_to_purge.RemoveAll(inactive_types); types_to_purge.RemoveAll(unready_types); } // If a type has already been disabled and unapplied or journaled, it will // not be part of the |types_to_purge| set, and therefore does not need // to be acted on again. ModelTypeSet types_to_journal = Intersection(fatal_types, types_to_purge); ModelTypeSet unapply_types = Union(crypto_types, clean_types); unapply_types.RetainAll(types_to_purge); DCHECK(Intersection(downloaded_types_, types_to_journal).Empty()); DCHECK(Intersection(downloaded_types_, crypto_types).Empty()); // |downloaded_types_| was already updated to include all enabled types. DCHECK(downloaded_types_.HasAll(types_to_download)); DVLOG(1) << "Types " << ModelTypeSetToString(types_to_download) << " added; calling ConfigureDataTypes"; params->reason = last_requested_context_.reason; params->enabled_types = enabled_types; params->disabled_types = disabled_types; params->to_download = types_to_download; params->to_purge = types_to_purge; params->to_journal = types_to_journal; params->to_unapply = unapply_types; params->ready_task = base::BindOnce(&DataTypeManagerImpl::DownloadReady, weak_ptr_factory_.GetWeakPtr(), download_types_queue_.front()); params->is_sync_feature_enabled = last_requested_context_.sync_mode == SyncMode::kFull; DCHECK(Intersection(active_types, types_to_purge).Empty()); DCHECK(Intersection(active_types, fatal_types).Empty()); DCHECK(Intersection(active_types, unapply_types).Empty()); DCHECK(Intersection(active_types, inactive_types).Empty()); return Difference(active_types, types_to_download); } void DataTypeManagerImpl::StartNextAssociation(AssociationGroup group) { DCHECK(!association_types_queue_.empty()); // If the model association manager is already associating, let it finish. // The model association done event will result in associating any remaining // association groups. if (model_association_manager_.state() != ModelAssociationManager::INITIALIZED) { return; } ModelTypeSet types_to_associate; if (group == READY_AT_CONFIG) { association_types_queue_.front().ready_association_request_time = base::Time::Now(); types_to_associate = association_types_queue_.front().ready_types; } else { DCHECK_EQ(UNREADY_AT_CONFIG, group); // Only start associating the rest of the types if they have all finished // downloading. if (association_types_queue_.front().download_ready_time.is_null()) return; association_types_queue_.front().full_association_request_time = base::Time::Now(); // We request the full set of types here for completeness sake. All types // within the READY_AT_CONFIG set will already be started and should be // no-ops. types_to_associate = association_types_queue_.front().types; } DVLOG(1) << "Associating " << ModelTypeSetToString(types_to_associate); model_association_manager_.StartAssociationAsync(types_to_associate); } void DataTypeManagerImpl::OnSingleDataTypeWillStop(ModelType type, const SyncError& error) { auto c_it = controllers_->find(type); DCHECK(c_it != controllers_->end()); // Delegate deactivation to the controller. c_it->second->DeactivateDataType(configurer_); if (error.IsSet()) { data_type_status_table_.UpdateFailedDataType(type, error); // Unrecoverable errors will shut down the entire backend, so no need to // reconfigure. if (error.error_type() != SyncError::UNRECOVERABLE_ERROR) { needs_reconfigure_ = true; last_requested_context_.reason = GetReasonForProgrammaticReconfigure(last_requested_context_.reason); // Do this asynchronously so the ModelAssociationManager has a chance to // finish stopping this type, otherwise DeactivateDataType() and Stop() // end up getting called twice on the controller. base::SequencedTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&DataTypeManagerImpl::ProcessReconfigure, weak_ptr_factory_.GetWeakPtr())); } } } void DataTypeManagerImpl::OnSingleDataTypeAssociationDone( ModelType type, const DataTypeAssociationStats& association_stats) { DCHECK(!association_types_queue_.empty()); if (!debug_info_listener_.IsInitialized()) return; AssociationTypesInfo& info = association_types_queue_.front(); configuration_stats_.push_back(DataTypeConfigurationStats()); configuration_stats_.back().model_type = type; configuration_stats_.back().association_stats = association_stats; if (info.types.Has(type)) { // Times in |info| only apply to non-slow types. configuration_stats_.back().download_wait_time = info.download_start_time - last_restart_time_; if (info.first_sync_types.Has(type)) { configuration_stats_.back().download_time = info.download_ready_time - info.download_start_time; } if (info.ready_types.Has(type)) { configuration_stats_.back().association_wait_time_for_high_priority = info.ready_association_request_time - info.download_start_time; } else { configuration_stats_.back().association_wait_time_for_high_priority = info.full_association_request_time - info.download_ready_time; } configuration_stats_.back().high_priority_types_configured_before = info.high_priority_types_before; configuration_stats_.back().same_priority_types_configured_before = info.configured_types; info.configured_types.Put(type); } } void DataTypeManagerImpl::OnModelAssociationDone( const DataTypeManager::ConfigureResult& result) { DCHECK(state_ == STOPPING || state_ == CONFIGURING); if (state_ == STOPPING) return; // Ignore abort/unrecoverable error if we need to reconfigure anyways. if (needs_reconfigure_) { ProcessReconfigure(); return; } if (result.status == ABORTED || result.status == UNRECOVERABLE_ERROR) { Abort(result.status); return; } DCHECK(result.status == OK); DCHECK(!association_types_queue_.empty()); // If this model association was for the full set of types, then this priority // set is done. Otherwise it was just the ready types and the unready types // still need to be associated. if (result.requested_types == association_types_queue_.front().types) { association_types_queue_.pop(); if (!association_types_queue_.empty()) { StartNextAssociation(READY_AT_CONFIG); } else if (download_types_queue_.empty()) { state_ = CONFIGURED; NotifyDone(result); } } else { DCHECK_EQ(association_types_queue_.front().ready_types, result.requested_types); // Will do nothing if the types are still downloading. StartNextAssociation(UNREADY_AT_CONFIG); } } void DataTypeManagerImpl::Stop(ShutdownReason reason) { if (state_ == STOPPED) return; bool need_to_notify = state_ == CONFIGURING; StopImpl(reason); if (need_to_notify) { ConfigureResult result(ABORTED, last_requested_types_); NotifyDone(result); } } void DataTypeManagerImpl::Abort(ConfigureStatus status) { DCHECK_EQ(CONFIGURING, state_); StopImpl(STOP_SYNC); DCHECK_NE(OK, status); ConfigureResult result(status, last_requested_types_); NotifyDone(result); } void DataTypeManagerImpl::StopImpl(ShutdownReason reason) { state_ = STOPPING; // Invalidate weak pointer to drop download callbacks. weak_ptr_factory_.InvalidateWeakPtrs(); // Stop all data types. This may trigger association callback but the // callback will do nothing because state is set to STOPPING above. model_association_manager_.Stop(reason); // Individual data type controllers might still be STOPPING, but we don't // reflect that in |state_| because, for all practical matters, the manager is // in a ready state and reconfguration can be triggered. // TODO(mastiz): Reconsider waiting in STOPPING state until all datatypes have // stopped. state_ = STOPPED; } void DataTypeManagerImpl::NotifyStart() { observer_->OnConfigureStart(); } void DataTypeManagerImpl::NotifyDone(const ConfigureResult& raw_result) { DCHECK(!last_restart_time_.is_null()); base::TimeDelta configure_time = base::Time::Now() - last_restart_time_; ConfigureResult result = raw_result; result.data_type_status_table = data_type_status_table_; const std::string prefix_uma = (last_requested_context_.reason == CONFIGURE_REASON_NEW_CLIENT) ? "Sync.ConfigureTime_Initial" : "Sync.ConfigureTime_Subsequent"; DVLOG(1) << "Total time spent configuring: " << configure_time.InSecondsF() << "s"; switch (result.status) { case DataTypeManager::OK: DVLOG(1) << "NotifyDone called with result: OK"; base::UmaHistogramLongTimes(prefix_uma + ".OK", configure_time); if (debug_info_listener_.IsInitialized() && !configuration_stats_.empty()) { debug_info_listener_.Call( FROM_HERE, &DataTypeDebugInfoListener::OnDataTypeConfigureComplete, configuration_stats_); } configuration_stats_.clear(); break; case DataTypeManager::ABORTED: DVLOG(1) << "NotifyDone called with result: ABORTED"; base::UmaHistogramLongTimes(prefix_uma + ".ABORTED", configure_time); break; case DataTypeManager::UNRECOVERABLE_ERROR: DVLOG(1) << "NotifyDone called with result: UNRECOVERABLE_ERROR"; base::UmaHistogramLongTimes(prefix_uma + ".UNRECOVERABLE_ERROR", configure_time); break; case DataTypeManager::UNKNOWN: NOTREACHED(); break; } observer_->OnConfigureDone(result); } ModelTypeSet DataTypeManagerImpl::GetActiveDataTypes() const { if (state_ != CONFIGURED) return ModelTypeSet(); return GetEnabledTypes(); } bool DataTypeManagerImpl::IsNigoriEnabled() const { return downloaded_types_.Has(NIGORI); } DataTypeManager::State DataTypeManagerImpl::state() const { return state_; } ModelTypeSet DataTypeManagerImpl::GetEnabledTypes() const { return Difference(last_requested_types_, data_type_status_table_.GetFailedTypes()); } } // namespace syncer
{ "content_hash": "744e374e5ec8d415f55c175433195482", "timestamp": "", "source": "github", "line_count": 913, "max_line_length": 80, "avg_line_length": 39.35596933187295, "alnum_prop": 0.711454970499833, "repo_name": "endlessm/chromium-browser", "id": "cbe7d0b352a5ed347351593b11530034024799ae", "size": "35932", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "components/sync/driver/data_type_manager_impl.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
<mat-card class="steps feed-card" > <mat-card-header > <mat-card-title> <!-- <mat-icon>playlist_add_check</mat-icon> --> <span>Setup Guide</span> </mat-card-title> <mat-card-subtitle>Required and optional steps</mat-card-subtitle> <span fxFlex></span> </mat-card-header> <mat-card-content> <mat-list role="list" dense> <mat-divider *ngIf="requiredSteps.length >0"></mat-divider> <h3 mat-subheader *ngIf="requiredSteps.length >0">Required</h3> <mat-divider *ngIf="requiredSteps.length >0"></mat-divider> <ng-container *ngFor="let step of requiredSteps; let $last=last"> <ng-template [ngTemplateOutlet]="setupStepSummary" [ngTemplateOutletContext]="{$implicit:step, $last:$last}"> </ng-template> </ng-container> <mat-divider *ngIf="optionalSteps.length >0"></mat-divider> <h3 mat-subheader *ngIf="optionalSteps.length >0">Optional</h3> <mat-divider *ngIf="optionalSteps.length >0"></mat-divider> <ng-container *ngFor="let step of optionalSteps; let $last=last"> <ng-template [ngTemplateOutlet]="setupStepSummary" [ngTemplateOutletContext]="{$implicit:step, $last:$last}"> </ng-template> </ng-container> </mat-list> </mat-card-content> </mat-card> <ng-template #setupStepSummary let-step let-$last="$last"> <mat-list-item (click)="onStepSelected(step)" [ngClass]="{'disabled-step':step.disabled}" class="overview-step"> <mat-icon matListAvatar color="green" *ngIf="step.complete">check_circle</mat-icon> <mat-icon matListAvatar color="accent" *ngIf="!step.complete && step.icon">{{step.icon}}</mat-icon> <h3 matLine [ngClass]="{'completed-step':step.complete}"> {{step.name}} </h3> <p matLine [ngClass]="{'completed-step':step.complete}"> {{step.description}}</p> <span></span> <mat-icon color="accent">keyboard_arrow_right</mat-icon> </mat-list-item> <mat-divider *ngIf=" !$last"></mat-divider> </ng-template>
{ "content_hash": "4ab0d563442bcda1377035e99dc62c86", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 114, "avg_line_length": 43.170212765957444, "alnum_prop": 0.641695416461311, "repo_name": "Teradata/kylo", "id": "20eaa659cb70fe44e11228c7d4aaf27d2ff44539", "size": "2029", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "ui/ui-app/src/main/resources/static/js/feed-mgr/feeds/define-feed-ng2/summary/setup-guide-summary/feed-setup-guide/feed-setup-guide.component.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "206880" }, { "name": "FreeMarker", "bytes": "785" }, { "name": "HTML", "bytes": "1076578" }, { "name": "Java", "bytes": "13931541" }, { "name": "JavaScript", "bytes": "1956411" }, { "name": "PLpgSQL", "bytes": "46248" }, { "name": "SQLPL", "bytes": "8898" }, { "name": "Scala", "bytes": "72686" }, { "name": "Shell", "bytes": "124425" }, { "name": "TypeScript", "bytes": "3763974" } ], "symlink_target": "" }
package generated.zcsclient.admin; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for getAllServersResponse complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="getAllServersResponse"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element ref="{urn:zimbraAdmin}server" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "getAllServersResponse", propOrder = { "server" }) public class testGetAllServersResponse { protected List<testServerInfo> server; /** * Gets the value of the server property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the server property. * * <p> * For example, to add a new item, do as follows: * <pre> * getServer().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link testServerInfo } * * */ public List<testServerInfo> getServer() { if (server == null) { server = new ArrayList<testServerInfo>(); } return this.server; } }
{ "content_hash": "783d30c65c1df9e1ba05479f0c39ea24", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 95, "avg_line_length": 26.65671641791045, "alnum_prop": 0.6377379619260918, "repo_name": "nico01f/z-pec", "id": "a1148f926d097fa52b8a223a2bf6d099395e6eac", "size": "1786", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ZimbraSoap/src/wsdl-test/generated/zcsclient/admin/testGetAllServersResponse.java", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "18110" }, { "name": "C", "bytes": "61139" }, { "name": "C#", "bytes": "1461640" }, { "name": "C++", "bytes": "723279" }, { "name": "CSS", "bytes": "2648118" }, { "name": "Groff", "bytes": "15389" }, { "name": "HTML", "bytes": "83875860" }, { "name": "Java", "bytes": "49998455" }, { "name": "JavaScript", "bytes": "39307223" }, { "name": "Makefile", "bytes": "13060" }, { "name": "PHP", "bytes": "4263" }, { "name": "PLSQL", "bytes": "17047" }, { "name": "Perl", "bytes": "2030870" }, { "name": "PowerShell", "bytes": "1485" }, { "name": "Python", "bytes": "129210" }, { "name": "Shell", "bytes": "575209" }, { "name": "XSLT", "bytes": "20635" } ], "symlink_target": "" }
package ru.yandex.qatools.allure.data.io; import com.google.inject.Inject; import ru.yandex.qatools.allure.model.Description; import ru.yandex.qatools.allure.model.Label; import ru.yandex.qatools.allure.model.TestCaseResult; import ru.yandex.qatools.allure.model.TestSuiteResult; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import static ru.yandex.qatools.allure.data.utils.DescriptionUtils.mergeDescriptions; /** * @author Dmitry Baev [email protected] * Date: 09.02.15 */ public class TestCaseReader implements Reader<TestCaseResult> { public static final String SUITE_NAME = "suite-name"; public static final String SUITE_TITLE = "suite-title"; private Iterator<TestSuiteResult> testSuites; private Iterator<TestCaseResult> testCases; private TestSuiteResult currentSuite; @Inject public TestCaseReader(Reader<TestSuiteResult> suiteResultsReader) { testSuites = suiteResultsReader.iterator(); } @Override public Iterator<TestCaseResult> iterator() { return new TestCaseResultIterator(); } private class TestCaseResultIterator implements Iterator<TestCaseResult> { private boolean nextSuite() { if ((testCases == null || !testCases.hasNext()) && testSuites.hasNext()) { currentSuite = testSuites.next(); testCases = currentSuite.getTestCases().iterator(); return true; } return false; } @Override public boolean hasNext() { return testCases != null && testCases.hasNext() || nextSuite() && hasNext(); } @Override public TestCaseResult next() { if (!hasNext()) { return null; } TestCaseResult result = testCases.next(); Set<Label> labels = new HashSet<>(currentSuite.getLabels()); labels.add(new Label().withName(SUITE_NAME).withValue(currentSuite.getName())); labels.add(new Label().withName(SUITE_TITLE).withValue(currentSuite.getTitle())); labels.addAll(result.getLabels()); result.setLabels(new ArrayList<>(labels)); Description description = mergeDescriptions(currentSuite, result); result.setDescription(description); return result; } @Override public void remove() { throw new UnsupportedOperationException(); } } }
{ "content_hash": "aacf50d53c97f81e8f3fd9488a3bccab", "timestamp": "", "source": "github", "line_count": 86, "max_line_length": 93, "avg_line_length": 29.46511627906977, "alnum_prop": 0.648776637726914, "repo_name": "allure-framework/allure1", "id": "5aa744ed2961288637d7b381d8b3b5fb247c937d", "size": "2534", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "allure-report-data/src/main/java/ru/yandex/qatools/allure/data/io/TestCaseReader.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "2521" }, { "name": "CSS", "bytes": "21989" }, { "name": "FreeMarker", "bytes": "536" }, { "name": "Groovy", "bytes": "121593" }, { "name": "HTML", "bytes": "20546" }, { "name": "Java", "bytes": "342254" }, { "name": "JavaScript", "bytes": "95541" }, { "name": "Shell", "bytes": "1788" } ], "symlink_target": "" }
package de.uni.freiburg.iig.telematik.swat.analysis.modelchecker.prism.modeltranlator; import java.util.Calendar; import java.util.Iterator; import de.invation.code.toval.validate.ParameterException; import de.uni.freiburg.iig.telematik.sepia.petrinet.abstr.AbstractPetriNet; import de.uni.freiburg.iig.telematik.sepia.petrinet.abstr.AbstractPlace; import de.uni.freiburg.iig.telematik.sepia.petrinet.abstr.AbstractTransition; import de.uni.freiburg.iig.telematik.sepia.petrinet.ifnet.DeclassificationTransition; import de.uni.freiburg.iig.telematik.sepia.petrinet.pt.PTNet; import de.uni.freiburg.iig.telematik.swat.analysis.modelchecker.prism.TransitionToIDMapper; /** * The PrismTranslator is used to translate a petri net into a DTMC (Discrete Time Markov Chain) * in the Prism language. The rules of the translation partially depends on the type of the petri net. * There are separate classes which extend this class in order to perform the translation for the * different petri net types (simple petri net, cpn, ifnet). * * @author Lukas Sättler * @version 1.0 */ public abstract class PrismModelAdapter { private final String VERSION = "1.0"; protected AbstractPetriNet<?,?,?,?,?> mAbstractNet; protected boolean bounded = true; public static final String transitionVarName = "current_trans"; public boolean isBoundedNet() { return bounded; } protected PrismModelAdapter(AbstractPetriNet<?,?,?,?,?> net) { mAbstractNet = net; //bounded = net.isBounded(); } public StringBuilder translate() throws PlaceException { StringBuilder placeVars = createPlaceVars(); StringBuilder transitionVars = createTransitionVars(); StringBuilder transitions = createTransitions(); return composeModel(transitionVars, placeVars, transitions); } public AbstractPetriNet<?,?,?,?,?> getNet() { return mAbstractNet; } private StringBuilder createTransitionVars() throws ParameterException { StringBuilder transitionVarBuilder = new StringBuilder(); for (AbstractTransition<?,?> t : mAbstractNet.getTransitions()) { transitionVarBuilder.append("//TransitionName: " + t.getName() + " " + "(TransitionLabel: " + t.getLabel() + ")" + "\n"); if(t instanceof DeclassificationTransition){ transitionVarBuilder.append("//Declassification Transition" + "\n"); } else { transitionVarBuilder.append("//Regular Transition" + "\n"); } //transitionVarBuilder.append(t.getName() + " : [0..1] init 0;" + "\n"); transitionVarBuilder.append(t.getName() + "_fired"+" : [0..1] init 0;" + "\n"+ "\n"); //remember last fired state transitionVarBuilder.append(t.getName() + "_last"+" : [0..1] init 0;" + "\n"+ "\n"); } int numberOfTransitions = TransitionToIDMapper.getTransitionCount(); transitionVarBuilder.append(transitionVarName + " : [0.." + numberOfTransitions + "] init 0;" + "\n"); return transitionVarBuilder; } protected StringBuilder composeModel(StringBuilder transitionVars, StringBuilder placeVars, StringBuilder transitions) { StringBuilder prismModelBuilder = new StringBuilder(); prismModelBuilder.append("//generated at: " + Calendar.getInstance().getTime()+ "\n"); prismModelBuilder.append("//by user: " + System.getProperty("user.name") + "\n"); prismModelBuilder.append("//with converter Version: " + VERSION + "\n"); prismModelBuilder.append("\n"); prismModelBuilder.append("//Nondeterminism is resolved probabilistically in this model!"+ "\n"); prismModelBuilder.append("dtmc"+ "\n"); prismModelBuilder.append("\n"); prismModelBuilder.append("module IFNet" + "\n"); prismModelBuilder.append("\n"); // append place variables prismModelBuilder.append(placeVars); //append transition variables prismModelBuilder.append(transitionVars); // append transitions prismModelBuilder.append(transitions); if (mAbstractNet.getDrainPlaces().size() == 1) { prismModelBuilder.append(createTerminationLoops()); } else { System.out.println("Warning! The current net isn't sound. Computations can be inaccurate."); } prismModelBuilder.append("endmodule"); prismModelBuilder.append("\n"); return prismModelBuilder; } private StringBuilder createTerminationLoops() { StringBuilder termLoopBuilder = new StringBuilder(); String enableCondition = ""; @SuppressWarnings("unchecked") Iterator<AbstractPlace<?,?>> placeIter = (Iterator<AbstractPlace<?, ?>>) mAbstractNet.getDrainPlaces().iterator(); // check whether output places contain a token while(placeIter.hasNext()){ AbstractPlace<?,?> curPlace = placeIter.next(); if (placeIter.hasNext()) { enableCondition += curPlace.getName() + "_black>=1 |"; } else { enableCondition += curPlace.getName() + "_black>=1"; } } String loopEffect = " (" + transitionVarName + "'= 0)"; termLoopBuilder.append("[] "); termLoopBuilder.append(enableCondition); termLoopBuilder.append(" -> "); termLoopBuilder.append(loopEffect); termLoopBuilder.append(";\n\n"); return termLoopBuilder; } protected abstract StringBuilder createPlaceVars() throws PlaceException; protected abstract StringBuilder createTransitions(); public static void main(String[] args) throws PlaceException { PTNet net = new PTNet(); net.addPlace("p1"); net.getPlace("p1").setCapacity(1); net.addPlace("p2"); net.getPlace("p2").setCapacity(1); net.addPlace("p3"); net.getPlace("p3").setCapacity(1); net.addTransition("t1"); net.addFlowRelationPT("p1", "t1"); net.addFlowRelationTP("t1", "p2"); net.addTransition("t2"); net.addFlowRelationPT("p2", "t2"); net.addFlowRelationTP("t2", "p3"); PTNetConverter c = new PTNetConverter(net); StringBuilder sb = c.translate(); System.out.println(sb.toString()); } }
{ "content_hash": "7e00a6adb21747779f34be0cf6b32ba4", "timestamp": "", "source": "github", "line_count": 176, "max_line_length": 104, "avg_line_length": 33.21022727272727, "alnum_prop": 0.7117194183062446, "repo_name": "iig-uni-freiburg/SWAT20", "id": "23e929e11d679960f839f5342c727db97730b614", "size": "5846", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/de/uni/freiburg/iig/telematik/swat/analysis/modelchecker/prism/modeltranlator/PrismModelAdapter.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C++", "bytes": "1007" }, { "name": "Java", "bytes": "1217898" }, { "name": "Shell", "bytes": "48" } ], "symlink_target": "" }
layout: page title: Chen Family Reunion date: 2016-05-24 author: Albert Kane tags: weekly links, java status: published summary: Phasellus sed tempus tortor. Vestibulum. banner: images/banner/office-01.jpg booking: startDate: 05/30/2017 endDate: 06/04/2017 ctyhocn: BNAEAHX groupCode: CFR published: true --- Morbi mattis porttitor urna vel facilisis. Vestibulum convallis semper vestibulum. Cras auctor ante vel ultrices sodales. Nulla facilisi. Aenean mattis bibendum quam at eleifend. Vestibulum sollicitudin, arcu sed auctor porta, magna mi consectetur nibh, eget facilisis libero lacus sit amet tortor. Donec quis sem rutrum, ullamcorper urna quis, scelerisque justo. Donec ut euismod velit. Vivamus at neque nisl. Vivamus ut interdum dui. Nunc nulla lorem, congue ut blandit sed, auctor quis orci. Aenean nec pulvinar metus, vel consequat nisl. Nam vel euismod massa. Proin ac sapien laoreet, elementum nisi ut, congue tortor. Proin mollis viverra ligula. Duis sed sem et nibh faucibus tincidunt. Praesent sit amet vulputate arcu. Donec finibus tortor a dui posuere faucibus. Pellentesque a est erat. Donec et tellus felis. Sed eget nisi quis nulla consequat vulputate vitae ac purus. Curabitur in tellus lorem. Etiam auctor pulvinar purus sed iaculis. Sed ac arcu malesuada leo pretium mollis. Maecenas sit amet tincidunt tellus. Maecenas quam elit, venenatis id leo ut, semper ornare lorem. Vivamus ultricies placerat ante, imperdiet mollis ex maximus et. 1 Nam et leo ac lectus tincidunt ultrices vitae pharetra odio 1 Morbi laoreet ipsum non lectus euismod feugiat 1 Sed sed ligula hendrerit, sollicitudin est a, imperdiet arcu 1 Praesent at elit sed metus posuere ullamcorper. Maecenas fringilla augue ut velit maximus cursus. Aenean varius mi augue, ac dictum arcu bibendum nec. Etiam commodo porta lorem, a elementum metus scelerisque id. Mauris iaculis, ligula ut lacinia pulvinar, orci urna pellentesque ante, non semper lectus urna vel arcu. Donec molestie est sed massa tempus euismod ac sit amet mi. Vivamus ultricies, metus vitae lacinia rutrum, metus tortor sodales ipsum, ultricies consequat urna nisl sit amet mauris. Nullam dictum arcu ornare turpis interdum, a fringilla lacus volutpat.
{ "content_hash": "5246368732e917e81d670e7f5d645560", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 589, "avg_line_length": 92.54166666666667, "alnum_prop": 0.8081945069788383, "repo_name": "KlishGroup/prose-pogs", "id": "90721f2904a20db86c5d3f843682b9b9133328f0", "size": "2225", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "pogs/B/BNAEAHX/CFR/index.md", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
require "rubygems" require "bundler/setup" Bundler.require(:default) require_all "lib" require "active_support/all" def app_init configure_figaro configure_honeybadger setup_resque end def configure_honeybadger Honeybadger.configure do |config| config.api_key = ENV["HONEYBADGER_API_KEY"] config.env = ENV["NAMESPACE"] end end def configure_figaro Figaro.application = Figaro::Application.new(environment: ENV["NAMESPACE"], path: "config/application.yml") Figaro.load end def setup_resque Resque.redis = Redis.new(host: ENV["REDIS_HOST"], port: ENV["REDIS_PORT"]) end
{ "content_hash": "64b9e6480e1d67f091a5807772a7b817", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 78, "avg_line_length": 22.964285714285715, "alnum_prop": 0.6889580093312597, "repo_name": "wearemolecule/cme-fix-listener", "id": "2ddb084daa5baf822a785641c8f60e63c628a324", "size": "674", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "config/application.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "329" }, { "name": "Ruby", "bytes": "82231" } ], "symlink_target": "" }
module.exports = function (opts) { require('../../index.js')(opts) }
{ "content_hash": "c403b1f14e0c07a9f8a791ad9f4feebb", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 34, "avg_line_length": 23.666666666666668, "alnum_prop": 0.6056338028169014, "repo_name": "sdgluck/elquire", "id": "08a655380d6c81c6bffbd8d73a9d338d1e265a50", "size": "71", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/_isolated/index.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "15518" } ], "symlink_target": "" }
const char FileTemplate::kSource[] = "{{source}}"; const char FileTemplate::kSourceNamePart[] = "{{source_name_part}}"; const char FileTemplate::kSourceFilePart[] = "{{source_file_part}}"; const char kSourceExpansion_Help[] = "How Source Expansion Works\n" "\n" " Source expansion is used for the custom script and copy target types\n" " to map source file names to output file names or arguments.\n" "\n" " To perform source expansion in the outputs, GN maps every entry in the\n" " sources to every entry in the outputs list, producing the cross\n" " product of all combinations, expanding placeholders (see below).\n" "\n" " Source expansion in the args works similarly, but performing the\n" " placeholder substitution produces a different set of arguments for\n" " each invocation of the script.\n" "\n" " If no placeholders are found, the outputs or args list will be treated\n" " as a static list of literal file names that do not depend on the\n" " sources.\n" "\n" " See \"gn help copy\" and \"gn help custom\" for more on how this is\n" " applied.\n" "\n" "Placeholders\n" "\n" " {{source}}\n" " The name of the source file relative to the root build output\n" " directory (which is the current directory when running compilers\n" " and scripts). This will generally be used for specifying inputs\n" " to a script in the \"args\" variable.\n" "\n" " {{source_file_part}}\n" " The file part of the source including the extension. For the\n" " source \"foo/bar.txt\" the source file part will be \"bar.txt\".\n" "\n" " {{source_name_part}}\n" " The filename part of the source file with no directory or\n" " extension. This will generally be used for specifying a\n" " transformation from a soruce file to a destination file with the\n" " same name but different extension. For the source \"foo/bar.txt\"\n" " the source name part will be \"bar\".\n" "\n" "Examples\n" "\n" " Non-varying outputs:\n" " script(\"hardcoded_outputs\") {\n" " sources = [ \"input1.idl\", \"input2.idl\" ]\n" " outputs = [ \"$target_out_dir/output1.dat\",\n" " \"$target_out_dir/output2.dat\" ]\n" " }\n" " The outputs in this case will be the two literal files given.\n" "\n" " Varying outputs:\n" " script(\"varying_outputs\") {\n" " sources = [ \"input1.idl\", \"input2.idl\" ]\n" " outputs = [ \"$target_out_dir/{{source_name_part}}.h\",\n" " \"$target_out_dir/{{source_name_part}}.cc\" ]\n" " }\n" " Performing source expansion will result in the following output names:\n" " //out/Debug/obj/mydirectory/input1.h\n" " //out/Debug/obj/mydirectory/input1.cc\n" " //out/Debug/obj/mydirectory/input2.h\n" " //out/Debug/obj/mydirectory/input2.cc\n"; FileTemplate::FileTemplate(const Value& t, Err* err) : has_substitutions_(false) { std::fill(types_required_, &types_required_[Subrange::NUM_TYPES], false); ParseInput(t, err); } FileTemplate::FileTemplate(const std::vector<std::string>& t) : has_substitutions_(false) { std::fill(types_required_, &types_required_[Subrange::NUM_TYPES], false); for (size_t i = 0; i < t.size(); i++) ParseOneTemplateString(t[i]); } FileTemplate::~FileTemplate() { } bool FileTemplate::IsTypeUsed(Subrange::Type type) const { DCHECK(type > Subrange::LITERAL && type < Subrange::NUM_TYPES); return types_required_[type]; } void FileTemplate::Apply(const Value& sources, const ParseNode* origin, std::vector<Value>* dest, Err* err) const { if (!sources.VerifyTypeIs(Value::LIST, err)) return; dest->reserve(sources.list_value().size() * templates_.container().size()); // Temporary holding place, allocate outside to re-use- buffer. std::vector<std::string> string_output; const std::vector<Value>& sources_list = sources.list_value(); for (size_t i = 0; i < sources_list.size(); i++) { if (!sources_list[i].VerifyTypeIs(Value::STRING, err)) return; ApplyString(sources_list[i].string_value(), &string_output); for (size_t out_i = 0; out_i < string_output.size(); out_i++) dest->push_back(Value(origin, string_output[i])); } } void FileTemplate::ApplyString(const std::string& str, std::vector<std::string>* output) const { // Compute all substitutions needed so we can just do substitutions below. // We skip the LITERAL one since that varies each time. std::string subst[Subrange::NUM_TYPES]; for (int i = 1; i < Subrange::NUM_TYPES; i++) { if (types_required_[i]) subst[i] = GetSubstitution(str, static_cast<Subrange::Type>(i)); } output->resize(templates_.container().size()); for (size_t template_i = 0; template_i < templates_.container().size(); template_i++) { const Template& t = templates_[template_i]; (*output)[template_i].clear(); for (size_t subrange_i = 0; subrange_i < t.container().size(); subrange_i++) { if (t[subrange_i].type == Subrange::LITERAL) (*output)[template_i].append(t[subrange_i].literal); else (*output)[template_i].append(subst[t[subrange_i].type]); } } } void FileTemplate::WriteWithNinjaExpansions(std::ostream& out) const { EscapeOptions escape_options; escape_options.mode = ESCAPE_NINJA_SHELL; escape_options.inhibit_quoting = true; for (size_t template_i = 0; template_i < templates_.container().size(); template_i++) { out << " "; // Separate args with spaces. const Template& t = templates_[template_i]; // Escape each subrange into a string. Since we're writing out Ninja // variables, we can't quote the whole thing, so we write in pieces, only // escaping the literals, and then quoting the whole thing at the end if // necessary. bool needs_quoting = false; std::string item_str; for (size_t subrange_i = 0; subrange_i < t.container().size(); subrange_i++) { if (t[subrange_i].type == Subrange::LITERAL) { item_str.append(EscapeString(t[subrange_i].literal, escape_options, &needs_quoting)); } else { // Don't escape this since we need to preserve the $. item_str.append("${"); item_str.append(GetNinjaVariableNameForType(t[subrange_i].type)); item_str.append("}"); } } if (needs_quoting) { // Need to shell quote the whole string. out << '"' << item_str << '"'; } else { out << item_str; } } } void FileTemplate::WriteNinjaVariablesForSubstitution( std::ostream& out, const std::string& source, const EscapeOptions& escape_options) const { for (int i = 1; i < Subrange::NUM_TYPES; i++) { if (types_required_[i]) { Subrange::Type type = static_cast<Subrange::Type>(i); out << " " << GetNinjaVariableNameForType(type) << " = "; EscapeStringToStream(out, GetSubstitution(source, type), escape_options); out << std::endl; } } } // static const char* FileTemplate::GetNinjaVariableNameForType(Subrange::Type type) { switch (type) { case Subrange::SOURCE: return "source"; case Subrange::NAME_PART: return "source_name_part"; case Subrange::FILE_PART: return "source_file_part"; default: NOTREACHED(); } return ""; } // static std::string FileTemplate::GetSubstitution(const std::string& source, Subrange::Type type) { switch (type) { case Subrange::SOURCE: return source; case Subrange::NAME_PART: return FindFilenameNoExtension(&source).as_string(); case Subrange::FILE_PART: return FindFilename(&source).as_string(); default: NOTREACHED(); } return std::string(); } void FileTemplate::ParseInput(const Value& value, Err* err) { switch (value.type()) { case Value::STRING: ParseOneTemplateString(value.string_value()); break; case Value::LIST: for (size_t i = 0; i < value.list_value().size(); i++) { if (!value.list_value()[i].VerifyTypeIs(Value::STRING, err)) return; ParseOneTemplateString(value.list_value()[i].string_value()); } break; default: *err = Err(value, "File template must be a string or list.", "A sarcastic comment about your skills goes here."); } } void FileTemplate::ParseOneTemplateString(const std::string& str) { templates_.container().resize(templates_.container().size() + 1); Template& t = templates_[templates_.container().size() - 1]; size_t cur = 0; while (true) { size_t next = str.find("{{", cur); // Pick up everything from the previous spot to here as a literal. if (next == std::string::npos) { if (cur != str.size()) t.container().push_back(Subrange(Subrange::LITERAL, str.substr(cur))); break; } else if (next > cur) { t.container().push_back( Subrange(Subrange::LITERAL, str.substr(cur, next - cur))); } // Decode the template param. if (str.compare(next, arraysize(kSource) - 1, kSource) == 0) { t.container().push_back(Subrange(Subrange::SOURCE)); types_required_[Subrange::SOURCE] = true; has_substitutions_ = true; cur = next + arraysize(kSource) - 1; } else if (str.compare(next, arraysize(kSourceNamePart) - 1, kSourceNamePart) == 0) { t.container().push_back(Subrange(Subrange::NAME_PART)); types_required_[Subrange::NAME_PART] = true; has_substitutions_ = true; cur = next + arraysize(kSourceNamePart) - 1; } else if (str.compare(next, arraysize(kSourceFilePart) - 1, kSourceFilePart) == 0) { t.container().push_back(Subrange(Subrange::FILE_PART)); types_required_[Subrange::FILE_PART] = true; has_substitutions_ = true; cur = next + arraysize(kSourceFilePart) - 1; } else { // If it's not a match, treat it like a one-char literal (this will be // rare, so it's not worth the bother to add to the previous literal) so // we can keep going. t.container().push_back(Subrange(Subrange::LITERAL, "{")); cur = next + 1; } } }
{ "content_hash": "69d3b8f6a54fb0e547b9651821f11808", "timestamp": "", "source": "github", "line_count": 281, "max_line_length": 80, "avg_line_length": 37.42348754448398, "alnum_prop": 0.6112590338531761, "repo_name": "mogoweb/chromium-crosswalk", "id": "1616c52b9d3ff7aa8bfc6465dd7646463fc6aacd", "size": "10834", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tools/gn/file_template.cc", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ASP", "bytes": "853" }, { "name": "AppleScript", "bytes": "6973" }, { "name": "Arduino", "bytes": "464" }, { "name": "Assembly", "bytes": "54831" }, { "name": "Awk", "bytes": "8660" }, { "name": "C", "bytes": "40940503" }, { "name": "C#", "bytes": "1132" }, { "name": "C++", "bytes": "182703853" }, { "name": "CSS", "bytes": "799795" }, { "name": "DOT", "bytes": "1873" }, { "name": "Java", "bytes": "4807735" }, { "name": "JavaScript", "bytes": "20714038" }, { "name": "Mercury", "bytes": "10299" }, { "name": "Objective-C", "bytes": "985558" }, { "name": "Objective-C++", "bytes": "6205987" }, { "name": "PHP", "bytes": "97817" }, { "name": "Perl", "bytes": "1213389" }, { "name": "Python", "bytes": "9735121" }, { "name": "Rebol", "bytes": "262" }, { "name": "Shell", "bytes": "1305641" }, { "name": "Tcl", "bytes": "277091" }, { "name": "TypeScript", "bytes": "1560024" }, { "name": "XSLT", "bytes": "13493" }, { "name": "nesC", "bytes": "14650" } ], "symlink_target": "" }
package com.comcast.cim.rest.client.xhtml; import static org.junit.Assert.*; import static org.easymock.classextension.EasyMock.*; import java.net.URL; import java.util.HashMap; import java.util.Map; import junit.framework.Assert; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.HttpVersion; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.message.BasicHttpResponse; import org.jdom.Document; import org.jdom.Element; import org.junit.Before; import org.junit.Test; import com.comcast.cim.rest.client.xhtml.RequestBuilder; import com.comcast.cim.rest.client.xhtml.XhtmlApplicationState; import com.comcast.cim.rest.client.xhtml.XhtmlHttpClient; import com.comcast.cim.rest.client.xhtml.XhtmlNavigator; import com.comcast.cim.rest.client.xhtml.XhtmlParser; public class TestXhtmlNavigator { private XhtmlParser mockParser; private RequestBuilder mockBuilder; private XhtmlHttpClient mockClient; private XhtmlNavigator impl; private Document doc; private URL context; private XhtmlApplicationState initState; private XhtmlApplicationState newState; private HttpResponse success; @Before public void setUp() throws Exception { mockParser = createMock(XhtmlParser.class); mockBuilder = createMock(RequestBuilder.class); mockClient = createMock(XhtmlHttpClient.class); impl = new XhtmlNavigator(mockParser, mockBuilder, mockClient); doc = new Document(); context = new URL("http://foo.example.com/"); initState = new XhtmlApplicationState(context, null, doc); success = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); newState = new XhtmlApplicationState(null, success, null); } private void replayMocks() { replay(mockParser); replay(mockBuilder); replay(mockClient); } private void verifyMocks() { verify(mockParser); verify(mockBuilder); verify(mockClient); } @Test public void testCanFollowLink() throws Exception { String rel = "relation"; Element a = new Element("a"); expect(mockParser.getLinkWithRelation(doc, rel)) .andReturn(a); HttpGet req = new HttpGet("http://foo.example.com/"); expect(mockBuilder.followLink(a, context)) .andReturn(req); expect(mockClient.execute(req)) .andReturn(newState); replayMocks(); XhtmlApplicationState result = impl.followLink(initState, rel); verifyMocks(); assertSame(newState, result); } @Test public void testCanFollowLinkFromSpecificRoot() throws Exception { String rel = "relation"; Element outer = new Element("div", XhtmlParser.XHTML_NS); Element wrong = new Element("a", XhtmlParser.XHTML_NS); wrong.setAttribute("rel",rel); wrong.setAttribute("href","/bad"); wrong.setText("Bad Link"); outer.addContent(wrong); Element inner = new Element("div", XhtmlParser.XHTML_NS); Element right = new Element("a", XhtmlParser.XHTML_NS); right.setAttribute("rel",rel); right.setAttribute("href","/good"); right.setText("Good Link"); inner.addContent(right); outer.addContent(inner); expect(mockParser.getLinkWithRelation(inner, rel)) .andReturn(right); HttpGet req = new HttpGet("http://foo.example.com/"); expect(mockBuilder.followLink(right, context)) .andReturn(req); expect(mockClient.execute(req)) .andReturn(newState); replayMocks(); XhtmlApplicationState result = impl.followLink(initState, inner, rel); verifyMocks(); assertSame(newState, result); } @Test public void testThrowsRelationNotFoundExceptionIfLinkNotPresent() throws Exception { String rel = "relation"; expect(mockParser.getLinkWithRelation(doc, rel)) .andReturn(null); replayMocks(); try { impl.followLink(initState, rel); Assert.fail("should have thrown exception"); } catch (RelationNotFoundException expected) { } verifyMocks(); } @Test public void testCanSubmitForm() throws Exception { String name = "formName"; Element form = new Element("form"); expect(mockParser.getFormWithName(doc, name)) .andReturn(form); HttpPost req = new HttpPost("http://foo.example.com/"); Map<String,String> args = new HashMap<String, String>(); expect(mockBuilder.submitForm(form, context, args)) .andReturn(req); expect(mockClient.execute(req)) .andReturn(newState); replayMocks(); XhtmlApplicationState result = impl.submitForm(initState, name, args); verifyMocks(); assertSame(newState, result); } @Test public void testThrowsRelationNotFoundExceptionIfFormNotPresent() throws Exception { String formName = "formName"; expect(mockParser.getFormWithName(doc, formName)) .andReturn(null); replayMocks(); try { impl.submitForm(initState, formName, null); fail("should have thrown exception"); } catch (RelationNotFoundException expected) { } verifyMocks(); } }
{ "content_hash": "dbc3b4750f9c5592d9c3beda9299b559", "timestamp": "", "source": "github", "line_count": 166, "max_line_length": 85, "avg_line_length": 29.234939759036145, "alnum_prop": 0.7455182361425922, "repo_name": "jvelilla/hypermedia-client-java", "id": "b6c34913e54f21dc9d4b9446e5828dee4a156166", "size": "5477", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/test/java/com/comcast/cim/rest/client/xhtml/TestXhtmlNavigator.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
#include "server.h" #include <sys/uio.h> #include <math.h> static void setProtocolError(client *c, int pos); /* Return the size consumed from the allocator, for the specified SDS string, * including internal fragmentation. This function is used in order to compute * the client output buffer size. */ size_t sdsZmallocSize(sds s) { void *sh = sdsAllocPtr(s); return zmalloc_size(sh); } /* Return the amount of memory used by the sds string at object->ptr * for a string object. */ size_t getStringObjectSdsUsedMemory(robj *o) { serverAssertWithInfo(NULL,o,o->type == OBJ_STRING); switch(o->encoding) { case OBJ_ENCODING_RAW: return sdsZmallocSize(o->ptr); case OBJ_ENCODING_EMBSTR: return zmalloc_size(o)-sizeof(robj); default: return 0; /* Just integer encoding for now. */ } } void *dupClientReplyValue(void *o) { incrRefCount((robj*)o); return o; } int listMatchObjects(void *a, void *b) { return equalStringObjects(a,b); } client *createClient(int fd) { client *c = zmalloc(sizeof(client)); /* passing -1 as fd it is possible to create a non connected client. * This is useful since all the commands needs to be executed * in the context of a client. When commands are executed in other * contexts (for instance a Lua script) we need a non connected client. */ if (fd != -1) { anetNonBlock(NULL,fd); anetEnableTcpNoDelay(NULL,fd); if (server.tcpkeepalive) anetKeepAlive(NULL,fd,server.tcpkeepalive); if (aeCreateFileEvent(server.el,fd,AE_READABLE, readQueryFromClient, c) == AE_ERR) { close(fd); zfree(c); return NULL; } } selectDb(c,0); c->id = server.next_client_id++; c->fd = fd; c->name = NULL; c->bufpos = 0; c->querybuf = sdsempty(); c->querybuf_peak = 0; c->reqtype = 0; c->argc = 0; c->argv = NULL; c->cmd = c->lastcmd = NULL; c->multibulklen = 0; c->bulklen = -1; c->sentlen = 0; c->flags = 0; c->ctime = c->lastinteraction = server.unixtime; c->authenticated = 0; c->replstate = REPL_STATE_NONE; c->repl_put_online_on_ack = 0; c->reploff = 0; c->repl_ack_off = 0; c->repl_ack_time = 0; c->slave_listening_port = 0; c->slave_ip[0] = '\0'; c->slave_capa = SLAVE_CAPA_NONE; c->reply = listCreate(); c->reply_bytes = 0; c->obuf_soft_limit_reached_time = 0; listSetFreeMethod(c->reply,decrRefCountVoid); listSetDupMethod(c->reply,dupClientReplyValue); c->btype = BLOCKED_NONE; c->bpop.timeout = 0; c->bpop.keys = dictCreate(&setDictType,NULL); c->bpop.target = NULL; c->bpop.numreplicas = 0; c->bpop.reploffset = 0; c->woff = 0; c->watched_keys = listCreate(); c->pubsub_channels = dictCreate(&setDictType,NULL); c->pubsub_patterns = listCreate(); c->peerid = NULL; listSetFreeMethod(c->pubsub_patterns,decrRefCountVoid); listSetMatchMethod(c->pubsub_patterns,listMatchObjects); if (fd != -1) listAddNodeTail(server.clients,c); initClientMultiState(c); #ifdef NBASE_ARC arc_smrc_create(c); #endif return c; } /* This function is called every time we are going to transmit new data * to the client. The behavior is the following: * * If the client should receive new data (normal clients will) the function * returns C_OK, and make sure to install the write handler in our event * loop so that when the socket is writable new data gets written. * * If the client should not receive new data, because it is a fake client * (used to load AOF in memory), a master or because the setup of the write * handler failed, the function returns C_ERR. * * The function may return C_OK without actually installing the write * event handler in the following cases: * * 1) The event handler should already be installed since the output buffer * already contained something. * 2) The client is a slave but not yet online, so we want to just accumulate * writes in the buffer but not actually sending them yet. * * Typically gets called every time a reply is built, before adding more * data to the clients output buffers. If the function returns C_ERR no * data should be appended to the output buffers. */ int prepareClientToWrite(client *c) { /* If it's the Lua client we always return ok without installing any * handler since there is no socket at all. */ if (c->flags & CLIENT_LUA) return C_OK; /* CLIENT REPLY OFF / SKIP handling: don't send replies. */ if (c->flags & (CLIENT_REPLY_OFF|CLIENT_REPLY_SKIP)) return C_ERR; /* Masters don't receive replies, unless CLIENT_MASTER_FORCE_REPLY flag * is set. */ if ((c->flags & CLIENT_MASTER) && !(c->flags & CLIENT_MASTER_FORCE_REPLY)) return C_ERR; if (c->fd <= 0) return C_ERR; /* Fake client for AOF loading. */ /* Schedule the client to write the output buffers to the socket only * if not already done (there were no pending writes already and the client * was yet not flagged), and, for slaves, if the slave can actually * receive writes at this stage. */ if (!clientHasPendingReplies(c) && !(c->flags & CLIENT_PENDING_WRITE) && (c->replstate == REPL_STATE_NONE || (c->replstate == SLAVE_STATE_ONLINE && !c->repl_put_online_on_ack))) { /* Here instead of installing the write handler, we just flag the * client and put it into a list of clients that have something * to write to the socket. This way before re-entering the event * loop, we can try to directly write to the client sockets avoiding * a system call. We'll only really install the write handler if * we'll not be able to write the whole reply at once. */ c->flags |= CLIENT_PENDING_WRITE; listAddNodeHead(server.clients_pending_write,c); } /* Authorize the caller to queue in the output buffer of this client. */ return C_OK; } /* Create a duplicate of the last object in the reply list when * it is not exclusively owned by the reply list. */ robj *dupLastObjectIfNeeded(list *reply) { robj *new, *cur; listNode *ln; serverAssert(listLength(reply) > 0); ln = listLast(reply); cur = listNodeValue(ln); if (cur->refcount > 1) { new = dupStringObject(cur); decrRefCount(cur); listNodeValue(ln) = new; } return listNodeValue(ln); } /* ----------------------------------------------------------------------------- * Low level functions to add more data to output buffers. * -------------------------------------------------------------------------- */ int _addReplyToBuffer(client *c, const char *s, size_t len) { size_t available = sizeof(c->buf)-c->bufpos; if (c->flags & CLIENT_CLOSE_AFTER_REPLY) return C_OK; /* If there already are entries in the reply list, we cannot * add anything more to the static buffer. */ if (listLength(c->reply) > 0) return C_ERR; /* Check that the buffer has enough space available for this string. */ if (len > available) return C_ERR; memcpy(c->buf+c->bufpos,s,len); c->bufpos+=len; return C_OK; } void _addReplyObjectToList(client *c, robj *o) { robj *tail; if (c->flags & CLIENT_CLOSE_AFTER_REPLY) return; if (listLength(c->reply) == 0) { incrRefCount(o); listAddNodeTail(c->reply,o); c->reply_bytes += getStringObjectSdsUsedMemory(o); } else { tail = listNodeValue(listLast(c->reply)); /* Append to this object when possible. */ if (tail->ptr != NULL && tail->encoding == OBJ_ENCODING_RAW && sdslen(tail->ptr)+sdslen(o->ptr) <= PROTO_REPLY_CHUNK_BYTES) { c->reply_bytes -= sdsZmallocSize(tail->ptr); tail = dupLastObjectIfNeeded(c->reply); tail->ptr = sdscatlen(tail->ptr,o->ptr,sdslen(o->ptr)); c->reply_bytes += sdsZmallocSize(tail->ptr); } else { incrRefCount(o); listAddNodeTail(c->reply,o); c->reply_bytes += getStringObjectSdsUsedMemory(o); } } asyncCloseClientOnOutputBufferLimitReached(c); } /* This method takes responsibility over the sds. When it is no longer * needed it will be free'd, otherwise it ends up in a robj. */ void _addReplySdsToList(client *c, sds s) { robj *tail; if (c->flags & CLIENT_CLOSE_AFTER_REPLY) { sdsfree(s); return; } if (listLength(c->reply) == 0) { listAddNodeTail(c->reply,createObject(OBJ_STRING,s)); c->reply_bytes += sdsZmallocSize(s); } else { tail = listNodeValue(listLast(c->reply)); /* Append to this object when possible. */ if (tail->ptr != NULL && tail->encoding == OBJ_ENCODING_RAW && sdslen(tail->ptr)+sdslen(s) <= PROTO_REPLY_CHUNK_BYTES) { c->reply_bytes -= sdsZmallocSize(tail->ptr); tail = dupLastObjectIfNeeded(c->reply); tail->ptr = sdscatlen(tail->ptr,s,sdslen(s)); c->reply_bytes += sdsZmallocSize(tail->ptr); sdsfree(s); } else { listAddNodeTail(c->reply,createObject(OBJ_STRING,s)); c->reply_bytes += sdsZmallocSize(s); } } asyncCloseClientOnOutputBufferLimitReached(c); } void _addReplyStringToList(client *c, const char *s, size_t len) { robj *tail; if (c->flags & CLIENT_CLOSE_AFTER_REPLY) return; if (listLength(c->reply) == 0) { robj *o = createStringObject(s,len); listAddNodeTail(c->reply,o); c->reply_bytes += getStringObjectSdsUsedMemory(o); } else { tail = listNodeValue(listLast(c->reply)); /* Append to this object when possible. */ if (tail->ptr != NULL && tail->encoding == OBJ_ENCODING_RAW && sdslen(tail->ptr)+len <= PROTO_REPLY_CHUNK_BYTES) { c->reply_bytes -= sdsZmallocSize(tail->ptr); tail = dupLastObjectIfNeeded(c->reply); tail->ptr = sdscatlen(tail->ptr,s,len); c->reply_bytes += sdsZmallocSize(tail->ptr); } else { robj *o = createStringObject(s,len); listAddNodeTail(c->reply,o); c->reply_bytes += getStringObjectSdsUsedMemory(o); } } asyncCloseClientOnOutputBufferLimitReached(c); } /* ----------------------------------------------------------------------------- * Higher level functions to queue data on the client output buffer. * The following functions are the ones that commands implementations will call. * -------------------------------------------------------------------------- */ void addReply(client *c, robj *obj) { if (prepareClientToWrite(c) != C_OK) return; /* This is an important place where we can avoid copy-on-write * when there is a saving child running, avoiding touching the * refcount field of the object if it's not needed. * * If the encoding is RAW and there is room in the static buffer * we'll be able to send the object to the client without * messing with its page. */ if (sdsEncodedObject(obj)) { if (_addReplyToBuffer(c,obj->ptr,sdslen(obj->ptr)) != C_OK) _addReplyObjectToList(c,obj); } else if (obj->encoding == OBJ_ENCODING_INT) { /* Optimization: if there is room in the static buffer for 32 bytes * (more than the max chars a 64 bit integer can take as string) we * avoid decoding the object and go for the lower level approach. */ if (listLength(c->reply) == 0 && (sizeof(c->buf) - c->bufpos) >= 32) { char buf[32]; int len; len = ll2string(buf,sizeof(buf),(long)obj->ptr); if (_addReplyToBuffer(c,buf,len) == C_OK) return; /* else... continue with the normal code path, but should never * happen actually since we verified there is room. */ } obj = getDecodedObject(obj); if (_addReplyToBuffer(c,obj->ptr,sdslen(obj->ptr)) != C_OK) _addReplyObjectToList(c,obj); decrRefCount(obj); } else { serverPanic("Wrong obj->encoding in addReply()"); } } void addReplySds(client *c, sds s) { if (prepareClientToWrite(c) != C_OK) { /* The caller expects the sds to be free'd. */ sdsfree(s); return; } if (_addReplyToBuffer(c,s,sdslen(s)) == C_OK) { sdsfree(s); } else { /* This method free's the sds when it is no longer needed. */ _addReplySdsToList(c,s); } } void addReplyString(client *c, const char *s, size_t len) { if (prepareClientToWrite(c) != C_OK) return; if (_addReplyToBuffer(c,s,len) != C_OK) _addReplyStringToList(c,s,len); } void addReplyErrorLength(client *c, const char *s, size_t len) { addReplyString(c,"-ERR ",5); addReplyString(c,s,len); addReplyString(c,"\r\n",2); } void addReplyError(client *c, const char *err) { addReplyErrorLength(c,err,strlen(err)); } void addReplyErrorFormat(client *c, const char *fmt, ...) { size_t l, j; va_list ap; va_start(ap,fmt); sds s = sdscatvprintf(sdsempty(),fmt,ap); va_end(ap); /* Make sure there are no newlines in the string, otherwise invalid protocol * is emitted. */ l = sdslen(s); for (j = 0; j < l; j++) { if (s[j] == '\r' || s[j] == '\n') s[j] = ' '; } addReplyErrorLength(c,s,sdslen(s)); sdsfree(s); } void addReplyStatusLength(client *c, const char *s, size_t len) { addReplyString(c,"+",1); addReplyString(c,s,len); addReplyString(c,"\r\n",2); } void addReplyStatus(client *c, const char *status) { addReplyStatusLength(c,status,strlen(status)); } void addReplyStatusFormat(client *c, const char *fmt, ...) { va_list ap; va_start(ap,fmt); sds s = sdscatvprintf(sdsempty(),fmt,ap); va_end(ap); addReplyStatusLength(c,s,sdslen(s)); sdsfree(s); } /* Adds an empty object to the reply list that will contain the multi bulk * length, which is not known when this function is called. */ void *addDeferredMultiBulkLength(client *c) { /* Note that we install the write event here even if the object is not * ready to be sent, since we are sure that before returning to the * event loop setDeferredMultiBulkLength() will be called. */ if (prepareClientToWrite(c) != C_OK) return NULL; listAddNodeTail(c->reply,createObject(OBJ_STRING,NULL)); return listLast(c->reply); } /* Populate the length object and try gluing it to the next chunk. */ void setDeferredMultiBulkLength(client *c, void *node, long length) { listNode *ln = (listNode*)node; robj *len, *next; /* Abort when *node is NULL (see addDeferredMultiBulkLength). */ if (node == NULL) return; len = listNodeValue(ln); len->ptr = sdscatprintf(sdsempty(),"*%ld\r\n",length); len->encoding = OBJ_ENCODING_RAW; /* in case it was an EMBSTR. */ c->reply_bytes += sdsZmallocSize(len->ptr); if (ln->next != NULL) { next = listNodeValue(ln->next); /* Only glue when the next node is non-NULL (an sds in this case) */ if (next->ptr != NULL) { c->reply_bytes -= sdsZmallocSize(len->ptr); c->reply_bytes -= getStringObjectSdsUsedMemory(next); len->ptr = sdscatlen(len->ptr,next->ptr,sdslen(next->ptr)); c->reply_bytes += sdsZmallocSize(len->ptr); listDelNode(c->reply,ln->next); } } asyncCloseClientOnOutputBufferLimitReached(c); } /* Add a double as a bulk reply */ void addReplyDouble(client *c, double d) { char dbuf[128], sbuf[128]; int dlen, slen; if (isinf(d)) { /* Libc in odd systems (Hi Solaris!) will format infinite in a * different way, so better to handle it in an explicit way. */ addReplyBulkCString(c, d > 0 ? "inf" : "-inf"); } else { dlen = snprintf(dbuf,sizeof(dbuf),"%.17g",d); slen = snprintf(sbuf,sizeof(sbuf),"$%d\r\n%s\r\n",dlen,dbuf); addReplyString(c,sbuf,slen); } } /* Add a long double as a bulk reply, but uses a human readable formatting * of the double instead of exposing the crude behavior of doubles to the * dear user. */ void addReplyHumanLongDouble(client *c, long double d) { robj *o = createStringObjectFromLongDouble(d,1); addReplyBulk(c,o); decrRefCount(o); } /* Add a long long as integer reply or bulk len / multi bulk count. * Basically this is used to output <prefix><long long><crlf>. */ void addReplyLongLongWithPrefix(client *c, long long ll, char prefix) { char buf[128]; int len; /* Things like $3\r\n or *2\r\n are emitted very often by the protocol * so we have a few shared objects to use if the integer is small * like it is most of the times. */ if (prefix == '*' && ll < OBJ_SHARED_BULKHDR_LEN && ll >= 0) { addReply(c,shared.mbulkhdr[ll]); return; } else if (prefix == '$' && ll < OBJ_SHARED_BULKHDR_LEN && ll >= 0) { addReply(c,shared.bulkhdr[ll]); return; } buf[0] = prefix; len = ll2string(buf+1,sizeof(buf)-1,ll); buf[len+1] = '\r'; buf[len+2] = '\n'; addReplyString(c,buf,len+3); } void addReplyLongLong(client *c, long long ll) { if (ll == 0) addReply(c,shared.czero); else if (ll == 1) addReply(c,shared.cone); else addReplyLongLongWithPrefix(c,ll,':'); } void addReplyMultiBulkLen(client *c, long length) { if (length < OBJ_SHARED_BULKHDR_LEN) addReply(c,shared.mbulkhdr[length]); else addReplyLongLongWithPrefix(c,length,'*'); } /* Create the length prefix of a bulk reply, example: $2234 */ void addReplyBulkLen(client *c, robj *obj) { size_t len; if (sdsEncodedObject(obj)) { len = sdslen(obj->ptr); } else { long n = (long)obj->ptr; /* Compute how many bytes will take this integer as a radix 10 string */ len = 1; if (n < 0) { len++; n = -n; } while((n = n/10) != 0) { len++; } } if (len < OBJ_SHARED_BULKHDR_LEN) addReply(c,shared.bulkhdr[len]); else addReplyLongLongWithPrefix(c,len,'$'); } /* Add a Redis Object as a bulk reply */ void addReplyBulk(client *c, robj *obj) { addReplyBulkLen(c,obj); addReply(c,obj); addReply(c,shared.crlf); } /* Add a C buffer as bulk reply */ void addReplyBulkCBuffer(client *c, const void *p, size_t len) { addReplyLongLongWithPrefix(c,len,'$'); addReplyString(c,p,len); addReply(c,shared.crlf); } /* Add sds to reply (takes ownership of sds and frees it) */ void addReplyBulkSds(client *c, sds s) { addReplySds(c,sdscatfmt(sdsempty(),"$%u\r\n", (unsigned long)sdslen(s))); addReplySds(c,s); addReply(c,shared.crlf); } /* Add a C nul term string as bulk reply */ void addReplyBulkCString(client *c, const char *s) { if (s == NULL) { addReply(c,shared.nullbulk); } else { addReplyBulkCBuffer(c,s,strlen(s)); } } /* Add a long long as a bulk reply */ void addReplyBulkLongLong(client *c, long long ll) { char buf[64]; int len; len = ll2string(buf,64,ll); addReplyBulkCBuffer(c,buf,len); } /* Copy 'src' client output buffers into 'dst' client output buffers. * The function takes care of freeing the old output buffers of the * destination client. */ void copyClientOutputBuffer(client *dst, client *src) { listRelease(dst->reply); dst->reply = listDup(src->reply); memcpy(dst->buf,src->buf,src->bufpos); dst->bufpos = src->bufpos; dst->reply_bytes = src->reply_bytes; } /* Return true if the specified client has pending reply buffers to write to * the socket. */ int clientHasPendingReplies(client *c) { return c->bufpos || listLength(c->reply); } #define MAX_ACCEPTS_PER_CALL 1000 static void acceptCommonHandler(int fd, int flags, char *ip) { client *c; if ((c = createClient(fd)) == NULL) { serverLog(LL_WARNING, "Error registering fd event for the new client: %s (fd=%d)", strerror(errno),fd); close(fd); /* May be already closed, just ignore errors */ return; } /* If maxclient directive is set and this is one client more... close the * connection. Note that we create the client instead to check before * for this condition, since now the socket is already set in non-blocking * mode and we can send an error for free using the Kernel I/O */ if (listLength(server.clients) > server.maxclients) { char *err = "-ERR max number of clients reached\r\n"; /* That's a best effort error message, don't check write errors */ if (write(c->fd,err,strlen(err)) == -1) { /* Nothing to do, Just to avoid the warning... */ } server.stat_rejected_conn++; freeClient(c); return; } /* If the server is running in protected mode (the default) and there * is no password set, nor a specific interface is bound, we don't accept * requests from non loopback interfaces. Instead we try to explain the * user what to do to fix it if needed. */ if (server.protected_mode && #ifdef NBASE_ARC !arc.cluster_mode && #endif server.bindaddr_count == 0 && server.requirepass == NULL && !(flags & CLIENT_UNIX_SOCKET) && ip != NULL) { if (strcmp(ip,"127.0.0.1") && strcmp(ip,"::1")) { char *err = "-DENIED Redis is running in protected mode because protected " "mode is enabled, no bind address was specified, no " "authentication password is requested to clients. In this mode " "connections are only accepted from the loopback interface. " "If you want to connect from external computers to Redis you " "may adopt one of the following solutions: " "1) Just disable protected mode sending the command " "'CONFIG SET protected-mode no' from the loopback interface " "by connecting to Redis from the same host the server is " "running, however MAKE SURE Redis is not publicly accessible " "from internet if you do so. Use CONFIG REWRITE to make this " "change permanent. " "2) Alternatively you can just disable the protected mode by " "editing the Redis configuration file, and setting the protected " "mode option to 'no', and then restarting the server. " "3) If you started the server manually just for testing, restart " "it with the '--protected-mode no' option. " "4) Setup a bind address or an authentication password. " "NOTE: You only need to do one of the above things in order for " "the server to start accepting connections from the outside.\r\n"; if (write(c->fd,err,strlen(err)) == -1) { /* Nothing to do, Just to avoid the warning... */ } server.stat_rejected_conn++; freeClient(c); return; } } server.stat_numconnections++; c->flags |= flags; #ifdef NBASE_ARC arc_smrc_accept_bh(c); #endif } void acceptTcpHandler(aeEventLoop *el, int fd, void *privdata, int mask) { int cport, cfd, max = MAX_ACCEPTS_PER_CALL; char cip[NET_IP_STR_LEN]; UNUSED(el); UNUSED(mask); UNUSED(privdata); while(max--) { cfd = anetTcpAccept(server.neterr, fd, cip, sizeof(cip), &cport); if (cfd == ANET_ERR) { if (errno != EWOULDBLOCK) serverLog(LL_WARNING, "Accepting client connection: %s", server.neterr); return; } serverLog(LL_VERBOSE,"Accepted %s:%d", cip, cport); acceptCommonHandler(cfd,0,cip); } } void acceptUnixHandler(aeEventLoop *el, int fd, void *privdata, int mask) { int cfd, max = MAX_ACCEPTS_PER_CALL; UNUSED(el); UNUSED(mask); UNUSED(privdata); while(max--) { cfd = anetUnixAccept(server.neterr, fd); if (cfd == ANET_ERR) { if (errno != EWOULDBLOCK) serverLog(LL_WARNING, "Accepting client connection: %s", server.neterr); return; } serverLog(LL_VERBOSE,"Accepted connection to %s", server.unixsocket); acceptCommonHandler(cfd,CLIENT_UNIX_SOCKET,NULL); } } static void freeClientArgv(client *c) { int j; for (j = 0; j < c->argc; j++) decrRefCount(c->argv[j]); c->argc = 0; c->cmd = NULL; } /* Close all the slaves connections. This is useful in chained replication * when we resync with our own master and want to force all our slaves to * resync with us as well. */ void disconnectSlaves(void) { while (listLength(server.slaves)) { listNode *ln = listFirst(server.slaves); freeClient((client*)ln->value); } } /* Remove the specified client from global lists where the client could * be referenced, not including the Pub/Sub channels. * This is used by freeClient() and replicationCacheMaster(). */ void unlinkClient(client *c) { listNode *ln; /* If this is marked as current client unset it. */ if (server.current_client == c) server.current_client = NULL; /* Certain operations must be done only if the client has an active socket. * If the client was already unlinked or if it's a "fake client" the * fd is already set to -1. */ if (c->fd != -1) { /* Remove from the list of active clients. */ ln = listSearchKey(server.clients,c); serverAssert(ln != NULL); listDelNode(server.clients,ln); /* Unregister async I/O handlers and close the socket. */ aeDeleteFileEvent(server.el,c->fd,AE_READABLE); aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE); close(c->fd); c->fd = -1; } /* Remove from the list of pending writes if needed. */ if (c->flags & CLIENT_PENDING_WRITE) { ln = listSearchKey(server.clients_pending_write,c); serverAssert(ln != NULL); listDelNode(server.clients_pending_write,ln); c->flags &= ~CLIENT_PENDING_WRITE; } /* When client was just unblocked because of a blocking operation, * remove it from the list of unblocked clients. */ if (c->flags & CLIENT_UNBLOCKED) { ln = listSearchKey(server.unblocked_clients,c); serverAssert(ln != NULL); listDelNode(server.unblocked_clients,ln); c->flags &= ~CLIENT_UNBLOCKED; } } void freeClient(client *c) { listNode *ln; /* If it is our master that's beging disconnected we should make sure * to cache the state to try a partial resynchronization later. * * Note that before doing this we make sure that the client is not in * some unexpected state, by checking its flags. */ if (server.master && c->flags & CLIENT_MASTER) { serverLog(LL_WARNING,"Connection with master lost."); if (!(c->flags & (CLIENT_CLOSE_AFTER_REPLY| CLIENT_CLOSE_ASAP| CLIENT_BLOCKED| CLIENT_UNBLOCKED))) { replicationCacheMaster(c); return; } } /* Log link disconnection with slave */ if ((c->flags & CLIENT_SLAVE) && !(c->flags & CLIENT_MONITOR)) { serverLog(LL_WARNING,"Connection with slave %s lost.", replicationGetSlaveName(c)); } /* Free the query buffer */ sdsfree(c->querybuf); c->querybuf = NULL; /* Deallocate structures used to block on blocking ops. */ if (c->flags & CLIENT_BLOCKED) unblockClient(c); dictRelease(c->bpop.keys); /* UNWATCH all the keys */ unwatchAllKeys(c); listRelease(c->watched_keys); /* Unsubscribe from all the pubsub channels */ pubsubUnsubscribeAllChannels(c,0); pubsubUnsubscribeAllPatterns(c,0); dictRelease(c->pubsub_channels); listRelease(c->pubsub_patterns); /* Free data structures. */ listRelease(c->reply); freeClientArgv(c); /* Unlink the client: this will close the socket, remove the I/O * handlers, and remove references of the client from different * places where active clients may be referenced. */ unlinkClient(c); /* Master/slave cleanup Case 1: * we lost the connection with a slave. */ if (c->flags & CLIENT_SLAVE) { if (c->replstate == SLAVE_STATE_SEND_BULK) { if (c->repldbfd != -1) close(c->repldbfd); if (c->replpreamble) sdsfree(c->replpreamble); } list *l = (c->flags & CLIENT_MONITOR) ? server.monitors : server.slaves; ln = listSearchKey(l,c); serverAssert(ln != NULL); listDelNode(l,ln); /* We need to remember the time when we started to have zero * attached slaves, as after some time we'll free the replication * backlog. */ if (c->flags & CLIENT_SLAVE && listLength(server.slaves) == 0) server.repl_no_slaves_since = server.unixtime; refreshGoodSlavesCount(); } /* Master/slave cleanup Case 2: * we lost the connection with the master. */ if (c->flags & CLIENT_MASTER) replicationHandleMasterDisconnection(); /* If this client was scheduled for async freeing we need to remove it * from the queue. */ if (c->flags & CLIENT_CLOSE_ASAP) { ln = listSearchKey(server.clients_to_close,c); serverAssert(ln != NULL); listDelNode(server.clients_to_close,ln); } /* Release other dynamically allocated client structure fields, * and finally release the client structure itself. */ if (c->name) decrRefCount(c->name); zfree(c->argv); freeClientMultiState(c); sdsfree(c->peerid); #ifdef NBASE_ARC arc_smrc_free(c); #endif zfree(c); } /* Schedule a client to free it at a safe time in the serverCron() function. * This function is useful when we need to terminate a client but we are in * a context where calling freeClient() is not possible, because the client * should be valid for the continuation of the flow of the program. */ void freeClientAsync(client *c) { if (c->flags & CLIENT_CLOSE_ASAP || c->flags & CLIENT_LUA) return; c->flags |= CLIENT_CLOSE_ASAP; listAddNodeTail(server.clients_to_close,c); } void freeClientsInAsyncFreeQueue(void) { while (listLength(server.clients_to_close)) { listNode *ln = listFirst(server.clients_to_close); client *c = listNodeValue(ln); c->flags &= ~CLIENT_CLOSE_ASAP; freeClient(c); listDelNode(server.clients_to_close,ln); } } /* Write data in output buffers to client. Return C_OK if the client * is still valid after the call, C_ERR if it was freed. */ int writeToClient(int fd, client *c, int handler_installed) { ssize_t nwritten = 0, totwritten = 0; size_t objlen; size_t objmem; robj *o; while(clientHasPendingReplies(c)) { if (c->bufpos > 0) { nwritten = write(fd,c->buf+c->sentlen,c->bufpos-c->sentlen); if (nwritten <= 0) break; c->sentlen += nwritten; totwritten += nwritten; /* If the buffer was sent, set bufpos to zero to continue with * the remainder of the reply. */ if ((int)c->sentlen == c->bufpos) { c->bufpos = 0; c->sentlen = 0; } } else { o = listNodeValue(listFirst(c->reply)); objlen = sdslen(o->ptr); objmem = getStringObjectSdsUsedMemory(o); if (objlen == 0) { listDelNode(c->reply,listFirst(c->reply)); c->reply_bytes -= objmem; continue; } nwritten = write(fd, ((char*)o->ptr)+c->sentlen,objlen-c->sentlen); if (nwritten <= 0) break; c->sentlen += nwritten; totwritten += nwritten; /* If we fully sent the object on head go to the next one */ if (c->sentlen == objlen) { listDelNode(c->reply,listFirst(c->reply)); c->sentlen = 0; c->reply_bytes -= objmem; } } /* Note that we avoid to send more than NET_MAX_WRITES_PER_EVENT * bytes, in a single threaded server it's a good idea to serve * other clients as well, even if a very large request comes from * super fast link that is always able to accept data (in real world * scenario think about 'KEYS *' against the loopback interface). * * However if we are over the maxmemory limit we ignore that and * just deliver as much data as it is possible to deliver. */ if (totwritten > NET_MAX_WRITES_PER_EVENT && (server.maxmemory == 0 || zmalloc_used_memory() < server.maxmemory)) break; } server.stat_net_output_bytes += totwritten; if (nwritten == -1) { if (errno == EAGAIN) { nwritten = 0; } else { serverLog(LL_VERBOSE, "Error writing to client: %s", strerror(errno)); freeClient(c); return C_ERR; } } if (totwritten > 0) { /* For clients representing masters we don't count sending data * as an interaction, since we always send REPLCONF ACK commands * that take some time to just fill the socket output buffer. * We just rely on data / pings received for timeout detection. */ if (!(c->flags & CLIENT_MASTER)) c->lastinteraction = server.unixtime; } if (!clientHasPendingReplies(c)) { c->sentlen = 0; if (handler_installed) aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE); /* Close connection after entire reply has been sent. */ if (c->flags & CLIENT_CLOSE_AFTER_REPLY) { freeClient(c); return C_ERR; } } return C_OK; } /* Write event handler. Just send data to the client. */ void sendReplyToClient(aeEventLoop *el, int fd, void *privdata, int mask) { UNUSED(el); UNUSED(mask); writeToClient(fd,privdata,1); } /* This function is called just before entering the event loop, in the hope * we can just write the replies to the client output buffer without any * need to use a syscall in order to install the writable event handler, * get it called, and so forth. */ int handleClientsWithPendingWrites(void) { listIter li; listNode *ln; int processed = listLength(server.clients_pending_write); listRewind(server.clients_pending_write,&li); while((ln = listNext(&li))) { client *c = listNodeValue(ln); c->flags &= ~CLIENT_PENDING_WRITE; listDelNode(server.clients_pending_write,ln); /* Try to write buffers to the client socket. */ if (writeToClient(c->fd,c,0) == C_ERR) continue; /* If after the synchronous writes above we still have data to * output to the client, we need to install the writable handler. */ if (clientHasPendingReplies(c)) { int ae_flags = AE_WRITABLE; /* For the fsync=always policy, we want that a given FD is never * served for reading and writing in the same event loop iteration, * so that in the middle of receiving the query, and serving it * to the client, we'll call beforeSleep() that will do the * actual fsync of AOF to disk. AE_BARRIER ensures that. */ if (server.aof_state == AOF_ON && server.aof_fsync == AOF_FSYNC_ALWAYS) { ae_flags |= AE_BARRIER; } if (aeCreateFileEvent(server.el, c->fd, ae_flags, sendReplyToClient, c) == AE_ERR) { freeClientAsync(c); } } } return processed; } /* resetClient prepare the client to process the next command */ void resetClient(client *c) { redisCommandProc *prevcmd = c->cmd ? c->cmd->proc : NULL; freeClientArgv(c); c->reqtype = 0; c->multibulklen = 0; c->bulklen = -1; /* We clear the ASKING flag as well if we are not inside a MULTI, and * if what we just executed is not the ASKING command itself. */ if (!(c->flags & CLIENT_MULTI) && prevcmd != askingCommand) c->flags &= ~CLIENT_ASKING; /* Remove the CLIENT_REPLY_SKIP flag if any so that the reply * to the next command will be sent, but set the flag if the command * we just processed was "CLIENT REPLY SKIP". */ c->flags &= ~CLIENT_REPLY_SKIP; if (c->flags & CLIENT_REPLY_SKIP_NEXT) { c->flags |= CLIENT_REPLY_SKIP; c->flags &= ~CLIENT_REPLY_SKIP_NEXT; } } int processInlineBuffer(client *c) { char *newline; int argc, j; sds *argv, aux; size_t querylen; #ifdef NBASE_ARC int has_cr = 0; #endif /* Search for end of line */ newline = strchr(c->querybuf,'\n'); /* Nothing to do without a \r\n */ if (newline == NULL) { if (sdslen(c->querybuf) > PROTO_INLINE_MAX_SIZE) { addReplyError(c,"Protocol error: too big inline request"); setProtocolError(c,0); } return C_ERR; } /* Handle the \r\n case. */ if (newline && newline != c->querybuf && *(newline-1) == '\r') { newline--; #ifdef NBASE_ARC has_cr = 1; #endif } /* Split the input buffer up to the \r\n */ querylen = newline-(c->querybuf); aux = sdsnewlen(c->querybuf,querylen); argv = sdssplitargs(aux,&argc); sdsfree(aux); if (argv == NULL) { addReplyError(c,"Protocol error: unbalanced quotes in request"); setProtocolError(c,0); return C_ERR; } /* Newline from slaves can be used to refresh the last ACK time. * This is useful for a slave to ping back while loading a big * RDB file. */ if (querylen == 0 && c->flags & CLIENT_SLAVE) c->repl_ack_time = server.unixtime; /* Leave data after the first line of the query in the buffer */ #ifdef NBASE_ARC sdsrange(c->querybuf,querylen+1+has_cr,-1); #else sdsrange(c->querybuf,querylen+2,-1); #endif /* Setup argv array on client structure */ if (argc) { if (c->argv) zfree(c->argv); c->argv = zmalloc(sizeof(robj*)*argc); } /* Create redis objects for all arguments. */ for (c->argc = 0, j = 0; j < argc; j++) { if (sdslen(argv[j])) { c->argv[c->argc] = createObject(OBJ_STRING,argv[j]); c->argc++; } else { sdsfree(argv[j]); } } zfree(argv); return C_OK; } /* Helper function. Trims query buffer to make the function that processes * multi bulk requests idempotent. */ static void setProtocolError(client *c, int pos) { #ifdef NBASE_ARC arc_smrc_set_protocol_error(c); #endif if (server.verbosity <= LL_VERBOSE) { sds client = catClientInfoString(sdsempty(),c); serverLog(LL_VERBOSE, "Protocol error from client: %s", client); sdsfree(client); } c->flags |= CLIENT_CLOSE_AFTER_REPLY; sdsrange(c->querybuf,pos,-1); } int processMultibulkBuffer(client *c) { char *newline = NULL; int pos = 0, ok; long long ll; if (c->multibulklen == 0) { /* The client should have been reset */ serverAssertWithInfo(c,NULL,c->argc == 0); /* Multi bulk length cannot be read without a \r\n */ newline = strchr(c->querybuf,'\r'); if (newline == NULL) { if (sdslen(c->querybuf) > PROTO_INLINE_MAX_SIZE) { addReplyError(c,"Protocol error: too big mbulk count string"); setProtocolError(c,0); } return C_ERR; } /* Buffer should also contain \n */ if (newline-(c->querybuf) > ((signed)sdslen(c->querybuf)-2)) return C_ERR; /* We know for sure there is a whole line since newline != NULL, * so go ahead and find out the multi bulk length. */ serverAssertWithInfo(c,NULL,c->querybuf[0] == '*'); ok = string2ll(c->querybuf+1,newline-(c->querybuf+1),&ll); if (!ok || ll > 1024*1024) { addReplyError(c,"Protocol error: invalid multibulk length"); setProtocolError(c,pos); return C_ERR; } pos = (newline-c->querybuf)+2; if (ll <= 0) { sdsrange(c->querybuf,pos,-1); return C_OK; } c->multibulklen = ll; /* Setup argv array on client structure */ if (c->argv) zfree(c->argv); c->argv = zmalloc(sizeof(robj*)*c->multibulklen); } serverAssertWithInfo(c,NULL,c->multibulklen > 0); while(c->multibulklen) { /* Read bulk length if unknown */ if (c->bulklen == -1) { newline = strchr(c->querybuf+pos,'\r'); if (newline == NULL) { if (sdslen(c->querybuf) > PROTO_INLINE_MAX_SIZE) { addReplyError(c, "Protocol error: too big bulk count string"); setProtocolError(c,0); return C_ERR; } break; } /* Buffer should also contain \n */ if (newline-(c->querybuf) > ((signed)sdslen(c->querybuf)-2)) break; if (c->querybuf[pos] != '$') { addReplyErrorFormat(c, "Protocol error: expected '$', got '%c'", c->querybuf[pos]); setProtocolError(c,pos); return C_ERR; } ok = string2ll(c->querybuf+pos+1,newline-(c->querybuf+pos+1),&ll); if (!ok || ll < 0 || ll > 512*1024*1024) { addReplyError(c,"Protocol error: invalid bulk length"); setProtocolError(c,pos); return C_ERR; } pos += newline-(c->querybuf+pos)+2; if (ll >= PROTO_MBULK_BIG_ARG) { size_t qblen; /* If we are going to read a large object from network * try to make it likely that it will start at c->querybuf * boundary so that we can optimize object creation * avoiding a large copy of data. */ sdsrange(c->querybuf,pos,-1); pos = 0; qblen = sdslen(c->querybuf); /* Hint the sds library about the amount of bytes this string is * going to contain. */ if (qblen < (size_t)ll+2) c->querybuf = sdsMakeRoomFor(c->querybuf,ll+2-qblen); } c->bulklen = ll; } /* Read bulk argument */ if (sdslen(c->querybuf)-pos < (unsigned)(c->bulklen+2)) { /* Not enough data (+2 == trailing \r\n) */ break; } else { /* Optimization: if the buffer contains JUST our bulk element * instead of creating a new object by *copying* the sds we * just use the current sds string. */ if (pos == 0 && c->bulklen >= PROTO_MBULK_BIG_ARG && (signed) sdslen(c->querybuf) == c->bulklen+2) { c->argv[c->argc++] = createObject(OBJ_STRING,c->querybuf); sdsIncrLen(c->querybuf,-2); /* remove CRLF */ /* Assume that if we saw a fat argument we'll see another one * likely... */ c->querybuf = sdsnewlen(NULL,c->bulklen+2); sdsclear(c->querybuf); pos = 0; } else { c->argv[c->argc++] = createStringObject(c->querybuf+pos,c->bulklen); pos += c->bulklen+2; } c->bulklen = -1; c->multibulklen--; } } /* Trim to pos */ if (pos) sdsrange(c->querybuf,pos,-1); /* We're done when c->multibulk == 0 */ if (c->multibulklen == 0) return C_OK; /* Still not read to process the command */ return C_ERR; } void processInputBuffer(client *c) { server.current_client = c; /* Keep processing while there is something in the input buffer */ while(sdslen(c->querybuf)) { /* Return if clients are paused. */ if (!(c->flags & CLIENT_SLAVE) && clientsArePaused()) break; /* Immediately abort if the client is in the middle of something. */ if (c->flags & CLIENT_BLOCKED) break; /* CLIENT_CLOSE_AFTER_REPLY closes the connection once the reply is * written to the client. Make sure to not let the reply grow after * this flag has been set (i.e. don't process more commands). * * The same applies for clients we want to terminate ASAP. */ if (c->flags & (CLIENT_CLOSE_AFTER_REPLY|CLIENT_CLOSE_ASAP)) break; /* Determine request type when unknown. */ if (!c->reqtype) { if (c->querybuf[0] == '*') { c->reqtype = PROTO_REQ_MULTIBULK; } else { c->reqtype = PROTO_REQ_INLINE; } } if (c->reqtype == PROTO_REQ_INLINE) { if (processInlineBuffer(c) != C_OK) break; } else if (c->reqtype == PROTO_REQ_MULTIBULK) { if (processMultibulkBuffer(c) != C_OK) break; } else { serverPanic("Unknown request type"); } /* Multibulk processing could see a <= 0 length. */ if (c->argc == 0) { resetClient(c); } else { /* Only reset the client when the command was executed. */ if (processCommand(c) == C_OK) resetClient(c); /* freeMemoryIfNeeded may flush slave output buffers. This may result * into a slave, that may be the active client, to be freed. */ if (server.current_client == NULL) break; } } server.current_client = NULL; } void readQueryFromClient(aeEventLoop *el, int fd, void *privdata, int mask) { client *c = (client*) privdata; int nread, readlen; size_t qblen; UNUSED(el); UNUSED(mask); readlen = PROTO_IOBUF_LEN; /* If this is a multi bulk request, and we are processing a bulk reply * that is large enough, try to maximize the probability that the query * buffer contains exactly the SDS string representing the object, even * at the risk of requiring more read(2) calls. This way the function * processMultiBulkBuffer() can avoid copying buffers to create the * Redis Object representing the argument. */ if (c->reqtype == PROTO_REQ_MULTIBULK && c->multibulklen && c->bulklen != -1 && c->bulklen >= PROTO_MBULK_BIG_ARG) { int remaining = (unsigned)(c->bulklen+2)-sdslen(c->querybuf); if (remaining < readlen) readlen = remaining; } qblen = sdslen(c->querybuf); if (c->querybuf_peak < qblen) c->querybuf_peak = qblen; c->querybuf = sdsMakeRoomFor(c->querybuf, readlen); nread = read(fd, c->querybuf+qblen, readlen); if (nread == -1) { if (errno == EAGAIN) { return; } else { serverLog(LL_VERBOSE, "Reading from client: %s",strerror(errno)); freeClient(c); return; } } else if (nread == 0) { serverLog(LL_VERBOSE, "Client closed connection"); freeClient(c); return; } sdsIncrLen(c->querybuf,nread); c->lastinteraction = server.unixtime; if (c->flags & CLIENT_MASTER) c->reploff += nread; server.stat_net_input_bytes += nread; if (sdslen(c->querybuf) > server.client_max_querybuf_len) { sds ci = catClientInfoString(sdsempty(),c), bytes = sdsempty(); bytes = sdscatrepr(bytes,c->querybuf,64); serverLog(LL_WARNING,"Closing client that reached max query buffer length: %s (qbuf initial bytes: %s)", ci, bytes); sdsfree(ci); sdsfree(bytes); freeClient(c); return; } processInputBuffer(c); } void getClientsMaxBuffers(unsigned long *longest_output_list, unsigned long *biggest_input_buffer) { client *c; listNode *ln; listIter li; unsigned long lol = 0, bib = 0; listRewind(server.clients,&li); while ((ln = listNext(&li)) != NULL) { c = listNodeValue(ln); if (listLength(c->reply) > lol) lol = listLength(c->reply); if (sdslen(c->querybuf) > bib) bib = sdslen(c->querybuf); } *longest_output_list = lol; *biggest_input_buffer = bib; } /* A Redis "Peer ID" is a colon separated ip:port pair. * For IPv4 it's in the form x.y.z.k:port, example: "127.0.0.1:1234". * For IPv6 addresses we use [] around the IP part, like in "[::1]:1234". * For Unix sockets we use path:0, like in "/tmp/redis:0". * * A Peer ID always fits inside a buffer of NET_PEER_ID_LEN bytes, including * the null term. * * On failure the function still populates 'peerid' with the "?:0" string * in case you want to relax error checking or need to display something * anyway (see anetPeerToString implementation for more info). */ void genClientPeerId(client *client, char *peerid, size_t peerid_len) { if (client->flags & CLIENT_UNIX_SOCKET) { /* Unix socket client. */ snprintf(peerid,peerid_len,"%s:0",server.unixsocket); } else { /* TCP client. */ anetFormatPeer(client->fd,peerid,peerid_len); } } /* This function returns the client peer id, by creating and caching it * if client->peerid is NULL, otherwise returning the cached value. * The Peer ID never changes during the life of the client, however it * is expensive to compute. */ char *getClientPeerId(client *c) { char peerid[NET_PEER_ID_LEN]; if (c->peerid == NULL) { genClientPeerId(c,peerid,sizeof(peerid)); c->peerid = sdsnew(peerid); } return c->peerid; } /* Concatenate a string representing the state of a client in an human * readable format, into the sds string 's'. */ sds catClientInfoString(sds s, client *client) { char flags[16], events[3], *p; int emask; p = flags; if (client->flags & CLIENT_SLAVE) { if (client->flags & CLIENT_MONITOR) *p++ = 'O'; else *p++ = 'S'; } if (client->flags & CLIENT_MASTER) *p++ = 'M'; if (client->flags & CLIENT_MULTI) *p++ = 'x'; if (client->flags & CLIENT_BLOCKED) *p++ = 'b'; if (client->flags & CLIENT_DIRTY_CAS) *p++ = 'd'; if (client->flags & CLIENT_CLOSE_AFTER_REPLY) *p++ = 'c'; if (client->flags & CLIENT_UNBLOCKED) *p++ = 'u'; if (client->flags & CLIENT_CLOSE_ASAP) *p++ = 'A'; if (client->flags & CLIENT_UNIX_SOCKET) *p++ = 'U'; if (client->flags & CLIENT_READONLY) *p++ = 'r'; #ifdef NBASE_ARC if (client->flags & CLIENT_LOCAL_CONN) *p++ = 'L'; #endif if (p == flags) *p++ = 'N'; *p++ = '\0'; emask = client->fd == -1 ? 0 : aeGetFileEvents(server.el,client->fd); p = events; if (emask & AE_READABLE) *p++ = 'r'; if (emask & AE_WRITABLE) *p++ = 'w'; *p = '\0'; return sdscatfmt(s, "id=%U addr=%s fd=%i name=%s age=%I idle=%I flags=%s db=%i sub=%i psub=%i multi=%i qbuf=%U qbuf-free=%U obl=%U oll=%U omem=%U events=%s cmd=%s", (unsigned long long) client->id, getClientPeerId(client), client->fd, client->name ? (char*)client->name->ptr : "", (long long)(server.unixtime - client->ctime), (long long)(server.unixtime - client->lastinteraction), flags, client->db->id, (int) dictSize(client->pubsub_channels), (int) listLength(client->pubsub_patterns), (client->flags & CLIENT_MULTI) ? client->mstate.count : -1, (unsigned long long) sdslen(client->querybuf), (unsigned long long) sdsavail(client->querybuf), (unsigned long long) client->bufpos, (unsigned long long) listLength(client->reply), (unsigned long long) getClientOutputBufferMemoryUsage(client), events, client->lastcmd ? client->lastcmd->name : "NULL"); } sds getAllClientsInfoString(void) { listNode *ln; listIter li; client *client; sds o = sdsnewlen(NULL,200*listLength(server.clients)); sdsclear(o); listRewind(server.clients,&li); while ((ln = listNext(&li)) != NULL) { client = listNodeValue(ln); o = catClientInfoString(o,client); o = sdscatlen(o,"\n",1); } return o; } void clientCommand(client *c) { listNode *ln; listIter li; client *client; if (!strcasecmp(c->argv[1]->ptr,"list") && c->argc == 2) { /* CLIENT LIST */ sds o = getAllClientsInfoString(); addReplyBulkCBuffer(c,o,sdslen(o)); sdsfree(o); } else if (!strcasecmp(c->argv[1]->ptr,"reply") && c->argc == 3) { /* CLIENT REPLY ON|OFF|SKIP */ if (!strcasecmp(c->argv[2]->ptr,"on")) { c->flags &= ~(CLIENT_REPLY_SKIP|CLIENT_REPLY_OFF); addReply(c,shared.ok); } else if (!strcasecmp(c->argv[2]->ptr,"off")) { c->flags |= CLIENT_REPLY_OFF; } else if (!strcasecmp(c->argv[2]->ptr,"skip")) { if (!(c->flags & CLIENT_REPLY_OFF)) c->flags |= CLIENT_REPLY_SKIP_NEXT; } else { addReply(c,shared.syntaxerr); return; } } else if (!strcasecmp(c->argv[1]->ptr,"kill")) { /* CLIENT KILL <ip:port> * CLIENT KILL <option> [value] ... <option> [value] */ char *addr = NULL; int type = -1; uint64_t id = 0; int skipme = 1; int killed = 0, close_this_client = 0; if (c->argc == 3) { /* Old style syntax: CLIENT KILL <addr> */ addr = c->argv[2]->ptr; skipme = 0; /* With the old form, you can kill yourself. */ } else if (c->argc > 3) { int i = 2; /* Next option index. */ /* New style syntax: parse options. */ while(i < c->argc) { int moreargs = c->argc > i+1; if (!strcasecmp(c->argv[i]->ptr,"id") && moreargs) { long long tmp; if (getLongLongFromObjectOrReply(c,c->argv[i+1],&tmp,NULL) != C_OK) return; id = tmp; } else if (!strcasecmp(c->argv[i]->ptr,"type") && moreargs) { type = getClientTypeByName(c->argv[i+1]->ptr); if (type == -1) { addReplyErrorFormat(c,"Unknown client type '%s'", (char*) c->argv[i+1]->ptr); return; } } else if (!strcasecmp(c->argv[i]->ptr,"addr") && moreargs) { addr = c->argv[i+1]->ptr; } else if (!strcasecmp(c->argv[i]->ptr,"skipme") && moreargs) { if (!strcasecmp(c->argv[i+1]->ptr,"yes")) { skipme = 1; } else if (!strcasecmp(c->argv[i+1]->ptr,"no")) { skipme = 0; } else { addReply(c,shared.syntaxerr); return; } } else { addReply(c,shared.syntaxerr); return; } i += 2; } } else { addReply(c,shared.syntaxerr); return; } /* Iterate clients killing all the matching clients. */ listRewind(server.clients,&li); while ((ln = listNext(&li)) != NULL) { client = listNodeValue(ln); if (addr && strcmp(getClientPeerId(client),addr) != 0) continue; if (type != -1 && getClientType(client) != type) continue; if (id != 0 && client->id != id) continue; if (c == client && skipme) continue; /* Kill it. */ if (c == client) { close_this_client = 1; } else { freeClient(client); } killed++; } /* Reply according to old/new format. */ if (c->argc == 3) { if (killed == 0) addReplyError(c,"No such client"); else addReply(c,shared.ok); } else { addReplyLongLong(c,killed); } /* If this client has to be closed, flag it as CLOSE_AFTER_REPLY * only after we queued the reply to its output buffers. */ if (close_this_client) c->flags |= CLIENT_CLOSE_AFTER_REPLY; } else if (!strcasecmp(c->argv[1]->ptr,"setname") && c->argc == 3) { int j, len = sdslen(c->argv[2]->ptr); char *p = c->argv[2]->ptr; /* Setting the client name to an empty string actually removes * the current name. */ if (len == 0) { if (c->name) decrRefCount(c->name); c->name = NULL; addReply(c,shared.ok); return; } /* Otherwise check if the charset is ok. We need to do this otherwise * CLIENT LIST format will break. You should always be able to * split by space to get the different fields. */ for (j = 0; j < len; j++) { if (p[j] < '!' || p[j] > '~') { /* ASCII is assumed. */ addReplyError(c, "Client names cannot contain spaces, " "newlines or special characters."); return; } } if (c->name) decrRefCount(c->name); c->name = c->argv[2]; incrRefCount(c->name); addReply(c,shared.ok); } else if (!strcasecmp(c->argv[1]->ptr,"getname") && c->argc == 2) { if (c->name) addReplyBulk(c,c->name); else addReply(c,shared.nullbulk); } else if (!strcasecmp(c->argv[1]->ptr,"pause") && c->argc == 3) { long long duration; if (getTimeoutFromObjectOrReply(c,c->argv[2],&duration,UNIT_MILLISECONDS) != C_OK) return; pauseClients(duration); addReply(c,shared.ok); } else { addReplyError(c, "Syntax error, try CLIENT (LIST | KILL | GETNAME | SETNAME | PAUSE | REPLY)"); } } /* This callback is bound to POST and "Host:" command names. Those are not * really commands, but are used in security attacks in order to talk to * Redis instances via HTTP, with a technique called "cross protocol scripting" * which exploits the fact that services like Redis will discard invalid * HTTP headers and will process what follows. * * As a protection against this attack, Redis will terminate the connection * when a POST or "Host:" header is seen, and will log the event from * time to time (to avoid creating a DOS as a result of too many logs). */ void securityWarningCommand(client *c) { static time_t logged_time; time_t now = time(NULL); if (labs(now-logged_time) > 60) { serverLog(LL_WARNING,"Possible SECURITY ATTACK detected. It looks like somebody is sending POST or Host: commands to Redis. This is likely due to an attacker attempting to use Cross Protocol Scripting to compromise your Redis instance. Connection aborted."); logged_time = now; } freeClientAsync(c); } /* Rewrite the command vector of the client. All the new objects ref count * is incremented. The old command vector is freed, and the old objects * ref count is decremented. */ void rewriteClientCommandVector(client *c, int argc, ...) { va_list ap; int j; robj **argv; /* The new argument vector */ argv = zmalloc(sizeof(robj*)*argc); va_start(ap,argc); for (j = 0; j < argc; j++) { robj *a; a = va_arg(ap, robj*); argv[j] = a; incrRefCount(a); } /* We free the objects in the original vector at the end, so we are * sure that if the same objects are reused in the new vector the * refcount gets incremented before it gets decremented. */ for (j = 0; j < c->argc; j++) decrRefCount(c->argv[j]); zfree(c->argv); /* Replace argv and argc with our new versions. */ c->argv = argv; c->argc = argc; c->cmd = lookupCommandOrOriginal(c->argv[0]->ptr); serverAssertWithInfo(c,NULL,c->cmd != NULL); va_end(ap); } /* Completely replace the client command vector with the provided one. */ void replaceClientCommandVector(client *c, int argc, robj **argv) { freeClientArgv(c); zfree(c->argv); c->argv = argv; c->argc = argc; c->cmd = lookupCommandOrOriginal(c->argv[0]->ptr); serverAssertWithInfo(c,NULL,c->cmd != NULL); } /* Rewrite a single item in the command vector. * The new val ref count is incremented, and the old decremented. * * It is possible to specify an argument over the current size of the * argument vector: in this case the array of objects gets reallocated * and c->argc set to the max value. However it's up to the caller to * * 1. Make sure there are no "holes" and all the arguments are set. * 2. If the original argument vector was longer than the one we * want to end with, it's up to the caller to set c->argc and * free the no longer used objects on c->argv. */ void rewriteClientCommandArgument(client *c, int i, robj *newval) { robj *oldval; if (i >= c->argc) { c->argv = zrealloc(c->argv,sizeof(robj*)*(i+1)); c->argc = i+1; c->argv[i] = NULL; } oldval = c->argv[i]; c->argv[i] = newval; incrRefCount(newval); if (oldval) decrRefCount(oldval); /* If this is the command name make sure to fix c->cmd. */ if (i == 0) { c->cmd = lookupCommandOrOriginal(c->argv[0]->ptr); serverAssertWithInfo(c,NULL,c->cmd != NULL); } } /* This function returns the number of bytes that Redis is virtually * using to store the reply still not read by the client. * It is "virtual" since the reply output list may contain objects that * are shared and are not really using additional memory. * * The function returns the total sum of the length of all the objects * stored in the output list, plus the memory used to allocate every * list node. The static reply buffer is not taken into account since it * is allocated anyway. * * Note: this function is very fast so can be called as many time as * the caller wishes. The main usage of this function currently is * enforcing the client output length limits. */ unsigned long getClientOutputBufferMemoryUsage(client *c) { unsigned long list_item_size = sizeof(listNode)+sizeof(robj); return c->reply_bytes + (list_item_size*listLength(c->reply)); } /* Get the class of a client, used in order to enforce limits to different * classes of clients. * * The function will return one of the following: * CLIENT_TYPE_NORMAL -> Normal client * CLIENT_TYPE_SLAVE -> Slave or client executing MONITOR command * CLIENT_TYPE_PUBSUB -> Client subscribed to Pub/Sub channels * CLIENT_TYPE_MASTER -> The client representing our replication master. */ int getClientType(client *c) { if (c->flags & CLIENT_MASTER) return CLIENT_TYPE_MASTER; if ((c->flags & CLIENT_SLAVE) && !(c->flags & CLIENT_MONITOR)) return CLIENT_TYPE_SLAVE; if (c->flags & CLIENT_PUBSUB) return CLIENT_TYPE_PUBSUB; return CLIENT_TYPE_NORMAL; } int getClientTypeByName(char *name) { if (!strcasecmp(name,"normal")) return CLIENT_TYPE_NORMAL; else if (!strcasecmp(name,"slave")) return CLIENT_TYPE_SLAVE; else if (!strcasecmp(name,"pubsub")) return CLIENT_TYPE_PUBSUB; else if (!strcasecmp(name,"master")) return CLIENT_TYPE_MASTER; else return -1; } char *getClientTypeName(int class) { switch(class) { case CLIENT_TYPE_NORMAL: return "normal"; case CLIENT_TYPE_SLAVE: return "slave"; case CLIENT_TYPE_PUBSUB: return "pubsub"; case CLIENT_TYPE_MASTER: return "master"; default: return NULL; } } /* The function checks if the client reached output buffer soft or hard * limit, and also update the state needed to check the soft limit as * a side effect. * * Return value: non-zero if the client reached the soft or the hard limit. * Otherwise zero is returned. */ int checkClientOutputBufferLimits(client *c) { int soft = 0, hard = 0, class; unsigned long used_mem = getClientOutputBufferMemoryUsage(c); class = getClientType(c); /* For the purpose of output buffer limiting, masters are handled * like normal clients. */ if (class == CLIENT_TYPE_MASTER) class = CLIENT_TYPE_NORMAL; if (server.client_obuf_limits[class].hard_limit_bytes && used_mem >= server.client_obuf_limits[class].hard_limit_bytes) hard = 1; if (server.client_obuf_limits[class].soft_limit_bytes && used_mem >= server.client_obuf_limits[class].soft_limit_bytes) soft = 1; /* We need to check if the soft limit is reached continuously for the * specified amount of seconds. */ if (soft) { if (c->obuf_soft_limit_reached_time == 0) { c->obuf_soft_limit_reached_time = server.unixtime; soft = 0; /* First time we see the soft limit reached */ } else { time_t elapsed = server.unixtime - c->obuf_soft_limit_reached_time; if (elapsed <= server.client_obuf_limits[class].soft_limit_seconds) { soft = 0; /* The client still did not reached the max number of seconds for the soft limit to be considered reached. */ } } } else { c->obuf_soft_limit_reached_time = 0; } return soft || hard; } /* Asynchronously close a client if soft or hard limit is reached on the * output buffer size. The caller can check if the client will be closed * checking if the client CLIENT_CLOSE_ASAP flag is set. * * Note: we need to close the client asynchronously because this function is * called from contexts where the client can't be freed safely, i.e. from the * lower level functions pushing data inside the client output buffers. */ void asyncCloseClientOnOutputBufferLimitReached(client *c) { serverAssert(c->reply_bytes < SIZE_MAX-(1024*64)); if (c->reply_bytes == 0 || c->flags & CLIENT_CLOSE_ASAP) return; if (checkClientOutputBufferLimits(c)) { sds client = catClientInfoString(sdsempty(),c); freeClientAsync(c); serverLog(LL_WARNING,"Client %s scheduled to be closed ASAP for overcoming of output buffer limits.", client); sdsfree(client); } } /* Helper function used by freeMemoryIfNeeded() in order to flush slaves * output buffers without returning control to the event loop. * This is also called by SHUTDOWN for a best-effort attempt to send * slaves the latest writes. */ void flushSlavesOutputBuffers(void) { listIter li; listNode *ln; listRewind(server.slaves,&li); while((ln = listNext(&li))) { client *slave = listNodeValue(ln); int events; /* Note that the following will not flush output buffers of slaves * in STATE_ONLINE but having put_online_on_ack set to true: in this * case the writable event is never installed, since the purpose * of put_online_on_ack is to postpone the moment it is installed. * This is what we want since slaves in this state should not receive * writes before the first ACK. */ events = aeGetFileEvents(server.el,slave->fd); if (events & AE_WRITABLE && slave->replstate == SLAVE_STATE_ONLINE && clientHasPendingReplies(slave)) { writeToClient(slave->fd,slave,0); } } } /* Pause clients up to the specified unixtime (in ms). While clients * are paused no command is processed from clients, so the data set can't * change during that time. * * However while this function pauses normal and Pub/Sub clients, slaves are * still served, so this function can be used on server upgrades where it is * required that slaves process the latest bytes from the replication stream * before being turned to masters. * * This function is also internally used by Redis Cluster for the manual * failover procedure implemented by CLUSTER FAILOVER. * * The function always succeed, even if there is already a pause in progress. * In such a case, the pause is extended if the duration is more than the * time left for the previous duration. However if the duration is smaller * than the time left for the previous pause, no change is made to the * left duration. */ void pauseClients(mstime_t end) { if (!server.clients_paused || end > server.clients_pause_end_time) server.clients_pause_end_time = end; server.clients_paused = 1; } /* Return non-zero if clients are currently paused. As a side effect the * function checks if the pause time was reached and clear it. */ int clientsArePaused(void) { if (server.clients_paused && server.clients_pause_end_time < server.mstime) { listNode *ln; listIter li; client *c; server.clients_paused = 0; /* Put all the clients in the unblocked clients queue in order to * force the re-processing of the input buffer if any. */ listRewind(server.clients,&li); while ((ln = listNext(&li)) != NULL) { c = listNodeValue(ln); /* Don't touch slaves and blocked clients. The latter pending * requests be processed when unblocked. */ if (c->flags & (CLIENT_SLAVE|CLIENT_BLOCKED)) continue; c->flags |= CLIENT_UNBLOCKED; listAddNodeTail(server.unblocked_clients,c); } } return server.clients_paused; } /* This function is called by Redis in order to process a few events from * time to time while blocked into some not interruptible operation. * This allows to reply to clients with the -LOADING error while loading the * data set at startup or after a full resynchronization with the master * and so forth. * * It calls the event loop in order to process a few events. Specifically we * try to call the event loop 4 times as long as we receive acknowledge that * some event was processed, in order to go forward with the accept, read, * write, close sequence needed to serve a client. * * The function returns the total number of events processed. */ int processEventsWhileBlocked(void) { int iterations = 4; /* See the function top-comment. */ int count = 0; while (iterations--) { int events = 0; events += aeProcessEvents(server.el, AE_FILE_EVENTS|AE_DONT_WAIT); events += handleClientsWithPendingWrites(); if (!events) break; count += events; } return count; }
{ "content_hash": "50a4169bfe8291c823b2c84350048909", "timestamp": "", "source": "github", "line_count": 1967, "max_line_length": 266, "avg_line_length": 36.253177427554654, "alnum_prop": 0.5938017108399944, "repo_name": "sanitysoon/nbase-arc", "id": "24b87bd5d41027959be1e1b3f76ec7ea07e3f2a5", "size": "72919", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "redis/src/networking.c", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1151" }, { "name": "C", "bytes": "6456177" }, { "name": "C++", "bytes": "394336" }, { "name": "CSS", "bytes": "1647" }, { "name": "HTML", "bytes": "416894" }, { "name": "Java", "bytes": "3113775" }, { "name": "Lua", "bytes": "11887" }, { "name": "M4", "bytes": "71933" }, { "name": "Makefile", "bytes": "190213" }, { "name": "Objective-C", "bytes": "24462" }, { "name": "Perl", "bytes": "175311" }, { "name": "Python", "bytes": "1226350" }, { "name": "Roff", "bytes": "937514" }, { "name": "Ruby", "bytes": "71136" }, { "name": "Shell", "bytes": "277765" }, { "name": "Smarty", "bytes": "1047" }, { "name": "Tcl", "bytes": "472171" }, { "name": "XSLT", "bytes": "303" } ], "symlink_target": "" }
/*************************************************************************** * Purpose : To create stopwatch to count time of program * * @author Sujit * @version 1.0 * @since 18-08-2017 ****************************************************************************/ public class StopWatch { private static long start; public StopWatch() { start = System.currentTimeMillis(); } public static long elapsedTime() { long now = System.currentTimeMillis(); return (now - start); } }
{ "content_hash": "b9a30aaae99dd9f8c40258a6b87c0768", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 77, "avg_line_length": 26.45, "alnum_prop": 0.44045368620037806, "repo_name": "sujitchincholkar/BridgeLabz-programs", "id": "e8e4127da8ffb3fe5005af2bf45d3efda1bc6a7e", "size": "529", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "com/bridgelabz/lib/StopWatch.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "98099" } ], "symlink_target": "" }
<?php /** * Author: Hassletauf <[email protected]> * Date: 10/2/2016 * Time: 11:26 AM */ namespace Konnektive\Request\Order; use Konnektive\Request\Request; /** * Class ImportUpsaleRequest * @link https://api2.konnektive.com/docs/upsale_import/ * @package Konnektive\Request\Order * * @property string $loginId Api Login Id provided by Konnektive * @property string $password Api password provided by Konnektive * @property string $orderId orderId returned by the import order api call * @property int $productId cproduct Id of upsale * @property int $productQty quantity of upsale, defaults to quantity of 1 if not set * @property double $productPrice if set this will override the default price as setup in Konnektive CRM * @property double $productShipPrice if set this will override the default shipping price as setup in Konnektive CRM * @property double $productSalesTax if set this will be added to any existing sales tax for the current order * @property int $replaceProductId cproduct Id of previously selected offer in order. If passed, upsell will replace the existing offer. */ class ImportUpsaleRequest extends Request { protected $endpointUri = "/upsale/import/"; protected $rules = [ 'loginId' => 'required|max:32', 'password' => 'required|max:32', 'orderId' => 'required|max:32', 'productId' => 'required|integer', 'productQty' => 'integer', 'productPrice' => 'numeric', 'productShipPrice' => 'numeric', 'productSalesTax' => 'numeric', 'replaceProductId' => 'integer' ]; }
{ "content_hash": "6fce0f804576bdc47df954253630126c", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 142, "avg_line_length": 38.41860465116279, "alnum_prop": 0.6834140435835351, "repo_name": "progjp/konnektive-api", "id": "9f77488652100b30c1906ec075ad5dfd362725a0", "size": "1652", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/Request/Order/ImportUpsaleRequest.php", "mode": "33261", "license": "mit", "language": [ { "name": "PHP", "bytes": "251231" } ], "symlink_target": "" }
import { factory } from '../../../utils/factory.js' import { clone } from '../../../utils/object.js' const name = 'matAlgo14xDs' const dependencies = ['typed'] export const createMatAlgo14xDs = /* #__PURE__ */ factory(name, dependencies, ({ typed }) => { /** * Iterates over DenseMatrix items and invokes the callback function f(Aij..z, b). * Callback function invoked MxN times. * * C(i,j,...z) = f(Aij..z, b) * * @param {Matrix} a The DenseMatrix instance (A) * @param {Scalar} b The Scalar value * @param {Function} callback The f(Aij..z,b) operation to invoke * @param {boolean} inverse A true value indicates callback should be invoked f(b,Aij..z) * * @return {Matrix} DenseMatrix (C) * * https://github.com/josdejong/mathjs/pull/346#issuecomment-97659042 */ return function matAlgo14xDs (a, b, callback, inverse) { // a arrays const adata = a._data const asize = a._size const adt = a._datatype // datatype let dt // callback signature to use let cf = callback // process data types if (typeof adt === 'string') { // datatype dt = adt // convert b to the same datatype b = typed.convert(b, dt) // callback cf = typed.find(callback, [dt, dt]) } // populate cdata, iterate through dimensions const cdata = asize.length > 0 ? _iterate(cf, 0, asize, asize[0], adata, b, inverse) : [] // c matrix return a.createDenseMatrix({ data: cdata, size: clone(asize), datatype: dt }) } // recursive function function _iterate (f, level, s, n, av, bv, inverse) { // initialize array for this level const cv = [] // check we reach the last level if (level === s.length - 1) { // loop arrays in last level for (let i = 0; i < n; i++) { // invoke callback and store value cv[i] = inverse ? f(bv, av[i]) : f(av[i], bv) } } else { // iterate current level for (let j = 0; j < n; j++) { // iterate next level cv[j] = _iterate(f, level + 1, s, s[level + 1], av[j], bv, inverse) } } return cv } })
{ "content_hash": "397ccedb7cb7efba9335136ae63454e1", "timestamp": "", "source": "github", "line_count": 75, "max_line_length": 102, "avg_line_length": 29.746666666666666, "alnum_prop": 0.5567010309278351, "repo_name": "josdejong/mathjs", "id": "342b2b19d98232351e0d7d0d1282ce3447ab2eaf", "size": "2231", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src/type/matrix/utils/matAlgo14xDs.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "1533" }, { "name": "JavaScript", "bytes": "3813243" }, { "name": "MATLAB", "bytes": "1451" }, { "name": "Python", "bytes": "4102" }, { "name": "TypeScript", "bytes": "56863" } ], "symlink_target": "" }
'use strict'; // Load modules const Util = require('util'); const Stream = require('stream'); const Fs = require('fs'); const Zlib = require('zlib'); const Lab = require('lab'); const Shot = require('../lib'); const Code = require('code'); // Declare internals const internals = {}; // Test shortcuts const lab = exports.lab = Lab.script(); const describe = lab.describe; const it = lab.it; const expect = Code.expect; describe('inject()', () => { it('returns non-chunked payload', (done) => { const output = 'example.com:8080|/hello'; const dispatch = function (req, res) { res.writeHead(200, { 'Content-Type': 'text/plain', 'Content-Length': output.length }); res.end(req.headers.host + '|' + req.url); }; Shot.inject(dispatch, 'http://example.com:8080/hello', (res) => { expect(res.headers.date).to.exist(); expect(res.headers.connection).to.exist(); expect(res.headers['transfer-encoding']).to.not.exist(); expect(res.payload).to.equal(output); expect(res.rawPayload.toString()).to.equal('example.com:8080|/hello'); done(); }); }); it('returns single buffer payload', (done) => { const dispatch = function (req, res) { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end(req.headers.host + '|' + req.url); }; Shot.inject(dispatch, { url: 'http://example.com:8080/hello' }, (res) => { expect(res.headers.date).to.exist(); expect(res.headers.connection).to.exist(); expect(res.headers['transfer-encoding']).to.equal('chunked'); expect(res.payload).to.equal('example.com:8080|/hello'); expect(res.rawPayload.toString()).to.equal('example.com:8080|/hello'); done(); }); }); it('passes headers', (done) => { const dispatch = function (req, res) { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end(req.headers.super); }; Shot.inject(dispatch, { method: 'get', url: 'http://example.com:8080/hello', headers: { Super: 'duper' } }, (res) => { expect(res.payload).to.equal('duper'); done(); }); }); it('passes remote address', (done) => { const dispatch = function (req, res) { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end(req.connection.remoteAddress); }; Shot.inject(dispatch, { method: 'get', url: 'http://example.com:8080/hello', remoteAddress: '1.2.3.4' }, (res) => { expect(res.payload).to.equal('1.2.3.4'); done(); }); }); it('passes localhost as default remote address', (done) => { const dispatch = function (req, res) { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end(req.connection.remoteAddress); }; Shot.inject(dispatch, { method: 'get', url: 'http://example.com:8080/hello' }, (res) => { expect(res.payload).to.equal('127.0.0.1'); done(); }); }); it('passes host option as host header', (done) => { const dispatch = function (req, res) { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end(req.headers.host); }; Shot.inject(dispatch, { method: 'get', url: '/hello', headers: { host: 'test.example.com' } }, (res) => { expect(res.payload).to.equal('test.example.com'); done(); }); }); it('passes localhost as default host header', (done) => { const dispatch = function (req, res) { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end(req.headers.host); }; Shot.inject(dispatch, { method: 'get', url: '/hello' }, (res) => { expect(res.payload).to.equal('localhost'); done(); }); }); it('passes authority as host header', (done) => { const dispatch = function (req, res) { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end(req.headers.host); }; Shot.inject(dispatch, { method: 'get', url: '/hello', authority: 'something' }, (res) => { expect(res.payload).to.equal('something'); done(); }); }); it('passes uri host as host header', (done) => { const dispatch = function (req, res) { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end(req.headers.host); }; Shot.inject(dispatch, { method: 'get', url: 'http://example.com:8080/hello' }, (res) => { expect(res.payload).to.equal('example.com:8080'); done(); }); }); it('optionally accepts an object as url', (done) => { const output = 'example.com:8080|/hello?test=1234'; const dispatch = function (req, res) { res.writeHead(200, { 'Content-Type': 'text/plain', 'Content-Length': output.length }); res.end(req.headers.host + '|' + req.url); }; const url = { protocol: 'http', hostname: 'example.com', port: '8080', pathname: 'hello', query: { test: '1234' } }; Shot.inject(dispatch, { url: url }, (res) => { expect(res.headers.date).to.exist(); expect(res.headers.connection).to.exist(); expect(res.headers['transfer-encoding']).to.not.exist(); expect(res.payload).to.equal(output); done(); }); }); it('leaves user-agent unmodified', (done) => { const dispatch = function (req, res) { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end(req.headers['user-agent']); }; Shot.inject(dispatch, { method: 'get', url: 'http://example.com:8080/hello', headers: { 'user-agent': 'duper' } }, (res) => { expect(res.payload).to.equal('duper'); done(); }); }); it('returns chunked payload', (done) => { const dispatch = function (req, res) { res.writeHead(200, 'OK'); res.write('a'); res.write('b'); res.end(); }; Shot.inject(dispatch, { method: 'get', url: '/' }, (res) => { expect(res.headers.date).to.exist(); expect(res.headers.connection).to.exist(); expect(res.headers['transfer-encoding']).to.equal('chunked'); expect(res.payload).to.equal('ab'); done(); }); }); it('sets trailers in response object', (done) => { const dispatch = function (req, res) { res.setHeader('Trailer', 'Test'); res.addTrailers({ 'Test': 123 }); res.end(); }; Shot.inject(dispatch, { method: 'get', url: '/' }, (res) => { expect(res.headers.trailer).to.equal('Test'); expect(res.headers.test).to.be.undefined(); expect(res.trailers.test).to.equal('123'); done(); }); }); it('parses zipped payload', (done) => { const dispatch = function (req, res) { res.writeHead(200, 'OK'); const stream = Fs.createReadStream('./package.json'); stream.pipe(Zlib.createGzip()).pipe(res); }; Shot.inject(dispatch, { method: 'get', url: '/' }, (res) => { Fs.readFile('./package.json', { encoding: 'utf-8' }, (err, file) => { Zlib.unzip(res.rawPayload, (err, unzipped) => { expect(err).to.not.exist(); expect(unzipped.toString('utf-8')).to.deep.equal(file); done(); }); }); }); }); it('returns multi buffer payload', (done) => { const dispatch = function (req, res) { res.writeHead(200); res.write('a'); res.write(new Buffer('b')); res.end(); }; Shot.inject(dispatch, { method: 'get', url: '/' }, (res) => { expect(res.payload).to.equal('ab'); done(); }); }); it('returns null payload', (done) => { const dispatch = function (req, res) { res.writeHead(200, { 'Content-Length': 0 }); res.end(); }; Shot.inject(dispatch, { method: 'get', url: '/' }, (res) => { expect(res.payload).to.equal(''); done(); }); }); it('allows ending twice', (done) => { const dispatch = function (req, res) { res.writeHead(200, { 'Content-Length': 0 }); res.end(); res.end(); }; Shot.inject(dispatch, { method: 'get', url: '/' }, (res) => { expect(res.payload).to.equal(''); done(); }); }); it('identifies injection object', (done) => { const dispatch = function (req, res) { expect(Shot.isInjection(req)).to.equal(true); expect(Shot.isInjection(res)).to.equal(true); res.writeHead(200, { 'Content-Length': 0 }); res.end(); }; Shot.inject(dispatch, { method: 'get', url: '/' }, (res) => { done(); }); }); it('pipes response', (done) => { const Read = function () { Stream.Readable.call(this); }; Util.inherits(Read, Stream.Readable); Read.prototype._read = function (size) { this.push('hi'); this.push(null); }; let finished = false; const dispatch = function (req, res) { res.writeHead(200); const stream = new Read(); res.on('finish', () => { finished = true; }); stream.pipe(res); }; Shot.inject(dispatch, { method: 'get', url: '/' }, (res) => { expect(finished).to.equal(true); expect(res.payload).to.equal('hi'); done(); }); }); it('pipes response with old stream', (done) => { const Read = function () { Stream.Readable.call(this); }; Util.inherits(Read, Stream.Readable); Read.prototype._read = function (size) { this.push('hi'); this.push(null); }; let finished = false; const dispatch = function (req, res) { res.writeHead(200); const stream = new Read(); stream.pause(); const stream2 = new Stream.Readable().wrap(stream); stream.resume(); res.on('finish', () => { finished = true; }); stream2.pipe(res); }; Shot.inject(dispatch, { method: 'get', url: '/' }, (res) => { expect(finished).to.equal(true); expect(res.payload).to.equal('hi'); done(); }); }); it('echos object payload', (done) => { const dispatch = function (req, res) { res.writeHead(200, { 'content-type': req.headers['content-type'] }); req.pipe(res); }; Shot.inject(dispatch, { method: 'post', url: '/test', payload: { a: 1 } }, (res) => { expect(res.headers['content-type']).to.equal('application/json'); expect(res.payload).to.equal('{"a":1}'); done(); }); }); it('echos buffer payload', (done) => { const dispatch = function (req, res) { res.writeHead(200, { 'content-type': req.headers['content-type'] }); req.pipe(res); }; Shot.inject(dispatch, { method: 'post', url: '/test', payload: new Buffer('test!') }, (res) => { expect(res.payload).to.equal('test!'); done(); }); }); it('echos object payload with non-english utf-8 string', (done) => { const dispatch = function (req, res) { res.writeHead(200, { 'content-type': req.headers['content-type'] }); req.pipe(res); }; Shot.inject(dispatch, { method: 'post', url: '/test', payload: { a: '½½א' } }, (res) => { expect(res.headers['content-type']).to.equal('application/json'); expect(res.payload).to.equal('{"a":"½½א"}'); done(); }); }); it('echos object payload without payload', (done) => { const dispatch = function (req, res) { res.writeHead(200); req.pipe(res); }; Shot.inject(dispatch, { method: 'post', url: '/test' }, (res) => { expect(res.payload).to.equal(''); done(); }); }); it('retains content-type header', (done) => { const dispatch = function (req, res) { res.writeHead(200, { 'content-type': req.headers['content-type'] }); req.pipe(res); }; Shot.inject(dispatch, { method: 'post', url: '/test', payload: { a: 1 }, headers: { 'content-type': 'something' } }, (res) => { expect(res.headers['content-type']).to.equal('something'); expect(res.payload).to.equal('{"a":1}'); done(); }); }); it('adds a content-length header if none set when payload specified', (done) => { const dispatch = function (req, res) { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end(req.headers['content-length']); }; Shot.inject(dispatch, { method: 'post', url: '/test', payload: { a: 1 } }, (res) => { expect(res.payload).to.equal('{"a":1}'.length.toString()); done(); }); }); it('retains a content-length header when payload specified', (done) => { const dispatch = function (req, res) { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end(req.headers['content-length']); }; Shot.inject(dispatch, { method: 'post', url: '/test', payload: '', headers: { 'content-length': '10' } }, (res) => { expect(res.payload).to.equal('10'); done(); }); }); }); describe('writeHead()', () => { it('returns single buffer payload', (done) => { const reply = 'Hello World'; const dispatch = function (req, res) { res.writeHead(200, 'OK', { 'Content-Type': 'text/plain', 'Content-Length': reply.length }); res.end(reply); }; Shot.inject(dispatch, { method: 'get', url: '/' }, (res) => { expect(res.payload).to.equal(reply); done(); }); }); }); describe('_read()', () => { it('plays payload', (done) => { const dispatch = function (req, res) { let buffer = ''; req.on('readable', () => { buffer = buffer + (req.read() || ''); }); req.on('error', (err) => { }); req.on('close', () => { }); req.on('end', () => { res.writeHead(200, { 'Content-Length': 0 }); res.end(buffer); req.destroy(); }); }; const body = 'something special just for you'; Shot.inject(dispatch, { method: 'get', url: '/', payload: body }, (res) => { expect(res.payload).to.equal(body); done(); }); }); it('simulates split', (done) => { const dispatch = function (req, res) { let buffer = ''; req.on('readable', () => { buffer = buffer + (req.read() || ''); }); req.on('error', (err) => { }); req.on('close', () => { }); req.on('end', () => { res.writeHead(200, { 'Content-Length': 0 }); res.end(buffer); req.destroy(); }); }; const body = 'something special just for you'; Shot.inject(dispatch, { method: 'get', url: '/', payload: body, simulate: { split: true } }, (res) => { expect(res.payload).to.equal(body); done(); }); }); it('simulates error', (done) => { const dispatch = function (req, res) { req.on('readable', () => { }); req.on('error', (err) => { res.writeHead(200, { 'Content-Length': 0 }); res.end('error'); }); }; const body = 'something special just for you'; Shot.inject(dispatch, { method: 'get', url: '/', payload: body, simulate: { error: true } }, (res) => { expect(res.payload).to.equal('error'); done(); }); }); it('simulates no end without payload', (done) => { let end = false; const dispatch = function (req, res) { req.resume(); req.on('end', () => { end = true; }); }; let replied = false; Shot.inject(dispatch, { method: 'get', url: '/', simulate: { end: false } }, (res) => { replied = true; }); setTimeout(() => { expect(end).to.equal(false); expect(replied).to.equal(false); done(); }, 10); }); it('simulates no end with payload', (done) => { let end = false; const dispatch = function (req, res) { req.resume(); req.on('end', () => { end = true; }); }; let replied = false; Shot.inject(dispatch, { method: 'get', url: '/', payload: '1234567', simulate: { end: false } }, (res) => { replied = true; }); setTimeout(() => { expect(end).to.equal(false); expect(replied).to.equal(false); done(); }, 10); }); it('simulates close', (done) => { const dispatch = function (req, res) { let buffer = ''; req.on('readable', () => { buffer = buffer + (req.read() || ''); }); req.on('error', (err) => { }); req.on('close', () => { res.writeHead(200, { 'Content-Length': 0 }); res.end('close'); }); req.on('end', () => { }); }; const body = 'something special just for you'; Shot.inject(dispatch, { method: 'get', url: '/', payload: body, simulate: { close: true } }, (res) => { expect(res.payload).to.equal('close'); done(); }); }); });
{ "content_hash": "0156287ac97d830003907b2e7d9e02fe", "timestamp": "", "source": "github", "line_count": 721, "max_line_length": 135, "avg_line_length": 26.23855755894591, "alnum_prop": 0.4682841738027276, "repo_name": "TumboTheGnome/phaserGraph", "id": "853021ab9d2934429de05921170fecfd481562e1", "size": "18924", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "node_modules/hapi/node_modules/shot/test/index.js", "mode": "33261", "license": "mit", "language": [ { "name": "HTML", "bytes": "541" }, { "name": "JavaScript", "bytes": "63788" } ], "symlink_target": "" }
package cz.jan.maly.model.game.wrappers; import cz.jan.maly.utils.MyLogger; import lombok.Getter; /** * Common parent for all type wrappers * Created by Jan on 27-Mar-17. */ abstract class AbstractWrapper<T> { @Getter final T type; @Getter private final String name; AbstractWrapper(T type, String name) { this.name = name; if (type == null) { MyLogger.getLogger().warning("Constructor: type is null."); throw new RuntimeException("Constructor: type is null."); } this.type = type; } /** * Returns true if given type equals to one of types passed as parameter. */ boolean isType(T myType, T[] types) { for (T otherType : types) { if (myType.equals(otherType)) { return true; } } return false; } /** * Returns true if wrapper represents bwapi type * * @param bwapiType * @return */ public boolean isForType(T bwapiType) { return type.equals(bwapiType); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AbstractWrapper<?> that = (AbstractWrapper<?>) o; return name.equals(that.name); } @Override public int hashCode() { return type.hashCode(); } }
{ "content_hash": "818ec7c3a0aa3797ea5ff16b469ea70c", "timestamp": "", "source": "github", "line_count": 63, "max_line_length": 77, "avg_line_length": 22.523809523809526, "alnum_prop": 0.5680056377730797, "repo_name": "honzaMaly/kusanagi", "id": "72827d284c892b0d3d9734238a9673a40d082303", "size": "1419", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "abstract-bot/src/main/java/cz/jan/maly/model/game/wrappers/AbstractWrapper.java", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "133" }, { "name": "HTML", "bytes": "6640" }, { "name": "Java", "bytes": "1121923" }, { "name": "TeX", "bytes": "125044" } ], "symlink_target": "" }
layout: post title: "A Nice Exercise" description: "The benefit of learning for an external reason" date: 2017-10-30 tags: ['Learning', 'Python','GIS'] comments: true share: true --- # A Nice Exercise They say the best advice for people learning to programing is to build things. It can be anything that interests the budding programmer. I didn't always *get* this advice, because it's open ended and it can leave the student wandering around. However, I've been making attempts at applying any kind Python to a GIS applications recently and it has only left me more curious. The first time this happened was when I was given a spreadsheet of addresses I had to find the coordinates of. I had over 200 entries and didn't want to google maps the coordinates for each, so I found a geocoder library for python and used that to get the coordinates. Libraries are probably seen as crutches by some more professional programmers, and I understand why after taking cs50, but it made me only want to keep applying python in different ways. My most recent was a short script using an imaging library to make JPGs into TIFs. Some regex was used, and it also lead me to explore the os library, which is not known to me since most of Javascript experience is limited to the web. It has shown me cool things programming can do and learned that I was capable of doing them as well.
{ "content_hash": "e501ed0e267ab1b5130f0fcd5dfebeef", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 793, "avg_line_length": 98, "alnum_prop": 0.7857142857142857, "repo_name": "Kjmanion/kjmanion.github.io", "id": "e224b816f06fc4f2f752013c95fc5041c3ae87e1", "size": "1376", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_posts/2017-10-30-A-Nice-Exercise.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "23898" }, { "name": "HTML", "bytes": "11067" }, { "name": "Ruby", "bytes": "2850" } ], "symlink_target": "" }
using System.Collections.Generic; namespace Dropbox.Api { public class MetadataResult { public string path { get; set; } public bool is_dir { get; set; } public string mime_type { get; set; } } }
{ "content_hash": "23037def20a16f6a0c829aafb3f7b74a", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 45, "avg_line_length": 21.272727272727273, "alnum_prop": 0.6068376068376068, "repo_name": "hamstercat/Emby.Plugins", "id": "acff57ef0a41a7a7d788b7de4bb08a2df5996eef", "size": "236", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "Dropbox/Api/MetadataResult.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "8544445" }, { "name": "HTML", "bytes": "206570" } ], "symlink_target": "" }
require 'test_helper' class ProyectoTest < ActiveSupport::TestCase # test "the truth" do # assert true # end end
{ "content_hash": "53dade6248a46a4833a0b40765b7b9f7", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 44, "avg_line_length": 17.428571428571427, "alnum_prop": 0.6967213114754098, "repo_name": "lalo2302/TodUni", "id": "cf084baafb59a343bc792477de75a8f978694000", "size": "122", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "test/models/proyecto_test.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "4718" }, { "name": "CoffeeScript", "bytes": "1913" }, { "name": "HTML", "bytes": "27054" }, { "name": "JavaScript", "bytes": "715" }, { "name": "Ruby", "bytes": "102487" } ], "symlink_target": "" }
package pl.srw.billcalculator.util.strategy; import android.annotation.TargetApi; import android.app.Activity; import android.app.ActivityOptions; import android.content.Intent; import android.os.Build; import android.view.View; class JellyBeanTransitions extends Transitions { @Override @TargetApi(Build.VERSION_CODES.JELLY_BEAN) public void startActivity(Activity activity, Intent intent, View view) { ActivityOptions opts = ActivityOptions.makeScaleUpAnimation(view, 0, 0, view.getWidth(), view.getHeight()); activity.startActivity(intent, opts.toBundle()); } }
{ "content_hash": "255f489365669a40d3424b9e41c13165", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 115, "avg_line_length": 33.333333333333336, "alnum_prop": 0.7683333333333333, "repo_name": "sewerk/Bill-Calculator", "id": "30c79e227b3afdfff0220f0dd4281621f781e669", "size": "600", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/pl/srw/billcalculator/util/strategy/JellyBeanTransitions.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "427319" }, { "name": "Kotlin", "bytes": "313019" } ], "symlink_target": "" }
package main import ( "context" clientconnectorservices "cloud.google.com/go/beyondcorp/clientconnectorservices/apiv1" clientconnectorservicespb "cloud.google.com/go/beyondcorp/clientconnectorservices/apiv1/clientconnectorservicespb" "google.golang.org/api/iterator" ) func main() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. // It will require modifications to work: // - It may require correct/in-range values for request initialization. // - It may require specifying regional endpoints when creating the service client as shown in: // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options c, err := clientconnectorservices.NewClient(ctx) if err != nil { // TODO: Handle error. } defer c.Close() req := &clientconnectorservicespb.ListClientConnectorServicesRequest{ // TODO: Fill request struct fields. // See https://pkg.go.dev/cloud.google.com/go/beyondcorp/clientconnectorservices/apiv1/clientconnectorservicespb#ListClientConnectorServicesRequest. } it := c.ListClientConnectorServices(ctx, req) for { resp, err := it.Next() if err == iterator.Done { break } if err != nil { // TODO: Handle error. } // TODO: Use resp. _ = resp } } // [END beyondcorp_v1_generated_ClientConnectorServicesService_ListClientConnectorServices_sync]
{ "content_hash": "cf892ba9fc2f5393690d4217c8e8697d", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 150, "avg_line_length": 32.714285714285715, "alnum_prop": 0.75254730713246, "repo_name": "googleapis/google-cloud-go", "id": "b6b80f56ab0c181664f63096d5111b0ab0cedcdf", "size": "2149", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "internal/generated/snippets/beyondcorp/clientconnectorservices/apiv1/Client/ListClientConnectorServices/main.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "10349" }, { "name": "C", "bytes": "74" }, { "name": "Dockerfile", "bytes": "1841" }, { "name": "Go", "bytes": "7626642" }, { "name": "M4", "bytes": "43723" }, { "name": "Makefile", "bytes": "1455" }, { "name": "Python", "bytes": "718" }, { "name": "Shell", "bytes": "27309" } ], "symlink_target": "" }
 #pragma once #include <aws/ebs/EBS_EXPORTS.h> #include <aws/ebs/EBSRequest.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/core/utils/memory/stl/AWSVector.h> #include <aws/ebs/model/Tag.h> #include <utility> #include <aws/core/utils/UUID.h> namespace Aws { namespace EBS { namespace Model { /** */ class AWS_EBS_API StartSnapshotRequest : public EBSRequest { public: StartSnapshotRequest(); // Service request name is the Operation name which will send this request out, // each operation should has unique request name, so that we can get operation's name from this request. // Note: this is not true for response, multiple operations may have the same response name, // so we can not get operation's name from response. inline virtual const char* GetServiceRequestName() const override { return "StartSnapshot"; } Aws::String SerializePayload() const override; /** * <p>The size of the volume, in GiB. The maximum size is <code>16384</code> GiB * (16 TiB).</p> */ inline long long GetVolumeSize() const{ return m_volumeSize; } /** * <p>The size of the volume, in GiB. The maximum size is <code>16384</code> GiB * (16 TiB).</p> */ inline bool VolumeSizeHasBeenSet() const { return m_volumeSizeHasBeenSet; } /** * <p>The size of the volume, in GiB. The maximum size is <code>16384</code> GiB * (16 TiB).</p> */ inline void SetVolumeSize(long long value) { m_volumeSizeHasBeenSet = true; m_volumeSize = value; } /** * <p>The size of the volume, in GiB. The maximum size is <code>16384</code> GiB * (16 TiB).</p> */ inline StartSnapshotRequest& WithVolumeSize(long long value) { SetVolumeSize(value); return *this;} /** * <p>The ID of the parent snapshot. If there is no parent snapshot, or if you are * creating the first snapshot for an on-premises volume, omit this parameter.</p> * <p>If your account is enabled for encryption by default, you cannot use an * unencrypted snapshot as a parent snapshot. You must first create an encrypted * copy of the parent snapshot using <a * href="https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CopySnapshot.html">CopySnapshot</a>.</p> */ inline const Aws::String& GetParentSnapshotId() const{ return m_parentSnapshotId; } /** * <p>The ID of the parent snapshot. If there is no parent snapshot, or if you are * creating the first snapshot for an on-premises volume, omit this parameter.</p> * <p>If your account is enabled for encryption by default, you cannot use an * unencrypted snapshot as a parent snapshot. You must first create an encrypted * copy of the parent snapshot using <a * href="https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CopySnapshot.html">CopySnapshot</a>.</p> */ inline bool ParentSnapshotIdHasBeenSet() const { return m_parentSnapshotIdHasBeenSet; } /** * <p>The ID of the parent snapshot. If there is no parent snapshot, or if you are * creating the first snapshot for an on-premises volume, omit this parameter.</p> * <p>If your account is enabled for encryption by default, you cannot use an * unencrypted snapshot as a parent snapshot. You must first create an encrypted * copy of the parent snapshot using <a * href="https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CopySnapshot.html">CopySnapshot</a>.</p> */ inline void SetParentSnapshotId(const Aws::String& value) { m_parentSnapshotIdHasBeenSet = true; m_parentSnapshotId = value; } /** * <p>The ID of the parent snapshot. If there is no parent snapshot, or if you are * creating the first snapshot for an on-premises volume, omit this parameter.</p> * <p>If your account is enabled for encryption by default, you cannot use an * unencrypted snapshot as a parent snapshot. You must first create an encrypted * copy of the parent snapshot using <a * href="https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CopySnapshot.html">CopySnapshot</a>.</p> */ inline void SetParentSnapshotId(Aws::String&& value) { m_parentSnapshotIdHasBeenSet = true; m_parentSnapshotId = std::move(value); } /** * <p>The ID of the parent snapshot. If there is no parent snapshot, or if you are * creating the first snapshot for an on-premises volume, omit this parameter.</p> * <p>If your account is enabled for encryption by default, you cannot use an * unencrypted snapshot as a parent snapshot. You must first create an encrypted * copy of the parent snapshot using <a * href="https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CopySnapshot.html">CopySnapshot</a>.</p> */ inline void SetParentSnapshotId(const char* value) { m_parentSnapshotIdHasBeenSet = true; m_parentSnapshotId.assign(value); } /** * <p>The ID of the parent snapshot. If there is no parent snapshot, or if you are * creating the first snapshot for an on-premises volume, omit this parameter.</p> * <p>If your account is enabled for encryption by default, you cannot use an * unencrypted snapshot as a parent snapshot. You must first create an encrypted * copy of the parent snapshot using <a * href="https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CopySnapshot.html">CopySnapshot</a>.</p> */ inline StartSnapshotRequest& WithParentSnapshotId(const Aws::String& value) { SetParentSnapshotId(value); return *this;} /** * <p>The ID of the parent snapshot. If there is no parent snapshot, or if you are * creating the first snapshot for an on-premises volume, omit this parameter.</p> * <p>If your account is enabled for encryption by default, you cannot use an * unencrypted snapshot as a parent snapshot. You must first create an encrypted * copy of the parent snapshot using <a * href="https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CopySnapshot.html">CopySnapshot</a>.</p> */ inline StartSnapshotRequest& WithParentSnapshotId(Aws::String&& value) { SetParentSnapshotId(std::move(value)); return *this;} /** * <p>The ID of the parent snapshot. If there is no parent snapshot, or if you are * creating the first snapshot for an on-premises volume, omit this parameter.</p> * <p>If your account is enabled for encryption by default, you cannot use an * unencrypted snapshot as a parent snapshot. You must first create an encrypted * copy of the parent snapshot using <a * href="https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CopySnapshot.html">CopySnapshot</a>.</p> */ inline StartSnapshotRequest& WithParentSnapshotId(const char* value) { SetParentSnapshotId(value); return *this;} /** * <p>The tags to apply to the snapshot.</p> */ inline const Aws::Vector<Tag>& GetTags() const{ return m_tags; } /** * <p>The tags to apply to the snapshot.</p> */ inline bool TagsHasBeenSet() const { return m_tagsHasBeenSet; } /** * <p>The tags to apply to the snapshot.</p> */ inline void SetTags(const Aws::Vector<Tag>& value) { m_tagsHasBeenSet = true; m_tags = value; } /** * <p>The tags to apply to the snapshot.</p> */ inline void SetTags(Aws::Vector<Tag>&& value) { m_tagsHasBeenSet = true; m_tags = std::move(value); } /** * <p>The tags to apply to the snapshot.</p> */ inline StartSnapshotRequest& WithTags(const Aws::Vector<Tag>& value) { SetTags(value); return *this;} /** * <p>The tags to apply to the snapshot.</p> */ inline StartSnapshotRequest& WithTags(Aws::Vector<Tag>&& value) { SetTags(std::move(value)); return *this;} /** * <p>The tags to apply to the snapshot.</p> */ inline StartSnapshotRequest& AddTags(const Tag& value) { m_tagsHasBeenSet = true; m_tags.push_back(value); return *this; } /** * <p>The tags to apply to the snapshot.</p> */ inline StartSnapshotRequest& AddTags(Tag&& value) { m_tagsHasBeenSet = true; m_tags.push_back(std::move(value)); return *this; } /** * <p>A description for the snapshot.</p> */ inline const Aws::String& GetDescription() const{ return m_description; } /** * <p>A description for the snapshot.</p> */ inline bool DescriptionHasBeenSet() const { return m_descriptionHasBeenSet; } /** * <p>A description for the snapshot.</p> */ inline void SetDescription(const Aws::String& value) { m_descriptionHasBeenSet = true; m_description = value; } /** * <p>A description for the snapshot.</p> */ inline void SetDescription(Aws::String&& value) { m_descriptionHasBeenSet = true; m_description = std::move(value); } /** * <p>A description for the snapshot.</p> */ inline void SetDescription(const char* value) { m_descriptionHasBeenSet = true; m_description.assign(value); } /** * <p>A description for the snapshot.</p> */ inline StartSnapshotRequest& WithDescription(const Aws::String& value) { SetDescription(value); return *this;} /** * <p>A description for the snapshot.</p> */ inline StartSnapshotRequest& WithDescription(Aws::String&& value) { SetDescription(std::move(value)); return *this;} /** * <p>A description for the snapshot.</p> */ inline StartSnapshotRequest& WithDescription(const char* value) { SetDescription(value); return *this;} /** * <p>A unique, case-sensitive identifier that you provide to ensure the * idempotency of the request. Idempotency ensures that an API request completes * only once. With an idempotent request, if the original request completes * successfully. The subsequent retries with the same client token return the * result from the original successful request and they have no additional * effect.</p> <p>If you do not specify a client token, one is automatically * generated by the AWS SDK.</p> <p>For more information, see <a * href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-direct-api-idempotency.html"> * Idempotency for StartSnapshot API</a> in the <i>Amazon Elastic Compute Cloud * User Guide</i>.</p> */ inline const Aws::String& GetClientToken() const{ return m_clientToken; } /** * <p>A unique, case-sensitive identifier that you provide to ensure the * idempotency of the request. Idempotency ensures that an API request completes * only once. With an idempotent request, if the original request completes * successfully. The subsequent retries with the same client token return the * result from the original successful request and they have no additional * effect.</p> <p>If you do not specify a client token, one is automatically * generated by the AWS SDK.</p> <p>For more information, see <a * href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-direct-api-idempotency.html"> * Idempotency for StartSnapshot API</a> in the <i>Amazon Elastic Compute Cloud * User Guide</i>.</p> */ inline bool ClientTokenHasBeenSet() const { return m_clientTokenHasBeenSet; } /** * <p>A unique, case-sensitive identifier that you provide to ensure the * idempotency of the request. Idempotency ensures that an API request completes * only once. With an idempotent request, if the original request completes * successfully. The subsequent retries with the same client token return the * result from the original successful request and they have no additional * effect.</p> <p>If you do not specify a client token, one is automatically * generated by the AWS SDK.</p> <p>For more information, see <a * href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-direct-api-idempotency.html"> * Idempotency for StartSnapshot API</a> in the <i>Amazon Elastic Compute Cloud * User Guide</i>.</p> */ inline void SetClientToken(const Aws::String& value) { m_clientTokenHasBeenSet = true; m_clientToken = value; } /** * <p>A unique, case-sensitive identifier that you provide to ensure the * idempotency of the request. Idempotency ensures that an API request completes * only once. With an idempotent request, if the original request completes * successfully. The subsequent retries with the same client token return the * result from the original successful request and they have no additional * effect.</p> <p>If you do not specify a client token, one is automatically * generated by the AWS SDK.</p> <p>For more information, see <a * href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-direct-api-idempotency.html"> * Idempotency for StartSnapshot API</a> in the <i>Amazon Elastic Compute Cloud * User Guide</i>.</p> */ inline void SetClientToken(Aws::String&& value) { m_clientTokenHasBeenSet = true; m_clientToken = std::move(value); } /** * <p>A unique, case-sensitive identifier that you provide to ensure the * idempotency of the request. Idempotency ensures that an API request completes * only once. With an idempotent request, if the original request completes * successfully. The subsequent retries with the same client token return the * result from the original successful request and they have no additional * effect.</p> <p>If you do not specify a client token, one is automatically * generated by the AWS SDK.</p> <p>For more information, see <a * href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-direct-api-idempotency.html"> * Idempotency for StartSnapshot API</a> in the <i>Amazon Elastic Compute Cloud * User Guide</i>.</p> */ inline void SetClientToken(const char* value) { m_clientTokenHasBeenSet = true; m_clientToken.assign(value); } /** * <p>A unique, case-sensitive identifier that you provide to ensure the * idempotency of the request. Idempotency ensures that an API request completes * only once. With an idempotent request, if the original request completes * successfully. The subsequent retries with the same client token return the * result from the original successful request and they have no additional * effect.</p> <p>If you do not specify a client token, one is automatically * generated by the AWS SDK.</p> <p>For more information, see <a * href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-direct-api-idempotency.html"> * Idempotency for StartSnapshot API</a> in the <i>Amazon Elastic Compute Cloud * User Guide</i>.</p> */ inline StartSnapshotRequest& WithClientToken(const Aws::String& value) { SetClientToken(value); return *this;} /** * <p>A unique, case-sensitive identifier that you provide to ensure the * idempotency of the request. Idempotency ensures that an API request completes * only once. With an idempotent request, if the original request completes * successfully. The subsequent retries with the same client token return the * result from the original successful request and they have no additional * effect.</p> <p>If you do not specify a client token, one is automatically * generated by the AWS SDK.</p> <p>For more information, see <a * href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-direct-api-idempotency.html"> * Idempotency for StartSnapshot API</a> in the <i>Amazon Elastic Compute Cloud * User Guide</i>.</p> */ inline StartSnapshotRequest& WithClientToken(Aws::String&& value) { SetClientToken(std::move(value)); return *this;} /** * <p>A unique, case-sensitive identifier that you provide to ensure the * idempotency of the request. Idempotency ensures that an API request completes * only once. With an idempotent request, if the original request completes * successfully. The subsequent retries with the same client token return the * result from the original successful request and they have no additional * effect.</p> <p>If you do not specify a client token, one is automatically * generated by the AWS SDK.</p> <p>For more information, see <a * href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-direct-api-idempotency.html"> * Idempotency for StartSnapshot API</a> in the <i>Amazon Elastic Compute Cloud * User Guide</i>.</p> */ inline StartSnapshotRequest& WithClientToken(const char* value) { SetClientToken(value); return *this;} /** * <p>Indicates whether to encrypt the snapshot. To create an encrypted snapshot, * specify <code>true</code>. To create an unencrypted snapshot, omit this * parameter.</p> <p>If you specify a value for <b>ParentSnapshotId</b>, omit this * parameter.</p> <p>If you specify <code>true</code>, the snapshot is encrypted * using the CMK specified using the <b>KmsKeyArn</b> parameter. If no value is * specified for <b>KmsKeyArn</b>, the default CMK for your account is used. If no * default CMK has been specified for your account, the AWS managed CMK is used. To * set a default CMK for your account, use <a * href="https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ModifyEbsDefaultKmsKeyId.html"> * ModifyEbsDefaultKmsKeyId</a>.</p> <p>If your account is enabled for encryption * by default, you cannot set this parameter to <code>false</code>. In this case, * you can omit this parameter.</p> <p>For more information, see <a * href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-accessing-snapshot.html#ebsapis-using-encryption"> * Using encryption</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.</p> */ inline bool GetEncrypted() const{ return m_encrypted; } /** * <p>Indicates whether to encrypt the snapshot. To create an encrypted snapshot, * specify <code>true</code>. To create an unencrypted snapshot, omit this * parameter.</p> <p>If you specify a value for <b>ParentSnapshotId</b>, omit this * parameter.</p> <p>If you specify <code>true</code>, the snapshot is encrypted * using the CMK specified using the <b>KmsKeyArn</b> parameter. If no value is * specified for <b>KmsKeyArn</b>, the default CMK for your account is used. If no * default CMK has been specified for your account, the AWS managed CMK is used. To * set a default CMK for your account, use <a * href="https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ModifyEbsDefaultKmsKeyId.html"> * ModifyEbsDefaultKmsKeyId</a>.</p> <p>If your account is enabled for encryption * by default, you cannot set this parameter to <code>false</code>. In this case, * you can omit this parameter.</p> <p>For more information, see <a * href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-accessing-snapshot.html#ebsapis-using-encryption"> * Using encryption</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.</p> */ inline bool EncryptedHasBeenSet() const { return m_encryptedHasBeenSet; } /** * <p>Indicates whether to encrypt the snapshot. To create an encrypted snapshot, * specify <code>true</code>. To create an unencrypted snapshot, omit this * parameter.</p> <p>If you specify a value for <b>ParentSnapshotId</b>, omit this * parameter.</p> <p>If you specify <code>true</code>, the snapshot is encrypted * using the CMK specified using the <b>KmsKeyArn</b> parameter. If no value is * specified for <b>KmsKeyArn</b>, the default CMK for your account is used. If no * default CMK has been specified for your account, the AWS managed CMK is used. To * set a default CMK for your account, use <a * href="https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ModifyEbsDefaultKmsKeyId.html"> * ModifyEbsDefaultKmsKeyId</a>.</p> <p>If your account is enabled for encryption * by default, you cannot set this parameter to <code>false</code>. In this case, * you can omit this parameter.</p> <p>For more information, see <a * href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-accessing-snapshot.html#ebsapis-using-encryption"> * Using encryption</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.</p> */ inline void SetEncrypted(bool value) { m_encryptedHasBeenSet = true; m_encrypted = value; } /** * <p>Indicates whether to encrypt the snapshot. To create an encrypted snapshot, * specify <code>true</code>. To create an unencrypted snapshot, omit this * parameter.</p> <p>If you specify a value for <b>ParentSnapshotId</b>, omit this * parameter.</p> <p>If you specify <code>true</code>, the snapshot is encrypted * using the CMK specified using the <b>KmsKeyArn</b> parameter. If no value is * specified for <b>KmsKeyArn</b>, the default CMK for your account is used. If no * default CMK has been specified for your account, the AWS managed CMK is used. To * set a default CMK for your account, use <a * href="https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ModifyEbsDefaultKmsKeyId.html"> * ModifyEbsDefaultKmsKeyId</a>.</p> <p>If your account is enabled for encryption * by default, you cannot set this parameter to <code>false</code>. In this case, * you can omit this parameter.</p> <p>For more information, see <a * href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-accessing-snapshot.html#ebsapis-using-encryption"> * Using encryption</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.</p> */ inline StartSnapshotRequest& WithEncrypted(bool value) { SetEncrypted(value); return *this;} /** * <p>The Amazon Resource Name (ARN) of the AWS Key Management Service (AWS KMS) * customer master key (CMK) to be used to encrypt the snapshot. If you do not * specify a CMK, the default AWS managed CMK is used.</p> <p>If you specify a * <b>ParentSnapshotId</b>, omit this parameter; the snapshot will be encrypted * using the same CMK that was used to encrypt the parent snapshot.</p> <p>If * <b>Encrypted</b> is set to <code>true</code>, you must specify a CMK ARN. </p> */ inline const Aws::String& GetKmsKeyArn() const{ return m_kmsKeyArn; } /** * <p>The Amazon Resource Name (ARN) of the AWS Key Management Service (AWS KMS) * customer master key (CMK) to be used to encrypt the snapshot. If you do not * specify a CMK, the default AWS managed CMK is used.</p> <p>If you specify a * <b>ParentSnapshotId</b>, omit this parameter; the snapshot will be encrypted * using the same CMK that was used to encrypt the parent snapshot.</p> <p>If * <b>Encrypted</b> is set to <code>true</code>, you must specify a CMK ARN. </p> */ inline bool KmsKeyArnHasBeenSet() const { return m_kmsKeyArnHasBeenSet; } /** * <p>The Amazon Resource Name (ARN) of the AWS Key Management Service (AWS KMS) * customer master key (CMK) to be used to encrypt the snapshot. If you do not * specify a CMK, the default AWS managed CMK is used.</p> <p>If you specify a * <b>ParentSnapshotId</b>, omit this parameter; the snapshot will be encrypted * using the same CMK that was used to encrypt the parent snapshot.</p> <p>If * <b>Encrypted</b> is set to <code>true</code>, you must specify a CMK ARN. </p> */ inline void SetKmsKeyArn(const Aws::String& value) { m_kmsKeyArnHasBeenSet = true; m_kmsKeyArn = value; } /** * <p>The Amazon Resource Name (ARN) of the AWS Key Management Service (AWS KMS) * customer master key (CMK) to be used to encrypt the snapshot. If you do not * specify a CMK, the default AWS managed CMK is used.</p> <p>If you specify a * <b>ParentSnapshotId</b>, omit this parameter; the snapshot will be encrypted * using the same CMK that was used to encrypt the parent snapshot.</p> <p>If * <b>Encrypted</b> is set to <code>true</code>, you must specify a CMK ARN. </p> */ inline void SetKmsKeyArn(Aws::String&& value) { m_kmsKeyArnHasBeenSet = true; m_kmsKeyArn = std::move(value); } /** * <p>The Amazon Resource Name (ARN) of the AWS Key Management Service (AWS KMS) * customer master key (CMK) to be used to encrypt the snapshot. If you do not * specify a CMK, the default AWS managed CMK is used.</p> <p>If you specify a * <b>ParentSnapshotId</b>, omit this parameter; the snapshot will be encrypted * using the same CMK that was used to encrypt the parent snapshot.</p> <p>If * <b>Encrypted</b> is set to <code>true</code>, you must specify a CMK ARN. </p> */ inline void SetKmsKeyArn(const char* value) { m_kmsKeyArnHasBeenSet = true; m_kmsKeyArn.assign(value); } /** * <p>The Amazon Resource Name (ARN) of the AWS Key Management Service (AWS KMS) * customer master key (CMK) to be used to encrypt the snapshot. If you do not * specify a CMK, the default AWS managed CMK is used.</p> <p>If you specify a * <b>ParentSnapshotId</b>, omit this parameter; the snapshot will be encrypted * using the same CMK that was used to encrypt the parent snapshot.</p> <p>If * <b>Encrypted</b> is set to <code>true</code>, you must specify a CMK ARN. </p> */ inline StartSnapshotRequest& WithKmsKeyArn(const Aws::String& value) { SetKmsKeyArn(value); return *this;} /** * <p>The Amazon Resource Name (ARN) of the AWS Key Management Service (AWS KMS) * customer master key (CMK) to be used to encrypt the snapshot. If you do not * specify a CMK, the default AWS managed CMK is used.</p> <p>If you specify a * <b>ParentSnapshotId</b>, omit this parameter; the snapshot will be encrypted * using the same CMK that was used to encrypt the parent snapshot.</p> <p>If * <b>Encrypted</b> is set to <code>true</code>, you must specify a CMK ARN. </p> */ inline StartSnapshotRequest& WithKmsKeyArn(Aws::String&& value) { SetKmsKeyArn(std::move(value)); return *this;} /** * <p>The Amazon Resource Name (ARN) of the AWS Key Management Service (AWS KMS) * customer master key (CMK) to be used to encrypt the snapshot. If you do not * specify a CMK, the default AWS managed CMK is used.</p> <p>If you specify a * <b>ParentSnapshotId</b>, omit this parameter; the snapshot will be encrypted * using the same CMK that was used to encrypt the parent snapshot.</p> <p>If * <b>Encrypted</b> is set to <code>true</code>, you must specify a CMK ARN. </p> */ inline StartSnapshotRequest& WithKmsKeyArn(const char* value) { SetKmsKeyArn(value); return *this;} /** * <p>The amount of time (in minutes) after which the snapshot is automatically * cancelled if:</p> <ul> <li> <p>No blocks are written to the snapshot.</p> </li> * <li> <p>The snapshot is not completed after writing the last block of data.</p> * </li> </ul> <p>If no value is specified, the timeout defaults to <code>60</code> * minutes.</p> */ inline int GetTimeout() const{ return m_timeout; } /** * <p>The amount of time (in minutes) after which the snapshot is automatically * cancelled if:</p> <ul> <li> <p>No blocks are written to the snapshot.</p> </li> * <li> <p>The snapshot is not completed after writing the last block of data.</p> * </li> </ul> <p>If no value is specified, the timeout defaults to <code>60</code> * minutes.</p> */ inline bool TimeoutHasBeenSet() const { return m_timeoutHasBeenSet; } /** * <p>The amount of time (in minutes) after which the snapshot is automatically * cancelled if:</p> <ul> <li> <p>No blocks are written to the snapshot.</p> </li> * <li> <p>The snapshot is not completed after writing the last block of data.</p> * </li> </ul> <p>If no value is specified, the timeout defaults to <code>60</code> * minutes.</p> */ inline void SetTimeout(int value) { m_timeoutHasBeenSet = true; m_timeout = value; } /** * <p>The amount of time (in minutes) after which the snapshot is automatically * cancelled if:</p> <ul> <li> <p>No blocks are written to the snapshot.</p> </li> * <li> <p>The snapshot is not completed after writing the last block of data.</p> * </li> </ul> <p>If no value is specified, the timeout defaults to <code>60</code> * minutes.</p> */ inline StartSnapshotRequest& WithTimeout(int value) { SetTimeout(value); return *this;} private: long long m_volumeSize; bool m_volumeSizeHasBeenSet; Aws::String m_parentSnapshotId; bool m_parentSnapshotIdHasBeenSet; Aws::Vector<Tag> m_tags; bool m_tagsHasBeenSet; Aws::String m_description; bool m_descriptionHasBeenSet; Aws::String m_clientToken; bool m_clientTokenHasBeenSet; bool m_encrypted; bool m_encryptedHasBeenSet; Aws::String m_kmsKeyArn; bool m_kmsKeyArnHasBeenSet; int m_timeout; bool m_timeoutHasBeenSet; }; } // namespace Model } // namespace EBS } // namespace Aws
{ "content_hash": "e485b33e3786e3cc96ecaf11dd0b4261", "timestamp": "", "source": "github", "line_count": 555, "max_line_length": 136, "avg_line_length": 52.71351351351351, "alnum_prop": 0.6858080393765381, "repo_name": "jt70471/aws-sdk-cpp", "id": "c2c00f58855a7d65a03c38b3bc6e78956174a993", "size": "29375", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-cpp-sdk-ebs/include/aws/ebs/model/StartSnapshotRequest.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "13452" }, { "name": "C++", "bytes": "278594037" }, { "name": "CMake", "bytes": "653931" }, { "name": "Dockerfile", "bytes": "5555" }, { "name": "HTML", "bytes": "4471" }, { "name": "Java", "bytes": "302182" }, { "name": "Python", "bytes": "110380" }, { "name": "Shell", "bytes": "4674" } ], "symlink_target": "" }
<p align="center"> <a href="https://crates.io/crates/alga-derive"> <img src="http://meritbadge.herokuapp.com/alga-derive?style=flat-square" alt="crates.io"> </a> <a href="https://travis-ci.org/rustsim/alga"> <img src="https://travis-ci.org/rustsim/alga.svg?branch=master" alt="Build status"> </a> </p> <p align = "center"> <strong> <a href="https://docs.rs/alga-derive">Documentation</a> </strong> </p> alga-derive − automatic deriving of abstract algebra traits for Rust ======== **alga-derive** allows automatic deriving of traits provided by **alga**. It supports deriving following **alga** traits: - `AbstractQuasigroup` - `AbstractMonoid` - `AbstractSemigroup` - `AbstractGroup` - `AbstractGroupAbelian` - `AbstractRing` - `AbstractRingCommutative` - `AbstractField` The custom derive can also be used to generate **quickcheck** tests that check that algebraic properties are satisfied by the target of the derive.
{ "content_hash": "87a7c30537cc34f83d52a4390a643fc2", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 98, "avg_line_length": 30.46875, "alnum_prop": 0.6912820512820513, "repo_name": "sebcrozet/alga", "id": "67a516f50896428c432a3c1fb2b67a2b6cad902f", "size": "977", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "alga_derive/README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Rust", "bytes": "138418" }, { "name": "Shell", "bytes": "1120" } ], "symlink_target": "" }
package org.kuali.rice.krad.uif.container; import java.util.HashSet; import java.util.Set; import org.kuali.rice.krad.datadictionary.parse.BeanTag; import org.kuali.rice.krad.datadictionary.parse.BeanTagAttribute; import org.kuali.rice.krad.datadictionary.parse.BeanTags; import org.kuali.rice.krad.uif.UifConstants; import org.kuali.rice.krad.uif.component.Component; import org.kuali.rice.krad.uif.util.LifecycleElement; import org.kuali.rice.krad.uif.widget.Accordion; /** * Accordion group class used to stack groups by there header titles in an accordion layout. * * @author Kuali Rice Team ([email protected]) */ @BeanTags({@BeanTag(name = "accordionGroup", parent = "Uif-AccordionGroup"), @BeanTag(name = "accordionSection", parent = "Uif-AccordionSection"), @BeanTag(name = "accordionSubSection", parent = "Uif-AccordionSubSection"), @BeanTag(name = "disclosureAccordionSection", parent = "Uif-Disclosure-AccordionSection"), @BeanTag(name = "disclosureAccordionSubSection", parent = "Uif-Disclosure-AccordionSubSection")}) public class AccordionGroup extends GroupBase { private static final long serialVersionUID = 7230145606607506418L; private Accordion accordionWidget; /** * {@inheritDoc} */ @Override public void performFinalize(Object model, LifecycleElement parent) { super.performFinalize(model, parent); this.addDataAttribute(UifConstants.DataAttributes.TYPE, "Uif-AccordionGroup"); } /** * Only groups are supported for this group. * * {@inheritDoc} */ @Override public Set<Class<? extends Component>> getSupportedComponents() { Set<Class<? extends Component>> supportedComponents = new HashSet<Class<? extends Component>>(); supportedComponents.add(Group.class); return supportedComponents; } /** * Gets the widget which contains any configuration for the accordion widget component used to render * this AccordionGroup. * * @return the accordionWidget */ @BeanTagAttribute public Accordion getAccordionWidget() { return this.accordionWidget; } /** * @see AccordionGroup#getAccordionWidget() */ public void setAccordionWidget(Accordion accordionWidget) { this.accordionWidget = accordionWidget; } }
{ "content_hash": "f02c4c0c4405d1d96c303d26bf622a12", "timestamp": "", "source": "github", "line_count": 69, "max_line_length": 105, "avg_line_length": 35.15942028985507, "alnum_prop": 0.692085737840066, "repo_name": "ricepanda/rice-git3", "id": "1d7907c51c955642909aee726743bc989474fdbe", "size": "3061", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "rice-framework/krad-web-framework/src/main/java/org/kuali/rice/krad/uif/container/AccordionGroup.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "800079" }, { "name": "Groovy", "bytes": "2237959" }, { "name": "Java", "bytes": "35408880" }, { "name": "JavaScript", "bytes": "2665736" }, { "name": "PHP", "bytes": "15766" }, { "name": "Shell", "bytes": "13217" }, { "name": "XSLT", "bytes": "107818" } ], "symlink_target": "" }
using System.Collections.Generic; using System.Linq; namespace DotVVM.Framework.Compilation.Parser.Dothtml.Parser { public class HierarchyBuildingVisitor : IDothtmlSyntaxTreeVisitor { public int CursorPosition { get; set; } public DothtmlNode LastFoundNode { get; set; } public bool Condition(DothtmlNode node) { int tagEnd = node.EndPosition; if(node is DothtmlElementNode) { var element = node as DothtmlElementNode; tagEnd = element.GetContentEndPosition() + (element.CorrespondingEndTag?.Length ?? 0); } //This is also enough for RootNode return node.StartPosition <= CursorPosition && (CursorPosition < tagEnd || (node.Tokens.Last().Length == 0 && node.Tokens.Last().StartPosition == tagEnd)); } public void Visit(DothtmlAttributeNode attribute) { LastFoundNode = attribute; } public void Visit(DothtmlValueBindingNode bindingValue) { LastFoundNode = bindingValue; } public void Visit(DotHtmlCommentNode comment) { LastFoundNode = comment; } public void Visit(DothtmlDirectiveNode directive) { LastFoundNode = directive; } public void Visit(DothtmlLiteralNode literal) { LastFoundNode = literal; } public void Visit(DothtmlBindingNode binding) { LastFoundNode = binding; } public void Visit(DothtmlNameNode name) { LastFoundNode = name; } public void Visit(DothtmlValueTextNode textValue) { LastFoundNode = textValue; } public void Visit(DothtmlElementNode element) { LastFoundNode = element; } public void Visit(DothtmlRootNode root) { LastFoundNode = root; } public List<DothtmlNode> GetHierarchy() { return GetHierarchyPrivate().ToList(); } private IEnumerable<DothtmlNode> GetHierarchyPrivate() { DothtmlNode currentNode = LastFoundNode; while (currentNode != null) { yield return currentNode; currentNode = currentNode.ParentNode; } } } }
{ "content_hash": "09e8c6c7f87f27087e624a56604a5753", "timestamp": "", "source": "github", "line_count": 93, "max_line_length": 168, "avg_line_length": 26.086021505376344, "alnum_prop": 0.5696619950535862, "repo_name": "darilek/dotvvm", "id": "ca621e752881a046d86c19ea0db3b50aa9de2402", "size": "2428", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/DotVVM.Framework/Compilation/Parser/Dothtml/Parser/HierarchyBuildingVisitor.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "3088" }, { "name": "C#", "bytes": "2180984" }, { "name": "CSS", "bytes": "944" }, { "name": "JavaScript", "bytes": "778699" }, { "name": "PowerShell", "bytes": "7123" }, { "name": "TypeScript", "bytes": "100653" } ], "symlink_target": "" }
.revolver { position: relative; width: 100%; height: 100%; overflow: hidden; } .revolver { width: 100%; position: relative; } .revolver .revolver-item { display: none; border-width: 0 1px; width: 1000px !important; max-width: 9999px !important; width: auto !important; } .revolver .revolver-active { display: block; } /* * responsive-revolver * https://github.com/filamentgroup/responsive-revolver * * Copyright (c) 2012 Filament Group, Inc. * Licensed under the MIT, GPL licenses. */ .revolver-slide { position: relative; overflow: hidden; -webkit-transform: translate3d(0, 0, 0); -moz-transform: translate3d(0, 0, 0); -ms-transform: translate3d(0, 0, 0); -o-transform: translate3d(0, 0, 0); transform: translate3d(0, 0, 0); } .revolver-slide .revolver-item { position: absolute; left: 100%; top: 0; width: 100%; /* necessary for non-active slides */ display: block; /* overrides basic revolver styles */ z-index: 1; } .revolver-no-transition .revolver-item { -webkit-transition: none; -moz-transition: none; -ms-transition: none; -o-transition: none; transition: none; } .revolver-slide .revolver-active { left: 0; position: relative; z-index: 2; } .revolver-slide .revolver-in { left: 0; } .revolver-slide-reverse .revolver-out { left: 100%; } .revolver-slide .revolver-out, .revolver-slide-reverse .revolver-item, .revolver-slide-reverse .revolver-in { left: -100%; } .revolver-slide-reverse .revolver-active { left: 0; } .fadeout { -webkit-transition: opacity .25s ease-out; -moz-transition: opacity .25s ease-out; transition: opacity .25s ease-out; opacity: 0; }
{ "content_hash": "68b657e82ab2e17aa4e2f61459e1c126", "timestamp": "", "source": "github", "line_count": 80, "max_line_length": 55, "avg_line_length": 20.225, "alnum_prop": 0.6965389369592089, "repo_name": "filamentgroup/Revolver", "id": "fe7bfcef3543c35154a1f418142279ba89112884", "size": "1790", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/Revolver.css", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "6389" }, { "name": "HTML", "bytes": "976" }, { "name": "JavaScript", "bytes": "51950" } ], "symlink_target": "" }
/* eslint-disable */ import rangy from 'rangy' /** * Save a cursor position in the given input field to restore later. * * @param {obj} containerEl Dom Node of the input field * @return {obj} Object with the range of the seclection start & end */ export function saveSelection(containerEl) { var charIndex = 0, start = 0, end = 0, foundStart = false, stop = {}; var sel = rangy.getSelection(), range; function traverseTextNodes(node, range) { if (node.nodeType == 3) { if (!foundStart && node == range.startContainer) { start = charIndex + range.startOffset; foundStart = true; } if (foundStart && node == range.endContainer) { end = charIndex + range.endOffset; throw stop; } charIndex += node.length; } else { for (var i = 0, len = node.childNodes.length; i < len; ++i) { traverseTextNodes(node.childNodes[i], range); } } } if (sel.rangeCount) { try { traverseTextNodes(containerEl, sel.getRangeAt(0)); } catch (ex) { if (ex != stop) { throw ex; } } } return { start: start, end: end }; } /** * Restore a cursor position * * @param {obj} containerEl Dom Node of the input field * @param {obj} savedSel Saved object with range start & end vaues * @return {obj} Object with the range of the seclection start & end */ export function restoreSelection(containerEl, savedSel) { var charIndex = 0, range = rangy.createRange(), foundStart = false, stop = {}; range.collapseToPoint(containerEl, 0); function traverseTextNodes(node) { if (node.nodeType == 3) { var nextCharIndex = charIndex + node.length; if (!foundStart && savedSel.start >= charIndex && savedSel.start <= nextCharIndex) { range.setStart(node, savedSel.start - charIndex); foundStart = true; } if (foundStart && savedSel.end >= charIndex && savedSel.end <= nextCharIndex) { range.setEnd(node, savedSel.end - charIndex); throw stop; } charIndex = nextCharIndex; } else { for (var i = 0, len = node.childNodes.length; i < len; ++i) { traverseTextNodes(node.childNodes[i]); } } } try { traverseTextNodes(containerEl); } catch (ex) { if (ex == stop) { rangy.getSelection().setSingleRange(range); } else { throw ex; } } }
{ "content_hash": "b877203cce4be1b51fe74dd8753574a1", "timestamp": "", "source": "github", "line_count": 87, "max_line_length": 96, "avg_line_length": 30.942528735632184, "alnum_prop": 0.5408618127786032, "repo_name": "floscr/colorna.me", "id": "ea336020b29436400b144da4f161d27dc5bcf656", "size": "2692", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/components/VirtualInput/utils/cursorHelper.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1809" }, { "name": "HTML", "bytes": "1995" }, { "name": "JavaScript", "bytes": "129443" }, { "name": "Vue", "bytes": "13977" } ], "symlink_target": "" }
package ru.o2genum.howtosay; /** * Progress indicator view * * @author Andrey Moiseev */ import android.content.Context; import android.util.AttributeSet; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.view.View; import android.widget.ImageView; public class PendingView extends ImageView { Context context; Animation animation; public PendingView(Context context, AttributeSet attrs) { super(context, attrs); this.context = context; initializeUI(); } public PendingView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); this.context = context; initializeUI(); } @Override public void onFinishInflate() { initializeUI(); } @Override public void onVisibilityChanged(View v, int visibility) { initializeUI(); } public void initializeUI() { invalidate(); if(getVisibility() == View.VISIBLE) { animation = AnimationUtils.loadAnimation(context, R.anim.rotation); startAnimation(animation); } } public void showAnim() { setVisibility(View.VISIBLE); initializeUI(); } public void hideAnim() { if(animation != null) { clearAnimation(); } setVisibility(View.INVISIBLE); } public void onSizeChanged(int w, int h, int oldw, int oldh) { initializeUI(); } }
{ "content_hash": "8d2dad4461d6c3beab7787272da9d73b", "timestamp": "", "source": "github", "line_count": 68, "max_line_length": 75, "avg_line_length": 22.426470588235293, "alnum_prop": 0.6268852459016393, "repo_name": "gelahcem/HowToSay", "id": "75c93a619451d0ac94c445f038842e03b3b27111", "size": "2124", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/ru/o2genum/howtosay/PendingView.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "73283" } ], "symlink_target": "" }
using MyApp.Domain; using MyApp.Web.Mvc.Models; using MyApp.Repository; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MyApp.Web.Mvc.Controllers { public class HomeController : Controller { public ActionResult Index() { return View(); } } }
{ "content_hash": "0dd043730d237ae5d296232208afec6b", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 44, "avg_line_length": 18.94736842105263, "alnum_prop": 0.675, "repo_name": "antanta/MyApp", "id": "82b57be77aa2a150e2403537894226aba5ecf8eb", "size": "362", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "MyApp.Web.Mvc/Controllers/HomeController.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "534" }, { "name": "C#", "bytes": "239458" }, { "name": "CSS", "bytes": "160022" }, { "name": "HTML", "bytes": "129693" }, { "name": "JavaScript", "bytes": "3784878" }, { "name": "TypeScript", "bytes": "719576" } ], "symlink_target": "" }
4096 - The 4 Gigabyte Destiny ==== Creator: William Chang NetID: wkc10 Started: 08292014 Last Edited: 09252014 Approx hours worked: 20 Genre: 2048 Spinoff TA's consulted: Yu Zhou Lee, Cody Lieu Students consulted: Shreyas Bharadwaj, Mike Zhu, Jesse Ling Main contains the main function. Resources Used: Oracle documentation, http://carlfx.wordpress.com/2012/03/29/javafx-2-gametutorial-part-1/, StackOverflow Current found bugs: Potential Heap out of memory error if button is pressed on the Win screen. Because of a last minute if statement and constructor change, reaching 2048 on the minionLevel will not load the Boss page, however pressing 'b' will get you there regardless. Once you become invincible in a given level, you remain invincible. Project was fun. Could have been more specific about requirements and grading to determine what is a good vs. a bad final product. ---------------------------------------------------------------------------------------------------------------------------------- Backstory/Prologue (Imagine it scrolling up with epic music like in Star Wars): ---------------------------------------------------------------------------------------------------------------------------------- In a not so distant alternate square dimension... where bubbles, indiscriminantly assigned random integers, float aimlessly and with no purpose... and in which the strong eat and the weak are eaten... The holy numeral 2048 (A round thing who shall not be named) reigns supreme. However, legend fortells of a second coming... Welcome to the World of 4096 - The Gigabyte Destiny (The other round thing who lived) In this world... YOU (playa), are just one byte. Yes, one measly, bubble-shaped byte. You are 2048 times smaller than the holy numeral. You are miniscule. And another adjective that's a synonym of small. However, you hunger with dem' aspirations: To be big. To be bad. To be an ass? Kinda, but not really... More like... To be a BIG BADASS. And beat the highscore of that 2048 guy. And digivolve. And so you shall... it is your DESTINY! ---------------------------------------------------------------------------------------------------------------------------------- Gameplay: ---------------------------------------------------------------------------------------------------------------------------------- The square shaped, 2D world in "4096" is populated with labeled bubbles. All occupy their preordained numerical states (as assigned randomly by the creator: ME, the great Will-ford) from 1, 2, 4, 8, ... , 1024. The other assigned blocks in this obstacleless world float downward thoughtlessly, with little to no hopes of the American Dream (aka meritocracy or that social climbing capitalist thing). You can absorb other blocks, others can't absorb you. You lose if your value drops below 1. Level 1: As a little 1 block with a hefty appetite, your goal in the game is to consume other blocks of equal assignment, which in turn doubles your own assignment, until you reach the hefty size of 2048. The single 1024 block in the level lies at the top, so if you hit it early, you lose. You must wait until you are 1024 as well, then attempt to consume it. It may seem easy, but so did FlappyBird. Level B0$$: Completing the task, you move on to the next level to showdown against the bully 2048, in an attempt to consume him as well, and break his record. This time, there is only the 2048 bubble. However, unlike the easy pickings of the first level, the boss level incurs the wrath of the 2048 bubble, which you cannot absorb. Shooting up the 2048 block, however, and then consuming the 2048 gives you a new high score, and you beat the game and achieve your destiny. ---------------------------------------------------------------------------------------------------------------------------------- Characters: ---------------------------------------------------------------------------------------------------------------------------------- 1 - YOU!!! (NEO, Luke Skywalker, Bob the Builder, whoever you are). This bubble guy has an appetite for destiny. 2 - Aimless dude with no destiny 4 - " 8 - " : . 2048 - THE ENEMY! ---------------------------------------------------------------------------------------------------------------------------------- Controls: Arrow Keys corresponding to directions for movement around the square world. Press once to go at constant velocity. >BossLevel: Press 'Shift' to shoot the 2048 block. Cheats: >Main Menu Press: 'b' - Load BossLevel. >>>>In either game level 'i' - Become Invincible 'b' - Load BossLevel. 'w' - Win the game. ---------------------------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------------------- Credits: ---------------------------------------------------------------------------------------------------------------------------------- Game - Kind of like 2048, except fighter mode, like the bacteria game. Puns - Many different movie references. CSS design of blocks and font taken from https://github.com/brunoborges/fx2048.git Tile class to make 2048 look authentic. All code other than this image information and boiler code from Robert Duvall, was created by William Chang.
{ "content_hash": "aad4b23ad7c65a16f38f5de7444ce835", "timestamp": "", "source": "github", "line_count": 132, "max_line_length": 320, "avg_line_length": 41.13636363636363, "alnum_prop": 0.5762430939226519, "repo_name": "thewillchang/4096_Game", "id": "0c3d843a0c490313172f4eac0a3e6b000e2fe6bb", "size": "5430", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "7063" }, { "name": "Java", "bytes": "30175" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_17) on Tue Apr 02 08:44:35 MDT 2013 --> <title>CreateRecipeActivity</title> <meta name="date" content="2013-04-02"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="CreateRecipeActivity"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../ca/ualberta/cs/oneclick_cookbook/package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/CreateRecipeActivity.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../ca/ualberta/cs/oneclick_cookbook/Constants.html" title="class in ca.ualberta.cs.oneclick_cookbook"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../ca/ualberta/cs/oneclick_cookbook/DeleteCache.html" title="class in ca.ualberta.cs.oneclick_cookbook"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?ca/ualberta/cs/oneclick_cookbook/CreateRecipeActivity.html" target="_top">Frames</a></li> <li><a href="CreateRecipeActivity.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">ca.ualberta.cs.oneclick_cookbook</div> <h2 title="Class CreateRecipeActivity" class="title">Class CreateRecipeActivity</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>Activity</li> <li> <ul class="inheritance"> <li>ca.ualberta.cs.oneclick_cookbook.CreateRecipeActivity</li> </ul> </li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <hr> <br> <pre>public class <span class="strong">CreateRecipeActivity</span> extends Activity</pre> <div class="block">Class that acts as the controller for the create recipe screen If the current recipe variable in GlobalApplication is set, does not create a new recipe, rather edits the current one. Is responsible for unsetting the current recipe for future instances to work correctly.</div> <dl><dt><span class="strong">Author:</span></dt> <dd>Kenneth Armstrong</dd></dl> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><strong><a href="../../../../ca/ualberta/cs/oneclick_cookbook/CreateRecipeActivity.html#CreateRecipeActivity()">CreateRecipeActivity</a></strong>()</code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method_summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span>Methods</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../ca/ualberta/cs/oneclick_cookbook/CreateRecipeActivity.html#clickHandler(View)">clickHandler</a></strong>(View&nbsp;v)</code> <div class="block">Function that handles the clicks from a user.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../ca/ualberta/cs/oneclick_cookbook/CreateRecipeActivity.html#onAddIngredients()">onAddIngredients</a></strong>()</code> <div class="block">Function that is called when the user clicks on the add ingredients button.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../ca/ualberta/cs/oneclick_cookbook/CreateRecipeActivity.html#onAddPhoto()">onAddPhoto</a></strong>()</code> <div class="block">Function that is called when the user clicks on the add photo button.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><strong><a href="../../../../ca/ualberta/cs/oneclick_cookbook/CreateRecipeActivity.html#onCreateOptionsMenu(Menu)">onCreateOptionsMenu</a></strong>(Menu&nbsp;menu)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../ca/ualberta/cs/oneclick_cookbook/CreateRecipeActivity.html#onDelete()">onDelete</a></strong>()</code> <div class="block">Function that is called when the user clicks on the delete button of the recipe.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../ca/ualberta/cs/oneclick_cookbook/CreateRecipeActivity.html#onDone()">onDone</a></strong>()</code> <div class="block">Function that is called when the user clicks on the done button of the recipe.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><strong><a href="../../../../ca/ualberta/cs/oneclick_cookbook/CreateRecipeActivity.html#onKeyDown(int, KeyEvent)">onKeyDown</a></strong>(int&nbsp;keyCode, KeyEvent&nbsp;event)</code> <div class="block">Overides the back key action.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../ca/ualberta/cs/oneclick_cookbook/CreateRecipeActivity.html#onNextPhoto()">onNextPhoto</a></strong>()</code> <div class="block">Function that is called when the user clicks on the image button.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../ca/ualberta/cs/oneclick_cookbook/CreateRecipeActivity.html#onRemovePhoto()">onRemovePhoto</a></strong>()</code> <div class="block">Function that is called when the user clicks on the remove photo button.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../ca/ualberta/cs/oneclick_cookbook/CreateRecipeActivity.html#onResume()">onResume</a></strong>()</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../ca/ualberta/cs/oneclick_cookbook/CreateRecipeActivity.html#saveInfo()">saveInfo</a></strong>()</code> <div class="block">Function that saves the users text that they have entered.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../ca/ualberta/cs/oneclick_cookbook/CreateRecipeActivity.html#setImage(ca.ualberta.cs.oneclick_cookbook.Recipe)">setImage</a></strong>(<a href="../../../../ca/ualberta/cs/oneclick_cookbook/Recipe.html" title="class in ca.ualberta.cs.oneclick_cookbook">Recipe</a>&nbsp;recipe)</code> <div class="block">Function that sets the image for the recipe.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../ca/ualberta/cs/oneclick_cookbook/CreateRecipeActivity.html#setInfo(ca.ualberta.cs.oneclick_cookbook.Recipe)">setInfo</a></strong>(<a href="../../../../ca/ualberta/cs/oneclick_cookbook/Recipe.html" title="class in ca.ualberta.cs.oneclick_cookbook">Recipe</a>&nbsp;recipe)</code> <div class="block">Function that takes the info of the recipe being edited and puts in into the text fields.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../ca/ualberta/cs/oneclick_cookbook/CreateRecipeActivity.html#showMessage(java.lang.String)">showMessage</a></strong>(java.lang.String&nbsp;message)</code> <div class="block">Function that displays a message to the user in the current activity</div> </td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="CreateRecipeActivity()"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>CreateRecipeActivity</h4> <pre>public&nbsp;CreateRecipeActivity()</pre> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method_detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="onResume()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>onResume</h4> <pre>public&nbsp;void&nbsp;onResume()</pre> </li> </ul> <a name="onKeyDown(int, KeyEvent)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>onKeyDown</h4> <pre>public&nbsp;boolean&nbsp;onKeyDown(int&nbsp;keyCode, KeyEvent&nbsp;event)</pre> <div class="block">Overides the back key action. Kills the current activity, as normal, but also sets the current recipe to null so that future recipes work properly.</div> </li> </ul> <a name="setInfo(ca.ualberta.cs.oneclick_cookbook.Recipe)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setInfo</h4> <pre>public&nbsp;void&nbsp;setInfo(<a href="../../../../ca/ualberta/cs/oneclick_cookbook/Recipe.html" title="class in ca.ualberta.cs.oneclick_cookbook">Recipe</a>&nbsp;recipe)</pre> <div class="block">Function that takes the info of the recipe being edited and puts in into the text fields. This is used to restore any info the user may have had prior to leaving the activity.</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>recipe</code> - The recipe to set the info for</dd></dl> </li> </ul> <a name="saveInfo()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>saveInfo</h4> <pre>public&nbsp;void&nbsp;saveInfo()</pre> <div class="block">Function that saves the users text that they have entered.</div> </li> </ul> <a name="setImage(ca.ualberta.cs.oneclick_cookbook.Recipe)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setImage</h4> <pre>public&nbsp;void&nbsp;setImage(<a href="../../../../ca/ualberta/cs/oneclick_cookbook/Recipe.html" title="class in ca.ualberta.cs.oneclick_cookbook">Recipe</a>&nbsp;recipe)</pre> <div class="block">Function that sets the image for the recipe.</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>recipe</code> - The recipe that it currently being viewed</dd></dl> </li> </ul> <a name="onCreateOptionsMenu(Menu)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>onCreateOptionsMenu</h4> <pre>public&nbsp;boolean&nbsp;onCreateOptionsMenu(Menu&nbsp;menu)</pre> </li> </ul> <a name="clickHandler(View)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>clickHandler</h4> <pre>public&nbsp;void&nbsp;clickHandler(View&nbsp;v)</pre> <div class="block">Function that handles the clicks from a user. Calls the appropriate function depending on the buton the user clicked.</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>v</code> - The view of the button that was clicked</dd></dl> </li> </ul> <a name="onAddIngredients()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>onAddIngredients</h4> <pre>public&nbsp;void&nbsp;onAddIngredients()</pre> <div class="block">Function that is called when the user clicks on the add ingredients button.</div> </li> </ul> <a name="onDone()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>onDone</h4> <pre>public&nbsp;void&nbsp;onDone()</pre> <div class="block">Function that is called when the user clicks on the done button of the recipe. Exits the create recipe activity.</div> </li> </ul> <a name="onDelete()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>onDelete</h4> <pre>public&nbsp;void&nbsp;onDelete()</pre> <div class="block">Function that is called when the user clicks on the delete button of the recipe.</div> </li> </ul> <a name="showMessage(java.lang.String)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>showMessage</h4> <pre>public&nbsp;void&nbsp;showMessage(java.lang.String&nbsp;message)</pre> <div class="block">Function that displays a message to the user in the current activity</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>message</code> - The message to display</dd></dl> </li> </ul> <a name="onAddPhoto()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>onAddPhoto</h4> <pre>public&nbsp;void&nbsp;onAddPhoto()</pre> <div class="block">Function that is called when the user clicks on the add photo button. Derived from the CameraDemo on eClass.</div> </li> </ul> <a name="onRemovePhoto()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>onRemovePhoto</h4> <pre>public&nbsp;void&nbsp;onRemovePhoto()</pre> <div class="block">Function that is called when the user clicks on the remove photo button.</div> </li> </ul> <a name="onNextPhoto()"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>onNextPhoto</h4> <pre>public&nbsp;void&nbsp;onNextPhoto()</pre> <div class="block">Function that is called when the user clicks on the image button. Cycles through the photo's in the recipe.</div> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../ca/ualberta/cs/oneclick_cookbook/package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/CreateRecipeActivity.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../ca/ualberta/cs/oneclick_cookbook/Constants.html" title="class in ca.ualberta.cs.oneclick_cookbook"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../ca/ualberta/cs/oneclick_cookbook/DeleteCache.html" title="class in ca.ualberta.cs.oneclick_cookbook"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?ca/ualberta/cs/oneclick_cookbook/CreateRecipeActivity.html" target="_top">Frames</a></li> <li><a href="CreateRecipeActivity.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
{ "content_hash": "cd82b9b91f44a57766504fe6500563d5", "timestamp": "", "source": "github", "line_count": 490, "max_line_length": 334, "avg_line_length": 37.13673469387755, "alnum_prop": 0.667967247348464, "repo_name": "cserafin/CMPUT301W13T14", "id": "00d6cdbeb9295e00b250f524c95a61c8de96a15d", "size": "18197", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/ca/ualberta/cs/oneclick_cookbook/CreateRecipeActivity.html", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "129001" }, { "name": "Shell", "bytes": "2598" } ], "symlink_target": "" }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class FinishLevel : MonoBehaviour { public GameObject managerScene; private LevelManager script; public Light myLight; public bool changeIntesity = false; public float intesitySpeed = 1.0f; public float maxIntesity = 10.0f; float startTime; private void Start() { managerScene = GameObject.FindWithTag("Manager"); script = managerScene.GetComponent<LevelManager>(); myLight = GetComponent<Light>(); startTime = Time.time; } void OnTriggerEnter(Collider other) { if (other.tag == "Player") { changeIntesity = true; script.LoadNext(); } if(changeIntesity) { myLight.intensity = Mathf.PingPong(Time.time * intesitySpeed, maxIntesity); } } }
{ "content_hash": "00b1248b9cbe465a40aee3bba7453006", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 87, "avg_line_length": 22.525, "alnum_prop": 0.6259711431742508, "repo_name": "azsumas/HorrorShooter", "id": "6e9e48830754fa038eced8198a35a3bca950db6b", "size": "903", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Assets/Scripts/Environment/FinishLevel.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "2251111" }, { "name": "GLSL", "bytes": "7138" }, { "name": "HLSL", "bytes": "314729" }, { "name": "ShaderLab", "bytes": "200985" }, { "name": "Smalltalk", "bytes": "116" } ], "symlink_target": "" }
import spinalcordtoolbox as sct def main(): print(sct.__version__) if __name__ == "__main__": main()
{ "content_hash": "a21860e4a0b776511230c21ded52ff27", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 31, "avg_line_length": 12.555555555555555, "alnum_prop": 0.5663716814159292, "repo_name": "neuropoly/spinalcordtoolbox", "id": "6eafa777b39dff7d5a6d6418a43268c86f10521f", "size": "136", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spinalcordtoolbox/scripts/sct_version.py", "mode": "33261", "license": "mit", "language": [ { "name": "C", "bytes": "5931" }, { "name": "C++", "bytes": "629016" }, { "name": "CMake", "bytes": "7000" }, { "name": "CSS", "bytes": "1237" }, { "name": "Dockerfile", "bytes": "293" }, { "name": "HTML", "bytes": "11480" }, { "name": "JavaScript", "bytes": "3171" }, { "name": "MATLAB", "bytes": "120557" }, { "name": "Python", "bytes": "2052822" }, { "name": "Rich Text Format", "bytes": "1619" }, { "name": "Shell", "bytes": "61227" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="ar-SA"> <title>Plug-n-Hack | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>بحث</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
{ "content_hash": "291c2a01a7b70ad32314e900aeaa51fc", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 184, "avg_line_length": 25.5, "alnum_prop": 0.6367389060887513, "repo_name": "secdec/zap-extensions", "id": "09564fdbf51dcc1077f55e1e65ca107311565628", "size": "972", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "addOns/plugnhack/src/main/javahelp/org/zaproxy/zap/extension/plugnhack/resources/help_ar_SA/helpset_ar_SA.hs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "86316" }, { "name": "C", "bytes": "1448" }, { "name": "ColdFusion", "bytes": "9100" }, { "name": "HTML", "bytes": "1623696" }, { "name": "Haskell", "bytes": "263320" }, { "name": "Java", "bytes": "1149358" }, { "name": "JavaScript", "bytes": "737" }, { "name": "PHP", "bytes": "111175" }, { "name": "Perl", "bytes": "16431" }, { "name": "Shell", "bytes": "10000" } ], "symlink_target": "" }
namespace gfx { enum class VectorIconId; } namespace net { class X509Certificate; } // This class is the model used by the toolbar, location bar and autocomplete // edit. It populates its states from the current navigation entry retrieved // from the navigation controller returned by GetNavigationController(). class ToolbarModel { public: virtual ~ToolbarModel(); // Returns the text to be displayed in the toolbar for the current page. // This will have been formatted for display to the user. // - If the current page's URL is a search URL for the user's default search // engine, the query will be extracted and returned for display instead // of the URL. // - Otherwise, the text will contain the URL returned by GetFormattedURL(). virtual base::string16 GetText() const = 0; // Returns a formatted URL for display in the toolbar. The formatting // includes: // - Some characters may be unescaped. // - The scheme and/or trailing slash may be dropped. // If |prefix_end| is non-NULL, it is set to the length of the pre-hostname // portion of the resulting URL. virtual base::string16 GetFormattedURL(size_t* prefix_end) const = 0; // Some search URLs bundle a special "corpus" param that we can extract and // display next to users' search terms in cases where we'd show the search // terms instead of the URL anyway. For example, a Google image search might // show the corpus "Images:" plus a search string. This is only used on // mobile. virtual base::string16 GetCorpusNameForMobile() const = 0; // Returns the URL of the current navigation entry. virtual GURL GetURL() const = 0; // Returns true if a call to GetText() would successfully replace the URL // with search terms. If |ignore_editing| is true, the result reflects the // underlying state of the page without regard to any user edits that may be // in progress in the omnibox. virtual bool WouldPerformSearchTermReplacement(bool ignore_editing) const = 0; // Returns the security level that the toolbar should display. If // |ignore_editing| is true, the result reflects the underlying state of the // page without regard to any user edits that may be in progress in the // omnibox. virtual security_state::SecurityStateModel::SecurityLevel GetSecurityLevel( bool ignore_editing) const = 0; // Returns true if a call to GetText() would return something other than the // URL because of search term replacement. bool WouldReplaceURL() const; // Returns the resource_id of the icon to show to the left of the address, // based on the current URL. When search term replacement is active, this // returns a search icon. This doesn't cover specialized icons while the // user is editing; see OmniboxView::GetIcon(). virtual int GetIcon() const = 0; // Like GetIcon(), but gets the vector asset ID. virtual gfx::VectorIconId GetVectorIcon() const = 0; // Returns the name of the EV cert holder. This returns an empty string if // the security level is not EV_SECURE. virtual base::string16 GetEVCertName() const = 0; // Returns whether the URL for the current navigation entry should be // in the location bar. virtual bool ShouldDisplayURL() const = 0; // Whether the text in the omnibox is currently being edited. void set_input_in_progress(bool input_in_progress) { input_in_progress_ = input_in_progress; } bool input_in_progress() const { return input_in_progress_; } // Whether URL replacement should be enabled. void set_url_replacement_enabled(bool enabled) { url_replacement_enabled_ = enabled; } bool url_replacement_enabled() const { return url_replacement_enabled_; } protected: ToolbarModel(); private: bool input_in_progress_; bool url_replacement_enabled_; DISALLOW_COPY_AND_ASSIGN(ToolbarModel); }; #endif // COMPONENTS_TOOLBAR_TOOLBAR_MODEL_H_
{ "content_hash": "df37de745f9d76e85398f02a5c8674ce", "timestamp": "", "source": "github", "line_count": 100, "max_line_length": 80, "avg_line_length": 39.16, "alnum_prop": 0.725485188968335, "repo_name": "heke123/chromium-crosswalk", "id": "d0aee6b5596410c0a2f947e0a022b1880eff057f", "size": "4354", "binary": false, "copies": "13", "ref": "refs/heads/master", "path": "components/toolbar/toolbar_model.h", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
"use strict" // TOOD: would like to extend String class UUID { constructor(uuid){ this.$type = "m.UUID"; if(uuid.$type && uuid.$type == this.$type){ this.uuid = uuid.uuid }else { this.uuid = uuid } } static zero(){ new UUID('00000000-0000-0000-0000-000000000000') } valueOf(){ return this.uuid } } class Integer extends Number{ constructor(x){ super(x) this.val = x this.$type = "m.Integer"; } valueOf(){ return this.val } } class Float extends Number{ constructor(x){ super(x) this.val = x this.$type = "m.Float"; } valueOf(){ return this.val } } class Double extends Number{ constructor(x){ super(x) this.val = x this.$type = "m.Double"; } valueOf(){ return this.val } } class Long extends Number{ constructor(x){ super(x) this.val = x this.$type = "m.Long"; } valueOf(){ return this.val } } class List extends Array{ constructor(){ super() this.$type = "m.List"; } } class Option{ static Some(val){ return new Some(val) } static None() { return new None() } } class Some extends Option{ constructor(val){ super() this.val = val this.$type = "m.Some"; } get(){ return this.val } valueOf(){ return this.val } map(f){ return f(this.val); } foreach(f){ f(this.val); } } class None extends Option{ constructor(){ super() this.$type = "m.None"; } map(f){} foreach(f){} } /** * @class Type * Helper class for doing runtime type checking and error reporting. */ class Type{ static check(inst, type, fail){ if( ! (inst instanceof type) ) { if(type.type && inst.$type && type.type() == inst.$type){// FIXME: this is a hack until we have our own mapper. return inst } if(typeof fail === "undefined") throw new Error('[ERROR] Type Check failed. ' + typeof(inst) + ' is not ' + type) else fail(new Error('[ERROR] Type Check failed. ' + typeof(inst) + ' is not ' + type)) } return inst } } /** * @class Model * Base type for all `Model` types in the system. */ class Model{ /** * * @param type {String} the full class name of the type be instantiated. */ constructor(type){ this.$type = type; //console.log('created type: '+ type); } } /** * @namespace Auth */ let Auth = {}; Auth.zeroId = new UUID('00000000-0000-0000-0000-000000000000') /** * @class GetPrimaryProfile * @extends Model */ Auth.GetPrimaryProfile = class extends Model{ /** * Return the full class name of this type. * @returns {string} */ static type(){ return 'm.Auth$GetPrimaryProfile'} constructor(uid, orgId){ super(Auth.GetPrimaryProfile.type()); this.uuid = null this.orgId = null if(arguments.length) { this.uuid = uuid; this.orgId = orgId; } } } /** * @class OrganizationRoles * @extends Model * Construct an organization role. */ Auth.OrganizationRoles = class extends Model{ /** * Return the full class name of this type. * @returns {string} */ static type(){ return 'm.Auth$OrganizationRoles'} constructor(role){ super(Auth.OrganizationRoles.type()); this.name = null if(arguments.length) { this.name = role; } } /** * Return OrganizationRoles TEAM * @returns {OrganizationRoles} */ static team(){ return new OrganizationRoles("team"); } /** * Return OrganizationRoles ADMIN * @returns {OrganizationRoles} */ static admin(){ return new OrganizationRoles("admin"); } /** * Return OrganizationRoles OWNER * @returns {OrganizationRoles} */ static owner(){ return new OrganizationRoles("owner"); } /** * Return OrganizationRoles ORGANIZATION * @returns {OrganizationRoles} */ static organization(){ return new OrganizationRoles("organization"); } /** * Return OrganizationRoles GUEST * @returns {OrganizationRoles} */ static guest(){ return new OrganizationRoles("guest"); } } /** * @class Provider * @extends Model * A simple view of a provider for a user. Users can have many providers for many different organization. * Users will typically have 1 provider="conversant" per orgId. */ Auth.Provider = class extends Model{ /** * Return the full class name of this type. * @returns {string} */ static type(){ return 'm.Auth$Provider'} /** * * @param orgId {String} * @param source {String} * @param provider {String} * @param id {String} * @param role {Auth.OrganizationRoles} * @param fullName {String} */ constructor(orgId, source, provider, id, role, fullName){ super(Auth.Provider.type()) this.orgId = null this.source = null this.provider = null this.id = null this.role = null this.fullName = null if(arguments.length) { this.orgId = new UUID(orgId) this.source = new UUID(source) this.provider = new String(provider) this.id = new String(id) this.role = Type.check(role, Auth.OrganizationRoles) this.fullName = new String(fullName) } } } /** * @class Provider * @extends Model * A simple view of a provider for a user. Users can have many providers for many different organization. * Users will typically have 1 provider="conversant" per orgId. */ Auth.Bot = class extends Model{ /** * Return the full class name of this type. * @returns {string} */ static type(){ return 'm.Auth$Bot'} /** * * @param orgId {String} * @param source {String} * @param provider {String} * @param id {String} * @param role {Auth.OrganizationRoles} * @param fullName {String} */ constructor(orgId, source, provider, id, role, fullName){ super(Auth.Bot.type()) this.orgId = null this.source = null this.provider = null this.id = null this.role = null this.fullName = null if(arguments.length) { this.orgId = new UUID(orgId) this.source = new UUID(source) this.provider = new String(provider) this.id = new String(id) this.role = Type.check(role, Auth.OrganizationRoles) this.fullName = new String(fullName) } } } /** * @class Role * @extends Model */ Auth.Role = class extends Model{ /** * Return the full class name of this type. * @returns {string} */ static type(){ return 'm.Auth$Role'} /** * * @param orgId {String} * @param source {String} * @param provider {String} * @param id {String} * @param role {Auth.OrganizationRoles} * @param fullName {String} */ constructor(orgId, source, provider, id, role, fullName){ super(Auth.Role.type()) this.orgId = null this.source = null this.provider = null this.id = null this.role = null this.fullName = null if(arguments.length) { this.orgId = new UUID(orgId) this.source = new UUID(source) this.provider = new String(provider) this.id = new String(id) this.role = Type.check(role, Auth.OrganizationRoles) this.fullName = new String(fullName) } } } /** * @class Organization * @extends Model * Organization Entity */ Auth.Organization = class extends Model{ /** * Return the full class name of this type. * @returns {string} */ static type(){ return 'm.Auth$Organization'} /** * * @param url {String} * @param name {String} * @param provider {Auth.Provider} * @param members [Auth.Provider[]] * @param settings {Map} */ constructor(url, name, provider, members, settings){ super(Auth.Provider.type()) this.url = null this.name = null this.provider = null this.members = null this.settings = null if(arguments.length) { this.url = new String(url) this.provider = Type.check(provider, Auth.Provider) this.members = members.map( p => Type.check(p,Auth.Provider) ) this.settings = settings } } } /** * @class PrimaryProfile * @extends Model * A list of profiles that are known for that user under that organiztion. * The primary will be a provider of type "conversant" */ Auth.PrimaryProfile = class extends Model{ /** * Return the full class name of this type. * @returns {string} */ static type(){ return 'm.Auth$PrimaryProfile'} /** * * @param primary {Auth.Provider} * @param providers {Auth.Provider[]} */ constructor(primary, providers){ super(Auth.PrimaryProfile.type()) this.primary = Type.check(primary,Auth.Provider) this.providers = providers.map( p => Type.check(p,Auth.Provider) ) } } /** * @class UserState * @extends Model * Used to pass a user action that requires synchronization by the system. */ Auth.UserState = class extends Model{ /** * Return the full class name of this type. * @returns {string} */ static type(){ return 'm.Auth$UserState'} //isOnline:Boolean, action:UserAction, state: Map[String, String] /** * * @param isOnline {Boolean} * @param action {Auth.UserState} * @param state {Map} */ constructor(isOnline, action, state){ super(Auth.UserState.type()) this.isOnline = null this.action = null this.state = null if(arguments.length) { this.isOnline = isOnline this.action = Type.check(action, Auth.UserAction) this.state = state } } } /** * @class UserAction * @extends Model * Some User level event that requies syncing. */ Auth.UserAction = class extends Model{ /** * Return the full class name of this type. * @returns {string} */ static type(){ return 'm.Auth$UserAction'} /** * * @param action {String} */ constructor(action){ super(Auth.UserAction.type()) this.action = null if(arguments.length) { this.action = new String(action) } } /** * None User Action * @returns {Auth.UserAction} */ static none(){ return Auth.UserAction("none") } /** * typing User Action * @returns {Auth.UserAction} */ static typing(){ return Auth.UserAction("typing") } /** * online User Action * @returns {Auth.UserAction} */ static online(){ return Auth.UserAction("online") } /** * presence User Action * @returns {Auth.UserAction} */ static presence(){ return Auth.UserAction("presence") } /** * offline User Action * @returns {Auth.UserAction} */ static offline(){ return Auth.UserAction("offline") } /** * collaborationEnter User Action * @returns {Auth.UserAction} */ static collaborationEnter(){ return Auth.UserAction("collaborationEnter") } } /** * @namespace Entities */ let Entities = {}; /** * @class NamedEntity * @extends Model */ Entities.NamedEntity = class extends Model{ /** * Return the full class name of this type. * @returns {string} */ /** * * @param uri {String} * @param token {String} */ constructor(type, uri, token){ super(type) this.uri = null this.token = null if( arguments.length > 1) { this.uri = new String(uri) this.token = new String(token) } } } /** * @class LocationEntity * @extends NamedEntity */ Entities.LocationEntity = class extends Entities.NamedEntity{ /** * Return the full class name of this type. * @returns {string} */ static type(){ return 'm.Entities$LocationEntity'} /** * * @param uri {String} * @param token {String} */ constructor(uri, token){ if(arguments.length) { super(Entities.LocationEntity.type(), uri, token) }else{ super(Entities.LocationEntity.type()) } } } /** * @class OrganizationEntity * @extends NamedEntity */ Entities.OrganizationEntity = class extends Entities.NamedEntity{ /** * Return the full class name of this type. * @returns {string} */ static type(){ return 'm.Entities$OrganizationEntity'} /** * * @param uri {String} * @param token {String} */ constructor(uri, token){ if(arguments.length) { super(Entities.OrganizationEntity.type(), uri, token) }else{ super(Entities.OrganizationEntity.type()) } } } /** * @class PersonEntity * @extends NamedEntity */ Entities.PersonEntity = class extends Entities.NamedEntity{ /** * Return the full class name of this type. * @returns {string} */ static type(){ return 'm.Entities$PersonEntity'} /** * * @param uri {String} * @param token {String} */ constructor(uri, token){ if(arguments.length) { super(Entities.PersonEntity.type(), uri, token) }else{ super(Entities.PersonEntity.type()) } } } /** * @namespace Collaboration */ let Collaboration = {}; /** * @class PlayerState * @extends Model */ Collaboration.PlayerState = class extends Model{ /** * Return the full class name of this type. * @returns {string} */ static type(){ return 'm.Collaboration$PlayerState'} /** * * @param action {String} */ constructor(state){ super(Collaboration.PlayerState.type()) this.state = null if(arguments.length) { this.state = new Integer(state) } } /** * UNSTARTED PlayerState * @returns {Collaboration.PlayerState} */ static UNSTARTED(){ return Collaboration.PlayerState(-1) } /** * ENDED PlayerState * @returns {Collaboration.PlayerState} */ static ENDED(){ return Collaboration.PlayerState(0) } /** * PLAYING PlayerState * @returns {Collaboration.PlayerState} */ static PLAYING(){ return Collaboration.PlayerState(1) } /** * PAUSED PlayerState * @returns {Collaboration.PlayerState} */ static PAUSED(){ return Collaboration.PlayerState(2) } /** * BUFFERING PlayerState * @returns {Collaboration.PlayerState} */ static BUFFERING(){ return Collaboration.PlayerState(3) } /** * CUED PlayerState * @returns {Collaboration.PlayerState} */ static CUED(){ return Collaboration.PlayerState(5) } } /** * @class View * @extends Model */ Collaboration.View = class extends Model{ /** * * @param id {UUID} * @param collaborationId {UUID} * @param app {Apps.App} * @param resource {Resource.Resource} * @param key {String} * @param entities {Entities.Entity[]} */ constructor(type, id, collaborationId, app, resource, key, entities){ super(type) this.id = null this.collaborationId = null this.app = null this.resource = null this.key = null this.entities = new Set() if(arguments.length > 1) { this.id = new UUID(id) this.collaborationId = new UUID(collaborationId) this.app = Type.check(app, Apps.App) this.resource = Type.check(resource, Resource.Resource) this.key = new String(key) // FIXME: Set does not define "map" this.entities = entities } } } /** * @class UrlView * @extends View */ Collaboration.UrlView = class extends Collaboration.View{ /** * Return the full class name of this type. * @returns {string} */ static type(){ return 'm.Collaboration$UrlView'} /** * * @param collaborationId {UUID} * @param app {Apps.App} * @param resource {Resource.Resource} * @param key {String} * @param entities {Entities.Entity[]} */ constructor(collaborationId, app, resource, key, entities){ if(arguments.length) { super(Collaboration.UrlView.type(), '00000000-0000-0000-0000-000000000000', collaborationId, app, resource, key, entities) }else{ super(Collaboration.UrlView.type()) } } } /** * @class DocumentView * @extends View */ Collaboration.DocumentView = class extends Collaboration.View{ /** * Return the full class name of this type. * @returns {string} */ static type(){ return 'm.Collaboration$DocumentView'} /** * * @param collaborationId {UUID} * @param app {Apps.App} * @param resource {Resource.Resource} * @param key {String} * @param entities {Entities.Entity[]} * @param page {Int} */ constructor(collaborationId, app, resource, key, entities, sampleTimeMs, playerState){ if(arguments.length) { super(Collaboration.DocumentView.type(), '00000000-0000-0000-0000-000000000000', collaborationId, app, resource, key, entities, page) this.page = page }else{ super(Collaboration.DocumentView.type()) this.page = null } } } /** * @class VideoView * @extends View */ Collaboration.VideoView = class extends Collaboration.View{ /** * Return the full class name of this type. * @returns {string} */ static type(){ return 'm.Collaboration$VideoView'} /** * * @param collaborationId {UUID} * @param app {Apps.App} * @param resource {Resource.Resource} * @param key {String} * @param entities {Entities.Entity[]} * @param sampleTimeMs {Double} * @param playerState {Conversant.PlayerState} */ constructor(collaborationId, app, resource, key, entities, sampleTimeMs, playerState){ if(arguments.length) { super(Collaboration.VideoView.type(), '00000000-0000-0000-0000-000000000000', collaborationId, app, resource, key, entities, sampleTimeMs, playerState) this.sampleTimeMs = sampleTimeMs this.playerState = Type.check(playerState, Collaboration.PlayerState) }else{ super(Collaboration.VideoView.type()) this.sampleTimeMs = null this.playerState = null } } } /** * @class ImageView * @extends View */ Collaboration.ImageView = class extends Collaboration.View{ /** * Return the full class name of this type. * @returns {string} */ static type(){ return 'm.Collaboration$ImageView'} /** * * @param collaborationId {UUID} * @param app {Apps.App} * @param resource {Resource.Resource} * @param key {String} * @param entities {Entities.Entity[]} * @param transform {Geom.Transform3d} */ constructor(collaborationId, app, resource, key, entities, transform){ if(arguments.length) { super(Collaboration.ImageView.type(), '00000000-0000-0000-0000-000000000000', collaborationId, app, resource, key, entities, transform) this.transform = Type.check(transform, Geom.Transform3d) }else{ super(Collaboration.ImageView.type()) this.transform = null } } } /** * @class GLView * @extends View */ Collaboration.GLView = class extends Collaboration.View{ /** * Return the full class name of this type. * @returns {string} */ static type(){ return 'm.Collaboration$GLView'} /** * * @param collaborationId {UUID} * @param app {Apps.App} * @param resource {Resource.Resource} * @param key {String} * @param entities {Entities.Entity[]} * @param transform {Geom.Transform3d} */ constructor(collaborationId, app, resource, key, entities, transform){ if(arguments.length) { super(Collaboration.GLView.type(), '00000000-0000-0000-0000-000000000000', collaborationId, app, resource, key, entities, transform) this.transform = Type.check(transform, Geom.Transform3d) }else{ super(Collaboration.GLView.type()) this.transform = null } } } /** * @class MapView * @extends View */ Collaboration.MapView = class extends Collaboration.View{ /** * Return the full class name of this type. * @returns {string} */ static type(){ return 'm.Collaboration$MapView'} /** * * @param collaborationId {UUID} * @param app {Apps.App} * @param resource {Resource.Resource} * @param key {String} * @param entities {Entities.Entity[]} * @param lat {Double} * @param lng {Double} * @param zoom {Double} * @param markers {String} * @param update {String} * @param address {String} * @param name {String} */ constructor(collaborationId, app, resource, key, entities, lat, lng, zoom, markers, update, address, name){ if(arguments.length) { super(Collaboration.MapView.type(), '00000000-0000-0000-0000-000000000000', collaborationId, app, resource, key, entities, transform) this.lat = lat this.lng = lng this.zoom = zoom this.markers = markers this.update = update this.address = address this.name = name }else{ super(Collaboration.MapView.type()) this.lat = null this.lng = null this.zoom = null this.markers = null this.update = null this.address = null this.name = null } } } /** * @class SyncViewEvent * @extends Model * Application Event to Sync the View state. */ Collaboration.SyncViewEvent = class extends Model{ /** * Return the full class name of this type. * @returns {string} */ static type(){ return 'm.Collaboration$SyncViewEvent'} /** * * @param collaborationId {String} * @param orgId {String} * @param provider {Auth.Provider} * @param viewerState {Collaboration.View} */ constructor(collaborationId, orgId, provider, viewerState){ super(Collaboration.SyncViewEvent.type()) this.collaborationId = null this.orgId = null this.provider = null this.viewerState = null if(arguments.length) { this.collaborationId = new UUID(collaborationId) this.orgId = new UUID(orgId) this.provider = Type.check(provider, Auth.Provider) this.viewerState = viewerState } } } /** * @class SyncUserEvent * @extends Model * System level event for passing user state. */ Collaboration.SyncUserEvent = class extends Model{ /** * Return the full class name of this type. * @returns {string} */ static type(){ return 'm.Collaboration$SyncUserEvent'} /** * * @param collaborationId {String} * @param orgId {String} * @param provider {Auth.Provider} * @param userState {Auth.UserState} */ constructor(collaborationId, orgId, provider, userState){ super(Collaboration.SyncUserEvent.type()) this.collaborationId = null this.orgId = null this.provider = null this.userState = null if(arguments.length) { this.collaborationId = new UUID(collaborationId) this.orgId = new UUID(orgId) this.provider = Type.check(provider, Auth.Provider) this.userState = Type.check(userState, Auth.UserState) } } } /** * @class Notification * @extends Model */ Collaboration.Notification = class extends Model{ /** * Return the full class name of this type. * @returns {string} */ static type(){ return 'm.Collaboration$Notification'} /** * * @param providerKey {String} * @param rules {Collaboration.NotificationRule[]} */ constructor(providerKey, rules){ super(Collaboration.Notification.type()) this.providerKey = null this.rules = null if(arguments.length) { this.providerKey = new String(providerKey) // TOOD: rules [NotificationRule] } } } /** * @class Collaboration * @extends Model */ Collaboration.Collaboration = class extends Model{ /** * Return the full class name of this type. * @returns {string} */ /** * * @param id {String} * @param orgId {String} * @param members {Auth.Provider[]} * @param notifications {Collaboration.Notification[]} * @param name OPTIONAL {String} * @param avatarUrl OPTIONAL {String} * @param cover OPTIONAL {String} * @param content {Collaboration.Content[]} * @param settings {Map} */ constructor(type, id, orgId, members, notifications, name, avatarUrl, cover, content, settings){ super(type) this.id = null this.orgId = null this.members = null this.notifications = null this.name = null this.avatarUrl = null this.cover = null this.content = null this.settings = null console.log('arguments.length',arguments.length) if( arguments.length > 1) { this.id = new UUID(id) this.orgId = new UUID(orgId) this.members = members.map((m) => Type.check(m, Auth.Provider)) this.notifications = Type.check(notifications, Collaboration.Notification) this.name = typeof name === "undefined" ? null : new String(name) this.avatarUrl = avatarUrl this.cover = cover this.content = content.map((c) => Type.check(c, Collaboration.Content)) this.settings = settings } } } /** * @class CollaborationAdHoc * @extends Collaboration */ Collaboration.CollaborationAdHoc = class extends Collaboration.Collaboration{ /** * Return the full class name of this type. * @returns {string} */ static type(){ return 'm.Collaboration$CollaborationAdHoc'} /** * * @param id {String} * @param orgId {String} * @param members {Auth.Provider[]} * @param notifications {Collaboration.Notification[]} * @param name OPTIONAL {String} * @param avatarUrl OPTIONAL {String} * @param cover OPTIONAL {String} * @param content {Collaboration.Content[]} * @param settings {Map} */ constructor(id, orgId, members, notifications, name, avatarUrl, cover, content, settings){ if(arguments.length) { super(Collaboration.CollaborationAdHoc.type(), id, orgId, members, notifications, name, avatarUrl, cover, content, settings) }else{ super(Collaboration.CollaborationAdHoc.type()) } } } /** * @class CollaborationGroup * @extends Collaboration */ Collaboration.CollaborationGroup = class extends Collaboration.Collaboration{ /** * Return the full class name of this type. * @returns {string} */ static type(){ return 'm.Collaboration$CollaborationGroup'} /** * * @param id {String} * @param orgId {String} * @param members {Auth.Provider[]} * @param notifications {Collaboration.Notification[]} * @param name OPTIONAL {String} * @param avatarUrl OPTIONAL {String} * @param cover OPTIONAL {String} * @param content {Collaboration.Content[]} * @param settings {Map} */ constructor(id, orgId, members, notifications, name, avatarUrl, cover, content, settings){ if(arguments.length) { super(Collaboration.CollaborationGroup.type(), id, orgId, members, notifications, name, avatarUrl, cover, content, settings) }else{ super(Collaboration.CollaborationGroup.type()) } } } /** * @class CollaborationCustomer * @extends Collaboration */ Collaboration.CollaborationCustomer = class extends Collaboration.Collaboration{ /** * Return the full class name of this type. * @returns {string} */ static type(){ return 'm.Collaboration$CollaborationCustomer'} /** * * @param id {String} * @param orgId {String} * @param members {Auth.Provider[]} * @param notifications {Collaboration.Notification[]} * @param name OPTIONAL {String} * @param avatarUrl OPTIONAL {String} * @param cover OPTIONAL {String} * @param content {Collaboration.Content[]} * @param settings {Map} */ constructor(id, orgId, members, notifications, name, avatarUrl, cover, content, settings){ if(arguments.length) { super(Collaboration.CollaborationCustomer.type(), id, orgId, members, notifications, name, avatarUrl, cover, content, settings) }else{ super(Collaboration.CollaborationCustomer.type()) } } } /** * @class CollaborationContact * @extends Collaboration */ Collaboration.CollaborationContact = class extends Collaboration.Collaboration{ /** * Return the full class name of this type. * @returns {string} */ static type(){ return 'm.Collaboration$CollaborationContact'} /** * * @param id {String} * @param members {Auth.Provider[]} * @param notifications {Collaboration.Notification[]} * @param name OPTIONAL {String} * @param avatarUrl OPTIONAL {String} * @param cover OPTIONAL {String} * @param content {Collaboration.Content[]} * @param settings {Map} */ constructor(id, members, notifications, name, avatarUrl, cover, content, settings){ if(arguments.length) { super(Collaboration.CollaborationContact.type(), id, m.Auth.zeroId, members, notifications, name, avatarUrl, cover, content, settings) }else{ super(Collaboration.CollaborationContact.type()) } } } /** * @class CollaborationConversation * @extends Collaboration */ Collaboration.CollaborationConversation = class extends Collaboration.Collaboration{ /** * Return the full class name of this type. * @returns {string} */ static type(){ return 'm.Collaboration$CollaborationConversation'} /** * * @param id {String} * @param members {Auth.Provider[]} * @param notifications {Collaboration.Notification[]} * @param name OPTIONAL {String} * @param avatarUrl OPTIONAL {String} * @param cover OPTIONAL {String} * @param content {Collaboration.Content[]} * @param settings {Map} */ constructor(id, members, notifications, name, avatarUrl, cover, content, settings){ if(arguments.length) { super(Collaboration.CollaborationConversation.type(), id, m.Auth.zeroId, members, notifications, name, avatarUrl, cover, content, settings) }else{ super(Collaboration.CollaborationConversation.type()) } } } /** * @class CollaborationChannel * @extends Collaboration */ Collaboration.CollaborationChannel = class extends Collaboration.Collaboration{ /** * Return the full class name of this type. * @returns {string} */ static type(){ return 'm.Collaboration$CollaborationChannel'} /** * * @param id {String} * @param orgId {String} * @param members {Auth.Provider[]} * @param notifications {Collaboration.Notification[]} * @param name Option{String} * @param avatarUrl OPTIONAL {String} * @param cover OPTIONAL {String} * @param content {Collaboration.Content[]} * @param settings {Map} */ constructor(id, orgId, members, notifications, name, avatarUrl, cover, content, settings){ if(arguments.length) { super(Collaboration.CollaborationChannel.type(), id, orgId, members, notifications, name, avatarUrl, cover, content, settings) }else{ super(Collaboration.CollaborationChannel.type()) } } } /** * @class Content * @extends Model */ Collaboration.Content = class extends Model{ /** * * @param id {String} * @param collaborationId {String} * @param orgId {String} * @param timestamp {String} * @param authors {Auth.Provider[]} * @param seen {Auth.Provider[]} * @param message {Collaboration.Message} * @param viewId {UUID} */ constructor(type, id, collaborationId, orgId, timestamp, authors, seen, message, viewId){ super(type) this.id = null this.collaborationId = null this.orgId = null this.timestamp = null this.authors = null this.seen = null this.message = null this.viewId = null if(arguments.length > 1) { this.id = new UUID(id) this.collaborationId = new UUID(collaborationId) this.orgId = new UUID(orgId) this.timestamp = new String(timestamp) // FIXME: Set does not define "map" //this.authors = authors.map((a) => Type.check(a, Auth.Provider)) this.authors = authors //this.seen = seen.map((s) => Type.check(s, Auth.Provider)) this.seen = seen this.message = message this.viewId = new UUID(viewId) } } } /** * @class ContentMsg * @extends Content */ Collaboration.ContentMsg = class extends Collaboration.Content{ /** * Return the full class name of this type. * @returns {string} */ static type(){ return 'm.Collaboration$ContentMsg'} /** * * @param id {String} * @param collaborationId {String} * @param orgId {String} * @param timestamp {String} * @param authors {Auth.Provider[]} * @param seen {Auth.Provider[]} * @param sentiment Option{String} * @param nlp Option{String} * @param ner {Entities.NamedEntity[]} * @param message {Collaboration.Message} * @param viewId {UUID} */ constructor(id, collaborationId, orgId, timestamp, authors, seen, sentiment, nlp, ner, message, viewId){ if(arguments.length) { super(Collaboration.ContentMsg.type(),id, collaborationId, orgId, timestamp, authors, seen, message, viewId) this.sentiment = sentiment this.nlp = nlp //this.ner = ner.map((s) => Type.check(s, Entities.NamedEntity)) // FIXME: Set does not have "map" defined on it.. this.ner = ner }else{ super(Collaboration.ContentMsg.type()) this.sentiment = null this.nlp = null this.ner = null } } } /** * @class ContentLinkCard * @extends Content */ Collaboration.ContentLinkCard = class extends Collaboration.Content{ /** * Return the full class name of this type. * @returns {string} */ static type(){ return 'm.Collaboration$ContentLinkCard'} /** * * @param id {String} * @param collaborationId {String} * @param orgId {String} * @param timestamp {String} * @param authors {Auth.Provider[]} * @param seen {Auth.Provider[]} * @param message {Collaboration.Message} * @param entityUri {String} * @param viewId {UUID} * @param meta {ETL.Meta} */ constructor(id, collaborationId, orgId, timestamp, authors, seen, message, entityUri, viewId, meta){ if(arguments.length) { super(Collaboration.ContentLinkCard.type(),id, collaborationId, orgId, timestamp, authors, seen, message, viewId) this.entityUri = new String(entityUri) this.meta = Type.check(s, ETL.EntityMeta) }else{ super(Collaboration.ContentLinkCard.type()) this.entityUri = null this.meta = null } } } /** * @class ContentNotification * @extends Content */ Collaboration.ContentNotification = class extends Collaboration.Content{ /** * Return the full class name of this type. * @returns {string} */ static type(){ return 'm.Collaboration$ContentNotification'} /** * * @param id {String} * @param collaborationId {String} * @param orgId {String} * @param timestamp {String} * @param authors {Auth.Provider[]} * @param seen {Auth.Provider[]} * @param message {Collaboration.Message} * @param viewId {UUID} * @param severity {Collaboration.NotificationLevel} * @param icon {String} */ constructor(id, collaborationId, orgId, timestamp, authors, seen, message, viewId, severity, icon){ if(arguments.length) { super(Collaboration.ContentNotification.type(),id, collaborationId, orgId, timestamp, authors, seen, message, viewId) this.severity = Type.check(severity, Collaboration.NotificationLevel) this.icon = new String(icon) }else{ super(Collaboration.ContentNotification.type()) this.severity = null this.icon = null } } } /** * @class ContentAppEvent * @extends Content */ Collaboration.ContentAppEvent = class extends Collaboration.Content{ /** * Return the full class name of this type. * @returns {string} */ static type(){ return 'm.Collaboration$ContentAppEvent'} /** * * @param id {String} * @param collaborationId {String} * @param orgId {String} * @param timestamp {String} * @param authors {Auth.Provider[]} * @param seen {Auth.Provider[]} * @param message {Collaboration.Message} * @param viewId {UUID} * @param coverImg {String} * @param actions Set{Apps.App[]} */ constructor(id, collaborationId, orgId, timestamp, authors, seen, message, viewId, coverImg, actions){ if(arguments.length) { super(Collaboration.ContentAppEvent.type(),id, collaborationId, orgId, timestamp, authors, seen, message, viewId) this.coverImg = new String(coverImg) //this.actions = actions.map((s) => Type.check(s, Apps.App)) this.actions = actions }else{ super(Collaboration.ContentAppEvent.type()) this.coverImg = null this.actions = null } } } /** * @class NotificationLevel * @extends Model */ Collaboration.NotificationLevel = class extends Model{ /** * Return the full class name of this type. * @returns {string} */ static type(){ return 'm.Collaboration$NotificationLevel'} /** * @param severity {String} */ constructor( severity ){ super(Collaboration.NotificationLevel.type()) this.severity = null if(arguments.length) { this.severity = new String(severity) } } static info() { new NotificationLevel("info") } static warning() { new NotificationLevel("warning") } static error(){ new NotificationLevel("error")} } /** * @class Message * @extends Model */ Collaboration.Message = class extends Model{ /** * * @param text {String} * @param mentions {Auth.Provider[]} */ constructor(type, text, mentions){ super(type) this.text = null this.mentions = null if(arguments.length > 1) { this.text = new String(text) // FIXME: no "map" on Set //this.mentions = mentions.map((a) => Type.check(a, Auth.Provider)) this.mentions = mentions } } } /** * @class MessageBasic * @extends Message */ Collaboration.MessageBasic = class extends Collaboration.Message{ /** * Return the full class name of this type. * @returns {string} */ static type(){ return 'm.Collaboration$MessageBasic'} /** * * @param text {String} * @param mentions {Auth.Provider[]} */ constructor(text, mentions){ if(arguments.length) { super(Collaboration.MessageBasic.type(), text, mentions) }else{ super(Collaboration.MessageBasic.type()) } } } /** * @class BroadcastContent * @extends Model */ Collaboration.BroadcastContent = class extends Model{ /** * Return the full class name of this type. * @returns {string} */ static type(){ return 'm.Collaboration$BroadcastContent'} /** * * @param content {Collaboration.Content} * @param view Option{Collaboration.View} */ constructor(content, view){ super(Collaboration.BroadcastContent.type()) this.content = null this.view = null if(arguments.length) { this.content = content this.view = view } } } /** * @namespace Apps */ let Apps = {}; /** * @class App * @extends Model * Identifies an application of the system. */ Apps.App = class extends Model{ /** * Return the full class name of this type. * @returns {string} */ static type(){ return 'm.Apps$App'} /** * * @param id {String} * @param name {String} * @param icon {String} * @param origin {String} The origin fo the iframe that the app will be hosted in * @param entry {String} The entry point for the application * @param args {String} */ constructor(id, name, icon, origin, entry, args){ super(Apps.App.type()) this.id = new String(id) this.name = new String(name) this.icon = new String(icon) this.origin = new String(origin) this.entry = new String(entry) this.args = args } static info(){ new Apps.App("info","Chat Info", "fa fa-info ", "apps.conversant.im", "https://apps.conversant.im/app/info", {}) } static invite(){ new Apps.App("invite","Add People", "fa fa-user-plus ", "apps.conversant.im", "https://apps.conversant.im/app/invite", {}) } static drive(){ new Apps.App("drive","Drive", "fa fa-folder ", "apps.conversant.im", "https://apps.conversant.im/app/drive", {}) } static webCall(){ new Apps.App("call","Web Call", "fa fa-phone ", "*.conversant.im", "https://apps.conversant.im/app/call", {}) } static youtube(){ new Apps.App("youtube","YouTube", "fa fa-youtube ", "apps.conversant.im", "https://apps.conversant.im/app/youtube", {}) } static map(){ new Apps.App("map","Maps", "fa fa-map-marker", "apps.conversant.im", "https://apps.conversant.im/app/map", {}) } static image(){ new Apps.App("image","Image Viewer", "fa fa-picture-o", "apps.conversant.im", "https://apps.conversant.im/app/image", {}) } static giffy(){ new Apps.App("giffy","Giffy", "fa fa-file-o", "apps.conversant.im", "https://apps.conversant.im/app/giffy", {}) } } /** * @class AppMode * @extends Model * */ Apps.AppMode = class extends Model{ /** * Return the full class name of this type. * @returns {string} */ static type(){ return 'm.Apps$AppMode'} /** * * @param mode {String} mode the app is to run in */ constructor(mode){ super(Apps.AppMode.type()) this.mode = null if(arguments.length){ this.mode = new String(mode) } } static syncApp(){ new Apps.AppMode("syncApp") } static collaborationApp(){ new Apps.AppMode("collaborationApp") } static standAloneApp(){ new Apps.AppMode("standAloneApp") } } /** * @class Launch * @extends Model * */ Apps.Launch = class extends Model{ /** * Return the full class name of this type. * @returns {string} */ static type(){ return 'm.Apps$Launch'} /** * * @param app {Apps.App} App to load * @param url {String} url to send to app * @param mode {Apps.Mode} The mode the app is expected to handle */ constructor(load, url, mode){ super(Apps.Launch.type()) this.load = null this.url = null this.mode = null if(arguments.length){ this.app = Type.check(app, Apps.App) this.url = new String(url) this.mode = Type.check(mode, Apps.AppMode) } } } /** * @class Init * @extends Model * Signal the host that the app is ready for initialization. */ Apps.Init = class extends Model{ /** * Return the full class name of this type. * @returns {string} */ static type(){ return 'm.Apps$Init'} /** * * @param appId {String} Your app id to initialize * @param mode {Apps.AppMode} mode you app is running in. */ constructor(appId, mode){ super(Apps.Init.type()) this.appId = new String(appId) this.mode = Type.check(mode, Apps.AppMode) } } /** * @class InitApp * @extends Model */ Apps.InitApp = class extends Model{ /** * Return the full class name of this type. * @returns {string} */ static type(){ return 'm.Apps$InitApp'} /** * * @param app {Apps.App} * @param restoreState {Collaboration.View} OPTIONAL The view state that is to be restored * @param mode {Apps.AppMode} */ constructor(app, restoreState, mode){ super(Apps.InitApp.type()) this.app = null this.restoreState = null if(arguments.length) { this.app = Type.check(app, Apps.App) this.restoreState = restoreState } } } /** * @class InitProfile * @extends Model */ Apps.InitProvider = class extends Model{ /** * Return the full class name of this type. * @returns {string} */ static type(){ return 'm.Apps$InitProvider'} /** * * @param provider {Auth.Provider} */ constructor(provider){ super(Apps.InitProvider.type()) this.provider = null if(arguments.length) { this.provider = Type.check(provider, Auth.Provider) } } } /** * @class InitOrganization * @extends Model */ Apps.InitOrganization = class extends Model{ /** * Return the full class name of this type. * @returns {string} */ static type(){ return 'm.Apps$InitOrganization'} /** * * @param organization {Auth.Organization} */ constructor(organization){ super(Apps.InitOrganization.type()) this.organization = null if(arguments.length) { this.organization = Type.check(organization, Auth.Organization) } } } /** * @class InitCollaboration * @extends Model */ Apps.InitCollaboration = class extends Model{ /** * Return the full class name of this type. * @returns {string} */ static type(){ return 'm.Apps$InitCollaboration'} /** * * @param collaboration Option{Collaboration.Collaboration} */ constructor(collaboration){ super(Apps.InitCollaboration.type()) this.collaboration = null if(arguments.length) { this.collaboration = collaboration } } } /** * @class InitTeam * @extends Model */ Apps.InitTeam = class extends Model{ /** * Return the full class name of this type. * @returns {string} */ static type(){ return 'm.Apps$InitTeam'} /** * * @param team {Collaboration.SyncUserEvent[]} */ constructor(team){ super(Apps.InitTeam.type()) this.team = null if(arguments.length) { this.team = team.map((t) => Type.check(t, Collaboration.SyncUserEvent)) } } } /** * @class InitPeers * @extends Model */ Apps.InitPeers = class extends Model{ /** * Return the full class name of this type. * @returns {string} */ static type(){ return 'm.Apps$InitPeers'} /** * * @param peers {Peers.PeerState[]} */ constructor(peers, room){ super(Apps.InitPeers.type()) this.peers = null this.room = null if(arguments.length) { this.peers = peers.map((p) => Type.check(t, Peers.PeerState)) this.room = new String(room) } } } /** * @namespace Peers */ let Peers = {}; /** * @class PeerState * @extends Model */ Peers.PeerState = class extends Model{ /** * Return the full class name of this type. * @returns {string} */ static type(){ return 'm.Peers$PeerState'} /** * @param provider {Auth.Provider} * @param collaborationId {String} * @param userAgent {String} * @param iceConnectionState {Peers.IceConnectionState} * @param signalingState {Peers.SignalingState} */ constructor( provider, collaborationId, userAgent, iceConnectionState, signalingState ){ super(Peers.PeerState.type()) this.provider = null this.collaborationId = null this.userAgent = null this.iceConnectionState = null this.signalingState = null if(arguments.length) { this.provider = null this.collaborationId = new String(collaborationId) this.userAgent = typeof userAgent === "undefined" ? null : new String(userAgent) this.iceConnectionState = Type.check(iceConnectionState, Peers.IceConnectionState) this.signalingState = Type.check(signalingState, Peers.SignalingState) } } } /** * @class IceConnectionState * @extends Model */ Peers.IceConnectionState = class extends Model{ /** * Return the full class name of this type. * @returns {string} */ static type(){ return 'm.Peers$IceConnectionState'} /** * @param state {String} */ constructor( state ){ super(Peers.IceConnectionState.type()) this.state = null if(arguments.length) { this.state = new String(state) } } static new() { new IceConnectionState("new") } static checking() { new IceConnectionState("checking") } static connected(){ new IceConnectionState("connected")} static completed(){ new IceConnectionState("completed")} static failed(){ new IceConnectionState("failed")} static disconnected(){ new IceConnectionState("disconnected")} static closed(){ new IceConnectionState("closed")} } /** * @class SignalingState * @extends Model */ Peers.SignalingState = class extends Model{ /** * Return the full class name of this type. * @returns {string} */ static type(){ return 'm.Peers$SignalingState'} /** * @param state {String} */ constructor( state ){ super(Peers.SignalingState.type()) this.state = null if(arguments.length) { this.state = new String(state) } } static stable() { new SignalingState("stable") } static haveLocalOffer() { new SignalingState("have-local-offer") } static haveLocalPranswer(){ new SignalingState("have-local-pranswer")} static haveRemotePranswer(){ new SignalingState("have-remote-pranswer")} static closed(){ new SignalingState("closed")} } /** * @namespace Resource */ let Resource = {}; /** * @class Resource * @extends Model */ Resource.Resource = class extends Model{ /** * Return the full class name of this type. * @returns {string} */ static type(){ return 'm.Resource$Resource'} /** * @param uri {String} * @param contentType {String} * @param thumbnail {String} */ constructor( uri, contentType, thumbnail ){ super(Resource.Resource.type()) this.uri = new String(uri) this.contentType = new String(contentType) this.thumbnail = new String(thumbnail) } } /** * @namespace Geom */ let Geom = {}; /** * @class Transform3d * @extends Model * A 3D transformation */ Geom.Transform3d = class extends Model{ /** * Return the full class name of this type. * @returns {string} */ static type(){ return 'm.Geom$Transform3d'} /** * * @param matrix {number[]} */ constructor(matrix){ super(Geom.Transform3d.type()) this.matrix = [1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0] if( arguments.length ) { this.matrix = matrix if (this.matrix.length != (4 * 4)) { throw new Error('Matrix is not 4x4') } } } /** * The identity matrix * @returns {number[]} */ static identity(){ return new Geom.Transform3d([1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0]); } } /** * @namespace ETL */ let ETL = {}; /** * @class EntityMeta * @extends Model */ ETL.EntityMeta = class extends Model{ /** * Return the full class name of this type. * @returns {string} */ static type(){ return 'm.ETL$EntityMeta'} /** * @param uri {String} * @param timestamp {String} * @param version {String} * @param icon {String} * @param thumb {String} * @param domain {String} * @param publishDate {String} * @param contentType {String} * @param title {String} * @param description {String} * @param authors {String[]} * @param keywords {String[]} * @param coverUrl {String} * @param imgs {String[]} * @param meta {Map} * @param content {String} * @param raw {String} */ constructor(uri,timestamp,version,icon,thumb,domain,publishDate,contentType,title,description,authors,keywords,coverUrl,imgs,meta,content,raw){ super(ETL.EntityMeta.type()) this.uri = null this.timestamp = null this.version = null this.icon= null this.thumb = null this.domain = null this.publishDate = null this.contentType = null this.title = null this.description = null this.authors = null this.keywords = null this.coverUrl = null this.imgs = null this.meta = null this.content = null this.raw = null if(arguments.length){ this.uri = new String(uri) this.timestamp = new String(timestamp) this.version = new String(version) this.icon= new String(icon) this.thumb = new String(thumb) this.domain = new String(domain) this.publishDate = typeof publishDate === "undefined" ? null : new String(publishDate) this.contentType = new String(contentType) this.title = new String(title) this.description = new String(description) this.authors = authors this.keywords = keywords this.coverUrl = new String(coverUrl) this.imgs = imgs this.meta = meta this.content = typeof content === "undefined" ? null : new String(content) this.raw = typeof raw === "undefined" ? null : new String(raw) } } } module.exports = { Type: Type, UUID: UUID, List: List, Integer: Integer, Float: Float, Double: Double, Long: Long, Option: Option, Auth:Auth, Collaboration:Collaboration, Apps:Apps, Entities: Entities, Geom:Geom, Peers: Peers, Resource: Resource, ETL:ETL } window.m = module.exports
{ "content_hash": "cf3f23f062e736810d448f523f702eaa", "timestamp": "", "source": "github", "line_count": 2118, "max_line_length": 163, "avg_line_length": 26.355524079320112, "alnum_prop": 0.5898496981422762, "repo_name": "conversant-im/conversant-client-api", "id": "5276f4f0e40f1afbe87b166e1867dc409d3be31a", "size": "55821", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "model.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "3152" }, { "name": "JavaScript", "bytes": "430928" } ], "symlink_target": "" }
/** * Checks if value is object-like. * A value is object-like if it's not null and has a typeof result of "object". * * @category Language * * First version: July 03, 2017 * Last updated : July 03, 2017 * * @export * @param {*} input * @returns {boolean} */ export function isObjectLike(input: any): boolean { return input != null && typeof input === 'object'; }
{ "content_hash": "77a5ce847bc0410c4940523127ef124a", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 79, "avg_line_length": 19.1, "alnum_prop": 0.6387434554973822, "repo_name": "CamelKing/beta", "id": "0c8985463d8ec1c509e436e55f3b8d9bfbd5d1c9", "size": "382", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/isObjectLike.ts", "mode": "33188", "license": "mit", "language": [ { "name": "TypeScript", "bytes": "227525" } ], "symlink_target": "" }
package config import ( "bytes" "context" "errors" "fmt" "testing" "github.com/cossacklabs/acra/decryptor/base/type_awareness" base_mysql "github.com/cossacklabs/acra/decryptor/mysql/base" common2 "github.com/cossacklabs/acra/encryptor/config/common" "github.com/cossacklabs/acra/masking/common" "github.com/jackc/pgx/pgtype" log "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" ) func TestCryptoEnvelopeDefaultValuesWithDefinedValue(t *testing.T) { testConfig := ` defaults: crypto_envelope: acrablock schemas: - table: test_table columns: - data1 - data2 - data3 encrypted: - column: data1 - column: data2 crypto_envelope: acrablock - column: data3 crypto_envelope: acrastruct ` schemaStore, err := MapTableSchemaStoreFromConfig([]byte(testConfig), UseMySQL) if err != nil { t.Fatal(err) } tableSchema := schemaStore.GetTableSchema("test_table") // check default value setting := tableSchema.GetColumnEncryptionSettings("data1") if setting.GetCryptoEnvelope() != CryptoEnvelopeTypeAcraBlock { t.Fatalf("Expect %s, took %s\n", CryptoEnvelopeTypeAcraBlock, setting.GetCryptoEnvelope()) } // check same value as default setting = tableSchema.GetColumnEncryptionSettings("data2") if setting.GetCryptoEnvelope() != CryptoEnvelopeTypeAcraBlock { t.Fatalf("Expect %s, took %s\n", CryptoEnvelopeTypeAcraBlock, setting.GetCryptoEnvelope()) } // check changed value setting = tableSchema.GetColumnEncryptionSettings("data3") if setting.GetCryptoEnvelope() != CryptoEnvelopeTypeAcraStruct { t.Fatalf("Expect %s, took %s\n", CryptoEnvelopeTypeAcraStruct, setting.GetCryptoEnvelope()) } } func TestCryptoEnvelopeDefaultValuesWithoutDefinedValue(t *testing.T) { testConfig := ` schemas: - table: test_table columns: - data1 - data2 - data3 encrypted: - column: data1 - column: data2 crypto_envelope: acrablock - column: data3 crypto_envelope: acrastruct ` schemaStore, err := MapTableSchemaStoreFromConfig([]byte(testConfig), UseMySQL) if err != nil { t.Fatal(err) } tableSchema := schemaStore.GetTableSchema("test_table") // check default value setting := tableSchema.GetColumnEncryptionSettings("data1") if setting.GetCryptoEnvelope() != CryptoEnvelopeTypeAcraBlock { t.Fatalf("Expect %s, took %s\n", CryptoEnvelopeTypeAcraStruct, setting.GetCryptoEnvelope()) } // check same value as default setting = tableSchema.GetColumnEncryptionSettings("data2") if setting.GetCryptoEnvelope() != CryptoEnvelopeTypeAcraBlock { t.Fatalf("Expect %s, took %s\n", CryptoEnvelopeTypeAcraBlock, setting.GetCryptoEnvelope()) } // check changed value setting = tableSchema.GetColumnEncryptionSettings("data3") if setting.GetCryptoEnvelope() != CryptoEnvelopeTypeAcraStruct { t.Fatalf("Expect %s, took %s\n", CryptoEnvelopeTypeAcraStruct, setting.GetCryptoEnvelope()) } } func TestReEncryptAcraStructDefaultValuesWithDefinedValue(t *testing.T) { testConfig := ` defaults: reencrypting_to_acrablocks: false schemas: - table: test_table columns: - data1 - data2 - data3 encrypted: - column: data1 - column: data2 reencrypting_to_acrablocks: false - column: data3 reencrypting_to_acrablocks: true ` schemaStore, err := MapTableSchemaStoreFromConfig([]byte(testConfig), UseMySQL) if err != nil { t.Fatal(err) } tableSchema := schemaStore.GetTableSchema("test_table") // check default value setting := tableSchema.GetColumnEncryptionSettings("data1") if setting.ShouldReEncryptAcraStructToAcraBlock() { t.Fatalf("Expect %t on ShouldReEncryptAcraStructToAcraBlock()\n", false) } // check same value as default setting = tableSchema.GetColumnEncryptionSettings("data2") if setting.ShouldReEncryptAcraStructToAcraBlock() { t.Fatalf("Expect %t on ShouldReEncryptAcraStructToAcraBlock()\n", false) } // check changed value setting = tableSchema.GetColumnEncryptionSettings("data3") if !setting.ShouldReEncryptAcraStructToAcraBlock() { t.Fatalf("Expect %t on ShouldReEncryptAcraStructToAcraBlock()\n", true) } } func TestReEncryptAcraStructDefaultValuesWithoutDefinedValue(t *testing.T) { testConfig := ` schemas: - table: test_table columns: - data1 - data2 - data3 encrypted: - column: data1 - column: data2 reencrypting_to_acrablocks: true - column: data3 reencrypting_to_acrablocks: false ` schemaStore, err := MapTableSchemaStoreFromConfig([]byte(testConfig), UseMySQL) if err != nil { t.Fatal(err) } tableSchema := schemaStore.GetTableSchema("test_table") // check default value setting := tableSchema.GetColumnEncryptionSettings("data1") if !setting.ShouldReEncryptAcraStructToAcraBlock() { t.Fatalf("Expect %t on ShouldReEncryptAcraStructToAcraBlock()\n", true) } // check same value as default setting = tableSchema.GetColumnEncryptionSettings("data2") if !setting.ShouldReEncryptAcraStructToAcraBlock() { t.Fatalf("Expect %t on ShouldReEncryptAcraStructToAcraBlock()\n", true) } // check changed value setting = tableSchema.GetColumnEncryptionSettings("data3") if setting.ShouldReEncryptAcraStructToAcraBlock() { t.Fatalf("Expect %t on ShouldReEncryptAcraStructToAcraBlock()\n", false) } } func TestInvalidMasking(t *testing.T) { registerMySQLDummyEncoders() type testcase struct { name string config string err error } testcases := []testcase{ {"masking can't be searchable", ` schemas: - table: test_table columns: - data1 encrypted: - column: data1 masking: "xxxx" plaintext_length: 9 plaintext_side: "right" searchable: true `, ErrInvalidEncryptorConfig}, {"plaintext_length should be > 0", ` schemas: - table: test_table columns: - data1 encrypted: - column: data1 masking: "xxxx" plaintext_length: -1 plaintext_side: "right" `, common.ErrInvalidPlaintextLength}, {"invalid crypto_envelope", ` schemas: - table: test_table columns: - data1 encrypted: - column: data1 masking: "xxxx" plaintext_length: 5 plaintext_side: "right" crypto_envelope: "invalid" `, ErrInvalidCryptoEnvelopeType}, {"should be specified plaintext_side", ` schemas: - table: test_table columns: - data1 encrypted: - column: data1 masking: "xxxx" plaintext_length: 9 `, common.ErrInvalidPlaintextSide}, {"should be specified masking pattern", ` schemas: - table: test_table columns: - data1 encrypted: - column: data1 plaintext_length: 9 plaintext_side: "right" `, common.ErrInvalidMaskingPattern}, {"searchable encryption doesn't support zones", ` schemas: - table: test_table columns: - data1 encrypted: - column: data1 searchable: true zone_id: DDDDDDDDMatNOMYjqVOuhACC `, ErrInvalidEncryptorConfig}, {"tokenization can't be searchable", ` schemas: - table: test_table columns: - data1 encrypted: - column: data1 token_type: int32 searchable: true `, errors.New("invalid encryptor config")}, {"invalid token type", ` schemas: - table: test_table columns: - data1 encrypted: - column: data1 tokenized: true token_type: invalid `, // use new declared to avoid cycle import errors.New("unknown token type")}, {"AcraBlock - type aware decryption, all supported types", ` schemas: - table: test_table columns: - data1 - data2 - data3 - data4 encrypted: - column: data1 data_type: str - column: data2 data_type: bytes - column: data3 data_type: int32 - column: data4 data_type: int64 `, nil}, {"type aware decryption, all supported types + masking", ` schemas: - table: test_table columns: - data1 - data2 - data3 - data4 encrypted: - column: data1 data_type: str masking: "00" plaintext_length: 2 plaintext_side: "left" - column: data2 data_type: bytes masking: "00" plaintext_length: 2 plaintext_side: "left" - column: data3 data_type: int32 - column: data4 data_type: int64 `, nil}, {"type aware decryption, all supported types, specified client id", ` schemas: - table: test_table columns: - data1 - data2 - data3 - data4 encrypted: - column: data1 data_type: str client_id: client - column: data2 data_type: bytes client_id: client - column: data3 data_type: int32 client_id: client - column: data4 data_type: int64 client_id: client `, nil}, {"type aware decryption, all supported types, specified client id + masking", ` schemas: - table: test_table columns: - data1 - data2 - data3 - data4 encrypted: - column: data1 data_type: str client_id: client masking: "00" plaintext_length: 2 plaintext_side: "left" - column: data2 data_type: bytes client_id: client masking: "00" plaintext_length: 2 plaintext_side: "left" - column: data3 data_type: int32 client_id: client - column: data4 data_type: int64 client_id: client `, nil}, {"type aware decryption, all supported types, specified zone id", ` schemas: - table: test_table columns: - data1 - data2 - data3 - data4 encrypted: - column: data1 data_type: str zone_id: client - column: data2 data_type: bytes zone_id: client - column: data3 data_type: int32 zone_id: client - column: data4 data_type: int64 zone_id: client `, nil}, {"type aware decryption, all supported types, default value", ` schemas: - table: test_table columns: - data1 - data2 - data3 - data4 encrypted: - column: data1 data_type: str response_on_fail: default_value default_data_value: "str" - column: data2 data_type: bytes response_on_fail: default_value default_data_value: "bytes" - column: data3 data_type: int32 response_on_fail: default_value default_data_value: "123" - column: data4 data_type: int64 response_on_fail: default_value default_data_value: "123" `, nil}, {"type aware decryption, all supported types, default value, specified client id", ` schemas: - table: test_table columns: - data1 - data2 - data3 - data4 encrypted: - column: data1 data_type: str response_on_fail: default_value default_data_value: "str" client_id: client - column: data2 data_type: bytes response_on_fail: default_value default_data_value: "bytes" client_id: client - column: data3 data_type: int32 response_on_fail: default_value default_data_value: "123" client_id: client - column: data4 data_type: int64 response_on_fail: default_value default_data_value: "123" client_id: client `, nil}, {"type aware decryption, all supported types, default value, specified zone id", ` schemas: - table: test_table columns: - data1 - data2 - data3 - data4 encrypted: - column: data1 data_type: str response_on_fail: default_value default_data_value: "str" zone_id: zone - column: data2 data_type: bytes response_on_fail: default_value default_data_value: "bytes" zone_id: zone - column: data3 data_type: int32 response_on_fail: default_value default_data_value: "123" zone_id: zone - column: data4 data_type: int64 response_on_fail: default_value default_data_value: "123" zone_id: zone `, nil}, {"AcraBlock - type aware decryption, all supported types", ` defaults: crypto_envelope: acrastruct schemas: - table: test_table columns: - data1 - data2 - data3 - data4 encrypted: - column: data1 data_type: str - column: data2 data_type: bytes - column: data3 data_type: int32 - column: data4 data_type: int64 `, nil}, {"type aware decryption, all supported types, specified client id", ` defaults: crypto_envelope: acrastruct schemas: - table: test_table columns: - data1 - data2 - data3 - data4 encrypted: - column: data1 data_type: str client_id: client - column: data2 data_type: bytes client_id: client - column: data3 data_type: int32 client_id: client - column: data4 data_type: int64 client_id: client `, nil}, {"type aware decryption, all supported types, specified zone id", ` defaults: crypto_envelope: acrastruct schemas: - table: test_table columns: - data1 - data2 - data3 - data4 encrypted: - column: data1 data_type: str zone_id: client - column: data2 data_type: bytes zone_id: client - column: data3 data_type: int32 zone_id: client - column: data4 data_type: int64 zone_id: client `, nil}, {"type aware decryption, all supported types, default value", ` defaults: crypto_envelope: acrastruct schemas: - table: test_table columns: - data1 - data2 - data3 - data4 encrypted: - column: data1 data_type: str response_on_fail: default_value default_data_value: "str" - column: data2 data_type: bytes response_on_fail: default_value default_data_value: "bytes" - column: data3 data_type: int32 response_on_fail: default_value default_data_value: "123" - column: data4 data_type: int64 response_on_fail: default_value default_data_value: "123" `, nil}, {"Acrastruct - type aware decryption, all supported types, default value, specified client id", ` defaults: crypto_envelope: acrastruct schemas: - table: test_table columns: - data1 - data2 - data3 - data4 encrypted: - column: data1 data_type: str response_on_fail: default_value default_data_value: "str" client_id: client - column: data2 data_type: bytes response_on_fail: default_value default_data_value: "bytes" client_id: client - column: data3 data_type: int32 response_on_fail: default_value default_data_value: "123" client_id: client - column: data4 data_type: int64 response_on_fail: default_value default_data_value: "123" client_id: client `, nil}, {"type aware decryption, all supported types, default value, specified zone id", ` defaults: crypto_envelope: acrastruct schemas: - table: test_table columns: - data1 - data2 - data3 - data4 encrypted: - column: data1 data_type: str response_on_fail: default_value default_data_value: "str" zone_id: zone - column: data2 data_type: bytes response_on_fail: default_value default_data_value: "bytes" zone_id: zone - column: data3 data_type: int32 response_on_fail: default_value default_data_value: "123" zone_id: zone - column: data4 data_type: int64 response_on_fail: default_value default_data_value: "123" zone_id: zone `, nil}, } for _, tcase := range testcases { _, err := MapTableSchemaStoreFromConfig([]byte(tcase.config), UseMySQL) u, ok := err.(interface { Unwrap() error }) if ok { err = u.Unwrap() } if tcase.err == err { continue } if tcase.err == nil { t.Fatalf("[%s] Expected nil, took %s\n", tcase.name, err) } if err == nil { t.Fatalf("[%s] Expected %s, took nil\n", tcase.name, tcase.err) } if err.Error() != tcase.err.Error() { t.Fatalf("[%s] Expect %s, took %s\n", tcase.name, tcase.err.Error(), err) } } } func TestDataTypeValidation(t *testing.T) { type testcase struct { config string err error } testcases := []testcase{ {` schemas: - table: test_table columns: - data1 encrypted: - column: data1 data_type: int32 tokenized: true token_type: int32 `, ErrInvalidEncryptorConfig}, {` schemas: - table: test_table columns: - data1 encrypted: - column: data1 data_type: int64 tokenized: true token_type: int64 `, ErrInvalidEncryptorConfig}, {` schemas: - table: test_table columns: - data1 encrypted: - column: data1 data_type: str tokenized: true token_type: str `, ErrInvalidEncryptorConfig}, {` schemas: - table: test_table columns: - data1 encrypted: - column: data1 data_type: bytes tokenized: true token_type: bytes `, ErrInvalidEncryptorConfig}, {` schemas: - table: test_table columns: - data1 encrypted: - column: data1 data_type: str tokenized: true token_type: email `, ErrInvalidEncryptorConfig}, {` schemas: - table: test_table columns: - data1 encrypted: - column: data1 data_type: int32 tokenized: true token_type: str `, ErrInvalidEncryptorConfig}, {` schemas: - table: test_table columns: - data1 encrypted: - column: data1 data_type: bytes tokenized: true token_type: str `, ErrInvalidEncryptorConfig}, {` schemas: - table: test_table columns: - data1 encrypted: - column: data1 data_type: bytes tokenized: true token_type: email `, ErrInvalidEncryptorConfig}, } for i, tcase := range testcases { _, err := MapTableSchemaStoreFromConfig([]byte(tcase.config), UseMySQL) u, ok := err.(interface { Unwrap() error }) if ok { err = u.Unwrap() } if tcase.err == err { continue } if err.Error() != tcase.err.Error() { t.Fatalf("[%d] Expect %s, took %s\n", i, tcase.err.Error(), err) } } } func TestTypeAwarenessOnFailDefaults(t *testing.T) { type testcase struct { name string onFail common2.ResponseOnFail config string } testcases := []testcase{ {"By default, onFail is 'ciphertext'", common2.ResponseOnFailCiphertext, ` schemas: - table: test_table columns: - data encrypted: - column: data`}, {"onFail is 'ciphertext' if data type is defined", common2.ResponseOnFailCiphertext, ` schemas: - table: test_table columns: - data_str - data_bytes - data_int32 - data_int64 encrypted: - column: data_str data_type: str - column: data_bytes data_type: bytes - column: data_int32 data_type: int32 - column: data_int64 data_type: int64`}, {"onFail is 'default_vaue' if explicitly defined", common2.ResponseOnFailDefault, ` schemas: - table: test_table columns: - data_str - data_bytes - data_int32 - data_int64 encrypted: - column: data_str data_type: str response_on_fail: default_value default_data_value: string - column: data_bytes data_type: bytes response_on_fail: default_value default_data_value: Ynl0ZXM= - column: data_int32 data_type: int32 response_on_fail: default_value default_data_value: 2147483647 - column: data_int64 data_type: int64 response_on_fail: default_value default_data_value: 9223372036854775807`}, {"onFail is 'error' if explicitly defined", common2.ResponseOnFailError, ` schemas: - table: test_table columns: - data_str - data_bytes - data_int32 - data_int64 encrypted: - column: data_str data_type: str response_on_fail: error - column: data_bytes data_type: bytes response_on_fail: error - column: data_int32 data_type: int32 response_on_fail: error - column: data_int64 data_type: int64 response_on_fail: error`}, {"onFail is implicitly 'default_value' if 'default_data_value' is defined", common2.ResponseOnFailDefault, ` schemas: - table: test_table columns: - data_str - data_bytes - data_int32 - data_int64 encrypted: - column: data_str data_type: str default_data_value: string - column: data_bytes data_type: bytes default_data_value: Ynl0ZXM= - column: data_int32 data_type: int32 default_data_value: 2147483647 - column: data_int64 data_type: int64 default_data_value: 9223372036854775807`}, } for _, tcase := range testcases { config, err := MapTableSchemaStoreFromConfig([]byte(tcase.config), UseMySQL) if err != nil { t.Fatalf("[%s] error=%s\n", tcase.name, err) } for _, column := range config.schemas["test_table"].EncryptionColumnSettings { if column.GetResponseOnFail() != tcase.onFail { t.Fatalf("[%s] GetResponseOnFail expected %q but found %q\n", tcase.name, tcase.onFail, column.GetResponseOnFail()) } } } } func TestInvalidTypeAwarenessOnFailCombinations(t *testing.T) { type testcase struct { name string config string } testcases := []testcase{ {"OnFail=error and default", ` schemas: - table: test_table columns: - data encrypted: - column: data data_type: str response_on_fail: error default_data_value: hidden by cossacklabs`}, {"OnFail=unknown", ` schemas: - table: test_table columns: - data encrypted: - column: data data_type: str response_on_fail: unknown`}, {"OnFail without data_type", ` schemas: - table: test_table columns: - data encrypted: - column: data response_on_fail: error`}, {"OnFail and default without data_type", ` schemas: - table: test_table columns: - data encrypted: - column: data response_on_fail: default_value default_data_value: ukraine`}, {"OnFai=ciphertext and default", ` schemas: - table: test_table columns: - data encrypted: - column: data data_type: str response_on_fail: ciphertext default_data_value: oops`}, } for _, tcase := range testcases { _, err := MapTableSchemaStoreFromConfig([]byte(tcase.config), UseMySQL) if err == nil { t.Fatalf("[%s] expected error, found nil\n", tcase.name) } } } func TestDeprecateTokenized(t *testing.T) { tokenTypes := []string{ "str", "email", "int64", "int32", "bytes", } for _, token := range tokenTypes { config := fmt.Sprintf(` schemas: - table: test_table columns: - data encrypted: - column: data tokenized: true token_type: %s `, token) _, err := MapTableSchemaStoreFromConfig([]byte(config), UseMySQL) if err != nil { t.Fatalf("[tokenize: true, token_type: %s] %s", token, err) } config = fmt.Sprintf(` schemas: - table: test_table columns: - data encrypted: - column: data token_type: %s `, token) _, err = MapTableSchemaStoreFromConfig([]byte(config), UseMySQL) if err != nil { t.Fatalf("[token_type: %s] %s", token, err) } config = fmt.Sprintf(` schemas: - table: test_table columns: - data encrypted: - column: data consistent_tokenization: true token_type: %s `, token) _, err = MapTableSchemaStoreFromConfig([]byte(config), UseMySQL) if err != nil { t.Fatalf("[consistent_tokenization: true, token_type: %s] %s", token, err) } } } func TestInvalidTokenizationCombinations(t *testing.T) { type testcase struct { name string config string } testcases := []testcase{ {"Tokenized: false and token_type non empty", ` schemas: - table: test_table columns: - data encrypted: - column: data tokenized: false token_type: str `}, {"tokenized: true without token_type", ` schemas: - table: test_table columns: - data encrypted: - column: data tokenized: true `}, {"tokenized: true with empty token_type", ` schemas: - table: test_table columns: - data encrypted: - column: data tokenized: true token_type: "" `}, } for _, tcase := range testcases { _, err := MapTableSchemaStoreFromConfig([]byte(tcase.config), UseMySQL) if err == nil { t.Fatalf("[%s] expected error, found nil\n", tcase.name) } } } func TestTokenizedDeprecationWarning(t *testing.T) { config := ` schemas: - table: test_table columns: - data encrypted: - column: data tokenized: true token_type: str` buff := bytes.NewBuffer([]byte{}) log.SetOutput(buff) _, err := MapTableSchemaStoreFromConfig([]byte(config), UseMySQL) if err != nil { t.Fatal(err) } output := buff.Bytes() msg := "Setting `tokenized` flag is not necessary anymore and will be ignored" if !bytes.Contains(output, []byte(msg)) { t.Fatal("warning is not found but expected") } } func TestWithDataTypeIDOption(t *testing.T) { type testcase struct { name string config string } testcases := []testcase{ { name: "Schema store with data_type_db_identifier", config: ` schemas: - table: test_type_aware_decryption_with_defaults columns: - id - value_str encrypted: - column: value_str data_type_db_identifier: 25 `, }, { name: "Schema store with data_type_db_identifier and on_fail options", config: ` schemas: - table: test_type_aware_decryption_with_defaults columns: - id - value_str encrypted: - column: value_str data_type_db_identifier: 25 response_on_fail: default_value default_data_value: "value_str" `, }, } type_awareness.RegisterPostgreSQLDataTypeIDEncoder(pgtype.TextOID, &dummyDataTypeEncoder{}) for _, tcase := range testcases { schemaStore, err := MapTableSchemaStoreFromConfig([]byte(tcase.config), UsePostgreSQL) if err != nil { t.Fatal(err) } dataTypeID := schemaStore.GetTableSchema("test_type_aware_decryption_with_defaults"). GetColumnEncryptionSettings("value_str").GetDBDataTypeID() assert.Equal(t, dataTypeID, uint32(25)) } } func TestInvalidWithDataTypeIDOption(t *testing.T) { type testcase struct { name string config string expectedError error } testcases := []testcase{ { name: "Schema store with data_type_db_identifier and data_type options", expectedError: common2.ErrDataTypeWithDataTypeID, config: ` schemas: - table: test_type_aware_decryption_with_defaults columns: - id - value_str encrypted: - column: value_str data_type: str data_type_db_identifier: 25 `, }, { name: "Schema store with not supported data_type options", config: ` schemas: - table: test_type_aware_decryption_with_defaults columns: - id - value_str encrypted: - column: value_str data_type_db_identifier: 10 `, expectedError: common2.ErrUnsupportedDataTypeID, }, } type_awareness.RegisterPostgreSQLDataTypeIDEncoder(pgtype.TextOID, nil) for _, tcase := range testcases { _, err := MapTableSchemaStoreFromConfig([]byte(tcase.config), UsePostgreSQL) if err == nil { t.Fatalf("expected got error on invalid config - %s", tcase.name) } if err != tcase.expectedError { t.Fatalf("expected got error %s - but found %s", tcase.expectedError.Error(), err.Error()) } } } func registerMySQLDummyEncoders() { type_awareness.RegisterMySQLDataTypeIDEncoder(uint32(base_mysql.TypeBlob), &dummyDataTypeEncoder{}) type_awareness.RegisterMySQLDataTypeIDEncoder(uint32(base_mysql.TypeString), &dummyDataTypeEncoder{}) type_awareness.RegisterMySQLDataTypeIDEncoder(uint32(base_mysql.TypeLong), &dummyDataTypeEncoder{}) type_awareness.RegisterMySQLDataTypeIDEncoder(uint32(base_mysql.TypeLongLong), &dummyDataTypeEncoder{}) } type dummyDataTypeEncoder struct{} // Encode implementation of Encode method of DataTypeEncoder interface for TypeLong func (t *dummyDataTypeEncoder) Encode(ctx context.Context, data []byte, format type_awareness.DataTypeFormat) (context.Context, []byte, error) { return nil, nil, nil } // Decode implementation of Decode method of DataTypeEncoder interface for TypeLong func (t *dummyDataTypeEncoder) Decode(ctx context.Context, data []byte, format type_awareness.DataTypeFormat) (context.Context, []byte, error) { return nil, nil, nil } // EncodeOnFail implementation of EncodeOnFail method of DataTypeEncoder interface for TypeLong func (t *dummyDataTypeEncoder) EncodeOnFail(ctx context.Context, format type_awareness.DataTypeFormat) (context.Context, []byte, error) { return nil, nil, nil } // EncodeDefault implementation of EncodeDefault method of DataTypeEncoder interface for TypeLong func (t *dummyDataTypeEncoder) encodeDefault(ctx context.Context, data []byte, format type_awareness.DataTypeFormat) (context.Context, []byte, error) { return nil, nil, nil } // ValidateDefaultValue implementation of ValidateDefaultValue method of DataTypeEncoder interface for TypeLong func (t *dummyDataTypeEncoder) ValidateDefaultValue(value *string) error { return nil }
{ "content_hash": "41d1efc9afb217c7fdf0b22c5730093e", "timestamp": "", "source": "github", "line_count": 1338, "max_line_length": 151, "avg_line_length": 22.736920777279522, "alnum_prop": 0.6247123791992637, "repo_name": "cossacklabs/acra", "id": "23abb037ca43f7a0a9753857dd592c616642c792", "size": "30422", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "encryptor/config/schemaStore_test.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "4962" }, { "name": "Dockerfile", "bytes": "15900" }, { "name": "Go", "bytes": "2875534" }, { "name": "Java", "bytes": "6144" }, { "name": "JavaScript", "bytes": "2405" }, { "name": "Makefile", "bytes": "14139" }, { "name": "Objective-C", "bytes": "10444" }, { "name": "PHP", "bytes": "1951" }, { "name": "Python", "bytes": "580725" }, { "name": "Ruby", "bytes": "6451" }, { "name": "Shell", "bytes": "24229" }, { "name": "Yacc", "bytes": "68250" } ], "symlink_target": "" }
package com.phonegap; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import android.webkit.WebSettings; public class WebViewReflect { private static Method mWebSettings_setDatabaseEnabled; private static Method mWebSettings_setDatabasePath; private static Method mWebSettings_setDomStorageEnabled; private static Method mWebSettings_setGeolocationEnabled; static { checkCompatibility(); } private static void setDatabaseEnabled(boolean e) throws IOException { try { mWebSettings_setDatabaseEnabled.invoke(e); } catch (InvocationTargetException ite) { /* unpack original exception when possible */ Throwable cause = ite.getCause(); if (cause instanceof IOException) { throw (IOException) cause; } else if (cause instanceof RuntimeException) { throw (RuntimeException) cause; } else if (cause instanceof Error) { throw (Error) cause; } else { /* unexpected checked exception; wrap and re-throw */ throw new RuntimeException(ite); } } catch (IllegalAccessException ie) { System.err.println("unexpected " + ie); } } public static void checkCompatibility() { try { mWebSettings_setDatabaseEnabled = WebSettings.class.getMethod( "setDatabaseEnabled", new Class[] { boolean.class } ); mWebSettings_setDatabasePath = WebSettings.class.getMethod( "setDatabasePath", new Class[] { String.class }); mWebSettings_setDomStorageEnabled = WebSettings.class.getMethod( "setDomStorageEnabled", new Class[] { boolean.class }); mWebSettings_setGeolocationEnabled = WebSettings.class.getMethod( "setGeolocationEnabled", new Class[] { boolean.class }); /* success, this is a newer device */ } catch (NoSuchMethodException nsme) { /* failure, must be older device */ } } public static void setStorage(WebSettings setting, boolean enable, String path) { if (mWebSettings_setDatabaseEnabled != null) { /* feature is supported */ try { mWebSettings_setDatabaseEnabled.invoke(setting, enable); mWebSettings_setDatabasePath.invoke(setting, path); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { /* feature not supported, do something else */ } } public static void setGeolocationEnabled(WebSettings setting, boolean enable) { if (mWebSettings_setGeolocationEnabled != null) { /* feature is supported */ try { mWebSettings_setGeolocationEnabled.invoke(setting, enable); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { /* feature not supported, do something else */ System.out.println("Native Geolocation not supported - we're ok"); } } public static void setDomStorage(WebSettings setting) { if(mWebSettings_setDomStorageEnabled != null) { /* feature is supported */ try { mWebSettings_setDomStorageEnabled.invoke(setting, true); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { /* feature not supported, do something else */ } } }
{ "content_hash": "fa27a363ec17c9d11d2f497cdb0b8dea", "timestamp": "", "source": "github", "line_count": 122, "max_line_length": 85, "avg_line_length": 35.21311475409836, "alnum_prop": 0.6347765363128491, "repo_name": "Repsly/phonegap-android", "id": "6d6c342195590aeeee3bae7e5fcd4bd15ee5a38c", "size": "4296", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "framework/src/com/phonegap/WebViewReflect.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "161490" }, { "name": "JavaScript", "bytes": "196418" }, { "name": "Ruby", "bytes": "12264" } ], "symlink_target": "" }
package com.sequenceiq.cloudbreak.cm; import static com.sequenceiq.cloudbreak.cmtemplate.CMRepositoryVersionUtil.CLOUDERAMANAGER_VERSION_7_1_0; import static com.sequenceiq.cloudbreak.cmtemplate.CMRepositoryVersionUtil.CLOUDERAMANAGER_VERSION_7_2_0; import static com.sequenceiq.cloudbreak.cmtemplate.CMRepositoryVersionUtil.CLOUDERAMANAGER_VERSION_7_6_0; import static com.sequenceiq.cloudbreak.cmtemplate.CMRepositoryVersionUtil.isVersionNewerOrEqualThanLimited; import java.io.IOException; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import javax.annotation.PostConstruct; import javax.inject.Inject; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpStatus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; import com.cloudera.api.swagger.CdpResourceApi; import com.cloudera.api.swagger.ClouderaManagerResourceApi; import com.cloudera.api.swagger.ClustersResourceApi; import com.cloudera.api.swagger.HostsResourceApi; import com.cloudera.api.swagger.MgmtServiceResourceApi; import com.cloudera.api.swagger.ToolsResourceApi; import com.cloudera.api.swagger.client.ApiClient; import com.cloudera.api.swagger.client.ApiException; import com.cloudera.api.swagger.model.ApiCluster; import com.cloudera.api.swagger.model.ApiClusterTemplate; import com.cloudera.api.swagger.model.ApiCommand; import com.cloudera.api.swagger.model.ApiConfig; import com.cloudera.api.swagger.model.ApiConfigList; import com.cloudera.api.swagger.model.ApiHost; import com.cloudera.api.swagger.model.ApiHostRef; import com.cloudera.api.swagger.model.ApiRemoteDataContext; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.sequenceiq.cloudbreak.api.endpoint.v4.common.StackType; import com.sequenceiq.cloudbreak.auth.altus.EntitlementService; import com.sequenceiq.cloudbreak.auth.crn.Crn; import com.sequenceiq.cloudbreak.client.HttpClientConfig; import com.sequenceiq.cloudbreak.cloud.model.ClouderaManagerProduct; import com.sequenceiq.cloudbreak.cloud.model.ClouderaManagerRepo; import com.sequenceiq.cloudbreak.cloud.scheduler.CancellationException; import com.sequenceiq.cloudbreak.cluster.api.ClusterSetupService; import com.sequenceiq.cloudbreak.cluster.service.ClusterClientInitException; import com.sequenceiq.cloudbreak.cluster.service.ClusterComponentConfigProvider; import com.sequenceiq.cloudbreak.cm.client.ClouderaManagerApiClientProvider; import com.sequenceiq.cloudbreak.cm.client.ClouderaManagerClientInitException; import com.sequenceiq.cloudbreak.cm.client.retry.ClouderaManagerApiFactory; import com.sequenceiq.cloudbreak.cm.error.mapper.ClouderaManagerStorageErrorMapper; import com.sequenceiq.cloudbreak.cm.exception.CloudStorageConfigurationFailedException; import com.sequenceiq.cloudbreak.cm.polling.ClouderaManagerPollingServiceProvider; import com.sequenceiq.cloudbreak.cmtemplate.CMRepositoryVersionUtil; import com.sequenceiq.cloudbreak.cmtemplate.CentralCmTemplateUpdater; import com.sequenceiq.cloudbreak.common.anonymizer.AnonymizerUtil; import com.sequenceiq.cloudbreak.common.exception.CloudbreakServiceException; import com.sequenceiq.cloudbreak.common.json.JsonUtil; import com.sequenceiq.cloudbreak.common.mappable.CloudPlatform; import com.sequenceiq.cloudbreak.domain.stack.cluster.ClusterCommand; import com.sequenceiq.cloudbreak.domain.stack.cluster.ClusterCommandType; import com.sequenceiq.cloudbreak.domain.stack.cluster.host.HostGroup; import com.sequenceiq.cloudbreak.domain.stack.instance.InstanceMetaData; import com.sequenceiq.cloudbreak.dto.KerberosConfig; import com.sequenceiq.cloudbreak.dto.ProxyConfig; import com.sequenceiq.cloudbreak.dto.StackDtoDelegate; import com.sequenceiq.cloudbreak.polling.ExtendedPollingResult; import com.sequenceiq.cloudbreak.repository.ClusterCommandRepository; import com.sequenceiq.cloudbreak.service.CloudbreakException; import com.sequenceiq.cloudbreak.template.TemplatePreparationObject; import com.sequenceiq.cloudbreak.view.ClusterView; import com.sequenceiq.cloudbreak.view.InstanceMetadataView; import com.sequenceiq.common.api.telemetry.model.Telemetry; @Service @Scope("prototype") public class ClouderaManagerSetupService implements ClusterSetupService { private static final Logger LOGGER = LoggerFactory.getLogger(ClouderaManagerSetupService.class); @Inject private ClouderaManagerApiClientProvider clouderaManagerApiClientProvider; @Inject private ClouderaManagerApiFactory clouderaManagerApiFactory; @Inject private ClouderaManagerPollingServiceProvider clouderaManagerPollingServiceProvider; @Inject private ClouderaHostGroupAssociationBuilder hostGroupAssociationBuilder; @Inject private CentralCmTemplateUpdater cmTemplateUpdater; @Inject private ClusterComponentConfigProvider clusterComponentProvider; @Inject private ClouderaManagerLicenseService clouderaManagerLicenseService; @Inject private ClouderaManagerMgmtSetupService mgmtSetupService; @Inject private ClouderaManagerKerberosService kerberosService; @Inject private ClouderaManagerMgmtLaunchService clouderaManagerMgmtLaunchService; @Inject private ClouderaManagerSupportSetupService clouderaManagerSupportSetupService; @Inject private ClouderaManagerYarnSetupService clouderaManagerYarnSetupService; @Inject private ClusterCommandRepository clusterCommandRepository; @Inject private ClouderaManagerStorageErrorMapper clouderaManagerStorageErrorMapper; @Inject private EntitlementService entitlementService; private final StackDtoDelegate stack; private final HttpClientConfig clientConfig; private ApiClient apiClient; public ClouderaManagerSetupService(StackDtoDelegate stack, HttpClientConfig clientConfig) { this.stack = stack; this.clientConfig = clientConfig; } @PostConstruct public void initApiClient() throws ClusterClientInitException { ClusterView cluster = stack.getCluster(); String user = cluster.getCloudbreakAmbariUser(); String password = cluster.getCloudbreakAmbariPassword(); try { ClouderaManagerRepo clouderaManagerRepoDetails = clusterComponentProvider.getClouderaManagerRepoDetails(cluster.getId()); if (isVersionNewerOrEqualThanLimited(clouderaManagerRepoDetails::getVersion, CLOUDERAMANAGER_VERSION_7_1_0)) { apiClient = clouderaManagerApiClientProvider.getV40Client(stack.getGatewayPort(), user, password, clientConfig); } else { apiClient = clouderaManagerApiClientProvider.getV31Client(stack.getGatewayPort(), user, password, clientConfig); } } catch (ClouderaManagerClientInitException e) { throw new ClusterClientInitException(e); } } @Override public void waitForServer(boolean defaultClusterManagerAuth) throws CloudbreakException, ClusterClientInitException { ApiClient client = defaultClusterManagerAuth ? createApiClient() : apiClient; ExtendedPollingResult pollingResult = clouderaManagerPollingServiceProvider.startPollingCmStartup(stack, client); if (pollingResult.isSuccess()) { LOGGER.debug("Cloudera Manager server has successfully started! Polling result: {}", pollingResult); } else if (pollingResult.isExited()) { throw new CancellationException("Polling of Cloudera Manager server start has been cancelled."); } else { LOGGER.debug("Could not start Cloudera Manager. polling result: {}", pollingResult); throw new CloudbreakException(String.format("Could not start Cloudera Manager. polling result: '%s'", pollingResult)); } } @Override public String prepareTemplate( Map<HostGroup, List<InstanceMetaData>> instanceMetaDataByHostGroup, TemplatePreparationObject templatePreparationObject, String sdxContext, String sdxCrn, KerberosConfig kerberosConfig) { Long clusterId = stack.getCluster().getId(); try { Set<InstanceMetadataView> instances = instanceMetaDataByHostGroup.values().stream().flatMap(Collection::stream).collect(Collectors.toSet()); waitForHosts(instances); String sdxContextName = Optional.ofNullable(sdxContext).map(this::setupRemoteDataContext).orElse(null); ClouderaManagerRepo clouderaManagerRepoDetails = clusterComponentProvider.getClouderaManagerRepoDetails(clusterId); ApiClusterTemplate apiClusterTemplate = getCmTemplate(templatePreparationObject, sdxContextName, instanceMetaDataByHostGroup, clouderaManagerRepoDetails, clusterId); return getExtendedBlueprintText(apiClusterTemplate); } catch (CancellationException cancellationException) { throw cancellationException; } catch (Exception e) { throw mapException(e); } } @Override public void validateLicence() { try { clouderaManagerLicenseService.validateClouderaManagerLicense(Crn.safeFromString(stack.getResourceCrn()).getAccountId()); } catch (Exception e) { throw mapException(e); } } @Override public void configureManagementServices(TemplatePreparationObject templatePreparationObject, String sdxContext, String sdxStackCrn, Telemetry telemetry, ProxyConfig proxyConfig) { String sdxContextName = Optional.ofNullable(sdxContext).map(this::setupRemoteDataContext).orElse(null); try { configureCmMgmtServices(templatePreparationObject, sdxStackCrn, telemetry, sdxContextName, proxyConfig); } catch (ApiException e) { throw mapApiException(e); } catch (Exception e) { throw mapException(e); } } @Override public void configureSupportTags(TemplatePreparationObject templatePreparationObject) { try { configureCmSupportTag(templatePreparationObject); } catch (Exception e) { throw mapException(e); } } @Override public void suppressWarnings() { clouderaManagerYarnSetupService.suppressWarnings(stack, apiClient); } @Override public void startManagementServices() { try { clouderaManagerMgmtLaunchService.startManagementServices(stack, apiClient); } catch (ApiException e) { throw mapApiException(e); } } @Override public void configureKerberos(KerberosConfig kerberosConfig) { ClusterView cluster = stack.getCluster(); try { ClouderaManagerRepo clouderaManagerRepoDetails = clusterComponentProvider.getClouderaManagerRepoDetails(cluster.getId()); if (!CMRepositoryVersionUtil.isEnableKerberosSupportedViaBlueprint(clouderaManagerRepoDetails)) { kerberosService.configureKerberosViaApi(apiClient, clientConfig, stack, kerberosConfig); } } catch (ApiException e) { throw mapApiException(e); } catch (Exception e) { throw mapException(e); } } @Override public void installCluster(String template) { ClusterView cluster = stack.getCluster(); try { Optional<ApiCluster> cmCluster = getCmClusterByName(cluster.getName()); boolean prewarmed = isPrewarmed(cluster.getId()); Optional<ClusterCommand> importCommand = clusterCommandRepository.findTopByClusterIdAndClusterCommandType(cluster.getId(), ClusterCommandType.IMPORT_CLUSTER); if (cmCluster.isEmpty() || importCommand.isEmpty()) { ApiClusterTemplate apiClusterTemplate = JsonUtil.readValue(template, ApiClusterTemplate.class); ClouderaManagerResourceApi clouderaManagerResourceApi = clouderaManagerApiFactory.getClouderaManagerResourceApi(apiClient); LOGGER.info("Generated Cloudera cluster template: {}", AnonymizerUtil.anonymize(template)); // addRepositories - if true the parcels repositories in the cluster template // will be added. ApiCommand apiCommand = clouderaManagerResourceApi .importClusterTemplate(calculateAddRepositories(apiClusterTemplate, prewarmed), apiClusterTemplate); ClusterCommand clusterCommand = new ClusterCommand(); clusterCommand.setClusterId(cluster.getId()); clusterCommand.setCommandId(apiCommand.getId()); clusterCommand.setClusterCommandType(ClusterCommandType.IMPORT_CLUSTER); importCommand = Optional.of(clusterCommandRepository.save(clusterCommand)); LOGGER.debug("Cloudera cluster template has been submitted, cluster install is in progress"); } importCommand.ifPresent(cmd -> clouderaManagerPollingServiceProvider.startPollingCmTemplateInstallation(stack, apiClient, cmd.getCommandId())); } catch (ApiException e) { String msg = "Installation of CDP with Cloudera Manager has failed: " + extractMessage(e); throw new ClouderaManagerOperationFailedException(msg, e); } catch (CloudStorageConfigurationFailedException e) { LOGGER.info("Error while configuring cloud storage. Message: {}", e.getMessage(), e); throw new ClouderaManagerOperationFailedException(mapStorageError(e, stack.getResourceCrn(), stack.getCloudPlatform(), cluster), e); } catch (Exception e) { throw mapException(e); } } private String mapStorageError(CloudStorageConfigurationFailedException exception, String stackCrn, String cloudPlatform, ClusterView cluster) { String accountId = Crn.safeFromString(stackCrn).getAccountId(); String result = exception.getMessage(); if ((CloudPlatform.AWS.equalsIgnoreCase(cloudPlatform) && !entitlementService.awsCloudStorageValidationEnabled(accountId)) || (CloudPlatform.AZURE.equalsIgnoreCase(cloudPlatform) && !entitlementService.azureCloudStorageValidationEnabled(accountId)) || (CloudPlatform.GCP.equalsIgnoreCase(cloudPlatform) && !entitlementService.gcpCloudStorageValidationEnabled(accountId))) { result = clouderaManagerStorageErrorMapper.map(exception, cloudPlatform, cluster); } return result; } @Override public void autoConfigureClusterManager() { MgmtServiceResourceApi mgmtApi = clouderaManagerApiFactory.getMgmtServiceResourceApi(apiClient); try { mgmtApi.autoConfigure(); } catch (ApiException e) { String msg = "Error happened when CM autoconfigure was called: " + extractMessage(e); LOGGER.error(msg, e); throw new ClouderaManagerOperationFailedException(msg, e); } } @Override public void updateConfig() { com.sequenceiq.cloudbreak.api.endpoint.v4.common.StackType stackType = stack.getType(); try { ClouderaManagerResourceApi clouderaManagerResourceApi = clouderaManagerApiFactory.getClouderaManagerResourceApi(apiClient); ApiConfigList apiConfigList = new ApiConfigList() .addItemsItem(removeRemoteParcelRepos()) .addItemsItem(setHeader(stackType)); clouderaManagerResourceApi.updateConfig("Updated configurations.", apiConfigList); } catch (ApiException e) { throw mapApiException(e); } catch (Exception e) { throw mapException(e); } } @Override public void refreshParcelRepos() { try { boolean prewarmed = isPrewarmed(stack.getCluster().getId()); if (prewarmed) { ClouderaManagerResourceApi clouderaManagerResourceApi = clouderaManagerApiFactory.getClouderaManagerResourceApi(apiClient); ApiCommand apiCommand = clouderaManagerResourceApi.refreshParcelRepos(); clouderaManagerPollingServiceProvider.startPollingCmParcelRepositoryRefresh(stack, apiClient, apiCommand.getId()); } } catch (Exception e) { LOGGER.info("Unable to refresh parcel repo", e); throw new CloudbreakServiceException(e); } } @Override public ExtendedPollingResult waitForHosts(Set<InstanceMetadataView> hostsInCluster) throws ClusterClientInitException { ClusterView cluster = stack.getCluster(); String user = cluster.getCloudbreakAmbariUser(); String password = cluster.getCloudbreakAmbariPassword(); ApiClient client; try { client = clouderaManagerApiClientProvider.getV31Client(stack.getGatewayPort(), user, password, clientConfig); } catch (ClouderaManagerClientInitException e) { throw new ClusterClientInitException(e); } List<String> privateIps = hostsInCluster.stream().map(InstanceMetadataView::getPrivateIp).collect(Collectors.toList()); return clouderaManagerPollingServiceProvider.startPollingCmHostStatus(stack, client, privateIps); } @Override public void waitForHostsHealthy(Set<InstanceMetadataView> hostsInCluster) throws ClusterClientInitException { ClusterView cluster = stack.getCluster(); String user = cluster.getCloudbreakAmbariUser(); String password = cluster.getCloudbreakAmbariPassword(); ApiClient client; try { client = clouderaManagerApiClientProvider.getV31Client(stack.getGatewayPort(), user, password, clientConfig); } catch (ClouderaManagerClientInitException e) { throw new ClusterClientInitException(e); } clouderaManagerPollingServiceProvider.startPollingCmHostStatusHealthy( stack, client, hostsInCluster.stream().map(x -> x.getDiscoveryFQDN()).collect(Collectors.toUnmodifiableSet())); } @Override public void waitForServices(int requestId) { } @Override public String getSdxContext() { ClusterView cluster = stack.getCluster(); String user = cluster.getCloudbreakAmbariUser(); String password = cluster.getCloudbreakAmbariPassword(); try { ApiClient rootClient = clouderaManagerApiClientProvider.getRootClient(stack.getGatewayPort(), user, password, clientConfig); CdpResourceApi cdpResourceApi = clouderaManagerApiFactory.getCdpResourceApi(rootClient); LOGGER.info("Get remote context from Datalake cluster: {}", stack.getName()); ApiRemoteDataContext remoteDataContext = cdpResourceApi.getRemoteContextByCluster(stack.getName()); return JsonUtil.writeValueAsString(remoteDataContext); } catch (ApiException | ClouderaManagerClientInitException e) { LOGGER.error("Error while getting remote context of Datalake cluster: {}", stack.getName(), e); throw new ClouderaManagerOperationFailedException("Error while getting remote context of Datalake cluster", e); } catch (JsonProcessingException e) { LOGGER.error("Failed to serialize remote context.", e); throw new ClouderaManagerOperationFailedException("Failed to serialize remote context.", e); } } @Override public void setupProxy(ProxyConfig proxyConfig) { LOGGER.info("Setup proxy for CM"); ClouderaManagerResourceApi clouderaManagerResourceApi = clouderaManagerApiFactory.getClouderaManagerResourceApi(apiClient); ApiConfigList proxyConfigList = new ApiConfigList(); proxyConfigList.addItemsItem(new ApiConfig().name("parcel_proxy_server").value(proxyConfig.getServerHost())); proxyConfigList.addItemsItem(new ApiConfig().name("parcel_proxy_port").value(String.valueOf(proxyConfig.getServerPort()))); proxyConfigList.addItemsItem(new ApiConfig().name("parcel_proxy_protocol").value(proxyConfig.getProtocol().toUpperCase())); proxyConfig.getProxyAuthentication().ifPresent(auth -> { proxyConfigList.addItemsItem(new ApiConfig().name("parcel_proxy_user").value(auth.getUserName())); proxyConfigList.addItemsItem(new ApiConfig().name("parcel_proxy_password").value(auth.getPassword())); }); addNoProxyHosts(proxyConfig, proxyConfigList); try { LOGGER.info("Update settings with: " + proxyConfigList); clouderaManagerResourceApi.updateConfig("Update proxy settings", proxyConfigList); } catch (ApiException e) { String failMessage = "Update proxy settings failed"; LOGGER.error(failMessage, e); throw new ClouderaManagerOperationFailedException(failMessage, e); } } private void addNoProxyHosts(ProxyConfig proxyConfig, ApiConfigList proxyConfigList) { if (StringUtils.isNotBlank(proxyConfig.getNoProxyHosts())) { ClusterView cluster = stack.getCluster(); ClouderaManagerRepo clouderaManagerRepoDetails = clusterComponentProvider.getClouderaManagerRepoDetails(cluster.getId()); if (isVersionNewerOrEqualThanLimited(clouderaManagerRepoDetails::getVersion, CLOUDERAMANAGER_VERSION_7_6_0)) { proxyConfigList.addItemsItem(new ApiConfig().name("parcel_no_proxy_list").value(proxyConfig.getNoProxyHosts())); } } } @Override public String setupRemoteDataContext(String sdxContext) { ClusterView cluster = stack.getCluster(); String user = cluster.getCloudbreakAmbariUser(); String password = cluster.getCloudbreakAmbariPassword(); try { ApiClient rootClient = clouderaManagerApiClientProvider.getRootClient(stack.getGatewayPort(), user, password, clientConfig); CdpResourceApi cdpResourceApi = clouderaManagerApiFactory.getCdpResourceApi(rootClient); ApiRemoteDataContext apiRemoteDataContext = JsonUtil.readValue(sdxContext, ApiRemoteDataContext.class); LOGGER.debug("Posting remote context to workload. EndpointId: {}", apiRemoteDataContext.getEndPointId()); return cdpResourceApi.postRemoteContext(apiRemoteDataContext).getEndPointId(); } catch (ApiException | ClouderaManagerClientInitException e) { LOGGER.info("Error while creating data context using: {}", sdxContext, e); throw new ClouderaManagerOperationFailedException(String.format("Error while creating data context: %s", e.getMessage()), e); } catch (IOException e) { LOGGER.info("Failed to parse SDX context to CM API object.", e); throw new ClouderaManagerOperationFailedException(String.format("Failed to parse SDX context to CM API object: %s", e.getMessage()), e); } } private ClouderaManagerOperationFailedException mapApiException(ApiException e) { LOGGER.info("Error while building the cluster. Message: {}; Response: {}", e.getMessage(), e.getResponseBody(), e); String msg = extractMessage(e); return new ClouderaManagerOperationFailedException(msg, e); } private ClouderaManagerOperationFailedException mapException(Exception e) { LOGGER.info("Error while building the cluster. Message: {}", e.getMessage(), e); return new ClouderaManagerOperationFailedException(e.getMessage(), e); } private ApiClient createApiClient() throws ClusterClientInitException { ApiClient client = null; try { client = clouderaManagerApiClientProvider.getDefaultClient(stack.getGatewayPort(), clientConfig, ClouderaManagerApiClientProvider.API_V_31); ToolsResourceApi toolsResourceApi = clouderaManagerApiFactory.getToolsResourceApi(client); toolsResourceApi.echo("TEST"); LOGGER.debug("Cloudera Manager already running, old admin user's password has not been changed yet."); return client; } catch (ClouderaManagerClientInitException e) { throw new ClusterClientInitException(e); } catch (ApiException e) { return returnClientBasedOnApiError(client, e); } } private ApiClient returnClientBasedOnApiError(ApiClient client, ApiException e) { if (org.springframework.http.HttpStatus.UNAUTHORIZED.value() == e.getCode()) { LOGGER.debug("Cloudera Manager already running, old admin user's password has been changed."); return apiClient; } LOGGER.debug("Cloudera Manager is not running yet.", e); return client; } private ApiClusterTemplate getCmTemplate(TemplatePreparationObject templatePreparationObject, String sdxContextName, Map<HostGroup, List<InstanceMetaData>> instanceMetaDataByHostGroup, ClouderaManagerRepo clouderaManagerRepoDetails, Long clusterId) { List<ClouderaManagerProduct> clouderaManagerProductDetails = clusterComponentProvider.getClouderaManagerProductDetails(clusterId); Map<String, List<Map<String, String>>> hostGroupMappings = hostGroupAssociationBuilder.buildHostGroupAssociations(instanceMetaDataByHostGroup); return cmTemplateUpdater.getCmTemplate(templatePreparationObject, hostGroupMappings, clouderaManagerRepoDetails, clouderaManagerProductDetails, sdxContextName); } private void configureCmMgmtServices(TemplatePreparationObject templatePreparationObject, String sdxCrn, Telemetry telemetry, String sdxContextName, ProxyConfig proxyConfig) throws ApiException { Optional<ApiHost> optionalCmHost = getCmHost(templatePreparationObject, apiClient); if (optionalCmHost.isPresent()) { ApiHost cmHost = optionalCmHost.get(); ApiHostRef cmHostRef = new ApiHostRef(); cmHostRef.setHostId(cmHost.getHostId()); cmHostRef.setHostname(cmHost.getHostname()); mgmtSetupService.setupMgmtServices(stack, apiClient, cmHostRef, telemetry, sdxContextName, sdxCrn, proxyConfig); } else { LOGGER.warn("Unable to determine Cloudera Manager host. Skipping management services installation."); } } private void configureCmSupportTag(TemplatePreparationObject templatePreparationObject) throws ApiException { Optional<ApiHost> optionalCmHost = getCmHost(templatePreparationObject, apiClient); if (optionalCmHost.isPresent()) { clouderaManagerSupportSetupService.prepareSupportRole(apiClient, stack.getType()); } else { LOGGER.warn("Unable to determine Cloudera Manager host. Skipping support tag setup."); } } private Optional<ApiHost> getCmHost(TemplatePreparationObject templatePreparationObject, ApiClient apiClient) throws ApiException { HostsResourceApi hostsResourceApi = clouderaManagerApiFactory.getHostsResourceApi(apiClient); return hostsResourceApi.readHosts(null, null, DataView.SUMMARY.name()) .getItems() .stream() .filter(host -> host.getHostname().equals(templatePreparationObject.getGeneralClusterConfigs().getPrimaryGatewayInstanceDiscoveryFQDN().get())) .findFirst(); } private boolean calculateAddRepositories(ApiClusterTemplate apiClusterTemplate, boolean prewarmed) { boolean addRepositories = !prewarmed; if (apiClusterTemplate.getCmVersion() != null && isVersionNewerOrEqualThanLimited(apiClusterTemplate.getCmVersion(), CLOUDERAMANAGER_VERSION_7_2_0)) { addRepositories = true; } return addRepositories; } private Optional<ApiCluster> getCmClusterByName(String name) throws ApiException { ClustersResourceApi clustersResourceApi = clouderaManagerApiFactory.getClustersResourceApi(apiClient); try { return Optional.of(clustersResourceApi.readCluster(name)); } catch (ApiException apiException) { if (apiException.getCode() != HttpStatus.SC_NOT_FOUND) { throw apiException; } return Optional.empty(); } } private ApiConfig removeRemoteParcelRepos() { return new ApiConfig().name("remote_parcel_repo_urls").value(""); } private ApiConfig setHeader(com.sequenceiq.cloudbreak.api.endpoint.v4.common.StackType stackType) { return new ApiConfig().name("custom_header_color").value(StackType.DATALAKE.equals(stackType) ? "RED" : "BLUE"); } private String getExtendedBlueprintText(ApiClusterTemplate apiClusterTemplate) { return JsonUtil.writeValueAsStringSilent(apiClusterTemplate); } private Boolean isPrewarmed(Long clusterId) { return clusterComponentProvider.getClouderaManagerRepoDetails(clusterId).getPredefined(); } private String extractMessage(ApiException apiException) { if (StringUtils.isEmpty(apiException.getResponseBody())) { return apiException.getMessage(); } try { JsonNode tree = JsonUtil.readTree(apiException.getResponseBody()); JsonNode message = tree.get("message"); if (message != null && message.isTextual()) { String text = message.asText(); if (StringUtils.isNotEmpty(text)) { return text; } } } catch (IOException e) { LOGGER.debug("Failed to parse API response body as JSON", e); } return apiException.getResponseBody(); } }
{ "content_hash": "a36f378a3b1da012776e9cdaa980b0b0", "timestamp": "", "source": "github", "line_count": 589, "max_line_length": 159, "avg_line_length": 50.72665534804754, "alnum_prop": 0.7262534306178459, "repo_name": "hortonworks/cloudbreak", "id": "b9974e299e2bd9274c933eaf3cfa971033904caa", "size": "29878", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cluster-cm/src/main/java/com/sequenceiq/cloudbreak/cm/ClouderaManagerSetupService.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "7535" }, { "name": "Dockerfile", "bytes": "9586" }, { "name": "Fluent", "bytes": "10" }, { "name": "FreeMarker", "bytes": "395982" }, { "name": "Groovy", "bytes": "523" }, { "name": "HTML", "bytes": "9917" }, { "name": "Java", "bytes": "55250904" }, { "name": "JavaScript", "bytes": "47923" }, { "name": "Jinja", "bytes": "190660" }, { "name": "Makefile", "bytes": "8537" }, { "name": "PLpgSQL", "bytes": "1830" }, { "name": "Perl", "bytes": "17726" }, { "name": "Python", "bytes": "29898" }, { "name": "SaltStack", "bytes": "222692" }, { "name": "Scala", "bytes": "11168" }, { "name": "Shell", "bytes": "416225" } ], "symlink_target": "" }
#include "core/html/track/TextTrackCueList.h" #include "wtf/StdLibExtras.h" #include <algorithm> namespace blink { TextTrackCueList::TextTrackCueList() : m_firstInvalidIndex(0) { } unsigned long TextTrackCueList::length() const { return m_list.size(); } TextTrackCue* TextTrackCueList::anonymousIndexedGetter(unsigned index) const { if (index < m_list.size()) return m_list[index].get(); return nullptr; } TextTrackCue* TextTrackCueList::getCueById(const AtomicString& id) const { for (size_t i = 0; i < m_list.size(); ++i) { if (m_list[i]->id() == id) return m_list[i].get(); } return nullptr; } void TextTrackCueList::collectActiveCues(TextTrackCueList& activeCues) const { activeCues.clear(); for (auto& cue : m_list) { if (cue->isActive()) activeCues.add(cue); } } bool TextTrackCueList::add(TextTrackCue* cue) { DCHECK_GE(cue->startTime(), 0); DCHECK_GE(cue->endTime(), 0); // Maintain text track cue order: // https://html.spec.whatwg.org/#text-track-cue-order size_t index = findInsertionIndex(cue); // FIXME: The cue should not exist in the list in the first place. if (!m_list.isEmpty() && (index > 0) && (m_list[index - 1].get() == cue)) return false; m_list.insert(index, cue); invalidateCueIndex(index); return true; } static bool cueIsBefore(const TextTrackCue* cue, TextTrackCue* otherCue) { if (cue->startTime() < otherCue->startTime()) return true; return cue->startTime() == otherCue->startTime() && cue->endTime() > otherCue->endTime(); } size_t TextTrackCueList::findInsertionIndex(const TextTrackCue* cueToInsert) const { auto it = std::upper_bound(m_list.begin(), m_list.end(), cueToInsert, cueIsBefore); size_t index = safeCast<size_t>(it - m_list.begin()); SECURITY_DCHECK(index <= m_list.size()); return index; } bool TextTrackCueList::remove(TextTrackCue* cue) { size_t index = m_list.find(cue); if (index == kNotFound) return false; m_list.remove(index); invalidateCueIndex(index); cue->invalidateCueIndex(); return true; } void TextTrackCueList::updateCueIndex(TextTrackCue* cue) { if (!remove(cue)) return; add(cue); } void TextTrackCueList::clear() { m_list.clear(); } void TextTrackCueList::invalidateCueIndex(size_t index) { // Store the smallest (first) index that we know has a cue that does not // meet the criteria: // cueIndex(list[index-1]) + 1 == cueIndex(list[index]) [index > 0] // This is a stronger requirement than we need, but it's easier to maintain. // We can then check if a cue's index is valid by comparing it with // |m_firstInvalidIndex| - if it's strictly less it is valid. m_firstInvalidIndex = std::min(m_firstInvalidIndex, index); } void TextTrackCueList::validateCueIndexes() { // Compute new index values for the cues starting at // |m_firstInvalidIndex|. If said index is beyond the end of the list, no // cues will need to be updated. for (size_t i = m_firstInvalidIndex; i < m_list.size(); ++i) m_list[i]->updateCueIndex(safeCast<unsigned>(i)); m_firstInvalidIndex = m_list.size(); } DEFINE_TRACE(TextTrackCueList) { visitor->trace(m_list); } DEFINE_TRACE_WRAPPERS(TextTrackCueList) { for (auto cue : m_list) { visitor->traceWrappers(cue); } } } // namespace blink
{ "content_hash": "2fb3642bde749742fe47b4a5ca269ac7", "timestamp": "", "source": "github", "line_count": 135, "max_line_length": 93, "avg_line_length": 25.533333333333335, "alnum_prop": 0.656803017116333, "repo_name": "danakj/chromium", "id": "5ee268e923a880e4161985b7e8866177a2a751bd", "size": "4799", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "third_party/WebKit/Source/core/html/track/TextTrackCueList.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
"""Support for MySensors covers.""" from __future__ import annotations from enum import Enum, unique from typing import Any from homeassistant.components import mysensors from homeassistant.components.cover import ATTR_POSITION, DOMAIN, CoverEntity from homeassistant.components.mysensors.const import MYSENSORS_DISCOVERY, DiscoveryInfo from homeassistant.config_entries import ConfigEntry from homeassistant.const import STATE_OFF, STATE_ON from homeassistant.core import HomeAssistant from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.entity_platform import AddEntitiesCallback from .helpers import on_unload @unique class CoverState(Enum): """An enumeration of the standard cover states.""" OPEN = 0 OPENING = 1 CLOSING = 2 CLOSED = 3 async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up this platform for a specific ConfigEntry(==Gateway).""" async def async_discover(discovery_info: DiscoveryInfo) -> None: """Discover and add a MySensors cover.""" mysensors.setup_mysensors_platform( hass, DOMAIN, discovery_info, MySensorsCover, async_add_entities=async_add_entities, ) on_unload( hass, config_entry.entry_id, async_dispatcher_connect( hass, MYSENSORS_DISCOVERY.format(config_entry.entry_id, DOMAIN), async_discover, ), ) class MySensorsCover(mysensors.device.MySensorsEntity, CoverEntity): """Representation of the value of a MySensors Cover child node.""" def get_cover_state(self) -> CoverState: """Return a CoverState enum representing the state of the cover.""" set_req = self.gateway.const.SetReq v_up = self._values.get(set_req.V_UP) == STATE_ON v_down = self._values.get(set_req.V_DOWN) == STATE_ON v_stop = self._values.get(set_req.V_STOP) == STATE_ON # If a V_DIMMER or V_PERCENTAGE is available, that is the amount # the cover is open. Otherwise, use 0 or 100 based on the V_LIGHT # or V_STATUS. amount = 100 if set_req.V_DIMMER in self._values: amount = self._values[set_req.V_DIMMER] else: amount = 100 if self._values.get(set_req.V_LIGHT) == STATE_ON else 0 if amount == 0: return CoverState.CLOSED if v_up and not v_down and not v_stop: return CoverState.OPENING if not v_up and v_down and not v_stop: return CoverState.CLOSING return CoverState.OPEN @property def is_closed(self) -> bool: """Return True if the cover is closed.""" return self.get_cover_state() == CoverState.CLOSED @property def is_closing(self) -> bool: """Return True if the cover is closing.""" return self.get_cover_state() == CoverState.CLOSING @property def is_opening(self) -> bool: """Return True if the cover is opening.""" return self.get_cover_state() == CoverState.OPENING @property def current_cover_position(self) -> int | None: """Return current position of cover. None is unknown, 0 is closed, 100 is fully open. """ set_req = self.gateway.const.SetReq return self._values.get(set_req.V_DIMMER) async def async_open_cover(self, **kwargs: Any) -> None: """Move the cover up.""" set_req = self.gateway.const.SetReq self.gateway.set_child_value( self.node_id, self.child_id, set_req.V_UP, 1, ack=1 ) if self.assumed_state: # Optimistically assume that cover has changed state. if set_req.V_DIMMER in self._values: self._values[set_req.V_DIMMER] = 100 else: self._values[set_req.V_LIGHT] = STATE_ON self.async_write_ha_state() async def async_close_cover(self, **kwargs: Any) -> None: """Move the cover down.""" set_req = self.gateway.const.SetReq self.gateway.set_child_value( self.node_id, self.child_id, set_req.V_DOWN, 1, ack=1 ) if self.assumed_state: # Optimistically assume that cover has changed state. if set_req.V_DIMMER in self._values: self._values[set_req.V_DIMMER] = 0 else: self._values[set_req.V_LIGHT] = STATE_OFF self.async_write_ha_state() async def async_set_cover_position(self, **kwargs: Any) -> None: """Move the cover to a specific position.""" position = kwargs.get(ATTR_POSITION) set_req = self.gateway.const.SetReq self.gateway.set_child_value( self.node_id, self.child_id, set_req.V_DIMMER, position, ack=1 ) if self.assumed_state: # Optimistically assume that cover has changed state. self._values[set_req.V_DIMMER] = position self.async_write_ha_state() async def async_stop_cover(self, **kwargs: Any) -> None: """Stop the device.""" set_req = self.gateway.const.SetReq self.gateway.set_child_value( self.node_id, self.child_id, set_req.V_STOP, 1, ack=1 )
{ "content_hash": "b1aba3b944937141ab365156552fb72f", "timestamp": "", "source": "github", "line_count": 153, "max_line_length": 87, "avg_line_length": 35.11764705882353, "alnum_prop": 0.6195793783733482, "repo_name": "lukas-hetzenecker/home-assistant", "id": "9219097bea455b40ee4fe8fbe9f60c511082d058", "size": "5373", "binary": false, "copies": "3", "ref": "refs/heads/dev", "path": "homeassistant/components/mysensors/cover.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "2443" }, { "name": "Python", "bytes": "38023745" }, { "name": "Shell", "bytes": "4910" } ], "symlink_target": "" }
import android.app.Activity; import android.os.Bundle; public class InstanceStateIntWithOnCreateActivity extends Activity { private int myInt; @Override protected void onCreate(Bundle state) { if (state != null) { this.myInt = state.getInt("myInt"); } super.onCreate(state); } @Override protected void onSaveInstanceState(Bundle state) { state.putInt("myInt", this.myInt); super.onSaveInstanceState(state); } }
{ "content_hash": "56cb74cd69780a8b3f04151b2fa86b40", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 68, "avg_line_length": 20.857142857142858, "alnum_prop": 0.7328767123287672, "repo_name": "Shedings/hrisey", "id": "75d36436b29649be30d334105e0ca73cee90a6b4", "size": "438", "binary": false, "copies": "3", "ref": "refs/heads/develop", "path": "test/transform/resource/after-delombok/InstanceStateIntWithOnCreateActivity.java", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "1905" }, { "name": "CSS", "bytes": "5532" }, { "name": "HTML", "bytes": "206142" }, { "name": "Java", "bytes": "2664250" }, { "name": "JavaScript", "bytes": "4148" } ], "symlink_target": "" }
require 'spec_helper' describe Travis::Api::App::Endpoint do class MyEndpoint < Travis::Api::App::Endpoint set :prefix, '/my_endpoint' get('/') { 'ok' } end it 'sets up endpoints automatically under given prefix' do get('/my_endpoint/').should be_ok body.should == "ok" end it 'does not require a trailing slash' do get('/my_endpoint').should be_ok body.should == "ok" end end
{ "content_hash": "18776ae823e06e2415a753ac7a1a703c", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 60, "avg_line_length": 23.11111111111111, "alnum_prop": 0.6442307692307693, "repo_name": "Tiger66639/travis-api", "id": "d5a01f6b724eec28a8b7ac3a5dd286136bf4b501", "size": "416", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/unit/endpoint_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "498801" }, { "name": "Shell", "bytes": "318" } ], "symlink_target": "" }
//---------------------------------------------------------------------------------- // Microsoft Developer & Platform Evangelism // // Copyright (c) Microsoft Corporation. All rights reserved. // // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, // EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. //---------------------------------------------------------------------------------- // The example companies, organizations, products, domain names, // e-mail addresses, logos, people, places, and events depicted // herein are fictitious. No association with any real company, // organization, product, domain name, email address, logo, person, // places, or events is intended or should be inferred. //---------------------------------------------------------------------------------- using System; using System.Globalization; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Management.Storage; using Microsoft.WindowsAzure.Management.Storage.Models; using AzureQuickStarts.Common; namespace DeployManageAzureStorage { internal partial class ManagementController : IDisposable { private StorageManagementClient _storageManagementClient; private PublishSettingsSubscriptionItem _publishSettingCreds; private ManagementControllerParameters _parameters; public ManagementController(ManagementControllerParameters parameters) { _parameters = parameters; // To authenticate against the Microsoft Azure service management API we require management certificate // load this from a publish settings file and later use it with the Service Management Libraries var credential = GetSubscriptionCloudCredentials(parameters.PublishSettingsFilePath); _storageManagementClient = CloudContext.Clients.CreateStorageManagementClient(credential); } private SubscriptionCloudCredentials GetSubscriptionCloudCredentials(string publishSettingsFilePath) { using (var fs = File.OpenRead(publishSettingsFilePath)) { var document = XDocument.Load(fs); var subscriptions = from e in document.Descendants("Subscription") select e; if (subscriptions.Count() >= 1) { // use first subscription in the publish settings file var subscription = subscriptions.First(); _publishSettingCreds = new PublishSettingsSubscriptionItem { SubscriptionName = subscription.Attribute("Name").Value, SubscriptionId = subscription.Attribute("Id").Value, ManagementCertificate = subscription.Attribute("ManagementCertificate").Value }; } else { Console.WriteLine("Invalid publishsettings file: Subscription not found."); } } return CertificateAuthenticationHelper.GetCredentials(_publishSettingCreds.SubscriptionId, _publishSettingCreds.ManagementCertificate); } internal bool CheckNameAvailbility() { CheckNameAvailabilityResponse r = _storageManagementClient.StorageAccounts.CheckNameAvailability( _parameters.StorageAccountName); return r.IsAvailable; } internal void CreateStorageAccount() { //Create a storage account in the given region _storageManagementClient.StorageAccounts.Create( new StorageAccountCreateParameters { Location = _parameters.Region, Name = _parameters.StorageAccountName, AccountType = _parameters.StorageAccountType }); } internal async Task CreateStorageAccountAsync() { //Create a storage account in the given region await _storageManagementClient.StorageAccounts.CreateAsync( new StorageAccountCreateParameters { Location = _parameters.Region, Name = _parameters.StorageAccountName, AccountType = _parameters.StorageAccountType }); } internal string GetStorageAccountConnectionString() { //Retrieve the storage account keys var keys = _storageManagementClient.StorageAccounts.GetKeys(_parameters.StorageAccountName); string connectionString = string.Format( CultureInfo.InvariantCulture, "DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}", _parameters.StorageAccountName, keys.PrimaryKey); return connectionString; } internal void RegenerateKeys() { StorageAccountRegenerateKeysParameters kp = new StorageAccountRegenerateKeysParameters(); kp.KeyType = StorageKeyType.Primary; kp.Name = _parameters.StorageAccountName; _storageManagementClient.StorageAccounts.RegenerateKeys(kp); } internal void UpdateStorageAccount(string Description, string Label, string AccountType) { var parms = new StorageAccountUpdateParameters(); parms.Description = Description; parms.Label = Label; parms.AccountType = AccountType; _storageManagementClient.StorageAccounts.Update( _parameters.StorageAccountName, parms); } internal StorageAccountGetResponse GetStorageAccountProperties() { StorageAccountGetResponse gr = new StorageAccountGetResponse(); gr = _storageManagementClient.StorageAccounts.Get( _parameters.StorageAccountName); return gr; } internal StorageAccountListResponse ListStorageAccounts() { var list = _storageManagementClient.StorageAccounts.List(); return list; } internal void TearDown() { //tear down everything that was created _storageManagementClient.StorageAccounts.Delete( _parameters.StorageAccountName); } public void Dispose() { if (_storageManagementClient != null) _storageManagementClient.Dispose(); } } }
{ "content_hash": "0f01ca8b9e5e884aeab29e769599d03f", "timestamp": "", "source": "github", "line_count": 174, "max_line_length": 147, "avg_line_length": 38.775862068965516, "alnum_prop": 0.6116792648584556, "repo_name": "vipinsehgal/AzureQuickStartsProjects", "id": "1e0a19b4e39c5d5e98efe0d3b3ffbe942914a92f", "size": "6749", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Data Services/DeployManageAzureStorage/ManagementController.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "336757" }, { "name": "Groff", "bytes": "98574" } ], "symlink_target": "" }
import math import torch import torch.nn as nn from fairseq import utils class SinusoidalPositionalEmbedding(nn.Module): """This module produces sinusoidal positional embeddings of any length. Padding symbols are ignored, but it is necessary to specify whether padding is added on the left side (left_pad=True) or right side (left_pad=False). """ def __init__(self, embedding_dim, padding_idx, left_pad, init_size=1024): super().__init__() self.embedding_dim = embedding_dim self.padding_idx = padding_idx self.left_pad = left_pad self.weights = SinusoidalPositionalEmbedding.get_embedding( init_size, embedding_dim, padding_idx, ) self.register_buffer('_float_tensor', torch.FloatTensor(1)) @staticmethod def get_embedding(num_embeddings, embedding_dim, padding_idx=None): """Build sinusoidal embeddings. This matches the implementation in tensor2tensor, but differs slightly from the description in Section 3.5 of "Attention Is All You Need". """ half_dim = embedding_dim // 2 emb = math.log(10000) / (half_dim - 1) emb = torch.exp(torch.arange(half_dim, dtype=torch.float) * -emb) emb = torch.arange(num_embeddings, dtype=torch.float).unsqueeze(1) * emb.unsqueeze(0) emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1).view(num_embeddings, -1) if embedding_dim % 2 == 1: # zero pad emb = torch.cat([emb, torch.zeros(num_embeddings, 1)], dim=1) if padding_idx is not None: emb[padding_idx, :] = 0 return emb def forward(self, input, incremental_state=None): """Input is expected to be of size [bsz x seqlen].""" # recompute/expand embeddings if needed bsz, seq_len = input.size() max_pos = self.padding_idx + 1 + seq_len if self.weights is None or max_pos > self.weights.size(0): self.weights = SinusoidalPositionalEmbedding.get_embedding( max_pos, self.embedding_dim, self.padding_idx, ) self.weights = self.weights.type_as(self._float_tensor) if incremental_state is not None: # positions is the same for every token when decoding a single step return self.weights[self.padding_idx + seq_len, :].expand(bsz, 1, -1) positions = utils.make_positions(input.data, self.padding_idx, self.left_pad) return self.weights.index_select(0, positions.view(-1)).view(bsz, seq_len, -1).detach() def max_positions(self): """Maximum number of supported positions.""" return int(1e5) # an arbitrary large number
{ "content_hash": "535f630cf458b264b12597429b10ba20", "timestamp": "", "source": "github", "line_count": 69, "max_line_length": 95, "avg_line_length": 40.01449275362319, "alnum_prop": 0.6247736327417602, "repo_name": "mlperf/training_results_v0.6", "id": "4b000e892eef4a94a3faa4477a9a878b3eca8f41", "size": "3047", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "NVIDIA/benchmarks/transformer/implementations/pytorch/fairseq/modules/sinusoidal_positional_embedding.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "1731" }, { "name": "Batchfile", "bytes": "13941" }, { "name": "C", "bytes": "208630" }, { "name": "C++", "bytes": "10999411" }, { "name": "CMake", "bytes": "129712" }, { "name": "CSS", "bytes": "64767" }, { "name": "Clojure", "bytes": "396764" }, { "name": "Cuda", "bytes": "2272433" }, { "name": "Dockerfile", "bytes": "67820" }, { "name": "Groovy", "bytes": "62557" }, { "name": "HTML", "bytes": "19753082" }, { "name": "Java", "bytes": "166294" }, { "name": "JavaScript", "bytes": "71846" }, { "name": "Julia", "bytes": "408765" }, { "name": "Jupyter Notebook", "bytes": "2713169" }, { "name": "Lua", "bytes": "4430" }, { "name": "MATLAB", "bytes": "34903" }, { "name": "Makefile", "bytes": "115694" }, { "name": "Perl", "bytes": "1535873" }, { "name": "Perl 6", "bytes": "7280" }, { "name": "PowerShell", "bytes": "6150" }, { "name": "Python", "bytes": "24905683" }, { "name": "R", "bytes": "351865" }, { "name": "Roff", "bytes": "293052" }, { "name": "Scala", "bytes": "1189019" }, { "name": "Shell", "bytes": "794096" }, { "name": "Smalltalk", "bytes": "3497" }, { "name": "TypeScript", "bytes": "361164" } ], "symlink_target": "" }
package com.nec.strudel.tkvs.store.mongodb; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.Random; import org.apache.log4j.Logger; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.MongoClient; import com.mongodb.ServerAddress; import com.nec.strudel.target.TargetLifecycle; import com.nec.strudel.tkvs.BackoffPolicy; import com.nec.strudel.tkvs.TkvStoreException; import com.nec.strudel.tkvs.impl.TransactionProfiler; import com.nec.strudel.tkvs.impl.TransactionalDbServer; import com.nec.strudel.tkvs.store.TransactionalStore; import com.nec.strudel.tkvs.store.impl.AbstractTransactionalStore; /** * property: * <ul> * <li> mongodb.mongos: server addresses to mongos * (e.g., "example1:27017,example2:27017", * "example1,example2,example3", "localhost") * The store uses the local one if it is in the list. * Otherwise, it randomly chooses one in the list. * </ul> * @author tatemura, Zheng Li (initial version) * */ public class MongodbStore extends AbstractTransactionalStore implements TransactionalStore { private static final Logger LOGGER = Logger.getLogger(MongodbStore.class); @Override public MongoDbServer createDbServer(String dbName, Properties props) { ServerAddress addr = chooseOne(getServerAddressList(props)); LOGGER.info("using mongos@" + addr.getHost() + ":" + addr.getPort()); try { return new MongoDbServer(dbName, addr, new BackoffPolicy(props)); } catch (IOException e) { throw new TkvStoreException( "MongodbStore failed to create (IOException)", e); } } ServerAddress chooseOne(List<ServerAddress> addrs) { if (addrs.size() == 1) { return addrs.get(0); } InetAddress local = thisHost(); String host = local.getHostName(); for (ServerAddress a : addrs) { if (a.sameHost("localhost")) { return a; } else if (a.sameHost(host)) { return a; } else { try { InetAddress addr = InetAddress.getByName( a.getHost()); if (local.equals(addr)) { return a; } } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } Random rand = new Random(); return addrs.get(rand.nextInt(addrs.size())); } InetAddress thisHost() { try { return InetAddress.getLocalHost(); } catch (UnknownHostException e) { throw new RuntimeException(e); } } List<ServerAddress> getServerAddressList(Properties props) { String[] mongos = props.getProperty("mongodb.mongos", "localhost").split(","); List<ServerAddress> list = new ArrayList<ServerAddress>(); for (String m : mongos) { String[] parts = m.split(":"); try { if (parts.length == 2) { list.add(new ServerAddress(parts[0], Integer.parseInt(parts[1]))); } else { list.add(new ServerAddress(m)); } } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return list; } @Override public TargetLifecycle lifecycle(String dbName, Properties props) { List<ServerAddress> list = getServerAddressList(props); boolean sharded = list.size() > 1; ServerAddress addr = chooseOne(list); return new MongodbLifecycle(dbName, addr, sharded, props); } public static class MongoDbServer implements TransactionalDbServer<TransactionProfiler> { private final MongoClient mongoClient; private final DBCollection coll; private final String dbName; private final BackoffPolicy policy; public static final String VERSIONFIELD = "!version!"; public static final String DOCNAME = "!group + key!"; public MongoDbServer(String dbName, String host) throws UnknownHostException, IOException { this(dbName, new ServerAddress(host), new BackoffPolicy()); } MongoDbServer(String dbName, ServerAddress host, BackoffPolicy policy) throws IOException { this.dbName = dbName; this.policy = policy; this.mongoClient = new MongoClient(host); DB db = this.mongoClient.getDB(dbName); this.coll = db.getCollection(dbName); } @Override public MongodbDB open(TransactionProfiler prof) { return new MongodbDB(dbName, coll, prof, policy); } @Override public void close() { this.mongoClient.close(); } } }
{ "content_hash": "8bd8319e4ae03cb5fc5229df03ff2430", "timestamp": "", "source": "github", "line_count": 148, "max_line_length": 93, "avg_line_length": 30.12162162162162, "alnum_prop": 0.7128757290264692, "repo_name": "tatemura/strudel", "id": "c5a6791fb7e4049d3626a939cbc66ac63bcbd68b", "size": "5219", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "store/tkvs-mongodb/src/main/java/com/nec/strudel/tkvs/store/mongodb/MongodbStore.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1703061" }, { "name": "Python", "bytes": "29516" }, { "name": "Shell", "bytes": "3337" } ], "symlink_target": "" }
<!-- Generated template for the Nearby page. See http://ionicframework.com/docs/v2/components/#navigation for more info on Ionic pages and navigation. --> <ion-header> <ion-navbar> <button ion-button menuToggle> <ion-icon name="menu"></ion-icon> </button> <ion-title>Nearby</ion-title> </ion-navbar> </ion-header> <ion-content padding> </ion-content>
{ "content_hash": "502f2b8956bf96425c929e913ca6e535", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 79, "avg_line_length": 18.333333333333332, "alnum_prop": 0.6675324675324675, "repo_name": "estevezluis1/go-app", "id": "9ab7e53ee3dbcf5369d4f62e039554939581e602", "size": "385", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/pages/transit/nearby/nearby.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2786" }, { "name": "HTML", "bytes": "8922" }, { "name": "JavaScript", "bytes": "9361" }, { "name": "TypeScript", "bytes": "9668" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <project version="4"> <component name="ChangeListManager"> <list default="true" id="849e2ea3-1dc1-4ecd-b767-88fbc76226e7" name="Default" comment=""> <change type="MODIFICATION" beforePath="$PROJECT_DIR$/.gitignore" afterPath="$PROJECT_DIR$/.gitignore" /> <change type="MODIFICATION" beforePath="$PROJECT_DIR$/.idea/.name" afterPath="$PROJECT_DIR$/.idea/.name" /> </list> <ignored path="GMapsFX-master.iws" /> <ignored path=".idea/workspace.xml" /> <ignored path="$PROJECT_DIR$/out/" /> <ignored path=".idea/dataSources.local.xml" /> <option name="EXCLUDED_CONVERTED_TO_IGNORED" value="true" /> <option name="TRACKING_ENABLED" value="true" /> <option name="SHOW_DIALOG" value="false" /> <option name="HIGHLIGHT_CONFLICTS" value="true" /> <option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" /> <option name="LAST_RESOLUTION" value="IGNORE" /> </component> <component name="ChangesViewManager" flattened_view="true" show_ignored="false" /> <component name="CreatePatchCommitExecutor"> <option name="PATCH_PATH" value="" /> </component> <component name="ExecutionTargetManager" SELECTED_TARGET="default_target" /> <component name="FavoritesManager"> <favorites_list name="GMapsFX-master" /> </component> <component name="FileEditorManager"> <leaf SIDE_TABS_SIZE_LIMIT_KEY="300"> <file leaf-file-name="SecondApp.java" pinned="false" current-in-tab="true"> <entry file="file://$PROJECT_DIR$/GMapsFX/src/main/java/com/lynden/gmapsfx/SecondApp.java"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.41262135"> <caret line="39" column="0" selection-start-line="39" selection-start-column="0" selection-end-line="39" selection-end-column="0" /> <folding> <element signature="imports" expanded="true" /> <marker date="1460722734088" expanded="true" signature="1320:1513" placeholder="..." /> </folding> </state> </provider> </entry> </file> <file leaf-file-name="GoogleMapView.java" pinned="false" current-in-tab="false"> <entry file="file://$PROJECT_DIR$/GMapsFX/src/main/java/com/lynden/gmapsfx/GoogleMapView.java"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="386" column="0" selection-start-line="386" selection-start-column="0" selection-end-line="386" selection-end-column="0" /> <folding /> </state> </provider> </entry> </file> <file leaf-file-name="Database.java" pinned="false" current-in-tab="false"> <entry file="file://$PROJECT_DIR$/GMapsFX/src/main/java/com/lynden/gmapsfx/Database.java"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" /> <folding> <marker date="1460723022005" expanded="true" signature="609:647" placeholder="select name,... markten_rotterdam" /> <marker date="1460723022005" expanded="true" signature="1953:1996" placeholder="select disti... markten_rotterdam" /> <marker date="1460723022005" expanded="true" signature="3091:3141" placeholder="select * fro... markten_rotterdam" /> <marker date="1460723022005" expanded="true" signature="4272:4293" placeholder="select * fro... markten_rotterdam" /> <marker date="1460723022005" expanded="true" signature="4272:4319" placeholder="select * fro... parkeerautomaten_rotterdam" /> <marker date="1460723022005" expanded="true" signature="5430:5470" placeholder="select * fro... parkeerautomaten_rotterdam" /> </folding> </state> </provider> </entry> </file> <file leaf-file-name="LegendBox.java" pinned="false" current-in-tab="false"> <entry file="file://$PROJECT_DIR$/GMapsFX/src/main/java/com/lynden/gmapsfx/LegendBox.java"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="32" column="34" selection-start-line="32" selection-start-column="34" selection-end-line="32" selection-end-column="34" /> <folding /> </state> </provider> </entry> </file> </leaf> </component> <component name="FileTemplateManagerImpl"> <option name="RECENT_TEMPLATES"> <list> <option value="HTML File" /> <option value="Class" /> </list> </option> </component> <component name="Git.Settings"> <option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" /> </component> <component name="GradleLocalSettings"> <option name="externalProjectsViewState"> <projects_view /> </option> </component> <component name="IdeDocumentHistory"> <option name="CHANGED_PATHS"> <list> <option value="$PROJECT_DIR$/GMapsFX/src/main/resources/html/mymap.html" /> <option value="$PROJECT_DIR$/GMapsFX/src/main/resources/html/maps.html" /> <option value="$PROJECT_DIR$/GMapsFX/src/main/java/com/lynden/gmapsfx/MainApp.java" /> <option value="$PROJECT_DIR$/GMapsFX/src/main/java/com/lynden/gmapsfx/MapComponentInitializedListener.java" /> <option value="$PROJECT_DIR$/GMapsFX/src/main/java/com/lynden/gmapsfx/GoogleMapView.java" /> <option value="$PROJECT_DIR$/GMapsFX/src/main/java/Database.java" /> <option value="$PROJECT_DIR$/GMapsFX/src/main/java/com/lynden/gmapsfx/FXMLController.java" /> <option value="$PROJECT_DIR$/GMapsFX/src/main/java/com/lynden/gmapsfx/javascript/object/InfoWindowOptions.java" /> <option value="$PROJECT_DIR$/GMapsFX/src/main/java/com/lynden/gmapsfx/startup_screen.java" /> <option value="$PROJECT_DIR$/GMapsFX/src/main/java/LegendBox.java" /> <option value="$PROJECT_DIR$/GMapsFX/src/main/java/com/lynden/gmapsfx/LegendBox.java" /> <option value="$PROJECT_DIR$/GMapsFX/src/main/java/com/lynden/gmapsfx/SecondApp.java" /> <option value="$PROJECT_DIR$/GMapsFX/src/main/java/com/lynden/gmapsfx/Database.java" /> </list> </option> </component> <component name="JsBuildToolGruntFileManager" detection-done="true" /> <component name="JsBuildToolPackageJson" detection-done="true" /> <component name="JsGulpfileManager"> <detection-done>true</detection-done> </component> <component name="MavenImportPreferences"> <option name="generalSettings"> <MavenGeneralSettings> <option name="mavenHome" value="Bundled (Maven 3)" /> </MavenGeneralSettings> </option> </component> <component name="ProjectFrameBounds"> <option name="x" value="-9" /> <option name="y" value="-9" /> <option name="width" value="1932" /> <option name="height" value="1048" /> </component> <component name="ProjectLevelVcsManager" settingsEditedManually="true"> <OptionsSetting value="true" id="Add" /> <OptionsSetting value="true" id="Remove" /> <OptionsSetting value="true" id="Checkout" /> <OptionsSetting value="true" id="Update" /> <OptionsSetting value="true" id="Status" /> <OptionsSetting value="true" id="Edit" /> <ConfirmationsSetting value="0" id="Add" /> <ConfirmationsSetting value="0" id="Remove" /> </component> <component name="ProjectView"> <navigator currentView="ProjectPane" proportions="" version="1"> <flattenPackages /> <showMembers /> <showModules /> <showLibraryContents /> <hideEmptyPackages /> <abbreviatePackageNames /> <autoscrollToSource /> <autoscrollFromSource /> <sortByType /> <manualOrder /> <foldersAlwaysOnTop value="true" /> </navigator> <panes> <pane id="Scope" /> <pane id="Scratches" /> <pane id="ProjectPane"> <subPane> <PATH> <PATH_ELEMENT> <option name="myItemId" value="GMapsFX-master" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" /> </PATH_ELEMENT> </PATH> <PATH> <PATH_ELEMENT> <option name="myItemId" value="GMapsFX-master" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" /> </PATH_ELEMENT> <PATH_ELEMENT> <option name="myItemId" value="main" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" /> </PATH_ELEMENT> </PATH> <PATH> <PATH_ELEMENT> <option name="myItemId" value="GMapsFX-master" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" /> </PATH_ELEMENT> <PATH_ELEMENT> <option name="myItemId" value="main" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" /> </PATH_ELEMENT> <PATH_ELEMENT> <option name="myItemId" value="resources" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" /> </PATH_ELEMENT> </PATH> <PATH> <PATH_ELEMENT> <option name="myItemId" value="GMapsFX-master" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" /> </PATH_ELEMENT> <PATH_ELEMENT> <option name="myItemId" value="main" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" /> </PATH_ELEMENT> <PATH_ELEMENT> <option name="myItemId" value="java" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" /> </PATH_ELEMENT> </PATH> <PATH> <PATH_ELEMENT> <option name="myItemId" value="GMapsFX-master" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" /> </PATH_ELEMENT> <PATH_ELEMENT> <option name="myItemId" value="main" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" /> </PATH_ELEMENT> <PATH_ELEMENT> <option name="myItemId" value="java" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" /> </PATH_ELEMENT> <PATH_ELEMENT> <option name="myItemId" value="gmapsfx" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" /> </PATH_ELEMENT> </PATH> <PATH> <PATH_ELEMENT> <option name="myItemId" value="GMapsFX-master" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" /> </PATH_ELEMENT> <PATH_ELEMENT> <option name="myItemId" value="main" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" /> </PATH_ELEMENT> <PATH_ELEMENT> <option name="myItemId" value="java" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" /> </PATH_ELEMENT> <PATH_ELEMENT> <option name="myItemId" value="gmapsfx" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" /> </PATH_ELEMENT> <PATH_ELEMENT> <option name="myItemId" value="javascript" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" /> </PATH_ELEMENT> </PATH> </subPane> </pane> <pane id="PackagesPane" /> </panes> </component> <component name="PropertiesComponent"> <property name="aspect.path.notification.shown" value="true" /> <property name="WebServerToolWindowFactoryState" value="false" /> <property name="settings.editor.selected.configurable" value="reference.settings.ide.settings.notifications" /> <property name="settings.editor.splitter.proportion" value="0.2" /> <property name="project.structure.last.edited" value="Artifacts" /> <property name="project.structure.proportion" value="0.15" /> <property name="project.structure.side.proportion" value="0.2" /> <property name="DefaultHtmlFileTemplate" value="HTML File" /> <property name="SearchEverywhereHistoryKey" value="mapResource&#9;PSI&#9;JAVA://javax.swing.plaf.ActionMapUIResource&#10;resource path&#9;PSI&#9;JAVA://com.sun.xml.internal.ws.transport.http.ResourceLoader#getResourcePaths" /> <property name="last_opened_file_path" value="$USER_HOME$/Desktop/School/PO 3/PRJCT3" /> </component> <component name="RecentsManager"> <key name="CopyClassDialog.RECENTS_KEY"> <recent name="com.lynden.gmapsfx" /> <recent name="" /> </key> <key name="MoveFile.RECENT_KEYS"> <recent name="C:\Users\David\Documents\GitHub\project_3_data\GMapsFX\src\main" /> </key> </component> <component name="RunManager" selected="Application.SecondApp"> <configuration default="false" name="MainApp" type="Application" factoryName="Application" temporary="true" nameIsGenerated="true"> <extension name="coverage" enabled="false" merge="false" sample_coverage="true" runner="idea"> <pattern> <option name="PATTERN" value="com.lynden.gmapsfx.*" /> <option name="ENABLED" value="true" /> </pattern> </extension> <option name="MAIN_CLASS_NAME" value="com.lynden.gmapsfx.MainApp" /> <option name="VM_PARAMETERS" /> <option name="PROGRAM_PARAMETERS" /> <option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" /> <option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" /> <option name="ALTERNATIVE_JRE_PATH" /> <option name="ENABLE_SWING_INSPECTOR" value="false" /> <option name="ENV_VARIABLES" /> <option name="PASS_PARENT_ENVS" value="true" /> <module name="main" /> <envs /> <method /> </configuration> <configuration default="false" name="mymap.html" type="JavascriptDebugType" factoryName="JavaScript Debug" temporary="true" nameIsGenerated="true" uri="http://localhost:63342/GMapsFX-master/main/resources/html/mymap.html"> <method /> </configuration> <configuration default="false" name="LoadDriver" type="Application" factoryName="Application" temporary="true" nameIsGenerated="true"> <extension name="coverage" enabled="false" merge="false" sample_coverage="true" runner="idea" /> <option name="MAIN_CLASS_NAME" value="LoadDriver" /> <option name="VM_PARAMETERS" /> <option name="PROGRAM_PARAMETERS" /> <option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" /> <option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" /> <option name="ALTERNATIVE_JRE_PATH" /> <option name="ENABLE_SWING_INSPECTOR" value="false" /> <option name="ENV_VARIABLES" /> <option name="PASS_PARENT_ENVS" value="true" /> <module name="main" /> <envs /> <method /> </configuration> <configuration default="false" name="SecondApp" type="Application" factoryName="Application" temporary="true" nameIsGenerated="true"> <extension name="coverage" enabled="false" merge="false" sample_coverage="true" runner="idea"> <pattern> <option name="PATTERN" value="com.lynden.gmapsfx.*" /> <option name="ENABLED" value="true" /> </pattern> </extension> <option name="MAIN_CLASS_NAME" value="com.lynden.gmapsfx.SecondApp" /> <option name="VM_PARAMETERS" /> <option name="PROGRAM_PARAMETERS" /> <option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" /> <option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" /> <option name="ALTERNATIVE_JRE_PATH" /> <option name="ENABLE_SWING_INSPECTOR" value="false" /> <option name="ENV_VARIABLES" /> <option name="PASS_PARENT_ENVS" value="true" /> <module name="main" /> <envs /> <method /> </configuration> <configuration default="false" name="startup_screen" type="Application" factoryName="Application" temporary="true" nameIsGenerated="true"> <extension name="coverage" enabled="false" merge="false" sample_coverage="true" runner="idea"> <pattern> <option name="PATTERN" value="com.lynden.gmapsfx.*" /> <option name="ENABLED" value="true" /> </pattern> </extension> <option name="MAIN_CLASS_NAME" value="com.lynden.gmapsfx.startup_screen" /> <option name="VM_PARAMETERS" /> <option name="PROGRAM_PARAMETERS" /> <option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" /> <option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" /> <option name="ALTERNATIVE_JRE_PATH" /> <option name="ENABLE_SWING_INSPECTOR" value="false" /> <option name="ENV_VARIABLES" /> <option name="PASS_PARENT_ENVS" value="true" /> <module name="main" /> <envs /> <method /> </configuration> <configuration default="true" type="#org.jetbrains.idea.devkit.run.PluginConfigurationType" factoryName="Plugin"> <module name="" /> <option name="VM_PARAMETERS" value="-Xmx512m -Xms256m -XX:MaxPermSize=250m -ea" /> <option name="PROGRAM_PARAMETERS" /> <method /> </configuration> <configuration default="true" type="AndroidRunConfigurationType" factoryName="Android Application"> <module name="" /> <option name="ACTIVITY_CLASS" value="" /> <option name="MODE" value="default_activity" /> <option name="DEPLOY" value="true" /> <option name="ARTIFACT_NAME" value="" /> <option name="TARGET_SELECTION_MODE" value="EMULATOR" /> <option name="USE_LAST_SELECTED_DEVICE" value="false" /> <option name="PREFERRED_AVD" value="" /> <option name="USE_COMMAND_LINE" value="true" /> <option name="COMMAND_LINE" value="" /> <option name="WIPE_USER_DATA" value="false" /> <option name="DISABLE_BOOT_ANIMATION" value="false" /> <option name="NETWORK_SPEED" value="full" /> <option name="NETWORK_LATENCY" value="none" /> <option name="CLEAR_LOGCAT" value="false" /> <option name="SHOW_LOGCAT_AUTOMATICALLY" value="true" /> <option name="FILTER_LOGCAT_AUTOMATICALLY" value="true" /> <option name="SELECTED_CLOUD_MATRIX_CONFIGURATION_ID" value="0" /> <option name="SELECTED_CLOUD_MATRIX_PROJECT_ID" value="" /> <option name="SELECTED_CLOUD_DEVICE_CONFIGURATION_ID" value="0" /> <option name="SELECTED_CLOUD_DEVICE_PROJECT_ID" value="" /> <option name="IS_VALID_CLOUD_MATRIX_SELECTION" value="false" /> <option name="INVALID_CLOUD_MATRIX_SELECTION_ERROR" value="" /> <option name="IS_VALID_CLOUD_DEVICE_SELECTION" value="false" /> <option name="INVALID_CLOUD_DEVICE_SELECTION_ERROR" value="" /> <option name="CLOUD_DEVICE_SERIAL_NUMBER" value="" /> <method /> </configuration> <configuration default="true" type="AndroidTestRunConfigurationType" factoryName="Android Tests"> <module name="" /> <option name="TESTING_TYPE" value="0" /> <option name="INSTRUMENTATION_RUNNER_CLASS" value="" /> <option name="METHOD_NAME" value="" /> <option name="CLASS_NAME" value="" /> <option name="PACKAGE_NAME" value="" /> <option name="TARGET_SELECTION_MODE" value="EMULATOR" /> <option name="USE_LAST_SELECTED_DEVICE" value="false" /> <option name="PREFERRED_AVD" value="" /> <option name="USE_COMMAND_LINE" value="true" /> <option name="COMMAND_LINE" value="" /> <option name="WIPE_USER_DATA" value="false" /> <option name="DISABLE_BOOT_ANIMATION" value="false" /> <option name="NETWORK_SPEED" value="full" /> <option name="NETWORK_LATENCY" value="none" /> <option name="CLEAR_LOGCAT" value="false" /> <option name="SHOW_LOGCAT_AUTOMATICALLY" value="true" /> <option name="FILTER_LOGCAT_AUTOMATICALLY" value="true" /> <option name="SELECTED_CLOUD_MATRIX_CONFIGURATION_ID" value="0" /> <option name="SELECTED_CLOUD_MATRIX_PROJECT_ID" value="" /> <option name="SELECTED_CLOUD_DEVICE_CONFIGURATION_ID" value="0" /> <option name="SELECTED_CLOUD_DEVICE_PROJECT_ID" value="" /> <option name="IS_VALID_CLOUD_MATRIX_SELECTION" value="false" /> <option name="INVALID_CLOUD_MATRIX_SELECTION_ERROR" value="" /> <option name="IS_VALID_CLOUD_DEVICE_SELECTION" value="false" /> <option name="INVALID_CLOUD_DEVICE_SELECTION_ERROR" value="" /> <option name="CLOUD_DEVICE_SERIAL_NUMBER" value="" /> <method /> </configuration> <configuration default="true" type="Applet" factoryName="Applet"> <module /> <option name="HTML_USED" value="false" /> <option name="WIDTH" value="400" /> <option name="HEIGHT" value="300" /> <option name="POLICY_FILE" value="$APPLICATION_HOME_DIR$/bin/appletviewer.policy" /> <method /> </configuration> <configuration default="true" type="Application" factoryName="Application"> <extension name="coverage" enabled="false" merge="false" sample_coverage="true" runner="idea" /> <option name="MAIN_CLASS_NAME" /> <option name="VM_PARAMETERS" /> <option name="PROGRAM_PARAMETERS" /> <option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" /> <option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" /> <option name="ALTERNATIVE_JRE_PATH" /> <option name="ENABLE_SWING_INSPECTOR" value="false" /> <option name="ENV_VARIABLES" /> <option name="PASS_PARENT_ENVS" value="true" /> <module name="" /> <envs /> <method /> </configuration> <configuration default="true" type="CucumberJavaRunConfigurationType" factoryName="Cucumber java"> <extension name="coverage" enabled="false" merge="false" sample_coverage="true" runner="idea" /> <option name="myFilePath" /> <option name="GLUE" /> <option name="myNameFilter" /> <option name="myGeneratedName" /> <option name="MAIN_CLASS_NAME" /> <option name="VM_PARAMETERS" /> <option name="PROGRAM_PARAMETERS" /> <option name="WORKING_DIRECTORY" /> <option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" /> <option name="ALTERNATIVE_JRE_PATH" /> <option name="ENABLE_SWING_INSPECTOR" value="false" /> <option name="ENV_VARIABLES" /> <option name="PASS_PARENT_ENVS" value="true" /> <module name="" /> <envs /> <method /> </configuration> <configuration default="true" type="FlashRunConfigurationType" factoryName="Flash App"> <option name="BCName" value="" /> <option name="IOSSimulatorSdkPath" value="" /> <option name="adlOptions" value="" /> <option name="airProgramParameters" value="" /> <option name="appDescriptorForEmulator" value="Android" /> <option name="debugTransport" value="USB" /> <option name="debuggerSdkRaw" value="BC SDK" /> <option name="emulator" value="NexusOne" /> <option name="emulatorAdlOptions" value="" /> <option name="fastPackaging" value="true" /> <option name="fullScreenHeight" value="0" /> <option name="fullScreenWidth" value="0" /> <option name="launchUrl" value="false" /> <option name="launcherParameters"> <LauncherParameters> <option name="browser" value="a7bb68e0-33c0-4d6f-a81a-aac1fdb870c8" /> <option name="launcherType" value="OSDefault" /> <option name="newPlayerInstance" value="false" /> <option name="playerPath" value="FlashPlayerDebugger.exe" /> </LauncherParameters> </option> <option name="mobileRunTarget" value="Emulator" /> <option name="moduleName" value="" /> <option name="overriddenMainClass" value="" /> <option name="overriddenOutputFileName" value="" /> <option name="overrideMainClass" value="false" /> <option name="runTrusted" value="true" /> <option name="screenDpi" value="0" /> <option name="screenHeight" value="0" /> <option name="screenWidth" value="0" /> <option name="url" value="http://" /> <option name="usbDebugPort" value="7936" /> <method /> </configuration> <configuration default="true" type="FlexUnitRunConfigurationType" factoryName="FlexUnit" appDescriptorForEmulator="Android" class_name="" emulatorAdlOptions="" method_name="" package_name="" scope="Class"> <option name="BCName" value="" /> <option name="launcherParameters"> <LauncherParameters> <option name="browser" value="a7bb68e0-33c0-4d6f-a81a-aac1fdb870c8" /> <option name="launcherType" value="OSDefault" /> <option name="newPlayerInstance" value="false" /> <option name="playerPath" value="FlashPlayerDebugger.exe" /> </LauncherParameters> </option> <option name="moduleName" value="" /> <option name="trusted" value="true" /> <method /> </configuration> <configuration default="true" type="GradleRunConfiguration" factoryName="Gradle"> <ExternalSystemSettings> <option name="executionName" /> <option name="externalProjectPath" /> <option name="externalSystemIdString" value="GRADLE" /> <option name="scriptParameters" /> <option name="taskDescriptions"> <list /> </option> <option name="taskNames"> <list /> </option> <option name="vmOptions" /> </ExternalSystemSettings> <method /> </configuration> <configuration default="true" type="GrailsRunConfigurationType" factoryName="Grails"> <module name="" /> <setting name="vmparams" value="" /> <setting name="cmdLine" value="run-app" /> <setting name="depsClasspath" value="false" /> <setting name="passParentEnv" value="true" /> <extension name="coverage" enabled="false" merge="false" sample_coverage="true" runner="idea" /> <setting name="launchBrowser" value="false" /> <method /> </configuration> <configuration default="true" type="JUnit" factoryName="JUnit"> <extension name="coverage" enabled="false" merge="false" sample_coverage="true" runner="idea" /> <module name="" /> <option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" /> <option name="ALTERNATIVE_JRE_PATH" /> <option name="PACKAGE_NAME" /> <option name="MAIN_CLASS_NAME" /> <option name="METHOD_NAME" /> <option name="TEST_OBJECT" value="class" /> <option name="VM_PARAMETERS" value="-ea" /> <option name="PARAMETERS" /> <option name="WORKING_DIRECTORY" value="$MODULE_DIR$" /> <option name="ENV_VARIABLES" /> <option name="PASS_PARENT_ENVS" value="true" /> <option name="TEST_SEARCH_SCOPE"> <value defaultName="singleModule" /> </option> <envs /> <patterns /> <method /> </configuration> <configuration default="true" type="JUnitTestDiscovery" factoryName="JUnit Test Discovery" changeList="All"> <extension name="coverage" enabled="false" merge="false" sample_coverage="true" runner="idea" /> <module name="" /> <option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" /> <option name="ALTERNATIVE_JRE_PATH" /> <option name="PACKAGE_NAME" /> <option name="MAIN_CLASS_NAME" /> <option name="METHOD_NAME" /> <option name="TEST_OBJECT" value="class" /> <option name="VM_PARAMETERS" /> <option name="PARAMETERS" /> <option name="WORKING_DIRECTORY" /> <option name="ENV_VARIABLES" /> <option name="PASS_PARENT_ENVS" value="true" /> <option name="TEST_SEARCH_SCOPE"> <value defaultName="singleModule" /> </option> <envs /> <patterns /> <method /> </configuration> <configuration default="true" type="JarApplication" factoryName="JAR Application"> <extension name="coverage" enabled="false" merge="false" sample_coverage="true" runner="idea" /> <envs /> <method /> </configuration> <configuration default="true" type="Java Scratch" factoryName="Java Scratch"> <extension name="coverage" enabled="false" merge="false" sample_coverage="true" runner="idea" /> <option name="SCRATCH_FILE_ID" value="0" /> <option name="MAIN_CLASS_NAME" /> <option name="VM_PARAMETERS" /> <option name="PROGRAM_PARAMETERS" /> <option name="WORKING_DIRECTORY" /> <option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" /> <option name="ALTERNATIVE_JRE_PATH" /> <option name="ENABLE_SWING_INSPECTOR" value="false" /> <option name="ENV_VARIABLES" /> <option name="PASS_PARENT_ENVS" value="true" /> <module name="" /> <envs /> <method /> </configuration> <configuration default="true" type="JavascriptDebugType" factoryName="JavaScript Debug"> <method /> </configuration> <configuration default="true" type="JetRunConfigurationType" factoryName="Kotlin"> <extension name="coverage" enabled="false" merge="false" sample_coverage="true" runner="idea" /> <option name="MAIN_CLASS_NAME" /> <option name="VM_PARAMETERS" /> <option name="PROGRAM_PARAMETERS" /> <option name="WORKING_DIRECTORY" /> <option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" /> <option name="ALTERNATIVE_JRE_PATH" /> <option name="PASS_PARENT_ENVS" value="true" /> <module name="main" /> <envs /> <method /> </configuration> <configuration default="true" type="KotlinStandaloneScriptRunConfigurationType" factoryName="Kotlin script"> <extension name="coverage" enabled="false" merge="false" sample_coverage="true" runner="idea" /> <option name="filePath" /> <option name="vmParameters" /> <option name="alternativeJrePath" /> <option name="programParameters" /> <option name="passParentEnvs" value="true" /> <option name="workingDirectory" /> <option name="isAlternativeJrePathEnabled" value="false" /> <envs /> <method /> </configuration> <configuration default="true" type="Remote" factoryName="Remote"> <option name="USE_SOCKET_TRANSPORT" value="true" /> <option name="SERVER_MODE" value="false" /> <option name="SHMEM_ADDRESS" value="javadebug" /> <option name="HOST" value="localhost" /> <option name="PORT" value="5005" /> <method /> </configuration> <configuration default="true" type="SpringBootApplicationConfigurationType" factoryName="Spring Boot"> <extension name="coverage" enabled="false" merge="false" sample_coverage="true" runner="idea" /> <module name="" /> <envs /> <method /> </configuration> <configuration default="true" type="TestNG" factoryName="TestNG"> <extension name="coverage" enabled="false" merge="false" sample_coverage="true" runner="idea" /> <module name="" /> <option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" /> <option name="ALTERNATIVE_JRE_PATH" /> <option name="SUITE_NAME" /> <option name="PACKAGE_NAME" /> <option name="MAIN_CLASS_NAME" /> <option name="METHOD_NAME" /> <option name="GROUP_NAME" /> <option name="TEST_OBJECT" value="CLASS" /> <option name="VM_PARAMETERS" value="-ea" /> <option name="PARAMETERS" /> <option name="WORKING_DIRECTORY" value="$MODULE_DIR$" /> <option name="OUTPUT_DIRECTORY" /> <option name="ANNOTATION_TYPE" /> <option name="ENV_VARIABLES" /> <option name="PASS_PARENT_ENVS" value="true" /> <option name="TEST_SEARCH_SCOPE"> <value defaultName="singleModule" /> </option> <option name="USE_DEFAULT_REPORTERS" value="false" /> <option name="PROPERTIES_FILE" /> <envs /> <properties /> <listeners /> <method /> </configuration> <configuration default="true" type="TestNGTestDiscovery" factoryName="TestNG Test Discovery" changeList="All"> <extension name="coverage" enabled="false" merge="false" sample_coverage="true" runner="idea" /> <module name="" /> <option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" /> <option name="ALTERNATIVE_JRE_PATH" /> <option name="SUITE_NAME" /> <option name="PACKAGE_NAME" /> <option name="MAIN_CLASS_NAME" /> <option name="METHOD_NAME" /> <option name="GROUP_NAME" /> <option name="TEST_OBJECT" value="CLASS" /> <option name="VM_PARAMETERS" /> <option name="PARAMETERS" /> <option name="WORKING_DIRECTORY" /> <option name="OUTPUT_DIRECTORY" /> <option name="ANNOTATION_TYPE" /> <option name="ENV_VARIABLES" /> <option name="PASS_PARENT_ENVS" value="true" /> <option name="TEST_SEARCH_SCOPE"> <value defaultName="singleModule" /> </option> <option name="USE_DEFAULT_REPORTERS" value="false" /> <option name="PROPERTIES_FILE" /> <envs /> <properties /> <listeners /> <method /> </configuration> <configuration default="true" type="js.build_tools.gulp" factoryName="Gulp.js"> <node-options /> <gulpfile /> <tasks /> <arguments /> <envs /> <method /> </configuration> <configuration default="true" type="js.build_tools.npm" factoryName="npm"> <command value="run-script" /> <scripts /> <envs /> <method /> </configuration> <configuration default="true" type="osgi.bnd.run" factoryName="Run Launcher"> <method /> </configuration> <configuration default="true" type="osgi.bnd.run" factoryName="Test Launcher (JUnit)"> <method /> </configuration> <list size="5"> <item index="0" class="java.lang.String" itemvalue="Application.MainApp" /> <item index="1" class="java.lang.String" itemvalue="JavaScript Debug.mymap.html" /> <item index="2" class="java.lang.String" itemvalue="Application.LoadDriver" /> <item index="3" class="java.lang.String" itemvalue="Application.SecondApp" /> <item index="4" class="java.lang.String" itemvalue="Application.startup_screen" /> </list> <recent_temporary> <list size="5"> <item index="0" class="java.lang.String" itemvalue="Application.SecondApp" /> <item index="1" class="java.lang.String" itemvalue="Application.startup_screen" /> <item index="2" class="java.lang.String" itemvalue="Application.MainApp" /> <item index="3" class="java.lang.String" itemvalue="Application.LoadDriver" /> <item index="4" class="java.lang.String" itemvalue="JavaScript Debug.mymap.html" /> </list> </recent_temporary> </component> <component name="ShelveChangesManager" show_recycled="false" /> <component name="SvnConfiguration"> <configuration /> </component> <component name="TaskManager"> <task active="true" id="Default" summary="Default task"> <changelist id="849e2ea3-1dc1-4ecd-b767-88fbc76226e7" name="Default" comment="" /> <created>1460374238701</created> <option name="number" value="Default" /> <updated>1460374238701</updated> <workItem from="1460374241890" duration="6196000" /> <workItem from="1460380636681" duration="2948000" /> <workItem from="1460468756650" duration="99000" /> <workItem from="1460548099921" duration="240000" /> <workItem from="1460548587113" duration="8140000" /> <workItem from="1460564303667" duration="5953000" /> <workItem from="1460620448675" duration="4567000" /> <workItem from="1460636957857" duration="169000" /> <workItem from="1460637259427" duration="657000" /> <workItem from="1460637951591" duration="9217000" /> <workItem from="1460649745002" duration="407000" /> <workItem from="1460651768966" duration="6142000" /> <workItem from="1460708293598" duration="15765000" /> <workItem from="1460743924073" duration="755000" /> <workItem from="1460751143099" duration="604000" /> </task> <servers /> </component> <component name="TimeTrackingManager"> <option name="totallyTimeSpent" value="61859000" /> </component> <component name="TodoView"> <todo-panel id="selected-file"> <is-autoscroll-to-source value="true" /> </todo-panel> <todo-panel id="all"> <are-packages-shown value="true" /> <is-autoscroll-to-source value="true" /> </todo-panel> </component> <component name="ToolWindowManager"> <frame x="-9" y="-9" width="1932" height="1048" extended-state="0" /> <editor active="false" /> <layout> <window_info id="Palette" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="3" side_tool="false" content_ui="tabs" /> <window_info id="TODO" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.32943925" sideWeight="0.49785638" order="13" side_tool="false" content_ui="tabs" /> <window_info id="Palette&#9;" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="2" side_tool="false" content_ui="tabs" /> <window_info id="Event Log" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.32943925" sideWeight="0.5021436" order="2" side_tool="true" content_ui="tabs" /> <window_info id="Version Control" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="3" side_tool="false" content_ui="tabs" /> <window_info id="Sequence" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" /> <window_info id="Terminal" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="4" side_tool="false" content_ui="tabs" /> <window_info id="Designer" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" /> <window_info id="Project" active="true" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" show_stripe_button="true" weight="0.20806451" sideWeight="0.5" order="3" side_tool="false" content_ui="combo" /> <window_info id="Database" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" /> <window_info id="Structure" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="4" side_tool="false" content_ui="tabs" /> <window_info id="Ant Build" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="2" side_tool="false" content_ui="tabs" /> <window_info id="UI Designer" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" /> <window_info id="Favorites" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="1" side_tool="true" content_ui="tabs" /> <window_info id="Cvs" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="9" side_tool="false" content_ui="tabs" /> <window_info id="Message" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="5" side_tool="false" content_ui="tabs" /> <window_info id="Commander" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.4" sideWeight="0.5" order="4" side_tool="false" content_ui="tabs" /> <window_info id="Application Servers" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="11" side_tool="false" content_ui="tabs" /> <window_info id="Maven Projects" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" /> <window_info id="Hierarchy" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="5" side_tool="false" content_ui="combo" /> <window_info id="Profiler" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="12" side_tool="false" content_ui="tabs" /> <window_info id="Debug" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.4" sideWeight="0.5" order="8" side_tool="false" content_ui="tabs" /> <window_info id="Changes" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="14" side_tool="false" content_ui="tabs" /> <window_info id="Messages" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.32827103" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" /> <window_info id="Inspection" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.4" sideWeight="0.5" order="10" side_tool="false" content_ui="tabs" /> <window_info id="Run" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.34345794" sideWeight="0.49785638" order="7" side_tool="false" content_ui="tabs" /> <window_info id="JetGradle" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="6" side_tool="false" content_ui="tabs" /> <window_info id="Problems" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="15" side_tool="false" content_ui="tabs" /> <window_info id="Find" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.32898173" sideWeight="0.5" order="6" side_tool="false" content_ui="tabs" /> </layout> </component> <component name="Vcs.Log.UiProperties"> <option name="RECENTLY_FILTERED_USER_GROUPS"> <collection /> </option> <option name="RECENTLY_FILTERED_BRANCH_GROUPS"> <collection /> </option> </component> <component name="VcsContentAnnotationSettings"> <option name="myLimit" value="2678400000" /> </component> <component name="XDebuggerManager"> <breakpoint-manager> <option name="time" value="1" /> </breakpoint-manager> <watches-manager /> </component> <component name="antWorkspaceConfiguration"> <option name="IS_AUTOSCROLL_TO_SOURCE" value="false" /> <option name="FILTER_TARGETS" value="false" /> </component> <component name="editorHistoryManager"> <entry file="file://$PROJECT_DIR$/GMapsFX/src/main/java/com/lynden/gmapsfx/javascript/object/InfoWindowOptions.java"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="42" column="40" selection-start-line="42" selection-start-column="40" selection-end-line="42" selection-end-column="40" /> <folding /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/GMapsFX/src/main/java/com/lynden/gmapsfx/Database.java"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="32" column="52" selection-start-line="32" selection-start-column="52" selection-end-line="32" selection-end-column="52" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/GMapsFX/src/main/java/com/lynden/gmapsfx/MapComponentInitializedListener.java"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="26" column="51" selection-start-line="26" selection-start-column="51" selection-end-line="26" selection-end-column="51" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/GMapsFX/src/main/java/com/lynden/gmapsfx/GoogleMapView.java"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="339" column="20" selection-start-line="339" selection-start-column="20" selection-end-line="339" selection-end-column="40" /> <folding /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/GMapsFX/src/main/resources/html/maps.html"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="10" column="27" selection-start-line="10" selection-start-column="27" selection-end-line="10" selection-end-column="27" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/GMapsFX/src/main/java/com/lynden/gmapsfx/SecondApp.java"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" /> <folding> <element signature="imports" expanded="true" /> <marker date="1460722734088" expanded="true" signature="1320:1513" placeholder="..." /> </folding> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/GMapsFX/src/main/java/com/lynden/gmapsfx/Database.java"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="16" column="24" selection-start-line="16" selection-start-column="24" selection-end-line="16" selection-end-column="24" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/GMapsFX/src/main/java/com/lynden/gmapsfx/MapComponentInitializedListener.java"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="26" column="51" selection-start-line="26" selection-start-column="51" selection-end-line="26" selection-end-column="51" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/GMapsFX/src/main/java/com/lynden/gmapsfx/GoogleMapView.java"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="339" column="20" selection-start-line="339" selection-start-column="20" selection-end-line="339" selection-end-column="40" /> <folding /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/GMapsFX/src/main/resources/html/maps.html"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="10" column="27" selection-start-line="10" selection-start-column="27" selection-end-line="10" selection-end-column="27" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/GMapsFX/src/main/java/com/lynden/gmapsfx/SecondApp.java"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="236" column="60" selection-start-line="236" selection-start-column="60" selection-end-line="236" selection-end-column="60" /> <folding> <element signature="imports" expanded="true" /> <marker date="1460722734088" expanded="true" signature="1320:1513" placeholder="..." /> </folding> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/GMapsFX/src/main/java/com/lynden/gmapsfx/javascript/object/InfoWindowOptions.java"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="41" column="52" selection-start-line="41" selection-start-column="52" selection-end-line="41" selection-end-column="52" /> <folding /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/GMapsFX/src/main/java/com/lynden/gmapsfx/Database.java"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/GMapsFX/src/main/java/com/lynden/gmapsfx/MapComponentInitializedListener.java"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="26" column="51" selection-start-line="26" selection-start-column="51" selection-end-line="26" selection-end-column="51" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/GMapsFX/src/main/java/com/lynden/gmapsfx/GoogleMapView.java"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="339" column="20" selection-start-line="339" selection-start-column="20" selection-end-line="339" selection-end-column="40" /> <folding /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/GMapsFX/src/main/resources/html/maps.html"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="10" column="27" selection-start-line="10" selection-start-column="27" selection-end-line="10" selection-end-column="27" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/GMapsFX/src/main/java/com/lynden/gmapsfx/SecondApp.java"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="73" column="0" selection-start-line="73" selection-start-column="0" selection-end-line="73" selection-end-column="0" /> <folding> <element signature="imports" expanded="true" /> <marker date="1460722734088" expanded="true" signature="1320:1513" placeholder="..." /> </folding> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/GMapsFX/src/main/java/com/lynden/gmapsfx/MapComponentInitializedListener.java"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="26" column="51" selection-start-line="26" selection-start-column="51" selection-end-line="26" selection-end-column="51" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/GMapsFX/src/main/java/com/lynden/gmapsfx/GoogleMapView.java"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" /> <folding /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/GMapsFX/src/main/resources/html/maps.html"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="10" column="27" selection-start-line="10" selection-start-column="27" selection-end-line="10" selection-end-column="27" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/GMapsFX/src/main/java/com/lynden/gmapsfx/GoogleMapView.java"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="161" column="0" selection-start-line="161" selection-start-column="0" selection-end-line="161" selection-end-column="0" /> <folding /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/GMapsFX/src/main/resources/html/maps.html"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="10" column="27" selection-start-line="10" selection-start-column="27" selection-end-line="10" selection-end-column="27" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/GMapsFX/src/main/java/com/lynden/gmapsfx/GoogleMapView.java"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="161" column="0" selection-start-line="161" selection-start-column="0" selection-end-line="161" selection-end-column="0" /> <folding /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/GMapsFX/src/main/resources/html/maps.html"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="10" column="27" selection-start-line="10" selection-start-column="27" selection-end-line="10" selection-end-column="27" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/GMapsFX/src/main/java/com/lynden/gmapsfx/GoogleMapView.java"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="161" column="0" selection-start-line="161" selection-start-column="0" selection-end-line="161" selection-end-column="0" /> <folding /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/GMapsFX/src/main/resources/html/arrays.html"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/GMapsFX/src/main/java/com/lynden/gmapsfx/javascript/object/MapTypeIdEnum.java"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.3148148"> <caret line="23" column="13" selection-start-line="23" selection-start-column="13" selection-end-line="23" selection-end-column="26" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/GMapsFX/src/test/java/com/lynden/gmapsfx/javascript/JavascriptRuntimeTest.java"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="26" column="13" selection-start-line="26" selection-start-column="13" selection-end-line="26" selection-end-column="13" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/GMapsFX/src/main/resources/html/maps_1.html"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/GMapsFX/src/main/resources/html/mymap.html"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="-10.461538"> <caret line="16" column="27" selection-start-line="16" selection-start-column="27" selection-end-line="16" selection-end-column="27" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/GMapsFX/src/main/resources/html/maps.html"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="10" column="27" selection-start-line="10" selection-start-column="27" selection-end-line="10" selection-end-column="27" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/GMapsFX/src/main/java/com/lynden/gmapsfx/javascript/object/MarkerOptions.java"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="24" column="5" selection-start-line="24" selection-start-column="5" selection-end-line="24" selection-end-column="5" /> </state> </provider> </entry> <entry file="jar://C:/Program Files/Java/jdk1.8.0_73/javafx-src.zip!/javafx/scene/image/Image.java"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.040816326"> <caret line="656" column="11" selection-start-line="656" selection-start-column="11" selection-end-line="656" selection-end-column="11" /> <folding /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/GMapsFX/src/main/java/com/lynden/gmapsfx/javascript/object/InfoWindowOptions.java"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.91806334"> <caret line="95" column="40" selection-start-line="95" selection-start-column="40" selection-end-line="95" selection-end-column="40" /> <folding /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/GMapsFX/src/main/java/com/lynden/gmapsfx/FXMLController.java"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.9013035"> <caret line="32" column="24" selection-start-line="32" selection-start-column="24" selection-end-line="32" selection-end-column="24" /> <folding /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/GMapsFX/src/main/java/com/lynden/gmapsfx/MapNotInitializedException.java"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.32774675"> <caret line="22" column="13" selection-start-line="22" selection-start-column="13" selection-end-line="22" selection-end-column="13" /> <folding /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/GMapsFX/src/main/java/com/lynden/gmapsfx/MapComponentInitializedListener.java"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.49162012"> <caret line="26" column="51" selection-start-line="26" selection-start-column="51" selection-end-line="26" selection-end-column="51" /> <folding /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/GMapsFX/src/main/java/com/lynden/gmapsfx/MapReadyListener.java"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="26" column="17" selection-start-line="26" selection-start-column="17" selection-end-line="26" selection-end-column="17" /> <folding /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/GMapsFX/src/main/java/com/lynden/gmapsfx/shapes/MapShapeOptions.java"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="101" column="4" selection-start-line="101" selection-start-column="4" selection-end-line="101" selection-end-column="4" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/GMapsFX/src/main/java/com/lynden/gmapsfx/shapes/Polygon.java"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/GMapsFX/src/main/java/com/lynden/gmapsfx/shapes/PolygonOptions.java"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="43" column="0" selection-start-line="43" selection-start-column="0" selection-end-line="43" selection-end-column="0" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/GMapsFX/src/main/java/com/lynden/gmapsfx/shapes/PolylineOptions.java"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="30" column="4" selection-start-line="30" selection-start-column="4" selection-end-line="30" selection-end-column="4" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/GMapsFX/src/main/java/com/lynden/gmapsfx/shapes/Circle.java"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="58" column="0" selection-start-line="58" selection-start-column="0" selection-end-line="58" selection-end-column="0" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/GMapsFX/src/main/java/com/lynden/gmapsfx/ArrayTester.java"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="-1.7039106"> <caret line="90" column="8" selection-start-line="90" selection-start-column="8" selection-end-line="90" selection-end-column="8" /> <folding /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/GMapsFX/src/main/java/com/lynden/gmapsfx/shapes/Polyline.java"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.7839851"> <caret line="46" column="0" selection-start-line="46" selection-start-column="0" selection-end-line="46" selection-end-column="0" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/GMapsFX/src/main/java/com/lynden/gmapsfx/javascript/object/Marker.java"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="86" column="0" selection-start-line="86" selection-start-column="0" selection-end-line="86" selection-end-column="0" /> <folding /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/GMapsFX/src/main/java/com/lynden/gmapsfx/javascript/object/MapShape.java"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="26" column="22" selection-start-line="26" selection-start-column="22" selection-end-line="26" selection-end-column="22" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/GMapsFX/src/main/java/com/lynden/gmapsfx/SecondApp.java"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.41262135"> <caret line="39" column="0" selection-start-line="39" selection-start-column="0" selection-end-line="39" selection-end-column="0" /> <folding> <element signature="imports" expanded="true" /> <marker date="1460722734088" expanded="true" signature="1320:1513" placeholder="..." /> </folding> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/GMapsFX/src/main/java/com/lynden/gmapsfx/GoogleMapView.java"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="386" column="0" selection-start-line="386" selection-start-column="0" selection-end-line="386" selection-end-column="0" /> <folding /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/GMapsFX/src/main/java/com/lynden/gmapsfx/Database.java"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="-0.0"> <caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" /> <folding> <marker date="1460723022005" expanded="true" signature="609:647" placeholder="select name,... markten_rotterdam" /> <marker date="1460723022005" expanded="true" signature="1953:1996" placeholder="select disti... markten_rotterdam" /> <marker date="1460723022005" expanded="true" signature="3091:3141" placeholder="select * fro... markten_rotterdam" /> <marker date="1460723022005" expanded="true" signature="4272:4293" placeholder="select * fro... markten_rotterdam" /> <marker date="1460723022005" expanded="true" signature="4272:4319" placeholder="select * fro... parkeerautomaten_rotterdam" /> <marker date="1460723022005" expanded="true" signature="5430:5470" placeholder="select * fro... parkeerautomaten_rotterdam" /> </folding> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/GMapsFX/src/main/java/com/lynden/gmapsfx/LegendBox.java"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="32" column="34" selection-start-line="32" selection-start-column="34" selection-end-line="32" selection-end-column="34" /> <folding /> </state> </provider> </entry> </component> <component name="masterDetails"> <states> <state key="ArtifactsStructureConfigurable.UI"> <settings> <artifact-editor /> <last-edited>main:jar</last-edited> <splitter-proportions> <option name="proportions"> <list> <option value="0.2" /> <option value="0.5" /> </list> </option> </splitter-proportions> </settings> </state> <state key="FacetStructureConfigurable.UI"> <settings> <last-edited>No facets are configured</last-edited> <splitter-proportions> <option name="proportions"> <list> <option value="0.2" /> </list> </option> </splitter-proportions> </settings> </state> <state key="GlobalLibrariesConfigurable.UI"> <settings> <splitter-proportions> <option name="proportions"> <list> <option value="0.2" /> </list> </option> </splitter-proportions> </settings> </state> <state key="JdkListConfigurable.UI"> <settings> <last-edited>1.8</last-edited> <splitter-proportions> <option name="proportions"> <list> <option value="0.2" /> </list> </option> </splitter-proportions> </settings> </state> <state key="ModuleStructureConfigurable.UI"> <settings> <last-edited>main</last-edited> <splitter-proportions> <option name="proportions"> <list> <option value="0.2" /> </list> </option> </splitter-proportions> </settings> </state> <state key="ProjectJDKs.UI"> <settings> <last-edited>1.8</last-edited> <splitter-proportions> <option name="proportions"> <list> <option value="0.2" /> </list> </option> </splitter-proportions> </settings> </state> <state key="ProjectLibrariesConfigurable.UI"> <settings> <last-edited>mysql-connector-java-5.1.38-bin</last-edited> <splitter-proportions> <option name="proportions"> <list> <option value="0.2" /> </list> </option> </splitter-proportions> </settings> </state> </states> </component> </project>
{ "content_hash": "35a1490ccb801f7eb084130b331f06bc", "timestamp": "", "source": "github", "line_count": 1319, "max_line_length": 252, "avg_line_length": 53.76345716451858, "alnum_prop": 0.6363764559889443, "repo_name": "0909023/project_3_data", "id": "68e0edab967235fb7dc761eee7a96593098cee26", "size": "70914", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": ".idea/workspace.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "19144" }, { "name": "Java", "bytes": "506171" }, { "name": "JavaScript", "bytes": "47048" } ], "symlink_target": "" }
package org.springframework.security.config.annotation.web.configurers; import javax.servlet.http.HttpServletRequest; import org.springframework.security.access.SecurityConfig; import org.springframework.security.config.annotation.web.HttpSecurityBuilder; import org.springframework.security.config.annotation.web.configurers.AbstractConfigAttributeRequestMatcherRegistry.UrlMapping; import org.springframework.security.web.util.matcher.RequestMatcher; /** * Configures non-null URL's to grant access to every URL * @author Rob Winch * @since 3.2 */ final class PermitAllSupport { public static void permitAll(HttpSecurityBuilder<? extends HttpSecurityBuilder<?>> http, String... urls) { for(String url : urls) { if(url != null) { permitAll(http, new ExactUrlRequestMatcher(url)); } } } @SuppressWarnings("unchecked") public static void permitAll(HttpSecurityBuilder<? extends HttpSecurityBuilder<?>> http, RequestMatcher... requestMatchers) { ExpressionUrlAuthorizationConfigurer<?> configurer = http.getConfigurer(ExpressionUrlAuthorizationConfigurer.class); if(configurer == null) { throw new IllegalStateException("permitAll only works with HttpSecurity.authorizeRequests()"); } for(RequestMatcher matcher : requestMatchers) { if(matcher != null) { configurer.getRegistry().addMapping(0, new UrlMapping(matcher, SecurityConfig.createList(ExpressionUrlAuthorizationConfigurer.permitAll))); } } } private final static class ExactUrlRequestMatcher implements RequestMatcher { private String processUrl; private ExactUrlRequestMatcher(String processUrl) { this.processUrl = processUrl; } public boolean matches(HttpServletRequest request) { String uri = request.getRequestURI(); String query = request.getQueryString(); if(query != null) { uri += "?" + query; } if ("".equals(request.getContextPath())) { return uri.equals(processUrl); } return uri.equals(request.getContextPath() + processUrl); } } private PermitAllSupport() {} }
{ "content_hash": "2d6ede42332ecbe4b7a060860fe7385c", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 155, "avg_line_length": 34.32835820895522, "alnum_prop": 0.6752173913043479, "repo_name": "tekul/spring-security", "id": "4f95e43f1e16f6ee158b73044b9887cc4054411f", "size": "2920", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "config/src/main/java/org/springframework/security/config/annotation/web/configurers/PermitAllSupport.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1373" }, { "name": "Groovy", "bytes": "720586" }, { "name": "Java", "bytes": "4944171" }, { "name": "Python", "bytes": "129" }, { "name": "Ruby", "bytes": "1312" }, { "name": "Shell", "bytes": "7778" }, { "name": "XSLT", "bytes": "5723" } ], "symlink_target": "" }
""" http://developer.openstack.org/api-ref-identity-v3.html#credentials-v3 """ from oslo_serialization import jsonutils as json from tempest.lib.common import rest_client class CredentialsClient(rest_client.RestClient): api_version = "v3" def create_credential(self, **kwargs): """Creates a credential. Available params: see http://developer.openstack.org/ api-ref-identity-v3.html#createCredential """ post_body = json.dumps({'credential': kwargs}) resp, body = self.post('credentials', post_body) self.expected_success(201, resp.status) body = json.loads(body) body['credential']['blob'] = json.loads(body['credential']['blob']) return rest_client.ResponseBody(resp, body) def update_credential(self, credential_id, **kwargs): """Updates a credential. Available params: see http://developer.openstack.org/ api-ref-identity-v3.html#updateCredential """ post_body = json.dumps({'credential': kwargs}) resp, body = self.patch('credentials/%s' % credential_id, post_body) self.expected_success(200, resp.status) body = json.loads(body) body['credential']['blob'] = json.loads(body['credential']['blob']) return rest_client.ResponseBody(resp, body) def show_credential(self, credential_id): """To GET Details of a credential.""" resp, body = self.get('credentials/%s' % credential_id) self.expected_success(200, resp.status) body = json.loads(body) body['credential']['blob'] = json.loads(body['credential']['blob']) return rest_client.ResponseBody(resp, body) def list_credentials(self): """Lists out all the available credentials.""" resp, body = self.get('credentials') self.expected_success(200, resp.status) body = json.loads(body) return rest_client.ResponseBody(resp, body) def delete_credential(self, credential_id): """Deletes a credential.""" resp, body = self.delete('credentials/%s' % credential_id) self.expected_success(204, resp.status) return rest_client.ResponseBody(resp, body)
{ "content_hash": "9315fc52fcf5f8ca3c7eadd12557c7cc", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 76, "avg_line_length": 38.827586206896555, "alnum_prop": 0.6309946714031972, "repo_name": "LIS/lis-tempest", "id": "6ab94d049596ff384fd39aa1348787f99001d028", "size": "2888", "binary": false, "copies": "6", "ref": "refs/heads/LIS", "path": "tempest/services/identity/v3/json/credentials_client.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "3607367" }, { "name": "Shell", "bytes": "50010" } ], "symlink_target": "" }
module Main where import qualified Server main :: IO () main = Server.main
{ "content_hash": "0c9bc11a164846bffbd4d4f0f23688af", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 23, "avg_line_length": 12.833333333333334, "alnum_prop": 0.7272727272727273, "repo_name": "nathanic/purescript-simple-chat-client", "id": "ac0edfd378be7064b111acf2ee976be021e07efd", "size": "77", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "server/app/Main.hs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "526" }, { "name": "Haskell", "bytes": "5542" }, { "name": "JavaScript", "bytes": "230" }, { "name": "PureScript", "bytes": "8883" } ], "symlink_target": "" }
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class M_news extends CI_Model { public function __construct() { parent::__construct(); } function total_record() { //hitung jumlah total data $this->db->from("berita"); return $this->db->count_all_results(); } function getNews($limit, $start = 0) { //ambil semua berita untuk halaman news, dengan pagination $this->db->select('*'); $this->db->select("DATE_FORMAT(tgl_posting, '%d') AS hari", FALSE ); //%d : Hari di bulan ini, angka (00-31) $this->db->select("DATE_FORMAT(tgl_posting, '%b') AS bulan", FALSE ); //%b : Singkatan nama bulan (Bahasa Inggris) (Jan..Dec)) $this->db->select("DATE_FORMAT(tgl_posting, '%Y') AS tahun", FALSE ); //%Y : Tahun, empat angka $this->db->from('berita'); //$this->db->join('t_user', 't_user.id_user = berita.id_user'); $this->db->order_by("id_berita", "desc"); $this->db->limit($limit, $start); return $this->db->get(); } function getNewsRead($read) { //ambil 1 berita untuk halaman news_read, tanpa pagination $this->db->select('*'); $this->db->select("DATE_FORMAT(tgl_posting, '%d') AS hari", FALSE ); //%d : Hari di bulan ini, angka (00-31) $this->db->select("DATE_FORMAT(tgl_posting, '%b') AS bulan", FALSE ); //%b : Singkatan nama bulan (Bahasa Inggris) (Jan..Dec)) $this->db->select("DATE_FORMAT(tgl_posting, '%Y') AS tahun", FALSE ); //%Y : Tahun, empat angka $this->db->from('berita'); //$this->db->join('t_user', 't_user.id_user = berita.id_user'); $this->db->where('id_berita', $read); $query = $this->db->get(); return $query->row_array(); } function getNewsLatest() { //ambil berita untuk latest news, limit 5 berita terbaru $this->db->select('*'); $this->db->from('berita'); $this->db->order_by("id_berita", "desc"); $this->db->limit(5); return $this->db->get(); } } /* End of file M_news.php */ /* Location: ./application/modules/berita_tag/models/M_news.php */ /* function getTags(){ $this->db->select('id_berita, tag_berita'); $this->db->from('berita'); $this->db->order_by("id_berita", "desc"); return $this->db->get(); } function getKategori(){ $this->db->select('*'); $this->db->from('berita_kategori'); $this->db->order_by("id_kategori", "desc"); return $this->db->get(); } */
{ "content_hash": "37d939426bafc93505b45cbc92952937", "timestamp": "", "source": "github", "line_count": 76, "max_line_length": 135, "avg_line_length": 33.61842105263158, "alnum_prop": 0.5565557729941292, "repo_name": "kikiiramdhani123/rpl-sampah", "id": "0461e9b8c051c4ba3fe1a7dfdc17a74c13cc1dcd", "size": "2555", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "application/modules/news/models/M_news.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "727" }, { "name": "CSS", "bytes": "646739" }, { "name": "HTML", "bytes": "8441930" }, { "name": "JavaScript", "bytes": "93015" }, { "name": "PHP", "bytes": "3697938" } ], "symlink_target": "" }
// Copyright (c) 2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_CONSENSUS_VERSIONBITS #define BITCOIN_CONSENSUS_VERSIONBITS #include "chain.h" #include <map> /** What block version to use for new blocks (pre versionbits) */ static const int32_t VERSIONBITS_LAST_OLD_BLOCK_VERSION = 4; /** What bits to set in version for versionbits blocks */ static const int32_t VERSIONBITS_TOP_BITS = 0x20000000UL; /** What bitmask determines whether versionbits is in use */ static const int32_t VERSIONBITS_TOP_MASK = 0xE0000000UL; /** Total bits available for versionbits */ static const int32_t VERSIONBITS_NUM_BITS = 29; enum ThresholdState { THRESHOLD_DEFINED, THRESHOLD_STARTED, THRESHOLD_LOCKED_IN, THRESHOLD_ACTIVE, THRESHOLD_FAILED, }; // A map that gives the state for blocks whose height is a multiple of Period(). // The map is indexed by the block's parent, however, so all keys in the map // will either be NULL or a block with (height + 1) % Period() == 0. typedef std::map<const CBlockIndex *, ThresholdState> ThresholdConditionCache; struct BIP9DeploymentInfo { /** Deployment name */ const char *name; /** Whether GBT clients can safely ignore this rule in simplified usage */ bool gbt_force; }; extern const struct BIP9DeploymentInfo VersionBitsDeploymentInfo[]; /** * Abstract class that implements BIP9-style threshold logic, and caches results. */ class AbstractThresholdConditionChecker { protected: virtual bool Condition(const CBlockIndex *pindex, const Consensus::Params &params) const = 0; virtual int64_t BeginTime(const Consensus::Params &params) const = 0; virtual int64_t EndTime(const Consensus::Params &params) const = 0; virtual int Period(const Consensus::Params &params) const = 0; virtual int Threshold(const Consensus::Params &params) const = 0; public: // Note that the function below takes a pindexPrev as input: they compute information for block B based on its parent. ThresholdState GetStateFor(const CBlockIndex *pindexPrev, const Consensus::Params &params, ThresholdConditionCache &cache) const; }; struct VersionBitsCache { ThresholdConditionCache caches[Consensus::MAX_VERSION_BITS_DEPLOYMENTS]; void Clear(); }; ThresholdState VersionBitsState(const CBlockIndex *pindexPrev, const Consensus::Params &params, Consensus::DeploymentPos pos, VersionBitsCache &cache); uint32_t VersionBitsMask(const Consensus::Params &params, Consensus::DeploymentPos pos); #endif
{ "content_hash": "cf7a9fdeb5bedc88b9ae3e65b0999742", "timestamp": "", "source": "github", "line_count": 71, "max_line_length": 151, "avg_line_length": 37.183098591549296, "alnum_prop": 0.7518939393939394, "repo_name": "realzzt/BitCoin2013", "id": "26ee0c63895ebaa8ad1c4f1d13550c52baa329ba", "size": "2640", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/versionbits.h", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "29375" }, { "name": "C", "bytes": "703206" }, { "name": "C++", "bytes": "4667168" }, { "name": "CSS", "bytes": "1216" }, { "name": "HTML", "bytes": "51842" }, { "name": "Java", "bytes": "33209" }, { "name": "M4", "bytes": "189542" }, { "name": "Makefile", "bytes": "102451" }, { "name": "Objective-C", "bytes": "4081" }, { "name": "Objective-C++", "bytes": "7465" }, { "name": "Protocol Buffer", "bytes": "2376" }, { "name": "Python", "bytes": "983598" }, { "name": "QMake", "bytes": "4108" }, { "name": "Shell", "bytes": "50752" } ], "symlink_target": "" }
export async function sleep(time: number): Promise<void> { return new Promise<void>((resolve, reject) => setTimeout(resolve, time)); }
{ "content_hash": "c99cb388dc3436aa4d81748109f7b669", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 74, "avg_line_length": 35.25, "alnum_prop": 0.7021276595744681, "repo_name": "CactusDev/Aerophyl", "id": "e7e3d05b0e1d6bd07c63d80589ddda290566d647", "size": "141", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/util.ts", "mode": "33188", "license": "mit", "language": [ { "name": "TypeScript", "bytes": "19620" } ], "symlink_target": "" }
/** * TaltioniAPI_GetHealthRecordItemTypes_ReceiverFault_FaultMessage.java * * This file was auto-generated from WSDL * by the Apache Axis2 version: 1.6.2 Built on : Apr 17, 2012 (05:33:49 IST) */ package fi.taltioni._0._1.taltioniapi; public class TaltioniAPI_GetHealthRecordItemTypes_ReceiverFault_FaultMessage extends java.lang.Exception{ private static final long serialVersionUID = 1375440886621L; private fi.taltioni._0._1.taltioniapi.TaltioniServiceStub.ReceiverFault1 faultMessage; public TaltioniAPI_GetHealthRecordItemTypes_ReceiverFault_FaultMessage() { super("TaltioniAPI_GetHealthRecordItemTypes_ReceiverFault_FaultMessage"); } public TaltioniAPI_GetHealthRecordItemTypes_ReceiverFault_FaultMessage(java.lang.String s) { super(s); } public TaltioniAPI_GetHealthRecordItemTypes_ReceiverFault_FaultMessage(java.lang.String s, java.lang.Throwable ex) { super(s, ex); } public TaltioniAPI_GetHealthRecordItemTypes_ReceiverFault_FaultMessage(java.lang.Throwable cause) { super(cause); } public void setFaultMessage(fi.taltioni._0._1.taltioniapi.TaltioniServiceStub.ReceiverFault1 msg){ faultMessage = msg; } public fi.taltioni._0._1.taltioniapi.TaltioniServiceStub.ReceiverFault1 getFaultMessage(){ return faultMessage; } }
{ "content_hash": "f4f091b58097bb8abb327eecb9c19d6d", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 124, "avg_line_length": 32.97674418604651, "alnum_prop": 0.7172073342736248, "repo_name": "Sensotrend/moves2taltioni", "id": "8bed210ef7e7fe7ad6c48fafe51cce1802152cb3", "size": "1418", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/fi/taltioni/_0/_1/taltioniapi/TaltioniAPI_GetHealthRecordItemTypes_ReceiverFault_FaultMessage.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "6075369" } ], "symlink_target": "" }
<?php /** * Message translations. * * This file is automatically generated by 'yii message' command. * It contains the localizable messages extracted from source code. * You may modify this file by translating the extracted messages. * * Each array element represents the translation (value) of a message (key). * If the value is empty, the message is considered as not translated. * Messages that no longer need translation will have their translations * enclosed between a pair of '@@' marks. * * Message string can be used with plural forms format. Check i18n section * of the guide for details. * * NOTE: this file must be saved in UTF-8 encoding. */ return [ 'BACKEND_UPDATE_SUBTITLE' => 'Обновление модели', 'BACKEND_UPDATE_TITLE' => 'Модели', 'ATTR_CREATED' => 'Дата создания', 'ATTR_ID' => 'ИД', 'ATTR_NAME' => 'Модель', 'ATTR_STATUS' => 'Стату', 'ATTR_UPDATED' => 'Дата обновления', 'BACKEND_CREATE_PLACEHOLDER_NAME' => 'vova07/blogs/models/Blog', 'BACKEND_CREATE_SUBMIT' => 'Сохранить', 'BACKEND_CREATE_SUBTITLE' => 'Создание модели', 'BACKEND_CREATE_TITLE' => 'Модели', 'BACKEND_FLASH_FAIL_ADMIN_CREATE' => 'Не удалось сохранить модель. Попробуйте пожалуйста еще раз!', 'BACKEND_FLASH_FAIL_ADMIN_DISABLE' => 'Не удалось выключить модуль. Попробуйте пожалуйста еще раз!', 'BACKEND_FLASH_FAIL_ADMIN_ENABLE' => 'Не удалось включить модуль. Попробуйте пожалуйста еще раз!', 'BACKEND_FLASH_FAIL_ADMIN_UPDATE' => 'Не удалось обновить модель. Попробуйте пожалуйста еще раз!', 'BACKEND_INDEX_MODULES_DISABLE_CONFIRMATION' => 'Все комментарии модуля будут удалены. Вы уверены что хотите отключить этот модуль?', 'BACKEND_INDEX_MODULE_BLOGS' => 'Блоги', 'BACKEND_INDEX_SUBTITLE' => 'Список моделей', 'BACKEND_INDEX_TITLE' => 'Модели', 'BACKEND_INDEX_TITLE_ENABLING' => 'Включить/Выключить комментарии для установленных модулей', 'BACKEND_UPDATE_SUBMIT' => 'Обновить', 'STATUS_DISABLED' => 'Отключён', 'STATUS_ENABLED' => 'Включён', ];
{ "content_hash": "5dae9ae37b3381c7bd654f507119b32f", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 137, "avg_line_length": 47.53488372093023, "alnum_prop": 0.6981409001956947, "repo_name": "Zotyrn/ext_site", "id": "0c2430ca5f3b5dd532427fc68dbcdeee2ec518db", "size": "2499", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "vendor/vova07/yii2-start-comments-module/messages/ru/comments-models.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "1543" }, { "name": "Batchfile", "bytes": "1032" }, { "name": "PHP", "bytes": "556869" } ], "symlink_target": "" }
package core.main_view.content_view.products_view.item_view; /** * Created by Mohammed Matar * Creation Date 2/27/15. */ public class ItemViewPresenter { }
{ "content_hash": "b1add0fda6e2874e2b1292a2ac586c33", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 60, "avg_line_length": 20, "alnum_prop": 0.73125, "repo_name": "jmatar-sd/b-shopper", "id": "446867f0b299407106bf6fc0465fb2cdc3c710c1", "size": "160", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "b-shopper-ui/src/main/java/core/main_view/content_view/products_view/item_view/ItemViewPresenter.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "6406" }, { "name": "Java", "bytes": "22071" } ], "symlink_target": "" }
import DocumentView from "trix/views/document_view" import { normalizeRange } from "trix/core/helpers" const { assert } = QUnit assert.locationRange = function (start, end) { const expectedLocationRange = normalizeRange([ start, end ]) const actualLocationRange = getEditorController().getLocationRange() this.deepEqual(actualLocationRange, expectedLocationRange) } assert.selectedRange = function (range) { const expectedRange = normalizeRange(range) const actualRange = getEditor().getSelectedRange() this.deepEqual(actualRange, expectedRange) } assert.textAttributes = function (range, attributes) { const document = window.getDocument().getDocumentAtRange(range) const blocks = document.getBlocks() if (blocks.length !== 1) { throw `range ${JSON.stringify(range)} spans more than one block` } const locationRange = window.getDocument().locationRangeFromRange(range) const textIndex = locationRange[0].index const textRange = [ locationRange[0].offset, locationRange[1].offset ] const text = window.getDocument().getTextAtIndex(textIndex).getTextAtRange(textRange) const pieces = text.getPieces() if (pieces.length !== 1) { throw `range ${JSON.stringify(range)} must only span one piece` } const piece = pieces[0] this.deepEqual(piece.getAttributes(), attributes) } assert.blockAttributes = function (range, attributes) { const document = window.getDocument().getDocumentAtRange(range) const blocks = document.getBlocks() if (blocks.length !== 1) { throw `range ${JSON.stringify(range)} spans more than one block` } const block = blocks[0] this.deepEqual(block.getAttributes(), attributes) } assert.documentHTMLEqual = function (trixDocument, html) { this.equal(getHTML(trixDocument), html) } const getHTML = (trixDocument) => DocumentView.render(trixDocument).innerHTML export const expectDocument = (expectedDocumentValue, element) => { if (!element) element = getEditorElement() assert.equal(element.editor.getDocument().toString(), expectedDocumentValue) } export { assert, getHTML }
{ "content_hash": "6a926d0e40ee5b201eb786b42235701d", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 87, "avg_line_length": 34.516666666666666, "alnum_prop": 0.748913568324481, "repo_name": "basecamp/trix", "id": "1dc65659126de430f6ccc70740b38761605477b1", "size": "2071", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "src/test/test_helpers/assertions.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "2683" }, { "name": "JavaScript", "bytes": "536367" }, { "name": "Ruby", "bytes": "3328" }, { "name": "SCSS", "bytes": "11194" }, { "name": "Shell", "bytes": "2017" } ], "symlink_target": "" }
var Q = require('q'); var Logger = require('bower-logger'); /** * Require commands only when called. * * Running `commandFactory(id)` is equivalent to `require(id)`. Both calls return * a command function. The difference is that `cmd = commandFactory()` and `cmd()` * return as soon as possible and load and execute the command asynchronously. */ function commandFactory(id) { if (process.env.STRICT_REQUIRE) { require(id); } function command() { var commandArgs = [].slice.call(arguments); return withLogger(function (logger) { commandArgs.unshift(logger); return require(id).apply(undefined, commandArgs); }); } function runFromArgv(argv) { return withLogger(function (logger) { return require(id).line.call(undefined, logger, argv); }); } function withLogger(func) { var logger = new Logger(); Q.try(func, logger) .done(function () { var args = [].slice.call(arguments); args.unshift('end'); logger.emit.apply(logger, args); }, function (error) { logger.emit('error', error); }); return logger; } command.line = runFromArgv; return command; } module.exports = { cache: { clean: commandFactory('./cache/clean'), list: commandFactory('./cache/list'), }, completion: commandFactory('./completion'), help: commandFactory('./help'), home: commandFactory('./home'), info: commandFactory('./info'), init: commandFactory('./init'), install: commandFactory('./install'), link: commandFactory('./link'), list: commandFactory('./list'), lookup: commandFactory('./lookup'), prune: commandFactory('./prune'), register: commandFactory('./register'), search: commandFactory('./search'), update: commandFactory('./update'), uninstall: commandFactory('./uninstall'), version: commandFactory('./version') };
{ "content_hash": "c6bbe9b9e6234e60c38ecaea0753e75c", "timestamp": "", "source": "github", "line_count": 71, "max_line_length": 82, "avg_line_length": 29.35211267605634, "alnum_prop": 0.5825335892514395, "repo_name": "rowanmiller/Demo-MVADec14", "id": "d58c3c6aea3b5925900d0f69213f6e3fb4415f38", "size": "2084", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "CompletedSource/CycleSales/src/CycleSales/node_modules/grunt-bower-task/node_modules/bower/lib/commands/index.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "41980" }, { "name": "CSS", "bytes": "1252" }, { "name": "JavaScript", "bytes": "2312" } ], "symlink_target": "" }
package com.navercorp.pinpoint.profiler.monitor.codahale; import com.google.inject.Inject; import com.navercorp.pinpoint.bootstrap.config.ProfilerConfig; import com.navercorp.pinpoint.profiler.context.TransactionCounter; import com.navercorp.pinpoint.profiler.context.active.ActiveTraceRepository; import com.navercorp.pinpoint.profiler.context.monitor.DataSourceMonitorWrapper; import com.navercorp.pinpoint.profiler.context.monitor.DefaultPluginMonitorContext; import com.navercorp.pinpoint.profiler.context.monitor.PluginMonitorContext; import com.navercorp.pinpoint.profiler.context.monitor.PluginMonitorWrapperLocator; import com.navercorp.pinpoint.profiler.monitor.MonitorName; import com.navercorp.pinpoint.profiler.monitor.codahale.activetrace.ActiveTraceMetricCollector; import com.navercorp.pinpoint.profiler.monitor.codahale.activetrace.DefaultActiveTraceMetricCollector; import com.navercorp.pinpoint.profiler.monitor.codahale.activetrace.metric.ActiveTraceMetricSet; import com.navercorp.pinpoint.profiler.monitor.codahale.cpu.CpuLoadCollector; import com.navercorp.pinpoint.profiler.monitor.codahale.cpu.DefaultCpuLoadCollector; import com.navercorp.pinpoint.profiler.monitor.codahale.cpu.metric.CpuLoadMetricSet; import com.navercorp.pinpoint.profiler.monitor.codahale.datasource.DataSourceCollector; import com.navercorp.pinpoint.profiler.monitor.codahale.datasource.DefaultDataSourceCollector; import com.navercorp.pinpoint.profiler.monitor.codahale.datasource.metric.DataSourceMetricSet; import com.navercorp.pinpoint.profiler.monitor.codahale.gc.CmsCollector; import com.navercorp.pinpoint.profiler.monitor.codahale.gc.CmsDetailedMetricsCollector; import com.navercorp.pinpoint.profiler.monitor.codahale.gc.G1Collector; import com.navercorp.pinpoint.profiler.monitor.codahale.gc.G1DetailedMetricsCollector; import com.navercorp.pinpoint.profiler.monitor.codahale.gc.GarbageCollector; import com.navercorp.pinpoint.profiler.monitor.codahale.gc.ParallelCollector; import com.navercorp.pinpoint.profiler.monitor.codahale.gc.ParallelDetailedMetricsCollector; import com.navercorp.pinpoint.profiler.monitor.codahale.gc.SerialCollector; import com.navercorp.pinpoint.profiler.monitor.codahale.gc.SerialDetailedMetricsCollector; import com.navercorp.pinpoint.profiler.monitor.codahale.gc.UnknownGarbageCollector; import com.navercorp.pinpoint.profiler.monitor.codahale.tps.DefaultTransactionMetricCollector; import com.navercorp.pinpoint.profiler.monitor.codahale.tps.TransactionMetricCollector; import com.navercorp.pinpoint.profiler.monitor.codahale.tps.metric.TransactionMetricSet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collection; import static com.navercorp.pinpoint.profiler.monitor.codahale.MetricMonitorValues.*; /** * @author emeroad * @author harebox * @author hyungil.jeong */ public class DefaultAgentStatCollectorFactory implements AgentStatCollectorFactory { private final Logger logger = LoggerFactory.getLogger(this.getClass()); private final MetricMonitorRegistry monitorRegistry; private final GarbageCollector garbageCollector; private final CpuLoadCollector cpuLoadCollector; private final TransactionMetricCollector transactionMetricCollector; private final ActiveTraceMetricCollector activeTraceMetricCollector; private final DataSourceCollector dataSourceCollector; @Inject public DefaultAgentStatCollectorFactory(ProfilerConfig profilerConfig, ActiveTraceRepository activeTraceRepository, TransactionCounter transactionCounter, PluginMonitorContext pluginMonitorContext) { if (profilerConfig == null) { throw new NullPointerException("profilerConfig must not be null"); } // if (activeTraceRepository == null) { // throw new NullPointerException("activeTraceRepository must not be null"); // } if (transactionCounter == null) { throw new NullPointerException("transactionCounter must not be null"); } // if (pluginMonitorContext == null) { // throw new NullPointerException("pluginMonitorContext must not be null"); // } this.monitorRegistry = createRegistry(); this.garbageCollector = createGarbageCollector(profilerConfig.isProfilerJvmCollectDetailedMetrics()); this.cpuLoadCollector = createCpuLoadCollector(profilerConfig.getProfilerJvmVendorName()); this.transactionMetricCollector = createTransactionMetricCollector(transactionCounter); this.activeTraceMetricCollector = createActiveTraceCollector(activeTraceRepository, profilerConfig.isTraceAgentActiveThread()); this.dataSourceCollector = createDataSourceCollector(pluginMonitorContext); } private MetricMonitorRegistry createRegistry() { final MetricMonitorRegistry monitorRegistry = new MetricMonitorRegistry(); return monitorRegistry; } /** * create with garbage collector types based on metric registry keys */ private GarbageCollector createGarbageCollector(boolean collectDetailedMetrics) { MetricMonitorRegistry registry = this.monitorRegistry; registry.registerJvmMemoryMonitor(new MonitorName(MetricMonitorValues.JVM_MEMORY)); registry.registerJvmGcMonitor(new MonitorName(MetricMonitorValues.JVM_GC)); Collection<String> keys = registry.getRegistry().getNames(); GarbageCollector garbageCollectorToReturn = new UnknownGarbageCollector(); if (collectDetailedMetrics) { if (keys.contains(JVM_GC_SERIAL_OLDGEN_COUNT)) { garbageCollectorToReturn = new SerialDetailedMetricsCollector(registry); } else if (keys.contains(JVM_GC_PS_OLDGEN_COUNT)) { garbageCollectorToReturn = new ParallelDetailedMetricsCollector(registry); } else if (keys.contains(JVM_GC_CMS_OLDGEN_COUNT)) { garbageCollectorToReturn = new CmsDetailedMetricsCollector(registry); } else if (keys.contains(JVM_GC_G1_OLDGEN_COUNT)) { garbageCollectorToReturn = new G1DetailedMetricsCollector(registry); } } else { if (keys.contains(JVM_GC_SERIAL_OLDGEN_COUNT)) { garbageCollectorToReturn = new SerialCollector(registry); } else if (keys.contains(JVM_GC_PS_OLDGEN_COUNT)) { garbageCollectorToReturn = new ParallelCollector(registry); } else if (keys.contains(JVM_GC_CMS_OLDGEN_COUNT)) { garbageCollectorToReturn = new CmsCollector(registry); } else if (keys.contains(JVM_GC_G1_OLDGEN_COUNT)) { garbageCollectorToReturn = new G1Collector(registry); } } if (logger.isInfoEnabled()) { logger.info("found : {}", garbageCollectorToReturn); } return garbageCollectorToReturn; } private CpuLoadCollector createCpuLoadCollector(String vendorName) { CpuLoadMetricSet cpuLoadMetricSet = this.monitorRegistry.registerCpuLoadMonitor(new MonitorName(MetricMonitorValues.CPU_LOAD), vendorName); if (logger.isInfoEnabled()) { logger.info("loaded : {}", cpuLoadMetricSet); } return new DefaultCpuLoadCollector(cpuLoadMetricSet); } private TransactionMetricCollector createTransactionMetricCollector(TransactionCounter transactionCounter) { if (transactionCounter == null) { return TransactionMetricCollector.EMPTY_TRANSACTION_METRIC_COLLECTOR; } MonitorName monitorName = new MonitorName(MetricMonitorValues.TRANSACTION); TransactionMetricSet transactionMetricSet = this.monitorRegistry.registerTpsMonitor(monitorName, transactionCounter); if (logger.isInfoEnabled()) { logger.info("loaded : {}", transactionMetricSet); } return new DefaultTransactionMetricCollector(transactionMetricSet); } private ActiveTraceMetricCollector createActiveTraceCollector(ActiveTraceRepository activeTraceRepository, boolean isTraceAgentActiveThread) { if (!isTraceAgentActiveThread) { return ActiveTraceMetricCollector.EMPTY_ACTIVE_TRACE_COLLECTOR; } if (activeTraceRepository != null) { ActiveTraceMetricSet activeTraceMetricSet = this.monitorRegistry.registerActiveTraceMetricSet(new MonitorName(MetricMonitorValues.ACTIVE_TRACE), activeTraceRepository); if (logger.isInfoEnabled()) { logger.info("loaded : {}", activeTraceMetricSet); } return new DefaultActiveTraceMetricCollector(activeTraceMetricSet); } else { logger.warn("agent set to trace active threads but no ActiveTraceLocator found"); } return ActiveTraceMetricCollector.EMPTY_ACTIVE_TRACE_COLLECTOR; } private DataSourceCollector createDataSourceCollector(PluginMonitorContext pluginMonitorContext) { if (pluginMonitorContext instanceof DefaultPluginMonitorContext) { PluginMonitorWrapperLocator<DataSourceMonitorWrapper> dataSourceMonitorLocator = ((DefaultPluginMonitorContext) pluginMonitorContext).getDataSourceMonitorLocator(); if (dataSourceMonitorLocator != null) { DataSourceMetricSet dataSourceMetricSet = this.monitorRegistry.registerDataSourceMonitor(new MonitorName(MetricMonitorValues.DATASOURCE), dataSourceMonitorLocator); return new DefaultDataSourceCollector(dataSourceMetricSet); } } return DataSourceCollector.EMPTY_DATASOURCE_COLLECTOR; } @Override public GarbageCollector getGarbageCollector() { return this.garbageCollector; } @Override public CpuLoadCollector getCpuLoadCollector() { return this.cpuLoadCollector; } @Override public TransactionMetricCollector getTransactionMetricCollector() { return this.transactionMetricCollector; } @Override public ActiveTraceMetricCollector getActiveTraceMetricCollector() { return this.activeTraceMetricCollector; } @Override public DataSourceCollector getDataSourceCollector() { return this.dataSourceCollector; } }
{ "content_hash": "6c61070088716874102e830f03aff716", "timestamp": "", "source": "github", "line_count": 200, "max_line_length": 203, "avg_line_length": 51.06, "alnum_prop": 0.7604778691735213, "repo_name": "sjmittal/pinpoint", "id": "ba1aa43da5162e99c2831e1380a2c01c2ffcdd47", "size": "10806", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "profiler/src/main/java/com/navercorp/pinpoint/profiler/monitor/codahale/DefaultAgentStatCollectorFactory.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "22853" }, { "name": "CSS", "bytes": "148240" }, { "name": "CoffeeScript", "bytes": "10124" }, { "name": "Groovy", "bytes": "1423" }, { "name": "HTML", "bytes": "627927" }, { "name": "Java", "bytes": "9799087" }, { "name": "JavaScript", "bytes": "4822318" }, { "name": "Makefile", "bytes": "5246" }, { "name": "PLSQL", "bytes": "4156" }, { "name": "Python", "bytes": "3523" }, { "name": "Ruby", "bytes": "943" }, { "name": "Shell", "bytes": "30663" }, { "name": "Thrift", "bytes": "9043" } ], "symlink_target": "" }
""" Shell utility functions which use non-blocking and eventlet / gevent friendly code. """ from __future__ import absolute_import import os import subprocess import six from st2common import log as logging from st2common.util import concurrency __all__ = ["run_command"] TIMEOUT_EXIT_CODE = -9 LOG = logging.getLogger(__name__) def run_command( cmd, stdin=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False, cwd=None, env=None, timeout=60, preexec_func=None, kill_func=None, read_stdout_func=None, read_stderr_func=None, read_stdout_buffer=None, read_stderr_buffer=None, stdin_value=None, bufsize=0, ): """ Run the provided command in a subprocess and wait until it completes. :param cmd: Command to run. :type cmd: ``str`` or ``list`` :param stdin: Process stdin. :type stdin: ``object`` :param stdout: Process stdout. :type stdout: ``object`` :param stderr: Process stderr. :type stderr: ``object`` :param shell: True to use a shell. :type shell ``boolean`` :param cwd: Optional working directory. :type cwd: ``str`` :param env: Optional environment to use with the command. If not provided, environment from the current process is inherited. :type env: ``dict`` :param timeout: How long to wait before timing out. :type timeout: ``float`` :param preexec_func: Optional pre-exec function. :type preexec_func: ``callable`` :param kill_func: Optional function which will be called on timeout to kill the process. If not provided, it defaults to `process.kill` NOTE: If you are utilizing shell=True, you shoulf always specify a custom kill function which correctly kills shell process + the shell children process. If you don't do that, timeout handler won't work correctly / as expected - only the shell process will be killed, but not also the child processs spawned by the shell. :type kill_func: ``callable`` :param read_stdout_func: Function which is responsible for reading process stdout when using live read mode. :type read_stdout_func: ``func`` :param read_stdout_func: Function which is responsible for reading process stderr when using live read mode. :type read_stdout_func: ``func`` :param bufsize: Buffer size argument to pass to subprocess.popen function. :type bufsize: ``int`` :rtype: ``tuple`` (exit_code, stdout, stderr, timed_out) """ LOG.debug("Entering st2common.util.green.run_command.") if not isinstance(cmd, (list, tuple) + six.string_types): raise TypeError( f"Command must be a type of list, tuple, or string, not '{type(cmd)}'." ) if (read_stdout_func and not read_stderr_func) or ( read_stderr_func and not read_stdout_func ): raise ValueError( "Both read_stdout_func and read_stderr_func arguments need " "to be provided." ) if read_stdout_func and not (read_stdout_buffer or read_stderr_buffer): raise ValueError( "read_stdout_buffer and read_stderr_buffer arguments need to be provided " "when read_stdout_func is provided" ) if not env: LOG.debug("env argument not provided. using process env (os.environ).") env = os.environ.copy() subprocess = concurrency.get_subprocess_module() # Note: We are using eventlet / gevent friendly implementation of subprocess which uses # GreenPipe so it doesn't block LOG.debug("Creating subprocess.") process = concurrency.subprocess_popen( args=cmd, stdin=stdin, stdout=stdout, stderr=stderr, env=env, cwd=cwd, shell=shell, preexec_fn=preexec_func, bufsize=bufsize, ) if read_stdout_func: LOG.debug("Spawning read_stdout_func function") read_stdout_thread = concurrency.spawn( read_stdout_func, process.stdout, read_stdout_buffer ) if read_stderr_func: LOG.debug("Spawning read_stderr_func function") read_stderr_thread = concurrency.spawn( read_stderr_func, process.stderr, read_stderr_buffer ) # Special attribute we use to determine if the process timed out or not process._timed_out = False # TODO: Now that we support Python >= 3.6 we should utilize timeout argument for the # communicate() method and handle killing the process + read threads there. def on_timeout_expired(timeout): global timed_out try: LOG.debug("Starting process wait inside timeout handler.") process.wait(timeout=timeout) except subprocess.TimeoutExpired: # Command has timed out, kill the process and propagate the error. # Note: We explicitly set the returncode to indicate the timeout. LOG.debug("Command execution timeout reached.") process._timed_out = True if kill_func: LOG.debug("Calling kill_func.") kill_func(process=process) else: LOG.debug("Killing process.") process.kill() process.wait() process._timed_out = True if read_stdout_func and read_stderr_func: LOG.debug("Killing read_stdout_thread and read_stderr_thread") concurrency.kill(read_stdout_thread) concurrency.kill(read_stderr_thread) LOG.debug("Spawning timeout handler thread.") timeout_thread = concurrency.spawn(on_timeout_expired, timeout) LOG.debug("Attaching to process.") if stdin_value: if six.PY3: stdin_value = stdin_value.encode("utf-8") process.stdin.write(stdin_value) if read_stdout_func and read_stderr_func: LOG.debug("Using real-time stdout and stderr read mode, calling process.wait()") process.wait() else: LOG.debug( "Using delayed stdout and stderr read mode, calling process.communicate()" ) stdout, stderr = process.communicate() concurrency.cancel(timeout_thread) if getattr(process, "_timed_out", False): exit_code = TIMEOUT_EXIT_CODE else: exit_code = process.returncode if read_stdout_func and read_stderr_func: # Wait on those green threads to finish reading from stdout and stderr before continuing concurrency.wait(read_stdout_thread) concurrency.wait(read_stderr_thread) stdout = read_stdout_buffer.getvalue() stderr = read_stderr_buffer.getvalue() if exit_code == TIMEOUT_EXIT_CODE: LOG.debug("Timeout.") timed_out = True else: LOG.debug("No timeout.") timed_out = False LOG.debug("Returning.") return (exit_code, stdout, stderr, timed_out)
{ "content_hash": "5510adcd7826ca53019f861ee3c28d53", "timestamp": "", "source": "github", "line_count": 225, "max_line_length": 96, "avg_line_length": 31.662222222222223, "alnum_prop": 0.623385738349242, "repo_name": "nzlosh/st2", "id": "64830c9423c25c5e10f3ab13852b736caee2b6ef", "size": "7752", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "st2common/st2common/util/green/shell.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "198" }, { "name": "JavaScript", "bytes": "444" }, { "name": "Jinja", "bytes": "174532" }, { "name": "Makefile", "bytes": "75242" }, { "name": "PowerShell", "bytes": "856" }, { "name": "Python", "bytes": "6453910" }, { "name": "Shell", "bytes": "93607" }, { "name": "Starlark", "bytes": "7236" } ], "symlink_target": "" }
<?php namespace ViewComponents\ViewComponents\Component\Html; use Nayjest\Tree\ChildNodeInterface; use ViewComponents\ViewComponents\Base\Html\AutoSubmittingInputInterface; use ViewComponents\ViewComponents\Base\Html\AutoSubmittingInputTagTrait; use ViewComponents\ViewComponents\Base\Html\TagInterface; use ViewComponents\ViewComponents\Component\DataView; class Select extends Tag implements AutoSubmittingInputInterface { use AutoSubmittingInputTagTrait; /** * @param array|null $attributes * @param array $options components or 'value' => 'label' array * @param string $selectedValue */ public function __construct( array $attributes = [], array $options = [], $selectedValue = null ) { parent::__construct( 'select', $attributes, self::makeOptionComponents($options) ); if ($selectedValue !== null) { $this->setOptionSelected($selectedValue); } } private function setOptionSelected($selectedValue) { /** @var TagInterface $option */ foreach ($this->children() as $option) { if (!$option instanceof TagInterface) { continue; } if ((string)$option->getAttribute('value') === (string)$selectedValue) { // @todo setAttribute not in tag interface $option->setAttribute('selected', 'selected'); } } } private static function makeOptionComponents($options) { $components = []; foreach ($options as $value => $label) { if ($label instanceof ChildNodeInterface) { $components[] = $label; } else { $components[] = new Tag( 'option', ['value' => $value], [new DataView($label)] ); } } return $components; } }
{ "content_hash": "fb31164f6f91e41c632fa6884fda82d9", "timestamp": "", "source": "github", "line_count": 64, "max_line_length": 84, "avg_line_length": 30.8125, "alnum_prop": 0.5730223123732252, "repo_name": "Nayjest/ViewComponents", "id": "ff814bb2108c10fbcb2fd97385f83f7b62ae635c", "size": "1972", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/Component/Html/Select.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "166092" } ], "symlink_target": "" }
SYNONYM #### According to Index Fungorum #### Published in null #### Original name Clavaria gollani Henn. ### Remarks null
{ "content_hash": "7cb0078e701fe00e6d0e7977aa4417d5", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 22, "avg_line_length": 9.692307692307692, "alnum_prop": 0.6984126984126984, "repo_name": "mdoering/backbone", "id": "b9f8fccb332be630d9e5675f3831d9f093f3b9e0", "size": "172", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Basidiomycota/Agaricomycetes/Agaricales/Clavariaceae/Clavaria/Clavaria gollanii/ Syn. Clavaria gollani/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "5bbb0764cf6dc2be5c4875a390cfc972", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "d55aab376985796c97459e46828a0552280e73ca", "size": "172", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Saxifragales/Saxifragaceae/Heuchera/Heuchera squamosa/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package com.zuoxiaolong.util; import com.google.gson.Gson; import java.awt.*; import java.io.IOException; import java.io.OutputStream; import java.net.*; import java.util.Map; import javax.servlet.http.HttpServletRequest; /** * @author 左潇龙 * @since 2015年5月24日 上午12:23:01 */ public abstract class HttpUtil { private static HttpURLConnection httpURLConnection(String url, String method) throws IOException { HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setRequestMethod(method); connection.setReadTimeout(3000); connection.setConnectTimeout(1000); connection.setDoInput(true); connection.setDoOutput(true); return connection; } public static String sendHttpJsonRequest(String url, String method , Object params) { try { HttpURLConnection connection = httpURLConnection(url, method); connection.setRequestProperty("Content-Type", "application/json; charset=utf-8"); connection.connect(); OutputStream outputStream = connection.getOutputStream(); outputStream.write(JsonUtils.toJson(params).getBytes("UTF-8")); outputStream.flush(); return new String(IOUtil.readStreamBytes(connection), "UTF-8"); } catch (IOException e) { throw new RuntimeException(e); } } public static String sendHttpRequest(String url, String method , Map<String, Object> params) { return sendHttpRequest(url, method, null, params); } public static String sendHttpRequest(String url, String method , Map<String, Object> headerMap, Map<String, Object> params) { try { StringBuffer stringBuffer = new StringBuffer(); for (String key : params.keySet()) { stringBuffer.append(key).append("=").append(URLEncoder.encode(params.get(key).toString(), "UTF-8")).append("&"); } if (method.equals("GET") && (params != null && params.size() > 0)) { url = url + "?" + stringBuffer.substring(0, stringBuffer.length() - 1); } HttpURLConnection connection = httpURLConnection(url, method); if (headerMap != null) { for (String headerName : headerMap.keySet()) { connection.setRequestProperty(headerName, headerMap.get(headerName).toString()); } } connection.connect(); if (method.equals("POST") && (params != null && params.size() > 0)) { OutputStream outputStream = connection.getOutputStream(); outputStream.write(stringBuffer.substring(0, stringBuffer.length() - 1).getBytes("UTF-8")); outputStream.flush(); } return new String(IOUtil.readStreamBytes(connection), "UTF-8"); } catch (IOException e) { throw new RuntimeException(e); } } public static String getVisitorIp(HttpServletRequest request) { String ipAddress = null; ipAddress = request.getHeader("x-forwarded-for"); if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getHeader("Proxy-Client-IP"); } if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getHeader("WL-Proxy-Client-IP"); } if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getRemoteAddr(); if (ipAddress.equals("127.0.0.1")) { // 根据网卡取本机配置的IP InetAddress inet = null; try { inet = InetAddress.getLocalHost(); } catch (UnknownHostException e) { e.printStackTrace(); } ipAddress = inet.getHostAddress(); } } // 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割 if (ipAddress != null && ipAddress.length() > 15) { if (ipAddress.indexOf(",") > 0) { ipAddress = ipAddress.substring(0, ipAddress.indexOf(",")); } } return ipAddress; } }
{ "content_hash": "e24e82c5fc17ed0f272613111e19a45f", "timestamp": "", "source": "github", "line_count": 107, "max_line_length": 126, "avg_line_length": 34.21495327102804, "alnum_prop": 0.6998087954110899, "repo_name": "xiaolongzuo/personal-blog-webapp", "id": "7813e015adbd3edddf8be372224be73dc8c88ed2", "size": "4371", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "personal-blog-webapp-common/src/main/java/com/zuoxiaolong/util/HttpUtil.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "686132" }, { "name": "FreeMarker", "bytes": "91244" }, { "name": "HTML", "bytes": "213" }, { "name": "Java", "bytes": "413217" }, { "name": "JavaScript", "bytes": "21386" }, { "name": "Less", "bytes": "5619" }, { "name": "Shell", "bytes": "5650" } ], "symlink_target": "" }
local common = require('test_scripts/WidgetSupport/common') --[[ Local Variables ]] local params = { displayLayout = "Layout1", dayColorScheme = { primaryColor = { red = 1, green = 2, blue = 3 } } } --[[ Local Functions ]] local function sendSetDisplayLayout_UNSUCCESS_noHMIResponse() local cid = common.getMobileSession():SendRPC("SetDisplayLayout", params) common.getHMIConnection():ExpectRequest("UI.Show") :Do(function() -- no response from HMI end) common.getMobileSession():ExpectResponse(cid, { success = false, resultCode = "GENERIC_ERROR" }) end local function sendSetDisplayLayout_UNSUCCESS_errorHMIResponse() local cid = common.getMobileSession():SendRPC("SetDisplayLayout", params) common.getHMIConnection():ExpectRequest("UI.Show") :Do(function(_, data) common.getHMIConnection():SendError(data.id, data.method, "TIMED_OUT", "Error code") end) common.getMobileSession():ExpectResponse(cid, { success = false, resultCode = "TIMED_OUT" }) end local function sendSetDisplayLayout_UNSUCCESS_invalidHMIResponse() local cid = common.getMobileSession():SendRPC("SetDisplayLayout", params) common.getHMIConnection():ExpectRequest("UI.Show") :Do(function(_, data) common.getHMIConnection():SendResponse(data.id, 123, "SUCCESS", {}) -- invalid method end) common.getMobileSession():ExpectResponse(cid, { success = false, resultCode = "GENERIC_ERROR" }) end --[[ Scenario ]] common.Step("Clean environment and Back-up/update PPT", common.precondition) common.Step("Start SDL, HMI, connect Mobile, start Session", common.start) common.Step("App registration", common.registerAppWOPTU) common.Title("Test") common.Step("App sends SetDisplayLayout no HMI response GENERIC_ERROR", sendSetDisplayLayout_UNSUCCESS_noHMIResponse) common.Step("App sends SetDisplayLayout error HMI response TIMED_OUT", sendSetDisplayLayout_UNSUCCESS_errorHMIResponse) common.Step("App sends SetDisplayLayout invalid HMI response GENERIC_ERROR", sendSetDisplayLayout_UNSUCCESS_invalidHMIResponse) common.Title("Postconditions") common.Step("Stop SDL, restore SDL settings and PPT", common.postcondition)
{ "content_hash": "df3560a7adbe4bfccc6147d6af07fb6e", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 98, "avg_line_length": 36.96610169491525, "alnum_prop": 0.7450710683172856, "repo_name": "smartdevicelink/sdl_atf_test_scripts", "id": "39d0192f2ee836e8081140018e02c285f212846e", "size": "3080", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test_scripts/WidgetSupport/Templates/SetDisplayLayout/003_SetDisplayLayout_unsuccessful_HMI_response.lua", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Lua", "bytes": "27589836" }, { "name": "Perl", "bytes": "2557" }, { "name": "Python", "bytes": "8898" }, { "name": "Shell", "bytes": "12889" } ], "symlink_target": "" }
import six from django.db import models, transaction from django.db.models import F, Max, Min from django.contrib.comments.models import Comment from django.contrib.contenttypes.models import ContentType from django.utils.safestring import mark_safe from django.utils.translation import ugettext, ugettext_lazy as _ from django_comments_xtd.conf import settings def max_thread_level_for_content_type(content_type): app_model = "%s.%s" % (content_type.app_label, content_type.model) if app_model in settings.COMMENTS_XTD_MAX_THREAD_LEVEL_BY_APP_MODEL: return settings.COMMENTS_XTD_MAX_THREAD_LEVEL_BY_APP_MODEL[app_model] else: return settings.COMMENTS_XTD_MAX_THREAD_LEVEL class MaxThreadLevelExceededException(Exception): def __init__(self, content_type=None): self.max_by_app = max_thread_level_for_content_type(content_type) def __str__(self): return ugettext("Can not post comments over the thread level %{max_thread_level}") % {"max_thread_level": self.max_by_app} class XtdCommentManager(models.Manager): def for_app_models(self, *args): """Return XtdComments for pairs "app.model" given in args""" content_types = [] for app_model in args: app, model = app_model.split(".") content_types.append(ContentType.objects.get(app_label=app, model=model)) return self.for_content_types(content_types) def for_content_types(self, content_types): qs = self.get_query_set().filter(content_type__in=content_types).reverse() return qs class XtdComment(Comment): thread_id = models.IntegerField(default=0, db_index=True) parent_id = models.IntegerField(default=0) level = models.SmallIntegerField(default=0) order = models.IntegerField(default=1, db_index=True) followup = models.BooleanField(help_text=_("Receive by email further comments in this conversation"), blank=True, default=False) objects = XtdCommentManager() class Meta: ordering = settings.COMMENTS_XTD_LIST_ORDER def save(self, *args, **kwargs): is_new = self.pk == None super(Comment, self).save(*args, **kwargs) if is_new: if not self.parent_id: self.parent_id = self.id self.thread_id = self.id else: if max_thread_level_for_content_type(self.content_type): with transaction.commit_on_success(): self._calculate_thread_data() else: raise MaxThreadLevelExceededException(self.content_type) kwargs["force_insert"] = False super(Comment, self).save(*args, **kwargs) def _calculate_thread_data(self): # Implements the following approach: # http://www.sqlteam.com/article/sql-for-threaded-discussion-forums parent = XtdComment.objects.get(pk=self.parent_id) if parent.level == max_thread_level_for_content_type(self.content_type): raise MaxThreadLevelExceededException(self.content_type) self.thread_id = parent.thread_id self.level = parent.level + 1 qc_eq_thread = XtdComment.objects.filter(thread_id = parent.thread_id) qc_ge_level = qc_eq_thread.filter(level__lte = parent.level, order__gt = parent.order) if qc_ge_level.count(): min_order = qc_ge_level.aggregate(Min('order'))['order__min'] XtdComment.objects.filter(thread_id = parent.thread_id, order__gte = min_order).update(order=F('order')+1) self.order = min_order else: max_order = qc_eq_thread.aggregate(Max('order'))['order__max'] self.order = max_order + 1 @models.permalink def get_reply_url(self): return ("comments-xtd-reply", None, {"cid": self.pk}) def allow_thread(self): if self.level < max_thread_level_for_content_type(self.content_type): return True else: return False class DummyDefaultManager: """ Dummy Manager to mock django's CommentForm.check_for_duplicate method. """ def __getattr__(self, name): return lambda *args, **kwargs: [] def using(self, *args, **kwargs): return self class TmpXtdComment(dict): """ Temporary XtdComment to be pickled, ziped and appended to a URL. """ _default_manager = DummyDefaultManager() def __getattr__(self, key): try: return self[key] except KeyError: return None def __setattr__(self, key, value): self[key] = value def save(self, *args, **kwargs): pass def _get_pk_val(self): if self.xtd_comment: return self.xtd_comment._get_pk_val() else: return "" def __reduce__(self): return (TmpXtdComment, (), None, None, six.iteritems(self))
{ "content_hash": "c7fabb4b897bce62584d22ece97bc949", "timestamp": "", "source": "github", "line_count": 137, "max_line_length": 132, "avg_line_length": 36.737226277372265, "alnum_prop": 0.6171269620504669, "repo_name": "CantemoInternal/django-comments-xtd", "id": "02ab19bf26c879ecfc5ea41cb55765cf6598cc3f", "size": "5033", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "django_comments_xtd/models.py", "mode": "33188", "license": "bsd-2-clause", "language": [], "symlink_target": "" }
package org.ta4j.core; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.List; /** * Base implementation of a {@link TimeSeries}. * <p> */ public class BaseTimeSeries implements TimeSeries { private static final long serialVersionUID = -1878027009398790126L; /** Name for unnamed series */ private static final String UNNAMED_SERIES_NAME = "unamed_series"; /** The logger */ private final Logger log = LoggerFactory.getLogger(getClass()); /** Name of the series */ private final String name; /** Begin index of the time series */ private int seriesBeginIndex = -1; /** End index of the time series */ private int seriesEndIndex = -1; /** List of ticks */ private final List<Tick> ticks; /** Maximum number of ticks for the time series */ private int maximumTickCount = Integer.MAX_VALUE; /** Number of removed ticks */ private int removedTicksCount = 0; /** True if the current series is constrained (i.e. its indexes cannot change), false otherwise */ private boolean constrained = false; /** * Constructor of an unnamed series. */ public BaseTimeSeries() { this(UNNAMED_SERIES_NAME); } /** * Constructor. * @param name the name of the series */ public BaseTimeSeries(String name) { this(name, new ArrayList<Tick>()); } /** * Constructor of an unnamed series. * @param ticks the list of ticks of the series */ public BaseTimeSeries(List<Tick> ticks) { this(UNNAMED_SERIES_NAME, ticks); } /** * Constructor. * @param name the name of the series * @param ticks the list of ticks of the series */ public BaseTimeSeries(String name, List<Tick> ticks) { this(name, ticks, 0, ticks.size() - 1, false); } /** * Constructor. * <p> * Constructs a constrained time series from an original one. * @param defaultSeries the original time series to construct a constrained series from * @param seriesBeginIndex the begin index (inclusive) of the time series * @param seriesEndIndex the end index (inclusive) of the time series */ public BaseTimeSeries(TimeSeries defaultSeries, int seriesBeginIndex, int seriesEndIndex) { this(defaultSeries.getName(), defaultSeries.getTickData(), seriesBeginIndex, seriesEndIndex, true); if (defaultSeries.getTickData() == null || defaultSeries.getTickData().isEmpty()) { throw new IllegalArgumentException("Cannot create a constrained series from a time series with a null/empty list of ticks"); } if (defaultSeries.getMaximumTickCount() != Integer.MAX_VALUE) { throw new IllegalStateException("Cannot create a constrained series from a time series for which a maximum tick count has been set"); } } /** * Constructor. * @param name the name of the series * @param ticks the list of ticks of the series * @param seriesBeginIndex the begin index (inclusive) of the time series * @param seriesEndIndex the end index (inclusive) of the time series * @param constrained true to constrain the time series (i.e. indexes cannot change), false otherwise */ private BaseTimeSeries(String name, List<Tick> ticks, int seriesBeginIndex, int seriesEndIndex, boolean constrained) { this.name = name; this.ticks = ticks == null ? new ArrayList<>() : ticks; if (ticks.isEmpty()) { // Tick list empty this.seriesBeginIndex = -1; this.seriesEndIndex = -1; this.constrained = false; return; } // Tick list not empty: checking indexes if (seriesEndIndex < seriesBeginIndex - 1) { throw new IllegalArgumentException("End index must be >= to begin index - 1"); } if (seriesEndIndex >= ticks.size()) { throw new IllegalArgumentException("End index must be < to the tick list size"); } this.seriesBeginIndex = seriesBeginIndex; this.seriesEndIndex = seriesEndIndex; this.constrained = constrained; } @Override public String getName() { return name; } @Override public Tick getTick(int i) { int innerIndex = i - removedTicksCount; if (innerIndex < 0) { if (i < 0) { // Cannot return the i-th tick if i < 0 throw new IndexOutOfBoundsException(buildOutOfBoundsMessage(this, i)); } log.trace("Time series `{}` ({} ticks): tick {} already removed, use {}-th instead", name, ticks.size(), i, removedTicksCount); if (ticks.isEmpty()) { throw new IndexOutOfBoundsException(buildOutOfBoundsMessage(this, removedTicksCount)); } innerIndex = 0; } else if (innerIndex >= ticks.size()) { // Cannot return the n-th tick if n >= ticks.size() throw new IndexOutOfBoundsException(buildOutOfBoundsMessage(this, i)); } return ticks.get(innerIndex); } @Override public int getTickCount() { if (seriesEndIndex < 0) { return 0; } final int startIndex = Math.max(removedTicksCount, seriesBeginIndex); return seriesEndIndex - startIndex + 1; } @Override public List<Tick> getTickData() { return ticks; } @Override public int getBeginIndex() { return seriesBeginIndex; } @Override public int getEndIndex() { return seriesEndIndex; } @Override public void setMaximumTickCount(int maximumTickCount) { if (constrained) { throw new IllegalStateException("Cannot set a maximum tick count on a constrained time series"); } if (maximumTickCount <= 0) { throw new IllegalArgumentException("Maximum tick count must be strictly positive"); } this.maximumTickCount = maximumTickCount; removeExceedingTicks(); } @Override public int getMaximumTickCount() { return maximumTickCount; } @Override public int getRemovedTicksCount() { return removedTicksCount; } @Override public void addTick(Tick tick) { if (tick == null) { throw new IllegalArgumentException("Cannot add null tick"); } if (!ticks.isEmpty()) { final int lastTickIndex = ticks.size() - 1; ZonedDateTime seriesEndTime = ticks.get(lastTickIndex).getEndTime(); if (!tick.getEndTime().isAfter(seriesEndTime)) { throw new IllegalArgumentException("Cannot add a tick with end time <= to series end time"); } } ticks.add(tick); if (seriesBeginIndex == -1) { // Begin index set to 0 only if if wasn't initialized seriesBeginIndex = 0; } seriesEndIndex++; removeExceedingTicks(); } /** * Removes the N first ticks which exceed the maximum tick count. */ private void removeExceedingTicks() { int tickCount = ticks.size(); if (tickCount > maximumTickCount) { // Removing old ticks int nbTicksToRemove = tickCount - maximumTickCount; for (int i = 0; i < nbTicksToRemove; i++) { ticks.remove(0); } // Updating removed ticks count removedTicksCount += nbTicksToRemove; } } /** * @param series a time series * @param index an out of bounds tick index * @return a message for an OutOfBoundsException */ private static String buildOutOfBoundsMessage(BaseTimeSeries series, int index) { return "Size of series: " + series.ticks.size() + " ticks, " + series.removedTicksCount + " ticks removed, index = " + index; } }
{ "content_hash": "b3bcdea02040960d9fefbd625938dd24", "timestamp": "", "source": "github", "line_count": 236, "max_line_length": 145, "avg_line_length": 33.97457627118644, "alnum_prop": 0.6172362185083562, "repo_name": "gcauchis/ta4j", "id": "4255401f5c74aad817b676deeb41f89ee26a4b27", "size": "9205", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ta4j-core/src/main/java/org/ta4j/core/BaseTimeSeries.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "1343531" } ], "symlink_target": "" }
import datetime from keystoneclient import access from keystoneclient.openstack.common import timeutils from keystoneclient.tests import client_fixtures as token_data from keystoneclient.tests.v2_0 import client_fixtures from keystoneclient.tests.v2_0 import utils UNSCOPED_TOKEN = client_fixtures.UNSCOPED_TOKEN PROJECT_SCOPED_TOKEN = client_fixtures.PROJECT_SCOPED_TOKEN DIABLO_TOKEN = token_data.TOKEN_RESPONSES[token_data.VALID_DIABLO_TOKEN] GRIZZLY_TOKEN = token_data.TOKEN_RESPONSES[token_data.SIGNED_TOKEN_SCOPED_KEY] class AccessInfoTest(utils.TestCase): def test_building_unscoped_accessinfo(self): auth_ref = access.AccessInfo.factory(body=UNSCOPED_TOKEN) self.assertTrue(auth_ref) self.assertIn('token', auth_ref) self.assertIn('serviceCatalog', auth_ref) self.assertFalse(auth_ref['serviceCatalog']) self.assertEqual(auth_ref.auth_token, '3e2813b7ba0b4006840c3825860b86ed') self.assertEqual(auth_ref.username, 'exampleuser') self.assertEqual(auth_ref.user_id, 'c4da488862bd435c9e6c0275a0d0e49a') self.assertEqual(auth_ref.tenant_name, None) self.assertEqual(auth_ref.tenant_id, None) self.assertEqual(auth_ref.auth_url, None) self.assertEqual(auth_ref.management_url, None) self.assertFalse(auth_ref.scoped) self.assertFalse(auth_ref.domain_scoped) self.assertFalse(auth_ref.project_scoped) self.assertFalse(auth_ref.trust_scoped) self.assertIsNone(auth_ref.project_domain_id) self.assertIsNone(auth_ref.project_domain_name) self.assertEqual(auth_ref.user_domain_id, 'default') self.assertEqual(auth_ref.user_domain_name, 'Default') self.assertEqual(auth_ref.expires, timeutils.parse_isotime( UNSCOPED_TOKEN['access']['token']['expires'])) def test_will_expire_soon(self): expires = timeutils.utcnow() + datetime.timedelta(minutes=5) UNSCOPED_TOKEN['access']['token']['expires'] = expires.isoformat() auth_ref = access.AccessInfo.factory(body=UNSCOPED_TOKEN) self.assertFalse(auth_ref.will_expire_soon(stale_duration=120)) self.assertTrue(auth_ref.will_expire_soon(stale_duration=300)) self.assertFalse(auth_ref.will_expire_soon()) def test_building_scoped_accessinfo(self): auth_ref = access.AccessInfo.factory(body=PROJECT_SCOPED_TOKEN) self.assertTrue(auth_ref) self.assertIn('token', auth_ref) self.assertIn('serviceCatalog', auth_ref) self.assertTrue(auth_ref['serviceCatalog']) self.assertEqual(auth_ref.auth_token, '04c7d5ffaeef485f9dc69c06db285bdb') self.assertEqual(auth_ref.username, 'exampleuser') self.assertEqual(auth_ref.user_id, 'c4da488862bd435c9e6c0275a0d0e49a') self.assertEqual(auth_ref.tenant_name, 'exampleproject') self.assertEqual(auth_ref.tenant_id, '225da22d3ce34b15877ea70b2a575f58') self.assertEqual(auth_ref.tenant_name, auth_ref.project_name) self.assertEqual(auth_ref.tenant_id, auth_ref.project_id) self.assertEqual(auth_ref.auth_url, ('http://public.com:5000/v2.0',)) self.assertEqual(auth_ref.management_url, ('http://admin:35357/v2.0',)) self.assertEqual(auth_ref.project_domain_id, 'default') self.assertEqual(auth_ref.project_domain_name, 'Default') self.assertEqual(auth_ref.user_domain_id, 'default') self.assertEqual(auth_ref.user_domain_name, 'Default') self.assertTrue(auth_ref.scoped) self.assertTrue(auth_ref.project_scoped) self.assertFalse(auth_ref.domain_scoped) def test_diablo_token(self): auth_ref = access.AccessInfo.factory(body=DIABLO_TOKEN) self.assertTrue(auth_ref) self.assertEqual(auth_ref.username, 'user_name1') self.assertEqual(auth_ref.project_id, 'tenant_id1') self.assertEqual(auth_ref.project_name, 'tenant_id1') self.assertEqual(auth_ref.project_domain_id, 'default') self.assertEqual(auth_ref.project_domain_name, 'Default') self.assertEqual(auth_ref.user_domain_id, 'default') self.assertEqual(auth_ref.user_domain_name, 'Default') self.assertFalse(auth_ref.scoped) def test_grizzly_token(self): auth_ref = access.AccessInfo.factory(body=GRIZZLY_TOKEN) self.assertEqual(auth_ref.project_id, 'tenant_id1') self.assertEqual(auth_ref.project_name, 'tenant_name1') self.assertEqual(auth_ref.project_domain_id, 'default') self.assertEqual(auth_ref.project_domain_name, 'Default') self.assertEqual(auth_ref.user_domain_id, 'default') self.assertEqual(auth_ref.user_domain_name, 'Default')
{ "content_hash": "16612d4d23fa842051d428b6b62ed8b6", "timestamp": "", "source": "github", "line_count": 109, "max_line_length": 79, "avg_line_length": 44.26605504587156, "alnum_prop": 0.6905699481865285, "repo_name": "ntt-sic/python-keystoneclient", "id": "e097120e8220b1ccb5ecf52fb80c9505d90ef1de", "size": "5443", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "keystoneclient/tests/v2_0/test_access.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "16002" }, { "name": "JavaScript", "bytes": "7403" }, { "name": "Python", "bytes": "661153" }, { "name": "Shell", "bytes": "11342" } ], "symlink_target": "" }
// BLASTX IMPLEMENTIERUNG VON ANNKATRIN BRESSIN UND MARJAN FAIZI // SOFTWAREPROJEKT VOM 2.4. - 29.5.2012 // VERSION VOM 21.APRIL.2013 #include "own_functions.h" // int find_matches(StrSetSA & trans_proteine,StrSetSA & trans_reads,int seed,Match_found seed_found){ Index <StrSetSA> index_trans_proteine(trans_proteine); Finder <Index<StrSetSA>> finder_in_proteine(index_trans_proteine); // Fuer jedes Reads for (int read=0;read<length(trans_reads);++read){ for (int begin=0;begin+seed<=length(trans_reads[read]);begin+=seed){ cout <<"infix "<<infix(trans_reads[read],begin,begin+seed)<<"\t"<<begin<<"\t"<<begin+seed<<endl; while(find(finder_in_proteine,infix(trans_reads[read],begin,begin+seed))){ Position<StrSetSA>::Type beginPosition(finder_in_proteine); cout <<"["<<beginPosition(finder_in_proteine)<<";"<<endPosition(finder_in_proteine)<<")\t"<< infix(finder_in_proteine)<<endl; } clear(finder_in_proteine); } } return 0; } // int FIND_MATCHES_FOR_ALL(StringSet<String<Dna5>> & Reads,StringSet<String<char> > & ReadID,StrSetSA & Proteine, StringSet<String<char> > & ProteinID, int seed,StrSetSA & Alphabete){ // Schleife fuer jedes Alphabet for(int alp=0;alp<length(Alphabete);++alp){ StrSetSA trans_reads; // alle Reads werden uebersetzt und in trans_reads gespeichert if (get_translate_for_all(Reads,trans_reads,Alphabete[alp])==1) return 1; // Ausgabe der Reads for (int p=0;p<length(trans_reads);p++) cout <<trans_reads[p]<<endl; cout <<endl; StrSetSA trans_proteine; // alle Proteine der Datenbank werden uebersetzt und in trans_proteine gespeichert if (translate_datenbank(trans_proteine,Proteine,Alphabete[alp])) return 1; // Ausgabe der Proteine for (int p=0;p<length(trans_proteine);p++) cout << trans_proteine[p]<<endl; cout <<endl; Match_found seed_found; if (find_matches(trans_proteine,trans_reads,seed,seed_found)==1) return 1; /* Index <StrSetSA> index_trans_proteine(trans_proteine); Index <StrSetSA> index_trans_reads(x); Finder <Index<StrSetSA>,Backtracking<HammingDistance> > finder_obj(index_trans_proteine); Pattern <Index<StrSetSA>,Backtracking<HammingDistance> > pattern_obj(index_trans_reads,length(x)); while(find(finder_obj,pattern_obj,0)){ cout <<"["<<beginPosition(finder_obj)<<";"<<endPosition(finder_obj)<<")\t"<<infix(finder_obj)<<endl; } */ } }
{ "content_hash": "643cc7b377f0a1e3232c593a993926e4", "timestamp": "", "source": "github", "line_count": 71, "max_line_length": 111, "avg_line_length": 34.985915492957744, "alnum_prop": 0.67914653784219, "repo_name": "bkahlert/seqan-research", "id": "afde60382cd83974e72524152519ebf2f23a8b47", "size": "2484", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "raw/pmsb13/pmsb13-data-20130530/sources/fjt74l9mlcqisdus/2013-05-03T20-45-25.881+0200/sandbox/my_sandbox/apps/blastX/finder.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "39014" }, { "name": "Awk", "bytes": "44044" }, { "name": "Batchfile", "bytes": "37736" }, { "name": "C", "bytes": "1261223" }, { "name": "C++", "bytes": "277576131" }, { "name": "CMake", "bytes": "5546616" }, { "name": "CSS", "bytes": "271972" }, { "name": "GLSL", "bytes": "2280" }, { "name": "Groff", "bytes": "2694006" }, { "name": "HTML", "bytes": "15207297" }, { "name": "JavaScript", "bytes": "362928" }, { "name": "LSL", "bytes": "22561" }, { "name": "Makefile", "bytes": "6418610" }, { "name": "Objective-C", "bytes": "3730085" }, { "name": "PHP", "bytes": "3302" }, { "name": "Perl", "bytes": "10468" }, { "name": "PostScript", "bytes": "22762" }, { "name": "Python", "bytes": "9267035" }, { "name": "R", "bytes": "230698" }, { "name": "Rebol", "bytes": "283" }, { "name": "Shell", "bytes": "437340" }, { "name": "Tcl", "bytes": "15439" }, { "name": "TeX", "bytes": "738415" }, { "name": "VimL", "bytes": "12685" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!-- generator="wordpress/2.2.1" --> <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" > <channel> <title>enthought blog</title> <link>http://blog.enthought.com</link> <description>News and information about Enthought, Inc. and Enthought's open source software.</description> <pubDate>Fri, 30 May 2008 19:07:00 +0000</pubDate> <generator>http://wordpress.org/?v=2.2.1</generator> <language>en</language> <item> <title>Traits for doing Reactive Programming</title> <link>http://blog.enthought.com/?p=33</link> <comments>http://blog.enthought.com/?p=33#comments</comments> <pubDate>Fri, 30 May 2008 19:07:00 +0000</pubDate> <dc:creator>judah</dc:creator> <category><![CDATA[Traits]]></category> <guid isPermaLink="false">http://blog.enthought.com/?p=33</guid> <description><![CDATA[I have done event-driven programming. I have done structured programming. I&#8217;ve done OOD that was exceeded only by the Platonic Ideal. I&#8217;ve done spaghetti code that would make an Italian chef proud. But I&#8217;ve never, until coming to Enthought, done Reactive Programming. Enthought&#8217;s Traits module leads to doing a different kind of [...]]]></description> <wfw:commentRss>http://blog.enthought.com/?feed=rss2&amp;p=33</wfw:commentRss> </item> <item> <title>Project Estimation Guidelines</title> <link>http://blog.enthought.com/?p=32</link> <comments>http://blog.enthought.com/?p=32#comments</comments> <pubDate>Mon, 19 May 2008 20:24:10 +0000</pubDate> <dc:creator>judah</dc:creator> <category><![CDATA[Open source software]]></category> <category><![CDATA[Python]]></category> <guid isPermaLink="false">http://blog.enthought.com/?p=32</guid> <description><![CDATA[When preparing to embark on a new project it is useful to establish a proper expectation on cost, time, and quality of the project. So here are a few things that you should think about and document as part of your planning process, Project scope statement: What exactly will the project accomplish? Project management plan: [...]]]></description> <wfw:commentRss>http://blog.enthought.com/?feed=rss2&amp;p=32</wfw:commentRss> </item> <item> <title>Greg Wilson speaking at the Austin Python User Group meeting</title> <link>http://blog.enthought.com/?p=31</link> <comments>http://blog.enthought.com/?p=31#comments</comments> <pubDate>Tue, 13 May 2008 03:30:02 +0000</pubDate> <dc:creator>travis</dc:creator> <category><![CDATA[News]]></category> <category><![CDATA[Python]]></category> <category><![CDATA[General]]></category> <guid isPermaLink="false">http://blog.enthought.com/?p=31</guid> <description><![CDATA[Wednesday, May 14th, Greg Wilson will be joining us in Austin for the monthly APUG meeting.  He&#8217;ll be talking about Beautiful Code.  If you&#8217;re in the area, swing by Enthought&#8217;s Offices right downtown at the corner of 6th and Congress (the Epicenter for Weirdness, as we like to call it). There&#8217;s more information at the python.org [...]]]></description> <wfw:commentRss>http://blog.enthought.com/?feed=rss2&amp;p=31</wfw:commentRss> </item> <item> <title>Facelift for code.enthought.com: of Commodities, Communities and Mullets</title> <link>http://blog.enthought.com/?p=30</link> <comments>http://blog.enthought.com/?p=30#comments</comments> <pubDate>Fri, 02 May 2008 19:26:57 +0000</pubDate> <dc:creator>travis</dc:creator> <category><![CDATA[News]]></category> <category><![CDATA[Enthought Tool Suite]]></category> <category><![CDATA[Open source software]]></category> <category><![CDATA[Python]]></category> <category><![CDATA[General]]></category> <guid isPermaLink="false">http://blog.enthought.com/?p=30</guid> <description><![CDATA[We&#8217;ve recently refreshed the look and content of our code.enthought.com site, so I thought I&#8217;d provide my thoughts about what the site is about and what it means to Enthought (and the world). I&#8217;ll apologize in advance for rambling. For several years Enthought has hosted code.enthought.com as a site for the Open Source tools that we&#8217;ve [...]]]></description> <wfw:commentRss>http://blog.enthought.com/?feed=rss2&amp;p=30</wfw:commentRss> </item> <item> <title>Python for Scientific Computing - Training Course</title> <link>http://blog.enthought.com/?p=29</link> <comments>http://blog.enthought.com/?p=29#comments</comments> <pubDate>Mon, 28 Apr 2008 17:59:37 +0000</pubDate> <dc:creator>travis</dc:creator> <category><![CDATA[News]]></category> <guid isPermaLink="false">http://blog.enthought.com/?p=29</guid> <description><![CDATA[ Enthought is offering an open training course for Scientific Computing with Python at its Austin, TX offices. Space is limited. We&#8217;ll accept the first 15 people who register. Date: June 23-27, 2008 Location: Austin, Texas, at Enthought&#8217;s offices Cost: 3 days: $1500; 5 days: $2500. You can attend either the [...]]]></description> <wfw:commentRss>http://blog.enthought.com/?feed=rss2&amp;p=29</wfw:commentRss> </item> <item> <title>EPD - The Kitchen-Sink-Included Python Distribution</title> <link>http://blog.enthought.com/?p=28</link> <comments>http://blog.enthought.com/?p=28#comments</comments> <pubDate>Tue, 22 Apr 2008 23:09:37 +0000</pubDate> <dc:creator>travis</dc:creator> <category><![CDATA[News]]></category> <category><![CDATA[Enthought Tool Suite]]></category> <category><![CDATA[Open source software]]></category> <category><![CDATA[Python]]></category> <category><![CDATA[General]]></category> <guid isPermaLink="false">http://blog.enthought.com/?p=28</guid> <description><![CDATA[The team here at Enthought has just released the Enthought Python Distribution (EPD): EPD is a Distribution of the Python Programming Language (currently version 2.5.2) that includes over 60 additional libraries. A short list includes (note, this is a partial list): Package Description Version Python Core Python 2.5.2 NumPy Multidimensional arrays and fast numerics for Python 1.0.4 SciPy Scientific Library for Python 0.6.0 Enthought Tool Suite (ETS) A suite [...]]]></description> <wfw:commentRss>http://blog.enthought.com/?feed=rss2&amp;p=28</wfw:commentRss> </item> <item> <title>PointIR - Multitouch with Python (PyCon 2008)</title> <link>http://blog.enthought.com/?p=27</link> <comments>http://blog.enthought.com/?p=27#comments</comments> <pubDate>Thu, 03 Apr 2008 20:38:57 +0000</pubDate> <dc:creator>travis</dc:creator> <category><![CDATA[Conferences]]></category> <category><![CDATA[Kiva]]></category> <category><![CDATA[Enable]]></category> <category><![CDATA[Mayavi2]]></category> <category><![CDATA[Chaco]]></category> <category><![CDATA[Open source software]]></category> <category><![CDATA[News]]></category> <category><![CDATA[Python]]></category> <guid isPermaLink="false">http://blog.enthought.com/?p=27</guid> <description><![CDATA[I’ve just uploaded a video from Peter’s presentation about the multitouch prototype that he and Dave Kammeyer and Robert Kern have developed over the past few months. It not only showcases what a few brilliant guys can pull off in their spare time, it shows the power of the open source tool stack that [...]]]></description> <wfw:commentRss>http://blog.enthought.com/?feed=rss2&amp;p=27</wfw:commentRss> <enclosure url="http://www.enthought.com/img/pycon_pointir_med.mp4" length="80157958" type="video/mp4" /> </item> <item> <title>A stroll through Kiva, Enable, and Chaco</title> <link>http://blog.enthought.com/?p=26</link> <comments>http://blog.enthought.com/?p=26#comments</comments> <pubDate>Tue, 18 Mar 2008 06:54:33 +0000</pubDate> <dc:creator>pwang</dc:creator> <category><![CDATA[Enable]]></category> <category><![CDATA[Kiva]]></category> <category><![CDATA[Chaco]]></category> <category><![CDATA[Open source software]]></category> <category><![CDATA[Python]]></category> <guid isPermaLink="false">http://blog.enthought.com/?p=26</guid> <description><![CDATA[In the past I&#8217;ve put off writing documentation for Chaco and Enable because every time I had faced the task, it seemed so daunting: there are over a hundred classes, a dozen different patterns and conventions, and so many areas for improvement and exploration. It frequently felt much easier just to work on code. But I [...]]]></description> <wfw:commentRss>http://blog.enthought.com/?feed=rss2&amp;p=26</wfw:commentRss> </item> <item> <title>PyCon 2008: Tutorials and Day 1</title> <link>http://blog.enthought.com/?p=25</link> <comments>http://blog.enthought.com/?p=25#comments</comments> <pubDate>Sat, 15 Mar 2008 05:22:00 +0000</pubDate> <dc:creator>oliphant</dc:creator> <category><![CDATA[Conferences]]></category> <category><![CDATA[Open source software]]></category> <category><![CDATA[Python]]></category> <guid isPermaLink="false">http://blog.enthought.com/?p=25</guid> <description><![CDATA[I&#8217;m having a great time at PyCon. Tutorial day was wonderful. It was so exciting to be in a room full of people who were interested in the more advanced features of NumPy. The array object in NumPy is a well-developed abstraction that can be used for manipulating data in addition [...]]]></description> <wfw:commentRss>http://blog.enthought.com/?feed=rss2&amp;p=25</wfw:commentRss> </item> <item> <title>PyCon 2008 Chicago</title> <link>http://blog.enthought.com/?p=24</link> <comments>http://blog.enthought.com/?p=24#comments</comments> <pubDate>Thu, 13 Mar 2008 01:54:53 +0000</pubDate> <dc:creator>travis</dc:creator> <category><![CDATA[Conferences]]></category> <guid isPermaLink="false">http://blog.enthought.com/?p=24</guid> <description><![CDATA[ We just arrived in Chicago to be met with a bus-full of PyCon folks&#8211;very cool. For those of you that can make it, come by the Enthought Booth and ask about the EPD pre-release CD for Windows. Also, get your hands all over the multitouch prototype we put together. ]]></description> <wfw:commentRss>http://blog.enthought.com/?feed=rss2&amp;p=24</wfw:commentRss> </item> </channel> </rss>
{ "content_hash": "627a47b467750c21be1fbe3439893b8f", "timestamp": "", "source": "github", "line_count": 236, "max_line_length": 350, "avg_line_length": 44.182203389830505, "alnum_prop": 0.7138198906684569, "repo_name": "bbc/kamaelia", "id": "bf090ca9bd33487062600b9c5366825b4d0c58f8", "size": "10433", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "Sketches/PO/KamPlanet/feeds/feed28.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "62985" }, { "name": "C", "bytes": "212854" }, { "name": "C++", "bytes": "327546" }, { "name": "CSS", "bytes": "114434" }, { "name": "ChucK", "bytes": "422" }, { "name": "Diff", "bytes": "483" }, { "name": "Gettext Catalog", "bytes": "3919909" }, { "name": "HTML", "bytes": "1288960" }, { "name": "Java", "bytes": "31832" }, { "name": "JavaScript", "bytes": "829491" }, { "name": "Makefile", "bytes": "5768" }, { "name": "NSIS", "bytes": "18867" }, { "name": "PHP", "bytes": "49059" }, { "name": "Perl", "bytes": "31234" }, { "name": "Processing", "bytes": "2885" }, { "name": "Pure Data", "bytes": "7485482" }, { "name": "Python", "bytes": "18896320" }, { "name": "Ruby", "bytes": "4165" }, { "name": "Shell", "bytes": "711244" } ], "symlink_target": "" }
Sistema de distribuição de disciplinas - UFG # Instalação ### 1. Baixar o [composer](https://getcomposer.org/doc/00-intro.md) `curl -sS https://getcomposer.org/installer | php` OU `php -r "readfile('https://getcomposer.org/installer');" | php` ### 2. Instalação das dependências via composer: `mv composer.phar src/` `cd src/` `php composer.phar install` # Executando o projeto `cd src/` `./bin/cake server` Isto irá iniciar o servidor web em http://localhost:8765/. Caso você deseje muder a porta ou o host do servidor basta utilizar os parâmetros -H e -p: Ex: `./bin/cake server -H 192.168.13.37 -p 5673`
{ "content_hash": "52f146886d97398a035469cb17af2a68", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 149, "avg_line_length": 21.413793103448278, "alnum_prop": 0.7069243156199678, "repo_name": "BrunoSoares-LABORA/sdd-ufg", "id": "02e2857020dd99fc06effae39c0512674002aa49", "size": "641", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "270" }, { "name": "Batchfile", "bytes": "937" }, { "name": "CSS", "bytes": "9282" }, { "name": "PHP", "bytes": "63644" }, { "name": "Shell", "bytes": "1354" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading.Tasks; namespace Joy.Storage { public interface ISaveAdapter { LoadResult Load(string input = null); void Process(EntityGroups pool); void Process(EntityGroup group); void Process(Entity entity); void DropEntityGroup(EntityGroup group); void Clear(); } }
{ "content_hash": "1075a782f2017626d57cecce6a807145", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 52, "avg_line_length": 25.05263157894737, "alnum_prop": 0.7100840336134454, "repo_name": "mind0n/hive", "id": "f4499d9c45adefd7fce94ab945480a759521a5e3", "size": "478", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Product/Website/Portal/Joy.Storage/ISaveAdapter.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "670329" }, { "name": "ActionScript", "bytes": "7830" }, { "name": "ApacheConf", "bytes": "47" }, { "name": "Batchfile", "bytes": "18096" }, { "name": "C", "bytes": "19746409" }, { "name": "C#", "bytes": "258148996" }, { "name": "C++", "bytes": "48534520" }, { "name": "CSS", "bytes": "933736" }, { "name": "ColdFusion", "bytes": "10780" }, { "name": "GLSL", "bytes": "3935" }, { "name": "HTML", "bytes": "4631854" }, { "name": "Java", "bytes": "10881" }, { "name": "JavaScript", "bytes": "10250558" }, { "name": "Logos", "bytes": "1526844" }, { "name": "MAXScript", "bytes": "18182" }, { "name": "Mathematica", "bytes": "1166912" }, { "name": "Objective-C", "bytes": "2937200" }, { "name": "PHP", "bytes": "81898" }, { "name": "Perl", "bytes": "9496" }, { "name": "PowerShell", "bytes": "44339" }, { "name": "Python", "bytes": "188058" }, { "name": "Shell", "bytes": "758" }, { "name": "Smalltalk", "bytes": "5818" }, { "name": "TypeScript", "bytes": "50090" } ], "symlink_target": "" }
package org.mockitousage.bugs.creation.api; import org.mockitousage.bugs.creation.otherpackage.PublicParentClass; public class PublicClass extends PublicParentClass {}
{ "content_hash": "8ae4b8669882f55db5e78c829f3e11af", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 69, "avg_line_length": 28.5, "alnum_prop": 0.847953216374269, "repo_name": "bric3/mockito", "id": "048208c627dd8b2b4cf285701059a145311bc74c", "size": "290", "binary": false, "copies": "4", "ref": "refs/heads/main", "path": "src/test/java/org/mockitousage/bugs/creation/api/PublicClass.java", "mode": "33188", "license": "mit", "language": [ { "name": "Groovy", "bytes": "1029" }, { "name": "Java", "bytes": "3197410" }, { "name": "Kotlin", "bytes": "33548" }, { "name": "Shell", "bytes": "567" }, { "name": "XSLT", "bytes": "7593" } ], "symlink_target": "" }
import { ContentProjectionPage } from './app.po'; describe('content-projection App', () => { let page: ContentProjectionPage; beforeEach(() => { page = new ContentProjectionPage(); }); it('should display welcome message', () => { page.navigateTo(); expect(page.getParagraphText()).toEqual('Welcome to app!'); }); });
{ "content_hash": "368117adc61c372fdca9e8ba56e783f6", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 63, "avg_line_length": 25.428571428571427, "alnum_prop": 0.6123595505617978, "repo_name": "TelerikAcademy/Angular", "id": "af16285decc69ffb6e2cc50778a1c542aff290e0", "size": "356", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "Topics/03. Components/demos/content-projection/e2e/app.e2e-spec.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "4521" }, { "name": "HTML", "bytes": "75054" }, { "name": "JavaScript", "bytes": "49643" }, { "name": "TypeScript", "bytes": "187714" } ], "symlink_target": "" }
local spec = require 'spec.spec' describe("Add keys", function() it("adds a header", function() local add = spec.middleware('add-keys/add_keys.lua') local request = spec.request({ method = 'GET', uri = '/'}) local next_middleware = spec.next_middleware(function() assert.contains(request, { method = 'GET', uri = '/', headers = { authentication = 'this-is-my-key'} }) return {status = 200, body = 'ok'} end) local response = add(request, next_middleware) assert.spy(next_middleware).was_called() assert.contains(response, {status = 200, body = 'ok'}) end) end)
{ "content_hash": "aa42faa7e8045fafd1cd701fdee1d153", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 70, "avg_line_length": 31.333333333333332, "alnum_prop": 0.5896656534954408, "repo_name": "APItools/middleware", "id": "f44589eb04cd6bcaf6d1052d6ba4ffb4034dbbb1", "size": "658", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "middleware/add-keys/add_keys_spec.lua", "mode": "33188", "license": "mit", "language": [ { "name": "Lua", "bytes": "91658" }, { "name": "Makefile", "bytes": "2094" }, { "name": "Ruby", "bytes": "4143" } ], "symlink_target": "" }
package fromwsdl.client_from_sei.client; import junit.framework.TestCase; import jakarta.xml.ws.Service; import java.net.URL; import javax.xml.namespace.QName; /** * Creating proxy from a SEI * * @author Jitendra Kotamraju */ public class SEITest extends TestCase { public SEITest(String name) throws Exception{ super(name); } public void testHello() throws Exception { URL wsdl = new Hello_Service().getWSDLDocumentLocation(); QName sname = new QName("urn:test", "Hello"); QName pname = new QName("urn:test", "HelloPort"); Service service = Service.create(wsdl, sname); MyHello proxy = service.getPort(pname, MyHello.class); testProxy(proxy); } public void testHello1() throws Exception {; Service service = new Hello_Service(); MyHello proxy = service.getPort(MyHello.class); testProxy(proxy); } public void testHello2() throws Exception { QName pname = new QName("urn:test", "HelloPort"); Service service = new Hello_Service(); MyHello proxy = service.getPort(pname, MyHello.class); testProxy(proxy); } private void testProxy(MyHello proxy) { MyHello_Type req = new MyHello_Type(); req.setArgument("arg"); req.setExtra("extra"); MyHelloResponse resp = proxy.hello(req); assertEquals("result", resp.getResult()); } }
{ "content_hash": "4fe0558ceaa5b331cfdd4c7738562abe", "timestamp": "", "source": "github", "line_count": 56, "max_line_length": 65, "avg_line_length": 25.571428571428573, "alnum_prop": 0.6410614525139665, "repo_name": "eclipse-ee4j/metro-jax-ws", "id": "3823250438cf3ad45b664472694335bd472802de", "size": "1768", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "jaxws-ri/tests/unit/testcases/fromwsdl/client_from_sei/client/SEITest.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "2375" }, { "name": "CSS", "bytes": "6017" }, { "name": "Groovy", "bytes": "2488" }, { "name": "HTML", "bytes": "89895" }, { "name": "Java", "bytes": "12221309" }, { "name": "Shell", "bytes": "32701" }, { "name": "XSLT", "bytes": "8914" } ], "symlink_target": "" }
import DS from 'ember-data'; import AjaxServiceSupport from 'ember-ajax/mixins/ajax-support'; const { JSONAPIAdapter } = DS; export default JSONAPIAdapter.extend(AjaxServiceSupport, { namespace: 'api', ajaxOptions() { const hash = this._super(...arguments); hash.headers = { 'X-Silly-Option': 'Hi!' }; return hash; } });
{ "content_hash": "c7bbbed7155296da6c1196c832cb495d", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 64, "avg_line_length": 19.666666666666668, "alnum_prop": 0.655367231638418, "repo_name": "ember-cli/ember-ajax", "id": "38781a9c389980937e678a19508c3140ab294eea", "size": "354", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/dummy/app/adapters/application.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "1729" }, { "name": "Handlebars", "bytes": "681" }, { "name": "JavaScript", "bytes": "78602" }, { "name": "TypeScript", "bytes": "38182" } ], "symlink_target": "" }