hexsha
stringlengths 40
40
| size
int64 1
1.03M
| ext
stringclasses 10
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 3
239
| max_stars_repo_name
stringlengths 5
130
| max_stars_repo_head_hexsha
stringlengths 40
78
| max_stars_repo_licenses
listlengths 1
10
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 3
239
| max_issues_repo_name
stringlengths 5
130
| max_issues_repo_head_hexsha
stringlengths 40
78
| max_issues_repo_licenses
listlengths 1
10
| max_issues_count
int64 1
67k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 3
239
| max_forks_repo_name
stringlengths 5
130
| max_forks_repo_head_hexsha
stringlengths 40
78
| max_forks_repo_licenses
listlengths 1
10
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 1
1.03M
| avg_line_length
float64 1
958k
| max_line_length
int64 1
1.03M
| alphanum_fraction
float64 0
1
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4a0b6b45f4a6883fea068dcd1e7fc20d152be13e
| 37,474
|
py
|
Python
|
django/test/client.py
|
martinsvoboda/django
|
c51bf80d56cbcdbec1b243b8db086f35b4598947
|
[
"CNRI-Python-GPL-Compatible",
"BSD-3-Clause"
] | 4
|
2021-07-02T08:22:36.000Z
|
2021-07-05T20:31:51.000Z
|
django/test/client.py
|
FutureSenzhong/django
|
1bbb98d9a4b7d83e422b14ae2429cb368eff5a13
|
[
"CNRI-Python-GPL-Compatible",
"BSD-3-Clause"
] | null | null | null |
django/test/client.py
|
FutureSenzhong/django
|
1bbb98d9a4b7d83e422b14ae2429cb368eff5a13
|
[
"CNRI-Python-GPL-Compatible",
"BSD-3-Clause"
] | null | null | null |
import json
import mimetypes
import os
import sys
from copy import copy
from functools import partial
from http import HTTPStatus
from importlib import import_module
from io import BytesIO
from urllib.parse import unquote_to_bytes, urljoin, urlparse, urlsplit
from asgiref.sync import sync_to_async
from django.conf import settings
from django.core.handlers.asgi import ASGIRequest
from django.core.handlers.base import BaseHandler
from django.core.handlers.wsgi import WSGIRequest
from django.core.serializers.json import DjangoJSONEncoder
from django.core.signals import (
got_request_exception, request_finished, request_started,
)
from django.db import close_old_connections
from django.http import HttpRequest, QueryDict, SimpleCookie
from django.test import signals
from django.test.utils import ContextList
from django.urls import resolve
from django.utils.encoding import force_bytes
from django.utils.functional import SimpleLazyObject
from django.utils.http import urlencode
from django.utils.itercompat import is_iterable
from django.utils.regex_helper import _lazy_re_compile
__all__ = (
'AsyncClient', 'AsyncRequestFactory', 'Client', 'RedirectCycleError',
'RequestFactory', 'encode_file', 'encode_multipart',
)
BOUNDARY = 'BoUnDaRyStRiNg'
MULTIPART_CONTENT = 'multipart/form-data; boundary=%s' % BOUNDARY
CONTENT_TYPE_RE = _lazy_re_compile(r'.*; charset=([\w\d-]+);?')
# Structured suffix spec: https://tools.ietf.org/html/rfc6838#section-4.2.8
JSON_CONTENT_TYPE_RE = _lazy_re_compile(r'^application\/(.+\+)?json')
class RedirectCycleError(Exception):
"""The test client has been asked to follow a redirect loop."""
def __init__(self, message, last_response):
super().__init__(message)
self.last_response = last_response
self.redirect_chain = last_response.redirect_chain
class FakePayload:
"""
A wrapper around BytesIO that restricts what can be read since data from
the network can't be sought and cannot be read outside of its content
length. This makes sure that views can't do anything under the test client
that wouldn't work in real life.
"""
def __init__(self, content=None):
self.__content = BytesIO()
self.__len = 0
self.read_started = False
if content is not None:
self.write(content)
def __len__(self):
return self.__len
def read(self, num_bytes=None):
if not self.read_started:
self.__content.seek(0)
self.read_started = True
if num_bytes is None:
num_bytes = self.__len or 0
assert self.__len >= num_bytes, "Cannot read more than the available bytes from the HTTP incoming data."
content = self.__content.read(num_bytes)
self.__len -= num_bytes
return content
def write(self, content):
if self.read_started:
raise ValueError("Unable to write a payload after it's been read")
content = force_bytes(content)
self.__content.write(content)
self.__len += len(content)
def closing_iterator_wrapper(iterable, close):
try:
yield from iterable
finally:
request_finished.disconnect(close_old_connections)
close() # will fire request_finished
request_finished.connect(close_old_connections)
def conditional_content_removal(request, response):
"""
Simulate the behavior of most Web servers by removing the content of
responses for HEAD requests, 1xx, 204, and 304 responses. Ensure
compliance with RFC 7230, section 3.3.3.
"""
if 100 <= response.status_code < 200 or response.status_code in (204, 304):
if response.streaming:
response.streaming_content = []
else:
response.content = b''
if request.method == 'HEAD':
if response.streaming:
response.streaming_content = []
else:
response.content = b''
return response
class ClientHandler(BaseHandler):
"""
A HTTP Handler that can be used for testing purposes. Use the WSGI
interface to compose requests, but return the raw HttpResponse object with
the originating WSGIRequest attached to its ``wsgi_request`` attribute.
"""
def __init__(self, enforce_csrf_checks=True, *args, **kwargs):
self.enforce_csrf_checks = enforce_csrf_checks
super().__init__(*args, **kwargs)
def __call__(self, environ):
# Set up middleware if needed. We couldn't do this earlier, because
# settings weren't available.
if self._middleware_chain is None:
self.load_middleware()
request_started.disconnect(close_old_connections)
request_started.send(sender=self.__class__, environ=environ)
request_started.connect(close_old_connections)
request = WSGIRequest(environ)
# sneaky little hack so that we can easily get round
# CsrfViewMiddleware. This makes life easier, and is probably
# required for backwards compatibility with external tests against
# admin views.
request._dont_enforce_csrf_checks = not self.enforce_csrf_checks
# Request goes through middleware.
response = self.get_response(request)
# Simulate behaviors of most Web servers.
conditional_content_removal(request, response)
# Attach the originating request to the response so that it could be
# later retrieved.
response.wsgi_request = request
# Emulate a WSGI server by calling the close method on completion.
if response.streaming:
response.streaming_content = closing_iterator_wrapper(
response.streaming_content, response.close)
else:
request_finished.disconnect(close_old_connections)
response.close() # will fire request_finished
request_finished.connect(close_old_connections)
return response
class AsyncClientHandler(BaseHandler):
"""An async version of ClientHandler."""
def __init__(self, enforce_csrf_checks=True, *args, **kwargs):
self.enforce_csrf_checks = enforce_csrf_checks
super().__init__(*args, **kwargs)
async def __call__(self, scope):
# Set up middleware if needed. We couldn't do this earlier, because
# settings weren't available.
if self._middleware_chain is None:
self.load_middleware(is_async=True)
# Extract body file from the scope, if provided.
if '_body_file' in scope:
body_file = scope.pop('_body_file')
else:
body_file = FakePayload('')
request_started.disconnect(close_old_connections)
await sync_to_async(request_started.send, thread_sensitive=False)(sender=self.__class__, scope=scope)
request_started.connect(close_old_connections)
request = ASGIRequest(scope, body_file)
# Sneaky little hack so that we can easily get round
# CsrfViewMiddleware. This makes life easier, and is probably required
# for backwards compatibility with external tests against admin views.
request._dont_enforce_csrf_checks = not self.enforce_csrf_checks
# Request goes through middleware.
response = await self.get_response_async(request)
# Simulate behaviors of most Web servers.
conditional_content_removal(request, response)
# Attach the originating ASGI request to the response so that it could
# be later retrieved.
response.asgi_request = request
# Emulate a server by calling the close method on completion.
if response.streaming:
response.streaming_content = await sync_to_async(closing_iterator_wrapper, thread_sensitive=False)(
response.streaming_content,
response.close,
)
else:
request_finished.disconnect(close_old_connections)
# Will fire request_finished.
await sync_to_async(response.close, thread_sensitive=False)()
request_finished.connect(close_old_connections)
return response
def store_rendered_templates(store, signal, sender, template, context, **kwargs):
"""
Store templates and contexts that are rendered.
The context is copied so that it is an accurate representation at the time
of rendering.
"""
store.setdefault('templates', []).append(template)
if 'context' not in store:
store['context'] = ContextList()
store['context'].append(copy(context))
def encode_multipart(boundary, data):
"""
Encode multipart POST data from a dictionary of form values.
The key will be used as the form data name; the value will be transmitted
as content. If the value is a file, the contents of the file will be sent
as an application/octet-stream; otherwise, str(value) will be sent.
"""
lines = []
def to_bytes(s):
return force_bytes(s, settings.DEFAULT_CHARSET)
# Not by any means perfect, but good enough for our purposes.
def is_file(thing):
return hasattr(thing, "read") and callable(thing.read)
# Each bit of the multipart form data could be either a form value or a
# file, or a *list* of form values and/or files. Remember that HTTP field
# names can be duplicated!
for (key, value) in data.items():
if value is None:
raise TypeError(
"Cannot encode None for key '%s' as POST data. Did you mean "
"to pass an empty string or omit the value?" % key
)
elif is_file(value):
lines.extend(encode_file(boundary, key, value))
elif not isinstance(value, str) and is_iterable(value):
for item in value:
if is_file(item):
lines.extend(encode_file(boundary, key, item))
else:
lines.extend(to_bytes(val) for val in [
'--%s' % boundary,
'Content-Disposition: form-data; name="%s"' % key,
'',
item
])
else:
lines.extend(to_bytes(val) for val in [
'--%s' % boundary,
'Content-Disposition: form-data; name="%s"' % key,
'',
value
])
lines.extend([
to_bytes('--%s--' % boundary),
b'',
])
return b'\r\n'.join(lines)
def encode_file(boundary, key, file):
def to_bytes(s):
return force_bytes(s, settings.DEFAULT_CHARSET)
# file.name might not be a string. For example, it's an int for
# tempfile.TemporaryFile().
file_has_string_name = hasattr(file, 'name') and isinstance(file.name, str)
filename = os.path.basename(file.name) if file_has_string_name else ''
if hasattr(file, 'content_type'):
content_type = file.content_type
elif filename:
content_type = mimetypes.guess_type(filename)[0]
else:
content_type = None
if content_type is None:
content_type = 'application/octet-stream'
filename = filename or key
return [
to_bytes('--%s' % boundary),
to_bytes('Content-Disposition: form-data; name="%s"; filename="%s"'
% (key, filename)),
to_bytes('Content-Type: %s' % content_type),
b'',
to_bytes(file.read())
]
class RequestFactory:
"""
Class that lets you create mock Request objects for use in testing.
Usage:
rf = RequestFactory()
get_request = rf.get('/hello/')
post_request = rf.post('/submit/', {'foo': 'bar'})
Once you have a request object you can pass it to any view function,
just as if that view had been hooked up using a URLconf.
"""
def __init__(self, *, json_encoder=DjangoJSONEncoder, **defaults):
self.json_encoder = json_encoder
self.defaults = defaults
self.cookies = SimpleCookie()
self.errors = BytesIO()
def _base_environ(self, **request):
"""
The base environment for a request.
"""
# This is a minimal valid WSGI environ dictionary, plus:
# - HTTP_COOKIE: for cookie support,
# - REMOTE_ADDR: often useful, see #8551.
# See https://www.python.org/dev/peps/pep-3333/#environ-variables
return {
'HTTP_COOKIE': '; '.join(sorted(
'%s=%s' % (morsel.key, morsel.coded_value)
for morsel in self.cookies.values()
)),
'PATH_INFO': '/',
'REMOTE_ADDR': '127.0.0.1',
'REQUEST_METHOD': 'GET',
'SCRIPT_NAME': '',
'SERVER_NAME': 'testserver',
'SERVER_PORT': '80',
'SERVER_PROTOCOL': 'HTTP/1.1',
'wsgi.version': (1, 0),
'wsgi.url_scheme': 'http',
'wsgi.input': FakePayload(b''),
'wsgi.errors': self.errors,
'wsgi.multiprocess': True,
'wsgi.multithread': False,
'wsgi.run_once': False,
**self.defaults,
**request,
}
def request(self, **request):
"Construct a generic request object."
return WSGIRequest(self._base_environ(**request))
def _encode_data(self, data, content_type):
if content_type is MULTIPART_CONTENT:
return encode_multipart(BOUNDARY, data)
else:
# Encode the content so that the byte representation is correct.
match = CONTENT_TYPE_RE.match(content_type)
if match:
charset = match[1]
else:
charset = settings.DEFAULT_CHARSET
return force_bytes(data, encoding=charset)
def _encode_json(self, data, content_type):
"""
Return encoded JSON if data is a dict, list, or tuple and content_type
is application/json.
"""
should_encode = JSON_CONTENT_TYPE_RE.match(content_type) and isinstance(data, (dict, list, tuple))
return json.dumps(data, cls=self.json_encoder) if should_encode else data
def _get_path(self, parsed):
path = parsed.path
# If there are parameters, add them
if parsed.params:
path += ";" + parsed.params
path = unquote_to_bytes(path)
# Replace the behavior where non-ASCII values in the WSGI environ are
# arbitrarily decoded with ISO-8859-1.
# Refs comment in `get_bytes_from_wsgi()`.
return path.decode('iso-8859-1')
def get(self, path, data=None, secure=False, **extra):
"""Construct a GET request."""
data = {} if data is None else data
return self.generic('GET', path, secure=secure, **{
'QUERY_STRING': urlencode(data, doseq=True),
**extra,
})
def post(self, path, data=None, content_type=MULTIPART_CONTENT,
secure=False, **extra):
"""Construct a POST request."""
data = self._encode_json({} if data is None else data, content_type)
post_data = self._encode_data(data, content_type)
return self.generic('POST', path, post_data, content_type,
secure=secure, **extra)
def head(self, path, data=None, secure=False, **extra):
"""Construct a HEAD request."""
data = {} if data is None else data
return self.generic('HEAD', path, secure=secure, **{
'QUERY_STRING': urlencode(data, doseq=True),
**extra,
})
def trace(self, path, secure=False, **extra):
"""Construct a TRACE request."""
return self.generic('TRACE', path, secure=secure, **extra)
def options(self, path, data='', content_type='application/octet-stream',
secure=False, **extra):
"Construct an OPTIONS request."
return self.generic('OPTIONS', path, data, content_type,
secure=secure, **extra)
def put(self, path, data='', content_type='application/octet-stream',
secure=False, **extra):
"""Construct a PUT request."""
data = self._encode_json(data, content_type)
return self.generic('PUT', path, data, content_type,
secure=secure, **extra)
def patch(self, path, data='', content_type='application/octet-stream',
secure=False, **extra):
"""Construct a PATCH request."""
data = self._encode_json(data, content_type)
return self.generic('PATCH', path, data, content_type,
secure=secure, **extra)
def delete(self, path, data='', content_type='application/octet-stream',
secure=False, **extra):
"""Construct a DELETE request."""
data = self._encode_json(data, content_type)
return self.generic('DELETE', path, data, content_type,
secure=secure, **extra)
def generic(self, method, path, data='',
content_type='application/octet-stream', secure=False,
**extra):
"""Construct an arbitrary HTTP request."""
parsed = urlparse(str(path)) # path can be lazy
data = force_bytes(data, settings.DEFAULT_CHARSET)
r = {
'PATH_INFO': self._get_path(parsed),
'REQUEST_METHOD': method,
'SERVER_PORT': '443' if secure else '80',
'wsgi.url_scheme': 'https' if secure else 'http',
}
if data:
r.update({
'CONTENT_LENGTH': str(len(data)),
'CONTENT_TYPE': content_type,
'wsgi.input': FakePayload(data),
})
r.update(extra)
# If QUERY_STRING is absent or empty, we want to extract it from the URL.
if not r.get('QUERY_STRING'):
# WSGI requires latin-1 encoded strings. See get_path_info().
query_string = parsed[4].encode().decode('iso-8859-1')
r['QUERY_STRING'] = query_string
return self.request(**r)
class AsyncRequestFactory(RequestFactory):
"""
Class that lets you create mock ASGI-like Request objects for use in
testing. Usage:
rf = AsyncRequestFactory()
get_request = await rf.get('/hello/')
post_request = await rf.post('/submit/', {'foo': 'bar'})
Once you have a request object you can pass it to any view function,
including synchronous ones. The reason we have a separate class here is:
a) this makes ASGIRequest subclasses, and
b) AsyncTestClient can subclass it.
"""
def _base_scope(self, **request):
"""The base scope for a request."""
# This is a minimal valid ASGI scope, plus:
# - headers['cookie'] for cookie support,
# - 'client' often useful, see #8551.
scope = {
'asgi': {'version': '3.0'},
'type': 'http',
'http_version': '1.1',
'client': ['127.0.0.1', 0],
'server': ('testserver', '80'),
'scheme': 'http',
'method': 'GET',
'headers': [],
**self.defaults,
**request,
}
scope['headers'].append((
b'cookie',
b'; '.join(sorted(
('%s=%s' % (morsel.key, morsel.coded_value)).encode('ascii')
for morsel in self.cookies.values()
)),
))
return scope
def request(self, **request):
"""Construct a generic request object."""
# This is synchronous, which means all methods on this class are.
# AsyncClient, however, has an async request function, which makes all
# its methods async.
if '_body_file' in request:
body_file = request.pop('_body_file')
else:
body_file = FakePayload('')
return ASGIRequest(self._base_scope(**request), body_file)
def generic(
self, method, path, data='', content_type='application/octet-stream',
secure=False, **extra,
):
"""Construct an arbitrary HTTP request."""
parsed = urlparse(str(path)) # path can be lazy.
data = force_bytes(data, settings.DEFAULT_CHARSET)
s = {
'method': method,
'path': self._get_path(parsed),
'server': ('127.0.0.1', '443' if secure else '80'),
'scheme': 'https' if secure else 'http',
'headers': [(b'host', b'testserver')],
}
if data:
s['headers'].extend([
(b'content-length', str(len(data)).encode('ascii')),
(b'content-type', content_type.encode('ascii')),
])
s['_body_file'] = FakePayload(data)
follow = extra.pop('follow', None)
if follow is not None:
s['follow'] = follow
s['headers'] += [
(key.lower().encode('ascii'), value.encode('latin1'))
for key, value in extra.items()
]
# If QUERY_STRING is absent or empty, we want to extract it from the
# URL.
if not s.get('query_string'):
s['query_string'] = parsed[4]
return self.request(**s)
class ClientMixin:
"""
Mixin with common methods between Client and AsyncClient.
"""
def store_exc_info(self, **kwargs):
"""Store exceptions when they are generated by a view."""
self.exc_info = sys.exc_info()
def check_exception(self, response):
"""
Look for a signaled exception, clear the current context exception
data, re-raise the signaled exception, and clear the signaled exception
from the local cache.
"""
response.exc_info = self.exc_info
if self.exc_info:
_, exc_value, _ = self.exc_info
self.exc_info = None
if self.raise_request_exception:
raise exc_value
@property
def session(self):
"""Return the current session variables."""
engine = import_module(settings.SESSION_ENGINE)
cookie = self.cookies.get(settings.SESSION_COOKIE_NAME)
if cookie:
return engine.SessionStore(cookie.value)
session = engine.SessionStore()
session.save()
self.cookies[settings.SESSION_COOKIE_NAME] = session.session_key
return session
def login(self, **credentials):
"""
Set the Factory to appear as if it has successfully logged into a site.
Return True if login is possible or False if the provided credentials
are incorrect.
"""
from django.contrib.auth import authenticate
user = authenticate(**credentials)
if user:
self._login(user)
return True
return False
def force_login(self, user, backend=None):
def get_backend():
from django.contrib.auth import load_backend
for backend_path in settings.AUTHENTICATION_BACKENDS:
backend = load_backend(backend_path)
if hasattr(backend, 'get_user'):
return backend_path
if backend is None:
backend = get_backend()
user.backend = backend
self._login(user, backend)
def _login(self, user, backend=None):
from django.contrib.auth import login
# Create a fake request to store login details.
request = HttpRequest()
if self.session:
request.session = self.session
else:
engine = import_module(settings.SESSION_ENGINE)
request.session = engine.SessionStore()
login(request, user, backend)
# Save the session values.
request.session.save()
# Set the cookie to represent the session.
session_cookie = settings.SESSION_COOKIE_NAME
self.cookies[session_cookie] = request.session.session_key
cookie_data = {
'max-age': None,
'path': '/',
'domain': settings.SESSION_COOKIE_DOMAIN,
'secure': settings.SESSION_COOKIE_SECURE or None,
'expires': None,
}
self.cookies[session_cookie].update(cookie_data)
def logout(self):
"""Log out the user by removing the cookies and session object."""
from django.contrib.auth import get_user, logout
request = HttpRequest()
if self.session:
request.session = self.session
request.user = get_user(request)
else:
engine = import_module(settings.SESSION_ENGINE)
request.session = engine.SessionStore()
logout(request)
self.cookies = SimpleCookie()
def _parse_json(self, response, **extra):
if not hasattr(response, '_json'):
if not JSON_CONTENT_TYPE_RE.match(response.get('Content-Type')):
raise ValueError(
'Content-Type header is "%s", not "application/json"'
% response.get('Content-Type')
)
response._json = json.loads(response.content.decode(response.charset), **extra)
return response._json
class Client(ClientMixin, RequestFactory):
"""
A class that can act as a client for testing purposes.
It allows the user to compose GET and POST requests, and
obtain the response that the server gave to those requests.
The server Response objects are annotated with the details
of the contexts and templates that were rendered during the
process of serving the request.
Client objects are stateful - they will retain cookie (and
thus session) details for the lifetime of the Client instance.
This is not intended as a replacement for Twill/Selenium or
the like - it is here to allow testing against the
contexts and templates produced by a view, rather than the
HTML rendered to the end-user.
"""
def __init__(self, enforce_csrf_checks=False, raise_request_exception=True, **defaults):
super().__init__(**defaults)
self.handler = ClientHandler(enforce_csrf_checks)
self.raise_request_exception = raise_request_exception
self.exc_info = None
self.extra = None
def request(self, **request):
"""
The master request method. Compose the environment dictionary and pass
to the handler, return the result of the handler. Assume defaults for
the query environment, which can be overridden using the arguments to
the request.
"""
environ = self._base_environ(**request)
# Curry a data dictionary into an instance of the template renderer
# callback function.
data = {}
on_template_render = partial(store_rendered_templates, data)
signal_uid = "template-render-%s" % id(request)
signals.template_rendered.connect(on_template_render, dispatch_uid=signal_uid)
# Capture exceptions created by the handler.
exception_uid = "request-exception-%s" % id(request)
got_request_exception.connect(self.store_exc_info, dispatch_uid=exception_uid)
try:
response = self.handler(environ)
finally:
signals.template_rendered.disconnect(dispatch_uid=signal_uid)
got_request_exception.disconnect(dispatch_uid=exception_uid)
# Check for signaled exceptions.
self.check_exception(response)
# Save the client and request that stimulated the response.
response.client = self
response.request = request
# Add any rendered template detail to the response.
response.templates = data.get('templates', [])
response.context = data.get('context')
response.json = partial(self._parse_json, response)
# Attach the ResolverMatch instance to the response.
urlconf = getattr(response.wsgi_request, 'urlconf', None)
response.resolver_match = SimpleLazyObject(
lambda: resolve(request['PATH_INFO'], urlconf=urlconf),
)
# Flatten a single context. Not really necessary anymore thanks to the
# __getattr__ flattening in ContextList, but has some edge case
# backwards compatibility implications.
if response.context and len(response.context) == 1:
response.context = response.context[0]
# Update persistent cookie data.
if response.cookies:
self.cookies.update(response.cookies)
return response
def get(self, path, data=None, follow=False, secure=False, **extra):
"""Request a response from the server using GET."""
self.extra = extra
response = super().get(path, data=data, secure=secure, **extra)
if follow:
response = self._handle_redirects(response, data=data, **extra)
return response
def post(self, path, data=None, content_type=MULTIPART_CONTENT,
follow=False, secure=False, **extra):
"""Request a response from the server using POST."""
self.extra = extra
response = super().post(path, data=data, content_type=content_type, secure=secure, **extra)
if follow:
response = self._handle_redirects(response, data=data, content_type=content_type, **extra)
return response
def head(self, path, data=None, follow=False, secure=False, **extra):
"""Request a response from the server using HEAD."""
self.extra = extra
response = super().head(path, data=data, secure=secure, **extra)
if follow:
response = self._handle_redirects(response, data=data, **extra)
return response
def options(self, path, data='', content_type='application/octet-stream',
follow=False, secure=False, **extra):
"""Request a response from the server using OPTIONS."""
self.extra = extra
response = super().options(path, data=data, content_type=content_type, secure=secure, **extra)
if follow:
response = self._handle_redirects(response, data=data, content_type=content_type, **extra)
return response
def put(self, path, data='', content_type='application/octet-stream',
follow=False, secure=False, **extra):
"""Send a resource to the server using PUT."""
self.extra = extra
response = super().put(path, data=data, content_type=content_type, secure=secure, **extra)
if follow:
response = self._handle_redirects(response, data=data, content_type=content_type, **extra)
return response
def patch(self, path, data='', content_type='application/octet-stream',
follow=False, secure=False, **extra):
"""Send a resource to the server using PATCH."""
self.extra = extra
response = super().patch(path, data=data, content_type=content_type, secure=secure, **extra)
if follow:
response = self._handle_redirects(response, data=data, content_type=content_type, **extra)
return response
def delete(self, path, data='', content_type='application/octet-stream',
follow=False, secure=False, **extra):
"""Send a DELETE request to the server."""
self.extra = extra
response = super().delete(path, data=data, content_type=content_type, secure=secure, **extra)
if follow:
response = self._handle_redirects(response, data=data, content_type=content_type, **extra)
return response
def trace(self, path, data='', follow=False, secure=False, **extra):
"""Send a TRACE request to the server."""
self.extra = extra
response = super().trace(path, data=data, secure=secure, **extra)
if follow:
response = self._handle_redirects(response, data=data, **extra)
return response
def _handle_redirects(self, response, data='', content_type='', **extra):
"""
Follow any redirects by requesting responses from the server using GET.
"""
response.redirect_chain = []
redirect_status_codes = (
HTTPStatus.MOVED_PERMANENTLY,
HTTPStatus.FOUND,
HTTPStatus.SEE_OTHER,
HTTPStatus.TEMPORARY_REDIRECT,
HTTPStatus.PERMANENT_REDIRECT,
)
while response.status_code in redirect_status_codes:
response_url = response.url
redirect_chain = response.redirect_chain
redirect_chain.append((response_url, response.status_code))
url = urlsplit(response_url)
if url.scheme:
extra['wsgi.url_scheme'] = url.scheme
if url.hostname:
extra['SERVER_NAME'] = url.hostname
if url.port:
extra['SERVER_PORT'] = str(url.port)
# Prepend the request path to handle relative path redirects
path = url.path or '/'
if not path.startswith('/'):
path = urljoin(response.request['PATH_INFO'], path)
if response.status_code in (HTTPStatus.TEMPORARY_REDIRECT, HTTPStatus.PERMANENT_REDIRECT):
# Preserve request method and query string (if needed)
# post-redirect for 307/308 responses.
request_method = response.request['REQUEST_METHOD'].lower()
if request_method not in ('get', 'head'):
extra['QUERY_STRING'] = url.query
request_method = getattr(self, request_method)
else:
request_method = self.get
data = QueryDict(url.query)
content_type = None
response = request_method(path, data=data, content_type=content_type, follow=False, **extra)
response.redirect_chain = redirect_chain
if redirect_chain[-1] in redirect_chain[:-1]:
# Check that we're not redirecting to somewhere we've already
# been to, to prevent loops.
raise RedirectCycleError("Redirect loop detected.", last_response=response)
if len(redirect_chain) > 20:
# Such a lengthy chain likely also means a loop, but one with
# a growing path, changing view, or changing query argument;
# 20 is the value of "network.http.redirection-limit" from Firefox.
raise RedirectCycleError("Too many redirects.", last_response=response)
return response
class AsyncClient(ClientMixin, AsyncRequestFactory):
"""
An async version of Client that creates ASGIRequests and calls through an
async request path.
Does not currently support "follow" on its methods.
"""
def __init__(self, enforce_csrf_checks=False, raise_request_exception=True, **defaults):
super().__init__(**defaults)
self.handler = AsyncClientHandler(enforce_csrf_checks)
self.raise_request_exception = raise_request_exception
self.exc_info = None
self.extra = None
async def request(self, **request):
"""
The master request method. Compose the scope dictionary and pass to the
handler, return the result of the handler. Assume defaults for the
query environment, which can be overridden using the arguments to the
request.
"""
if 'follow' in request:
raise NotImplementedError(
'AsyncClient request methods do not accept the follow '
'parameter.'
)
scope = self._base_scope(**request)
# Curry a data dictionary into an instance of the template renderer
# callback function.
data = {}
on_template_render = partial(store_rendered_templates, data)
signal_uid = 'template-render-%s' % id(request)
signals.template_rendered.connect(on_template_render, dispatch_uid=signal_uid)
# Capture exceptions created by the handler.
exception_uid = 'request-exception-%s' % id(request)
got_request_exception.connect(self.store_exc_info, dispatch_uid=exception_uid)
try:
response = await self.handler(scope)
finally:
signals.template_rendered.disconnect(dispatch_uid=signal_uid)
got_request_exception.disconnect(dispatch_uid=exception_uid)
# Check for signaled exceptions.
self.check_exception(response)
# Save the client and request that stimulated the response.
response.client = self
response.request = request
# Add any rendered template detail to the response.
response.templates = data.get('templates', [])
response.context = data.get('context')
response.json = partial(self._parse_json, response)
# Attach the ResolverMatch instance to the response.
urlconf = getattr(response.asgi_request, 'urlconf', None)
response.resolver_match = SimpleLazyObject(
lambda: resolve(request['path'], urlconf=urlconf),
)
# Flatten a single context. Not really necessary anymore thanks to the
# __getattr__ flattening in ContextList, but has some edge case
# backwards compatibility implications.
if response.context and len(response.context) == 1:
response.context = response.context[0]
# Update persistent cookie data.
if response.cookies:
self.cookies.update(response.cookies)
return response
| 40.165059
| 112
| 0.626381
|
4a0b6b4a3ecaf41490e5d2426ce74ac604d41103
| 5,757
|
py
|
Python
|
contrib/seeds/makeseeds.py
|
fartonium/fartonium
|
0d454e4368356eb2ea40b6ade622f8f6089488f7
|
[
"MIT"
] | null | null | null |
contrib/seeds/makeseeds.py
|
fartonium/fartonium
|
0d454e4368356eb2ea40b6ade622f8f6089488f7
|
[
"MIT"
] | null | null | null |
contrib/seeds/makeseeds.py
|
fartonium/fartonium
|
0d454e4368356eb2ea40b6ade622f8f6089488f7
|
[
"MIT"
] | null | null | null |
#!/usr/bin/env python3
# Copyright (c) 2013-2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Generate seeds.txt from Pieter's DNS seeder
#
NSEEDS=512
MAX_SEEDS_PER_ASN=2
MIN_BLOCKS = 337600
# These are hosts that have been observed to be behaving strangely (e.g.
# aggressively connecting to every node).
SUSPICIOUS_HOSTS = {
"130.211.129.106", "178.63.107.226",
"83.81.130.26", "88.198.17.7", "148.251.238.178", "176.9.46.6",
"54.173.72.127", "54.174.10.182", "54.183.64.54", "54.194.231.211",
"54.66.214.167", "54.66.220.137", "54.67.33.14", "54.77.251.214",
"54.94.195.96", "54.94.200.247"
}
import re
import sys
import dns.resolver
import collections
PATTERN_IPV4 = re.compile(r"^((\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})):(\d+)$")
PATTERN_IPV6 = re.compile(r"^\[([0-9a-z:]+)\]:(\d+)$")
PATTERN_ONION = re.compile(r"^([abcdefghijklmnopqrstuvwxyz234567]{16}\.onion):(\d+)$")
PATTERN_AGENT = re.compile(r"^(/Satoshi:0.13.(0|1|2|99)/|/FartoniumCore:0.13.(0|1|2|99)/|/FartoniumCore:0.14.(0|1|2|99)/)$")
def parseline(line):
sline = line.split()
if len(sline) < 11:
return None
m = PATTERN_IPV4.match(sline[0])
sortkey = None
ip = None
if m is None:
m = PATTERN_IPV6.match(sline[0])
if m is None:
m = PATTERN_ONION.match(sline[0])
if m is None:
return None
else:
net = 'onion'
ipstr = sortkey = m.group(1)
port = int(m.group(2))
else:
net = 'ipv6'
if m.group(1) in ['::']: # Not interested in localhost
return None
ipstr = m.group(1)
sortkey = ipstr # XXX parse IPv6 into number, could use name_to_ipv6 from generate-seeds
port = int(m.group(2))
else:
# Do IPv4 sanity check
ip = 0
for i in range(0,4):
if int(m.group(i+2)) < 0 or int(m.group(i+2)) > 255:
return None
ip = ip + (int(m.group(i+2)) << (8*(3-i)))
if ip == 0:
return None
net = 'ipv4'
sortkey = ip
ipstr = m.group(1)
port = int(m.group(6))
# Skip bad results.
if sline[1] == 0:
return None
# Extract uptime %.
uptime30 = float(sline[7][:-1])
# Extract Unix timestamp of last success.
lastsuccess = int(sline[2])
# Extract protocol version.
version = int(sline[10])
# Extract user agent.
agent = sline[11][1:-1]
# Extract service flags.
service = int(sline[9], 16)
# Extract blocks.
blocks = int(sline[8])
# Construct result.
return {
'net': net,
'ip': ipstr,
'port': port,
'ipnum': ip,
'uptime': uptime30,
'lastsuccess': lastsuccess,
'version': version,
'agent': agent,
'service': service,
'blocks': blocks,
'sortkey': sortkey,
}
def filtermultiport(ips):
'''Filter out hosts with more nodes per IP'''
hist = collections.defaultdict(list)
for ip in ips:
hist[ip['sortkey']].append(ip)
return [value[0] for (key,value) in list(hist.items()) if len(value)==1]
# Based on Greg Maxwell's seed_filter.py
def filterbyasn(ips, max_per_asn, max_total):
# Sift out ips by type
ips_ipv4 = [ip for ip in ips if ip['net'] == 'ipv4']
ips_ipv6 = [ip for ip in ips if ip['net'] == 'ipv6']
ips_onion = [ip for ip in ips if ip['net'] == 'onion']
# Filter IPv4 by ASN
result = []
asn_count = {}
for ip in ips_ipv4:
if len(result) == max_total:
break
try:
asn = int([x.to_text() for x in dns.resolver.query('.'.join(reversed(ip['ip'].split('.'))) + '.origin.asn.cymru.com', 'TXT').response.answer][0].split('\"')[1].split(' ')[0])
if asn not in asn_count:
asn_count[asn] = 0
if asn_count[asn] == max_per_asn:
continue
asn_count[asn] += 1
result.append(ip)
except:
sys.stderr.write('ERR: Could not resolve ASN for "' + ip['ip'] + '"\n')
# TODO: filter IPv6 by ASN
# Add back non-IPv4
result.extend(ips_ipv6)
result.extend(ips_onion)
return result
def main():
lines = sys.stdin.readlines()
ips = [parseline(line) for line in lines]
# Skip entries with valid address.
ips = [ip for ip in ips if ip is not None]
# Skip entries from suspicious hosts.
ips = [ip for ip in ips if ip['ip'] not in SUSPICIOUS_HOSTS]
# Enforce minimal number of blocks.
ips = [ip for ip in ips if ip['blocks'] >= MIN_BLOCKS]
# Require service bit 1.
ips = [ip for ip in ips if (ip['service'] & 1) == 1]
# Require at least 50% 30-day uptime.
ips = [ip for ip in ips if ip['uptime'] > 50]
# Require a known and recent user agent.
ips = [ip for ip in ips if PATTERN_AGENT.match(ip['agent'])]
# Sort by availability (and use last success as tie breaker)
ips.sort(key=lambda x: (x['uptime'], x['lastsuccess'], x['ip']), reverse=True)
# Filter out hosts with multiple bitcoin ports, these are likely abusive
ips = filtermultiport(ips)
# Look up ASNs and limit results, both per ASN and globally.
ips = filterbyasn(ips, MAX_SEEDS_PER_ASN, NSEEDS)
# Sort the results by IP address (for deterministic output).
ips.sort(key=lambda x: (x['net'], x['sortkey']))
for ip in ips:
if ip['net'] == 'ipv6':
print('[%s]:%i' % (ip['ip'], ip['port']))
else:
print('%s:%i' % (ip['ip'], ip['port']))
if __name__ == '__main__':
main()
| 33.277457
| 186
| 0.570262
|
4a0b6be79eded706f5d09dea2afa98509198bf49
| 5,753
|
py
|
Python
|
geotag/exif.py
|
puigfp/geotag
|
840cd7166bafc8bc649f5a34d302811a1d707f6c
|
[
"MIT"
] | null | null | null |
geotag/exif.py
|
puigfp/geotag
|
840cd7166bafc8bc649f5a34d302811a1d707f6c
|
[
"MIT"
] | 1
|
2021-09-10T18:01:16.000Z
|
2021-09-10T18:02:37.000Z
|
geotag/exif.py
|
puigfp/geotag
|
840cd7166bafc8bc649f5a34d302811a1d707f6c
|
[
"MIT"
] | 4
|
2020-04-29T08:47:34.000Z
|
2021-12-24T14:30:20.000Z
|
import bisect
import json
import os
import re
import subprocess
from datetime import datetime, timedelta, timezone
from typing import List, Optional
import pytz
from .location_history import Location
from .log import log
from .timezone import gps_coords_to_utc_offset
def read_exif(root: str) -> List[dict]:
log.info("reading exif from photos using exiftool...")
completed = subprocess.run(
["exiftool", "-json", "-r", root], capture_output=True, check=True
)
return json.loads(completed.stdout)
def write_exif(root_path: str, exif_diff_path: str):
log.info("writing exif diff to photos using exiftool...")
subprocess.run(
["exiftool", "-overwrite_original", f"-json={exif_diff_path}", "-r", root_path],
check=True,
)
# regex for parsing the EXIF time offset format ("±HH:MM")
REGEX_TIMEZONE_OFFSET = re.compile(
r"(?P<sign>\+|-)?(?P<hours>\d{2}):(?P<minutes>\d{2})"
)
def parse_exif_timezone_offset(s: str) -> int:
"""
Parses an EXIF time offset ("±HH:MM") and returns a signed number of minutes.
"""
match = REGEX_TIMEZONE_OFFSET.fullmatch(s)
if match is None:
raise Exception(f'"{s}" isn\'t a valid EXIF time offset string ("±HH:MM")')
groups = match.groupdict()
sign = +1 if groups["sign"] in ("+", None) else -1
hours = int(groups["hours"])
minutes = int(groups["minutes"])
return sign * (60 * hours + minutes)
def format_exif_timezone_offset(offset: int) -> str:
"""
Serializes a number of minutes to a EXIF time offset ("±HH:MM") string.
"""
sign = 1 if offset >= 0 else -1
if sign == -1:
offset = -offset
sign_str = "+" if sign == 1 else "-"
hours_str = str(offset // 60).zfill(2)
minutes_str = str(offset % 60).zfill(2)
return f"{sign_str}{hours_str}:{minutes_str}"
def get_file_exif_diff(
img_exif: dict, img_date: datetime, location: Location,
) -> Optional[dict]:
diff = {"SourceFile": img_exif["SourceFile"]}
# update date/time/utc offset
try:
utc_offset_target = gps_coords_to_utc_offset(
img_date, lat=location.latitude, lng=location.longitude
)
diff = {
**diff,
"DateTimeOriginal": img_date.astimezone(
tz=timezone(timedelta(minutes=utc_offset_target))
).strftime("%Y:%m:%d %H:%M:%S"),
"OffsetTimeOriginal": format_exif_timezone_offset(utc_offset_target),
}
except pytz.exceptions.AmbiguousTimeError as e:
log.error(
f'skipping "{img_path}" date/time/utc offset update, '
f"encountered an ambiguous time error: {e}"
)
# update location
location_datetime = datetime.fromtimestamp(location.timestamp, tz=timezone.utc)
diff = {
**diff,
"GPSDateTime": location_datetime.strftime("%Y:%m:%d %H:%M:%SZ"),
"GPSTimeStamp": location_datetime.strftime("%H:%M:%S"),
"GPSDateStamp": location_datetime.strftime("%Y:%m:%d"),
# XXX: it seems we need to write the GPS metadata in EXIF and XMP to make
# Lightroom able to read it
"EXIF:GPSLatitude": location.latitude,
"EXIF:GPSLongitude": location.longitude,
"XMP:GPSLatitude": location.latitude,
"XMP:GPSLongitude": location.longitude,
}
return diff
def get_exif_diff(
list_exif: List[dict], location_history: List[Location], utc_offset_default: int
) -> List[dict]:
log.info("computing exif diff")
location_timestamps = [location.timestamp for location in location_history]
date_interval = (
datetime.fromtimestamp(location_timestamps[0], tz=timezone.utc),
datetime.fromtimestamp(location_timestamps[-1], tz=timezone.utc),
)
exif_diff = []
for img_exif in list_exif:
img_path = img_exif["SourceFile"]
if "DateTimeOriginal" not in img_exif:
log.warning(f'skipping "{img_path}", could not find date/time metadata')
continue
if "GPSPosition" in img_exif:
log.warning(f'skipping "{img_path}", gps info already present')
continue
# infer image original date UTC offset
utc_offset_str = img_exif.get("OffsetTimeOriginal")
utc_offset = (
parse_exif_timezone_offset(utc_offset_str)
if utc_offset_str is not None
else utc_offset_default
)
# parse image original date
img_date = datetime.strptime(
img_exif["DateTimeOriginal"], "%Y:%m:%d %H:%M:%S",
).replace(tzinfo=timezone(timedelta(minutes=utc_offset)))
# find closest location
if not date_interval[0] <= img_date < date_interval[1]:
log.warning(
f'skipping "{img_path}", {img_date} is out of location history range '
f"[{date_interval[0]}, {date_interval[1]}]"
)
continue
img_timestamp = img_date.timestamp()
i = bisect.bisect_left(location_timestamps, img_timestamp)
closest_location = min(
[location_history[i], location_history[i + 1]],
key=lambda location: abs(location.timestamp - img_timestamp),
)
delta_timestamp = abs(closest_location.timestamp - img_timestamp)
if delta_timestamp > 60 * 60: # 1 hour
log.warning(
f'skipping "{img_path}", timestamp ({img_timestamp}) is too far from '
f"the closest history timestamp (delta={delta_timestamp}s)"
)
continue
# append diff
img_exif_diff = get_file_exif_diff(img_exif, img_date, closest_location)
if img_exif_diff is not None:
exif_diff.append(img_exif_diff)
return exif_diff
| 34.244048
| 88
| 0.63167
|
4a0b6c011167158925934dfc24520a48af74627f
| 346
|
py
|
Python
|
src/pico_code/pico/resistomatic/raw-resisitance.py
|
romilly/pico-code
|
57bbc14e0a5c3e874162fcfb1fcd7cca3a838cce
|
[
"MIT"
] | 15
|
2021-02-04T02:38:23.000Z
|
2022-01-20T17:55:15.000Z
|
src/pico_code/pico/resistomatic/raw-resisitance.py
|
romilly/pico-code
|
57bbc14e0a5c3e874162fcfb1fcd7cca3a838cce
|
[
"MIT"
] | 1
|
2021-05-06T10:09:51.000Z
|
2021-05-06T10:09:51.000Z
|
src/pico_code/pico/resistomatic/raw-resisitance.py
|
romilly/pico-code
|
57bbc14e0a5c3e874162fcfb1fcd7cca3a838cce
|
[
"MIT"
] | 2
|
2021-02-04T20:09:01.000Z
|
2021-02-18T16:16:22.000Z
|
import machine
import time
potentiometer = machine.ADC(26)
def run():
while True:
raw_v = potentiometer.read_u16()
voltage = 3.3 * raw_v / 65535.0
r_fixed = 1000 # Ohms
try:
r = r_fixed * voltage/(3.3 - voltage)
print(r)
except:
pass
time.sleep(1.0)
run()
| 19.222222
| 49
| 0.523121
|
4a0b6cfaa6a6bebaaa2eaebb08de085305f82026
| 7,652
|
py
|
Python
|
recipes/sentry-crashpad/all/conanfile.py
|
rockandsalt/conan-center-index
|
d739adcec3e4dd4c250eff559ceb738e420673dd
|
[
"MIT"
] | 1
|
2020-01-31T22:47:14.000Z
|
2020-01-31T22:47:14.000Z
|
recipes/sentry-crashpad/all/conanfile.py
|
rockandsalt/conan-center-index
|
d739adcec3e4dd4c250eff559ceb738e420673dd
|
[
"MIT"
] | 3
|
2020-05-05T11:27:44.000Z
|
2022-02-28T20:19:50.000Z
|
recipes/sentry-crashpad/all/conanfile.py
|
rockandsalt/conan-center-index
|
d739adcec3e4dd4c250eff559ceb738e420673dd
|
[
"MIT"
] | 1
|
2020-10-12T10:45:13.000Z
|
2020-10-12T10:45:13.000Z
|
import os
from conans import ConanFile, CMake, tools
from conans.errors import ConanInvalidConfiguration
required_conan_version = ">=1.28.0"
class SentryCrashpadConan(ConanFile):
name = "sentry-crashpad"
description = "Crashpad is a crash-reporting system."
url = "https://github.com/conan-io/conan-center-index"
homepage = "https://github.com/getsentry/sentry-native"
license = "Apache-2.0"
topics = ("conan", "crashpad", "error-reporting", "crash-reporting")
provides = "crashpad", "mini_chromium"
settings = "os", "arch", "compiler", "build_type"
options = {
"fPIC": [True, False],
"with_tls": ["openssl", False],
}
default_options = {
"fPIC": True,
"with_tls": "openssl",
}
exports_sources = "CMakeLists.txt", "patches/*"
generators = "cmake"
short_paths = True
_cmake = None
@property
def _build_subfolder(self):
return "build_subfolder"
@property
def _source_subfolder(self):
return "source_subfolder"
@property
def _minimum_compilers_version(self):
return {
"Visual Studio": "15",
"gcc": "5",
"clang": "3.4",
"apple-clang": "5.1",
}
def config_options(self):
if self.settings.os == "Windows":
del self.options.fPIC
if self.settings.os not in ("Linux", "Android") or tools.Version(self.version) < "0.4":
del self.options.with_tls
def requirements(self):
self.requires("zlib/1.2.11")
if self.options.get_safe("with_tls"):
self.requires("openssl/1.1.1l")
def validate(self):
if self.settings.compiler.cppstd:
# Set as required in crashpad CMake file.
# See https://github.com/getsentry/crashpad/blob/71bcaad4cf30294b8de1bfa02064ab629437163b/CMakeLists.txt#L67
tools.check_min_cppstd(self, 14)
minimum_version = self._minimum_compilers_version.get(str(self.settings.compiler), False)
if not minimum_version:
self.output.warn("Compiler is unknown. Assuming it supports C++14.")
elif tools.Version(self.settings.compiler.version) < minimum_version:
raise ConanInvalidConfiguration("Build requires support for C++14. Minimum version for {} is {}"
.format(str(self.settings.compiler), minimum_version))
if tools.Version(self.version) < "0.4.7" and self.settings.os == "Macos" and self.settings.arch == "armv8":
raise ConanInvalidConfiguration("This version doesn't support ARM compilation")
def source(self):
tools.get(**self.conan_data["sources"][self.version], destination=self._source_subfolder)
def _configure_cmake(self):
if self._cmake:
return self._cmake
self._cmake = CMake(self)
self._cmake.definitions["CRASHPAD_ENABLE_INSTALL"] = True
self._cmake.definitions["CRASHPAD_ENABLE_INSTALL_DEV"] = True
self._cmake.definitions["CRASHPAD_ZLIB_SYSTEM"] = True
self._cmake.configure(build_folder=self._build_subfolder)
return self._cmake
def build(self):
for patch in self.conan_data.get("patches", {}).get(self.version, []):
tools.patch(**patch)
if tools.Version(self.version) > "0.4":
openssl_repl = "find_package(OpenSSL REQUIRED)" if self.options.get_safe("with_tls") else ""
tools.replace_in_file(os.path.join(self._source_subfolder, "external", "crashpad", "CMakeLists.txt"),
"find_package(OpenSSL)", openssl_repl)
cmake = self._configure_cmake()
cmake.build()
def package(self):
self.copy("LICENSE", dst="licenses", src=os.path.join(self._source_subfolder, "external", "crashpad"))
cmake = self._configure_cmake()
cmake.install()
tools.rmdir(os.path.join(self.package_folder, "lib", "cmake"))
tools.remove_files_by_mask(os.path.join(self.package_folder, "bin"), "*.pdb")
def package_info(self):
self.cpp_info.names["cmake_find_package"] = "crashpad"
self.cpp_info.names["cmake_find_package_multi"] = "crashpad"
self.cpp_info.filenames["cmake_find_package"] = "crashpad"
self.cpp_info.filenames["cmake_find_package_multi"] = "crashpad"
self.cpp_info.components["mini_chromium"].includedirs.append(os.path.join("include", "crashpad", "mini_chromium"))
self.cpp_info.components["mini_chromium"].libs = ["mini_chromium"]
if self.settings.os in ("Linux", "FreeBSD"):
self.cpp_info.components["mini_chromium"].system_libs.append("pthread")
if tools.is_apple_os(self.settings.os):
if self.settings.os == "Macos":
self.cpp_info.components["mini_chromium"].frameworks = ["ApplicationServices", "CoreFoundation", "Foundation", "IOKit", "Security"]
else: # iOS
self.cpp_info.components["mini_chromium"].frameworks = ["CoreFoundation", "CoreGraphics", "CoreText", "Foundation", "Security"]
self.cpp_info.components["compat"].includedirs.append(os.path.join("include", "crashpad"))
# On Apple crashpad_compat is an interface library
if not tools.is_apple_os(self.settings.os):
self.cpp_info.components["compat"].libs = ["crashpad_compat"]
if self.settings.os in ("Linux", "FreeBSD"):
self.cpp_info.components["compat"].system_libs.append("dl")
self.cpp_info.components["util"].libs = ["crashpad_util"]
self.cpp_info.components["util"].requires = ["compat", "mini_chromium", "zlib::zlib"]
if self.settings.os in ("Linux", "FreeBSD"):
self.cpp_info.components["util"].system_libs.extend(["pthread", "rt"])
elif self.settings.os == "Windows":
self.cpp_info.components["util"].system_libs.append("winhttp")
if self.options.get_safe("with_tls") == "openssl":
self.cpp_info.components["util"].requires.append("openssl::openssl")
if self.settings.os == "Macos":
self.cpp_info.components["util"].frameworks.extend(["CoreFoundation", "Foundation", "IOKit"])
self.cpp_info.components["util"].system_libs.append("bsm")
self.cpp_info.components["client"].libs = ["crashpad_client"]
self.cpp_info.components["client"].requires = ["util", "mini_chromium"]
self.cpp_info.components["snapshot"].libs = ["crashpad_snapshot"]
self.cpp_info.components["snapshot"].requires = ["client", "compat", "util", "mini_chromium"]
if self.settings.os == "Windows":
self.cpp_info.components["snapshot"].system_libs.append("powrprof")
self.cpp_info.components["minidump"].libs = ["crashpad_minidump"]
self.cpp_info.components["minidump"].requires = ["compat", "snapshot", "util", "mini_chromium"]
if tools.Version(self.version) > "0.3":
if self.settings.os == "Windows":
self.cpp_info.components["getopt"].libs = ["crashpad_getopt"]
self.cpp_info.components["handler"].libs = ["crashpad_handler_lib"]
self.cpp_info.components["handler"].requires = ["compat", "minidump", "snapshot", "util", "mini_chromium"]
if self.settings.os == "Windows":
self.cpp_info.components["handler"].requires.append("getopt")
self.cpp_info.components["tools"].libs = ["crashpad_tools"]
bin_path = os.path.join(self.package_folder, "bin")
self.output.info("Appending PATH environment variable: {}".format(bin_path))
self.env_info.PATH.append(bin_path)
| 46.096386
| 147
| 0.643361
|
4a0b712c839885f9afd428c3963565850a5b9e6d
| 330
|
py
|
Python
|
app/base/routes.py
|
YaPunk/bokunosite
|
30884700cb059645a573ef6396051638ab66adb4
|
[
"MIT"
] | null | null | null |
app/base/routes.py
|
YaPunk/bokunosite
|
30884700cb059645a573ef6396051638ab66adb4
|
[
"MIT"
] | null | null | null |
app/base/routes.py
|
YaPunk/bokunosite
|
30884700cb059645a573ef6396051638ab66adb4
|
[
"MIT"
] | null | null | null |
from flask import render_template, url_for
from flask_login import current_user, login_required
from app.base import base
from app.models import Section
@base.route('/')
@base.route('/index')
def index():
return render_template(
"index.html",
title="Index Page",
sections=Section.query.all(),
)
| 20.625
| 52
| 0.693939
|
4a0b713bf259d60804b7a1402e883987767f0eec
| 2,783
|
py
|
Python
|
mapElites/createChildren.py
|
Sascha0912/SAIL
|
5dfb8d0b925d5e61933bf10591d959433fffaf26
|
[
"MIT"
] | 2
|
2019-03-12T10:21:54.000Z
|
2019-07-17T14:56:33.000Z
|
mapElites/createChildren.py
|
Sascha0912/SAIL
|
5dfb8d0b925d5e61933bf10591d959433fffaf26
|
[
"MIT"
] | null | null | null |
mapElites/createChildren.py
|
Sascha0912/SAIL
|
5dfb8d0b925d5e61933bf10591d959433fffaf26
|
[
"MIT"
] | 1
|
2020-08-31T07:22:09.000Z
|
2020-08-31T07:22:09.000Z
|
import numpy as np
import pandas as pd
def createChildren(map, nChildren, p, d):
# Remove empty bins from parent pool
if (isinstance(map,tuple)):
if (isinstance(map[0],tuple)):
map = map[0][0]
else:
map = map[0]
# print("map.genes") # map.genes enthält nur in den ersten beiden 25x25 maps genome. Die anderen sind alle mit nan gefüllt
# print(map.genes)
parentPool = pd.DataFrame(data=np.empty([len(map.genes[0].index) * len(map.genes[0].columns), len(map.genes)]))
# print("parentPool")
# print(parentPool)
# print("map.genes")
# print(map.genes[0].to_numpy())
# Reshaping to columns
reshaped_genes = [] # index 1 = first attribute, ...
for i in range(0,len(map.genes)):
# print(map. genes[i].shape)
# tmp_to_numpy = map.genes[i].to_numpy()
reshaped_genes.append(map.genes[i].to_numpy().reshape(( map.genes[i].shape[0] * map.genes[i].shape[1], 1 ), order='F'))
# print("reshaped")
# print(reshaped_genes)
k = 0 # counter for reshaped array
for i in range(0, len(map.genes[0].index) * len(map.genes[0].columns)): # each sample (25)
for j in range(0, len(map.genes)): # each attribute (2)
entry = reshaped_genes[j][i][0]
# if (np.isnan(entry)): # only checks first attribute of sample if nan
# break
parentPool.at[i, j] = entry
# if j==len(map.genes)-1:
# k = k+1
parentPool.dropna(inplace=True)
parentPool.reset_index(drop=True, inplace=True)
# print("parentPool")
# print(parentPool)
# print("nChildren: " + str(nChildren))
# Choose parents and create mutation
selected_parents = np.random.randint(len(parentPool.index), size=nChildren)
# print("selected_parents")
# print(selected_parents)
parents = parentPool.iloc[selected_parents,:]
parents.reset_index(drop=True, inplace=True)
# print("parents")
# print(parents)
mutation = pd.DataFrame(data=np.random.normal(size=(nChildren,d.dof)) * p.mutSigma)
# print("mutation")
# print(mutation)
children = parents.add(mutation)
# ADJUSTSCALE
children[0] = children[0].clip(upper=0.2,lower=-0.2)
children[1] = children[1].clip(upper=0.2,lower=-0.2)
children[2] = children[2].clip(upper=0,lower=-2)
children[3] = children[3].clip(upper=0,lower=-2)
children[4] = children[4].clip(upper=0.2,lower=-0.2)
children[5] = children[5].clip(upper=0.2,lower=-0.2)
# children[children<-2] = -2 # DOMAINCHANGE
# children[children>0] = 0
# print("children")
# print(children)
# children[children<0] = 0
# children[children>4] = 4
# print("children")
# print(children)
return children
| 35.227848
| 127
| 0.617319
|
4a0b715e9d2f3d455218814e913960590720f3a7
| 123
|
py
|
Python
|
view.py
|
LunexCoding/EasyGeometry
|
93bde6294403e7a6d58694c759e64f6b8829347d
|
[
"Apache-2.0"
] | null | null | null |
view.py
|
LunexCoding/EasyGeometry
|
93bde6294403e7a6d58694c759e64f6b8829347d
|
[
"Apache-2.0"
] | null | null | null |
view.py
|
LunexCoding/EasyGeometry
|
93bde6294403e7a6d58694c759e64f6b8829347d
|
[
"Apache-2.0"
] | null | null | null |
class _View:
def showMessage(self, msg):
print(msg)
def requestInput(self, msg):
return msg
g_view = _View()
| 13.666667
| 30
| 0.658537
|
4a0b729e80a51eeba71b2ee4be33e203e00ed348
| 3,432
|
py
|
Python
|
gc_win.py
|
lauren-lopez/learning_python
|
c91bcf2e6468a3dd0f4e8a928d2c0de1e5706ade
|
[
"MIT"
] | null | null | null |
gc_win.py
|
lauren-lopez/learning_python
|
c91bcf2e6468a3dd0f4e8a928d2c0de1e5706ade
|
[
"MIT"
] | null | null | null |
gc_win.py
|
lauren-lopez/learning_python
|
c91bcf2e6468a3dd0f4e8a928d2c0de1e5706ade
|
[
"MIT"
] | null | null | null |
#!/usr/bin/env python3
# Write a program that computes the GC fraction of a DNA sequence in a window
# Window size is 11 nt
# Output with 4 significant figures using whichever method you prefer
seq = 'ACGACGCAGGAGGAGAGTTTCAGAGATCACGAATACATCCATATTACCCAGAGAGAG'
w = 11
s = 0 #start position
gc_count = 0
for i in range(s, len(seq)-w+1): #doesn't work - prints total number GC
for c in seq[s:s+w]:
if c == 'G' or c == 'C': gc_count += 1
gc_frac = gc_count/w
print('%d %s %.4f' % (i, seq[s:s+w], gc_frac))
s += 1
gc_count = 0
#Failed attempts below - kept for future reference
#for i in range(s, len(seq)-w+1): #doesn't work - prints total number GC
# for c in seq:
# if c == 'G' or c == 'C': gc_count += 1
# print(i, seq[s:s+w], gc_count)
# s += 1
# gc_count = 0
#for i in range(s, len(seq)-w+1): # doesn't work - gc count always 0
# if seq[i:(i+w)] == 'G' or seq[i:(i+w)] == 'C': gc_count += 1
# print(i, seq[s:s+w], gc_count)
# s += 1
# gc_count = 0
#for i in range(s, len(seq)-w+1): # doesn't work - gc count always 0
# if seq[i:i+w] == 'G' or seq[i:i+w] == 'C': gc_count += 1
# print(i, seq[s:s+w], gc_count)
# s += 1
# gc_count = 0
#for i in range(s, len(seq)-w+1): #doesn't work - only checks first letter in window
# if seq[i] == 'G' or seq[i] == 'C': gc_count += 1
# print(i, seq[s:s+w], gc_count)
# s += 1
# gc_count = 0 #resets GC count within 11-nt window back to 0 after each loop
#for i in range(s, len(seq)-w+1): #works, but pretty sure method is wrong
# if seq[i] == 'G' or seq[i] == 'C': gc_count += 1
# if seq[i+1] == 'G' or seq[i+1] == 'C': gc_count += 1
# if seq[i+2] == 'G' or seq[i+2] == 'C': gc_count += 1
# if seq[i+3] == 'G' or seq[i+3] == 'C': gc_count += 1
# if seq[i+4] == 'G' or seq[i+4] == 'C': gc_count += 1
# if seq[i+5] == 'G' or seq[i+5] == 'C': gc_count += 1
# if seq[i+6] == 'G' or seq[i+6] == 'C': gc_count += 1
# if seq[i+7] == 'G' or seq[i+7] == 'C': gc_count += 1
# if seq[i+8] == 'G' or seq[i+8] == 'C': gc_count += 1
# if seq[i+9] == 'G' or seq[i+9] == 'C': gc_count += 1
# if seq[i+10] == 'G' or seq[i+10] == 'C': gc_count += 1
# gc_frac = gc_count/w
# print('%d %s %.4f' % (i, seq[s:s+w], gc_frac))
# s += 1
# gc_count = 0 #resets GC count within 11-nt window back to 0 after each loop
"""
0 ACGACGCAGGA 0.6364
1 CGACGCAGGAG 0.7273
2 GACGCAGGAGG 0.7273
3 ACGCAGGAGGA 0.6364
4 CGCAGGAGGAG 0.7273
5 GCAGGAGGAGA 0.6364
6 CAGGAGGAGAG 0.6364
7 AGGAGGAGAGT 0.5455
8 GGAGGAGAGTT 0.5455
9 GAGGAGAGTTT 0.4545
10 AGGAGAGTTTC 0.4545
11 GGAGAGTTTCA 0.4545
12 GAGAGTTTCAG 0.4545
13 AGAGTTTCAGA 0.3636
14 GAGTTTCAGAG 0.4545
15 AGTTTCAGAGA 0.3636
16 GTTTCAGAGAT 0.3636
17 TTTCAGAGATC 0.3636
18 TTCAGAGATCA 0.3636
19 TCAGAGATCAC 0.4545
20 CAGAGATCACG 0.5455
21 AGAGATCACGA 0.4545
22 GAGATCACGAA 0.4545
23 AGATCACGAAT 0.3636
24 GATCACGAATA 0.3636
25 ATCACGAATAC 0.3636
26 TCACGAATACA 0.3636
27 CACGAATACAT 0.3636
28 ACGAATACATC 0.3636
29 CGAATACATCC 0.4545
30 GAATACATCCA 0.3636
31 AATACATCCAT 0.2727
32 ATACATCCATA 0.2727
33 TACATCCATAT 0.2727
34 ACATCCATATT 0.2727
35 CATCCATATTA 0.2727
36 ATCCATATTAC 0.2727
37 TCCATATTACC 0.3636
38 CCATATTACCC 0.4545
39 CATATTACCCA 0.3636
40 ATATTACCCAG 0.3636
41 TATTACCCAGA 0.3636
42 ATTACCCAGAG 0.4545
43 TTACCCAGAGA 0.4545
44 TACCCAGAGAG 0.5455
45 ACCCAGAGAGA 0.5455
46 CCCAGAGAGAG 0.6364
"""
| 30.371681
| 84
| 0.623543
|
4a0b72af24f04ace53d3d7ad7d97cc5957363430
| 95
|
py
|
Python
|
feedback-collector/main.py
|
mertmsrli/astair
|
fef832473884196025e727dd4d91e3b841d1eb92
|
[
"Apache-2.0"
] | 7
|
2019-08-20T12:14:12.000Z
|
2021-09-13T11:19:48.000Z
|
feedback-collector/main.py
|
mertmsrli/astair
|
fef832473884196025e727dd4d91e3b841d1eb92
|
[
"Apache-2.0"
] | 7
|
2020-03-01T07:44:10.000Z
|
2022-02-26T16:48:36.000Z
|
feedback-collector/main.py
|
mertmsrli/astair
|
fef832473884196025e727dd4d91e3b841d1eb92
|
[
"Apache-2.0"
] | 9
|
2019-06-25T04:45:00.000Z
|
2020-05-15T22:48:15.000Z
|
import os
from app import app
if __name__ == '__main__':
app.debug = True
app.run()
| 10.555556
| 26
| 0.631579
|
4a0b749e3c03a81de39b3f7ccdee6dfecb8e95ac
| 188
|
py
|
Python
|
{{cookiecutter.project_slug}}/{{cookiecutter.app_name_slug}}/apps.py
|
Alurith/django-cookiecutter
|
ce969b48c5d1b40bbcd3de6b6f286cb6a3c3a9d0
|
[
"MIT"
] | 1
|
2022-03-30T08:05:35.000Z
|
2022-03-30T08:05:35.000Z
|
{{cookiecutter.project_slug}}/{{cookiecutter.app_name_slug}}/apps.py
|
Alurith/django-cookiecutter
|
ce969b48c5d1b40bbcd3de6b6f286cb6a3c3a9d0
|
[
"MIT"
] | 2
|
2022-03-25T20:51:13.000Z
|
2022-03-25T20:56:41.000Z
|
{{cookiecutter.project_slug}}/{{cookiecutter.app_name_slug}}/apps.py
|
Alurith/django-cookiecutter
|
ce969b48c5d1b40bbcd3de6b6f286cb6a3c3a9d0
|
[
"MIT"
] | null | null | null |
from django.apps import AppConfig
class {{cookiecutter.app_class}}Config(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = '{{cookiecutter.app_name_slug}}'
| 26.857143
| 56
| 0.760638
|
4a0b74f010b680591dda530941936fb13f788128
| 11,195
|
py
|
Python
|
codehint/tests/test_codehint.py
|
ipazc/codehint
|
47399f46986b3bacc573a188028b4dc6c234d42a
|
[
"MIT"
] | 1
|
2017-11-13T16:15:17.000Z
|
2017-11-13T16:15:17.000Z
|
codehint/tests/test_codehint.py
|
ipazc/codehint
|
47399f46986b3bacc573a188028b4dc6c234d42a
|
[
"MIT"
] | null | null | null |
codehint/tests/test_codehint.py
|
ipazc/codehint
|
47399f46986b3bacc573a188028b4dc6c234d42a
|
[
"MIT"
] | null | null | null |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
#MIT License
#
#Copyright (c) 2017 Iván de Paz Centeno
#
#Permission is hereby granted, free of charge, to any person obtaining a copy
#of this software and associated documentation files (the "Software"), to deal
#in the Software without restriction, including without limitation the rights
#to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#copies of the Software, and to permit persons to whom the Software is
#furnished to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in all
#copies or substantial portions of the Software.
#
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
#SOFTWARE.
import unittest
from codehint import hint
__author__ = 'Iván de Paz Centeno'
class TestCodehint(unittest.TestCase):
"""
Unitary tests for the codehint class.
"""
def test_description_on_simple_funcs(self):
"""
Description on simple functions without params works as expected
"""
def simple_func():
return 2
truth = """------------------------
def simple_func():
=== Parameters: 0 ======
========================
Result (type Any) ->
"""
self.assertEqual(hint(simple_func, do_print=False), truth)
def test_description_on_simple_funcs_with_params(self):
"""
Description on simple functions with params works as expected
"""
def simple_func1(a):
return 2
def simple_func2(a, b):
return 2
truth_func1 = """------------------------
def simple_func1(a):
=== Parameters: 1 ======
[0] a (type Any) -> Not provided
========================
Result (type Any) ->
"""
self.assertEqual(hint(simple_func1, do_print=False), truth_func1)
truth_func2 = """------------------------
def simple_func2(a, b):
=== Parameters: 2 ======
[0] a (type Any) -> Not provided
[1] b (type Any) -> Not provided
========================
Result (type Any) ->
"""
self.assertEqual(hint(simple_func2, do_print=False), truth_func2)
def test_description_on_funcs_with_doc_params(self):
"""
Description on functions with documented params works as expected
"""
def func1(a):
"""
:param a: Parameter a, to test the retrieval of the docs.
"""
return 2
def func2(a, b):
"""
:param a: Parameter a, to test the retrieval of the docs.
:param b: Parameter b, to test the retrieval of the docs (again).
"""
return 2
truth_func1 = """------------------------
def func1(a):
=== Parameters: 1 ======
[0] a (type Any) -> Parameter a, to test the retrieval of the docs.
========================
Result (type Any) ->
"""
self.assertEqual(hint(func1, do_print=False), truth_func1)
truth_func2 = """------------------------
def func2(a, b):
=== Parameters: 2 ======
[0] a (type Any) -> Parameter a, to test the retrieval of the docs.
[1] b (type Any) -> Parameter b, to test the retrieval of the docs (again).
========================
Result (type Any) ->
"""
self.assertEqual(hint(func2, do_print=False), truth_func2)
def test_description_on_funcs_with_doc_params_and_documented_return_and_main(self):
"""
Description on functions with documented params, main description and return description works as expected
"""
def func1(a):
"""
:param a: Parameter a, to test the retrieval of the docs.
:return: True in case FOO. False otherwise.
"""
return 2
def func2(a):
"""
This is the main description of the func2.
:param a: Parameter a, to test the retrieval of the docs.
"""
return 2
def func3(a):
"""
This is the main description of the func3.
:param a: Parameter a, to test the retrieval of the docs.
:return: True if it is working, false otherwise.
"""
return 2
truth_func1 = """------------------------
def func1(a):
=== Parameters: 1 ======
[0] a (type Any) -> Parameter a, to test the retrieval of the docs.
========================
Result (type Any) -> True in case FOO. False otherwise.
"""
self.assertEqual(hint(func1, do_print=False), truth_func1)
truth_func2 = """------------------------
def func2(a):
This is the main description of the func2.
=== Parameters: 1 ======
[0] a (type Any) -> Parameter a, to test the retrieval of the docs.
========================
Result (type Any) ->
"""
self.assertEqual(hint(func2, do_print=False), truth_func2)
truth_func3 = """------------------------
def func3(a):
This is the main description of the func3.
=== Parameters: 1 ======
[0] a (type Any) -> Parameter a, to test the retrieval of the docs.
========================
Result (type Any) -> True if it is working, false otherwise.
"""
self.assertEqual(hint(func3, do_print=False), truth_func3)
def test_description_on_funcs_with_doc_and_types_params_and_documented(self):
"""
Description on functions with documented params (with also Types) works as expected.
"""
def func1(a:int):
"""
:param a: Parameter a, to test the retrieval of the docs.
"""
return 2
def func2(a, b:str):
"""
This is the main description of the func2.
:param a: Parameter a, to test the retrieval of the docs.
:param b: Parameter b, to test the retrieval of the docs.
"""
return 2
def func3(a:list, b:str):
"""
This is the main description of the func3.
:param b: Parameter b, to test the retrieval of the docs.
"""
return 2
def func4(a:list, b:str) -> dict:
"""
This is the main description of the func4.
:param b: Parameter b, to test the retrieval of the docs.
:return: dict result
"""
return 2
truth_func1 = """------------------------
def func1(a:int):
=== Parameters: 1 ======
[0] a (type int) -> Parameter a, to test the retrieval of the docs.
========================
Result (type Any) ->
"""
self.assertEqual(hint(func1, do_print=False), truth_func1)
truth_func2 = """------------------------
def func2(a, b:str):
This is the main description of the func2.
=== Parameters: 2 ======
[0] a (type Any) -> Parameter a, to test the retrieval of the docs.
[1] b (type str) -> Parameter b, to test the retrieval of the docs.
========================
Result (type Any) ->
"""
self.assertEqual(hint(func2, do_print=False), truth_func2)
truth_func3 = """------------------------
def func3(a:list, b:str):
This is the main description of the func3.
=== Parameters: 2 ======
[0] a (type list) -> Not provided
[1] b (type str) -> Parameter b, to test the retrieval of the docs.
========================
Result (type Any) ->
"""
self.assertEqual(hint(func3, do_print=False), truth_func3)
truth_func4 = """------------------------
def func4(a:list, b:str) -> dict:
This is the main description of the func4.
=== Parameters: 2 ======
[0] a (type list) -> Not provided
[1] b (type str) -> Parameter b, to test the retrieval of the docs.
========================
Result (type dict) -> dict result
"""
self.assertEqual(hint(func4, do_print=False), truth_func4)
def test_multilines_descriptions(self):
"""
Multi-line descriptions on functions works as expected.
"""
def func1():
"""
this is a multiline
document for the
func1. AKA Main description.
"""
return 2
def func2(a):
"""
this is a multiline
document for the
func2. AKA Main description.
:param a: this is a multiline description
for parameter a. Right?
"""
def func3(a, b):
"""
this is a multiline
document for the
func3. AKA Main description.
:param a: this is a multiline description
for parameter a. Right?
:param b: this is a multiline description
for parameter b. Right?
"""
return 2
def func4(a, b):
"""
this is a multiline
document for the
func4. AKA Main description.
:param a: this is a multiline description
for parameter a. Right?
:param b: this is a multiline description
for parameter b. Right?
:return: this is true in any case,
false otherwise, since this is in a second line.
"""
return 2
truth_func1 = """------------------------
def func1():
this is a multiline document for the func1. AKA Main description.
=== Parameters: 0 ======
========================
Result (type Any) ->
"""
self.assertEqual(hint(func1, do_print=False), truth_func1)
truth_func2 = """------------------------
def func2(a):
this is a multiline document for the func2. AKA Main description.
=== Parameters: 1 ======
[0] a (type Any) -> this is a multiline description for parameter a. Right?
========================
Result (type Any) ->
"""
self.assertEqual(hint(func2, do_print=False), truth_func2)
truth_func3 = """------------------------
def func3(a, b):
this is a multiline document for the func3. AKA Main description.
=== Parameters: 2 ======
[0] a (type Any) -> this is a multiline description for parameter a. Right?
[1] b (type Any) -> this is a multiline description for parameter b. Right?
========================
Result (type Any) ->
"""
self.assertEqual(hint(func3, do_print=False), truth_func3)
truth_func4 = """------------------------
def func4(a, b):
this is a multiline document for the func4. AKA Main description.
=== Parameters: 2 ======
[0] a (type Any) -> this is a multiline description for parameter a. Right?
[1] b (type Any) -> this is a multiline description for parameter b. Right?
========================
Result (type Any) -> this is true in any case, false otherwise, since this is in a second line.
"""
self.assertEqual(hint(func4, do_print=False), truth_func4)
if __name__ == '__main__':
unittest.main()
| 30.504087
| 114
| 0.556498
|
4a0b756a59ec4549912a06d942d592e56afe11bc
| 24,600
|
py
|
Python
|
milvus_cli/utils.py
|
shiyu22/milvus_cli
|
cd38ad46f187e07490c0949fb94d1704e5dfb1b9
|
[
"Apache-2.0"
] | 18
|
2021-08-20T10:15:08.000Z
|
2022-03-26T06:40:24.000Z
|
milvus_cli/utils.py
|
shiyu22/milvus_cli
|
cd38ad46f187e07490c0949fb94d1704e5dfb1b9
|
[
"Apache-2.0"
] | 25
|
2021-08-23T02:02:32.000Z
|
2021-12-13T07:18:54.000Z
|
milvus_cli/utils.py
|
shiyu22/milvus_cli
|
cd38ad46f187e07490c0949fb94d1704e5dfb1b9
|
[
"Apache-2.0"
] | 12
|
2021-08-25T12:04:04.000Z
|
2022-01-30T14:56:20.000Z
|
from tabulate import tabulate
import readline
import re
import os
from functools import reduce
from Types import DataTypeByNum
from Types import ParameterException, ConnectException
from time import time
def getPackageVersion():
import pkg_resources # part of setuptools
try:
version = pkg_resources.require("milvus_cli")[0].version
except Exception as e:
raise ParameterException(
"Could not get version under single executable file mode."
)
return version
def checkEmpty(x):
return not not x
def getMilvusTimestamp(isSimilar=True):
ts = time()
if isSimilar:
return int(ts) << 18
class PyOrm(object):
host = "127.0.0.1"
port = 19530
alias = "default"
def connect(self, alias=None, host=None, port=None, disconnect=False):
self.alias = alias
self.host = host
self.port = port
from pymilvus import connections
if disconnect:
connections.disconnect(alias)
return
connections.connect(self.alias, host=self.host, port=self.port)
def checkConnection(self):
from pymilvus import list_collections
try:
list_collections(timeout=10.0, using=self.alias)
except Exception as e:
raise ConnectException(f"Connect to Milvus error!{str(e)}")
def showConnection(self, alias="default", showAll=False):
from pymilvus import connections
tempAlias = self.alias if self.alias else alias
allConnections = connections.list_connections()
if showAll:
return tabulate(
allConnections, headers=["Alias", "Instance"], tablefmt="pretty"
)
aliasList = map(lambda x: x[0], allConnections)
if tempAlias in aliasList:
host, port = connections.get_connection_addr(tempAlias).values()
# return """Host: {}\nPort: {}\nAlias: {}""".format(host, port, alias)
return tabulate(
[["Host", host], ["Port", port], ["Alias", tempAlias]],
tablefmt="pretty",
)
else:
return "Connection not found!"
def _list_collection_names(self, timeout=None):
from pymilvus import list_collections
return list(list_collections(timeout, self.alias))
def _list_partition_names(self, collectionName):
target = self.getTargetCollection(collectionName)
result = target.partitions
return [i.name for i in result]
def _list_field_names(self, collectionName, showVectorOnly=False):
target = self.getTargetCollection(collectionName)
result = target.schema.fields
if showVectorOnly:
return reduce(
lambda x, y: x + [y.name] if y.dtype in [100, 101] else x, result, []
)
return [i.name for i in result]
def _list_index(self, collectionName):
target = self.getTargetCollection(collectionName)
try:
result = target.index()
except Exception as e:
return {}
else:
details = {
"field_name": result.field_name,
"index_type": result.params["index_type"],
"metric_type": result.params["metric_type"],
"params": result.params["params"],
}
# for p in result.params['params']:
# details[p] = result.params['params'][p]
return details
def listCollections(self, timeout=None, showLoadedOnly=False):
result = []
collectionNames = self._list_collection_names(timeout)
for name in collectionNames:
loadingProgress = self.showCollectionLoadingProgress(name)
loaded, total = loadingProgress.values()
# isLoaded = (total > 0) and (loaded == total)
# shouldBeAdded = isLoaded if showLoadedOnly else True
# if shouldBeAdded:
result.append([name, "{}/{}".format(loaded, total)])
return tabulate(
result,
headers=["Collection Name", "Entities(Loaded/Total)"],
tablefmt="grid",
showindex=True,
)
def flushCollectionByNumEntities(self, collectionName):
col = self.getTargetCollection(collectionName)
return col.num_entities
def showCollectionLoadingProgress(self, collectionName, partition_names=None):
from pymilvus import loading_progress
self.flushCollectionByNumEntities(collectionName)
return loading_progress(collectionName, partition_names, self.alias)
def showIndexBuildingProgress(self, collectionName, index_name=""):
from pymilvus import index_building_progress
return index_building_progress(collectionName, index_name, self.alias)
def getTargetCollection(self, collectionName):
from pymilvus import Collection
try:
target = Collection(collectionName)
except Exception as e:
raise ParameterException("Collection error!\n")
else:
return target
def getTargetPartition(self, collectionName, partitionName):
try:
targetCollection = self.getTargetCollection(collectionName)
target = targetCollection.partition(partitionName)
except Exception as e:
raise ParameterException("Partition error!\n")
else:
return target
def loadCollection(self, collectionName):
target = self.getTargetCollection(collectionName)
target.load()
result = self.showCollectionLoadingProgress(collectionName)
return tabulate(
[
[
collectionName,
result.get("num_loaded_entities"),
result.get("num_total_entities"),
]
],
headers=["Collection Name", "Loaded", "Total"],
tablefmt="grid",
)
def releaseCollection(self, collectionName):
target = self.getTargetCollection(collectionName)
target.release()
result = self.showCollectionLoadingProgress(collectionName)
return tabulate(
[
[
collectionName,
result.get("num_loaded_entities"),
result.get("num_total_entities"),
]
],
headers=["Collection Name", "Loaded", "Total"],
tablefmt="grid",
)
def releasePartition(self, collectionName, partitionName):
targetPartition = self.getTargetPartition(collectionName, partitionName)
targetPartition.release()
result = self.showCollectionLoadingProgress(collectionName, [partitionName])
return result
def releasePartitions(self, collectionName, partitionNameList):
result = []
for name in partitionNameList:
tmp = self.releasePartition(collectionName, name)
result.append(
[name, tmp.get("num_loaded_entities"), tmp.get("num_total_entities")]
)
return tabulate(
result, headers=["Partition Name", "Loaded", "Total"], tablefmt="grid"
)
def loadPartition(self, collectionName, partitionName):
targetPartition = self.getTargetPartition(collectionName, partitionName)
targetPartition.load()
result = self.showCollectionLoadingProgress(collectionName, [partitionName])
return result
def loadPartitions(self, collectionName, partitionNameList):
result = []
for name in partitionNameList:
tmp = self.loadPartition(collectionName, name)
result.append(
[name, tmp.get("num_loaded_entities"), tmp.get("num_total_entities")]
)
return tabulate(
result, headers=["Partition Name", "Loaded", "Total"], tablefmt="grid"
)
def listPartitions(self, collectionName):
target = self.getTargetCollection(collectionName)
result = target.partitions
rows = list(map(lambda x: [x.name, x.description], result))
return tabulate(
rows,
headers=["Partition Name", "Description"],
tablefmt="grid",
showindex=True,
)
def listIndexes(self, collectionName):
target = self.getTargetCollection(collectionName)
result = target.indexes
rows = list(
map(
lambda x: [
x.field_name,
x.params["index_type"],
x.params["metric_type"],
x.params["params"]["nlist"],
],
result,
)
)
return tabulate(
rows,
headers=["Field Name", "Index Type", "Metric Type", "Nlist"],
tablefmt="grid",
showindex=True,
)
def getCollectionDetails(self, collectionName="", collection=None):
try:
target = collection or self.getTargetCollection(collectionName)
except Exception as e:
return "Error!\nPlease check your input collection name."
rows = []
schema = target.schema
partitions = target.partitions
indexes = target.indexes
fieldSchemaDetails = ""
for fieldSchema in schema.fields:
_name = f"{'*' if fieldSchema.is_primary else ''}{fieldSchema.name}"
_type = DataTypeByNum[fieldSchema.dtype]
_desc = fieldSchema.description
_params = fieldSchema.params
_dim = _params.get("dim")
_params_desc = f"dim: {_dim}" if _dim else ""
fieldSchemaDetails += f"\n - {_name} {_type} {_params_desc} {_desc}"
schemaDetails = """Description: {}\n\nAuto ID: {}\n\nFields(* is the primary field):{}""".format(
schema.description, schema.auto_id, fieldSchemaDetails
)
partitionDetails = " - " + "\n- ".join(map(lambda x: x.name, partitions))
indexesDetails = " - " + "\n- ".join(map(lambda x: x.field_name, indexes))
rows.append(["Name", target.name])
rows.append(["Description", target.description])
rows.append(["Is Empty", target.is_empty])
rows.append(["Entities", target.num_entities])
rows.append(["Primary Field", target.primary_field.name])
rows.append(["Schema", schemaDetails])
rows.append(["Partitions", partitionDetails])
rows.append(["Indexes", indexesDetails])
return tabulate(rows, tablefmt="grid")
def getPartitionDetails(self, collection, partitionName=""):
partition = collection.partition(partitionName)
if not partition:
return "No such partition!"
rows = []
rows.append(["Partition Name", partition.name])
rows.append(["Description", partition.description])
rows.append(["Is empty", partition.is_empty])
rows.append(["Number of Entities", partition.num_entities])
return tabulate(rows, tablefmt="grid")
def getIndexDetails(self, collection):
index = collection.index()
if not index:
return "No index!"
rows = []
rows.append(["Corresponding Collection", index.collection_name])
rows.append(["Corresponding Field", index.field_name])
rows.append(["Index Type", index.params["index_type"]])
rows.append(["Metric Type", index.params["metric_type"]])
params = index.params["params"]
paramsDetails = "\n- ".join(map(lambda k: f"{k[0]}: {k[1]}", params.items()))
rows.append(["Params", paramsDetails])
return tabulate(rows, tablefmt="grid")
def createCollection(
self, collectionName, primaryField, autoId, description, fields
):
from pymilvus import Collection, DataType, FieldSchema, CollectionSchema
fieldList = []
for field in fields:
[fieldName, fieldType, fieldData] = field.split(":")
isVector = False
if fieldType in ["BINARY_VECTOR", "FLOAT_VECTOR"]:
fieldList.append(
FieldSchema(
name=fieldName, dtype=DataType[fieldType], dim=int(fieldData)
)
)
else:
fieldList.append(
FieldSchema(
name=fieldName, dtype=DataType[fieldType], description=fieldData
)
)
schema = CollectionSchema(
fields=fieldList,
primary_field=primaryField,
auto_id=autoId,
description=description,
)
collection = Collection(name=collectionName, schema=schema)
return self.getCollectionDetails(collection=collection)
def createPartition(self, collectionName, description, partitionName):
collection = self.getTargetCollection(collectionName)
collection.create_partition(partitionName, description=description)
return self.getPartitionDetails(collection, partitionName)
def createIndex(
self, collectionName, fieldName, indexType, metricType, params, timeout
):
collection = self.getTargetCollection(collectionName)
indexParams = {}
for param in params:
paramList = param.split(":")
[paramName, paramValue] = paramList
indexParams[paramName] = int(paramValue)
index = {
"index_type": indexType,
"params": indexParams,
"metric_type": metricType,
}
collection.create_index(fieldName, index, timeout=timeout)
return self.getIndexDetails(collection)
def isCollectionExist(self, collectionName):
from pymilvus import has_collection
return has_collection(collectionName, using=self.alias)
def isPartitionExist(self, collection, partitionName):
return collection.has_partition(partitionName)
def isIndexExist(self, collection):
return collection.has_index()
def dropCollection(self, collectionName, timeout):
collection = self.getTargetCollection(collectionName)
collection.drop(timeout=timeout)
return self.isCollectionExist(collectionName)
def dropPartition(self, collectionName, partitionName, timeout):
collection = self.getTargetCollection(collectionName)
collection.drop_partition(partitionName, timeout=timeout)
return self.isPartitionExist(collection, partitionName)
def dropIndex(self, collectionName, timeout):
collection = self.getTargetCollection(collectionName)
collection.drop_index(timeout=timeout)
return self.isIndexExist(collection)
def search(self, collectionName, searchParameters, prettierFormat=True):
collection = self.getTargetCollection(collectionName)
collection.load()
res = collection.search(**searchParameters)
if not prettierFormat:
return res
# hits = res[0]
results = []
for hits in res:
results += [
tabulate(
map(lambda x: [x.id, x.distance, x.score], hits),
headers=["Index", "ID", "Distance", "Score"],
tablefmt="grid",
showindex=True,
)
]
# return tabulate(map(lambda x: [x.id, x.distance], hits), headers=['Index', 'ID', 'Distance'], tablefmt='grid', showindex=True)
return results
def query(self, collectionName, queryParameters):
collection = self.getTargetCollection(collectionName)
collection.load()
res = collection.query(**queryParameters)
# return f"- Query results: {res}"
if not len(res):
return f"- Query results: {res}"
headers = [i for i in res[0]]
return tabulate(
[[_[i] for i in _] for _ in res],
headers=headers,
tablefmt="grid",
showindex=True,
)
def insert(self, collectionName, data, partitionName=None, timeout=None):
collection = self.getTargetCollection(collectionName)
result = collection.insert(data, partition_name=partitionName, timeout=timeout)
entitiesNum = collection.num_entities
return [result, entitiesNum]
def importData(self, collectionName, data, partitionName=None, timeout=None):
[result, entitiesNum] = self.insert(
collectionName, data, partitionName, timeout
)
insert_count = result.insert_count
timestamp = result.timestamp
prettierResult = []
prettierResult.append(["Total insert entities: ", insert_count])
prettierResult.append(["Total collection entities: ", entitiesNum])
prettierResult.append(["Milvus timestamp: ", timestamp])
return tabulate(prettierResult)
def calcDistance(self, vectors_left, vectors_right, params=None, timeout=None):
from pymilvus import utility
result = utility.calc_distance(
vectors_left, vectors_right, params, timeout, using=self.alias
)
return result
def deleteEntities(self, expr, collectionName, partition_name=None, timeout=None):
collection = self.getTargetCollection(collectionName)
result = collection.delete(expr, partition_name=partition_name, timeout=timeout)
return result
def getQuerySegmentInfo(self, collectionName, timeout=None, prettierFormat=False):
from pymilvus import utility
result = utility.get_query_segment_info(
collectionName, timeout=timeout, using=self.alias
)
if not prettierFormat or not result:
return result
firstChild = result[0]
headers = ["segmentID", "collectionID", "partitionID", "mem_size", "num_rows"]
return tabulate(
[[getattr(_, i) for i in headers] for _ in result],
headers=headers,
showindex=True,
)
def createCollectionAlias(
self, collectionName, collectionAliasName="", timeout=None
):
collection = self.getTargetCollection(collectionName)
result = collection.create_alias(collectionAliasName, timeout=timeout)
return result
def dropCollectionAlias(self, collectionName, collectionAliasName="", timeout=None):
collection = self.getTargetCollection(collectionName)
result = collection.drop_alias(collectionAliasName, timeout=timeout)
return result
def alterCollectionAlias(
self, collectionName, collectionAliasName="", timeout=None
):
collection = self.getTargetCollection(collectionName)
result = collection.alter_alias(collectionAliasName, timeout=timeout)
return result
def createCollectionAliasList(self, collectionName, aliasList=[], timeout=None):
collection = self.getTargetCollection(collectionName)
result = []
for aliasItem in aliasList:
aliasResult = collection.create_alias(aliasItem, timeout=timeout)
result.append(aliasResult)
return result
def alterCollectionAliasList(self, collectionName, aliasList=[], timeout=None):
collection = self.getTargetCollection(collectionName)
result = []
for aliasItem in aliasList:
aliasResult = collection.alter_alias(aliasItem, timeout=timeout)
result.append(aliasResult)
return result
# def loadBalance(self, src_node_id, dst_node_ids, sealed_segment_ids, timeout=None):
# from pymilvus import utility
# utility.load_balance(src_node_id, dst_node_ids, sealed_segment_ids, timeout=timeout)
class Completer(object):
# COMMANDS = ['clear', 'connect', 'create', 'delete', 'describe', 'exit',
# 'list', 'load', 'query', 'release', 'search', 'show', 'version' ]
RE_SPACE = re.compile(".*\s+$", re.M)
CMDS_DICT = {
"calc": [],
"clear": [],
"connect": [],
"create": ["alias", "collection", "partition", "index"],
"delete": ["alias", "collection", "partition", "index"],
"describe": ["collection", "partition", "index"],
"exit": [],
"help": [],
"import": [],
"list": ["collections", "partitions", "indexes"],
"load": [],
"query": [],
"release": [],
"search": [],
"show": ["connection", "index_progress", "loading_progress", "query_segment"],
"version": [],
}
def __init__(self) -> None:
super().__init__()
self.COMMANDS = list(self.CMDS_DICT.keys())
self.createCompleteFuncs(self.CMDS_DICT)
def createCompleteFuncs(self, cmdDict):
for cmd in cmdDict:
sub_cmds = cmdDict[cmd]
complete_example = self.makeComplete(cmd, sub_cmds)
setattr(self, "complete_%s" % cmd, complete_example)
def makeComplete(self, cmd, sub_cmds):
def f_complete(args):
f"Completions for the {cmd} command."
if not args:
return self._complete_path(".")
if len(args) <= 1 and not cmd == "import":
return self._complete_2nd_level(sub_cmds, args[-1])
return self._complete_path(args[-1])
return f_complete
def _listdir(self, root):
"List directory 'root' appending the path separator to subdirs."
res = []
for name in os.listdir(root):
path = os.path.join(root, name)
if os.path.isdir(path):
name += os.sep
res.append(name)
return res
def _complete_path(self, path=None):
"Perform completion of filesystem path."
if not path:
return self._listdir(".")
dirname, rest = os.path.split(path)
tmp = dirname if dirname else "."
res = [
os.path.join(dirname, p) for p in self._listdir(tmp) if p.startswith(rest)
]
# more than one match, or single match which does not exist (typo)
if len(res) > 1 or not os.path.exists(path):
return res
# resolved to a single directory, so return list of files below it
if os.path.isdir(path):
return [os.path.join(path, p) for p in self._listdir(path)]
# exact file match terminates this completion
return [path + " "]
def _complete_2nd_level(self, SUB_COMMANDS=[], cmd=None):
if not cmd:
return [c + " " for c in SUB_COMMANDS]
res = [c for c in SUB_COMMANDS if c.startswith(cmd)]
if len(res) > 1 or not (cmd in SUB_COMMANDS):
return res
return [cmd + " "]
# def complete_create(self, args):
# "Completions for the 'create' command."
# if not args:
# return self._complete_path('.')
# sub_cmds = ['collection', 'partition', 'index']
# if len(args) <= 1:
# return self._complete_2nd_level(sub_cmds, args[-1])
# return self._complete_path(args[-1])
def complete(self, text, state):
"Generic readline completion entry point."
buffer = readline.get_line_buffer()
line = readline.get_line_buffer().split()
# show all commands
if not line:
return [c + " " for c in self.COMMANDS][state]
# account for last argument ending in a space
if self.RE_SPACE.match(buffer):
line.append("")
# resolve command to the implementation function
cmd = line[0].strip()
if cmd in self.COMMANDS:
impl = getattr(self, "complete_%s" % cmd)
args = line[1:]
if args:
return (impl(args) + [None])[state]
return [cmd + " "][state]
results = [c + " " for c in self.COMMANDS if c.startswith(cmd)] + [None]
return results[state]
WELCOME_MSG = """
__ __ _ _ ____ _ ___
| \/ (_) |_ ___ _ ___ / ___| | |_ _|
| |\/| | | \ \ / / | | / __| | | | | | |
| | | | | |\ V /| |_| \__ \ | |___| |___ | |
|_| |_|_|_| \_/ \__,_|___/ \____|_____|___|
Learn more: https://github.com/milvus-io/milvus_cli.
"""
EXIT_MSG = "\n\nThanks for using.\nWe hope your feedback: https://github.com/milvus-io/milvus_cli/issues/new.\n\n"
| 38.021638
| 136
| 0.601179
|
4a0b760b321c880e815e6c5ad003f4fc984b1c11
| 775
|
py
|
Python
|
basic/37-charm.fi/scripts/print_price.py
|
yingjingyang/Dapp-Learning
|
5bf10a02932926e429c1a61704d9a9dfee3a13ea
|
[
"MIT"
] | 987
|
2021-12-19T09:57:18.000Z
|
2022-03-31T15:39:45.000Z
|
basic/37-charm.fi/scripts/print_price.py
|
yingjingyang/Dapp-Learning
|
5bf10a02932926e429c1a61704d9a9dfee3a13ea
|
[
"MIT"
] | 73
|
2021-07-04T03:53:57.000Z
|
2021-12-18T06:17:13.000Z
|
basic/37-charm.fi/scripts/print_price.py
|
yingjingyang/Dapp-Learning
|
5bf10a02932926e429c1a61704d9a9dfee3a13ea
|
[
"MIT"
] | 263
|
2021-06-28T15:26:56.000Z
|
2021-12-19T08:14:37.000Z
|
from brownie import accounts, project
import time
POOL = "0x7858e59e0c01ea06df3af3d20ac7b0003275d4bf" # USDC / USDT / 0.05%
POOL = "0x6c6bc977e13df9b0de53b251522280bb72383700" # DAI / USDC / 0.05%
# POOL = "0x6f48eca74b38d2936b02ab603ff4e36a6c0e3a77" # DAI / USDT / 0.05%
SECONDS_AGO = 60
def main():
UniswapV3Core = project.load("Uniswap/uniswap-v3-core@1.0.0")
pool = UniswapV3Core.interface.IUniswapV3Pool(POOL)
while True:
(before, after), _ = pool.observe([SECONDS_AGO, 0])
twap = (after - before) / SECONDS_AGO
last = pool.slot0()[1]
print(f"twap\t{twap}\t{1.0001**twap}")
print(f"last\t{last}\t{1.0001**last}")
print(f"trend\t{last-twap}")
print()
time.sleep(max(SECONDS_AGO, 60))
| 28.703704
| 75
| 0.652903
|
4a0b76adbb7381da124cc5227a35b02ce530af81
| 3,787
|
py
|
Python
|
nova/network/neutronv2/__init__.py
|
vasart/nova
|
bca5004d367e0418e35f8a72fe0f2e106e977ab0
|
[
"Apache-2.0"
] | 1
|
2021-09-10T15:29:02.000Z
|
2021-09-10T15:29:02.000Z
|
nova/network/neutronv2/__init__.py
|
PFZheng/nova
|
84be8abbccb5ddc2d7c5a7db59019ed1edb19e7f
|
[
"Apache-2.0"
] | null | null | null |
nova/network/neutronv2/__init__.py
|
PFZheng/nova
|
84be8abbccb5ddc2d7c5a7db59019ed1edb19e7f
|
[
"Apache-2.0"
] | null | null | null |
# Copyright 2012 OpenStack Foundation
# All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from neutronclient.common import exceptions
from neutronclient.v2_0 import client as clientv20
from oslo.config import cfg
from nova.openstack.common import lockutils
from nova.openstack.common import log as logging
CONF = cfg.CONF
LOG = logging.getLogger(__name__)
class AdminTokenStore(object):
_instance = None
def __init__(self):
self.admin_auth_token = None
@classmethod
def get(cls):
if cls._instance is None:
cls._instance = cls()
return cls._instance
def _get_client(token=None, admin=False):
params = {
'endpoint_url': CONF.neutron.url,
'timeout': CONF.neutron.url_timeout,
'insecure': CONF.neutron.api_insecure,
'ca_cert': CONF.neutron.ca_certificates_file,
'auth_strategy': CONF.neutron.auth_strategy,
'token': token,
}
if admin:
params['username'] = CONF.neutron.admin_username
if CONF.neutron.admin_tenant_id:
params['tenant_id'] = CONF.neutron.admin_tenant_id
else:
params['tenant_name'] = CONF.neutron.admin_tenant_name
params['password'] = CONF.neutron.admin_password
params['auth_url'] = CONF.neutron.admin_auth_url
return clientv20.Client(**params)
class ClientWrapper(clientv20.Client):
'''A neutron client wrapper class.
Wraps the callable methods, executes it and updates the token,
as it might change when expires.
'''
def __init__(self, base_client):
# Expose all attributes from the base_client instance
self.__dict__ = base_client.__dict__
self.base_client = base_client
def __getattribute__(self, name):
obj = object.__getattribute__(self, name)
if callable(obj):
obj = object.__getattribute__(self, 'proxy')(obj)
return obj
def proxy(self, obj):
def wrapper(*args, **kwargs):
ret = obj(*args, **kwargs)
new_token = self.base_client.get_auth_info()['auth_token']
_update_token(new_token)
return ret
return wrapper
def _update_token(new_token):
with lockutils.lock('neutron_admin_auth_token_lock'):
token_store = AdminTokenStore.get()
token_store.admin_auth_token = new_token
def get_client(context, admin=False):
# NOTE(dprince): In the case where no auth_token is present
# we allow use of neutron admin tenant credentials if
# it is an admin context.
# This is to support some services (metadata API) where
# an admin context is used without an auth token.
if admin or (context.is_admin and not context.auth_token):
with lockutils.lock('neutron_admin_auth_token_lock'):
orig_token = AdminTokenStore.get().admin_auth_token
client = _get_client(orig_token, admin=True)
return ClientWrapper(client)
# We got a user token that we can use that as-is
if context.auth_token:
token = context.auth_token
return _get_client(token=token)
# We did not get a user token and we should not be using
# an admin token so log an error
raise exceptions.Unauthorized()
| 33.219298
| 78
| 0.684183
|
4a0b76dd505f31467e5ae4c32bf513145b1bbfc4
| 2,208
|
py
|
Python
|
task_server/lib/passwd.py
|
ipeterov/convenient-rpc
|
e0e7bb2a6fa99848fe319cf26e34d2ebf8558b2e
|
[
"MIT"
] | null | null | null |
task_server/lib/passwd.py
|
ipeterov/convenient-rpc
|
e0e7bb2a6fa99848fe319cf26e34d2ebf8558b2e
|
[
"MIT"
] | 19
|
2016-04-19T20:18:50.000Z
|
2016-05-04T20:55:53.000Z
|
task_server/lib/passwd.py
|
ipeterov/convenient-rpc
|
e0e7bb2a6fa99848fe319cf26e34d2ebf8558b2e
|
[
"MIT"
] | null | null | null |
import sqlite3
import uuid
import hashlib
from functools import wraps
from flask import request, Response
class PasswordManager:
def __init__(self, dbfile='rpc-passwords.db', sha256_rounds=1000000, pepper='2fde251d-33fd-42c8-bdd9-8ac7788d5f5a'):
self.sha256_rounds = sha256_rounds
self.pepper = pepper
self.conn = sqlite3.connect(dbfile, check_same_thread=False)
self.cursor = self.conn.cursor()
self.cursor.execute('CREATE TABLE IF NOT EXISTS passwords (username text, passhash blob, salt text)')
self.conn.commit()
def register(self, username, password):
self.cursor.execute('SELECT * FROM passwords WHERE username=?', (username,))
if self.cursor.fetchone():
raise UserPresentException()
salt = str(uuid.uuid4())
spice = salt + self.pepper
passhash = hashlib.pbkdf2_hmac('sha256', password.encode('utf-8'), spice.encode('utf-8'), self.sha256_rounds)
self.cursor.execute('INSERT INTO passwords VALUES (?, ?, ?)', (username, passhash, salt))
self.conn.commit()
def check_auth(self, username, password):
self.cursor.execute('SELECT * FROM passwords WHERE username=?', (username,))
entry = self.cursor.fetchone()
if entry:
username, passhash, salt = entry
spice = salt + self.pepper
return passhash == hashlib.pbkdf2_hmac('sha256', password.encode('utf-8'), spice.encode('utf-8'), self.sha256_rounds)
else:
return False
def requires_auth(self, f):
@wraps(f)
def decorated(*args, **kwargs):
auth = request.authorization
if not auth or not self.check_auth(auth.username, auth.password):
return self.authenticate()
return f(*args, **kwargs)
return decorated
@staticmethod
def authenticate():
"""Sends a 401 response that enables basic auth"""
return Response(
'Could not verify your access level for that URL.\n'
'You have to login with proper credentials', 401,
{'WWW-Authenticate': 'Basic realm="Login Required"'})
class UserPresentException(Exception):
pass
| 36.196721
| 129
| 0.643569
|
4a0b76ebfb66c9a5df286de26096619a4acd1392
| 3,471
|
py
|
Python
|
pesto-cli/pesto/cli/app.py
|
fchouteau/pesto
|
32cac6658cfe0fe0db636b2d9e75b10a05282bca
|
[
"Apache-2.0"
] | null | null | null |
pesto-cli/pesto/cli/app.py
|
fchouteau/pesto
|
32cac6658cfe0fe0db636b2d9e75b10a05282bca
|
[
"Apache-2.0"
] | null | null | null |
pesto-cli/pesto/cli/app.py
|
fchouteau/pesto
|
32cac6658cfe0fe0db636b2d9e75b10a05282bca
|
[
"Apache-2.0"
] | null | null | null |
import argparse
import os
from typing import Any
import pkg_resources
from pkg_resources import resource_string
from pesto.common.pesto import PESTO_WORKSPACE
from pesto.cli import build, init, list as list_builds, test
from pesto.cli.core.utils import PESTO_LOG
from pesto.version import PESTO_VERSION
ALGO_TEMPLATE_PATH = pkg_resources.get_provider('pesto.cli').__dict__['module_path'] + '/resources/template'
def display_banner() -> None:
processing_factory_banner = resource_string('pesto.cli.resources', 'banner.txt') \
.decode('utf-8') \
.replace(' ---------------', ': {:10s}----'.format(PESTO_VERSION))
PESTO_LOG.info(processing_factory_banner)
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(dest='subcommand', title='subcommands', help='Valid subcommands')
subparsers.required = True
# init
parser_init = subparsers.add_parser('init')
parser_init.add_argument('-t', '--template', help='path to the algorithm template', default=ALGO_TEMPLATE_PATH)
parser_init.add_argument('target', help='path to the new algorithm folder')
# build
parser_build = subparsers.add_parser('build')
parser_build.add_argument('build_config', help='path to build.json')
parser_build.add_argument('-p', '--profile', nargs='+', help='Select specific files to update',
default=None)
parser_build.add_argument('--proxy', help='Define a proxy url to use during docker construction',
default=None)
# test
parser_test = subparsers.add_parser('test')
parser_test.add_argument('build_config', help='path to build.json')
parser_test.add_argument('-p', '--profile', nargs='+', help='Select specific files to update',
default=None)
parser_test.add_argument('--nvidia', action='store_true', default=False, help='Run docker with nvidia-runtime')
# # list builds
# parser_list = subparsers.add_parser('list')
return parser.parse_args()
def main() -> None:
display_banner()
args = parse_args()
if args.subcommand == 'init':
init.init(args.target, args.template)
elif args.subcommand == 'build':
build.build(search_build_config(args), args.profile, args.proxy)
elif args.subcommand == 'test':
test.test(search_build_config(args), args.profile, nvidia=args.nvidia)
elif args.subcommand == 'list':
list_builds.list_builds(PESTO_WORKSPACE)
def search_build_config(args: Any) -> str:
build_config_path = str(args.build_config)
PESTO_LOG.debug('search build config ...')
if ':' in build_config_path:
PESTO_LOG.info('search {} in PESTO build repository : {}'.format(build_config_path, PESTO_WORKSPACE))
name, version = build_config_path.split(':')
build_config_path = os.path.join(PESTO_WORKSPACE, name, version, name)
if not build_config_path.endswith('.json'):
PESTO_LOG.warning('build parameter {} is not a json ...'.format(build_config_path))
build_config_path = os.path.join(build_config_path, 'pesto', 'build', 'build.json')
PESTO_LOG.warning('search for build.json in {}'.format(build_config_path))
if not os.path.exists(build_config_path):
raise ValueError('build.json not found at {}'.format(build_config_path))
return build_config_path
if __name__ == "__main__":
main()
| 38.142857
| 116
| 0.689139
|
4a0b778155f6fc8adf0d1e8b8d76ae9f609803cb
| 3,785
|
py
|
Python
|
dhis2_core/src/dhis2/code_list/svcm_resources.py
|
dhis2/dhis2-python-cli
|
d5ec976a5c04e6897756e3be14924ec74a4456fd
|
[
"BSD-3-Clause"
] | 7
|
2020-10-15T08:54:50.000Z
|
2021-12-19T14:37:49.000Z
|
dhis2_core/src/dhis2/code_list/svcm_resources.py
|
dhis2/dhis2-python-cli
|
d5ec976a5c04e6897756e3be14924ec74a4456fd
|
[
"BSD-3-Clause"
] | 3
|
2016-08-12T14:11:14.000Z
|
2021-03-08T17:06:29.000Z
|
dhis2_core/src/dhis2/code_list/svcm_resources.py
|
dhis2/dhis2-python-cli
|
d5ec976a5c04e6897756e3be14924ec74a4456fd
|
[
"BSD-3-Clause"
] | 4
|
2016-02-10T23:03:08.000Z
|
2020-12-28T13:18:49.000Z
|
import logging
from typing import List
from fhir.resources.bundle import Bundle, BundleEntry, BundleEntryRequest
from fhir.resources.codesystem import CodeSystem, CodeSystemConcept
from fhir.resources.identifier import Identifier
from fhir.resources.valueset import ValueSet, ValueSetCompose, ValueSetComposeInclude
from .models.svcm import CodeList
log = logging.getLogger(__name__)
def build_svcm_codesystem(code_list: CodeList, base_url: str) -> CodeSystem:
resource = CodeSystem()
resource.url = f"{base_url}/api/{code_list.type}/{code_list.id}/codeSystem"
resource.valueSet = f"{base_url}/api/{code_list.type}/{code_list.id}/valueSet"
resource.identifier = [Identifier()]
resource.identifier[0].system = f"{base_url}/api/{code_list.type}"
resource.identifier[0].value = code_list.id
if code_list.code:
identifier = Identifier()
identifier.system = f"{base_url}/api/{code_list.type}"
identifier.value = code_list.code
resource.identifier.append(identifier)
resource.publisher = base_url
resource.status = "active"
resource.content = "complete"
resource.version = str(code_list.version)
resource.name = code_list.name
resource.title = code_list.name
resource.description = code_list.name
resource.experimental = False
resource.caseSensitive = True
resource.concept = []
for code in code_list.codes:
concept = CodeSystemConcept()
resource.concept.append(concept)
concept.code = code.get("code")
concept.display = code.get("name")
concept.definition = code.get("name")
return resource
def build_svcm_valueset(code_list: CodeList, base_url: str) -> ValueSet:
resource = ValueSet()
resource.url = f"{base_url}/api/{code_list.type}/{code_list.id}/valueSet"
resource.identifier = [Identifier()]
resource.identifier[0].system = f"{base_url}/api/{code_list.type}"
resource.identifier[0].value = code_list.id
if code_list.code:
identifier = Identifier()
identifier.system = f"{base_url}/api/{code_list.type}"
identifier.value = code_list.code
resource.identifier.append(identifier)
resource.status = "active"
resource.version = str(code_list.version)
resource.name = code_list.name
resource.title = code_list.name
resource.description = code_list.name
resource.experimental = False
resource.immutable = True
resource.compose = ValueSetCompose()
resource.compose.include = [ValueSetComposeInclude()]
resource.compose.include[0].system = f"{base_url}/api/{code_list.type}/{code_list.id}/codeSystem"
return resource
def build_code_system_bundle_entry(code_list: CodeList, base_url: str) -> BundleEntry:
entry = BundleEntry()
entry.request = BundleEntryRequest()
entry.request.method = "PUT"
entry.request.url = f"CodeSystem?identifier={code_list.id}"
entry.resource = build_svcm_codesystem(code_list, base_url)
return entry
def build_value_set_bundle_entry(code_list: CodeList, base_url: str) -> BundleEntry:
entry = BundleEntry()
entry.request = BundleEntryRequest()
entry.request.method = "PUT"
entry.request.url = f"ValueSet?identifier={code_list.id}"
entry.resource = build_svcm_valueset(code_list, base_url)
return entry
def build_bundle(code_lists: List[CodeList], base_url: str) -> Bundle:
bundle = Bundle()
bundle.type = "transaction"
bundle.entry = []
log.info(f"Building FHIR bundle from '{len(code_lists)}' DHIS2 code lists")
for code_list in code_lists:
bundle.entry.append(build_value_set_bundle_entry(code_list, base_url))
bundle.entry.append(build_code_system_bundle_entry(code_list, base_url))
return bundle
| 32.350427
| 101
| 0.720211
|
4a0b77dbbceea169a61a692692b2468bca97f522
| 539
|
py
|
Python
|
Abstraction/Demo1.py
|
poojavaibhavsahu/Pooja_Python
|
58122bfa8586883145042b11fe1cc013c803ab4f
|
[
"bzip2-1.0.6"
] | null | null | null |
Abstraction/Demo1.py
|
poojavaibhavsahu/Pooja_Python
|
58122bfa8586883145042b11fe1cc013c803ab4f
|
[
"bzip2-1.0.6"
] | null | null | null |
Abstraction/Demo1.py
|
poojavaibhavsahu/Pooja_Python
|
58122bfa8586883145042b11fe1cc013c803ab4f
|
[
"bzip2-1.0.6"
] | null | null | null |
from abc import ABC,abstractmethod
class A(ABC):#makes a class abstract
@abstractmethod
def msg(self):
pass
def display(self):#non abstarct method
print("Hello display method")
class B(A):
def msg(self):
print("Hello msg called")
obj=B()
obj.msg()
obj.display()
# from abc import ABC,abstractmethod
#
# class A(ABC):
# @abstractmethod
# def msg(self): #abstract method
# pass
#
#
# class B(A):
# def msg(self):
# print("hi")
#
# obj=B()
# obj.msg()
| 10.365385
| 42
| 0.576994
|
4a0b78124d5eadccb0a305f5e73f88ee0c17ed40
| 180
|
py
|
Python
|
EasyVision/vision/exceptions.py
|
foxis/EasyVision
|
ffb2ce1a93fdace39c6bcc13c8ae518cec76919e
|
[
"MIT",
"BSD-3-Clause"
] | 7
|
2018-12-27T07:45:31.000Z
|
2021-06-17T03:49:15.000Z
|
EasyVision/vision/exceptions.py
|
itohio/EasyVision
|
de6a4bb9160cd08278ae9c5738497132a4cd3202
|
[
"MIT",
"BSD-3-Clause"
] | null | null | null |
EasyVision/vision/exceptions.py
|
itohio/EasyVision
|
de6a4bb9160cd08278ae9c5738497132a4cd3202
|
[
"MIT",
"BSD-3-Clause"
] | 3
|
2019-08-21T03:36:56.000Z
|
2021-10-08T16:12:53.000Z
|
# -*- coding: utf-8 -*-
"""Exceptions used for Vision capturing adapters.
"""
from EasyVision.exceptions import EasyVisionError
class DeviceNotFound(EasyVisionError):
pass
| 16.363636
| 49
| 0.738889
|
4a0b78ebd87be2f7414033047c09a1453033c1e7
| 1,381
|
py
|
Python
|
firmware/uvc_controller/mbed-os/tools/host_tests/serial_complete_auto.py
|
davewhiiite/uvc
|
fd45223097eed5a824294db975b3c74aa5f5cc8f
|
[
"MIT"
] | 1
|
2021-06-12T14:54:07.000Z
|
2021-06-12T14:54:07.000Z
|
firmware/uvc_controller/mbed-os/tools/host_tests/serial_complete_auto.py
|
davewhiiite/uvc
|
fd45223097eed5a824294db975b3c74aa5f5cc8f
|
[
"MIT"
] | null | null | null |
firmware/uvc_controller/mbed-os/tools/host_tests/serial_complete_auto.py
|
davewhiiite/uvc
|
fd45223097eed5a824294db975b3c74aa5f5cc8f
|
[
"MIT"
] | null | null | null |
"""
mbed SDK
Copyright (c) 2011-2013 ARM Limited
SPDX-License-Identifier: Apache-2.0
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import sys
import uuid
import time
import string
from sys import stdout
class SerialCompleteTest(object):
def test(self, selftest):
strip_chars = string.whitespace + "\0"
out_str = selftest.mbed.serial_readline()
selftest.notify("HOST: " + out_str)
if not out_str:
selftest.notify("HOST: No output detected")
return selftest.RESULT_IO_SERIAL
out_str_stripped = out_str.strip(strip_chars)
if out_str_stripped != "123456789":
selftest.notify("HOST: Unexpected output. '123456789' Expected. but received '%s'" % out_str_stripped)
return selftest.RESULT_FAILURE
else:
return selftest.RESULT_SUCCESS
| 30.688889
| 115
| 0.692252
|
4a0b790ae1e8b24632de8359ec773d6ef6a85a81
| 657
|
py
|
Python
|
LeetCode_problems/count-good-triplets/Solution.py
|
gbrls/CompetitiveCode
|
b6f1b817a655635c3c843d40bd05793406fea9c6
|
[
"MIT"
] | 165
|
2020-10-03T08:01:11.000Z
|
2022-03-31T02:42:08.000Z
|
LeetCode_problems/count-good-triplets/Solution.py
|
gbrls/CompetitiveCode
|
b6f1b817a655635c3c843d40bd05793406fea9c6
|
[
"MIT"
] | 383
|
2020-10-03T07:39:11.000Z
|
2021-11-20T07:06:35.000Z
|
LeetCode_problems/count-good-triplets/Solution.py
|
gbrls/CompetitiveCode
|
b6f1b817a655635c3c843d40bd05793406fea9c6
|
[
"MIT"
] | 380
|
2020-10-03T08:05:04.000Z
|
2022-03-19T06:56:59.000Z
|
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 5 2020
@author: Shrey1608
"""
# Approach : 1) using 3 loops for checking the condition(Time complexity O(n^3)| space complexity O(1))
# Solution:(Approach 1)
class Solution:
def countGoodTriplets(self, arr: List[int], a: int, b: int, c: int) -> int:
n=len(arr)
count=0
for i in range(n-2):
for j in range(i+1,n-1):
if (abs(arr[i] - arr[j]) > a):
continue
for k in range(j+1,n):
if (abs(arr[j] - arr[k]) <= b and abs(arr[i] - arr[k]) <= c):
count+=1
return count
| 28.565217
| 103
| 0.493151
|
4a0b79f38746c8e72d3db11000eee4ac7555117b
| 162
|
py
|
Python
|
scripts/hello.py
|
martimfj/dev_aberto_package
|
4ec26b16bdfdafc5fe7359376d26edf88512554e
|
[
"MIT"
] | null | null | null |
scripts/hello.py
|
martimfj/dev_aberto_package
|
4ec26b16bdfdafc5fe7359376d26edf88512554e
|
[
"MIT"
] | null | null | null |
scripts/hello.py
|
martimfj/dev_aberto_package
|
4ec26b16bdfdafc5fe7359376d26edf88512554e
|
[
"MIT"
] | null | null | null |
#!/usr/bin/env python3
from dev_aberto import hello
if __name__ == "__main__":
date, name = hello()
print(f"Último commit feito em: {date} por {name}")
| 20.25
| 55
| 0.666667
|
4a0b7b2ead8b00d3425b03d5c9d04902ab01c20f
| 6,195
|
py
|
Python
|
account/api/serializers.py
|
Shubhamag19/Login-SignUp-DRF
|
49a698f834b731964fa17ef7d1a2b4e10dcba892
|
[
"Apache-2.0"
] | null | null | null |
account/api/serializers.py
|
Shubhamag19/Login-SignUp-DRF
|
49a698f834b731964fa17ef7d1a2b4e10dcba892
|
[
"Apache-2.0"
] | null | null | null |
account/api/serializers.py
|
Shubhamag19/Login-SignUp-DRF
|
49a698f834b731964fa17ef7d1a2b4e10dcba892
|
[
"Apache-2.0"
] | null | null | null |
from django.contrib.auth import get_user_model
from django.db.models import Q
from rest_framework import serializers
from .. import models
from rest_framework.serializers import (
ModelSerializer,
ValidationError,
)
# User = get_user_model()
class StuCreateSerializer(ModelSerializer):
email = serializers.EmailField(label='Email')
sapid = serializers.IntegerField(label='Sap id')
email2 = serializers.EmailField(label='Confirm email', write_only=True)
password = serializers.CharField(style={'input_type': 'password', 'placeholder': 'Password'}, write_only=True)
class Meta:
# model = User
model = models.CustomUser
fields = ['username', 'sapid', 'email', 'email2', 'password']
extra_kwargs = {"password": {"write_only": True},
}
def validate_email(self, value):
data = self.get_initial()
email1 = data.get("email2")
email2 = value
if email1 != email2:
raise ValidationError("Emails must match")
user_queryset = models.CustomUser.objects.filter(email=email2)
if user_queryset.exists():
raise ValidationError("This email address is registered.")
return value
def validate_email2(self, value):
data = self.get_initial()
email1 = data.get("email")
email2 = value
if email1 != email2:
raise ValidationError("Emails must match")
return value
def create(self, validated_data):
username = validated_data['username']
sapid = validated_data['sapid']
email = validated_data['email']
password = validated_data['password']
user_obj = models.CustomUser(
username=username,
sapid=sapid,
email=email
)
user_obj.set_password(password)
user_obj.save()
return validated_data
class TeacherCreateSerializer(ModelSerializer):
email = serializers.EmailField(label='Email')
dept = serializers.CharField(label='Department')
email2 = serializers.EmailField(label='Confirm email', write_only=True)
password = serializers.CharField(style={'input_type': 'password', 'placeholder': 'Password'}, write_only=True)
class Meta:
# model = User
model = models.CustomUser
fields = ['username', 'dept', 'email', 'email2', 'password']
extra_kwargs = {"password": {"write_only": True},
}
def validate_email(self, value):
data = self.get_initial()
email1 = data.get("email2")
email2 = value
if email1 != email2:
raise ValidationError("Emails must match")
user_queryset = models.CustomUser.objects.filter(email=email2)
if user_queryset.exists():
raise ValidationError("This email address is registered.")
return value
def validate_email2(self, value):
data = self.get_initial()
email1 = data.get("email")
email2 = value
if email1 != email2:
raise ValidationError("Emails must match")
return value
def create(self, validated_data):
username = validated_data['username']
dept = validated_data['dept']
email = validated_data['email']
password = validated_data['password']
user_obj = models.CustomUser(
username=username,
dept=dept,
email=email
)
user_obj.set_password(password)
user_obj.save()
return validated_data
class UserLoginSerializer(ModelSerializer):
token = serializers.CharField(allow_blank=True, read_only=True)
field_value = serializers.CharField(required=False, allow_blank=True, label='SapId/Email', write_only=True)
# sapid = serializers.IntegerField(required=False, allow_null=True)
# email = serializers.EmailField(label='Email', required=False, allow_blank=True)
password = serializers.CharField(style={'input_type': 'password',
'placeholder': 'Type your password to get hacked ;)'},
write_only=True)
class Meta:
# model = User
model = models.CustomUser
# fields = ['username', 'sapid', 'email', 'password', 'token']
fields = ['field_value', 'password', 'token']
extra_kwargs = {"password":
{"write_only": True}
}
def validate(self, data):
user_obj = None
# email = data.get("email", None)
field_value = data.get("field_value", None)
# sapid = data.get("sapid", None)
password = data["password"]
# if not email and not username and not sapid:
# raise ValidationError("Username or email or sapid is required")
# if email and username and sapid:
# raise ValidationError('Enter a single field')
# user = models.CustomUser.objects.filter(
# Q(email=email) | Q(username=username) | Q(sapid=sapid)
# ).distinct()
# user = models.CustomUser.objects.filter(
# Q(username=username) | Q(sapid=sapid)
# ).distinct
# user = user.exclude(email__isnull=True).exclude(email__iexact='')
if '@' in field_value:
user = models.CustomUser.objects.filter(email__iexact=field_value).first()
elif field_value.isdigit():
user = models.CustomUser.objects.filter(sapid=field_value).first()
else:
# user = models.CustomUser.objects.filter(username__iexact=field_value).first()
raise ValidationError('Incorrect field value')
if not user:
raise serializers.ValidationError("User does not exist")
# if user.exists() and user.count() == 1:
# user_obj = user.first()
# else:
# raise ValidationError("This username or email is not valid")
user_obj = user
if user_obj:
if not user_obj.check_password(password):
raise ValidationError("Incorrect credentials")
data["token"] = "some random token"
return data
| 36.441176
| 114
| 0.611461
|
4a0b7b61dd427edf9e6e8e43034bf7c9c4d55d65
| 4,734
|
py
|
Python
|
homeassistant/components/upnp/device.py
|
andiwand/home-assistant
|
eb584a26e29c3b7998f2ef89a1dcd8bd41e9bb21
|
[
"Apache-2.0"
] | 4
|
2019-01-10T14:47:54.000Z
|
2021-04-22T02:06:27.000Z
|
homeassistant/components/upnp/device.py
|
au190/home-assistant
|
e87ecbd5007acad7468d7118d02b21f6d783c8bc
|
[
"Apache-2.0"
] | 5
|
2021-02-08T20:50:07.000Z
|
2022-03-12T00:39:31.000Z
|
homeassistant/components/upnp/device.py
|
au190/home-assistant
|
e87ecbd5007acad7468d7118d02b21f6d783c8bc
|
[
"Apache-2.0"
] | 3
|
2018-08-29T19:26:20.000Z
|
2020-01-19T11:58:22.000Z
|
"""Hass representation of an UPnP/IGD."""
import asyncio
from ipaddress import IPv4Address
import aiohttp
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.typing import HomeAssistantType
from .const import LOGGER as _LOGGER
class Device:
"""Hass representation of an UPnP/IGD."""
def __init__(self, igd_device):
"""Initializer."""
self._igd_device = igd_device
self._mapped_ports = []
@classmethod
async def async_create_device(cls,
hass: HomeAssistantType,
ssdp_description: str):
"""Create UPnP/IGD device."""
# build async_upnp_client requester
from async_upnp_client.aiohttp import AiohttpSessionRequester
session = async_get_clientsession(hass)
requester = AiohttpSessionRequester(session, True)
# create async_upnp_client device
from async_upnp_client import UpnpFactory
factory = UpnpFactory(requester,
disable_state_variable_validation=True)
upnp_device = await factory.async_create_device(ssdp_description)
# wrap with async_upnp_client IgdDevice
from async_upnp_client.igd import IgdDevice
igd_device = IgdDevice(upnp_device, None)
return cls(igd_device)
@property
def udn(self):
"""Get the UDN."""
return self._igd_device.udn
@property
def name(self):
"""Get the name."""
return self._igd_device.name
async def async_add_port_mappings(self, ports, local_ip):
"""Add port mappings."""
if local_ip == '127.0.0.1':
_LOGGER.error(
'Could not create port mapping, our IP is 127.0.0.1')
# determine local ip, ensure sane IP
local_ip = IPv4Address(local_ip)
# create port mappings
for external_port, internal_port in ports.items():
await self._async_add_port_mapping(external_port,
local_ip,
internal_port)
self._mapped_ports.append(external_port)
async def _async_add_port_mapping(self,
external_port,
local_ip,
internal_port):
"""Add a port mapping."""
# create port mapping
from async_upnp_client import UpnpError
_LOGGER.info('Creating port mapping %s:%s:%s (TCP)',
external_port, local_ip, internal_port)
try:
await self._igd_device.async_add_port_mapping(
remote_host=None,
external_port=external_port,
protocol='TCP',
internal_port=internal_port,
internal_client=local_ip,
enabled=True,
description="Home Assistant",
lease_duration=None)
self._mapped_ports.append(external_port)
except (asyncio.TimeoutError, aiohttp.ClientError, UpnpError):
_LOGGER.error('Could not add port mapping: %s:%s:%s',
external_port, local_ip, internal_port)
async def async_delete_port_mappings(self):
"""Remove a port mapping."""
for port in self._mapped_ports:
await self._async_delete_port_mapping(port)
async def _async_delete_port_mapping(self, external_port):
"""Remove a port mapping."""
from async_upnp_client import UpnpError
_LOGGER.info('Deleting port mapping %s (TCP)', external_port)
try:
await self._igd_device.async_delete_port_mapping(
remote_host=None,
external_port=external_port,
protocol='TCP')
self._mapped_ports.remove(external_port)
except (asyncio.TimeoutError, aiohttp.ClientError, UpnpError):
_LOGGER.error('Could not delete port mapping')
async def async_get_total_bytes_received(self):
"""Get total bytes received."""
return await self._igd_device.async_get_total_bytes_received()
async def async_get_total_bytes_sent(self):
"""Get total bytes sent."""
return await self._igd_device.async_get_total_bytes_sent()
async def async_get_total_packets_received(self):
"""Get total packets received."""
# pylint: disable=invalid-name
return await self._igd_device.async_get_total_packets_received()
async def async_get_total_packets_sent(self):
"""Get total packets sent."""
return await self._igd_device.async_get_total_packets_sent()
| 36.697674
| 73
| 0.619772
|
4a0b7d227e301a548c50367abf12a3c206c84b35
| 2,055
|
py
|
Python
|
migrations/env.py
|
tbsschroeder/dbas
|
9c86eccde65cd64bc5719573b3b8449d8f333e08
|
[
"MIT"
] | 23
|
2017-05-18T13:33:51.000Z
|
2021-12-26T18:04:09.000Z
|
migrations/env.py
|
tbsschroeder/dbas
|
9c86eccde65cd64bc5719573b3b8449d8f333e08
|
[
"MIT"
] | 8
|
2019-12-26T17:19:44.000Z
|
2020-05-28T15:38:31.000Z
|
migrations/env.py
|
tbsschroeder/dbas
|
9c86eccde65cd64bc5719573b3b8449d8f333e08
|
[
"MIT"
] | 7
|
2017-09-27T11:15:42.000Z
|
2021-12-26T18:12:38.000Z
|
"""Pylons bootstrap environment.
Place 'pylons_config_file' into alembic.ini, and the application will
be loaded from there.
"""
import os
from alembic import context
from sqlalchemy import engine_from_config
from dbas.database import get_db_environs, DiscussionBase
# customize this section for non-standard engine configurations.
meta = __import__('dbas.database').database
# add your model's MetaData object here
# for 'autogenerate' support
target_metadata = DiscussionBase.metadata
def run_migrations_offline():
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
context.configure(
url=_get_dbas_engine().url, target_metadata=target_metadata,
literal_binds=True)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
# specify here how the engine is acquired
engine = _get_dbas_engine()
with engine.connect() as connection:
context.configure(
connection=connection,
target_metadata=target_metadata,
version_table_schema=target_metadata.schema,
include_schemas=True
)
with context.begin_transaction():
context.execute('SET search_path TO public')
context.run_migrations()
def _get_dbas_engine():
settings = dict() # get_dbas_environs()
os.environ['DB_USER'] = 'postgres'
settings.update(get_db_environs("sqlalchemy.discussion.url", db_name="discussion"))
return engine_from_config(settings, "sqlalchemy.discussion.")
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
| 27.4
| 87
| 0.716302
|
4a0b7e00c57e7fc8b68782db9e635d23a9811244
| 4,728
|
py
|
Python
|
Evo_Path_min.py
|
oossparsa/country-tour
|
7bf900f52b507b792094423f180318807759d23e
|
[
"MIT"
] | null | null | null |
Evo_Path_min.py
|
oossparsa/country-tour
|
7bf900f52b507b792094423f180318807759d23e
|
[
"MIT"
] | null | null | null |
Evo_Path_min.py
|
oossparsa/country-tour
|
7bf900f52b507b792094423f180318807759d23e
|
[
"MIT"
] | null | null | null |
#parsa badiei
import random
path = './'
positions = []
def start():
global positions
positions = get_positions(path+"Positions_(cities).txt")
p= int (input('population ? '))
u= int (input('number of parents ? '))
l = p-u
preparefile()
fitness=[20000]
iteration = 0
population= createPopulation(p, positions)
while not IsFinished( iteration , fitness):
fitness = EvaluatePopulation(population)
parents = poolOfParents(u , population , fitness)
stats(EvaluatePopulation(parents),iteration)
newGeneration = inheritance(parents , l)
population = newGeneration.copy()
iteration +=1
finishUp(population , fitness)
return
def preparefile():
file = open(path + "results-min.txt", 'w')
file.write("minimization\n#\t\tMax\t\tMean\t\tmin\n\n")
file.close()
def get_positions(filename):
global positions
file = open(filename).readlines()
del file[0]
positions = []
for line in file:
arrayline = line.split('\t')[1:-1]
arrayline[0] = int(arrayline[0])
arrayline[1] = int(arrayline[1])
positions.append(arrayline)
print('number of cities:',len(positions))
return positions
def createGnome(positions):
gnome=[]
copyofcities = positions*2
while copyofcities.__len__()>0:
r = random.randint(0,copyofcities.__len__()-1)
if not gnome.__len__()==0 and not copyofcities.__len__()==1 and gnome[-1][0] == copyofcities[r][0] and gnome[-1][1] == copyofcities[r][1]:
continue
gnome.append(copyofcities[r])
del copyofcities[r]
#print('lencities',copyofcities.__len__(),end=' ')
#correct for illegal gnomes
if(gnome[-1][0] == gnome[-2][0] and gnome[-1][1] == gnome[-2][1]):
temp = gnome[0]
gnome[0] = gnome[-2]
gnome[-2] = temp
return gnome
def createPopulation(p, positions):
population = []
for x in range(p):
population.append(createGnome(positions))
return population
def fitnessEvaluation(gnome):
fitness = 0
for x in range(len(gnome)-1):
fitness += abs(gnome[x][0] - gnome[x+1][0]) + abs(gnome[x][1] - gnome[x+1][1])
return fitness
def EvaluatePopulation(population):
fitness = []
for i in population:
fitness.append(fitnessEvaluation(i))
return fitness
def IsFinished(iteration , fitness):
if min(fitness) < 2000 or iteration>1000:
return True
else:
return False
def poolOfParents(u , pop, fit):
parents=[]
population = pop.copy()
fitness = fit.copy()
#rank based parent selection
for x in range(u):
i = fitness.index(min(fitness))
parents.append(population[i])
del fitness[i]
del population[i]
return parents
def inheritance(pool,landa):
newGeneration = pool.copy()
p1=[]
p2=[]
for i in range(landa):
p1 =pool[random.randint(0,len(pool)-1)]
p2 =pool[random.randint(0, len(pool) - 1)]
c1 = []
crosspoint = random.randint(0,len(p1)-1)
c1 += p1[0:crosspoint]
c1 += p2[crosspoint:]
newGeneration.append(c1)
return newGeneration
def checkadjacentcities(newGen):
for indi in newGen:
for x in range(indi.__len__()-1):
if indi[x][0] == indi[x+1][0] and indi[x][1] == indi[x+1][1] :
indi = createGnome(positions)
return newGen
def mutation(pop):
#flipping two cities
m = int(0.1*len(pop))
r11 = random.randint(0,len(pop)-1)
r12 = random.randint(0,len(pop[0])-1)
r21 = random.randint(0,len(pop)-1)
r22 = random.randint(0,len(pop[0])-1)
for i in range(m):
temp = pop[r11][r12]
pop[r11][r12] = pop [r21][r22]
pop[r21][r22] = temp
def stats(fitness,iter):
Max = max(fitness)
m = min(fitness)
mean = round(sum(fitness) / len(fitness),1)
file = open(path+"results-min.txt",'a')
strToWrite = str(iter)+'\t\t'+str(Max)+'\t\t'+str(mean)+'\t\t'+str(m)+'\n'
file.write(strToWrite)
def finishUp(pop , fit):
file = open(path+"FinalPath-min.txt", 'w')
bestIndividual = pop[fit.index(max(fit))]
coordinates = ''
for cord in bestIndividual:
coordinates += str(cord[0])+'\t\t'+str(cord[1])+'\n'
maxfitness = 'min fitness: '+ str(min(fit)) +'\n\n'
strtowrite = maxfitness + coordinates
file.write(strtowrite)
print(strtowrite)
start()
def test():
p = [1,2,3,4,2,1,4]
p[4:] = [7,7,7]
print(p)
return
| 27.488372
| 147
| 0.577411
|
4a0b7e0ff5288c03300fa120cf9be0ed2bc74a87
| 1,528
|
py
|
Python
|
src/applications/blog/models.py
|
Cheshir-wrr/TMSZ37
|
da807c939c5898b92032076c480137da44112b07
|
[
"MIT"
] | null | null | null |
src/applications/blog/models.py
|
Cheshir-wrr/TMSZ37
|
da807c939c5898b92032076c480137da44112b07
|
[
"MIT"
] | 7
|
2021-04-06T18:19:48.000Z
|
2021-09-22T19:43:54.000Z
|
src/applications/blog/models.py
|
Cheshir-wrr/TMSZ37
|
da807c939c5898b92032076c480137da44112b07
|
[
"MIT"
] | null | null | null |
import delorean
from django.contrib.auth import get_user_model
from django.db import models
from django.db.models import Manager
from django.urls import reverse_lazy
User = get_user_model()
def _now():
return delorean.utcnow().datetime
class PostManager(Manager):
pass
class Post(models.Model):
objects = PostManager()
title = models.TextField(null=True, blank=True, unique=True)
content = models.TextField(null=True, blank=True)
created_at = models.DateTimeField(default=_now)
nr_views = models.IntegerField(default=0)
author = models.ForeignKey(User, on_delete=models.CASCADE)
likers = models.ManyToManyField(User, related_name="liked_posts", blank=True)
@property
def nr_likes(self):
return self.likers.count()
def is_liked_by(self, user: User) -> bool:
liked = Post.objects.filter(pk=self.pk, likers=user).exists()
return liked
class Meta:
ordering = ["-created_at"]
def get_absolute_url(self):
kwargs = {"pk": self.pk}
url = reverse_lazy("blog:post", kwargs=kwargs)
return url
class Comments(models.Model):
email = models.EmailField()
name = models.CharField("Имя", max_length=100)
text = models.TextField("Сообщение", max_length=5000)
post = models.ForeignKey(Post, verbose_name="Пост", on_delete=models.CASCADE)
def __str__(self):
return f"{self.name} - {self.post}"
class Meta:
verbose_name = "Комментарий"
verbose_name_plural = "Комментарии"
| 26.344828
| 81
| 0.689136
|
4a0b7ed73ee162d9a45fd760877953a4f54987d8
| 5,882
|
py
|
Python
|
trafaret_config/simple.py
|
phipleg/trafaret-config
|
0063a5027e7db015e0b0b0dafd8159df409121f2
|
[
"Apache-2.0",
"MIT"
] | 26
|
2016-12-07T16:40:44.000Z
|
2020-11-09T03:27:23.000Z
|
trafaret_config/simple.py
|
phipleg/trafaret-config
|
0063a5027e7db015e0b0b0dafd8159df409121f2
|
[
"Apache-2.0",
"MIT"
] | 6
|
2017-10-27T13:50:21.000Z
|
2020-09-24T17:08:48.000Z
|
trafaret_config/simple.py
|
phipleg/trafaret-config
|
0063a5027e7db015e0b0b0dafd8159df409121f2
|
[
"Apache-2.0",
"MIT"
] | 5
|
2016-12-05T10:23:29.000Z
|
2020-06-05T15:31:24.000Z
|
import os
import re
from weakref import WeakKeyDictionary
from io import StringIO
import trafaret as _trafaret
from yaml import load, dump, ScalarNode
from yaml.scanner import ScannerError
try:
from yaml import CSafeLoader as SafeLoader
except ImportError:
from yaml import SafeLoader
from .error import ConfigError, ErrorLine
VARS_REGEX = re.compile(r'\$(\w+)|\$\{([^}]+)\}')
try:
STR_TYPES = (str, unicode)
UNICODE_TYPE = unicode
except NameError:
STR_TYPES = str
UNICODE_TYPE = str
class ConfigDict(dict):
__slots__ = ('marks', 'extra')
def __init__(self, data, marks, extra):
dict.__init__(self, data)
self.marks = marks
self.extra = extra
class ConfigList(list):
__slots__ = ('marks', 'extra')
def __init__(self, data, marks, extra):
list.__init__(self, data)
self.marks = marks
self.extra = extra
class SubstInfo(object):
def __init__(self, original, vars):
self.original = original
self.vars = vars
def _trafaret_config_hint(self):
return (
[repr(self.original).lstrip('u')] +
[_format_var(k, v) for k, v in self.vars.items()]
)
def _format_var(key, value):
if value is None:
return 'variable {} is undefined'.format(repr(key).lstrip('u'))
else:
value = UNICODE_TYPE(value)
if value.isdecimal():
kind = 'numeric'
elif value.isalnum():
if all(c.isdecimal() or 97 <= ord(c) <= 102
for c in value.lower()):
kind = 'hexadecimal'
elif value.isalpha():
kind = 'letter'
else:
kind = 'alphanumeric'
else:
kind = 'various'
return 'variable {} consists of {} {} characters'.format(
repr(key).lstrip('u'), len(value), kind)
class ConfigLoader(SafeLoader):
def __init__(self, stream, expand_vars, errors):
SafeLoader.__init__(self, stream)
self.__vars = expand_vars
self.__errors = errors
self.__used_vars = set()
def construct_yaml_map(self, node):
data = ConfigDict({}, {}, {})
yield data
data.update(self.construct_mapping(node))
marks = {'__self__': [node.start_mark, node.end_mark]}
for (key, value) in node.value:
if isinstance(key, ScalarNode):
key_str = self.construct_scalar(key)
marks[key_str] = cur_marks = [key.start_mark, value.end_mark]
if self.__vars is not None and isinstance(value, ScalarNode):
val = self.construct_scalar(value)
if isinstance(val, STR_TYPES):
nval, ext = self.__expand_vars(val, cur_marks)
if nval != val:
data[key_str] = nval
data.extra[key_str] = ext
data.marks = marks
def construct_yaml_seq(self, node):
data = ConfigList([], {}, {})
yield data
data.extend(self.construct_sequence(node))
marks = {'__self__': [node.start_mark, node.end_mark]}
for idx, value in enumerate(node.value):
marks[idx] = cur_marks = [value.start_mark, value.end_mark]
if self.__vars is not None and isinstance(value, ScalarNode):
val = data[idx]
if isinstance(val, str):
data[idx], ext = self.__expand_vars(val, cur_marks)
data.extra[idx] = ext
data.marks = marks
def __expand_vars(self, value, marks):
replaced = {}
def replacer(match):
key = match.group(1)
if not key:
key = match.group(2)
replaced[key] = self.__vars.get(key)
self.__used_vars.add(key)
try:
return self.__vars[key]
except KeyError:
self.__errors.append(ErrorLine(
marks, None,
'variable {} not found'.format(repr(key).lstrip('u')),
value))
return match.group(0)
return VARS_REGEX.sub(replacer, value), SubstInfo(value, replaced)
def get_expanded_vars(self):
return set(self.__used_vars)
ConfigLoader.add_constructor(
'tag:yaml.org,2002:map',
ConfigLoader.construct_yaml_map)
ConfigLoader.add_constructor(
'tag:yaml.org,2002:seq',
ConfigLoader.construct_yaml_seq)
def read_and_validate(filename, trafaret, vars=os.environ):
with open(filename) as input:
return _validate_input(input, trafaret, filename=filename, vars=vars)
def read_and_get_vars(filename, trafaret, vars=os.environ):
with open(filename) as input:
errors = []
loader = ConfigLoader(input, vars, errors)
try:
loader.get_single_data()
except ScannerError as e:
raise ConfigError.from_scanner_error(e, filename, errors)
finally:
loader.dispose()
return loader.get_expanded_vars()
def parse_and_validate(string, trafaret,
filename='<config.yaml>', vars=os.environ):
errors = []
input = StringIO(string)
input.name = filename
return _validate_input(input, trafaret, filename=filename, vars=vars)
def _validate_input(input, trafaret, filename, vars):
errors = []
loader = ConfigLoader(input, vars, errors)
try:
data = loader.get_single_data()
except ScannerError as e:
raise ConfigError.from_scanner_error(e, filename, errors)
finally:
loader.dispose()
try:
result = trafaret.check(data)
except _trafaret.DataError as e:
raise ConfigError.from_data_error(e, data, errors)
if errors:
raise ConfigError.from_loader_errors(errors)
return result
| 30.164103
| 77
| 0.591125
|
4a0b7ed7e6003314fc9ff03b24c9b17f61e6d483
| 3,314
|
py
|
Python
|
vnpy/trader/vtFunction.py
|
alonemelive/vnpy
|
be2122f88fb2319d2b9dd6d787efbed00655daaa
|
[
"MIT"
] | null | null | null |
vnpy/trader/vtFunction.py
|
alonemelive/vnpy
|
be2122f88fb2319d2b9dd6d787efbed00655daaa
|
[
"MIT"
] | null | null | null |
vnpy/trader/vtFunction.py
|
alonemelive/vnpy
|
be2122f88fb2319d2b9dd6d787efbed00655daaa
|
[
"MIT"
] | null | null | null |
# encoding: UTF-8
"""
包含一些开发中常用的函数
"""
import os
import decimal
import json
import traceback
from datetime import datetime
from math import isnan
#----------------------------------------------------------------------
def safeUnicode(value):
"""检查接口数据潜在的错误,保证转化为的字符串正确"""
# 检查是数字接近0时会出现的浮点数上限
if type(value) is int or type(value) is float:
if value > MAX_NUMBER or isnan(value):
value = 0
# 检查防止小数点位过多
if type(value) is float:
d = decimal.Decimal(str(value))
if abs(d.as_tuple().exponent) > MAX_DECIMAL:
value = round(value, ndigits=MAX_DECIMAL)
return unicode(value)
#----------------------------------------------------------------------
def todayDate():
"""获取当前本机电脑时间的日期"""
return datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
# 图标路径
iconPathDict = {}
path = os.path.abspath(os.path.dirname(__file__)) # 遍历vnpy安装目录
for root, subdirs, files in os.walk(path):
for fileName in files:
if '.ico' in fileName:
iconPathDict[fileName] = os.path.join(root, fileName)
path = os.getcwd() # 遍历工作目录
for root, subdirs, files in os.walk(path):
for fileName in files:
if '.ico' in fileName:
iconPathDict[fileName] = os.path.join(root, fileName)
#----------------------------------------------------------------------
def loadIconPath(iconName):
"""加载程序图标路径"""
global iconPathDict
return iconPathDict.get(iconName, '')
#----------------------------------------------------------------------
def getTempPath(name):
"""获取存放临时文件的路径"""
tempPath = os.path.join(os.getcwd(), 'temp')
if not os.path.exists(tempPath):
os.makedirs(tempPath)
path = os.path.join(tempPath, name)
return path
# JSON配置文件路径
jsonPathDict = {}
#----------------------------------------------------------------------
def getJsonPath(name, moduleFile):
"""
获取JSON配置文件的路径:
1. 优先从当前工作目录查找JSON文件
2. 若无法找到则前往模块所在目录查找
"""
currentFolder = os.getcwd()
currentJsonPath = os.path.join(currentFolder, name)
if os.path.isfile(currentJsonPath):
jsonPathDict[name] = currentJsonPath
return currentJsonPath
currentFolder = os.getenv('HOME') + "/etc"
currentJsonPath = os.path.join(currentFolder, name)
if os.path.isfile(currentJsonPath):
jsonPathDict[name] = currentJsonPath
return currentJsonPath
moduleFolder = os.path.abspath(os.path.dirname(moduleFile))
moduleJsonPath = os.path.join(moduleFolder, '.', name)
jsonPathDict[name] = moduleJsonPath
return moduleJsonPath
# 加载全局配置
#----------------------------------------------------------------------
def loadJsonSetting(settingFileName):
"""加载JSON配置"""
settingFilePath = getJsonPath(settingFileName, __file__)
setting = {}
try:
with open(settingFilePath, 'rb') as f:
setting = f.read()
if type(setting) is not str:
setting = str(setting, encoding='utf8')
setting = json.loads(setting)
except:
traceback.print_exc()
return setting
# 函数常量
MAX_NUMBER = 10000000000000
globalSetting = loadJsonSetting('VT_setting.json')
MAX_DECIMAL = globalSetting.get('maxDecimal', 4)
| 26.512
| 80
| 0.562161
|
4a0b7f7535bd79fa9908f85dea394de249ae409b
| 37,210
|
py
|
Python
|
benchmarks/tpch/modin_queries.py
|
qinxuye/dataframe-benchmarks
|
0452afa161af3a6ac01e1a43efc7d0fad74c73c2
|
[
"Apache-2.0"
] | null | null | null |
benchmarks/tpch/modin_queries.py
|
qinxuye/dataframe-benchmarks
|
0452afa161af3a6ac01e1a43efc7d0fad74c73c2
|
[
"Apache-2.0"
] | null | null | null |
benchmarks/tpch/modin_queries.py
|
qinxuye/dataframe-benchmarks
|
0452afa161af3a6ac01e1a43efc7d0fad74c73c2
|
[
"Apache-2.0"
] | null | null | null |
"""
This code is adapted from
https://github.com/Bodo-inc/Bodo-examples/blob/master/examples/tpch/ray_queries.py
"""
import argparse
import time
import ray
import modin.pandas as pd
def load_lineitem(data_folder):
data_path = data_folder + "/lineitem.pq"
df = pd.read_parquet(
data_path,
)
return df
def load_part(data_folder):
data_path = data_folder + "/part.pq"
df = pd.read_parquet(
data_path,
)
return df
def load_orders(data_folder):
data_path = data_folder + "/orders.pq"
df = pd.read_parquet(
data_path,
)
return df
def load_customer(data_folder):
data_path = data_folder + "/customer.pq"
df = pd.read_parquet(
data_path,
)
return df
def load_nation(data_folder):
data_path = data_folder + "/nation.pq"
df = pd.read_parquet(
data_path,
)
return df
def load_region(data_folder):
data_path = data_folder + "/region.pq"
df = pd.read_parquet(
data_path,
)
return df
def load_supplier(data_folder):
data_path = data_folder + "/supplier.pq"
df = pd.read_parquet(
data_path,
)
return df
def load_partsupp(data_folder):
data_path = data_folder + "/partsupp.pq"
df = pd.read_parquet(
data_path,
)
return df
def q01(lineitem):
t1 = time.time()
date = pd.Timestamp("1998-09-02")
print(list(lineitem.columns.values))
lineitem_filtered = lineitem.loc[
:,
[
"L_ORDERKEY",
"L_QUANTITY",
"L_EXTENDEDPRICE",
"L_DISCOUNT",
"L_TAX",
"L_RETURNFLAG",
"L_LINESTATUS",
"L_SHIPDATE",
],
]
sel = lineitem_filtered.L_SHIPDATE <= date
lineitem_filtered = lineitem_filtered[sel]
lineitem_filtered["AVG_QTY"] = lineitem_filtered.L_QUANTITY
lineitem_filtered["AVG_PRICE"] = lineitem_filtered.L_EXTENDEDPRICE
lineitem_filtered["DISC_PRICE"] = lineitem_filtered.L_EXTENDEDPRICE * (
1 - lineitem_filtered.L_DISCOUNT
)
lineitem_filtered["CHARGE"] = (
lineitem_filtered.L_EXTENDEDPRICE
* (1 - lineitem_filtered.L_DISCOUNT)
* (1 + lineitem_filtered.L_TAX)
)
# ray needs double square bracket
gb = lineitem_filtered.groupby(["L_RETURNFLAG", "L_LINESTATUS"], as_index=False)[
[
"L_ORDERKEY",
"L_QUANTITY",
"L_EXTENDEDPRICE",
"L_DISCOUNT",
"AVG_QTY",
"AVG_PRICE",
"CHARGE",
"DISC_PRICE",
]
]
total = gb.agg(
{
"L_QUANTITY": "sum",
"L_EXTENDEDPRICE": "sum",
"DISC_PRICE": "sum",
"CHARGE": "sum",
"AVG_QTY": "mean",
"AVG_PRICE": "mean",
"L_DISCOUNT": "mean",
"L_ORDERKEY": "count",
}
)
total = total.sort_values(["L_RETURNFLAG", "L_LINESTATUS"])
print(total)
print("Q01 Execution time (s): ", time.time() - t1)
def q02(part, partsupp, supplier, nation, region):
t1 = time.time()
nation_filtered = nation.loc[:, ["N_NATIONKEY", "N_NAME", "N_REGIONKEY"]]
region_filtered = region[(region["R_NAME"] == "EUROPE")]
region_filtered = region_filtered.loc[:, ["R_REGIONKEY"]]
r_n_merged = nation_filtered.merge(
region_filtered, left_on="N_REGIONKEY", right_on="R_REGIONKEY", how="inner"
)
r_n_merged = r_n_merged.loc[:, ["N_NATIONKEY", "N_NAME"]]
supplier_filtered = supplier.loc[
:,
[
"S_SUPPKEY",
"S_NAME",
"S_ADDRESS",
"S_NATIONKEY",
"S_PHONE",
"S_ACCTBAL",
"S_COMMENT",
],
]
s_r_n_merged = r_n_merged.merge(
supplier_filtered, left_on="N_NATIONKEY", right_on="S_NATIONKEY", how="inner"
)
s_r_n_merged = s_r_n_merged.loc[
:,
[
"N_NAME",
"S_SUPPKEY",
"S_NAME",
"S_ADDRESS",
"S_PHONE",
"S_ACCTBAL",
"S_COMMENT",
],
]
partsupp_filtered = partsupp.loc[:, ["PS_PARTKEY", "PS_SUPPKEY", "PS_SUPPLYCOST"]]
ps_s_r_n_merged = s_r_n_merged.merge(
partsupp_filtered, left_on="S_SUPPKEY", right_on="PS_SUPPKEY", how="inner"
)
ps_s_r_n_merged = ps_s_r_n_merged.loc[
:,
[
"N_NAME",
"S_NAME",
"S_ADDRESS",
"S_PHONE",
"S_ACCTBAL",
"S_COMMENT",
"PS_PARTKEY",
"PS_SUPPLYCOST",
],
]
part_filtered = part.loc[:, ["P_PARTKEY", "P_MFGR", "P_SIZE", "P_TYPE"]]
part_filtered = part_filtered[
(part_filtered["P_SIZE"] == 15)
& (part_filtered["P_TYPE"].str.endswith("BRASS"))
]
part_filtered = part_filtered.loc[:, ["P_PARTKEY", "P_MFGR"]]
merged_df = part_filtered.merge(
ps_s_r_n_merged, left_on="P_PARTKEY", right_on="PS_PARTKEY", how="inner"
)
merged_df = merged_df.loc[
:,
[
"N_NAME",
"S_NAME",
"S_ADDRESS",
"S_PHONE",
"S_ACCTBAL",
"S_COMMENT",
"PS_SUPPLYCOST",
"P_PARTKEY",
"P_MFGR",
],
]
min_values = merged_df.groupby("P_PARTKEY", as_index=False)["PS_SUPPLYCOST"].min()
min_values.columns = ["P_PARTKEY_CPY", "MIN_SUPPLYCOST"]
merged_df = merged_df.merge(
min_values,
left_on=["P_PARTKEY", "PS_SUPPLYCOST"],
right_on=["P_PARTKEY_CPY", "MIN_SUPPLYCOST"],
how="inner",
)
total = merged_df.loc[
:,
[
"S_ACCTBAL",
"S_NAME",
"N_NAME",
"P_PARTKEY",
"P_MFGR",
"S_ADDRESS",
"S_PHONE",
"S_COMMENT",
],
]
total = total.sort_values(
by=[
"S_ACCTBAL",
"N_NAME",
"S_NAME",
"P_PARTKEY",
],
ascending=[
False,
True,
True,
True,
],
)
print(total)
print("Q02 Execution time (s): ", time.time() - t1)
def q03(lineitem, orders, customer):
t1 = time.time()
date = pd.Timestamp("1995-03-04")
lineitem_filtered = lineitem.loc[
:, ["L_ORDERKEY", "L_EXTENDEDPRICE", "L_DISCOUNT", "L_SHIPDATE"]
]
orders_filtered = orders.loc[
:, ["O_ORDERKEY", "O_CUSTKEY", "O_ORDERDATE", "O_SHIPPRIORITY"]
]
customer_filtered = customer.loc[:, ["C_MKTSEGMENT", "C_CUSTKEY"]]
lsel = lineitem_filtered.L_SHIPDATE > date
osel = orders_filtered.O_ORDERDATE < date
csel = customer_filtered.C_MKTSEGMENT == "HOUSEHOLD"
flineitem = lineitem_filtered[lsel]
forders = orders_filtered[osel]
fcustomer = customer_filtered[csel]
jn1 = fcustomer.merge(forders, left_on="C_CUSTKEY", right_on="O_CUSTKEY")
jn2 = jn1.merge(flineitem, left_on="O_ORDERKEY", right_on="L_ORDERKEY")
jn2["TMP"] = jn2.L_EXTENDEDPRICE * (1 - jn2.L_DISCOUNT)
total = (
jn2.groupby(["L_ORDERKEY", "O_ORDERDATE", "O_SHIPPRIORITY"], as_index=False)[
"TMP"
]
.sum()
.sort_values(["TMP"], ascending=False)
)
res = total.loc[:, ["L_ORDERKEY", "TMP", "O_ORDERDATE", "O_SHIPPRIORITY"]]
print(res.head(10))
print("Q03 Execution time (s): ", time.time() - t1)
def q04(lineitem, orders):
t1 = time.time()
date1 = pd.Timestamp("1993-11-01")
date2 = pd.Timestamp("1993-08-01")
lsel = lineitem.L_COMMITDATE < lineitem.L_RECEIPTDATE
osel = (orders.O_ORDERDATE < date1) & (orders.O_ORDERDATE >= date2)
flineitem = lineitem[lsel]
forders = orders[osel]
jn = forders[forders["O_ORDERKEY"].isin(flineitem["L_ORDERKEY"])]
total = (
jn.groupby("O_ORDERPRIORITY", as_index=False)["O_ORDERKEY"]
.count()
.sort_values(["O_ORDERPRIORITY"])
)
print(total)
print("Q04 Execution time (s): ", time.time() - t1)
def q05(lineitem, orders, customer, nation, region, supplier):
t1 = time.time()
date1 = pd.Timestamp("1996-01-01")
date2 = pd.Timestamp("1997-01-01")
rsel = region.R_NAME == "ASIA"
osel = (orders.O_ORDERDATE >= date1) & (orders.O_ORDERDATE < date2)
forders = orders[osel]
fregion = region[rsel]
jn1 = fregion.merge(nation, left_on="R_REGIONKEY", right_on="N_REGIONKEY")
jn2 = jn1.merge(customer, left_on="N_NATIONKEY", right_on="C_NATIONKEY")
jn3 = jn2.merge(forders, left_on="C_CUSTKEY", right_on="O_CUSTKEY")
jn4 = jn3.merge(lineitem, left_on="O_ORDERKEY", right_on="L_ORDERKEY")
jn5 = supplier.merge(
jn4, left_on=["S_SUPPKEY", "S_NATIONKEY"], right_on=["L_SUPPKEY", "N_NATIONKEY"]
)
jn5["TMP"] = jn5.L_EXTENDEDPRICE * (1.0 - jn5.L_DISCOUNT)
gb = jn5.groupby("N_NAME", as_index=False)["TMP"].sum()
total = gb.sort_values("TMP", ascending=False)
print(total)
print("Q05 Execution time (s): ", time.time() - t1)
def q06(lineitem):
t1 = time.time()
date1 = pd.Timestamp("1996-01-01")
date2 = pd.Timestamp("1997-01-01")
lineitem_filtered = lineitem.loc[
:, ["L_QUANTITY", "L_EXTENDEDPRICE", "L_DISCOUNT", "L_SHIPDATE"]
]
sel = (
(lineitem_filtered.L_SHIPDATE >= date1)
& (lineitem_filtered.L_SHIPDATE < date2)
& (lineitem_filtered.L_DISCOUNT >= 0.08)
& (lineitem_filtered.L_DISCOUNT <= 0.1)
& (lineitem_filtered.L_QUANTITY < 24)
)
flineitem = lineitem_filtered[sel]
total = (flineitem.L_EXTENDEDPRICE * flineitem.L_DISCOUNT).sum()
print(total)
print("Q06 Execution time (s): ", time.time() - t1)
def q07(lineitem, supplier, orders, customer, nation):
"""This version is faster than q07_old. Keeping the old one for reference"""
t1 = time.time()
lineitem_filtered = lineitem[
(lineitem["L_SHIPDATE"] >= pd.Timestamp("1995-01-01"))
& (lineitem["L_SHIPDATE"] < pd.Timestamp("1997-01-01"))
]
lineitem_filtered["L_YEAR"] = lineitem_filtered["L_SHIPDATE"].apply(
lambda x: x.year
)
lineitem_filtered["VOLUME"] = lineitem_filtered["L_EXTENDEDPRICE"] * (
1.0 - lineitem_filtered["L_DISCOUNT"]
)
lineitem_filtered = lineitem_filtered.loc[
:, ["L_ORDERKEY", "L_SUPPKEY", "L_YEAR", "VOLUME"]
]
supplier_filtered = supplier.loc[:, ["S_SUPPKEY", "S_NATIONKEY"]]
orders_filtered = orders.loc[:, ["O_ORDERKEY", "O_CUSTKEY"]]
customer_filtered = customer.loc[:, ["C_CUSTKEY", "C_NATIONKEY"]]
n1 = nation[(nation["N_NAME"] == "FRANCE")].loc[:, ["N_NATIONKEY", "N_NAME"]]
n2 = nation[(nation["N_NAME"] == "GERMANY")].loc[:, ["N_NATIONKEY", "N_NAME"]]
# ----- do nation 1 -----
N1_C = customer_filtered.merge(
n1, left_on="C_NATIONKEY", right_on="N_NATIONKEY", how="inner"
)
N1_C = N1_C.drop(columns=["C_NATIONKEY", "N_NATIONKEY"]).rename(
columns={"N_NAME": "CUST_NATION"}
)
N1_C_O = N1_C.merge(
orders_filtered, left_on="C_CUSTKEY", right_on="O_CUSTKEY", how="inner"
)
N1_C_O = N1_C_O.drop(columns=["C_CUSTKEY", "O_CUSTKEY"])
# NOTE: this is faster than first merging lineitem with N1_C_O
N2_S = supplier_filtered.merge(
n2, left_on="S_NATIONKEY", right_on="N_NATIONKEY", how="inner"
)
N2_S = N2_S.drop(columns=["S_NATIONKEY", "N_NATIONKEY"]).rename(
columns={"N_NAME": "SUPP_NATION"}
)
N2_S_L = N2_S.merge(
lineitem_filtered, left_on="S_SUPPKEY", right_on="L_SUPPKEY", how="inner"
)
N2_S_L = N2_S_L.drop(columns=["S_SUPPKEY", "L_SUPPKEY"])
total1 = N1_C_O.merge(
N2_S_L, left_on="O_ORDERKEY", right_on="L_ORDERKEY", how="inner"
)
total1 = total1.drop(columns=["O_ORDERKEY", "L_ORDERKEY"])
# ----- do nation 2 ----- (same as nation 1 section but with nation 2)
N2_C = customer_filtered.merge(
n2, left_on="C_NATIONKEY", right_on="N_NATIONKEY", how="inner"
)
N2_C = N2_C.drop(columns=["C_NATIONKEY", "N_NATIONKEY"]).rename(
columns={"N_NAME": "CUST_NATION"}
)
N2_C_O = N2_C.merge(
orders_filtered, left_on="C_CUSTKEY", right_on="O_CUSTKEY", how="inner"
)
N2_C_O = N2_C_O.drop(columns=["C_CUSTKEY", "O_CUSTKEY"])
N1_S = supplier_filtered.merge(
n1, left_on="S_NATIONKEY", right_on="N_NATIONKEY", how="inner"
)
N1_S = N1_S.drop(columns=["S_NATIONKEY", "N_NATIONKEY"]).rename(
columns={"N_NAME": "SUPP_NATION"}
)
N1_S_L = N1_S.merge(
lineitem_filtered, left_on="S_SUPPKEY", right_on="L_SUPPKEY", how="inner"
)
N1_S_L = N1_S_L.drop(columns=["S_SUPPKEY", "L_SUPPKEY"])
total2 = N2_C_O.merge(
N1_S_L, left_on="O_ORDERKEY", right_on="L_ORDERKEY", how="inner"
)
total2 = total2.drop(columns=["O_ORDERKEY", "L_ORDERKEY"])
# concat results
total = pd.concat([total1, total2])
total = total.groupby(["SUPP_NATION", "CUST_NATION", "L_YEAR"], as_index=False).agg(
REVENUE=pd.NamedAgg(column="VOLUME", aggfunc="sum")
)
total = total.sort_values(
by=["SUPP_NATION", "CUST_NATION", "L_YEAR"],
ascending=[
True,
True,
True,
],
)
print(total)
print("Q07 Execution time (s): ", time.time() - t1)
def q08(part, lineitem, supplier, orders, customer, nation, region):
t1 = time.time()
part_filtered = part[(part["P_TYPE"] == "ECONOMY ANODIZED STEEL")]
part_filtered = part_filtered.loc[:, ["P_PARTKEY"]]
lineitem_filtered = lineitem.loc[:, ["L_PARTKEY", "L_SUPPKEY", "L_ORDERKEY"]]
lineitem_filtered["VOLUME"] = lineitem["L_EXTENDEDPRICE"] * (
1.0 - lineitem["L_DISCOUNT"]
)
total = part_filtered.merge(
lineitem_filtered, left_on="P_PARTKEY", right_on="L_PARTKEY", how="inner"
)
total = total.loc[:, ["L_SUPPKEY", "L_ORDERKEY", "VOLUME"]]
supplier_filtered = supplier.loc[:, ["S_SUPPKEY", "S_NATIONKEY"]]
total = total.merge(
supplier_filtered, left_on="L_SUPPKEY", right_on="S_SUPPKEY", how="inner"
)
total = total.loc[:, ["L_ORDERKEY", "VOLUME", "S_NATIONKEY"]]
orders_filtered = orders[
(orders["O_ORDERDATE"] >= pd.Timestamp("1995-01-01"))
& (orders["O_ORDERDATE"] < pd.Timestamp("1997-01-01"))
]
orders_filtered["O_YEAR"] = orders_filtered["O_ORDERDATE"].apply(lambda x: x.year)
orders_filtered = orders_filtered.loc[:, ["O_ORDERKEY", "O_CUSTKEY", "O_YEAR"]]
total = total.merge(
orders_filtered, left_on="L_ORDERKEY", right_on="O_ORDERKEY", how="inner"
)
total = total.loc[:, ["VOLUME", "S_NATIONKEY", "O_CUSTKEY", "O_YEAR"]]
customer_filtered = customer.loc[:, ["C_CUSTKEY", "C_NATIONKEY"]]
total = total.merge(
customer_filtered, left_on="O_CUSTKEY", right_on="C_CUSTKEY", how="inner"
)
total = total.loc[:, ["VOLUME", "S_NATIONKEY", "O_YEAR", "C_NATIONKEY"]]
n1_filtered = nation.loc[:, ["N_NATIONKEY", "N_REGIONKEY"]]
n2_filtered = nation.loc[:, ["N_NATIONKEY", "N_NAME"]].rename(
columns={"N_NAME": "NATION"}
)
total = total.merge(
n1_filtered, left_on="C_NATIONKEY", right_on="N_NATIONKEY", how="inner"
)
total = total.loc[:, ["VOLUME", "S_NATIONKEY", "O_YEAR", "N_REGIONKEY"]]
total = total.merge(
n2_filtered, left_on="S_NATIONKEY", right_on="N_NATIONKEY", how="inner"
)
total = total.loc[:, ["VOLUME", "O_YEAR", "N_REGIONKEY", "NATION"]]
region_filtered = region[(region["R_NAME"] == "AMERICA")]
region_filtered = region_filtered.loc[:, ["R_REGIONKEY"]]
total = total.merge(
region_filtered, left_on="N_REGIONKEY", right_on="R_REGIONKEY", how="inner"
)
total = total.loc[:, ["VOLUME", "O_YEAR", "NATION"]]
def udf(df):
demonimator = df["VOLUME"].sum()
df = df[df["NATION"] == "BRAZIL"]
numerator = df["VOLUME"].sum()
return numerator / demonimator
# modin returns empty column with as_index=false
total = total.groupby("O_YEAR").apply(udf).reset_index()
total.columns = ["O_YEAR", "MKT_SHARE"]
total = total.sort_values(
by=[
"O_YEAR",
],
ascending=[
True,
],
)
print(total)
print("Q08 Execution time (s): ", time.time() - t1)
def q09(lineitem, orders, part, nation, partsupp, supplier):
t1 = time.time()
psel = part.P_NAME.str.contains("ghost")
fpart = part[psel]
jn1 = lineitem.merge(fpart, left_on="L_PARTKEY", right_on="P_PARTKEY")
jn2 = jn1.merge(supplier, left_on="L_SUPPKEY", right_on="S_SUPPKEY")
jn3 = jn2.merge(nation, left_on="S_NATIONKEY", right_on="N_NATIONKEY")
jn4 = partsupp.merge(
jn3, left_on=["PS_PARTKEY", "PS_SUPPKEY"], right_on=["L_PARTKEY", "L_SUPPKEY"]
)
jn5 = jn4.merge(orders, left_on="L_ORDERKEY", right_on="O_ORDERKEY")
jn5["TMP"] = jn5.L_EXTENDEDPRICE * (1 - jn5.L_DISCOUNT) - (
(1 * jn5.PS_SUPPLYCOST) * jn5.L_QUANTITY
)
jn5["O_YEAR"] = jn5.O_ORDERDATE.apply(lambda x: x.year)
gb = jn5.groupby(["N_NAME", "O_YEAR"], as_index=False)["TMP"].sum()
total = gb.sort_values(["N_NAME", "O_YEAR"], ascending=[True, False])
print(total)
print("Q09 Execution time (s): ", time.time() - t1)
def q10(lineitem, orders, customer, nation):
t1 = time.time()
date1 = pd.Timestamp("1994-11-01")
date2 = pd.Timestamp("1995-02-01")
osel = (orders.O_ORDERDATE >= date1) & (orders.O_ORDERDATE < date2)
lsel = lineitem.L_RETURNFLAG == "R"
forders = orders[osel]
flineitem = lineitem[lsel]
jn1 = flineitem.merge(forders, left_on="L_ORDERKEY", right_on="O_ORDERKEY")
jn2 = jn1.merge(customer, left_on="O_CUSTKEY", right_on="C_CUSTKEY")
jn3 = jn2.merge(nation, left_on="C_NATIONKEY", right_on="N_NATIONKEY")
jn3["TMP"] = jn3.L_EXTENDEDPRICE * (1.0 - jn3.L_DISCOUNT)
gb = jn3.groupby(
[
"C_CUSTKEY",
"C_NAME",
"C_ACCTBAL",
"C_PHONE",
"N_NAME",
"C_ADDRESS",
"C_COMMENT",
],
as_index=False,
)["TMP"].sum()
total = gb.sort_values("TMP", ascending=False)
print(total.head(20))
print("Q10 Execution time (s): ", time.time() - t1)
def q11(partsupp, supplier, nation):
t1 = time.time()
partsupp_filtered = partsupp.loc[:, ["PS_PARTKEY", "PS_SUPPKEY"]]
partsupp_filtered["TOTAL_COST"] = (
partsupp["PS_SUPPLYCOST"] * partsupp["PS_AVAILQTY"]
)
supplier_filtered = supplier.loc[:, ["S_SUPPKEY", "S_NATIONKEY"]]
ps_supp_merge = partsupp_filtered.merge(
supplier_filtered, left_on="PS_SUPPKEY", right_on="S_SUPPKEY", how="inner"
)
ps_supp_merge = ps_supp_merge.loc[:, ["PS_PARTKEY", "S_NATIONKEY", "TOTAL_COST"]]
nation_filtered = nation[(nation["N_NAME"] == "GERMANY")]
nation_filtered = nation_filtered.loc[:, ["N_NATIONKEY"]]
ps_supp_n_merge = ps_supp_merge.merge(
nation_filtered, left_on="S_NATIONKEY", right_on="N_NATIONKEY", how="inner"
)
ps_supp_n_merge = ps_supp_n_merge.loc[:, ["PS_PARTKEY", "TOTAL_COST"]]
sum_val = ps_supp_n_merge["TOTAL_COST"].sum() * 0.0001
total = ps_supp_n_merge.groupby(["PS_PARTKEY"], as_index=False).agg(
VALUE=pd.NamedAgg(column="TOTAL_COST", aggfunc="sum")
)
total = total[total["VALUE"] > sum_val]
total = total.sort_values("VALUE", ascending=False)
print(total)
print("Q11 Execution time (s): ", time.time() - t1)
def q12(lineitem, orders):
t1 = time.time()
date1 = pd.Timestamp("1994-01-01")
date2 = pd.Timestamp("1995-01-01")
sel = (
(lineitem.L_RECEIPTDATE < date2)
& (lineitem.L_COMMITDATE < date2)
& (lineitem.L_SHIPDATE < date2)
& (lineitem.L_SHIPDATE < lineitem.L_COMMITDATE)
& (lineitem.L_COMMITDATE < lineitem.L_RECEIPTDATE)
& (lineitem.L_RECEIPTDATE >= date1)
& ((lineitem.L_SHIPMODE == "MAIL") | (lineitem.L_SHIPMODE == "SHIP"))
)
flineitem = lineitem[sel]
jn = flineitem.merge(orders, left_on="L_ORDERKEY", right_on="O_ORDERKEY")
def g1(x):
return ((x == "1-URGENT") | (x == "2-HIGH")).sum()
def g2(x):
return ((x != "1-URGENT") & (x != "2-HIGH")).sum()
total = jn.groupby("L_SHIPMODE", as_index=False)["O_ORDERPRIORITY"].agg((g1, g2))
total = total.sort_values("L_SHIPMODE")
print(total)
print("Q12 Execution time (s): ", time.time() - t1)
def q13(customer, orders):
t1 = time.time()
customer_filtered = customer.loc[:, ["C_CUSTKEY"]]
orders_filtered = orders[
~orders["O_COMMENT"].str.contains("special(\S|\s)*requests")
]
orders_filtered = orders_filtered.loc[:, ["O_ORDERKEY", "O_CUSTKEY"]]
c_o_merged = customer_filtered.merge(
orders_filtered, left_on="C_CUSTKEY", right_on="O_CUSTKEY", how="left"
)
c_o_merged = c_o_merged.loc[:, ["C_CUSTKEY", "O_ORDERKEY"]]
count_df = c_o_merged.groupby(["C_CUSTKEY"], as_index=False).agg(
C_COUNT=pd.NamedAgg(column="O_ORDERKEY", aggfunc="count")
)
total = count_df.groupby(["C_COUNT"], as_index=False).size()
total.columns = ["C_COUNT", "CUSTDIST"]
total = total.sort_values(
by=["CUSTDIST", "C_COUNT"],
ascending=[
False,
False,
],
)
print(total)
print("Q13 Execution time (s): ", time.time() - t1)
def q14(lineitem, part):
t1 = time.time()
startDate = pd.Timestamp("1994-03-01")
endDate = pd.Timestamp("1994-04-01")
p_type_like = "PROMO"
part_filtered = part.loc[:, ["P_PARTKEY", "P_TYPE"]]
lineitem_filtered = lineitem.loc[
:, ["L_EXTENDEDPRICE", "L_DISCOUNT", "L_SHIPDATE", "L_PARTKEY"]
]
sel = (lineitem_filtered.L_SHIPDATE >= startDate) & (
lineitem_filtered.L_SHIPDATE < endDate
)
flineitem = lineitem_filtered[sel]
jn = flineitem.merge(part_filtered, left_on="L_PARTKEY", right_on="P_PARTKEY")
jn["TMP"] = jn.L_EXTENDEDPRICE * (1.0 - jn.L_DISCOUNT)
total = jn[jn.P_TYPE.str.startswith(p_type_like)].TMP.sum() * 100 / jn.TMP.sum()
print(total)
print("Q14 Execution time (s): ", time.time() - t1)
def q15(lineitem, supplier):
t1 = time.time()
lineitem_filtered = lineitem[
(lineitem["L_SHIPDATE"] >= pd.Timestamp("1996-01-01"))
& (
lineitem["L_SHIPDATE"]
< (pd.Timestamp("1996-01-01") + pd.DateOffset(months=3))
)
]
lineitem_filtered["REVENUE_PARTS"] = lineitem_filtered["L_EXTENDEDPRICE"] * (
1.0 - lineitem_filtered["L_DISCOUNT"]
)
lineitem_filtered = lineitem_filtered.loc[:, ["L_SUPPKEY", "REVENUE_PARTS"]]
revenue_table = (
lineitem_filtered.groupby("L_SUPPKEY", as_index=False)
.agg(TOTAL_REVENUE=pd.NamedAgg(column="REVENUE_PARTS", aggfunc="sum"))
.rename(columns={"L_SUPPKEY": "SUPPLIER_NO"}, copy=False)
)
max_revenue = revenue_table["TOTAL_REVENUE"].max()
revenue_table = revenue_table[revenue_table["TOTAL_REVENUE"] == max_revenue]
supplier_filtered = supplier.loc[:, ["S_SUPPKEY", "S_NAME", "S_ADDRESS", "S_PHONE"]]
total = supplier_filtered.merge(
revenue_table, left_on="S_SUPPKEY", right_on="SUPPLIER_NO", how="inner"
)
total = total.loc[
:, ["S_SUPPKEY", "S_NAME", "S_ADDRESS", "S_PHONE", "TOTAL_REVENUE"]
]
print(total)
print("Q15 Execution time (s): ", time.time() - t1)
def q16(part, partsupp, supplier):
t1 = time.time()
part_filtered = part[
(part["P_BRAND"] != "Brand#45")
& (~part["P_TYPE"].str.contains("^MEDIUM POLISHED"))
& part["P_SIZE"].isin([49, 14, 23, 45, 19, 3, 36, 9])
]
part_filtered = part_filtered.loc[:, ["P_PARTKEY", "P_BRAND", "P_TYPE", "P_SIZE"]]
partsupp_filtered = partsupp.loc[:, ["PS_PARTKEY", "PS_SUPPKEY"]]
total = part_filtered.merge(
partsupp_filtered, left_on="P_PARTKEY", right_on="PS_PARTKEY", how="inner"
)
total = total.loc[:, ["P_BRAND", "P_TYPE", "P_SIZE", "PS_SUPPKEY"]]
supplier_filtered = supplier[
supplier["S_COMMENT"].str.contains("Customer(\S|\s)*Complaints")
]
supplier_filtered = supplier_filtered.loc[:, ["S_SUPPKEY"]].drop_duplicates()
# left merge to select only ps_suppkey values not in supplier_filtered
total = total.merge(
supplier_filtered, left_on="PS_SUPPKEY", right_on="S_SUPPKEY", how="left"
)
total = total[total["S_SUPPKEY"].isna()]
total = total.loc[:, ["P_BRAND", "P_TYPE", "P_SIZE", "PS_SUPPKEY"]]
total = total.groupby(["P_BRAND", "P_TYPE", "P_SIZE"], as_index=False)[
"PS_SUPPKEY"
].nunique()
total.columns = ["P_BRAND", "P_TYPE", "P_SIZE", "SUPPLIER_CNT"]
total = total.sort_values(
by=["SUPPLIER_CNT", "P_BRAND", "P_TYPE", "P_SIZE"],
ascending=[False, True, True, True],
)
print(total)
print("Q16 Execution time (s): ", time.time() - t1)
def q17(lineitem, part):
t1 = time.time()
left = lineitem.loc[:, ["L_PARTKEY", "L_QUANTITY", "L_EXTENDEDPRICE"]]
right = part[((part["P_BRAND"] == "Brand#23") & (part["P_CONTAINER"] == "MED BOX"))]
right = right.loc[:, ["P_PARTKEY"]]
line_part_merge = left.merge(
right, left_on="L_PARTKEY", right_on="P_PARTKEY", how="inner"
)
line_part_merge = line_part_merge.loc[
:, ["L_QUANTITY", "L_EXTENDEDPRICE", "P_PARTKEY"]
]
lineitem_filtered = lineitem.loc[:, ["L_PARTKEY", "L_QUANTITY"]]
lineitem_avg = lineitem_filtered.groupby(["L_PARTKEY"], as_index=False).agg(
avg=pd.NamedAgg(column="L_QUANTITY", aggfunc="mean")
)
lineitem_avg["avg"] = 0.2 * lineitem_avg["avg"]
lineitem_avg = lineitem_avg.loc[:, ["L_PARTKEY", "avg"]]
total = line_part_merge.merge(
lineitem_avg, left_on="P_PARTKEY", right_on="L_PARTKEY", how="inner"
)
total = total[total["L_QUANTITY"] < total["avg"]]
total = pd.DataFrame({"avg_yearly": [total["L_EXTENDEDPRICE"].sum() / 7.0]})
print(total)
print("Q17 Execution time (s): ", time.time() - t1)
def q18(lineitem, orders, customer):
t1 = time.time()
gb1 = lineitem.groupby("L_ORDERKEY", as_index=False)["L_QUANTITY"].sum()
fgb1 = gb1[gb1.L_QUANTITY > 300]
jn1 = fgb1.merge(orders, left_on="L_ORDERKEY", right_on="O_ORDERKEY")
jn2 = jn1.merge(customer, left_on="O_CUSTKEY", right_on="C_CUSTKEY")
gb2 = jn2.groupby(
["C_NAME", "C_CUSTKEY", "O_ORDERKEY", "O_ORDERDATE", "O_TOTALPRICE"],
as_index=False,
)["L_QUANTITY"].sum()
total = gb2.sort_values(["O_TOTALPRICE", "O_ORDERDATE"], ascending=[False, True])
print(total.head(100))
print("Q18 Execution time (s): ", time.time() - t1)
def q19(lineitem, part):
t1 = time.time()
Brand31 = "Brand#31"
Brand43 = "Brand#43"
SMBOX = "SM BOX"
SMCASE = "SM CASE"
SMPACK = "SM PACK"
SMPKG = "SM PKG"
MEDBAG = "MED BAG"
MEDBOX = "MED BOX"
MEDPACK = "MED PACK"
MEDPKG = "MED PKG"
LGBOX = "LG BOX"
LGCASE = "LG CASE"
LGPACK = "LG PACK"
LGPKG = "LG PKG"
DELIVERINPERSON = "DELIVER IN PERSON"
AIR = "AIR"
AIRREG = "AIRREG"
lsel = (
(
((lineitem.L_QUANTITY <= 36) & (lineitem.L_QUANTITY >= 26))
| ((lineitem.L_QUANTITY <= 25) & (lineitem.L_QUANTITY >= 15))
| ((lineitem.L_QUANTITY <= 14) & (lineitem.L_QUANTITY >= 4))
)
& (lineitem.L_SHIPINSTRUCT == DELIVERINPERSON)
& ((lineitem.L_SHIPMODE == AIR) | (lineitem.L_SHIPMODE == AIRREG))
)
psel = (part.P_SIZE >= 1) & (
(
(part.P_SIZE <= 5)
& (part.P_BRAND == Brand31)
& (
(part.P_CONTAINER == SMBOX)
| (part.P_CONTAINER == SMCASE)
| (part.P_CONTAINER == SMPACK)
| (part.P_CONTAINER == SMPKG)
)
)
| (
(part.P_SIZE <= 10)
& (part.P_BRAND == Brand43)
& (
(part.P_CONTAINER == MEDBAG)
| (part.P_CONTAINER == MEDBOX)
| (part.P_CONTAINER == MEDPACK)
| (part.P_CONTAINER == MEDPKG)
)
)
| (
(part.P_SIZE <= 15)
& (part.P_BRAND == Brand43)
& (
(part.P_CONTAINER == LGBOX)
| (part.P_CONTAINER == LGCASE)
| (part.P_CONTAINER == LGPACK)
| (part.P_CONTAINER == LGPKG)
)
)
)
flineitem = lineitem[lsel]
fpart = part[psel]
jn = flineitem.merge(fpart, left_on="L_PARTKEY", right_on="P_PARTKEY")
jnsel = (
(jn.P_BRAND == Brand31)
& (
(jn.P_CONTAINER == SMBOX)
| (jn.P_CONTAINER == SMCASE)
| (jn.P_CONTAINER == SMPACK)
| (jn.P_CONTAINER == SMPKG)
)
& (jn.L_QUANTITY >= 4)
& (jn.L_QUANTITY <= 14)
& (jn.P_SIZE <= 5)
| (jn.P_BRAND == Brand43)
& (
(jn.P_CONTAINER == MEDBAG)
| (jn.P_CONTAINER == MEDBOX)
| (jn.P_CONTAINER == MEDPACK)
| (jn.P_CONTAINER == MEDPKG)
)
& (jn.L_QUANTITY >= 15)
& (jn.L_QUANTITY <= 25)
& (jn.P_SIZE <= 10)
| (jn.P_BRAND == Brand43)
& (
(jn.P_CONTAINER == LGBOX)
| (jn.P_CONTAINER == LGCASE)
| (jn.P_CONTAINER == LGPACK)
| (jn.P_CONTAINER == LGPKG)
)
& (jn.L_QUANTITY >= 26)
& (jn.L_QUANTITY <= 36)
& (jn.P_SIZE <= 15)
)
jn = jn[jnsel]
total = (jn.L_EXTENDEDPRICE * (1.0 - jn.L_DISCOUNT)).sum()
print(total)
print("Q19 Execution time (s): ", time.time() - t1)
def q20(lineitem, part, nation, partsupp, supplier):
t1 = time.time()
date1 = pd.Timestamp("1996-01-01")
date2 = pd.Timestamp("1997-01-01")
psel = part.P_NAME.str.startswith("azure")
nsel = nation.N_NAME == "JORDAN"
lsel = (lineitem.L_SHIPDATE >= date1) & (lineitem.L_SHIPDATE < date2)
fpart = part[psel]
fnation = nation[nsel]
flineitem = lineitem[lsel]
jn1 = fpart.merge(partsupp, left_on="P_PARTKEY", right_on="PS_PARTKEY")
jn2 = jn1.merge(
flineitem,
left_on=["PS_PARTKEY", "PS_SUPPKEY"],
right_on=["L_PARTKEY", "L_SUPPKEY"],
)
gb = jn2.groupby(["PS_PARTKEY", "PS_SUPPKEY", "PS_AVAILQTY"], as_index=False)[
"L_QUANTITY"
].sum()
gbsel = gb.PS_AVAILQTY > (0.5 * gb.L_QUANTITY)
fgb = gb[gbsel]
jn3 = fgb.merge(supplier, left_on="PS_SUPPKEY", right_on="S_SUPPKEY")
jn4 = fnation.merge(jn3, left_on="N_NATIONKEY", right_on="S_NATIONKEY")
jn4 = jn4.loc[:, ["S_NAME", "S_ADDRESS"]]
total = jn4.sort_values("S_NAME").drop_duplicates()
print(total)
print("Q20 Execution time (s): ", time.time() - t1)
def q21(lineitem, orders, supplier, nation):
t1 = time.time()
lineitem_filtered = lineitem.loc[
:, ["L_ORDERKEY", "L_SUPPKEY", "L_RECEIPTDATE", "L_COMMITDATE"]
]
# Exists
lineitem_orderkeys = (
lineitem_filtered.loc[:, ["L_ORDERKEY", "L_SUPPKEY"]]
.groupby("L_ORDERKEY", as_index=False)["L_SUPPKEY"]
.nunique()
)
lineitem_orderkeys.columns = ["L_ORDERKEY", "nunique_col"]
lineitem_orderkeys = lineitem_orderkeys[lineitem_orderkeys["nunique_col"] > 1]
lineitem_orderkeys = lineitem_orderkeys.loc[:, ["L_ORDERKEY"]]
# Filter
lineitem_filtered = lineitem_filtered[
lineitem_filtered["L_RECEIPTDATE"] > lineitem_filtered["L_COMMITDATE"]
]
lineitem_filtered = lineitem_filtered.loc[:, ["L_ORDERKEY", "L_SUPPKEY"]]
# Merge Filter + Exists
lineitem_filtered = lineitem_filtered.merge(
lineitem_orderkeys, on="L_ORDERKEY", how="inner"
)
# Not Exists: Check the exists condition isn't still satisfied on the output.
lineitem_orderkeys = lineitem_filtered.groupby("L_ORDERKEY", as_index=False)[
"L_SUPPKEY"
].nunique()
lineitem_orderkeys.columns = ["L_ORDERKEY", "nunique_col"]
lineitem_orderkeys = lineitem_orderkeys[lineitem_orderkeys["nunique_col"] == 1]
lineitem_orderkeys = lineitem_orderkeys.loc[:, ["L_ORDERKEY"]]
# Merge Filter + Not Exists
lineitem_filtered = lineitem_filtered.merge(
lineitem_orderkeys, on="L_ORDERKEY", how="inner"
)
orders_filtered = orders.loc[:, ["O_ORDERSTATUS", "O_ORDERKEY"]]
orders_filtered = orders_filtered[orders_filtered["O_ORDERSTATUS"] == "F"]
orders_filtered = orders_filtered.loc[:, ["O_ORDERKEY"]]
total = lineitem_filtered.merge(
orders_filtered, left_on="L_ORDERKEY", right_on="O_ORDERKEY", how="inner"
)
total = total.loc[:, ["L_SUPPKEY"]]
supplier_filtered = supplier.loc[:, ["S_SUPPKEY", "S_NATIONKEY", "S_NAME"]]
total = total.merge(
supplier_filtered, left_on="L_SUPPKEY", right_on="S_SUPPKEY", how="inner"
)
total = total.loc[:, ["S_NATIONKEY", "S_NAME"]]
nation_filtered = nation.loc[:, ["N_NAME", "N_NATIONKEY"]]
nation_filtered = nation_filtered[nation_filtered["N_NAME"] == "SAUDI ARABIA"]
total = total.merge(
nation_filtered, left_on="S_NATIONKEY", right_on="N_NATIONKEY", how="inner"
)
total = total.loc[:, ["S_NAME"]]
total = total.groupby("S_NAME", as_index=False).size()
total.columns = ["S_NAME", "NUMWAIT"]
total = total.sort_values(
by=[
"NUMWAIT",
"S_NAME",
],
ascending=[
False,
True,
],
)
print(total)
print("Q21 Execution time (s): ", time.time() - t1)
def q22(customer, orders):
t1 = time.time()
customer_filtered = customer.loc[:, ["C_ACCTBAL", "C_CUSTKEY"]]
customer_filtered["CNTRYCODE"] = customer["C_PHONE"].str.slice(0, 2)
customer_filtered = customer_filtered[
(customer["C_ACCTBAL"] > 0.00)
& customer_filtered["CNTRYCODE"].isin(
["13", "31", "23", "29", "30", "18", "17"]
)
]
avg_value = customer_filtered["C_ACCTBAL"].mean()
customer_filtered = customer_filtered[customer_filtered["C_ACCTBAL"] > avg_value]
# Select only the keys that don't match by performing a left join and only selecting columns with an na value
orders_filtered = orders.loc[:, ["O_CUSTKEY"]].drop_duplicates()
customer_keys = customer_filtered.loc[:, ["C_CUSTKEY"]].drop_duplicates()
customer_selected = customer_keys.merge(
orders_filtered, left_on="C_CUSTKEY", right_on="O_CUSTKEY", how="left"
)
customer_selected = customer_selected[customer_selected["O_CUSTKEY"].isna()]
customer_selected = customer_selected.loc[:, ["C_CUSTKEY"]]
customer_selected = customer_selected.merge(
customer_filtered, on="C_CUSTKEY", how="inner"
)
customer_selected = customer_selected.loc[:, ["CNTRYCODE", "C_ACCTBAL"]]
agg1 = customer_selected.groupby(["CNTRYCODE"], as_index=False).size()
agg1.columns = ["CNTRYCODE", "NUMCUST"]
agg2 = customer_selected.groupby(["CNTRYCODE"], as_index=False).agg(
TOTACCTBAL=pd.NamedAgg(column="C_ACCTBAL", aggfunc="sum")
)
total = agg1.merge(agg2, on="CNTRYCODE", how="inner")
total = total.sort_values(
by=[
"CNTRYCODE",
],
ascending=[
True,
],
)
print(total)
print("Q22 Execution time (s): ", time.time() - t1)
def run_queries(data_folder):
# Load the data
t1 = time.time()
lineitem = load_lineitem(data_folder)
orders = load_orders(data_folder)
customer = load_customer(data_folder)
nation = load_nation(data_folder)
region = load_region(data_folder)
supplier = load_supplier(data_folder)
part = load_part(data_folder)
partsupp = load_partsupp(data_folder)
print("Reading time (s): ", time.time() - t1)
t1 = time.time()
# Run the Queries:
q01(lineitem)
q02(part, partsupp, supplier, nation, region)
q03(lineitem, orders, customer)
q04(lineitem, orders)
q05(lineitem, orders, customer, nation, region, supplier)
q06(lineitem)
# q07 cannot finish
# q07(lineitem, supplier, orders, customer, nation)
q08(part, lineitem, supplier, orders, customer, nation, region)
q09(lineitem, orders, part, nation, partsupp, supplier)
q10(lineitem, orders, customer, nation)
q11(partsupp, supplier, nation)
q12(lineitem, orders)
q13(customer, orders)
q14(lineitem, part)
q15(lineitem, supplier)
q16(part, partsupp, supplier)
q17(lineitem, part)
q18(lineitem, orders, customer)
q19(lineitem, part)
q20(lineitem, part, nation, partsupp, supplier)
q21(lineitem, orders, supplier, nation)
q22(customer, orders)
print("Total Query time (s): ", time.time() - t1)
def main():
ray.init()
parser = argparse.ArgumentParser(description="tpch-queries")
parser.add_argument(
"--folder",
type=str,
help="The folder containing TPCH data",
)
args = parser.parse_args()
folder = args.folder
run_queries(folder)
if __name__ == "__main__":
main()
| 34.613953
| 113
| 0.603225
|
4a0b80f7159be69aa7cdd2616a0f226abe08f9b5
| 3,833
|
py
|
Python
|
dev/circuitpython/examples/rfm69_rpi_interrupt.py
|
scripsi/picodeebee
|
0ec77e92f09fa8711705623482e57a5e0b702696
|
[
"MIT"
] | 7
|
2021-03-15T10:06:20.000Z
|
2022-03-23T02:53:15.000Z
|
Lights/adafruit-circuitpython-bundle-6.x-mpy-20210310/examples/rfm69_rpi_interrupt.py
|
IanSMoyes/SpiderPi
|
cc3469980ae87b92d0dc43c05dbd579f0fa8c4b1
|
[
"Apache-2.0"
] | 5
|
2021-04-27T18:21:11.000Z
|
2021-05-02T14:17:14.000Z
|
Lights/adafruit-circuitpython-bundle-6.x-mpy-20210310/examples/rfm69_rpi_interrupt.py
|
IanSMoyes/SpiderPi
|
cc3469980ae87b92d0dc43c05dbd579f0fa8c4b1
|
[
"Apache-2.0"
] | null | null | null |
# SPDX-FileCopyrightText: 2020 Tony DiCola, Jerry Needell for Adafruit Industries
# SPDX-License-Identifier: MIT
# Example using Interrupts to send a message and then wait indefinitely for messages
# to be received. Interrupts are used only for receive. sending is done with polling.
# This example is for systems that support interrupts like the Raspberry Pi with "blinka"
# CircuitPython does not support interrupts so it will not work on Circutpython boards
import time
import board
import busio
import digitalio
import RPi.GPIO as io
import adafruit_rfm69
# setup interrupt callback function
def rfm69_callback(rfm69_irq):
global packet_received # pylint: disable=global-statement
print(
"IRQ detected on pin {0} payload_ready {1} ".format(
rfm69_irq, rfm69.payload_ready
)
)
# see if this was a payload_ready interrupt ignore if not
if rfm69.payload_ready:
packet = rfm69.receive(timeout=None)
if packet is not None:
# Received a packet!
packet_received = True
# Print out the raw bytes of the packet:
print("Received (raw bytes): {0}".format(packet))
print([hex(x) for x in packet])
print("RSSI: {0}".format(rfm69.last_rssi))
# Define radio parameters.
RADIO_FREQ_MHZ = 915.0 # Frequency of the radio in Mhz. Must match your
# module! Can be a value like 915.0, 433.0, etc.
# Define pins connected to the chip, use these if wiring up the breakout according to the guide:
CS = digitalio.DigitalInOut(board.CE1)
RESET = digitalio.DigitalInOut(board.D25)
# Initialize SPI bus.
spi = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO)
# Initialze RFM radio
rfm69 = adafruit_rfm69.RFM69(spi, CS, RESET, RADIO_FREQ_MHZ)
# Optionally set an encryption key (16 byte AES key). MUST match both
# on the transmitter and receiver (or be set to None to disable/the default).
rfm69.encryption_key = (
b"\x01\x02\x03\x04\x05\x06\x07\x08\x01\x02\x03\x04\x05\x06\x07\x08"
)
# Print out some chip state:
print("Temperature: {0}C".format(rfm69.temperature))
print("Frequency: {0}mhz".format(rfm69.frequency_mhz))
print("Bit rate: {0}kbit/s".format(rfm69.bitrate / 1000))
print("Frequency deviation: {0}hz".format(rfm69.frequency_deviation))
# configure the interrupt pin and event handling.
RFM69_G0 = 22
io.setmode(io.BCM)
io.setup(RFM69_G0, io.IN, pull_up_down=io.PUD_DOWN) # activate input
io.add_event_detect(RFM69_G0, io.RISING)
io.add_event_callback(RFM69_G0, rfm69_callback)
packet_received = False
# Send a packet. Note you can only send a packet up to 60 bytes in length.
# This is a limitation of the radio packet size, so if you need to send larger
# amounts of data you will need to break it into smaller send calls. Each send
# call will wait for the previous one to finish before continuing.
rfm69.send(bytes("Hello world!\r\n", "utf-8"), keep_listening=True)
print("Sent hello world message!")
# If you don't wawnt to send a message to start you can just start lintening
# rmf69.listen()
# Wait to receive packets. Note that this library can't receive data at a fast
# rate, in fact it can only receive and process one 60 byte packet at a time.
# This means you should only use this for low bandwidth scenarios, like sending
# and receiving a single message at a time.
print("Waiting for packets...")
# the loop is where you can do any desire processing
# the global variable packet_received can be used to determine if a packet was received.
while True:
# the sleep time is arbitrary since any incomming packe will trigger an interrupt
# and be received.
time.sleep(0.1)
if packet_received:
print("received message!")
packet_received = False
| 41.215054
| 97
| 0.715106
|
4a0b81235c2a09c734ab00ab068170212a6a89ab
| 10,054
|
py
|
Python
|
print_results.py
|
jooooohannes/h2-mapping
|
362324a02feaa9a439c4b1240367288b3a4aca46
|
[
"MIT"
] | null | null | null |
print_results.py
|
jooooohannes/h2-mapping
|
362324a02feaa9a439c4b1240367288b3a4aca46
|
[
"MIT"
] | null | null | null |
print_results.py
|
jooooohannes/h2-mapping
|
362324a02feaa9a439c4b1240367288b3a4aca46
|
[
"MIT"
] | null | null | null |
import pandas as pd
from Transport_cost_functions import *
from geo_path import *
import plotly.graph_objects as go
def print_basic_results(df):
"""Prints the important results from the input dataframe."""
min_cost = min(df['Total Cost per kg H2'])
mindex = df.index.values[df['Total Cost per kg H2'] == min_cost]
mindex = mindex[0]
cheapest_source = (df['Latitude'][mindex], df['Longitude'][mindex])
cheapest_medium = df['Cheapest Medium'][mindex]
cheapest_elec = df['Cheaper source'][mindex]
print('Index: ' + str(mindex))
print('Minimum cost: ' + str(min_cost))
print('Cheapest source: ' + str(cheapest_source[0]) + ', ' + str(cheapest_source[1]))
print('Cheapest medium: ' + str(cheapest_medium))
print('Cheaper electricity: ' + str(cheapest_elec))
return min_cost, mindex
def get_path(df, end_plant_tuple, centralised, pipeline):
"""Prints and plots the path of transport taken from the cheapest found solution."""
min_cost = min(df['Total Cost per kg H2'])
mindex = df.index.values[df['Total Cost per kg H2'] == min_cost]
mindex = mindex[0]
df, end_port_tuple = check_port_path(df, end_plant_tuple)
# Get straight line distance from end point to end port
direct_distance_end = geopy.distance.distance(end_plant_tuple, end_port_tuple).km # Needs [lat, long]
try:
driving_distance_end = get_driving_distance(end_plant_tuple, end_port_tuple) # Needs [lat, long]
except:
driving_distance_end = np.nan
# Calculate minimum costs from end port to end location for all medium possibilities
end_nh3_options = [nh3_costs(truck_dist=driving_distance_end, convert=False, centralised=centralised),
nh3_costs(pipe_dist=direct_distance_end, convert=False, centralised=centralised, pipeline=pipeline),
h2_gas_costs(pipe_dist=direct_distance_end, pipeline=pipeline),
h2_gas_costs(truck_dist=driving_distance_end)]
cost_end_nh3 = np.nanmin(end_nh3_options)
try:
end_nh3_transport = end_nh3_options.index(np.nanmin(end_nh3_options))
if end_nh3_transport == 0:
nh3_end = 'NH3 Truck'
elif end_nh3_transport == 1:
nh3_end = 'NH3 Pipe'
elif end_nh3_transport == 2:
nh3_end = 'H2 Gas Pipe'
elif end_nh3_transport == 3:
nh3_end = 'H2 Gas Truck'
except:
nh3_end = 'Not possible'
end_lohc_options = [lohc_costs(truck_dist=driving_distance_end, convert=False, centralised=centralised),
h2_gas_costs(pipe_dist=direct_distance_end, pipeline=pipeline),
h2_gas_costs(truck_dist=driving_distance_end)]
cost_end_lohc = np.nanmin(end_lohc_options)
try:
end_lohc_transport = end_lohc_options.index(np.nanmin(end_lohc_options))
if end_lohc_transport == 0:
lohc_end = 'LOHC Truck'
elif end_lohc_transport == 1:
lohc_end = 'H2 Gas Pipe'
elif end_lohc_transport == 2:
lohc_end = 'H2 Gas Truck'
except:
lohc_end = 'Not possible'
end_h2_liq_options = [h2_liq_costs(truck_dist=driving_distance_end, convert=False, centralised=centralised),
h2_gas_costs(pipe_dist=direct_distance_end, pipeline=pipeline),
h2_gas_costs(truck_dist=driving_distance_end)]
cost_end_h2_liq = np.nanmin(end_h2_liq_options)
try:
end_h2_liq_transport = end_h2_liq_options.index(np.nanmin(end_h2_liq_options))
if end_h2_liq_transport == 0:
h2_liq_end = 'H2 Liq Truck'
elif end_h2_liq_transport == 1:
h2_liq_end = 'H2 Gas Pipe'
elif end_h2_liq_transport == 2:
h2_liq_end = 'H2 Gas Truck'
except:
h2_liq_end = 'Not possible'
direct_distance_total = geopy.distance.distance((df.at[mindex, 'Latitude'], df.at[mindex, 'Longitude']),
end_plant_tuple).km # Needs [lat, long]
# Check if it is possible to truck the whole way to end destination. If so, get costs.
if direct_distance_total < 500:
try:
driving_distance_total = get_driving_distance((df.at[mindex, 'Latitude'], df.at[mindex, 'Longitude']),
end_plant_tuple) # Needs [lat, long]
except:
driving_distance_total = np.nan
else:
driving_distance_total = np.nan
# Calculate minimum costs from gen to start port for all medium possibilities
start_nh3_options = [
nh3_costs(truck_dist=df.at[mindex, 'Gen-Port Driving Dist.'], convert=False, centralised=centralised),
nh3_costs(pipe_dist=df.at[mindex, 'Gen-Port Direct Dist.'], convert=False, centralised=centralised, pipeline=pipeline),
h2_gas_costs(pipe_dist=df.at[mindex, 'Gen-Port Direct Dist.'], pipeline=pipeline),
h2_gas_costs(truck_dist=df.at[mindex, 'Gen-Port Driving Dist.'])]
cost_start_nh3 = np.nanmin(start_nh3_options)
start_nh3_transport = start_nh3_options.index(np.nanmin(start_nh3_options))
if start_nh3_transport == 0:
nh3_start = 'NH3 Truck'
elif start_nh3_transport == 1:
nh3_start = 'NH3 Pipe'
elif start_nh3_transport == 2:
nh3_start = 'H2 Gas Pipe'
elif start_nh3_transport == 3:
nh3_start = 'H2 Gas Truck'
start_lohc_options = [
lohc_costs(truck_dist=df.at[mindex, 'Gen-Port Driving Dist.'], convert=False, centralised=centralised),
h2_gas_costs(pipe_dist=df.at[mindex, 'Gen-Port Direct Dist.'], pipeline=pipeline),
h2_gas_costs(truck_dist=df.at[mindex, 'Gen-Port Driving Dist.'])]
cost_start_lohc = np.nanmin(start_lohc_options)
start_lohc_transport = start_lohc_options.index(np.nanmin(start_lohc_options))
if start_lohc_transport == 0:
lohc_start = 'LOHC Truck'
elif start_lohc_transport == 1:
lohc_start = 'H2 Gas Pipe'
elif start_lohc_transport == 2:
lohc_start = 'H2 Gas Truck'
start_h2_liq_options = [
h2_liq_costs(truck_dist=df.at[mindex, 'Gen-Port Driving Dist.'], convert=False, centralised=centralised),
h2_gas_costs(pipe_dist=df.at[mindex, 'Gen-Port Direct Dist.'], pipeline=pipeline),
h2_gas_costs(truck_dist=df.at[mindex, 'Gen-Port Driving Dist.'])]
cost_start_h2_liq = np.nanmin(start_h2_liq_options)
start_h2_liq_transport = start_h2_liq_options.index(np.nanmin(start_h2_liq_options))
if start_h2_liq_transport == 0:
h2_liq_start = 'H2 Liq Truck'
elif start_h2_liq_transport == 1:
h2_liq_start = 'H2 Gas Pipe'
elif start_h2_liq_transport == 2:
h2_liq_start = 'H2 Gas Truck'
# Calculate shipping costs
cost_shipping_nh3 = nh3_costs(ship_dist=df['Shipping Dist.'][mindex], centralised=centralised)
cost_shipping_lohc = lohc_costs(ship_dist=df['Shipping Dist.'][mindex], centralised=centralised)
cost_shipping_h2_liq = h2_liq_costs(ship_dist=df['Shipping Dist.'][mindex], centralised=centralised)
# Calculate minimum total transport costs for each medium
total_nh3_options = [(cost_start_nh3 + cost_shipping_nh3 + cost_end_nh3),
nh3_costs(truck_dist=driving_distance_total, centralised=centralised),
nh3_costs(pipe_dist=direct_distance_total, centralised=centralised, pipeline=pipeline)]
nh3_options = total_nh3_options.index(np.nanmin(total_nh3_options))
if nh3_options == 0:
nh3 = 'NH3 Ship'
elif nh3_options == 1:
nh3 = 'NH3 Truck'
elif nh3_options == 2:
nh3 = 'NH3 Pipe'
total_lohc_options = [(cost_start_lohc + cost_shipping_lohc + cost_end_lohc),
lohc_costs(truck_dist=driving_distance_total, centralised=centralised)]
lohc_options = total_lohc_options.index(np.nanmin(total_lohc_options))
if lohc_options == 0:
lohc = 'LOHC Ship'
elif lohc_options == 1:
lohc = 'LOHC Truck'
total_h2_liq_options = [(cost_start_h2_liq + cost_shipping_h2_liq + cost_end_h2_liq),
h2_liq_costs(truck_dist=driving_distance_total, centralised=centralised)]
h2_liq_options = total_h2_liq_options.index(np.nanmin(total_h2_liq_options))
if h2_liq_options == 0:
h2_liq = 'H2 Liq Ship'
elif h2_liq_options == 1:
h2_liq = 'H2 Liq Truck'
total_h2_gas_options = [h2_gas_costs(truck_dist=driving_distance_total),
h2_gas_costs(pipe_dist=direct_distance_total, pipeline=pipeline)]
try:
h2_gas_options = total_h2_gas_options.index(np.nanmin(total_h2_gas_options))
if h2_gas_options == 0:
h2_gas = 'H2 Gas Truck'
elif h2_gas_options == 1:
h2_gas = 'H2 Gas Pipe'
except:
h2_gas = 'Not possible'
total_total_options = [df.at[mindex, 'NH3 Cost'], df.at[mindex, 'LOHC Cost'], df.at[mindex, 'H2 Liq Cost'],
df.at[mindex, 'H2 Gas Cost']]
if np.nanmin(total_total_options) == df.at[mindex, 'NH3 Cost']:
if nh3 == 'NH3 Ship':
final_path = nh3_start + ' + Ship + ' + nh3_end
else:
final_path = nh3
elif np.nanmin(total_total_options) == df.at[mindex, 'LOHC Cost']:
if lohc == 'LOHC Ship':
final_path = lohc_start + ' + Ship + ' + lohc_end
else:
final_path = lohc
elif np.nanmin(total_total_options) == df.at[mindex, 'H2 Liq Cost']:
if h2_liq == 'H2 Liq Ship':
final_path = h2_liq_start + ' + Ship + ' + h2_liq_end
else:
final_path = h2_liq
elif np.nanmin(total_total_options) == df.at[mindex, 'H2 Gas Cost']:
final_path = h2_gas
print('Transport method: ' + final_path)
return final_path
| 47.649289
| 128
| 0.647603
|
4a0b81c67aee59e123c7813b5f7173af2e915ecf
| 1,273
|
py
|
Python
|
commlit/up_scale.py
|
robert-manolache/kaggle-commlit
|
7d377d43559c19915158230e4ac5f5a5d2a308bf
|
[
"MIT"
] | null | null | null |
commlit/up_scale.py
|
robert-manolache/kaggle-commlit
|
7d377d43559c19915158230e4ac5f5a5d2a308bf
|
[
"MIT"
] | null | null | null |
commlit/up_scale.py
|
robert-manolache/kaggle-commlit
|
7d377d43559c19915158230e4ac5f5a5d2a308bf
|
[
"MIT"
] | null | null | null |
# -------------------------- # -------------------------- #
# Upscaling data size module # -------------------------- #
# -------------------------- # -------------------------- #
import numpy as np
import pandas as pd
def upscale_targets(df, n=10):
"""
"""
og_cols = df.columns
if n > 1:
up_df = df.copy()[["id", "target", "standard_error"]]
up_df.loc[:, "noise"] = up_df["standard_error"].apply(
lambda x: x*np.random.randn(n)
)
up_df = up_df.explode("noise")
up_df.loc[:, "target"] = (up_df["target"] +
up_df["noise"]).astype(float)
df = df.drop(columns=["target"]
).merge(up_df[["id", "target"]], on="id")
return df[og_cols]
def even_upsample(grp, n_row=100, n_rep=5):
"""
"""
n_grp = grp.shape[0]
grp_df = []
for i in range(n_rep):
if n_grp >= n_row:
i_df = grp.sample(n_row)
else:
i_df = pd.concat([grp]*(n_row // n_grp) +
[grp.sample(n_row % n_grp)],
ignore_index=True)
i_df.loc[:, "grp_id"] = i
grp_df.append(i_df)
return pd.concat(grp_df, ignore_index=True)
| 28.288889
| 62
| 0.427337
|
4a0b8204a20ec640a161ca686e82095226ee656a
| 11,841
|
py
|
Python
|
djangosige/apps/fiscal/models/nota_fiscal.py
|
felipealbuquerq/djangoSIGE
|
2af100fa23b60a1b0d489d511e92e7fde52e214a
|
[
"MIT"
] | 1
|
2018-08-24T01:29:49.000Z
|
2018-08-24T01:29:49.000Z
|
djangosige/apps/fiscal/models/nota_fiscal.py
|
felipealbuquerq/djangoSIGE
|
2af100fa23b60a1b0d489d511e92e7fde52e214a
|
[
"MIT"
] | null | null | null |
djangosige/apps/fiscal/models/nota_fiscal.py
|
felipealbuquerq/djangoSIGE
|
2af100fa23b60a1b0d489d511e92e7fde52e214a
|
[
"MIT"
] | 1
|
2020-07-30T00:03:48.000Z
|
2020-07-30T00:03:48.000Z
|
# -*- coding: utf-8 -*-
from django.db import models
from django.core.validators import RegexValidator, MinValueValidator
from django.template.defaultfilters import date
from decimal import Decimal
import os
import re
from djangosige.configs.settings import MEDIA_ROOT, APP_ROOT
IND_PAG_ESCOLHAS = (
(u'0', u'Pagamento à vista'),
(u'1', u'Pagamento a prazo'),
(u'2', u'Outros'),
)
MOD_NFE_ESCOLHAS = (
(u'55', u'NF-e (55)'),
(u'65', u'NFC-e (65)'),
)
TP_NFE_ESCOLHAS = (
(u'0', u'Entrada'),
(u'1', u'Saída'),
)
IDDEST_ESCOLHAS = (
(u'1', u'Operação interna'),
(u'2', u'Operação interestadual'),
(u'3', u'Operação com exterior'),
)
TP_IMP_ESCOLHAS = (
(u'0', u'Sem geração de DANFE'),
(u'1', u'DANFE normal, Retrato'),
(u'2', u'DANFE normal, Paisagem'),
#(u'3', u'DANFE Simplificado'),
(u'4', u'DANFE NFC-e'),
#(u'5', u'DANFE NFC-e em mensagem eletrônica'),
)
TP_EMIS_ESCOLHAS = (
(u'1', u'Emissão normal'),
(u'2', u'Emissão em contingência'),
#(u'2', u'Contingência FS-IA, com impressão do DANFE em formulário de segurança'),
#(u'3', u'Contingência SCAN (Sistema de Contingência do Ambiente Nacional)'),
#(u'4', u'Contingência DPEC (Declaração Prévia da Emissão em Contingência)'),
#(u'5', u'Contingência FS-DA, com impressão do DANFE em formulário de segurança'),
#(u'6', u'Contingência SVC-AN (SEFAZ Virtual de Contingência do AN)'),
#(u'7', u'Contingência SVC-RS (SEFAZ Virtual de Contingência do RS)'),
#(u'9', u'Contingência off-line da NFC-e'),
)
TP_AMB_ESCOLHAS = (
(u'1', 'Produção'),
(u'2', 'Homologação'),
)
FIN_NFE_ESCOLHAS = (
(u'1', u'NF-e normal'),
(u'2', u'NF-e complementar'),
(u'3', u'NF-e de ajuste'),
(u'4', u'Devolução de mercadoria'),
)
IND_FINAL_ESCOLHAS = (
(u'0', u'0 - Não'),
(u'1', u'1 - Sim'),
)
IND_PRES_ESCOLHAS = (
(u'0', u'Não se aplica'),
(u'1', u'Operação presencial'),
(u'2', u'Operação não presencial, pela Internet'),
(u'3', u'Operação não presencial, Teleatendimento'),
(u'4', u'NFC-e em operação com entrega a domicílio'),
(u'5', u'Operação presencial, fora do estabelecimento'),
(u'9', u'Operação não presencial, outros.'),
)
VERSOES = (
#('2.00', 'v2.00'),
('3.10', 'v3.10'),
)
ORIENTACAO_LOGO_DANFE = (
(u'H', u'Horizontal'),
(u'V', u'Vertical'),
)
STATUS_NFE_ESCOLHAS = (
(u'0', u'Assinada'),
(u'1', u'Autorizada'),
(u'2', u'Denegada'),
(u'3', u'Em Digitação'),
(u'4', u'Em Processamento na SEFAZ'),
(u'5', u'Rejeitada'),
(u'6', u'Validada'),
(u'7', u'Pendente'),
(u'8', u'Cancelada'),
(u'9', u'Importada por XML')
)
ERROS_NFE_TIPOS = (
(u'0', 'Erro'),
(u'1', 'Alerta'),
)
RETORNO_SEFAZ_TIPOS = (
(u'0', u'Erro'),
(u'1', u'Resultado do processamento'),
(u'2', u'Rejeição'),
(u'3', u'Motivo denegação'),
(u'4', u'Alerta'),
)
def arquivo_proc_path(instance, filename):
return 'ArquivosXML/ProcNFeUpload/{0}'.format(filename)
class NotaFiscal(models.Model):
chave = models.CharField(max_length=44)
versao = models.CharField(max_length=4, choices=VERSOES, default='3.10')
natop = models.CharField(max_length=60)
indpag = models.CharField(max_length=1, choices=IND_PAG_ESCOLHAS)
mod = models.CharField(
max_length=2, choices=MOD_NFE_ESCOLHAS, default=u'55')
serie = models.CharField(max_length=3)
dhemi = models.DateTimeField()
dhsaient = models.DateTimeField(null=True, blank=True)
iddest = models.CharField(max_length=1, choices=IDDEST_ESCOLHAS)
tp_imp = models.CharField(max_length=1, choices=TP_IMP_ESCOLHAS)
tp_emis = models.CharField(
max_length=1, choices=TP_EMIS_ESCOLHAS, default=u'1')
tp_amb = models.CharField(max_length=1, choices=TP_AMB_ESCOLHAS)
fin_nfe = models.CharField(
max_length=1, choices=FIN_NFE_ESCOLHAS, default=u'1')
ind_final = models.CharField(
max_length=1, choices=IND_FINAL_ESCOLHAS, default=u'0')
ind_pres = models.CharField(
max_length=1, choices=IND_PRES_ESCOLHAS, default=u'0')
inf_ad_fisco = models.CharField(max_length=2000, null=True, blank=True)
inf_cpl = models.CharField(max_length=5000, null=True, blank=True)
status_nfe = models.CharField(max_length=1, choices=STATUS_NFE_ESCOLHAS)
arquivo_proc = models.FileField(
max_length=2055, upload_to=arquivo_proc_path, null=True, blank=True)
numero_lote = models.CharField(max_length=16, null=True, blank=True)
numero_protocolo = models.CharField(max_length=16, null=True, blank=True)
just_canc = models.CharField(max_length=255, null=True, blank=True)
@property
def consumidor(self):
if self.mod == '65':
return True
else:
return False
@property
def contingencia(self):
if self.tp_emis == '1':
return False
else:
return True
@property
def caminho_proc_completo(self):
if self.arquivo_proc:
if APP_ROOT in self.arquivo_proc.name:
return self.arquivo_proc.name
else:
return os.path.join(APP_ROOT, self.arquivo_proc.url)
else:
return ''
def format_data_emissao(self):
return '%s' % date(self.dhemi.date(), "d/m/Y")
class NotaFiscalSaida(NotaFiscal):
tpnf = models.CharField(
max_length=1, choices=TP_NFE_ESCOLHAS, default=u'1')
n_nf_saida = models.CharField(max_length=9, validators=[
RegexValidator(r'^\d{1,10}$')], unique=True)
venda = models.ForeignKey('vendas.PedidoVenda', related_name="venda_nfe",
on_delete=models.SET_NULL, null=True, blank=True)
emit_saida = models.ForeignKey(
'cadastro.Empresa', related_name="emit_nfe_saida", on_delete=models.SET_NULL, null=True, blank=True)
dest_saida = models.ForeignKey(
'cadastro.Cliente', related_name="dest_nfe_saida", on_delete=models.SET_NULL, null=True, blank=True)
# Cobranca Fatura(NF-e)
n_fat = models.CharField(max_length=60, null=True, blank=True, unique=True)
v_orig = models.DecimalField(max_digits=13, decimal_places=2, validators=[
MinValueValidator(Decimal('0.00'))], null=True, blank=True)
v_desc = models.DecimalField(max_digits=13, decimal_places=2, validators=[
MinValueValidator(Decimal('0.00'))], null=True, blank=True)
v_liq = models.DecimalField(max_digits=13, decimal_places=2, validators=[
MinValueValidator(Decimal('0.00'))], null=True, blank=True)
grupo_cobr = models.BooleanField(default=True)
class Meta:
verbose_name = "Nota Fiscal"
permissions = (
("view_notafiscal", "Can view nota fiscal"),
("emitir_notafiscal", "Pode emitir notas fiscais"),
("cancelar_notafiscal", "Pode cancelar notas fiscais"),
("gerar_danfe", "Pode gerar DANFE/DANFCE"),
("consultar_cadastro", "Pode consultar cadastro no SEFAZ"),
("inutilizar_notafiscal", "Pode inutilizar notas fiscais"),
("consultar_notafiscal", "Pode consultar notas fiscais"),
("baixar_notafiscal", "Pode baixar notas fiscais"),
("manifestacao_destinatario", "Pode efetuar manifestação do destinatário"),
)
@property
def estado(self):
if self.emit_saida:
if self.emit_saida.endereco_padrao:
return self.emit_saida.endereco_padrao.uf
return ''
def get_emit_cmun(self):
if self.emit_saida:
if self.emit_saida.endereco_padrao:
return self.emit_saida.endereco_padrao.cmun
return ''
def __unicode__(self):
s = u'Série %s, Nº %s, Chave %s' % (
self.serie, self.n_nf_saida, self.chave)
return s
def __str__(self):
s = u'Série %s, Nº %s, Chave %s' % (
self.serie, self.n_nf_saida, self.chave)
return s
class NotaFiscalEntrada(NotaFiscal):
n_nf_entrada = models.CharField(max_length=9, validators=[
RegexValidator(r'^\d{1,10}$')])
compra = models.ForeignKey('compras.PedidoCompra', related_name="compra_nfe",
on_delete=models.SET_NULL, null=True, blank=True)
emit_entrada = models.ForeignKey(
'cadastro.Fornecedor', related_name="emit_nfe_entrada", on_delete=models.SET_NULL, null=True, blank=True)
dest_entrada = models.ForeignKey(
'cadastro.Empresa', related_name="dest_nfe_entrada", on_delete=models.SET_NULL, null=True, blank=True)
class Meta:
verbose_name = "Nota Fiscal de Fornecedor"
permissions = (
("view_notafiscalentrada", "Can view nota fiscal entrada"),
)
@property
def estado(self):
if self.emit_entrada:
if self.emit_entrada.endereco_padrao:
return self.emit_entrada.endereco_padrao.uf
return ''
def __unicode__(self):
s = u'Série %s, Nº %s, Chave %s' % (
self.serie, self.n_nf_entrada, self.chave)
return s
def __str__(self):
s = u'Série %s, Nº %s, Chave %s' % (
self.serie, self.n_nf_entrada, self.chave)
return s
class AutXML(models.Model):
nfe = models.ForeignKey('fiscal.NotaFiscalSaida',
related_name="aut_xml", on_delete=models.CASCADE)
cpf_cnpj = models.CharField(max_length=32, null=True, blank=True)
def get_cpf_cnpj_apenas_digitos(self):
return re.sub('[./-]', '', self.cpf_cnpj)
class ConfiguracaoNotaFiscal(models.Model):
arquivo_certificado_a1 = models.FileField(
upload_to='arquivos/certificado/', null=True, blank=True)
senha_certificado = models.CharField(max_length=255, null=True, blank=True)
serie_atual = models.CharField(max_length=3, default='101')
ambiente = models.CharField(
max_length=1, choices=TP_AMB_ESCOLHAS, default=u'2')
imp_danfe = models.CharField(
max_length=1, choices=TP_IMP_ESCOLHAS, default=u'1')
inserir_logo_danfe = models.BooleanField(default=True)
orientacao_logo_danfe = models.CharField(
max_length=1, choices=ORIENTACAO_LOGO_DANFE, default=u'H')
csc = models.CharField(max_length=64, null=True, blank=True)
cidtoken = models.CharField(max_length=8, null=True, blank=True)
class Meta:
default_permissions = ()
verbose_name = "Configuração NF-e"
permissions = (
("view_configuracaonotafiscal", "Can view configuracao nota fiscal"),
("configurar_nfe", "Pode modificar configuração de NF-e"),
)
@property
def leiaute_logo_vertical(self):
if self.orientacao_logo_danfe == 'H':
return False
else:
return True
def get_certificado_a1(self):
return os.path.join(MEDIA_ROOT, self.arquivo_certificado_a1.name)
class ErrosValidacaoNotaFiscal(models.Model):
nfe = models.ForeignKey('fiscal.NotaFiscalSaida',
related_name="erros_nfe", on_delete=models.CASCADE)
tipo = models.CharField(
max_length=1, choices=ERROS_NFE_TIPOS, null=True, blank=True)
descricao = models.CharField(max_length=255, null=True, blank=True)
class RespostaSefazNotaFiscal(models.Model):
nfe = models.ForeignKey('fiscal.NotaFiscalSaida',
related_name="erros_nfe_sefaz", on_delete=models.CASCADE)
tipo = models.CharField(
max_length=1, choices=RETORNO_SEFAZ_TIPOS, null=True, blank=True)
codigo = models.CharField(max_length=3, null=True, blank=True)
descricao = models.CharField(max_length=255, null=True, blank=True)
| 34.929204
| 113
| 0.638544
|
4a0b8213f39a268ec4669c50d1e2a67c7a592920
| 1,216
|
py
|
Python
|
chapter_01/p06_string_compression.py
|
efecini/cracking-the-code-interview
|
488b46a6f66184e28f88cd459be427e8a31e77f4
|
[
"MIT"
] | null | null | null |
chapter_01/p06_string_compression.py
|
efecini/cracking-the-code-interview
|
488b46a6f66184e28f88cd459be427e8a31e77f4
|
[
"MIT"
] | null | null | null |
chapter_01/p06_string_compression.py
|
efecini/cracking-the-code-interview
|
488b46a6f66184e28f88cd459be427e8a31e77f4
|
[
"MIT"
] | null | null | null |
import time
import unittest
def compress_string(string):
compressed = []
counter = 0
for i in range(len(string)): # noqa
if i != 0 and string[i] != string[i - 1]:
compressed.append(string[i - 1] + str(counter))
counter = 0
counter += 1
# add last repeated character
if counter:
compressed.append(string[-1] + str(counter))
# returns original string if compressed string isn't smaller
return min(string, "".join(compressed), key=len)
class Test(unittest.TestCase):
test_cases = [
("aabcccccaaa", "a2b1c5a3"),
("abcdef", "abcdef"),
("aabb", "aabb"),
("aaa", "a3"),
("a", "a"),
("", ""),
]
testable_functions = [
compress_string,
]
def test_string_compression(self):
for f in self.testable_functions:
start = time.perf_counter()
for _ in range(1000):
for test_string, expected in self.test_cases:
assert f(test_string) == expected
duration = time.perf_counter() - start
print(f"{f.__name__} {duration * 1000:.1f}ms")
if __name__ == "__main__":
unittest.main()
| 25.333333
| 64
| 0.555099
|
4a0b831669978d66ee48a67c9073f513129e9221
| 775
|
py
|
Python
|
sklvq/distances/tests/test_euclidean.py
|
rickvanveen/LVQLib
|
4fba52a14ed37b0444becb96ef09c40d38d263ff
|
[
"BSD-3-Clause"
] | 44
|
2020-10-21T19:54:29.000Z
|
2022-03-23T15:43:52.000Z
|
sklvq/distances/tests/test_euclidean.py
|
rickvanveen/LVQLib
|
4fba52a14ed37b0444becb96ef09c40d38d263ff
|
[
"BSD-3-Clause"
] | 40
|
2020-10-30T13:34:23.000Z
|
2021-06-30T09:32:59.000Z
|
sklvq/distances/tests/test_euclidean.py
|
rickvanveen/LVQLib
|
4fba52a14ed37b0444becb96ef09c40d38d263ff
|
[
"BSD-3-Clause"
] | 5
|
2021-03-15T13:10:03.000Z
|
2021-06-22T16:32:38.000Z
|
import numpy as np
from .test_common import check_distance
from .test_common import check_init_distance
from sklvq.models import GLVQ
def test_euclidean():
check_init_distance("euclidean")
data = np.array([[1, 2, 3], [-1, -2, -3], [0, 0, 0]], dtype="float64")
p = np.array([[1, 2, 3], [-1, -2, -3], [0, 0, 0]])
model = GLVQ(distance_type="euclidean")
model.fit(data, np.array([0, 1, 2]))
model.set_prototypes(p)
check_distance(model._distance, data, model)
# Check force_all_finite settings
model = GLVQ(distance_type="euclidean", force_all_finite="allow-nan")
model.fit(data, np.array([0, 1, 2]))
model.set_prototypes(p)
data[0, 0] = np.nan
data[1, 0] = np.nan
check_distance(model._distance, data, model)
| 24.21875
| 74
| 0.650323
|
4a0b83ac4ac42ec6cc437a1a5de66d18953e9d3a
| 931
|
bzl
|
Python
|
third_party/llvm/workspace.bzl
|
glarik/tensorflow
|
0022bdd0838cc3783c60804ba0bdeebf3d51df21
|
[
"Apache-2.0"
] | 1
|
2021-12-15T18:26:58.000Z
|
2021-12-15T18:26:58.000Z
|
third_party/llvm/workspace.bzl
|
glarik/tensorflow
|
0022bdd0838cc3783c60804ba0bdeebf3d51df21
|
[
"Apache-2.0"
] | null | null | null |
third_party/llvm/workspace.bzl
|
glarik/tensorflow
|
0022bdd0838cc3783c60804ba0bdeebf3d51df21
|
[
"Apache-2.0"
] | null | null | null |
"""Provides the repository macro to import LLVM."""
load("//third_party:repo.bzl", "tf_http_archive")
def repo(name):
"""Imports LLVM."""
LLVM_COMMIT = "df6d0579e18e868ef4b6e97794eacd5af86e1b8a"
LLVM_SHA256 = "badaf6e0e5331669a7d572e0c45f2ed611629e9340a0212e891acbd29730f069"
tf_http_archive(
name = name,
sha256 = LLVM_SHA256,
strip_prefix = "llvm-project-" + LLVM_COMMIT,
urls = [
"https://storage.googleapis.com/mirror.tensorflow.org/github.com/llvm/llvm-project/archive/{commit}.tar.gz".format(commit = LLVM_COMMIT),
"https://github.com/llvm/llvm-project/archive/{commit}.tar.gz".format(commit = LLVM_COMMIT),
],
link_files = {
"//third_party/llvm:llvm.autogenerated.BUILD": "llvm/BUILD",
"//third_party/mlir:BUILD": "mlir/BUILD",
"//third_party/mlir:test.BUILD": "mlir/test/BUILD",
},
)
| 38.791667
| 149
| 0.646617
|
4a0b847d2faeaba392f9f41a482c20b0ed243ebe
| 1,381
|
py
|
Python
|
Scripts/allocationcheck.py
|
mrbinx/mrbinx_python
|
abc14762f6afd4e23ccd95cecd59a637ced20d89
|
[
"MIT"
] | null | null | null |
Scripts/allocationcheck.py
|
mrbinx/mrbinx_python
|
abc14762f6afd4e23ccd95cecd59a637ced20d89
|
[
"MIT"
] | null | null | null |
Scripts/allocationcheck.py
|
mrbinx/mrbinx_python
|
abc14762f6afd4e23ccd95cecd59a637ced20d89
|
[
"MIT"
] | null | null | null |
inp = str("X = alloc(regA, regB, regA, regC, regA) ;\
X = alloc(regA, regB, regA, regC, regB) ;\
X = alloc(regA, regB, regC, regA, regB) ;\
X = alloc(regA, regB, regC, regA, regC) ;\
X = alloc(regA, regC, regA, regB, regA) ;\
X = alloc(regA, regC, regA, regB, regC) ;\
X = alloc(regA, regC, regB, regA, regB) ;\
X = alloc(regA, regC, regB, regA, regC) ;\
X = alloc(regB, regA, regB, regC, regA) ;\
X = alloc(regB, regA, regB, regC, regB) ;\
X = alloc(regB, regA, regC, regB, regA) ;\
X = alloc(regB, regA, regC, regB, regC) ;\
X = alloc(regB, regC, regA, regB, regA) ;\
X = alloc(regB, regC, regA, regB, regC) ;\
X = alloc(regB, regC, regB, regA, regB) ;\
X = alloc(regB, regC, regB, regA, regC) ;\
X = alloc(regC, regA, regB, regC, regA) ;\
X = alloc(regC, regA, regB, regC, regB) ;\
X = alloc(regC, regA, regC, regB, regA) ;\
X = alloc(regC, regA, regC, regB, regC) ;\
X = alloc(regC, regB, regA, regC, regA) ;\
X = alloc(regC, regB, regA, regC, regB) ;\
X = alloc(regC, regB, regC, regA, regB) ;\
X = alloc(regC, regB, regC, regA, regC) ;")
inxx = inp.split(" ;")
inxx = inxx[0:-2]
print(inxx)
for x in inxx:
y = x[10:-1]
#print(y)
inx = y.split(", ")
#print(inx)
if inx[0] == inx[1]:
print("X")
elif inx[1] == inx[2]:
print("X")
elif inx[2] == inx[3]:
print("X")
elif inx[3] == inx[4]:
print("X")
elif inx[1] == inx[3]:
print("X")
else:
print("EXEC")
| 28.183673
| 53
| 0.57929
|
4a0b8503fed2bba423cb0c1d9b961292728e789a
| 6,010
|
py
|
Python
|
lib/python/treadmill/dnsctx.py
|
krcooke/treadmill
|
613008fee88a150f983ab12d8ef2e118fb77bb51
|
[
"Apache-2.0"
] | 133
|
2016-09-15T13:36:12.000Z
|
2021-01-18T06:29:13.000Z
|
lib/python/treadmill/dnsctx.py
|
krcooke/treadmill
|
613008fee88a150f983ab12d8ef2e118fb77bb51
|
[
"Apache-2.0"
] | 108
|
2016-12-28T23:41:27.000Z
|
2020-03-05T21:20:37.000Z
|
lib/python/treadmill/dnsctx.py
|
krcooke/treadmill
|
613008fee88a150f983ab12d8ef2e118fb77bb51
|
[
"Apache-2.0"
] | 69
|
2016-09-23T20:38:58.000Z
|
2020-11-11T02:31:21.000Z
|
"""DNS Context.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import logging
import os
import random
from treadmill import dnsutils
from treadmill import context
_LOGGER = logging.getLogger(__name__)
def _resolve_srv(dns_domain, dns_server, srv_rec):
"""Returns randomized list of host, port tuples for given srv record.
"""
_LOGGER.debug('Query DNS -t SRV %s.%s', srv_rec, dns_domain)
if not dns_domain:
raise context.ContextError('Treadmill DNS domain not specified.')
result = dnsutils.srv(
srv_rec + '.' + dns_domain, dns_server
)
random.shuffle(result)
return result
def _srv_to_urls(srv_recs, protocol=None):
"""Converts list of SRV records to list of URLs.
"""
return [dnsutils.srv_rec_to_url(srv_rec,
protocol=protocol)
for srv_rec in srv_recs]
def _api(ctx, target, proto=None):
"""Resolve cell api."""
srv_recs = _resolve_srv(ctx.dns_domain, ctx.dns_server, target)
if not srv_recs:
raise context.ContextError('No srv records found: %s' % target)
return (srv_recs, proto)
def _cell_api(ctx, scope=None):
"""Resolve cell api given context and scope.
Default srv lookup - _http._tcp.cellapi.<cell>.cell
Override - environment var: TREADMILL_CELLAPI_LOOKUP_<cell>
all upper case.
"""
if scope is None:
if not ctx.cell:
raise context.ContextError('Cell not specified.')
scope = cell_scope(ctx.cell)
# Check if there is srv record override for the given cell.
env_override = 'TREADMILL_CELLAPI_LOOKUP_{cell}'.format(
cell=ctx.cell
).upper()
srvlookup = os.environ.get(env_override, '_http._tcp.cellapi.{scope}')
return _api(ctx, srvlookup.format(scope=scope, cell=ctx.cell), 'http')
def _state_api(ctx, scope=None):
"""Resolve state api given context and scope.
Default srv lookup - _http._tcp.stateapi.<cell>.cell
Override - environment var: TREADMILL_STATEAPI_LOOKUP_<cell>
all upper case.
"""
if scope is None:
if not ctx.cell:
raise context.ContextError('Cell not specified.')
scope = cell_scope(ctx.cell)
env_override = 'TREADMILL_STATEAPI_LOOKUP_{cell}'.format(
cell=ctx.cell
).upper()
srvlookup = os.environ.get(env_override, '_http._tcp.stateapi.{scope}')
return _api(ctx, srvlookup.format(scope=scope, cell=ctx.cell), 'http')
def _ws_api(ctx, scope=None):
"""Resolve webscocket api given context and scope.
Default srv lookup - _ws._tcp.wsapi.<cell>.cell
Override - environment var: TREADMILL_WS_LOOKUP_<cell>
all upper case.
"""
if scope is None:
if not ctx.cell:
raise context.ContextError('Cell not specified.')
scope = cell_scope(ctx.cell)
env_override = 'TREADMILL_WSAPI_LOOKUP_{cell}'.format(
cell=ctx.cell
).upper()
srvlookup = os.environ.get(env_override, '_ws._tcp.wsapi.{scope}')
return _api(ctx, srvlookup.format(scope=scope, cell=ctx.cell), 'ws')
def _admin_api(ctx, scope=None):
"""Resolve admin API SRV records."""
# Default.
def _lookup(ctx, scope):
"""Lookup admin api based on scope."""
if scope == 'global':
default_lookup = '_http._tcp.adminapi'
else:
default_lookup = '_http._tcp.adminapi.{scope}'
env_override = 'TREADMILL_ADMINAPI_LOOKUP_{scope}'.format(
scope=scope
).upper().replace('.', '_')
srvlookup = os.environ.get(env_override, default_lookup)
if not srvlookup:
return None
return _api(ctx, srvlookup.format(scope=scope), 'http')
if scope is not None:
return _lookup(ctx, scope)
else:
scopes = ctx.get('api_scope', [])
if 'global' not in scopes:
scopes.append('global')
for api_scope in scopes:
try:
result = _lookup(ctx, api_scope)
if result:
return result
except context.ContextError:
pass
raise context.ContextError('no admin api found.')
def _zk_url(ctx):
"""Resolve Zookeeper connection string from DNS."""
if not ctx.dns_domain:
_LOGGER.warning('DNS domain is not set.')
zkurl_rec = dnsutils.txt('zk.%s' % (ctx.cell), ctx.dns_server)
else:
zkurl_rec = dnsutils.txt(
'zk.%s.%s' % (ctx.cell, ctx.dns_domain),
ctx.dns_server
)
if zkurl_rec:
return zkurl_rec[0]
else:
return None
def _ldap_url(ctx):
"""Resolve LDAP for given cell."""
if not ctx.cell:
raise context.ContextError('Cell not specified.')
ldap_srv_rec = dnsutils.srv(
'_ldap._tcp.%s.%s' % (ctx.cell, ctx.dns_domain),
ctx.dns_server
)
return _srv_to_urls(ldap_srv_rec, 'ldap')
_RESOLVERS = {
'admin_api': lambda ctx: _srv_to_urls(*_admin_api(ctx)),
'cell_api': lambda ctx: _srv_to_urls(*_cell_api(ctx)),
'ldap_url': _ldap_url,
'state_api': lambda ctx: _srv_to_urls(*_state_api(ctx)),
'ws_api': lambda ctx: _srv_to_urls(*_ws_api(ctx)),
'zk_url': _zk_url,
}
def resolve(ctx, attr):
"""URL Resolve attribute from DNS.
"""
url = _RESOLVERS[attr](ctx)
_LOGGER.debug('Resolved from DNS: %s - %s', attr, url)
return url
_APILOOKUPS = {
'admin_api': _admin_api,
'cell_api': _cell_api,
'state_api': _state_api,
'ws_api': _ws_api,
}
def lookup(ctx, attr, scope=None):
"""Do a srv lookup in DNS.
"""
value = _APILOOKUPS[attr](ctx, scope=scope)
_LOGGER.debug('API SRV Lookedup from DNS: %s - %r', attr, value)
return value
def cell_scope(cell):
"""Returns a cell's scope (subdomain) in DNS.
"""
return '{cell}.cell'.format(cell=cell)
def init(_ctx):
"""Init context.
"""
| 26.359649
| 75
| 0.63411
|
4a0b853f3997dbeb60a732fbce26af498a89c9e3
| 24,311
|
py
|
Python
|
test/aqua/test_amplitude_estimation_circuitfactory.py
|
MartenSkogh/qiskit-aqua
|
4a997e6328e06e250212ef82c9414ad16834b7c6
|
[
"Apache-2.0"
] | 1
|
2020-10-02T15:35:03.000Z
|
2020-10-02T15:35:03.000Z
|
test/aqua/test_amplitude_estimation_circuitfactory.py
|
MartenSkogh/qiskit-aqua
|
4a997e6328e06e250212ef82c9414ad16834b7c6
|
[
"Apache-2.0"
] | null | null | null |
test/aqua/test_amplitude_estimation_circuitfactory.py
|
MartenSkogh/qiskit-aqua
|
4a997e6328e06e250212ef82c9414ad16834b7c6
|
[
"Apache-2.0"
] | null | null | null |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the quantum amplitude estimation algorithm."""
import warnings
import unittest
from test.aqua import QiskitAquaTestCase
import numpy as np
from ddt import ddt, idata, data, unpack
from qiskit import QuantumRegister, QuantumCircuit, BasicAer, execute
from qiskit.circuit.library import QFT
from qiskit.aqua import QuantumInstance
from qiskit.aqua.components.uncertainty_models import GaussianConditionalIndependenceModel as GCI
from qiskit.aqua.components.uncertainty_problems import \
UnivariatePiecewiseLinearObjective as PwlObjective
from qiskit.aqua.components.uncertainty_problems import (MultivariateProblem,
UncertaintyProblem)
from qiskit.aqua.circuits import WeightedSumOperator
from qiskit.aqua.algorithms import (AmplitudeEstimation, MaximumLikelihoodAmplitudeEstimation,
IterativeAmplitudeEstimation)
from qiskit.aqua.algorithms.amplitude_estimators.q_factory import QFactory
class BernoulliAFactory(UncertaintyProblem):
r"""Circuit Factory representing the operator A in a Bernoulli problem.
Given a probability $p$, the operator A prepares the state $\sqrt{1 - p}|0> + \sqrt{p}|1>$.
"""
def __init__(self, probability=0.5):
#
super().__init__(1)
self._probability = probability
self.i_state = 0
self._theta_p = 2 * np.arcsin(np.sqrt(probability))
def build(self, qc, q, q_ancillas=None, params=None):
# A is a rotation of angle theta_p around the Y-axis
qc.ry(self._theta_p, q[self.i_state])
def value_to_estimation(self, value):
return value
class BernoulliQFactory(QFactory):
"""Circuit Factory representing the operator Q in a Bernoulli problem.
This implementation exploits the fact that powers of Q can be implemented efficiently by just
multiplying the angle. Note, that since amplitude estimation only requires controlled powers of
Q only that method is overridden.
"""
def __init__(self, bernoulli_expected_value):
super().__init__(bernoulli_expected_value, i_objective=0)
def build(self, qc, q, q_ancillas=None, params=None):
i_state = self.a_factory.i_state
theta_p = self.a_factory._theta_p
# Q is a rotation of angle 2*theta_p around the Y-axis
qc.ry(2 * theta_p, q[i_state])
def build_power(self, qc, q, power, q_ancillas=None):
i_state = self.a_factory.i_state
theta_p = self.a_factory._theta_p
qc.ry(2 * power * theta_p, q[i_state])
def build_controlled_power(self, qc, q, q_control, power,
q_ancillas=None, use_basis_gates=True):
i_state = self.a_factory.i_state
theta_p = self.a_factory._theta_p
qc.cry(2 * power * theta_p, q_control, q[i_state])
class SineIntegralAFactory(UncertaintyProblem):
r"""Construct the A operator to approximate the integral
\int_0^1 \sin^2(x) d x
with a specified number of qubits.
"""
def __init__(self, num_qubits):
super().__init__(num_qubits + 1)
self._i_objective = num_qubits
def build(self, qc, q, q_ancillas=None, params=None):
n = self.num_target_qubits - 1
q_state = [q[i] for i in range(self.num_target_qubits) if i != self._i_objective]
q_objective = q[self._i_objective]
# prepare 1/sqrt{2^n} sum_x |x>_n
for q_i in q_state:
qc.h(q_i)
# apply the sine/cosine term
qc.ry(2 * 1 / 2 / 2**n, q_objective)
for i, q_i in enumerate(q_state):
qc.cry(2 * 2**i / 2**n, q_i, q_objective)
@ddt
class TestBernoulli(QiskitAquaTestCase):
"""Tests based on the Bernoulli A operator.
This class tests
* the estimation result
* the constructed circuits
"""
def setUp(self):
super().setUp()
warnings.filterwarnings(action="ignore", category=DeprecationWarning)
self._statevector = QuantumInstance(backend=BasicAer.get_backend('statevector_simulator'),
seed_simulator=2, seed_transpiler=2)
self._unitary = QuantumInstance(backend=BasicAer.get_backend('unitary_simulator'), shots=1,
seed_simulator=42, seed_transpiler=91)
def qasm(shots=100):
return QuantumInstance(backend=BasicAer.get_backend('qasm_simulator'), shots=shots,
seed_simulator=2, seed_transpiler=2)
self._qasm = qasm
def tearDown(self):
super().tearDown()
warnings.filterwarnings(action="always", category=DeprecationWarning)
@idata([
[0.2, AmplitudeEstimation(2), {'estimation': 0.5, 'mle': 0.2}],
[0.4, AmplitudeEstimation(4), {'estimation': 0.30866, 'mle': 0.4}],
[0.82, AmplitudeEstimation(5), {'estimation': 0.85355, 'mle': 0.82}],
[0.49, AmplitudeEstimation(3), {'estimation': 0.5, 'mle': 0.49}],
[0.2, MaximumLikelihoodAmplitudeEstimation(2), {'estimation': 0.2}],
[0.4, MaximumLikelihoodAmplitudeEstimation(4), {'estimation': 0.4}],
[0.82, MaximumLikelihoodAmplitudeEstimation(5), {'estimation': 0.82}],
[0.49, MaximumLikelihoodAmplitudeEstimation(3), {'estimation': 0.49}],
[0.2, IterativeAmplitudeEstimation(0.1, 0.1), {'estimation': 0.2}],
[0.4, IterativeAmplitudeEstimation(0.00001, 0.01), {'estimation': 0.4}],
[0.82, IterativeAmplitudeEstimation(0.00001, 0.05), {'estimation': 0.82}],
[0.49, IterativeAmplitudeEstimation(0.001, 0.01), {'estimation': 0.49}]
])
@unpack
def test_statevector(self, prob, qae, expect):
"""Test running QAE using the statevector simulator."""
# construct factories for A and Q
qae.a_factory = BernoulliAFactory(prob)
qae.q_factory = BernoulliQFactory(qae.a_factory)
result = qae.run(self._statevector)
for key, value in expect.items():
self.assertAlmostEqual(value, result[key], places=3,
msg="estimate `{}` failed".format(key))
@idata([
[0.2, 100, AmplitudeEstimation(4), {'estimation': 0.14644, 'mle': 0.193888}],
[0.0, 1000, AmplitudeEstimation(2), {'estimation': 0.0, 'mle': 0.0}],
[0.8, 10, AmplitudeEstimation(7), {'estimation': 0.79784, 'mle': 0.801612}],
[0.2, 100, MaximumLikelihoodAmplitudeEstimation(4), {'estimation': 0.199606}],
[0.4, 1000, MaximumLikelihoodAmplitudeEstimation(6), {'estimation': 0.399488}],
# [0.8, 10, MaximumLikelihoodAmplitudeEstimation(7), {'estimation': 0.800926}],
[0.2, 100, IterativeAmplitudeEstimation(0.0001, 0.01), {'estimation': 0.199987}],
[0.4, 1000, IterativeAmplitudeEstimation(0.001, 0.05), {'estimation': 0.400071}],
[0.8, 10, IterativeAmplitudeEstimation(0.1, 0.05), {'estimation': 0.811711}]
])
@unpack
def test_qasm(self, prob, shots, qae, expect):
""" qasm test """
# construct factories for A and Q
qae.a_factory = BernoulliAFactory(prob)
qae.q_factory = BernoulliQFactory(qae.a_factory)
result = qae.run(self._qasm(shots))
for key, value in expect.items():
self.assertAlmostEqual(value, result[key], places=3,
msg="estimate `{}` failed".format(key))
@data(True, False)
def test_qae_circuit(self, efficient_circuit):
"""Test circuits resulting from canonical amplitude estimation.
Build the circuit manually and from the algorithm and compare the resulting unitaries.
"""
prob = 0.5
for m in range(2, 7):
qae = AmplitudeEstimation(m, a_factory=BernoulliAFactory(prob))
angle = 2 * np.arcsin(np.sqrt(prob))
# manually set up the inefficient AE circuit
q_ancilla = QuantumRegister(m, 'a')
q_objective = QuantumRegister(1, 'q')
circuit = QuantumCircuit(q_ancilla, q_objective)
# initial Hadamard gates
for i in range(m):
circuit.h(q_ancilla[i])
# A operator
circuit.ry(angle, q_objective)
if efficient_circuit:
qae.q_factory = BernoulliQFactory(qae.a_factory)
for power in range(m):
circuit.cry(2 * 2 ** power * angle, q_ancilla[power], q_objective[0])
else:
q_factory = QFactory(qae.a_factory, i_objective=0)
for power in range(m):
for _ in range(2**power):
q_factory.build_controlled(circuit, q_objective, q_ancilla[power])
# fourier transform
iqft = QFT(m, do_swaps=False).inverse()
circuit.append(iqft.to_instruction(), q_ancilla)
expected_unitary = self._unitary.execute(circuit).get_unitary()
actual_circuit = qae.construct_circuit(measurement=False)
actual_unitary = self._unitary.execute(actual_circuit).get_unitary()
diff = np.sum(np.abs(actual_unitary - expected_unitary))
self.assertAlmostEqual(diff, 0)
@data(True, False)
def test_iqae_circuits(self, efficient_circuit):
"""Test circuits resulting from iterative amplitude estimation.
Build the circuit manually and from the algorithm and compare the resulting unitaries.
"""
prob = 0.5
for k in range(2, 7):
qae = IterativeAmplitudeEstimation(0.01, 0.05, a_factory=BernoulliAFactory(prob))
angle = 2 * np.arcsin(np.sqrt(prob))
# manually set up the inefficient AE circuit
q_objective = QuantumRegister(1, 'q')
circuit = QuantumCircuit(q_objective)
# A operator
circuit.ry(angle, q_objective)
if efficient_circuit:
qae.q_factory = BernoulliQFactory(qae.a_factory)
# for power in range(k):
# circuit.ry(2 ** power * angle, q_objective[0])
circuit.ry(2 * k * angle, q_objective[0])
else:
q_factory = QFactory(qae.a_factory, i_objective=0)
for _ in range(k):
q_factory.build(circuit, q_objective)
expected_unitary = self._unitary.execute(circuit).get_unitary()
actual_circuit = qae.construct_circuit(k, measurement=False)
actual_unitary = self._unitary.execute(actual_circuit).get_unitary()
diff = np.sum(np.abs(actual_unitary - expected_unitary))
self.assertAlmostEqual(diff, 0)
@data(True, False)
def test_mlae_circuits(self, efficient_circuit):
""" Test the circuits constructed for MLAE """
prob = 0.5
for k in range(1, 7):
qae = MaximumLikelihoodAmplitudeEstimation(k, a_factory=BernoulliAFactory(prob))
angle = 2 * np.arcsin(np.sqrt(prob))
# compute all the circuits used for MLAE
circuits = []
# 0th power
q_objective = QuantumRegister(1, 'q')
circuit = QuantumCircuit(q_objective)
circuit.ry(angle, q_objective)
circuits += [circuit]
# powers of 2
for power in range(k):
q_objective = QuantumRegister(1, 'q')
circuit = QuantumCircuit(q_objective)
# A operator
circuit.ry(angle, q_objective)
# Q^(2^j) operator
if efficient_circuit:
qae.q_factory = BernoulliQFactory(qae.a_factory)
circuit.ry(2 * 2 ** power * angle, q_objective[0])
else:
q_factory = QFactory(qae.a_factory, i_objective=0)
for _ in range(2**power):
q_factory.build(circuit, q_objective)
actual_circuits = qae.construct_circuits(measurement=False)
for actual, expected in zip(actual_circuits, circuits):
expected_unitary = self._unitary.execute(expected).get_unitary()
actual_unitary = self._unitary.execute(actual).get_unitary()
diff = np.sum(np.abs(actual_unitary - expected_unitary))
self.assertAlmostEqual(diff, 0)
@ddt
class TestProblemSetting(QiskitAquaTestCase):
"""Test the setting and getting of the A and Q operator and the objective qubit index."""
def setUp(self):
super().setUp()
warnings.filterwarnings(action="ignore", category=DeprecationWarning)
self.a_bernoulli = BernoulliAFactory(0)
self.q_bernoulli = BernoulliQFactory(self.a_bernoulli)
self.i_bernoulli = 0
num_qubits = 5
self.a_integral = SineIntegralAFactory(num_qubits)
self.q_intergal = QFactory(self.a_integral, num_qubits)
self.i_intergal = num_qubits
def tearDown(self):
super().tearDown()
warnings.filterwarnings(action="always", category=DeprecationWarning)
@idata([
[AmplitudeEstimation(2)],
[IterativeAmplitudeEstimation(0.1, 0.001)],
[MaximumLikelihoodAmplitudeEstimation(3)],
])
@unpack
def test_operators(self, qae):
""" Test if A/Q operator + i_objective set correctly """
self.assertIsNone(qae.a_factory)
self.assertIsNone(qae.q_factory)
self.assertIsNone(qae.i_objective)
self.assertIsNone(qae._a_factory)
self.assertIsNone(qae._q_factory)
self.assertIsNone(qae._i_objective)
qae.a_factory = self.a_bernoulli
self.assertIsNotNone(qae.a_factory)
self.assertIsNotNone(qae.q_factory)
self.assertIsNotNone(qae.i_objective)
self.assertIsNotNone(qae._a_factory)
self.assertIsNone(qae._q_factory)
self.assertIsNone(qae._i_objective)
qae.q_factory = self.q_bernoulli
self.assertIsNotNone(qae.a_factory)
self.assertIsNotNone(qae.q_factory)
self.assertIsNotNone(qae.i_objective)
self.assertIsNotNone(qae._a_factory)
self.assertIsNotNone(qae._q_factory)
self.assertIsNone(qae._i_objective)
qae.i_objective = self.i_bernoulli
self.assertIsNotNone(qae.a_factory)
self.assertIsNotNone(qae.q_factory)
self.assertIsNotNone(qae.i_objective)
self.assertIsNotNone(qae._a_factory)
self.assertIsNotNone(qae._q_factory)
self.assertIsNotNone(qae._i_objective)
@data(
AmplitudeEstimation(2),
IterativeAmplitudeEstimation(0.1, 0.001),
MaximumLikelihoodAmplitudeEstimation(3),
)
def test_a_factory_update(self, qae):
"""Test if the Q factory is updated if the a_factory changes -- except set manually."""
# Case 1: Set to BernoulliAFactory with default Q operator
qae.a_factory = self.a_bernoulli
self.assertIsInstance(qae.q_factory.a_factory, BernoulliAFactory)
self.assertEqual(qae.i_objective, self.i_bernoulli)
# Case 2: Change to SineIntegralAFactory with default Q operator
qae.a_factory = self.a_integral
self.assertIsInstance(qae.q_factory.a_factory, SineIntegralAFactory)
self.assertEqual(qae.i_objective, self.i_intergal)
# Case 3: Set to BernoulliAFactory with special Q operator
qae.a_factory = self.a_bernoulli
qae.q_factory = self.q_bernoulli
self.assertIsInstance(qae.q_factory, BernoulliQFactory)
self.assertEqual(qae.i_objective, self.i_bernoulli)
# Case 4: Set to SineIntegralAFactory, and do not set Q. Then the old Q operator
# should remain
qae.a_factory = self.a_integral
self.assertIsInstance(qae.q_factory, BernoulliQFactory)
self.assertEqual(qae.i_objective, self.i_bernoulli)
@ddt
class TestSineIntegral(QiskitAquaTestCase):
"""Tests based on the A operator to integrate sin^2(x).
This class tests
* the estimation result
* the confidence intervals
"""
def setUp(self):
super().setUp()
warnings.filterwarnings(action="ignore", category=DeprecationWarning)
self._statevector = QuantumInstance(backend=BasicAer.get_backend('statevector_simulator'),
seed_simulator=123,
seed_transpiler=41)
def qasm(shots=100):
return QuantumInstance(backend=BasicAer.get_backend('qasm_simulator'), shots=shots,
seed_simulator=7192, seed_transpiler=90000)
self._qasm = qasm
def tearDown(self):
super().tearDown()
warnings.filterwarnings(action="always", category=DeprecationWarning)
@idata([
[2, AmplitudeEstimation(2), {'estimation': 0.5, 'mle': 0.270290}],
[4, MaximumLikelihoodAmplitudeEstimation(4), {'estimation': 0.272675}],
[3, IterativeAmplitudeEstimation(0.1, 0.1), {'estimation': 0.272082}],
])
@unpack
def test_statevector(self, n, qae, expect):
""" Statevector end-to-end test """
# construct factories for A and Q
qae.a_factory = SineIntegralAFactory(n)
result = qae.run(self._statevector)
for key, value in expect.items():
self.assertAlmostEqual(value, result[key], places=3,
msg="estimate `{}` failed".format(key))
@idata([
[4, 10, AmplitudeEstimation(2), {'estimation': 0.5, 'mle': 0.333333}],
[3, 10, MaximumLikelihoodAmplitudeEstimation(2), {'estimation': 0.256878}],
[3, 1000, IterativeAmplitudeEstimation(0.01, 0.01), {'estimation': 0.271790}],
])
@unpack
def test_qasm(self, n, shots, qae, expect):
"""QASM simulator end-to-end test."""
# construct factories for A and Q
qae.a_factory = SineIntegralAFactory(n)
result = qae.run(self._qasm(shots))
for key, value in expect.items():
self.assertAlmostEqual(value, result[key], places=3,
msg="estimate `{}` failed".format(key))
@idata([
[AmplitudeEstimation(3), 'mle',
{'likelihood_ratio': [0.24947346406470136, 0.3003771197734433],
'fisher': [0.24861769995820207, 0.2999286066724035],
'observed_fisher': [0.24845622030041542, 0.30009008633019013]}
],
[MaximumLikelihoodAmplitudeEstimation(3), 'estimation',
{'likelihood_ratio': [0.25987941798909114, 0.27985361366769945],
'fisher': [0.2584889015125656, 0.2797018754936686],
'observed_fisher': [0.2659279996107888, 0.2722627773954454]}],
])
@unpack
def test_confidence_intervals(self, qae, key, expect):
"""End-to-end test for all confidence intervals."""
n = 3
qae.a_factory = SineIntegralAFactory(n)
# statevector simulator
result = qae.run(self._statevector)
methods = ['lr', 'fi', 'oi'] # short for likelihood_ratio, fisher, observed_fisher
alphas = [0.1, 0.00001, 0.9] # alpha shouldn't matter in statevector
for alpha, method in zip(alphas, methods):
confint = qae.confidence_interval(alpha, method)
# confidence interval based on statevector should be empty, as we are sure of the result
self.assertAlmostEqual(confint[1] - confint[0], 0.0)
self.assertAlmostEqual(confint[0], result[key])
# qasm simulator
shots = 100
alpha = 0.01
result = qae.run(self._qasm(shots))
for method, expected_confint in expect.items():
confint = qae.confidence_interval(alpha, method)
self.assertEqual(confint, expected_confint)
self.assertTrue(confint[0] <= result[key] <= confint[1])
def test_iqae_confidence_intervals(self):
"""End-to-end test for the IQAE confidence interval."""
n = 3
qae = IterativeAmplitudeEstimation(0.1, 0.01, a_factory=SineIntegralAFactory(n))
expected_confint = [0.19840508760087738, 0.35110155403424115]
# statevector simulator
result = qae.run(self._statevector)
confint = result['confidence_interval']
# confidence interval based on statevector should be empty, as we are sure of the result
self.assertAlmostEqual(confint[1] - confint[0], 0.0)
self.assertAlmostEqual(confint[0], result['estimation'])
# qasm simulator
shots = 100
result = qae.run(self._qasm(shots))
confint = result['confidence_interval']
self.assertEqual(confint, expected_confint)
self.assertTrue(confint[0] <= result['estimation'] <= confint[1])
@ddt
class TestCreditRiskAnalysis(QiskitAquaTestCase):
"""Test a more difficult example, motivated from Credit Risk Analysis."""
def setUp(self):
super().setUp()
warnings.filterwarnings(action="ignore", category=DeprecationWarning)
def tearDown(self):
super().tearDown()
warnings.filterwarnings(action="always", category=DeprecationWarning)
@data('statevector_simulator')
def test_conditional_value_at_risk(self, simulator):
""" conditional value at risk test """
# define backend to be used
backend = BasicAer.get_backend(simulator)
# set problem parameters
n_z = 2
z_max = 2
# z_values = np.linspace(-z_max, z_max, 2 ** n_z)
p_zeros = [0.15, 0.25]
rhos = [0.1, 0.05]
lgd = [1, 2]
k_l = len(p_zeros)
# alpha = 0.05
# set var value
var = 2
var_prob = 0.961940
# determine number of qubits required to represent total loss
# n_s = WeightedSumOperator.get_required_sum_qubits(lgd)
# create circuit factory (add Z qubits with weight/loss 0)
agg = WeightedSumOperator(n_z + k_l, [0] * n_z + lgd)
# define linear objective
breakpoints = [0, var]
slopes = [0, 1]
offsets = [0, 0] # subtract VaR and add it later to the estimate
f_min = 0
f_max = 3 - var
c_approx = 0.25
# construct circuit factory for uncertainty model (Gaussian Conditional Independence model)
gci = GCI(n_z, z_max, p_zeros, rhos)
cvar_objective = PwlObjective(
agg.num_sum_qubits,
0,
2 ** agg.num_sum_qubits - 1, # max value that can be reached by the qubit register
breakpoints,
slopes,
offsets,
f_min,
f_max,
c_approx
)
multivariate_cvar = MultivariateProblem(gci, agg, cvar_objective)
num_qubits = multivariate_cvar.num_target_qubits
num_ancillas = multivariate_cvar.required_ancillas()
q = QuantumRegister(num_qubits, name='q')
q_a = QuantumRegister(num_ancillas, name='q_a')
qc = QuantumCircuit(q, q_a)
multivariate_cvar.build(qc, q, q_a)
job = execute(qc, backend=backend)
# evaluate resulting statevector
value = 0
for i, a_i in enumerate(job.result().get_statevector()):
b = ('{0:0%sb}' %
multivariate_cvar.num_target_qubits).\
format(i)[-multivariate_cvar.num_target_qubits:]
a_m = np.round(np.real(a_i), decimals=4)
if np.abs(a_m) > 1e-6 and b[0] == '1':
value += a_m ** 2
# normalize and add VaR to estimate
value = multivariate_cvar.value_to_estimation(value)
normalized_value = value / (1.0 - var_prob) + var
# compare to precomputed solution
self.assertEqual(0.0, np.round(normalized_value - 3.3796, decimals=4))
if __name__ == '__main__':
unittest.main()
| 38.959936
| 100
| 0.629879
|
4a0b857f7481f6f4728b557d7dce976aa52cdf93
| 2,765
|
py
|
Python
|
arsenal/tests/unit/external/test_ironic_client_wrapper.py
|
rackerlabs/arsenal
|
39b7a35a9af9dbfd05897c64b2971fcbd219ccdb
|
[
"Apache-2.0"
] | 5
|
2015-04-21T20:46:47.000Z
|
2021-02-21T20:54:49.000Z
|
arsenal/tests/unit/external/test_ironic_client_wrapper.py
|
rackerlabs/arsenal
|
39b7a35a9af9dbfd05897c64b2971fcbd219ccdb
|
[
"Apache-2.0"
] | 69
|
2015-02-12T19:50:17.000Z
|
2017-01-11T20:20:49.000Z
|
arsenal/tests/unit/external/test_ironic_client_wrapper.py
|
rackerlabs/onmetal-image-scheduler
|
39b7a35a9af9dbfd05897c64b2971fcbd219ccdb
|
[
"Apache-2.0"
] | 3
|
2015-08-25T21:39:24.000Z
|
2017-03-13T17:41:04.000Z
|
# Copyright 2014 Red Hat, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from ironicclient import client as ironic_client
import mock
from oslo_config import cfg
from arsenal.external import ironic_client_wrapper as client_wrapper
from arsenal.tests.unit import base as test_base
from arsenal.tests.unit.external import ironic_utils
CONF = cfg.CONF
FAKE_CLIENT = ironic_utils.FakeClient()
def get_new_fake_client(*args, **kwargs):
return ironic_utils.FakeClient()
class IronicClientWrapperTestCase(test_base.TestCase):
def setUp(self):
super(IronicClientWrapperTestCase, self).setUp()
self.ironicclient = client_wrapper.IronicClientWrapper()
# Do not waste time sleeping
cfg.CONF.set_override('call_retry_interval', 0, 'client_wrapper')
@mock.patch.object(ironic_client, 'get_client')
def test__get_client_no_auth_token(self, mock_ir_cli):
self.flags(admin_auth_token=None, group='ironic')
ironicclient = client_wrapper.IronicClientWrapper()
# dummy call to have _get_client() called
ironicclient.call("node.list")
expected = {'os_username': CONF.ironic.admin_username,
'os_password': CONF.ironic.admin_password,
'os_auth_url': CONF.ironic.admin_url,
'os_tenant_name': CONF.ironic.admin_tenant_name,
'os_service_type': 'baremetal',
'os_endpoint_type': 'public',
'ironic_url': CONF.ironic.api_endpoint}
mock_ir_cli.assert_called_once_with(CONF.ironic.api_version,
**expected)
@mock.patch.object(ironic_client, 'get_client')
def test__get_client_with_auth_token(self, mock_ir_cli):
self.flags(admin_auth_token='fake-token', group='ironic')
ironicclient = client_wrapper.IronicClientWrapper()
# dummy call to have _get_client() called
ironicclient.call("node.list")
expected = {'os_auth_token': 'fake-token',
'ironic_url': CONF.ironic.api_endpoint}
mock_ir_cli.assert_called_once_with(CONF.ironic.api_version,
**expected)
| 41.268657
| 78
| 0.682459
|
4a0b8606e8316eab7dd6055007760cc0fb4e57de
| 2,039
|
py
|
Python
|
envs/__init__.py
|
bjinwright/env
|
68bee09ef3224c2d7d94467f65173fbc1ae782bc
|
[
"Apache-2.0"
] | 23
|
2017-03-28T20:09:28.000Z
|
2020-11-05T13:01:29.000Z
|
envs/__init__.py
|
bjinwright/env
|
68bee09ef3224c2d7d94467f65173fbc1ae782bc
|
[
"Apache-2.0"
] | 14
|
2017-09-07T02:58:40.000Z
|
2022-02-07T18:36:21.000Z
|
envs/__init__.py
|
bjinwright/env
|
68bee09ef3224c2d7d94467f65173fbc1ae782bc
|
[
"Apache-2.0"
] | 8
|
2017-09-07T03:08:37.000Z
|
2019-08-13T23:56:12.000Z
|
import ast
import json
import os
import sys
from decimal import Decimal
from .exceptions import EnvsValueException
_envs_list = []
class CLIArguments():
LIST_ENVS = 'list-envs'
CHECK_ENVS = 'check-envs'
CONVERT_SETTINGS = 'convert-settings'
ARGUMENTS = CLIArguments()
ENVS_RESULT_FILENAME = '.envs_result'
def validate_boolean(value):
true_vals = ('True', 'true', 1, '1')
false_vals = ('False', 'false', 0, '0')
if value in true_vals:
value = True
elif value in false_vals:
value = False
else:
raise ValueError('This value is not a boolean value.')
return value
class Env(object):
valid_types = {
'string': None,
'boolean': validate_boolean,
'list': list,
'tuple': tuple,
'integer': int,
'float': float,
'dict': dict,
'decimal': Decimal
}
def __call__(self, key, default=None, var_type='string', allow_none=True):
if ARGUMENTS.LIST_ENVS in sys.argv or ARGUMENTS.CHECK_ENVS in sys.argv:
with open(ENVS_RESULT_FILENAME, 'a') as f:
json.dump({'key': key, 'var_type': var_type, 'default': default, 'value': os.getenv(key)}, f)
f.write(',')
value = os.getenv(key, default)
if not var_type in self.valid_types.keys():
raise ValueError(
'The var_type argument should be one of the following {0}'.format(
','.join(self.valid_types.keys())))
if value is None:
if not allow_none:
raise EnvsValueException('{}: Environment Variable Not Set'.format(key))
return value
return self.validate_type(value, self.valid_types[var_type], key)
def validate_type(self, value, klass, key):
if not klass:
return value
if klass in (validate_boolean, Decimal):
return klass(value)
if isinstance(value, klass):
return value
return klass(ast.literal_eval(value))
env = Env()
| 28.319444
| 109
| 0.600785
|
4a0b8663fad39445fa1c2d77c879aab1eb9e4e3c
| 1,729
|
py
|
Python
|
app/user/serializers.py
|
engr-mudassar/recipe-app-api
|
83a16aaa4d1b1b8c25d3783a08b1c07b696a0947
|
[
"MIT"
] | null | null | null |
app/user/serializers.py
|
engr-mudassar/recipe-app-api
|
83a16aaa4d1b1b8c25d3783a08b1c07b696a0947
|
[
"MIT"
] | null | null | null |
app/user/serializers.py
|
engr-mudassar/recipe-app-api
|
83a16aaa4d1b1b8c25d3783a08b1c07b696a0947
|
[
"MIT"
] | null | null | null |
from django.contrib.auth import get_user_model, authenticate
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
class UserSerializer(serializers.ModelSerializer):
"""Serializer for the users objects"""
class Meta:
model = get_user_model()
fields = ('email', 'password', 'name')
extra_kwargs = {'password': {'write_only': True, 'min_length': 5}}
def create(self, validated_data):
"""Create a new user with encrypted password and return it"""
return get_user_model().objects.create_user(**validated_data)
def update(self, instance, validated_data):
"""Update a user, setting the password correctly and return it"""
password = validated_data.pop('password', None)
user = super().update(instance, validated_data)
if password:
user.set_password(password)
user.save()
return user
class AuthTokenSerializer(serializers.Serializer):
"""Serialize for the user authentication object"""
email = serializers.CharField()
password = serializers.CharField(
style={'input_type': 'password'},
trim_whitespace=False
)
def validate(self, attrs):
"""Validate and authenticate the user"""
email = attrs.get('email')
password = attrs.get('password')
user = authenticate(
request=self.context.get('request'),
username=email,
password=password
)
if not user:
msg = _('Unable to authenticate with provided credentials')
raise serializers.ValidationError(msg, code='authentication')
attrs['user'] = user
return attrs
| 30.875
| 74
| 0.646038
|
4a0b86641855b96c325baa6b1838e46caf06af5b
| 374
|
py
|
Python
|
modoboa/dnstools/factories.py
|
Arvedui/modoboa
|
404f4bc0f544506d23ac534ff02ae6c6e3b6558c
|
[
"ISC"
] | 2
|
2021-04-20T19:40:09.000Z
|
2021-04-20T20:23:57.000Z
|
modoboa/dnstools/factories.py
|
vavilon/modoboa
|
9fcd133bc883a94cbf66c5bc9687787caadc8ca2
|
[
"0BSD"
] | 19
|
2021-05-05T03:31:52.000Z
|
2021-12-11T09:58:52.000Z
|
modoboa/dnstools/factories.py
|
vavilon/modoboa
|
9fcd133bc883a94cbf66c5bc9687787caadc8ca2
|
[
"0BSD"
] | 1
|
2020-01-10T11:43:00.000Z
|
2020-01-10T11:43:00.000Z
|
"""App related factories."""
from __future__ import unicode_literals
import factory
from modoboa.admin import factories as admin_factories
from . import models
class DNSRecordFactory(factory.django.DjangoModelFactory):
"""Factory for dns records."""
class Meta:
model = models.DNSRecord
domain = factory.SubFactory(admin_factories.DomainFactory)
| 19.684211
| 62
| 0.759358
|
4a0b87c5523556bf87d62178987918e532f9d133
| 1,630
|
py
|
Python
|
unittests/declaration_files_tester.py
|
mamoll/pygccxml
|
91348c3e56ec891496c00bc7771e647791114c7d
|
[
"BSL-1.0"
] | null | null | null |
unittests/declaration_files_tester.py
|
mamoll/pygccxml
|
91348c3e56ec891496c00bc7771e647791114c7d
|
[
"BSL-1.0"
] | null | null | null |
unittests/declaration_files_tester.py
|
mamoll/pygccxml
|
91348c3e56ec891496c00bc7771e647791114c7d
|
[
"BSL-1.0"
] | null | null | null |
# Copyright 2014-2016 Insight Software Consortium.
# Copyright 2004-2008 Roman Yakovenko.
# Distributed under the Boost Software License, Version 1.0.
# See http://www.boost.org/LICENSE_1_0.txt
import os
import unittest
import parser_test_case
from pygccxml import parser
from pygccxml import declarations
class tester_t(parser_test_case.parser_test_case_t):
def __init__(self, *args):
parser_test_case.parser_test_case_t.__init__(self, *args)
self.__files = [
'core_ns_join_1.hpp',
'core_ns_join_2.hpp',
'core_ns_join_3.hpp',
'core_membership.hpp',
'core_class_hierarchy.hpp',
'core_types.hpp',
'core_diamand_hierarchy_base.hpp',
'core_diamand_hierarchy_derived1.hpp',
'core_diamand_hierarchy_derived2.hpp',
'core_diamand_hierarchy_final_derived.hpp',
'core_overloads_1.hpp',
'core_overloads_2.hpp']
def test(self):
prj_reader = parser.project_reader_t(self.config)
decls = prj_reader.read_files(
self.__files,
compilation_mode=parser.COMPILATION_MODE.ALL_AT_ONCE)
files = declarations.declaration_files(decls)
result = set()
for fn in files:
result.add(os.path.split(fn)[1])
self.assertTrue(set(self.__files).issubset(result))
def create_suite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(tester_t))
return suite
def run_suite():
unittest.TextTestRunner(verbosity=2).run(create_suite())
if __name__ == "__main__":
run_suite()
| 30.185185
| 65
| 0.669939
|
4a0b886fedfbd42b40be1f2a23010b9f3aec0f5b
| 332
|
py
|
Python
|
api/tests/health.py
|
DarkbordermanTemplate/fastapi-redis-sqlalchemy
|
80fbdc419b19592b08bc2227c9d7c2925b7b91e2
|
[
"BSD-2-Clause"
] | 5
|
2021-02-08T06:37:48.000Z
|
2021-09-12T14:55:34.000Z
|
api/tests/test_endpoint/health.py
|
DarkbordermanTemplate/fastapi-redis-linebot
|
36a5a945c9f38dfccfe4a7b5e507db6dd82a6768
|
[
"BSD-2-Clause"
] | null | null | null |
api/tests/test_endpoint/health.py
|
DarkbordermanTemplate/fastapi-redis-linebot
|
36a5a945c9f38dfccfe4a7b5e507db6dd82a6768
|
[
"BSD-2-Clause"
] | null | null | null |
import pytest
from tests import APITestcase, AssertRequest, AssertResponse
ROUTE = "/health"
CASES = [
APITestcase(
"ok", AssertRequest("GET", ROUTE, None, None), AssertResponse("OK", 200)
)
]
@pytest.mark.parametrize("case", CASES, ids=[case.name for case in CASES])
def test(case: APITestcase):
case.run()
| 20.75
| 80
| 0.680723
|
4a0b88dab2daf4cf75516a094936b2dc39fa93d4
| 14,134
|
py
|
Python
|
test/functional/p2p_unrequested_blocks.py
|
qtumcashproject/qtumcash
|
4f095de839e524c4d43a861769695d199bfd7544
|
[
"MIT"
] | 2
|
2020-04-30T09:41:04.000Z
|
2020-05-08T12:03:21.000Z
|
test/functional/p2p_unrequested_blocks.py
|
qtumcashproject/qtumcash
|
4f095de839e524c4d43a861769695d199bfd7544
|
[
"MIT"
] | null | null | null |
test/functional/p2p_unrequested_blocks.py
|
qtumcashproject/qtumcash
|
4f095de839e524c4d43a861769695d199bfd7544
|
[
"MIT"
] | null | null | null |
#!/usr/bin/env python3
# Copyright (c) 2015-2019 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test processing of unrequested blocks.
Setup: two nodes, node0+node1, not connected to each other. Node1 will have
nMinimumChainWork set to 0x10, so it won't process low-work unrequested blocks.
We have one P2PInterface connection to node0 called test_node, and one to node1
called min_work_node.
The test:
1. Generate one block on each node, to leave IBD.
2. Mine a new block on each tip, and deliver to each node from node's peer.
The tip should advance for node0, but node1 should skip processing due to
nMinimumChainWork.
Node1 is unused in tests 3-7:
3. Mine a block that forks from the genesis block, and deliver to test_node.
Node0 should not process this block (just accept the header), because it
is unrequested and doesn't have more or equal work to the tip.
4a,b. Send another two blocks that build on the forking block.
Node0 should process the second block but be stuck on the shorter chain,
because it's missing an intermediate block.
4c.Send 288 more blocks on the longer chain (the number of blocks ahead
we currently store).
Node0 should process all but the last block (too far ahead in height).
5. Send a duplicate of the block in #3 to Node0.
Node0 should not process the block because it is unrequested, and stay on
the shorter chain.
6. Send Node0 an inv for the height 3 block produced in #4 above.
Node0 should figure out that Node0 has the missing height 2 block and send a
getdata.
7. Send Node0 the missing block again.
Node0 should process and the tip should advance.
8. Create a fork which is invalid at a height longer than the current chain
(ie to which the node will try to reorg) but which has headers built on top
of the invalid block. Check that we get disconnected if we send more headers
on the chain the node now knows to be invalid.
9. Test Node1 is able to sync when connected to node0 (which should have sufficient
work on its chain).
"""
import time
from test_framework.blocktools import create_block, create_coinbase, create_tx_with_script
from test_framework.messages import CBlockHeader, CInv, msg_block, msg_headers, msg_inv
from test_framework.mininode import mininode_lock, P2PInterface
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (
assert_equal,
assert_raises_rpc_error,
connect_nodes,
)
class AcceptBlockTest(BitcoinTestFramework):
def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 2
self.extra_args = [[], ["-minimumchainwork=0x10"]]
def setup_network(self):
# Node0 will be used to test behavior of processing unrequested blocks
# from peers which are not whitelisted, while Node1 will be used for
# the whitelisted case.
# Node2 will be used for non-whitelisted peers to test the interaction
# with nMinimumChainWork.
self.setup_nodes()
def run_test(self):
# Setup the p2p connections
# test_node connects to node0 (not whitelisted)
test_node = self.nodes[0].add_p2p_connection(P2PInterface())
# min_work_node connects to node1 (whitelisted)
min_work_node = self.nodes[1].add_p2p_connection(P2PInterface())
# 1. Have nodes mine a block (leave IBD)
[n.generatetoaddress(1, n.get_deterministic_priv_key().address) for n in self.nodes]
tips = [int("0x" + n.getbestblockhash(), 0) for n in self.nodes]
# 2. Send one block that builds on each tip.
# This should be accepted by node0
blocks_h2 = [] # the height 2 blocks on each node's chain
block_time = int(time.time()) + 1
for i in range(2):
blocks_h2.append(create_block(tips[i], create_coinbase(2), block_time))
blocks_h2[i].solve()
block_time += 1
test_node.send_message(msg_block(blocks_h2[0]))
min_work_node.send_message(msg_block(blocks_h2[1]))
for x in [test_node, min_work_node]:
x.sync_with_ping()
assert_equal(self.nodes[0].getblockcount(), 2)
assert_equal(self.nodes[1].getblockcount(), 1)
self.log.info("First height 2 block accepted by node0; correctly rejected by node1")
# 3. Send another block that builds on genesis.
block_h1f = create_block(int("0x" + self.nodes[0].getblockhash(0), 0), create_coinbase(1), block_time)
block_time += 1
block_h1f.solve()
test_node.send_message(msg_block(block_h1f))
test_node.sync_with_ping()
tip_entry_found = False
for x in self.nodes[0].getchaintips():
if x['hash'] == block_h1f.hash:
assert_equal(x['status'], "headers-only")
tip_entry_found = True
assert tip_entry_found
assert_raises_rpc_error(-1, "Block not found on disk", self.nodes[0].getblock, block_h1f.hash)
# 4. Send another two block that build on the fork.
block_h2f = create_block(block_h1f.sha256, create_coinbase(2), block_time)
block_time += 1
block_h2f.solve()
test_node.send_message(msg_block(block_h2f))
test_node.sync_with_ping()
# Since the earlier block was not processed by node, the new block
# can't be fully validated.
tip_entry_found = False
for x in self.nodes[0].getchaintips():
if x['hash'] == block_h2f.hash:
assert_equal(x['status'], "headers-only")
tip_entry_found = True
assert tip_entry_found
# But this block should be accepted by node since it has equal work.
# NOT true for qtumcash as we only store blocks with MORE work.
self.nodes[0].getblockheader(block_h2f.hash)
self.log.info("Second height 2 block accepted, but not reorg'ed to")
# 4b. Now send another block that builds on the forking chain.
block_h3 = create_block(block_h2f.sha256, create_coinbase(3), block_h2f.nTime+1)
block_h3.solve()
test_node.send_message(msg_block(block_h3))
# Then send the prev block as well
self.nodes[0].submitblock(block_h2f.serialize().hex())
test_node.sync_with_ping()
# Since the earlier block was not processed by node, the new block
# can't be fully validated.
tip_entry_found = False
for x in self.nodes[0].getchaintips():
if x['hash'] == block_h3.hash:
assert_equal(x['status'], "headers-only")
tip_entry_found = True
assert tip_entry_found
self.nodes[0].getblock(block_h3.hash)
# But this block should be accepted by node since it has more work.
self.nodes[0].getblock(block_h3.hash)
self.log.info("Unrequested more-work block accepted")
# 4c. Now mine 288 more blocks and deliver; all should be processed but
# the last (height-too-high) on node (as long as it is not missing any headers)
tip = block_h3
all_blocks = []
for i in range(288):
next_block = create_block(tip.sha256, create_coinbase(i + 4), tip.nTime+1)
next_block.solve()
all_blocks.append(next_block)
tip = next_block
# Now send the block at height 5 and check that it wasn't accepted (missing header)
test_node.send_message(msg_block(all_blocks[1]))
test_node.sync_with_ping()
assert_raises_rpc_error(-5, "Block not found", self.nodes[0].getblock, all_blocks[1].hash)
assert_raises_rpc_error(-5, "Block not found", self.nodes[0].getblockheader, all_blocks[1].hash)
# The block at height 5 should be accepted if we provide the missing header, though
headers_message = msg_headers()
headers_message.headers.append(CBlockHeader(all_blocks[0]))
test_node.send_message(headers_message)
test_node.send_message(msg_block(all_blocks[1]))
test_node.sync_with_ping()
self.nodes[0].getblock(all_blocks[1].hash)
# Now send the blocks in all_blocks
for i in range(288):
test_node.send_message(msg_block(all_blocks[i]))
test_node.sync_with_ping()
# Blocks 1-287 should be accepted, block 288 should be ignored because it's too far ahead
for x in all_blocks[:-1]:
self.nodes[0].getblock(x.hash)
assert_raises_rpc_error(-1, "Block not found on disk", self.nodes[0].getblock, all_blocks[-1].hash)
# 5. Test handling of unrequested block on the node that didn't process
# Should still not be processed (even though it has a child that has more
# work).
# The node should have requested the blocks at some point, so
# disconnect/reconnect first
self.nodes[0].disconnect_p2ps()
self.nodes[1].disconnect_p2ps()
test_node = self.nodes[0].add_p2p_connection(P2PInterface())
test_node.send_message(msg_block(block_h1f))
test_node.sync_with_ping()
assert_equal(self.nodes[0].getblockcount(), 2)
self.log.info("Unrequested block that would complete more-work chain was ignored")
# 6. Try to get node to request the missing block.
# Poke the node with an inv for block at height 3 and see if that
# triggers a getdata on block 2 (it should if block 2 is missing).
with mininode_lock:
# Clear state so we can check the getdata request
test_node.last_message.pop("getdata", None)
test_node.send_message(msg_inv([CInv(2, block_h3.sha256)]))
test_node.sync_with_ping()
with mininode_lock:
getdata = test_node.last_message["getdata"]
# Check that the getdata includes the right block
assert_equal(getdata.inv[0].hash, block_h1f.sha256)
self.log.info("Inv at tip triggered getdata for unprocessed block")
# 7. Send the missing block for the third time (now it is requested)
test_node.send_message(msg_block(block_h1f))
test_node.sync_with_ping()
assert_equal(self.nodes[0].getblockcount(), 290)
self.nodes[0].getblock(all_blocks[286].hash)
assert_equal(self.nodes[0].getbestblockhash(), all_blocks[286].hash)
assert_raises_rpc_error(-1, "Block not found on disk", self.nodes[0].getblock, all_blocks[287].hash)
self.log.info("Successfully reorged to longer chain from non-whitelisted peer")
# 8. Create a chain which is invalid at a height longer than the
# current chain, but which has more blocks on top of that
block_289f = create_block(all_blocks[284].sha256, create_coinbase(289), all_blocks[284].nTime+1)
block_289f.solve()
block_290f = create_block(block_289f.sha256, create_coinbase(290), block_289f.nTime+1)
block_290f.solve()
block_291 = create_block(block_290f.sha256, create_coinbase(291), block_290f.nTime+1)
# block_291 spends a coinbase below maturity!
block_291.vtx.append(create_tx_with_script(block_290f.vtx[0], 0, script_sig=b"42", amount=1))
block_291.hashMerkleRoot = block_291.calc_merkle_root()
block_291.solve()
block_292 = create_block(block_291.sha256, create_coinbase(292), block_291.nTime+1)
block_292.solve()
# Now send all the headers on the chain and enough blocks to trigger reorg
headers_message = msg_headers()
headers_message.headers.append(CBlockHeader(block_289f))
headers_message.headers.append(CBlockHeader(block_290f))
headers_message.headers.append(CBlockHeader(block_291))
headers_message.headers.append(CBlockHeader(block_292))
test_node.send_message(headers_message)
test_node.sync_with_ping()
tip_entry_found = False
for x in self.nodes[0].getchaintips():
if x['hash'] == block_292.hash:
assert_equal(x['status'], "headers-only")
tip_entry_found = True
assert tip_entry_found
assert_raises_rpc_error(-1, "Block not found on disk", self.nodes[0].getblock, block_292.hash)
test_node.send_message(msg_block(block_289f))
test_node.send_message(msg_block(block_290f))
test_node.sync_with_ping()
self.nodes[0].getblock(block_289f.hash)
self.nodes[0].getblock(block_290f.hash)
test_node.send_message(msg_block(block_291))
# At this point we've sent an obviously-bogus block, wait for full processing
# without assuming whether we will be disconnected or not
try:
# Only wait a short while so the test doesn't take forever if we do get
# disconnected
test_node.sync_with_ping(timeout=1)
except AssertionError:
test_node.wait_for_disconnect()
self.nodes[0].disconnect_p2ps()
test_node = self.nodes[0].add_p2p_connection(P2PInterface())
# We should have failed reorg and switched back to 290 (but have block 291)
assert_equal(self.nodes[0].getblockcount(), 290)
assert_equal(self.nodes[0].getbestblockhash(), all_blocks[286].hash)
assert_equal(self.nodes[0].getblock(block_291.hash)["confirmations"], -1)
# Now send a new header on the invalid chain, indicating we're forked off, and expect to get disconnected
block_293 = create_block(block_292.sha256, create_coinbase(293), block_292.nTime+1)
block_293.solve()
headers_message = msg_headers()
headers_message.headers.append(CBlockHeader(block_293))
test_node.send_message(headers_message)
test_node.wait_for_disconnect()
# 9. Connect node1 to node0 and ensure it is able to sync
connect_nodes(self.nodes[0], 1)
self.sync_blocks([self.nodes[0], self.nodes[1]])
self.log.info("Successfully synced nodes 1 and 0")
if __name__ == '__main__':
AcceptBlockTest().main()
| 44.446541
| 113
| 0.681902
|
4a0b89c24e2965e8b78647be24aa02954a5a7154
| 4,326
|
py
|
Python
|
clippercard/client.py
|
goldengate88/clippercard-python
|
adf4548fc61b848b625d0547ba512f12a2a1d615
|
[
"MIT"
] | null | null | null |
clippercard/client.py
|
goldengate88/clippercard-python
|
adf4548fc61b848b625d0547ba512f12a2a1d615
|
[
"MIT"
] | null | null | null |
clippercard/client.py
|
goldengate88/clippercard-python
|
adf4548fc61b848b625d0547ba512f12a2a1d615
|
[
"MIT"
] | null | null | null |
"""
Copyright (c) 2012-2021 (https://github.com/clippercard/clippercard-python)
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
# === imports ===
import bs4
import requests
import clippercard.parser as parser
# === Error Classes ===
class ClipperCardError(Exception):
"""base error for client"""
class ClipperCardAuthError(ClipperCardError):
"""unable to login with provided credentials"""
class ClipperCardContentError(ClipperCardError):
"""unable to recognize and parse web content"""
# === ClipperCardWebSession ===
class ClipperCardWebSession(requests.Session):
"""
A stateful session for clippercard.com
"""
LOGIN_URL = "https://www.clippercard.com/ClipperWeb/account"
BALANCE_URL = "https://www.clippercard.com/ClipperWeb/account.html"
HEADERS = {
"FAKE_USER_AGENT": (
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/90.0.4430.85 Safari/537.36"
)
}
def __init__(self, username=None, password=None):
requests.Session.__init__(self)
self.headers.update(self.HEADERS)
self._account_resp_soup = None
if username and password:
self.login(username, password)
def login(self, username, password):
"""
Mimicks user login form submission
"""
login_landing_resp = self.get(self.LOGIN_URL)
if login_landing_resp.ok:
req_data = {
"_csrf": parser.parse_login_form_csrf(login_landing_resp.text),
"email": username,
"password": password,
}
else:
raise ClipperCardError(
"ClipperCard.com site may be down right now. Try again later."
)
login_resp = self.post(self.LOGIN_URL, data=req_data)
if not login_resp.ok:
raise ClipperCardError(
"ClipperCard.com site may be down right now. Try again later."
)
resp_soup = bs4.BeautifulSoup(login_resp.text, "html.parser")
possible_error_msg = resp_soup.find(
"div", attrs={"class": "form-error-message"}
)
if possible_error_msg is not None:
raise ClipperCardAuthError(
parser.cleanup_whitespace(possible_error_msg.get_text())
)
# assume account page is reachable now
self._account_resp_soup = resp_soup
return login_resp
@property
def profile_info(self):
"""
Returns *Profile* namedtuples associated with logged in user
"""
if not self._account_resp_soup:
raise ClipperCardError("Must login first")
return parser.parse_profile_info(self._account_resp_soup)
@property
def cards(self):
"""
Returns list of *Card* namedtuples associated with logged in user
"""
if not self._account_resp_soup:
raise ClipperCardError("Must login first")
return parser.parse_cards(self._account_resp_soup)
def print_summary(self):
"""return a text summary of the account"""
print(self.profile_info)
print("=" * 80)
for card in sorted(self.cards, key=lambda card: card.serial_number):
print(card)
print("-" * 80)
| 33.276923
| 80
| 0.661812
|
4a0b8aa172d699d5be86361d3461c9b6503c610f
| 92
|
py
|
Python
|
test/basic/store.py
|
eseunghwan/brue
|
0a8b856cb610c51f6386c074a96add9a1a5d40d7
|
[
"MIT"
] | 1
|
2021-11-15T15:02:47.000Z
|
2021-11-15T15:02:47.000Z
|
test/basic/store.py
|
eseunghwan/brue
|
0a8b856cb610c51f6386c074a96add9a1a5d40d7
|
[
"MIT"
] | null | null | null |
test/basic/store.py
|
eseunghwan/brue
|
0a8b856cb610c51f6386c074a96add9a1a5d40d7
|
[
"MIT"
] | null | null | null |
# -*- coding: utf-8 -*-
from brue import brueStore
store = brueStore(
count_num = 1
)
| 11.5
| 26
| 0.619565
|
4a0b8aea196d76615c0dcb4567e6c2448df2028e
| 1,369
|
py
|
Python
|
extensions/setup.py
|
Wintakeb/mypy
|
fc4ad4db1a0e070d719e0844d35ef4f144cc24e0
|
[
"PSF-2.0"
] | null | null | null |
extensions/setup.py
|
Wintakeb/mypy
|
fc4ad4db1a0e070d719e0844d35ef4f144cc24e0
|
[
"PSF-2.0"
] | null | null | null |
extensions/setup.py
|
Wintakeb/mypy
|
fc4ad4db1a0e070d719e0844d35ef4f144cc24e0
|
[
"PSF-2.0"
] | 1
|
2019-02-13T04:45:01.000Z
|
2019-02-13T04:45:01.000Z
|
# NOTE: This package must support Python 2.7 in addition to Python 3.x
from setuptools import setup
version = '0.4.0-dev'
description = 'Experimental type system extensions for programs checked with the mypy typechecker.'
long_description = '''
Mypy Extensions
===============
The "mypy_extensions" module defines experimental extensions to the
standard "typing" module that are supported by the mypy typechecker.
'''.lstrip()
classifiers = [
'Development Status :: 2 - Pre-Alpha',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Software Development',
]
setup(
name='mypy_extensions',
version=version,
description=description,
long_description=long_description,
author='The mypy developers',
author_email='jukka.lehtosalo@iki.fi',
url='http://www.mypy-lang.org/',
license='MIT License',
py_modules=['mypy_extensions'],
classifiers=classifiers,
install_requires=[
'typing >= 3.5.3; python_version < "3.5"',
],
)
| 30.422222
| 99
| 0.669832
|
4a0b8c041e2f2ab1e0a62d716d8cb0b86ceb22e9
| 2,008
|
py
|
Python
|
examples/example_parametric_reactors/make_animation.py
|
PullRequest-Agent/paramak
|
f807d88098458d1975dd1a4a47dcea22d9f74785
|
[
"MIT"
] | 1
|
2020-11-25T10:46:32.000Z
|
2020-11-25T10:46:32.000Z
|
examples/example_parametric_reactors/make_animation.py
|
PullRequest-Agent/paramak
|
f807d88098458d1975dd1a4a47dcea22d9f74785
|
[
"MIT"
] | null | null | null |
examples/example_parametric_reactors/make_animation.py
|
PullRequest-Agent/paramak
|
f807d88098458d1975dd1a4a47dcea22d9f74785
|
[
"MIT"
] | null | null | null |
__doc__ = """ Creates a series of images of a ball reactor images and
combines them into gif animations using the command line tool convert,
part of the imagemagick suite """
import argparse
import os
import uuid
import numpy as np
import paramak
from tqdm import tqdm
parser = argparse.ArgumentParser()
parser.add_argument("-n", "--number_of_models", type=int, default=10)
args = parser.parse_args()
for i in tqdm(range(args.number_of_models)):
my_reactor = paramak.BallReactor(
inner_bore_radial_thickness=50,
inboard_tf_leg_radial_thickness=np.random.uniform(20, 50),
center_column_shield_radial_thickness=np.random.uniform(20, 60),
divertor_radial_thickness=50,
inner_plasma_gap_radial_thickness=50,
plasma_radial_thickness=np.random.uniform(20, 200),
outer_plasma_gap_radial_thickness=50,
firstwall_radial_thickness=5,
blanket_radial_thickness=np.random.uniform(10, 200),
blanket_rear_wall_radial_thickness=10,
elongation=np.random.uniform(1.2, 1.7),
triangularity=np.random.uniform(0.3, 0.55),
number_of_tf_coils=16,
rotation_angle=180,
pf_coil_radial_thicknesses=[50, 50, 50, 50],
pf_coil_vertical_thicknesses=[50, 50, 50, 50],
pf_coil_to_rear_blanket_radial_gap=50,
pf_coil_to_tf_coil_radial_gap=50,
outboard_tf_coil_radial_thickness=100,
outboard_tf_coil_poloidal_thickness=50,
)
my_reactor.export_2d_image(
filename="output_for_animation_2d/" + str(uuid.uuid4()) + ".png"
)
my_reactor.export_svg(
filename="output_for_animation_svg/" + str(uuid.uuid4()) + ".svg"
)
print(str(args.number_of_models), "models made")
os.system("convert -delay 40 output_for_animation_2d/*.png 2d.gif")
os.system("convert -delay 40 output_for_animation_3d/*.png 3d.gif")
os.system("convert -delay 40 output_for_animation_svg/*.svg 3d_svg.gif")
print("animation file made 2d.gif, 3d.gif and 3d_svg.gif")
| 34.62069
| 73
| 0.72261
|
4a0b8cf0670b20997b5b07e86eb9e2095c08cffb
| 489
|
py
|
Python
|
api/src/handlers/status.py
|
vai0/Citizen-Center
|
77fd113d2dc8af3e2436c1a94c0b0f75ad3fab59
|
[
"MIT"
] | null | null | null |
api/src/handlers/status.py
|
vai0/Citizen-Center
|
77fd113d2dc8af3e2436c1a94c0b0f75ad3fab59
|
[
"MIT"
] | null | null | null |
api/src/handlers/status.py
|
vai0/Citizen-Center
|
77fd113d2dc8af3e2436c1a94c0b0f75ad3fab59
|
[
"MIT"
] | null | null | null |
import logging
import azure.functions as func
import simplejson as json
from os import environ
def main(req: func.HttpRequest) -> func.HttpResponse:
logging.info('Python HTTP trigger function processed a request.')
version = '0.0.0'
if (environ["CP_VERSION"]):
version = environ["CP_VERSION"]
body = {
"version": version,
"status": "OK"
}
return func.HttpResponse(body=json.dumps(body), status_code=200, mimetype="application/json")
| 21.26087
| 97
| 0.672802
|
4a0b8d801de90ba05298d774df75e3b866b94c15
| 7,898
|
py
|
Python
|
dlp/synth.py
|
hzyi-google/google-cloud-python
|
aa3c3ca303b385a6b118204ce91fa803c1d001b9
|
[
"Apache-2.0"
] | 1
|
2020-01-09T14:42:37.000Z
|
2020-01-09T14:42:37.000Z
|
dlp/synth.py
|
hzyi-google/google-cloud-python
|
aa3c3ca303b385a6b118204ce91fa803c1d001b9
|
[
"Apache-2.0"
] | 6
|
2019-05-27T22:05:58.000Z
|
2019-08-05T16:46:16.000Z
|
dlp/synth.py
|
hzyi-google/google-cloud-python
|
aa3c3ca303b385a6b118204ce91fa803c1d001b9
|
[
"Apache-2.0"
] | null | null | null |
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This script is used to synthesize generated parts of this library."""
import synthtool as s
import synthtool.gcp as gcp
import logging
logging.basicConfig(level=logging.DEBUG)
gapic = gcp.GAPICGenerator()
common = gcp.CommonTemplates()
# ----------------------------------------------------------------------------
# Generate dlp GAPIC layer
# ----------------------------------------------------------------------------
library = gapic.py_library(
"dlp",
"v2",
config_path="/google/privacy/dlp/artman_dlp_v2.yaml",
include_protos=True,
)
excludes = ["README.rst", "nox.py", "setup.py", "docs/index.rst"]
s.move(library, excludes=excludes)
# Fix namespace
s.replace("google/**/*.py", "google\.cloud\.privacy\.dlp_v2", "google.cloud.dlp_v2")
# Add missing utf-8 marker
s.replace(
"google/cloud/dlp_v2/proto/dlp_pb2.py",
"# Generated by the protocol buffer compiler. DO NOT EDIT!",
"# -*- coding: utf-8 -*-\n\g<0>",
)
# Fix raw-latex bits in storage_pb2.py
s.replace(
"google/cloud/dlp_v2/proto/storage_pb2.py",
"number regex.*\n(\s+)latex:.*\n",
'number regex "(\\d\{3\}) \\d\{3\}-\\d\{4\} "\\\n'
"\g<1>could be adjusted upwards if the area code is \\\n",
)
# Fix Docstrings in google/cloud/dlp_v2/proto/storage_pb2.py
s.replace(
"google/cloud/dlp_v2/proto/storage_pb2.py",
"(hotword_regex:)\n(\s+Regular expression.*)\n",
"\g<1> \\\n\g<2> \\\n",
)
s.replace(
"google/cloud/dlp_v2/proto/storage_pb2.py",
"(likelihood_adjustment:)\n",
"\g<1> \\\n",
)
# Fix Docstrings in google/cloud/dlp_v2/proto/dlp_pb2.py
s.replace(
"google/cloud/dlp_v2/proto/dlp_pb2.py",
"(max_findings_per_item:)\n(\s+Max number.*)\n(\s+scanned. When.*)\n"
"(\s+maximum returned is 1000.*)\n(\s+When set within.*)\n",
"\g<1> \\\n\g<2> \\\n\g<3> \\\n\g<4> \\\n\g<5> \\\n",
)
s.replace(
"google/cloud/dlp_v2/proto/dlp_pb2.py",
"(max_findings_per_request:)\n(\s+Max number of.*)\n(\s+When set .*)\n",
"\g<1> \\\n\g<2> \\\n\g<3> \\\n",
)
s.replace(
"google/cloud/dlp_v2/proto/dlp_pb2.py",
"(max_findings_per_info_type:)\n",
"\g<1> \\\n",
)
s.replace(
"google/cloud/dlp_v2/proto/dlp_pb2.py",
"(snapshot_inspect_template:)\n(\s+If run with an .*)\n",
"\g<1> \\\n\g<2> \\\n",
)
to_replace = [
"processed_bytes:",
"total_estimated_bytes:",
"info_type_stats:",
"Statistics of how many instances of each info type were found",
"requested_options:",
]
for replace in to_replace:
s.replace("google/cloud/dlp_v2/proto/dlp_pb2.py", f"({replace})\n", "\g<1> \\\n")
s.replace(
"google/cloud/dlp_v2/proto/dlp_pb2.py",
"(sensitive_value_frequency_lower_bound:)\n(\s+Lower bound.*)\n",
"\g<1> \\\n\g<2> \\\n",
)
s.replace(
"google/cloud/dlp_v2/proto/dlp_pb2.py",
"(sensitive_value_frequency_upper_bound:)\n(\s+Upper bound.*)\n",
"\g<1> \\\n\g<2> \\\n",
)
s.replace(
"google/cloud/dlp_v2/proto/dlp_pb2.py",
"(bucket_size:)\n(\s+Total number of equivalence.*)\n",
"\g<1> \\\n\g<2>\n",
)
s.replace(
"google/cloud/dlp_v2/proto/dlp_pb2.py",
"(bucket_values:)\n(\s+Sample of equivalence.*)\n",
"\g<1> \\\n\g<2> \\\n",
)
s.replace(
"google/cloud/dlp_v2/proto/dlp_pb2.py",
"(offset_minutes:)\n(\s+Set only.*)\n",
"\g<1> \\\n\g<2> \\\n",
)
s.replace(
"google/cloud/dlp_v2/proto/dlp_pb2.py",
"(result:)\n(\s+A summary of the outcome of this inspect job.)",
"\g<1> \\\n\g<2>",
)
s.replace(
"google/cloud/dlp_v2/proto/dlp_pb2.py",
"(storage_config:)\n(\s+The data to scan.\n)",
"\g<1> \\\n\g<2>",
)
s.replace(
"google/cloud/dlp_v2/proto/dlp_pb2.py",
"(inspect_config:)\n(\s+How and what to scan for.\n)",
"\g<1> \\\n\g<2>",
)
s.replace(
"google/cloud/dlp_v2/proto/dlp_pb2.py",
"(inspect_template_name:)\n(\s+If provided, will be.*)\n"
"(\s+InspectConfig.*)\n(\s+values persisted.*)\n(\s+actions:)\n"
"(\s+Actions to.*)\n",
"\g<1> \\\n\g<2> \\\n\g<3> \\\n\g<4> \\\n\g<5> \\\n\g<6> \\\n",
)
s.replace(
"google/cloud/dlp_v2/proto/dlp_pb2.py",
" (\s+Set of values defining the equivalence class.*)\n"
" (\s+quasi-identifier.*)\n"
" (\s+message. The order.*)\n",
"\g<1> \\\n\g<2> \\\n\g<3>\n",
)
s.replace(
"google/cloud/dlp_v2/proto/dlp_pb2.py",
" (\s+Size of the equivalence class, for example number of rows with)\n"
" (\s+the above set of values.)\n",
"\g<1> \\\n\g<2>\n",
)
s.replace(
"google/cloud/dlp_v2/proto/dlp_pb2.py",
"(equivalence_class_size_lower_bound:)\n(\s+Lower bound.*)\n",
"\g<1> \\\n\g<2> \\\n",
)
s.replace(
"google/cloud/dlp_v2/proto/dlp_pb2.py",
"(equivalence_class_size_upper_bound:)\n(\s+Upper bound.*)\n",
"\g<1> \\\n\g<2> \\\n",
)
s.replace(
"google/cloud/dlp_v2/proto/dlp_pb2.py",
"(bucket_value_count:)\n(\s+Total number of distinct equivalence.*)\n",
"\g<1> \\\n\g<2>\n",
)
# Docstrings from categorical histogram bucket
s.replace(
"google/cloud/dlp_v2/proto/dlp_pb2.py",
"(value_frequency_lower_bound:)\n\s+(Lower bound.*)\n\s+(bucket.\n)"
"(\s+value_frequency_upper.*)\n\s+(Upper.*)\n\s+(bucket.\n)"
"(\s+bucket_size:)\n\s+(Total.*\n)"
"(\s+bucket_values:)\n\s+(Sample of value.*)\n\s+(of values.*\n)"
"(\s+bucket_value_count:)\n\s+(Total number.*\n)",
"\g<1> \g<2> \g<3>\g<4> \g<5> \g<6>\g<7> \g<8>" "\g<9> \g<10> \g<11>\g<12> \g<13>",
)
# Fix docstrings tagged field indentation issues in dlp_pb2.py
s.replace(
"google/cloud/dlp_v2/proto/dlp_pb2.py",
"(DESCRIPTOR .*_TAGGEDFIELD,\n\s+__module__.*\n\s+,\n\s+__doc__.*\n)"
"(\s+field:)\n(\s+Identifies .*)\n(\s+tag:)\n(\s+Semantic.*)\n"
"(\s+determine.*)\n(\s+reidentifiability.*)\n(\s+info_type:)\n"
"(\s+A column.*)\n(\s+public dataset.*)\n(\s+available.*)\n(\s+ages.*)\n"
"(\s+supported Info.*)\n(\s+supported.*)\n(\s+custom_tag:)\n(\s+A col.*)\n"
"(\s+user must.*)\n(\s+statist.*)\n(\s+\(below.*)\n(\s+inferred:)\n"
"(\s+If no semantic.*)\n",
"\g<1>\g<2> \\\n\g<3>\n\g<4> \\\n\g<5> \\\n\g<6> \\\n"
"\g<7> \\\n\g<8> \\\n\g<9> \\\n\g<10> \\\n\g<11> \\\n\g<12> \\\n"
"\g<13> \\\n\g<14>\n\g<15> \\\n\g<16> \\\n\g<17> \\\n\g<18> \\\n"
"\g<19>\n\g<20> \\\n\g<21> \\\n",
)
s.replace(
"google/cloud/dlp_v2/proto/dlp_pb2.py",
r'''(\s+)__doc__ = """Attributes:''',
r'\g<1>__doc="""\n Attributes:'
)
s.replace(
"google/cloud/dlp_v2/proto/dlp_pb2.py",
"(////////.*)\n\s+(///////////////\n)",
"\g<1> \g<2>",
)
# Fix Docstrings in google/cloud/dlp_v2/gapic/dlp_service_client.py
s.replace(
"google/cloud/dlp_v2/gapic/dlp_service_client.py",
"^\s+resource was created.",
" \g<0>",
)
# Fix Docstrings in google/cloud/dlp_v2/gapic/enums.py
s.replace(
"google/cloud/dlp_v2/gapic/enums.py",
"(\s+)WHITESPACE \(int\).*\n",
"\g<1>WHITESPACE (int): Whitespace character\n",
)
s.replace("google/cloud/dlp_v2/gapic/enums.py", ".*:raw-latex:.*\n", "")
# ----------------------------------------------------------------------------
# Add templated files
# ----------------------------------------------------------------------------
templated_files = common.py_library(unit_cov_level=97, cov_level=100)
s.move(templated_files, excludes=['noxfile.py'])
s.shell.run(["nox", "-s", "blacken"], hide_output=False)
| 30.494208
| 87
| 0.582299
|
4a0b8feabde7e95e353640e11f8f53d7d3c9d6db
| 412
|
py
|
Python
|
tpvenv/Scripts/pip-script.py
|
fgetwewr/tphone
|
434b7088c33ac9ea4992d30ff59a853e7e2b3188
|
[
"MIT"
] | null | null | null |
tpvenv/Scripts/pip-script.py
|
fgetwewr/tphone
|
434b7088c33ac9ea4992d30ff59a853e7e2b3188
|
[
"MIT"
] | null | null | null |
tpvenv/Scripts/pip-script.py
|
fgetwewr/tphone
|
434b7088c33ac9ea4992d30ff59a853e7e2b3188
|
[
"MIT"
] | null | null | null |
#!C:\Users\shuai\Desktop\project\tphone\tpvenv\Scripts\python.exe
# EASY-INSTALL-ENTRY-SCRIPT: 'pip==10.0.1','console_scripts','pip'
__requires__ = 'pip==10.0.1'
import re
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(
load_entry_point('pip==10.0.1', 'console_scripts', 'pip')()
)
| 31.692308
| 69
| 0.667476
|
4a0b9011cac0f8e452055e0d5ca5c467f84265eb
| 19,884
|
py
|
Python
|
Bio/Align/Applications/_Mafft.py
|
bioinf-mcb/biopython
|
1a1f4a7ee4e0efba517d3d607c56c27e72e399cc
|
[
"BSD-3-Clause"
] | 5
|
2015-06-14T17:01:57.000Z
|
2020-10-05T03:27:56.000Z
|
Bio/Align/Applications/_Mafft.py
|
uci-ics-32/biopython
|
ff7d3703d442192a1f6d84c52e028d566d44ff1c
|
[
"BSD-3-Clause"
] | 14
|
2021-03-26T20:54:22.000Z
|
2021-04-06T17:18:53.000Z
|
Bio/Align/Applications/_Mafft.py
|
uci-ics-32/biopython
|
ff7d3703d442192a1f6d84c52e028d566d44ff1c
|
[
"BSD-3-Clause"
] | 8
|
2016-02-20T22:53:21.000Z
|
2022-02-04T06:10:23.000Z
|
# Copyright 2009 by Cymon J. Cox. All rights reserved.
#
# This file is part of the Biopython distribution and governed by your
# choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
# Please see the LICENSE file that should have been included as part of this
# package.
"""Command line wrapper for the multiple alignment programme MAFFT."""
from Bio.Application import _Option, _Switch, _Argument, AbstractCommandline
class MafftCommandline(AbstractCommandline):
"""Command line wrapper for the multiple alignment program MAFFT.
http://align.bmr.kyushu-u.ac.jp/mafft/software/
Notes
-----
Last checked against version: MAFFT v6.717b (2009/12/03)
References
----------
Katoh, Toh (BMC Bioinformatics 9:212, 2008) Improved accuracy of
multiple ncRNA alignment by incorporating structural information into
a MAFFT-based framework (describes RNA structural alignment methods)
Katoh, Toh (Briefings in Bioinformatics 9:286-298, 2008) Recent
developments in the MAFFT multiple sequence alignment program
(outlines version 6)
Katoh, Toh (Bioinformatics 23:372-374, 2007) Errata PartTree: an
algorithm to build an approximate tree from a large number of
unaligned sequences (describes the PartTree algorithm)
Katoh, Kuma, Toh, Miyata (Nucleic Acids Res. 33:511-518, 2005) MAFFT
version 5: improvement in accuracy of multiple sequence alignment
(describes [ancestral versions of] the G-INS-i, L-INS-i and E-INS-i
strategies)
Katoh, Misawa, Kuma, Miyata (Nucleic Acids Res. 30:3059-3066, 2002)
Examples
--------
>>> from Bio.Align.Applications import MafftCommandline
>>> mafft_exe = "/opt/local/mafft"
>>> in_file = "../Doc/examples/opuntia.fasta"
>>> mafft_cline = MafftCommandline(mafft_exe, input=in_file)
>>> print(mafft_cline)
/opt/local/mafft ../Doc/examples/opuntia.fasta
If the mafft binary is on the path (typically the case on a Unix style
operating system) then you don't need to supply the executable location:
>>> from Bio.Align.Applications import MafftCommandline
>>> in_file = "../Doc/examples/opuntia.fasta"
>>> mafft_cline = MafftCommandline(input=in_file)
>>> print(mafft_cline)
mafft ../Doc/examples/opuntia.fasta
You would typically run the command line with mafft_cline() or via
the Python subprocess module, as described in the Biopython tutorial.
Note that MAFFT will write the alignment to stdout, which you may
want to save to a file and then parse, e.g.::
stdout, stderr = mafft_cline()
with open("aligned.fasta", "w") as handle:
handle.write(stdout)
from Bio import AlignIO
align = AlignIO.read("aligned.fasta", "fasta")
Alternatively, to parse the output with AlignIO directly you can
use StringIO to turn the string into a handle::
stdout, stderr = mafft_cline()
from io import StringIO
from Bio import AlignIO
align = AlignIO.read(StringIO(stdout), "fasta")
"""
def __init__(self, cmd="mafft", **kwargs):
"""Initialize the class."""
BLOSUM_MATRICES = ["30", "45", "62", "80"]
self.parameters = [
# **** Algorithm ****
# Automatically selects an appropriate strategy from L-INS-i, FFT-NS-
# i and FFT-NS-2, according to data size. Default: off (always FFT-NS-2)
_Switch(["--auto", "auto"], "Automatically select strategy. Default off."),
# Distance is calculated based on the number of shared 6mers. Default: on
_Switch(
["--6merpair", "6merpair", "sixmerpair"],
"Distance is calculated based on the number of shared "
"6mers. Default: on",
),
# All pairwise alignments are computed with the Needleman-Wunsch
# algorithm. More accurate but slower than --6merpair. Suitable for a
# set of globally alignable sequences. Applicable to up to ~200
# sequences. A combination with --maxiterate 1000 is recommended (G-
# INS-i). Default: off (6mer distance is used)
_Switch(
["--globalpair", "globalpair"],
"All pairwise alignments are computed with the "
"Needleman-Wunsch algorithm. Default: off",
),
# All pairwise alignments are computed with the Smith-Waterman
# algorithm. More accurate but slower than --6merpair. Suitable for a
# set of locally alignable sequences. Applicable to up to ~200
# sequences. A combination with --maxiterate 1000 is recommended (L-
# INS-i). Default: off (6mer distance is used)
_Switch(
["--localpair", "localpair"],
"All pairwise alignments are computed with the "
"Smith-Waterman algorithm. Default: off",
),
# All pairwise alignments are computed with a local algorithm with
# the generalized affine gap cost (Altschul 1998). More accurate but
# slower than --6merpair. Suitable when large internal gaps are
# expected. Applicable to up to ~200 sequences. A combination with --
# maxiterate 1000 is recommended (E-INS-i). Default: off (6mer
# distance is used)
_Switch(
["--genafpair", "genafpair"],
"All pairwise alignments are computed with a local "
"algorithm with the generalized affine gap cost "
"(Altschul 1998). Default: off",
),
# All pairwise alignments are computed with FASTA (Pearson and Lipman
# 1988). FASTA is required. Default: off (6mer distance is used)
_Switch(
["--fastapair", "fastapair"],
"All pairwise alignments are computed with FASTA "
"(Pearson and Lipman 1988). Default: off",
),
# Weighting factor for the consistency term calculated from pairwise
# alignments. Valid when either of --blobalpair, --localpair, --
# genafpair, --fastapair or --blastpair is selected. Default: 2.7
_Option(
["--weighti", "weighti"],
"Weighting factor for the consistency term calculated "
"from pairwise alignments. Default: 2.7",
checker_function=lambda x: isinstance(x, float),
equate=False,
),
# Guide tree is built number times in the progressive stage. Valid
# with 6mer distance. Default: 2
_Option(
["--retree", "retree"],
"Guide tree is built number times in the progressive "
"stage. Valid with 6mer distance. Default: 2",
checker_function=lambda x: isinstance(x, int),
equate=False,
),
# Number cycles of iterative refinement are performed. Default: 0
_Option(
["--maxiterate", "maxiterate"],
"Number cycles of iterative refinement are performed. Default: 0",
checker_function=lambda x: isinstance(x, int),
equate=False,
),
# Number of threads to use. Default: 1
_Option(
["--thread", "thread"],
"Number of threads to use. Default: 1",
checker_function=lambda x: isinstance(x, int),
equate=False,
),
# Use FFT approximation in group-to-group alignment. Default: on
_Switch(
["--fft", "fft"],
"Use FFT approximation in group-to-group alignment. Default: on",
),
# Do not use FFT approximation in group-to-group alignment. Default:
# off
_Switch(
["--nofft", "nofft"],
"Do not use FFT approximation in group-to-group "
"alignment. Default: off",
),
# Alignment score is not checked in the iterative refinement stage.
# Default: off (score is checked)
_Switch(
["--noscore", "noscore"],
"Alignment score is not checked in the iterative "
"refinement stage. Default: off (score is checked)",
),
# Use the Myers-Miller (1988) algorithm. Default: automatically
# turned on when the alignment length exceeds 10,000 (aa/nt).
_Switch(
["--memsave", "memsave"],
"Use the Myers-Miller (1988) algorithm. Default: "
"automatically turned on when the alignment length "
"exceeds 10,000 (aa/nt).",
),
# Use a fast tree-building method (PartTree, Katoh and Toh 2007) with
# the 6mer distance. Recommended for a large number (> ~10,000) of
# sequences are input. Default: off
_Switch(
["--parttree", "parttree"],
"Use a fast tree-building method with the 6mer "
"distance. Default: off",
),
# The PartTree algorithm is used with distances based on DP. Slightly
# more accurate and slower than --parttree. Recommended for a large
# number (> ~10,000) of sequences are input. Default: off
_Switch(
["--dpparttree", "dpparttree"],
"The PartTree algorithm is used with distances "
"based on DP. Default: off",
),
# The PartTree algorithm is used with distances based on FASTA.
# Slightly more accurate and slower than --parttree. Recommended for
# a large number (> ~10,000) of sequences are input. FASTA is
# required. Default: off
_Switch(
["--fastaparttree", "fastaparttree"],
"The PartTree algorithm is used with distances based "
"on FASTA. Default: off",
),
# The number of partitions in the PartTree algorithm. Default: 50
_Option(
["--partsize", "partsize"],
"The number of partitions in the PartTree algorithm. Default: 50",
checker_function=lambda x: isinstance(x, int),
equate=False,
),
# Do not make alignment larger than number sequences. Valid only with
# the --*parttree options. Default: the number of input sequences
_Switch(
["--groupsize", "groupsize"],
"Do not make alignment larger than number sequences. "
"Default: the number of input sequences",
),
# Adjust direction according to the first sequence
# Mafft V6 beta function
_Switch(
["--adjustdirection", "adjustdirection"],
"Adjust direction according to the first sequence. Default off.",
),
# Adjust direction according to the first sequence
# for highly diverged data; very slow
# Mafft V6 beta function
_Switch(
["--adjustdirectionaccurately", "adjustdirectionaccurately"],
"Adjust direction according to the first sequence,"
"for highly diverged data; very slow"
"Default off.",
),
# **** Parameter ****
# Gap opening penalty at group-to-group alignment. Default: 1.53
_Option(
["--op", "op"],
"Gap opening penalty at group-to-group alignment. Default: 1.53",
checker_function=lambda x: isinstance(x, float),
equate=False,
),
# Offset value, which works like gap extension penalty, for group-to-
# group alignment. Deafult: 0.123
_Option(
["--ep", "ep"],
"Offset value, which works like gap extension penalty, "
"for group-to- group alignment. Default: 0.123",
checker_function=lambda x: isinstance(x, float),
equate=False,
),
# Gap opening penalty at local pairwise alignment. Valid when the --
# localpair or --genafpair option is selected. Default: -2.00
_Option(
["--lop", "lop"],
"Gap opening penalty at local pairwise alignment. Default: 0.123",
checker_function=lambda x: isinstance(x, float),
equate=False,
),
# Offset value at local pairwise alignment. Valid when the --
# localpair or --genafpair option is selected. Default: 0.1
_Option(
["--lep", "lep"],
"Offset value at local pairwise alignment. Default: 0.1",
checker_function=lambda x: isinstance(x, float),
equate=False,
),
# Gap extension penalty at local pairwise alignment. Valid when the -
# -localpair or --genafpair option is selected. Default: -0.1
_Option(
["--lexp", "lexp"],
"Gap extension penalty at local pairwise alignment. Default: -0.1",
checker_function=lambda x: isinstance(x, float),
equate=False,
),
# Gap opening penalty to skip the alignment. Valid when the --
# genafpair option is selected. Default: -6.00
_Option(
["--LOP", "LOP"],
"Gap opening penalty to skip the alignment. Default: -6.00",
checker_function=lambda x: isinstance(x, float),
equate=False,
),
# Gap extension penalty to skip the alignment. Valid when the --
# genafpair option is selected. Default: 0.00
_Option(
["--LEXP", "LEXP"],
"Gap extension penalty to skip the alignment. Default: 0.00",
checker_function=lambda x: isinstance(x, float),
equate=False,
),
# BLOSUM number matrix (Henikoff and Henikoff 1992) is used.
# number=30, 45, 62 or 80. Default: 62
_Option(
["--bl", "bl"],
"BLOSUM number matrix is used. Default: 62",
checker_function=lambda x: x in BLOSUM_MATRICES,
equate=False,
),
# JTT PAM number (Jones et al. 1992) matrix is used. number>0.
# Default: BLOSUM62
_Option(
["--jtt", "jtt"],
"JTT PAM number (Jones et al. 1992) matrix is used. "
"number>0. Default: BLOSUM62",
equate=False,
),
# Transmembrane PAM number (Jones et al. 1994) matrix is used.
# number>0. Default: BLOSUM62
_Option(
["--tm", "tm"],
"Transmembrane PAM number (Jones et al. 1994) "
"matrix is used. number>0. Default: BLOSUM62",
filename=True, # to ensure spaced inputs are quoted
equate=False,
),
# Use a user-defined AA scoring matrix. The format of matrixfile is
# the same to that of BLAST. Ignored when nucleotide sequences are
# input. Default: BLOSUM62
_Option(
["--aamatrix", "aamatrix"],
"Use a user-defined AA scoring matrix. Default: BLOSUM62",
filename=True, # to ensure spaced inputs are quoted
equate=False,
),
# Incorporate the AA/nuc composition information into the scoring
# matrix. Default: off
_Switch(
["--fmodel", "fmodel"],
"Incorporate the AA/nuc composition information into "
"the scoring matrix (True) or not (False, default)",
),
# **** Output ****
# Name length for CLUSTAL and PHYLIP format output
_Option(
["--namelength", "namelength"],
"""Name length in CLUSTAL and PHYLIP output.
MAFFT v6.847 (2011) added --namelength for use with
the --clustalout option for CLUSTAL output.
MAFFT v7.024 (2013) added support for this with the
--phylipout option for PHYLIP output (default 10).
""",
checker_function=lambda x: isinstance(x, int),
equate=False,
),
# Output format: clustal format. Default: off (fasta format)
_Switch(
["--clustalout", "clustalout"],
"Output format: clustal (True) or fasta (False, default)",
),
# Output format: phylip format.
# Added in beta with v6.847, fixed in v6.850 (2011)
_Switch(
["--phylipout", "phylipout"],
"Output format: phylip (True), or fasta (False, default)",
),
# Output order: same as input. Default: on
_Switch(
["--inputorder", "inputorder"],
"Output order: same as input (True, default) or alignment "
"based (False)",
),
# Output order: aligned. Default: off (inputorder)
_Switch(
["--reorder", "reorder"],
"Output order: aligned (True) or in input order (False, default)",
),
# Guide tree is output to the input.tree file. Default: off
_Switch(
["--treeout", "treeout"],
"Guide tree is output to the input.tree file (True) or "
"not (False, default)",
),
# Do not report progress. Default: off
_Switch(
["--quiet", "quiet"],
"Do not report progress (True) or not (False, default).",
),
# **** Input ****
# Assume the sequences are nucleotide. Deafult: auto
_Switch(
["--nuc", "nuc"],
"Assume the sequences are nucleotide (True/False). Default: auto",
),
# Assume the sequences are amino acid. Deafult: auto
_Switch(
["--amino", "amino"],
"Assume the sequences are amino acid (True/False). Default: auto",
),
# MAFFT has multiple --seed commands where the unaligned input is
# aligned to the seed alignment. There can be multiple seeds in the
# form: "mafft --seed align1 --seed align2 [etc] input"
# Effectively for n number of seed alignments.
# TODO - Can we use class _ArgumentList here?
_Option(
["--seed", "seed"],
"Seed alignments given in alignment_n (fasta format) "
"are aligned with sequences in input.",
filename=True,
equate=False,
),
# The input (must be FASTA format)
_Argument(["input"], "Input file name", filename=True, is_required=True),
# mafft-profile takes a second alignment input as an argument:
# mafft-profile align1 align2
_Argument(
["input1"],
"Second input file name for the mafft-profile command",
filename=True,
),
]
AbstractCommandline.__init__(self, cmd, **kwargs)
if __name__ == "__main__":
from Bio._utils import run_doctest
run_doctest()
| 45.605505
| 87
| 0.550795
|
4a0b9260713374341ea40cddf439cd5e6917effe
| 1,372
|
py
|
Python
|
tests/test_modelling.py
|
dennisbrookner/pymol-psico
|
3c7730882e879fe5d23e57dd808b9642a4413b0e
|
[
"BSD-2-Clause"
] | null | null | null |
tests/test_modelling.py
|
dennisbrookner/pymol-psico
|
3c7730882e879fe5d23e57dd808b9642a4413b0e
|
[
"BSD-2-Clause"
] | null | null | null |
tests/test_modelling.py
|
dennisbrookner/pymol-psico
|
3c7730882e879fe5d23e57dd808b9642a4413b0e
|
[
"BSD-2-Clause"
] | 1
|
2021-12-27T14:25:52.000Z
|
2021-12-27T14:25:52.000Z
|
import psico.modelling
from pymol import cmd
from pathlib import Path
DATA_PATH = Path(__file__).resolve().parent / 'data'
def test_mutate():
cmd.reinitialize()
cmd.load(DATA_PATH / '2x19-frag-mse.pdb')
psico.modelling.mutate("resi 134", "K", inplace=1)
assert psico.modelling.get_seq("all") == "LSKMPD"
def test_mutate_all():
cmd.reinitialize()
cmd.load(DATA_PATH / '2x19-frag-mse.pdb')
psico.modelling.mutate_all("resi 134+137", "K", inplace=1)
assert psico.modelling.get_seq("all") == "LSKMPK"
def test_add_missing_atoms():
cmd.reinitialize()
cmd.load(DATA_PATH / '2x19-frag-mse.pdb')
cmd.remove("not backbone")
assert cmd.count_atoms("resi 132") == 4
psico.modelling.add_missing_atoms('resi 132+133', cycles=10)
assert cmd.count_atoms("resi 132") == 8
def test_peptide_rebuild():
cmd.reinitialize()
cmd.load(DATA_PATH / '2x19-frag-mse.pdb', "m1")
psico.modelling.peptide_rebuild("m2", "m1", cycles=100)
assert psico.modelling.get_seq("m2") == "LSMMPD"
def test_get_seq():
cmd.reinitialize()
cmd.load(DATA_PATH / '2x19-frag-mse.pdb')
assert psico.modelling.get_seq("all") == "LSMMPD"
cmd.remove("resi 134")
assert psico.modelling.get_seq("all") == "LS/MPD"
cmd.alter("resi 137", "resn = 'XXX'")
assert psico.modelling.get_seq("all", unknown="#") == "LS/MP#"
| 29.826087
| 66
| 0.672012
|
4a0b935510aec2ba7a413a526862bc3b48785362
| 982
|
py
|
Python
|
docs/examples/lib/gui-qt.py
|
ivanov/ipython
|
62cc379d3b454923cb48e94663f385f54ec806cc
|
[
"BSD-3-Clause-Clear"
] | 2
|
2015-04-21T12:12:43.000Z
|
2015-04-21T12:12:54.000Z
|
docs/examples/lib/gui-qt.py
|
08saikiranreddy/ipython
|
3498382180ad409592f46a9dd0d190ca917bfbff
|
[
"BSD-3-Clause-Clear"
] | 1
|
2015-07-16T22:26:53.000Z
|
2015-07-16T22:26:53.000Z
|
docs/examples/lib/gui-qt.py
|
08saikiranreddy/ipython
|
3498382180ad409592f46a9dd0d190ca917bfbff
|
[
"BSD-3-Clause-Clear"
] | null | null | null |
#!/usr/bin/env python
"""Simple Qt4 example to manually test event loop integration.
This is meant to run tests manually in ipython as:
In [5]: %gui qt
In [6]: %run gui-qt.py
Ref: Modified from http://zetcode.com/tutorials/pyqt4/firstprograms/
"""
import sys
from PyQt4 import QtGui, QtCore
class SimpleWindow(QtGui.QWidget):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.setGeometry(300, 300, 200, 80)
self.setWindowTitle('Hello World')
quit = QtGui.QPushButton('Close', self)
quit.setGeometry(10, 10, 60, 35)
self.connect(quit, QtCore.SIGNAL('clicked()'),
self, QtCore.SLOT('close()'))
if __name__ == '__main__':
app = QtCore.QCoreApplication.instance()
if app is None:
app = QtGui.QApplication([])
sw = SimpleWindow()
sw.show()
try:
from IPython import appstart_qt4; appstart_qt4(app)
except ImportError:
app.exec_()
| 23.95122
| 68
| 0.645621
|
4a0b94139858bea57c03fd3396c4679677d92ada
| 737
|
py
|
Python
|
setup.py
|
laurentb/confman
|
1f8d05f494a8b3c8fbf89a477b2bd67bc60dbac7
|
[
"MIT"
] | null | null | null |
setup.py
|
laurentb/confman
|
1f8d05f494a8b3c8fbf89a477b2bd67bc60dbac7
|
[
"MIT"
] | null | null | null |
setup.py
|
laurentb/confman
|
1f8d05f494a8b3c8fbf89a477b2bd67bc60dbac7
|
[
"MIT"
] | null | null | null |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
setup(
name='confman',
version='0.3.1',
description='Lazy, rootless, yet powerful config file management mostly using symlinks',
long_description=open('README').read(),
author='Laurent Bachelier',
author_email='laurent@bachelier.name',
url='http://git.p.engu.in/laurentb/confman/',
py_modules=['confman'],
classifiers=[
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
],
)
| 30.708333
| 92
| 0.618725
|
4a0b945d7da4ac9d1d92a815f134a7a7d2790fb7
| 2,348
|
py
|
Python
|
LeetCodeSolutions/LeetCode_0428.py
|
lih627/python-algorithm-templates
|
a61fd583e33a769b44ab758990625d3381793768
|
[
"MIT"
] | 24
|
2020-03-28T06:10:25.000Z
|
2021-11-23T05:01:29.000Z
|
LeetCodeSolutions/LeetCode_0428.py
|
lih627/python-algorithm-templates
|
a61fd583e33a769b44ab758990625d3381793768
|
[
"MIT"
] | null | null | null |
LeetCodeSolutions/LeetCode_0428.py
|
lih627/python-algorithm-templates
|
a61fd583e33a769b44ab758990625d3381793768
|
[
"MIT"
] | 8
|
2020-05-18T02:43:16.000Z
|
2021-05-24T18:11:38.000Z
|
"""
# Definition for a Node.
class Node(object):
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string.
:type root: Node
:rtype: str
"""
# 1[1]3[3,2,4]2[5,6]
if not root:
return ''
from collections import deque
que = deque([root])
tmp = "[{}]".format(root.val)
n = str(len(tmp))
ans = n + tmp
while que:
node = que.popleft()
if not node.children:
ans += "0[]"
else:
tmp = "[{}]".format(",".join([str(_node.val) for _node in node.children]))
n = str(len(tmp))
ans += str(n) + tmp
que.extend(node.children)
# 切除尾部'0[]'序列
while ans and ans[-3:] == "0[]":
ans = ans[:-3]
print(ans)
return ans
def deserialize(self, data: str) -> 'Node':
"""Decodes your encoded data to tree.
:type data: str
:rtype: Node
"""
if not data:
return None
length = ''
idx = 0
while data[idx] != "[":
length += data[idx]
idx += 1
length = int(length)
next_idx = idx + length
root_val = int(data[idx + 1: next_idx - 1])
root = Node(root_val, [])
idx = next_idx
from collections import deque
que = deque([root])
while idx < len(data):
# print([_.val for _ in que])
node = que.popleft()
if data[idx] == '0':
idx += 3
continue
length = ''
while data[idx] != '[':
length += data[idx]
idx += 1
length = int(length)
next_idx = idx + length
node_vals = [int(_) for _ in data[idx + 1: next_idx - 1].split(',')]
for val in node_vals:
_node = Node(val, [])
node.children.append(_node)
que.append(_node)
idx = next_idx
return root
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.deserialize(codec.serialize(root))
| 27.623529
| 90
| 0.456985
|
4a0b94acaa55e9beb1a8b120291042a77eb23b64
| 5,940
|
py
|
Python
|
pymatgen/symmetry/tests/test_settings.py
|
naik-aakash/pymatgen
|
394e0d71bf1d1025fcf75498cbb16aa3f41ce78c
|
[
"MIT"
] | 1
|
2022-03-24T04:12:16.000Z
|
2022-03-24T04:12:16.000Z
|
pymatgen/symmetry/tests/test_settings.py
|
naik-aakash/pymatgen
|
394e0d71bf1d1025fcf75498cbb16aa3f41ce78c
|
[
"MIT"
] | null | null | null |
pymatgen/symmetry/tests/test_settings.py
|
naik-aakash/pymatgen
|
394e0d71bf1d1025fcf75498cbb16aa3f41ce78c
|
[
"MIT"
] | null | null | null |
#!/usr/bin/env python
import unittest
import numpy as np
from pymatgen.symmetry.settings import JonesFaithfulTransformation, Lattice, SymmOp
__author__ = "Matthew Horton"
__copyright__ = "Copyright 2017, The Materials Project"
__version__ = "0.1"
__maintainer__ = "Matthew Horton"
__email__ = "mkhorton@lbl.gov"
__status__ = "Development"
__date__ = "Apr 2017"
class JonesFaithfulTransformationTest(unittest.TestCase):
def setUp(self):
self.test_strings = [
"a,b,c;0,0,0", # identity
"a-b,a+b,2c;0,0,1/2",
"a/4+b/4-c/2,a/4-b/4,-a/2-b/2;0,0,0",
"a,b,c;1/4,1/2,3/4",
] # pure translation
self.test_Pps = [
([[1, 0, 0], [0, 1, 0], [0, 0, 1]], [0, 0, 0]),
([[1, 1, 0], [-1, 1, 0], [0, 0, 2]], [0, 0, 0.5]),
([[0.25, 0.25, -0.5], [0.25, -0.25, -0.5], [-0.5, 0, 0]], [0, 0, 0]),
([[1, 0, 0], [0, 1, 0], [0, 0, 1]], [0.25, 0.5, 0.75]),
]
def test_init(self):
for test_string, test_Pp in zip(self.test_strings, self.test_Pps):
jft = JonesFaithfulTransformation.from_transformation_string(test_string)
jft2 = JonesFaithfulTransformation(test_Pp[0], test_Pp[1])
self.assertTrue(np.allclose(jft.P, jft2.P))
self.assertTrue(np.allclose(jft.p, jft2.p))
self.assertEqual(test_string, jft.transformation_string)
self.assertEqual(test_string, jft2.transformation_string)
def test_inverse(self):
for test_string in self.test_strings:
jft = JonesFaithfulTransformation.from_transformation_string(test_string)
self.assertEqual(jft, jft.inverse.inverse)
self.assertEqual(jft.transformation_string, jft.inverse.inverse.transformation_string)
def test_transform_lattice(self):
lattice = Lattice.cubic(5)
all_ref_lattices = [
[[5.0, 0.0, 0.0], [0.0, 5.0, 0.0], [0.0, 0.0, 5.0]],
[[5.0, 5.0, 0.0], [-5.0, 5.0, 0.0], [0.0, 0.0, 10.0]],
[[1.25, 1.25, -2.5], [1.25, -1.25, -2.5], [-2.5, 0.0, 0.0]],
[[5.0, 0.0, 0.0], [0.0, 5.0, 0.0], [0.0, 0.0, 5.0]],
]
for ref_lattice, (P, p) in zip(all_ref_lattices, self.test_Pps):
jft = JonesFaithfulTransformation(P, p)
self.assertTrue(np.allclose(jft.transform_lattice(lattice).matrix, ref_lattice))
def test_transform_coords(self):
coords = [[0, 0, 0], [0.5, 0.5, 0.5]]
all_ref_coords = [
[[0.0, 0.0, 0.0], [0.5, 0.5, 0.5]],
[[0.0, 0.0, -0.25], [0.0, 0.5, 0.0]],
[[0.0, 0.0, 0.0], [-1.0, 0.0, -1.5]],
[[-0.25, -0.5, -0.75], [0.25, 0.0, -0.25]],
]
for ref_coords, (P, p) in zip(all_ref_coords, self.test_Pps):
jft = JonesFaithfulTransformation(P, p)
transformed_coords = jft.transform_coords(coords)
for coord, ref_coord in zip(transformed_coords, ref_coords):
self.assertTrue(np.allclose(coord, ref_coord))
def test_transform_symmops(self):
# reference data for this test taken from GENPOS
# http://cryst.ehu.es/cryst/get_gen.html
# Fm-3m
input_symmops = """x,y,z
-x,-y,z
-x,y,-z
x,-y,-z
z,x,y
z,-x,-y
-z,-x,y
-z,x,-y
y,z,x
-y,z,-x
y,-z,-x
-y,-z,x
y,x,-z
-y,-x,-z
y,-x,z
-y,x,z
x,z,-y
-x,z,y
-x,-z,-y
x,-z,y
z,y,-x
z,-y,x
-z,y,x
-z,-y,-x
-x,-y,-z
x,y,-z
x,-y,z
-x,y,z
-z,-x,-y
-z,x,y
z,x,-y
z,-x,y
-y,-z,-x
y,-z,x
-y,z,x
y,z,-x
-y,-x,z
y,x,z
-y,x,-z
y,-x,-z
-x,-z,y
x,-z,-y
x,z,y
-x,z,-y
-z,-y,x
-z,y,-x
z,-y,-x
z,y,x"""
# Fm-3m transformed by (a-b,a+b,2c;0,0,1/2)
ref_transformed_symmops = """x,y,z
-x,-y,z
-y,-x,-z+1/2
y,x,-z+1/2
-1/2x-1/2y+z+1/4,1/2x+1/2y+z+1/4,-1/2x+1/2y+3/4
1/2x+1/2y+z+1/4,-1/2x-1/2y+z+1/4,1/2x-1/2y+3/4
1/2x+1/2y-z+3/4,-1/2x-1/2y-z+3/4,-1/2x+1/2y+3/4
-1/2x-1/2y-z+3/4,1/2x+1/2y-z+3/4,1/2x-1/2y+3/4
-1/2x+1/2y-z+3/4,-1/2x+1/2y+z+1/4,1/2x+1/2y+3/4
1/2x-1/2y-z+3/4,1/2x-1/2y+z+1/4,-1/2x-1/2y+3/4
-1/2x+1/2y+z+1/4,-1/2x+1/2y-z+3/4,-1/2x-1/2y+3/4
1/2x-1/2y+z+1/4,1/2x-1/2y-z+3/4,1/2x+1/2y+3/4
-x,y,-z+1/2
x,-y,-z+1/2
y,-x,z
-y,x,z
1/2x+1/2y-z+3/4,1/2x+1/2y+z+1/4,1/2x-1/2y+3/4
-1/2x-1/2y-z+3/4,-1/2x-1/2y+z+1/4,-1/2x+1/2y+3/4
-1/2x-1/2y+z+1/4,-1/2x-1/2y-z+3/4,1/2x-1/2y+3/4
1/2x+1/2y+z+1/4,1/2x+1/2y-z+3/4,-1/2x+1/2y+3/4
1/2x-1/2y+z+1/4,-1/2x+1/2y+z+1/4,-1/2x-1/2y+3/4
-1/2x+1/2y+z+1/4,1/2x-1/2y+z+1/4,1/2x+1/2y+3/4
1/2x-1/2y-z+3/4,-1/2x+1/2y-z+3/4,1/2x+1/2y+3/4
-1/2x+1/2y-z+3/4,1/2x-1/2y-z+3/4,-1/2x-1/2y+3/4
-x,-y,-z+1/2
x,y,-z+1/2
y,x,z
-y,-x,z
1/2x+1/2y-z+3/4,-1/2x-1/2y-z+3/4,1/2x-1/2y+3/4
-1/2x-1/2y-z+3/4,1/2x+1/2y-z+3/4,-1/2x+1/2y+3/4
-1/2x-1/2y+z+1/4,1/2x+1/2y+z+1/4,1/2x-1/2y+3/4
1/2x+1/2y+z+1/4,-1/2x-1/2y+z+1/4,-1/2x+1/2y+3/4
1/2x-1/2y+z+1/4,1/2x-1/2y-z+3/4,-1/2x-1/2y+3/4
-1/2x+1/2y+z+1/4,-1/2x+1/2y-z+3/4,1/2x+1/2y+3/4
1/2x-1/2y-z+3/4,1/2x-1/2y+z+1/4,1/2x+1/2y+3/4
-1/2x+1/2y-z+3/4,-1/2x+1/2y+z+1/4,-1/2x-1/2y+3/4
x,-y,z
-x,y,z
-y,x,-z+1/2
y,-x,-z+1/2
-1/2x-1/2y+z+1/4,-1/2x-1/2y-z+3/4,-1/2x+1/2y+3/4
1/2x+1/2y+z+1/4,1/2x+1/2y-z+3/4,1/2x-1/2y+3/4
1/2x+1/2y-z+3/4,1/2x+1/2y+z+1/4,-1/2x+1/2y+3/4
-1/2x-1/2y-z+3/4,-1/2x-1/2y+z+1/4,1/2x-1/2y+3/4
-1/2x+1/2y-z+3/4,1/2x-1/2y-z+3/4,1/2x+1/2y+3/4
1/2x-1/2y-z+3/4,-1/2x+1/2y-z+3/4,-1/2x-1/2y+3/4
-1/2x+1/2y+z+1/4,1/2x-1/2y+z+1/4,-1/2x-1/2y+3/4
1/2x-1/2y+z+1/4,-1/2x+1/2y+z+1/4,1/2x+1/2y+3/4"""
jft = JonesFaithfulTransformation.from_transformation_string(self.test_strings[1])
input_symmops = [SymmOp.from_xyz_string(s) for s in input_symmops.split()]
ref_transformed_symmops = [SymmOp.from_xyz_string(s) for s in ref_transformed_symmops.split()]
transformed_symmops = [jft.transform_symmop(op) for op in input_symmops]
for transformed_op, ref_transformed_op in zip(transformed_symmops, ref_transformed_symmops):
self.assertEqual(transformed_op, ref_transformed_op)
if __name__ == "__main__":
unittest.main()
| 30.306122
| 102
| 0.561111
|
4a0b956e639f4ab782a41258db5781282ba11b73
| 1,765
|
py
|
Python
|
src/models/methods/_area.py
|
gayashiva/air_model
|
fb6fb02b866a821ee8a83551be78c25bdb7da7c9
|
[
"FTL"
] | 3
|
2021-12-23T18:12:40.000Z
|
2022-01-12T10:48:21.000Z
|
src/models/methods/_area.py
|
Gayashiva/AIR_model
|
fb6fb02b866a821ee8a83551be78c25bdb7da7c9
|
[
"FTL"
] | 1
|
2022-01-31T15:59:08.000Z
|
2022-01-31T15:59:08.000Z
|
src/models/methods/_area.py
|
gayashiva/air_model
|
fb6fb02b866a821ee8a83551be78c25bdb7da7c9
|
[
"FTL"
] | null | null | null |
"""Icestupa class function that calculates surface area, ice radius and height
"""
import pandas as pd
import math
import numpy as np
from functools import lru_cache
import logging
logger = logging.getLogger("__main__")
def get_area(self, i):
if (self.df.j_cone[i]> 0) & (
self.df.loc[i - 1, "r_cone"] >= self.R_F
): # Growth rate positive and radius goes beyond spray radius
self.df.loc[i, "r_cone"] = self.df.loc[i - 1, "r_cone"]
self.df.loc[i, "h_cone"] = (
3 * self.df.loc[i, "iceV"] / (math.pi * self.df.loc[i, "r_cone"] ** 2)
)
self.df.loc[i, "s_cone"] = (
self.df.loc[i - 1, "h_cone"] / self.df.loc[i - 1, "r_cone"]
)
else:
# Maintain constant Height to radius ratio
self.df.loc[i, "s_cone"] = self.df.loc[i - 1, "s_cone"]
# Ice Radius
self.df.loc[i, "r_cone"] = math.pow(
3 * self.df.loc[i, "iceV"] / (math.pi * self.df.loc[i, "s_cone"]), 1 / 3
)
# Ice Height
self.df.loc[i, "h_cone"] = self.df.loc[i, "s_cone"] * self.df.loc[i, "r_cone"]
# Area of Conical Ice Surface
self.df.loc[i, "A_cone"] = (
math.pi
# * self.A_cone_corr
* self.df.loc[i, "r_cone"]
* math.pow(
(
math.pow(self.df.loc[i, "r_cone"], 2)
+ math.pow((self.df.loc[i, "h_cone"]), 2)
),
1 / 2,
)
)
self.df.loc[i, "f_cone"] = (
0.5
* self.df.loc[i, "h_cone"]
* self.df.loc[i, "r_cone"]
* math.cos(self.df.loc[i, "sea"])
+ math.pi
* math.pow(self.df.loc[i, "r_cone"], 2)
* 0.5
* math.sin(self.df.loc[i, "sea"])
) / self.df.loc[i, "A_cone"]
| 28.467742
| 86
| 0.503116
|
4a0b95f53edbf0d297051471f1fc396cc0964007
| 2,237
|
py
|
Python
|
model-optimizer/mo/front/kaldi/extractors/splice_component_ext.py
|
Dimitri1/openvino
|
05d97220d21a2ed91377524883485fdadf660761
|
[
"Apache-2.0"
] | 3
|
2020-02-09T23:25:37.000Z
|
2021-01-19T09:44:12.000Z
|
model-optimizer/mo/front/kaldi/extractors/splice_component_ext.py
|
Dimitri1/openvino
|
05d97220d21a2ed91377524883485fdadf660761
|
[
"Apache-2.0"
] | null | null | null |
model-optimizer/mo/front/kaldi/extractors/splice_component_ext.py
|
Dimitri1/openvino
|
05d97220d21a2ed91377524883485fdadf660761
|
[
"Apache-2.0"
] | 2
|
2020-04-18T16:24:39.000Z
|
2021-01-19T09:42:19.000Z
|
"""
Copyright (c) 2018-2019 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import numpy as np
from extensions.ops.splice import Splice
from mo.front.extractor import FrontExtractorOp
from mo.front.kaldi.loader.utils import find_next_tag, read_placeholder, read_binary_integer32_token, \
collect_until_whitespace
from mo.front.kaldi.utils import read_binary_vector
from mo.utils.error import Error
class SpliceFrontExtractor(FrontExtractorOp):
op = 'splicecomponent'
enabled = True
@staticmethod
def extract(node):
pb = node.parameters
mapping_rule = {
'context': list()
}
tag = find_next_tag(pb)
if tag == '<LeftContext>':
read_placeholder(pb, 1)
l_context = read_binary_integer32_token(pb)
tag = find_next_tag(pb)
if tag != '<RightContext>':
raise Error('Unknown token {} in SpliceComponent node {}'.format(tag, node.id))
read_placeholder(pb, 1)
r_context = read_binary_integer32_token(pb)
for i in range(-l_context, r_context + 1):
mapping_rule['context'].append(i)
elif tag == '<Context>':
collect_until_whitespace(pb)
mapping_rule['context'] = read_binary_vector(pb, False, dtype=np.int32)
else:
raise Error('Unknown token {} in SpliceComponent node {}'.format(tag, node.id))
tag = find_next_tag(pb)
if tag == '<ConstComponentDim>':
read_placeholder(pb, 1)
const_dim = read_binary_integer32_token(pb)
mapping_rule['const_dim'] = const_dim
Splice.update_node_stat(node, mapping_rule)
return __class__.enabled
| 36.672131
| 103
| 0.671882
|
4a0b96850419e38fee6bfe26bfbe4655f62fd857
| 184
|
py
|
Python
|
src/poms/msauth.py
|
lauro-cesar/poms
|
bbaa3c875d07ef041f429af074b4be9414abc8cb
|
[
"Apache-2.0"
] | 1
|
2021-07-31T21:12:03.000Z
|
2021-07-31T21:12:03.000Z
|
src/poms/msauth.py
|
lauro-cesar/poms
|
bbaa3c875d07ef041f429af074b4be9414abc8cb
|
[
"Apache-2.0"
] | null | null | null |
src/poms/msauth.py
|
lauro-cesar/poms
|
bbaa3c875d07ef041f429af074b4be9414abc8cb
|
[
"Apache-2.0"
] | null | null | null |
import asyncio
import os
import ast
import signal
import sys
import threading
import websockets
class MsAuth():
def __init__(*args,**kwargs):
pass
def autotest():
return True
| 12.266667
| 30
| 0.755435
|
4a0b96b3fad01c900abde76717842a65d3dc1ff4
| 1,136
|
py
|
Python
|
datamgt/helpers/getRating.py
|
CareHomeHub/CareHomePlatform
|
d811084bb72810fc0c35c6ccab18745480aefb3d
|
[
"MIT"
] | 1
|
2021-02-16T00:41:40.000Z
|
2021-02-16T00:41:40.000Z
|
datamgt/helpers/getRating.py
|
CareHomeHub/CareHomePlatform
|
d811084bb72810fc0c35c6ccab18745480aefb3d
|
[
"MIT"
] | 15
|
2021-02-16T00:34:01.000Z
|
2021-04-07T23:33:21.000Z
|
datamgt/helpers/getRating.py
|
CareHomeHub/CareHomePlatform
|
d811084bb72810fc0c35c6ccab18745480aefb3d
|
[
"MIT"
] | null | null | null |
def getRatings(cqc_data):
cnt = 0
# count = len(cqc_data)
# print(count)
result = []
for element in cqc_data:
cnt += 1
doc={}
if 'currentRatings' in element['loc']:
doc["loc"] = element['loc']['locationId']
doc["overall"] = element['loc']['currentRatings']['overall']['rating']
doc["safe"] = element['loc']['currentRatings']['overall']['keyQuestionRatings'][0]['rating']
doc["Well-led"] = element['loc']['currentRatings']['overall']['keyQuestionRatings'][1]['rating']
doc["Caring"] = element['loc']['currentRatings']['overall']['keyQuestionRatings'][2]['rating']
doc["Responsive"] = element['loc']['currentRatings']['overall']['keyQuestionRatings'][3]['rating']
doc["Effective"] = element['loc']['currentRatings']['overall']['keyQuestionRatings'][4]['rating']
result.append(doc)
else:
print(f"currentRatings {element['loc']} missing")
print(f"cqc_data ratings overall: {element['loc']}")
print(f"\n\n\nResult (getRatings ) :\n\ {result}")
return result
| 43.692308
| 110
| 0.575704
|
4a0b97c467b1e130937780ac289f9a53f764cb05
| 2,555
|
py
|
Python
|
examples/Python/ReconstructionSystem/integrate_scene.py
|
dmontagu/Open3D
|
0667179c2d69f3e191104b6f70378b4dee6f406a
|
[
"MIT"
] | null | null | null |
examples/Python/ReconstructionSystem/integrate_scene.py
|
dmontagu/Open3D
|
0667179c2d69f3e191104b6f70378b4dee6f406a
|
[
"MIT"
] | 1
|
2021-01-21T13:43:32.000Z
|
2021-01-21T13:43:32.000Z
|
examples/Python/ReconstructionSystem/integrate_scene.py
|
Surfndez/Open3D
|
59c0645a169c589345a1b04753d5afdb5800b349
|
[
"MIT"
] | 1
|
2019-09-20T22:26:49.000Z
|
2019-09-20T22:26:49.000Z
|
# Open3D: www.open3d.org
# The MIT License (MIT)
# See license file or visit www.open3d.org for details
# examples/Python/Tutorial/ReconstructionSystem/integrate_scene.py
import numpy as np
import math
import sys
from open3d import *
sys.path.append("../Utility")
from file import *
def scalable_integrate_rgb_frames(path_dataset, intrinsic, config):
[color_files, depth_files] = get_rgbd_file_lists(path_dataset)
n_files = len(color_files)
n_fragments = int(math.ceil(float(n_files) / \
config['n_frames_per_fragment']))
volume = ScalableTSDFVolume(voxel_length = config["tsdf_cubic_size"]/512.0,
sdf_trunc = 0.04, color_type = TSDFVolumeColorType.RGB8)
pose_graph_fragment = read_pose_graph(join(
path_dataset, config["template_refined_posegraph_optimized"]))
for fragment_id in range(len(pose_graph_fragment.nodes)):
pose_graph_rgbd = read_pose_graph(join(path_dataset,
config["template_fragment_posegraph_optimized"] % fragment_id))
for frame_id in range(len(pose_graph_rgbd.nodes)):
frame_id_abs = fragment_id * \
config['n_frames_per_fragment'] + frame_id
print("Fragment %03d / %03d :: integrate rgbd frame %d (%d of %d)."
% (fragment_id, n_fragments-1, frame_id_abs, frame_id+1,
len(pose_graph_rgbd.nodes)))
color = read_image(color_files[frame_id_abs])
depth = read_image(depth_files[frame_id_abs])
rgbd = create_rgbd_image_from_color_and_depth(color, depth,
depth_trunc = config["max_depth"],
convert_rgb_to_intensity = False)
pose = np.dot(pose_graph_fragment.nodes[fragment_id].pose,
pose_graph_rgbd.nodes[frame_id].pose)
volume.integrate(rgbd, intrinsic, np.linalg.inv(pose))
mesh = volume.extract_triangle_mesh()
mesh.compute_vertex_normals()
if config["debug_mode"]:
draw_geometries([mesh])
mesh_name = join(path_dataset, config["template_global_mesh"])
write_triangle_mesh(mesh_name, mesh, False, True)
def run(config):
print("integrate the whole RGBD sequence using estimated camera pose.")
if config["path_intrinsic"]:
intrinsic = read_pinhole_camera_intrinsic(config["path_intrinsic"])
else:
intrinsic = PinholeCameraIntrinsic(
PinholeCameraIntrinsicParameters.PrimeSenseDefault)
scalable_integrate_rgb_frames(config["path_dataset"], intrinsic, config)
| 41.209677
| 79
| 0.68728
|
4a0b97d766b23d42d47feface588f635c3a0b2f3
| 5,010
|
py
|
Python
|
push_and_test/dependency_manager.py
|
dvnstrcklnd/pfish-tools
|
605e0babaf526241c0b39c26617397380822e6b7
|
[
"MIT"
] | null | null | null |
push_and_test/dependency_manager.py
|
dvnstrcklnd/pfish-tools
|
605e0babaf526241c0b39c26617397380822e6b7
|
[
"MIT"
] | null | null | null |
push_and_test/dependency_manager.py
|
dvnstrcklnd/pfish-tools
|
605e0babaf526241c0b39c26617397380822e6b7
|
[
"MIT"
] | null | null | null |
import os
import glob
import re
import json
import subprocess
import time
import pathlib
class DependencyManager():
PFISH_CMD = "python3 ../script/pyfish.py"
NEWLINE = "\n"
def __init__(self, category, operation_type, dependencies_file, definitions):
self.operation_type_category = category
self.operation_type_name = operation_type
self.definitions = definitions
self.operation_type_directory = self.select_directory(self.operation_type_category,
self.operation_type_name)
self.dependencies_file = dependencies_file
self.all_dependencies = self.load_all_dependencies()
self.dependencies = self.select_dependencies()
self.pfish_default = self.get_pfish_default()
def push_all_libraries(self, force):
for dependency in self.dependencies["libraries"]:
self.push_library(dependency, force)
def push_library(self, dependency, force):
if force or self.library_stale(dependency):
category = dependency["category"]
name = dependency["name"]
msg = self.push_library_check_status(category, name)
print(msg)
self.add_dependency_timestamp(dependency)
def push_library_check_status(self, category, name):
directory = self.select_directory(category, name)
msg = self.pfish_exec('push', directory)
if self.library_push_status(msg, name) == 'created':
msg = self.pfish_exec('push', directory)
return msg
# TODO: This is not working because the messages from are not being passed back
def library_push_status(self, msg, name):
if re.search("writing file {}".format(name), msg):
return 'complete'
elif re.search("Checking whether Definition File is for a Library", msg):
return 'created'
else:
return 'error'
def push_operation_type(self, force):
if force or self.operation_type_stale():
msg = self.pfish_exec('push', self.operation_type_directory)
print(msg)
self.add_operation_type_timestamp()
def test_operation_type(self):
msg = self.pfish_exec('test', self.operation_type_directory)
print(msg)
self.add_operation_type_timestamp()
def pfish_exec(self, task, directory):
cmd = "{} {} -d '{}'".format(DependencyManager.PFISH_CMD, task, directory)
return self.subprocess_check_output(cmd)
def add_dependency_timestamp(self, dependency):
self.add_timestamp(dependency)
def add_operation_type_timestamp(self):
self.add_timestamp(self.dependencies)
def add_timestamp(self, target):
target["last_push"][self.pfish_default] = self.timestamp()
self.save_all_dependencies()
def timestamp(self):
return time.time()
def operation_type_stale(self):
ptime = self.dependencies["last_push"].get(self.pfish_default)
if not ptime: return True
files = ["protocol.rb", "test.rb", "cost_model.rb", "documentation.rb", "precondition.rb"]
for file in files:
mtime = self.file_mtime(os.path.join(self.operation_type_directory, file))
if mtime > ptime: return True
return False
def library_stale(self, dependency):
directory = self.select_directory(dependency["category"], dependency["name"])
mtime = self.file_mtime(os.path.join(directory, "source.rb"))
ptime = dependency["last_push"].get(self.pfish_default)
if ptime:
return mtime > ptime
else:
return True
def file_mtime(self, filename):
fname = pathlib.Path(filename)
assert fname.exists(), f'No such file: {filename}'
return fname.stat().st_mtime
def get_pfish_default(self):
cmd = "{} configure show".format(DependencyManager.PFISH_CMD)
msg = self.subprocess_check_output(cmd)
return msg.split(DependencyManager.NEWLINE)[0].split(" ")[-1]
def subprocess_check_output(self, cmd):
msg = subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT)
return msg.decode("utf-8")
def load_all_dependencies(self):
with open(self.dependencies_file, 'r') as f:
all_dependencies = json.load(f)
return all_dependencies
def save_all_dependencies(self):
with open(self.dependencies_file, 'w') as f:
json.dump(self.all_dependencies, f, indent=2)
def select_dependencies(self):
return self.select(self.all_dependencies, self.operation_type_category,
self.operation_type_name)
def select_directory(self, category, name):
return self.select(self.definitions, category, name).get("directory")
def select(self, lst, category, name):
selected = (x for x in lst if x["category"] == category and x["name"] == name)
return next(selected, None)
| 37.954545
| 98
| 0.656287
|
4a0b97dd07f7f33a79771b4e9ca3680d7300b00e
| 36,924
|
py
|
Python
|
typhos/widgets.py
|
ronpandolfi/typhos
|
2a92d895438d3b0fc41ad51dd5b7f783ca306cf1
|
[
"BSD-3-Clause-LBNL"
] | null | null | null |
typhos/widgets.py
|
ronpandolfi/typhos
|
2a92d895438d3b0fc41ad51dd5b7f783ca306cf1
|
[
"BSD-3-Clause-LBNL"
] | null | null | null |
typhos/widgets.py
|
ronpandolfi/typhos
|
2a92d895438d3b0fc41ad51dd5b7f783ca306cf1
|
[
"BSD-3-Clause-LBNL"
] | null | null | null |
"""
Typhos widgets and related utilities.
"""
import collections
import datetime
import inspect
import logging
import numpy as np
import pydm
import pydm.widgets
import pydm.widgets.base
import pydm.widgets.byte
import pydm.widgets.enum_button
import qtawesome as qta
from ophyd.signal import EpicsSignalBase
from pydm.widgets.display_format import DisplayFormat
from pyqtgraph.parametertree import parameterTypes as ptypes
from qtpy import QtGui, QtWidgets
from qtpy.QtCore import Property, QObject, QSize, Qt, Signal, Slot
from qtpy.QtWidgets import (QAction, QDialog, QDockWidget, QPushButton,
QToolBar, QVBoxLayout, QWidget)
from . import plugins, utils, variety
from .textedit import TyphosTextEdit # noqa: F401
from .tweakable import TyphosTweakable # noqa: F401
from .variety import use_for_variety_read, use_for_variety_write
logger = logging.getLogger(__name__)
EXPONENTIAL_UNITS = ['mtorr', 'torr', 'kpa', 'pa']
class SignalWidgetInfo(
collections.namedtuple(
'SignalWidgetInfo',
'read_cls read_kwargs write_cls write_kwargs'
)):
"""
Provides information on how to create signal widgets: class and kwargs.
Parameters
----------
read_cls : type
The readback widget class.
read_kwargs : dict
The readback widget initialization keyword arguments.
write_cls : type
The setpoint widget class.
write_kwargs : dict
The setpoint widget initialization keyword arguments.
"""
@classmethod
def from_signal(cls, obj, desc=None):
"""
Create a `SignalWidgetInfo` given an object and its description.
Parameters
----------
obj : :class:`ophyd.OphydObj`
The object
desc : dict, optional
The object description, if available.
"""
if desc is None:
desc = obj.describe()
read_cls, read_kwargs = widget_type_from_description(
obj, desc, read_only=True)
is_read_only = utils.is_signal_ro(obj) or (
read_cls is not None and issubclass(read_cls, SignalDialogButton))
if is_read_only:
write_cls = None
write_kwargs = {}
else:
write_cls, write_kwargs = widget_type_from_description(obj, desc)
return cls(read_cls, read_kwargs, write_cls, write_kwargs)
class TogglePanel(QWidget):
"""
Generic Panel Widget
Displays a widget below QPushButton that hides and shows the contents. It
is up to subclasses to re-point the attribute :attr:`.contents` to the
widget whose visibility you would like to toggle.
By default, it is assumed that the Panel is initialized with the
:attr:`.contents` widget as visible, however the contents will be hidden
and the button synced to the proper position if :meth:`.show_contents` is
called after instance creation
Parameters
----------
title : str
Title of Panel. This will be the text on the QPushButton
parent : QWidget
Attributes
----------
contents : QWidget
Widget whose visibility is controlled via the QPushButton
"""
def __init__(self, title, parent=None):
super().__init__(parent=parent)
# Create Widget Infrastructure
self.title = title
self.setLayout(QVBoxLayout())
self.layout().setContentsMargins(2, 2, 2, 2)
self.layout().setSpacing(5)
# Create button control
# Assuming widget is visible, set the button as checked
self.contents = None
self.hide_button = QPushButton(self.title)
self.hide_button.setCheckable(True)
self.hide_button.setChecked(True)
self.layout().addWidget(self.hide_button)
self.hide_button.clicked.connect(self.show_contents)
@Slot(bool)
def show_contents(self, show):
"""
Show the contents of the Widget
Hides the :attr:`.contents` QWidget and sets the :attr:`.hide_button`
to the proper status to indicate whether the widget is hidden or not
Parameters
----------
show : bool
"""
# Configure our button in case this slot was called elsewhere
self.hide_button.setChecked(show)
# Show or hide the widget if the contents exist
if self.contents:
if show:
self.show()
self.contents.show()
else:
self.contents.hide()
@use_for_variety_write('enum')
@use_for_variety_write('text-enum')
class TyphosComboBox(pydm.widgets.PyDMEnumComboBox):
"""
Notes
-----
"""
def wheelEvent(self, event: QtGui.QWheelEvent):
event.ignore()
@use_for_variety_write('scalar')
@use_for_variety_write('text')
class TyphosLineEdit(pydm.widgets.PyDMLineEdit):
"""
Reimplementation of PyDMLineEdit to set some custom defaults
Notes
-----
"""
def __init__(self, *args, display_format=None, **kwargs):
self._channel = None
self._setpoint_history_count = 5
self._setpoint_history = collections.deque(
[], self._setpoint_history_count)
super().__init__(*args, **kwargs)
self.showUnits = True
if display_format is not None:
self.displayFormat = display_format
@property
def setpoint_history(self):
"""
History of setpoints, as a dictionary of {setpoint: timestamp}
"""
return dict(self._setpoint_history)
@Property(int, designable=True)
def setpointHistoryCount(self):
"""
Number of items to show in the context menu "setpoint history"
"""
return self._setpoint_history_count
@setpointHistoryCount.setter
def setpointHistoryCount(self, value):
self._setpoint_history_count = max((0, int(value)))
self._setpoint_history = collections.deque(
self._setpoint_history, self._setpoint_history_count)
def _remove_history_item_by_value(self, remove_value):
"""
Remove an item from the history buffer by value
"""
new_history = [(value, ts) for value, ts in self._setpoint_history
if value != remove_value]
self._setpoint_history = collections.deque(
new_history, self._setpoint_history_count)
def _add_history_item(self, value, *, timestamp=None):
"""
Add an item to the history buffer
"""
if value in dict(self._setpoint_history):
# Push this value to the end of the list as most-recently used
self._remove_history_item_by_value(value)
self._setpoint_history.append(
(value, timestamp or datetime.datetime.now())
)
def send_value(self):
"""
Update channel value while recording setpoint history
"""
value = self.text().strip()
retval = super().send_value()
self._add_history_item(value)
return retval
def _create_history_menu(self):
if not self._setpoint_history:
return None
history_menu = QtWidgets.QMenu("&History")
font = QtGui.QFontDatabase.systemFont(QtGui.QFontDatabase.FixedFont)
history_menu.setFont(font)
max_len = max(len(value)
for value, timestamp in self._setpoint_history)
# Pad values such that timestamp lines up:
# (Value) @ (Timestamp)
action_format = '{value:<%d} @ {timestamp}' % (max_len + 1)
for value, timestamp in reversed(self._setpoint_history):
timestamp = timestamp.strftime('%m/%d %H:%M')
action = history_menu.addAction(
action_format.format(value=value, timestamp=timestamp))
def history_selected(*, value=value):
self.setText(str(value))
action.triggered.connect(history_selected)
return history_menu
def widget_ctx_menu(self):
menu = super().widget_ctx_menu()
if self._setpoint_history_count > 0:
self._history_menu = self._create_history_menu()
if self._history_menu is not None:
menu.addSeparator()
menu.addMenu(self._history_menu)
return menu
def unit_changed(self, new_unit):
"""
Callback invoked when the Channel has new unit value.
This callback also triggers an update_format_string call so the
new unit value is considered if ```showUnits``` is set.
Parameters
----------
new_unit : str
The new unit
"""
if self._unit == new_unit:
return
super().unit_changed(new_unit)
default = (self.displayFormat == DisplayFormat.Default)
if new_unit.lower() in EXPONENTIAL_UNITS and default:
self.displayFormat = DisplayFormat.Exponential
@use_for_variety_read('array-nd')
@use_for_variety_read('command-enum')
@use_for_variety_read('command-setpoint-tracks-readback')
@use_for_variety_read('enum')
@use_for_variety_read('scalar')
@use_for_variety_read('scalar-range')
@use_for_variety_read('scalar-tweakable')
@use_for_variety_read('text')
@use_for_variety_read('text-enum')
@use_for_variety_read('text-multiline')
@use_for_variety_write('array-nd')
class TyphosLabel(pydm.widgets.PyDMLabel):
"""
Reimplementation of PyDMLabel to set some custom defaults
Notes
-----
"""
def __init__(self, *args, display_format=None, **kwargs):
super().__init__(*args, **kwargs)
self.setAlignment(Qt.AlignCenter)
self.setSizePolicy(QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.Maximum)
self.showUnits = True
if display_format is not None:
self.displayFormat = display_format
def unit_changed(self, new_unit):
"""
Callback invoked when the Channel has new unit value.
This callback also triggers an update_format_string call so the
new unit value is considered if ```showUnits``` is set.
Parameters
----------
new_unit : str
The new unit
"""
if self._unit == new_unit:
return
super().unit_changed(new_unit)
default = (self.displayFormat == DisplayFormat.Default)
if new_unit.lower() in EXPONENTIAL_UNITS and default:
self.displayFormat = DisplayFormat.Exponential
class TyphosSidebarItem(ptypes.ParameterItem):
"""
Class to display a Device or Tool in the sidebar
Notes
-----
"""
def __init__(self, param, depth):
super().__init__(param, depth)
# Configure a QToolbar
self.toolbar = QToolBar()
self.toolbar.setToolButtonStyle(Qt.ToolButtonIconOnly)
self.toolbar.setIconSize(QSize(15, 15))
# Setup the action to open the widget
self.open_action = QAction(
qta.icon('fa.square', color='green'), 'Open', self.toolbar)
self.open_action.triggered.connect(self.open_requested)
# Setup the action to embed the widget
self.embed_action = QAction(
qta.icon('fa.th-large', color='yellow'), 'Embed', self.toolbar)
self.embed_action.triggered.connect(self.embed_requested)
# Setup the action to hide the widget
self.hide_action = QAction(
qta.icon('fa.times-circle', color='red'), 'Close', self.toolbar)
self.hide_action.triggered.connect(self.hide_requested)
self.hide_action.setEnabled(False)
# Add actions to toolbars
self.toolbar.addAction(self.open_action)
self.toolbar.addAction(self.hide_action)
if self.param.embeddable:
self.toolbar.insertAction(self.hide_action, self.embed_action)
def open_requested(self, triggered):
"""Request to open display for sidebar item"""
self.param.sigOpen.emit(self)
self._mark_shown()
def embed_requested(self, triggered):
"""Request to open embedded display for sidebar item"""
self.param.sigEmbed.emit(self)
self._mark_shown()
def hide_requested(self, triggered):
"""Request to hide display for sidebar item"""
self.param.sigHide.emit(self)
self._mark_hidden()
def _mark_shown(self):
self.open_action.setEnabled(False)
self.embed_action.setEnabled(False)
self.hide_action.setEnabled(True)
def _mark_hidden(self):
self.open_action.setEnabled(True)
self.embed_action.setEnabled(True)
self.hide_action.setEnabled(False)
def treeWidgetChanged(self):
"""Update the widget when add to a QTreeWidget"""
super().treeWidgetChanged()
tree = self.treeWidget()
if tree is None:
return
tree.setItemWidget(self, 1, self.toolbar)
class SubDisplay(QDockWidget):
"""QDockWidget modified to emit a signal when closed"""
closing = Signal()
def closeEvent(self, evt):
self.closing.emit()
super().closeEvent(evt)
class HappiChannel(pydm.widgets.channel.PyDMChannel, QObject):
"""
PyDMChannel to transport Device Information
Parameters
----------
tx_slot: callable
Slot on widget to accept a dictionary of both the device and metadata
information
"""
def __init__(self, *, tx_slot, **kwargs):
super().__init__(**kwargs)
QObject.__init__(self)
self._tx_slot = tx_slot
self._last_md = None
@Slot(dict)
def tx_slot(self, value):
"""Transmission Slot"""
# Do not fire twice for the same device
if not self._last_md or self._last_md != value['md']:
self._last_md = value['md']
self._tx_slot(value)
else:
logger.debug("HappiChannel %r received same device. "
"Ignoring for now ...", self)
class TyphosDesignerMixin(pydm.widgets.base.PyDMWidget):
"""
A mixin class used to display Typhos widgets in the Qt designer.
"""
# Unused properties that we don't want visible in designer
alarmSensitiveBorder = Property(bool, designable=False)
alarmSensitiveContent = Property(bool, designable=False)
precisionFromPV = Property(bool, designable=False)
precision = Property(int, designable=False)
showUnits = Property(bool, designable=False)
@Property(str)
def channel(self):
"""The channel address to use for this widget"""
if self._channel:
return str(self._channel)
return None
@channel.setter
def channel(self, value):
if self._channel != value:
# Remove old connection
if self._channels:
self._channels.clear()
for channel in self._channels:
if hasattr(channel, 'disconnect'):
channel.disconnect()
# Load new channel
self._channel = str(value)
channel = HappiChannel(address=self._channel,
tx_slot=self._tx)
self._channels = [channel]
# Connect the channel to the HappiPlugin
if hasattr(channel, 'connect'):
channel.connect()
@Slot(object)
def _tx(self, value):
"""Receive information from happi channel"""
self.add_device(value['obj'])
class SignalDialogButton(QPushButton):
"""QPushButton to launch a QDialog with a PyDMWidget"""
text = NotImplemented
icon = NotImplemented
parent_widget_class = QtWidgets.QWidget
def __init__(self, init_channel, text=None, icon=None, parent=None):
self.text = text or self.text
self.icon = icon or self.icon
super().__init__(qta.icon(self.icon), self.text, parent=parent)
self.clicked.connect(self.show_dialog)
self.dialog = None
self.channel = init_channel
self.setIconSize(QSize(15, 15))
def widget(self, channel):
"""Return a widget created with channel"""
raise NotImplementedError
def show_dialog(self):
"""Show the channel in a QDialog"""
# Dialog Creation
if not self.dialog:
logger.debug("Creating QDialog for %r", self.channel)
# Set up the QDialog
parent = utils.find_parent_with_class(
self, self.parent_widget_class)
self.dialog = QDialog(parent)
self.dialog.setWindowTitle(self.channel)
self.dialog.setLayout(QVBoxLayout())
self.dialog.layout().setContentsMargins(2, 2, 2, 2)
# Add the widget
widget = self.widget()
self.dialog.layout().addWidget(widget)
# Handle a lost dialog
else:
logger.debug("Redisplaying QDialog for %r", self.channel)
self.dialog.close()
# Show the dialog
logger.debug("Showing QDialog for %r", self.channel)
self.dialog.show()
@use_for_variety_read('array-image')
class ImageDialogButton(SignalDialogButton):
"""
QPushButton to show a 2-d array.
Notes
-----
"""
text = 'Show Image'
icon = 'fa.camera'
parent_widget_class = QtWidgets.QMainWindow
def widget(self):
"""Create PyDMImageView"""
return pydm.widgets.PyDMImageView(
parent=self, image_channel=self.channel)
@use_for_variety_read('array-timeseries')
@use_for_variety_read('array-histogram') # TODO: histogram settings?
class WaveformDialogButton(SignalDialogButton):
"""
QPushButton to show a 1-d array.
Notes
-----
"""
text = 'Show Waveform'
icon = 'fa5s.chart-line'
parent_widget_class = QtWidgets.QMainWindow
def widget(self):
"""Create PyDMWaveformPlot"""
return pydm.widgets.PyDMWaveformPlot(
init_y_channels=[self.channel], parent=self)
# @variety.uses_key_handlers
@use_for_variety_write('command')
@use_for_variety_write('command-proc')
@use_for_variety_write('command-setpoint-tracks-readback') # TODO
class TyphosCommandButton(pydm.widgets.PyDMPushButton):
"""
A pushbutton widget which executes a command by sending a specific value.
See Also
--------
:class:`TyphosCommandEnumButton`
Notes
-----
"""
default_label = 'Command'
def __init__(self, *args, variety_metadata=None, ophyd_signal=None,
**kwargs):
super().__init__(*args, **kwargs)
self.ophyd_signal = ophyd_signal
self.variety_metadata = variety_metadata
self._forced_enum_strings = None
variety_metadata = variety.create_variety_property()
def enum_strings_changed(self, new_enum_strings):
return super().enum_strings_changed(
self._forced_enum_strings or new_enum_strings)
def _update_variety_metadata(self, *, value, enum_strings=None,
enum_dict=None, tags=None, **kwargs):
self.pressValue = value
enum_strings = variety.get_enum_strings(enum_strings, enum_dict)
if enum_strings is not None:
self._forced_enum_strings = tuple(enum_strings)
self.enum_strings_changed(None) # force an update
tags = set(tags or {})
if 'protected' in tags:
self.passwordProtected = True
self.password = 'typhos' # ... yeah (TODO)
if 'confirm' in tags:
self.showConfirmDialog = True
variety._warn_unhandled_kwargs(self, kwargs)
if not self.text():
self.setText(self.default_label)
@variety.uses_key_handlers
@use_for_variety_write('command-enum')
class TyphosCommandEnumButton(pydm.widgets.enum_button.PyDMEnumButton):
"""
A group of buttons which represent several command options.
These options can come from directly from the control layer or can be
overridden with variety metadata.
See Also
--------
:class:`TyphosCommandButton`
Notes
-----
"""
def __init__(self, *args, variety_metadata=None, ophyd_signal=None,
**kwargs):
super().__init__(*args, **kwargs)
self.ophyd_signal = ophyd_signal
self.variety_metadata = variety_metadata
self._forced_enum_strings = None
variety_metadata = variety.create_variety_property()
def enum_strings_changed(self, new_enum_strings):
return super().enum_strings_changed(
self._forced_enum_strings or new_enum_strings)
def _update_variety_metadata(self, *, value, enum_strings=None,
enum_dict=None, tags=None, **kwargs):
enum_strings = variety.get_enum_strings(enum_strings, enum_dict)
if enum_strings is not None:
self._forced_enum_strings = tuple(enum_strings)
self.enum_strings_changed(None) # force an update
variety._warn_unhandled_kwargs(self, kwargs)
@use_for_variety_read('bitmask')
@variety.uses_key_handlers
class TyphosByteIndicator(pydm.widgets.PyDMByteIndicator):
"""
Displays an integer value as individual, read-only bit indicators.
Notes
-----
"""
def __init__(self, *args, variety_metadata=None, ophyd_signal=None,
**kwargs):
super().__init__(*args, **kwargs)
self.ophyd_signal = ophyd_signal
self.variety_metadata = variety_metadata
variety_metadata = variety.create_variety_property()
def _update_variety_metadata(self, *, bits, orientation, first_bit, style,
meaning=None, tags=None, **kwargs):
self.numBits = bits
self.orientation = {
'horizontal': Qt.Horizontal,
'vertical': Qt.Vertical,
}[orientation]
self.bigEndian = (first_bit == 'most-significant')
# TODO: labels do not display properly
# if meaning:
# self.labels = meaning[:bits]
# self.showLabels = True
variety._warn_unhandled_kwargs(self, kwargs)
@variety.key_handler('style')
def _variety_key_handler_style(self, *, shape, on_color, off_color,
**kwargs):
"""Variety hook for the sub-dictionary "style"."""
on_color = QtGui.QColor(on_color)
if on_color is not None:
self.onColor = on_color
off_color = QtGui.QColor(off_color)
if off_color is not None:
self.offColor = off_color
self.circles = (shape == 'circle')
variety._warn_unhandled_kwargs(self, kwargs)
@use_for_variety_read('command')
@use_for_variety_read('command-proc')
class TyphosCommandIndicator(pydm.widgets.PyDMByteIndicator):
"""Displays command status as a read-only bit indicator."""
def __init__(self, *args, ophyd_signal=None, **kwargs):
super().__init__(*args, **kwargs)
self.ophyd_signal = ophyd_signal
self.numBits = 1
self.showLabels = False
self.circles = True
class ClickableBitIndicator(pydm.widgets.byte.PyDMBitIndicator):
"""A bit indicator that emits `clicked` when clicked."""
clicked = Signal()
def mousePressEvent(self, event: QtGui.QMouseEvent):
super().mousePressEvent(event)
if event.button() == Qt.LeftButton:
self.clicked.emit()
@use_for_variety_write('bitmask')
class TyphosByteSetpoint(TyphosByteIndicator,
pydm.widgets.base.PyDMWritableWidget):
"""
Displays an integer value as individual, toggleable bit indicators.
Notes
-----
"""
def __init__(self, *args, variety_metadata=None, ophyd_signal=None,
**kwargs):
# NOTE: need to have these in the signature explicitly
super().__init__(*args, variety_metadata=variety_metadata,
ophyd_signal=ophyd_signal, **kwargs)
self._requests_pending = {}
def _get_setpoint_from_requests(self):
setpoint = self.value
for bit, request in self._requests_pending.items():
mask = 1 << bit
if request:
setpoint |= mask
else:
setpoint &= ~mask
return setpoint
def _bit_clicked(self, bit):
if bit in self._requests_pending:
old_value = self._requests_pending[bit]
else:
old_value = bool(self.value & (1 << bit))
self._requests_pending[bit] = not old_value
self.send_value_signal[int].emit(self._get_setpoint_from_requests())
def value_changed(self, value):
"""Receive and update the TyphosTextEdit for a new channel value."""
for bit, request in list(self._requests_pending.items()):
mask = 1 << bit
is_set = bool(value & mask)
if is_set == request:
self._requests_pending.pop(bit, None)
super().value_changed(value)
@Property(int, designable=True)
def numBits(self):
"""
Number of bits to interpret.
Re-implemented from PyDM to support changing of bit indicators.
"""
return self._num_bits
@numBits.setter
def numBits(self, num_bits):
if num_bits < 1:
return
self._num_bits = num_bits
for indicator in self._indicators:
indicator.deleteLater()
self._indicators = [
ClickableBitIndicator(parent=self, circle=self.circles)
for bit in range(self._num_bits)
]
for bit, indicator in enumerate(self._indicators):
def indicator_clicked(*, bit=bit):
self._bit_clicked(bit)
indicator.clicked.connect(indicator_clicked)
new_labels = [f"Bit {bit}"
for bit in range(len(self.labels), self._num_bits)]
self.labels = self.labels + new_labels
@variety.uses_key_handlers
@use_for_variety_write('scalar-range')
class TyphosScalarRange(pydm.widgets.PyDMSlider):
"""
A slider widget which displays a scalar value with an explicit range.
Notes
-----
"""
def __init__(self, *args, variety_metadata=None, ophyd_signal=None,
**kwargs):
super().__init__(*args, **kwargs)
self.ophyd_signal = ophyd_signal
self._delta_value = None
self._delta_signal = None
self._delta_signal_sub = None
self.variety_metadata = variety_metadata
variety_metadata = variety.create_variety_property()
def __dtor__(self):
"""PyQt5 destructor hook"""
# Ensure our delta signal subscription is cleared:
self.delta_signal = None
@variety.key_handler('range')
def _variety_key_handler_range(self, value, source, **kwargs):
"""Variety hook for the sub-dictionary "range"."""
if source == 'value':
if value is not None:
low, high = value
self.userMinimum = low
self.userMaximum = high
self.userDefinedLimits = True
# elif source == 'use_limits':
else:
variety._warn_unhandled(self, 'range.source', source)
variety._warn_unhandled_kwargs(self, kwargs)
@variety.key_handler('delta')
def _variety_key_handler_delta(self, source, value=None, signal=None,
**kwargs):
"""Variety hook for the sub-dictionary "delta"."""
if source == 'value':
if value is not None:
self.delta_value = value
elif source == 'signal':
if signal is not None:
self.delta_signal = variety.get_referenced_signal(self, signal)
else:
variety._warn_unhandled(self, 'delta.source', source)
# range_ = kwargs.pop('range') # unhandled
variety._warn_unhandled_kwargs(self, kwargs)
@variety.key_handler('display_format')
def _variety_key_handler_display_format(self, value):
"""Variety hook for the sub-dictionary "delta"."""
self.displayFormat = variety.get_display_format(value)
@property
def delta_signal(self):
"""Delta signal, used as the source for "delta_value"."""
return self._delta_signal
@delta_signal.setter
def delta_signal(self, signal):
if self._delta_signal is not None:
self._delta_signal.unsubscribe(self._delta_signal_sub)
if signal is None:
return
def update_delta(value, **kwargs):
self.delta_value = value
self._delta_signal_sub = signal.subscribe(update_delta)
self._delta_signal = signal
@Property(float, designable=True)
def delta_value(self):
"""
Delta value, an alternative to "num_points" provided by PyDMSlider.
num_points is calculated using the current min/max and the delta value,
if set.
"""
return self._delta_value
@delta_value.setter
def delta_value(self, value):
if value is None:
self._delta_value = None
return
if value <= 0.0:
return
self._delta_value = value
if self.minimum is not None and self.maximum is not None:
self._mute_internal_slider_changes = True
try:
self.num_steps = (self.maximum - self.minimum) / value
except Exception:
logger.exception('Failed to set number of steps with '
'min=%s, max=%s, delta=%s', self.minimum,
self.maximum, value)
finally:
self._mute_internal_slider_changes = False
def connection_changed(self, connected):
ret = super().connection_changed(connected)
if connected:
self.delta_value = self._delta_value
return ret
@variety.uses_key_handlers
@use_for_variety_write('array-tabular')
class TyphosArrayTable(pydm.widgets.PyDMWaveformTable):
"""
A table widget which reshapes and displays a given waveform value.
Notes
-----
"""
def __init__(self, *args, variety_metadata=None, ophyd_signal=None,
**kwargs):
super().__init__(*args, **kwargs)
self.ophyd_signal = ophyd_signal
self.variety_metadata = variety_metadata
variety_metadata = variety.create_variety_property()
def value_changed(self, value):
try:
len(value)
except TypeError:
logger.debug('Non-waveform value? %r', value)
return
# shape = self.variety_metadata.get('shape')
# if shape is not None:
# expected_length = np.multiply.reduce(shape)
# if len(value) == expected_length:
# value = np.array(value).reshape(shape)
return super().value_changed(value)
def _calculate_size(self, padding=5):
width = self.verticalHeader().width() + padding
for col in range(self.columnCount()):
width += self.columnWidth(col)
height = self.horizontalHeader().height() + padding
for row in range(self.rowCount()):
height += self.rowHeight(row)
return QSize(width, height)
def _update_variety_metadata(self, *, shape=None, tags=None, **kwargs):
if shape:
# TODO
columns = max(shape[0], 1)
rows = max(np.product(shape[1:]), 1)
self.setRowCount(rows)
self.setColumnCount(columns)
self.rowHeaderLabels = [f'{idx}' for idx in range(rows)]
self.columnHeaderLabels = [f'{idx}' for idx in range(columns)]
if rows <= 5 and columns <= 5:
full_size = self._calculate_size()
self.setFixedSize(full_size)
variety._warn_unhandled_kwargs(self, kwargs)
def _get_scalar_widget_class(desc, variety_md, read_only):
"""
From a given description, return the widget to use.
Parameters
----------
desc : dict
The object description.
variety_md : dict
The variety metadata. Currently unused.
read_only : bool
Set if used for the readback widget.
"""
# Check for enum_strs, if so create a QCombobox
if read_only:
return TyphosLabel
if 'enum_strs' in desc:
# Create a QCombobox if the widget has enum_strs
return TyphosComboBox
# Otherwise a LineEdit will suffice
return TyphosLineEdit
def _get_ndimensional_widget_class(dimensions, desc, variety_md, read_only):
"""
From a given description and dimensionality, return the widget to use.
Parameters
----------
dimensions : int
The number of dimensions (e.g., 0D or scalar, 1D array, ND array)
desc : dict
The object description.
variety_md : dict
The variety metadata. Currently unused.
read_only : bool
Set if used for the readback widget.
"""
if dimensions == 0:
return _get_scalar_widget_class(desc, variety_md, read_only)
return {
1: WaveformDialogButton,
2: ImageDialogButton
}.get(dimensions, TyphosLabel)
def widget_type_from_description(signal, desc, read_only=False):
"""
Determine which widget class should be used for the given signal
Parameters
----------
signal : ophyd.Signal
Signal object to determine widget class
desc : dict
Previously recorded description from the signal
read_only: bool, optional
Should the chosen widget class be read-only?
Returns
-------
widget_class : class
The class to use for the widget
kwargs : dict
Keyword arguments for the class
"""
if isinstance(signal, EpicsSignalBase):
# Still re-route EpicsSignal through the ca:// plugin
pv = (signal._read_pv
if read_only else signal._write_pv)
init_channel = utils.channel_name(pv.pvname)
else:
# Register signal with plugin
plugins.register_signal(signal)
init_channel = utils.channel_name(signal.name, protocol='sig')
variety_metadata = utils.get_variety_metadata(signal)
kwargs = {
'init_channel': init_channel,
}
if variety_metadata:
widget_cls = variety._get_widget_class_from_variety(
desc, variety_metadata, read_only)
else:
try:
dimensions = len(desc.get('shape', []))
except TypeError:
dimensions = 0
widget_cls = _get_ndimensional_widget_class(
dimensions, desc, variety_metadata, read_only)
if widget_cls is None:
return None, None
if desc.get('dtype') == 'string' and widget_cls in (TyphosLabel,
TyphosLineEdit):
kwargs['display_format'] = DisplayFormat.String
class_signature = inspect.signature(widget_cls)
if 'variety_metadata' in class_signature.parameters:
kwargs['variety_metadata'] = variety_metadata
if 'ophyd_signal' in class_signature.parameters:
kwargs['ophyd_signal'] = signal
return widget_cls, kwargs
def determine_widget_type(signal, read_only=False):
"""
Determine which widget class should be used for the given signal.
Parameters
----------
signal : ophyd.Signal
Signal object to determine widget class
read_only: bool, optional
Should the chosen widget class be read-only?
Returns
-------
widget_class : class
The class to use for the widget
kwargs : dict
Keyword arguments for the class
"""
try:
desc = signal.describe()[signal.name]
except Exception:
logger.error("Unable to connect to %r during widget creation",
signal.name)
desc = {}
return widget_type_from_description(signal, desc, read_only=read_only)
def create_signal_widget(signal, read_only=False, tooltip=None):
"""
Factory for creating a PyDMWidget from a signal
Parameters
----------
signal : ophyd.Signal
Signal object to create widget
read_only: bool, optional
Whether this widget should be able to write back to the signal you
provided
tooltip : str, optional
Tooltip to use for the widget
Returns
-------
widget : PyDMWidget
PyDMLabel, PyDMLineEdit, or PyDMEnumComboBox based on whether we should
be able to write back to the widget and if the signal has ``enum_strs``
"""
widget_cls, kwargs = determine_widget_type(signal, read_only=read_only)
if widget_cls is None:
return
logger.debug("Creating %s for %s", widget_cls, signal.name)
widget = widget_cls(**kwargs)
widget.setObjectName(f'{signal.name}_{widget_cls.__name__}')
if tooltip is not None:
widget.setToolTip(tooltip)
return widget
| 31.451448
| 79
| 0.631053
|
4a0b99db21c7acd63905dc5e9519ad2255d3a3c4
| 2,375
|
py
|
Python
|
aegnn/utils/bounding_box.py
|
uzh-rpg/aegnn
|
d96e13b2f80f3c7515a65baf966544e0914d068d
|
[
"MIT"
] | null | null | null |
aegnn/utils/bounding_box.py
|
uzh-rpg/aegnn
|
d96e13b2f80f3c7515a65baf966544e0914d068d
|
[
"MIT"
] | null | null | null |
aegnn/utils/bounding_box.py
|
uzh-rpg/aegnn
|
d96e13b2f80f3c7515a65baf966544e0914d068d
|
[
"MIT"
] | null | null | null |
import torch
import torchvision
from typing import Tuple, Union
def crop_to_frame(bbox: torch.Tensor, image_shape: Union[torch.Tensor, Tuple[int, int]]) -> torch.Tensor:
"""Checks if bounding boxes are inside the image frame of given shape. If not crop it to its border.
:param bbox: bounding box to check (x, y, width, height).
:param image_shape: image dimensions (width, height).
"""
array_width = torch.ones_like(bbox[..., 0], device=bbox.device) * (image_shape[0] - 1)
array_height = torch.ones_like(bbox[..., 1], device=bbox.device) * (image_shape[1] - 1)
wh = torch.stack([array_width, array_height], dim=-1)
xy_delta_min = torch.min(bbox[..., :2], torch.zeros_like(bbox[..., :2], device=bbox.device))
bbox[..., 0:2] = bbox[..., 0:2] - xy_delta_min
bbox[..., 2:4] = bbox[..., 2:4] + xy_delta_min
xy_delta_max = torch.min(wh - bbox[..., :2], torch.zeros_like(bbox[..., :2], device=bbox.device))
bbox[..., 0:2] = bbox[..., 0:2] + xy_delta_max
bbox[..., 2:4] = bbox[..., 2:4] - xy_delta_max
bbox[..., 2] = torch.min(bbox[..., 2], array_width - bbox[..., 0])
bbox[..., 3] = torch.min(bbox[..., 3], array_height - bbox[..., 1])
return bbox
def non_max_suppression(detected_bbox: torch.Tensor, iou: float = 0.6) -> torch.Tensor:
"""
Iterates over the bounding boxes to perform non maximum suppression within each batch.
:param detected_bbox: [batch_idx, top_left_corner_u, top_left_corner_v, width, height, predicted_class,
predicted class confidence, object_score])
:param iou: intersection over union, threshold for which the bbox are considered overlapping
"""
i_sample = 0
keep_bbox = []
while i_sample < detected_bbox.shape[0]:
same_batch_mask = detected_bbox[:, 0] == detected_bbox[i_sample, 0]
nms_input = detected_bbox[same_batch_mask][:, [1, 2, 3, 4, 7]].clone()
nms_input[:, [2, 3]] += nms_input[:, [0, 1]]
# (u, v) or (x, y) should not matter
keep_idx = torchvision.ops.nms(nms_input[:, :4], nms_input[:, 4], iou)
keep_bbox.append(detected_bbox[same_batch_mask][keep_idx])
i_sample += same_batch_mask.sum()
if len(keep_bbox) != 0:
filtered_bbox = torch.cat(keep_bbox, dim=0)
else:
filtered_bbox = torch.zeros([0, 8])
return filtered_bbox
| 43.981481
| 108
| 0.632842
|
4a0b9c470e707f8cd4edfaa87a9d679286c7977a
| 405
|
py
|
Python
|
tools/stntools/stnmisc.py
|
HEATlab/durability
|
85e53f497dfa609f76b5cbf7f5c9ee19deeb2755
|
[
"MIT"
] | null | null | null |
tools/stntools/stnmisc.py
|
HEATlab/durability
|
85e53f497dfa609f76b5cbf7f5c9ee19deeb2755
|
[
"MIT"
] | null | null | null |
tools/stntools/stnmisc.py
|
HEATlab/durability
|
85e53f497dfa609f76b5cbf7f5c9ee19deeb2755
|
[
"MIT"
] | null | null | null |
#!/usr/bin/env python
## \fn replaceReceivedTimepoints(STN_1,STN_2)
# \brief modifies the zero timepoint bounds of the received timepoints
# of STN_2 so that they are the same as STN_1
def replaceReceivedTimepoints(STN_1, STN_2):
for timepoint in STN_1.receivedTimepoints:
STN_2.verts[timepoint] = STN_1.verts[timepoint]
STN_2.edges[(0,timepoint)] = STN_1.edges[(0,timepoint)]
return STN_2
| 40.5
| 71
| 0.760494
|
4a0b9caabca07a0bdd98cfa7bdf2a16600d1d550
| 1,109
|
py
|
Python
|
src/genie/libs/parser/iosxr/tests/ShowMsdpSummary/cli/equal/golden_output_1_expected.py
|
balmasea/genieparser
|
d1e71a96dfb081e0a8591707b9d4872decd5d9d3
|
[
"Apache-2.0"
] | 204
|
2018-06-27T00:55:27.000Z
|
2022-03-06T21:12:18.000Z
|
src/genie/libs/parser/iosxr/tests/ShowMsdpSummary/cli/equal/golden_output_1_expected.py
|
balmasea/genieparser
|
d1e71a96dfb081e0a8591707b9d4872decd5d9d3
|
[
"Apache-2.0"
] | 468
|
2018-06-19T00:33:18.000Z
|
2022-03-31T23:23:35.000Z
|
src/genie/libs/parser/iosxr/tests/ShowMsdpSummary/cli/equal/golden_output_1_expected.py
|
balmasea/genieparser
|
d1e71a96dfb081e0a8591707b9d4872decd5d9d3
|
[
"Apache-2.0"
] | 309
|
2019-01-16T20:21:07.000Z
|
2022-03-30T12:56:41.000Z
|
expected_output = {
'vrf': {
'VRF1': {
'current_external_active_sa': 0,
'maximum_external_sa_global': 20000,
'peer_address': {
'10.4.1.1': {
'active_sa_cnt': 0,
'as': 0,
'cfg_max_ext_sas': 0,
'name': 'R1',
'reset_count': 0,
'state': 'Listen',
'tlv': {
'receive': 0,
'sent': 0,
},
'uptime_downtime': '18:25:02',
},
'10.229.11.11': {
'active_sa_cnt': 0,
'as': 0,
'cfg_max_ext_sas': 0,
'name': '?',
'reset_count': 0,
'state': 'Listen',
'tlv': {
'receive': 0,
'sent': 0,
},
'uptime_downtime': '18:14:53',
},
},
},
},
}
| 28.435897
| 50
| 0.272317
|
4a0b9cc133aa65d7c937e6137c4061addf838b25
| 7,903
|
py
|
Python
|
tests/test_sample_database.py
|
dm03514/piicatcher
|
c9c30d2dbda4d8c3d0e0d48e66dc282a22503b54
|
[
"Apache-2.0"
] | null | null | null |
tests/test_sample_database.py
|
dm03514/piicatcher
|
c9c30d2dbda4d8c3d0e0d48e66dc282a22503b54
|
[
"Apache-2.0"
] | 1
|
2020-12-18T05:01:38.000Z
|
2020-12-18T05:01:38.000Z
|
tests/test_sample_database.py
|
grofers/piicatcher
|
181d008ba0aea4d7101fa83ddc075e9106164106
|
[
"Apache-2.0"
] | null | null | null |
import csv
from abc import ABC, abstractmethod
from argparse import Namespace
from unittest import TestCase
import psycopg2
import pymysql
import pytest
from piicatcher.explorer.databases import MySQLExplorer, PostgreSQLExplorer
def load_sample_data(connection):
create_table = """
CREATE TABLE SAMPLE(
id VARCHAR(255), gender VARCHAR(255), birthdate DATE, maiden_name VARCHAR(255), lname VARCHAR(255),
fname VARCHAR(255), address VARCHAR(255), city VARCHAR(255), state VARCHAR(255), zip VARCHAR(255),
phone VARCHAR(255), email VARCHAR(255), cc_type VARCHAR(255), cc_number VARCHAR(255), cc_cvc VARCHAR(255),
cc_expiredate DATE
)
"""
sql = """
INSERT INTO SAMPLE VALUES(%s,%s,%s,%s,%s,%s,%s,%s,
%s,%s,%s,%s,%s,%s,%s,%s)
"""
# Get Data
with open("tests/samples/sample-data.csv") as csv_file:
reader = csv.reader(csv_file)
with connection.cursor() as cursor:
cursor.execute(create_table)
header = True
for row in reader:
if not header:
cursor.execute(sql, row)
header = False
connection.commit()
def drop_sample_data(connection):
drop_table = "DROP TABLE SAMPLE"
with connection.cursor() as cursor:
cursor.execute(drop_table)
connection.commit()
# pylint: disable=too-few-public-methods
class CommonSampleDataTestCases:
class CommonSampleDataTests(ABC, TestCase):
@property
def shallow_scan_result(self):
raise NotImplementedError
@property
def deep_scan_result(self):
raise NotImplementedError
@classmethod
@abstractmethod
def get_connection(cls):
raise NotImplementedError
@classmethod
def setUpClass(cls):
connection = cls.get_connection()
load_sample_data(connection)
connection.close()
@classmethod
def tearDownClass(cls):
connection = cls.get_connection()
drop_sample_data(connection)
connection.close()
@property
@abstractmethod
def explorer(self):
raise NotImplementedError
@pytest.mark.skip(reason="Results are not deterministic")
def test_deep_scan(self):
explorer = self.explorer
try:
explorer.scan()
finally:
explorer.close_connection()
self.assertListEqual(explorer.get_tabular(True), self.deep_scan_result)
def test_shallow_scan(self):
explorer = self.explorer
try:
explorer.shallow_scan()
finally:
explorer.close_connection()
self.assertListEqual(explorer.get_tabular(True), self.shallow_scan_result)
class VanillaMySqlExplorerTest(CommonSampleDataTestCases.CommonSampleDataTests):
@property
def deep_scan_result(self):
return [
["piidb", "SAMPLE", "address", True],
["piidb", "SAMPLE", "cc_cvc", False],
["piidb", "SAMPLE", "cc_number", True],
["piidb", "SAMPLE", "cc_type", False],
["piidb", "SAMPLE", "city", True],
["piidb", "SAMPLE", "email", True],
["piidb", "SAMPLE", "fname", True],
["piidb", "SAMPLE", "gender", True],
["piidb", "SAMPLE", "id", True],
["piidb", "SAMPLE", "lname", True],
["piidb", "SAMPLE", "maiden_name", True],
["piidb", "SAMPLE", "phone", True],
["piidb", "SAMPLE", "state", True],
["piidb", "SAMPLE", "zip", True],
]
@property
def shallow_scan_result(self):
return [
["piidb", "SAMPLE", "address", True],
["piidb", "SAMPLE", "cc_cvc", False],
["piidb", "SAMPLE", "cc_number", False],
["piidb", "SAMPLE", "cc_type", False],
["piidb", "SAMPLE", "city", True],
["piidb", "SAMPLE", "email", True],
["piidb", "SAMPLE", "fname", True],
["piidb", "SAMPLE", "gender", True],
["piidb", "SAMPLE", "id", False],
["piidb", "SAMPLE", "lname", True],
["piidb", "SAMPLE", "maiden_name", True],
["piidb", "SAMPLE", "phone", False],
["piidb", "SAMPLE", "state", True],
["piidb", "SAMPLE", "zip", False],
]
@property
def namespace(self):
return Namespace(
host="127.0.0.1",
user="piiuser",
password="p11secret",
database="piidb",
include_schema=(),
exclude_schema=(),
include_table=(),
exclude_table=(),
catalog=None,
)
@classmethod
def get_connection(cls):
return pymysql.connect(
host="127.0.0.1", user="piiuser", password="p11secret", database="piidb"
)
@property
def explorer(self):
return MySQLExplorer(self.namespace)
class SmallSampleMysqlExplorer(MySQLExplorer):
@property
def small_table_max(self):
return 5
class SmallSampleMySqlExplorerTest(VanillaMySqlExplorerTest):
@property
def explorer(self):
return SmallSampleMysqlExplorer(self.namespace)
class VanillaPGExplorerTest(CommonSampleDataTestCases.CommonSampleDataTests):
@property
def deep_scan_result(self):
return [
["public", "sample", "address", True],
["public", "sample", "cc_cvc", False],
["public", "sample", "cc_number", True],
["public", "sample", "cc_type", False],
["public", "sample", "city", True],
["public", "sample", "email", True],
["public", "sample", "fname", True],
["public", "sample", "gender", True],
["public", "sample", "id", True],
["public", "sample", "lname", True],
["public", "sample", "maiden_name", True],
["public", "sample", "phone", True],
["public", "sample", "state", True],
["public", "sample", "zip", True],
]
@property
def shallow_scan_result(self):
return [
["public", "sample", "address", True],
["public", "sample", "cc_cvc", False],
["public", "sample", "cc_number", False],
["public", "sample", "cc_type", False],
["public", "sample", "city", True],
["public", "sample", "email", True],
["public", "sample", "fname", True],
["public", "sample", "gender", True],
["public", "sample", "id", False],
["public", "sample", "lname", True],
["public", "sample", "maiden_name", True],
["public", "sample", "phone", False],
["public", "sample", "state", True],
["public", "sample", "zip", False],
]
@property
def namespace(self):
return Namespace(
host="127.0.0.1",
user="piiuser",
password="p11secret",
database="piidb",
include_schema=(),
exclude_schema=(),
include_table=(),
exclude_table=(),
catalog=None,
)
@classmethod
def get_connection(cls):
return psycopg2.connect(
host="127.0.0.1", user="piiuser", password="p11secret", database="piidb"
)
@property
def explorer(self):
return PostgreSQLExplorer(self.namespace)
class SmallSamplePGExplorer(PostgreSQLExplorer):
@property
def small_table_max(self):
return 5
class SmallSamplePGExplorerTest(VanillaPGExplorerTest):
@property
def explorer(self):
return SmallSamplePGExplorer(self.namespace)
| 31.612
| 118
| 0.544224
|
4a0b9d374caa6e5304eb3661910731013974081d
| 832
|
py
|
Python
|
src/basic/010_buildins/use_htmlparser1.py
|
hbulpf/pydemo
|
2989cc50781230718e46dcac5dc0ca70630ebffe
|
[
"Apache-2.0"
] | 6
|
2020-03-24T15:58:42.000Z
|
2020-04-18T13:32:41.000Z
|
src/basic/010_buildins/use_htmlparser1.py
|
hbulpf/pydemo
|
2989cc50781230718e46dcac5dc0ca70630ebffe
|
[
"Apache-2.0"
] | 1
|
2022-01-13T03:51:17.000Z
|
2022-01-13T03:51:17.000Z
|
src/basic/010_buildins/use_htmlparser1.py
|
hbulpf/pydemo
|
2989cc50781230718e46dcac5dc0ca70630ebffe
|
[
"Apache-2.0"
] | 1
|
2020-02-01T09:36:05.000Z
|
2020-02-01T09:36:05.000Z
|
from html.parser import HTMLParser
from html.entities import name2codepoint
class MyHTMLParser(HTMLParser):
def handle_starttag(self, tag, attrs):
print('starttag: <%s>' % tag)
def handle_endtag(self, tag):
print('endtag:</%s>' % tag)
# def handle_startendtag(self, tag, attrs):
# print('<%s/>' % tag)
def handle_data(self, data):
print('data:%s' % data)
# def handle_comment(self, data):
# print('<!--', data, '-->')
# def handle_entityref(self, name):
# print('entityref:&%s;' % name)
# def handle_charref(self, name):
# print('charref:&#%s;' % name)
parser = MyHTMLParser()
parser.feed('''<html>
<head></head>
<body>
<!-- test html parser -->
<p>Some <a href=\"#\">html</a> HTML tutorial...Ӓ<br>END</p>
</body></html>''')
| 25.212121
| 74
| 0.582933
|
4a0b9e616046210791c2258d23a8776590431bcc
| 1,536
|
py
|
Python
|
PostFeedbackHttpTrigger/tests/test_sanitise_input.py
|
office-for-students/feedback-api
|
6f58d7c8de135dc71e5500fcaab71660ca6d7632
|
[
"MIT"
] | null | null | null |
PostFeedbackHttpTrigger/tests/test_sanitise_input.py
|
office-for-students/feedback-api
|
6f58d7c8de135dc71e5500fcaab71660ca6d7632
|
[
"MIT"
] | null | null | null |
PostFeedbackHttpTrigger/tests/test_sanitise_input.py
|
office-for-students/feedback-api
|
6f58d7c8de135dc71e5500fcaab71660ca6d7632
|
[
"MIT"
] | 1
|
2019-09-29T07:04:44.000Z
|
2019-09-29T07:04:44.000Z
|
import unittest
from SharedCode.utils import sanitise_url_string, sanitise_question_string
class TestSanitiseUrlString(unittest.TestCase):
def test_with_permitted_url(self):
input_url = (
"https://prod-discover-uni.azurewebsites.net/course-finder/"
"results/?subject_query=%22Artificial+intelligence%22&institution_query"
"=&mode_query=Part-time&countries_query=England"
)
sanitised_url = sanitise_url_string(input_url)
self.assertEqual(input_url, sanitised_url)
def test_with_some_chars_not_permitted(self):
bad_str = "<script>;"
expected_sanitised_str = "script"
sanitised_str = sanitise_url_string(bad_str)
self.assertEqual(expected_sanitised_str, sanitised_str)
class TestSanitiseQuestionString(unittest.TestCase):
def test_with_valid_input_str_1(self):
valid_str = "I like discoveruni. It's really useful! :?& fred@acme.com"
sanitised_str = sanitise_question_string(valid_str)
self.assertEqual(valid_str, sanitised_str)
def test_with_valid_input_str_2(self):
valid_str = "how_was_this_useful"
sanitised_str = sanitise_question_string(valid_str)
self.assertEqual(valid_str, sanitised_str)
def test_with_some_chars_not_permitted(self):
bad_str = "<script>;#%="
expected_sanitised_str = "script"
sanitised_str = sanitise_question_string(bad_str)
self.assertEqual(expected_sanitised_str, sanitised_str)
# TODO add more tests
| 36.571429
| 84
| 0.725911
|
4a0b9ee96d9cd6133443bb700b398728debdfbae
| 930
|
py
|
Python
|
leetcode/704/main.py
|
shankar-shiv/CS1010E_Kattis_practice
|
9a8597b7ab61d5afa108a8b943ca2bb3603180c6
|
[
"MIT"
] | null | null | null |
leetcode/704/main.py
|
shankar-shiv/CS1010E_Kattis_practice
|
9a8597b7ab61d5afa108a8b943ca2bb3603180c6
|
[
"MIT"
] | null | null | null |
leetcode/704/main.py
|
shankar-shiv/CS1010E_Kattis_practice
|
9a8597b7ab61d5afa108a8b943ca2bb3603180c6
|
[
"MIT"
] | null | null | null |
# You must write an algorithm with O(log n) runtime complexity.
# mid = L + (R-L) // 2
class Solution:
def search(self, nums: list[int], target: int) -> int:
if nums == []:
return -1
mid = len(nums) // 2 # or mid = lo + (high - lo) // 2
if target == nums[mid]:
return mid
elif target < nums[mid]:
return self.search(nums[:mid], target)
else:
return self.search(nums[mid+1:], target)
def binary_search_2(key, seq):
def helper(low, high):
if low > high:
return False
mid = (low + high) // 2
if key == seq[mid]:
return True
elif key < seq[mid]:
return helper(low, mid-1)
else:
return helper(mid+1, high)
return helper(0, len(seq) - 1)
seq = [-1, 0, 3]
key = 3
# s = Solution()
# print(s.search(seq, key))
print(classic_search(seq, key))
| 24.473684
| 63
| 0.512903
|
4a0b9f43885597fed018651c82384a78c8ce6f22
| 17,614
|
py
|
Python
|
game_agent.py
|
nbclsc/AIND-Isolation-master
|
11b20f5e52fa45f420d3f30b511578e17abedf09
|
[
"MIT"
] | null | null | null |
game_agent.py
|
nbclsc/AIND-Isolation-master
|
11b20f5e52fa45f420d3f30b511578e17abedf09
|
[
"MIT"
] | null | null | null |
game_agent.py
|
nbclsc/AIND-Isolation-master
|
11b20f5e52fa45f420d3f30b511578e17abedf09
|
[
"MIT"
] | null | null | null |
"""Finish all TODO items in this file to complete the isolation project, then
test your agent's strength against a set of known agents using tournament.py
and include the results in your report.
"""
import random
class SearchTimeout(Exception):
"""Subclass base exception for code clarity. """
pass
def custom_score(game, player):
"""Calculate the heuristic value of a game state from the point of view
of the given player.
This should be the best heuristic function for your project submission.
Note: this function should be called from within a Player instance as
`self.score()` -- you should not need to call this function directly.
Parameters
----------
game : `isolation.Board`
An instance of `isolation.Board` encoding the current state of the
game (e.g., player locations and blocked cells).
player : object
A player instance in the current game (i.e., an object corresponding to
one of the player objects `game.__player_1__` or `game.__player_2__`.)
Returns
-------
float
The heuristic value of the current game state to the specified player.
"""
# TODO: finish this function!
# raise NotImplementedError
if game.is_loser(player):
return float("-inf")
if game.is_winner(player):
return float("inf")
# distance to center
# w, h = game.width / 2., game.height / 2.
# y, x = game.get_player_location(player)
# return float(abs(x - w) + abs(y - h))
# manhattan distance from player to opponent
y_me, x_me = game.get_player_location(player)
y_op, x_op = game.get_player_location(game.get_opponent(player))
return float(abs(x_me - x_op) + abs(y_me - y_op))
def custom_score_2(game, player):
"""Calculate the heuristic value of a game state from the point of view
of the given player.
Note: this function should be called from within a Player instance as
`self.score()` -- you should not need to call this function directly.
Parameters
----------
game : `isolation.Board`
An instance of `isolation.Board` encoding the current state of the
game (e.g., player locations and blocked cells).
player : object
A player instance in the current game (i.e., an object corresponding to
one of the player objects `game.__player_1__` or `game.__player_2__`.)
Returns
-------
float
The heuristic value of the current game state to the specified player.
"""
# TODO: finish this function!
# raise NotImplementedError
if game.is_loser(player):
return float("-inf")
if game.is_winner(player):
return float("inf")
# difference between my number of legal moves and opponent legal moves
me_moves = len(game.get_legal_moves(player))
op_moves = len(game.get_legal_moves(game.get_opponent(player)))
return float(me_moves - op_moves)
def custom_score_3(game, player):
"""Calculate the heuristic value of a game state from the point of view
of the given player.
Note: this function should be called from within a Player instance as
`self.score()` -- you should not need to call this function directly.
Parameters
----------
game : `isolation.Board`
An instance of `isolation.Board` encoding the current state of the
game (e.g., player locations and blocked cells).
player : object
A player instance in the current game (i.e., an object corresponding to
one of the player objects `game.__player_1__` or `game.__player_2__`.)
Returns
-------
float
The heuristic value of the current game state to the specified player.
"""
# TODO: finish this function!
# raise NotImplementedError
if game.is_loser(player):
return float("-inf")
if game.is_winner(player):
return float("inf")
# manhattan dist of player to corners
# y, x = game.get_player_location(player)
# h_corner = game.height - 1
# w_corner = game.width - 1
# top_left = float(abs(x - 0) + abs(y - 0))
# bot_left = float(abs(x - h_corner) + abs(y - 0))
# top_right = float(abs(x - 0) + abs(y - w_corner))
# bot_right = float(abs(x - h_corner) + abs(y - w_corner))
# # sum of players distance to all corners
# return top_left + bot_left + top_right + bot_right
# This heuristic worked well against Mini/Max opponents but poorly against
# alpha/beta opponents.
#
# w, h = game.width / 2., game.height / 2.
# y, x = game.get_player_location(player)
# own_moves = len(game.get_legal_moves(player))
# opp_moves = len(game.get_legal_moves(game.get_opponent(player)))
# return float(((h - y)**2 + (w - x)**2)*.8 + (own_moves - opp_moves)*.2)
# distance to center for player and opponent
w, h = game.width / 2., game.height / 2.
y_me, x_me = game.get_player_location(player)
y_op, x_op = game.get_player_location(game.get_opponent(player))
mdist_me = float(abs(x_me - w) + abs(y_me - h))
mdist_op = float(abs(x_op - w) + abs(y_op - h))
# return distance of player from center minus distance of opponent from center
return float(mdist_me - mdist_op) # + float(abs(x_me - x_op) + abs(y_me - y_op))
class IsolationPlayer:
"""Base class for minimax and alphabeta agents -- this class is never
constructed or tested directly.
******************** DO NOT MODIFY THIS CLASS ********************
Parameters
----------
search_depth : int (optional)
A strictly positive integer (i.e., 1, 2, 3,...) for the number of
layers in the game tree to explore for fixed-depth search. (i.e., a
depth of one (1) would only explore the immediate sucessors of the
current state.)
score_fn : callable (optional)
A function to use for heuristic evaluation of game states.
timeout : float (optional)
Time remaining (in milliseconds) when search is aborted. Should be a
positive value large enough to allow the function to return before the
timer expires.
"""
def __init__(self, search_depth=3, score_fn=custom_score, timeout=10.):
self.search_depth = search_depth
self.score = score_fn
self.time_left = None
self.TIMER_THRESHOLD = timeout
class MinimaxPlayer(IsolationPlayer):
"""Game-playing agent that chooses a move using depth-limited minimax
search. You must finish and test this player to make sure it properly uses
minimax to return a good move before the search time limit expires.
"""
def get_move(self, game, time_left):
"""Search for the best move from the available legal moves and return a
result before the time limit expires.
************** YOU DO NOT NEED TO MODIFY THIS FUNCTION *************
For fixed-depth search, this function simply wraps the call to the
minimax method, but this method provides a common interface for all
Isolation agents, and you will replace it in the AlphaBetaPlayer with
iterative deepening search.
Parameters
----------
game : `isolation.Board`
An instance of `isolation.Board` encoding the current state of the
game (e.g., player locations and blocked cells).
time_left : callable
A function that returns the number of milliseconds left in the
current turn. Returning with any less than 0 ms remaining forfeits
the game.
Returns
-------
(int, int)
Board coordinates corresponding to a legal move; may return
(-1, -1) if there are no available legal moves.
"""
self.time_left = time_left
# Initialize the best move so that this function returns something
# in case the search fails due to timeout
best_move = (-1, -1)
try:
# The try/except block will automatically catch the exception
# raised when the timer is about to expire.
return self.minimax(game, self.search_depth)
except SearchTimeout:
pass # Handle any actions required after timeout as needed
# Return the best move from the last completed search iteration
return best_move
def minimax(self, game, depth):
"""Implement depth-limited minimax search algorithm as described in
the lectures.
This should be a modified version of MINIMAX-DECISION in the AIMA text.
https://github.com/aimacode/aima-pseudocode/blob/master/md/Minimax-Decision.md
**********************************************************************
You MAY add additional methods to this class, or define helper
functions to implement the required functionality.
**********************************************************************
Parameters
----------
game : isolation.Board
An instance of the Isolation game `Board` class representing the
current game state
depth : int
Depth is an integer representing the maximum number of plies to
search in the game tree before aborting
Returns
-------
(int, int)
The board coordinates of the best move found in the current search;
(-1, -1) if there are no legal moves
Notes
-----
(1) You MUST use the `self.score()` method for board evaluation
to pass the project tests; you cannot call any other evaluation
function directly.
(2) If you use any helper functions (e.g., as shown in the AIMA
pseudocode) then you must copy the timer check into the top of
each helper function or else your agent will timeout during
testing.
"""
if self.time_left() < self.TIMER_THRESHOLD:
raise SearchTimeout()
# TODO: finish this function!
# raise NotImplementedError
if self.time_left() < self.TIMER_THRESHOLD:
raise SearchTimeout()
legal_moves = game.get_legal_moves()
if not legal_moves:
return (-1, -1)
best_move = legal_moves[0]
best_score = float('-inf')
for move in legal_moves:
score = self.min_score(game, move, depth-1)
if score > best_score:
best_move = move
best_score = score
return best_move
def min_score(self, game, node, depth):
if self.time_left() < self.TIMER_THRESHOLD:
raise SearchTimeout()
if depth == 0:
return self.score(game.forecast_move(node), self)
clone = game.forecast_move(node)
legal_moves = clone.get_legal_moves()
if not legal_moves:
return game.is_winner(game)
best_score = float('inf')
for move in legal_moves:
score = self.max_score(clone, move, depth-1)
if score < best_score:
best_score = score
return best_score
def max_score(self, game, node, depth):
if self.time_left() < self.TIMER_THRESHOLD:
raise SearchTimeout()
if depth == 0:
return self.score(game.forecast_move(node), self)
clone = game.forecast_move(node)
legal_moves = clone.get_legal_moves()
if not legal_moves:
return game.is_loser(game)
best_score = float('-inf')
for move in legal_moves:
score = self.min_score(clone, move, depth-1)
if score > best_score:
best_score = score
return best_score
class AlphaBetaPlayer(IsolationPlayer):
"""Game-playing agent that chooses a move using iterative deepening minimax
search with alpha-beta pruning. You must finish and test this player to
make sure it returns a good move before the search time limit expires.
"""
def get_move(self, game, time_left):
"""Search for the best move from the available legal moves and return a
result before the time limit expires.
Modify the get_move() method from the MinimaxPlayer class to implement
iterative deepening search instead of fixed-depth search.
**********************************************************************
NOTE: If time_left() < 0 when this function returns, the agent will
forfeit the game due to timeout. You must return _before_ the
timer reaches 0.
**********************************************************************
Parameters
----------
game : `isolation.Board`
An instance of `isolation.Board` encoding the current state of the
game (e.g., player locations and blocked cells).
time_left : callable
A function that returns the number of milliseconds left in the
current turn. Returning with any less than 0 ms remaining forfeits
the game.
Returns
-------
(int, int)
Board coordinates corresponding to a legal move; may return
(-1, -1) if there are no available legal moves.
"""
self.time_left = time_left
# TODO: finish this function!
# raise NotImplementedError
best_move = (-1, -1)
try:
# The try/except block will automatically catch the exception
# raised when the timer is about to expire.
depth = 1
while True:
best_move = self.alphabeta(game, depth)
depth += 1
return best_move
except SearchTimeout:
pass # Handle any actions required after timeout as needed
# Return the best move from the last completed search iteration
return best_move
def alphabeta(self, game, depth, alpha=float("-inf"), beta=float("inf")):
"""Implement depth-limited minimax search with alpha-beta pruning as
described in the lectures.
This should be a modified version of ALPHA-BETA-SEARCH in the AIMA text
https://github.com/aimacode/aima-pseudocode/blob/master/md/Alpha-Beta-Search.md
**********************************************************************
You MAY add additional methods to this class, or define helper
functions to implement the required functionality.
**********************************************************************
Parameters
----------
game : isolation.Board
An instance of the Isolation game `Board` class representing the
current game state
depth : int
Depth is an integer representing the maximum number of plies to
search in the game tree before aborting
alpha : float
Alpha limits the lower bound of search on minimizing layers
beta : float
Beta limits the upper bound of search on maximizing layers
Returns
-------
(int, int)
The board coordinates of the best move found in the current search;
(-1, -1) if there are no legal moves
Notes
-----
(1) You MUST use the `self.score()` method for board evaluation
to pass the project tests; you cannot call any other evaluation
function directly.
(2) If you use any helper functions (e.g., as shown in the AIMA
pseudocode) then you must copy the timer check into the top of
each helper function or else your agent will timeout during
testing.
"""
if self.time_left() < self.TIMER_THRESHOLD:
raise SearchTimeout()
# TODO: finish this function!
# raise NotImplementedError
legal_moves = game.get_legal_moves()
if not legal_moves:
return (-1, -1)
best_move = self.max_score(game, depth, alpha, beta)
return best_move[1]
def max_score(self, game, depth, alpha, beta):
if self.time_left() < self.TIMER_THRESHOLD:
raise SearchTimeout()
if depth == 0:
return tuple([self.score(game, self), game.get_player_location(self)])
legal_moves = game.get_legal_moves()
if not legal_moves:
return tuple([self.score(game, self), None])
v = tuple([float('-inf'), None])
for move in legal_moves:
clone = game.forecast_move(move)
maxy = tuple([self.min_score(clone, depth-1, alpha, beta)[0], move])
if v[0] < maxy[0]:
v = maxy
if beta <= v[0]:
return v
alpha = max(alpha, v[0])
return v
def min_score(self, game, depth, alpha, beta):
if self.time_left() < self.TIMER_THRESHOLD:
raise SearchTimeout()
if depth == 0:
return tuple([self.score(game, self), game.get_player_location(self)])
legal_moves = game.get_legal_moves()
if not legal_moves:
return tuple([self.score(game, self), None])
v = tuple([float('inf'), None])
for move in legal_moves:
clone = game.forecast_move(move)
miny = tuple([self.max_score(clone, depth-1, alpha, beta)[0], move])
if miny[0] < v[0]:
v = miny
if v[0] <= alpha:
return v
beta = min(beta, v[0])
return v
| 36.849372
| 87
| 0.602021
|
4a0b9f9675fb114608861f3200ce890d4ef6eec9
| 3,471
|
py
|
Python
|
tests/components/epson/test_config_flow.py
|
tbarbette/core
|
8e58c3aa7bc8d2c2b09b6bd329daa1c092d52d3c
|
[
"Apache-2.0"
] | 6
|
2017-08-02T19:26:39.000Z
|
2020-03-14T22:47:41.000Z
|
tests/components/epson/test_config_flow.py
|
tbarbette/core
|
8e58c3aa7bc8d2c2b09b6bd329daa1c092d52d3c
|
[
"Apache-2.0"
] | 60
|
2020-07-06T15:10:30.000Z
|
2022-03-31T06:01:46.000Z
|
tests/components/epson/test_config_flow.py
|
tbarbette/core
|
8e58c3aa7bc8d2c2b09b6bd329daa1c092d52d3c
|
[
"Apache-2.0"
] | 14
|
2018-08-19T16:28:26.000Z
|
2021-09-02T18:26:53.000Z
|
"""Test the epson config flow."""
from unittest.mock import patch
from homeassistant import config_entries, setup
from homeassistant.components.epson.const import DOMAIN
from homeassistant.const import CONF_HOST, CONF_NAME, CONF_PORT, STATE_UNAVAILABLE
async def test_form(hass):
"""Test we get the form."""
await setup.async_setup_component(hass, "persistent_notification", {})
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] == "form"
assert result["errors"] == {}
assert result["step_id"] == config_entries.SOURCE_USER
with patch(
"homeassistant.components.epson.Projector.get_property",
return_value="04",
), patch(
"homeassistant.components.epson.async_setup", return_value=True
) as mock_setup, patch(
"homeassistant.components.epson.async_setup_entry",
return_value=True,
) as mock_setup_entry:
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_HOST: "1.1.1.1", CONF_NAME: "test-epson", CONF_PORT: 80},
)
assert result2["type"] == "create_entry"
assert result2["title"] == "test-epson"
assert result2["data"] == {CONF_HOST: "1.1.1.1", CONF_PORT: 80}
await hass.async_block_till_done()
assert len(mock_setup.mock_calls) == 1
assert len(mock_setup_entry.mock_calls) == 1
async def test_form_cannot_connect(hass):
"""Test we handle cannot connect error."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
with patch(
"homeassistant.components.epson.Projector.get_property",
return_value=STATE_UNAVAILABLE,
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_HOST: "1.1.1.1", CONF_NAME: "test-epson", CONF_PORT: 80},
)
assert result2["type"] == "form"
assert result2["errors"] == {"base": "cannot_connect"}
async def test_import(hass):
"""Test config.yaml import."""
with patch(
"homeassistant.components.epson.Projector.get_property",
return_value="04",
), patch("homeassistant.components.epson.async_setup", return_value=True), patch(
"homeassistant.components.epson.async_setup_entry",
return_value=True,
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_IMPORT},
data={CONF_HOST: "1.1.1.1", CONF_NAME: "test-epson", CONF_PORT: 80},
)
assert result["type"] == "create_entry"
assert result["title"] == "test-epson"
assert result["data"] == {CONF_HOST: "1.1.1.1", CONF_PORT: 80}
async def test_import_cannot_connect(hass):
"""Test we handle cannot connect error with import."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_IMPORT}
)
with patch(
"homeassistant.components.epson.Projector.get_property",
return_value=STATE_UNAVAILABLE,
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_HOST: "1.1.1.1", CONF_NAME: "test-epson", CONF_PORT: 80},
)
assert result2["type"] == "form"
assert result2["errors"] == {"base": "cannot_connect"}
| 36.536842
| 85
| 0.659464
|
4a0ba0664ecfd878d30689b1365698b4f4a3b0bb
| 24,976
|
py
|
Python
|
python/venv/lib/python2.7/site-packages/openstackclient/tests/identity/v3/test_role.py
|
sjsucohort6/openstack
|
8471e6e599c3f52319926a582358358ef84cbadb
|
[
"MIT"
] | null | null | null |
python/venv/lib/python2.7/site-packages/openstackclient/tests/identity/v3/test_role.py
|
sjsucohort6/openstack
|
8471e6e599c3f52319926a582358358ef84cbadb
|
[
"MIT"
] | null | null | null |
python/venv/lib/python2.7/site-packages/openstackclient/tests/identity/v3/test_role.py
|
sjsucohort6/openstack
|
8471e6e599c3f52319926a582358358ef84cbadb
|
[
"MIT"
] | null | null | null |
# Copyright 2013 Nebula Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
import copy
from openstackclient.identity.v3 import role
from openstackclient.tests import fakes
from openstackclient.tests.identity.v3 import fakes as identity_fakes
class TestRole(identity_fakes.TestIdentityv3):
def setUp(self):
super(TestRole, self).setUp()
# Get a shortcut to the UserManager Mock
self.users_mock = self.app.client_manager.identity.users
self.users_mock.reset_mock()
# Get a shortcut to the UserManager Mock
self.groups_mock = self.app.client_manager.identity.groups
self.groups_mock.reset_mock()
# Get a shortcut to the DomainManager Mock
self.domains_mock = self.app.client_manager.identity.domains
self.domains_mock.reset_mock()
# Get a shortcut to the ProjectManager Mock
self.projects_mock = self.app.client_manager.identity.projects
self.projects_mock.reset_mock()
# Get a shortcut to the RoleManager Mock
self.roles_mock = self.app.client_manager.identity.roles
self.roles_mock.reset_mock()
def _is_inheritance_testcase(self):
return False
class TestRoleInherited(TestRole):
def _is_inheritance_testcase(self):
return True
class TestRoleAdd(TestRole):
def setUp(self):
super(TestRoleAdd, self).setUp()
self.users_mock.get.return_value = fakes.FakeResource(
None,
copy.deepcopy(identity_fakes.USER),
loaded=True,
)
self.groups_mock.get.return_value = fakes.FakeResource(
None,
copy.deepcopy(identity_fakes.GROUP),
loaded=True,
)
self.domains_mock.get.return_value = fakes.FakeResource(
None,
copy.deepcopy(identity_fakes.DOMAIN),
loaded=True,
)
self.projects_mock.get.return_value = fakes.FakeResource(
None,
copy.deepcopy(identity_fakes.PROJECT),
loaded=True,
)
self.roles_mock.get.return_value = fakes.FakeResource(
None,
copy.deepcopy(identity_fakes.ROLE),
loaded=True,
)
self.roles_mock.grant.return_value = fakes.FakeResource(
None,
copy.deepcopy(identity_fakes.ROLE),
loaded=True,
)
# Get the command object to test
self.cmd = role.AddRole(self.app, None)
def test_role_add_user_domain(self):
arglist = [
'--user', identity_fakes.user_name,
'--domain', identity_fakes.domain_name,
identity_fakes.role_name,
]
if self._is_inheritance_testcase():
arglist.append('--inherited')
verifylist = [
('user', identity_fakes.user_name),
('group', None),
('domain', identity_fakes.domain_name),
('project', None),
('role', identity_fakes.role_name),
('inherited', self._is_inheritance_testcase()),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.run(parsed_args)
self.assertEqual(0, result)
# Set expected values
kwargs = {
'user': identity_fakes.user_id,
'domain': identity_fakes.domain_id,
'os_inherit_extension_inherited': self._is_inheritance_testcase(),
}
# RoleManager.grant(role, user=, group=, domain=, project=)
self.roles_mock.grant.assert_called_with(
identity_fakes.role_id,
**kwargs
)
def test_role_add_user_project(self):
arglist = [
'--user', identity_fakes.user_name,
'--project', identity_fakes.project_name,
identity_fakes.role_name,
]
if self._is_inheritance_testcase():
arglist.append('--inherited')
verifylist = [
('user', identity_fakes.user_name),
('group', None),
('domain', None),
('project', identity_fakes.project_name),
('role', identity_fakes.role_name),
('inherited', self._is_inheritance_testcase()),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.run(parsed_args)
self.assertEqual(0, result)
# Set expected values
kwargs = {
'user': identity_fakes.user_id,
'project': identity_fakes.project_id,
'os_inherit_extension_inherited': self._is_inheritance_testcase(),
}
# RoleManager.grant(role, user=, group=, domain=, project=)
self.roles_mock.grant.assert_called_with(
identity_fakes.role_id,
**kwargs
)
def test_role_add_group_domain(self):
arglist = [
'--group', identity_fakes.group_name,
'--domain', identity_fakes.domain_name,
identity_fakes.role_name,
]
if self._is_inheritance_testcase():
arglist.append('--inherited')
verifylist = [
('user', None),
('group', identity_fakes.group_name),
('domain', identity_fakes.domain_name),
('project', None),
('role', identity_fakes.role_name),
('inherited', self._is_inheritance_testcase()),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.run(parsed_args)
self.assertEqual(0, result)
# Set expected values
kwargs = {
'group': identity_fakes.group_id,
'domain': identity_fakes.domain_id,
'os_inherit_extension_inherited': self._is_inheritance_testcase(),
}
# RoleManager.grant(role, user=, group=, domain=, project=)
self.roles_mock.grant.assert_called_with(
identity_fakes.role_id,
**kwargs
)
def test_role_add_group_project(self):
arglist = [
'--group', identity_fakes.group_name,
'--project', identity_fakes.project_name,
identity_fakes.role_name,
]
if self._is_inheritance_testcase():
arglist.append('--inherited')
verifylist = [
('user', None),
('group', identity_fakes.group_name),
('domain', None),
('project', identity_fakes.project_name),
('role', identity_fakes.role_name),
('inherited', self._is_inheritance_testcase()),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.run(parsed_args)
self.assertEqual(0, result)
# Set expected values
kwargs = {
'group': identity_fakes.group_id,
'project': identity_fakes.project_id,
'os_inherit_extension_inherited': self._is_inheritance_testcase(),
}
# RoleManager.grant(role, user=, group=, domain=, project=)
self.roles_mock.grant.assert_called_with(
identity_fakes.role_id,
**kwargs
)
class TestRoleAddInherited(TestRoleAdd, TestRoleInherited):
pass
class TestRoleCreate(TestRole):
def setUp(self):
super(TestRoleCreate, self).setUp()
self.roles_mock.create.return_value = fakes.FakeResource(
None,
copy.deepcopy(identity_fakes.ROLE),
loaded=True,
)
# Get the command object to test
self.cmd = role.CreateRole(self.app, None)
def test_role_create_no_options(self):
arglist = [
identity_fakes.role_name,
]
verifylist = [
('name', identity_fakes.role_name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
# DisplayCommandBase.take_action() returns two tuples
columns, data = self.cmd.take_action(parsed_args)
# Set expected values
kwargs = {
'name': identity_fakes.role_name,
}
# RoleManager.create(name=)
self.roles_mock.create.assert_called_with(
**kwargs
)
collist = ('id', 'name')
self.assertEqual(collist, columns)
datalist = (
identity_fakes.role_id,
identity_fakes.role_name,
)
self.assertEqual(datalist, data)
class TestRoleDelete(TestRole):
def setUp(self):
super(TestRoleDelete, self).setUp()
self.roles_mock.get.return_value = fakes.FakeResource(
None,
copy.deepcopy(identity_fakes.ROLE),
loaded=True,
)
self.roles_mock.delete.return_value = None
# Get the command object to test
self.cmd = role.DeleteRole(self.app, None)
def test_role_delete_no_options(self):
arglist = [
identity_fakes.role_name,
]
verifylist = [
('roles', [identity_fakes.role_name]),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
# DisplayCommandBase.take_action() returns two tuples
self.cmd.take_action(parsed_args)
self.roles_mock.delete.assert_called_with(
identity_fakes.role_id,
)
class TestRoleList(TestRole):
def setUp(self):
super(TestRoleList, self).setUp()
self.roles_mock.list.return_value = [
fakes.FakeResource(
None,
copy.deepcopy(identity_fakes.ROLE),
loaded=True,
),
]
self.domains_mock.get.return_value = fakes.FakeResource(
None,
copy.deepcopy(identity_fakes.DOMAIN),
loaded=True,
)
self.projects_mock.get.return_value = fakes.FakeResource(
None,
copy.deepcopy(identity_fakes.PROJECT),
loaded=True,
)
self.users_mock.get.return_value = fakes.FakeResource(
None,
copy.deepcopy(identity_fakes.USER),
loaded=True,
)
self.groups_mock.get.return_value = fakes.FakeResource(
None,
copy.deepcopy(identity_fakes.GROUP),
loaded=True,
)
# Get the command object to test
self.cmd = role.ListRole(self.app, None)
def test_role_list_no_options(self):
arglist = []
verifylist = []
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
# DisplayCommandBase.take_action() returns two tuples
columns, data = self.cmd.take_action(parsed_args)
self.roles_mock.list.assert_called_with()
collist = ('ID', 'Name')
self.assertEqual(collist, columns)
datalist = ((
identity_fakes.role_id,
identity_fakes.role_name,
), )
self.assertEqual(datalist, tuple(data))
def test_user_list_user(self):
arglist = [
'--user', identity_fakes.user_id,
]
verifylist = [
('user', identity_fakes.user_id),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
# DisplayCommandBase.take_action() returns two tuples
columns, data = self.cmd.take_action(parsed_args)
# Set expected values
kwargs = {
'domain': 'default',
'user': self.users_mock.get(),
}
# RoleManager.list(user=, group=, domain=, project=, **kwargs)
self.roles_mock.list.assert_called_with(
**kwargs
)
collist = ('ID', 'Name')
self.assertEqual(collist, columns)
datalist = ((
identity_fakes.role_id,
identity_fakes.role_name,
), )
self.assertEqual(datalist, tuple(data))
def test_role_list_domain_user(self):
arglist = [
'--domain', identity_fakes.domain_name,
'--user', identity_fakes.user_id,
]
verifylist = [
('domain', identity_fakes.domain_name),
('user', identity_fakes.user_id),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
# DisplayCommandBase.take_action() returns two tuples
columns, data = self.cmd.take_action(parsed_args)
# Set expected values
kwargs = {
'domain': self.domains_mock.get(),
'user': self.users_mock.get(),
}
# RoleManager.list(user=, group=, domain=, project=, **kwargs)
self.roles_mock.list.assert_called_with(
**kwargs
)
collist = ('ID', 'Name', 'Domain', 'User')
self.assertEqual(collist, columns)
datalist = ((
identity_fakes.role_id,
identity_fakes.role_name,
identity_fakes.domain_name,
identity_fakes.user_name,
), )
self.assertEqual(datalist, tuple(data))
def test_role_list_domain_group(self):
arglist = [
'--domain', identity_fakes.domain_name,
'--group', identity_fakes.group_id,
]
verifylist = [
('domain', identity_fakes.domain_name),
('group', identity_fakes.group_id),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
# DisplayCommandBase.take_action() returns two tuples
columns, data = self.cmd.take_action(parsed_args)
# Set expected values
kwargs = {
'domain': self.domains_mock.get(),
'group': self.groups_mock.get(),
}
# RoleManager.list(user=, group=, domain=, project=, **kwargs)
self.roles_mock.list.assert_called_with(
**kwargs
)
collist = ('ID', 'Name', 'Domain', 'Group')
self.assertEqual(collist, columns)
datalist = ((
identity_fakes.role_id,
identity_fakes.role_name,
identity_fakes.domain_name,
identity_fakes.group_name,
), )
self.assertEqual(datalist, tuple(data))
def test_role_list_project_user(self):
arglist = [
'--project', identity_fakes.project_name,
'--user', identity_fakes.user_id,
]
verifylist = [
('project', identity_fakes.project_name),
('user', identity_fakes.user_id),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
# DisplayCommandBase.take_action() returns two tuples
columns, data = self.cmd.take_action(parsed_args)
# Set expected values
kwargs = {
'project': self.projects_mock.get(),
'user': self.users_mock.get(),
}
# RoleManager.list(user=, group=, domain=, project=, **kwargs)
self.roles_mock.list.assert_called_with(
**kwargs
)
collist = ('ID', 'Name', 'Project', 'User')
self.assertEqual(collist, columns)
datalist = ((
identity_fakes.role_id,
identity_fakes.role_name,
identity_fakes.project_name,
identity_fakes.user_name,
), )
self.assertEqual(datalist, tuple(data))
def test_role_list_project_group(self):
arglist = [
'--project', identity_fakes.project_name,
'--group', identity_fakes.group_id,
]
verifylist = [
('project', identity_fakes.project_name),
('group', identity_fakes.group_id),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
# DisplayCommandBase.take_action() returns two tuples
columns, data = self.cmd.take_action(parsed_args)
# Set expected values
kwargs = {
'project': self.projects_mock.get(),
'group': self.groups_mock.get(),
}
# RoleManager.list(user=, group=, domain=, project=, **kwargs)
self.roles_mock.list.assert_called_with(
**kwargs
)
collist = ('ID', 'Name', 'Project', 'Group')
self.assertEqual(collist, columns)
datalist = ((
identity_fakes.role_id,
identity_fakes.role_name,
identity_fakes.project_name,
identity_fakes.group_name,
), )
self.assertEqual(datalist, tuple(data))
class TestRoleRemove(TestRole):
def setUp(self):
super(TestRoleRemove, self).setUp()
self.users_mock.get.return_value = fakes.FakeResource(
None,
copy.deepcopy(identity_fakes.USER),
loaded=True,
)
self.groups_mock.get.return_value = fakes.FakeResource(
None,
copy.deepcopy(identity_fakes.GROUP),
loaded=True,
)
self.domains_mock.get.return_value = fakes.FakeResource(
None,
copy.deepcopy(identity_fakes.DOMAIN),
loaded=True,
)
self.projects_mock.get.return_value = fakes.FakeResource(
None,
copy.deepcopy(identity_fakes.PROJECT),
loaded=True,
)
self.roles_mock.get.return_value = fakes.FakeResource(
None,
copy.deepcopy(identity_fakes.ROLE),
loaded=True,
)
self.roles_mock.revoke.return_value = None
# Get the command object to test
self.cmd = role.RemoveRole(self.app, None)
def test_role_remove_user_domain(self):
arglist = [
'--user', identity_fakes.user_name,
'--domain', identity_fakes.domain_name,
identity_fakes.role_name,
]
if self._is_inheritance_testcase():
arglist.append('--inherited')
verifylist = [
('user', identity_fakes.user_name),
('group', None),
('domain', identity_fakes.domain_name),
('project', None),
('role', identity_fakes.role_name),
('inherited', self._is_inheritance_testcase()),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
# DisplayCommandBase.take_action() returns two tuples
self.cmd.take_action(parsed_args)
# Set expected values
kwargs = {
'user': identity_fakes.user_id,
'domain': identity_fakes.domain_id,
'os_inherit_extension_inherited': self._is_inheritance_testcase(),
}
# RoleManager.revoke(role, user=, group=, domain=, project=)
self.roles_mock.revoke.assert_called_with(
identity_fakes.role_id,
**kwargs
)
def test_role_remove_user_project(self):
arglist = [
'--user', identity_fakes.user_name,
'--project', identity_fakes.project_name,
identity_fakes.role_name,
]
if self._is_inheritance_testcase():
arglist.append('--inherited')
verifylist = [
('user', identity_fakes.user_name),
('group', None),
('domain', None),
('project', identity_fakes.project_name),
('role', identity_fakes.role_name),
('inherited', self._is_inheritance_testcase()),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
# DisplayCommandBase.take_action() returns two tuples
self.cmd.take_action(parsed_args)
# Set expected values
kwargs = {
'user': identity_fakes.user_id,
'project': identity_fakes.project_id,
'os_inherit_extension_inherited': self._is_inheritance_testcase(),
}
# RoleManager.revoke(role, user=, group=, domain=, project=)
self.roles_mock.revoke.assert_called_with(
identity_fakes.role_id,
**kwargs
)
def test_role_remove_group_domain(self):
arglist = [
'--group', identity_fakes.group_name,
'--domain', identity_fakes.domain_name,
identity_fakes.role_name,
]
if self._is_inheritance_testcase():
arglist.append('--inherited')
verifylist = [
('user', None),
('group', identity_fakes.group_name),
('domain', identity_fakes.domain_name),
('project', None),
('role', identity_fakes.role_name),
('role', identity_fakes.role_name),
('inherited', self._is_inheritance_testcase()),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
# DisplayCommandBase.take_action() returns two tuples
self.cmd.take_action(parsed_args)
# Set expected values
kwargs = {
'group': identity_fakes.group_id,
'domain': identity_fakes.domain_id,
'os_inherit_extension_inherited': self._is_inheritance_testcase(),
}
# RoleManager.revoke(role, user=, group=, domain=, project=)
self.roles_mock.revoke.assert_called_with(
identity_fakes.role_id,
**kwargs
)
def test_role_remove_group_project(self):
arglist = [
'--group', identity_fakes.group_name,
'--project', identity_fakes.project_name,
identity_fakes.role_name,
]
if self._is_inheritance_testcase():
arglist.append('--inherited')
verifylist = [
('user', None),
('group', identity_fakes.group_name),
('domain', None),
('project', identity_fakes.project_name),
('role', identity_fakes.role_name),
('inherited', self._is_inheritance_testcase()),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
# DisplayCommandBase.take_action() returns two tuples
self.cmd.take_action(parsed_args)
# Set expected values
kwargs = {
'group': identity_fakes.group_id,
'project': identity_fakes.project_id,
'os_inherit_extension_inherited': self._is_inheritance_testcase(),
}
# RoleManager.revoke(role, user=, group=, domain=, project=)
self.roles_mock.revoke.assert_called_with(
identity_fakes.role_id,
**kwargs
)
class TestRoleSet(TestRole):
def setUp(self):
super(TestRoleSet, self).setUp()
self.roles_mock.get.return_value = fakes.FakeResource(
None,
copy.deepcopy(identity_fakes.ROLE),
loaded=True,
)
self.roles_mock.update.return_value = None
# Get the command object to test
self.cmd = role.SetRole(self.app, None)
def test_role_set_no_options(self):
arglist = [
'--name', 'over',
identity_fakes.role_name,
]
verifylist = [
('name', 'over'),
('role', identity_fakes.role_name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
# DisplayCommandBase.take_action() returns two tuples
self.cmd.take_action(parsed_args)
# Set expected values
kwargs = {
'name': 'over',
}
# RoleManager.update(role, name=)
self.roles_mock.update.assert_called_with(
identity_fakes.role_id,
**kwargs
)
class TestRoleShow(TestRole):
def setUp(self):
super(TestRoleShow, self).setUp()
self.roles_mock.get.return_value = fakes.FakeResource(
None,
copy.deepcopy(identity_fakes.ROLE),
loaded=True,
)
# Get the command object to test
self.cmd = role.ShowRole(self.app, None)
def test_role_show(self):
arglist = [
identity_fakes.role_name,
]
verifylist = [
('role', identity_fakes.role_name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
# DisplayCommandBase.take_action() returns two tuples
columns, data = self.cmd.take_action(parsed_args)
# RoleManager.get(role)
self.roles_mock.get.assert_called_with(
identity_fakes.role_name,
)
collist = ('id', 'name')
self.assertEqual(collist, columns)
datalist = (
identity_fakes.role_id,
identity_fakes.role_name,
)
self.assertEqual(datalist, data)
| 31.695431
| 78
| 0.586083
|
4a0ba073a16b0bb01226fb6a115eddea0317400b
| 2,987
|
py
|
Python
|
configs/_base_/models/maskflownet.py
|
hologerry/mmflow
|
40caf064851bd95317424e31cc137c0007a2bece
|
[
"Apache-2.0"
] | 481
|
2021-11-16T07:04:23.000Z
|
2022-03-31T22:21:21.000Z
|
configs/_base_/models/maskflownet.py
|
hologerry/mmflow
|
40caf064851bd95317424e31cc137c0007a2bece
|
[
"Apache-2.0"
] | 72
|
2021-11-16T12:25:55.000Z
|
2022-03-28T13:10:45.000Z
|
configs/_base_/models/maskflownet.py
|
hologerry/mmflow
|
40caf064851bd95317424e31cc137c0007a2bece
|
[
"Apache-2.0"
] | 48
|
2021-11-16T06:48:46.000Z
|
2022-03-30T12:46:40.000Z
|
MaskflownetS_checkpoint = 'https://download.openmmlab.com/mmflow/maskflownet/maskflownets_8x1_sfine_flyingthings3d_subset_384x768.pth' # noqa
model = dict(
type='MaskFlowNet',
maskflownetS=dict(
type='MaskFlowNetS',
freeze_net=True,
encoder=dict(
type='PWCNetEncoder',
in_channels=3,
net_type='Basic',
pyramid_levels=[
'level1', 'level2', 'level3', 'level4', 'level5', 'level6'
],
out_channels=(16, 32, 64, 96, 128, 196),
strides=(2, 2, 2, 2, 2, 2),
dilations=(1, 1, 1, 1, 1, 1),
act_cfg=dict(type='LeakyReLU', negative_slope=0.1)),
decoder=dict(
type='MaskFlowNetSDecoder',
warp_in_channels=dict(
level6=196, level5=128, level4=96, level3=64, level2=32),
up_channels=dict(
level6=16, level5=16, level4=16, level3=16, level2=16),
warp_type='AsymOFMM',
in_channels=dict(
level6=81, level5=227, level4=195, level3=163, level2=131),
corr_cfg=dict(type='Correlation', max_displacement=4),
act_cfg=dict(type='LeakyReLU', negative_slope=0.1),
scaled=False,
post_processor=dict(type='ContextNet', in_channels=579)),
# model training and testing settings
train_cfg=dict(),
test_cfg=dict(),
init_cfg=dict(type='Pretrained', checkpoint=MaskflownetS_checkpoint)),
encoder=dict(
type='PWCNetEncoder',
in_channels=4,
net_type='Basic',
pyramid_levels=[
'level1', 'level2', 'level3', 'level4', 'level5', 'level6'
],
out_channels=(16, 32, 64, 96, 128, 196),
strides=(2, 2, 2, 2, 2, 2),
dilations=(1, 1, 1, 1, 1, 1),
act_cfg=dict(type='LeakyReLU', negative_slope=0.1)),
decoder=dict(
type='MaskFlowNetDecoder',
warp_in_channels=dict(
level6=196, level5=128, level4=96, level3=64, level2=32),
up_channels=dict(
level6=16, level5=16, level4=16, level3=16, level2=16),
warp_type='Basic',
with_mask=False,
in_channels=dict(
level6=52, level5=198, level4=166, level3=134, level2=102),
corr_cfg=dict(type='Correlation', max_displacement=2),
act_cfg=dict(type='LeakyReLU', negative_slope=0.1),
scaled=False,
post_processor=dict(type='ContextNet', in_channels=550),
flow_loss=dict(
type='MultiLevelEPE',
p=2,
reduction='sum',
weights={
'level2': 0.005,
'level3': 0.01,
'level4': 0.02,
'level5': 0.08,
'level6': 0.32
}),
),
# model training and testing settings
train_cfg=dict(),
test_cfg=dict(),
init_cfg=dict(
type='Kaiming', a=0.1, distribution='uniform', layer='Conv2d'))
| 38.792208
| 142
| 0.555072
|
4a0ba076d3a9576af25df3edbbb91f697a9f0d65
| 641
|
py
|
Python
|
test/test_noise2.py
|
fsgeek/tikzplotlib
|
aee7a4ff145159476a7d07248f4b93c2372e73e7
|
[
"MIT"
] | null | null | null |
test/test_noise2.py
|
fsgeek/tikzplotlib
|
aee7a4ff145159476a7d07248f4b93c2372e73e7
|
[
"MIT"
] | null | null | null |
test/test_noise2.py
|
fsgeek/tikzplotlib
|
aee7a4ff145159476a7d07248f4b93c2372e73e7
|
[
"MIT"
] | null | null | null |
import matplotlib.pyplot as plt
import numpy as np
from helpers import assert_equality
def plot():
# Make plot with horizontal colorbar
fig = plt.figure()
ax = fig.add_subplot(111)
np.random.seed(123)
data = np.clip(np.random.randn(250, 250), -1, 1)
cax = ax.imshow(data, interpolation="nearest")
ax.set_title("Gaussian noise with horizontal colorbar")
cbar = fig.colorbar(cax, ticks=[-1, 0, 1], orientation="horizontal")
# horizontal colorbar
cbar.ax.set_xticklabels(["Low", "Medium", "High"])
return fig
def test():
assert_equality(plot, __file__[:-3] + "_reference.tex")
return
| 23.740741
| 72
| 0.672387
|
4a0ba36714cb28942aa89b0ed52d3204c2ba8541
| 533
|
py
|
Python
|
define2-1-to-xlsx/documents.py
|
swhume/odmlib_examples
|
7b1b38c9951b8c3b9f5673db6d7ccd2bbe2f49de
|
[
"MIT"
] | 4
|
2021-08-04T01:40:34.000Z
|
2022-03-28T10:23:44.000Z
|
define2xls/documents.py
|
swhume/odmlib_examples
|
7b1b38c9951b8c3b9f5673db6d7ccd2bbe2f49de
|
[
"MIT"
] | 1
|
2022-03-19T13:14:28.000Z
|
2022-03-31T19:00:30.000Z
|
define2-1-to-xlsx/documents.py
|
swhume/odmlib_examples
|
7b1b38c9951b8c3b9f5673db6d7ccd2bbe2f49de
|
[
"MIT"
] | 1
|
2021-12-10T14:31:55.000Z
|
2021-12-10T14:31:55.000Z
|
import csv
import os
class Documents:
HEADERS = ["ID", "Title", "Href"]
def __init__(self, odmlib_mdv, data_path):
self.mdv = odmlib_mdv
self.path = data_path
self.file_name = os.path.join(self.path, "documents.csv")
def extract(self):
with open(self.file_name, 'w', newline='') as f:
writer = csv.writer(f, dialect="excel")
writer.writerow(self.HEADERS)
for lf in self.mdv.leaf:
writer.writerow([lf.ID, lf.title._content, lf.href])
| 28.052632
| 68
| 0.592871
|
4a0ba39dc396fa6cdd579b8f71634a8cf20edc6b
| 632
|
py
|
Python
|
manage.py
|
rgrlinux/bps
|
a8e6c15efed4bddc6372e5498b3615aeb1daf021
|
[
"MIT"
] | null | null | null |
manage.py
|
rgrlinux/bps
|
a8e6c15efed4bddc6372e5498b3615aeb1daf021
|
[
"MIT"
] | 5
|
2021-03-30T14:05:15.000Z
|
2021-09-22T19:29:45.000Z
|
manage.py
|
rgrlinux/bps
|
a8e6c15efed4bddc6372e5498b3615aeb1daf021
|
[
"MIT"
] | null | null | null |
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bichanopreto.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
| 28.727273
| 76
| 0.685127
|
4a0ba4da391948660b8e9371a3c92e5d5b4bb5fb
| 2,319
|
py
|
Python
|
tests/on_wlm/test_simple_base_settings_on_wlm.py
|
neuralvis/SmartSim
|
0248ffe8a61be58afe376c5c363172f3e91d227b
|
[
"BSD-2-Clause"
] | null | null | null |
tests/on_wlm/test_simple_base_settings_on_wlm.py
|
neuralvis/SmartSim
|
0248ffe8a61be58afe376c5c363172f3e91d227b
|
[
"BSD-2-Clause"
] | null | null | null |
tests/on_wlm/test_simple_base_settings_on_wlm.py
|
neuralvis/SmartSim
|
0248ffe8a61be58afe376c5c363172f3e91d227b
|
[
"BSD-2-Clause"
] | null | null | null |
import time
import pytest
from smartsim import Experiment, constants
from smartsim.settings.settings import RunSettings
"""
Test the launch and stop of simple models and ensembles that use base
RunSettings while on WLM that do not include a run command
These tests will execute code (very light scripts) on the head node
as no run command will exec them out onto the compute nodes
the reason we test this is because we want to make sure that each
WLM launcher also supports the ability to run scripts on the head node
that also contain an invoking run command
"""
# retrieved from pytest fixtures
if pytest.test_launcher not in pytest.wlm_options:
pytestmark = pytest.mark.skip(reason="Not testing WLM integrations")
def test_simple_model_on_wlm(fileutils, wlmutils):
launcher = wlmutils.get_test_launcher()
if launcher not in ["pbs", "slurm", "cobalt"]:
pytest.skip("Test only runs on systems with PBSPro, Slurm, or Cobalt as WLM")
exp_name = "test-simplebase-settings-model-launch"
exp = Experiment(exp_name, launcher=wlmutils.get_test_launcher())
test_dir = fileutils.make_test_dir(exp_name)
script = fileutils.get_test_conf_path("sleep.py")
settings = RunSettings("python", exe_args=f"{script} --time=5")
M = exp.create_model("m", path=test_dir, run_settings=settings)
# launch model twice to show that it can also be restarted
for _ in range(2):
exp.start(M, block=True)
assert exp.get_status(M)[0] == constants.STATUS_COMPLETED
def test_simple_model_stop_on_wlm(fileutils, wlmutils):
launcher = wlmutils.get_test_launcher()
if launcher not in ["pbs", "slurm", "cobalt"]:
pytest.skip("Test only runs on systems with PBSPro, Slurm, or Cobalt as WLM")
exp_name = "test-simplebase-settings-model-stop"
exp = Experiment(exp_name, launcher=wlmutils.get_test_launcher())
test_dir = fileutils.make_test_dir(exp_name)
script = fileutils.get_test_conf_path("sleep.py")
settings = RunSettings("python", exe_args=f"{script} --time=5")
M = exp.create_model("m", path=test_dir, run_settings=settings)
# stop launched model
exp.start(M, block=False)
time.sleep(2)
exp.stop(M)
assert M.name in exp._control._jobs.completed
assert exp.get_status(M)[0] == constants.STATUS_CANCELLED
| 36.809524
| 85
| 0.736524
|
4a0ba7065bcedec4affc7df295820e2f48d7b10e
| 7,445
|
py
|
Python
|
app/main/views/organisations.py
|
karlchillmaid/notifications-admin
|
9ef6da4ef9e2fa97b7debb4b573cb035a5cb8880
|
[
"MIT"
] | null | null | null |
app/main/views/organisations.py
|
karlchillmaid/notifications-admin
|
9ef6da4ef9e2fa97b7debb4b573cb035a5cb8880
|
[
"MIT"
] | null | null | null |
app/main/views/organisations.py
|
karlchillmaid/notifications-admin
|
9ef6da4ef9e2fa97b7debb4b573cb035a5cb8880
|
[
"MIT"
] | null | null | null |
from flask import flash, redirect, render_template, request, session, url_for
from flask_login import current_user, login_required
from notifications_python_client.errors import HTTPError
from werkzeug.exceptions import abort
from app import (
current_organisation,
org_invite_api_client,
organisations_client,
user_api_client,
)
from app.main import main
from app.main.forms import (
ConfirmPasswordForm,
CreateOrUpdateOrganisation,
InviteOrgUserForm,
RenameOrganisationForm,
SearchUsersForm,
)
from app.utils import user_has_permissions, user_is_platform_admin
@main.route("/organisations", methods=['GET'])
@login_required
@user_is_platform_admin
def organisations():
orgs = organisations_client.get_organisations()
return render_template(
'views/organisations/index.html',
organisations=orgs
)
@main.route("/organisations/add", methods=['GET', 'POST'])
@login_required
@user_is_platform_admin
def add_organisation():
form = CreateOrUpdateOrganisation()
if form.validate_on_submit():
organisations_client.create_organisation(
name=form.name.data,
)
return redirect(url_for('.organisations'))
return render_template(
'views/organisations/add-organisation.html',
form=form
)
@main.route("/organisations/<org_id>", methods=['GET'])
@login_required
@user_has_permissions()
def organisation_dashboard(org_id):
organisation_services = organisations_client.get_organisation_services(org_id)
for service in organisation_services:
has_permission = current_user.has_permission_for_service(service['id'], 'view_activity')
service.update({'has_permission_to_view': has_permission})
return render_template(
'views/organisations/organisation/index.html',
organisation_services=organisation_services
)
@main.route("/organisations/<org_id>/users", methods=['GET'])
@login_required
@user_has_permissions()
def manage_org_users(org_id):
users = sorted(
user_api_client.get_users_for_organisation(org_id=org_id) + [
invite for invite in org_invite_api_client.get_invites_for_organisation(org_id=org_id)
if invite.status != 'accepted'
],
key=lambda user: user.email_address,
)
return render_template(
'views/organisations/organisation/users/index.html',
users=users,
show_search_box=(len(users) > 7),
form=SearchUsersForm(),
)
@main.route("/organisations/<org_id>/users/invite", methods=['GET', 'POST'])
@login_required
@user_has_permissions()
def invite_org_user(org_id):
form = InviteOrgUserForm(
invalid_email_address=current_user.email_address
)
if form.validate_on_submit():
email_address = form.email_address.data
invited_org_user = org_invite_api_client.create_invite(
current_user.id,
org_id,
email_address
)
flash('Invite sent to {}'.format(invited_org_user.email_address), 'default_with_tick')
return redirect(url_for('.manage_org_users', org_id=org_id))
return render_template(
'views/organisations/organisation/users/invite-org-user.html',
form=form
)
@main.route("/organisations/<org_id>/users/<user_id>", methods=['GET', 'POST'])
@login_required
@user_has_permissions()
def edit_user_org_permissions(org_id, user_id):
user = user_api_client.get_user(user_id)
return render_template(
'views/organisations/organisation/users/user/index.html',
user=user
)
@main.route("/organisations/<org_id>/users/<user_id>/delete", methods=['GET', 'POST'])
@login_required
@user_has_permissions()
def remove_user_from_organisation(org_id, user_id):
user = user_api_client.get_user(user_id)
if request.method == 'POST':
try:
organisations_client.remove_user_from_organisation(org_id, user_id)
except HTTPError as e:
msg = "You cannot remove the only user for a service"
if e.status_code == 400 and msg in e.message:
flash(msg, 'info')
return redirect(url_for(
'.manage_org_users',
org_id=org_id))
else:
abort(500, e)
return redirect(url_for(
'.manage_org_users',
org_id=org_id
))
flash('Are you sure you want to remove {}?'.format(user.name), 'remove')
return render_template(
'views/organisations/organisation/users/user/index.html',
user=user,
)
@main.route("/organisations/<org_id>/cancel-invited-user/<invited_user_id>", methods=['GET'])
@login_required
@user_has_permissions()
def cancel_invited_org_user(org_id, invited_user_id):
org_invite_api_client.cancel_invited_user(org_id=org_id, invited_user_id=invited_user_id)
return redirect(url_for('main.manage_org_users', org_id=org_id))
@main.route("/organisations/<org_id>/settings/", methods=['GET'])
@login_required
@user_has_permissions()
def organisation_settings(org_id):
return render_template(
'views/organisations/organisation/settings/index.html',
)
@main.route("/organisations/<org_id>/settings/edit-name", methods=['GET', 'POST'])
@login_required
@user_has_permissions()
def edit_organisation_name(org_id):
form = RenameOrganisationForm()
if request.method == 'GET':
form.name.data = current_organisation.get('name')
if form.validate_on_submit():
unique_name = organisations_client.is_organisation_name_unique(org_id, form.name.data)
if not unique_name:
form.name.errors.append("This organisation name is already in use")
return render_template('views/organisations/organisation/settings/edit-name/index.html', form=form)
session['organisation_name_change'] = form.name.data
return redirect(url_for('.confirm_edit_organisation_name', org_id=org_id))
return render_template(
'views/organisations/organisation/settings/edit-name/index.html',
form=form,
)
@main.route("/organisations/<org_id>/settings/edit-name/confirm", methods=['GET', 'POST'])
@login_required
@user_has_permissions()
def confirm_edit_organisation_name(org_id):
# Validate password for form
def _check_password(pwd):
return user_api_client.verify_password(current_user.id, pwd)
form = ConfirmPasswordForm(_check_password)
if form.validate_on_submit():
try:
organisations_client.update_organisation_name(
current_organisation['id'],
name=session['organisation_name_change'],
)
except HTTPError as e:
error_msg = "Organisation name already exists"
if e.status_code == 400 and error_msg in e.message:
# Redirect the user back to the change service name screen
flash('This organisation name is already in use', 'error')
return redirect(url_for('main.edit_organisation_name', org_id=org_id))
else:
raise e
else:
session.pop('organisation_name_change')
return redirect(url_for('.organisation_settings', org_id=org_id))
return render_template(
'views/organisations/organisation/settings/edit-name/confirm.html',
new_name=session['organisation_name_change'],
form=form)
| 32.797357
| 111
| 0.694426
|
4a0ba87f979b67b7a8bb27eabf870bdab3cd0fcf
| 3,663
|
py
|
Python
|
docs/target/sphinx/docutils/parsers/rst/languages/fr.py
|
SergeyParamoshkin/sqoop2
|
504ad690617d570483e5693464e73aa641f61fb0
|
[
"Apache-2.0"
] | 1
|
2015-03-22T16:49:07.000Z
|
2015-03-22T16:49:07.000Z
|
docs/target/sphinx/docutils/parsers/rst/languages/fr.py
|
SergeyParamoshkin/sqoop2
|
504ad690617d570483e5693464e73aa641f61fb0
|
[
"Apache-2.0"
] | null | null | null |
docs/target/sphinx/docutils/parsers/rst/languages/fr.py
|
SergeyParamoshkin/sqoop2
|
504ad690617d570483e5693464e73aa641f61fb0
|
[
"Apache-2.0"
] | null | null | null |
# $Id: fr.py 6460 2010-10-29 22:18:44Z milde $
# Authors: David Goodger <goodger@python.org>; William Dode
# Copyright: This module has been placed in the public domain.
# New language mappings are welcome. Before doing a new translation, please
# read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be
# translated for each language: one in docutils/languages, the other in
# docutils/parsers/rst/languages.
"""
French-language mappings for language-dependent features of
reStructuredText.
"""
__docformat__ = 'reStructuredText'
directives = {
u'attention': 'attention',
u'pr\u00E9caution': 'caution',
u'danger': 'danger',
u'erreur': 'error',
u'conseil': 'hint',
u'important': 'important',
u'note': 'note',
u'astuce': 'tip',
u'avertissement': 'warning',
u'admonition': 'admonition',
u'encadr\u00E9': 'sidebar',
u'sujet': 'topic',
u'bloc-textuel': 'line-block',
u'bloc-interpr\u00E9t\u00E9': 'parsed-literal',
u'code-interpr\u00E9t\u00E9': 'parsed-literal',
u'intertitre': 'rubric',
u'exergue': 'epigraph',
u'\u00E9pigraphe': 'epigraph',
u'chapeau': 'highlights',
u'accroche': 'pull-quote',
u'compound (translation required)': 'compound',
u'container (translation required)': 'container',
#u'questions': 'questions',
#u'qr': 'questions',
#u'faq': 'questions',
u'tableau': 'table',
u'csv-table (translation required)': 'csv-table',
u'list-table (translation required)': 'list-table',
u'm\u00E9ta': 'meta',
'math (translation required)': 'math',
#u'imagemap (translation required)': 'imagemap',
u'image': 'image',
u'figure': 'figure',
u'inclure': 'include',
u'brut': 'raw',
u'remplacer': 'replace',
u'remplace': 'replace',
u'unicode': 'unicode',
u'date': 'date',
u'classe': 'class',
u'role (translation required)': 'role',
u'default-role (translation required)': 'default-role',
u'titre (translation required)': 'title',
u'sommaire': 'contents',
u'table-des-mati\u00E8res': 'contents',
u'sectnum': 'sectnum',
u'section-num\u00E9rot\u00E9e': 'sectnum',
u'liens': 'target-notes',
u'header (translation required)': 'header',
u'footer (translation required)': 'footer',
#u'footnotes (translation required)': 'footnotes',
#u'citations (translation required)': 'citations',
}
"""French name to registered (in directives/__init__.py) directive name
mapping."""
roles = {
u'abr\u00E9viation': 'abbreviation',
u'acronyme': 'acronym',
u'sigle': 'acronym',
u'index': 'index',
u'indice': 'subscript',
u'ind': 'subscript',
u'exposant': 'superscript',
u'exp': 'superscript',
u'titre-r\u00E9f\u00E9rence': 'title-reference',
u'titre': 'title-reference',
u'pep-r\u00E9f\u00E9rence': 'pep-reference',
u'rfc-r\u00E9f\u00E9rence': 'rfc-reference',
u'emphase': 'emphasis',
u'fort': 'strong',
u'litt\u00E9ral': 'literal',
'math (translation required)': 'math',
u'nomm\u00E9e-r\u00E9f\u00E9rence': 'named-reference',
u'anonyme-r\u00E9f\u00E9rence': 'anonymous-reference',
u'note-r\u00E9f\u00E9rence': 'footnote-reference',
u'citation-r\u00E9f\u00E9rence': 'citation-reference',
u'substitution-r\u00E9f\u00E9rence': 'substitution-reference',
u'lien': 'target',
u'uri-r\u00E9f\u00E9rence': 'uri-reference',
u'brut': 'raw',}
"""Mapping of French role names to canonical role names for interpreted text.
"""
| 35.911765
| 77
| 0.621895
|
4a0ba89e8a788aec30d28516cd78942ca8902868
| 3,186
|
py
|
Python
|
chromagnon/SuperFastHash.py
|
arsinclair/Chromagnon
|
3cab2736b5ad33f991a25bbe4b4d6d1bb91c9fed
|
[
"BSD-3-Clause"
] | 211
|
2015-02-10T11:28:50.000Z
|
2022-03-24T20:36:16.000Z
|
chromagnon/SuperFastHash.py
|
arsinclair/Chromagnon
|
3cab2736b5ad33f991a25bbe4b4d6d1bb91c9fed
|
[
"BSD-3-Clause"
] | 17
|
2015-02-06T16:47:50.000Z
|
2020-12-02T15:16:04.000Z
|
chromagnon/SuperFastHash.py
|
arsinclair/Chromagnon
|
3cab2736b5ad33f991a25bbe4b4d6d1bb91c9fed
|
[
"BSD-3-Clause"
] | 49
|
2016-01-25T11:49:28.000Z
|
2021-10-20T12:56:29.000Z
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2012, Jean-Rémy Bancel <jean-remy.bancel@telecom-paristech.org>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the Chromagon Project nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL Jean-Rémy Bancel BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
Python implementation of SuperFastHash algorithm
Maybe it is better to use c_uint32 to limit the size of variables to 32bits
instead of using 0xFFFFFFFF mask.
"""
import binascii
import sys
def get16bits(data):
"""Returns the first 16bits of a string"""
return int(binascii.hexlify(data[1::-1]), 16)
def superFastHash(data):
hash = length = len(data)
if length == 0:
return 0
rem = length & 3
length >>= 2
while length > 0:
hash += get16bits(data) & 0xFFFFFFFF
tmp = (get16bits(data[2:])<< 11) ^ hash
hash = ((hash << 16) & 0xFFFFFFFF) ^ tmp
data = data[4:]
hash += hash >> 11
hash = hash & 0xFFFFFFFF
length -= 1
if rem == 3:
hash += get16bits (data)
hash ^= (hash << 16) & 0xFFFFFFFF
hash ^= (int(binascii.hexlify(data[2]), 16) << 18) & 0xFFFFFFFF
hash += hash >> 11
elif rem == 2:
hash += get16bits (data)
hash ^= (hash << 11) & 0xFFFFFFFF
hash += hash >> 17
elif rem == 1:
hash += int(binascii.hexlify(data[0]), 16)
hash ^= (hash << 10) & 0xFFFFFFFF
hash += hash >> 1
hash = hash & 0xFFFFFFFF
hash ^= (hash << 3) & 0xFFFFFFFF
hash += hash >> 5
hash = hash & 0xFFFFFFFF
hash ^= (hash << 4) & 0xFFFFFFFF
hash += hash >> 17
hash = hash & 0xFFFFFFFF
hash ^= (hash << 25) & 0xFFFFFFFF
hash += hash >> 6
hash = hash & 0xFFFFFFFF
return hash
if __name__ == "__main__":
print "%08x"%superFastHash(sys.argv[1])
| 36.204545
| 80
| 0.663214
|
4a0ba8a907b8dd5d13ea188a7a2e26f9ba72a911
| 4,172
|
py
|
Python
|
server/woker.py
|
felipeaq/trab1_redes
|
69b102a5509ff8edfabc47ee70a82fb2a5ecd06f
|
[
"Apache-2.0"
] | null | null | null |
server/woker.py
|
felipeaq/trab1_redes
|
69b102a5509ff8edfabc47ee70a82fb2a5ecd06f
|
[
"Apache-2.0"
] | null | null | null |
server/woker.py
|
felipeaq/trab1_redes
|
69b102a5509ff8edfabc47ee70a82fb2a5ecd06f
|
[
"Apache-2.0"
] | null | null | null |
import random
import json
import socket
from http_request import HttpRequest
class ExternalFiles: # classe que contém links externos
def __init__(self,book_file,dollar_server,dollar_link,stock_link,stock_server):
self.book_file=book_file
self.dollar_server=dollar_server
self.dollar_link=dollar_link
self.stock_link=stock_link
self.stock_server=stock_server
class Worker:
def __init__(self,sock,conn,client,timeout):
self.sock=sock
self.conn=conn
self.client=client
#dicionario de metodos:
self.methods={"\\verlivros":self.books,"\\verdolar":self.dollar2real,"\\veracao":self.stock_price}
self.timeout=timeout
self.external_files=ExternalFiles("bibliografias.txt",
"economia.awesomeapi.com.br",
"economia.awesomeapi.com.br/all/USD-BRL",
"/api/v3/stock/real-time-price/",
"financialmodelingprep.com")
def get_message(self,data):
#processa a mensagem do cliente
message_list=[]
try:
message_list=data.decode().split()
except:
print ("mensagem impossível de decodificar") # se for algo tipo um crtl+c, retorna mensagem de erro
if not message_list: #se não ouver nada na mensagem, retorna vazio
return ""
message=message_list[0]
args=[]
if len(message_list)>1: # fazer parser dos argumentos do comando
args=message_list[1:]
print (message.encode())
if not message in self.methods.keys(): # se não for uma palavra reservada, então retorna a propria palavra
return message
return self.methods[message](*args) #retorna a palvra correspondente ao método
def execute(self):
data = "bla"
self.conn.settimeout(self.timeout)
while data: #recebe mensagem responde
try:
data= self.conn.recv(32)
message=self.get_message(data)
self.conn.sendall(message.encode())
except socket.timeout: #aguarda algum tempo, caso de timeout ele desconecta
print ("timeout no cliente",self.client)
data=None
self.conn.close()
def books(self,*args): #metodo que retona um livro aleatório sobre investimento
f=open(self.external_files.book_file,"r")
book_list=f.read().split("<>")
return random.choice(book_list)
def dollar2real(self,*args): #metodo que converte 1 dolar em real em um servidor externo e retona
try:
h=HttpRequest()
dollar_string=h.make_request(self.external_files.dollar_link,self.external_files.dollar_server)
d= json.loads(dollar_string.decode())["USD"]
message="preço de baixo: {}\npreço de alta: {}\npreço de bid: {}\npreço de ask: {}\n".format(
d["low"],d["high"],d["bid"],d["ask"])
except:
message="impossivel alcançar servidor {}".format(self.external_files.dollar_server)
return message
def stock_price(self,*args): #metodo que busca preço de ação por palavra chave
if len(args)!=1:
return "para ver o preço de ações deve ser passado o nome de uma \
exemplo: \\veracao AAPL"
h=HttpRequest()
try:
temp= h.make_request(self.external_files.stock_link+args[0],self.external_files.stock_server,port=443)
except:
#caso de erro no servidor
print (self.external_files.stock_server.encode())
return "impossível conectar ao servidor de terceiro\n"
try:
d=json.loads(temp)["price"]
except KeyError: #caso seja uma ação errada
return "Ação {} não encontrada\n".format(args[0])
except json.JSONDecodeError:
return "Recebemos uma mensagem estranha do servidor externo, nossos engenheiros estão trabalhando nisso".format(args[0])
except Exception as e:
print (temp)
return "Problema com o servidor externo\n"
return "preço da ação "+args[0]+": "+ str(d)+"\n" #preço formatado da ação
| 43.458333
| 132
| 0.630393
|
4a0ba8efd418f3fbc22cf4780fdbdbf41d62eaf1
| 6,207
|
py
|
Python
|
autogluon/task/object_detection/dataset/voc.py
|
CharlotteSean/autogluon
|
58c51d4fd5c8abe3db5c509ac94064111cf1198d
|
[
"Apache-2.0"
] | 1
|
2020-01-13T06:17:29.000Z
|
2020-01-13T06:17:29.000Z
|
autogluon/task/object_detection/dataset/voc.py
|
CharlotteSean/autogluon
|
58c51d4fd5c8abe3db5c509ac94064111cf1198d
|
[
"Apache-2.0"
] | null | null | null |
autogluon/task/object_detection/dataset/voc.py
|
CharlotteSean/autogluon
|
58c51d4fd5c8abe3db5c509ac94064111cf1198d
|
[
"Apache-2.0"
] | null | null | null |
"""Pascal VOC object detection dataset."""
from __future__ import absolute_import
from __future__ import division
import os
import warnings
import numpy as np
import glob
try:
import xml.etree.cElementTree as ET
except ImportError:
import xml.etree.ElementTree as ET
import mxnet as mx
from gluoncv.data.base import VisionDataset
from ....core import *
from .base import DatasetBase
import autogluon as ag
from gluoncv import data as gdata
from gluoncv.utils.metrics.voc_detection import VOC07MApMetric
class CustomVOCDetectionBase(gdata.VOCDetection):
"""custom Dataset which follows VOC protocol.
Parameters
----------
class: tuple of classes, default None
reuse the weights if the corresponding class appears in the pretrained model,
otherwise, randomly initialize the weights for new categories.
root : str, default '~/mxnet/datasets/voc'
Path to folder storing the dataset.
splits : list of tuples, default ((2007, 'trainval'), (2012, 'trainval'))
List of combinations of (year, name)
For years, candidates can be: 2007, 2012.
For names, candidates can be: 'train', 'val', 'trainval', 'test'.
transform : callable, default None
A function that takes data and label and transforms them. Refer to
:doc:`./transforms` for examples.
A transform function for object detection should take label into consideration,
because any geometric modification will require label to be modified.
index_map : dict, default None
In default, the 20 classes are mapped into indices from 0 to 19. We can
customize it by providing a str to int dict specifying how to map class
names to indices. Use by advanced users only, when you want to swap the orders
of class labels.
preload_label : bool, default True
If True, then parse and load all labels into memory during
initialization. It often accelerate speed but require more memory
usage. Typical preloaded labels took tens of MB. You only need to disable it
when your dataset is extremely large.
"""
def __init__(self, classes=None, root=os.path.join('~', '.mxnet', 'datasets', 'voc'),
splits=((2007, 'trainval'), (2012, 'trainval')),
transform=None, index_map=None, preload_label=True):
# update classes
if classes:
self._set_class(classes)
super(CustomVOCDetectionBase, self).__init__(root=root,
splits=splits,
transform=transform,
index_map=index_map,
preload_label=False),
self._items_new = [self._items[each_id] for each_id in range(len(self._items)) if self._check_valid(each_id) ]
self._items = self._items_new
self._label_cache = self._preload_labels() if preload_label else None
@classmethod
def _set_class(cls, classes):
cls.CLASSES = classes
def _load_items(self, splits):
"""Load individual image indices from splits."""
ids = []
for subfolder, name in splits:
root = os.path.join(self._root, subfolder) if subfolder else self._root
lf = os.path.join(root, 'ImageSets', 'Main', name + '.txt')
with open(lf, 'r') as f:
ids += [(root, line.strip()) for line in f.readlines()]
return ids
def _check_valid(self, idx):
"""Parse xml file and return labels."""
img_id = self._items[idx]
anno_path = self._anno_path.format(*img_id)
root = ET.parse(anno_path).getroot()
size = root.find('size')
width = float(size.find('width').text)
height = float(size.find('height').text)
if idx not in self._im_shapes:
# store the shapes for later usage
self._im_shapes[idx] = (width, height)
label = []
for obj in root.iter('object'):
try:
difficult = int(obj.find('difficult').text)
except ValueError:
difficult = 0
cls_name = obj.find('name').text.strip().lower()
if cls_name not in self.classes:
continue
cls_id = self.index_map[cls_name]
xml_box = obj.find('bndbox')
xmin = (float(xml_box.find('xmin').text) - 1)
ymin = (float(xml_box.find('ymin').text) - 1)
xmax = (float(xml_box.find('xmax').text) - 1)
ymax = (float(xml_box.find('ymax').text) - 1)
if not ((0 <= xmin < width) and (0 <= ymin < height) \
and (xmin < xmax <= width) and (ymin < ymax <= height)):
return False
return True
@obj()
class CustomVOCDetection():
def __init__(self, root, splits, name, classes, **kwargs):
super().__init__()
self.root = root
# search classes from gt files for custom dataset
if not (classes or name):
classes = self.generate_gt()
self.dataset = CustomVOCDetectionBase(classes=classes,
root=root,
splits=splits)
self.metric = VOC07MApMetric(iou_thresh=0.5, class_names=self.dataset.classes)
def get_dataset_and_metric(self):
return (self.dataset, self.metric)
def get_classes(self):
return self.dataset.classes
def generate_gt(self):
classes = []
all_xml = glob.glob( os.path.join(self.root, 'Annotations', '*.xml') )
for each_xml_file in all_xml:
tree = ET.parse(each_xml_file)
root = tree.getroot()
for child in root:
if child.tag=='object':
for item in child:
if item.tag=='name':
object_name = item.text
if object_name not in classes:
classes.append(object_name)
classes = sorted(classes)
return classes
| 39.535032
| 118
| 0.588207
|
4a0ba92f65375fa3d074defe7768f00fa675dc21
| 2,705
|
py
|
Python
|
ebl/tests/transliteration/test_markup.py
|
ElectronicBabylonianLiterature/ebl-api
|
aef627b81abdcc6bca62c394096f3055c5a8de83
|
[
"MIT"
] | 4
|
2020-04-12T14:24:51.000Z
|
2020-10-15T15:48:15.000Z
|
ebl/tests/transliteration/test_markup.py
|
ElectronicBabylonianLiterature/ebl-api
|
aef627b81abdcc6bca62c394096f3055c5a8de83
|
[
"MIT"
] | 200
|
2019-12-04T09:53:20.000Z
|
2022-03-30T20:11:31.000Z
|
ebl/tests/transliteration/test_markup.py
|
ElectronicBabylonianLiterature/ebl-api
|
aef627b81abdcc6bca62c394096f3055c5a8de83
|
[
"MIT"
] | 1
|
2021-09-06T16:22:39.000Z
|
2021-09-06T16:22:39.000Z
|
from typing import Sequence
import pytest
from ebl.bibliography.domain.reference import Reference, ReferenceType, BibliographyId
from ebl.transliteration.domain.language import Language
from ebl.transliteration.domain.markup import (
BibliographyPart,
EmphasisPart,
LanguagePart,
MarkupPart,
StringPart,
rstrip,
title_case,
to_title,
)
from ebl.transliteration.domain.sign_tokens import Divider, Reading
PUNCTUATION = ";,:.-–—"
TEXT = "sed nec tortor varius, iaculis."
LANGUAGE_PART = LanguagePart(
Language.AKKADIAN, [Reading.of_name("kur"), Divider.of(":")]
)
BIBLIOGRAPHY_PART = BibliographyPart(
Reference(BibliographyId("1"), ReferenceType.DISCUSSION, TEXT + PUNCTUATION)
)
@pytest.mark.parametrize( # pyre-ignore[56]
"part,expected",
[
(
StringPart(f"{PUNCTUATION}A{PUNCTUATION}A{PUNCTUATION}"),
StringPart(f"{PUNCTUATION}A{PUNCTUATION}A"),
),
(
EmphasisPart(f"{PUNCTUATION}A{PUNCTUATION}A{PUNCTUATION}"),
EmphasisPart(f"{PUNCTUATION}A{PUNCTUATION}A"),
),
(LANGUAGE_PART, LANGUAGE_PART),
(BIBLIOGRAPHY_PART, BIBLIOGRAPHY_PART),
],
)
def test_part_rstrip(part: MarkupPart, expected: MarkupPart) -> None:
assert part.rstrip() == expected
@pytest.mark.parametrize( # pyre-ignore[56]
"part,expected",
[
(StringPart(TEXT), StringPart(TEXT.title())),
(EmphasisPart(TEXT), EmphasisPart(TEXT.title())),
(LANGUAGE_PART, LANGUAGE_PART),
(BIBLIOGRAPHY_PART, BIBLIOGRAPHY_PART),
],
)
def test_part_title_case(part: MarkupPart, expected: MarkupPart) -> None:
assert part.title_case() == expected
@pytest.mark.parametrize( # pyre-ignore[56]
"parts,expected",
[
(tuple(), tuple()),
([StringPart("foo--")], (StringPart("foo"),)),
(
[StringPart("foo--"), StringPart("foo--")],
(StringPart("foo--"), StringPart("foo")),
),
],
)
def test_rstrip(parts: Sequence[MarkupPart], expected: Sequence[MarkupPart]) -> None:
assert rstrip(parts) == expected
@pytest.mark.parametrize( # pyre-ignore[56]
"parts,expected",
[
(tuple(), tuple()),
(
[StringPart("foo bar")],
(StringPart("Foo Bar"),),
),
],
)
def test_title_case(
parts: Sequence[MarkupPart], expected: Sequence[MarkupPart]
) -> None:
assert title_case(parts) == expected
@pytest.mark.parametrize( # pyre-ignore[56]
"parts",
[
tuple(),
[StringPart("foo-- bar--")],
],
)
def test_to_title(parts: Sequence[MarkupPart]) -> None:
assert to_title(parts) == title_case(rstrip(parts))
| 26.782178
| 86
| 0.634011
|
4a0ba98bc34623694e532c8beec5bbc165a8fccb
| 1,179
|
py
|
Python
|
Cantmera/screen.py
|
ullrichd21/CantmeraOS
|
d17a6e918132e7f19045e710d1b278779fd22c42
|
[
"MIT"
] | null | null | null |
Cantmera/screen.py
|
ullrichd21/CantmeraOS
|
d17a6e918132e7f19045e710d1b278779fd22c42
|
[
"MIT"
] | null | null | null |
Cantmera/screen.py
|
ullrichd21/CantmeraOS
|
d17a6e918132e7f19045e710d1b278779fd22c42
|
[
"MIT"
] | null | null | null |
#!/usr/bin/env python
import board as board
import busio
import digitalio
# Import the SSD1306 module.
import adafruit_ssd1306
import time
class Screen():
def __init__(self):
time.sleep(5) # Sleep and wait for screen to be ready!
# init SPI
spi = busio.SPI(board.SCLK, MOSI=board.MOSI)
reset_pin = digitalio.DigitalInOut(board.D4) # any pin!
cs_pin = digitalio.DigitalInOut(board.D27) # any pin!
dc_pin = digitalio.DigitalInOut(board.D22) # any pin!
WIDTH = 128
HEIGHT = 32
BORDER = 5
# Create the SSD1306 OLED class.
# The first two parameters are the pixel width and pixel height. Change these
# to the right size for your display!
self.oled = adafruit_ssd1306.SSD1306_SPI(WIDTH, HEIGHT, spi, dc_pin, reset_pin, cs_pin)
self.clear()
self.oled.show()
def display(self, image):
print(f"Display {image}")
self.clear()
self.oled.image(image)
self.oled.show()
def clear(self):
# Clear display.
self.oled.fill(0)
self.oled.show()
# if __name__ == "__main__":
# main()
| 25.630435
| 95
| 0.610687
|
4a0baa007762c7d6d59f8b431fc7502b144564b2
| 3,527
|
py
|
Python
|
bot_vk.py
|
Sam1808/Quiz-bots
|
105295619af9f4c83bdeed24879714c8a7070c83
|
[
"MIT"
] | null | null | null |
bot_vk.py
|
Sam1808/Quiz-bots
|
105295619af9f4c83bdeed24879714c8a7070c83
|
[
"MIT"
] | null | null | null |
bot_vk.py
|
Sam1808/Quiz-bots
|
105295619af9f4c83bdeed24879714c8a7070c83
|
[
"MIT"
] | null | null | null |
import logging
import os
import random
import redis
import vk_api as vk
from bot_utils import get_arguments
from bot_utils import get_quiz_qa
from dotenv import load_dotenv
from vk_api.keyboard import VkKeyboard, VkKeyboardColor
from vk_api.longpoll import VkLongPoll, VkEventType
from vk_api.utils import get_random_id
def send_message(event, vk_api, message):
vk_api.messages.send(
user_id=event.user_id,
message=message,
random_id=random.randint(1, 1000)
)
def send_keyboard(event, vk_api):
keyboard = VkKeyboard()
keyboard.add_button('Новый вопрос', color=VkKeyboardColor.POSITIVE)
keyboard.add_button('Сдаться', color=VkKeyboardColor.NEGATIVE)
keyboard.add_line()
keyboard.add_button('Мой счет', color=VkKeyboardColor.PRIMARY)
vk_api.messages.send(
user_id=event.user_id,
random_id=get_random_id(),
keyboard=keyboard.get_keyboard(),
message='Начинаем викторину'
)
def send_new_question(event, vk_api, quiz_qa, redis_connection):
question = random.choice([*quiz_qa])
redis_connection.set(f'vk-{event.user_id}', question)
send_message(event, vk_api, message=f'Вопрос: {question}')
def check_answer(event, vk_api, quiz_qa, redis_connection):
quiz_question = redis_connection.get(f'vk-{event.user_id}')
if quiz_question:
quiz_question = quiz_question.decode('utf-8')
message = 'Неправильно… Попробуешь ещё раз?'
if event.text.lower() in quiz_qa[quiz_question].lower():
message = '''
Правильно! Поздравляю!
Для следующего вопроса нажми «Новый вопрос»'''
send_message(event, vk_api, message)
else:
message = '''
Приветствую! Отправь start для запуска викторины
и нажми кнопку «Новый вопрос»'''
send_message(event, vk_api, message)
def give_up(event, vk_api, quiz_qa, redis_connection):
quiz_question = redis_connection.get(f'vk-{event.user_id}')
if quiz_question:
quiz_question = quiz_question.decode('utf-8')
answer = f'Ответ: {quiz_qa[quiz_question]}'
send_message(event, vk_api, answer)
send_new_question(event, vk_api, quiz_qa, redis_connection)
if __name__ == "__main__":
arguments = get_arguments()
level = logging.DEBUG if arguments.debug else logging.INFO
logging.basicConfig(level=level)
load_dotenv()
vk_token = os.environ['VK-TOKEN']
redis_host = os.environ['REDIS-BASE']
redis_port = os.environ['REDIS-PORT']
redis_password = os.environ['REDIS-PASSWORD']
logging.debug('Open Redis connection')
redis_connection = redis.Redis(
host=redis_host,
port=redis_port,
password=redis_password
)
logging.debug(
'Read questions and answers from files & make QA dictionary'
)
quiz_qa = get_quiz_qa('questions')
logging.debug('Run VK.com bot')
vk_session = vk.VkApi(token=vk_token)
vk_api = vk_session.get_api()
longpoll = VkLongPoll(vk_session)
for event in longpoll.listen():
if event.type == VkEventType.MESSAGE_NEW and event.to_me:
if event.text == 'start':
send_keyboard(event, vk_api)
elif event.text == 'Новый вопрос':
send_new_question(event, vk_api, quiz_qa, redis_connection)
elif event.text == 'Сдаться':
give_up(event, vk_api, quiz_qa, redis_connection)
else:
check_answer(event, vk_api, quiz_qa, redis_connection)
| 32.962617
| 75
| 0.681316
|
4a0baa40b18851f8ab9e7aaec14e9d891789369f
| 101
|
py
|
Python
|
9.py
|
tarandeepgill2002/pythonAcadview
|
0f1be688a7588b518fe52a05dd1b9ec78b46bb83
|
[
"MIT"
] | null | null | null |
9.py
|
tarandeepgill2002/pythonAcadview
|
0f1be688a7588b518fe52a05dd1b9ec78b46bb83
|
[
"MIT"
] | null | null | null |
9.py
|
tarandeepgill2002/pythonAcadview
|
0f1be688a7588b518fe52a05dd1b9ec78b46bb83
|
[
"MIT"
] | null | null | null |
name=input("enter the name:")
age=int(input("enter the age:"))
print("name:",name)
print("age:",age)
| 20.2
| 32
| 0.663366
|
4a0baaca98c56228b1b228c954682a863557e36c
| 1,819
|
py
|
Python
|
common/common_pytorch/model/srnet_utils/group_index.py
|
ailingzengzzz/Split-and-Recombine-Net
|
1b6285c9f5b46140832e7e4d24e8e5a7dbb24234
|
[
"Apache-2.0"
] | 8
|
2021-07-28T06:57:08.000Z
|
2022-02-17T11:54:10.000Z
|
common/common_pytorch/model/srnet_utils/group_index.py
|
ailingzengzzz/Split-and-Recombine-Net
|
1b6285c9f5b46140832e7e4d24e8e5a7dbb24234
|
[
"Apache-2.0"
] | 4
|
2021-10-09T03:13:46.000Z
|
2021-12-28T06:38:52.000Z
|
common/common_pytorch/model/srnet_utils/group_index.py
|
ailingzengzzz/Split-and-Recombine-Net
|
1b6285c9f5b46140832e7e4d24e8e5a7dbb24234
|
[
"Apache-2.0"
] | null | null | null |
import torch
def get_input(group):
if group == 2:
print('Now group is:', group)
conv_seq = [range(0, 16), [0, 1, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33]]
final_outc = 55
elif group == 3:
print('Now group is:', group)
conv_seq = [range(0, 14), [0, 1, 14, 15, 16, 17, 18, 19, 20, 21],
[0, 1, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33]]
final_outc = 58
elif group == 5:
print('Now group is:', group)
conv_seq = [range(0, 8), [0, 1, 8, 9, 10, 11, 12, 13], [0, 1, 14, 15, 16, 17, 18, 19, 20, 21],
[0, 1, 22, 23, 24, 25, 26, 27], [0, 1, 28, 29, 30, 31, 32, 33]]
final_outc = 64
elif group == 1:
print('Now group is:', group)
conv_seq = [range(0, 34)]
final_outc = 51
else:
raise KeyError('Invalid group number!')
return conv_seq, final_outc
# #
def shrink_output(x):
num_joints_out = x.shape[-1]
pose_dim = 3 # means [X,Y,Z]: three values
if num_joints_out == 1:
x = x[:, :, :pose_dim]
elif num_joints_out == 64: #Group = 5
x = torch.cat([x[:, :, :(4*pose_dim)], x[:, :, (5*pose_dim):(8*pose_dim)], x[:, :, (9*pose_dim):(13*pose_dim)], x[:, :, (14*pose_dim):(17*pose_dim)], x[:, :, (18*pose_dim):(21*pose_dim)]], dim=-1)
elif num_joints_out == 58: #Group = 3
x = torch.cat([x[:, :, :(7*pose_dim)], x[:, :, (8*pose_dim):(12*pose_dim)], x[:, :, (13*pose_dim):(19*pose_dim)]], dim=-1)
elif num_joints_out == 55: #Group = 2
x = torch.cat([x[:, :, :(8*pose_dim)], x[:, :, (9*pose_dim):(18*pose_dim)]], dim=-1)
elif num_joints_out == 52: #Group = 1
x = x[:, :, :(17*pose_dim)]
else:
raise KeyError('Invalid outputs!')
return x
| 39.543478
| 204
| 0.502474
|
4a0bab0d05f61561c91f92cc447608dc8bd2170b
| 2,273
|
py
|
Python
|
src/py/flwr/server/strategy/fast_and_slow_test.py
|
sandracl72/flower
|
bb7f6e2e1f52753820784d262618113b4e7ebc42
|
[
"Apache-2.0"
] | null | null | null |
src/py/flwr/server/strategy/fast_and_slow_test.py
|
sandracl72/flower
|
bb7f6e2e1f52753820784d262618113b4e7ebc42
|
[
"Apache-2.0"
] | null | null | null |
src/py/flwr/server/strategy/fast_and_slow_test.py
|
sandracl72/flower
|
bb7f6e2e1f52753820784d262618113b4e7ebc42
|
[
"Apache-2.0"
] | null | null | null |
# Copyright 2020 Adap GmbH. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for Fast-and-Slow strategy."""
import unittest
from ...server.strategy import fast_and_slow
# pylint: disable=no-self-use,missing-class-docstring,missing-function-docstring
class FastAndSlowTestCase(unittest.TestCase):
def test_fast_round(self) -> None:
# Prepare
values = [
# 1 fast, 1 slow
(0, 1, 1, True),
(1, 1, 1, False),
(2, 1, 1, True),
# 2 fast, 1 slow
(0, 2, 1, True),
(1, 2, 1, True),
(2, 2, 1, False),
(3, 2, 1, True),
(4, 2, 1, True),
(5, 2, 1, False),
# 1 fast, 2 slow
(0, 1, 2, True),
(1, 1, 2, False),
(2, 1, 2, False),
(3, 1, 2, True),
(4, 1, 2, False),
(5, 1, 2, False),
# 3 fast, 2 slow
(0, 3, 2, True),
(1, 3, 2, True),
(2, 3, 2, True),
(3, 3, 2, False),
(4, 3, 2, False),
(5, 3, 2, True),
]
# Execute and assert
for rnd, r_fast, r_slow, expected in values:
actual = fast_and_slow.is_fast_round(rnd, r_fast, r_slow)
assert actual == expected
def test_next_timeout_below_max(self) -> None:
# Prepare
durations = [15.6, 13.1, 18.7]
percentile = 0.5
expected = 16
# Execute
actual = fast_and_slow.next_timeout(durations, percentile)
# Assert
assert actual == expected
if __name__ == "__main__":
unittest.main(verbosity=2)
| 30.716216
| 80
| 0.527497
|
4a0bab4a0c246080e3222d0fb70a551eee1fbdac
| 10,361
|
py
|
Python
|
python_modules/dagster/dagster/utils/test/schedule_storage.py
|
basilvetas/dagster
|
b08f5534a0b0277dab38cb7b6a46d324e94b8940
|
[
"Apache-2.0"
] | 2
|
2021-06-21T17:50:26.000Z
|
2021-06-21T19:14:23.000Z
|
python_modules/dagster/dagster/utils/test/schedule_storage.py
|
basilvetas/dagster
|
b08f5534a0b0277dab38cb7b6a46d324e94b8940
|
[
"Apache-2.0"
] | null | null | null |
python_modules/dagster/dagster/utils/test/schedule_storage.py
|
basilvetas/dagster
|
b08f5534a0b0277dab38cb7b6a46d324e94b8940
|
[
"Apache-2.0"
] | 1
|
2021-08-18T17:21:57.000Z
|
2021-08-18T17:21:57.000Z
|
import sys
import time
import pytest
from dagster import DagsterInvariantViolationError
from dagster.core.code_pointer import ModuleCodePointer
from dagster.core.origin import RepositoryPythonOrigin, SchedulePythonOrigin
from dagster.core.scheduler import ScheduleState, ScheduleStatus
from dagster.core.scheduler.scheduler import ScheduleTickData, ScheduleTickStatus
from dagster.seven import get_current_datetime_in_utc, get_timestamp_from_utc_datetime
from dagster.utils.error import SerializableErrorInfo
class TestScheduleStorage:
"""
You can extend this class to easily run these set of tests on any schedule storage. When extending,
you simply need to override the `schedule_storage` fixture and return your implementation of
`ScheduleStorage`.
For example:
```
TestScheduleStorage.__test__ = False
class TestMyStorageImplementation(TestScheduleStorage):
__test__ = True
@pytest.fixture(scope='function', name='storage')
def schedule_storage(self): # pylint: disable=arguments-differ
return MyStorageImplementation()
```
"""
@pytest.fixture(name="storage", params=[])
def schedule_storage(self, request):
with request.param() as s:
yield s
@staticmethod
def fake_repo_target():
return RepositoryPythonOrigin(sys.executable, ModuleCodePointer("fake", "fake"))
@classmethod
def build_schedule(
cls, schedule_name, cron_schedule, status=ScheduleStatus.STOPPED,
):
fake_target = SchedulePythonOrigin(schedule_name, cls.fake_repo_target())
return ScheduleState(fake_target, status, cron_schedule, start_timestamp=None)
def test_basic_schedule_storage(self, storage):
assert storage
schedule = self.build_schedule("my_schedule", "* * * * *")
storage.add_schedule_state(schedule)
schedules = storage.all_stored_schedule_state(self.fake_repo_target().get_id())
assert len(schedules) == 1
schedule = schedules[0]
assert schedule.name == "my_schedule"
assert schedule.cron_schedule == "* * * * *"
assert schedule.start_timestamp == None
def test_add_multiple_schedules(self, storage):
assert storage
schedule = self.build_schedule("my_schedule", "* * * * *")
schedule_2 = self.build_schedule("my_schedule_2", "* * * * *")
schedule_3 = self.build_schedule("my_schedule_3", "* * * * *")
storage.add_schedule_state(schedule)
storage.add_schedule_state(schedule_2)
storage.add_schedule_state(schedule_3)
schedules = storage.all_stored_schedule_state(self.fake_repo_target().get_id())
assert len(schedules) == 3
assert any(s.name == "my_schedule" for s in schedules)
assert any(s.name == "my_schedule_2" for s in schedules)
assert any(s.name == "my_schedule_3" for s in schedules)
def test_get_schedule_state(self, storage):
assert storage
state = self.build_schedule("my_schedule", "* * * * *")
storage.add_schedule_state(state)
schedule = storage.get_schedule_state(state.schedule_origin_id)
assert schedule.name == "my_schedule"
assert schedule.start_timestamp == None
def test_get_schedule_state_not_found(self, storage):
assert storage
storage.add_schedule_state(self.build_schedule("my_schedule", "* * * * *"))
schedule = storage.get_schedule_state("fake_id")
assert schedule is None
def test_update_schedule(self, storage):
assert storage
schedule = self.build_schedule("my_schedule", "* * * * *")
storage.add_schedule_state(schedule)
now_time = get_current_datetime_in_utc()
new_schedule = schedule.with_status(ScheduleStatus.RUNNING, start_time_utc=now_time)
storage.update_schedule_state(new_schedule)
schedules = storage.all_stored_schedule_state(self.fake_repo_target().get_id())
assert len(schedules) == 1
schedule = schedules[0]
assert schedule.name == "my_schedule"
assert schedule.status == ScheduleStatus.RUNNING
assert schedule.start_timestamp == get_timestamp_from_utc_datetime(now_time)
stopped_schedule = schedule.with_status(ScheduleStatus.STOPPED)
storage.update_schedule_state(stopped_schedule)
schedules = storage.all_stored_schedule_state(self.fake_repo_target().get_id())
assert len(schedules) == 1
schedule = schedules[0]
assert schedule.name == "my_schedule"
assert schedule.status == ScheduleStatus.STOPPED
assert schedule.start_timestamp == None
def test_update_schedule_not_found(self, storage):
assert storage
schedule = self.build_schedule("my_schedule", "* * * * *")
with pytest.raises(DagsterInvariantViolationError):
storage.update_schedule_state(schedule)
def test_delete_schedule_state(self, storage):
assert storage
schedule = self.build_schedule("my_schedule", "* * * * *")
storage.add_schedule_state(schedule)
storage.delete_schedule_state(schedule.schedule_origin_id)
schedules = storage.all_stored_schedule_state(self.fake_repo_target().get_id())
assert len(schedules) == 0
def test_delete_schedule_not_found(self, storage):
assert storage
schedule = self.build_schedule("my_schedule", "* * * * *")
with pytest.raises(DagsterInvariantViolationError):
storage.delete_schedule_state(schedule.schedule_origin_id)
def test_add_schedule_with_same_name(self, storage):
assert storage
schedule = self.build_schedule("my_schedule", "* * * * *")
storage.add_schedule_state(schedule)
with pytest.raises(DagsterInvariantViolationError):
storage.add_schedule_state(schedule)
def build_tick(self, current_time, status=ScheduleTickStatus.STARTED, run_id=None, error=None):
return ScheduleTickData(
"my_schedule", "my_schedule", "* * * * *", current_time, status, run_id, error
)
def test_create_tick(self, storage):
assert storage
current_time = time.time()
tick = storage.create_schedule_tick(self.build_tick(current_time))
assert tick.tick_id == 1
ticks = storage.get_schedule_ticks("my_schedule")
assert len(ticks) == 1
tick = ticks[0]
assert tick.tick_id == 1
assert tick.schedule_name == "my_schedule"
assert tick.cron_schedule == "* * * * *"
assert tick.timestamp == current_time
assert tick.status == ScheduleTickStatus.STARTED
assert tick.run_id == None
assert tick.error == None
def test_update_tick_to_success(self, storage):
assert storage
current_time = time.time()
tick = storage.create_schedule_tick(self.build_tick(current_time))
updated_tick = tick.with_status(ScheduleTickStatus.SUCCESS, run_id="1234")
assert updated_tick.status == ScheduleTickStatus.SUCCESS
storage.update_schedule_tick(updated_tick)
ticks = storage.get_schedule_ticks("my_schedule")
assert len(ticks) == 1
tick = ticks[0]
assert tick.tick_id == 1
assert tick.schedule_name == "my_schedule"
assert tick.cron_schedule == "* * * * *"
assert tick.timestamp == current_time
assert tick.status == ScheduleTickStatus.SUCCESS
assert tick.run_id == "1234"
assert tick.error == None
def test_update_tick_to_skip(self, storage):
assert storage
current_time = time.time()
tick = storage.create_schedule_tick(self.build_tick(current_time))
updated_tick = tick.with_status(ScheduleTickStatus.SKIPPED)
assert updated_tick.status == ScheduleTickStatus.SKIPPED
storage.update_schedule_tick(updated_tick)
ticks = storage.get_schedule_ticks("my_schedule")
assert len(ticks) == 1
tick = ticks[0]
assert tick.tick_id == 1
assert tick.schedule_name == "my_schedule"
assert tick.cron_schedule == "* * * * *"
assert tick.timestamp == current_time
assert tick.status == ScheduleTickStatus.SKIPPED
assert tick.run_id == None
assert tick.error == None
def test_update_tick_to_failure(self, storage):
assert storage
current_time = time.time()
tick = storage.create_schedule_tick(self.build_tick(current_time))
updated_tick = tick.with_status(
ScheduleTickStatus.FAILURE,
error=SerializableErrorInfo(message="Error", stack=[], cls_name="TestError"),
)
assert updated_tick.status == ScheduleTickStatus.FAILURE
storage.update_schedule_tick(updated_tick)
ticks = storage.get_schedule_ticks("my_schedule")
assert len(ticks) == 1
tick = ticks[0]
assert tick.tick_id == 1
assert tick.schedule_name == "my_schedule"
assert tick.cron_schedule == "* * * * *"
assert tick.timestamp == current_time
assert tick.status == ScheduleTickStatus.FAILURE
assert tick.run_id == None
assert tick.error == SerializableErrorInfo(message="Error", stack=[], cls_name="TestError")
def test_get_schedule_stats(self, storage):
assert storage
current_time = time.time()
error = SerializableErrorInfo(message="Error", stack=[], cls_name="TestError")
# Create ticks
for x in range(2):
storage.create_schedule_tick(self.build_tick(current_time))
for x in range(3):
storage.create_schedule_tick(
self.build_tick(current_time, ScheduleTickStatus.SUCCESS, run_id=str(x)),
)
for x in range(4):
storage.create_schedule_tick(self.build_tick(current_time, ScheduleTickStatus.SKIPPED),)
for x in range(5):
storage.create_schedule_tick(
self.build_tick(current_time, ScheduleTickStatus.FAILURE, error=error),
)
stats = storage.get_schedule_tick_stats("my_schedule")
assert stats.ticks_started == 2
assert stats.ticks_succeeded == 3
assert stats.ticks_skipped == 4
assert stats.ticks_failed == 5
| 36.227273
| 103
| 0.676383
|
4a0bada2fbe2392bda5d2388a8ad3a7459de7d0d
| 3,431
|
py
|
Python
|
src/md_docs/plugins/nav_plugins.py
|
TroyWilliams3687/md_docs
|
f26d440fb77e1e06bb9a3845a3bf75f8ba979a4d
|
[
"MIT"
] | null | null | null |
src/md_docs/plugins/nav_plugins.py
|
TroyWilliams3687/md_docs
|
f26d440fb77e1e06bb9a3845a3bf75f8ba979a4d
|
[
"MIT"
] | null | null | null |
src/md_docs/plugins/nav_plugins.py
|
TroyWilliams3687/md_docs
|
f26d440fb77e1e06bb9a3845a3bf75f8ba979a4d
|
[
"MIT"
] | null | null | null |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# -----------
# SPDX-License-Identifier: MIT
# Copyright (c) 2021 Troy Williams
# uuid: 52b7bf58-ceb3-11eb-9734-2d229bf17d60
# author: Troy Williams
# email: troy.williams@bluebill.net
# date: 2021-06-16
# -----------
"""
Define the default Navigation plugins included with the system.
"""
# ------------
# System Modules - Included with Python
import logging
import csv
from pathlib import Path
# ------------
# 3rd Party - From pip
# ------------
# Custom Modules
from ..md_docs.common import relative_path
from ..md_docs.document import MarkdownDocument
from ..tools.plugins import NavigationPlugin, register
# -------------
# Logging
log = logging.getLogger(__name__)
# -------------
@register(name="CSV Navigation")
class BasicCSV(NavigationPlugin):
"""
This plugin will take all of the MarkdownDocument objects and
allow the build system to construct a CSV file from it:
```
UUID, Title, Path
03bd16cc-ceb9-11eb-9734-2d229bf17d60, "How to load a wireframe from DXF", designer/import/dxf.html
1a6b59ec-ceb9-11eb-9734-2d229bf17d60, "Isosurface from Stope", designer/issurface/stope.html
```
The components will be extracted from the document YAML block and
the file path.
"""
def __call__(
self,
document_root=None,
output=None,
documents=None,
**kwargs,
):
"""
Given the root path and a list of MarkdownDocument objects,
construct a CSV file containing the UUID, the document title
and relative path to the HTML file
# Parameters
document_root:Path
- The valid path to the root of the MarkdownDocument folder
- It can be used to create relative paths from full paths
output:Path
- The valid path to the location that file should be written.
- This is the folder where the plugin will write the navigation file too
documents:iterable(MarkdownDocument)
- The list of MarkdownDocument objects that will be used to
construct the navigation document.
# Return
None - The file will be written by the plugin to the root
folder.
"""
log.debug("Entering `BasicCSV`")
csv_file = output / 'url_map.csv'
log.debug(f"{csv_file=}")
headers = ['uuid', 'title', 'path']
with csv_file.open("w", encoding="utf-8") as fo:
writer = csv.DictWriter(fo, fieldnames=headers)
writer.writeheader()
for md in documents:
uuid = ''
title = ''
if md.yaml_block is None:
log.info(f'YAML Block MISSING - Skipping - {md.filename}')
elif 'UUID' not in md.yaml_block:
log.info(f'YAML Block KEY MISSING - UUID - Skipping - {md.filename}')
else:
uuid = md.yaml_block.get('UUID', '')
title = md.yaml_block.get('title', '')
row = {
"uuid":uuid,
'title':title,
'path':relative_path(md.filename.parent, document_root) / f'{md.filename.stem}.html',
}
log.debug(f"Writing: {md.filename}")
writer.writerow(row)
log.debug("BasicCSV - Completed.")
| 25.227941
| 105
| 0.582629
|
4a0bae2d4f176adc16a28fbf4e54b28eeb6d0607
| 4,716
|
py
|
Python
|
src/sentry/integrations/jira_server/client.py
|
conan25216/sentry
|
fe38ab19fb096688140b2065da0e45fa26762200
|
[
"BSD-3-Clause"
] | 1
|
2018-12-04T12:57:00.000Z
|
2018-12-04T12:57:00.000Z
|
src/sentry/integrations/jira_server/client.py
|
conan25216/sentry
|
fe38ab19fb096688140b2065da0e45fa26762200
|
[
"BSD-3-Clause"
] | null | null | null |
src/sentry/integrations/jira_server/client.py
|
conan25216/sentry
|
fe38ab19fb096688140b2065da0e45fa26762200
|
[
"BSD-3-Clause"
] | null | null | null |
from __future__ import absolute_import
import jwt
from django.core.urlresolvers import reverse
from oauthlib.oauth1 import SIGNATURE_RSA
from requests_oauthlib import OAuth1
from six.moves.urllib.parse import parse_qsl
from sentry.integrations.client import ApiClient, ApiError
from sentry.utils.http import absolute_uri
class JiraServerSetupClient(ApiClient):
"""
Client for making requests to JiraServer to follow OAuth1 flow.
"""
request_token_url = u'{}/plugins/servlet/oauth/request-token'
access_token_url = u'{}/plugins/servlet/oauth/access-token'
authorize_url = u'{}/plugins/servlet/oauth/authorize?oauth_token={}'
def __init__(self, base_url, consumer_key, private_key, verify_ssl=True):
self.base_url = base_url
self.consumer_key = consumer_key
self.private_key = private_key
self.verify_ssl = verify_ssl
def get_request_token(self):
"""
Step 1 of the oauth flow.
Get a request token that we can have the user verify.
"""
url = self.request_token_url.format(self.base_url)
resp = self.post(url, allow_text=True)
return dict(parse_qsl(resp.text))
def get_authorize_url(self, request_token):
"""
Step 2 of the oauth flow.
Get a URL that the user can verify our request token at.
"""
return self.authorize_url.format(self.base_url, request_token['oauth_token'])
def get_access_token(self, request_token, verifier):
"""
Step 3 of the oauth flow.
Use the verifier and request token from step 1 to get an access token.
"""
if not verifier:
raise ApiError('Missing OAuth token verifier')
auth = OAuth1(
client_key=self.consumer_key,
resource_owner_key=request_token['oauth_token'],
resource_owner_secret=request_token['oauth_token_secret'],
verifier=verifier,
rsa_key=self.private_key,
signature_method=SIGNATURE_RSA,
signature_type='auth_header')
url = self.access_token_url.format(self.base_url)
resp = self.post(url, auth=auth, allow_text=True)
return dict(parse_qsl(resp.text))
def create_issue_webhook(self, external_id, secret, credentials):
auth = OAuth1(
client_key=credentials['consumer_key'],
rsa_key=credentials['private_key'],
resource_owner_key=credentials['access_token'],
resource_owner_secret=credentials['access_token_secret'],
signature_method=SIGNATURE_RSA,
signature_type='auth_header')
# Create a JWT token that we can add to the webhook URL
# so we can locate the matching integration later.
token = jwt.encode({'id': external_id}, secret)
path = reverse(
'sentry-extensions-jiraserver-issue-updated',
kwargs={'token': token})
data = {
'name': 'Sentry Issue Sync',
'url': absolute_uri(path),
'events': ['jira:issue_created', 'jira:issue_updated']
}
return self.post('/rest/webhooks/1.0/webhook', auth=auth, data=data)
def request(self, *args, **kwargs):
"""
Add OAuth1 RSA signatures.
"""
if 'auth' not in kwargs:
kwargs['auth'] = OAuth1(
client_key=self.consumer_key,
rsa_key=self.private_key,
signature_method=SIGNATURE_RSA,
signature_type='auth_header')
return self._request(*args, **kwargs)
class JiraServer(object):
"""
Contains the jira-server specifics that a JiraClient needs
in order to communicate with jira
"""
def __init__(self, credentials):
self.credentials = credentials
@property
def cache_prefix(self):
return 'sentry-jira-server:'
def request_hook(self, method, path, data, params, **kwargs):
"""
Used by Jira Client to apply the jira-server authentication
Which is RSA signed OAuth1
"""
if 'auth' not in kwargs:
kwargs['auth'] = OAuth1(
client_key=self.credentials['consumer_key'],
rsa_key=self.credentials['private_key'],
resource_owner_key=self.credentials['access_token'],
resource_owner_secret=self.credentials['access_token_secret'],
signature_method=SIGNATURE_RSA,
signature_type='auth_header')
request_spec = kwargs.copy()
request_spec.update(dict(
method=method,
path=path,
data=data,
params=params))
return request_spec
| 35.727273
| 85
| 0.634012
|
4a0bae8e8115c5648e562ca45338a61300be4e73
| 513
|
py
|
Python
|
confirmation/management/commands/cleanupconfirmation.py
|
dehnert/zulip
|
f5935e81c7cf2f11ff4ccfcd31d2a1061b8d7ff5
|
[
"Apache-2.0"
] | 1
|
2017-07-27T19:49:12.000Z
|
2017-07-27T19:49:12.000Z
|
confirmation/management/commands/cleanupconfirmation.py
|
dehnert/zulip
|
f5935e81c7cf2f11ff4ccfcd31d2a1061b8d7ff5
|
[
"Apache-2.0"
] | 9
|
2021-02-08T20:22:36.000Z
|
2022-03-11T23:22:45.000Z
|
confirmation/management/commands/cleanupconfirmation.py
|
tobby2002/zulip
|
66e7c455759f9368bae16b9a604cf63f8e3524cd
|
[
"Apache-2.0"
] | 1
|
2021-04-09T05:50:23.000Z
|
2021-04-09T05:50:23.000Z
|
# -*- coding: utf-8 -*-
# Copyright: (c) 2008, Jarek Zgoda <jarek.zgoda@gmail.com>
__revision__ = '$Id: cleanupconfirmation.py 5 2008-11-18 09:10:12Z jarek.zgoda $'
from typing import Any
from django.core.management.base import NoArgsCommand
from confirmation.models import Confirmation
class Command(NoArgsCommand):
help = 'Delete expired confirmations from database'
def handle_noargs(self, **options):
# type: (**Any) -> None
Confirmation.objects.delete_expired_confirmations()
| 25.65
| 81
| 0.723197
|
4a0bae9f39e2d50681dd4a143bde93fac8483002
| 799
|
py
|
Python
|
pedantic/decorators/fn_deco_deprecated.py
|
LostInDarkMath/Pedantic-python-decorators
|
32ed54c9593e80f63c0499093cb07847d8a5e1df
|
[
"Apache-2.0"
] | 15
|
2020-09-10T13:06:53.000Z
|
2021-12-21T12:39:18.000Z
|
pedantic/decorators/fn_deco_deprecated.py
|
LostInDarkMath/Pedantic-python-decorators
|
32ed54c9593e80f63c0499093cb07847d8a5e1df
|
[
"Apache-2.0"
] | 39
|
2020-08-12T12:38:03.000Z
|
2022-03-22T18:09:48.000Z
|
pedantic/decorators/fn_deco_deprecated.py
|
LostInDarkMath/pedantic-python-decorators
|
66865a958a36440b48e790f22ea42d2beb725b16
|
[
"Apache-2.0"
] | null | null | null |
from functools import wraps
from typing import Any
from pedantic.constants import F, ReturnType
from pedantic.helper_methods import _raise_warning
def deprecated(func: F) -> F:
"""
Use this decorator to mark a function as deprecated. It will raise a warning when the function is called.
Example:
>>> @deprecated
... def my_function(a, b, c):
... pass
>>> my_function(5, 4, 3)
"""
@wraps(func)
def wrapper(*args: Any, **kwargs: Any) -> ReturnType:
_raise_warning(msg=f'Call to deprecated function {func.__qualname__}.', category=DeprecationWarning)
return func(*args, **kwargs)
return wrapper
if __name__ == "__main__":
import doctest
doctest.testmod(verbose=False, optionflags=doctest.ELLIPSIS)
| 26.633333
| 113
| 0.660826
|
4a0baf3f69fb6c6d859f1c2ecc89d4c8b0f89c73
| 8,444
|
py
|
Python
|
examples/contrib/gp/sv-dkl.py
|
ciguaran/pyro
|
2dfa8da0dd400c3712768385d8306848e93dab9a
|
[
"Apache-2.0"
] | 1
|
2020-10-02T20:17:38.000Z
|
2020-10-02T20:17:38.000Z
|
examples/contrib/gp/sv-dkl.py
|
Ezecc/pyro
|
11a96cde05756def826c232d76f9cff66f6e6d4f
|
[
"Apache-2.0"
] | 1
|
2020-05-12T16:26:21.000Z
|
2020-05-12T17:23:13.000Z
|
examples/contrib/gp/sv-dkl.py
|
Ezecc/pyro
|
11a96cde05756def826c232d76f9cff66f6e6d4f
|
[
"Apache-2.0"
] | null | null | null |
# Copyright (c) 2017-2019 Uber Technologies, Inc.
# SPDX-License-Identifier: Apache-2.0
"""
An example to use Pyro Gaussian Process module to classify MNIST and binary MNIST.
Follow the idea from reference [1], we will combine a convolutional neural network
(CNN) with a RBF kernel to create a "deep" kernel:
>>> deep_kernel = gp.kernels.Warping(rbf, iwarping_fn=cnn)
SparseVariationalGP model allows us train the data in mini-batch (time complexity
scales linearly to the number of data points).
Note that the implementation here is different from [1]. There the authors
use CNN as a feature extraction layer, then add a Gaussian Process layer on the
top of CNN. Hence, their inducing points lie in the space of extracted features.
Here we join CNN module and RBF kernel together to make it a deep kernel.
Hence, our inducing points lie in the space of original images.
After 16 epochs with default hyperparameters, the accuaracy of 10-class MNIST
is 98.45% and the accuaracy of binary MNIST is 99.41%.
Reference:
[1] Stochastic Variational Deep Kernel Learning
Andrew G. Wilson, Zhiting Hu, Ruslan R. Salakhutdinov, Eric P. Xing
"""
# Code adapted from https://github.com/pytorch/examples/tree/master/mnist
import argparse
import time
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import transforms
import pyro
import pyro.contrib.gp as gp
import pyro.infer as infer
from pyro.contrib.examples.util import get_data_loader, get_data_directory
class CNN(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(1, 10, kernel_size=5)
self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
self.fc1 = nn.Linear(320, 50)
self.fc2 = nn.Linear(50, 10)
def forward(self, x):
x = F.relu(F.max_pool2d(self.conv1(x), 2))
x = F.relu(F.max_pool2d(self.conv2(x), 2))
x = x.view(-1, 320)
x = F.relu(self.fc1(x))
x = self.fc2(x)
return x
def train(args, train_loader, gpmodule, optimizer, loss_fn, epoch):
for batch_idx, (data, target) in enumerate(train_loader):
if args.cuda:
data, target = data.cuda(), target.cuda()
if args.binary:
target = (target % 2).float() # convert numbers 0->9 to 0 or 1
gpmodule.set_data(data, target)
optimizer.zero_grad()
loss = loss_fn(gpmodule.model, gpmodule.guide)
loss.backward()
optimizer.step()
batch_idx = batch_idx + 1
if batch_idx % args.log_interval == 0:
print("Train Epoch: {:2d} [{:5d}/{} ({:2.0f}%)]\tLoss: {:.6f}"
.format(epoch, batch_idx * len(data), len(train_loader.dataset),
100. * batch_idx / len(train_loader), loss))
def test(args, test_loader, gpmodule):
correct = 0
for data, target in test_loader:
if args.cuda:
data, target = data.cuda(), target.cuda()
if args.binary:
target = (target % 2).float() # convert numbers 0->9 to 0 or 1
# get prediction of GP model on new data
f_loc, f_var = gpmodule(data)
# use its likelihood to give prediction class
pred = gpmodule.likelihood(f_loc, f_var)
# compare prediction and target to count accuracy
correct += pred.eq(target).long().cpu().sum().item()
print("\nTest set: Accuracy: {}/{} ({:.2f}%)\n"
.format(correct, len(test_loader.dataset), 100. * correct / len(test_loader.dataset)))
def main(args):
data_dir = args.data_dir if args.data_dir is not None else get_data_directory(__file__)
train_loader = get_data_loader(dataset_name='MNIST',
data_dir=data_dir,
batch_size=args.batch_size,
dataset_transforms=[transforms.Normalize((0.1307,), (0.3081,))],
is_training_set=True,
shuffle=True)
test_loader = get_data_loader(dataset_name='MNIST',
data_dir=data_dir,
batch_size=args.test_batch_size,
dataset_transforms=[transforms.Normalize((0.1307,), (0.3081,))],
is_training_set=False,
shuffle=False)
if args.cuda:
train_loader.num_workers = 1
test_loader.num_workers = 1
cnn = CNN()
# Create deep kernel by warping RBF with CNN.
# CNN will transform a high dimension image into a low dimension 2D tensors for RBF kernel.
# This kernel accepts inputs are inputs of CNN and gives outputs are covariance matrix of RBF
# on outputs of CNN.
rbf = gp.kernels.RBF(input_dim=10, lengthscale=torch.ones(10))
deep_kernel = gp.kernels.Warping(rbf, iwarping_fn=cnn)
# init inducing points (taken randomly from dataset)
batches = []
for i, (data, _) in enumerate(train_loader):
batches.append(data)
if i >= ((args.num_inducing - 1) // args.batch_size):
break
Xu = torch.cat(batches)[:args.num_inducing].clone()
if args.binary:
likelihood = gp.likelihoods.Binary()
latent_shape = torch.Size([])
else:
# use MultiClass likelihood for 10-class classification problem
likelihood = gp.likelihoods.MultiClass(num_classes=10)
# Because we use Categorical distribution in MultiClass likelihood, we need GP model
# returns a list of probabilities of each class. Hence it is required to use
# latent_shape = 10.
latent_shape = torch.Size([10])
# Turns on "whiten" flag will help optimization for variational models.
gpmodule = gp.models.VariationalSparseGP(X=Xu, y=None, kernel=deep_kernel, Xu=Xu,
likelihood=likelihood, latent_shape=latent_shape,
num_data=60000, whiten=True, jitter=2e-6)
if args.cuda:
gpmodule.cuda()
optimizer = torch.optim.Adam(gpmodule.parameters(), lr=args.lr)
elbo = infer.JitTraceMeanField_ELBO() if args.jit else infer.TraceMeanField_ELBO()
loss_fn = elbo.differentiable_loss
for epoch in range(1, args.epochs + 1):
start_time = time.time()
train(args, train_loader, gpmodule, optimizer, loss_fn, epoch)
with torch.no_grad():
test(args, test_loader, gpmodule)
print("Amount of time spent for epoch {}: {}s\n"
.format(epoch, int(time.time() - start_time)))
if __name__ == '__main__':
assert pyro.__version__.startswith('1.4.0')
parser = argparse.ArgumentParser(description='Pyro GP MNIST Example')
parser.add_argument('--data-dir', type=str, default=None, metavar='PATH',
help='default directory to cache MNIST data')
parser.add_argument('--num-inducing', type=int, default=70, metavar='N',
help='number of inducing input (default: 70)')
parser.add_argument('--binary', action='store_true', default=False,
help='do binary classification')
parser.add_argument('--batch-size', type=int, default=64, metavar='N',
help='input batch size for training (default: 64)')
parser.add_argument('--test-batch-size', type=int, default=1000, metavar='N',
help='input batch size for testing (default: 1000)')
parser.add_argument('--epochs', type=int, default=10, metavar='N',
help='number of epochs to train (default: 10)')
parser.add_argument('--lr', type=float, default=0.01, metavar='LR',
help='learning rate (default: 0.01)')
parser.add_argument('--cuda', action='store_true', default=False,
help='enables CUDA training')
parser.add_argument('--jit', action='store_true', default=False,
help='enables PyTorch jit')
parser.add_argument('--seed', type=int, default=1, metavar='S',
help='random seed (default: 1)')
parser.add_argument('--log-interval', type=int, default=10, metavar='N',
help='how many batches to wait before logging training status')
args = parser.parse_args()
pyro.set_rng_seed(args.seed)
if args.cuda:
torch.backends.cudnn.deterministic = True
main(args)
| 42.432161
| 99
| 0.625651
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.