max_stars_repo_path stringlengths 4 286 | max_stars_repo_name stringlengths 5 119 | max_stars_count int64 0 191k | id stringlengths 1 7 | content stringlengths 6 1.03M | content_cleaned stringlengths 6 1.03M | language stringclasses 111 values | language_score float64 0.03 1 | comments stringlengths 0 556k | edu_score float64 0.32 5.03 | edu_int_score int64 0 5 |
|---|---|---|---|---|---|---|---|---|---|---|
PyChess/BoardPiece.py | SurtzSean/Chess | 0 | 6620251 | <reponame>SurtzSean/Chess
import pygame
class BoardPiece():
def __init__(self, occupiedBy, color, SIZE, row, col):
self.occupiedBy = occupiedBy
self.color = color
self.SIZE = SIZE
self.row = row
self.col = col
self.MARGIN = SIZE * .1
self.area = pygame.Rect((self.MARGIN + self.SIZE) * self.col + self.MARGIN,
(self.MARGIN + self.SIZE) * self.row + self.MARGIN, self.SIZE, self.SIZE)
self.center = self.area.center
def drawPiece(self, screen):
pygame.draw.rect(screen, self.color, [(self.MARGIN + self.SIZE) * self.col + self.MARGIN,
(self.MARGIN + self.SIZE) * self.row + self.MARGIN, self.SIZE, self.SIZE])
if(self.occupiedBy != None):
image = pygame.image.load(self.occupiedBy.image)
screen.blit(
image, [self.center[0] - (self.SIZE/2.45), self.center[1] - (self.SIZE/2.45)])
def drawValid(self, screen, color):
if color == 'RED':
pygame.draw.circle(screen, (255, 0, 0), self.center, 10)
elif color == 'BLUE':
pygame.draw.circle(screen, (0, 0, 255), self.center, 10)
def drawPrev(self, screen):
pygame.draw.circle(screen, (0, 0, 255), self.center, 27, 2)
| import pygame
class BoardPiece():
def __init__(self, occupiedBy, color, SIZE, row, col):
self.occupiedBy = occupiedBy
self.color = color
self.SIZE = SIZE
self.row = row
self.col = col
self.MARGIN = SIZE * .1
self.area = pygame.Rect((self.MARGIN + self.SIZE) * self.col + self.MARGIN,
(self.MARGIN + self.SIZE) * self.row + self.MARGIN, self.SIZE, self.SIZE)
self.center = self.area.center
def drawPiece(self, screen):
pygame.draw.rect(screen, self.color, [(self.MARGIN + self.SIZE) * self.col + self.MARGIN,
(self.MARGIN + self.SIZE) * self.row + self.MARGIN, self.SIZE, self.SIZE])
if(self.occupiedBy != None):
image = pygame.image.load(self.occupiedBy.image)
screen.blit(
image, [self.center[0] - (self.SIZE/2.45), self.center[1] - (self.SIZE/2.45)])
def drawValid(self, screen, color):
if color == 'RED':
pygame.draw.circle(screen, (255, 0, 0), self.center, 10)
elif color == 'BLUE':
pygame.draw.circle(screen, (0, 0, 255), self.center, 10)
def drawPrev(self, screen):
pygame.draw.circle(screen, (0, 0, 255), self.center, 27, 2) | none | 1 | 3.223099 | 3 | |
django_whoshere/tests/tests.py | Koed00/django-whoshere | 18 | 6620252 | from django.contrib.auth.models import User
from django.core.cache import cache
from django.template import Template, Context
from django.test import TestCase, RequestFactory, Client
from django_whoshere.apps import PREFIX, parse
from django_whoshere.middleware import TrackMiddleware
from django_whoshere.models import UserSession
class WhosHereTestCase(TestCase):
def setUp(self):
self.factory = RequestFactory()
self.user = User.objects.create_superuser('WHosHereTestUser', '<EMAIL>',
'<PASSWORD>')
self.key = '{}:{}'.format(PREFIX, self.user.pk)
self.user_agent = 'Mozilla/5.0'
cache.delete(self.key)
def tearDown(self):
self.user.delete()
cache.delete(self.key)
def test_tags(self):
request = self.factory.get('/', HTTP_USER_AGENT=self.user_agent)
context = Context({'request': request})
TrackMiddleware.process_request(request)
t = Template('{% load whoshere %}{% active_user_count %}{% active_users as users%}'
'{% your_ip %}{% your_agent %}{% your_city %}{% your_country %}')
result = t.render(context)
if parse:
self.assertEqual(result, '0127.0.0.1Other / Other / Otherunknownunknown')
else:
self.assertEqual(result, '0127.0.0.1{}unknownunknown'.format(self.user_agent))
def test_admin_page(self):
c = Client()
response = c.post('/admin/login/?next=/admin/django_whoshere/usersession/',
{'username': 'WHosHereTestUser', 'password': '<PASSWORD>'}, follow=True)
self.assertEqual(response.status_code, 200)
response = c.get('/admin/django_whoshere/usersession/1/')
self.assertEqual(response.status_code, 200)
def test_user_request(self):
request = self.factory.get('/', HTTP_USER_AGENT=self.user_agent)
# anon
TrackMiddleware.process_request(request)
# authenticated
request.user = self.user
TrackMiddleware.process_request(request)
self.assertNotEqual(cache.get(self.key), None)
active_user = UserSession.objects.first()
self.assertEqual(active_user.ip, '127.0.0.1')
if parse:
self.assertEqual(active_user.user_agent.ua_string, self.user_agent)
else:
self.assertEqual(active_user.user_agent, self.user_agent)
self.assertEqual(active_user.city(), 'unknown')
self.assertEqual(active_user.country(), 'unknown')
self.assertEqual(UserSession.active_user_ids(), [1])
self.assertEqual(UserSession.active_users()[0], self.user)
self.assertEqual(UserSession.active_user_count(), 1)
| from django.contrib.auth.models import User
from django.core.cache import cache
from django.template import Template, Context
from django.test import TestCase, RequestFactory, Client
from django_whoshere.apps import PREFIX, parse
from django_whoshere.middleware import TrackMiddleware
from django_whoshere.models import UserSession
class WhosHereTestCase(TestCase):
def setUp(self):
self.factory = RequestFactory()
self.user = User.objects.create_superuser('WHosHereTestUser', '<EMAIL>',
'<PASSWORD>')
self.key = '{}:{}'.format(PREFIX, self.user.pk)
self.user_agent = 'Mozilla/5.0'
cache.delete(self.key)
def tearDown(self):
self.user.delete()
cache.delete(self.key)
def test_tags(self):
request = self.factory.get('/', HTTP_USER_AGENT=self.user_agent)
context = Context({'request': request})
TrackMiddleware.process_request(request)
t = Template('{% load whoshere %}{% active_user_count %}{% active_users as users%}'
'{% your_ip %}{% your_agent %}{% your_city %}{% your_country %}')
result = t.render(context)
if parse:
self.assertEqual(result, '0127.0.0.1Other / Other / Otherunknownunknown')
else:
self.assertEqual(result, '0127.0.0.1{}unknownunknown'.format(self.user_agent))
def test_admin_page(self):
c = Client()
response = c.post('/admin/login/?next=/admin/django_whoshere/usersession/',
{'username': 'WHosHereTestUser', 'password': '<PASSWORD>'}, follow=True)
self.assertEqual(response.status_code, 200)
response = c.get('/admin/django_whoshere/usersession/1/')
self.assertEqual(response.status_code, 200)
def test_user_request(self):
request = self.factory.get('/', HTTP_USER_AGENT=self.user_agent)
# anon
TrackMiddleware.process_request(request)
# authenticated
request.user = self.user
TrackMiddleware.process_request(request)
self.assertNotEqual(cache.get(self.key), None)
active_user = UserSession.objects.first()
self.assertEqual(active_user.ip, '127.0.0.1')
if parse:
self.assertEqual(active_user.user_agent.ua_string, self.user_agent)
else:
self.assertEqual(active_user.user_agent, self.user_agent)
self.assertEqual(active_user.city(), 'unknown')
self.assertEqual(active_user.country(), 'unknown')
self.assertEqual(UserSession.active_user_ids(), [1])
self.assertEqual(UserSession.active_users()[0], self.user)
self.assertEqual(UserSession.active_user_count(), 1)
| en | 0.56473 | # anon # authenticated | 2.113021 | 2 |
demo/celery/task/main.py | marco-souza/falsy | 127 | 6620253 | from celery import Celery
app = Celery('ymon', include=['demo.celery.task.tasks'])
app.config_from_object('demo.celery.task.celeryconfig')
if __name__ == '__main__':
app.start() | from celery import Celery
app = Celery('ymon', include=['demo.celery.task.tasks'])
app.config_from_object('demo.celery.task.celeryconfig')
if __name__ == '__main__':
app.start() | none | 1 | 1.56969 | 2 | |
test_package/conanfile.py | matt-ross16/flextool | 0 | 6620254 | from conans import ConanFile, CMake, tools, AutoToolsBuildEnvironment, RunEnvironment
from conans.errors import ConanInvalidConfiguration, ConanException
from conans.tools import os_info
import os, re, stat, fnmatch, platform, glob
from functools import total_ordering
class TestPackageConan(ConanFile):
settings = "os", "compiler", "build_type", "arch"
generators = "cmake", "cmake_paths", "virtualenv", "cmake_find_package_multi"
topics = ('c++')
def build(self):
bin_path = ""
for p in self.deps_cpp_info.bin_paths:
bin_path = "%s%s%s" % (p, os.pathsep, bin_path)
lib_path = ""
for p in self.deps_cpp_info.lib_paths:
lib_path = "%s%s%s" % (p, os.pathsep, lib_path)
env = {
"PATH": "%s:%s" % (bin_path, os.environ['PATH']),
"LD_LIBRARY_PATH": "%s:%s" % (lib_path, os.environ['LD_LIBRARY_PATH'])
}
self.output.info("=================linux environment for %s=================\n" % (self.name))
self.output.info('PATH = %s' % (env['PATH']))
self.output.info('LD_LIBRARY_PATH = %s' % (env['LD_LIBRARY_PATH']))
self.output.info('')
with tools.environment_append(env):
cmake = CMake(self)
cmake.configure()
cmake.build()
def test(self):
if not tools.cross_building(self.settings):
self.output.info('self.source_folder = %s' % (self.source_folder))
#
# cling_includes must point to cling/Interpreter/RuntimeUniverse.h
#
cling_conan_ROOT = self.deps_cpp_info["cling_conan"].rootpath
cling_includes = cling_conan_ROOT
cling_includes = os.path.join(cling_includes, "include")
self.output.info('cling_includes = %s' % (cling_includes))
#
# clang_includes must point to stddef.h from lib/clang/5.0.0/include
#
clang_includes = cling_conan_ROOT
clang_includes = os.path.join(clang_includes, "lib")
clang_includes = os.path.join(clang_includes, "clang")
clang_includes = os.path.join(clang_includes, "5.0.0")
clang_includes = os.path.join(clang_includes, "include")
self.output.info('clang_includes = %s' % (clang_includes))
# NOTE: must use `--extra-arg`, not `-extra-arg`
test_invalid_arg="-extra-arg=-Itest_INVALID_argument"
#
# run executable
# NOTE: generates file in filesystem
#
flextool_cmd = "flextool" \
" --outdir=." \
" --indir=." \
" --vmodule=*=100 --enable-logging=stderr --log-level=100" \
" --extra-arg=-I{}" \
" {}" \
" --extra-arg=-I{}" \
" {}/main.cpp".format(
cling_includes, test_invalid_arg, clang_includes, self.source_folder)
self.output.info('flextool_cmd = %s' % (flextool_cmd))
self.run(flextool_cmd, run_environment=True)
| from conans import ConanFile, CMake, tools, AutoToolsBuildEnvironment, RunEnvironment
from conans.errors import ConanInvalidConfiguration, ConanException
from conans.tools import os_info
import os, re, stat, fnmatch, platform, glob
from functools import total_ordering
class TestPackageConan(ConanFile):
settings = "os", "compiler", "build_type", "arch"
generators = "cmake", "cmake_paths", "virtualenv", "cmake_find_package_multi"
topics = ('c++')
def build(self):
bin_path = ""
for p in self.deps_cpp_info.bin_paths:
bin_path = "%s%s%s" % (p, os.pathsep, bin_path)
lib_path = ""
for p in self.deps_cpp_info.lib_paths:
lib_path = "%s%s%s" % (p, os.pathsep, lib_path)
env = {
"PATH": "%s:%s" % (bin_path, os.environ['PATH']),
"LD_LIBRARY_PATH": "%s:%s" % (lib_path, os.environ['LD_LIBRARY_PATH'])
}
self.output.info("=================linux environment for %s=================\n" % (self.name))
self.output.info('PATH = %s' % (env['PATH']))
self.output.info('LD_LIBRARY_PATH = %s' % (env['LD_LIBRARY_PATH']))
self.output.info('')
with tools.environment_append(env):
cmake = CMake(self)
cmake.configure()
cmake.build()
def test(self):
if not tools.cross_building(self.settings):
self.output.info('self.source_folder = %s' % (self.source_folder))
#
# cling_includes must point to cling/Interpreter/RuntimeUniverse.h
#
cling_conan_ROOT = self.deps_cpp_info["cling_conan"].rootpath
cling_includes = cling_conan_ROOT
cling_includes = os.path.join(cling_includes, "include")
self.output.info('cling_includes = %s' % (cling_includes))
#
# clang_includes must point to stddef.h from lib/clang/5.0.0/include
#
clang_includes = cling_conan_ROOT
clang_includes = os.path.join(clang_includes, "lib")
clang_includes = os.path.join(clang_includes, "clang")
clang_includes = os.path.join(clang_includes, "5.0.0")
clang_includes = os.path.join(clang_includes, "include")
self.output.info('clang_includes = %s' % (clang_includes))
# NOTE: must use `--extra-arg`, not `-extra-arg`
test_invalid_arg="-extra-arg=-Itest_INVALID_argument"
#
# run executable
# NOTE: generates file in filesystem
#
flextool_cmd = "flextool" \
" --outdir=." \
" --indir=." \
" --vmodule=*=100 --enable-logging=stderr --log-level=100" \
" --extra-arg=-I{}" \
" {}" \
" --extra-arg=-I{}" \
" {}/main.cpp".format(
cling_includes, test_invalid_arg, clang_includes, self.source_folder)
self.output.info('flextool_cmd = %s' % (flextool_cmd))
self.run(flextool_cmd, run_environment=True)
| en | 0.71866 | # # cling_includes must point to cling/Interpreter/RuntimeUniverse.h # # # clang_includes must point to stddef.h from lib/clang/5.0.0/include # # NOTE: must use `--extra-arg`, not `-extra-arg` # # run executable # NOTE: generates file in filesystem # | 2.061135 | 2 |
xs/nn/td_functional.py | eLeVeNnN/xshinnosuke | 290 | 6620255 | <reponame>eLeVeNnN/xshinnosuke
from core import __global as GLOBAL
from utils.common import ndarray
# base math operation
def add(a: ndarray, b: ndarray, out: ndarray = None):
return GLOBAL.np.add(a, b, out=out)
def sub(a: ndarray, b: ndarray, out: ndarray = None):
return GLOBAL.np.subtract(a, b, out=out)
def mul(a: ndarray, b: ndarray, out: ndarray = None):
return GLOBAL.np.multiply(a, b, out=out)
def div(a: ndarray, b: ndarray, out: ndarray = None):
return GLOBAL.np.divide(a, b, out=out)
def floor_div(a: ndarray, b: ndarray, out: ndarray = None):
return GLOBAL.np.true_divide(a, b, out=out)
def mm(a: ndarray, b: ndarray, out: ndarray = None):
return GLOBAL.np.dot(a, b, out=out)
def exp(x: ndarray, out: ndarray = None):
return GLOBAL.np.exp(x, out=out)
def max(x: ndarray, axis: int = None, keepdims: bool = False, out: ndarray = None):
return GLOBAL.np.max(x, axis=axis, keepdims=keepdims, out=out)
def maximum(x1: ndarray, x2: ndarray, out: ndarray = None):
return GLOBAL.np.maximum(x1, x2, out=out)
def sum(x: ndarray, axis: int = None, keepdims: bool = False, out: ndarray = None):
return GLOBAL.np.sum(x, axis, keepdims=keepdims, out=out)
def mean(x: ndarray, axis: int = None, keepdims: bool = False, out: ndarray = None):
return GLOBAL.np.mean(x, axis, keepdims=keepdims, out=out)
def norm(x: ndarray, p: int = 2, axis: int = None, keepdims: bool = False, out: ndarray = None):
x = GLOBAL.np.abs(x)
x = GLOBAL.np.power(x, p)
out = GLOBAL.np.sum(x, axis=axis, keepdims=keepdims, out=out)
out = GLOBAL.np.power(out, 1 / p)
return out
# base activation
def relu(x: ndarray, out: ndarray = None):
return GLOBAL.np.maximum(0., x, out=out)
def sigmoid(x: ndarray, out: ndarray = None):
out = GLOBAL.np.exp(-x, out=out)
out = GLOBAL.np.add(1., out, out=out)
return GLOBAL.np.divide(1., out, out=out)
def tanh(x: ndarray, out: ndarray = None):
return GLOBAL.np.tanh(x, out=out)
def softmax(x: ndarray, out: ndarray = None):
# more stable softmax
out = GLOBAL.np.subtract(x, max(x, axis=-1, keepdims=True), out=out)
GLOBAL.np.exp(out, out=out)
GLOBAL.np.divide(out, sum(out, axis=-1, keepdims=True), out=out)
return out
def log_softmax(x: ndarray, out: ndarray = None):
out = softmax(x, out)
out = GLOBAL.np.log(out, out=out)
return out
# base nn function
def flatten(x: ndarray, start: int = 1):
output_shape = tuple(x.shape[:start]) + (-1,)
return GLOBAL.np.reshape(x, output_shape)
def long(data: ndarray):
return data.astype(GLOBAL.np.int64)
def expand_as(inputs: ndarray, target: ndarray):
new_axis_list = []
inputs_idx = 0
for i in range(target.ndim):
if inputs_idx >= inputs.ndim:
new_axis_list.append(i)
elif inputs.shape[inputs_idx] == target.shape[i]:
inputs_idx += 1
else:
new_axis_list.append(i)
try:
return GLOBAL.np.expand_dims(inputs, axis=new_axis_list)
except TypeError:
for a in new_axis_list:
inputs = GLOBAL.np.expand_dims(inputs, axis=a)
return inputs
def nll_loss(pred: ndarray, target: ndarray, reduction: str = 'mean', out: ndarray = None):
to_sum_dim = GLOBAL.np.prod(GLOBAL.np.asarray(pred.shape[:-1])).item()
log_probs = pred.reshape(-1, pred.shape[-1])
y_flat = target.reshape(to_sum_dim).astype(GLOBAL.np.int)
if reduction == 'sum':
sum_val = -GLOBAL.np.sum(log_probs[GLOBAL.np.arange(to_sum_dim), y_flat])
out = GLOBAL.np.multiply(-1, sum_val, out=out)
elif reduction == 'mean':
sum_val = -GLOBAL.np.sum(log_probs[GLOBAL.np.arange(to_sum_dim), y_flat])
out = GLOBAL.np.divide(sum_val, pred.shape[0], out=out)
else:
out = GLOBAL.np.multiply(-1, log_probs[GLOBAL.np.arange(to_sum_dim), y_flat], out=out)
out = GLOBAL.np.abs(out)
return out
def bce_loss(pred: ndarray, target: ndarray, reduction: str = 'mean', out: ndarray = None):
if reduction == 'sum':
loss_val = GLOBAL.np.sum(GLOBAL.np.add(GLOBAL.np.multiply(target, GLOBAL.np.log(pred)),
GLOBAL.np.multiply(GLOBAL.np.subtract(1, target), GLOBAL.np.log(GLOBAL.np.subtract(1, pred)))))
out = GLOBAL.np.multiply(-1, loss_val, out=out)
elif reduction == 'mean':
loss_val = GLOBAL.np.mean(GLOBAL.np.add(GLOBAL.np.multiply(target, GLOBAL.np.log(pred)),
GLOBAL.np.multiply(GLOBAL.np.subtract(1, target), GLOBAL.np.log(GLOBAL.np.subtract(1, pred)))))
out = GLOBAL.np.multiply(-1, loss_val, out=out)
else:
out = GLOBAL.np.add(GLOBAL.np.multiply(target, GLOBAL.np.log(pred)),
GLOBAL.np.multiply(GLOBAL.np.subtract(1, target), GLOBAL.np.log(GLOBAL.np.subtract(1, pred))), out=out)
out = GLOBAL.np.multiply(-1, out, out=out)
return out
| from core import __global as GLOBAL
from utils.common import ndarray
# base math operation
def add(a: ndarray, b: ndarray, out: ndarray = None):
return GLOBAL.np.add(a, b, out=out)
def sub(a: ndarray, b: ndarray, out: ndarray = None):
return GLOBAL.np.subtract(a, b, out=out)
def mul(a: ndarray, b: ndarray, out: ndarray = None):
return GLOBAL.np.multiply(a, b, out=out)
def div(a: ndarray, b: ndarray, out: ndarray = None):
return GLOBAL.np.divide(a, b, out=out)
def floor_div(a: ndarray, b: ndarray, out: ndarray = None):
return GLOBAL.np.true_divide(a, b, out=out)
def mm(a: ndarray, b: ndarray, out: ndarray = None):
return GLOBAL.np.dot(a, b, out=out)
def exp(x: ndarray, out: ndarray = None):
return GLOBAL.np.exp(x, out=out)
def max(x: ndarray, axis: int = None, keepdims: bool = False, out: ndarray = None):
return GLOBAL.np.max(x, axis=axis, keepdims=keepdims, out=out)
def maximum(x1: ndarray, x2: ndarray, out: ndarray = None):
return GLOBAL.np.maximum(x1, x2, out=out)
def sum(x: ndarray, axis: int = None, keepdims: bool = False, out: ndarray = None):
return GLOBAL.np.sum(x, axis, keepdims=keepdims, out=out)
def mean(x: ndarray, axis: int = None, keepdims: bool = False, out: ndarray = None):
return GLOBAL.np.mean(x, axis, keepdims=keepdims, out=out)
def norm(x: ndarray, p: int = 2, axis: int = None, keepdims: bool = False, out: ndarray = None):
x = GLOBAL.np.abs(x)
x = GLOBAL.np.power(x, p)
out = GLOBAL.np.sum(x, axis=axis, keepdims=keepdims, out=out)
out = GLOBAL.np.power(out, 1 / p)
return out
# base activation
def relu(x: ndarray, out: ndarray = None):
return GLOBAL.np.maximum(0., x, out=out)
def sigmoid(x: ndarray, out: ndarray = None):
out = GLOBAL.np.exp(-x, out=out)
out = GLOBAL.np.add(1., out, out=out)
return GLOBAL.np.divide(1., out, out=out)
def tanh(x: ndarray, out: ndarray = None):
return GLOBAL.np.tanh(x, out=out)
def softmax(x: ndarray, out: ndarray = None):
# more stable softmax
out = GLOBAL.np.subtract(x, max(x, axis=-1, keepdims=True), out=out)
GLOBAL.np.exp(out, out=out)
GLOBAL.np.divide(out, sum(out, axis=-1, keepdims=True), out=out)
return out
def log_softmax(x: ndarray, out: ndarray = None):
out = softmax(x, out)
out = GLOBAL.np.log(out, out=out)
return out
# base nn function
def flatten(x: ndarray, start: int = 1):
output_shape = tuple(x.shape[:start]) + (-1,)
return GLOBAL.np.reshape(x, output_shape)
def long(data: ndarray):
return data.astype(GLOBAL.np.int64)
def expand_as(inputs: ndarray, target: ndarray):
new_axis_list = []
inputs_idx = 0
for i in range(target.ndim):
if inputs_idx >= inputs.ndim:
new_axis_list.append(i)
elif inputs.shape[inputs_idx] == target.shape[i]:
inputs_idx += 1
else:
new_axis_list.append(i)
try:
return GLOBAL.np.expand_dims(inputs, axis=new_axis_list)
except TypeError:
for a in new_axis_list:
inputs = GLOBAL.np.expand_dims(inputs, axis=a)
return inputs
def nll_loss(pred: ndarray, target: ndarray, reduction: str = 'mean', out: ndarray = None):
to_sum_dim = GLOBAL.np.prod(GLOBAL.np.asarray(pred.shape[:-1])).item()
log_probs = pred.reshape(-1, pred.shape[-1])
y_flat = target.reshape(to_sum_dim).astype(GLOBAL.np.int)
if reduction == 'sum':
sum_val = -GLOBAL.np.sum(log_probs[GLOBAL.np.arange(to_sum_dim), y_flat])
out = GLOBAL.np.multiply(-1, sum_val, out=out)
elif reduction == 'mean':
sum_val = -GLOBAL.np.sum(log_probs[GLOBAL.np.arange(to_sum_dim), y_flat])
out = GLOBAL.np.divide(sum_val, pred.shape[0], out=out)
else:
out = GLOBAL.np.multiply(-1, log_probs[GLOBAL.np.arange(to_sum_dim), y_flat], out=out)
out = GLOBAL.np.abs(out)
return out
def bce_loss(pred: ndarray, target: ndarray, reduction: str = 'mean', out: ndarray = None):
if reduction == 'sum':
loss_val = GLOBAL.np.sum(GLOBAL.np.add(GLOBAL.np.multiply(target, GLOBAL.np.log(pred)),
GLOBAL.np.multiply(GLOBAL.np.subtract(1, target), GLOBAL.np.log(GLOBAL.np.subtract(1, pred)))))
out = GLOBAL.np.multiply(-1, loss_val, out=out)
elif reduction == 'mean':
loss_val = GLOBAL.np.mean(GLOBAL.np.add(GLOBAL.np.multiply(target, GLOBAL.np.log(pred)),
GLOBAL.np.multiply(GLOBAL.np.subtract(1, target), GLOBAL.np.log(GLOBAL.np.subtract(1, pred)))))
out = GLOBAL.np.multiply(-1, loss_val, out=out)
else:
out = GLOBAL.np.add(GLOBAL.np.multiply(target, GLOBAL.np.log(pred)),
GLOBAL.np.multiply(GLOBAL.np.subtract(1, target), GLOBAL.np.log(GLOBAL.np.subtract(1, pred))), out=out)
out = GLOBAL.np.multiply(-1, out, out=out)
return out | en | 0.605444 | # base math operation # base activation # more stable softmax # base nn function | 2.610921 | 3 |
datastructure/practice/c1/p_1_35.py | stoneyangxu/python-kata | 0 | 6620256 | import random
def random_birthday():
return random.randint(1, 365)
def generate_person_list(n):
return [random_birthday() for i in range(n)]
def has_same_birthday(person_list):
s = set()
for n in person_list:
if n in s:
return True
else:
s.add(n)
return False
def main():
for n in range(5, 105, 5):
same_count = 0
total = 0
for i in range(10000):
if has_same_birthday(generate_person_list(n)):
same_count += 1
total += 1
print("n = {0:3d}, percent: {1:2.2f}%".format(n, same_count / total * 100))
if __name__ == '__main__':
main()
| import random
def random_birthday():
return random.randint(1, 365)
def generate_person_list(n):
return [random_birthday() for i in range(n)]
def has_same_birthday(person_list):
s = set()
for n in person_list:
if n in s:
return True
else:
s.add(n)
return False
def main():
for n in range(5, 105, 5):
same_count = 0
total = 0
for i in range(10000):
if has_same_birthday(generate_person_list(n)):
same_count += 1
total += 1
print("n = {0:3d}, percent: {1:2.2f}%".format(n, same_count / total * 100))
if __name__ == '__main__':
main()
| none | 1 | 3.553943 | 4 | |
tests/datamodel/test_pivot_input_types.py | kubajir/msticpy | 820 | 6620257 | # -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
"""Test pivot function handling of different input types."""
import warnings
from collections import namedtuple
import pandas as pd
import pytest
import pytest_check as check
from msticpy.data import QueryProvider
from msticpy.data.query_container import QueryContainer
from msticpy.datamodel import entities
from msticpy.datamodel.pivot import Pivot
from msticpy.sectools import GeoLiteLookup, IPStackLookup, TILookup
__author__ = "<NAME>"
# pylint: disable=redefined-outer-name
@pytest.fixture(scope="session")
def data_providers():
"""Return dict of providers."""
with warnings.catch_warnings():
warnings.simplefilter("ignore", category=UserWarning)
return {
"ti_lookup": TILookup(),
"geolite": GeoLiteLookup(),
# "ip_stack": IPStackLookup(),
}
def _reset_entities():
"""Clear any query containers in entities."""
for entity_name in ("Host", "IpAddress", "Account", "Url"):
entity = getattr(entities, entity_name)
for attr in dir(entity):
if isinstance(getattr(entity, attr), QueryContainer):
delattr(entity, attr)
@pytest.fixture(scope="session")
def _create_pivot(data_providers):
_reset_entities()
providers = data_providers.values()
with warnings.catch_warnings():
warnings.simplefilter("ignore", category=UserWarning)
return Pivot(providers=providers)
PivotQuery = namedtuple(
"PivotQuery",
"entity, value, provider, pivot_func, func_param, src_df_col, key_col, exp_col",
)
_IP_LIST = {
"172.16.58.3": "Public",
"172.16.17.32": "Public",
"192.168.0.1": "Private",
"127.0.0.1": "Loopback",
}
# pylint: disable=line-too-long
_B64_ENCODINGS = {
"VGhpcyBpcyBhIHRlc3Qgb2YgYmFzZTY0IGVuY29kZWQgc3RyaW5n": "This is a test of base64 encoded string",
"QSBLdXN0byBxdWVyeSBpcyBhIHJlYWQtb25seSByZXF1ZXN0IHRvIHByb2Nlc3MgZGF0YS"
+ "BhbmQgcmV0dXJuIHJlc3VsdHMu": "A Kusto query is a read-only request to process data and return results.",
"VGhpcyBpcyBhbiBlbWJlZGRlZCBCNjQgVkdocGN5QnBjeUJoSUhSbGMzUWdiMllnWW1GelpU"
+ "WTBJR1Z1WTI5a1pXUWdjM1J5YVc1bg==": "This is an embedded B64 VGhpcyBpcyBhIHRlc3Qgb2YgYmFzZTY0IGVuY29kZWQgc3RyaW5n",
}
# pylint: enable=line-too-long
_URLS = {
"https://www.contoso.com/path?p1=test&p2=10.2.4.5&hash=00236a2ae558018ed13b5222ef1bd987": {
"dns": "www.contoso.com",
"url": "input",
"ipv4": "10.2.4.5",
"md5_hash": "00236a2ae558018ed13b5222ef1bd987",
},
"https://www.microsoft.com/path?p1=test&p2=10.2.4.5&"
+ "hash=EE35D33B6F6A069CE82E45C83FBDE97A267261E9": {
"dns": "www.microsoft.com",
"url": "input",
"ipv4": "10.2.4.5",
"sha1_hash": "EE35D33B6F6A069CE82E45C83FBDE97A267261E9",
},
}
_PIVOT_QUERIES = [
pytest.param(
PivotQuery(
entity=entities.IpAddress,
value=_IP_LIST,
provider="util",
pivot_func="ip_type",
func_param="ip_str",
src_df_col="ip",
key_col="ip",
exp_col="result",
),
id="IpAddress-ip_type",
),
pytest.param(
PivotQuery(
entity=entities.Process,
value=_B64_ENCODINGS,
provider="util",
pivot_func="b64decode",
func_param="value",
src_df_col="cmdline",
key_col="original_string",
exp_col="decoded_string",
),
id="Process-b64decode",
),
pytest.param(
PivotQuery(
entity=entities.Url,
value=_URLS,
provider="util",
pivot_func="extract_iocs",
func_param="value",
src_df_col="cmdline",
key_col="Input",
exp_col="Observable",
),
id="Url-extract_iocs",
),
]
@pytest.mark.parametrize("test_case", _PIVOT_QUERIES)
def test_pivot_funcs_value(_create_pivot, test_case):
"""Test calling function with value."""
func = getattr(getattr(test_case.entity, test_case.provider), test_case.pivot_func)
# Test value input
val = next(iter(test_case.value.keys()))
params = {test_case.func_param: val}
result_df = func(**params)
expected = next(iter(test_case.value.values()))
if isinstance(expected, dict):
for exp_value in expected.values():
if exp_value == "input":
exp_value = val
check.is_in(exp_value, result_df[test_case.exp_col].values)
else:
check.is_in(expected, result_df.iloc[0][test_case.exp_col])
@pytest.mark.parametrize("test_case", _PIVOT_QUERIES)
def test_pivot_funcs_itbl(_create_pivot, test_case):
"""Test calling function with iterable input."""
func = getattr(getattr(test_case.entity, test_case.provider), test_case.pivot_func)
# Test value input
val = test_case.value.keys()
params = {test_case.func_param: val}
result_df = func(**params)
for key, expected in test_case.value.items():
key_results = result_df[result_df[test_case.key_col] == key]
if isinstance(expected, dict):
for exp_value in expected.values():
if exp_value == "input":
exp_value = key
check.is_in(exp_value, key_results[test_case.exp_col].values)
else:
check.is_in(expected, key_results.iloc[0][test_case.exp_col])
@pytest.mark.parametrize("test_case", _PIVOT_QUERIES)
def test_pivot_funcs_df(_create_pivot, test_case):
"""Test calling function with DF input attributes."""
func = getattr(getattr(test_case.entity, test_case.provider), test_case.pivot_func)
# Test DF input
val = test_case.value.keys()
in_df = pd.DataFrame(val, columns=[test_case.src_df_col])
result_df = func(data=in_df, src_column=test_case.src_df_col)
for key, expected in test_case.value.items():
key_results = result_df[result_df[test_case.key_col] == key]
if isinstance(expected, dict):
for exp_value in expected.values():
if exp_value == "input":
exp_value = key
check.is_in(exp_value, key_results[test_case.exp_col].values)
else:
check.is_in(expected, key_results.iloc[0][test_case.exp_col])
@pytest.mark.parametrize("join_type", ["left", "inner", "right"])
@pytest.mark.parametrize("test_case", _PIVOT_QUERIES)
def test_pivot_funcs_df_merge(_create_pivot, join_type, test_case):
"""Test calling function with DF input attributes."""
func = getattr(getattr(test_case.entity, test_case.provider), test_case.pivot_func)
# Test DF input
val = enumerate(test_case.value.keys())
in_df = pd.DataFrame(val, columns=["idx", test_case.src_df_col])
in_df["extra_col1"] = "test1"
in_df["extra_col2"] = "test2"
result_no_merge_df = func(data=in_df, src_column=test_case.src_df_col)
result_df = func(data=in_df, src_column=test_case.src_df_col, join=join_type)
in_cols = in_df.shape[1]
no_merge_cols = result_no_merge_df.shape[1]
merge_cols = result_df.shape[1]
# merged DF should have result + input cols - join key col
check.greater_equal(no_merge_cols + in_cols, merge_cols)
if join_type in ("left", "inner"):
# inner and left joins should have same or greater length as input
check.greater_equal(result_df.shape[0], in_df.shape[0])
# all the keys from the input should be in the merged output
for key in in_df[test_case.src_df_col]:
check.is_in(key, result_df[test_case.key_col].values)
if join_type == "right":
# We don't know how many results we get back from right join
# (although should not be zero)
check.greater(len(result_df), 0)
# but all of its key values should be present in input
for key in result_df[test_case.key_col].values:
check.is_in(key, in_df[test_case.src_df_col].values)
| # -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
"""Test pivot function handling of different input types."""
import warnings
from collections import namedtuple
import pandas as pd
import pytest
import pytest_check as check
from msticpy.data import QueryProvider
from msticpy.data.query_container import QueryContainer
from msticpy.datamodel import entities
from msticpy.datamodel.pivot import Pivot
from msticpy.sectools import GeoLiteLookup, IPStackLookup, TILookup
__author__ = "<NAME>"
# pylint: disable=redefined-outer-name
@pytest.fixture(scope="session")
def data_providers():
"""Return dict of providers."""
with warnings.catch_warnings():
warnings.simplefilter("ignore", category=UserWarning)
return {
"ti_lookup": TILookup(),
"geolite": GeoLiteLookup(),
# "ip_stack": IPStackLookup(),
}
def _reset_entities():
"""Clear any query containers in entities."""
for entity_name in ("Host", "IpAddress", "Account", "Url"):
entity = getattr(entities, entity_name)
for attr in dir(entity):
if isinstance(getattr(entity, attr), QueryContainer):
delattr(entity, attr)
@pytest.fixture(scope="session")
def _create_pivot(data_providers):
_reset_entities()
providers = data_providers.values()
with warnings.catch_warnings():
warnings.simplefilter("ignore", category=UserWarning)
return Pivot(providers=providers)
PivotQuery = namedtuple(
"PivotQuery",
"entity, value, provider, pivot_func, func_param, src_df_col, key_col, exp_col",
)
_IP_LIST = {
"172.16.58.3": "Public",
"172.16.17.32": "Public",
"192.168.0.1": "Private",
"127.0.0.1": "Loopback",
}
# pylint: disable=line-too-long
_B64_ENCODINGS = {
"VGhpcyBpcyBhIHRlc3Qgb2YgYmFzZTY0IGVuY29kZWQgc3RyaW5n": "This is a test of base64 encoded string",
"QSBLdXN0byBxdWVyeSBpcyBhIHJlYWQtb25seSByZXF1ZXN0IHRvIHByb2Nlc3MgZGF0YS"
+ "BhbmQgcmV0dXJuIHJlc3VsdHMu": "A Kusto query is a read-only request to process data and return results.",
"VGhpcyBpcyBhbiBlbWJlZGRlZCBCNjQgVkdocGN5QnBjeUJoSUhSbGMzUWdiMllnWW1GelpU"
+ "WTBJR1Z1WTI5a1pXUWdjM1J5YVc1bg==": "This is an embedded B64 VGhpcyBpcyBhIHRlc3Qgb2YgYmFzZTY0IGVuY29kZWQgc3RyaW5n",
}
# pylint: enable=line-too-long
_URLS = {
"https://www.contoso.com/path?p1=test&p2=10.2.4.5&hash=00236a2ae558018ed13b5222ef1bd987": {
"dns": "www.contoso.com",
"url": "input",
"ipv4": "10.2.4.5",
"md5_hash": "00236a2ae558018ed13b5222ef1bd987",
},
"https://www.microsoft.com/path?p1=test&p2=10.2.4.5&"
+ "hash=EE35D33B6F6A069CE82E45C83FBDE97A267261E9": {
"dns": "www.microsoft.com",
"url": "input",
"ipv4": "10.2.4.5",
"sha1_hash": "EE35D33B6F6A069CE82E45C83FBDE97A267261E9",
},
}
_PIVOT_QUERIES = [
pytest.param(
PivotQuery(
entity=entities.IpAddress,
value=_IP_LIST,
provider="util",
pivot_func="ip_type",
func_param="ip_str",
src_df_col="ip",
key_col="ip",
exp_col="result",
),
id="IpAddress-ip_type",
),
pytest.param(
PivotQuery(
entity=entities.Process,
value=_B64_ENCODINGS,
provider="util",
pivot_func="b64decode",
func_param="value",
src_df_col="cmdline",
key_col="original_string",
exp_col="decoded_string",
),
id="Process-b64decode",
),
pytest.param(
PivotQuery(
entity=entities.Url,
value=_URLS,
provider="util",
pivot_func="extract_iocs",
func_param="value",
src_df_col="cmdline",
key_col="Input",
exp_col="Observable",
),
id="Url-extract_iocs",
),
]
@pytest.mark.parametrize("test_case", _PIVOT_QUERIES)
def test_pivot_funcs_value(_create_pivot, test_case):
"""Test calling function with value."""
func = getattr(getattr(test_case.entity, test_case.provider), test_case.pivot_func)
# Test value input
val = next(iter(test_case.value.keys()))
params = {test_case.func_param: val}
result_df = func(**params)
expected = next(iter(test_case.value.values()))
if isinstance(expected, dict):
for exp_value in expected.values():
if exp_value == "input":
exp_value = val
check.is_in(exp_value, result_df[test_case.exp_col].values)
else:
check.is_in(expected, result_df.iloc[0][test_case.exp_col])
@pytest.mark.parametrize("test_case", _PIVOT_QUERIES)
def test_pivot_funcs_itbl(_create_pivot, test_case):
"""Test calling function with iterable input."""
func = getattr(getattr(test_case.entity, test_case.provider), test_case.pivot_func)
# Test value input
val = test_case.value.keys()
params = {test_case.func_param: val}
result_df = func(**params)
for key, expected in test_case.value.items():
key_results = result_df[result_df[test_case.key_col] == key]
if isinstance(expected, dict):
for exp_value in expected.values():
if exp_value == "input":
exp_value = key
check.is_in(exp_value, key_results[test_case.exp_col].values)
else:
check.is_in(expected, key_results.iloc[0][test_case.exp_col])
@pytest.mark.parametrize("test_case", _PIVOT_QUERIES)
def test_pivot_funcs_df(_create_pivot, test_case):
"""Test calling function with DF input attributes."""
func = getattr(getattr(test_case.entity, test_case.provider), test_case.pivot_func)
# Test DF input
val = test_case.value.keys()
in_df = pd.DataFrame(val, columns=[test_case.src_df_col])
result_df = func(data=in_df, src_column=test_case.src_df_col)
for key, expected in test_case.value.items():
key_results = result_df[result_df[test_case.key_col] == key]
if isinstance(expected, dict):
for exp_value in expected.values():
if exp_value == "input":
exp_value = key
check.is_in(exp_value, key_results[test_case.exp_col].values)
else:
check.is_in(expected, key_results.iloc[0][test_case.exp_col])
@pytest.mark.parametrize("join_type", ["left", "inner", "right"])
@pytest.mark.parametrize("test_case", _PIVOT_QUERIES)
def test_pivot_funcs_df_merge(_create_pivot, join_type, test_case):
"""Test calling function with DF input attributes."""
func = getattr(getattr(test_case.entity, test_case.provider), test_case.pivot_func)
# Test DF input
val = enumerate(test_case.value.keys())
in_df = pd.DataFrame(val, columns=["idx", test_case.src_df_col])
in_df["extra_col1"] = "test1"
in_df["extra_col2"] = "test2"
result_no_merge_df = func(data=in_df, src_column=test_case.src_df_col)
result_df = func(data=in_df, src_column=test_case.src_df_col, join=join_type)
in_cols = in_df.shape[1]
no_merge_cols = result_no_merge_df.shape[1]
merge_cols = result_df.shape[1]
# merged DF should have result + input cols - join key col
check.greater_equal(no_merge_cols + in_cols, merge_cols)
if join_type in ("left", "inner"):
# inner and left joins should have same or greater length as input
check.greater_equal(result_df.shape[0], in_df.shape[0])
# all the keys from the input should be in the merged output
for key in in_df[test_case.src_df_col]:
check.is_in(key, result_df[test_case.key_col].values)
if join_type == "right":
# We don't know how many results we get back from right join
# (although should not be zero)
check.greater(len(result_df), 0)
# but all of its key values should be present in input
for key in result_df[test_case.key_col].values:
check.is_in(key, in_df[test_case.src_df_col].values)
| en | 0.653393 | # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- Test pivot function handling of different input types. # pylint: disable=redefined-outer-name Return dict of providers. # "ip_stack": IPStackLookup(), Clear any query containers in entities. # pylint: disable=line-too-long # pylint: enable=line-too-long Test calling function with value. # Test value input Test calling function with iterable input. # Test value input Test calling function with DF input attributes. # Test DF input Test calling function with DF input attributes. # Test DF input # merged DF should have result + input cols - join key col # inner and left joins should have same or greater length as input # all the keys from the input should be in the merged output # We don't know how many results we get back from right join # (although should not be zero) # but all of its key values should be present in input | 1.960377 | 2 |
rsk_lid/v1/utils/utils/utils/combine_lexicons.py | saikrishnarallabandi/Lang_ID | 0 | 6620258 | # author: <NAME>, CMU, 2015
import sys
from os import path
import ntpath
combine_option=sys.argv[1]
dst_dir=sys.argv[2]
src_dirs=sys.argv[3:]
src_units = []
src_lex = []
units = []
lex = []
startIndex=0
mappings = []
for i in range(len(src_dirs)):
lang = src_dirs[i]
src_units.append(open(path.join(lang, "units.txt")).readlines())
src_lex.append(open(path.join(lang, "lexicon_numbers.txt")).readlines())
print "Language " + lang + " has " + str(len(src_units[-1])) + " units and " + str(len(src_lex[-1])) + " words in the lexicon"
if combine_option == 'agg':
for i in range(len(src_dirs)):
mapping = []
for unit in src_units[i]:
units.append("l" + str(i+1) + "_" + unit.split(' ')[0] + " " + str(startIndex + int(unit.split(' ')[1])))
mapping.append(len(units))
for line in src_lex[i]:
tkns = line.strip().split(' ')
lex.append("l" + str(i+1) + "_" + tkns[0] + " ")
for l in range(1, len(tkns)):
if tkns[l] == ".":
lex[-1] = lex[-1] + tkns[l] + " "
else:
lex[-1] = lex[-1] + str(startIndex + int(tkns[l])) + " "
mappings.append(mapping)
startIndex = startIndex + len(src_units[i])
elif combine_option == 'block':
for i in range(len(src_dirs)):
mapping = []
for unit in src_units[i]:
units.append("l" + str(i+1) + "_" + unit.split(' ')[0] + " " + str(startIndex + int(unit.split(' ')[1])))
mapping.append(len(units)+i)
for line in src_lex[i]:
tkns = line.strip().split(' ')
lex.append("l" + str(i+1) + "_" + tkns[0] + " ")
for l in range(1, len(tkns)):
if tkns[l] == ".":
lex[-1] = lex[-1] + tkns[l] + " "
else:
lex[-1] = lex[-1] + str(startIndex + int(tkns[l])) + " "
mappings.append(mapping)
startIndex = startIndex + len(src_units[i]) + 1
elif combine_option == 'share':
for i in range(len(src_dirs)):
mapping = []
for unit in src_units[i]:
u = unit.split(' ')[0]
if not u in units:
units.append(str(u))
mapping.append(units.index(u) + 1)
for line in src_lex[i]:
tkns = line.strip().split(' ')
lex.append(tkns[0] + " ")
for l in range(1, len(tkns)):
if tkns[l] == ".":
lex[-1] = lex[-1] + tkns[l] + " "
else:
lex[-1] = lex[-1] + str(mapping[int(tkns[l])-1]) + " "
mappings.append(mapping)
print "LEN: "+ str(len(mappings))
for i in range(len(src_dirs)):
mapping_file=open(path.join(dst_dir, path.basename(path.normpath(src_dirs[i] + "../../..")) + str(i) + "-mapping.txt"), 'w+');
mapping = mappings[i]
for i in range(len(mapping)):
m = mapping[i]
m = str(i+1) + " " + str(m)
mapping_file.write("%s\n" % m)
units_file=open(path.join(dst_dir, "units.txt"), "w")
i = 1
for u in units:
if combine_option == 'share':
u = u + " " + str(i)
units_file.write("%s\n" % u)
i = i + 1
lex_file=open(path.join(dst_dir, "lexicon_numbers.txt"), "w")
for l in lex:
lex_file.write("%s\n" % l)
units_file.close()
lex_file.close()
| # author: <NAME>, CMU, 2015
import sys
from os import path
import ntpath
combine_option=sys.argv[1]
dst_dir=sys.argv[2]
src_dirs=sys.argv[3:]
src_units = []
src_lex = []
units = []
lex = []
startIndex=0
mappings = []
for i in range(len(src_dirs)):
lang = src_dirs[i]
src_units.append(open(path.join(lang, "units.txt")).readlines())
src_lex.append(open(path.join(lang, "lexicon_numbers.txt")).readlines())
print "Language " + lang + " has " + str(len(src_units[-1])) + " units and " + str(len(src_lex[-1])) + " words in the lexicon"
if combine_option == 'agg':
for i in range(len(src_dirs)):
mapping = []
for unit in src_units[i]:
units.append("l" + str(i+1) + "_" + unit.split(' ')[0] + " " + str(startIndex + int(unit.split(' ')[1])))
mapping.append(len(units))
for line in src_lex[i]:
tkns = line.strip().split(' ')
lex.append("l" + str(i+1) + "_" + tkns[0] + " ")
for l in range(1, len(tkns)):
if tkns[l] == ".":
lex[-1] = lex[-1] + tkns[l] + " "
else:
lex[-1] = lex[-1] + str(startIndex + int(tkns[l])) + " "
mappings.append(mapping)
startIndex = startIndex + len(src_units[i])
elif combine_option == 'block':
for i in range(len(src_dirs)):
mapping = []
for unit in src_units[i]:
units.append("l" + str(i+1) + "_" + unit.split(' ')[0] + " " + str(startIndex + int(unit.split(' ')[1])))
mapping.append(len(units)+i)
for line in src_lex[i]:
tkns = line.strip().split(' ')
lex.append("l" + str(i+1) + "_" + tkns[0] + " ")
for l in range(1, len(tkns)):
if tkns[l] == ".":
lex[-1] = lex[-1] + tkns[l] + " "
else:
lex[-1] = lex[-1] + str(startIndex + int(tkns[l])) + " "
mappings.append(mapping)
startIndex = startIndex + len(src_units[i]) + 1
elif combine_option == 'share':
for i in range(len(src_dirs)):
mapping = []
for unit in src_units[i]:
u = unit.split(' ')[0]
if not u in units:
units.append(str(u))
mapping.append(units.index(u) + 1)
for line in src_lex[i]:
tkns = line.strip().split(' ')
lex.append(tkns[0] + " ")
for l in range(1, len(tkns)):
if tkns[l] == ".":
lex[-1] = lex[-1] + tkns[l] + " "
else:
lex[-1] = lex[-1] + str(mapping[int(tkns[l])-1]) + " "
mappings.append(mapping)
print "LEN: "+ str(len(mappings))
for i in range(len(src_dirs)):
mapping_file=open(path.join(dst_dir, path.basename(path.normpath(src_dirs[i] + "../../..")) + str(i) + "-mapping.txt"), 'w+');
mapping = mappings[i]
for i in range(len(mapping)):
m = mapping[i]
m = str(i+1) + " " + str(m)
mapping_file.write("%s\n" % m)
units_file=open(path.join(dst_dir, "units.txt"), "w")
i = 1
for u in units:
if combine_option == 'share':
u = u + " " + str(i)
units_file.write("%s\n" % u)
i = i + 1
lex_file=open(path.join(dst_dir, "lexicon_numbers.txt"), "w")
for l in lex:
lex_file.write("%s\n" % l)
units_file.close()
lex_file.close()
| en | 0.679438 | # author: <NAME>, CMU, 2015 | 2.361272 | 2 |
dataset/filter_noun_pairs.py | vered1986/HypNN | 91 | 6620259 | <filename>dataset/filter_noun_pairs.py
import codecs
import re
import random
import math
from docopt import docopt
from knowledge_resource import KnowledgeResource
NEG_POS_RATIO = 4
def main():
"""
Filter out pairs from the dataset, to keep only those with enough path occurrences in the corpus
"""
# Get the arguments
args = docopt("""Filter out pairs from the dataset, to keep only those with enough path occurrences in the corpus
Usage:
filter_noun_pairs.py <corpus_prefix> <dataset_file> <min_occurrences>
<corpus_prefix> = the corpus' resource file prefix
<dataset_file> = the original dataset file
<min_occurrences> = the minimum required occurrences in different paths
""")
corpus_prefix = args['<corpus_prefix>']
dataset_file = args['<dataset_file>']
min_occurrences = int(args['<min_occurrences>'])
# Load the resource (processed corpus)
print 'Loading the corpus...'
corpus = KnowledgeResource(corpus_prefix)
print 'Done!'
# Load the dataset
print 'Loading the dataset...'
dataset = load_dataset(dataset_file)
# Filter noun-pairs: keep only noun pairs that occurred with at least 5 unique paths
print 'Filtering out noun-pairs...'
filtered_pairs = filter_noun_pairs(corpus, dataset.keys(), min_occurrences)
positives = [(x, y) for (x, y) in filtered_pairs if dataset[(x, y)] == 'True' ]
negatives = [(x, y) for (x, y) in filtered_pairs if dataset[(x, y)] == 'False' ]
if len(negatives) > len(positives) * NEG_POS_RATIO:
filtered_pairs = random.sample(negatives, len(positives) * NEG_POS_RATIO) + positives
else:
filtered_pairs = random.sample(positives, int(math.ceil(len(negatives) / NEG_POS_RATIO))) + negatives
random.shuffle(filtered_pairs)
with codecs.open(dataset_file.replace('.tsv', '_filtered.tsv'), 'w', 'utf-8') as f_out:
print >> f_out, '\n'.join(['\t'.join([x, y, dataset[(x, y)]]) for (x, y) in filtered_pairs])
print 'Done!'
def load_dataset(dataset_file):
"""
Load the dataset
:param dataset_file:
:return:
"""
with codecs.open(dataset_file, 'r', 'utf-8') as f_in:
lines = [tuple(line.strip().split('\t')) for line in f_in]
dataset = { (x, y) : label for (x, y, label) in lines }
return dataset
def filter_noun_pairs(corpus, dataset_keys, min_occurrences):
"""
Filter out pairs from the dataset, to keep only those with enough path occurrences in the corpus
:param corpus: the corpus resource object
:param dataset_keys: the (x,y) pairs in the dataset
:param min_occurrences: the minimum required occurrences in different paths
:return:
"""
first_filter = [(x, y) for (x, y) in dataset_keys if len(x) > 3 and len(y) > 3 and
len(set(x.split(' ')).intersection(y.split(' '))) == 0]
keys = [(corpus.get_id_by_term(str(x)), corpus.get_id_by_term(str(y))) for (x, y) in first_filter]
no_sat_pattern = re.compile('^X/.*Y/[^/]+/[^/]+$')
paths_x_to_y = [set(get_paths(corpus, x_id, y_id, no_sat_pattern)) for (x_id, y_id) in keys]
filtered_keys = [first_filter[i] for i, key in enumerate(keys) if len(paths_x_to_y[i]) >= min_occurrences]
return filtered_keys
def get_paths(corpus, x, y, pattern):
"""
Returns the paths between (x, y) term-pair
:param corpus: the corpus resource object
:param x: the X entity
:param y: the Y entity
:param pattern: path patterns to exclude (e.g. satellites)
:return: all paths between (x, y) which do not match the pattern
"""
x_to_y_paths = corpus.get_relations(x, y)
paths = [path_id for path_id in x_to_y_paths.keys() if pattern.match(corpus.get_path_by_id(path_id))]
return paths
if __name__ == '__main__':
main() | <filename>dataset/filter_noun_pairs.py
import codecs
import re
import random
import math
from docopt import docopt
from knowledge_resource import KnowledgeResource
NEG_POS_RATIO = 4
def main():
"""
Filter out pairs from the dataset, to keep only those with enough path occurrences in the corpus
"""
# Get the arguments
args = docopt("""Filter out pairs from the dataset, to keep only those with enough path occurrences in the corpus
Usage:
filter_noun_pairs.py <corpus_prefix> <dataset_file> <min_occurrences>
<corpus_prefix> = the corpus' resource file prefix
<dataset_file> = the original dataset file
<min_occurrences> = the minimum required occurrences in different paths
""")
corpus_prefix = args['<corpus_prefix>']
dataset_file = args['<dataset_file>']
min_occurrences = int(args['<min_occurrences>'])
# Load the resource (processed corpus)
print 'Loading the corpus...'
corpus = KnowledgeResource(corpus_prefix)
print 'Done!'
# Load the dataset
print 'Loading the dataset...'
dataset = load_dataset(dataset_file)
# Filter noun-pairs: keep only noun pairs that occurred with at least 5 unique paths
print 'Filtering out noun-pairs...'
filtered_pairs = filter_noun_pairs(corpus, dataset.keys(), min_occurrences)
positives = [(x, y) for (x, y) in filtered_pairs if dataset[(x, y)] == 'True' ]
negatives = [(x, y) for (x, y) in filtered_pairs if dataset[(x, y)] == 'False' ]
if len(negatives) > len(positives) * NEG_POS_RATIO:
filtered_pairs = random.sample(negatives, len(positives) * NEG_POS_RATIO) + positives
else:
filtered_pairs = random.sample(positives, int(math.ceil(len(negatives) / NEG_POS_RATIO))) + negatives
random.shuffle(filtered_pairs)
with codecs.open(dataset_file.replace('.tsv', '_filtered.tsv'), 'w', 'utf-8') as f_out:
print >> f_out, '\n'.join(['\t'.join([x, y, dataset[(x, y)]]) for (x, y) in filtered_pairs])
print 'Done!'
def load_dataset(dataset_file):
"""
Load the dataset
:param dataset_file:
:return:
"""
with codecs.open(dataset_file, 'r', 'utf-8') as f_in:
lines = [tuple(line.strip().split('\t')) for line in f_in]
dataset = { (x, y) : label for (x, y, label) in lines }
return dataset
def filter_noun_pairs(corpus, dataset_keys, min_occurrences):
"""
Filter out pairs from the dataset, to keep only those with enough path occurrences in the corpus
:param corpus: the corpus resource object
:param dataset_keys: the (x,y) pairs in the dataset
:param min_occurrences: the minimum required occurrences in different paths
:return:
"""
first_filter = [(x, y) for (x, y) in dataset_keys if len(x) > 3 and len(y) > 3 and
len(set(x.split(' ')).intersection(y.split(' '))) == 0]
keys = [(corpus.get_id_by_term(str(x)), corpus.get_id_by_term(str(y))) for (x, y) in first_filter]
no_sat_pattern = re.compile('^X/.*Y/[^/]+/[^/]+$')
paths_x_to_y = [set(get_paths(corpus, x_id, y_id, no_sat_pattern)) for (x_id, y_id) in keys]
filtered_keys = [first_filter[i] for i, key in enumerate(keys) if len(paths_x_to_y[i]) >= min_occurrences]
return filtered_keys
def get_paths(corpus, x, y, pattern):
"""
Returns the paths between (x, y) term-pair
:param corpus: the corpus resource object
:param x: the X entity
:param y: the Y entity
:param pattern: path patterns to exclude (e.g. satellites)
:return: all paths between (x, y) which do not match the pattern
"""
x_to_y_paths = corpus.get_relations(x, y)
paths = [path_id for path_id in x_to_y_paths.keys() if pattern.match(corpus.get_path_by_id(path_id))]
return paths
if __name__ == '__main__':
main() | en | 0.749614 | Filter out pairs from the dataset, to keep only those with enough path occurrences in the corpus # Get the arguments Filter out pairs from the dataset, to keep only those with enough path occurrences in the corpus Usage: filter_noun_pairs.py <corpus_prefix> <dataset_file> <min_occurrences> <corpus_prefix> = the corpus' resource file prefix <dataset_file> = the original dataset file <min_occurrences> = the minimum required occurrences in different paths # Load the resource (processed corpus) # Load the dataset # Filter noun-pairs: keep only noun pairs that occurred with at least 5 unique paths Load the dataset :param dataset_file: :return: Filter out pairs from the dataset, to keep only those with enough path occurrences in the corpus :param corpus: the corpus resource object :param dataset_keys: the (x,y) pairs in the dataset :param min_occurrences: the minimum required occurrences in different paths :return: Returns the paths between (x, y) term-pair :param corpus: the corpus resource object :param x: the X entity :param y: the Y entity :param pattern: path patterns to exclude (e.g. satellites) :return: all paths between (x, y) which do not match the pattern | 3.123122 | 3 |
generate_mpiwrapper_definitions_fortran.py | ocaisa/MPIwrapper | 0 | 6620260 | <filename>generate_mpiwrapper_definitions_fortran.py
#!/usr/bin/env python3
import re
from string import Template
from mpi_constants_fortran import constants_fortran
def wrap(line):
lines = []
while len(line) > 72:
lines.append(line[0:72] + "&")
line = " &" + line[72:]
lines.append(line)
return "\n".join(lines)
print()
print("! Fortran constants")
# Declarations
for (tp, nm) in constants_fortran:
subs = {'mpi_nm': nm,
'abi_nm': re.sub(r"MPI(X?)_", r"MPI\1ABI_", nm)}
tmpl = []
tmpl.append(" integer $abi_nm")
tmpl.append(" common /$abi_nm/ $abi_nm")
print("\n".join(map(lambda line: wrap(Template(line).substitute(subs)), tmpl)))
# Definitions
for (tp, nm) in constants_fortran:
subs = {'mpi_nm': nm,
'abi_nm': re.sub(r"MPI(X?)_", r"MPI\1ABI_", nm)}
tmpl = []
tmpl.append(" $abi_nm = $mpi_nm")
print("\n".join(map(lambda line: wrap(Template(line).substitute(subs)), tmpl)))
| <filename>generate_mpiwrapper_definitions_fortran.py
#!/usr/bin/env python3
import re
from string import Template
from mpi_constants_fortran import constants_fortran
def wrap(line):
lines = []
while len(line) > 72:
lines.append(line[0:72] + "&")
line = " &" + line[72:]
lines.append(line)
return "\n".join(lines)
print()
print("! Fortran constants")
# Declarations
for (tp, nm) in constants_fortran:
subs = {'mpi_nm': nm,
'abi_nm': re.sub(r"MPI(X?)_", r"MPI\1ABI_", nm)}
tmpl = []
tmpl.append(" integer $abi_nm")
tmpl.append(" common /$abi_nm/ $abi_nm")
print("\n".join(map(lambda line: wrap(Template(line).substitute(subs)), tmpl)))
# Definitions
for (tp, nm) in constants_fortran:
subs = {'mpi_nm': nm,
'abi_nm': re.sub(r"MPI(X?)_", r"MPI\1ABI_", nm)}
tmpl = []
tmpl.append(" $abi_nm = $mpi_nm")
print("\n".join(map(lambda line: wrap(Template(line).substitute(subs)), tmpl)))
| en | 0.241458 | #!/usr/bin/env python3 # Declarations # Definitions | 2.663498 | 3 |
src/config.py | klapen/web-screenshot-importer | 0 | 6620261 | <reponame>klapen/web-screenshot-importer
import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname(__file__))
# Configure the SQLAlchemy
app.config['SQLALCHEMY_ECHO'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////' + os.path.join(basedir, 'main.db')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
db = SQLAlchemy(app)
ma = Marshmallow(app)
| import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname(__file__))
# Configure the SQLAlchemy
app.config['SQLALCHEMY_ECHO'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////' + os.path.join(basedir, 'main.db')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
db = SQLAlchemy(app)
ma = Marshmallow(app) | en | 0.239999 | # Configure the SQLAlchemy | 2.180604 | 2 |
IntegratedGradientsRunner.py | xypan1232/ToxDL | 4 | 6620262 | __author__ = 'jasper.zuallaert'
import sys
import numpy as np
import InputManager as im
import os
import warnings
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import tensorflow as tf
MAXIMUM_LENGTH = 1002 # hard-coded maximum length, for now
# Called from SingleTermWorkflow, or as a standalone python script
# Takes a trained model, and generates saliency maps for all sequences in a given test_dataset
# The train_dataset given is used for calculating the reference, if desired
# Note that this should only be used in case of one-hot encoding
# Other inputs are Tensorflow tensors/placeholders and a session object
# - termN: the index of the term in the Y labels (0 if only one term in dataset)
# - prediction_logits: tf Tensor of shape (n, c) with n the number of samples in the batch, and c the number of classes
# in the dataset
# - sess: The tf session object containing the model
# - X_ph: Placeholder as initialized in NetworkTopologyConstructor.py
# - seqlens_ph: Placeholder as initialized in NetworkTopologyConstructor.py
# - dropout_ph: Placeholder as initialized in NetworkTopologyConstructor.py
# - train_dataset: Dataset object, which should be the training+validation set (used to calculate the reference)
# - test_dataset: Dataset object, containing the test set (for which saliency maps will be generated)
# - use_reference: Indicates whether to run Integrated Gradients with a reference (= the average amino acid frequencies
# or without (=
# Because of varying input lengths, the frequencies are calculated separately for the first 'ran'
# (variable name, see code; by default 5) and the last 'ran' amino acids, and for all the ones in
# between, the average for all amino acids from position 5 until -5 is calculated.
# - outF: An output file to write to (can be None for standard output)
def runIntegratedGradientsOnTestSet(termN,
predictions_logits,
sess,
X_ph,
seqlens_ph,
dropout_ph,
train_dataset,
test_dataset,
use_reference = False,
outF = None):
graph = tf.get_default_graph()
### get the tensor that yields the embedding output (one-hot encoding)
embedding_f = graph.get_tensor_by_name("embedding_out:0")
### get the logit of the one term we're interested in
term_logit = tf.expand_dims(tf.gather(predictions_logits, termN, axis=1), 1)
### tensor for gradient calculation on that embedding output
gs = tf.gradients(term_logit, embedding_f)
epoch_finished = False
outFile = open(outF, 'w') if outF else None
### Calculate the reference (ran first positions, ran last positions and an average for all positions in between)
ran = 5
freqs = np.zeros((ran * 2 + 1, 20), dtype=np.float32)
if use_reference:
for sequence, seqlen in zip(train_dataset.getX(),train_dataset.getLengths()):
seqlen = min(MAXIMUM_LENGTH, seqlen)
for pos in range(ran):
freqs[pos][int(sequence[pos]-1)] += 1
freqs[-pos-1][int(sequence[seqlen-pos-1]-1)] += 1
for pos in range(ran,seqlen-ran):
freqs[ran][int(sequence[pos]-1)] += 1
for pos in range(ran*2+1):
freqs[pos] /= sum(freqs[pos])
### Increase num_integration_steps for higher precision
### Here, for each step, the gradient is calculated for the difference with the reference (which increases with
### each step)
num_integration_steps = 30
while not epoch_finished:
batch_x, lengths_x, batch_y, vector_data, epoch_finished = test_dataset.next_batch(1024)
lengths_x = [min(x,MAXIMUM_LENGTH) for x in lengths_x] # max 1002 by default!
embedding_results = sess.run(embedding_f, feed_dict={X_ph: batch_x, seqlens_ph: lengths_x})
### Calculate the difference from reference
if use_reference:
difference_part = np.zeros_like(embedding_results)
for seq_n in range(len(batch_x)):
for pos in range(ran):
difference_part[seq_n][pos] = (embedding_results[seq_n][pos] - freqs[pos]) / num_integration_steps
for pos in range(ran,lengths_x[seq_n]-ran):
difference_part[seq_n][pos] = (embedding_results[seq_n][pos] - freqs[ran]) / num_integration_steps
for pos in range(lengths_x[seq_n]-ran,lengths_x[seq_n]):
difference_part[seq_n][pos] = (embedding_results[seq_n][pos] - freqs[pos-lengths_x[seq_n]]) / num_integration_steps
# k = 3 # this was some code to check correctness. Leaving it here for now
# print(lengths_x[k])
# for aa_n in range(20):
# print(','.join(['{: .3f}'.format(difference_part[k][index][aa_n][0]) for index in range(lengths_x[k])]))
# print()
# for aa_n in range(20):
# print(','.join(['{:6d}'.format(int(embedding_results[k][index][aa_n][0])) for index in range(lengths_x[k])]))
# print()
# for aa_n in range(20):
# print(','.join(['{: .3f}'.format(freqs[index][aa_n][0]) for index in range(ran*2+1)]))
# exit()
else:
difference_part = embedding_results / num_integration_steps
### Calculate the gradients for each step
allNucs = batch_x
allClasses = [y[termN] for y in batch_y]
allSeqLens = lengths_x
allValues = np.zeros((len(batch_x), len(batch_x[0]),20), np.float32)
allPreds = [p[termN] for p in sess.run(tf.math.sigmoid(predictions_logits),feed_dict={X_ph: batch_x, seqlens_ph: lengths_x,dropout_ph: 0.0})]
for step in range(1, num_integration_steps + 1):
baseline = np.zeros_like(embedding_results)
if use_reference:
for seq_n in range(len(batch_x)):
for pos in range(ran):
baseline[seq_n][pos] = freqs[pos]
for pos in range(ran,lengths_x[seq_n]-ran):
baseline[seq_n][pos] = freqs[ran]
for pos in range(lengths_x[seq_n]-ran,lengths_x[seq_n]):
baseline[seq_n][pos] = freqs[pos-lengths_x[seq_n]]
batch_x_for_this_step_1 = baseline + difference_part * (step - 1)
batch_x_for_this_step_2 = baseline + difference_part * step
all_gradients_1 = sess.run(gs, feed_dict={embedding_f: batch_x_for_this_step_1, seqlens_ph: lengths_x,dropout_ph: 0.0})[0]
all_gradients_2 = sess.run(gs, feed_dict={embedding_f: batch_x_for_this_step_2, seqlens_ph: lengths_x,dropout_ph: 0.0})[0]
allValues += (all_gradients_1 + all_gradients_2) / 2 * difference_part
### Generate outputs. Note that the sequence printed out could be truncated if the actual length surpasses the
### maximum length (1002 by default)
for pred, seq, cl, seqlen, values in zip(allPreds, allNucs, allClasses, allSeqLens, allValues):
print('{},{},actual_length={}'.format(pred, cl, seqlen),file=outFile)
print(','.join(['_ACDEFGHIKLMNPQRSTVWY'[int(nuc)] for nuc in seq[:seqlen]]),file=outFile)
print(','.join([str(score[int(nuc)-1]) for score, nuc in zip(values[:seqlen], seq[:seqlen])]),file=outFile)
# Function to call if we want to use IntegratedGradients.py from another file (such as SingleTermWorkflow.py)
# - For parameters, see the explanation for the function above
def runFromSession(termN, sess, train_set, test_set, useRef = True, outF = None):
graph = tf.get_default_graph()
prediction_logits = graph.get_tensor_by_name("my_logits:0")
X_placeholder = graph.get_tensor_by_name("X_placeholder:0")
seqlen_ph = graph.get_tensor_by_name("seqlen_placeholder:0")
dropout_ph = graph.get_tensor_by_name("dropout_placeholder:0")
runIntegratedGradientsOnTestSet(termN, prediction_logits, sess, X_placeholder, seqlen_ph, dropout_ph, train_set, test_set, useRef, outF)
# If called as a standalone python script, it should have the 5 arguments as stated below
if len(sys.argv) != 6 and sys.argv[0] == 'IntegratedGradientsRunner.py':
print('Usage: python IntegratedGradientsRunner.py <term number> <parameter file> <train file> <test file> <use_reference>')
elif sys.argv[0] == 'IntegratedGradientsRunner.py':
termN = int(sys.argv[1])
paramFile = sys.argv[2] # e.g. 'parameters/test_181212_225609
trainFile = sys.argv[3] # e.g. 'inputs/mf_train.dat'
testFile = sys.argv[4] # e.g. 'inputs/mf_test.dat'
useRef = bool(sys.argv[5])
train_set = im.getSequences(trainFile,1,MAXIMUM_LENGTH,silent=True)
test_set = im.getSequences(testFile,1,MAXIMUM_LENGTH,silent=True)
config = tf.ConfigProto(allow_soft_placement=True)
config.gpu_options.allow_growth = True
sess = tf.Session(config=config)
paramFile = paramFile
paramFileFullName = paramFile + '/' + paramFile[paramFile.rfind('/') + 1:]
saver = tf.train.import_meta_graph(paramFileFullName + '.meta')
saver.restore(sess, tf.train.latest_checkpoint(paramFile))
runFromSession(termN, sess, train_set, test_set, useRef=useRef)
| __author__ = 'jasper.zuallaert'
import sys
import numpy as np
import InputManager as im
import os
import warnings
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import tensorflow as tf
MAXIMUM_LENGTH = 1002 # hard-coded maximum length, for now
# Called from SingleTermWorkflow, or as a standalone python script
# Takes a trained model, and generates saliency maps for all sequences in a given test_dataset
# The train_dataset given is used for calculating the reference, if desired
# Note that this should only be used in case of one-hot encoding
# Other inputs are Tensorflow tensors/placeholders and a session object
# - termN: the index of the term in the Y labels (0 if only one term in dataset)
# - prediction_logits: tf Tensor of shape (n, c) with n the number of samples in the batch, and c the number of classes
# in the dataset
# - sess: The tf session object containing the model
# - X_ph: Placeholder as initialized in NetworkTopologyConstructor.py
# - seqlens_ph: Placeholder as initialized in NetworkTopologyConstructor.py
# - dropout_ph: Placeholder as initialized in NetworkTopologyConstructor.py
# - train_dataset: Dataset object, which should be the training+validation set (used to calculate the reference)
# - test_dataset: Dataset object, containing the test set (for which saliency maps will be generated)
# - use_reference: Indicates whether to run Integrated Gradients with a reference (= the average amino acid frequencies
# or without (=
# Because of varying input lengths, the frequencies are calculated separately for the first 'ran'
# (variable name, see code; by default 5) and the last 'ran' amino acids, and for all the ones in
# between, the average for all amino acids from position 5 until -5 is calculated.
# - outF: An output file to write to (can be None for standard output)
def runIntegratedGradientsOnTestSet(termN,
predictions_logits,
sess,
X_ph,
seqlens_ph,
dropout_ph,
train_dataset,
test_dataset,
use_reference = False,
outF = None):
graph = tf.get_default_graph()
### get the tensor that yields the embedding output (one-hot encoding)
embedding_f = graph.get_tensor_by_name("embedding_out:0")
### get the logit of the one term we're interested in
term_logit = tf.expand_dims(tf.gather(predictions_logits, termN, axis=1), 1)
### tensor for gradient calculation on that embedding output
gs = tf.gradients(term_logit, embedding_f)
epoch_finished = False
outFile = open(outF, 'w') if outF else None
### Calculate the reference (ran first positions, ran last positions and an average for all positions in between)
ran = 5
freqs = np.zeros((ran * 2 + 1, 20), dtype=np.float32)
if use_reference:
for sequence, seqlen in zip(train_dataset.getX(),train_dataset.getLengths()):
seqlen = min(MAXIMUM_LENGTH, seqlen)
for pos in range(ran):
freqs[pos][int(sequence[pos]-1)] += 1
freqs[-pos-1][int(sequence[seqlen-pos-1]-1)] += 1
for pos in range(ran,seqlen-ran):
freqs[ran][int(sequence[pos]-1)] += 1
for pos in range(ran*2+1):
freqs[pos] /= sum(freqs[pos])
### Increase num_integration_steps for higher precision
### Here, for each step, the gradient is calculated for the difference with the reference (which increases with
### each step)
num_integration_steps = 30
while not epoch_finished:
batch_x, lengths_x, batch_y, vector_data, epoch_finished = test_dataset.next_batch(1024)
lengths_x = [min(x,MAXIMUM_LENGTH) for x in lengths_x] # max 1002 by default!
embedding_results = sess.run(embedding_f, feed_dict={X_ph: batch_x, seqlens_ph: lengths_x})
### Calculate the difference from reference
if use_reference:
difference_part = np.zeros_like(embedding_results)
for seq_n in range(len(batch_x)):
for pos in range(ran):
difference_part[seq_n][pos] = (embedding_results[seq_n][pos] - freqs[pos]) / num_integration_steps
for pos in range(ran,lengths_x[seq_n]-ran):
difference_part[seq_n][pos] = (embedding_results[seq_n][pos] - freqs[ran]) / num_integration_steps
for pos in range(lengths_x[seq_n]-ran,lengths_x[seq_n]):
difference_part[seq_n][pos] = (embedding_results[seq_n][pos] - freqs[pos-lengths_x[seq_n]]) / num_integration_steps
# k = 3 # this was some code to check correctness. Leaving it here for now
# print(lengths_x[k])
# for aa_n in range(20):
# print(','.join(['{: .3f}'.format(difference_part[k][index][aa_n][0]) for index in range(lengths_x[k])]))
# print()
# for aa_n in range(20):
# print(','.join(['{:6d}'.format(int(embedding_results[k][index][aa_n][0])) for index in range(lengths_x[k])]))
# print()
# for aa_n in range(20):
# print(','.join(['{: .3f}'.format(freqs[index][aa_n][0]) for index in range(ran*2+1)]))
# exit()
else:
difference_part = embedding_results / num_integration_steps
### Calculate the gradients for each step
allNucs = batch_x
allClasses = [y[termN] for y in batch_y]
allSeqLens = lengths_x
allValues = np.zeros((len(batch_x), len(batch_x[0]),20), np.float32)
allPreds = [p[termN] for p in sess.run(tf.math.sigmoid(predictions_logits),feed_dict={X_ph: batch_x, seqlens_ph: lengths_x,dropout_ph: 0.0})]
for step in range(1, num_integration_steps + 1):
baseline = np.zeros_like(embedding_results)
if use_reference:
for seq_n in range(len(batch_x)):
for pos in range(ran):
baseline[seq_n][pos] = freqs[pos]
for pos in range(ran,lengths_x[seq_n]-ran):
baseline[seq_n][pos] = freqs[ran]
for pos in range(lengths_x[seq_n]-ran,lengths_x[seq_n]):
baseline[seq_n][pos] = freqs[pos-lengths_x[seq_n]]
batch_x_for_this_step_1 = baseline + difference_part * (step - 1)
batch_x_for_this_step_2 = baseline + difference_part * step
all_gradients_1 = sess.run(gs, feed_dict={embedding_f: batch_x_for_this_step_1, seqlens_ph: lengths_x,dropout_ph: 0.0})[0]
all_gradients_2 = sess.run(gs, feed_dict={embedding_f: batch_x_for_this_step_2, seqlens_ph: lengths_x,dropout_ph: 0.0})[0]
allValues += (all_gradients_1 + all_gradients_2) / 2 * difference_part
### Generate outputs. Note that the sequence printed out could be truncated if the actual length surpasses the
### maximum length (1002 by default)
for pred, seq, cl, seqlen, values in zip(allPreds, allNucs, allClasses, allSeqLens, allValues):
print('{},{},actual_length={}'.format(pred, cl, seqlen),file=outFile)
print(','.join(['_ACDEFGHIKLMNPQRSTVWY'[int(nuc)] for nuc in seq[:seqlen]]),file=outFile)
print(','.join([str(score[int(nuc)-1]) for score, nuc in zip(values[:seqlen], seq[:seqlen])]),file=outFile)
# Function to call if we want to use IntegratedGradients.py from another file (such as SingleTermWorkflow.py)
# - For parameters, see the explanation for the function above
def runFromSession(termN, sess, train_set, test_set, useRef = True, outF = None):
graph = tf.get_default_graph()
prediction_logits = graph.get_tensor_by_name("my_logits:0")
X_placeholder = graph.get_tensor_by_name("X_placeholder:0")
seqlen_ph = graph.get_tensor_by_name("seqlen_placeholder:0")
dropout_ph = graph.get_tensor_by_name("dropout_placeholder:0")
runIntegratedGradientsOnTestSet(termN, prediction_logits, sess, X_placeholder, seqlen_ph, dropout_ph, train_set, test_set, useRef, outF)
# If called as a standalone python script, it should have the 5 arguments as stated below
if len(sys.argv) != 6 and sys.argv[0] == 'IntegratedGradientsRunner.py':
print('Usage: python IntegratedGradientsRunner.py <term number> <parameter file> <train file> <test file> <use_reference>')
elif sys.argv[0] == 'IntegratedGradientsRunner.py':
termN = int(sys.argv[1])
paramFile = sys.argv[2] # e.g. 'parameters/test_181212_225609
trainFile = sys.argv[3] # e.g. 'inputs/mf_train.dat'
testFile = sys.argv[4] # e.g. 'inputs/mf_test.dat'
useRef = bool(sys.argv[5])
train_set = im.getSequences(trainFile,1,MAXIMUM_LENGTH,silent=True)
test_set = im.getSequences(testFile,1,MAXIMUM_LENGTH,silent=True)
config = tf.ConfigProto(allow_soft_placement=True)
config.gpu_options.allow_growth = True
sess = tf.Session(config=config)
paramFile = paramFile
paramFileFullName = paramFile + '/' + paramFile[paramFile.rfind('/') + 1:]
saver = tf.train.import_meta_graph(paramFileFullName + '.meta')
saver.restore(sess, tf.train.latest_checkpoint(paramFile))
runFromSession(termN, sess, train_set, test_set, useRef=useRef)
| en | 0.774248 | # hard-coded maximum length, for now # Called from SingleTermWorkflow, or as a standalone python script # Takes a trained model, and generates saliency maps for all sequences in a given test_dataset # The train_dataset given is used for calculating the reference, if desired # Note that this should only be used in case of one-hot encoding # Other inputs are Tensorflow tensors/placeholders and a session object # - termN: the index of the term in the Y labels (0 if only one term in dataset) # - prediction_logits: tf Tensor of shape (n, c) with n the number of samples in the batch, and c the number of classes # in the dataset # - sess: The tf session object containing the model # - X_ph: Placeholder as initialized in NetworkTopologyConstructor.py # - seqlens_ph: Placeholder as initialized in NetworkTopologyConstructor.py # - dropout_ph: Placeholder as initialized in NetworkTopologyConstructor.py # - train_dataset: Dataset object, which should be the training+validation set (used to calculate the reference) # - test_dataset: Dataset object, containing the test set (for which saliency maps will be generated) # - use_reference: Indicates whether to run Integrated Gradients with a reference (= the average amino acid frequencies # or without (= # Because of varying input lengths, the frequencies are calculated separately for the first 'ran' # (variable name, see code; by default 5) and the last 'ran' amino acids, and for all the ones in # between, the average for all amino acids from position 5 until -5 is calculated. # - outF: An output file to write to (can be None for standard output) ### get the tensor that yields the embedding output (one-hot encoding) ### get the logit of the one term we're interested in ### tensor for gradient calculation on that embedding output ### Calculate the reference (ran first positions, ran last positions and an average for all positions in between) ### Increase num_integration_steps for higher precision ### Here, for each step, the gradient is calculated for the difference with the reference (which increases with ### each step) # max 1002 by default! ### Calculate the difference from reference # k = 3 # this was some code to check correctness. Leaving it here for now # print(lengths_x[k]) # for aa_n in range(20): # print(','.join(['{: .3f}'.format(difference_part[k][index][aa_n][0]) for index in range(lengths_x[k])])) # print() # for aa_n in range(20): # print(','.join(['{:6d}'.format(int(embedding_results[k][index][aa_n][0])) for index in range(lengths_x[k])])) # print() # for aa_n in range(20): # print(','.join(['{: .3f}'.format(freqs[index][aa_n][0]) for index in range(ran*2+1)])) # exit() ### Calculate the gradients for each step ### Generate outputs. Note that the sequence printed out could be truncated if the actual length surpasses the ### maximum length (1002 by default) # Function to call if we want to use IntegratedGradients.py from another file (such as SingleTermWorkflow.py) # - For parameters, see the explanation for the function above # If called as a standalone python script, it should have the 5 arguments as stated below # e.g. 'parameters/test_181212_225609 # e.g. 'inputs/mf_train.dat' # e.g. 'inputs/mf_test.dat' | 2.415389 | 2 |
deep_learning/optimizers/lars.py | BobbyZhouZijian/AI-Algo-Implmentations | 0 | 6620263 | import torch
from torch.optim import Optimizer
class LARS(Optimizer):
def __init__(self, params, lr=1e-3, beta=0.9, eps=1e-6, weight_decay=0):
default = dict(
lr=lr,
beta=beta,
eps=eps,
weight_decay=weight_decay,
)
super(LARS, self).__init__(params, default)
def step(self, closure=None):
loss = closure() if closure is not None else None
for group in self.param_groups:
for p in group['params']:
if p.grad is None:
continue
grad = p.grad.data
state = self.state[p]
# initialization
if len(state) == 0:
state['step'] = 0
state['momentum'] = torch.zeros_like(p.data)
momentum = state['momentum']
state['step'] += 1
step_size, beta, weight_decay = group['lr'], group['beta'], group['weight_decay']
sgd_step = grad
if weight_decay != 0:
sgd_step.add_(p.data, alpha=weight_decay)
momentum.mul_(beta).add_(grad + sgd_step, alpha=1 - beta)
weight_norm = p.data.pow(2).sum().sqrt().clamp(0, 10)
momentum_norm = momentum.pow(2).sum().sqrt()
if momentum_norm == 0 or weight_norm == 0:
trust_ratio = 1
else:
trust_ratio = weight_norm / momentum_norm
state['weight_norm'] = weight_norm
state['momentum_norm'] = momentum_norm
state['trust_ratio'] = trust_ratio
p.data.add_(momentum, alpha=-trust_ratio * step_size)
return loss
| import torch
from torch.optim import Optimizer
class LARS(Optimizer):
def __init__(self, params, lr=1e-3, beta=0.9, eps=1e-6, weight_decay=0):
default = dict(
lr=lr,
beta=beta,
eps=eps,
weight_decay=weight_decay,
)
super(LARS, self).__init__(params, default)
def step(self, closure=None):
loss = closure() if closure is not None else None
for group in self.param_groups:
for p in group['params']:
if p.grad is None:
continue
grad = p.grad.data
state = self.state[p]
# initialization
if len(state) == 0:
state['step'] = 0
state['momentum'] = torch.zeros_like(p.data)
momentum = state['momentum']
state['step'] += 1
step_size, beta, weight_decay = group['lr'], group['beta'], group['weight_decay']
sgd_step = grad
if weight_decay != 0:
sgd_step.add_(p.data, alpha=weight_decay)
momentum.mul_(beta).add_(grad + sgd_step, alpha=1 - beta)
weight_norm = p.data.pow(2).sum().sqrt().clamp(0, 10)
momentum_norm = momentum.pow(2).sum().sqrt()
if momentum_norm == 0 or weight_norm == 0:
trust_ratio = 1
else:
trust_ratio = weight_norm / momentum_norm
state['weight_norm'] = weight_norm
state['momentum_norm'] = momentum_norm
state['trust_ratio'] = trust_ratio
p.data.add_(momentum, alpha=-trust_ratio * step_size)
return loss
| en | 0.54543 | # initialization | 2.216845 | 2 |
assesments/migrations/0004_rename_desription_assesment_description.py | gotoiot/service-django-rest-api | 0 | 6620264 | <filename>assesments/migrations/0004_rename_desription_assesment_description.py<gh_stars>0
# Generated by Django 3.2.7 on 2021-10-07 12:00
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('assesments', '0003_alter_taker_age'),
]
operations = [
migrations.RenameField(
model_name='assesment',
old_name='desription',
new_name='description',
),
]
| <filename>assesments/migrations/0004_rename_desription_assesment_description.py<gh_stars>0
# Generated by Django 3.2.7 on 2021-10-07 12:00
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('assesments', '0003_alter_taker_age'),
]
operations = [
migrations.RenameField(
model_name='assesment',
old_name='desription',
new_name='description',
),
]
| en | 0.910972 | # Generated by Django 3.2.7 on 2021-10-07 12:00 | 1.502711 | 2 |
reddit_thebutton/controllers.py | reddit-archive/reddit-plugin-thebutton | 13 | 6620265 | from datetime import datetime
from pylons import c, g
from r2.controllers import add_controller
from r2.controllers.api import ApiController
from r2.lib.validator import (
nop,
validate,
VInt,
VModhash,
VUser,
)
from reddit_thebutton.models import (
ACCOUNT_CREATION_CUTOFF,
ButtonPressByUser,
check_tick_mac,
get_seconds_left,
has_timer_expired,
has_timer_started,
press_button,
set_current_press,
str_to_datetime,
)
from reddit_thebutton.pages import (
TheButtonBase,
TheButton,
)
@add_controller
class ButtonApiController(ApiController):
@validate(
VUser(),
VModhash(),
seconds_remaining=VInt('seconds', min=0, max=60),
previous_seconds=VInt('prev_seconds'),
tick_time=nop('tick_time'),
tick_mac=nop('tick_mac'),
)
def POST_press_button(self, seconds_remaining, previous_seconds, tick_time, tick_mac):
if not g.live_config['thebutton_is_active']:
return
if c.user._date > ACCOUNT_CREATION_CUTOFF:
return
user_has_pressed = ButtonPressByUser.has_pressed(c.user)
if user_has_pressed and not c.user.employee:
return
if has_timer_expired():
# time has expired: no longer possible to press the button
return
has_started = has_timer_started()
if not has_started:
# the timer can only be started through reddit-shell
return
cheater = False
if (seconds_remaining is None or
previous_seconds is None or
tick_time is None or
tick_mac is None):
# incomplete info from client, just let them press it anyways
seconds_remaining = max(0, int(get_seconds_left()))
elif not check_tick_mac(previous_seconds, tick_time, tick_mac):
# can't trust the values sent by the client
seconds_remaining = max(0, int(get_seconds_left()))
cheater = True
else:
# client sent a valid mac so we can trust:
# previous_seconds - the timer value at the last tick
# tick_time - the datetime at the last tick
# check to make sure tick_time wasn't too long ago
then = str_to_datetime(tick_time)
now = datetime.now(g.tz)
if then and (now - then).total_seconds() > 60:
# client sent an old (but potentially valid) mac, etc.
seconds_remaining = max(0, int(get_seconds_left()))
cheater = True
# GOTCHA: the client actually sends the same value for
# previous_seconds and seconds_remaining so make sure those match.
# If the client sent down its own ticking down timer as
# seconds_remaining we would want to compare to previous_seconds to
# make sure they weren't too far apart
if previous_seconds != seconds_remaining:
seconds_remaining = max(0, int(get_seconds_left()))
cheater = True
press_button(c.user)
g.stats.simple_event("thebutton.press")
if cheater:
g.stats.simple_event("thebutton.cheater")
# don't flair on first press (the starter)
if not has_started:
return
if user_has_pressed:
# don't flair on multiple employee presses
return
if cheater:
flair_css = "cheater"
elif seconds_remaining > 51:
flair_css = "press-6"
elif seconds_remaining > 41:
flair_css = "press-5"
elif seconds_remaining > 31:
flair_css = "press-4"
elif seconds_remaining > 21:
flair_css = "press-3"
elif seconds_remaining > 11:
flair_css = "press-2"
else:
flair_css = "press-1"
flair_text = "%ss" % seconds_remaining
setattr(c.user, 'flair_%s_text' % g.live_config["thebutton_srid"], flair_text)
setattr(c.user, 'flair_%s_css_class' % g.live_config["thebutton_srid"], flair_css)
c.user._commit()
| from datetime import datetime
from pylons import c, g
from r2.controllers import add_controller
from r2.controllers.api import ApiController
from r2.lib.validator import (
nop,
validate,
VInt,
VModhash,
VUser,
)
from reddit_thebutton.models import (
ACCOUNT_CREATION_CUTOFF,
ButtonPressByUser,
check_tick_mac,
get_seconds_left,
has_timer_expired,
has_timer_started,
press_button,
set_current_press,
str_to_datetime,
)
from reddit_thebutton.pages import (
TheButtonBase,
TheButton,
)
@add_controller
class ButtonApiController(ApiController):
@validate(
VUser(),
VModhash(),
seconds_remaining=VInt('seconds', min=0, max=60),
previous_seconds=VInt('prev_seconds'),
tick_time=nop('tick_time'),
tick_mac=nop('tick_mac'),
)
def POST_press_button(self, seconds_remaining, previous_seconds, tick_time, tick_mac):
if not g.live_config['thebutton_is_active']:
return
if c.user._date > ACCOUNT_CREATION_CUTOFF:
return
user_has_pressed = ButtonPressByUser.has_pressed(c.user)
if user_has_pressed and not c.user.employee:
return
if has_timer_expired():
# time has expired: no longer possible to press the button
return
has_started = has_timer_started()
if not has_started:
# the timer can only be started through reddit-shell
return
cheater = False
if (seconds_remaining is None or
previous_seconds is None or
tick_time is None or
tick_mac is None):
# incomplete info from client, just let them press it anyways
seconds_remaining = max(0, int(get_seconds_left()))
elif not check_tick_mac(previous_seconds, tick_time, tick_mac):
# can't trust the values sent by the client
seconds_remaining = max(0, int(get_seconds_left()))
cheater = True
else:
# client sent a valid mac so we can trust:
# previous_seconds - the timer value at the last tick
# tick_time - the datetime at the last tick
# check to make sure tick_time wasn't too long ago
then = str_to_datetime(tick_time)
now = datetime.now(g.tz)
if then and (now - then).total_seconds() > 60:
# client sent an old (but potentially valid) mac, etc.
seconds_remaining = max(0, int(get_seconds_left()))
cheater = True
# GOTCHA: the client actually sends the same value for
# previous_seconds and seconds_remaining so make sure those match.
# If the client sent down its own ticking down timer as
# seconds_remaining we would want to compare to previous_seconds to
# make sure they weren't too far apart
if previous_seconds != seconds_remaining:
seconds_remaining = max(0, int(get_seconds_left()))
cheater = True
press_button(c.user)
g.stats.simple_event("thebutton.press")
if cheater:
g.stats.simple_event("thebutton.cheater")
# don't flair on first press (the starter)
if not has_started:
return
if user_has_pressed:
# don't flair on multiple employee presses
return
if cheater:
flair_css = "cheater"
elif seconds_remaining > 51:
flair_css = "press-6"
elif seconds_remaining > 41:
flair_css = "press-5"
elif seconds_remaining > 31:
flair_css = "press-4"
elif seconds_remaining > 21:
flair_css = "press-3"
elif seconds_remaining > 11:
flair_css = "press-2"
else:
flair_css = "press-1"
flair_text = "%ss" % seconds_remaining
setattr(c.user, 'flair_%s_text' % g.live_config["thebutton_srid"], flair_text)
setattr(c.user, 'flair_%s_css_class' % g.live_config["thebutton_srid"], flair_css)
c.user._commit()
| en | 0.913616 | # time has expired: no longer possible to press the button # the timer can only be started through reddit-shell # incomplete info from client, just let them press it anyways # can't trust the values sent by the client # client sent a valid mac so we can trust: # previous_seconds - the timer value at the last tick # tick_time - the datetime at the last tick # check to make sure tick_time wasn't too long ago # client sent an old (but potentially valid) mac, etc. # GOTCHA: the client actually sends the same value for # previous_seconds and seconds_remaining so make sure those match. # If the client sent down its own ticking down timer as # seconds_remaining we would want to compare to previous_seconds to # make sure they weren't too far apart # don't flair on first press (the starter) # don't flair on multiple employee presses | 2.631415 | 3 |
corona_website_app/views.py | Nicholas-Chong/coronavirus_website | 3 | 6620266 | <reponame>Nicholas-Chong/coronavirus_website
from django.shortcuts import render, redirect
from django.http import HttpResponse
from corona_website_app.models import Country, Dates
import json
def index(request):
consolidated = Country.objects.all().order_by('name')
last_updated = str(Dates.objects.all()[0].dates[-1])
context = {
'consolidated' : consolidated,
'last_updated' : last_updated,
}
return render(request, 'corona_website_app/index.html', context=context)
def charts(request):
x_labels = Dates.objects.all()[0].dates
countrys = list(Country.objects.all().order_by('name').values())
# cases_data = {}
# names = []
# for country in countrys:
# cases_data[country.name] = country.daily_confirmed_cases
# names.append(country.name)
context = {
'x_labels' : json.dumps(x_labels),
'countries_json' : json.dumps(countrys),
'countries' : countrys
}
return render(request, 'corona_website_app/charts.html', context=context)
def individual_chart(request):
country_to_chart_name = request.COOKIES['indv_country_to_chart']
country_to_chart_object = list(Country.objects.filter(name=country_to_chart_name).values())
x_labels = Dates.objects.all()[0].dates
context = {
'x_labels' : json.dumps(x_labels),
'country' : json.dumps(country_to_chart_object),
'country_name' : country_to_chart_name,
}
return render(request, 'corona_website_app/chart_individual.html', context=context)
def maps(request):
num_cases_per_country = [country.num_cases for country in Country.objects.exclude(country_code = '').order_by('name')]
country_codes = [country.country_code for country in Country.objects.exclude(country_code = '').order_by('name')]
context = {
'num_cases' : num_cases_per_country,
'codes' : country_codes,
}
return render(request, 'corona_website_app/map.html', context=context)
def about(request):
return render(request, 'corona_website_app/about.html')
| from django.shortcuts import render, redirect
from django.http import HttpResponse
from corona_website_app.models import Country, Dates
import json
def index(request):
consolidated = Country.objects.all().order_by('name')
last_updated = str(Dates.objects.all()[0].dates[-1])
context = {
'consolidated' : consolidated,
'last_updated' : last_updated,
}
return render(request, 'corona_website_app/index.html', context=context)
def charts(request):
x_labels = Dates.objects.all()[0].dates
countrys = list(Country.objects.all().order_by('name').values())
# cases_data = {}
# names = []
# for country in countrys:
# cases_data[country.name] = country.daily_confirmed_cases
# names.append(country.name)
context = {
'x_labels' : json.dumps(x_labels),
'countries_json' : json.dumps(countrys),
'countries' : countrys
}
return render(request, 'corona_website_app/charts.html', context=context)
def individual_chart(request):
country_to_chart_name = request.COOKIES['indv_country_to_chart']
country_to_chart_object = list(Country.objects.filter(name=country_to_chart_name).values())
x_labels = Dates.objects.all()[0].dates
context = {
'x_labels' : json.dumps(x_labels),
'country' : json.dumps(country_to_chart_object),
'country_name' : country_to_chart_name,
}
return render(request, 'corona_website_app/chart_individual.html', context=context)
def maps(request):
num_cases_per_country = [country.num_cases for country in Country.objects.exclude(country_code = '').order_by('name')]
country_codes = [country.country_code for country in Country.objects.exclude(country_code = '').order_by('name')]
context = {
'num_cases' : num_cases_per_country,
'codes' : country_codes,
}
return render(request, 'corona_website_app/map.html', context=context)
def about(request):
return render(request, 'corona_website_app/about.html') | en | 0.34762 | # cases_data = {} # names = [] # for country in countrys: # cases_data[country.name] = country.daily_confirmed_cases # names.append(country.name) | 2.209554 | 2 |
data/extract_cancellations.py | Impactstory/rickscafe-api | 1 | 6620267 | import csv
import re
'''
test cases for the dates extraction
v.18(2007)-
2006-
v.1(1999)-v.4(2003).
v.4:no.3(2005:Dec.)-v.7:no.1(2009:Jan.).
v.2(2001)-v.8:no.3(2007:May/June).
v.28(1996)-v.33:no.4(2001:Nov./Dec.).
v.3:no.2(2008)-v.6(2011).
v.1-2(2013)-
'''
dates = {
"jan": "01",
"feb": "02",
"mar": "03",
"apr": "04",
"may": "05",
"jun": "06",
"jul": "07",
"aug": "08",
"sep": "09",
"oct": "10",
"nov": "11",
"dec": "12",
}
def extract_date(str):
if not str:
return ""
# extract start date
ret = ""
regex = r"\d\d\d\d:\w\w\w|\d\d\d\d"
m = re.search(regex, str)
if m:
my_date = m.group()
my_date = my_date.lower()
my_date = my_date.replace(":", "-")
for month_string, month_iso in dates.iteritems():
my_date = my_date.replace(month_string, month_iso)
ret = my_date
return ret
def split_dates(str):
segments = str.split("-")
date_segments = [x for x in segments if re.search("\d\d\d\d", x)]
if len(date_segments) == 0:
return ["", ""]
elif len(date_segments) == 1:
return date_segments + [""]
else:
return date_segments
def journal_with_dates(journal_row):
all_issns = (journal_row[0] + ";" + journal_row[1]).split(";")
all_issns = "|".join([x for x in all_issns if x])
date_halves = split_dates(journal_row[3])
start_date = extract_date(date_halves[0])
end_date = extract_date(date_halves[1])
return [
all_issns,
start_date,
end_date
]
def get_and_store():
output_rows = []
with open('cancellations-input.csv') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
journal_arr = []
for journal_row in csv_reader:
journal_arr.append(journal_row)
for journal_row in journal_arr[1:]:
new_journal_row = journal_with_dates(journal_row)
output_rows.append(new_journal_row)
with open('cancellations-output.csv', mode='w') as f:
writer = csv.writer(f)
for row in output_rows:
# writer.writerow(row)
# normalize. multiple rows per journal, but just one row per ISSN
for issn in row[0].split("|"):
writer.writerow([issn, row[1], row[2]])
if __name__ == "__main__":
print "i am running"
get_and_store()
| import csv
import re
'''
test cases for the dates extraction
v.18(2007)-
2006-
v.1(1999)-v.4(2003).
v.4:no.3(2005:Dec.)-v.7:no.1(2009:Jan.).
v.2(2001)-v.8:no.3(2007:May/June).
v.28(1996)-v.33:no.4(2001:Nov./Dec.).
v.3:no.2(2008)-v.6(2011).
v.1-2(2013)-
'''
dates = {
"jan": "01",
"feb": "02",
"mar": "03",
"apr": "04",
"may": "05",
"jun": "06",
"jul": "07",
"aug": "08",
"sep": "09",
"oct": "10",
"nov": "11",
"dec": "12",
}
def extract_date(str):
if not str:
return ""
# extract start date
ret = ""
regex = r"\d\d\d\d:\w\w\w|\d\d\d\d"
m = re.search(regex, str)
if m:
my_date = m.group()
my_date = my_date.lower()
my_date = my_date.replace(":", "-")
for month_string, month_iso in dates.iteritems():
my_date = my_date.replace(month_string, month_iso)
ret = my_date
return ret
def split_dates(str):
segments = str.split("-")
date_segments = [x for x in segments if re.search("\d\d\d\d", x)]
if len(date_segments) == 0:
return ["", ""]
elif len(date_segments) == 1:
return date_segments + [""]
else:
return date_segments
def journal_with_dates(journal_row):
all_issns = (journal_row[0] + ";" + journal_row[1]).split(";")
all_issns = "|".join([x for x in all_issns if x])
date_halves = split_dates(journal_row[3])
start_date = extract_date(date_halves[0])
end_date = extract_date(date_halves[1])
return [
all_issns,
start_date,
end_date
]
def get_and_store():
output_rows = []
with open('cancellations-input.csv') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
journal_arr = []
for journal_row in csv_reader:
journal_arr.append(journal_row)
for journal_row in journal_arr[1:]:
new_journal_row = journal_with_dates(journal_row)
output_rows.append(new_journal_row)
with open('cancellations-output.csv', mode='w') as f:
writer = csv.writer(f)
for row in output_rows:
# writer.writerow(row)
# normalize. multiple rows per journal, but just one row per ISSN
for issn in row[0].split("|"):
writer.writerow([issn, row[1], row[2]])
if __name__ == "__main__":
print "i am running"
get_and_store()
| en | 0.300622 | test cases for the dates extraction v.18(2007)- 2006- v.1(1999)-v.4(2003). v.4:no.3(2005:Dec.)-v.7:no.1(2009:Jan.). v.2(2001)-v.8:no.3(2007:May/June). v.28(1996)-v.33:no.4(2001:Nov./Dec.). v.3:no.2(2008)-v.6(2011). v.1-2(2013)- # extract start date # writer.writerow(row) # normalize. multiple rows per journal, but just one row per ISSN | 3.584791 | 4 |
ansible_self_service/l4_core/models.py | ansible-self-service/ansible-self-service | 0 | 6620268 | from dataclasses import dataclass, field
from enum import Enum
from pathlib import Path
from typing import List, ClassVar, Dict, Optional, Tuple
from .exceptions import AppCollectionsAlreadyExistsException, AppCollectionsConfigDoesNotExistException, \
AppCollectionConfigValidationException
from .protocols import AppDirLocatorProtocol, GitClientProtocol, AppCollectionConfigParserProtocol
class AppEvent(Enum):
"""Events that may happen during the application life cycle.
Primarily used for registering callbacks with the UI.
"""
MAIN_WINDOW_READY = 1
@dataclass
class Config:
""""Contains the app config."""
def __init__(self, app_dir_locator: AppDirLocatorProtocol):
self.app_dir_locator = app_dir_locator
@property
def git_directory(self):
"""App data directory containing all git repos with Ansible playbooks."""
git_directory = self.app_dir_locator.get_app_data_dir() / 'git'
git_directory.mkdir(parents=True, exist_ok=True)
return git_directory
@dataclass(frozen=True)
class AnsibleRunResult:
"""Contains data about a completed Ansible run."""
stdout: str
stderr: str
return_code: int
@property
def was_successful(self):
"""True if this run has been successful."""
return self.return_code != 0
@dataclass(frozen=True)
class AppCategory:
"""Used for categorizing self service items it the UI."""
name: str
@dataclass(frozen=True)
class App:
"""A single application that can be installed, updated or removed."""
name: str
description: str
categories: List[AppCategory]
@dataclass
class AppCollection:
"""A collection of apps belonging to the same repository."""
_git_client: GitClientProtocol
_app_collection_config_parser: AppCollectionConfigParserProtocol
name: str
directory: Path
categories: Dict[str, AppCategory] = field(default_factory=dict)
apps: Dict[str, App] = field(default_factory=dict)
validation_error = None
_initialized: bool = False
CONFIG_FILE_NAME: ClassVar[str] = 'self-service.yaml'
class Decorators:
"""Nested class with decorators."""
@classmethod
def initialize(cls, func):
"""Decorator checking if the catalog is initialized before calling the wrapped function."""
def wrapper(self, *args, **kwargs):
if not self._initialized: # pylint: disable=W0212
self.refresh()
self._initialized = True # pylint: disable=W0212
return func(self, *args, **kwargs)
return wrapper
def refresh(self):
"""Read the repo config and (re-)initialize the collection."""
config = self.directory / self.CONFIG_FILE_NAME
if not config.exists():
raise AppCollectionsConfigDoesNotExistException()
try:
categories, apps = self._app_collection_config_parser.from_file(config)
self.categories = {category.name: category for category in categories}
self.apps = {app.name: app for app in apps}
self.validation_error = None
except AppCollectionConfigValidationException as exception:
self.categories = {}
self.apps = {}
self.validation_error = str(exception)
@property # type: ignore
@Decorators.initialize
def revision(self):
"""Return the current revision of the repo."""
return self._git_client.get_revision(self.directory)
@property # type: ignore
@Decorators.initialize
def url(self):
"""Extract the remote URL from the repo."""
return self._git_client.get_origin_url(self.directory)
@Decorators.initialize
def update(self, revision: Optional[str]) -> Tuple[str, str]:
"""Update the repository.
Update to latest main/master commit if no revision is provided.
"""
old_revision = self.revision
self._git_client.update(directory=self.directory, revision=revision)
new_revision = self.revision
return old_revision, new_revision
@dataclass
class AppCatalog:
""""Contains all known apps."""
_config: Config
_git_client: GitClientProtocol
_app_collection_config_parser: AppCollectionConfigParserProtocol
_collections: Dict[str, AppCollection] = field(default_factory=dict)
_initialized: bool = False
class Decorators:
"""Nested class with decorators."""
@classmethod
def initialize(cls, func):
"""Decorator checking if the catalog is initialized before calling the wrapped function."""
def wrapper(self, *args, **kwargs):
if not self._initialized: # pylint: disable=W0212
self.refresh()
self._initialized = True # pylint: disable=W0212
return func(self, *args, **kwargs)
return wrapper
def refresh(self):
"""Check the git directory for existing repos and add them to the list.py."""
self._collections = {}
for child in self._config.git_directory.iterdir():
if self._git_client.is_git_directory(child):
collection_name = str(child.name)
self._collections[collection_name] = self.create_app_collection(child, collection_name)
def get_directory_for_collection(self, name):
"""Locate the target directory for the app repository."""
target_dir = self._config.git_directory / name
return target_dir
def create_app_collection(self, directory: Path, collection_name: str):
"""Factory method for instantiating AppCollection."""
return AppCollection(
_git_client=self._git_client,
_app_collection_config_parser=self._app_collection_config_parser,
name=collection_name,
directory=directory
)
@Decorators.initialize
def get_collection_by_name(self, name: str) -> Optional[AppCollection]:
"""Get an app by name or return none if none exists."""
return self._collections.get(name, None)
@Decorators.initialize
def list(self) -> List[AppCollection]:
"""List all apps."""
return [value for key, value in sorted(self._collections.items())]
@Decorators.initialize
def add(self, name: str, url: str) -> AppCollection:
"""Add an app collection."""
target_dir = self.get_directory_for_collection(name)
if target_dir.exists():
raise AppCollectionsAlreadyExistsException()
self._git_client.clone_repo(url, target_dir)
app_collection = self.create_app_collection(target_dir, name)
self._collections[name] = app_collection
return app_collection
@Decorators.initialize
def remove(self, name):
"""Remove an app collection."""
target_dir = self.get_directory_for_collection(name)
if target_dir.exists():
self._git_client.remove_repo(target_dir)
self._collections.pop(name)
| from dataclasses import dataclass, field
from enum import Enum
from pathlib import Path
from typing import List, ClassVar, Dict, Optional, Tuple
from .exceptions import AppCollectionsAlreadyExistsException, AppCollectionsConfigDoesNotExistException, \
AppCollectionConfigValidationException
from .protocols import AppDirLocatorProtocol, GitClientProtocol, AppCollectionConfigParserProtocol
class AppEvent(Enum):
"""Events that may happen during the application life cycle.
Primarily used for registering callbacks with the UI.
"""
MAIN_WINDOW_READY = 1
@dataclass
class Config:
""""Contains the app config."""
def __init__(self, app_dir_locator: AppDirLocatorProtocol):
self.app_dir_locator = app_dir_locator
@property
def git_directory(self):
"""App data directory containing all git repos with Ansible playbooks."""
git_directory = self.app_dir_locator.get_app_data_dir() / 'git'
git_directory.mkdir(parents=True, exist_ok=True)
return git_directory
@dataclass(frozen=True)
class AnsibleRunResult:
"""Contains data about a completed Ansible run."""
stdout: str
stderr: str
return_code: int
@property
def was_successful(self):
"""True if this run has been successful."""
return self.return_code != 0
@dataclass(frozen=True)
class AppCategory:
"""Used for categorizing self service items it the UI."""
name: str
@dataclass(frozen=True)
class App:
"""A single application that can be installed, updated or removed."""
name: str
description: str
categories: List[AppCategory]
@dataclass
class AppCollection:
"""A collection of apps belonging to the same repository."""
_git_client: GitClientProtocol
_app_collection_config_parser: AppCollectionConfigParserProtocol
name: str
directory: Path
categories: Dict[str, AppCategory] = field(default_factory=dict)
apps: Dict[str, App] = field(default_factory=dict)
validation_error = None
_initialized: bool = False
CONFIG_FILE_NAME: ClassVar[str] = 'self-service.yaml'
class Decorators:
"""Nested class with decorators."""
@classmethod
def initialize(cls, func):
"""Decorator checking if the catalog is initialized before calling the wrapped function."""
def wrapper(self, *args, **kwargs):
if not self._initialized: # pylint: disable=W0212
self.refresh()
self._initialized = True # pylint: disable=W0212
return func(self, *args, **kwargs)
return wrapper
def refresh(self):
"""Read the repo config and (re-)initialize the collection."""
config = self.directory / self.CONFIG_FILE_NAME
if not config.exists():
raise AppCollectionsConfigDoesNotExistException()
try:
categories, apps = self._app_collection_config_parser.from_file(config)
self.categories = {category.name: category for category in categories}
self.apps = {app.name: app for app in apps}
self.validation_error = None
except AppCollectionConfigValidationException as exception:
self.categories = {}
self.apps = {}
self.validation_error = str(exception)
@property # type: ignore
@Decorators.initialize
def revision(self):
"""Return the current revision of the repo."""
return self._git_client.get_revision(self.directory)
@property # type: ignore
@Decorators.initialize
def url(self):
"""Extract the remote URL from the repo."""
return self._git_client.get_origin_url(self.directory)
@Decorators.initialize
def update(self, revision: Optional[str]) -> Tuple[str, str]:
"""Update the repository.
Update to latest main/master commit if no revision is provided.
"""
old_revision = self.revision
self._git_client.update(directory=self.directory, revision=revision)
new_revision = self.revision
return old_revision, new_revision
@dataclass
class AppCatalog:
""""Contains all known apps."""
_config: Config
_git_client: GitClientProtocol
_app_collection_config_parser: AppCollectionConfigParserProtocol
_collections: Dict[str, AppCollection] = field(default_factory=dict)
_initialized: bool = False
class Decorators:
"""Nested class with decorators."""
@classmethod
def initialize(cls, func):
"""Decorator checking if the catalog is initialized before calling the wrapped function."""
def wrapper(self, *args, **kwargs):
if not self._initialized: # pylint: disable=W0212
self.refresh()
self._initialized = True # pylint: disable=W0212
return func(self, *args, **kwargs)
return wrapper
def refresh(self):
"""Check the git directory for existing repos and add them to the list.py."""
self._collections = {}
for child in self._config.git_directory.iterdir():
if self._git_client.is_git_directory(child):
collection_name = str(child.name)
self._collections[collection_name] = self.create_app_collection(child, collection_name)
def get_directory_for_collection(self, name):
"""Locate the target directory for the app repository."""
target_dir = self._config.git_directory / name
return target_dir
def create_app_collection(self, directory: Path, collection_name: str):
"""Factory method for instantiating AppCollection."""
return AppCollection(
_git_client=self._git_client,
_app_collection_config_parser=self._app_collection_config_parser,
name=collection_name,
directory=directory
)
@Decorators.initialize
def get_collection_by_name(self, name: str) -> Optional[AppCollection]:
"""Get an app by name or return none if none exists."""
return self._collections.get(name, None)
@Decorators.initialize
def list(self) -> List[AppCollection]:
"""List all apps."""
return [value for key, value in sorted(self._collections.items())]
@Decorators.initialize
def add(self, name: str, url: str) -> AppCollection:
"""Add an app collection."""
target_dir = self.get_directory_for_collection(name)
if target_dir.exists():
raise AppCollectionsAlreadyExistsException()
self._git_client.clone_repo(url, target_dir)
app_collection = self.create_app_collection(target_dir, name)
self._collections[name] = app_collection
return app_collection
@Decorators.initialize
def remove(self, name):
"""Remove an app collection."""
target_dir = self.get_directory_for_collection(name)
if target_dir.exists():
self._git_client.remove_repo(target_dir)
self._collections.pop(name)
| en | 0.799239 | Events that may happen during the application life cycle. Primarily used for registering callbacks with the UI. "Contains the app config. App data directory containing all git repos with Ansible playbooks. Contains data about a completed Ansible run. True if this run has been successful. Used for categorizing self service items it the UI. A single application that can be installed, updated or removed. A collection of apps belonging to the same repository. Nested class with decorators. Decorator checking if the catalog is initialized before calling the wrapped function. # pylint: disable=W0212 # pylint: disable=W0212 Read the repo config and (re-)initialize the collection. # type: ignore Return the current revision of the repo. # type: ignore Extract the remote URL from the repo. Update the repository. Update to latest main/master commit if no revision is provided. "Contains all known apps. Nested class with decorators. Decorator checking if the catalog is initialized before calling the wrapped function. # pylint: disable=W0212 # pylint: disable=W0212 Check the git directory for existing repos and add them to the list.py. Locate the target directory for the app repository. Factory method for instantiating AppCollection. Get an app by name or return none if none exists. List all apps. Add an app collection. Remove an app collection. | 2.425853 | 2 |
nutrac/security.py | piraz/intrac | 0 | 6620269 | #!/usr/bin/env python
#
# Copyright 2018 <NAME>
#
# 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.
# TODO: Private key methods belong to podship_platform project
def generate_private_key():
""" FROM pyraspora: pyaspora.user.models
Generate a 4096-bit RSA key. The key will be stored in the User
object. The private key will be protected with password <<PASSWORD>>,
which is usually the user password.
"""
# TODO: seems to be candidate as part of some security toolkit
from Crypto.PublicKey import RSA
RSAkey = RSA.generate(4096)
return RSAkey.exportKey(
format='PEM',
pkcs=1
).decode("ascii")
| #!/usr/bin/env python
#
# Copyright 2018 <NAME>
#
# 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.
# TODO: Private key methods belong to podship_platform project
def generate_private_key():
""" FROM pyraspora: pyaspora.user.models
Generate a 4096-bit RSA key. The key will be stored in the User
object. The private key will be protected with password <<PASSWORD>>,
which is usually the user password.
"""
# TODO: seems to be candidate as part of some security toolkit
from Crypto.PublicKey import RSA
RSAkey = RSA.generate(4096)
return RSAkey.exportKey(
format='PEM',
pkcs=1
).decode("ascii")
| en | 0.856707 | #!/usr/bin/env python # # Copyright 2018 <NAME> # # 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. # TODO: Private key methods belong to podship_platform project FROM pyraspora: pyaspora.user.models Generate a 4096-bit RSA key. The key will be stored in the User object. The private key will be protected with password <<PASSWORD>>, which is usually the user password. # TODO: seems to be candidate as part of some security toolkit | 2.068561 | 2 |
danceschool/register/migrations/0003_auto_20200106_2159.py | django-danceschool/django-danceschool | 32 | 6620270 | # Generated by Django 2.2.6 on 2020-01-07 02:59
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('register', '0002_auto_20200106_1908'),
]
operations = [
migrations.AddField(
model_name='doorregisterpaymentmethod',
name='allowAutoSubmit',
field=models.BooleanField(default=False, help_text='If the payatdoor app is enabled, this setting can be used to permit automatic recording of non-electronic door payments to speed the registration process. For auto-submission to work, the name of this payment method must match the name of a payment method in the setting ATTHEDOOR_PAYMENTMETHOD_CHOICES for the payatdoor app. Valid defaults are Cash and Check.', verbose_name='Auto-submission'),
),
migrations.AlterField(
model_name='doorregisterpaymentmethod',
name='requireFullRegistration',
field=models.BooleanField(default=False, help_text='If checked, then whenever this payment method is used, the student information form will be required. The full registration process may also be required by a particular register plugin or registration choice.', verbose_name='Is full registration (name and email) always required for this method?'),
),
]
| # Generated by Django 2.2.6 on 2020-01-07 02:59
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('register', '0002_auto_20200106_1908'),
]
operations = [
migrations.AddField(
model_name='doorregisterpaymentmethod',
name='allowAutoSubmit',
field=models.BooleanField(default=False, help_text='If the payatdoor app is enabled, this setting can be used to permit automatic recording of non-electronic door payments to speed the registration process. For auto-submission to work, the name of this payment method must match the name of a payment method in the setting ATTHEDOOR_PAYMENTMETHOD_CHOICES for the payatdoor app. Valid defaults are Cash and Check.', verbose_name='Auto-submission'),
),
migrations.AlterField(
model_name='doorregisterpaymentmethod',
name='requireFullRegistration',
field=models.BooleanField(default=False, help_text='If checked, then whenever this payment method is used, the student information form will be required. The full registration process may also be required by a particular register plugin or registration choice.', verbose_name='Is full registration (name and email) always required for this method?'),
),
]
| en | 0.853091 | # Generated by Django 2.2.6 on 2020-01-07 02:59 | 1.81864 | 2 |
src/activities.py | jzucker2/RufusRaspberry | 1 | 6620271 | import logging
from dataclasses import dataclass
from enum import Enum
from .utils import HTTPRequestMethod
log = logging.getLogger(__name__)
@dataclass
class Activity:
name: str
url: str
method: str = HTTPRequestMethod.GET.value
class ActivityName(Enum):
ALL_OFF = 'all-off'
APPLE_TV = 'apple-tv'
VINYL = 'vinyl'
BEDTIME = 'bedtime'
LEAVE_ALBION = 'leave-albion'
WELCOME_HOME = 'welcome-home'
NIGHTLY_MOVIE = 'nightly-movie'
WORK_FROM_HOME = 'work-from-home'
YOGA = 'yoga'
MASTER_VOLUME_UP = 'master-volume-up'
MASTER_VOLUME_DOWN = 'master-volume-down'
MASTER_TOGGLE_MUTE = 'master-toggle-mute'
LIVING_ROOM_VOLUME_ADJUSTMENT = 'living-room-volume-adjustment'
DINING_ROOM_VOLUME_ADJUSTMENT = 'dining-room-volume-adjustment'
KITCHEN_VOLUME_ADJUSTMENT = 'kitchen-volume-adjustment'
GLOBAL_VOLUME_ADJUSTMENT = 'global-volume-adjustment'
LIVING_ROOM_MUTE_TOGGLE = 'living-room-mute-toggle'
DINING_ROOM_MUTE_TOGGLE = 'dining-room-mute-toggle'
KITCHEN_MUTE_TOGGLE = 'kitchen-mute-toggle'
GLOBAL_MUTE_TOGGLE = 'global-mute-toggle'
class Activities(object):
@classmethod
def all_activity_names(cls):
return cls.ACTIVITIES.keys()
@classmethod
def all_activities(cls):
return cls.ACTIVITIES.values()
@classmethod
def get_activity_url_suffix(cls, activity_name):
return cls.get_activity(activity_name).url
@classmethod
def get_activity_method(cls, activity_name_string):
return cls.get_activity(activity_name_string).method
@classmethod
def get_activity(cls, activity_name):
return cls.ACTIVITIES[activity_name]
ACTIVITIES = {
ActivityName.ALL_OFF.value: Activity(name=ActivityName.ALL_OFF.value, url='api/v1/activities/all-off?kitchen=0&dining_room=0'),
ActivityName.APPLE_TV.value: Activity(name=ActivityName.APPLE_TV.value, url='api/v1/activities/apple-tv'),
ActivityName.VINYL.value: Activity(name=ActivityName.VINYL.value, url='api/v1/activities/vinyl?kitchen=1&dining_room=1'),
ActivityName.BEDTIME.value: Activity(name=ActivityName.BEDTIME.value, url='api/v1/activities/bedtime?kitchen=0&dining_room=0'),
ActivityName.LEAVE_ALBION.value: Activity(name=ActivityName.LEAVE_ALBION.value,
url='api/v1/activities/leave?kitchen=0&dining_room=0'),
ActivityName.WELCOME_HOME.value: Activity(name=ActivityName.WELCOME_HOME.value,
url='api/v1/activities/welcome-home'),
ActivityName.NIGHTLY_MOVIE.value: Activity(name=ActivityName.NIGHTLY_MOVIE.value,
url='api/v1/activities/nightly-movie'),
ActivityName.WORK_FROM_HOME.value: Activity(name=ActivityName.WORK_FROM_HOME.value,
url='api/v1/activities/wfh?kitchen=1&dining_room=1'),
ActivityName.YOGA.value: Activity(name=ActivityName.YOGA.value,
url='api/v1/activities/yoga?kitchen=0&dining_room=0'),
ActivityName.MASTER_VOLUME_UP.value: Activity(name=ActivityName.MASTER_VOLUME_UP.value,
url='api/v1/volume/step/1'),
ActivityName.MASTER_VOLUME_DOWN.value: Activity(name=ActivityName.MASTER_VOLUME_DOWN.value,
url='api/v1/volume/step/-1'),
ActivityName.LIVING_ROOM_VOLUME_ADJUSTMENT.value: Activity(name=ActivityName.LIVING_ROOM_VOLUME_ADJUSTMENT.value,
url='api/v1/volume/step/{value}'),
ActivityName.KITCHEN_VOLUME_ADJUSTMENT.value: Activity(
name=ActivityName.KITCHEN_VOLUME_ADJUSTMENT.value,
url='api/v1/volume/zone_name/kitchen/step/{value}'),
ActivityName.DINING_ROOM_VOLUME_ADJUSTMENT.value: Activity(
name=ActivityName.DINING_ROOM_VOLUME_ADJUSTMENT.value,
url='api/v1/volume/zone_name/dining_room/step/{value}'),
ActivityName.GLOBAL_VOLUME_ADJUSTMENT.value: Activity(
name=ActivityName.GLOBAL_VOLUME_ADJUSTMENT.value,
url='api/v1/volume/global/step/{value}'),
ActivityName.MASTER_TOGGLE_MUTE.value: Activity(name=ActivityName.MASTER_TOGGLE_MUTE.value,
url='api/v1/volume/mute',
method=HTTPRequestMethod.PATCH.value),
ActivityName.LIVING_ROOM_MUTE_TOGGLE.value: Activity(
name=ActivityName.LIVING_ROOM_MUTE_TOGGLE.value,
url='api/v1/volume/mute', # works for just main zone
method=HTTPRequestMethod.PATCH.value),
ActivityName.KITCHEN_MUTE_TOGGLE.value: Activity(
name=ActivityName.KITCHEN_MUTE_TOGGLE.value,
url='api/v1/volume/zone_name/kitchen/toggle-mute',
method=HTTPRequestMethod.PATCH.value),
ActivityName.DINING_ROOM_MUTE_TOGGLE.value: Activity(
name=ActivityName.DINING_ROOM_MUTE_TOGGLE.value,
url='api/v1/volume/zone_name/dining_room/toggle-mute',
method=HTTPRequestMethod.PATCH.value),
ActivityName.GLOBAL_MUTE_TOGGLE.value: Activity(
name=ActivityName.GLOBAL_MUTE_TOGGLE.value,
url='api/v1/volume/global/toggle-mute',
method=HTTPRequestMethod.PATCH.value),
}
| import logging
from dataclasses import dataclass
from enum import Enum
from .utils import HTTPRequestMethod
log = logging.getLogger(__name__)
@dataclass
class Activity:
name: str
url: str
method: str = HTTPRequestMethod.GET.value
class ActivityName(Enum):
ALL_OFF = 'all-off'
APPLE_TV = 'apple-tv'
VINYL = 'vinyl'
BEDTIME = 'bedtime'
LEAVE_ALBION = 'leave-albion'
WELCOME_HOME = 'welcome-home'
NIGHTLY_MOVIE = 'nightly-movie'
WORK_FROM_HOME = 'work-from-home'
YOGA = 'yoga'
MASTER_VOLUME_UP = 'master-volume-up'
MASTER_VOLUME_DOWN = 'master-volume-down'
MASTER_TOGGLE_MUTE = 'master-toggle-mute'
LIVING_ROOM_VOLUME_ADJUSTMENT = 'living-room-volume-adjustment'
DINING_ROOM_VOLUME_ADJUSTMENT = 'dining-room-volume-adjustment'
KITCHEN_VOLUME_ADJUSTMENT = 'kitchen-volume-adjustment'
GLOBAL_VOLUME_ADJUSTMENT = 'global-volume-adjustment'
LIVING_ROOM_MUTE_TOGGLE = 'living-room-mute-toggle'
DINING_ROOM_MUTE_TOGGLE = 'dining-room-mute-toggle'
KITCHEN_MUTE_TOGGLE = 'kitchen-mute-toggle'
GLOBAL_MUTE_TOGGLE = 'global-mute-toggle'
class Activities(object):
@classmethod
def all_activity_names(cls):
return cls.ACTIVITIES.keys()
@classmethod
def all_activities(cls):
return cls.ACTIVITIES.values()
@classmethod
def get_activity_url_suffix(cls, activity_name):
return cls.get_activity(activity_name).url
@classmethod
def get_activity_method(cls, activity_name_string):
return cls.get_activity(activity_name_string).method
@classmethod
def get_activity(cls, activity_name):
return cls.ACTIVITIES[activity_name]
ACTIVITIES = {
ActivityName.ALL_OFF.value: Activity(name=ActivityName.ALL_OFF.value, url='api/v1/activities/all-off?kitchen=0&dining_room=0'),
ActivityName.APPLE_TV.value: Activity(name=ActivityName.APPLE_TV.value, url='api/v1/activities/apple-tv'),
ActivityName.VINYL.value: Activity(name=ActivityName.VINYL.value, url='api/v1/activities/vinyl?kitchen=1&dining_room=1'),
ActivityName.BEDTIME.value: Activity(name=ActivityName.BEDTIME.value, url='api/v1/activities/bedtime?kitchen=0&dining_room=0'),
ActivityName.LEAVE_ALBION.value: Activity(name=ActivityName.LEAVE_ALBION.value,
url='api/v1/activities/leave?kitchen=0&dining_room=0'),
ActivityName.WELCOME_HOME.value: Activity(name=ActivityName.WELCOME_HOME.value,
url='api/v1/activities/welcome-home'),
ActivityName.NIGHTLY_MOVIE.value: Activity(name=ActivityName.NIGHTLY_MOVIE.value,
url='api/v1/activities/nightly-movie'),
ActivityName.WORK_FROM_HOME.value: Activity(name=ActivityName.WORK_FROM_HOME.value,
url='api/v1/activities/wfh?kitchen=1&dining_room=1'),
ActivityName.YOGA.value: Activity(name=ActivityName.YOGA.value,
url='api/v1/activities/yoga?kitchen=0&dining_room=0'),
ActivityName.MASTER_VOLUME_UP.value: Activity(name=ActivityName.MASTER_VOLUME_UP.value,
url='api/v1/volume/step/1'),
ActivityName.MASTER_VOLUME_DOWN.value: Activity(name=ActivityName.MASTER_VOLUME_DOWN.value,
url='api/v1/volume/step/-1'),
ActivityName.LIVING_ROOM_VOLUME_ADJUSTMENT.value: Activity(name=ActivityName.LIVING_ROOM_VOLUME_ADJUSTMENT.value,
url='api/v1/volume/step/{value}'),
ActivityName.KITCHEN_VOLUME_ADJUSTMENT.value: Activity(
name=ActivityName.KITCHEN_VOLUME_ADJUSTMENT.value,
url='api/v1/volume/zone_name/kitchen/step/{value}'),
ActivityName.DINING_ROOM_VOLUME_ADJUSTMENT.value: Activity(
name=ActivityName.DINING_ROOM_VOLUME_ADJUSTMENT.value,
url='api/v1/volume/zone_name/dining_room/step/{value}'),
ActivityName.GLOBAL_VOLUME_ADJUSTMENT.value: Activity(
name=ActivityName.GLOBAL_VOLUME_ADJUSTMENT.value,
url='api/v1/volume/global/step/{value}'),
ActivityName.MASTER_TOGGLE_MUTE.value: Activity(name=ActivityName.MASTER_TOGGLE_MUTE.value,
url='api/v1/volume/mute',
method=HTTPRequestMethod.PATCH.value),
ActivityName.LIVING_ROOM_MUTE_TOGGLE.value: Activity(
name=ActivityName.LIVING_ROOM_MUTE_TOGGLE.value,
url='api/v1/volume/mute', # works for just main zone
method=HTTPRequestMethod.PATCH.value),
ActivityName.KITCHEN_MUTE_TOGGLE.value: Activity(
name=ActivityName.KITCHEN_MUTE_TOGGLE.value,
url='api/v1/volume/zone_name/kitchen/toggle-mute',
method=HTTPRequestMethod.PATCH.value),
ActivityName.DINING_ROOM_MUTE_TOGGLE.value: Activity(
name=ActivityName.DINING_ROOM_MUTE_TOGGLE.value,
url='api/v1/volume/zone_name/dining_room/toggle-mute',
method=HTTPRequestMethod.PATCH.value),
ActivityName.GLOBAL_MUTE_TOGGLE.value: Activity(
name=ActivityName.GLOBAL_MUTE_TOGGLE.value,
url='api/v1/volume/global/toggle-mute',
method=HTTPRequestMethod.PATCH.value),
}
| en | 0.940662 | # works for just main zone | 2.603697 | 3 |
qcodes_measurements/plot/local/RemoteProcessWrapper.py | QNLSydney/qcodes-measurements | 2 | 6620272 | <reponame>QNLSydney/qcodes-measurements<filename>qcodes_measurements/plot/local/RemoteProcessWrapper.py
import re
import sys
import numpy as np
import PyQt5.QtGui
import PyQt5.QtWidgets
from ...logging import get_logger
from ..multiprocess import ObjectProxy, QtProcess, ClosedError
# Get access to module level variables
this = sys.modules[__name__]
rpg = None
logger = get_logger("RPGWrapper")
__all__ = ["ensure_ndarray", "auto_wrap", "RPGWrappedBase", "get_remote"]
def ensure_ndarray(array):
"""
Ensure the given array is a numpy array. Necessary for some parts of pyqtgraph.
"""
if array is None:
return None
if not isinstance(array, np.ndarray):
return np.array(array)
return array
def auto_wrap(f):
"""
Decorator to ensure values are wrapped by RPGWrappedBase
"""
def wrap(*args, **kwargs):
val = f(*args, **kwargs)
if val is None:
return val
return RPGWrappedBase.autowrap(val)
return wrap
def _set_defaults(remote):
"""
Set up the default state of the plot windows. Add any other global config options here.
"""
remote.setConfigOption('background', 'w')
remote.setConfigOption('foreground', 'k')
remote.setConfigOption('leftButtonPan', False)
remote.setConfigOption('antialias', True)
remote._setProxyOptions(deferGetattr=False)
def start_remote():
# Check that a QApplication has been created
if PyQt5.QtWidgets.QApplication.instance() is None:
this.app = PyQt5.QtWidgets.QApplication([])
else:
this.app = PyQt5.QtWidgets.QApplication.instance()
this.proc = QtProcess(debug=False)
this.rpg = this.proc._import('qcodes_measurements.plot.rpyplot', timeout=20)
this.rbuiltins = this.proc._import("builtins")
_set_defaults(this.rpg)
def restart_remote():
if len(QtProcess.handlers) == 0:
start_remote()
else:
for pid in QtProcess.handlers:
try:
proc = QtProcess.handlers[pid]
if isinstance(proc, QtProcess):
if not proc.exited:
QtProcess.handlers[pid].join()
except ClosedError:
continue
QtProcess.handlers.clear()
start_remote()
def get_remote():
return this.rpg
def remote_callable(remote_obj):
# If the object is local, shortcut to the local callable
if not isinstance(remote_obj, ObjectProxy):
return callable(remote_obj)
# Call callable on the remote
return this.rbuiltins.callable(remote_obj)
class RPGWrappedBase(ObjectProxy):
# Keep track of children so they aren't recomputed each time
_subclass_types = None
# Reserve names for local variables, so they aren't proxied.
_base_inst = None
# Cache remote functions, allowing proxy options for each to be set
_remote_functions = None
_remote_function_options = None
def __init__(self, *args, **kwargs): # pylint: disable=super-init-not-called
self._remote_functions = {}
self._remote_function_options = {}
# Check that the remote process has been started, and is still alive
if getattr(this, "rpg", None) is None:
start_remote()
if this.rpg._handler.proc.is_alive() is False:
restart_remote()
if '_base' in self.__class__.__dict__:
base = getattr(this.rpg, self.__class__._base)
base = base(*args, **kwargs)
self._base_inst = base
else:
raise TypeError("Base instance not defined. Don't know how to create remote object.")
def __wrap__(self, *args, **kwargs):
if args or kwargs:
raise TypeError(f"RPGWrappedBase.__wrap__ expects no arguments. Got args={args}, kwargs={kwargs}")
self._remote_functions = {}
self._remote_function_options = {}
# And make sure that ndarrays are still proxied
@classmethod
def wrap(cls, instance, *args, **kwargs):
if not isinstance(instance, ObjectProxy):
raise TypeError("We can only wrap ObjectProxies")
# Create an empty instance of RPGWrappedBase,
# and copy over instance variables
base_inst = cls.__new__(cls)
base_inst.__dict__ = {**base_inst.__dict__,
**instance.__dict__}
base_inst._base_inst = instance
# If we do want to initialize some instance variables, we can do it in
# the special __wrap__ method
__wrap__ = getattr(base_inst, '__wrap__', None)
if __wrap__ is not None:
__wrap__(*args, **kwargs)
return base_inst
@staticmethod
def autowrap(inst):
logger.debug("Trying to autowrap %r.", inst)
# Figure out the types that we know how to autowrap
if RPGWrappedBase._subclass_types is None:
logger.debug("Populating subclass types")
RPGWrappedBase._subclass_types = {}
def append_subclasses(sc_dict, cls):
for typ in cls.__subclasses__():
append_subclasses(sc_dict, typ)
base = getattr(typ, '_base', None)
if base is None:
continue
typestr = base
sc_dict[typestr] = typ
append_subclasses(RPGWrappedBase._subclass_types, RPGWrappedBase)
# Then, if we have an object proxy, wrap it if it is in the list of wrappable types
if isinstance(inst, ObjectProxy):
if isinstance(inst, RPGWrappedBase):
logger.debug("Object already wrapped. Has types: %r.", inst.__class__.__mro__)
return inst
# Check if we have a list of objects:
if inst.__getattr__("__class__").__name__ in ("tuple", "list"):
logger.debug("Wrapping remote list.")
# Need to iterate over things in a dumb way to suppress warnings
return tuple(RPGWrappedBase.autowrap(inst[i]) for i in range(len(inst)))
# Otherwise look to see if we have an extended type
typestr = re.match(r"<[a-zA-Z_.]+\.([a-zA-Z_]+) object at 0x[0-9A-Fa-f]+>", inst._typeStr)
if typestr:
logger.debug("Extracted remote type: %s.", typestr.groups()[0])
typestr = typestr.groups()[0]
if typestr in RPGWrappedBase._subclass_types:
return RPGWrappedBase._subclass_types[typestr].wrap(inst)
else:
logger.debug("Object is not an ObjectProxy. Has types: %r.", inst.__class__.__mro__)
# Otherwise, just return the bare instance
return inst
def wrap_adders(self, f):
def save(*args, **kwargs):
res = f(*args, **kwargs)
# If the adder doesn't return the newly added item, we can assume the added item
# was passed as the first non-keyword argument
if res is None:
if len(args) > 0:
res = args[0]
else:
return
# Try to translate to one of the friendly names
res = RPGWrappedBase.autowrap(res)
return res
return save
def wrap_getters(self, f):
return auto_wrap(f)
def __setattr__(self, name, val, **kwargs): # pylint: disable=arguments-differ
for cls in self.__class__.__mro__:
if name in cls.__dict__:
object.__setattr__(self, name, val)
return
if name in self.__dict__:
object.__setattr__(self, name, val)
elif name == "__dict__":
object.__setattr__(self, name, val)
else:
super().__setattr__(name, val, **kwargs)
def __getattr__(self, name, **kwargs):
# Check for ipython special methods
if re.match("_repr_.*_", name):
raise AttributeError("Ignoring iPython special methods")
if re.match("_ipython_.*_", name):
raise AttributeError("Ignoring iPython special methods")
# Figure out where we should look for the attribute ("remote", "local" or "both")
search_location = kwargs.pop("_location", "both")
attr = None
# Get attribute from object proxy, checking if it exists locally first
if search_location in ("local", "both"):
logger.debug("Looking for attr %s locally.", name)
for cls in self.__class__.__mro__:
if name in cls.__dict__:
v = cls.__dict__[name]
if hasattr(v, '__get__'):
attr = v.__get__(None, self)
logger.debug("Found attr %s locally in subclass %r, and is a property. Returns value: %r.", name, cls, attr)
else:
attr = v
logger.debug("Found attr %s locally in subclass %r. Returns value: %r.", name, cls, attr)
break
else:
if name in self._base_inst.__dict__:
attr = self._base_inst.__dict__[name]
logger.debug("Found attr %s locally in base_inst (%r). Returns value: %r", name, self._base_inst, attr)
# Otherwise check whether the attribute exists on the remote
if search_location in ("remote", "both") and attr is None:
logger.debug("Looking for attr %s remotely.", name)
# Check whether this function has been cached
if name in self._remote_functions:
logger.debug("Found cached value for %s.", name)
return self._remote_functions[name]
# Otherwise look for it on the remote
attr = self._base_inst.__getattr__(name, **kwargs)
logger.debug("Found attr %s remotely. Returns value %r.", name, attr)
# If we didn't find the attribute in either location, raise an AttributeError
if attr is None:
raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'")
# Check if item is a wrappable type
attr = self.autowrap(attr)
# Wrap adders and getters
if name.startswith("add") and remote_callable(attr):
return self.wrap_adders(attr)
elif name.startswith("get") and remote_callable(attr):
return self.wrap_getters(attr)
# Save a cached copy, if we have a function with specific options
if remote_callable(attr) and name in self._remote_function_options:
attr._setProxyOptions(**self._remote_function_options[name])
self._remote_functions[name] = self.wrap_getters(attr)
return self._remote_functions[name]
if remote_callable(attr):
return self.wrap_getters(attr)
return attr
def __repr__(self):
return "<%s for %s>" % (self.__class__.__name__, super().__repr__())
| import re
import sys
import numpy as np
import PyQt5.QtGui
import PyQt5.QtWidgets
from ...logging import get_logger
from ..multiprocess import ObjectProxy, QtProcess, ClosedError
# Get access to module level variables
this = sys.modules[__name__]
rpg = None
logger = get_logger("RPGWrapper")
__all__ = ["ensure_ndarray", "auto_wrap", "RPGWrappedBase", "get_remote"]
def ensure_ndarray(array):
"""
Ensure the given array is a numpy array. Necessary for some parts of pyqtgraph.
"""
if array is None:
return None
if not isinstance(array, np.ndarray):
return np.array(array)
return array
def auto_wrap(f):
"""
Decorator to ensure values are wrapped by RPGWrappedBase
"""
def wrap(*args, **kwargs):
val = f(*args, **kwargs)
if val is None:
return val
return RPGWrappedBase.autowrap(val)
return wrap
def _set_defaults(remote):
"""
Set up the default state of the plot windows. Add any other global config options here.
"""
remote.setConfigOption('background', 'w')
remote.setConfigOption('foreground', 'k')
remote.setConfigOption('leftButtonPan', False)
remote.setConfigOption('antialias', True)
remote._setProxyOptions(deferGetattr=False)
def start_remote():
# Check that a QApplication has been created
if PyQt5.QtWidgets.QApplication.instance() is None:
this.app = PyQt5.QtWidgets.QApplication([])
else:
this.app = PyQt5.QtWidgets.QApplication.instance()
this.proc = QtProcess(debug=False)
this.rpg = this.proc._import('qcodes_measurements.plot.rpyplot', timeout=20)
this.rbuiltins = this.proc._import("builtins")
_set_defaults(this.rpg)
def restart_remote():
if len(QtProcess.handlers) == 0:
start_remote()
else:
for pid in QtProcess.handlers:
try:
proc = QtProcess.handlers[pid]
if isinstance(proc, QtProcess):
if not proc.exited:
QtProcess.handlers[pid].join()
except ClosedError:
continue
QtProcess.handlers.clear()
start_remote()
def get_remote():
return this.rpg
def remote_callable(remote_obj):
# If the object is local, shortcut to the local callable
if not isinstance(remote_obj, ObjectProxy):
return callable(remote_obj)
# Call callable on the remote
return this.rbuiltins.callable(remote_obj)
class RPGWrappedBase(ObjectProxy):
# Keep track of children so they aren't recomputed each time
_subclass_types = None
# Reserve names for local variables, so they aren't proxied.
_base_inst = None
# Cache remote functions, allowing proxy options for each to be set
_remote_functions = None
_remote_function_options = None
def __init__(self, *args, **kwargs): # pylint: disable=super-init-not-called
self._remote_functions = {}
self._remote_function_options = {}
# Check that the remote process has been started, and is still alive
if getattr(this, "rpg", None) is None:
start_remote()
if this.rpg._handler.proc.is_alive() is False:
restart_remote()
if '_base' in self.__class__.__dict__:
base = getattr(this.rpg, self.__class__._base)
base = base(*args, **kwargs)
self._base_inst = base
else:
raise TypeError("Base instance not defined. Don't know how to create remote object.")
def __wrap__(self, *args, **kwargs):
if args or kwargs:
raise TypeError(f"RPGWrappedBase.__wrap__ expects no arguments. Got args={args}, kwargs={kwargs}")
self._remote_functions = {}
self._remote_function_options = {}
# And make sure that ndarrays are still proxied
@classmethod
def wrap(cls, instance, *args, **kwargs):
if not isinstance(instance, ObjectProxy):
raise TypeError("We can only wrap ObjectProxies")
# Create an empty instance of RPGWrappedBase,
# and copy over instance variables
base_inst = cls.__new__(cls)
base_inst.__dict__ = {**base_inst.__dict__,
**instance.__dict__}
base_inst._base_inst = instance
# If we do want to initialize some instance variables, we can do it in
# the special __wrap__ method
__wrap__ = getattr(base_inst, '__wrap__', None)
if __wrap__ is not None:
__wrap__(*args, **kwargs)
return base_inst
@staticmethod
def autowrap(inst):
logger.debug("Trying to autowrap %r.", inst)
# Figure out the types that we know how to autowrap
if RPGWrappedBase._subclass_types is None:
logger.debug("Populating subclass types")
RPGWrappedBase._subclass_types = {}
def append_subclasses(sc_dict, cls):
for typ in cls.__subclasses__():
append_subclasses(sc_dict, typ)
base = getattr(typ, '_base', None)
if base is None:
continue
typestr = base
sc_dict[typestr] = typ
append_subclasses(RPGWrappedBase._subclass_types, RPGWrappedBase)
# Then, if we have an object proxy, wrap it if it is in the list of wrappable types
if isinstance(inst, ObjectProxy):
if isinstance(inst, RPGWrappedBase):
logger.debug("Object already wrapped. Has types: %r.", inst.__class__.__mro__)
return inst
# Check if we have a list of objects:
if inst.__getattr__("__class__").__name__ in ("tuple", "list"):
logger.debug("Wrapping remote list.")
# Need to iterate over things in a dumb way to suppress warnings
return tuple(RPGWrappedBase.autowrap(inst[i]) for i in range(len(inst)))
# Otherwise look to see if we have an extended type
typestr = re.match(r"<[a-zA-Z_.]+\.([a-zA-Z_]+) object at 0x[0-9A-Fa-f]+>", inst._typeStr)
if typestr:
logger.debug("Extracted remote type: %s.", typestr.groups()[0])
typestr = typestr.groups()[0]
if typestr in RPGWrappedBase._subclass_types:
return RPGWrappedBase._subclass_types[typestr].wrap(inst)
else:
logger.debug("Object is not an ObjectProxy. Has types: %r.", inst.__class__.__mro__)
# Otherwise, just return the bare instance
return inst
def wrap_adders(self, f):
def save(*args, **kwargs):
res = f(*args, **kwargs)
# If the adder doesn't return the newly added item, we can assume the added item
# was passed as the first non-keyword argument
if res is None:
if len(args) > 0:
res = args[0]
else:
return
# Try to translate to one of the friendly names
res = RPGWrappedBase.autowrap(res)
return res
return save
def wrap_getters(self, f):
return auto_wrap(f)
def __setattr__(self, name, val, **kwargs): # pylint: disable=arguments-differ
for cls in self.__class__.__mro__:
if name in cls.__dict__:
object.__setattr__(self, name, val)
return
if name in self.__dict__:
object.__setattr__(self, name, val)
elif name == "__dict__":
object.__setattr__(self, name, val)
else:
super().__setattr__(name, val, **kwargs)
def __getattr__(self, name, **kwargs):
# Check for ipython special methods
if re.match("_repr_.*_", name):
raise AttributeError("Ignoring iPython special methods")
if re.match("_ipython_.*_", name):
raise AttributeError("Ignoring iPython special methods")
# Figure out where we should look for the attribute ("remote", "local" or "both")
search_location = kwargs.pop("_location", "both")
attr = None
# Get attribute from object proxy, checking if it exists locally first
if search_location in ("local", "both"):
logger.debug("Looking for attr %s locally.", name)
for cls in self.__class__.__mro__:
if name in cls.__dict__:
v = cls.__dict__[name]
if hasattr(v, '__get__'):
attr = v.__get__(None, self)
logger.debug("Found attr %s locally in subclass %r, and is a property. Returns value: %r.", name, cls, attr)
else:
attr = v
logger.debug("Found attr %s locally in subclass %r. Returns value: %r.", name, cls, attr)
break
else:
if name in self._base_inst.__dict__:
attr = self._base_inst.__dict__[name]
logger.debug("Found attr %s locally in base_inst (%r). Returns value: %r", name, self._base_inst, attr)
# Otherwise check whether the attribute exists on the remote
if search_location in ("remote", "both") and attr is None:
logger.debug("Looking for attr %s remotely.", name)
# Check whether this function has been cached
if name in self._remote_functions:
logger.debug("Found cached value for %s.", name)
return self._remote_functions[name]
# Otherwise look for it on the remote
attr = self._base_inst.__getattr__(name, **kwargs)
logger.debug("Found attr %s remotely. Returns value %r.", name, attr)
# If we didn't find the attribute in either location, raise an AttributeError
if attr is None:
raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'")
# Check if item is a wrappable type
attr = self.autowrap(attr)
# Wrap adders and getters
if name.startswith("add") and remote_callable(attr):
return self.wrap_adders(attr)
elif name.startswith("get") and remote_callable(attr):
return self.wrap_getters(attr)
# Save a cached copy, if we have a function with specific options
if remote_callable(attr) and name in self._remote_function_options:
attr._setProxyOptions(**self._remote_function_options[name])
self._remote_functions[name] = self.wrap_getters(attr)
return self._remote_functions[name]
if remote_callable(attr):
return self.wrap_getters(attr)
return attr
def __repr__(self):
return "<%s for %s>" % (self.__class__.__name__, super().__repr__()) | en | 0.824124 | # Get access to module level variables Ensure the given array is a numpy array. Necessary for some parts of pyqtgraph. Decorator to ensure values are wrapped by RPGWrappedBase Set up the default state of the plot windows. Add any other global config options here. # Check that a QApplication has been created # If the object is local, shortcut to the local callable # Call callable on the remote # Keep track of children so they aren't recomputed each time # Reserve names for local variables, so they aren't proxied. # Cache remote functions, allowing proxy options for each to be set # pylint: disable=super-init-not-called # Check that the remote process has been started, and is still alive # And make sure that ndarrays are still proxied # Create an empty instance of RPGWrappedBase, # and copy over instance variables # If we do want to initialize some instance variables, we can do it in # the special __wrap__ method # Figure out the types that we know how to autowrap # Then, if we have an object proxy, wrap it if it is in the list of wrappable types # Check if we have a list of objects: # Need to iterate over things in a dumb way to suppress warnings # Otherwise look to see if we have an extended type # Otherwise, just return the bare instance # If the adder doesn't return the newly added item, we can assume the added item # was passed as the first non-keyword argument # Try to translate to one of the friendly names # pylint: disable=arguments-differ # Check for ipython special methods # Figure out where we should look for the attribute ("remote", "local" or "both") # Get attribute from object proxy, checking if it exists locally first # Otherwise check whether the attribute exists on the remote # Check whether this function has been cached # Otherwise look for it on the remote # If we didn't find the attribute in either location, raise an AttributeError # Check if item is a wrappable type # Wrap adders and getters # Save a cached copy, if we have a function with specific options | 2.169094 | 2 |
wiki_util.py | vladiscripts/ws_interlinker_via_wikidata | 0 | 6620273 | <reponame>vladiscripts/ws_interlinker_via_wikidata
#!/usr/bin/env python
# coding: utf-8
from __init__ import *
# import requests
# import sqlite3
# import json
# from lxml.html import fromstring
# import re
# from urllib.parse import urlencode, urlparse, parse_qs, parse_qsl, unquote, quote
# import pywikibot as pwb
# from vladi_helpers import vladi_helpers
# from vladi_helpers.file_helpers import csv_save_dict_fromListWithHeaders, json_save_to_file, json_load_from_file
import vladi_helpers.lib_for_mwparserfromhell as mymwp
# def parse_pagename(title: str) ->Optional[pwb.Page]:
# rootpagename, subpagename = None, None
# if '/' in title:
# rootpagename, _, subpagename = title.partition('/')
# return rootpagename, subpagename
# def param_value_clear(tpl, name, test_run=False, remove_param=False):
# if not test_run:
# if remove_param:
# mymwp.removeTplParameters(tpl, name)
# else:
# mymwp.param_value_clear(tpl, name, new_val='\n')
def page_posting(page: pwb.Page, page_text: str, summary: str = None, test_run: bool = False) -> None:
page_text = page_text.strip()
if page.text != page_text:
if test_run:
return
page.text = page_text
page.save(summary)
def get_wikipage(site: str, title: str = None, page: pwb.Page = None) -> Optional[pwb.Page]:
page = page or pwb.Page(site, title)
while page.isRedirectPage():
page = page.getRedirectTarget()
if page.exists():
return page
def pagegenerator(args: list = None):
""" Get list of pages which using 'Template:infobox former country'
без кавычек имена станиц/категорий в параметрах
"""
from pywikibot import pagegenerators
# args = ['-family:wikipedia', '-lang:en', '-ns:0'] + [f'-transcludes:{tpl}' for tpl in tpl_names]
gen_factory = pwb.pagegenerators.GeneratorFactory()
local_args = pwb.handle_args(args)
for arg in local_args:
gen_factory.handle_arg(arg)
gen = gen_factory.getCombinedGenerator(preload=False)
return gen
def remove_param(p, name: str, value_only: bool = False) -> None:
mymwp.removeTplParameters(p.tpl, name, remove_value_only=value_only)
if value_only:
p.params_to_value_clear.append(name)
else:
p.params_to_delete.append(name)
def make_summary(p) -> str:
_summary = []
if p.params_to_delete:
lst = ','.join(p.params_to_delete)
_summary.append(f'ссылка перенесена в Викиданные ({lst})')
if p.params_to_value_clear:
# _summary.append(f'ссылка на несущ. страницу (%s)' % ','.join(p.params_to_value_clear))
lst = ','.join(p.params_to_value_clear)
_summary.append(f'очистка параметра ({lst}), перенесено в Викиданные или ссылка на несущ. страницу')
summary = '; '.join(_summary + p.summaries)
return summary
def make_re_wikilink_category(cat_name: str) -> str:
return fr'\[\[Категория:{cat_name}(?:\|.*)?\]\]'
def make_wikilink_category(cat_name: str, text: str = None) -> str:
if text:
return f'[[Категория:{cat_name}|{text}]]'
return f'[[Категория:{cat_name}]]'
def set_or_remove_category(p, cat_name: str, condition: bool, add_cat: bool = False, log_on_add: str = None) -> None:
cat_full = make_wikilink_category(cat_name)
cat_full_re = make_re_wikilink_category(cat_name)
if condition:
if add_cat:
if log_on_add: pwb.stdout(log_on_add)
if not [i for i in p.wikicode.filter_wikilinks(matches=cat_full_re)]:
p.wikicode.append(cat_full)
p.summaries.append('категория')
return
else:
for i in p.wikicode.filter_wikilinks(matches=cat_full_re):
p.wikicode.remove(i)
| #!/usr/bin/env python
# coding: utf-8
from __init__ import *
# import requests
# import sqlite3
# import json
# from lxml.html import fromstring
# import re
# from urllib.parse import urlencode, urlparse, parse_qs, parse_qsl, unquote, quote
# import pywikibot as pwb
# from vladi_helpers import vladi_helpers
# from vladi_helpers.file_helpers import csv_save_dict_fromListWithHeaders, json_save_to_file, json_load_from_file
import vladi_helpers.lib_for_mwparserfromhell as mymwp
# def parse_pagename(title: str) ->Optional[pwb.Page]:
# rootpagename, subpagename = None, None
# if '/' in title:
# rootpagename, _, subpagename = title.partition('/')
# return rootpagename, subpagename
# def param_value_clear(tpl, name, test_run=False, remove_param=False):
# if not test_run:
# if remove_param:
# mymwp.removeTplParameters(tpl, name)
# else:
# mymwp.param_value_clear(tpl, name, new_val='\n')
def page_posting(page: pwb.Page, page_text: str, summary: str = None, test_run: bool = False) -> None:
page_text = page_text.strip()
if page.text != page_text:
if test_run:
return
page.text = page_text
page.save(summary)
def get_wikipage(site: str, title: str = None, page: pwb.Page = None) -> Optional[pwb.Page]:
page = page or pwb.Page(site, title)
while page.isRedirectPage():
page = page.getRedirectTarget()
if page.exists():
return page
def pagegenerator(args: list = None):
""" Get list of pages which using 'Template:infobox former country'
без кавычек имена станиц/категорий в параметрах
"""
from pywikibot import pagegenerators
# args = ['-family:wikipedia', '-lang:en', '-ns:0'] + [f'-transcludes:{tpl}' for tpl in tpl_names]
gen_factory = pwb.pagegenerators.GeneratorFactory()
local_args = pwb.handle_args(args)
for arg in local_args:
gen_factory.handle_arg(arg)
gen = gen_factory.getCombinedGenerator(preload=False)
return gen
def remove_param(p, name: str, value_only: bool = False) -> None:
mymwp.removeTplParameters(p.tpl, name, remove_value_only=value_only)
if value_only:
p.params_to_value_clear.append(name)
else:
p.params_to_delete.append(name)
def make_summary(p) -> str:
_summary = []
if p.params_to_delete:
lst = ','.join(p.params_to_delete)
_summary.append(f'ссылка перенесена в Викиданные ({lst})')
if p.params_to_value_clear:
# _summary.append(f'ссылка на несущ. страницу (%s)' % ','.join(p.params_to_value_clear))
lst = ','.join(p.params_to_value_clear)
_summary.append(f'очистка параметра ({lst}), перенесено в Викиданные или ссылка на несущ. страницу')
summary = '; '.join(_summary + p.summaries)
return summary
def make_re_wikilink_category(cat_name: str) -> str:
return fr'\[\[Категория:{cat_name}(?:\|.*)?\]\]'
def make_wikilink_category(cat_name: str, text: str = None) -> str:
if text:
return f'[[Категория:{cat_name}|{text}]]'
return f'[[Категория:{cat_name}]]'
def set_or_remove_category(p, cat_name: str, condition: bool, add_cat: bool = False, log_on_add: str = None) -> None:
cat_full = make_wikilink_category(cat_name)
cat_full_re = make_re_wikilink_category(cat_name)
if condition:
if add_cat:
if log_on_add: pwb.stdout(log_on_add)
if not [i for i in p.wikicode.filter_wikilinks(matches=cat_full_re)]:
p.wikicode.append(cat_full)
p.summaries.append('категория')
return
else:
for i in p.wikicode.filter_wikilinks(matches=cat_full_re):
p.wikicode.remove(i) | en | 0.175752 | #!/usr/bin/env python # coding: utf-8 # import requests # import sqlite3 # import json # from lxml.html import fromstring # import re # from urllib.parse import urlencode, urlparse, parse_qs, parse_qsl, unquote, quote # import pywikibot as pwb # from vladi_helpers import vladi_helpers # from vladi_helpers.file_helpers import csv_save_dict_fromListWithHeaders, json_save_to_file, json_load_from_file # def parse_pagename(title: str) ->Optional[pwb.Page]: # rootpagename, subpagename = None, None # if '/' in title: # rootpagename, _, subpagename = title.partition('/') # return rootpagename, subpagename # def param_value_clear(tpl, name, test_run=False, remove_param=False): # if not test_run: # if remove_param: # mymwp.removeTplParameters(tpl, name) # else: # mymwp.param_value_clear(tpl, name, new_val='\n') Get list of pages which using 'Template:infobox former country' без кавычек имена станиц/категорий в параметрах # args = ['-family:wikipedia', '-lang:en', '-ns:0'] + [f'-transcludes:{tpl}' for tpl in tpl_names] # _summary.append(f'ссылка на несущ. страницу (%s)' % ','.join(p.params_to_value_clear)) | 2.302652 | 2 |
mad_web/madcon/serializers.py | txcsmad/txcsmad.com | 1 | 6620274 | <reponame>txcsmad/txcsmad.com
# Serializers define the API representation.
from rest_framework import serializers
from mad_web.madcon.models import Registration, MADcon
from mad_web.users.serializers import UserSerializer
class RegistrationSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Registration
fields = (
'id', 'dietary_restrictions', 'first_time', 'status', 't_shirt_size', 'madcon', 'created_at')
class RegistrationUserSerializier(serializers.HyperlinkedModelSerializer):
user = UserSerializer(read_only=True)
class Meta:
model = Registration
fields = ('id', 'dietary_restrictions', 'first_time', 'status', 't_shirt_size', 'madcon', 'created_at', 'user')
class MADconSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = MADcon
fields = ('id', 'date')
| # Serializers define the API representation.
from rest_framework import serializers
from mad_web.madcon.models import Registration, MADcon
from mad_web.users.serializers import UserSerializer
class RegistrationSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Registration
fields = (
'id', 'dietary_restrictions', 'first_time', 'status', 't_shirt_size', 'madcon', 'created_at')
class RegistrationUserSerializier(serializers.HyperlinkedModelSerializer):
user = UserSerializer(read_only=True)
class Meta:
model = Registration
fields = ('id', 'dietary_restrictions', 'first_time', 'status', 't_shirt_size', 'madcon', 'created_at', 'user')
class MADconSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = MADcon
fields = ('id', 'date') | en | 0.63932 | # Serializers define the API representation. | 2.279416 | 2 |
practice/weekly-contest-148/snapshot-array.py | yangtau/algorithms-practice | 1 | 6620275 | <filename>practice/weekly-contest-148/snapshot-array.py
class SnapshotArray:
def __init__(self, length: int):
self._snap={}
self.snap_id = 0
def set(self, index: int, val: int) -> None:
self._snap.setdefault(self.snap_id, {})
self._snap[self.snap_id][index] = val
def snap(self) -> int:
_snap_id = self.snap_id
self.snap_id += 1
return _snap_id
def get(self, index: int, snap_id: int) -> int:
for i in range(snap_id, -1, -1):
if i in self._snap and index in self._snap[i]:
return self._snap[i][index]
return 0
| <filename>practice/weekly-contest-148/snapshot-array.py
class SnapshotArray:
def __init__(self, length: int):
self._snap={}
self.snap_id = 0
def set(self, index: int, val: int) -> None:
self._snap.setdefault(self.snap_id, {})
self._snap[self.snap_id][index] = val
def snap(self) -> int:
_snap_id = self.snap_id
self.snap_id += 1
return _snap_id
def get(self, index: int, snap_id: int) -> int:
for i in range(snap_id, -1, -1):
if i in self._snap and index in self._snap[i]:
return self._snap[i][index]
return 0
| none | 1 | 3.351759 | 3 | |
algos/patterns/slidingWindows/longestZerosAfterKreplacment.py | iamlmn/PyDS | 0 | 6620276 | # Given an array containing 0s and 1s, if you are allowed to replace no more than ‘k’ 0s with 1s, find the length of the longest contiguous subarray having all 1s.
# Example 1:
# Input: Array=[0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1], k=2
# Output: 6
# Explanation: Replace the '0' at index 5 and 8 to have the longest contiguous subarray of 1s having length 6.
# Example 2:
# Input: Array=[0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1], k=3
# Output: 9
# Explanation: Replace the '0' at index 6, 9, and 10 to have the longest contiguous subarray of 1s having length 9.
def longestSubStringAfterReplacement(listInput, k):
'''
time complexity : O(n)
space : O(1)
'''
maxLength,numOnes, start = 0, 0, 0
for i in range(len(listInput)):
if listInput[i] == 1:
numOnes += 1
if (i - start + 1 - numOnes) > k:
if listInput[start] == 1:
numOnes -= 1
start += 1
maxLength = max(maxLength, i - start + 1)
return maxLength
def longestSubStringAfterReplacement_2(listInput, k):
maxLength,numZeros, start = 0, 0, 0
for i in range(len(listInput)):
if listInput[i] == 0:
numZeros += 1
if numZeros > k:
if listInput[start] == 0:
numZeros -= 1
start += 1
maxLength = max(maxLength, i - start + 1)
return maxLength
if __name__ == '__main__':
list1 = [0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1]
list2 = [0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1]
longestSubStringAfterReplacement = longestSubStringAfterReplacement_2
print(f"longestSubStringAfterReplacement{longestSubStringAfterReplacement(list1, 2)}")
print(f"longestSubStringAfterReplacement{longestSubStringAfterReplacement(list2, 3)}") | # Given an array containing 0s and 1s, if you are allowed to replace no more than ‘k’ 0s with 1s, find the length of the longest contiguous subarray having all 1s.
# Example 1:
# Input: Array=[0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1], k=2
# Output: 6
# Explanation: Replace the '0' at index 5 and 8 to have the longest contiguous subarray of 1s having length 6.
# Example 2:
# Input: Array=[0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1], k=3
# Output: 9
# Explanation: Replace the '0' at index 6, 9, and 10 to have the longest contiguous subarray of 1s having length 9.
def longestSubStringAfterReplacement(listInput, k):
'''
time complexity : O(n)
space : O(1)
'''
maxLength,numOnes, start = 0, 0, 0
for i in range(len(listInput)):
if listInput[i] == 1:
numOnes += 1
if (i - start + 1 - numOnes) > k:
if listInput[start] == 1:
numOnes -= 1
start += 1
maxLength = max(maxLength, i - start + 1)
return maxLength
def longestSubStringAfterReplacement_2(listInput, k):
maxLength,numZeros, start = 0, 0, 0
for i in range(len(listInput)):
if listInput[i] == 0:
numZeros += 1
if numZeros > k:
if listInput[start] == 0:
numZeros -= 1
start += 1
maxLength = max(maxLength, i - start + 1)
return maxLength
if __name__ == '__main__':
list1 = [0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1]
list2 = [0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1]
longestSubStringAfterReplacement = longestSubStringAfterReplacement_2
print(f"longestSubStringAfterReplacement{longestSubStringAfterReplacement(list1, 2)}")
print(f"longestSubStringAfterReplacement{longestSubStringAfterReplacement(list2, 3)}") | en | 0.761781 | # Given an array containing 0s and 1s, if you are allowed to replace no more than ‘k’ 0s with 1s, find the length of the longest contiguous subarray having all 1s. # Example 1: # Input: Array=[0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1], k=2 # Output: 6 # Explanation: Replace the '0' at index 5 and 8 to have the longest contiguous subarray of 1s having length 6. # Example 2: # Input: Array=[0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1], k=3 # Output: 9 # Explanation: Replace the '0' at index 6, 9, and 10 to have the longest contiguous subarray of 1s having length 9. time complexity : O(n) space : O(1) | 3.953542 | 4 |
spdypy/__init__.py | Lukasa/spdypy | 3 | 6620277 | # -*- coding: utf-8 -*-
"""
spdypy - SPDY for lovers
~~~~~~~~~~~~~~~~~~~~~~~~
SPDYPy is a library for easily making and working with SPDY connections,
written in pure Python, depending on nothing but the standard library.
:copyright: (c) 2013 by <NAME>.
:license: MIT, see LICENSE for details.
"""
__title__ = 'spdypy'
__version__ = '0.0.0'
__build__ = 0x000000
__author__ = '<NAME>'
__license__ = 'MIT'
__copyright__ = 'Copyright 2013 <NAME>'
# Python version check.
import sys
version = sys.version_info
if version[0] < 3 or version[1] < 3:
raise ImportError("Minimum Python version is 3.3.")
from .connection import SPDYConnection
| # -*- coding: utf-8 -*-
"""
spdypy - SPDY for lovers
~~~~~~~~~~~~~~~~~~~~~~~~
SPDYPy is a library for easily making and working with SPDY connections,
written in pure Python, depending on nothing but the standard library.
:copyright: (c) 2013 by <NAME>.
:license: MIT, see LICENSE for details.
"""
__title__ = 'spdypy'
__version__ = '0.0.0'
__build__ = 0x000000
__author__ = '<NAME>'
__license__ = 'MIT'
__copyright__ = 'Copyright 2013 <NAME>'
# Python version check.
import sys
version = sys.version_info
if version[0] < 3 or version[1] < 3:
raise ImportError("Minimum Python version is 3.3.")
from .connection import SPDYConnection
| en | 0.830699 | # -*- coding: utf-8 -*- spdypy - SPDY for lovers ~~~~~~~~~~~~~~~~~~~~~~~~ SPDYPy is a library for easily making and working with SPDY connections, written in pure Python, depending on nothing but the standard library. :copyright: (c) 2013 by <NAME>. :license: MIT, see LICENSE for details. # Python version check. | 1.796029 | 2 |
www/main.py | Yaoxin/improved_webpy | 0 | 6620278 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
import web
from base import *
from config import configs
from url import urls
modules = ['apps.test']
def add_modules(module_list=None):
for mod in module_list:
load_module(mod)
# init db:
create_engine(configs.db.user, configs.db.passwd, configs.db.database)
# add modules
add_modules(modules)
# init wsgi app:
app = web.application(urls, globals(), autoreload=False)
web.config.debug = False
if __name__ == '__main__':
app.run()
else:
application = app.wsgifunc()
| #!/usr/bin/env python
# -*- coding: UTF-8 -*-
import web
from base import *
from config import configs
from url import urls
modules = ['apps.test']
def add_modules(module_list=None):
for mod in module_list:
load_module(mod)
# init db:
create_engine(configs.db.user, configs.db.passwd, configs.db.database)
# add modules
add_modules(modules)
# init wsgi app:
app = web.application(urls, globals(), autoreload=False)
web.config.debug = False
if __name__ == '__main__':
app.run()
else:
application = app.wsgifunc()
| en | 0.099891 | #!/usr/bin/env python # -*- coding: UTF-8 -*- # init db: # add modules # init wsgi app: | 2.104859 | 2 |
wink.py | pmvr/micropython-fido2 | 3 | 6620279 | <gh_stars>1-10
import pyb
timer_wink = None
timer_wink_counter = 0
def init_timer():
global timer_wink, timer_wink_counter
timer_wink = pyb.Timer(4)
timer_wink.init(freq=2)
timer_wink.callback(None)
timer_wink_counter = 0
def setup_timer(counter=10):
global timer_wink, timer_wink_counter
timer_wink.callback(None)
timer_wink_counter = counter
timer_wink.callback(flash_led)
def flash_led(self):
global timer_wink_counter
if timer_wink_counter > 0:
timer_wink_counter -= 1
pyb.LED(1).toggle()
| import pyb
timer_wink = None
timer_wink_counter = 0
def init_timer():
global timer_wink, timer_wink_counter
timer_wink = pyb.Timer(4)
timer_wink.init(freq=2)
timer_wink.callback(None)
timer_wink_counter = 0
def setup_timer(counter=10):
global timer_wink, timer_wink_counter
timer_wink.callback(None)
timer_wink_counter = counter
timer_wink.callback(flash_led)
def flash_led(self):
global timer_wink_counter
if timer_wink_counter > 0:
timer_wink_counter -= 1
pyb.LED(1).toggle() | none | 1 | 2.861397 | 3 | |
src/app/test/mixer.py | vaibhavantil2/education-backend | 151 | 6620280 | <reponame>vaibhavantil2/education-backend
import uuid
from mixer.backend.django import mixer
__all__ = [
mixer,
]
mixer.register('users.User', username=lambda: str(uuid.uuid4()))
| import uuid
from mixer.backend.django import mixer
__all__ = [
mixer,
]
mixer.register('users.User', username=lambda: str(uuid.uuid4())) | none | 1 | 1.534302 | 2 | |
nipy/io/imageformats/testing/__init__.py | yarikoptic/NiPy-OLD | 1 | 6620281 | ''' Utilities for testing '''
# Allow failed import of nose if not now running tests
try:
import nose.tools as nt
except ImportError:
pass
else:
from lightunit import ParametricTestCase, parametric
# wrappers to change context for nose.tools tests '''
assert_equal = lambda x, y: nt.assert_equal(x, y)
assert_not_equal = lambda x, y: nt.assert_not_equal(x, y)
assert_true = lambda x: nt.assert_true(x)
assert_false = lambda x: nt.assert_false(x)
def assert_raises(error, func, *args, **kwargs):
return nt.assert_raises(error, func, *args, **kwargs)
| ''' Utilities for testing '''
# Allow failed import of nose if not now running tests
try:
import nose.tools as nt
except ImportError:
pass
else:
from lightunit import ParametricTestCase, parametric
# wrappers to change context for nose.tools tests '''
assert_equal = lambda x, y: nt.assert_equal(x, y)
assert_not_equal = lambda x, y: nt.assert_not_equal(x, y)
assert_true = lambda x: nt.assert_true(x)
assert_false = lambda x: nt.assert_false(x)
def assert_raises(error, func, *args, **kwargs):
return nt.assert_raises(error, func, *args, **kwargs)
| en | 0.744198 | Utilities for testing # Allow failed import of nose if not now running tests # wrappers to change context for nose.tools tests ''' | 2.188835 | 2 |
smh_app/utils.py | TransparentHealth/smh-organization | 3 | 6620282 | <gh_stars>1-10
from decimal import Decimal
import requests
from django.conf import settings
TRUE_LIST = [1, "1", "true", "True", "TRUE", "YES", "Yes", "yes", True]
FALSE_LIST = [0, "0", "False", "FALSE", "false", "NO", "No", "no", False]
def bool_env(env_val):
""" check for boolean values """
if env_val:
if env_val in TRUE_LIST:
return True
if env_val in FALSE_LIST:
return False
return env_val
else:
if env_val in FALSE_LIST:
return False
return
def int_env(env_val):
""" convert to integer from String """
return int(Decimal(float(env_val)))
def get_vmi_user_data(request):
""" Makes a call to the VMI user_profile endpoint and returns a response """
user_endpoint = settings.SOCIAL_AUTH_VERIFYMYIDENTITY_OPENIDCONNECT_HOST + '/api/v1/user/'
social_auth_extra_data = request.user.social_auth.values().first()['extra_data']
token = social_auth_extra_data['access_token'] if social_auth_extra_data else None
response = requests.get(
url=user_endpoint, headers={'Authorization': "Bearer {}".format(token)}
)
return response
| from decimal import Decimal
import requests
from django.conf import settings
TRUE_LIST = [1, "1", "true", "True", "TRUE", "YES", "Yes", "yes", True]
FALSE_LIST = [0, "0", "False", "FALSE", "false", "NO", "No", "no", False]
def bool_env(env_val):
""" check for boolean values """
if env_val:
if env_val in TRUE_LIST:
return True
if env_val in FALSE_LIST:
return False
return env_val
else:
if env_val in FALSE_LIST:
return False
return
def int_env(env_val):
""" convert to integer from String """
return int(Decimal(float(env_val)))
def get_vmi_user_data(request):
""" Makes a call to the VMI user_profile endpoint and returns a response """
user_endpoint = settings.SOCIAL_AUTH_VERIFYMYIDENTITY_OPENIDCONNECT_HOST + '/api/v1/user/'
social_auth_extra_data = request.user.social_auth.values().first()['extra_data']
token = social_auth_extra_data['access_token'] if social_auth_extra_data else None
response = requests.get(
url=user_endpoint, headers={'Authorization': "Bearer {}".format(token)}
)
return response | en | 0.633731 | check for boolean values convert to integer from String Makes a call to the VMI user_profile endpoint and returns a response | 2.383406 | 2 |
tests/fixtures/metars.py | WxBDM/metar_to_xml | 0 | 6620283 | import pytest
# ==== METARS to be used for validation. No niche cases. ===
@pytest.fixture
def normal_metar():
return "KIAH 141953Z 01015KT 10SM OVC014 25/21 A2972 RMK AO2 SLP064 T02500206"
@pytest.fixture
def variable_wind_metar():
return "KGNV 141953Z VRB03KT 10SM SCT040 32/24 A3001 RMK AO2 LTG DSNT NE-S SLPNO T03220239 $"
@pytest.fixture
def visibility_metar():
return "KNID 141722Z VRB03KT 2 1/2SM HZ SCT000 27/M01 A2998 RMK AO2 SFC VIS 3 T02671011 $"
@pytest.fixture
def multiple_cloud_layer_metar():
return "KTPA 110353Z 15006KT 10SM VCTS FEW020 FEW038 SCT110 BKN160 27/23 A3007 RMK AO2 LTG DSNT W AND NW SLP182 OCNL LTGIC DSNT NW CB DSNT NW T02670233"
@pytest.fixture
def automated_metar():
return "KP60 211356Z AUTO 00000KT M05/M06 A3057 RMK AO1 SLP375 T10501056"
@pytest.fixture
def multiple_wx_conditions_metar():
return 'KDTW 231453Z 25010KT 1 1/2SM -DZ BR BKN005 OVC010 11/09 A2967 RMK AO2 SFC VIS 2 1/2 DZE1356B32RAB1356E32 SLP046 P0000 60002 T01060094 51011'
@pytest.fixture
def all_metars(automated_metar, multiple_cloud_layer_metar, visibility_metar,
variable_wind_metar, normal_metar, multiple_wx_conditions_metar):
return [normal_metar, variable_wind_metar, visibility_metar,
multiple_cloud_layer_metar, automated_metar, multiple_wx_conditions_metar]
# === Niche case metars - use under certain circumstances
@pytest.fixture
def runway_visual_range_metar():
return "KMBS 231423Z 33021G30KT 1 1/4SM R23/5000VP6000FT -RA BR SCT006 OVC010 10/09 A2970 RMK AO2 PK WND 33030/1417 P0005 T01000089"
@pytest.fixture
def wx_conditions_vicinity(multiple_cloud_layer_metar):
return multiple_cloud_layer_metar
@pytest.fixture
def vertical_visibility():
return "KHVR 081327Z AUTO 31005KT 1/2SM FZFG VV003 M03/M03 A3002 RMK AO2 T10331033"
| import pytest
# ==== METARS to be used for validation. No niche cases. ===
@pytest.fixture
def normal_metar():
return "KIAH 141953Z 01015KT 10SM OVC014 25/21 A2972 RMK AO2 SLP064 T02500206"
@pytest.fixture
def variable_wind_metar():
return "KGNV 141953Z VRB03KT 10SM SCT040 32/24 A3001 RMK AO2 LTG DSNT NE-S SLPNO T03220239 $"
@pytest.fixture
def visibility_metar():
return "KNID 141722Z VRB03KT 2 1/2SM HZ SCT000 27/M01 A2998 RMK AO2 SFC VIS 3 T02671011 $"
@pytest.fixture
def multiple_cloud_layer_metar():
return "KTPA 110353Z 15006KT 10SM VCTS FEW020 FEW038 SCT110 BKN160 27/23 A3007 RMK AO2 LTG DSNT W AND NW SLP182 OCNL LTGIC DSNT NW CB DSNT NW T02670233"
@pytest.fixture
def automated_metar():
return "KP60 211356Z AUTO 00000KT M05/M06 A3057 RMK AO1 SLP375 T10501056"
@pytest.fixture
def multiple_wx_conditions_metar():
return 'KDTW 231453Z 25010KT 1 1/2SM -DZ BR BKN005 OVC010 11/09 A2967 RMK AO2 SFC VIS 2 1/2 DZE1356B32RAB1356E32 SLP046 P0000 60002 T01060094 51011'
@pytest.fixture
def all_metars(automated_metar, multiple_cloud_layer_metar, visibility_metar,
variable_wind_metar, normal_metar, multiple_wx_conditions_metar):
return [normal_metar, variable_wind_metar, visibility_metar,
multiple_cloud_layer_metar, automated_metar, multiple_wx_conditions_metar]
# === Niche case metars - use under certain circumstances
@pytest.fixture
def runway_visual_range_metar():
return "KMBS 231423Z 33021G30KT 1 1/4SM R23/5000VP6000FT -RA BR SCT006 OVC010 10/09 A2970 RMK AO2 PK WND 33030/1417 P0005 T01000089"
@pytest.fixture
def wx_conditions_vicinity(multiple_cloud_layer_metar):
return multiple_cloud_layer_metar
@pytest.fixture
def vertical_visibility():
return "KHVR 081327Z AUTO 31005KT 1/2SM FZFG VV003 M03/M03 A3002 RMK AO2 T10331033"
| en | 0.63988 | # ==== METARS to be used for validation. No niche cases. === # === Niche case metars - use under certain circumstances | 2.211563 | 2 |
earley_parser/test_module/test_grammar_module/__init__.py | Andy-Messer/formal-languages-practice-2 | 0 | 6620284 | from early_parser.test_module.test_grammar_module.tests import *
| from early_parser.test_module.test_grammar_module.tests import *
| none | 1 | 1.093768 | 1 | |
main.py | Kurt212/TarkovTradeBot | 40 | 6620285 | import requests, zlib, hashlib, json
import time, threading
import logging
import random
from multiprocessing.pool import ThreadPool
from enum import Enum
class GameConstants:
RUBLES = '5449016a4bdc2d6f028b456f'
DOLLARS = '5696686a4bdc2da3298b456a'
EURO = '569668774bdc2da2298b4568'
Therapist = '54cb57776803fa99248b456e'
gasan = '<KEY>'
labKey = '<KEY>'
salewa = '<KEY>'
class FleaOffer:
def __init__(self, offer: dict):
self.offer = offer
self.id = offer['_id']
self.user = dict()
self.user['id'] = offer['user']['id']
self.user['nickname'] = offer['user']['nickname']
self.item_tpl = offer['items'][0]['_tpl']
self.count = offer['items'][0]['upd']['StackObjectsCount']
self.requirements = list()
self.requirements = offer['requirements']
self.summary_cost = offer['summaryCost']
self.start_time = offer['startTime']
self.end_time = offer['endTime']
def __str__(self):
return f'{self.user["nickname"]} - {self.summary_cost} - x{self.count}'
def _repr_(self):
return str(self)
def remove_white_space(s):
return s.replace(' ', '').replace('\n', '')
class GameRequest:
def __init__(self, url: str, data: str, cookies={}):
self.request = requests.post(url, data, cookies=cookies)
self.cookies = self.request.cookies.get_dict()
def _get_content(self):
return zlib.decompress(self.request.content).decode()
def __str__(self):
return self._get_content()
def __repr__(self):
return str(self)
def get_json(self) -> dict:
return json.loads(self._get_content())
class GameConnection:
logger = logging.getLogger("GameConnection")
logger.setLevel("DEBUG")
cookies = None
def __init__(self, email="", password="", cookies=''):
self.logger.debug("Connecting to game")
if cookies != '':
self.cookies = {'PHPSESSID': cookies}
else:
self.email = email
self.password = password
self.cookies = self._get_cookies()
self.logger.debug(f"Using cookies: {self.cookies}")
def _get_cookies(self):
loginReq = self._login()
return loginReq.cookies
def _login(self):
if self.email == "" or self.password == "":
raise ValueError("Email or password are invalid")
device_id = "ENTER_YOUR_DEVICE_ID_HERE"
major_v = "ENTER_MAJOR_GAME_VERSION_HERE" # eg. "0.11.7.3087"
# minor_v = "bgkidft87ddd"
data = dict()
data['version'] = {}
data['version']['major'] = major_v
data['version']['backend'] = 6
data['device_id'] = device_id
data['develop'] = True
data['email'] = self.email
data['pass'] = self.password
req = self.prod_request('/client/game/login', json.dumps(data))
self.logger.debug("Login request: " + str(req))
# TODO: require Hardware code if login is done for the first time
return req
def _send_request(self, path, data):
data = zlib.compress(remove_white_space(data).encode())
cookies = {}
if self.cookies is not None:
cookies = self.cookies
req = GameRequest(path, data=data, cookies=cookies)
return req
def prod_request(self, path: str, data: str) -> GameRequest:
return self._send_request("http://prod.escapefromtarkov.com" + path, data)
def trading_request(self, path: str, data: str) -> GameRequest:
return self._send_request("http://trading.escapefromtarkov.com" + path, data)
def ragfair_request(self, path: str, data: str) -> GameRequest:
return self._send_request("http://ragfair.escapefromtarkov.com" + path, data)
class FleaBuyResult(Enum):
OK = 0,
BOUGHT = 1
OUTOFSPACE = 2
UNKNOWN = -1
class Game:
logger = logging.getLogger("Game")
logger.setLevel("DEBUG")
profileLock = threading.Lock()
def __init__(self, email="", password="", cookies=None):
self.logger.debug("Initializing game")
self.connection = GameConnection(email, password, cookies)
self.keep_alive_thread = threading.Thread(target=self._keep_alive)
self.keep_alive_thread.daemon = True
self.keep_alive_thread.start()
self.moneyStacks = {}
self.PMC = None
self.update_profile()
self.connection.prod_request('/client/game/profile/select',
json.dumps({'uid': self.PMC['_id']}))
self.all_item_list = self.connection.prod_request('/client/items', '{}').get_json()['data']
"""
Method running in separate thread. Sends alive req to server to keep cookies valid.
"""
def _keep_alive(self):
while True:
self.connection.prod_request('/client/game/keepalive', '')
time.sleep(5 * 60)
"""
Reloads information about PMC, including money, inventory items etc.
"""
def update_profile(self):
with self.profileLock:
list_req = self.connection.prod_request("/client/game/profile/list", "{}")
profile_list = list_req.get_json()
for item in profile_list['data']:
if item['Info']['LastTimePlayedAsSavage'] == 0:
self.PMC = item
self._inventory = dict()
for item in self.PMC['Inventory']['items']:
self._inventory[item['_id']] = item
for currency in (GameConstants.RUBLES, GameConstants.DOLLARS, GameConstants.EURO):
self.moneyStacks[currency] = {}
for item_id, item in self._inventory.items():
for currency in (GameConstants.RUBLES, GameConstants.DOLLARS, GameConstants.EURO):
if item['_tpl'] == currency:
count = item['upd']['StackObjectsCount']
self.moneyStacks[currency][item_id] = count
"""
:return dictionary of pairs item_id -> item_desc
"""
def get_inventory(self):
with self.profileLock:
return self._inventory
"""
Returns money stack ids, which sum >= value
"""
def find_moneystack(self, money: int, currency=GameConstants.RUBLES) -> list:
with self.profileLock:
result = []
for (id, value) in self.moneyStacks[currency].items():
if value >= money:
result.append((id, money))
break
else:
money -= value
result.append((id, value))
return result
"""
Get inventory item ids by item template
"""
def inventory_items_ids(self, item_tpl: str) -> list:
return [item['_id'] for item in self.PMC['Inventory']['items'] if item['_tpl'] == item_tpl]
def get_traders_list(self):
req = self.connection.trading_request('/client/trading/api/getTradersList', '')
result = dict()
for trader in req.get_json()['data']:
result[trader['_id']] = trader
return result
def get_trader_assort(self, trader_id: str) -> list:
req = self.connection.trading_request('/client/trading/api/getTraderAssort/' + trader_id, '')
return req.get_json()['data']
def flea_find(self, limit=15, priceFrom=0, priceTo=0,
removeBartering=True, removeMerchantOffers=True, item_tpl=''):
data = {
"page": 0,
"limit": limit,
"sortType": 5,
"sortDirection": 0,
"currency": 0,
"priceFrom": priceFrom,
"priceTo": priceTo,
"quantityFrom": 0,
"quantityTo": 0,
"conditionFrom": 0,
"conditionTo": 100,
"oneHourExpiration": False,
"onlyPrioritized": False,
"removeBartering": removeBartering,
"removeMerchantOffers": removeMerchantOffers,
"onlyFunctional": True,
"updateOfferCount": True,
"handbookId": item_tpl,
"linkedSearchId": "",
"neededSearchId": ""
}
req = self.connection.ragfair_request('/client/ragfair/search', json.dumps(data))
# for item in req.get_json()['data']['offers']:
offers = req.get_json()['data']['offers']
result = list()
for offer in offers:
result.append(FleaOffer(offer))
result.sort(key=lambda x: x.summary_cost)
return result
def flea_buy(self, offer: FleaOffer) -> FleaBuyResult:
self.logger.info(f'------------ Buying {offer.id} x {offer.count} for {offer.summary_cost} ------------')
spent_time = time.time() - offer.start_time
start_from = 56
if spent_time < start_from:
to_wait = start_from - spent_time
self.logger.info(f"Need to wait {to_wait}")
time.sleep(to_wait)
while time.time() < offer.end_time:
try:
time.sleep(0.05)
data = {
"data": [
{
"Action": "RagFairBuyOffer",
"offerId": offer.id,
"count": offer.count,
"items": []
}
]
}
# TODO: support not only rubbles purchases
stacks = self.find_moneystack(offer.summary_cost * offer.count, GameConstants.RUBLES)
for stack in stacks:
stack_info = dict()
stack_info['id'] = stack[0]
stack_info['count'] = stack[1]
data['data'][0]['items'].append(stack_info)
req = self.connection.prod_request('/client/game/profile/items/moving', json.dumps(data))
result_data = req.get_json()
# still is not available
if result_data['err'] in (228, 1512):
continue
if result_data['err'] == 1505:
return FleaBuyResult.OUTOFSPACE
# this means that transaction is okay
if result_data['err'] == 0:
self.update_profile()
# offer was sold out
if len(result_data['data']['badRequest']) > 0:
return FleaBuyResult.BOUGHT
# added new item to inventory
elif len(result_data['data']['items'].keys()) > 0:
return FleaBuyResult.OK
print(result_data)
return FleaBuyResult.UNKNOWN
except Exception as e:
self.logger.exception(str(e))
def get_stash_size(self):
stash_id = self.PMC['Inventory']['stash']
stash_tpl = self.get_inventory()[stash_id]['tpl']
stash_props = self.all_item_list[stash_tpl]['_props']['Grids'][0]['_props']
return stash_props['cellsV'], stash_props['cellsH']
class FleaBuyThread(ThreadPool):
def __init__(self, game: Game, offer: FleaOffer):
super().__init__(processes=1)
self.game = game
self.offer = offer
self.async_result = None
def start(self):
self.async_result = self.apply_async(self.game.flea_buy, [self.offer])
def is_ready(self):
return self.async_result.ready()
def get_result(self, timeout=None):
return self.async_result.get(timeout)
class TarkovBot:
logger = logging.getLogger("TarkovBot")
logger.setLevel("DEBUG")
def __init__(self, email='', password='', cookies=''):
FORMAT = '%(asctime)s: %(message)s'
logging.basicConfig(format=FORMAT, )
self.logger.debug("Initializing bot")
self.game = Game(email, password, cookies)
def filter_inventory(self, item_tpl):
inv = self.game.get_inventory()
return list(filter(lambda x: x[1]['_tpl'] == item_tpl, inv.items()))
def flea_market_buy(self, item_tpl: str, upper_price: int, offer_count=5, until_amount=None, delay_from=5, delay_to=10):
if until_amount is None:
until_amount = 1000
offer_container = list()
offer_id_set = set()
while len(self.filter_inventory(item_tpl)) < until_amount:
try:
container_copy = list(offer_container)
for offer_thread in offer_container:
if offer_thread.is_ready():
offer_id_set.remove(offer_thread.offer.id)
container_copy.remove(offer_thread)
result = offer_thread.get_result()
offer = offer_thread.offer
assert isinstance(offer, FleaOffer)
if result == FleaBuyResult.OK:
self.logger.info(
f'------------ Successfully bought offer {offer.id}'
f' for {offer.summary_cost} -----------'
)
else:
self.logger.info(
f'------------ Failed to buy offer {offer.id} - {result} -----------'
)
offer_container = container_copy
if len(offer_container) < offer_count:
new_offers = self.game.flea_find(limit=15, priceTo=upper_price, item_tpl=item_tpl)
new_offers = [item for item in new_offers if item.id not in offer_id_set]
if len(new_offers) != 0:
can_add_count = offer_count - len(offer_container)
self.logger.info(f'Found {len(new_offers)} offers. Can add {can_add_count}')
for i in range(min(can_add_count, len(new_offers))):
buy_thread = FleaBuyThread(self.game, new_offers[i])
buy_thread.start()
offer_container.append(buy_thread)
offer_id_set.add(new_offers[i].id)
except KeyboardInterrupt as keyBoard:
for offer_thread in offer_container:
self.logger.debug(f"Terminating thread for {offer_thread.offer.id}")
offer_thread.terminate()
break
except Exception as e:
self.logger.exception(str(e))
finally:
try:
time.sleep(random.randint(delay_from, delay_to))
except KeyboardInterrupt as keyBoard:
for offer_thread in offer_container:
self.logger.debug(f"Terminating thread for {offer_thread.offer.id}")
offer_thread.terminate()
break
"""
Tries to free some space by merging and transfering ruble stacks
"""
def merge_all_rubles(self):
all_rubles = sorted(list(bot.game.moneyStacks[GameConstants.RUBLES].items()), key=lambda x: x[1])
all_rubles = [item for item in all_rubles if item[1] != 500000]
merge_data = []
for i in range(len(all_rubles)):
itemI = list(all_rubles[i])
if itemI[1] == 500000:
continue
for j in range(i + 1, len(all_rubles)):
itemJ = list(all_rubles[j])
# merge i to j
if itemI[1] == 0 or itemJ[1] == 500000:
continue
can_merge = 500000 - itemJ[1]
if itemI[1] > can_merge:
itemI[1] -= can_merge
itemJ[1] = 500000
merge_data.append([itemI[0], itemJ[0], can_merge])
else:
itemJ[1] += itemI[1]
itemI[1] = 0
merge_data.append([itemI[0], itemJ[0]])
all_rubles[i] = itemI
all_rubles[j] = itemJ
if itemI[1] == 0:
break
data = {
'data': []
}
for merge in merge_data:
if len(merge) == 2:
d = {"Action":"Merge","item":merge[0],"with":merge[1]}
else:
d = {"Action":"Transfer","item":merge[0],"with":merge[1], 'count': merge[2]}
data['data'].append(d)
if len(data['data']) > 0:
req = bot.game.connection.prod_request('/client/game/profile/items/moving', json.dumps(data))
print(req)
bot.game.update_profile()
email = "ENTER_YOUR_EMAIL_HERE"
password = "<PASSWORD>"
cookie = 'ENTER_COOKIE_IF_NEEDED_HERE'
bot = TarkovBot(email=email, password=password, cookies=cookie)
| import requests, zlib, hashlib, json
import time, threading
import logging
import random
from multiprocessing.pool import ThreadPool
from enum import Enum
class GameConstants:
RUBLES = '5449016a4bdc2d6f028b456f'
DOLLARS = '5696686a4bdc2da3298b456a'
EURO = '569668774bdc2da2298b4568'
Therapist = '54cb57776803fa99248b456e'
gasan = '<KEY>'
labKey = '<KEY>'
salewa = '<KEY>'
class FleaOffer:
def __init__(self, offer: dict):
self.offer = offer
self.id = offer['_id']
self.user = dict()
self.user['id'] = offer['user']['id']
self.user['nickname'] = offer['user']['nickname']
self.item_tpl = offer['items'][0]['_tpl']
self.count = offer['items'][0]['upd']['StackObjectsCount']
self.requirements = list()
self.requirements = offer['requirements']
self.summary_cost = offer['summaryCost']
self.start_time = offer['startTime']
self.end_time = offer['endTime']
def __str__(self):
return f'{self.user["nickname"]} - {self.summary_cost} - x{self.count}'
def _repr_(self):
return str(self)
def remove_white_space(s):
return s.replace(' ', '').replace('\n', '')
class GameRequest:
def __init__(self, url: str, data: str, cookies={}):
self.request = requests.post(url, data, cookies=cookies)
self.cookies = self.request.cookies.get_dict()
def _get_content(self):
return zlib.decompress(self.request.content).decode()
def __str__(self):
return self._get_content()
def __repr__(self):
return str(self)
def get_json(self) -> dict:
return json.loads(self._get_content())
class GameConnection:
logger = logging.getLogger("GameConnection")
logger.setLevel("DEBUG")
cookies = None
def __init__(self, email="", password="", cookies=''):
self.logger.debug("Connecting to game")
if cookies != '':
self.cookies = {'PHPSESSID': cookies}
else:
self.email = email
self.password = password
self.cookies = self._get_cookies()
self.logger.debug(f"Using cookies: {self.cookies}")
def _get_cookies(self):
loginReq = self._login()
return loginReq.cookies
def _login(self):
if self.email == "" or self.password == "":
raise ValueError("Email or password are invalid")
device_id = "ENTER_YOUR_DEVICE_ID_HERE"
major_v = "ENTER_MAJOR_GAME_VERSION_HERE" # eg. "0.11.7.3087"
# minor_v = "bgkidft87ddd"
data = dict()
data['version'] = {}
data['version']['major'] = major_v
data['version']['backend'] = 6
data['device_id'] = device_id
data['develop'] = True
data['email'] = self.email
data['pass'] = self.password
req = self.prod_request('/client/game/login', json.dumps(data))
self.logger.debug("Login request: " + str(req))
# TODO: require Hardware code if login is done for the first time
return req
def _send_request(self, path, data):
data = zlib.compress(remove_white_space(data).encode())
cookies = {}
if self.cookies is not None:
cookies = self.cookies
req = GameRequest(path, data=data, cookies=cookies)
return req
def prod_request(self, path: str, data: str) -> GameRequest:
return self._send_request("http://prod.escapefromtarkov.com" + path, data)
def trading_request(self, path: str, data: str) -> GameRequest:
return self._send_request("http://trading.escapefromtarkov.com" + path, data)
def ragfair_request(self, path: str, data: str) -> GameRequest:
return self._send_request("http://ragfair.escapefromtarkov.com" + path, data)
class FleaBuyResult(Enum):
OK = 0,
BOUGHT = 1
OUTOFSPACE = 2
UNKNOWN = -1
class Game:
logger = logging.getLogger("Game")
logger.setLevel("DEBUG")
profileLock = threading.Lock()
def __init__(self, email="", password="", cookies=None):
self.logger.debug("Initializing game")
self.connection = GameConnection(email, password, cookies)
self.keep_alive_thread = threading.Thread(target=self._keep_alive)
self.keep_alive_thread.daemon = True
self.keep_alive_thread.start()
self.moneyStacks = {}
self.PMC = None
self.update_profile()
self.connection.prod_request('/client/game/profile/select',
json.dumps({'uid': self.PMC['_id']}))
self.all_item_list = self.connection.prod_request('/client/items', '{}').get_json()['data']
"""
Method running in separate thread. Sends alive req to server to keep cookies valid.
"""
def _keep_alive(self):
while True:
self.connection.prod_request('/client/game/keepalive', '')
time.sleep(5 * 60)
"""
Reloads information about PMC, including money, inventory items etc.
"""
def update_profile(self):
with self.profileLock:
list_req = self.connection.prod_request("/client/game/profile/list", "{}")
profile_list = list_req.get_json()
for item in profile_list['data']:
if item['Info']['LastTimePlayedAsSavage'] == 0:
self.PMC = item
self._inventory = dict()
for item in self.PMC['Inventory']['items']:
self._inventory[item['_id']] = item
for currency in (GameConstants.RUBLES, GameConstants.DOLLARS, GameConstants.EURO):
self.moneyStacks[currency] = {}
for item_id, item in self._inventory.items():
for currency in (GameConstants.RUBLES, GameConstants.DOLLARS, GameConstants.EURO):
if item['_tpl'] == currency:
count = item['upd']['StackObjectsCount']
self.moneyStacks[currency][item_id] = count
"""
:return dictionary of pairs item_id -> item_desc
"""
def get_inventory(self):
with self.profileLock:
return self._inventory
"""
Returns money stack ids, which sum >= value
"""
def find_moneystack(self, money: int, currency=GameConstants.RUBLES) -> list:
with self.profileLock:
result = []
for (id, value) in self.moneyStacks[currency].items():
if value >= money:
result.append((id, money))
break
else:
money -= value
result.append((id, value))
return result
"""
Get inventory item ids by item template
"""
def inventory_items_ids(self, item_tpl: str) -> list:
return [item['_id'] for item in self.PMC['Inventory']['items'] if item['_tpl'] == item_tpl]
def get_traders_list(self):
req = self.connection.trading_request('/client/trading/api/getTradersList', '')
result = dict()
for trader in req.get_json()['data']:
result[trader['_id']] = trader
return result
def get_trader_assort(self, trader_id: str) -> list:
req = self.connection.trading_request('/client/trading/api/getTraderAssort/' + trader_id, '')
return req.get_json()['data']
def flea_find(self, limit=15, priceFrom=0, priceTo=0,
removeBartering=True, removeMerchantOffers=True, item_tpl=''):
data = {
"page": 0,
"limit": limit,
"sortType": 5,
"sortDirection": 0,
"currency": 0,
"priceFrom": priceFrom,
"priceTo": priceTo,
"quantityFrom": 0,
"quantityTo": 0,
"conditionFrom": 0,
"conditionTo": 100,
"oneHourExpiration": False,
"onlyPrioritized": False,
"removeBartering": removeBartering,
"removeMerchantOffers": removeMerchantOffers,
"onlyFunctional": True,
"updateOfferCount": True,
"handbookId": item_tpl,
"linkedSearchId": "",
"neededSearchId": ""
}
req = self.connection.ragfair_request('/client/ragfair/search', json.dumps(data))
# for item in req.get_json()['data']['offers']:
offers = req.get_json()['data']['offers']
result = list()
for offer in offers:
result.append(FleaOffer(offer))
result.sort(key=lambda x: x.summary_cost)
return result
def flea_buy(self, offer: FleaOffer) -> FleaBuyResult:
self.logger.info(f'------------ Buying {offer.id} x {offer.count} for {offer.summary_cost} ------------')
spent_time = time.time() - offer.start_time
start_from = 56
if spent_time < start_from:
to_wait = start_from - spent_time
self.logger.info(f"Need to wait {to_wait}")
time.sleep(to_wait)
while time.time() < offer.end_time:
try:
time.sleep(0.05)
data = {
"data": [
{
"Action": "RagFairBuyOffer",
"offerId": offer.id,
"count": offer.count,
"items": []
}
]
}
# TODO: support not only rubbles purchases
stacks = self.find_moneystack(offer.summary_cost * offer.count, GameConstants.RUBLES)
for stack in stacks:
stack_info = dict()
stack_info['id'] = stack[0]
stack_info['count'] = stack[1]
data['data'][0]['items'].append(stack_info)
req = self.connection.prod_request('/client/game/profile/items/moving', json.dumps(data))
result_data = req.get_json()
# still is not available
if result_data['err'] in (228, 1512):
continue
if result_data['err'] == 1505:
return FleaBuyResult.OUTOFSPACE
# this means that transaction is okay
if result_data['err'] == 0:
self.update_profile()
# offer was sold out
if len(result_data['data']['badRequest']) > 0:
return FleaBuyResult.BOUGHT
# added new item to inventory
elif len(result_data['data']['items'].keys()) > 0:
return FleaBuyResult.OK
print(result_data)
return FleaBuyResult.UNKNOWN
except Exception as e:
self.logger.exception(str(e))
def get_stash_size(self):
stash_id = self.PMC['Inventory']['stash']
stash_tpl = self.get_inventory()[stash_id]['tpl']
stash_props = self.all_item_list[stash_tpl]['_props']['Grids'][0]['_props']
return stash_props['cellsV'], stash_props['cellsH']
class FleaBuyThread(ThreadPool):
def __init__(self, game: Game, offer: FleaOffer):
super().__init__(processes=1)
self.game = game
self.offer = offer
self.async_result = None
def start(self):
self.async_result = self.apply_async(self.game.flea_buy, [self.offer])
def is_ready(self):
return self.async_result.ready()
def get_result(self, timeout=None):
return self.async_result.get(timeout)
class TarkovBot:
logger = logging.getLogger("TarkovBot")
logger.setLevel("DEBUG")
def __init__(self, email='', password='', cookies=''):
FORMAT = '%(asctime)s: %(message)s'
logging.basicConfig(format=FORMAT, )
self.logger.debug("Initializing bot")
self.game = Game(email, password, cookies)
def filter_inventory(self, item_tpl):
inv = self.game.get_inventory()
return list(filter(lambda x: x[1]['_tpl'] == item_tpl, inv.items()))
def flea_market_buy(self, item_tpl: str, upper_price: int, offer_count=5, until_amount=None, delay_from=5, delay_to=10):
if until_amount is None:
until_amount = 1000
offer_container = list()
offer_id_set = set()
while len(self.filter_inventory(item_tpl)) < until_amount:
try:
container_copy = list(offer_container)
for offer_thread in offer_container:
if offer_thread.is_ready():
offer_id_set.remove(offer_thread.offer.id)
container_copy.remove(offer_thread)
result = offer_thread.get_result()
offer = offer_thread.offer
assert isinstance(offer, FleaOffer)
if result == FleaBuyResult.OK:
self.logger.info(
f'------------ Successfully bought offer {offer.id}'
f' for {offer.summary_cost} -----------'
)
else:
self.logger.info(
f'------------ Failed to buy offer {offer.id} - {result} -----------'
)
offer_container = container_copy
if len(offer_container) < offer_count:
new_offers = self.game.flea_find(limit=15, priceTo=upper_price, item_tpl=item_tpl)
new_offers = [item for item in new_offers if item.id not in offer_id_set]
if len(new_offers) != 0:
can_add_count = offer_count - len(offer_container)
self.logger.info(f'Found {len(new_offers)} offers. Can add {can_add_count}')
for i in range(min(can_add_count, len(new_offers))):
buy_thread = FleaBuyThread(self.game, new_offers[i])
buy_thread.start()
offer_container.append(buy_thread)
offer_id_set.add(new_offers[i].id)
except KeyboardInterrupt as keyBoard:
for offer_thread in offer_container:
self.logger.debug(f"Terminating thread for {offer_thread.offer.id}")
offer_thread.terminate()
break
except Exception as e:
self.logger.exception(str(e))
finally:
try:
time.sleep(random.randint(delay_from, delay_to))
except KeyboardInterrupt as keyBoard:
for offer_thread in offer_container:
self.logger.debug(f"Terminating thread for {offer_thread.offer.id}")
offer_thread.terminate()
break
"""
Tries to free some space by merging and transfering ruble stacks
"""
def merge_all_rubles(self):
all_rubles = sorted(list(bot.game.moneyStacks[GameConstants.RUBLES].items()), key=lambda x: x[1])
all_rubles = [item for item in all_rubles if item[1] != 500000]
merge_data = []
for i in range(len(all_rubles)):
itemI = list(all_rubles[i])
if itemI[1] == 500000:
continue
for j in range(i + 1, len(all_rubles)):
itemJ = list(all_rubles[j])
# merge i to j
if itemI[1] == 0 or itemJ[1] == 500000:
continue
can_merge = 500000 - itemJ[1]
if itemI[1] > can_merge:
itemI[1] -= can_merge
itemJ[1] = 500000
merge_data.append([itemI[0], itemJ[0], can_merge])
else:
itemJ[1] += itemI[1]
itemI[1] = 0
merge_data.append([itemI[0], itemJ[0]])
all_rubles[i] = itemI
all_rubles[j] = itemJ
if itemI[1] == 0:
break
data = {
'data': []
}
for merge in merge_data:
if len(merge) == 2:
d = {"Action":"Merge","item":merge[0],"with":merge[1]}
else:
d = {"Action":"Transfer","item":merge[0],"with":merge[1], 'count': merge[2]}
data['data'].append(d)
if len(data['data']) > 0:
req = bot.game.connection.prod_request('/client/game/profile/items/moving', json.dumps(data))
print(req)
bot.game.update_profile()
email = "ENTER_YOUR_EMAIL_HERE"
password = "<PASSWORD>"
cookie = 'ENTER_COOKIE_IF_NEEDED_HERE'
bot = TarkovBot(email=email, password=password, cookies=cookie)
| en | 0.833269 | # eg. "0.11.7.3087" # minor_v = "bgkidft87ddd" # TODO: require Hardware code if login is done for the first time Method running in separate thread. Sends alive req to server to keep cookies valid. Reloads information about PMC, including money, inventory items etc. :return dictionary of pairs item_id -> item_desc Returns money stack ids, which sum >= value Get inventory item ids by item template # for item in req.get_json()['data']['offers']: # TODO: support not only rubbles purchases # still is not available # this means that transaction is okay # offer was sold out # added new item to inventory Tries to free some space by merging and transfering ruble stacks # merge i to j | 2.320829 | 2 |
pylanetary/rings/core.py | emolter/planetary_toolkit | 0 | 6620286 |
from astropy import table
from astroquery.solarsystem.pds import RingNode
from astroquery.solarsystem.jpl import Horizons
from astropy.coordinates import Angle
import astropy.units as u
from astropy import convolution
from photutils import aperture
import numpy as np
from PyAstronomy import pyasl
from collections import OrderedDict
from scipy.spatial.transform import Rotation
'''
goal:
pull together JPL Horizons query, ring node query,
and static ring data from data/ to make model ring
systems as observed from any location
is there a better/more astropy-like library to import for keplerian ellipses than PyAstronomy?
yes, but it is annoying to use
much later: get an undergrad to make Keplerian ellipse module of Astropy
'''
class Ring:
def __init__(self, a, e, omega, i, w, width = 1.0, flux = 1.0):
'''
model of a planetary ring
Parameters
----------
a : semimajor axis
e : eccentricity
Omega : longitude of ascending node
i : inclination
w : argument of periapsis
width : float or Quantity, optional. default 1 km (i.e., very thin)
flux : float or Quantity, optional. default 1.0.
Attributes
----------
a : semimajor axis
e : eccentricity
omega : longitude of ascending node
i : inclination
w : argument of periapsis
width :
flux :
Examples
--------
'''
# to do: write tests that pass astropy Quantities with units other than km and deg
self.a = u.Quantity(a, unit=u.km)
self.e = e
self.omega = u.Quantity(omega, unit=u.deg)
self.i = u.Quantity(i, unit=u.deg)
self.w = u.Quantity(w, unit=u.deg)
self.width = u.Quantity(width, unit=u.km)
self.flux = flux
def __str__(self):
'''
String representation
Examples
--------
>>> from pylanetary.rings import Ring
>>> epsilon_ring = Ring(whatever)
>>> print(epsilon_ring)
Ring instance; a=whatever, e=whatever, i=whatever, width=whatever
'''
return f'Ring instance; a={self.a}, e={self.e}, i={self.i}, width={self.width}'
def as_elliptical_annulus(shape, pixscale, width, center = None):
'''
return elliptical annulus surrounding the ring of the given width
'''
if center is None:
center = (data.shape[0]/2.0, data.shape[1]/2.0)
ann = aperture.EllipticalAnnulus(center,
a_in=self.a - width/2.,
a_out=self.a + width/2.,
b_out= abs((self.a + width/2.) * np.sin(90*u.deg - self.i)).value,
b_in= None,
theta = Angle(self.w, 'deg'))
# test whether the angles coming in here are actually correct
return ann
def as_keplers3rd_wedges(width, n):
'''
return n partial elliptical annulus wedges with equal orbital time spent in each
useful for ring as f(azimuth) because should take out foreshortening correction
but should check this! what did I do for the paper?
also perfect data experiments would be good
'''
# do this later, it's complicated to do right
return ann_list
def as_orbit(T=1, tau=0):
'''
make a PyAstronomy.KeplerEllipse object at the ring's orbit
to get position of ring particles as a function of time
Parameters
----------
T : orbital period
tau : time of periapsis passage
returns
-------
PyAstronomy Keplerian Ellipse object
examples
--------
>>> epsilon_ring = Ring(a, e, omega, i, w)
>>> orbit = epsilon_ring.as_orbit(T, tau=0)
>>> print(orbit.pos)
>>> print(orbit.radius)
>>> print(orbit.vel)
>>> print(orbit.peri)
'''
# decide: is it this code's job to calculate the orbital period
# from semimajor axis based on planet mass?
# would require planet masses in a data table
# if so, can do later
ke = pyasl.KeplerEllipse(self.a, T, tau = self.tau, e = self.e, Omega = self.omega, i = self.i, w = self.w)
return ke
def as_2d_array(self, shape, pixscale, opening_angle=90.*u.deg, center=None, width=None, flux=None, beamsize=None):
'''
return a 2-d array that looks like a mock observation
optional smearing over Gaussian beam
Parameters
----------
shape : tuple, required. output image shape
pixscale : float/int or astropy Quantity, required. pixel scale
of the output image. If float/int (i.e. no units specified), then
kilometers is assumed
width : float/int or astropy Quantity. If float/int (i.e. no units specified), then
kilometers is assumed
flux : float/int or astropy Quantity. sets brightness of the array
NEED TO DECIDE: what default units make sense here? - probably a surface brightness
beamsize : float/int or 3-element array-like, optional.
FWHM of Gaussian beam with which to convolve the observation
units of fwhm are number of pixels.
if array-like, has form (FWHM_X, FWHM_Y, POSITION_ANGLE)
units of position angle are assumed degrees unless astropy Angle is passed
if no beamsize is specified, will make infinite-resolution
Returns
-------
2-d numpy array
Examples
--------
'''
# to do: write a test that passes pixscale with units other than km
if flux is None:
flux = self.flux
if width is None:
width = self.width
pixscale = u.Quantity(pixscale, u.km)
# put the ring onto a 2-D array using EllipticalAnnulus
if center is None:
center = (shape[0]/2.0, shape[1]/2.0)
ann = aperture.EllipticalAnnulus(center,
a_in=((self.a - width/2.)/pixscale).value,
a_out=((self.a + width/2.)/pixscale).value,
b_out= (abs((self.a + width/2.) * np.sin(90*u.deg - self.i))/pixscale).value,
theta = self.w.to(u.radian)
)
arr_sharp = ann.to_mask(method='exact').to_image(shape)
# project to opening angle
if beamsize is None:
return arr_sharp
else:
# make the Gaussian beam. convert FWHM to sigma
beam = convolution.Gaussian2DKernel(beamsize[0] / 2.35482004503,
beamsize[1] / 2.35482004503,
Angle(beamsize[2], unit=u.deg))
return convolution.convolve_fft(arr_sharp, beam)
class RingSystemModelObservation:
def __init__(self,
planet,
location=None,
epoch=None,
ringnames=None,
fluxes='default'):
'''
make a model of a ring system
Parameters
----------
planet: str, required. one of Jupiter, Saturn, Uranus, Neptune
epoch : `~astropy.time.Time` object, or str in format YYYY-MM-DD hh:mm, optional.
If str is provided then UTC is assumed.
If no epoch is provided, the current time is used.
location : array-like, or `~astropy.coordinates.EarthLocation`, optional
Observer's location as a
3-element array of Earth longitude, latitude, altitude, or
`~astropy.coordinates.EarthLocation`. Longitude and
latitude should be anything that initializes an
`~astropy.coordinates.Angle` object, and altitude should
initialize an `~astropy.units.Quantity` object (with units
of length). If ``None``, then the geocenter is used.
ringnames : list, optional. which rings to include in the model
if no ringnames provided then all rings are assumed.
Case-sensitive! Typically capitalized, e.g. "Alpha"
(for now - annoying to make case-insensitive)
if fluxes == 'default':
fluxes = list(self.ringtable['Optical Depth'])
Attributes
----------
planetname : str, name of planet
rings : dict of ringmodel.Ring objects, with ring names as keys
note ring names are case-sensitive! Typically capitalized, e.g. "Alpha"
ringtable : table of ephemeris data as well as time-invariant parameters for
Examples
--------
Need an example of how to add a custom ring
should be possible by just adding a ringmodel.Ring() object
into the dict self.ring
Need an example of how to modify ring data
should be possible by just changing the ringmodel.Ring() object
in the dict self.ring
'''
planet = planet.lower().capitalize()
self.planetname = planet
# query planetary ring node and static data
self.systemtable, self.bodytable, ringtable = RingNode.ephemeris(planet, epoch=epoch, location=location)
ring_static_data = table.Table.read(f'data/{planet}_ring_data.hdf5', format = 'hdf5')
planet_ephem = self.bodytable.loc[planet]
#self.ob_lat, self.ob_lon = planet_ephem['sub_obs_lat'], planet_ephem['sub_obs_lon']
# TO DO: change the way the static data tables are read in to be more package-y
# match the static and ephemeris data for rings using a table merge
ring_static_data.rename_column('Feature', 'ring')
ringtable = table.join(ringtable, ring_static_data, keys='ring', join_type='right')
ringtable.add_index('ring')
if ringnames is None:
ringnames = list(ringtable['ring'])
# make self.ringtable and fluxes contain only the rings in ringnames
self.ringtable = ringtable.loc[ringnames]
if fluxes == 'default':
fluxes = list(self.ringtable['Optical Depth'])
self.rings = {}
for i in range(len(ringnames)):
ringname = ringnames[i]
flux = fluxes[i]
try:
ringparams = ringtable.loc[ringname]
except Exception as e:
raise ValueError(f"Ring name {ringname} not found in the data table of known rings")
# make a Ring object for each one
# TO DO: MORE MATH HERE
omega = ringparams['ascending node'] # CHECK THIS
i = u.Quantity(ringparams['Inclination (deg)'], unit=u.deg) # CHECK THIS
w = ringparams['pericenter'] # CHECK THIS
# many of the less-well-observed rings have masked values
# for many of these quantities, particularly omega, i, w, or even e. these go to
# zero when made into floats, so it is ok
thisring = Ring(ringparams['Middle Boundary (km)'] * u.km,
ringparams['Eccentricity'],
omega,
i,
w,
width = ringparams['Width'],
flux = flux)
self.rings[ringname] = thisring
#print(ringtable.loc['Epsilon'])
# TO DO: does the line above actually work?
def as_2d_array(self, shape, pixscale, center=None, beamsize=None):
'''
return a 2-d array that looks like a mock observation
optional smearing over Gaussian beam
Parameters
----------
shape : tuple, required. output image shape in number of pixels
pixscale : float/int or astropy Quantity, required. pixel scale
of the output image. If float/int (i.e. no units specified), then
kilometers is assumed
beamsize : float/int or 3-element array-like, optional.
FWHM of Gaussian beam with which to convolve the observation
units of fwhm are number of pixels.
if array-like, has form (FWHM_X, FWHM_Y, POSITION_ANGLE)
units of position angle are assumed degrees unless astropy Angle is passed
if no beamsize is specified, will make infinite-resolution
Returns
-------
2-d numpy array
Examples
--------
'''
arr_out = np.zeros(shape)
for ringname in self.rings.keys():
arr_out += self.rings[ringname].as_2d_array(shape, pixscale, center=center, beamsize=None)
## project this onto the observer plane using ring opening angle and north pole angle
r = Rotation('xyz', [self.systemtable['sub_obs_lon'], 0, 90*u.deg - self.systemtable[opening_angle]], degrees=True)
rvec = r.as_rotvec()
# TO DO: finish this!
# run convolution with beam outside loop so it is only done once
if beamsize is None:
return arr_out
else:
# make the Gaussian beam. convert FWHM to sigma
beam = convolution.Gaussian2DKernel(beamsize[0] / 2.35482004503,
beamsize[1] / 2.35482004503,
Angle(beamsize[2], unit=u.deg))
return convolution.convolve(arr_out, beam)
if __name__ == "__main__":
uranus_rings = RingSystemModelObservation('uranus',
epoch='2022-05-03 11:50',
ringnames = ['Six', 'Five', 'Four', 'Alpha', 'Beta', 'Eta', 'Gamma', 'Delta', 'Epsilon'])
obs = uranus_rings.as_2d_array((500, 500), 300*u.km, beamsize = (7,4,30*u.degree))
import matplotlib.pyplot as plt
plt.imshow(obs, origin = 'lower')
plt.show() |
from astropy import table
from astroquery.solarsystem.pds import RingNode
from astroquery.solarsystem.jpl import Horizons
from astropy.coordinates import Angle
import astropy.units as u
from astropy import convolution
from photutils import aperture
import numpy as np
from PyAstronomy import pyasl
from collections import OrderedDict
from scipy.spatial.transform import Rotation
'''
goal:
pull together JPL Horizons query, ring node query,
and static ring data from data/ to make model ring
systems as observed from any location
is there a better/more astropy-like library to import for keplerian ellipses than PyAstronomy?
yes, but it is annoying to use
much later: get an undergrad to make Keplerian ellipse module of Astropy
'''
class Ring:
def __init__(self, a, e, omega, i, w, width = 1.0, flux = 1.0):
'''
model of a planetary ring
Parameters
----------
a : semimajor axis
e : eccentricity
Omega : longitude of ascending node
i : inclination
w : argument of periapsis
width : float or Quantity, optional. default 1 km (i.e., very thin)
flux : float or Quantity, optional. default 1.0.
Attributes
----------
a : semimajor axis
e : eccentricity
omega : longitude of ascending node
i : inclination
w : argument of periapsis
width :
flux :
Examples
--------
'''
# to do: write tests that pass astropy Quantities with units other than km and deg
self.a = u.Quantity(a, unit=u.km)
self.e = e
self.omega = u.Quantity(omega, unit=u.deg)
self.i = u.Quantity(i, unit=u.deg)
self.w = u.Quantity(w, unit=u.deg)
self.width = u.Quantity(width, unit=u.km)
self.flux = flux
def __str__(self):
'''
String representation
Examples
--------
>>> from pylanetary.rings import Ring
>>> epsilon_ring = Ring(whatever)
>>> print(epsilon_ring)
Ring instance; a=whatever, e=whatever, i=whatever, width=whatever
'''
return f'Ring instance; a={self.a}, e={self.e}, i={self.i}, width={self.width}'
def as_elliptical_annulus(shape, pixscale, width, center = None):
'''
return elliptical annulus surrounding the ring of the given width
'''
if center is None:
center = (data.shape[0]/2.0, data.shape[1]/2.0)
ann = aperture.EllipticalAnnulus(center,
a_in=self.a - width/2.,
a_out=self.a + width/2.,
b_out= abs((self.a + width/2.) * np.sin(90*u.deg - self.i)).value,
b_in= None,
theta = Angle(self.w, 'deg'))
# test whether the angles coming in here are actually correct
return ann
def as_keplers3rd_wedges(width, n):
'''
return n partial elliptical annulus wedges with equal orbital time spent in each
useful for ring as f(azimuth) because should take out foreshortening correction
but should check this! what did I do for the paper?
also perfect data experiments would be good
'''
# do this later, it's complicated to do right
return ann_list
def as_orbit(T=1, tau=0):
'''
make a PyAstronomy.KeplerEllipse object at the ring's orbit
to get position of ring particles as a function of time
Parameters
----------
T : orbital period
tau : time of periapsis passage
returns
-------
PyAstronomy Keplerian Ellipse object
examples
--------
>>> epsilon_ring = Ring(a, e, omega, i, w)
>>> orbit = epsilon_ring.as_orbit(T, tau=0)
>>> print(orbit.pos)
>>> print(orbit.radius)
>>> print(orbit.vel)
>>> print(orbit.peri)
'''
# decide: is it this code's job to calculate the orbital period
# from semimajor axis based on planet mass?
# would require planet masses in a data table
# if so, can do later
ke = pyasl.KeplerEllipse(self.a, T, tau = self.tau, e = self.e, Omega = self.omega, i = self.i, w = self.w)
return ke
def as_2d_array(self, shape, pixscale, opening_angle=90.*u.deg, center=None, width=None, flux=None, beamsize=None):
'''
return a 2-d array that looks like a mock observation
optional smearing over Gaussian beam
Parameters
----------
shape : tuple, required. output image shape
pixscale : float/int or astropy Quantity, required. pixel scale
of the output image. If float/int (i.e. no units specified), then
kilometers is assumed
width : float/int or astropy Quantity. If float/int (i.e. no units specified), then
kilometers is assumed
flux : float/int or astropy Quantity. sets brightness of the array
NEED TO DECIDE: what default units make sense here? - probably a surface brightness
beamsize : float/int or 3-element array-like, optional.
FWHM of Gaussian beam with which to convolve the observation
units of fwhm are number of pixels.
if array-like, has form (FWHM_X, FWHM_Y, POSITION_ANGLE)
units of position angle are assumed degrees unless astropy Angle is passed
if no beamsize is specified, will make infinite-resolution
Returns
-------
2-d numpy array
Examples
--------
'''
# to do: write a test that passes pixscale with units other than km
if flux is None:
flux = self.flux
if width is None:
width = self.width
pixscale = u.Quantity(pixscale, u.km)
# put the ring onto a 2-D array using EllipticalAnnulus
if center is None:
center = (shape[0]/2.0, shape[1]/2.0)
ann = aperture.EllipticalAnnulus(center,
a_in=((self.a - width/2.)/pixscale).value,
a_out=((self.a + width/2.)/pixscale).value,
b_out= (abs((self.a + width/2.) * np.sin(90*u.deg - self.i))/pixscale).value,
theta = self.w.to(u.radian)
)
arr_sharp = ann.to_mask(method='exact').to_image(shape)
# project to opening angle
if beamsize is None:
return arr_sharp
else:
# make the Gaussian beam. convert FWHM to sigma
beam = convolution.Gaussian2DKernel(beamsize[0] / 2.35482004503,
beamsize[1] / 2.35482004503,
Angle(beamsize[2], unit=u.deg))
return convolution.convolve_fft(arr_sharp, beam)
class RingSystemModelObservation:
def __init__(self,
planet,
location=None,
epoch=None,
ringnames=None,
fluxes='default'):
'''
make a model of a ring system
Parameters
----------
planet: str, required. one of Jupiter, Saturn, Uranus, Neptune
epoch : `~astropy.time.Time` object, or str in format YYYY-MM-DD hh:mm, optional.
If str is provided then UTC is assumed.
If no epoch is provided, the current time is used.
location : array-like, or `~astropy.coordinates.EarthLocation`, optional
Observer's location as a
3-element array of Earth longitude, latitude, altitude, or
`~astropy.coordinates.EarthLocation`. Longitude and
latitude should be anything that initializes an
`~astropy.coordinates.Angle` object, and altitude should
initialize an `~astropy.units.Quantity` object (with units
of length). If ``None``, then the geocenter is used.
ringnames : list, optional. which rings to include in the model
if no ringnames provided then all rings are assumed.
Case-sensitive! Typically capitalized, e.g. "Alpha"
(for now - annoying to make case-insensitive)
if fluxes == 'default':
fluxes = list(self.ringtable['Optical Depth'])
Attributes
----------
planetname : str, name of planet
rings : dict of ringmodel.Ring objects, with ring names as keys
note ring names are case-sensitive! Typically capitalized, e.g. "Alpha"
ringtable : table of ephemeris data as well as time-invariant parameters for
Examples
--------
Need an example of how to add a custom ring
should be possible by just adding a ringmodel.Ring() object
into the dict self.ring
Need an example of how to modify ring data
should be possible by just changing the ringmodel.Ring() object
in the dict self.ring
'''
planet = planet.lower().capitalize()
self.planetname = planet
# query planetary ring node and static data
self.systemtable, self.bodytable, ringtable = RingNode.ephemeris(planet, epoch=epoch, location=location)
ring_static_data = table.Table.read(f'data/{planet}_ring_data.hdf5', format = 'hdf5')
planet_ephem = self.bodytable.loc[planet]
#self.ob_lat, self.ob_lon = planet_ephem['sub_obs_lat'], planet_ephem['sub_obs_lon']
# TO DO: change the way the static data tables are read in to be more package-y
# match the static and ephemeris data for rings using a table merge
ring_static_data.rename_column('Feature', 'ring')
ringtable = table.join(ringtable, ring_static_data, keys='ring', join_type='right')
ringtable.add_index('ring')
if ringnames is None:
ringnames = list(ringtable['ring'])
# make self.ringtable and fluxes contain only the rings in ringnames
self.ringtable = ringtable.loc[ringnames]
if fluxes == 'default':
fluxes = list(self.ringtable['Optical Depth'])
self.rings = {}
for i in range(len(ringnames)):
ringname = ringnames[i]
flux = fluxes[i]
try:
ringparams = ringtable.loc[ringname]
except Exception as e:
raise ValueError(f"Ring name {ringname} not found in the data table of known rings")
# make a Ring object for each one
# TO DO: MORE MATH HERE
omega = ringparams['ascending node'] # CHECK THIS
i = u.Quantity(ringparams['Inclination (deg)'], unit=u.deg) # CHECK THIS
w = ringparams['pericenter'] # CHECK THIS
# many of the less-well-observed rings have masked values
# for many of these quantities, particularly omega, i, w, or even e. these go to
# zero when made into floats, so it is ok
thisring = Ring(ringparams['Middle Boundary (km)'] * u.km,
ringparams['Eccentricity'],
omega,
i,
w,
width = ringparams['Width'],
flux = flux)
self.rings[ringname] = thisring
#print(ringtable.loc['Epsilon'])
# TO DO: does the line above actually work?
def as_2d_array(self, shape, pixscale, center=None, beamsize=None):
'''
return a 2-d array that looks like a mock observation
optional smearing over Gaussian beam
Parameters
----------
shape : tuple, required. output image shape in number of pixels
pixscale : float/int or astropy Quantity, required. pixel scale
of the output image. If float/int (i.e. no units specified), then
kilometers is assumed
beamsize : float/int or 3-element array-like, optional.
FWHM of Gaussian beam with which to convolve the observation
units of fwhm are number of pixels.
if array-like, has form (FWHM_X, FWHM_Y, POSITION_ANGLE)
units of position angle are assumed degrees unless astropy Angle is passed
if no beamsize is specified, will make infinite-resolution
Returns
-------
2-d numpy array
Examples
--------
'''
arr_out = np.zeros(shape)
for ringname in self.rings.keys():
arr_out += self.rings[ringname].as_2d_array(shape, pixscale, center=center, beamsize=None)
## project this onto the observer plane using ring opening angle and north pole angle
r = Rotation('xyz', [self.systemtable['sub_obs_lon'], 0, 90*u.deg - self.systemtable[opening_angle]], degrees=True)
rvec = r.as_rotvec()
# TO DO: finish this!
# run convolution with beam outside loop so it is only done once
if beamsize is None:
return arr_out
else:
# make the Gaussian beam. convert FWHM to sigma
beam = convolution.Gaussian2DKernel(beamsize[0] / 2.35482004503,
beamsize[1] / 2.35482004503,
Angle(beamsize[2], unit=u.deg))
return convolution.convolve(arr_out, beam)
if __name__ == "__main__":
uranus_rings = RingSystemModelObservation('uranus',
epoch='2022-05-03 11:50',
ringnames = ['Six', 'Five', 'Four', 'Alpha', 'Beta', 'Eta', 'Gamma', 'Delta', 'Epsilon'])
obs = uranus_rings.as_2d_array((500, 500), 300*u.km, beamsize = (7,4,30*u.degree))
import matplotlib.pyplot as plt
plt.imshow(obs, origin = 'lower')
plt.show() | en | 0.726063 | goal: pull together JPL Horizons query, ring node query, and static ring data from data/ to make model ring systems as observed from any location is there a better/more astropy-like library to import for keplerian ellipses than PyAstronomy? yes, but it is annoying to use much later: get an undergrad to make Keplerian ellipse module of Astropy model of a planetary ring Parameters ---------- a : semimajor axis e : eccentricity Omega : longitude of ascending node i : inclination w : argument of periapsis width : float or Quantity, optional. default 1 km (i.e., very thin) flux : float or Quantity, optional. default 1.0. Attributes ---------- a : semimajor axis e : eccentricity omega : longitude of ascending node i : inclination w : argument of periapsis width : flux : Examples -------- # to do: write tests that pass astropy Quantities with units other than km and deg String representation Examples -------- >>> from pylanetary.rings import Ring >>> epsilon_ring = Ring(whatever) >>> print(epsilon_ring) Ring instance; a=whatever, e=whatever, i=whatever, width=whatever return elliptical annulus surrounding the ring of the given width # test whether the angles coming in here are actually correct return n partial elliptical annulus wedges with equal orbital time spent in each useful for ring as f(azimuth) because should take out foreshortening correction but should check this! what did I do for the paper? also perfect data experiments would be good # do this later, it's complicated to do right make a PyAstronomy.KeplerEllipse object at the ring's orbit to get position of ring particles as a function of time Parameters ---------- T : orbital period tau : time of periapsis passage returns ------- PyAstronomy Keplerian Ellipse object examples -------- >>> epsilon_ring = Ring(a, e, omega, i, w) >>> orbit = epsilon_ring.as_orbit(T, tau=0) >>> print(orbit.pos) >>> print(orbit.radius) >>> print(orbit.vel) >>> print(orbit.peri) # decide: is it this code's job to calculate the orbital period # from semimajor axis based on planet mass? # would require planet masses in a data table # if so, can do later return a 2-d array that looks like a mock observation optional smearing over Gaussian beam Parameters ---------- shape : tuple, required. output image shape pixscale : float/int or astropy Quantity, required. pixel scale of the output image. If float/int (i.e. no units specified), then kilometers is assumed width : float/int or astropy Quantity. If float/int (i.e. no units specified), then kilometers is assumed flux : float/int or astropy Quantity. sets brightness of the array NEED TO DECIDE: what default units make sense here? - probably a surface brightness beamsize : float/int or 3-element array-like, optional. FWHM of Gaussian beam with which to convolve the observation units of fwhm are number of pixels. if array-like, has form (FWHM_X, FWHM_Y, POSITION_ANGLE) units of position angle are assumed degrees unless astropy Angle is passed if no beamsize is specified, will make infinite-resolution Returns ------- 2-d numpy array Examples -------- # to do: write a test that passes pixscale with units other than km # put the ring onto a 2-D array using EllipticalAnnulus # project to opening angle # make the Gaussian beam. convert FWHM to sigma make a model of a ring system Parameters ---------- planet: str, required. one of Jupiter, Saturn, Uranus, Neptune epoch : `~astropy.time.Time` object, or str in format YYYY-MM-DD hh:mm, optional. If str is provided then UTC is assumed. If no epoch is provided, the current time is used. location : array-like, or `~astropy.coordinates.EarthLocation`, optional Observer's location as a 3-element array of Earth longitude, latitude, altitude, or `~astropy.coordinates.EarthLocation`. Longitude and latitude should be anything that initializes an `~astropy.coordinates.Angle` object, and altitude should initialize an `~astropy.units.Quantity` object (with units of length). If ``None``, then the geocenter is used. ringnames : list, optional. which rings to include in the model if no ringnames provided then all rings are assumed. Case-sensitive! Typically capitalized, e.g. "Alpha" (for now - annoying to make case-insensitive) if fluxes == 'default': fluxes = list(self.ringtable['Optical Depth']) Attributes ---------- planetname : str, name of planet rings : dict of ringmodel.Ring objects, with ring names as keys note ring names are case-sensitive! Typically capitalized, e.g. "Alpha" ringtable : table of ephemeris data as well as time-invariant parameters for Examples -------- Need an example of how to add a custom ring should be possible by just adding a ringmodel.Ring() object into the dict self.ring Need an example of how to modify ring data should be possible by just changing the ringmodel.Ring() object in the dict self.ring # query planetary ring node and static data #self.ob_lat, self.ob_lon = planet_ephem['sub_obs_lat'], planet_ephem['sub_obs_lon'] # TO DO: change the way the static data tables are read in to be more package-y # match the static and ephemeris data for rings using a table merge # make self.ringtable and fluxes contain only the rings in ringnames # make a Ring object for each one # TO DO: MORE MATH HERE # CHECK THIS # CHECK THIS # CHECK THIS # many of the less-well-observed rings have masked values # for many of these quantities, particularly omega, i, w, or even e. these go to # zero when made into floats, so it is ok #print(ringtable.loc['Epsilon']) # TO DO: does the line above actually work? return a 2-d array that looks like a mock observation optional smearing over Gaussian beam Parameters ---------- shape : tuple, required. output image shape in number of pixels pixscale : float/int or astropy Quantity, required. pixel scale of the output image. If float/int (i.e. no units specified), then kilometers is assumed beamsize : float/int or 3-element array-like, optional. FWHM of Gaussian beam with which to convolve the observation units of fwhm are number of pixels. if array-like, has form (FWHM_X, FWHM_Y, POSITION_ANGLE) units of position angle are assumed degrees unless astropy Angle is passed if no beamsize is specified, will make infinite-resolution Returns ------- 2-d numpy array Examples -------- ## project this onto the observer plane using ring opening angle and north pole angle # TO DO: finish this! # run convolution with beam outside loop so it is only done once # make the Gaussian beam. convert FWHM to sigma | 2.791624 | 3 |
syzygy/scripts/benchmark/optimize.py | nzeh/syzygy | 343 | 6620287 | <gh_stars>100-1000
#!python
# Copyright 2012 Google 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.
"""A utility script to automate the process of instrumenting, profiling and
optimizing Chrome."""
import chrome_utils
import instrument
import logging
import optparse
import os
import os.path
import profile
import runner
import shutil
import sys
import tempfile
_LOGGER = logging.getLogger(__name__)
class OptimizationError(Exception):
"""Raised on any failures in the optimization process."""
pass
def _ProcessBBEntries(log_files, output_dir):
"""Summarize the basic-block entry counts in @p log_files to a JSON file in
@p output_dir.
The file path to the generated JSON file is returned.
"""
output_file = os.path.join(output_dir, 'bbentries.json')
cmd = [
runner._GetExePath('grinder.exe'), # pylint: disable=W0212
'--mode=bbentry',
'--output-file=%s' % output_file,
]
cmd.extend(log_files)
ret = chrome_utils.Subprocess(cmd)
if ret != 0:
raise OptimizationError('Failed to process basic-block entries.')
return output_file
def _InstrumentAndProfile(work_dir, mode, opts):
"""Generate an instrumented chrome directory for @p mode in @p workdir using
the given @p opts and profile it.
If the mode is 'bbentry' generate a summary JSON file.
Returns the list of trace or summary files.
"""
instrumented_dir = os.path.join(work_dir, mode, 'instrumented')
profile_data_dir = os.path.join(work_dir, mode, 'profile-data')
# Instrument the provided Chrome executables in input_dir, and store
# the profiled executables in instrumented_dir.
instrument.InstrumentChrome(opts.input_dir, instrumented_dir, mode, [])
# Then profile the instrumented executables in instrumented_dir.
trace_files = profile.ProfileChrome(instrumented_dir,
profile_data_dir,
opts.iterations,
opts.chrome_frame,
opts.startup_type,
opts.startup_urls)
# For bbentry mode we need to run the grinder to generate a summary file
# to return.
if mode == 'bbentry':
summary_file = _ProcessBBEntries(trace_files, work_dir)
return [summary_file]
# Otherwise we just return the raw set of trace files.
return trace_files
# Give us silent access to the internals of our runner.
# pylint: disable=W0212
def _OptimizeChromeBinary(chrome_dir, work_dir, output_dir, log_files,
bb_entry_file, basename, optional):
"""Optimizes a single Chrome binary with the given |basename|. The original
binary in |chrome_dir| will be optimized using the data in the provided
|log_files|, assuming that they have been generated with respect to the
instrumented binary in |work_dir|. If |bb_entry_file| is provided then basic
block optimizations will also be applied.
Args:
chrome_dir: The directory holding the original Chrome binaries.
work_dir: The work directory containing the instrumented files.
output_dir: The directory where the optimized binaries will be written.
log_files: The calltrace log files to be used in generating an order file.
bb_entry_file: The BB entry counts to be used in optimizing the binary.
basename: The basename of the binary to optimize.
optional: If False then the binary must be present and must optimized.
Otherwise, this will do nothing and silently return if the input
binary does not exist.
"""
# Calculate all the path parameters.
input_image = os.path.join(chrome_dir, basename)
if not os.path.isfile(input_image):
if not optional:
raise OptimizationError('Missing mandatory "%s".' % basename)
_LOGGER.info('Not instrumenting missing optional "%s".', basename)
return
instrumented_image = os.path.join(
work_dir, 'calltrace', 'instrumented', basename)
order_file = os.path.join(work_dir, basename + '-order.json')
output_image = os.path.join(output_dir, basename)
# Generate the ordering file for the binary.
_LOGGER.info('Generating ordering file for "%s".', basename)
cmd = [
runner._GetExePath('reorder.exe'),
'--verbose',
'--output-stats',
'--input-image=%s' % input_image,
'--instrumented-image=%s' % instrumented_image,
'--output-file=%s' % order_file,
]
if bb_entry_file:
cmd.append('--basic_block_entry_counts=%s' % bb_entry_file)
cmd.extend(log_files)
ret = chrome_utils.Subprocess(cmd)
if ret != 0:
raise OptimizationError(
'Failed to generate an ordering for "%s".' % basename)
# Populate output_dir with a copy of the original chrome installation.
_LOGGER.info('Copying "%s" to output dir "%s".', chrome_dir, output_dir)
if os.path.isfile(output_dir):
raise OptimizationError('File present at output dir location: "%s"',
output_dir)
chrome_utils.CopyChromeFiles(chrome_dir, output_dir)
# Replace the binary in output_dir with an optimized version.
_LOGGER.info('Optimizing "%s".', basename)
cmd = [runner._GetExePath('relink.exe'),
'--verbose',
'--input-image=%s' % input_image,
'--output-image=%s' % output_image,
'--order-file=%s' % order_file,
'--overwrite']
ret = chrome_utils.Subprocess(cmd)
if ret != 0:
raise OptimizationError('Failed to relink "%s".' % basename)
def _OptimizeChrome(chrome_dir, work_dir, output_dir, log_files, bb_entry_file):
"""Generate an optimized version of the Chrome binaries in |chrome_dir| based
on the calltrace instrumented version in |work_dir|, the calltrace
|log_files| and an optional JSON |bb_entry_file|. The optimized Chrome
binaries will be written to |output_dir|.
chrome_dir: The directory holding the original Chrome binaries.
work_dir: The work directory containing the instrumented files.
output_dir: The directory where the optimized binaries will be written.
log_files: The calltrace log files to be used in generating an order file.
bb_entry_file: The BB entry counts to be used in optimizing the binary.
"""
for basename in instrument.EXECUTABLES:
_OptimizeChromeBinary(chrome_dir, work_dir, output_dir, log_files,
bb_entry_file, basename, False)
for basename in instrument.EXECUTABLES_OPTIONAL:
_OptimizeChromeBinary(chrome_dir, work_dir, output_dir, log_files,
bb_entry_file, basename, True)
def _CopyBinaries(orig_dir, src_dir, tgt_dir):
"""Copies the optimized Chrome binaries and PDB files from |src_dir| to
|tgt_dir|. For optional binaries it is expected that the copy succeed if a
copy of the binary also exists in |orig_dir|.
Args:
orig_dir: The directory containing the original binaries.
src_dir: The source directory.
tgt_dir: The target directory.
"""
if not os.path.isdir(tgt_dir):
_LOGGER.info('_CopyBinaries target dir not found. Creating "%s".', tgt_dir)
os.makedirs(tgt_dir)
# Generate a list of files to copy.
files = []
for path in instrument.EXECUTABLES:
files.append(path)
files.append(path + '.pdb')
for path in instrument.EXECUTABLES_OPTIONAL:
orig_file = os.path.join(orig_dir, path)
if os.path.isfile(orig_file):
files.append(path)
files.append(path + '.pdb')
# Copy over the files.
for path in files:
src_file = os.path.join(src_dir, path)
tgt_file = os.path.join(tgt_dir, path)
_LOGGER.info('Placing optimized "%s" in "%s".', path, tgt_dir)
shutil.copy2(src_file, tgt_file)
_USAGE = """%prog [options]
Instruments, then profiles the Chrome executables supplied in an input directory
for a number of iterations, then optimizes the executable order with respect to
the profile runs.
"""
def _ParseArguments():
"""Parse the sys.argv command-line arguments, returning the options."""
parser = optparse.OptionParser(usage=_USAGE)
parser.add_option('--verbose', dest='verbose',
default=False, action='store_true',
help='Verbose logging.')
parser.add_option('--iterations', dest='iterations', type='int',
default=10,
help='Number of profile iterations, 10 by default.')
parser.add_option('--chrome-frame', dest='chrome_frame',
default=False, action='store_true',
help=('Optimize for both Chrome Frame and Chrome usage '
'patterns. Without this flag, optimize only for '
'Chrome usage patterns.'))
parser.add_option('--input-dir', dest='input_dir',
help=('The input directory where the original Chrome '
'executables are to be found.'))
parser.add_option('--output-dir', dest='output_dir',
help=('The directory where the optimized chrome '
'installation will be created. From this location, '
'one can subsequently run benchmarks.'))
parser.add_option('--copy-to', dest='copy_to',
help=('(Optional) The output directory where the final '
'optimized PE and PDB files will be copied.'))
parser.add_option('--keep-temp-dirs', dest='keep_temp_dirs',
action='store_true',
help='Keep temp directories instead of deleting them.')
parser.add_option('--mode',
choices=instrument.MODES,
default=instrument.DEFAULT_MODE,
help='The instrumentation mode. Allowed values are: '
'%s (default: %%default).' % (
', '.join(instrument.MODES)))
parser.add_option('--startup-type', dest='startup_type', metavar='TYPE',
choices=runner.ALL_STARTUP_TYPES,
default=runner.DEFAULT_STARTUP_TYPE,
help='The type of Chrome session to open on startup. The '
'allowed values are: %s (default: %%default).' % (
', '.join(runner.ALL_STARTUP_TYPES)))
parser.add_option('--startup-url', dest='startup_urls', metavar='URL',
default=[], action='append',
help='Add URL to the startup scenario used for profiling. '
'This option may be given multiple times; each URL '
'will be added to the startup scenario.')
(opts, args) = parser.parse_args()
if len(args):
parser.error('Unexpected argument(s).')
# Minimally configure logging.
if opts.verbose:
logging.basicConfig(level=logging.INFO)
else:
logging.basicConfig(level=logging.WARNING)
if not opts.input_dir or not opts.output_dir:
parser.error('You must provide input and output directories')
opts.input_dir = os.path.abspath(opts.input_dir)
opts.output_dir = os.path.abspath(opts.output_dir)
if opts.copy_to:
opts.copy_to = os.path.abspath(opts.copy_to)
return opts
def main():
"""Parses arguments and runs the optimization."""
opts = _ParseArguments()
work_dir = tempfile.mkdtemp(prefix='chrome-instr')
_LOGGER.info('Created working directory "%s".', work_dir)
try:
# We always instrument in calltrace mode to be able to generate a coarse
# function layout for the binary.
trace_files = _InstrumentAndProfile(work_dir, 'calltrace', opts)
# If we're in bbentry mode then we further instrument and profile to get
# summary stats for basic-block entry counts.
if opts.mode == 'bbentry':
bb_entry_file = _InstrumentAndProfile(work_dir, 'bbentry', opts)[0]
else:
bb_entry_file = None
# Lastly generate an ordering, and reorder the inputs to
# the output dir.
_OptimizeChrome(
opts.input_dir, work_dir, opts.output_dir, trace_files, bb_entry_file)
if opts.copy_to:
_CopyBinaries(opts.input_dir, opts.output_dir, opts.copy_to)
except OptimizationError:
_LOGGER.exception('Optimization failed.')
return 1
finally:
if opts.keep_temp_dirs:
_LOGGER.info('Keeping temporary directory "%s".', work_dir)
else:
_LOGGER.info('Deleting temporary directory "%s".', work_dir)
chrome_utils.RmTree(work_dir)
return 0
if __name__ == '__main__':
sys.exit(main())
| #!python
# Copyright 2012 Google 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.
"""A utility script to automate the process of instrumenting, profiling and
optimizing Chrome."""
import chrome_utils
import instrument
import logging
import optparse
import os
import os.path
import profile
import runner
import shutil
import sys
import tempfile
_LOGGER = logging.getLogger(__name__)
class OptimizationError(Exception):
"""Raised on any failures in the optimization process."""
pass
def _ProcessBBEntries(log_files, output_dir):
"""Summarize the basic-block entry counts in @p log_files to a JSON file in
@p output_dir.
The file path to the generated JSON file is returned.
"""
output_file = os.path.join(output_dir, 'bbentries.json')
cmd = [
runner._GetExePath('grinder.exe'), # pylint: disable=W0212
'--mode=bbentry',
'--output-file=%s' % output_file,
]
cmd.extend(log_files)
ret = chrome_utils.Subprocess(cmd)
if ret != 0:
raise OptimizationError('Failed to process basic-block entries.')
return output_file
def _InstrumentAndProfile(work_dir, mode, opts):
"""Generate an instrumented chrome directory for @p mode in @p workdir using
the given @p opts and profile it.
If the mode is 'bbentry' generate a summary JSON file.
Returns the list of trace or summary files.
"""
instrumented_dir = os.path.join(work_dir, mode, 'instrumented')
profile_data_dir = os.path.join(work_dir, mode, 'profile-data')
# Instrument the provided Chrome executables in input_dir, and store
# the profiled executables in instrumented_dir.
instrument.InstrumentChrome(opts.input_dir, instrumented_dir, mode, [])
# Then profile the instrumented executables in instrumented_dir.
trace_files = profile.ProfileChrome(instrumented_dir,
profile_data_dir,
opts.iterations,
opts.chrome_frame,
opts.startup_type,
opts.startup_urls)
# For bbentry mode we need to run the grinder to generate a summary file
# to return.
if mode == 'bbentry':
summary_file = _ProcessBBEntries(trace_files, work_dir)
return [summary_file]
# Otherwise we just return the raw set of trace files.
return trace_files
# Give us silent access to the internals of our runner.
# pylint: disable=W0212
def _OptimizeChromeBinary(chrome_dir, work_dir, output_dir, log_files,
bb_entry_file, basename, optional):
"""Optimizes a single Chrome binary with the given |basename|. The original
binary in |chrome_dir| will be optimized using the data in the provided
|log_files|, assuming that they have been generated with respect to the
instrumented binary in |work_dir|. If |bb_entry_file| is provided then basic
block optimizations will also be applied.
Args:
chrome_dir: The directory holding the original Chrome binaries.
work_dir: The work directory containing the instrumented files.
output_dir: The directory where the optimized binaries will be written.
log_files: The calltrace log files to be used in generating an order file.
bb_entry_file: The BB entry counts to be used in optimizing the binary.
basename: The basename of the binary to optimize.
optional: If False then the binary must be present and must optimized.
Otherwise, this will do nothing and silently return if the input
binary does not exist.
"""
# Calculate all the path parameters.
input_image = os.path.join(chrome_dir, basename)
if not os.path.isfile(input_image):
if not optional:
raise OptimizationError('Missing mandatory "%s".' % basename)
_LOGGER.info('Not instrumenting missing optional "%s".', basename)
return
instrumented_image = os.path.join(
work_dir, 'calltrace', 'instrumented', basename)
order_file = os.path.join(work_dir, basename + '-order.json')
output_image = os.path.join(output_dir, basename)
# Generate the ordering file for the binary.
_LOGGER.info('Generating ordering file for "%s".', basename)
cmd = [
runner._GetExePath('reorder.exe'),
'--verbose',
'--output-stats',
'--input-image=%s' % input_image,
'--instrumented-image=%s' % instrumented_image,
'--output-file=%s' % order_file,
]
if bb_entry_file:
cmd.append('--basic_block_entry_counts=%s' % bb_entry_file)
cmd.extend(log_files)
ret = chrome_utils.Subprocess(cmd)
if ret != 0:
raise OptimizationError(
'Failed to generate an ordering for "%s".' % basename)
# Populate output_dir with a copy of the original chrome installation.
_LOGGER.info('Copying "%s" to output dir "%s".', chrome_dir, output_dir)
if os.path.isfile(output_dir):
raise OptimizationError('File present at output dir location: "%s"',
output_dir)
chrome_utils.CopyChromeFiles(chrome_dir, output_dir)
# Replace the binary in output_dir with an optimized version.
_LOGGER.info('Optimizing "%s".', basename)
cmd = [runner._GetExePath('relink.exe'),
'--verbose',
'--input-image=%s' % input_image,
'--output-image=%s' % output_image,
'--order-file=%s' % order_file,
'--overwrite']
ret = chrome_utils.Subprocess(cmd)
if ret != 0:
raise OptimizationError('Failed to relink "%s".' % basename)
def _OptimizeChrome(chrome_dir, work_dir, output_dir, log_files, bb_entry_file):
"""Generate an optimized version of the Chrome binaries in |chrome_dir| based
on the calltrace instrumented version in |work_dir|, the calltrace
|log_files| and an optional JSON |bb_entry_file|. The optimized Chrome
binaries will be written to |output_dir|.
chrome_dir: The directory holding the original Chrome binaries.
work_dir: The work directory containing the instrumented files.
output_dir: The directory where the optimized binaries will be written.
log_files: The calltrace log files to be used in generating an order file.
bb_entry_file: The BB entry counts to be used in optimizing the binary.
"""
for basename in instrument.EXECUTABLES:
_OptimizeChromeBinary(chrome_dir, work_dir, output_dir, log_files,
bb_entry_file, basename, False)
for basename in instrument.EXECUTABLES_OPTIONAL:
_OptimizeChromeBinary(chrome_dir, work_dir, output_dir, log_files,
bb_entry_file, basename, True)
def _CopyBinaries(orig_dir, src_dir, tgt_dir):
"""Copies the optimized Chrome binaries and PDB files from |src_dir| to
|tgt_dir|. For optional binaries it is expected that the copy succeed if a
copy of the binary also exists in |orig_dir|.
Args:
orig_dir: The directory containing the original binaries.
src_dir: The source directory.
tgt_dir: The target directory.
"""
if not os.path.isdir(tgt_dir):
_LOGGER.info('_CopyBinaries target dir not found. Creating "%s".', tgt_dir)
os.makedirs(tgt_dir)
# Generate a list of files to copy.
files = []
for path in instrument.EXECUTABLES:
files.append(path)
files.append(path + '.pdb')
for path in instrument.EXECUTABLES_OPTIONAL:
orig_file = os.path.join(orig_dir, path)
if os.path.isfile(orig_file):
files.append(path)
files.append(path + '.pdb')
# Copy over the files.
for path in files:
src_file = os.path.join(src_dir, path)
tgt_file = os.path.join(tgt_dir, path)
_LOGGER.info('Placing optimized "%s" in "%s".', path, tgt_dir)
shutil.copy2(src_file, tgt_file)
_USAGE = """%prog [options]
Instruments, then profiles the Chrome executables supplied in an input directory
for a number of iterations, then optimizes the executable order with respect to
the profile runs.
"""
def _ParseArguments():
"""Parse the sys.argv command-line arguments, returning the options."""
parser = optparse.OptionParser(usage=_USAGE)
parser.add_option('--verbose', dest='verbose',
default=False, action='store_true',
help='Verbose logging.')
parser.add_option('--iterations', dest='iterations', type='int',
default=10,
help='Number of profile iterations, 10 by default.')
parser.add_option('--chrome-frame', dest='chrome_frame',
default=False, action='store_true',
help=('Optimize for both Chrome Frame and Chrome usage '
'patterns. Without this flag, optimize only for '
'Chrome usage patterns.'))
parser.add_option('--input-dir', dest='input_dir',
help=('The input directory where the original Chrome '
'executables are to be found.'))
parser.add_option('--output-dir', dest='output_dir',
help=('The directory where the optimized chrome '
'installation will be created. From this location, '
'one can subsequently run benchmarks.'))
parser.add_option('--copy-to', dest='copy_to',
help=('(Optional) The output directory where the final '
'optimized PE and PDB files will be copied.'))
parser.add_option('--keep-temp-dirs', dest='keep_temp_dirs',
action='store_true',
help='Keep temp directories instead of deleting them.')
parser.add_option('--mode',
choices=instrument.MODES,
default=instrument.DEFAULT_MODE,
help='The instrumentation mode. Allowed values are: '
'%s (default: %%default).' % (
', '.join(instrument.MODES)))
parser.add_option('--startup-type', dest='startup_type', metavar='TYPE',
choices=runner.ALL_STARTUP_TYPES,
default=runner.DEFAULT_STARTUP_TYPE,
help='The type of Chrome session to open on startup. The '
'allowed values are: %s (default: %%default).' % (
', '.join(runner.ALL_STARTUP_TYPES)))
parser.add_option('--startup-url', dest='startup_urls', metavar='URL',
default=[], action='append',
help='Add URL to the startup scenario used for profiling. '
'This option may be given multiple times; each URL '
'will be added to the startup scenario.')
(opts, args) = parser.parse_args()
if len(args):
parser.error('Unexpected argument(s).')
# Minimally configure logging.
if opts.verbose:
logging.basicConfig(level=logging.INFO)
else:
logging.basicConfig(level=logging.WARNING)
if not opts.input_dir or not opts.output_dir:
parser.error('You must provide input and output directories')
opts.input_dir = os.path.abspath(opts.input_dir)
opts.output_dir = os.path.abspath(opts.output_dir)
if opts.copy_to:
opts.copy_to = os.path.abspath(opts.copy_to)
return opts
def main():
"""Parses arguments and runs the optimization."""
opts = _ParseArguments()
work_dir = tempfile.mkdtemp(prefix='chrome-instr')
_LOGGER.info('Created working directory "%s".', work_dir)
try:
# We always instrument in calltrace mode to be able to generate a coarse
# function layout for the binary.
trace_files = _InstrumentAndProfile(work_dir, 'calltrace', opts)
# If we're in bbentry mode then we further instrument and profile to get
# summary stats for basic-block entry counts.
if opts.mode == 'bbentry':
bb_entry_file = _InstrumentAndProfile(work_dir, 'bbentry', opts)[0]
else:
bb_entry_file = None
# Lastly generate an ordering, and reorder the inputs to
# the output dir.
_OptimizeChrome(
opts.input_dir, work_dir, opts.output_dir, trace_files, bb_entry_file)
if opts.copy_to:
_CopyBinaries(opts.input_dir, opts.output_dir, opts.copy_to)
except OptimizationError:
_LOGGER.exception('Optimization failed.')
return 1
finally:
if opts.keep_temp_dirs:
_LOGGER.info('Keeping temporary directory "%s".', work_dir)
else:
_LOGGER.info('Deleting temporary directory "%s".', work_dir)
chrome_utils.RmTree(work_dir)
return 0
if __name__ == '__main__':
sys.exit(main()) | en | 0.74721 | #!python # Copyright 2012 Google 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. A utility script to automate the process of instrumenting, profiling and optimizing Chrome. Raised on any failures in the optimization process. Summarize the basic-block entry counts in @p log_files to a JSON file in @p output_dir. The file path to the generated JSON file is returned. # pylint: disable=W0212 Generate an instrumented chrome directory for @p mode in @p workdir using the given @p opts and profile it. If the mode is 'bbentry' generate a summary JSON file. Returns the list of trace or summary files. # Instrument the provided Chrome executables in input_dir, and store # the profiled executables in instrumented_dir. # Then profile the instrumented executables in instrumented_dir. # For bbentry mode we need to run the grinder to generate a summary file # to return. # Otherwise we just return the raw set of trace files. # Give us silent access to the internals of our runner. # pylint: disable=W0212 Optimizes a single Chrome binary with the given |basename|. The original binary in |chrome_dir| will be optimized using the data in the provided |log_files|, assuming that they have been generated with respect to the instrumented binary in |work_dir|. If |bb_entry_file| is provided then basic block optimizations will also be applied. Args: chrome_dir: The directory holding the original Chrome binaries. work_dir: The work directory containing the instrumented files. output_dir: The directory where the optimized binaries will be written. log_files: The calltrace log files to be used in generating an order file. bb_entry_file: The BB entry counts to be used in optimizing the binary. basename: The basename of the binary to optimize. optional: If False then the binary must be present and must optimized. Otherwise, this will do nothing and silently return if the input binary does not exist. # Calculate all the path parameters. # Generate the ordering file for the binary. # Populate output_dir with a copy of the original chrome installation. # Replace the binary in output_dir with an optimized version. Generate an optimized version of the Chrome binaries in |chrome_dir| based on the calltrace instrumented version in |work_dir|, the calltrace |log_files| and an optional JSON |bb_entry_file|. The optimized Chrome binaries will be written to |output_dir|. chrome_dir: The directory holding the original Chrome binaries. work_dir: The work directory containing the instrumented files. output_dir: The directory where the optimized binaries will be written. log_files: The calltrace log files to be used in generating an order file. bb_entry_file: The BB entry counts to be used in optimizing the binary. Copies the optimized Chrome binaries and PDB files from |src_dir| to |tgt_dir|. For optional binaries it is expected that the copy succeed if a copy of the binary also exists in |orig_dir|. Args: orig_dir: The directory containing the original binaries. src_dir: The source directory. tgt_dir: The target directory. # Generate a list of files to copy. # Copy over the files. %prog [options] Instruments, then profiles the Chrome executables supplied in an input directory for a number of iterations, then optimizes the executable order with respect to the profile runs. Parse the sys.argv command-line arguments, returning the options. # Minimally configure logging. Parses arguments and runs the optimization. # We always instrument in calltrace mode to be able to generate a coarse # function layout for the binary. # If we're in bbentry mode then we further instrument and profile to get # summary stats for basic-block entry counts. # Lastly generate an ordering, and reorder the inputs to # the output dir. | 2.317731 | 2 |
tobias/utils/filter_important_factors.py | petrokvitka/TOBIAS | 0 | 6620288 | #!/usr/bin/env python3
import pandas as pd
from pandas import ExcelWriter
from pandas import ExcelFile
from argparse import ArgumentParser
import heapq
#--------------------------------------------------------------------------------------------------------------#
def get_important(args):
file = args.file_in #input file bindetect_result.txt
filter = args.filter #filter how many binding factors of every condition will be selected
file_out = args.file_out #name of output output file
list_file = [] #contains all lines of file
new_file = [] #list for the filtered file
with open(file) as f: #open bindetect results
for i in f:
i = i.strip()
i = i.split('\t') #read file tab sapareted
list_file.append(i)
index_list = [list_file[0].index(i) for i in list_file[0] if '_change' in i]#get the indexs of the columens
important_values = [[max(heapq.nsmallest(filter,[float(a[i]) for a in list_file[1:]])), min(heapq.nlargest(filter,[float(a[i]) for a in list_file[1:]]))] for i in index_list]
#important_values contains the maximum and minimum value of the bindingfactor
for i in list_file[1:]:
for a,b in zip(index_list, important_values):
if float(i[a]) >= float(max(b)) or float(i[a]) <= float(min(b)): #filters if binding value is important
new_file.append(i) #important lines get append to new list
print(i[0]) #print stdout for nextflowpipeline
break #if line is added for loop jumps to next line
#build new tab seperater text file
book = {i:[] for i in list_file[0]}
[[book[key].append(value) for key,value in zip(list_file[0], i)] for i in new_file] #dict for exele wirter key first line value hole line
df = pd.DataFrame(book)
df.to_csv(file_out , '\t', index=False)
#--------------------------------------------------------------------------------------------------------#
def main():
parser = ArgumentParser()
parser.add_argument("-in", dest="file_in", type=str, help="Input file")
parser.add_argument("-filter", dest="filter", type=int, help="Filter")
parser.add_argument("-o", dest="file_out", type=str, help="Output file")
args = parser.parse_args()
get_important(args)
#--------------------------------------------------------------------------------------------------------#
if __name__ == '__main__':
main()
| #!/usr/bin/env python3
import pandas as pd
from pandas import ExcelWriter
from pandas import ExcelFile
from argparse import ArgumentParser
import heapq
#--------------------------------------------------------------------------------------------------------------#
def get_important(args):
file = args.file_in #input file bindetect_result.txt
filter = args.filter #filter how many binding factors of every condition will be selected
file_out = args.file_out #name of output output file
list_file = [] #contains all lines of file
new_file = [] #list for the filtered file
with open(file) as f: #open bindetect results
for i in f:
i = i.strip()
i = i.split('\t') #read file tab sapareted
list_file.append(i)
index_list = [list_file[0].index(i) for i in list_file[0] if '_change' in i]#get the indexs of the columens
important_values = [[max(heapq.nsmallest(filter,[float(a[i]) for a in list_file[1:]])), min(heapq.nlargest(filter,[float(a[i]) for a in list_file[1:]]))] for i in index_list]
#important_values contains the maximum and minimum value of the bindingfactor
for i in list_file[1:]:
for a,b in zip(index_list, important_values):
if float(i[a]) >= float(max(b)) or float(i[a]) <= float(min(b)): #filters if binding value is important
new_file.append(i) #important lines get append to new list
print(i[0]) #print stdout for nextflowpipeline
break #if line is added for loop jumps to next line
#build new tab seperater text file
book = {i:[] for i in list_file[0]}
[[book[key].append(value) for key,value in zip(list_file[0], i)] for i in new_file] #dict for exele wirter key first line value hole line
df = pd.DataFrame(book)
df.to_csv(file_out , '\t', index=False)
#--------------------------------------------------------------------------------------------------------#
def main():
parser = ArgumentParser()
parser.add_argument("-in", dest="file_in", type=str, help="Input file")
parser.add_argument("-filter", dest="filter", type=int, help="Filter")
parser.add_argument("-o", dest="file_out", type=str, help="Output file")
args = parser.parse_args()
get_important(args)
#--------------------------------------------------------------------------------------------------------#
if __name__ == '__main__':
main()
| en | 0.478335 | #!/usr/bin/env python3 #--------------------------------------------------------------------------------------------------------------# #input file bindetect_result.txt #filter how many binding factors of every condition will be selected #name of output output file #contains all lines of file #list for the filtered file #open bindetect results #read file tab sapareted #get the indexs of the columens #important_values contains the maximum and minimum value of the bindingfactor #filters if binding value is important #important lines get append to new list #print stdout for nextflowpipeline #if line is added for loop jumps to next line #build new tab seperater text file #dict for exele wirter key first line value hole line #--------------------------------------------------------------------------------------------------------# #--------------------------------------------------------------------------------------------------------# | 3.181688 | 3 |
riccardo-negri/02/x.py | Tommimon/advent-of-code-2020 | 3 | 6620289 | <filename>riccardo-negri/02/x.py
#!/usr/bin/env python
# Day 2 solution of Advent Of Code 2020 by <NAME>
# Part one solution:638
# Part two solution:699
count_1 = 0
count_2 = 0
with open('input.txt', 'r') as f:
for line in f.readlines():
line = line.replace('-', ' ' )
line = line.split(' ')
if line[3].count(line[2][0]) >= int(line[0]) and line[3].count(line[2][0]) <= int(line[1]):
count_1 += 1 # part one
if (line[3][int(line[0])-1] == line[2][0]) ^ (line[3][int(line[1])-1] == line[2][0]):
count_2 += 1 # part two
print('Part one solution:' + str(count_1))
print('Part two solution:' + str(count_2)) | <filename>riccardo-negri/02/x.py
#!/usr/bin/env python
# Day 2 solution of Advent Of Code 2020 by <NAME>
# Part one solution:638
# Part two solution:699
count_1 = 0
count_2 = 0
with open('input.txt', 'r') as f:
for line in f.readlines():
line = line.replace('-', ' ' )
line = line.split(' ')
if line[3].count(line[2][0]) >= int(line[0]) and line[3].count(line[2][0]) <= int(line[1]):
count_1 += 1 # part one
if (line[3][int(line[0])-1] == line[2][0]) ^ (line[3][int(line[1])-1] == line[2][0]):
count_2 += 1 # part two
print('Part one solution:' + str(count_1))
print('Part two solution:' + str(count_2)) | en | 0.645449 | #!/usr/bin/env python # Day 2 solution of Advent Of Code 2020 by <NAME> # Part one solution:638 # Part two solution:699 # part one # part two | 3.378671 | 3 |
pytest_asgi_server/clients.py | garytyler/pytest-asgi-server | 2 | 6620290 | # from __future__ import annotations
import httpx
import websockets
from .servers import PytestUvicornXServer
class PytestAsgiXClient(httpx.AsyncClient):
def __init__(self, xserver: PytestUvicornXServer):
self.xserver = xserver
self.__instantiated = False
def __call__(self, *args, **kwargs) -> "PytestAsgiXClient":
self.xserver.start()
base_url = self.xserver.http_base_url
super().__init__(base_url=base_url, *args, **kwargs)
self.__instantiated = True
return self
async def __aenter__(self) -> "PytestAsgiXClient":
if not self.__instantiated:
self.__call__()
await super().__aenter__()
return self
async def __aexit__(self, *args) -> None:
await super().__aexit__()
self.xserver.stop()
def __exit__(self, *args):
self.xserver.stop()
def websocket_connect(self, uri: str, *args, **kwargs):
if not self.xserver.ws_base_url:
raise RuntimeError(
f"{self.__class__.__name__} must be instantiated or "
"wrapped in an asynchronous context manager before"
"calling 'connect_websocket"
)
address = self.xserver.ws_base_url + uri
return websockets.connect(address)
| # from __future__ import annotations
import httpx
import websockets
from .servers import PytestUvicornXServer
class PytestAsgiXClient(httpx.AsyncClient):
def __init__(self, xserver: PytestUvicornXServer):
self.xserver = xserver
self.__instantiated = False
def __call__(self, *args, **kwargs) -> "PytestAsgiXClient":
self.xserver.start()
base_url = self.xserver.http_base_url
super().__init__(base_url=base_url, *args, **kwargs)
self.__instantiated = True
return self
async def __aenter__(self) -> "PytestAsgiXClient":
if not self.__instantiated:
self.__call__()
await super().__aenter__()
return self
async def __aexit__(self, *args) -> None:
await super().__aexit__()
self.xserver.stop()
def __exit__(self, *args):
self.xserver.stop()
def websocket_connect(self, uri: str, *args, **kwargs):
if not self.xserver.ws_base_url:
raise RuntimeError(
f"{self.__class__.__name__} must be instantiated or "
"wrapped in an asynchronous context manager before"
"calling 'connect_websocket"
)
address = self.xserver.ws_base_url + uri
return websockets.connect(address)
| en | 0.53732 | # from __future__ import annotations | 2.346051 | 2 |
bilderfee/django_compat/context_processors.py | bilderfee/bilderfee-py | 0 | 6620291 | from bilderfee.bilderfee import Gravity
from bilderfee.bilderfee import Ext
def bilderfee_ctx(request):
return {
'BF_GRAVITY_SMART': Gravity.SMART,
'BF_GRAVITY_NORTH': Gravity.NORTH,
'BF_GRAVITY_SOUTH': Gravity.SOUTH,
'BF_GRAVITY_EAST': Gravity.EAST,
'BF_GRAVITY_WEST': Gravity.WEST,
'BF_GRAVITY_CENTER': Gravity.CENTER,
# File Extension
'BF_EXT_JPEG': Ext.JPEG,
'BF_EXT_PNG': Ext.PNG,
'BF_EXT_GIF': Ext.GIF,
'BF_EXT_WEBP': Ext.WEBP,
'BF_EXT_ICO': Ext.ICO,
}
| from bilderfee.bilderfee import Gravity
from bilderfee.bilderfee import Ext
def bilderfee_ctx(request):
return {
'BF_GRAVITY_SMART': Gravity.SMART,
'BF_GRAVITY_NORTH': Gravity.NORTH,
'BF_GRAVITY_SOUTH': Gravity.SOUTH,
'BF_GRAVITY_EAST': Gravity.EAST,
'BF_GRAVITY_WEST': Gravity.WEST,
'BF_GRAVITY_CENTER': Gravity.CENTER,
# File Extension
'BF_EXT_JPEG': Ext.JPEG,
'BF_EXT_PNG': Ext.PNG,
'BF_EXT_GIF': Ext.GIF,
'BF_EXT_WEBP': Ext.WEBP,
'BF_EXT_ICO': Ext.ICO,
}
| en | 0.3488 | # File Extension | 1.90036 | 2 |
intlScrape_script.py | arnavs-0/dystic-api | 3 | 6620292 | <reponame>arnavs-0/dystic-api
import json
from datetime import datetime
import requests
from bs4 import BeautifulSoup
template = 'https://{}.indeed.com/jobs?q={}&l={}'
def get_url(country, position, location):
template = 'https://{}.indeed.com/jobs?q={}&l={}'
url = template.format(country, position, location)
return url
# noinspection DuplicatedCode
def get_record(country, card):
atag = card.h2.a
job_title = atag.get('title')
job_url = 'https://' + country + '.indeed.com' + atag.get('href')
company = card.find('span', 'company').text.strip()
location = card.find('div', 'recJobLoc').get('data-rc-loc')
try:
remote = card.find('span', 'remote').text.strip()
except AttributeError:
remote = 'Not Remote'
summary = card.find('div', 'summary').text.strip()
date_post = card.find('span', 'date').text.strip()
date_today = datetime.today().strftime('%Y-%m-%d')
try:
salary = card.find('span', 'salaryText').text.strip()
except AttributeError:
salary = ''
record = (job_title, job_url, company, location, remote, summary, date_post, date_today, salary)
return record
def intlScrape(country, position, location):
records = []
url = get_url(country, position, location)
while True:
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
cards = soup.find_all('div', 'jobsearch-SerpJobCard')
for card in cards:
record = get_record(country, card)
records.append(record)
try:
url = 'https://' + country + '.indeed.com' + soup.find('a', {'aria-label': 'Next'}).get('href')
except AttributeError:
break
if records:
return json.dumps(
[{"statusCode": 200, "JobTitle": x[0], "JobUrl": x[1], "Company": x[2], "Location": x[3], "Remote": x[4],
"Summary": x[5], "PostDate": x[6], "ExtractDate": x[7], "Salary": x[8]} for x in records],
indent=1)
else:
return json.dumps({"success": False, "statusCode": 400, "reason": "No job was found with given request"})
| import json
from datetime import datetime
import requests
from bs4 import BeautifulSoup
template = 'https://{}.indeed.com/jobs?q={}&l={}'
def get_url(country, position, location):
template = 'https://{}.indeed.com/jobs?q={}&l={}'
url = template.format(country, position, location)
return url
# noinspection DuplicatedCode
def get_record(country, card):
atag = card.h2.a
job_title = atag.get('title')
job_url = 'https://' + country + '.indeed.com' + atag.get('href')
company = card.find('span', 'company').text.strip()
location = card.find('div', 'recJobLoc').get('data-rc-loc')
try:
remote = card.find('span', 'remote').text.strip()
except AttributeError:
remote = 'Not Remote'
summary = card.find('div', 'summary').text.strip()
date_post = card.find('span', 'date').text.strip()
date_today = datetime.today().strftime('%Y-%m-%d')
try:
salary = card.find('span', 'salaryText').text.strip()
except AttributeError:
salary = ''
record = (job_title, job_url, company, location, remote, summary, date_post, date_today, salary)
return record
def intlScrape(country, position, location):
records = []
url = get_url(country, position, location)
while True:
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
cards = soup.find_all('div', 'jobsearch-SerpJobCard')
for card in cards:
record = get_record(country, card)
records.append(record)
try:
url = 'https://' + country + '.indeed.com' + soup.find('a', {'aria-label': 'Next'}).get('href')
except AttributeError:
break
if records:
return json.dumps(
[{"statusCode": 200, "JobTitle": x[0], "JobUrl": x[1], "Company": x[2], "Location": x[3], "Remote": x[4],
"Summary": x[5], "PostDate": x[6], "ExtractDate": x[7], "Salary": x[8]} for x in records],
indent=1)
else:
return json.dumps({"success": False, "statusCode": 400, "reason": "No job was found with given request"}) | en | 0.3074 | # noinspection DuplicatedCode | 2.903852 | 3 |
ContactList/utils/tests/test_routing.py | SimonOkello/ContactList-API | 1 | 6620293 | from django.test import TestCase
from ContactList.utils.rounting import APP_INITIAL, get_app_urls
class TestRouting(TestCase):
def test_get_correct_app_urls(self):
self.assertEqual(get_app_urls('authentication'),
f"{APP_INITIAL}.{'authentication'}.urls")
| from django.test import TestCase
from ContactList.utils.rounting import APP_INITIAL, get_app_urls
class TestRouting(TestCase):
def test_get_correct_app_urls(self):
self.assertEqual(get_app_urls('authentication'),
f"{APP_INITIAL}.{'authentication'}.urls")
| none | 1 | 2.158663 | 2 | |
dyconnmap/fc/esc.py | wmvanvliet/dyconnmap | 42 | 6620294 | # -*- coding: utf-8 -*-
""" Envelope-to-Signal Correlation
Proposed by Bruns and Eckhorn [Bruns2004_], Envelope-to-Signal Correlation (*ESC*)
is similar to Amplitude Envelope Correlation (:mod:`dyconnmap.fc.aec`), but the
the amplitude of the lower frequency oscillation is signed; and thus the phase
information is preserved.
.. math::
r_{ESC} = \\text{corr}(\\chi_{lo}, \\alpha_{hi})
Where :math:`\\chi` is the input signal filtered to the frequency band :math:`lo`
and :math:`\\alpha` denotes the Instantaneous Amplitude of the same input signal
at the frequency band :math:`hi`.
|
-----
.. [Bruns2004] <NAME>., & <NAME>. (2004). Task-related coupling from high-to low-frequency signals among visual cortical areas in human subdural recordings. International Journal of Psychophysiology, 51(2), 97-116.
.. [Penny2008] <NAME>., <NAME>., <NAME>., & <NAME>. (2008). Testing for nested oscillation. Journal of neuroscience methods, 174(1), 50-61. Chicago
"""
# Author: <NAME> <<EMAIL>>
from ..analytic_signal import analytic_signal
import numpy as np
def esc(data, fb_lo, fb_hi, fs):
""" Envelope-Signal-Correlation
Estimate the Envelope-Signal-Correlation the given :attr:`data`.
Parameters
----------
data : array-like, shape(n_channels, n_samples)
Multichannel recording data.
fb_lo : list of length 2
The low and high frequencies of the lower band.
fb_hi : list of length 2
The low and high frequencies of the upper band.
fs : float
Sampling frequency.
pairs : array-like or `None`
- If an `array-like` is given, notice that each element is a tuple of length two.
- If `None` is passed, complete connectivity will be assumed.
Returns
-------
r : array-like, shape(n_channels, n_channels)
Estimated Pearson correlation coefficient.
"""
_, _, f = analytic_signal(data, fb_lo, fs)
h, _, _ = analytic_signal(data, fb_hi, fs)
escv = np.corrcoef(f, np.abs(h))
escv = np.float32(escv)
return escv
| # -*- coding: utf-8 -*-
""" Envelope-to-Signal Correlation
Proposed by Bruns and Eckhorn [Bruns2004_], Envelope-to-Signal Correlation (*ESC*)
is similar to Amplitude Envelope Correlation (:mod:`dyconnmap.fc.aec`), but the
the amplitude of the lower frequency oscillation is signed; and thus the phase
information is preserved.
.. math::
r_{ESC} = \\text{corr}(\\chi_{lo}, \\alpha_{hi})
Where :math:`\\chi` is the input signal filtered to the frequency band :math:`lo`
and :math:`\\alpha` denotes the Instantaneous Amplitude of the same input signal
at the frequency band :math:`hi`.
|
-----
.. [Bruns2004] <NAME>., & <NAME>. (2004). Task-related coupling from high-to low-frequency signals among visual cortical areas in human subdural recordings. International Journal of Psychophysiology, 51(2), 97-116.
.. [Penny2008] <NAME>., <NAME>., <NAME>., & <NAME>. (2008). Testing for nested oscillation. Journal of neuroscience methods, 174(1), 50-61. Chicago
"""
# Author: <NAME> <<EMAIL>>
from ..analytic_signal import analytic_signal
import numpy as np
def esc(data, fb_lo, fb_hi, fs):
""" Envelope-Signal-Correlation
Estimate the Envelope-Signal-Correlation the given :attr:`data`.
Parameters
----------
data : array-like, shape(n_channels, n_samples)
Multichannel recording data.
fb_lo : list of length 2
The low and high frequencies of the lower band.
fb_hi : list of length 2
The low and high frequencies of the upper band.
fs : float
Sampling frequency.
pairs : array-like or `None`
- If an `array-like` is given, notice that each element is a tuple of length two.
- If `None` is passed, complete connectivity will be assumed.
Returns
-------
r : array-like, shape(n_channels, n_channels)
Estimated Pearson correlation coefficient.
"""
_, _, f = analytic_signal(data, fb_lo, fs)
h, _, _ = analytic_signal(data, fb_hi, fs)
escv = np.corrcoef(f, np.abs(h))
escv = np.float32(escv)
return escv
| en | 0.680743 | # -*- coding: utf-8 -*- Envelope-to-Signal Correlation Proposed by Bruns and Eckhorn [Bruns2004_], Envelope-to-Signal Correlation (*ESC*) is similar to Amplitude Envelope Correlation (:mod:`dyconnmap.fc.aec`), but the the amplitude of the lower frequency oscillation is signed; and thus the phase information is preserved. .. math:: r_{ESC} = \\text{corr}(\\chi_{lo}, \\alpha_{hi}) Where :math:`\\chi` is the input signal filtered to the frequency band :math:`lo` and :math:`\\alpha` denotes the Instantaneous Amplitude of the same input signal at the frequency band :math:`hi`. | ----- .. [Bruns2004] <NAME>., & <NAME>. (2004). Task-related coupling from high-to low-frequency signals among visual cortical areas in human subdural recordings. International Journal of Psychophysiology, 51(2), 97-116. .. [Penny2008] <NAME>., <NAME>., <NAME>., & <NAME>. (2008). Testing for nested oscillation. Journal of neuroscience methods, 174(1), 50-61. Chicago # Author: <NAME> <<EMAIL>> Envelope-Signal-Correlation Estimate the Envelope-Signal-Correlation the given :attr:`data`. Parameters ---------- data : array-like, shape(n_channels, n_samples) Multichannel recording data. fb_lo : list of length 2 The low and high frequencies of the lower band. fb_hi : list of length 2 The low and high frequencies of the upper band. fs : float Sampling frequency. pairs : array-like or `None` - If an `array-like` is given, notice that each element is a tuple of length two. - If `None` is passed, complete connectivity will be assumed. Returns ------- r : array-like, shape(n_channels, n_channels) Estimated Pearson correlation coefficient. | 2.220554 | 2 |
tests/test_models.py | ulgens/django-dbcheck | 0 | 6620295 | <gh_stars>0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_django-dbcheck
------------
Tests for `django-dbcheck` models module.
"""
from django.test import TestCase
from django_dbcheck import models
class TestDjango_dbcheck(TestCase):
def setUp(self):
pass
def test_something(self):
pass
def tearDown(self):
pass
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_django-dbcheck
------------
Tests for `django-dbcheck` models module.
"""
from django.test import TestCase
from django_dbcheck import models
class TestDjango_dbcheck(TestCase):
def setUp(self):
pass
def test_something(self):
pass
def tearDown(self):
pass | en | 0.282243 | #!/usr/bin/env python # -*- coding: utf-8 -*- test_django-dbcheck ------------ Tests for `django-dbcheck` models module. | 1.723317 | 2 |
frappe_graphql/__init__.py | fahimalizain/frappe_graphql | 23 | 6620296 | <filename>frappe_graphql/__init__.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from .utils.loader import get_schema # noqa
from .utils.cursor_pagination import CursorPaginator # noqa
from .utils.exceptions import ERROR_CODED_EXCEPTIONS, GQLExecutionUserError, GQLExecutionUserErrorMultiple # noqa
from .utils.roles import REQUIRE_ROLES # noqa
from .utils.subscriptions import setup_subscription, get_consumers, notify_consumer, \
notify_consumers, notify_all_consumers, subscription_keepalive, complete_subscription # noqa
__version__ = '1.0.0'
| <filename>frappe_graphql/__init__.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from .utils.loader import get_schema # noqa
from .utils.cursor_pagination import CursorPaginator # noqa
from .utils.exceptions import ERROR_CODED_EXCEPTIONS, GQLExecutionUserError, GQLExecutionUserErrorMultiple # noqa
from .utils.roles import REQUIRE_ROLES # noqa
from .utils.subscriptions import setup_subscription, get_consumers, notify_consumer, \
notify_consumers, notify_all_consumers, subscription_keepalive, complete_subscription # noqa
__version__ = '1.0.0'
| te | 0.256178 | # -*- coding: utf-8 -*- # noqa # noqa # noqa # noqa # noqa | 1.196207 | 1 |
lcm/lcm/nf_pm/serializers/pm_subscription.py | onap/vfc-gvnfm-vnflcm | 1 | 6620297 | <reponame>onap/vfc-gvnfm-vnflcm
# Copyright (c) 2019, CMCC Technologies Co., Ltd.
#
# 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 rest_framework import serializers
from lcm.nf_pm.serializers.Link import LinkSerializer
from lcm.nf_pm.serializers.pm_subscription_request import PmNotificationsFilterSerializer
class PmSubscriptionSerializer(serializers.Serializer):
id = serializers.CharField(help_text="Identifier that identifies the subscription",
required=True, allow_null=False)
filter = PmNotificationsFilterSerializer(help_text="Filter settings for this subscription, to define the"
" subset of all notifications this subscription "
"relates to.", required=False, allow_null=True)
callbackUri = serializers.CharField(help_text="The URI of the endpoint to send the notification to",
required=True, allow_null=False)
_links = LinkSerializer(
help_text="Links to resources related to this resource.",
required=True,
allow_null=False)
| # Copyright (c) 2019, CMCC Technologies Co., Ltd.
#
# 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 rest_framework import serializers
from lcm.nf_pm.serializers.Link import LinkSerializer
from lcm.nf_pm.serializers.pm_subscription_request import PmNotificationsFilterSerializer
class PmSubscriptionSerializer(serializers.Serializer):
id = serializers.CharField(help_text="Identifier that identifies the subscription",
required=True, allow_null=False)
filter = PmNotificationsFilterSerializer(help_text="Filter settings for this subscription, to define the"
" subset of all notifications this subscription "
"relates to.", required=False, allow_null=True)
callbackUri = serializers.CharField(help_text="The URI of the endpoint to send the notification to",
required=True, allow_null=False)
_links = LinkSerializer(
help_text="Links to resources related to this resource.",
required=True,
allow_null=False) | en | 0.853739 | # Copyright (c) 2019, CMCC Technologies Co., Ltd. # # 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. | 1.831409 | 2 |
vcf.py | animesh-chouhan/vcfCreator | 0 | 6620298 | <reponame>animesh-chouhan/vcfCreator<filename>vcf.py
import sys
import csv
import logging
import os.path
from prettytable import PrettyTable
def ask_user(to_print):
print(to_print)
check = str(input("Reply in (Y/N): ")).lower().strip()
try:
if check[0] == 'y':
return True
elif check[0] == 'n':
return False
else:
print('Invalid Input')
return ask_user()
except Exception as error:
print("Please enter valid inputs")
print(error)
return ask_user()
def encode(text):
#char to encode "\\" / "\," / "\n"(Backslashes, commas, and newlines must be encoded)
encoded = text.replace('\\', '\\\\')
encoded = encoded.replace(',', '\\,')
return encoded
#print(encode("this is one value,this \is another"))
def name_formatter(data, index, formatter, former):
formatted = ""
for form in former:
if form in index.keys():
formatted += data[index[form]] + " "
if form in formatter.keys():
formatted += data[formatter[form]] + " "
return formatted
def check_format(data, index, formatter):
inp = input("\nPlease specify the format for the names:\nE.g. name + roomno + company if the fields in csv file are name, name_roomno, name_company\n")
former = inp.replace(" ", "").split("+")
try:
print("\n")
print(name_formatter(data, index, formatter, former))
except Exception as e:
print("ERROR: " + str(e))
if(not ask_user("Is this formatting fine?")):
check_format(data, index, formatter)
return former
def vcfcreator(filename="sample.csv"): #main function
if not os.path.isfile(filename): #checking if the file exists
print("File doesn't exist. :(")
return 0
else:
data = []
print("File found. Processing...")
with open(filename, 'r') as csvfile: #loading the file
reader = csv.reader(csvfile, delimiter=',')
for row in reader:
data.append(row)
table = PrettyTable(data[0])
try:
table.add_row(data[1])
except:
print("The csv file doesn't seem to have any data")
print(table, "\n")
logging.info(data[0])
attributes = {'FN': 'name',
'NICKNAME': 'nick',
'BDAY': 'birthday',
'ANNIVERSARY': 'anniversary',
'TEL;WORK;VOICE': 'phone',
'ADR;HOME': 'address',
'EMAIL': 'email'
}
with open(filename.split(".")[0]+".vcf", "w+") as file:
index = {}
for i, column in enumerate(data[0]):
index[column] = i
logging.info(index)
# formatter attributes
formatter = {}
for key in data[0]:
splitted_key = key.split("_")
try:
if splitted_key[0] == "name" and splitted_key[1]:
formatter[splitted_key[1]] = data[0].index(key)
except:
pass
former = check_format(data[1], index, formatter)
#vcard writer
for i, row in enumerate(data[1:]):
file.write("BEGIN:VCARD\n")
file.write("VERSION:4.0\n")
for attribute in attributes.keys():
if attributes[attribute] in data[0]:
if attributes[attribute] == 'name' and formatter:
file.write("{}:{}\n".format(attribute, encode(name_formatter(data[i+1], index, formatter, former))))
else:
file.write("{}:{}\n".format(attribute, encode(data[i+1][index[attributes[attribute]]])))
file.write("END:VCARD\n")
if(ask_user(("Check the contacts imported with the {} file".format(filename.split(".")[0]+".vcf"))) == True):
print("Thanks for using :)")
else:
print("Raise an issue with the details and the vcf file created")
if __name__ == "__main__":
print("""
_ ______________ ______ __
| | / / ____/ ____/ / ____/_______ ____ _/ /_____ _____
| | / / / / /_ / / / ___/ _ \/ __ `/ __/ __ \/ ___/
| |/ / /___/ __/ / /___/ / / __/ /_/ / /_/ /_/ / /
|___/\____/_/ \____/_/ \___/\__,_/\__/\____/_/
""")
try:
vcfcreator(sys.argv[1])
except(IndexError):
print("No file provided. Running the sample csv!")
vcfcreator()
| import sys
import csv
import logging
import os.path
from prettytable import PrettyTable
def ask_user(to_print):
print(to_print)
check = str(input("Reply in (Y/N): ")).lower().strip()
try:
if check[0] == 'y':
return True
elif check[0] == 'n':
return False
else:
print('Invalid Input')
return ask_user()
except Exception as error:
print("Please enter valid inputs")
print(error)
return ask_user()
def encode(text):
#char to encode "\\" / "\," / "\n"(Backslashes, commas, and newlines must be encoded)
encoded = text.replace('\\', '\\\\')
encoded = encoded.replace(',', '\\,')
return encoded
#print(encode("this is one value,this \is another"))
def name_formatter(data, index, formatter, former):
formatted = ""
for form in former:
if form in index.keys():
formatted += data[index[form]] + " "
if form in formatter.keys():
formatted += data[formatter[form]] + " "
return formatted
def check_format(data, index, formatter):
inp = input("\nPlease specify the format for the names:\nE.g. name + roomno + company if the fields in csv file are name, name_roomno, name_company\n")
former = inp.replace(" ", "").split("+")
try:
print("\n")
print(name_formatter(data, index, formatter, former))
except Exception as e:
print("ERROR: " + str(e))
if(not ask_user("Is this formatting fine?")):
check_format(data, index, formatter)
return former
def vcfcreator(filename="sample.csv"): #main function
if not os.path.isfile(filename): #checking if the file exists
print("File doesn't exist. :(")
return 0
else:
data = []
print("File found. Processing...")
with open(filename, 'r') as csvfile: #loading the file
reader = csv.reader(csvfile, delimiter=',')
for row in reader:
data.append(row)
table = PrettyTable(data[0])
try:
table.add_row(data[1])
except:
print("The csv file doesn't seem to have any data")
print(table, "\n")
logging.info(data[0])
attributes = {'FN': 'name',
'NICKNAME': 'nick',
'BDAY': 'birthday',
'ANNIVERSARY': 'anniversary',
'TEL;WORK;VOICE': 'phone',
'ADR;HOME': 'address',
'EMAIL': 'email'
}
with open(filename.split(".")[0]+".vcf", "w+") as file:
index = {}
for i, column in enumerate(data[0]):
index[column] = i
logging.info(index)
# formatter attributes
formatter = {}
for key in data[0]:
splitted_key = key.split("_")
try:
if splitted_key[0] == "name" and splitted_key[1]:
formatter[splitted_key[1]] = data[0].index(key)
except:
pass
former = check_format(data[1], index, formatter)
#vcard writer
for i, row in enumerate(data[1:]):
file.write("BEGIN:VCARD\n")
file.write("VERSION:4.0\n")
for attribute in attributes.keys():
if attributes[attribute] in data[0]:
if attributes[attribute] == 'name' and formatter:
file.write("{}:{}\n".format(attribute, encode(name_formatter(data[i+1], index, formatter, former))))
else:
file.write("{}:{}\n".format(attribute, encode(data[i+1][index[attributes[attribute]]])))
file.write("END:VCARD\n")
if(ask_user(("Check the contacts imported with the {} file".format(filename.split(".")[0]+".vcf"))) == True):
print("Thanks for using :)")
else:
print("Raise an issue with the details and the vcf file created")
if __name__ == "__main__":
print("""
_ ______________ ______ __
| | / / ____/ ____/ / ____/_______ ____ _/ /_____ _____
| | / / / / /_ / / / ___/ _ \/ __ `/ __/ __ \/ ___/
| |/ / /___/ __/ / /___/ / / __/ /_/ / /_/ /_/ / /
|___/\____/_/ \____/_/ \___/\__,_/\__/\____/_/
""")
try:
vcfcreator(sys.argv[1])
except(IndexError):
print("No file provided. Running the sample csv!")
vcfcreator() | en | 0.397921 | #char to encode "\\" / "\," / "\n"(Backslashes, commas, and newlines must be encoded) #print(encode("this is one value,this \is another")) #main function #checking if the file exists #loading the file # formatter attributes #vcard writer _ ______________ ______ __ | | / / ____/ ____/ / ____/_______ ____ _/ /_____ _____ | | / / / / /_ / / / ___/ _ \/ __ `/ __/ __ \/ ___/ | |/ / /___/ __/ / /___/ / / __/ /_/ / /_/ /_/ / / |___/\____/_/ \____/_/ \___/\__,_/\__/\____/_/ | 3.228779 | 3 |
municipal_finance/models/income_expenditure.py | desafinadude/municipal-data | 0 | 6620299 | <reponame>desafinadude/municipal-data<filename>municipal_finance/models/income_expenditure.py
from django.db import models
from .small_auto_field import SmallAutoField
from .amount_type import AmountTypeV2
from .government_functions import GovernmentFunctionsV2
class IncexpItems(models.Model):
label = models.TextField()
position_in_return_form = models.IntegerField(null=True)
return_form_structure = models.TextField(null=True)
composition = models.TextField(null=True)
class Meta:
abstract = True
class IncexpItemsV1(IncexpItems):
code = models.TextField(primary_key=True)
class Meta:
db_table = 'incexp_items'
class IncexpItemsV2(IncexpItems):
id = SmallAutoField(primary_key=True)
code = models.TextField(unique=True)
class Meta:
db_table = 'incexp_items_v2'
class IncexpFacts(models.Model):
demarcation_code = models.TextField()
period_code = models.TextField()
amount = models.BigIntegerField(null=True)
financial_year = models.IntegerField()
period_length = models.TextField()
financial_period = models.IntegerField()
class Meta:
abstract = True
class IncexpFactsV1(IncexpFacts):
item_code = models.TextField()
amount_type_code = models.TextField()
function_code = models.TextField()
class Meta:
db_table = 'incexp_facts'
unique_together = (
(
'demarcation_code',
'period_code',
'function_code',
'item_code',
),
(
'amount_type_code',
'demarcation_code',
'financial_period',
'financial_year',
'function_code',
'item_code',
'period_length',
),
)
class IncexpFactsV2(IncexpFacts):
item = models.ForeignKey(
IncexpItemsV2,
models.DO_NOTHING,
)
amount_type = models.ForeignKey(
AmountTypeV2,
models.DO_NOTHING,
)
function = models.ForeignKey(
GovernmentFunctionsV2,
models.DO_NOTHING,
)
class Meta:
db_table = 'incexp_facts_v2'
unique_together = (
(
'demarcation_code',
'period_code',
'function',
'item',
),
(
'amount_type',
'demarcation_code',
'financial_period',
'financial_year',
'function',
'item',
'period_length',
),
)
| from django.db import models
from .small_auto_field import SmallAutoField
from .amount_type import AmountTypeV2
from .government_functions import GovernmentFunctionsV2
class IncexpItems(models.Model):
label = models.TextField()
position_in_return_form = models.IntegerField(null=True)
return_form_structure = models.TextField(null=True)
composition = models.TextField(null=True)
class Meta:
abstract = True
class IncexpItemsV1(IncexpItems):
code = models.TextField(primary_key=True)
class Meta:
db_table = 'incexp_items'
class IncexpItemsV2(IncexpItems):
id = SmallAutoField(primary_key=True)
code = models.TextField(unique=True)
class Meta:
db_table = 'incexp_items_v2'
class IncexpFacts(models.Model):
demarcation_code = models.TextField()
period_code = models.TextField()
amount = models.BigIntegerField(null=True)
financial_year = models.IntegerField()
period_length = models.TextField()
financial_period = models.IntegerField()
class Meta:
abstract = True
class IncexpFactsV1(IncexpFacts):
item_code = models.TextField()
amount_type_code = models.TextField()
function_code = models.TextField()
class Meta:
db_table = 'incexp_facts'
unique_together = (
(
'demarcation_code',
'period_code',
'function_code',
'item_code',
),
(
'amount_type_code',
'demarcation_code',
'financial_period',
'financial_year',
'function_code',
'item_code',
'period_length',
),
)
class IncexpFactsV2(IncexpFacts):
item = models.ForeignKey(
IncexpItemsV2,
models.DO_NOTHING,
)
amount_type = models.ForeignKey(
AmountTypeV2,
models.DO_NOTHING,
)
function = models.ForeignKey(
GovernmentFunctionsV2,
models.DO_NOTHING,
)
class Meta:
db_table = 'incexp_facts_v2'
unique_together = (
(
'demarcation_code',
'period_code',
'function',
'item',
),
(
'amount_type',
'demarcation_code',
'financial_period',
'financial_year',
'function',
'item',
'period_length',
),
) | none | 1 | 1.954661 | 2 | |
hubnspoke/flnode/start_pipeline_nii.py | Warvito/monaifl | 0 | 6620300 | <reponame>Warvito/monaifl
import os
import sys
sys.path.append('.')
import torch as t
from monai.networks.nets import BasicUNet
from monai.transforms import (Compose, LoadImageD, AddChannelD, AddCoordinateChannelsD, Rand3DElasticD, SplitChannelD,
DeleteItemsD, ScaleIntensityRangeD, ConcatItemsD, RandSpatialCropD, ToTensorD, CastToTypeD)
from monai.data import Dataset, DataLoader
from monai.metrics import compute_meandice
from torch import nn, sigmoid, cuda
from flnode.pipeline2.monaiopener_nii import MonaiOpenerNii, MedNISTDataset
from flnode.pipeline2.monaialgo_nii import MonaiAlgo
from common.utils import Mapping
import numpy as np
from pathlib import Path
import logging
logging.basicConfig(format='%(asctime)s - %(message)s')
logger = logging.getLogger()
logger.setLevel(logging.NOTSET)
if cuda.is_available():
DEVICE = "cuda:0"
else:
DEVICE = "cpu"
def instantiateMonaiAlgo(frac_val = 0.1, frac_test = 0.1, dataset_name='MedicalDecathlon1'):
cwd = Path.cwd()
print('Instantiating again...')
datasetName = dataset_name
data_path = '../data_provider/dummy_data/'
data_dir = os.path.join(data_path, datasetName)
folders = os.listdir(data_dir)
mo = MonaiOpenerNii(data_dir)
logger.info("----------------------------")
logger.info("Dataset Summary")
print("----------------------------")
mo.data_summary(folders)
train, val, test = mo.get_x_y(folders, frac_val, frac_test)
logger.info(f"Training count: {len(train)}, Validation count: {len(val)}, Test count: {len(test)}")
train_transforms = Compose(
[LoadImageD(keys=['img', 'seg'], reader='NiBabelReader', as_closest_canonical=False),
AddChannelD(keys=['img', 'seg']),
AddCoordinateChannelsD(keys=['img'], spatial_channels=(1, 2, 3)),
Rand3DElasticD(keys=['img', 'seg'], sigma_range=(1, 3), magnitude_range=(-10, 10), prob=0.5,
mode=('bilinear', 'nearest'),
rotate_range=(-0.34, 0.34),
scale_range=(-0.1, 0.1), spatial_size=None),
SplitChannelD(keys=['img']),
ScaleIntensityRangeD(keys=['img_0'], a_min=-15, a_max=100, b_min=-1, b_max=1, clip=True),
ConcatItemsD(keys=['img_0', 'img_1', 'img_2', 'img_3'], name='img'),
DeleteItemsD(keys=['img_0', 'img_1', 'img_2', 'img_3']),
RandSpatialCropD(keys=['img', 'seg'], roi_size=(128, 128, 128), random_center=True, random_size=False),
ToTensorD(keys=['img', 'seg'])
])
val_transforms = Compose(
[LoadImageD(keys=['img', 'seg'], reader='NiBabelReader', as_closest_canonical=False),
AddChannelD(keys=['img', 'seg']),
AddCoordinateChannelsD(keys=['img'], spatial_channels=(1, 2, 3)),
SplitChannelD(keys=['img']),
ScaleIntensityRangeD(keys=['img_0'], a_min=-15, a_max=100, b_min=-1, b_max=1, clip=True),
ConcatItemsD(keys=['img_0', 'img_1', 'img_2', 'img_3'], name='img'),
DeleteItemsD(keys=['img_0', 'img_1', 'img_2', 'img_3'],),
CastToTypeD(keys=['img'], dtype=np.float32),
ToTensorD(keys=['img', 'seg'])
])
# monai algorithm object
ma = MonaiAlgo()
train_dataset = Dataset(train, transform=train_transforms)
val_dataset = Dataset(val, transform=val_transforms)
test_dataset = Dataset(test, transform=val_transforms)
ma.train_loader = DataLoader(train_dataset, batch_size=1, shuffle=True, num_workers=2)
ma.val_loader = DataLoader(val_dataset, batch_size=1, shuffle=False, num_workers=2)
ma.test_loader = DataLoader(test_dataset, batch_size=1, shuffle=False, num_workers=2)
# model initiliatization
class BasicUnet(nn.Module):
def __init__(self, num_classes=1):
super().__init__()
self.net = BasicUNet(dimensions=3,
features=(32, 32, 64, 128, 256, 32),
in_channels=4,
out_channels=num_classes
)
def forward(self, x, do_sigmoid=True):
logits = self.net(x)
if do_sigmoid:
return sigmoid(logits)
else:
return logits
ma.model = BasicUnet().to(DEVICE)
# model loss function
def mean_dice(output, target, average=True):
# empty labels return a dice score of NaN - replace with 0
dice_per_batch = compute_meandice(output, target, include_background=False)
dice_per_batch[dice_per_batch.isnan()] = 0
if average:
return dice_per_batch.mean().cpu()
else:
return dice_per_batch.cpu()
ma.loss = mean_dice
# model metric
ma.metric = compute_meandice
# model optimizer
ma.optimizer = t.optim.Adam(ma.model.parameters(), lr=1e-5, weight_decay=0, amsgrad=True)
# number of epochs
ma.epochs = 1
return ma
if __name__ == '__main__':
ma = instantiateMonaiAlgo()
| import os
import sys
sys.path.append('.')
import torch as t
from monai.networks.nets import BasicUNet
from monai.transforms import (Compose, LoadImageD, AddChannelD, AddCoordinateChannelsD, Rand3DElasticD, SplitChannelD,
DeleteItemsD, ScaleIntensityRangeD, ConcatItemsD, RandSpatialCropD, ToTensorD, CastToTypeD)
from monai.data import Dataset, DataLoader
from monai.metrics import compute_meandice
from torch import nn, sigmoid, cuda
from flnode.pipeline2.monaiopener_nii import MonaiOpenerNii, MedNISTDataset
from flnode.pipeline2.monaialgo_nii import MonaiAlgo
from common.utils import Mapping
import numpy as np
from pathlib import Path
import logging
logging.basicConfig(format='%(asctime)s - %(message)s')
logger = logging.getLogger()
logger.setLevel(logging.NOTSET)
if cuda.is_available():
DEVICE = "cuda:0"
else:
DEVICE = "cpu"
def instantiateMonaiAlgo(frac_val = 0.1, frac_test = 0.1, dataset_name='MedicalDecathlon1'):
cwd = Path.cwd()
print('Instantiating again...')
datasetName = dataset_name
data_path = '../data_provider/dummy_data/'
data_dir = os.path.join(data_path, datasetName)
folders = os.listdir(data_dir)
mo = MonaiOpenerNii(data_dir)
logger.info("----------------------------")
logger.info("Dataset Summary")
print("----------------------------")
mo.data_summary(folders)
train, val, test = mo.get_x_y(folders, frac_val, frac_test)
logger.info(f"Training count: {len(train)}, Validation count: {len(val)}, Test count: {len(test)}")
train_transforms = Compose(
[LoadImageD(keys=['img', 'seg'], reader='NiBabelReader', as_closest_canonical=False),
AddChannelD(keys=['img', 'seg']),
AddCoordinateChannelsD(keys=['img'], spatial_channels=(1, 2, 3)),
Rand3DElasticD(keys=['img', 'seg'], sigma_range=(1, 3), magnitude_range=(-10, 10), prob=0.5,
mode=('bilinear', 'nearest'),
rotate_range=(-0.34, 0.34),
scale_range=(-0.1, 0.1), spatial_size=None),
SplitChannelD(keys=['img']),
ScaleIntensityRangeD(keys=['img_0'], a_min=-15, a_max=100, b_min=-1, b_max=1, clip=True),
ConcatItemsD(keys=['img_0', 'img_1', 'img_2', 'img_3'], name='img'),
DeleteItemsD(keys=['img_0', 'img_1', 'img_2', 'img_3']),
RandSpatialCropD(keys=['img', 'seg'], roi_size=(128, 128, 128), random_center=True, random_size=False),
ToTensorD(keys=['img', 'seg'])
])
val_transforms = Compose(
[LoadImageD(keys=['img', 'seg'], reader='NiBabelReader', as_closest_canonical=False),
AddChannelD(keys=['img', 'seg']),
AddCoordinateChannelsD(keys=['img'], spatial_channels=(1, 2, 3)),
SplitChannelD(keys=['img']),
ScaleIntensityRangeD(keys=['img_0'], a_min=-15, a_max=100, b_min=-1, b_max=1, clip=True),
ConcatItemsD(keys=['img_0', 'img_1', 'img_2', 'img_3'], name='img'),
DeleteItemsD(keys=['img_0', 'img_1', 'img_2', 'img_3'],),
CastToTypeD(keys=['img'], dtype=np.float32),
ToTensorD(keys=['img', 'seg'])
])
# monai algorithm object
ma = MonaiAlgo()
train_dataset = Dataset(train, transform=train_transforms)
val_dataset = Dataset(val, transform=val_transforms)
test_dataset = Dataset(test, transform=val_transforms)
ma.train_loader = DataLoader(train_dataset, batch_size=1, shuffle=True, num_workers=2)
ma.val_loader = DataLoader(val_dataset, batch_size=1, shuffle=False, num_workers=2)
ma.test_loader = DataLoader(test_dataset, batch_size=1, shuffle=False, num_workers=2)
# model initiliatization
class BasicUnet(nn.Module):
def __init__(self, num_classes=1):
super().__init__()
self.net = BasicUNet(dimensions=3,
features=(32, 32, 64, 128, 256, 32),
in_channels=4,
out_channels=num_classes
)
def forward(self, x, do_sigmoid=True):
logits = self.net(x)
if do_sigmoid:
return sigmoid(logits)
else:
return logits
ma.model = BasicUnet().to(DEVICE)
# model loss function
def mean_dice(output, target, average=True):
# empty labels return a dice score of NaN - replace with 0
dice_per_batch = compute_meandice(output, target, include_background=False)
dice_per_batch[dice_per_batch.isnan()] = 0
if average:
return dice_per_batch.mean().cpu()
else:
return dice_per_batch.cpu()
ma.loss = mean_dice
# model metric
ma.metric = compute_meandice
# model optimizer
ma.optimizer = t.optim.Adam(ma.model.parameters(), lr=1e-5, weight_decay=0, amsgrad=True)
# number of epochs
ma.epochs = 1
return ma
if __name__ == '__main__':
ma = instantiateMonaiAlgo() | en | 0.564447 | # monai algorithm object # model initiliatization # model loss function # empty labels return a dice score of NaN - replace with 0 # model metric # model optimizer # number of epochs | 1.874489 | 2 |
tests/urls.py | ibrmora/django-oscar-accounts | 0 | 6620301 | from django.conf.urls import include, url
from django.contrib import admin
from oscar.app import application
from oscar_accounts.api.app import application as api_app
from oscar_accounts.dashboard.app import application as accounts_app
admin.autodiscover()
urlpatterns = [
url(r'^dashboard/accounts/', accounts_app.urls),
url(r'^api/', api_app.urls),
url(r'^i18n/', include('django.conf.urls.i18n')),
url(r'', application.urls),
]
| from django.conf.urls import include, url
from django.contrib import admin
from oscar.app import application
from oscar_accounts.api.app import application as api_app
from oscar_accounts.dashboard.app import application as accounts_app
admin.autodiscover()
urlpatterns = [
url(r'^dashboard/accounts/', accounts_app.urls),
url(r'^api/', api_app.urls),
url(r'^i18n/', include('django.conf.urls.i18n')),
url(r'', application.urls),
]
| none | 1 | 1.616682 | 2 | |
layers/__init__.py | miliadis/DeepVideoCS | 65 | 6620302 | from .measurements import *
| from .measurements import *
| none | 1 | 1.152132 | 1 | |
labelbox/__init__.py | shalevy1/labelbox-python | 0 | 6620303 | <gh_stars>0
"The Labelbox python package."
__version__ = '1.0.2'
| "The Labelbox python package."
__version__ = '1.0.2' | none | 1 | 1.088321 | 1 | |
src/ertk/pytorch/models/mlp.py | agkphysics/emotion | 1 | 6620304 | <filename>src/ertk/pytorch/models/mlp.py
from typing import Sequence
from torch import nn
class Model(nn.Module):
def __init__(
self,
n_features: int,
n_classes: int,
units: Sequence[int] = [512],
dropout: float = 0.5,
):
super().__init__()
sizes = [n_features] + list(units)
self.hidden = nn.Sequential(
*(
nn.Sequential(
nn.Linear(sizes[i], sizes[i + 1]), nn.ReLU(), nn.Dropout(dropout)
)
for i in range(len(units))
)
)
self.final = nn.Linear(units[-1], n_classes)
def forward(self, x):
return self.final(self.hidden(x))
| <filename>src/ertk/pytorch/models/mlp.py
from typing import Sequence
from torch import nn
class Model(nn.Module):
def __init__(
self,
n_features: int,
n_classes: int,
units: Sequence[int] = [512],
dropout: float = 0.5,
):
super().__init__()
sizes = [n_features] + list(units)
self.hidden = nn.Sequential(
*(
nn.Sequential(
nn.Linear(sizes[i], sizes[i + 1]), nn.ReLU(), nn.Dropout(dropout)
)
for i in range(len(units))
)
)
self.final = nn.Linear(units[-1], n_classes)
def forward(self, x):
return self.final(self.hidden(x))
| none | 1 | 3.254267 | 3 | |
test/test_thread_fuzzing.py | ivanlyon/exercises | 0 | 6620305 | <filename>test/test_thread_fuzzing.py
import unittest
from general import thread_fuzzing
###############################################################################
class TestThreadFuzzing(unittest.TestCase):
'''
Unittest class for the testing of the thread_fuzzing tutorial.
'''
def test_ordered_output(self):
'''Test functions expected to produce ordered output.'''
test_values = [5, 10]
for t in test_values:
valid_result = thread_fuzzing.get_results(t)
self.assertEqual(valid_result, thread_fuzzing.get_results_function(t))
self.assertEqual(valid_result, thread_fuzzing.get_results_function_threads(t))
self.assertEqual(valid_result, thread_fuzzing.get_results_function_threads_fuzzed_locks(t))
def test_unordered_output(self):
'''Test functions expected to produce ordered output.'''
self.assertNotEqual(thread_fuzzing.get_results(5), thread_fuzzing.get_results_function_threads_fuzzed(5))
###############################################################################
if __name__ == '__main__':
unittest.main()
| <filename>test/test_thread_fuzzing.py
import unittest
from general import thread_fuzzing
###############################################################################
class TestThreadFuzzing(unittest.TestCase):
'''
Unittest class for the testing of the thread_fuzzing tutorial.
'''
def test_ordered_output(self):
'''Test functions expected to produce ordered output.'''
test_values = [5, 10]
for t in test_values:
valid_result = thread_fuzzing.get_results(t)
self.assertEqual(valid_result, thread_fuzzing.get_results_function(t))
self.assertEqual(valid_result, thread_fuzzing.get_results_function_threads(t))
self.assertEqual(valid_result, thread_fuzzing.get_results_function_threads_fuzzed_locks(t))
def test_unordered_output(self):
'''Test functions expected to produce ordered output.'''
self.assertNotEqual(thread_fuzzing.get_results(5), thread_fuzzing.get_results_function_threads_fuzzed(5))
###############################################################################
if __name__ == '__main__':
unittest.main()
| de | 0.504085 | ############################################################################### Unittest class for the testing of the thread_fuzzing tutorial. Test functions expected to produce ordered output. Test functions expected to produce ordered output. ############################################################################### | 3.302993 | 3 |
Medical-Record-Managment-System/uploads/migrations/0007_auto_20200717_1057.py | AtluriNikhil/College_Projects | 0 | 6620306 | # Generated by Django 3.0.7 on 2020-07-17 05:27
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('uploads', '0006_queries'),
]
operations = [
migrations.AlterField(
model_name='queries',
name='mobile',
field=models.IntegerField(),
),
]
| # Generated by Django 3.0.7 on 2020-07-17 05:27
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('uploads', '0006_queries'),
]
operations = [
migrations.AlterField(
model_name='queries',
name='mobile',
field=models.IntegerField(),
),
]
| en | 0.802614 | # Generated by Django 3.0.7 on 2020-07-17 05:27 | 1.424178 | 1 |
tests/media/show/mapper_tests.py | OpenEntityMap/oem-client | 0 | 6620307 | from __future__ import absolute_import, division, print_function
from oem.core.exceptions import AbsoluteNumberRequiredError
from oem.media.show import ShowMapper, EpisodeIdentifier
from oem_core.models import Collection, Show, Season, Episode, EpisodeMapping
from tests.core.mock import MockService
import pytest
collection = Collection(None, 'anidb', 'tvdb')
service = MockService('anidb', 'tvdb')
#
# Show
#
def test_show_invalid_default_season():
mapper = ShowMapper(service)
assert mapper.match(
Show(collection, {}, [], default_season='INVALID'),
EpisodeIdentifier(1, 1)
) is None
#
# Season
#
def test_season_absolute_number_required():
mapper = ShowMapper(service)
show = Show(collection, {}, [])
show.seasons['a'] = Season(collection, show, 'a')
with pytest.raises(AbsoluteNumberRequiredError):
mapper.match(show, EpisodeIdentifier(1, 1))
def test_season_invalid_default_season():
mapper = ShowMapper(service)
show = Show(collection, {}, [])
show.seasons['1'] = Season(collection, show, '1', default_season='INVALID')
assert mapper.match(show, EpisodeIdentifier(1, 1)) is None
def test_season_invalid_match():
mapper = ShowMapper(service)
show = Show(collection, {}, [])
show.seasons['1'] = Season(collection, show, '1')
assert mapper.match(show, EpisodeIdentifier(1, 1)) is None
#
# Episode
#
def test_episode_invalid_mapping_season():
mapper = ShowMapper(service)
show = Show(collection, {}, [])
show.seasons['1'] = Season(collection, show, '1')
show.seasons['1'].episodes['1'] = Episode(collection, show.seasons['1'], '1')
show.seasons['1'].episodes['1'].mappings = [
EpisodeMapping(collection, show.seasons['1'].episodes['1'], 'INVALID', '1')
]
assert mapper.match(show, EpisodeIdentifier(1, 1)) is None
def test_episode_invalid_mapping_episode():
mapper = ShowMapper(service)
show = Show(collection, {}, [])
show.seasons['1'] = Season(collection, show, '1')
show.seasons['1'].episodes['1'] = Episode(collection, show.seasons['1'], '1')
show.seasons['1'].episodes['1'].mappings = [
EpisodeMapping(collection, show.seasons['1'].episodes['1'], '1', 'INVALID')
]
assert mapper.match(show, EpisodeIdentifier(1, 1)) is None
def test_episode_invalid_match():
mapper = ShowMapper(service)
show = Show(collection, {}, [])
show.seasons['1'] = Season(collection, show, '1')
show.seasons['1'].episodes['1'] = Episode(collection, show.seasons['1'], '1')
show.seasons['1'].episodes['1'].mappings = [
EpisodeMapping(collection, show.seasons['1'].episodes['1'], '1', '1')
]
assert mapper.match(show, EpisodeIdentifier(1, 1)) is None
| from __future__ import absolute_import, division, print_function
from oem.core.exceptions import AbsoluteNumberRequiredError
from oem.media.show import ShowMapper, EpisodeIdentifier
from oem_core.models import Collection, Show, Season, Episode, EpisodeMapping
from tests.core.mock import MockService
import pytest
collection = Collection(None, 'anidb', 'tvdb')
service = MockService('anidb', 'tvdb')
#
# Show
#
def test_show_invalid_default_season():
mapper = ShowMapper(service)
assert mapper.match(
Show(collection, {}, [], default_season='INVALID'),
EpisodeIdentifier(1, 1)
) is None
#
# Season
#
def test_season_absolute_number_required():
mapper = ShowMapper(service)
show = Show(collection, {}, [])
show.seasons['a'] = Season(collection, show, 'a')
with pytest.raises(AbsoluteNumberRequiredError):
mapper.match(show, EpisodeIdentifier(1, 1))
def test_season_invalid_default_season():
mapper = ShowMapper(service)
show = Show(collection, {}, [])
show.seasons['1'] = Season(collection, show, '1', default_season='INVALID')
assert mapper.match(show, EpisodeIdentifier(1, 1)) is None
def test_season_invalid_match():
mapper = ShowMapper(service)
show = Show(collection, {}, [])
show.seasons['1'] = Season(collection, show, '1')
assert mapper.match(show, EpisodeIdentifier(1, 1)) is None
#
# Episode
#
def test_episode_invalid_mapping_season():
mapper = ShowMapper(service)
show = Show(collection, {}, [])
show.seasons['1'] = Season(collection, show, '1')
show.seasons['1'].episodes['1'] = Episode(collection, show.seasons['1'], '1')
show.seasons['1'].episodes['1'].mappings = [
EpisodeMapping(collection, show.seasons['1'].episodes['1'], 'INVALID', '1')
]
assert mapper.match(show, EpisodeIdentifier(1, 1)) is None
def test_episode_invalid_mapping_episode():
mapper = ShowMapper(service)
show = Show(collection, {}, [])
show.seasons['1'] = Season(collection, show, '1')
show.seasons['1'].episodes['1'] = Episode(collection, show.seasons['1'], '1')
show.seasons['1'].episodes['1'].mappings = [
EpisodeMapping(collection, show.seasons['1'].episodes['1'], '1', 'INVALID')
]
assert mapper.match(show, EpisodeIdentifier(1, 1)) is None
def test_episode_invalid_match():
mapper = ShowMapper(service)
show = Show(collection, {}, [])
show.seasons['1'] = Season(collection, show, '1')
show.seasons['1'].episodes['1'] = Episode(collection, show.seasons['1'], '1')
show.seasons['1'].episodes['1'].mappings = [
EpisodeMapping(collection, show.seasons['1'].episodes['1'], '1', '1')
]
assert mapper.match(show, EpisodeIdentifier(1, 1)) is None
| en | 0.905739 | # # Show # # # Season # # # Episode # | 2.221569 | 2 |
v0/aia_eis_v0/goa/physic_based/multi_verse_optimizer/multi_verse_opt_0.py | DreamBoatOve/aia_eis | 1 | 6620308 | <gh_stars>1-10
import math
import random
import copy
def normalize(nums_list, type = 2):
num_sum = sum([pow(num, type) for num in nums_list])
return [num / math.sqrt(num_sum) for num in nums_list]
class MVO_0:
class Universe:
def __init__(self, limits_list, fitness_function):
self.limits_list = limits_list
self.fitness_function = fitness_function
self.uni_objs_list = [random.uniform(limit[0], limit[1]) for limit in self.limits_list]
self.infl_rate = fitness_function(self.uni_objs_list)
def update(self):
# Check the updated universe is in boundary. If not, make it in the boundary again
for obj_index, uni_obj in enumerate(self.uni_objs_list):
if uni_obj > self.limits_list[obj_index][1]:
self.uni_objs_list[obj_index] = self.limits_list[obj_index][1]
elif uni_obj < self.limits_list[obj_index][0]:
self.uni_objs_list[obj_index] = self.limits_list[obj_index][0]
self.infl_rate = self.fitness_function(self.uni_objs_list)
def __init__(self, iter_time, universe_num, limits_list, fitness_function):
self.iter_time = iter_time
self.universe_num = universe_num
self.limits_list = limits_list
self.fitness_function = fitness_function
# Initialize the universes
self.universes_list = [self.Universe(self.limits_list, self.fitness_function) for i in range(self.universe_num)]
# Initialize the global best universe
self.global_best_universe = self.Universe(limits_list = self.limits_list, fitness_function = fitness_function)
self.global_best_universe.infl_rate = float('inf')
def search_best_infl_rate(self):
self.sorted_universes_list = sorted(self.universes_list, key=lambda uni: uni.infl_rate, reverse=False)
current_best_universe = self.sorted_universes_list[0]
if current_best_universe.infl_rate < self.global_best_universe.infl_rate:
self.global_best_universe = copy.deepcopy(current_best_universe)
self.normalized_uni_infl_rate = normalize([universe.infl_rate for universe in self.sorted_universes_list])
def roulette_wheel_select_white_hole(self):
# Stick to the original thought, white hole with higher inflation rate
sum_normalized_uni_infl_rate = sum(self.normalized_uni_infl_rate)
random_pointer = random.uniform(0, sum_normalized_uni_infl_rate)
current_pointer = 0.0
for index, uni_infl_rate in enumerate(self.normalized_uni_infl_rate):
current_pointer += uni_infl_rate
if current_pointer > random_pointer:
return index
def inflate(self):
current_best_universes_list = []
for iter in range(self.iter_time):
# WEP: wormhole exist probability, eq 3.3
WEP = 0.2 + iter * (1 - 0.2) / self.iter_time
# TDR: Travelling distance rate, eq 3.4
TDR = 1 - pow(iter, 1/6) / pow(self.iter_time, 1/6)
self.search_best_infl_rate()
current_best_universes_list.append(self.global_best_universe)
for uni_index in range(self.universe_num):
for obj_index in range(len(self.limits_list)):
# Exploration:For each dimension, we explore first. Select a bad choice (white hole with high inflation rate) to sabotage the good ones for more wider search space
r1 = random.random()
# print('r1 = ',r1)
if r1 < self.normalized_uni_infl_rate[uni_index]:
white_hole_index = self.roulette_wheel_select_white_hole()
self.sorted_universes_list[uni_index].uni_objs_list[obj_index] = self.sorted_universes_list[white_hole_index].uni_objs_list[obj_index]
# Exploitation: make each universe similar to the best one. Along with the increase of WEP, its chance of moving towards the best universe is greater
r2 = random.random()
# print('r2 = ', r2)
if r2 < WEP:
r3 = random.random()
r4 = random.random()
# print('r3 =',r3, 'r4 =', r4)
boundary_min = self.limits_list[obj_index][0]
boundary_max = self.limits_list[obj_index][1]
if r3 < 0.5:
self.sorted_universes_list[uni_index].uni_objs_list[obj_index] = self.global_best_universe.uni_objs_list[obj_index] + TDR * (boundary_max - boundary_min) * r4
else:
self.sorted_universes_list[uni_index].uni_objs_list[obj_index] = self.global_best_universe.uni_objs_list[obj_index] - TDR * (boundary_max - boundary_min) * r4
# After the current iteration, update the inflation rate
for uni_index in range(self.universe_num):
self.sorted_universes_list[uni_index].update()
return current_best_universes_list
if __name__ == '__main__':
iter_time = 500
universe_num = 600
dim = 30
f1_limits_list = [[-100, 100] for i in range(dim)]
from GA_pack.fittness_functions.f1 import f1
f1_fitness_function = f1
mvo = MVO_0(iter_time, universe_num, limits_list = f1_limits_list, fitness_function = f1_fitness_function)
current_best_universes_list = mvo.inflate()
global_best_univese = mvo.global_best_universe
print('Best position:', global_best_univese.uni_objs_list)
print('Found minimum of the f1 function', global_best_univese.infl_rate)
# Draw the best universe in each iteration.
iter_list = [i for i in range(iter_time)]
infl_rate_list = [universe.infl_rate for universe in current_best_universes_list]
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
line1, = ax.plot(iter_list, infl_rate_list, label='Iteration {0}\nUniverse number {1}\nDimension {2}'.format(iter_time, universe_num, dim))
line1.set_dashes([2, 2, 10, 2]) # 2pt line, 2pt break, 10pt line, 2pt break
ax.legend()
plt.xlabel('Iteration times')
plt.ylabel('Inflation rate')
plt.title('Search the minimum of f1 = sum(Xi ^ 2)')
plt.show()
| import math
import random
import copy
def normalize(nums_list, type = 2):
num_sum = sum([pow(num, type) for num in nums_list])
return [num / math.sqrt(num_sum) for num in nums_list]
class MVO_0:
class Universe:
def __init__(self, limits_list, fitness_function):
self.limits_list = limits_list
self.fitness_function = fitness_function
self.uni_objs_list = [random.uniform(limit[0], limit[1]) for limit in self.limits_list]
self.infl_rate = fitness_function(self.uni_objs_list)
def update(self):
# Check the updated universe is in boundary. If not, make it in the boundary again
for obj_index, uni_obj in enumerate(self.uni_objs_list):
if uni_obj > self.limits_list[obj_index][1]:
self.uni_objs_list[obj_index] = self.limits_list[obj_index][1]
elif uni_obj < self.limits_list[obj_index][0]:
self.uni_objs_list[obj_index] = self.limits_list[obj_index][0]
self.infl_rate = self.fitness_function(self.uni_objs_list)
def __init__(self, iter_time, universe_num, limits_list, fitness_function):
self.iter_time = iter_time
self.universe_num = universe_num
self.limits_list = limits_list
self.fitness_function = fitness_function
# Initialize the universes
self.universes_list = [self.Universe(self.limits_list, self.fitness_function) for i in range(self.universe_num)]
# Initialize the global best universe
self.global_best_universe = self.Universe(limits_list = self.limits_list, fitness_function = fitness_function)
self.global_best_universe.infl_rate = float('inf')
def search_best_infl_rate(self):
self.sorted_universes_list = sorted(self.universes_list, key=lambda uni: uni.infl_rate, reverse=False)
current_best_universe = self.sorted_universes_list[0]
if current_best_universe.infl_rate < self.global_best_universe.infl_rate:
self.global_best_universe = copy.deepcopy(current_best_universe)
self.normalized_uni_infl_rate = normalize([universe.infl_rate for universe in self.sorted_universes_list])
def roulette_wheel_select_white_hole(self):
# Stick to the original thought, white hole with higher inflation rate
sum_normalized_uni_infl_rate = sum(self.normalized_uni_infl_rate)
random_pointer = random.uniform(0, sum_normalized_uni_infl_rate)
current_pointer = 0.0
for index, uni_infl_rate in enumerate(self.normalized_uni_infl_rate):
current_pointer += uni_infl_rate
if current_pointer > random_pointer:
return index
def inflate(self):
current_best_universes_list = []
for iter in range(self.iter_time):
# WEP: wormhole exist probability, eq 3.3
WEP = 0.2 + iter * (1 - 0.2) / self.iter_time
# TDR: Travelling distance rate, eq 3.4
TDR = 1 - pow(iter, 1/6) / pow(self.iter_time, 1/6)
self.search_best_infl_rate()
current_best_universes_list.append(self.global_best_universe)
for uni_index in range(self.universe_num):
for obj_index in range(len(self.limits_list)):
# Exploration:For each dimension, we explore first. Select a bad choice (white hole with high inflation rate) to sabotage the good ones for more wider search space
r1 = random.random()
# print('r1 = ',r1)
if r1 < self.normalized_uni_infl_rate[uni_index]:
white_hole_index = self.roulette_wheel_select_white_hole()
self.sorted_universes_list[uni_index].uni_objs_list[obj_index] = self.sorted_universes_list[white_hole_index].uni_objs_list[obj_index]
# Exploitation: make each universe similar to the best one. Along with the increase of WEP, its chance of moving towards the best universe is greater
r2 = random.random()
# print('r2 = ', r2)
if r2 < WEP:
r3 = random.random()
r4 = random.random()
# print('r3 =',r3, 'r4 =', r4)
boundary_min = self.limits_list[obj_index][0]
boundary_max = self.limits_list[obj_index][1]
if r3 < 0.5:
self.sorted_universes_list[uni_index].uni_objs_list[obj_index] = self.global_best_universe.uni_objs_list[obj_index] + TDR * (boundary_max - boundary_min) * r4
else:
self.sorted_universes_list[uni_index].uni_objs_list[obj_index] = self.global_best_universe.uni_objs_list[obj_index] - TDR * (boundary_max - boundary_min) * r4
# After the current iteration, update the inflation rate
for uni_index in range(self.universe_num):
self.sorted_universes_list[uni_index].update()
return current_best_universes_list
if __name__ == '__main__':
iter_time = 500
universe_num = 600
dim = 30
f1_limits_list = [[-100, 100] for i in range(dim)]
from GA_pack.fittness_functions.f1 import f1
f1_fitness_function = f1
mvo = MVO_0(iter_time, universe_num, limits_list = f1_limits_list, fitness_function = f1_fitness_function)
current_best_universes_list = mvo.inflate()
global_best_univese = mvo.global_best_universe
print('Best position:', global_best_univese.uni_objs_list)
print('Found minimum of the f1 function', global_best_univese.infl_rate)
# Draw the best universe in each iteration.
iter_list = [i for i in range(iter_time)]
infl_rate_list = [universe.infl_rate for universe in current_best_universes_list]
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
line1, = ax.plot(iter_list, infl_rate_list, label='Iteration {0}\nUniverse number {1}\nDimension {2}'.format(iter_time, universe_num, dim))
line1.set_dashes([2, 2, 10, 2]) # 2pt line, 2pt break, 10pt line, 2pt break
ax.legend()
plt.xlabel('Iteration times')
plt.ylabel('Inflation rate')
plt.title('Search the minimum of f1 = sum(Xi ^ 2)')
plt.show() | en | 0.788212 | # Check the updated universe is in boundary. If not, make it in the boundary again # Initialize the universes # Initialize the global best universe # Stick to the original thought, white hole with higher inflation rate # WEP: wormhole exist probability, eq 3.3 # TDR: Travelling distance rate, eq 3.4 # Exploration:For each dimension, we explore first. Select a bad choice (white hole with high inflation rate) to sabotage the good ones for more wider search space # print('r1 = ',r1) # Exploitation: make each universe similar to the best one. Along with the increase of WEP, its chance of moving towards the best universe is greater # print('r2 = ', r2) # print('r3 =',r3, 'r4 =', r4) # After the current iteration, update the inflation rate # Draw the best universe in each iteration. # 2pt line, 2pt break, 10pt line, 2pt break | 3.008215 | 3 |
RsNet/worker.py | gehuangyi20/random_spiking | 1 | 6620309 | ## worker.py -- evaluation code
##
## Copyright (C) 2017, <NAME> <<EMAIL>>.
##
## This program is licenced under the BSD 2-Clause licence,
## contained in the LICENCE file in this directory.
import matplotlib
from scipy.stats import entropy
from numpy.linalg import norm
from matplotlib.ticker import FuncFormatter
from tensorflow.keras.models import Sequential, load_model
from tensorflow.keras.activations import softmax
import numpy as np
import os
import tensorflow as tf
from tensorflow.keras.layers import Lambda
from RsNet.tf_config import CHANNELS_LAST
from utils import load_obj, load_model_idx, load_cache, save_cache
matplotlib.use('Agg')
class AEDetector:
def __init__(self, path, p=1, verbose=1):
"""
Error based detector.
Marks examples for filtering decisions.
path: Path to the autoencoder used.
p: Distance measure to use.
"""
self.model = load_model(path)
if verbose:
self.model.summary()
self.path = path
self.p = p
def mark(self, X, data_format=CHANNELS_LAST):
if self.model.inputs[0].shape[1:] != np.shape(X)[1:]:
if data_format == CHANNELS_LAST:
X = np.transpose(X, [0, 3, 1, 2])
else:
X = np.transpose(X, [0, 2, 3, 1])
diff = np.abs(X - self.model.predict(X))
marks = np.mean(np.power(diff, self.p), axis=(1, 2, 3))
return marks
def tf_mark(self, X, data_format=CHANNELS_LAST):
if self.model.inputs[0].shape[1:] != np.shape(X)[1:]:
if data_format == CHANNELS_LAST:
X = tf.transpose(X, [0, 3, 1, 2])
else:
X = tf.transpose(X, [0, 2, 3, 1])
diff = tf.abs(X - self.model(X))
marks = tf.reduce_mean(tf.pow(diff, self.p), axis=(1, 2, 3))
return marks
def layer(self, X, name, data_format=CHANNELS_LAST):
def _layer(_x, model, p):
if self.model.inputs[0].shape[1:] != np.shape(_x)[1:]:
if data_format == CHANNELS_LAST:
_x = tf.transpose(_x, [0, 3, 1, 2])
else:
_x = tf.transpose(_x, [0, 2, 3, 1])
diff = tf.abs(_x - model(_x))
marks = tf.reduce_mean(tf.pow(diff, p), axis=(1, 2, 3))
return marks
return Lambda(lambda x: _layer(x, self.model, self.p), name=name)(X)
def print(self):
return "AEDetector:" + self.path.split("/")[-1]
class IdReformer:
def __init__(self, path="IdentityFunction"):
"""
Identity reformer.
Reforms an example to itself.
"""
self.path = path
self.heal = lambda X: X
self.heal_tf = lambda X: X
def print(self):
return "IdReformer:" + self.path
class SimpleReformer:
def __init__(self, path, verbose=1):
"""
Reformer.
Reforms examples with autoencoder. Action of reforming is called heal.
path: Path to the autoencoder used.
"""
self.model = load_model(path)
if verbose:
self.model.summary()
self.path = path
def heal(self, X):
X = self.model.predict(X)
return np.clip(X, 0.0, 1.0)
def heal_tf(self, X):
X = self.model(X)
return tf.clip_by_value(X, 0.0, 1.0)
def print(self):
return "SimpleReformer:" + self.path.split("/")[-1]
def JSD(P, Q):
_P = P / norm(P, ord=1)
_Q = Q / norm(Q, ord=1)
_M = 0.5 * (_P + _Q)
return 0.5 * (entropy(_P, _M) + entropy(_Q, _M))
def JSD_tf(P, Q):
_P = P / tf.expand_dims(tf.norm(P, ord=1, axis=1), axis=1)
_Q = Q / tf.expand_dims(tf.norm(Q, ord=1, axis=1), axis=1)
_M = 0.5 * (_P + _Q)
def kl(p, q):
return tf.reduce_sum(p * tf.log(p / q), axis=1)
return 0.5 * (kl(_P, _M) + kl(_Q, _M))
class DBDetector:
def __init__(self, reconstructor, prober, classifier, option="jsd", T=1):
"""
Divergence-Based Detector.
reconstructor: One autoencoder.
prober: Another autoencoder.
classifier: Classifier object.
option: Measure of distance, jsd as default.
T: Temperature to soften the classification decision.
"""
self.prober = prober
self.reconstructor = reconstructor
self.classifier = classifier
self.option = option
self.T = T
def mark(self, X, data_format):
return self.mark_jsd(X)
def mark_jsd(self, X):
Xp = self.prober.heal(X)
Xr = self.reconstructor.heal(X)
Pp = self.classifier.classify(Xp, option="prob", T=self.T)
Pr = self.classifier.classify(Xr, option="prob", T=self.T)
marks = [(JSD(Pp[i], Pr[i])) for i in range(len(Pr))]
return np.array(marks)
def tf_mark(self, X, data_format):
Xp = self.prober.heal_tf(X)
Xr = self.reconstructor.heal_tf(X)
Pp = self.classifier.classify_tf(Xp, option="prob", T=self.T)
Pr = self.classifier.classify_tf(Xr, option="prob", T=self.T)
marks = JSD_tf(Pp, Pr)
return marks
def print(self):
return "Divergence-Based Detector"
class Classifier:
def __init__(self, classifier_path, model_class, data_format, model=None):
"""
Keras classifier wrapper.
Note that the wrapped classifier should spit logits as output.
classifier_path: Path to Keras classifier file.
"""
self.path = classifier_path
self.model = model_class(classifier_path, output_logits=True,
input_data_format=data_format, data_format=data_format).model \
if model is None else model.model
self.softmax = Sequential()
self.softmax.add(Lambda(lambda X: softmax(X, axis=1), input_shape=(10,)))
def classify(self, X, option="logit", T=1):
if option == "logit":
return self.model.predict(X)
if option == "prob":
logits = self.model.predict(X)/T
return self.softmax.predict(logits)
def classify_tf(self, X, option="logit", T=1):
if option == "logit":
return self.model(X)
if option == "prob":
logits = self.model(X) / T
return self.softmax(logits)
def print(self):
return "Classifier:"+self.path.split("/")[-1]
class Operator:
def __init__(self, data, classifier, det_dict, reformer, data_format):
"""
Operator.
Describes the classification problem and defense.
data: Standard problem dataset. Including train, test, and validation.
classifier: Target classifier.
reformer: Reformer of defense.
det_dict: Detector(s) of defense.
"""
self.data = data
self.classifier = classifier
self.det_dict = det_dict
self.reformer = reformer
self.data_format = data_format
self.normal = self.operate(AttackData(self.data.test_data,
np.argmax(self.data.test_labels, axis=1), "Normal",
input_data_format=data_format, data_format=data_format))
def get_thrs(self, drop_rate):
"""
Get filtering threshold by marking validation set.
"""
thrs = dict()
for name, detector in self.det_dict.items():
num = int(len(self.data.validation_data) * drop_rate[name])
marks = detector.mark(self.data.validation_data, self.data_format)
marks = np.sort(marks)
thrs[name] = marks[-num]
return thrs
def operate(self, untrusted_obj):
"""
For untrusted input(normal or adversarial), classify original input and
reformed input. Classifier is unaware of the source of input.
untrusted_obj: Input data.
"""
X = untrusted_obj.data
Y_true = untrusted_obj.labels
X_prime = self.reformer.heal(X)
Y = np.argmax(self.classifier.classify(X), axis=1)
Y_judgement = (Y == Y_true[:len(X_prime)])
Y_prime = np.argmax(self.classifier.classify(X_prime), axis=1)
Y_prime_judgement = (Y_prime == Y_true[:len(X_prime)])
return np.array(list(zip(Y_judgement, Y_prime_judgement)))
def filter(self, X, thrs):
"""
untrusted_obj: Untrusted input to test against.
thrs: Thresholds.
return:
all_pass: Index of examples that passed all detectors.
collector: Number of examples that escaped each detector.
"""
collector = dict()
all_pass = np.array(range(10000))
for name, detector in self.det_dict.items():
marks = detector.mark(X, self.data_format)
idx_pass = np.argwhere(marks < thrs[name])
collector[name] = len(idx_pass)
all_pass = np.intersect1d(all_pass, idx_pass)
return all_pass, collector
def print(self):
components = [self.reformer, self.classifier]
return " ".join(map(lambda obj: getattr(obj, "print")(), components))
class AttackData:
def __init__(self, examples, labels, name="", directory='./attack_data/',
input_data_format=CHANNELS_LAST, data_format=CHANNELS_LAST):
"""
Input data wrapper. May be normal or adversarial.
examples: Path or object of input examples.
labels: Ground truth labels.
"""
if isinstance(examples, str):
self.data = load_obj(examples, directory=directory)
else:
self.data = examples
if input_data_format != data_format:
if data_format == CHANNELS_LAST:
self.data = np.transpose(self.data, [0, 2, 3, 1])
else:
self.data = np.transpose(self.data, [0, 3, 1, 2])
self.labels = labels
self.name = name
def print(self):
return "Attack:"+self.name
class Evaluator:
def __init__(self, operator, untrusted_data, graph_dir="./graph", data_format=CHANNELS_LAST):
"""
Evaluator.
For strategy described by operator, conducts tests on untrusted input.
Mainly stats and plotting code. Most methods omitted for clarity.
operator: Operator object.
untrusted_data: Input data to test against.
graph_dir: Where to spit the graphs.
"""
self.operator = operator
self.untrusted_data = untrusted_data
self.graph_dir = graph_dir
self.data_format = data_format
self.data_package = operator.operate(untrusted_data)
def bind_operator(self, operator):
self.operator = operator
self.data_package = operator.operate(self.untrusted_data)
def load_data(self, data):
self.untrusted_data = data
self.data_package = self.operator.operate(self.untrusted_data)
def get_normal_acc(self, normal_all_pass):
"""
Break down of who does what in defense. Accuracy of defense on normal
input.
both: Both detectors and reformer take effect
det_only: detector(s) take effect
ref_only: Only reformer takes effect
none: Attack effect with no defense
"""
normal_tups = self.operator.normal
num_normal = len(normal_tups)
filtered_normal_tups = normal_tups[normal_all_pass]
both_acc = sum(1 for _, XpC in filtered_normal_tups if XpC)/num_normal
det_only_acc = sum(1 for XC, XpC in filtered_normal_tups if XC)/num_normal
ref_only_acc = sum([1 for _, XpC in normal_tups if XpC])/num_normal
none_acc = sum([1 for XC, _ in normal_tups if XC])/num_normal
return both_acc, det_only_acc, ref_only_acc, none_acc
def get_attack_acc(self, attack_pass):
attack_tups = self.data_package
num_untrusted = len(attack_tups)
filtered_attack_tups = attack_tups[attack_pass]
both_acc = 1 - sum(1 for _, XpC in filtered_attack_tups if not XpC)/num_untrusted
det_only_acc = 1 - sum(1 for XC, XpC in filtered_attack_tups if not XC)/num_untrusted
ref_only_acc = sum([1 for _, XpC in attack_tups if XpC])/num_untrusted
none_acc = sum([1 for XC, _ in attack_tups if XC])/num_untrusted
return both_acc, det_only_acc, ref_only_acc, none_acc
def plot_various_confidences(self, graph_name, drop_rate, data_format,
Y, directory='./attack_data/',
confs=(0.0, 10.0, 20.0, 30.0, 40.0),
get_attack_data_name=lambda c: "example_carlini_"+str(c)):
"""
Test defense performance against Carlini L2 attack of various confidences.
graph_name: Name of graph file.
drop_rate: How many normal examples should each detector drops?
idx_file: Index of adversarial examples in standard test set.
confs: A series of confidence to test against.
get_attack_data_name: Function mapping confidence to corresponding file.
"""
import matplotlib.pyplot as plt
import pylab
pylab.rcParams['figure.figsize'] = 6, 4
fig = plt.figure(1, (6, 4))
ax = fig.add_subplot(1, 1, 1)
det_only = []
ref_only = []
both = []
none = []
print("Drop Rate:", drop_rate)
thrs = self.operator.get_thrs(drop_rate)
all_pass, _detector = self.operator.filter(self.operator.data.test_data, thrs)
all_on_acc, _, _, _ = self.get_normal_acc(all_pass)
print(_detector)
print("Classification accuracy with all defense on:", all_on_acc)
for confidence in confs:
f = get_attack_data_name(confidence)
attack_data = AttackData(f, Y, "Carlini L2 " + str(confidence), directory=directory,
input_data_format=CHANNELS_LAST, data_format=data_format)
# compute number of all input data and filter out valid data
total = len(attack_data.data)
valid_adv_idx = np.argwhere(np.sum(attack_data.data, axis=(1, 2, 3)) > [0] * total).flatten()
attack_data.data = attack_data.data[valid_adv_idx]
attack_data.labels = attack_data.labels[valid_adv_idx]
self.load_data(attack_data)
print("Confidence:", confidence)
valid_adv_len = len(valid_adv_idx)
print("valid attack %d/%d" % (valid_adv_len, total))
all_pass, detector_breakdown = self.operator.filter(self.untrusted_data.data, thrs)
both_acc, det_only_acc, ref_only_acc, none_acc = self.get_attack_acc(all_pass)
print(detector_breakdown)
both.append(both_acc)
det_only.append(det_only_acc)
ref_only.append(ref_only_acc)
none.append(none_acc)
size = 2.5
plt.plot(confs, none, c="green", label="No fefense", marker="x", markersize=size)
plt.plot(confs, det_only, c="orange", label="With detector", marker="o", markersize=size)
plt.plot(confs, ref_only, c="blue", label="With reformer", marker="^", markersize=size)
plt.plot(confs, both, c="red", label="With detector & reformer", marker="s", markersize=size)
pylab.legend(loc='lower left', bbox_to_anchor=(0.02, 0.1), prop={'size':8})
plt.grid(linestyle='dotted')
plt.xlabel(r"Confidence in Carlini $L^2$ attack")
plt.ylabel("Classification accuracy")
plt.xlim(min(confs)-1.0, max(confs)+1.0)
plt.ylim(-0.05, 1.05)
ax.yaxis.set_major_formatter(FuncFormatter('{0:.0%}'.format))
save_path = os.path.join(self.graph_dir, graph_name+".pdf")
plt.savefig(save_path)
plt.clf()
def print(self):
return " ".join([self.operator.print(), self.untrusted_data.print()])
def build_detector(detector_model_dir, detector_model_names, save_model_name, save_model_dir, model_path,
MODEL, det_model, data, data_format, is_det_joint, model_idx, gpu_count=1):
det_dict = {}
det_set = {}
det_idx_set = {}
dropout_rate_set = {}
det_gpu_idx = {}
for val in detector_model_names:
if val == '':
continue
cur_det_name, cur_p, cur_det_type, cur_dropout_rate, cur_model_id = val.split('/')
cur_model_id = int(cur_model_id)
cur_det_path = os.path.join(detector_model_dir, cur_det_name)
cur_detector = {
"p": cur_p,
"type": cur_det_type,
"dropout_rate": cur_dropout_rate
}
det_dict[cur_det_name] = cur_detector
if type(det_model) is list:
cur_det_model = det_model[cur_model_id]
cur_model_path = os.path.join(save_model_dir, save_model_name[cur_model_id])
cur_det_idx = model_idx[cur_model_id]
else:
cur_det_model = det_model
cur_model_path = model_path
cur_det_idx = model_idx
default_det_idx = cur_det_idx
with tf.device('/gpu:' + str(cur_model_id % gpu_count)):
# build detector
print("# build detector: ", cur_det_name)
print("type:", cur_det_type)
print("p:", cur_p)
print("drop_rate:", cur_dropout_rate)
if cur_det_type == 'AED':
cur_detector = AEDetector(cur_det_path, p=int(cur_p))
cur_det_idx = load_model_idx(cur_det_path)
elif cur_det_type == "DBD":
id_reformer = IdReformer()
print("# build reformer", cur_det_name)
cur_reformer_t = SimpleReformer(cur_det_path)
classifier = Classifier(cur_model_path, MODEL,
data_format=data_format, model=cur_det_model)
cur_detector = DBDetector(reconstructor=id_reformer, prober=cur_reformer_t,
classifier=classifier, T=int(cur_p))
cur_det_idx = load_model_idx(cur_det_path)
if cur_det_idx is None:
cur_det_idx = default_det_idx
det_idx_set[cur_det_name] = cur_det_idx['validate']
dropout_rate_set[cur_det_name] = float(cur_dropout_rate)
det_set[cur_det_name] = cur_detector
det_gpu_idx[cur_det_name] = cur_model_id % gpu_count
# compute thrs
thrs_set = {}
det_info = {
"model": save_model_name,
"model_dir": save_model_dir,
"det": det_dict,
"det_dir": detector_model_dir,
"joint_thrs": is_det_joint
}
cache_path = os.path.join(detector_model_dir, "cache")
if is_det_joint:
marks_set = []
num = 0
cache = load_cache(det_info, cache_path)
if cache is None:
cache_data = {}
for cur_det_name, cur_det in det_set.items():
validation_data = data.train_data_orig[det_idx_set[cur_det_name]]
num = int(len(validation_data) * dropout_rate_set[cur_det_name])
marks = cur_det.mark(validation_data, data_format=data_format)
marks_set.append(marks)
marks = np.sort(marks)
cache_data[cur_det_name] = marks[-num]
print("compute thrs for model #", cur_det_name, "#:", marks[-num])
marks_set = np.transpose(marks_set)
marks_max = np.max(marks_set, axis=1)
marks_max = np.sort(marks_max)
max_thrs = marks_max[-num]
cache_data['thrs'] = max_thrs
if len(det_set) > 0:
hash_id = save_cache(det_info, cache_data, cache_path)
print("save cache:", hash_id)
else:
print("hit cache:", cache['hash_id'])
cache_data = cache['data']
for cur_det_name, cur_det in det_set.items():
print("compute thrs for model #", cur_det_name, "#:", cache_data[cur_det_name])
max_thrs = cache_data['thrs']
for cur_det_name, cur_det in det_set.items():
thrs_set[cur_det_name] = max_thrs
print("use joint thrs:", max_thrs)
else:
cache = load_cache(det_info, cache_path)
if cache is None:
cache_data = {}
for cur_det_name, cur_det in det_set.items():
validation_data = data.train_data_orig[det_idx_set[cur_det_name]]
num = int(len(validation_data) * dropout_rate_set[cur_det_name])
marks = cur_det.mark(validation_data, data_format=data_format)
marks = np.sort(marks)
thrs_set[cur_det_name] = marks[-num]
cache_data[cur_det_name] = marks[-num]
print("compute thrs for model #", cur_det_name, "#:", marks[-num])
if len(det_set) > 0:
hash_id = save_cache(det_info, cache_data, cache_path)
print("save cache:", hash_id)
else:
print("hit cache:", cache['hash_id'])
cache_data = cache['data']
for cur_det_name, cur_det in det_set.items():
thrs_set[cur_det_name] = cache_data[cur_det_name]
print("compute thrs for model #", cur_det_name, "#:", cache_data[cur_det_name])
return det_set, thrs_set, det_gpu_idx | ## worker.py -- evaluation code
##
## Copyright (C) 2017, <NAME> <<EMAIL>>.
##
## This program is licenced under the BSD 2-Clause licence,
## contained in the LICENCE file in this directory.
import matplotlib
from scipy.stats import entropy
from numpy.linalg import norm
from matplotlib.ticker import FuncFormatter
from tensorflow.keras.models import Sequential, load_model
from tensorflow.keras.activations import softmax
import numpy as np
import os
import tensorflow as tf
from tensorflow.keras.layers import Lambda
from RsNet.tf_config import CHANNELS_LAST
from utils import load_obj, load_model_idx, load_cache, save_cache
matplotlib.use('Agg')
class AEDetector:
def __init__(self, path, p=1, verbose=1):
"""
Error based detector.
Marks examples for filtering decisions.
path: Path to the autoencoder used.
p: Distance measure to use.
"""
self.model = load_model(path)
if verbose:
self.model.summary()
self.path = path
self.p = p
def mark(self, X, data_format=CHANNELS_LAST):
if self.model.inputs[0].shape[1:] != np.shape(X)[1:]:
if data_format == CHANNELS_LAST:
X = np.transpose(X, [0, 3, 1, 2])
else:
X = np.transpose(X, [0, 2, 3, 1])
diff = np.abs(X - self.model.predict(X))
marks = np.mean(np.power(diff, self.p), axis=(1, 2, 3))
return marks
def tf_mark(self, X, data_format=CHANNELS_LAST):
if self.model.inputs[0].shape[1:] != np.shape(X)[1:]:
if data_format == CHANNELS_LAST:
X = tf.transpose(X, [0, 3, 1, 2])
else:
X = tf.transpose(X, [0, 2, 3, 1])
diff = tf.abs(X - self.model(X))
marks = tf.reduce_mean(tf.pow(diff, self.p), axis=(1, 2, 3))
return marks
def layer(self, X, name, data_format=CHANNELS_LAST):
def _layer(_x, model, p):
if self.model.inputs[0].shape[1:] != np.shape(_x)[1:]:
if data_format == CHANNELS_LAST:
_x = tf.transpose(_x, [0, 3, 1, 2])
else:
_x = tf.transpose(_x, [0, 2, 3, 1])
diff = tf.abs(_x - model(_x))
marks = tf.reduce_mean(tf.pow(diff, p), axis=(1, 2, 3))
return marks
return Lambda(lambda x: _layer(x, self.model, self.p), name=name)(X)
def print(self):
return "AEDetector:" + self.path.split("/")[-1]
class IdReformer:
def __init__(self, path="IdentityFunction"):
"""
Identity reformer.
Reforms an example to itself.
"""
self.path = path
self.heal = lambda X: X
self.heal_tf = lambda X: X
def print(self):
return "IdReformer:" + self.path
class SimpleReformer:
def __init__(self, path, verbose=1):
"""
Reformer.
Reforms examples with autoencoder. Action of reforming is called heal.
path: Path to the autoencoder used.
"""
self.model = load_model(path)
if verbose:
self.model.summary()
self.path = path
def heal(self, X):
X = self.model.predict(X)
return np.clip(X, 0.0, 1.0)
def heal_tf(self, X):
X = self.model(X)
return tf.clip_by_value(X, 0.0, 1.0)
def print(self):
return "SimpleReformer:" + self.path.split("/")[-1]
def JSD(P, Q):
_P = P / norm(P, ord=1)
_Q = Q / norm(Q, ord=1)
_M = 0.5 * (_P + _Q)
return 0.5 * (entropy(_P, _M) + entropy(_Q, _M))
def JSD_tf(P, Q):
_P = P / tf.expand_dims(tf.norm(P, ord=1, axis=1), axis=1)
_Q = Q / tf.expand_dims(tf.norm(Q, ord=1, axis=1), axis=1)
_M = 0.5 * (_P + _Q)
def kl(p, q):
return tf.reduce_sum(p * tf.log(p / q), axis=1)
return 0.5 * (kl(_P, _M) + kl(_Q, _M))
class DBDetector:
def __init__(self, reconstructor, prober, classifier, option="jsd", T=1):
"""
Divergence-Based Detector.
reconstructor: One autoencoder.
prober: Another autoencoder.
classifier: Classifier object.
option: Measure of distance, jsd as default.
T: Temperature to soften the classification decision.
"""
self.prober = prober
self.reconstructor = reconstructor
self.classifier = classifier
self.option = option
self.T = T
def mark(self, X, data_format):
return self.mark_jsd(X)
def mark_jsd(self, X):
Xp = self.prober.heal(X)
Xr = self.reconstructor.heal(X)
Pp = self.classifier.classify(Xp, option="prob", T=self.T)
Pr = self.classifier.classify(Xr, option="prob", T=self.T)
marks = [(JSD(Pp[i], Pr[i])) for i in range(len(Pr))]
return np.array(marks)
def tf_mark(self, X, data_format):
Xp = self.prober.heal_tf(X)
Xr = self.reconstructor.heal_tf(X)
Pp = self.classifier.classify_tf(Xp, option="prob", T=self.T)
Pr = self.classifier.classify_tf(Xr, option="prob", T=self.T)
marks = JSD_tf(Pp, Pr)
return marks
def print(self):
return "Divergence-Based Detector"
class Classifier:
def __init__(self, classifier_path, model_class, data_format, model=None):
"""
Keras classifier wrapper.
Note that the wrapped classifier should spit logits as output.
classifier_path: Path to Keras classifier file.
"""
self.path = classifier_path
self.model = model_class(classifier_path, output_logits=True,
input_data_format=data_format, data_format=data_format).model \
if model is None else model.model
self.softmax = Sequential()
self.softmax.add(Lambda(lambda X: softmax(X, axis=1), input_shape=(10,)))
def classify(self, X, option="logit", T=1):
if option == "logit":
return self.model.predict(X)
if option == "prob":
logits = self.model.predict(X)/T
return self.softmax.predict(logits)
def classify_tf(self, X, option="logit", T=1):
if option == "logit":
return self.model(X)
if option == "prob":
logits = self.model(X) / T
return self.softmax(logits)
def print(self):
return "Classifier:"+self.path.split("/")[-1]
class Operator:
def __init__(self, data, classifier, det_dict, reformer, data_format):
"""
Operator.
Describes the classification problem and defense.
data: Standard problem dataset. Including train, test, and validation.
classifier: Target classifier.
reformer: Reformer of defense.
det_dict: Detector(s) of defense.
"""
self.data = data
self.classifier = classifier
self.det_dict = det_dict
self.reformer = reformer
self.data_format = data_format
self.normal = self.operate(AttackData(self.data.test_data,
np.argmax(self.data.test_labels, axis=1), "Normal",
input_data_format=data_format, data_format=data_format))
def get_thrs(self, drop_rate):
"""
Get filtering threshold by marking validation set.
"""
thrs = dict()
for name, detector in self.det_dict.items():
num = int(len(self.data.validation_data) * drop_rate[name])
marks = detector.mark(self.data.validation_data, self.data_format)
marks = np.sort(marks)
thrs[name] = marks[-num]
return thrs
def operate(self, untrusted_obj):
"""
For untrusted input(normal or adversarial), classify original input and
reformed input. Classifier is unaware of the source of input.
untrusted_obj: Input data.
"""
X = untrusted_obj.data
Y_true = untrusted_obj.labels
X_prime = self.reformer.heal(X)
Y = np.argmax(self.classifier.classify(X), axis=1)
Y_judgement = (Y == Y_true[:len(X_prime)])
Y_prime = np.argmax(self.classifier.classify(X_prime), axis=1)
Y_prime_judgement = (Y_prime == Y_true[:len(X_prime)])
return np.array(list(zip(Y_judgement, Y_prime_judgement)))
def filter(self, X, thrs):
"""
untrusted_obj: Untrusted input to test against.
thrs: Thresholds.
return:
all_pass: Index of examples that passed all detectors.
collector: Number of examples that escaped each detector.
"""
collector = dict()
all_pass = np.array(range(10000))
for name, detector in self.det_dict.items():
marks = detector.mark(X, self.data_format)
idx_pass = np.argwhere(marks < thrs[name])
collector[name] = len(idx_pass)
all_pass = np.intersect1d(all_pass, idx_pass)
return all_pass, collector
def print(self):
components = [self.reformer, self.classifier]
return " ".join(map(lambda obj: getattr(obj, "print")(), components))
class AttackData:
def __init__(self, examples, labels, name="", directory='./attack_data/',
input_data_format=CHANNELS_LAST, data_format=CHANNELS_LAST):
"""
Input data wrapper. May be normal or adversarial.
examples: Path or object of input examples.
labels: Ground truth labels.
"""
if isinstance(examples, str):
self.data = load_obj(examples, directory=directory)
else:
self.data = examples
if input_data_format != data_format:
if data_format == CHANNELS_LAST:
self.data = np.transpose(self.data, [0, 2, 3, 1])
else:
self.data = np.transpose(self.data, [0, 3, 1, 2])
self.labels = labels
self.name = name
def print(self):
return "Attack:"+self.name
class Evaluator:
def __init__(self, operator, untrusted_data, graph_dir="./graph", data_format=CHANNELS_LAST):
"""
Evaluator.
For strategy described by operator, conducts tests on untrusted input.
Mainly stats and plotting code. Most methods omitted for clarity.
operator: Operator object.
untrusted_data: Input data to test against.
graph_dir: Where to spit the graphs.
"""
self.operator = operator
self.untrusted_data = untrusted_data
self.graph_dir = graph_dir
self.data_format = data_format
self.data_package = operator.operate(untrusted_data)
def bind_operator(self, operator):
self.operator = operator
self.data_package = operator.operate(self.untrusted_data)
def load_data(self, data):
self.untrusted_data = data
self.data_package = self.operator.operate(self.untrusted_data)
def get_normal_acc(self, normal_all_pass):
"""
Break down of who does what in defense. Accuracy of defense on normal
input.
both: Both detectors and reformer take effect
det_only: detector(s) take effect
ref_only: Only reformer takes effect
none: Attack effect with no defense
"""
normal_tups = self.operator.normal
num_normal = len(normal_tups)
filtered_normal_tups = normal_tups[normal_all_pass]
both_acc = sum(1 for _, XpC in filtered_normal_tups if XpC)/num_normal
det_only_acc = sum(1 for XC, XpC in filtered_normal_tups if XC)/num_normal
ref_only_acc = sum([1 for _, XpC in normal_tups if XpC])/num_normal
none_acc = sum([1 for XC, _ in normal_tups if XC])/num_normal
return both_acc, det_only_acc, ref_only_acc, none_acc
def get_attack_acc(self, attack_pass):
attack_tups = self.data_package
num_untrusted = len(attack_tups)
filtered_attack_tups = attack_tups[attack_pass]
both_acc = 1 - sum(1 for _, XpC in filtered_attack_tups if not XpC)/num_untrusted
det_only_acc = 1 - sum(1 for XC, XpC in filtered_attack_tups if not XC)/num_untrusted
ref_only_acc = sum([1 for _, XpC in attack_tups if XpC])/num_untrusted
none_acc = sum([1 for XC, _ in attack_tups if XC])/num_untrusted
return both_acc, det_only_acc, ref_only_acc, none_acc
def plot_various_confidences(self, graph_name, drop_rate, data_format,
Y, directory='./attack_data/',
confs=(0.0, 10.0, 20.0, 30.0, 40.0),
get_attack_data_name=lambda c: "example_carlini_"+str(c)):
"""
Test defense performance against Carlini L2 attack of various confidences.
graph_name: Name of graph file.
drop_rate: How many normal examples should each detector drops?
idx_file: Index of adversarial examples in standard test set.
confs: A series of confidence to test against.
get_attack_data_name: Function mapping confidence to corresponding file.
"""
import matplotlib.pyplot as plt
import pylab
pylab.rcParams['figure.figsize'] = 6, 4
fig = plt.figure(1, (6, 4))
ax = fig.add_subplot(1, 1, 1)
det_only = []
ref_only = []
both = []
none = []
print("Drop Rate:", drop_rate)
thrs = self.operator.get_thrs(drop_rate)
all_pass, _detector = self.operator.filter(self.operator.data.test_data, thrs)
all_on_acc, _, _, _ = self.get_normal_acc(all_pass)
print(_detector)
print("Classification accuracy with all defense on:", all_on_acc)
for confidence in confs:
f = get_attack_data_name(confidence)
attack_data = AttackData(f, Y, "Carlini L2 " + str(confidence), directory=directory,
input_data_format=CHANNELS_LAST, data_format=data_format)
# compute number of all input data and filter out valid data
total = len(attack_data.data)
valid_adv_idx = np.argwhere(np.sum(attack_data.data, axis=(1, 2, 3)) > [0] * total).flatten()
attack_data.data = attack_data.data[valid_adv_idx]
attack_data.labels = attack_data.labels[valid_adv_idx]
self.load_data(attack_data)
print("Confidence:", confidence)
valid_adv_len = len(valid_adv_idx)
print("valid attack %d/%d" % (valid_adv_len, total))
all_pass, detector_breakdown = self.operator.filter(self.untrusted_data.data, thrs)
both_acc, det_only_acc, ref_only_acc, none_acc = self.get_attack_acc(all_pass)
print(detector_breakdown)
both.append(both_acc)
det_only.append(det_only_acc)
ref_only.append(ref_only_acc)
none.append(none_acc)
size = 2.5
plt.plot(confs, none, c="green", label="No fefense", marker="x", markersize=size)
plt.plot(confs, det_only, c="orange", label="With detector", marker="o", markersize=size)
plt.plot(confs, ref_only, c="blue", label="With reformer", marker="^", markersize=size)
plt.plot(confs, both, c="red", label="With detector & reformer", marker="s", markersize=size)
pylab.legend(loc='lower left', bbox_to_anchor=(0.02, 0.1), prop={'size':8})
plt.grid(linestyle='dotted')
plt.xlabel(r"Confidence in Carlini $L^2$ attack")
plt.ylabel("Classification accuracy")
plt.xlim(min(confs)-1.0, max(confs)+1.0)
plt.ylim(-0.05, 1.05)
ax.yaxis.set_major_formatter(FuncFormatter('{0:.0%}'.format))
save_path = os.path.join(self.graph_dir, graph_name+".pdf")
plt.savefig(save_path)
plt.clf()
def print(self):
return " ".join([self.operator.print(), self.untrusted_data.print()])
def build_detector(detector_model_dir, detector_model_names, save_model_name, save_model_dir, model_path,
MODEL, det_model, data, data_format, is_det_joint, model_idx, gpu_count=1):
det_dict = {}
det_set = {}
det_idx_set = {}
dropout_rate_set = {}
det_gpu_idx = {}
for val in detector_model_names:
if val == '':
continue
cur_det_name, cur_p, cur_det_type, cur_dropout_rate, cur_model_id = val.split('/')
cur_model_id = int(cur_model_id)
cur_det_path = os.path.join(detector_model_dir, cur_det_name)
cur_detector = {
"p": cur_p,
"type": cur_det_type,
"dropout_rate": cur_dropout_rate
}
det_dict[cur_det_name] = cur_detector
if type(det_model) is list:
cur_det_model = det_model[cur_model_id]
cur_model_path = os.path.join(save_model_dir, save_model_name[cur_model_id])
cur_det_idx = model_idx[cur_model_id]
else:
cur_det_model = det_model
cur_model_path = model_path
cur_det_idx = model_idx
default_det_idx = cur_det_idx
with tf.device('/gpu:' + str(cur_model_id % gpu_count)):
# build detector
print("# build detector: ", cur_det_name)
print("type:", cur_det_type)
print("p:", cur_p)
print("drop_rate:", cur_dropout_rate)
if cur_det_type == 'AED':
cur_detector = AEDetector(cur_det_path, p=int(cur_p))
cur_det_idx = load_model_idx(cur_det_path)
elif cur_det_type == "DBD":
id_reformer = IdReformer()
print("# build reformer", cur_det_name)
cur_reformer_t = SimpleReformer(cur_det_path)
classifier = Classifier(cur_model_path, MODEL,
data_format=data_format, model=cur_det_model)
cur_detector = DBDetector(reconstructor=id_reformer, prober=cur_reformer_t,
classifier=classifier, T=int(cur_p))
cur_det_idx = load_model_idx(cur_det_path)
if cur_det_idx is None:
cur_det_idx = default_det_idx
det_idx_set[cur_det_name] = cur_det_idx['validate']
dropout_rate_set[cur_det_name] = float(cur_dropout_rate)
det_set[cur_det_name] = cur_detector
det_gpu_idx[cur_det_name] = cur_model_id % gpu_count
# compute thrs
thrs_set = {}
det_info = {
"model": save_model_name,
"model_dir": save_model_dir,
"det": det_dict,
"det_dir": detector_model_dir,
"joint_thrs": is_det_joint
}
cache_path = os.path.join(detector_model_dir, "cache")
if is_det_joint:
marks_set = []
num = 0
cache = load_cache(det_info, cache_path)
if cache is None:
cache_data = {}
for cur_det_name, cur_det in det_set.items():
validation_data = data.train_data_orig[det_idx_set[cur_det_name]]
num = int(len(validation_data) * dropout_rate_set[cur_det_name])
marks = cur_det.mark(validation_data, data_format=data_format)
marks_set.append(marks)
marks = np.sort(marks)
cache_data[cur_det_name] = marks[-num]
print("compute thrs for model #", cur_det_name, "#:", marks[-num])
marks_set = np.transpose(marks_set)
marks_max = np.max(marks_set, axis=1)
marks_max = np.sort(marks_max)
max_thrs = marks_max[-num]
cache_data['thrs'] = max_thrs
if len(det_set) > 0:
hash_id = save_cache(det_info, cache_data, cache_path)
print("save cache:", hash_id)
else:
print("hit cache:", cache['hash_id'])
cache_data = cache['data']
for cur_det_name, cur_det in det_set.items():
print("compute thrs for model #", cur_det_name, "#:", cache_data[cur_det_name])
max_thrs = cache_data['thrs']
for cur_det_name, cur_det in det_set.items():
thrs_set[cur_det_name] = max_thrs
print("use joint thrs:", max_thrs)
else:
cache = load_cache(det_info, cache_path)
if cache is None:
cache_data = {}
for cur_det_name, cur_det in det_set.items():
validation_data = data.train_data_orig[det_idx_set[cur_det_name]]
num = int(len(validation_data) * dropout_rate_set[cur_det_name])
marks = cur_det.mark(validation_data, data_format=data_format)
marks = np.sort(marks)
thrs_set[cur_det_name] = marks[-num]
cache_data[cur_det_name] = marks[-num]
print("compute thrs for model #", cur_det_name, "#:", marks[-num])
if len(det_set) > 0:
hash_id = save_cache(det_info, cache_data, cache_path)
print("save cache:", hash_id)
else:
print("hit cache:", cache['hash_id'])
cache_data = cache['data']
for cur_det_name, cur_det in det_set.items():
thrs_set[cur_det_name] = cache_data[cur_det_name]
print("compute thrs for model #", cur_det_name, "#:", cache_data[cur_det_name])
return det_set, thrs_set, det_gpu_idx | en | 0.699589 | ## worker.py -- evaluation code ## ## Copyright (C) 2017, <NAME> <<EMAIL>>. ## ## This program is licenced under the BSD 2-Clause licence, ## contained in the LICENCE file in this directory. Error based detector. Marks examples for filtering decisions. path: Path to the autoencoder used. p: Distance measure to use. Identity reformer. Reforms an example to itself. Reformer. Reforms examples with autoencoder. Action of reforming is called heal. path: Path to the autoencoder used. Divergence-Based Detector. reconstructor: One autoencoder. prober: Another autoencoder. classifier: Classifier object. option: Measure of distance, jsd as default. T: Temperature to soften the classification decision. Keras classifier wrapper. Note that the wrapped classifier should spit logits as output. classifier_path: Path to Keras classifier file. Operator. Describes the classification problem and defense. data: Standard problem dataset. Including train, test, and validation. classifier: Target classifier. reformer: Reformer of defense. det_dict: Detector(s) of defense. Get filtering threshold by marking validation set. For untrusted input(normal or adversarial), classify original input and reformed input. Classifier is unaware of the source of input. untrusted_obj: Input data. untrusted_obj: Untrusted input to test against. thrs: Thresholds. return: all_pass: Index of examples that passed all detectors. collector: Number of examples that escaped each detector. Input data wrapper. May be normal or adversarial. examples: Path or object of input examples. labels: Ground truth labels. Evaluator. For strategy described by operator, conducts tests on untrusted input. Mainly stats and plotting code. Most methods omitted for clarity. operator: Operator object. untrusted_data: Input data to test against. graph_dir: Where to spit the graphs. Break down of who does what in defense. Accuracy of defense on normal input. both: Both detectors and reformer take effect det_only: detector(s) take effect ref_only: Only reformer takes effect none: Attack effect with no defense Test defense performance against Carlini L2 attack of various confidences. graph_name: Name of graph file. drop_rate: How many normal examples should each detector drops? idx_file: Index of adversarial examples in standard test set. confs: A series of confidence to test against. get_attack_data_name: Function mapping confidence to corresponding file. # compute number of all input data and filter out valid data # build detector # compute thrs #", cur_det_name, "#:", marks[-num]) #", cur_det_name, "#:", cache_data[cur_det_name]) #", cur_det_name, "#:", marks[-num]) #", cur_det_name, "#:", cache_data[cur_det_name]) | 2.059931 | 2 |
examples/request_id.py | b-rad-c/kwogger | 0 | 6620310 | <filename>examples/request_id.py<gh_stars>0
#!/usr/bin/env python3
import kwogger
def main():
log = kwogger.rotate_by_size('request_demo', 'request_id.log', server='www.example.com')
# create a unique id for this mock web request that links each logging entry for easy searching when troubleshooting
log.generate_id('request_id')
log.info('Sample message')
x, y = 1, '1'
try:
z = x + y
except TypeError:
log.error_exc('Uh-oh!', x=x, y=y)
if __name__ == '__main__':
main()
| <filename>examples/request_id.py<gh_stars>0
#!/usr/bin/env python3
import kwogger
def main():
log = kwogger.rotate_by_size('request_demo', 'request_id.log', server='www.example.com')
# create a unique id for this mock web request that links each logging entry for easy searching when troubleshooting
log.generate_id('request_id')
log.info('Sample message')
x, y = 1, '1'
try:
z = x + y
except TypeError:
log.error_exc('Uh-oh!', x=x, y=y)
if __name__ == '__main__':
main()
| en | 0.607733 | #!/usr/bin/env python3 # create a unique id for this mock web request that links each logging entry for easy searching when troubleshooting | 2.59872 | 3 |
src/func_net_pred.py | jon-young/genetic_interact | 0 | 6620311 | #!/usr/bin/env python
"""
Predict genetic interactions using a functional gene network
and known interactions
@author: jyoung
"""
import collections
import matplotlib.pyplot as plt
import numpy as np
import os
import pandas as pd
import re
import sys
from sklearn import metrics
def setup_filepaths(organism):
"""Setup full file paths for functional net and BIOGRID"""
if organism == 'cerevisiae':
biogridpath = os.path.join('..', 'data',
'BIOGRID-3.4.130-yeast-post2006.txt')
fnetpath = os.path.join('..', 'data', 'YeastNetDataFrame.pkl')
elif organism == 'sapiens':
biogridpath = os.path.join('..', '..', 'DataDownload', 'BIOGRID',
'BIOGRID-ORGANISM-3.4.130.tab2',
'BIOGRID-ORGANISM-Homo_sapiens-3.4.130.tab2.txt')
fnetpath = os.path.join('..', 'data', 'HumanNetDataFrame.pkl')
elif organism == 'melanogaster':
biogridpath = os.path.join('..', '..', 'DataDownload', 'BIOGRID',
'BIOGRID-ORGANISM-3.4.130.tab2',
'BIOGRID-ORGANISM-Drosophila_melanogaster-3.4.130.tab2.txt')
fnetpath = os.path.join('..', 'data', 'FlyNetDataFrame.pkl')
else:
print('ORGANISM NOT FOUND! Exiting...')
sys.exit()
return biogridpath, fnetpath
def determine_col(organism, gene):
"""Determine which gene column in the BIOGRID file to read"""
entrezRegEx = re.compile(r'\d+')
if organism == 'cerevisiae':
sysNameRegEx = re.compile(r'Y[A-Z][A-Z]\d+')
ofcSymRegEx = re.compile(r'[A-Z]+')
elif organism == 'sapiens':
sysNameRegEx = re.compile(r'\w+')
ofcSymRegEx = re.compile(r'[A-Za-z]+.')
else: # organism == 'melanogaster'
sysNameRegEx = re.compile(r'Dmel_.')
ofcSymRegEx = re.compile(r'\w+')
if entrezRegEx.match(gene) is not None:
colName = 'Entrez Gene Interactor A'
elif sysNameRegEx.match(gene) is not None:
colName = 'Systematic Name Interactor A'
elif ofcSymRegEx.match(gene) is not None:
colName = 'Official Symbol Interactor A'
else:
print('ERROR: Unable to match ID type! Exiting...')
sys.exit()
return colName
def read_biogrid(biogridpath, experimentSys, colName):
"""Read BIOGRID genetic interactions and return dictionary converting each
interactor ID to its genetic interaction partners"""
seedSets = collections.defaultdict(set)
biogridfile = open(biogridpath)
header = biogridfile.readline().split('\t')
geneColNum = header.index(colName)
expSysColNum = header.index('Experimental System')
for line in biogridfile:
tokens = line.split('\t')
if tokens[expSysColNum] == experimentSys:
seedSets[tokens[geneColNum]].add(tokens[geneColNum + 1])
seedSets[tokens[geneColNum + 1]].add(tokens[geneColNum])
return seedSets
def seed_set_predictability(funcNetDf, seedSets):
"""For each seed gene, measure its predictability of genetic interactions
by AUC. Also return a dictionary converting the seed gene (provided it is
in the network) to the set of its known genetic interaction partners."""
seedAUC = list()
seed2interactors = dict()
for seedGene in seedSets.keys():
interactors = [gene for gene in seedSets[seedGene]
if gene in funcNetDf.index]
if len(interactors) > 0:
llsSum = funcNetDf.loc[interactors,:].sum(axis=0)
trueLabels = pd.Series([0]*llsSum.size, index=llsSum.index)
trueLabels.loc[interactors] = 1
auc = metrics.roc_auc_score(trueLabels, llsSum)
seedAUC.append((auc, seedGene))
seed2interactors[seedGene] = interactors
seedAUC.sort()
return seedAUC, seed2interactors
def plot_aucs(seedAUC):
"""ARGUMENTS: <list> [(seed AUC, seed Entrez)]"""
aucs = [t[0] for t in seedAUC]
pos = np.arange(1, len(aucs)+1)
plt.barh(pos, aucs, height=1.0, align='center')
plt.ylim([0, len(aucs)+1])
ax = plt.axes()
ax.set_yticklabels([])
plt.xlabel('AUC')
plt.ylabel('Seed sets')
plt.tight_layout()
plt.show()
def main():
if len(sys.argv) < 3: # validate input parameters
print('Usage: python {} <organism>'\
' <genetic interaction>'.format(sys.argv[0]))
sys.exit()
organism = sys.argv[1]
intactType = sys.argv[2]
biogridpath, fnetpath = setup_filepaths(organism)
funcNetDf = pd.read_pickle(fnetpath)
numNodes = len(funcNetDf.columns)
print('\nNumber of genes in functional network: {}'.format(numNodes))
geneExample = funcNetDf.columns[0]
colName = determine_col(organism, geneExample)
seedSets = read_biogrid(biogridpath, intactType, colName)
seedAUC, seed2intacts = seed_set_predictability(funcNetDf, seedSets)
print('Number of seed sets: {}\n'.format(len(seedAUC)))
plot_aucs(seedAUC)
if __name__=="__main__":
main()
| #!/usr/bin/env python
"""
Predict genetic interactions using a functional gene network
and known interactions
@author: jyoung
"""
import collections
import matplotlib.pyplot as plt
import numpy as np
import os
import pandas as pd
import re
import sys
from sklearn import metrics
def setup_filepaths(organism):
"""Setup full file paths for functional net and BIOGRID"""
if organism == 'cerevisiae':
biogridpath = os.path.join('..', 'data',
'BIOGRID-3.4.130-yeast-post2006.txt')
fnetpath = os.path.join('..', 'data', 'YeastNetDataFrame.pkl')
elif organism == 'sapiens':
biogridpath = os.path.join('..', '..', 'DataDownload', 'BIOGRID',
'BIOGRID-ORGANISM-3.4.130.tab2',
'BIOGRID-ORGANISM-Homo_sapiens-3.4.130.tab2.txt')
fnetpath = os.path.join('..', 'data', 'HumanNetDataFrame.pkl')
elif organism == 'melanogaster':
biogridpath = os.path.join('..', '..', 'DataDownload', 'BIOGRID',
'BIOGRID-ORGANISM-3.4.130.tab2',
'BIOGRID-ORGANISM-Drosophila_melanogaster-3.4.130.tab2.txt')
fnetpath = os.path.join('..', 'data', 'FlyNetDataFrame.pkl')
else:
print('ORGANISM NOT FOUND! Exiting...')
sys.exit()
return biogridpath, fnetpath
def determine_col(organism, gene):
"""Determine which gene column in the BIOGRID file to read"""
entrezRegEx = re.compile(r'\d+')
if organism == 'cerevisiae':
sysNameRegEx = re.compile(r'Y[A-Z][A-Z]\d+')
ofcSymRegEx = re.compile(r'[A-Z]+')
elif organism == 'sapiens':
sysNameRegEx = re.compile(r'\w+')
ofcSymRegEx = re.compile(r'[A-Za-z]+.')
else: # organism == 'melanogaster'
sysNameRegEx = re.compile(r'Dmel_.')
ofcSymRegEx = re.compile(r'\w+')
if entrezRegEx.match(gene) is not None:
colName = 'Entrez Gene Interactor A'
elif sysNameRegEx.match(gene) is not None:
colName = 'Systematic Name Interactor A'
elif ofcSymRegEx.match(gene) is not None:
colName = 'Official Symbol Interactor A'
else:
print('ERROR: Unable to match ID type! Exiting...')
sys.exit()
return colName
def read_biogrid(biogridpath, experimentSys, colName):
"""Read BIOGRID genetic interactions and return dictionary converting each
interactor ID to its genetic interaction partners"""
seedSets = collections.defaultdict(set)
biogridfile = open(biogridpath)
header = biogridfile.readline().split('\t')
geneColNum = header.index(colName)
expSysColNum = header.index('Experimental System')
for line in biogridfile:
tokens = line.split('\t')
if tokens[expSysColNum] == experimentSys:
seedSets[tokens[geneColNum]].add(tokens[geneColNum + 1])
seedSets[tokens[geneColNum + 1]].add(tokens[geneColNum])
return seedSets
def seed_set_predictability(funcNetDf, seedSets):
"""For each seed gene, measure its predictability of genetic interactions
by AUC. Also return a dictionary converting the seed gene (provided it is
in the network) to the set of its known genetic interaction partners."""
seedAUC = list()
seed2interactors = dict()
for seedGene in seedSets.keys():
interactors = [gene for gene in seedSets[seedGene]
if gene in funcNetDf.index]
if len(interactors) > 0:
llsSum = funcNetDf.loc[interactors,:].sum(axis=0)
trueLabels = pd.Series([0]*llsSum.size, index=llsSum.index)
trueLabels.loc[interactors] = 1
auc = metrics.roc_auc_score(trueLabels, llsSum)
seedAUC.append((auc, seedGene))
seed2interactors[seedGene] = interactors
seedAUC.sort()
return seedAUC, seed2interactors
def plot_aucs(seedAUC):
"""ARGUMENTS: <list> [(seed AUC, seed Entrez)]"""
aucs = [t[0] for t in seedAUC]
pos = np.arange(1, len(aucs)+1)
plt.barh(pos, aucs, height=1.0, align='center')
plt.ylim([0, len(aucs)+1])
ax = plt.axes()
ax.set_yticklabels([])
plt.xlabel('AUC')
plt.ylabel('Seed sets')
plt.tight_layout()
plt.show()
def main():
if len(sys.argv) < 3: # validate input parameters
print('Usage: python {} <organism>'\
' <genetic interaction>'.format(sys.argv[0]))
sys.exit()
organism = sys.argv[1]
intactType = sys.argv[2]
biogridpath, fnetpath = setup_filepaths(organism)
funcNetDf = pd.read_pickle(fnetpath)
numNodes = len(funcNetDf.columns)
print('\nNumber of genes in functional network: {}'.format(numNodes))
geneExample = funcNetDf.columns[0]
colName = determine_col(organism, geneExample)
seedSets = read_biogrid(biogridpath, intactType, colName)
seedAUC, seed2intacts = seed_set_predictability(funcNetDf, seedSets)
print('Number of seed sets: {}\n'.format(len(seedAUC)))
plot_aucs(seedAUC)
if __name__=="__main__":
main()
| en | 0.808259 | #!/usr/bin/env python Predict genetic interactions using a functional gene network and known interactions @author: jyoung Setup full file paths for functional net and BIOGRID Determine which gene column in the BIOGRID file to read # organism == 'melanogaster' Read BIOGRID genetic interactions and return dictionary converting each interactor ID to its genetic interaction partners For each seed gene, measure its predictability of genetic interactions by AUC. Also return a dictionary converting the seed gene (provided it is in the network) to the set of its known genetic interaction partners. ARGUMENTS: <list> [(seed AUC, seed Entrez)] # validate input parameters | 2.522645 | 3 |
01-Apprenez/3.04.py | gruiick/openclassrooms-py | 0 | 6620312 | #!/usr/bin/env python3
# coding: utf-8
# $Id: 3.04.py 1.5 $
# SPDX-License-Identifier: BSD-2-Clause
""" tri(s) """
prenoms = ['Laetitia', 'Marguerite', 'Toscane', 'Lucie', 'Maxime', 'Célestine', 'Fanélie', 'Lucienne', 'Sancie', 'Modeste', 'Sidonie', 'Danielle', 'Cassandre', 'Madeleine', 'Eugénie', 'Bethsabée', 'Amélie', 'Jacqueline', 'Josie', 'Abelle']
# prenoms.sort() # méthode de liste, la liste est triée, l'ordre en est modifié
# sorted(prenoms) # méthode 'builtin' python : retourne une copie triée de n'importe quel itérable
etudiants1 = [
# Prénom, age, moyenne
("Clément", 14, 16),
("Charles", 13, 12),
("Oriane", 14, 18),
("Kevin", 15, 12),
("Damien", 13, 11),
]
# lambda colonnes: colonnes[2] # (on veut trier sur la moyenne
# sorted(etudiants1, key=lambda colonnes: colonnes[2])
class Etudiant:
""" représentation d'un étudiant
prénom
age
note (moyenne, entre 0 et 20)
"""
def __init__(self, prenom, age, moyenne):
self.prenom = prenom
self.age = age
self.moyenne = moyenne
def __repr__(self):
return '<Etudiant {} (âge={}, moyenne={})>'.format(self.prenom, self.age, self.moyenne)
def __lt__(self, autre_etudiant):
""" comparaison lesser than """
return self.moyenne < autre_etudiant.moyenne
etudiants2 = [
Etudiant("Clément", 14, 16),
Etudiant("Charles", 13, 12),
Etudiant("Oriane", 14, 18),
Etudiant("Kevin", 15, 12),
Etudiant("Damien", 13, 11),
]
sorted(etudiants2)
sorted(etudiants2, key=lambda etudiant2: etudiant2.moyenne) # equiv __lt__
sorted(etudiants2, key=lambda etudiant2: etudiant2.age, reverse=True) # equiv __gt__
# les lambda sont lentes sur de grands jeux de données
# le module 'operator' contient des fonctions utiles
from operator import itemgetter # sur un itérable
# tri sur la liste de contenus
sorted(etudiants1, key=itemgetter(2))
from operator import attrgetter # sur les attributs d'un objet
# tri sur cet attribut de la liste d'objet
sorted(etudiants2, key=attrgetter('age'))
class LigneInventaire:
""" une ligne d'inventaire de vente
Classe représentant une ligne d'un inventaire de vente.
Attributs attendus par le constructeur :
produit -- le nom du produit
prix -- le prix unitaire du produit
quantite -- la quantité vendue du produit.
"""
def __init__(self, produit, prix, quantite):
""" """
self.produit = produit
self.prix = prix
self.quantite = quantite
def __repr__(self):
""" """
return '<LigneInventaire {} ({} x {})>'.format(self.produit, self.prix, self.quantite)
inventaire = [
LigneInventaire("pomme rouge", 1.2, 19),
LigneInventaire("orange", 1.4, 24),
LigneInventaire("banane", 0.9, 21),
LigneInventaire("poire", 1.2, 24),
]
# tri prix croissant, quantité croissante
from operator import attrgetter
sorted(inventaire, key=attrgetter("prix", "quantite"))
# tri prix croissant, quantité DÉcroissante (et first)
inventaire.sort(key=attrgetter("quantite"), reverse=True)
sorted(inventaire, key=attrgetter("prix"))
| #!/usr/bin/env python3
# coding: utf-8
# $Id: 3.04.py 1.5 $
# SPDX-License-Identifier: BSD-2-Clause
""" tri(s) """
prenoms = ['Laetitia', 'Marguerite', 'Toscane', 'Lucie', 'Maxime', 'Célestine', 'Fanélie', 'Lucienne', 'Sancie', 'Modeste', 'Sidonie', 'Danielle', 'Cassandre', 'Madeleine', 'Eugénie', 'Bethsabée', 'Amélie', 'Jacqueline', 'Josie', 'Abelle']
# prenoms.sort() # méthode de liste, la liste est triée, l'ordre en est modifié
# sorted(prenoms) # méthode 'builtin' python : retourne une copie triée de n'importe quel itérable
etudiants1 = [
# Prénom, age, moyenne
("Clément", 14, 16),
("Charles", 13, 12),
("Oriane", 14, 18),
("Kevin", 15, 12),
("Damien", 13, 11),
]
# lambda colonnes: colonnes[2] # (on veut trier sur la moyenne
# sorted(etudiants1, key=lambda colonnes: colonnes[2])
class Etudiant:
""" représentation d'un étudiant
prénom
age
note (moyenne, entre 0 et 20)
"""
def __init__(self, prenom, age, moyenne):
self.prenom = prenom
self.age = age
self.moyenne = moyenne
def __repr__(self):
return '<Etudiant {} (âge={}, moyenne={})>'.format(self.prenom, self.age, self.moyenne)
def __lt__(self, autre_etudiant):
""" comparaison lesser than """
return self.moyenne < autre_etudiant.moyenne
etudiants2 = [
Etudiant("Clément", 14, 16),
Etudiant("Charles", 13, 12),
Etudiant("Oriane", 14, 18),
Etudiant("Kevin", 15, 12),
Etudiant("Damien", 13, 11),
]
sorted(etudiants2)
sorted(etudiants2, key=lambda etudiant2: etudiant2.moyenne) # equiv __lt__
sorted(etudiants2, key=lambda etudiant2: etudiant2.age, reverse=True) # equiv __gt__
# les lambda sont lentes sur de grands jeux de données
# le module 'operator' contient des fonctions utiles
from operator import itemgetter # sur un itérable
# tri sur la liste de contenus
sorted(etudiants1, key=itemgetter(2))
from operator import attrgetter # sur les attributs d'un objet
# tri sur cet attribut de la liste d'objet
sorted(etudiants2, key=attrgetter('age'))
class LigneInventaire:
""" une ligne d'inventaire de vente
Classe représentant une ligne d'un inventaire de vente.
Attributs attendus par le constructeur :
produit -- le nom du produit
prix -- le prix unitaire du produit
quantite -- la quantité vendue du produit.
"""
def __init__(self, produit, prix, quantite):
""" """
self.produit = produit
self.prix = prix
self.quantite = quantite
def __repr__(self):
""" """
return '<LigneInventaire {} ({} x {})>'.format(self.produit, self.prix, self.quantite)
inventaire = [
LigneInventaire("pomme rouge", 1.2, 19),
LigneInventaire("orange", 1.4, 24),
LigneInventaire("banane", 0.9, 21),
LigneInventaire("poire", 1.2, 24),
]
# tri prix croissant, quantité croissante
from operator import attrgetter
sorted(inventaire, key=attrgetter("prix", "quantite"))
# tri prix croissant, quantité DÉcroissante (et first)
inventaire.sort(key=attrgetter("quantite"), reverse=True)
sorted(inventaire, key=attrgetter("prix"))
| fr | 0.972468 | #!/usr/bin/env python3 # coding: utf-8 # $Id: 3.04.py 1.5 $ # SPDX-License-Identifier: BSD-2-Clause tri(s) # prenoms.sort() # méthode de liste, la liste est triée, l'ordre en est modifié # sorted(prenoms) # méthode 'builtin' python : retourne une copie triée de n'importe quel itérable # Prénom, age, moyenne # lambda colonnes: colonnes[2] # (on veut trier sur la moyenne # sorted(etudiants1, key=lambda colonnes: colonnes[2]) représentation d'un étudiant prénom age note (moyenne, entre 0 et 20) comparaison lesser than # equiv __lt__ # equiv __gt__ # les lambda sont lentes sur de grands jeux de données # le module 'operator' contient des fonctions utiles # sur un itérable # tri sur la liste de contenus # sur les attributs d'un objet # tri sur cet attribut de la liste d'objet une ligne d'inventaire de vente Classe représentant une ligne d'un inventaire de vente. Attributs attendus par le constructeur : produit -- le nom du produit prix -- le prix unitaire du produit quantite -- la quantité vendue du produit. # tri prix croissant, quantité croissante # tri prix croissant, quantité DÉcroissante (et first) | 3.050099 | 3 |
src/fortios_xutils/__init__.py | ssato/fortios-xutils | 0 | 6620313 | r"""Very experimental miscellaneous and extra utilities for fortios.
"""
from __future__ import absolute_import
from .api import ( # noqa: F401
parse_and_save_show_configs,
query_json_files,
collect_networks,
collect_and_save_networks,
compose_networks,
compose_and_save_networks,
make_firewall_policy_table,
make_firewall_policy_tables,
make_and_save_firewall_policy_table,
make_and_save_firewall_policy_tables,
load_firewall_policy_table,
search_firewall_policy_table_by_addr,
load_network_graph,
find_network_nodes_by_ip,
find_network_paths,
NODE_TYPES,
NODE_ANY, NODE_NET, NODE_HOST, NODE_ROUTER, NODE_SWITCH, NODE_FIREWALL
)
__version__ = "0.4.2"
__all__ = """
parse_and_save_show_configs
query_json_files
collect_networks
collect_and_save_networks
compose_networks
compose_and_save_networks
make_firewall_policy_table
make_firewall_policy_tables
make_and_save_firewall_policy_table
make_and_save_firewall_policy_tables
load_firewall_policy_table
search_firewall_policy_table_by_addr
load_network_graph
find_network_nodes_by_ip
find_network_paths
NODE_TYPES
NODE_ANY
NODE_NET
NODE_HOST
NODE_ROUTER
NODE_SWITCH
NODE_FIREWALL
""".split()
# vim:sw=4:ts=4:et:
| r"""Very experimental miscellaneous and extra utilities for fortios.
"""
from __future__ import absolute_import
from .api import ( # noqa: F401
parse_and_save_show_configs,
query_json_files,
collect_networks,
collect_and_save_networks,
compose_networks,
compose_and_save_networks,
make_firewall_policy_table,
make_firewall_policy_tables,
make_and_save_firewall_policy_table,
make_and_save_firewall_policy_tables,
load_firewall_policy_table,
search_firewall_policy_table_by_addr,
load_network_graph,
find_network_nodes_by_ip,
find_network_paths,
NODE_TYPES,
NODE_ANY, NODE_NET, NODE_HOST, NODE_ROUTER, NODE_SWITCH, NODE_FIREWALL
)
__version__ = "0.4.2"
__all__ = """
parse_and_save_show_configs
query_json_files
collect_networks
collect_and_save_networks
compose_networks
compose_and_save_networks
make_firewall_policy_table
make_firewall_policy_tables
make_and_save_firewall_policy_table
make_and_save_firewall_policy_tables
load_firewall_policy_table
search_firewall_policy_table_by_addr
load_network_graph
find_network_nodes_by_ip
find_network_paths
NODE_TYPES
NODE_ANY
NODE_NET
NODE_HOST
NODE_ROUTER
NODE_SWITCH
NODE_FIREWALL
""".split()
# vim:sw=4:ts=4:et:
| en | 0.459686 | Very experimental miscellaneous and extra utilities for fortios. # noqa: F401 parse_and_save_show_configs query_json_files collect_networks collect_and_save_networks compose_networks compose_and_save_networks make_firewall_policy_table make_firewall_policy_tables make_and_save_firewall_policy_table make_and_save_firewall_policy_tables load_firewall_policy_table search_firewall_policy_table_by_addr load_network_graph find_network_nodes_by_ip find_network_paths NODE_TYPES NODE_ANY NODE_NET NODE_HOST NODE_ROUTER NODE_SWITCH NODE_FIREWALL # vim:sw=4:ts=4:et: | 1.617156 | 2 |
cmd/timeseries/try_tsfresh.py | Peizhong/py | 0 | 6620314 | <reponame>Peizhong/py
from tsfresh.examples.robot_execution_failures import download_robot_execution_failures, \
load_robot_execution_failures
from tsfresh import extract_features, extract_relevant_features, select_features
from tsfresh.utilities.dataframe_functions import impute
from tsfresh.feature_extraction import ComprehensiveFCParameters
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
import matplotlib.pyplot as plt
download_robot_execution_failures()
df, y = load_robot_execution_failures()
print(df.head())
df[df.id == 3][['time', 'F_x', 'F_y', 'F_z', 'T_x', 'T_y', 'T_z']].plot(x='time', title='Success example (id 3)', figsize=(12, 6))
df[df.id == 20][['time', 'F_x', 'F_y', 'F_z', 'T_x', 'T_y', 'T_z']].plot(x='time', title='Failure example (id 20)', figsize=(12, 6))
# plt.show()
# extract features: for each robot execution (which is our id) and for each of the measured sensor values (F_* and T_*)
# tsfresh will result in a single row for each id and will calculate the features for each columns (we call them "kind") separately
extraction_settings = ComprehensiveFCParameters()
X = extract_features(df, column_id='id', column_sort='time',
default_fc_parameters=extraction_settings,
# we impute = remove all NaN features automatically
impute_function=impute)
# features survive the feature selection given this target
X_filtered = select_features(X, y)
print(X_filtered.head())
X_full_train, X_full_test, y_train, y_test = train_test_split(X, y, test_size=.4)
X_filtered_train, X_filtered_test = X_full_train[X_filtered.columns], X_full_test[X_filtered.columns]
# Compared to using all features
classifier_full = DecisionTreeClassifier()
classifier_full.fit(X_full_train, y_train)
print(classification_report(y_test, classifier_full.predict(X_full_test)))
# Compared to using only the relevant features, achieves better classification performance with less data
classifier_filtered = DecisionTreeClassifier()
classifier_filtered.fit(X_filtered_train, y_train)
print(classification_report(y_test, classifier_filtered.predict(X_filtered_test)))
# list of selected features
X_filtered_2 = extract_relevant_features(df, y, column_id='id', column_sort='time',
default_fc_parameters=extraction_settings)
print(X_filtered_2.head())
| from tsfresh.examples.robot_execution_failures import download_robot_execution_failures, \
load_robot_execution_failures
from tsfresh import extract_features, extract_relevant_features, select_features
from tsfresh.utilities.dataframe_functions import impute
from tsfresh.feature_extraction import ComprehensiveFCParameters
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
import matplotlib.pyplot as plt
download_robot_execution_failures()
df, y = load_robot_execution_failures()
print(df.head())
df[df.id == 3][['time', 'F_x', 'F_y', 'F_z', 'T_x', 'T_y', 'T_z']].plot(x='time', title='Success example (id 3)', figsize=(12, 6))
df[df.id == 20][['time', 'F_x', 'F_y', 'F_z', 'T_x', 'T_y', 'T_z']].plot(x='time', title='Failure example (id 20)', figsize=(12, 6))
# plt.show()
# extract features: for each robot execution (which is our id) and for each of the measured sensor values (F_* and T_*)
# tsfresh will result in a single row for each id and will calculate the features for each columns (we call them "kind") separately
extraction_settings = ComprehensiveFCParameters()
X = extract_features(df, column_id='id', column_sort='time',
default_fc_parameters=extraction_settings,
# we impute = remove all NaN features automatically
impute_function=impute)
# features survive the feature selection given this target
X_filtered = select_features(X, y)
print(X_filtered.head())
X_full_train, X_full_test, y_train, y_test = train_test_split(X, y, test_size=.4)
X_filtered_train, X_filtered_test = X_full_train[X_filtered.columns], X_full_test[X_filtered.columns]
# Compared to using all features
classifier_full = DecisionTreeClassifier()
classifier_full.fit(X_full_train, y_train)
print(classification_report(y_test, classifier_full.predict(X_full_test)))
# Compared to using only the relevant features, achieves better classification performance with less data
classifier_filtered = DecisionTreeClassifier()
classifier_filtered.fit(X_filtered_train, y_train)
print(classification_report(y_test, classifier_filtered.predict(X_filtered_test)))
# list of selected features
X_filtered_2 = extract_relevant_features(df, y, column_id='id', column_sort='time',
default_fc_parameters=extraction_settings)
print(X_filtered_2.head()) | en | 0.862827 | # plt.show() # extract features: for each robot execution (which is our id) and for each of the measured sensor values (F_* and T_*) # tsfresh will result in a single row for each id and will calculate the features for each columns (we call them "kind") separately # we impute = remove all NaN features automatically # features survive the feature selection given this target # Compared to using all features # Compared to using only the relevant features, achieves better classification performance with less data # list of selected features | 2.903506 | 3 |
src/screens/screen_.py | jolark/MaxPaint | 0 | 6620315 | <gh_stars>0
"""
base class for every screen
"""
class Screen_(object):
def __init__(self):
pass
def render(self, screen):
raise NotImplementedError
def update(self):
pass
def handle_events(self, events):
raise NotImplementedError
| """
base class for every screen
"""
class Screen_(object):
def __init__(self):
pass
def render(self, screen):
raise NotImplementedError
def update(self):
pass
def handle_events(self, events):
raise NotImplementedError | en | 0.884964 | base class for every screen | 2.475618 | 2 |
aioamqp/tests/test_basic.py | michael-k/aioamqp | 0 | 6620316 | <reponame>michael-k/aioamqp<filename>aioamqp/tests/test_basic.py
"""
Amqp basic class tests
"""
import asyncio
import struct
import unittest
from . import testcase
from . import testing
from .. import exceptions
from .. import properties
class QosTestCase(testcase.RabbitTestCase, unittest.TestCase):
@testing.coroutine
def test_basic_qos_default_args(self):
result = yield from self.channel.basic_qos()
self.assertTrue(result)
@testing.coroutine
def test_basic_qos(self):
result = yield from self.channel.basic_qos(
prefetch_size=0,
prefetch_count=100,
connection_global=False)
self.assertTrue(result)
@testing.coroutine
def test_basic_qos_prefetch_size(self):
with self.assertRaises(exceptions.ChannelClosed) as cm:
yield from self.channel.basic_qos(
prefetch_size=10,
prefetch_count=100,
connection_global=False)
self.assertEqual(cm.exception.code, 540)
@testing.coroutine
def test_basic_qos_wrong_values(self):
with self.assertRaises(struct.error):
yield from self.channel.basic_qos(
prefetch_size=100000,
prefetch_count=1000000000,
connection_global=False)
class BasicCancelTestCase(testcase.RabbitTestCase, unittest.TestCase):
@testing.coroutine
def test_basic_cancel(self):
@asyncio.coroutine
def callback(channel, body, envelope, _properties):
pass
queue_name = 'queue_name'
exchange_name = 'exchange_name'
yield from self.channel.queue_declare(queue_name)
yield from self.channel.exchange_declare(exchange_name, type_name='direct')
yield from self.channel.queue_bind(queue_name, exchange_name, routing_key='')
result = yield from self.channel.basic_consume(callback, queue_name=queue_name)
result = yield from self.channel.basic_cancel(result['consumer_tag'])
result = yield from self.channel.publish("payload", exchange_name, routing_key='')
yield from asyncio.sleep(5, loop=self.loop)
result = yield from self.channel.queue_declare(queue_name, passive=True)
self.assertEqual(result['message_count'], 1)
self.assertEqual(result['consumer_count'], 0)
@testing.coroutine
def test_basic_cancel_unknown_ctag(self):
result = yield from self.channel.basic_cancel("unknown_ctag")
self.assertTrue(result)
class BasicGetTestCase(testcase.RabbitTestCase, unittest.TestCase):
@testing.coroutine
def test_basic_get(self):
queue_name = 'queue_name'
exchange_name = 'exchange_name'
routing_key = ''
yield from self.channel.queue_declare(queue_name)
yield from self.channel.exchange_declare(exchange_name, type_name='direct')
yield from self.channel.queue_bind(queue_name, exchange_name, routing_key=routing_key)
yield from self.channel.publish("payload", exchange_name, routing_key=routing_key)
result = yield from self.channel.basic_get(queue_name)
self.assertEqual(result['routing_key'], routing_key)
self.assertFalse(result['redelivered'])
self.assertIn('delivery_tag', result)
self.assertEqual(result['exchange_name'].split('.')[-1], exchange_name)
self.assertEqual(result['message'], b'payload')
self.assertIsInstance(result['properties'], properties.Properties)
@testing.coroutine
def test_basic_get_empty(self):
queue_name = 'queue_name'
exchange_name = 'exchange_name'
routing_key = ''
yield from self.channel.queue_declare(queue_name)
yield from self.channel.exchange_declare(exchange_name, type_name='direct')
yield from self.channel.queue_bind(queue_name, exchange_name, routing_key=routing_key)
with self.assertRaises(exceptions.EmptyQueue):
yield from self.channel.basic_get(queue_name)
class BasicDeliveryTestCase(testcase.RabbitTestCase, unittest.TestCase):
@asyncio.coroutine
def publish(self, queue_name, exchange_name, routing_key, payload):
yield from self.channel.queue_declare(queue_name, exclusive=False, no_wait=False)
yield from self.channel.exchange_declare(exchange_name, type_name='fanout')
yield from self.channel.queue_bind(queue_name, exchange_name, routing_key=routing_key)
yield from self.channel.publish(payload, exchange_name, queue_name)
@testing.coroutine
def test_ack_message(self):
queue_name = 'queue_name'
exchange_name = 'exchange_name'
routing_key = ''
yield from self.publish(
queue_name, exchange_name, routing_key, "payload"
)
qfuture = asyncio.Future(loop=self.loop)
@asyncio.coroutine
def qcallback(channel, body, envelope, _properties):
qfuture.set_result(envelope)
yield from self.channel.basic_consume(qcallback, queue_name=queue_name)
envelope = yield from qfuture
yield from qfuture
yield from self.channel.basic_client_ack(envelope.delivery_tag)
@testing.coroutine
def test_basic_nack(self):
queue_name = 'queue_name'
exchange_name = 'exchange_name'
routing_key = ''
yield from self.publish(
queue_name, exchange_name, routing_key, "payload"
)
qfuture = asyncio.Future(loop=self.loop)
@asyncio.coroutine
def qcallback(channel, body, envelope, _properties):
yield from self.channel.basic_client_nack(
envelope.delivery_tag, multiple=True, requeue=False
)
qfuture.set_result(True)
yield from self.channel.basic_consume(qcallback, queue_name=queue_name)
yield from qfuture
@testing.coroutine
def test_basic_nack_norequeue(self):
queue_name = 'queue_name'
exchange_name = 'exchange_name'
routing_key = ''
yield from self.publish(
queue_name, exchange_name, routing_key, "payload"
)
qfuture = asyncio.Future(loop=self.loop)
@asyncio.coroutine
def qcallback(channel, body, envelope, _properties):
yield from self.channel.basic_client_nack(envelope.delivery_tag, requeue=False)
qfuture.set_result(True)
yield from self.channel.basic_consume(qcallback, queue_name=queue_name)
yield from qfuture
@testing.coroutine
def test_basic_nack_requeue(self):
queue_name = 'queue_name'
exchange_name = 'exchange_name'
routing_key = ''
yield from self.publish(
queue_name, exchange_name, routing_key, "payload"
)
qfuture = asyncio.Future(loop=self.loop)
called = False
@asyncio.coroutine
def qcallback(channel, body, envelope, _properties):
nonlocal called
if not called:
called = True
yield from self.channel.basic_client_nack(envelope.delivery_tag, requeue=True)
else:
yield from self.channel.basic_client_ack(envelope.delivery_tag)
qfuture.set_result(True)
yield from self.channel.basic_consume(qcallback, queue_name=queue_name)
yield from qfuture
@testing.coroutine
def test_basic_reject(self):
queue_name = 'queue_name'
exchange_name = 'exchange_name'
routing_key = ''
yield from self.publish(
queue_name, exchange_name, routing_key, "payload"
)
qfuture = asyncio.Future(loop=self.loop)
@asyncio.coroutine
def qcallback(channel, body, envelope, _properties):
qfuture.set_result(envelope)
yield from self.channel.basic_consume(qcallback, queue_name=queue_name)
envelope = yield from qfuture
yield from self.channel.basic_reject(envelope.delivery_tag)
| """
Amqp basic class tests
"""
import asyncio
import struct
import unittest
from . import testcase
from . import testing
from .. import exceptions
from .. import properties
class QosTestCase(testcase.RabbitTestCase, unittest.TestCase):
@testing.coroutine
def test_basic_qos_default_args(self):
result = yield from self.channel.basic_qos()
self.assertTrue(result)
@testing.coroutine
def test_basic_qos(self):
result = yield from self.channel.basic_qos(
prefetch_size=0,
prefetch_count=100,
connection_global=False)
self.assertTrue(result)
@testing.coroutine
def test_basic_qos_prefetch_size(self):
with self.assertRaises(exceptions.ChannelClosed) as cm:
yield from self.channel.basic_qos(
prefetch_size=10,
prefetch_count=100,
connection_global=False)
self.assertEqual(cm.exception.code, 540)
@testing.coroutine
def test_basic_qos_wrong_values(self):
with self.assertRaises(struct.error):
yield from self.channel.basic_qos(
prefetch_size=100000,
prefetch_count=1000000000,
connection_global=False)
class BasicCancelTestCase(testcase.RabbitTestCase, unittest.TestCase):
@testing.coroutine
def test_basic_cancel(self):
@asyncio.coroutine
def callback(channel, body, envelope, _properties):
pass
queue_name = 'queue_name'
exchange_name = 'exchange_name'
yield from self.channel.queue_declare(queue_name)
yield from self.channel.exchange_declare(exchange_name, type_name='direct')
yield from self.channel.queue_bind(queue_name, exchange_name, routing_key='')
result = yield from self.channel.basic_consume(callback, queue_name=queue_name)
result = yield from self.channel.basic_cancel(result['consumer_tag'])
result = yield from self.channel.publish("payload", exchange_name, routing_key='')
yield from asyncio.sleep(5, loop=self.loop)
result = yield from self.channel.queue_declare(queue_name, passive=True)
self.assertEqual(result['message_count'], 1)
self.assertEqual(result['consumer_count'], 0)
@testing.coroutine
def test_basic_cancel_unknown_ctag(self):
result = yield from self.channel.basic_cancel("unknown_ctag")
self.assertTrue(result)
class BasicGetTestCase(testcase.RabbitTestCase, unittest.TestCase):
@testing.coroutine
def test_basic_get(self):
queue_name = 'queue_name'
exchange_name = 'exchange_name'
routing_key = ''
yield from self.channel.queue_declare(queue_name)
yield from self.channel.exchange_declare(exchange_name, type_name='direct')
yield from self.channel.queue_bind(queue_name, exchange_name, routing_key=routing_key)
yield from self.channel.publish("payload", exchange_name, routing_key=routing_key)
result = yield from self.channel.basic_get(queue_name)
self.assertEqual(result['routing_key'], routing_key)
self.assertFalse(result['redelivered'])
self.assertIn('delivery_tag', result)
self.assertEqual(result['exchange_name'].split('.')[-1], exchange_name)
self.assertEqual(result['message'], b'payload')
self.assertIsInstance(result['properties'], properties.Properties)
@testing.coroutine
def test_basic_get_empty(self):
queue_name = 'queue_name'
exchange_name = 'exchange_name'
routing_key = ''
yield from self.channel.queue_declare(queue_name)
yield from self.channel.exchange_declare(exchange_name, type_name='direct')
yield from self.channel.queue_bind(queue_name, exchange_name, routing_key=routing_key)
with self.assertRaises(exceptions.EmptyQueue):
yield from self.channel.basic_get(queue_name)
class BasicDeliveryTestCase(testcase.RabbitTestCase, unittest.TestCase):
@asyncio.coroutine
def publish(self, queue_name, exchange_name, routing_key, payload):
yield from self.channel.queue_declare(queue_name, exclusive=False, no_wait=False)
yield from self.channel.exchange_declare(exchange_name, type_name='fanout')
yield from self.channel.queue_bind(queue_name, exchange_name, routing_key=routing_key)
yield from self.channel.publish(payload, exchange_name, queue_name)
@testing.coroutine
def test_ack_message(self):
queue_name = 'queue_name'
exchange_name = 'exchange_name'
routing_key = ''
yield from self.publish(
queue_name, exchange_name, routing_key, "payload"
)
qfuture = asyncio.Future(loop=self.loop)
@asyncio.coroutine
def qcallback(channel, body, envelope, _properties):
qfuture.set_result(envelope)
yield from self.channel.basic_consume(qcallback, queue_name=queue_name)
envelope = yield from qfuture
yield from qfuture
yield from self.channel.basic_client_ack(envelope.delivery_tag)
@testing.coroutine
def test_basic_nack(self):
queue_name = 'queue_name'
exchange_name = 'exchange_name'
routing_key = ''
yield from self.publish(
queue_name, exchange_name, routing_key, "payload"
)
qfuture = asyncio.Future(loop=self.loop)
@asyncio.coroutine
def qcallback(channel, body, envelope, _properties):
yield from self.channel.basic_client_nack(
envelope.delivery_tag, multiple=True, requeue=False
)
qfuture.set_result(True)
yield from self.channel.basic_consume(qcallback, queue_name=queue_name)
yield from qfuture
@testing.coroutine
def test_basic_nack_norequeue(self):
queue_name = 'queue_name'
exchange_name = 'exchange_name'
routing_key = ''
yield from self.publish(
queue_name, exchange_name, routing_key, "payload"
)
qfuture = asyncio.Future(loop=self.loop)
@asyncio.coroutine
def qcallback(channel, body, envelope, _properties):
yield from self.channel.basic_client_nack(envelope.delivery_tag, requeue=False)
qfuture.set_result(True)
yield from self.channel.basic_consume(qcallback, queue_name=queue_name)
yield from qfuture
@testing.coroutine
def test_basic_nack_requeue(self):
queue_name = 'queue_name'
exchange_name = 'exchange_name'
routing_key = ''
yield from self.publish(
queue_name, exchange_name, routing_key, "payload"
)
qfuture = asyncio.Future(loop=self.loop)
called = False
@asyncio.coroutine
def qcallback(channel, body, envelope, _properties):
nonlocal called
if not called:
called = True
yield from self.channel.basic_client_nack(envelope.delivery_tag, requeue=True)
else:
yield from self.channel.basic_client_ack(envelope.delivery_tag)
qfuture.set_result(True)
yield from self.channel.basic_consume(qcallback, queue_name=queue_name)
yield from qfuture
@testing.coroutine
def test_basic_reject(self):
queue_name = 'queue_name'
exchange_name = 'exchange_name'
routing_key = ''
yield from self.publish(
queue_name, exchange_name, routing_key, "payload"
)
qfuture = asyncio.Future(loop=self.loop)
@asyncio.coroutine
def qcallback(channel, body, envelope, _properties):
qfuture.set_result(envelope)
yield from self.channel.basic_consume(qcallback, queue_name=queue_name)
envelope = yield from qfuture
yield from self.channel.basic_reject(envelope.delivery_tag) | en | 0.788081 | Amqp basic class tests | 2.37149 | 2 |
migrations/versions/50505ee6888a_license_dependency_added.py | NikhilKalige/atom-website | 2 | 6620317 | """
Create license, dependency tables
Add stars, keywords to package
Revision ID: 50505ee6888a
Revises: 5<PASSWORD>
Create Date: 2014-12-24 00:42:33.975402
"""
# revision identifiers, used by Alembic.
revision = '50505ee6888a'
down_revision = '589962765a19'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.create_table('dependency',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=50), nullable=False),
sa.Column('link', sa.String(length=255), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_table('license',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=50), nullable=False),
sa.Column('link', sa.String(length=255), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_table('dependencies',
sa.Column('dependency_id', sa.Integer(), nullable=True),
sa.Column('package_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['dependency_id'], ['dependency.id'], ),
sa.ForeignKeyConstraint(['package_id'], ['package.id'], )
)
op.add_column(u'package', sa.Column('keywords', sa.Text(), nullable=True))
op.add_column(u'package', sa.Column('license_id', sa.Integer(), nullable=True))
op.add_column(u'package', sa.Column('stars', sa.Integer(), nullable=True))
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_column(u'package', 'stars')
op.drop_column(u'package', 'license_id')
op.drop_column(u'package', 'keywords')
op.drop_table('dependencies')
op.drop_table('license')
op.drop_table('dependency')
### end Alembic commands ###
| """
Create license, dependency tables
Add stars, keywords to package
Revision ID: 50505ee6888a
Revises: 5<PASSWORD>
Create Date: 2014-12-24 00:42:33.975402
"""
# revision identifiers, used by Alembic.
revision = '50505ee6888a'
down_revision = '589962765a19'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.create_table('dependency',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=50), nullable=False),
sa.Column('link', sa.String(length=255), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_table('license',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=50), nullable=False),
sa.Column('link', sa.String(length=255), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_table('dependencies',
sa.Column('dependency_id', sa.Integer(), nullable=True),
sa.Column('package_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['dependency_id'], ['dependency.id'], ),
sa.ForeignKeyConstraint(['package_id'], ['package.id'], )
)
op.add_column(u'package', sa.Column('keywords', sa.Text(), nullable=True))
op.add_column(u'package', sa.Column('license_id', sa.Integer(), nullable=True))
op.add_column(u'package', sa.Column('stars', sa.Integer(), nullable=True))
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_column(u'package', 'stars')
op.drop_column(u'package', 'license_id')
op.drop_column(u'package', 'keywords')
op.drop_table('dependencies')
op.drop_table('license')
op.drop_table('dependency')
### end Alembic commands ###
| en | 0.507292 | Create license, dependency tables Add stars, keywords to package Revision ID: 50505ee6888a Revises: 5<PASSWORD> Create Date: 2014-12-24 00:42:33.975402 # revision identifiers, used by Alembic. ### commands auto generated by Alembic - please adjust! ### ### end Alembic commands ### ### commands auto generated by Alembic - please adjust! ### ### end Alembic commands ### | 1.605168 | 2 |
stringprep.py | theclashingfritz/Cog-Invasion-Online-Dump | 1 | 6620318 | <gh_stars>1-10
# uncompyle6 version 3.2.4
# Python bytecode 2.7 (62211)
# Decompiled from: Python 2.7.15 (v2.7.15:ca079a3ea3, Apr 30 2018, 16:30:26) [MSC v.1500 64 bit (AMD64)]
# Embedded file name: stringprep
from unicodedata import ucd_3_2_0 as unicodedata
def in_table_a1(code):
if unicodedata.category(code) != 'Cn':
return False
c = ord(code)
if 64976 <= c < 65008:
return False
return c & 65535 not in (65534, 65535)
b1_set = set([173, 847, 6150, 6155, 6156, 6157, 8203, 8204, 8205, 8288, 65279] + range(65024, 65040))
def in_table_b1(code):
return ord(code) in b1_set
b3_exceptions = {181: u'\u03bc',
223: u'ss', 304: u'i\u0307', 329: u'\u02bcn', 383: u's',
496: u'j\u030c', 837: u'\u03b9', 890: u' \u03b9', 912: u'\u03b9\u0308\u0301',
944: u'\u03c5\u0308\u0301', 962: u'\u03c3', 976: u'\u03b2', 977: u'\u03b8',
978: u'\u03c5', 979: u'\u03cd', 980: u'\u03cb', 981: u'\u03c6',
982: u'\u03c0', 1008: u'\u03ba', 1009: u'\u03c1', 1010: u'\u03c3',
1013: u'\u03b5', 1415: u'\u0565\u0582', 7830: u'h\u0331', 7831: u't\u0308',
7832: u'w\u030a', 7833: u'y\u030a', 7834: u'a\u02be', 7835: u'\u1e61',
8016: u'\u03c5\u0313', 8018: u'\u03c5\u0313\u0300', 8020: u'\u03c5\u0313\u0301', 8022: u'\u03c5\u0313\u0342',
8064: u'\u1f00\u03b9', 8065: u'\u1f01\u03b9', 8066: u'\u1f02\u03b9', 8067: u'\u1f03\u03b9',
8068: u'\u1f04\u03b9', 8069: u'\u1f05\u03b9', 8070: u'\u1f06\u03b9', 8071: u'\u1f07\u03b9',
8072: u'\u1f00\u03b9', 8073: u'\u1f01\u03b9', 8074: u'\u1f02\u03b9', 8075: u'\u1f03\u03b9',
8076: u'\u1f04\u03b9', 8077: u'\u1f05\u03b9', 8078: u'\u1f06\u03b9', 8079: u'\u1f07\u03b9',
8080: u'\u1f20\u03b9', 8081: u'\u1f21\u03b9', 8082: u'\u1f22\u03b9', 8083: u'\u1f23\u03b9',
8084: u'\u1f24\u03b9', 8085: u'\u1f25\u03b9', 8086: u'\u1f26\u03b9', 8087: u'\u1f27\u03b9',
8088: u'\u1f20\u03b9', 8089: u'\u1f21\u03b9', 8090: u'\u1f22\u03b9', 8091: u'\u1f23\u03b9',
8092: u'\u1f24\u03b9', 8093: u'\u1f25\u03b9', 8094: u'\u1f26\u03b9', 8095: u'\u1f27\u03b9',
8096: u'\u1f60\u03b9', 8097: u'\u1f61\u03b9', 8098: u'\u1f62\u03b9', 8099: u'\u1f63\u03b9',
8100: u'\u1f64\u03b9', 8101: u'\u1f65\u03b9', 8102: u'\u1f66\u03b9', 8103: u'\u1f67\u03b9',
8104: u'\u1f60\u03b9', 8105: u'\u1f61\u03b9', 8106: u'\u1f62\u03b9', 8107: u'\u1f63\u03b9',
8108: u'\u1f64\u03b9', 8109: u'\u1f65\u03b9', 8110: u'\u1f66\u03b9', 8111: u'\u1f67\u03b9',
8114: u'\u1f70\u03b9', 8115: u'\u03b1\u03b9', 8116: u'\u03ac\u03b9', 8118: u'\u03b1\u0342',
8119: u'\u03b1\u0342\u03b9', 8124: u'\u03b1\u03b9', 8126: u'\u03b9', 8130: u'\u1f74\u03b9',
8131: u'\u03b7\u03b9', 8132: u'\u03ae\u03b9', 8134: u'\u03b7\u0342', 8135: u'\u03b7\u0342\u03b9',
8140: u'\u03b7\u03b9', 8146: u'\u03b9\u0308\u0300', 8147: u'\u03b9\u0308\u0301', 8150: u'\u03b9\u0342',
8151: u'\u03b9\u0308\u0342', 8162: u'\u03c5\u0308\u0300', 8163: u'\u03c5\u0308\u0301', 8164: u'\u03c1\u0313',
8166: u'\u03c5\u0342', 8167: u'\u03c5\u0308\u0342', 8178: u'\u1f7c\u03b9', 8179: u'\u03c9\u03b9',
8180: u'\u03ce\u03b9', 8182: u'\u03c9\u0342', 8183: u'\u03c9\u0342\u03b9', 8188: u'\u03c9\u03b9',
8360: u'rs', 8450: u'c', 8451: u'\xb0c', 8455: u'\u025b',
8457: u'\xb0f', 8459: u'h', 8460: u'h', 8461: u'h',
8464: u'i', 8465: u'i', 8466: u'l', 8469: u'n',
8470: u'no', 8473: u'p', 8474: u'q', 8475: u'r',
8476: u'r', 8477: u'r', 8480: u'sm', 8481: u'tel',
8482: u'tm', 8484: u'z', 8488: u'z', 8492: u'b',
8493: u'c', 8496: u'e', 8497: u'f', 8499: u'm',
8510: u'\u03b3', 8511: u'\u03c0', 8517: u'd', 13169: u'hpa',
13171: u'au', 13173: u'ov', 13184: u'pa', 13185: u'na',
13186: u'\u03bca', 13187: u'ma', 13188: u'ka', 13189: u'kb',
13190: u'mb', 13191: u'gb', 13194: u'pf', 13195: u'nf',
13196: u'\u03bcf', 13200: u'hz', 13201: u'khz', 13202: u'mhz',
13203: u'ghz', 13204: u'thz', 13225: u'pa', 13226: u'kpa',
13227: u'mpa', 13228: u'gpa', 13236: u'pv', 13237: u'nv',
13238: u'\u03bcv', 13239: u'mv', 13240: u'kv', 13241: u'mv',
13242: u'pw', 13243: u'nw', 13244: u'\u03bcw', 13245: u'mw',
13246: u'kw', 13247: u'mw', 13248: u'k\u03c9', 13249: u'm\u03c9',
13251: u'bq', 13254: u'c\u2215kg', 13255: u'co.', 13256: u'db',
13257: u'gy', 13259: u'hp', 13261: u'kk', 13262: u'km',
13271: u'ph', 13273: u'ppm', 13274: u'pr', 13276: u'sv',
13277: u'wb', 64256: u'ff', 64257: u'fi', 64258: u'fl',
64259: u'ffi', 64260: u'ffl', 64261: u'st', 64262: u'st',
64275: u'\u0574\u0576', 64276: u'\u0574\u0565', 64277: u'\u0574\u056b', 64278: u'\u057e\u0576',
64279: u'\u0574\u056d', 119808: u'a', 119809: u'b', 119810: u'c',
119811: u'd', 119812: u'e', 119813: u'f', 119814: u'g',
119815: u'h', 119816: u'i', 119817: u'j', 119818: u'k',
119819: u'l', 119820: u'm', 119821: u'n', 119822: u'o',
119823: u'p', 119824: u'q', 119825: u'r', 119826: u's',
119827: u't', 119828: u'u', 119829: u'v', 119830: u'w',
119831: u'x', 119832: u'y', 119833: u'z', 119860: u'a',
119861: u'b', 119862: u'c', 119863: u'd', 119864: u'e',
119865: u'f', 119866: u'g', 119867: u'h', 119868: u'i',
119869: u'j', 119870: u'k', 119871: u'l', 119872: u'm',
119873: u'n', 119874: u'o', 119875: u'p', 119876: u'q',
119877: u'r', 119878: u's', 119879: u't', 119880: u'u',
119881: u'v', 119882: u'w', 119883: u'x', 119884: u'y',
119885: u'z', 119912: u'a', 119913: u'b', 119914: u'c',
119915: u'd', 119916: u'e', 119917: u'f', 119918: u'g',
119919: u'h', 119920: u'i', 119921: u'j', 119922: u'k',
119923: u'l', 119924: u'm', 119925: u'n', 119926: u'o',
119927: u'p', 119928: u'q', 119929: u'r', 119930: u's',
119931: u't', 119932: u'u', 119933: u'v', 119934: u'w',
119935: u'x', 119936: u'y', 119937: u'z', 119964: u'a',
119966: u'c', 119967: u'd', 119970: u'g', 119973: u'j',
119974: u'k', 119977: u'n', 119978: u'o', 119979: u'p',
119980: u'q', 119982: u's', 119983: u't', 119984: u'u',
119985: u'v', 119986: u'w', 119987: u'x', 119988: u'y',
119989: u'z', 120016: u'a', 120017: u'b', 120018: u'c',
120019: u'd', 120020: u'e', 120021: u'f', 120022: u'g',
120023: u'h', 120024: u'i', 120025: u'j', 120026: u'k',
120027: u'l', 120028: u'm', 120029: u'n', 120030: u'o',
120031: u'p', 120032: u'q', 120033: u'r', 120034: u's',
120035: u't', 120036: u'u', 120037: u'v', 120038: u'w',
120039: u'x', 120040: u'y', 120041: u'z', 120068: u'a',
120069: u'b', 120071: u'd', 120072: u'e', 120073: u'f',
120074: u'g', 120077: u'j', 120078: u'k', 120079: u'l',
120080: u'm', 120081: u'n', 120082: u'o', 120083: u'p',
120084: u'q', 120086: u's', 120087: u't', 120088: u'u',
120089: u'v', 120090: u'w', 120091: u'x', 120092: u'y',
120120: u'a', 120121: u'b', 120123: u'd', 120124: u'e',
120125: u'f', 120126: u'g', 120128: u'i', 120129: u'j',
120130: u'k', 120131: u'l', 120132: u'm', 120134: u'o',
120138: u's', 120139: u't', 120140: u'u', 120141: u'v',
120142: u'w', 120143: u'x', 120144: u'y', 120172: u'a',
120173: u'b', 120174: u'c', 120175: u'd', 120176: u'e',
120177: u'f', 120178: u'g', 120179: u'h', 120180: u'i',
120181: u'j', 120182: u'k', 120183: u'l', 120184: u'm',
120185: u'n', 120186: u'o', 120187: u'p', 120188: u'q',
120189: u'r', 120190: u's', 120191: u't', 120192: u'u',
120193: u'v', 120194: u'w', 120195: u'x', 120196: u'y',
120197: u'z', 120224: u'a', 120225: u'b', 120226: u'c',
120227: u'd', 120228: u'e', 120229: u'f', 120230: u'g',
120231: u'h', 120232: u'i', 120233: u'j', 120234: u'k',
120235: u'l', 120236: u'm', 120237: u'n', 120238: u'o',
120239: u'p', 120240: u'q', 120241: u'r', 120242: u's',
120243: u't', 120244: u'u', 120245: u'v', 120246: u'w',
120247: u'x', 120248: u'y', 120249: u'z', 120276: u'a',
120277: u'b', 120278: u'c', 120279: u'd', 120280: u'e',
120281: u'f', 120282: u'g', 120283: u'h', 120284: u'i',
120285: u'j', 120286: u'k', 120287: u'l', 120288: u'm',
120289: u'n', 120290: u'o', 120291: u'p', 120292: u'q',
120293: u'r', 120294: u's', 120295: u't', 120296: u'u',
120297: u'v', 120298: u'w', 120299: u'x', 120300: u'y',
120301: u'z', 120328: u'a', 120329: u'b', 120330: u'c',
120331: u'd', 120332: u'e', 120333: u'f', 120334: u'g',
120335: u'h', 120336: u'i', 120337: u'j', 120338: u'k',
120339: u'l', 120340: u'm', 120341: u'n', 120342: u'o',
120343: u'p', 120344: u'q', 120345: u'r', 120346: u's',
120347: u't', 120348: u'u', 120349: u'v', 120350: u'w',
120351: u'x', 120352: u'y', 120353: u'z', 120380: u'a',
120381: u'b', 120382: u'c', 120383: u'd', 120384: u'e',
120385: u'f', 120386: u'g', 120387: u'h', 120388: u'i',
120389: u'j', 120390: u'k', 120391: u'l', 120392: u'm',
120393: u'n', 120394: u'o', 120395: u'p', 120396: u'q',
120397: u'r', 120398: u's', 120399: u't', 120400: u'u',
120401: u'v', 120402: u'w', 120403: u'x', 120404: u'y',
120405: u'z', 120432: u'a', 120433: u'b', 120434: u'c',
120435: u'd', 120436: u'e', 120437: u'f', 120438: u'g',
120439: u'h', 120440: u'i', 120441: u'j', 120442: u'k',
120443: u'l', 120444: u'm', 120445: u'n', 120446: u'o',
120447: u'p', 120448: u'q', 120449: u'r', 120450: u's',
120451: u't', 120452: u'u', 120453: u'v', 120454: u'w',
120455: u'x', 120456: u'y', 120457: u'z', 120488: u'\u03b1',
120489: u'\u03b2', 120490: u'\u03b3', 120491: u'\u03b4', 120492: u'\u03b5',
120493: u'\u03b6', 120494: u'\u03b7', 120495: u'\u03b8', 120496: u'\u03b9',
120497: u'\u03ba', 120498: u'\u03bb', 120499: u'\u03bc', 120500: u'\u03bd',
120501: u'\u03be', 120502: u'\u03bf', 120503: u'\u03c0', 120504: u'\u03c1',
120505: u'\u03b8', 120506: u'\u03c3', 120507: u'\u03c4', 120508: u'\u03c5',
120509: u'\u03c6', 120510: u'\u03c7', 120511: u'\u03c8', 120512: u'\u03c9',
120531: u'\u03c3', 120546: u'\u03b1', 120547: u'\u03b2', 120548: u'\u03b3',
120549: u'\u03b4', 120550: u'\u03b5', 120551: u'\u03b6', 120552: u'\u03b7',
120553: u'\u03b8', 120554: u'\u03b9', 120555: u'\u03ba', 120556: u'\u03bb',
120557: u'\u03bc', 120558: u'\u03bd', 120559: u'\u03be', 120560: u'\u03bf',
120561: u'\u03c0', 120562: u'\u03c1', 120563: u'\u03b8', 120564: u'\u03c3',
120565: u'\u03c4', 120566: u'\u03c5', 120567: u'\u03c6', 120568: u'\u03c7',
120569: u'\u03c8', 120570: u'\u03c9', 120589: u'\u03c3', 120604: u'\u03b1',
120605: u'\u03b2', 120606: u'\u03b3', 120607: u'\u03b4', 120608: u'\u03b5',
120609: u'\u03b6', 120610: u'\u03b7', 120611: u'\u03b8', 120612: u'\u03b9',
120613: u'\u03ba', 120614: u'\u03bb', 120615: u'\u03bc', 120616: u'\u03bd',
120617: u'\u03be', 120618: u'\u03bf', 120619: u'\u03c0', 120620: u'\u03c1',
120621: u'\u03b8', 120622: u'\u03c3', 120623: u'\u03c4', 120624: u'\u03c5',
120625: u'\u03c6', 120626: u'\u03c7', 120627: u'\u03c8', 120628: u'\u03c9',
120647: u'\u03c3', 120662: u'\u03b1', 120663: u'\u03b2', 120664: u'\u03b3',
120665: u'\u03b4', 120666: u'\u03b5', 120667: u'\u03b6', 120668: u'\u03b7',
120669: u'\u03b8', 120670: u'\u03b9', 120671: u'\u03ba', 120672: u'\u03bb',
120673: u'\u03bc', 120674: u'\u03bd', 120675: u'\u03be', 120676: u'\u03bf',
120677: u'\u03c0', 120678: u'\u03c1', 120679: u'\u03b8', 120680: u'\u03c3',
120681: u'\u03c4', 120682: u'\u03c5', 120683: u'\u03c6', 120684: u'\u03c7',
120685: u'\u03c8', 120686: u'\u03c9', 120705: u'\u03c3', 120720: u'\u03b1',
120721: u'\u03b2', 120722: u'\u03b3', 120723: u'\u03b4', 120724: u'\u03b5',
120725: u'\u03b6', 120726: u'\u03b7', 120727: u'\u03b8', 120728: u'\u03b9',
120729: u'\u03ba', 120730: u'\u03bb', 120731: u'\u03bc', 120732: u'\u03bd',
120733: u'\u03be', 120734: u'\u03bf', 120735: u'\u03c0', 120736: u'\u03c1',
120737: u'\u03b8', 120738: u'\u03c3', 120739: u'\u03c4', 120740: u'\u03c5',
120741: u'\u03c6', 120742: u'\u03c7', 120743: u'\u03c8', 120744: u'\u03c9',
120763: u'\u03c3'}
def map_table_b3(code):
r = b3_exceptions.get(ord(code))
if r is not None:
return r
return code.lower()
def map_table_b2(a):
al = map_table_b3(a)
b = unicodedata.normalize('NFKC', al)
bl = (u'').join([ map_table_b3(ch) for ch in b ])
c = unicodedata.normalize('NFKC', bl)
if b != c:
return c
return al
def in_table_c11(code):
return code == u' '
def in_table_c12(code):
return unicodedata.category(code) == 'Zs' and code != u' '
def in_table_c11_c12(code):
return unicodedata.category(code) == 'Zs'
def in_table_c21(code):
return ord(code) < 128 and unicodedata.category(code) == 'Cc'
c22_specials = set([1757, 1807, 6158, 8204, 8205, 8232, 8233, 65279] + range(8288, 8292) + range(8298, 8304) + range(65529, 65533) + range(119155, 119163))
def in_table_c22(code):
c = ord(code)
if c < 128:
return False
if unicodedata.category(code) == 'Cc':
return True
return c in c22_specials
def in_table_c21_c22(code):
return unicodedata.category(code) == 'Cc' or ord(code) in c22_specials
def in_table_c3(code):
return unicodedata.category(code) == 'Co'
def in_table_c4(code):
c = ord(code)
if c < 64976:
return False
if c < 65008:
return True
return ord(code) & 65535 in (65534, 65535)
def in_table_c5(code):
return unicodedata.category(code) == 'Cs'
c6_set = set(range(65529, 65534))
def in_table_c6(code):
return ord(code) in c6_set
c7_set = set(range(12272, 12284))
def in_table_c7(code):
return ord(code) in c7_set
c8_set = set([832, 833, 8206, 8207] + range(8234, 8239) + range(8298, 8304))
def in_table_c8(code):
return ord(code) in c8_set
c9_set = set([917505] + range(917536, 917632))
def in_table_c9(code):
return ord(code) in c9_set
def in_table_d1(code):
return unicodedata.bidirectional(code) in ('R', 'AL')
def in_table_d2(code):
return unicodedata.bidirectional(code) == 'L' | # uncompyle6 version 3.2.4
# Python bytecode 2.7 (62211)
# Decompiled from: Python 2.7.15 (v2.7.15:ca079a3ea3, Apr 30 2018, 16:30:26) [MSC v.1500 64 bit (AMD64)]
# Embedded file name: stringprep
from unicodedata import ucd_3_2_0 as unicodedata
def in_table_a1(code):
if unicodedata.category(code) != 'Cn':
return False
c = ord(code)
if 64976 <= c < 65008:
return False
return c & 65535 not in (65534, 65535)
b1_set = set([173, 847, 6150, 6155, 6156, 6157, 8203, 8204, 8205, 8288, 65279] + range(65024, 65040))
def in_table_b1(code):
return ord(code) in b1_set
b3_exceptions = {181: u'\u03bc',
223: u'ss', 304: u'i\u0307', 329: u'\u02bcn', 383: u's',
496: u'j\u030c', 837: u'\u03b9', 890: u' \u03b9', 912: u'\u03b9\u0308\u0301',
944: u'\u03c5\u0308\u0301', 962: u'\u03c3', 976: u'\u03b2', 977: u'\u03b8',
978: u'\u03c5', 979: u'\u03cd', 980: u'\u03cb', 981: u'\u03c6',
982: u'\u03c0', 1008: u'\u03ba', 1009: u'\u03c1', 1010: u'\u03c3',
1013: u'\u03b5', 1415: u'\u0565\u0582', 7830: u'h\u0331', 7831: u't\u0308',
7832: u'w\u030a', 7833: u'y\u030a', 7834: u'a\u02be', 7835: u'\u1e61',
8016: u'\u03c5\u0313', 8018: u'\u03c5\u0313\u0300', 8020: u'\u03c5\u0313\u0301', 8022: u'\u03c5\u0313\u0342',
8064: u'\u1f00\u03b9', 8065: u'\u1f01\u03b9', 8066: u'\u1f02\u03b9', 8067: u'\u1f03\u03b9',
8068: u'\u1f04\u03b9', 8069: u'\u1f05\u03b9', 8070: u'\u1f06\u03b9', 8071: u'\u1f07\u03b9',
8072: u'\u1f00\u03b9', 8073: u'\u1f01\u03b9', 8074: u'\u1f02\u03b9', 8075: u'\u1f03\u03b9',
8076: u'\u1f04\u03b9', 8077: u'\u1f05\u03b9', 8078: u'\u1f06\u03b9', 8079: u'\u1f07\u03b9',
8080: u'\u1f20\u03b9', 8081: u'\u1f21\u03b9', 8082: u'\u1f22\u03b9', 8083: u'\u1f23\u03b9',
8084: u'\u1f24\u03b9', 8085: u'\u1f25\u03b9', 8086: u'\u1f26\u03b9', 8087: u'\u1f27\u03b9',
8088: u'\u1f20\u03b9', 8089: u'\u1f21\u03b9', 8090: u'\u1f22\u03b9', 8091: u'\u1f23\u03b9',
8092: u'\u1f24\u03b9', 8093: u'\u1f25\u03b9', 8094: u'\u1f26\u03b9', 8095: u'\u1f27\u03b9',
8096: u'\u1f60\u03b9', 8097: u'\u1f61\u03b9', 8098: u'\u1f62\u03b9', 8099: u'\u1f63\u03b9',
8100: u'\u1f64\u03b9', 8101: u'\u1f65\u03b9', 8102: u'\u1f66\u03b9', 8103: u'\u1f67\u03b9',
8104: u'\u1f60\u03b9', 8105: u'\u1f61\u03b9', 8106: u'\u1f62\u03b9', 8107: u'\u1f63\u03b9',
8108: u'\u1f64\u03b9', 8109: u'\u1f65\u03b9', 8110: u'\u1f66\u03b9', 8111: u'\u1f67\u03b9',
8114: u'\u1f70\u03b9', 8115: u'\u03b1\u03b9', 8116: u'\u03ac\u03b9', 8118: u'\u03b1\u0342',
8119: u'\u03b1\u0342\u03b9', 8124: u'\u03b1\u03b9', 8126: u'\u03b9', 8130: u'\u1f74\u03b9',
8131: u'\u03b7\u03b9', 8132: u'\u03ae\u03b9', 8134: u'\u03b7\u0342', 8135: u'\u03b7\u0342\u03b9',
8140: u'\u03b7\u03b9', 8146: u'\u03b9\u0308\u0300', 8147: u'\u03b9\u0308\u0301', 8150: u'\u03b9\u0342',
8151: u'\u03b9\u0308\u0342', 8162: u'\u03c5\u0308\u0300', 8163: u'\u03c5\u0308\u0301', 8164: u'\u03c1\u0313',
8166: u'\u03c5\u0342', 8167: u'\u03c5\u0308\u0342', 8178: u'\u1f7c\u03b9', 8179: u'\u03c9\u03b9',
8180: u'\u03ce\u03b9', 8182: u'\u03c9\u0342', 8183: u'\u03c9\u0342\u03b9', 8188: u'\u03c9\u03b9',
8360: u'rs', 8450: u'c', 8451: u'\xb0c', 8455: u'\u025b',
8457: u'\xb0f', 8459: u'h', 8460: u'h', 8461: u'h',
8464: u'i', 8465: u'i', 8466: u'l', 8469: u'n',
8470: u'no', 8473: u'p', 8474: u'q', 8475: u'r',
8476: u'r', 8477: u'r', 8480: u'sm', 8481: u'tel',
8482: u'tm', 8484: u'z', 8488: u'z', 8492: u'b',
8493: u'c', 8496: u'e', 8497: u'f', 8499: u'm',
8510: u'\u03b3', 8511: u'\u03c0', 8517: u'd', 13169: u'hpa',
13171: u'au', 13173: u'ov', 13184: u'pa', 13185: u'na',
13186: u'\u03bca', 13187: u'ma', 13188: u'ka', 13189: u'kb',
13190: u'mb', 13191: u'gb', 13194: u'pf', 13195: u'nf',
13196: u'\u03bcf', 13200: u'hz', 13201: u'khz', 13202: u'mhz',
13203: u'ghz', 13204: u'thz', 13225: u'pa', 13226: u'kpa',
13227: u'mpa', 13228: u'gpa', 13236: u'pv', 13237: u'nv',
13238: u'\u03bcv', 13239: u'mv', 13240: u'kv', 13241: u'mv',
13242: u'pw', 13243: u'nw', 13244: u'\u03bcw', 13245: u'mw',
13246: u'kw', 13247: u'mw', 13248: u'k\u03c9', 13249: u'm\u03c9',
13251: u'bq', 13254: u'c\u2215kg', 13255: u'co.', 13256: u'db',
13257: u'gy', 13259: u'hp', 13261: u'kk', 13262: u'km',
13271: u'ph', 13273: u'ppm', 13274: u'pr', 13276: u'sv',
13277: u'wb', 64256: u'ff', 64257: u'fi', 64258: u'fl',
64259: u'ffi', 64260: u'ffl', 64261: u'st', 64262: u'st',
64275: u'\u0574\u0576', 64276: u'\u0574\u0565', 64277: u'\u0574\u056b', 64278: u'\u057e\u0576',
64279: u'\u0574\u056d', 119808: u'a', 119809: u'b', 119810: u'c',
119811: u'd', 119812: u'e', 119813: u'f', 119814: u'g',
119815: u'h', 119816: u'i', 119817: u'j', 119818: u'k',
119819: u'l', 119820: u'm', 119821: u'n', 119822: u'o',
119823: u'p', 119824: u'q', 119825: u'r', 119826: u's',
119827: u't', 119828: u'u', 119829: u'v', 119830: u'w',
119831: u'x', 119832: u'y', 119833: u'z', 119860: u'a',
119861: u'b', 119862: u'c', 119863: u'd', 119864: u'e',
119865: u'f', 119866: u'g', 119867: u'h', 119868: u'i',
119869: u'j', 119870: u'k', 119871: u'l', 119872: u'm',
119873: u'n', 119874: u'o', 119875: u'p', 119876: u'q',
119877: u'r', 119878: u's', 119879: u't', 119880: u'u',
119881: u'v', 119882: u'w', 119883: u'x', 119884: u'y',
119885: u'z', 119912: u'a', 119913: u'b', 119914: u'c',
119915: u'd', 119916: u'e', 119917: u'f', 119918: u'g',
119919: u'h', 119920: u'i', 119921: u'j', 119922: u'k',
119923: u'l', 119924: u'm', 119925: u'n', 119926: u'o',
119927: u'p', 119928: u'q', 119929: u'r', 119930: u's',
119931: u't', 119932: u'u', 119933: u'v', 119934: u'w',
119935: u'x', 119936: u'y', 119937: u'z', 119964: u'a',
119966: u'c', 119967: u'd', 119970: u'g', 119973: u'j',
119974: u'k', 119977: u'n', 119978: u'o', 119979: u'p',
119980: u'q', 119982: u's', 119983: u't', 119984: u'u',
119985: u'v', 119986: u'w', 119987: u'x', 119988: u'y',
119989: u'z', 120016: u'a', 120017: u'b', 120018: u'c',
120019: u'd', 120020: u'e', 120021: u'f', 120022: u'g',
120023: u'h', 120024: u'i', 120025: u'j', 120026: u'k',
120027: u'l', 120028: u'm', 120029: u'n', 120030: u'o',
120031: u'p', 120032: u'q', 120033: u'r', 120034: u's',
120035: u't', 120036: u'u', 120037: u'v', 120038: u'w',
120039: u'x', 120040: u'y', 120041: u'z', 120068: u'a',
120069: u'b', 120071: u'd', 120072: u'e', 120073: u'f',
120074: u'g', 120077: u'j', 120078: u'k', 120079: u'l',
120080: u'm', 120081: u'n', 120082: u'o', 120083: u'p',
120084: u'q', 120086: u's', 120087: u't', 120088: u'u',
120089: u'v', 120090: u'w', 120091: u'x', 120092: u'y',
120120: u'a', 120121: u'b', 120123: u'd', 120124: u'e',
120125: u'f', 120126: u'g', 120128: u'i', 120129: u'j',
120130: u'k', 120131: u'l', 120132: u'm', 120134: u'o',
120138: u's', 120139: u't', 120140: u'u', 120141: u'v',
120142: u'w', 120143: u'x', 120144: u'y', 120172: u'a',
120173: u'b', 120174: u'c', 120175: u'd', 120176: u'e',
120177: u'f', 120178: u'g', 120179: u'h', 120180: u'i',
120181: u'j', 120182: u'k', 120183: u'l', 120184: u'm',
120185: u'n', 120186: u'o', 120187: u'p', 120188: u'q',
120189: u'r', 120190: u's', 120191: u't', 120192: u'u',
120193: u'v', 120194: u'w', 120195: u'x', 120196: u'y',
120197: u'z', 120224: u'a', 120225: u'b', 120226: u'c',
120227: u'd', 120228: u'e', 120229: u'f', 120230: u'g',
120231: u'h', 120232: u'i', 120233: u'j', 120234: u'k',
120235: u'l', 120236: u'm', 120237: u'n', 120238: u'o',
120239: u'p', 120240: u'q', 120241: u'r', 120242: u's',
120243: u't', 120244: u'u', 120245: u'v', 120246: u'w',
120247: u'x', 120248: u'y', 120249: u'z', 120276: u'a',
120277: u'b', 120278: u'c', 120279: u'd', 120280: u'e',
120281: u'f', 120282: u'g', 120283: u'h', 120284: u'i',
120285: u'j', 120286: u'k', 120287: u'l', 120288: u'm',
120289: u'n', 120290: u'o', 120291: u'p', 120292: u'q',
120293: u'r', 120294: u's', 120295: u't', 120296: u'u',
120297: u'v', 120298: u'w', 120299: u'x', 120300: u'y',
120301: u'z', 120328: u'a', 120329: u'b', 120330: u'c',
120331: u'd', 120332: u'e', 120333: u'f', 120334: u'g',
120335: u'h', 120336: u'i', 120337: u'j', 120338: u'k',
120339: u'l', 120340: u'm', 120341: u'n', 120342: u'o',
120343: u'p', 120344: u'q', 120345: u'r', 120346: u's',
120347: u't', 120348: u'u', 120349: u'v', 120350: u'w',
120351: u'x', 120352: u'y', 120353: u'z', 120380: u'a',
120381: u'b', 120382: u'c', 120383: u'd', 120384: u'e',
120385: u'f', 120386: u'g', 120387: u'h', 120388: u'i',
120389: u'j', 120390: u'k', 120391: u'l', 120392: u'm',
120393: u'n', 120394: u'o', 120395: u'p', 120396: u'q',
120397: u'r', 120398: u's', 120399: u't', 120400: u'u',
120401: u'v', 120402: u'w', 120403: u'x', 120404: u'y',
120405: u'z', 120432: u'a', 120433: u'b', 120434: u'c',
120435: u'd', 120436: u'e', 120437: u'f', 120438: u'g',
120439: u'h', 120440: u'i', 120441: u'j', 120442: u'k',
120443: u'l', 120444: u'm', 120445: u'n', 120446: u'o',
120447: u'p', 120448: u'q', 120449: u'r', 120450: u's',
120451: u't', 120452: u'u', 120453: u'v', 120454: u'w',
120455: u'x', 120456: u'y', 120457: u'z', 120488: u'\u03b1',
120489: u'\u03b2', 120490: u'\u03b3', 120491: u'\u03b4', 120492: u'\u03b5',
120493: u'\u03b6', 120494: u'\u03b7', 120495: u'\u03b8', 120496: u'\u03b9',
120497: u'\u03ba', 120498: u'\u03bb', 120499: u'\u03bc', 120500: u'\u03bd',
120501: u'\u03be', 120502: u'\u03bf', 120503: u'\u03c0', 120504: u'\u03c1',
120505: u'\u03b8', 120506: u'\u03c3', 120507: u'\u03c4', 120508: u'\u03c5',
120509: u'\u03c6', 120510: u'\u03c7', 120511: u'\u03c8', 120512: u'\u03c9',
120531: u'\u03c3', 120546: u'\u03b1', 120547: u'\u03b2', 120548: u'\u03b3',
120549: u'\u03b4', 120550: u'\u03b5', 120551: u'\u03b6', 120552: u'\u03b7',
120553: u'\u03b8', 120554: u'\u03b9', 120555: u'\u03ba', 120556: u'\u03bb',
120557: u'\u03bc', 120558: u'\u03bd', 120559: u'\u03be', 120560: u'\u03bf',
120561: u'\u03c0', 120562: u'\u03c1', 120563: u'\u03b8', 120564: u'\u03c3',
120565: u'\u03c4', 120566: u'\u03c5', 120567: u'\u03c6', 120568: u'\u03c7',
120569: u'\u03c8', 120570: u'\u03c9', 120589: u'\u03c3', 120604: u'\u03b1',
120605: u'\u03b2', 120606: u'\u03b3', 120607: u'\u03b4', 120608: u'\u03b5',
120609: u'\u03b6', 120610: u'\u03b7', 120611: u'\u03b8', 120612: u'\u03b9',
120613: u'\u03ba', 120614: u'\u03bb', 120615: u'\u03bc', 120616: u'\u03bd',
120617: u'\u03be', 120618: u'\u03bf', 120619: u'\u03c0', 120620: u'\u03c1',
120621: u'\u03b8', 120622: u'\u03c3', 120623: u'\u03c4', 120624: u'\u03c5',
120625: u'\u03c6', 120626: u'\u03c7', 120627: u'\u03c8', 120628: u'\u03c9',
120647: u'\u03c3', 120662: u'\u03b1', 120663: u'\u03b2', 120664: u'\u03b3',
120665: u'\u03b4', 120666: u'\u03b5', 120667: u'\u03b6', 120668: u'\u03b7',
120669: u'\u03b8', 120670: u'\u03b9', 120671: u'\u03ba', 120672: u'\u03bb',
120673: u'\u03bc', 120674: u'\u03bd', 120675: u'\u03be', 120676: u'\u03bf',
120677: u'\u03c0', 120678: u'\u03c1', 120679: u'\u03b8', 120680: u'\u03c3',
120681: u'\u03c4', 120682: u'\u03c5', 120683: u'\u03c6', 120684: u'\u03c7',
120685: u'\u03c8', 120686: u'\u03c9', 120705: u'\u03c3', 120720: u'\u03b1',
120721: u'\u03b2', 120722: u'\u03b3', 120723: u'\u03b4', 120724: u'\u03b5',
120725: u'\u03b6', 120726: u'\u03b7', 120727: u'\u03b8', 120728: u'\u03b9',
120729: u'\u03ba', 120730: u'\u03bb', 120731: u'\u03bc', 120732: u'\u03bd',
120733: u'\u03be', 120734: u'\u03bf', 120735: u'\u03c0', 120736: u'\u03c1',
120737: u'\u03b8', 120738: u'\u03c3', 120739: u'\u03c4', 120740: u'\u03c5',
120741: u'\u03c6', 120742: u'\u03c7', 120743: u'\u03c8', 120744: u'\u03c9',
120763: u'\u03c3'}
def map_table_b3(code):
r = b3_exceptions.get(ord(code))
if r is not None:
return r
return code.lower()
def map_table_b2(a):
al = map_table_b3(a)
b = unicodedata.normalize('NFKC', al)
bl = (u'').join([ map_table_b3(ch) for ch in b ])
c = unicodedata.normalize('NFKC', bl)
if b != c:
return c
return al
def in_table_c11(code):
return code == u' '
def in_table_c12(code):
return unicodedata.category(code) == 'Zs' and code != u' '
def in_table_c11_c12(code):
return unicodedata.category(code) == 'Zs'
def in_table_c21(code):
return ord(code) < 128 and unicodedata.category(code) == 'Cc'
c22_specials = set([1757, 1807, 6158, 8204, 8205, 8232, 8233, 65279] + range(8288, 8292) + range(8298, 8304) + range(65529, 65533) + range(119155, 119163))
def in_table_c22(code):
c = ord(code)
if c < 128:
return False
if unicodedata.category(code) == 'Cc':
return True
return c in c22_specials
def in_table_c21_c22(code):
return unicodedata.category(code) == 'Cc' or ord(code) in c22_specials
def in_table_c3(code):
return unicodedata.category(code) == 'Co'
def in_table_c4(code):
c = ord(code)
if c < 64976:
return False
if c < 65008:
return True
return ord(code) & 65535 in (65534, 65535)
def in_table_c5(code):
return unicodedata.category(code) == 'Cs'
c6_set = set(range(65529, 65534))
def in_table_c6(code):
return ord(code) in c6_set
c7_set = set(range(12272, 12284))
def in_table_c7(code):
return ord(code) in c7_set
c8_set = set([832, 833, 8206, 8207] + range(8234, 8239) + range(8298, 8304))
def in_table_c8(code):
return ord(code) in c8_set
c9_set = set([917505] + range(917536, 917632))
def in_table_c9(code):
return ord(code) in c9_set
def in_table_d1(code):
return unicodedata.bidirectional(code) in ('R', 'AL')
def in_table_d2(code):
return unicodedata.bidirectional(code) == 'L' | en | 0.573805 | # uncompyle6 version 3.2.4 # Python bytecode 2.7 (62211) # Decompiled from: Python 2.7.15 (v2.7.15:ca079a3ea3, Apr 30 2018, 16:30:26) [MSC v.1500 64 bit (AMD64)] # Embedded file name: stringprep | 2.314346 | 2 |
cmpy/models/tightbinding.py | dylanljones/cmpy | 2 | 6620319 | <reponame>dylanljones/cmpy
# coding: utf-8
#
# This code is part of cmpy.
#
# Copyright (c) 2022, <NAME>
import itertools
import numpy as np
from scipy import sparse
from scipy import linalg as la
from abc import abstractmethod
from lattpy import Lattice
from .abc import AbstractModel
def eigvalsh_chain(num_sites, eps, t):
"""Computes the eigenvalues of the Hamiltonain of a 1D tight-binding model.
Parameters
----------
num_sites : int
The number of lattice sites N in the model.
eps : float or (N) np.ndarray
The on-site energy of the model
t : float
The hopping energy of the model.
Returns
-------
eigvals : (N) np.ndarray
The eigenvalues of the Hamiltonian.
eigvecs : (N, N) np.ndarray
The eigenvectors of the Hamiltonian.
"""
if isinstance(eps, (float, int, complex)):
diag = eps * np.ones(num_sites)
else:
diag = eps
off_diag = t * np.ones(num_sites - 1)
return la.eigvalsh_tridiagonal(diag, off_diag)
def eigh_chain(num_sites, eps, t):
"""Computes the eigen-values and -vectors of the Hamiltonain of a 1D model.
Parameters
----------
num_sites : int
The number of lattice sites N in the model.
eps : float or (N) np.ndarray
The on-site energy of the model
t : float
The hopping energy of the model.
Returns
-------
eigvals : (N) np.ndarray
The eigenvalues of the Hamiltonian.
eigvecs : (N, N) np.ndarray
The eigenvectors of the Hamiltonian.
"""
if isinstance(eps, (float, int, complex)):
diag = eps * np.ones(num_sites)
else:
diag = eps
off_diag = t * np.ones(num_sites - 1)
return la.eigh_tridiagonal(diag, off_diag)
class AbstractTightBinding(Lattice, AbstractModel):
"""Abstract Tight-binding model based on a lattice.
Parameters
----------
vectors : (N, N) array_like
The basis vectors of a lattice.
"""
def __init__(self, vectors):
AbstractModel.__init__(self)
Lattice.__init__(self, vectors)
self.path = None
@abstractmethod
def get_energy(self, alpha=0):
"""Returns the on-site energy of an atom in the unit-cell of the lattice.
Parameters
----------
alpha : int, optional
The index of the atom.
Returns
-------
energy: array_like
The on-site energy of the atom. Can either be a scalar or a square matrix.
"""
pass
@abstractmethod
def get_hopping(self, distidx=0):
"""Returns the hopping-site energy between atoms with a certain distance.
Parameters
----------
distidx : int, optional
The distance index of the atom-pair.
Returns
-------
energy: array_like
The hopping energy. Can either be a scalar or a square matrix.
"""
pass
def analyze(self) -> None:
super().analyze()
self.finalize()
def finalize(self):
"""Called after analyzing the lattice. Parameters should be initialized here."""
pass
def hamiltonian_cell(self, dtype=None):
"""Constructs the hamiltonian of the unit-cell.
Parameters
----------
dtype : str or np.dtype or type, optional
Optional datatype of the resulting matrix.
Returns
-------
ham : (N, N) np.ndarray
The hamiltonian matrix of the unit-cell. The shape is the number of atoms
in the unit-cell.
"""
ham = np.zeros((self.num_base, self.num_base), dtype=dtype)
for alpha in range(self.num_base):
ham[alpha, alpha] = self.get_energy(alpha)
for distidx in range(self.num_distances):
t = self.get_hopping(distidx)
for idx in self.get_neighbors(alpha=alpha, distidx=distidx):
alpha2 = idx[-1]
ham[alpha, alpha2] = t
return ham
def hamiltonian_data(self, dtype=None):
"""Computes the elements of the hamiltonian.
Parameters
----------
dtype : str or np.dtype or type, optional
Optional datatype of the data.
Returns
-------
rows : (N, ) np.ndarray
The row indices of the elements.
cols : (N, ) np.ndarray
The column indices of the elements.
data : (N, ) np.ndarray
The elements of the hamiltonian matrix.
"""
dmap = self.data.map()
data = np.zeros(dmap.size, dtype=dtype)
for alpha in range(self.num_base):
data[dmap.onsite(alpha)] = self.get_energy(alpha)
for distidx in range(self.num_distances):
data[dmap.hopping(distidx)] = self.get_hopping(distidx)
rows, cols = dmap.indices
return rows, cols, data
def hamiltonian(self, dtype=None):
"""Constructs the hamiltonian as a sparse matrix in CSR format.
Parameters
----------
dtype : str or np.dtype or type, optional
Optional datatype of the resulting matrix.
Returns
-------
ham : (N, N) sparse.csr_matrix
The hamiltonian matrix in sparse format.
"""
rows, cols, data = self.hamiltonian_data(dtype)
arg = data, (rows, cols)
return sparse.csr_matrix(arg)
def get_neighbor_vectors_to(self, alpha1, alpha2, distidx=0):
"""Computes the neighbor vector between two sites."""
keys = list(sorted(self._base_neighbors[alpha1].keys()))
dist = keys[distidx]
indices = self._base_neighbors[alpha1][dist]
indices = indices[indices[:, -1] == alpha2]
pos0 = self._positions[alpha1]
positions = self.get_positions(indices)
return positions - pos0
def hamiltonian_kernel(self, k, ham_cell=None):
"""Computes the fourier transformed hamiltonian of the unit-cell.
Parameters
----------
k : (N, ) array_like
The point in frequency-space.
ham_cell : (N, N) array_like, optional
Optional cell-hamiltonian in real-space. If ``None`` the hamiltonian
will be constructed.
Returns
-------
ham_k : (N, N) np.ndarray
The transformed hamiltonian.
"""
if ham_cell is None:
ham_cell = self.hamiltonian_cell(dtype=np.complex64)
ham = ham_cell.copy()
if self.num_base == 1:
ham = np.array([[self.get_energy(0)]], dtype=np.complex64)
for distidx in range(self.num_distances):
ham += self.get_hopping(distidx) * self.fourier_weights(
k, distidx=distidx
)
return ham
for alpha in range(self.num_base):
ham[alpha, alpha] = self.get_energy(alpha)
for distidx in range(self.num_distances):
for alpha2 in range(alpha + 1, self.num_base):
vecs = self.get_neighbor_vectors_to(alpha, alpha2, distidx)
ham[alpha, alpha2] *= np.sum(np.exp(1j * np.inner(k, +vecs)))
ham[alpha2, alpha] *= np.sum(np.exp(1j * np.inner(k, -vecs)))
return ham
def dispersion(self, k, mu=0.0, sort=False):
"""Computes the energy dispersion for one or multiple points in frequency-space.
Parameters
----------
k : (..., N) array_like
The point(s) in frequency-space.
mu : float, optional
The chemical potential.
sort : bool, optional
Flag if energy values are sorted. The default is ``False``.
Returns
-------
disp : (..., N) np.ndarray
The energy values for the given point(s).
"""
k = np.atleast_2d(k)
disp = np.zeros((len(k), self.num_base), dtype=np.float32)
ham_cell = self.hamiltonian_cell()
for i, _k in enumerate(k):
ham_k = self.hamiltonian_kernel(_k, ham_cell)
eigvals = la.eigvalsh(ham_k).real
if sort:
eigvals = np.sort(eigvals)
disp[i] = eigvals
return (disp[0] if len(k) == 1 else disp) - mu
def bands(self, nums=100, mu=0.0, sort=False, offset=0.0, check=True):
brillouin = self.brillouin_zone()
k_ranges = brillouin.linspace(nums, offset)
lengths = [len(k) for k in k_ranges]
bands = np.zeros((*lengths, self.num_base))
ham_cell = self.hamiltonian_cell()
for item in itertools.product(*[range(n) for n in lengths]):
k = np.array([k_ranges[i][item[i]] for i in range(len(k_ranges))])
if not check or brillouin.check(k):
ham_k = self.hamiltonian_kernel(k, ham_cell)
eigvals = la.eigvalsh(ham_k).real
if sort:
eigvals = np.sort(eigvals)
bands[item] = eigvals
else:
bands[item] = np.nan
return k_ranges, bands.T - mu
class BaseTightBindingModel(AbstractTightBinding):
def __init__(self, vectors):
super().__init__(vectors)
def set_energies(self, *eps):
self.set_param("eps", np.array(eps))
def set_hopping(self, *t):
self.set_param("hop", np.array(t))
def get_energy(self, alpha=0):
return self.eps[alpha]
def get_hopping(self, distidx=0):
return self.hop[distidx]
def finalize(self):
self.set_param("eps", np.zeros(self.num_base))
self.set_param("hop", np.ones(self.num_distances))
| # coding: utf-8
#
# This code is part of cmpy.
#
# Copyright (c) 2022, <NAME>
import itertools
import numpy as np
from scipy import sparse
from scipy import linalg as la
from abc import abstractmethod
from lattpy import Lattice
from .abc import AbstractModel
def eigvalsh_chain(num_sites, eps, t):
"""Computes the eigenvalues of the Hamiltonain of a 1D tight-binding model.
Parameters
----------
num_sites : int
The number of lattice sites N in the model.
eps : float or (N) np.ndarray
The on-site energy of the model
t : float
The hopping energy of the model.
Returns
-------
eigvals : (N) np.ndarray
The eigenvalues of the Hamiltonian.
eigvecs : (N, N) np.ndarray
The eigenvectors of the Hamiltonian.
"""
if isinstance(eps, (float, int, complex)):
diag = eps * np.ones(num_sites)
else:
diag = eps
off_diag = t * np.ones(num_sites - 1)
return la.eigvalsh_tridiagonal(diag, off_diag)
def eigh_chain(num_sites, eps, t):
"""Computes the eigen-values and -vectors of the Hamiltonain of a 1D model.
Parameters
----------
num_sites : int
The number of lattice sites N in the model.
eps : float or (N) np.ndarray
The on-site energy of the model
t : float
The hopping energy of the model.
Returns
-------
eigvals : (N) np.ndarray
The eigenvalues of the Hamiltonian.
eigvecs : (N, N) np.ndarray
The eigenvectors of the Hamiltonian.
"""
if isinstance(eps, (float, int, complex)):
diag = eps * np.ones(num_sites)
else:
diag = eps
off_diag = t * np.ones(num_sites - 1)
return la.eigh_tridiagonal(diag, off_diag)
class AbstractTightBinding(Lattice, AbstractModel):
"""Abstract Tight-binding model based on a lattice.
Parameters
----------
vectors : (N, N) array_like
The basis vectors of a lattice.
"""
def __init__(self, vectors):
AbstractModel.__init__(self)
Lattice.__init__(self, vectors)
self.path = None
@abstractmethod
def get_energy(self, alpha=0):
"""Returns the on-site energy of an atom in the unit-cell of the lattice.
Parameters
----------
alpha : int, optional
The index of the atom.
Returns
-------
energy: array_like
The on-site energy of the atom. Can either be a scalar or a square matrix.
"""
pass
@abstractmethod
def get_hopping(self, distidx=0):
"""Returns the hopping-site energy between atoms with a certain distance.
Parameters
----------
distidx : int, optional
The distance index of the atom-pair.
Returns
-------
energy: array_like
The hopping energy. Can either be a scalar or a square matrix.
"""
pass
def analyze(self) -> None:
super().analyze()
self.finalize()
def finalize(self):
"""Called after analyzing the lattice. Parameters should be initialized here."""
pass
def hamiltonian_cell(self, dtype=None):
"""Constructs the hamiltonian of the unit-cell.
Parameters
----------
dtype : str or np.dtype or type, optional
Optional datatype of the resulting matrix.
Returns
-------
ham : (N, N) np.ndarray
The hamiltonian matrix of the unit-cell. The shape is the number of atoms
in the unit-cell.
"""
ham = np.zeros((self.num_base, self.num_base), dtype=dtype)
for alpha in range(self.num_base):
ham[alpha, alpha] = self.get_energy(alpha)
for distidx in range(self.num_distances):
t = self.get_hopping(distidx)
for idx in self.get_neighbors(alpha=alpha, distidx=distidx):
alpha2 = idx[-1]
ham[alpha, alpha2] = t
return ham
def hamiltonian_data(self, dtype=None):
"""Computes the elements of the hamiltonian.
Parameters
----------
dtype : str or np.dtype or type, optional
Optional datatype of the data.
Returns
-------
rows : (N, ) np.ndarray
The row indices of the elements.
cols : (N, ) np.ndarray
The column indices of the elements.
data : (N, ) np.ndarray
The elements of the hamiltonian matrix.
"""
dmap = self.data.map()
data = np.zeros(dmap.size, dtype=dtype)
for alpha in range(self.num_base):
data[dmap.onsite(alpha)] = self.get_energy(alpha)
for distidx in range(self.num_distances):
data[dmap.hopping(distidx)] = self.get_hopping(distidx)
rows, cols = dmap.indices
return rows, cols, data
def hamiltonian(self, dtype=None):
"""Constructs the hamiltonian as a sparse matrix in CSR format.
Parameters
----------
dtype : str or np.dtype or type, optional
Optional datatype of the resulting matrix.
Returns
-------
ham : (N, N) sparse.csr_matrix
The hamiltonian matrix in sparse format.
"""
rows, cols, data = self.hamiltonian_data(dtype)
arg = data, (rows, cols)
return sparse.csr_matrix(arg)
def get_neighbor_vectors_to(self, alpha1, alpha2, distidx=0):
"""Computes the neighbor vector between two sites."""
keys = list(sorted(self._base_neighbors[alpha1].keys()))
dist = keys[distidx]
indices = self._base_neighbors[alpha1][dist]
indices = indices[indices[:, -1] == alpha2]
pos0 = self._positions[alpha1]
positions = self.get_positions(indices)
return positions - pos0
def hamiltonian_kernel(self, k, ham_cell=None):
"""Computes the fourier transformed hamiltonian of the unit-cell.
Parameters
----------
k : (N, ) array_like
The point in frequency-space.
ham_cell : (N, N) array_like, optional
Optional cell-hamiltonian in real-space. If ``None`` the hamiltonian
will be constructed.
Returns
-------
ham_k : (N, N) np.ndarray
The transformed hamiltonian.
"""
if ham_cell is None:
ham_cell = self.hamiltonian_cell(dtype=np.complex64)
ham = ham_cell.copy()
if self.num_base == 1:
ham = np.array([[self.get_energy(0)]], dtype=np.complex64)
for distidx in range(self.num_distances):
ham += self.get_hopping(distidx) * self.fourier_weights(
k, distidx=distidx
)
return ham
for alpha in range(self.num_base):
ham[alpha, alpha] = self.get_energy(alpha)
for distidx in range(self.num_distances):
for alpha2 in range(alpha + 1, self.num_base):
vecs = self.get_neighbor_vectors_to(alpha, alpha2, distidx)
ham[alpha, alpha2] *= np.sum(np.exp(1j * np.inner(k, +vecs)))
ham[alpha2, alpha] *= np.sum(np.exp(1j * np.inner(k, -vecs)))
return ham
def dispersion(self, k, mu=0.0, sort=False):
"""Computes the energy dispersion for one or multiple points in frequency-space.
Parameters
----------
k : (..., N) array_like
The point(s) in frequency-space.
mu : float, optional
The chemical potential.
sort : bool, optional
Flag if energy values are sorted. The default is ``False``.
Returns
-------
disp : (..., N) np.ndarray
The energy values for the given point(s).
"""
k = np.atleast_2d(k)
disp = np.zeros((len(k), self.num_base), dtype=np.float32)
ham_cell = self.hamiltonian_cell()
for i, _k in enumerate(k):
ham_k = self.hamiltonian_kernel(_k, ham_cell)
eigvals = la.eigvalsh(ham_k).real
if sort:
eigvals = np.sort(eigvals)
disp[i] = eigvals
return (disp[0] if len(k) == 1 else disp) - mu
def bands(self, nums=100, mu=0.0, sort=False, offset=0.0, check=True):
brillouin = self.brillouin_zone()
k_ranges = brillouin.linspace(nums, offset)
lengths = [len(k) for k in k_ranges]
bands = np.zeros((*lengths, self.num_base))
ham_cell = self.hamiltonian_cell()
for item in itertools.product(*[range(n) for n in lengths]):
k = np.array([k_ranges[i][item[i]] for i in range(len(k_ranges))])
if not check or brillouin.check(k):
ham_k = self.hamiltonian_kernel(k, ham_cell)
eigvals = la.eigvalsh(ham_k).real
if sort:
eigvals = np.sort(eigvals)
bands[item] = eigvals
else:
bands[item] = np.nan
return k_ranges, bands.T - mu
class BaseTightBindingModel(AbstractTightBinding):
def __init__(self, vectors):
super().__init__(vectors)
def set_energies(self, *eps):
self.set_param("eps", np.array(eps))
def set_hopping(self, *t):
self.set_param("hop", np.array(t))
def get_energy(self, alpha=0):
return self.eps[alpha]
def get_hopping(self, distidx=0):
return self.hop[distidx]
def finalize(self):
self.set_param("eps", np.zeros(self.num_base))
self.set_param("hop", np.ones(self.num_distances)) | en | 0.541442 | # coding: utf-8 # # This code is part of cmpy. # # Copyright (c) 2022, <NAME> Computes the eigenvalues of the Hamiltonain of a 1D tight-binding model. Parameters ---------- num_sites : int The number of lattice sites N in the model. eps : float or (N) np.ndarray The on-site energy of the model t : float The hopping energy of the model. Returns ------- eigvals : (N) np.ndarray The eigenvalues of the Hamiltonian. eigvecs : (N, N) np.ndarray The eigenvectors of the Hamiltonian. Computes the eigen-values and -vectors of the Hamiltonain of a 1D model. Parameters ---------- num_sites : int The number of lattice sites N in the model. eps : float or (N) np.ndarray The on-site energy of the model t : float The hopping energy of the model. Returns ------- eigvals : (N) np.ndarray The eigenvalues of the Hamiltonian. eigvecs : (N, N) np.ndarray The eigenvectors of the Hamiltonian. Abstract Tight-binding model based on a lattice. Parameters ---------- vectors : (N, N) array_like The basis vectors of a lattice. Returns the on-site energy of an atom in the unit-cell of the lattice. Parameters ---------- alpha : int, optional The index of the atom. Returns ------- energy: array_like The on-site energy of the atom. Can either be a scalar or a square matrix. Returns the hopping-site energy between atoms with a certain distance. Parameters ---------- distidx : int, optional The distance index of the atom-pair. Returns ------- energy: array_like The hopping energy. Can either be a scalar or a square matrix. Called after analyzing the lattice. Parameters should be initialized here. Constructs the hamiltonian of the unit-cell. Parameters ---------- dtype : str or np.dtype or type, optional Optional datatype of the resulting matrix. Returns ------- ham : (N, N) np.ndarray The hamiltonian matrix of the unit-cell. The shape is the number of atoms in the unit-cell. Computes the elements of the hamiltonian. Parameters ---------- dtype : str or np.dtype or type, optional Optional datatype of the data. Returns ------- rows : (N, ) np.ndarray The row indices of the elements. cols : (N, ) np.ndarray The column indices of the elements. data : (N, ) np.ndarray The elements of the hamiltonian matrix. Constructs the hamiltonian as a sparse matrix in CSR format. Parameters ---------- dtype : str or np.dtype or type, optional Optional datatype of the resulting matrix. Returns ------- ham : (N, N) sparse.csr_matrix The hamiltonian matrix in sparse format. Computes the neighbor vector between two sites. Computes the fourier transformed hamiltonian of the unit-cell. Parameters ---------- k : (N, ) array_like The point in frequency-space. ham_cell : (N, N) array_like, optional Optional cell-hamiltonian in real-space. If ``None`` the hamiltonian will be constructed. Returns ------- ham_k : (N, N) np.ndarray The transformed hamiltonian. Computes the energy dispersion for one or multiple points in frequency-space. Parameters ---------- k : (..., N) array_like The point(s) in frequency-space. mu : float, optional The chemical potential. sort : bool, optional Flag if energy values are sorted. The default is ``False``. Returns ------- disp : (..., N) np.ndarray The energy values for the given point(s). | 2.718329 | 3 |
mkt/purchase/tests/test_utils_.py | Joergen/zamboni | 0 | 6620320 | import amo
import amo.tests
import waffle
from users.models import UserProfile
from mkt.purchase.utils import payments_enabled
from mkt.site.fixtures import fixture
from test_utils import RequestFactory
class TestUtils(amo.tests.TestCase):
fixtures = fixture('user_2519')
def setUp(self):
self.req = RequestFactory().get('/')
def test_settings(self):
with self.settings(PAYMENT_LIMITED=False):
assert payments_enabled(self.req)
def test_not_flag(self):
with self.settings(PAYMENT_LIMITED=True):
assert not payments_enabled(self.req)
def test_flag(self):
profile = UserProfile.objects.get(pk=2519)
flag = waffle.models.Flag.objects.create(name='override-app-payments')
flag.everyone = None
flag.users.add(profile.user)
flag.save()
self.req.user = profile.user
with self.settings(PAYMENT_LIMITED=True):
assert payments_enabled(self.req)
| import amo
import amo.tests
import waffle
from users.models import UserProfile
from mkt.purchase.utils import payments_enabled
from mkt.site.fixtures import fixture
from test_utils import RequestFactory
class TestUtils(amo.tests.TestCase):
fixtures = fixture('user_2519')
def setUp(self):
self.req = RequestFactory().get('/')
def test_settings(self):
with self.settings(PAYMENT_LIMITED=False):
assert payments_enabled(self.req)
def test_not_flag(self):
with self.settings(PAYMENT_LIMITED=True):
assert not payments_enabled(self.req)
def test_flag(self):
profile = UserProfile.objects.get(pk=2519)
flag = waffle.models.Flag.objects.create(name='override-app-payments')
flag.everyone = None
flag.users.add(profile.user)
flag.save()
self.req.user = profile.user
with self.settings(PAYMENT_LIMITED=True):
assert payments_enabled(self.req)
| none | 1 | 1.823725 | 2 | |
setup.py | craighagan/ssmbotocredentialprovider | 0 | 6620321 | <reponame>craighagan/ssmbotocredentialprovider
#!/usr/bin/env python
import os
from setuptools import setup, find_packages
setup(name='ssmbotocredentialprovider',
version='1.0.1',
description='AWS SSM Credential Provider: create boto sessions which obtain and renew credentials from an AWS SSM device certificate',
author='<NAME>',
author_email='<EMAIL>',
url='https://github.com/craighagan/ssmbotocredentialprovider',
license='MIT',
packages = find_packages(exclude=["test"]),
install_requires=["boto3","requests"],
setup_requires=["pytest-runner"],
tests_require=["pytest", "pytest-runner"],
scripts=["bin/fakemetadata-server.py"],
)
| #!/usr/bin/env python
import os
from setuptools import setup, find_packages
setup(name='ssmbotocredentialprovider',
version='1.0.1',
description='AWS SSM Credential Provider: create boto sessions which obtain and renew credentials from an AWS SSM device certificate',
author='<NAME>',
author_email='<EMAIL>',
url='https://github.com/craighagan/ssmbotocredentialprovider',
license='MIT',
packages = find_packages(exclude=["test"]),
install_requires=["boto3","requests"],
setup_requires=["pytest-runner"],
tests_require=["pytest", "pytest-runner"],
scripts=["bin/fakemetadata-server.py"],
) | ru | 0.26433 | #!/usr/bin/env python | 1.469875 | 1 |
tests/__init__.py | sfshaw/SNR | 1 | 6620322 | <filename>tests/__init__.py
'''Tests for functionality of various components.
'''
| <filename>tests/__init__.py
'''Tests for functionality of various components.
'''
| en | 0.926905 | Tests for functionality of various components. | 1.039784 | 1 |
lib/models/autorf/models/resnet20.py | pprp/pytorch-cifar-model-zoo | 23 | 6620323 | <gh_stars>10-100
from collections import namedtuple
import torch
import torch.nn as nn
from torch.autograd import Variable
from torch.utils.model_zoo import load_url as load_state_dict_from_url
from torchvision.models import ResNet
# from utils.utils import drop_path
from ..operations import *
from ..spaces import OPS
from ..attention_structure import *
Genotype = namedtuple("Genotype", "normal normal_concat")
class CifarRFBasicBlock(nn.Module):
def __init__(self, inplanes, planes, stride, step, genotype):
super(CifarRFBasicBlock, self).__init__()
self._steps = step
self.conv1 = conv3x3(inplanes, planes, stride)
self.bn1 = nn.BatchNorm2d(planes)
self.relu = nn.ReLU()
self.conv2 = conv3x3(planes, planes)
self.bn2 = nn.BatchNorm2d(planes)
self.genotype = genotype
if inplanes != planes:
self.downsample = nn.Sequential(
nn.Conv2d(inplanes, planes, kernel_size=1, stride=stride, bias=False),
nn.BatchNorm2d(planes),
)
else:
self.downsample = lambda x: x
self.stride = stride
self.attention = ReceptiveFieldAttention(planes, genotype=self.genotype)
def forward(self, x):
residual = self.downsample(x)
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
out = self.attention(out)
out = out + residual
out = self.relu(out)
return out
class CifarAttentionBasicBlock(nn.Module):
def __init__(self, inplanes, planes, stride, step, genotype):
super(CifarAttentionBasicBlock, self).__init__()
self.conv1 = conv3x3(inplanes, planes, stride)
self.bn1 = nn.BatchNorm2d(planes)
self.relu = nn.ReLU()
self.conv2 = conv3x3(planes, planes)
self.bn2 = nn.BatchNorm2d(planes)
self.genotype = genotype
if inplanes != planes:
self.downsample = nn.Sequential(
nn.Conv2d(inplanes, planes, kernel_size=1, stride=stride, bias=False),
nn.BatchNorm2d(planes),
)
else:
self.downsample = lambda x: x
self.stride = stride
self._step = step
# print(f"line 158: planes: {planes}")
self.attention = LAAttention(self._step, planes, self.genotype)
def forward(self, x):
residual = self.downsample(x)
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
out = self.attention(out)
out = residual + out
out = self.relu(out)
return out
class CifarAttentionResNet(nn.Module):
def __init__(self, block, n_size, num_classes, genotype):
super(CifarAttentionResNet, self).__init__()
self.inplane = 16
self.genotype = genotype
self.channel_in = 16
self.conv1 = nn.Conv2d(
3, self.inplane, kernel_size=3, stride=1, padding=1, bias=False
)
self.bn1 = nn.BatchNorm2d(self.inplane)
self.relu = nn.ReLU()
self._step = 4
self.layer1 = self._make_layer(
block,
self.channel_in,
blocks=n_size,
stride=1,
step=self._step,
genotype=self.genotype,
)
self.layer2 = self._make_layer(
block,
self.channel_in * 2,
blocks=n_size,
stride=2,
step=self._step,
genotype=self.genotype,
)
self.layer3 = self._make_layer(
block,
self.channel_in * 4,
blocks=n_size,
stride=2,
step=self._step,
genotype=self.genotype,
)
self.avgpool = nn.AdaptiveAvgPool2d(1)
self.fc = nn.Linear(self.channel_in * 4, num_classes)
def initialize(self):
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight)
elif isinstance(m, nn.BatchNorm2d):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
def _make_layer(self, block, planes, blocks, stride, step, genotype):
strides = [stride] + [1] * (blocks - 1)
self.layers = nn.ModuleList()
for stride in strides:
Block = block(self.inplane, planes, stride, step, genotype)
self.layers += [Block]
self.inplane = planes
return self.layers
def forward(self, x):
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
for i, layer in enumerate(self.layer1):
x = layer(x)
for i, layer in enumerate(self.layer2):
x = layer(x)
for i, layer in enumerate(self.layer3):
x = layer(x)
x = self.avgpool(x)
x = x.view(x.size(0), -1)
x = self.fc(x)
return x
def rf_resnet20(**kwargs):
model = CifarAttentionResNet(CifarRFBasicBlock, 3, **kwargs)
return model
def attention_resnet20(num_classes, genotype, **kwargs):
"""Constructs a ResNet-20 model."""
model = CifarAttentionResNet(
CifarAttentionBasicBlock, 3, num_classes, genotype, **kwargs
)
return model
def attention_resnet32(**kwargs):
"""Constructs a ResNet-32 model."""
model = CifarAttentionResNet(CifarAttentionBasicBlock, 5, **kwargs)
return model
if __name__ == "__main__":
g = Genotype(
normal=[
("max_pool_3x3", 0),
("max_pool_3x3", 0),
("noise", 1),
("avg_pool_5x5", 0),
("noise", 1),
("noise", 2),
],
normal_concat=range(0, 4),
)
m = CifarRFBasicBlock(16, 8, 1, 3, g)
i = torch.zeros(3, 16, 32, 32)
o = m(i)
print(o.shape)
| from collections import namedtuple
import torch
import torch.nn as nn
from torch.autograd import Variable
from torch.utils.model_zoo import load_url as load_state_dict_from_url
from torchvision.models import ResNet
# from utils.utils import drop_path
from ..operations import *
from ..spaces import OPS
from ..attention_structure import *
Genotype = namedtuple("Genotype", "normal normal_concat")
class CifarRFBasicBlock(nn.Module):
def __init__(self, inplanes, planes, stride, step, genotype):
super(CifarRFBasicBlock, self).__init__()
self._steps = step
self.conv1 = conv3x3(inplanes, planes, stride)
self.bn1 = nn.BatchNorm2d(planes)
self.relu = nn.ReLU()
self.conv2 = conv3x3(planes, planes)
self.bn2 = nn.BatchNorm2d(planes)
self.genotype = genotype
if inplanes != planes:
self.downsample = nn.Sequential(
nn.Conv2d(inplanes, planes, kernel_size=1, stride=stride, bias=False),
nn.BatchNorm2d(planes),
)
else:
self.downsample = lambda x: x
self.stride = stride
self.attention = ReceptiveFieldAttention(planes, genotype=self.genotype)
def forward(self, x):
residual = self.downsample(x)
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
out = self.attention(out)
out = out + residual
out = self.relu(out)
return out
class CifarAttentionBasicBlock(nn.Module):
def __init__(self, inplanes, planes, stride, step, genotype):
super(CifarAttentionBasicBlock, self).__init__()
self.conv1 = conv3x3(inplanes, planes, stride)
self.bn1 = nn.BatchNorm2d(planes)
self.relu = nn.ReLU()
self.conv2 = conv3x3(planes, planes)
self.bn2 = nn.BatchNorm2d(planes)
self.genotype = genotype
if inplanes != planes:
self.downsample = nn.Sequential(
nn.Conv2d(inplanes, planes, kernel_size=1, stride=stride, bias=False),
nn.BatchNorm2d(planes),
)
else:
self.downsample = lambda x: x
self.stride = stride
self._step = step
# print(f"line 158: planes: {planes}")
self.attention = LAAttention(self._step, planes, self.genotype)
def forward(self, x):
residual = self.downsample(x)
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
out = self.attention(out)
out = residual + out
out = self.relu(out)
return out
class CifarAttentionResNet(nn.Module):
def __init__(self, block, n_size, num_classes, genotype):
super(CifarAttentionResNet, self).__init__()
self.inplane = 16
self.genotype = genotype
self.channel_in = 16
self.conv1 = nn.Conv2d(
3, self.inplane, kernel_size=3, stride=1, padding=1, bias=False
)
self.bn1 = nn.BatchNorm2d(self.inplane)
self.relu = nn.ReLU()
self._step = 4
self.layer1 = self._make_layer(
block,
self.channel_in,
blocks=n_size,
stride=1,
step=self._step,
genotype=self.genotype,
)
self.layer2 = self._make_layer(
block,
self.channel_in * 2,
blocks=n_size,
stride=2,
step=self._step,
genotype=self.genotype,
)
self.layer3 = self._make_layer(
block,
self.channel_in * 4,
blocks=n_size,
stride=2,
step=self._step,
genotype=self.genotype,
)
self.avgpool = nn.AdaptiveAvgPool2d(1)
self.fc = nn.Linear(self.channel_in * 4, num_classes)
def initialize(self):
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight)
elif isinstance(m, nn.BatchNorm2d):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
def _make_layer(self, block, planes, blocks, stride, step, genotype):
strides = [stride] + [1] * (blocks - 1)
self.layers = nn.ModuleList()
for stride in strides:
Block = block(self.inplane, planes, stride, step, genotype)
self.layers += [Block]
self.inplane = planes
return self.layers
def forward(self, x):
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
for i, layer in enumerate(self.layer1):
x = layer(x)
for i, layer in enumerate(self.layer2):
x = layer(x)
for i, layer in enumerate(self.layer3):
x = layer(x)
x = self.avgpool(x)
x = x.view(x.size(0), -1)
x = self.fc(x)
return x
def rf_resnet20(**kwargs):
model = CifarAttentionResNet(CifarRFBasicBlock, 3, **kwargs)
return model
def attention_resnet20(num_classes, genotype, **kwargs):
"""Constructs a ResNet-20 model."""
model = CifarAttentionResNet(
CifarAttentionBasicBlock, 3, num_classes, genotype, **kwargs
)
return model
def attention_resnet32(**kwargs):
"""Constructs a ResNet-32 model."""
model = CifarAttentionResNet(CifarAttentionBasicBlock, 5, **kwargs)
return model
if __name__ == "__main__":
g = Genotype(
normal=[
("max_pool_3x3", 0),
("max_pool_3x3", 0),
("noise", 1),
("avg_pool_5x5", 0),
("noise", 1),
("noise", 2),
],
normal_concat=range(0, 4),
)
m = CifarRFBasicBlock(16, 8, 1, 3, g)
i = torch.zeros(3, 16, 32, 32)
o = m(i)
print(o.shape) | en | 0.627962 | # from utils.utils import drop_path # print(f"line 158: planes: {planes}") Constructs a ResNet-20 model. Constructs a ResNet-32 model. | 2.385843 | 2 |
shakepay_api/authentication.py | redviking1/shakepay-python-interface | 3 | 6620324 | <gh_stars>1-10
import json
import random
import requests
from os import error
"""Sign into shakepay account using a given username and password.
returns dictionary which will contain an error if status is -1.
VERIFY_LOGIN_EMAIL -> Check emails to approve login, then rerun the method with the returned account.
INVALID_ACCOUNT -> Account username/password combonation doesn't exist.
REQUIRE_MFA -> MFA Token is required, rerun with the returned account and MFA token.
API_RATE_LIMITED -> Cloudflair has banned your IP, you are being rate limited.
INVALID_MFA_TOKEN -> MFA token is invalid
"""
def authenticate(username, password, account=None, mfa=None):
# Check if a mfa token is provided,
# if its not proform a simple login
if mfa == None:
# If an account is passed, use it insted
if account == None:
# Generate a fake device to attach authentication to
profile = __generateDeviceProfile()
else:
profile = account
# Request authentication
resp = requests.post(
url='https://api.shakepay.com/authentication',
headers=profile,
data=f'{{"strategy":"local","username":"{username}","password":"{password}","totpType":"sms"}}'
)
# Account login verification required
if resp.status_code == 403:
return {"status": -1, "authentication": profile, "error": "VERIFY_LOGIN_EMAIL"}
# Invalid email or password
if resp.status_code == 401:
return {"status": -1, "error": "INVALID_ACCOUNT"}
# Authentication token successfully requested
if resp.status_code == 201:
profile['Authorization'] = json.loads(resp.text)['accessToken']
# Check to see if they need a MFA token
if __checkMFA(profile):
return {"status": -1, "authentication": profile, "error": "REQUIRE_MFA"}
return {"status": 1, "authentication": profile}
if resp.status_code == 429:
return {"status": -1, "error": "API_RATE_LIMITED"}
# If a mfa token is provided,
# proform a mfa login
if mfa != None:
data = f'{{"strategy":"mfa","mfaToken":"{mfa}"}}'
resp = requests.post(
url='https://api.shakepay.com/authentication',
headers=account,
data=data
)
# Authentication token successfully requested
if resp.status_code == 201:
account['Authorization'] = json.loads(resp.text)['accessToken']
return {"status": 1, "authentication": account}
# MFA token was invalid
if resp.status_code == 401:
return {"status": -1, "error": "INVALID_MFA_TOKEN"}
"""Saves authentication data with given name."""
def saveAccount(auth, filename):
try:
with open(f'{filename}.json', 'w') as file:
json.dump(auth, file)
except:
error(f"Unable to write {filename}.json!")
"""Loads authentication data with given name."""
def loadAccount(filename):
try:
with open(f'{filename}.json', 'r') as file:
return json.load(file)
except:
error(f"Unable to load {filename}.json!")
#######################################################################################################################################
"""Check for multifactor authentication (PRIVATE).
Return true if MFA code is needed, false otherwise."""
def __checkMFA(account):
resp = requests.get(
url='https://api.shakepay.com/wallets',
headers=account,
data=''
)
responce = json.loads(resp.text)
if responce["name"] == "NotAuthenticated":
return True
return False
"""Generate a fake phone profile (PRIVATE)."""
def __generateDeviceProfile():
return {
'Host': 'api.shakepay.com',
'x-device-serial-number': '',
'x-device-name': __generateRandomText(11),
'x-device-has-notch': 'false',
'User-Agent': 'Shakepay App v1.7.24 (17024) on Apple iPhone 8 (iOS 14.6)',
'x-device-locale': 'en-CA',
'x-device-manufacturer': 'Apple',
'x-device-is-tablet': 'false',
'x-device-total-disk-capacity': '63978983424',
'x-device-system-name': 'Created by',
'x-device-carrier': ['Koodo', 'Telus', 'React', 'NextJS', 'Public', 'v8engine'][random.randint(0, 5)],
'x-device-model': 'Python API Interface',
'x-device-id': 'iPhone10,4',
'x-device-total-memory': '2070495232',
'x-device-country': 'CA',
'x-device-mac-address': '02:00:00:00:00:00',
'Connection': 'keep-alive',
'x-device-tzoffset': '240',
'Accept-Language': 'en-ca',
'x-device-ip-address': f'192.168.1.{random.randint(5,200)}',
'x-device-unique-id': f'{__generateRandomID(8, True)}-{__generateRandomID(4, True)}-{__generateRandomID(4, True)}-{__generateRandomID(4, True)}-{__generateRandomID(12, True)}',
'x-notification-token': f'{__generateRandomID(22, False)}:{__generateRandomID(116, False)}_{__generateRandomID(10, False)}-{__generateRandomID(12, False)}',
'Content-Type': 'application/json',
'Accept': 'application/json',
'x-device-brand': 'Apple',
'Accept-Encoding': 'gzip, deflate, br',
'x-device-system-version': 'Quzique',
}
"""Used to generate authentication data (PRIVATE)."""
def __generateRandomText(length):
temp = [['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'][random.randint(0,25)] for x in range(length)]
return ''.join([temp[n].upper() if random.randint(0, 1) == 1 else temp[n] for n in range(length)])
"""Used to generate authentication data (PRIVATE)."""
def __generateRandomID(length, caplocks=False):
temp = [['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'][random.randint(0,35)] for x in range(length)]
return ''.join([temp[n].upper() if random.randint(0, 1) == 1 or caplocks else temp[n] for n in range(length)])
| import json
import random
import requests
from os import error
"""Sign into shakepay account using a given username and password.
returns dictionary which will contain an error if status is -1.
VERIFY_LOGIN_EMAIL -> Check emails to approve login, then rerun the method with the returned account.
INVALID_ACCOUNT -> Account username/password combonation doesn't exist.
REQUIRE_MFA -> MFA Token is required, rerun with the returned account and MFA token.
API_RATE_LIMITED -> Cloudflair has banned your IP, you are being rate limited.
INVALID_MFA_TOKEN -> MFA token is invalid
"""
def authenticate(username, password, account=None, mfa=None):
# Check if a mfa token is provided,
# if its not proform a simple login
if mfa == None:
# If an account is passed, use it insted
if account == None:
# Generate a fake device to attach authentication to
profile = __generateDeviceProfile()
else:
profile = account
# Request authentication
resp = requests.post(
url='https://api.shakepay.com/authentication',
headers=profile,
data=f'{{"strategy":"local","username":"{username}","password":"{password}","totpType":"sms"}}'
)
# Account login verification required
if resp.status_code == 403:
return {"status": -1, "authentication": profile, "error": "VERIFY_LOGIN_EMAIL"}
# Invalid email or password
if resp.status_code == 401:
return {"status": -1, "error": "INVALID_ACCOUNT"}
# Authentication token successfully requested
if resp.status_code == 201:
profile['Authorization'] = json.loads(resp.text)['accessToken']
# Check to see if they need a MFA token
if __checkMFA(profile):
return {"status": -1, "authentication": profile, "error": "REQUIRE_MFA"}
return {"status": 1, "authentication": profile}
if resp.status_code == 429:
return {"status": -1, "error": "API_RATE_LIMITED"}
# If a mfa token is provided,
# proform a mfa login
if mfa != None:
data = f'{{"strategy":"mfa","mfaToken":"{mfa}"}}'
resp = requests.post(
url='https://api.shakepay.com/authentication',
headers=account,
data=data
)
# Authentication token successfully requested
if resp.status_code == 201:
account['Authorization'] = json.loads(resp.text)['accessToken']
return {"status": 1, "authentication": account}
# MFA token was invalid
if resp.status_code == 401:
return {"status": -1, "error": "INVALID_MFA_TOKEN"}
"""Saves authentication data with given name."""
def saveAccount(auth, filename):
try:
with open(f'{filename}.json', 'w') as file:
json.dump(auth, file)
except:
error(f"Unable to write {filename}.json!")
"""Loads authentication data with given name."""
def loadAccount(filename):
try:
with open(f'{filename}.json', 'r') as file:
return json.load(file)
except:
error(f"Unable to load {filename}.json!")
#######################################################################################################################################
"""Check for multifactor authentication (PRIVATE).
Return true if MFA code is needed, false otherwise."""
def __checkMFA(account):
resp = requests.get(
url='https://api.shakepay.com/wallets',
headers=account,
data=''
)
responce = json.loads(resp.text)
if responce["name"] == "NotAuthenticated":
return True
return False
"""Generate a fake phone profile (PRIVATE)."""
def __generateDeviceProfile():
return {
'Host': 'api.shakepay.com',
'x-device-serial-number': '',
'x-device-name': __generateRandomText(11),
'x-device-has-notch': 'false',
'User-Agent': 'Shakepay App v1.7.24 (17024) on Apple iPhone 8 (iOS 14.6)',
'x-device-locale': 'en-CA',
'x-device-manufacturer': 'Apple',
'x-device-is-tablet': 'false',
'x-device-total-disk-capacity': '63978983424',
'x-device-system-name': 'Created by',
'x-device-carrier': ['Koodo', 'Telus', 'React', 'NextJS', 'Public', 'v8engine'][random.randint(0, 5)],
'x-device-model': 'Python API Interface',
'x-device-id': 'iPhone10,4',
'x-device-total-memory': '2070495232',
'x-device-country': 'CA',
'x-device-mac-address': '02:00:00:00:00:00',
'Connection': 'keep-alive',
'x-device-tzoffset': '240',
'Accept-Language': 'en-ca',
'x-device-ip-address': f'192.168.1.{random.randint(5,200)}',
'x-device-unique-id': f'{__generateRandomID(8, True)}-{__generateRandomID(4, True)}-{__generateRandomID(4, True)}-{__generateRandomID(4, True)}-{__generateRandomID(12, True)}',
'x-notification-token': f'{__generateRandomID(22, False)}:{__generateRandomID(116, False)}_{__generateRandomID(10, False)}-{__generateRandomID(12, False)}',
'Content-Type': 'application/json',
'Accept': 'application/json',
'x-device-brand': 'Apple',
'Accept-Encoding': 'gzip, deflate, br',
'x-device-system-version': 'Quzique',
}
"""Used to generate authentication data (PRIVATE)."""
def __generateRandomText(length):
temp = [['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'][random.randint(0,25)] for x in range(length)]
return ''.join([temp[n].upper() if random.randint(0, 1) == 1 else temp[n] for n in range(length)])
"""Used to generate authentication data (PRIVATE)."""
def __generateRandomID(length, caplocks=False):
temp = [['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'][random.randint(0,35)] for x in range(length)]
return ''.join([temp[n].upper() if random.randint(0, 1) == 1 or caplocks else temp[n] for n in range(length)]) | en | 0.645087 | Sign into shakepay account using a given username and password. returns dictionary which will contain an error if status is -1. VERIFY_LOGIN_EMAIL -> Check emails to approve login, then rerun the method with the returned account. INVALID_ACCOUNT -> Account username/password combonation doesn't exist. REQUIRE_MFA -> MFA Token is required, rerun with the returned account and MFA token. API_RATE_LIMITED -> Cloudflair has banned your IP, you are being rate limited. INVALID_MFA_TOKEN -> MFA token is invalid # Check if a mfa token is provided, # if its not proform a simple login # If an account is passed, use it insted # Generate a fake device to attach authentication to # Request authentication # Account login verification required # Invalid email or password # Authentication token successfully requested # Check to see if they need a MFA token # If a mfa token is provided, # proform a mfa login # Authentication token successfully requested # MFA token was invalid Saves authentication data with given name. Loads authentication data with given name. ####################################################################################################################################### Check for multifactor authentication (PRIVATE). Return true if MFA code is needed, false otherwise. Generate a fake phone profile (PRIVATE). Used to generate authentication data (PRIVATE). Used to generate authentication data (PRIVATE). | 3.181045 | 3 |
website/forms/email_form.py | JamesBrofos/Thor-Server | 0 | 6620325 | from flask_wtf import FlaskForm
from wtforms import TextField, SubmitField
from wtforms.validators import Required, Email
class EmailForm(FlaskForm):
email = TextField("Email", validators=[
Required(message="You must enter an email."),
Email()
])
submit = SubmitField("Submit")
| from flask_wtf import FlaskForm
from wtforms import TextField, SubmitField
from wtforms.validators import Required, Email
class EmailForm(FlaskForm):
email = TextField("Email", validators=[
Required(message="You must enter an email."),
Email()
])
submit = SubmitField("Submit")
| none | 1 | 2.896866 | 3 | |
Day6/list.py | ananthramas/pythonEducation | 0 | 6620326 | <reponame>ananthramas/pythonEducation
student_list = ["Komali", "Navin & Navya","Udeepth", "Akshar","Adityamithran"]
# Index starts from 0
long_name = student_list[0]
for student_name in student_list :
if len(student_name) > len(long_name) :
long_name = student_name
print(long_name)
| student_list = ["Komali", "Navin & Navya","Udeepth", "Akshar","Adityamithran"]
# Index starts from 0
long_name = student_list[0]
for student_name in student_list :
if len(student_name) > len(long_name) :
long_name = student_name
print(long_name) | en | 0.84309 | # Index starts from 0 | 3.949843 | 4 |
tamr_client/_types/transformations.py | ianbakst/tamr-client | 9 | 6620327 | <filename>tamr_client/_types/transformations.py
from dataclasses import dataclass, field
from typing import List
from tamr_client._types import Dataset
@dataclass(frozen=True)
class InputTransformation:
transformation: str
datasets: List[Dataset] = field(default_factory=list)
@dataclass(frozen=True)
class Transformations:
input_scope: List[InputTransformation] = field(default_factory=list)
unified_scope: List[str] = field(default_factory=list)
| <filename>tamr_client/_types/transformations.py
from dataclasses import dataclass, field
from typing import List
from tamr_client._types import Dataset
@dataclass(frozen=True)
class InputTransformation:
transformation: str
datasets: List[Dataset] = field(default_factory=list)
@dataclass(frozen=True)
class Transformations:
input_scope: List[InputTransformation] = field(default_factory=list)
unified_scope: List[str] = field(default_factory=list)
| none | 1 | 1.995264 | 2 | |
language/_java.py | tushortz/intellekt | 18 | 6620328 | <reponame>tushortz/intellekt
import html
import json
import os
import re
from urllib import request
from . import helpers
JAVASE_CONTENTS = helpers.get_content_to_json("javase.json")
JAVAFX_CONTENTS = helpers.get_content_to_json("javafx.json")
def _get_methods(json_data, package_name, class_name):
methods = []
for content in json_data:
p = content.get("p")
c = content.get("c")
l = content.get("l")
if l.isupper():
symbol = "▢"
elif l[0].isupper() and l[1].islower():
symbol = "◼"
else:
symbol = "➛"
if p == package_name and c == class_name:
left_display = "{0} {1}\t{2}".format(symbol, l, c)
methods.append([left_display, helpers.placeholder_format(l)])
elif p == package_name and class_name == "*":
left_display = "{0} {1}\t{2}".format(symbol, l, c)
methods.append([left_display, helpers.placeholder_format(l)])
return methods
def get_methods(package_name, class_name="*"):
data = _get_methods(JAVASE_CONTENTS, package_name, class_name)
if not data:
data = _get_methods(JAVAFX_CONTENTS, package_name, class_name)
return data
def get_imports_from_view(view_text):
imports = sorted(set(re.findall(
r"((?:java|javax|javafx|com|org)\.[a-z0-9\_\.]+)\.([_A-Z\*][\w_\.]*)", view_text)))
specials = {}
for i in imports:
if i[1] == "*":
specials[i[0]] = i[1]
filtered_imports = []
for i in imports:
if i[0] not in specials or i[1] == "*":
filtered_imports.append(i)
return filtered_imports
def suggest_import(line_text):
imports = re.search(
r"import ((java|javax|javafx|com|org)\.[\w\.]+)", line_text, re.I)
if not imports:
return
imports = imports.group(1)
suggestions = []
for content in JAVASE_CONTENTS + JAVAFX_CONTENTS:
p = content.get("p")
c = content.get("c")
import_text = "{0}.{1}".format(p, c)
if re.match(imports, import_text):
suggestions.append(
"<a href='{0}'>{1}</a>".format(get_url(import_text), import_text))
suggestions = sorted(set(suggestions))
suggestions = "<br>".join(suggestions)
return suggestions
def get_url(text):
url_prefix = "https://docs.oracle.com/javase/10/docs/api/{0}.html"
if text.endswith("*") or text.endswith("."):
url_prefix = "https://docs.oracle.com/javase/10/docs/api/{0}/package-summary.html"
text = text.rsplit(".", 1)[0]
url = text.replace(".", "/")
url = url_prefix.format(url)
return url
def get_documentation(line_text):
imports = re.search(
r"import ((java|javax|javafx|com|org)\.[\w\.]+)", line_text, re.I)
if not imports:
return
imports = imports.group(1)
url = get_url(imports)
r = request.urlopen(url).read().decode("utf-8")
data = re.search(r'<div class="block">(.*?)(?:</div|h2)>', r, re.DOTALL)
if not data:
return
if data:
data = data.group(1).strip(".")
data = data.encode('ascii', 'ignore').decode("utf-8")
data = "<strong>{0}</strong><br><br>{1}".format(imports, data)
return data
| import html
import json
import os
import re
from urllib import request
from . import helpers
JAVASE_CONTENTS = helpers.get_content_to_json("javase.json")
JAVAFX_CONTENTS = helpers.get_content_to_json("javafx.json")
def _get_methods(json_data, package_name, class_name):
methods = []
for content in json_data:
p = content.get("p")
c = content.get("c")
l = content.get("l")
if l.isupper():
symbol = "▢"
elif l[0].isupper() and l[1].islower():
symbol = "◼"
else:
symbol = "➛"
if p == package_name and c == class_name:
left_display = "{0} {1}\t{2}".format(symbol, l, c)
methods.append([left_display, helpers.placeholder_format(l)])
elif p == package_name and class_name == "*":
left_display = "{0} {1}\t{2}".format(symbol, l, c)
methods.append([left_display, helpers.placeholder_format(l)])
return methods
def get_methods(package_name, class_name="*"):
data = _get_methods(JAVASE_CONTENTS, package_name, class_name)
if not data:
data = _get_methods(JAVAFX_CONTENTS, package_name, class_name)
return data
def get_imports_from_view(view_text):
imports = sorted(set(re.findall(
r"((?:java|javax|javafx|com|org)\.[a-z0-9\_\.]+)\.([_A-Z\*][\w_\.]*)", view_text)))
specials = {}
for i in imports:
if i[1] == "*":
specials[i[0]] = i[1]
filtered_imports = []
for i in imports:
if i[0] not in specials or i[1] == "*":
filtered_imports.append(i)
return filtered_imports
def suggest_import(line_text):
imports = re.search(
r"import ((java|javax|javafx|com|org)\.[\w\.]+)", line_text, re.I)
if not imports:
return
imports = imports.group(1)
suggestions = []
for content in JAVASE_CONTENTS + JAVAFX_CONTENTS:
p = content.get("p")
c = content.get("c")
import_text = "{0}.{1}".format(p, c)
if re.match(imports, import_text):
suggestions.append(
"<a href='{0}'>{1}</a>".format(get_url(import_text), import_text))
suggestions = sorted(set(suggestions))
suggestions = "<br>".join(suggestions)
return suggestions
def get_url(text):
url_prefix = "https://docs.oracle.com/javase/10/docs/api/{0}.html"
if text.endswith("*") or text.endswith("."):
url_prefix = "https://docs.oracle.com/javase/10/docs/api/{0}/package-summary.html"
text = text.rsplit(".", 1)[0]
url = text.replace(".", "/")
url = url_prefix.format(url)
return url
def get_documentation(line_text):
imports = re.search(
r"import ((java|javax|javafx|com|org)\.[\w\.]+)", line_text, re.I)
if not imports:
return
imports = imports.group(1)
url = get_url(imports)
r = request.urlopen(url).read().decode("utf-8")
data = re.search(r'<div class="block">(.*?)(?:</div|h2)>', r, re.DOTALL)
if not data:
return
if data:
data = data.group(1).strip(".")
data = data.encode('ascii', 'ignore').decode("utf-8")
data = "<strong>{0}</strong><br><br>{1}".format(imports, data)
return data | none | 1 | 2.810314 | 3 | |
python/infraxys_aliyun/helper.py | infraxys-alicloud/ali-commons | 0 | 6620329 | from os.path import expanduser
from infraxys.json.json_utils import JsonUtils
from aliyunsdkcore.client import AcsClient
from infraxys.logger import Logger
class AliyunHelper(object):
@staticmethod
def get_client(profile_name):
logger = Logger.get_logger(AliyunHelper.__class__.__name__)
logger.info("Retrieving Aliyun profile details from ~/.aliyun/config.json")
user_home = expanduser("~")
config_json = JsonUtils.get_instance().load_from_file(f'{user_home}/.aliyun/config.json')
for profile_json in config_json['profiles']:
if profile_json['name'] == profile_name:
access_key_id = profile_json['access_key_id']
access_key_secret = profile_json['access_key_secret']
region_id = profile_json['region_id']
if not access_key_id:
raise Exception(f'Aliyun profile {profile_name} not found.')
client = AcsClient(ak=access_key_id, secret=access_key_secret, region_id=region_id)
return client | from os.path import expanduser
from infraxys.json.json_utils import JsonUtils
from aliyunsdkcore.client import AcsClient
from infraxys.logger import Logger
class AliyunHelper(object):
@staticmethod
def get_client(profile_name):
logger = Logger.get_logger(AliyunHelper.__class__.__name__)
logger.info("Retrieving Aliyun profile details from ~/.aliyun/config.json")
user_home = expanduser("~")
config_json = JsonUtils.get_instance().load_from_file(f'{user_home}/.aliyun/config.json')
for profile_json in config_json['profiles']:
if profile_json['name'] == profile_name:
access_key_id = profile_json['access_key_id']
access_key_secret = profile_json['access_key_secret']
region_id = profile_json['region_id']
if not access_key_id:
raise Exception(f'Aliyun profile {profile_name} not found.')
client = AcsClient(ak=access_key_id, secret=access_key_secret, region_id=region_id)
return client | none | 1 | 1.996419 | 2 | |
external_tools/src/main/python/images/qc_mappings.py | mpi2/PhenotypeData | 1 | 6620330 | """Mappings for entities that used by scripts in this directory
"""
# Phenotype centres in Solr have spaces, but in some of the code the spaces
# removed. This maps from
SITES_SPACES_TO_NOSPACES_MAP = {
'UC Davies': 'UCD',
'MRC Harwell': 'HRWL',
}
SITES_NOSPACES_TO_SPACES_MAP = {
'UCD': 'UC Davis',
'HRWL': 'MRC Harwell',
}
PARAMETER_ID_TO_CLASS_MAP = {
'034': 3, # whole_body_dorsal
'048': 4, # whole_body_lateral
'049': 2, # forepaw
'050': 5, # head_lateral
'051': 1, # head_dorsal
'052': 6, # hind_leg_hip
}
CLASS_TO_PARAMETER_ID_MAP = {
1: '051', # head_dorsal
2: '049', # forepaw
3: '034', # whole_body_dorsal
4: '048', # whole_body_lateral
5: '050', # head_lateral
6: '052', # hind_leg_hip
}
STRUCTURE_TO_LABEL_MAP = {
"head_dorsal": 1,
"forepaw": 2,
"whole_body_dorsal": 3,
"whole_body_lateral": 4,
"head_lateral": 5,
"hind_leg_hip": 6,
"unreadable_image": -1,
"uncategorisable_image": -2
}
LABEL_TO_STRUCTURE_MAP = {
1: "head_dorsal",
2: "forepaw",
3: "whole_body_dorsal",
4: "whole_body_lateral",
5: "head_lateral",
6: "hind_leg_hip",
-1: "unreadable_image",
-2: "uncategorisable_image"
}
def sites_spaces_to_nospaces_map(site):
"""Map site with spaces to site with no spaces.
"""
if site.count(" ") == 0:
return site
else:
return SITES_SPACES_TO_NOSPACES_MAP[site]
def sites_nospaces_to_spaces_map(site):
"""Map site with no spaces to site with spaces.
"""
try:
return SITES_NOSPACES_TO_SPACES_MAP[site]
except KeyError:
return site
def parameter_id_to_class_map(pid):
"""Return class for parameter stable ID"""
# Assumes parameter ID of form *_XRY_PID_001
key = pid.split("_")[2]
return PARAMETER_ID_TO_CLASS_MAP[key]
def class_to_parameter_id_map(class_label, prefix=""):
"""Return parameter stable ID for class"""
pid = CLASS_TO_PARAMETER_ID_MAP[class_label]
# if prefix supplied form whole parameter stable ID (PREFIX_XRY_PID_001)
if prefix != "":
return "_".join([prefix, "XRY", pid, "001"])
else:
return pid
| """Mappings for entities that used by scripts in this directory
"""
# Phenotype centres in Solr have spaces, but in some of the code the spaces
# removed. This maps from
SITES_SPACES_TO_NOSPACES_MAP = {
'UC Davies': 'UCD',
'MRC Harwell': 'HRWL',
}
SITES_NOSPACES_TO_SPACES_MAP = {
'UCD': 'UC Davis',
'HRWL': 'MRC Harwell',
}
PARAMETER_ID_TO_CLASS_MAP = {
'034': 3, # whole_body_dorsal
'048': 4, # whole_body_lateral
'049': 2, # forepaw
'050': 5, # head_lateral
'051': 1, # head_dorsal
'052': 6, # hind_leg_hip
}
CLASS_TO_PARAMETER_ID_MAP = {
1: '051', # head_dorsal
2: '049', # forepaw
3: '034', # whole_body_dorsal
4: '048', # whole_body_lateral
5: '050', # head_lateral
6: '052', # hind_leg_hip
}
STRUCTURE_TO_LABEL_MAP = {
"head_dorsal": 1,
"forepaw": 2,
"whole_body_dorsal": 3,
"whole_body_lateral": 4,
"head_lateral": 5,
"hind_leg_hip": 6,
"unreadable_image": -1,
"uncategorisable_image": -2
}
LABEL_TO_STRUCTURE_MAP = {
1: "head_dorsal",
2: "forepaw",
3: "whole_body_dorsal",
4: "whole_body_lateral",
5: "head_lateral",
6: "hind_leg_hip",
-1: "unreadable_image",
-2: "uncategorisable_image"
}
def sites_spaces_to_nospaces_map(site):
"""Map site with spaces to site with no spaces.
"""
if site.count(" ") == 0:
return site
else:
return SITES_SPACES_TO_NOSPACES_MAP[site]
def sites_nospaces_to_spaces_map(site):
"""Map site with no spaces to site with spaces.
"""
try:
return SITES_NOSPACES_TO_SPACES_MAP[site]
except KeyError:
return site
def parameter_id_to_class_map(pid):
"""Return class for parameter stable ID"""
# Assumes parameter ID of form *_XRY_PID_001
key = pid.split("_")[2]
return PARAMETER_ID_TO_CLASS_MAP[key]
def class_to_parameter_id_map(class_label, prefix=""):
"""Return parameter stable ID for class"""
pid = CLASS_TO_PARAMETER_ID_MAP[class_label]
# if prefix supplied form whole parameter stable ID (PREFIX_XRY_PID_001)
if prefix != "":
return "_".join([prefix, "XRY", pid, "001"])
else:
return pid
| en | 0.592165 | Mappings for entities that used by scripts in this directory # Phenotype centres in Solr have spaces, but in some of the code the spaces # removed. This maps from # whole_body_dorsal # whole_body_lateral # forepaw # head_lateral # head_dorsal # hind_leg_hip # head_dorsal # forepaw # whole_body_dorsal # whole_body_lateral # head_lateral # hind_leg_hip Map site with spaces to site with no spaces. Map site with no spaces to site with spaces. Return class for parameter stable ID # Assumes parameter ID of form *_XRY_PID_001 Return parameter stable ID for class # if prefix supplied form whole parameter stable ID (PREFIX_XRY_PID_001) | 2.298673 | 2 |
chapter6/junk.py | srimani-programmer/Opencv-with-Python-Blueprints-second-Edition | 0 | 6620331 | import tensorflow as tf
from datasets import gtsrb
import numpy as np
import cv2
def normalize(x):
one_size = cv2.resize(x, (32, 32)).astype(np.float32) / 255
return one_size - np.mean(one_size)
def train_tf_model(X_train, y_train):
model = tf.keras.models.Sequential([
tf.keras.layers.Conv2D(44, (3, 3), input_shape=(32, 32, 3),
activation='relu'),
tf.keras.layers.MaxPooling2D(pool_size=(2, 2), strides=2),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(21, activation='softmax')
])
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(X_train, y_train, epochs=10)
return model
# if __name__ == '__main__':
(raw_X_train, y_train), (raw_X_test, y_test) = gtsrb.load_data()
X_train = np.array([normalize(x) for x in raw_X_train])
X_test = np.array([normalize(x) for x in raw_X_test])
model = train_tf_model(X_train, y_train)
model
from tensorflow.python.saved_model import builder as saved_model_builder
from tensorflow.python.saved_model.signature_def_utils import predict_signature_def
from tensorflow.python.saved_model import tag_constants
tf.saved_model.save(model, "models/10/")
builder = saved_model_builder.SavedModelBuilder("models/12/")
signature = predict_signature_def(inputs={"images": model.input},
outputs={"scores": model.output})
with tf.keras.backend.get_session() as sess:
# Save the meta graph and the variables
builder.add_meta_graph_and_variables(sess=sess, tags=[tag_constants.SERVING],
signature_def_map={"predict": signature})
builder.save()
tf.train.write_graph(tf.keras.backend.get_session().graph_def, 'models/', 'graph.pb', as_text=False)
m = cv2.dnn.readNetFromTensorflow('models/11/saved_model.pb')
m = cv2.dnn.readNetFromTensorflow('models/graph.pb')
| import tensorflow as tf
from datasets import gtsrb
import numpy as np
import cv2
def normalize(x):
one_size = cv2.resize(x, (32, 32)).astype(np.float32) / 255
return one_size - np.mean(one_size)
def train_tf_model(X_train, y_train):
model = tf.keras.models.Sequential([
tf.keras.layers.Conv2D(44, (3, 3), input_shape=(32, 32, 3),
activation='relu'),
tf.keras.layers.MaxPooling2D(pool_size=(2, 2), strides=2),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(21, activation='softmax')
])
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(X_train, y_train, epochs=10)
return model
# if __name__ == '__main__':
(raw_X_train, y_train), (raw_X_test, y_test) = gtsrb.load_data()
X_train = np.array([normalize(x) for x in raw_X_train])
X_test = np.array([normalize(x) for x in raw_X_test])
model = train_tf_model(X_train, y_train)
model
from tensorflow.python.saved_model import builder as saved_model_builder
from tensorflow.python.saved_model.signature_def_utils import predict_signature_def
from tensorflow.python.saved_model import tag_constants
tf.saved_model.save(model, "models/10/")
builder = saved_model_builder.SavedModelBuilder("models/12/")
signature = predict_signature_def(inputs={"images": model.input},
outputs={"scores": model.output})
with tf.keras.backend.get_session() as sess:
# Save the meta graph and the variables
builder.add_meta_graph_and_variables(sess=sess, tags=[tag_constants.SERVING],
signature_def_map={"predict": signature})
builder.save()
tf.train.write_graph(tf.keras.backend.get_session().graph_def, 'models/', 'graph.pb', as_text=False)
m = cv2.dnn.readNetFromTensorflow('models/11/saved_model.pb')
m = cv2.dnn.readNetFromTensorflow('models/graph.pb')
| en | 0.497884 | # if __name__ == '__main__': # Save the meta graph and the variables | 2.747319 | 3 |
test/hardware/test_memory.py | CospanDesign/nysa | 15 | 6620332 | <reponame>CospanDesign/nysa
#!/usr/bin/python
import json
import sys
import os
import time
import argparse
from array import array as Array
NAME = os.path.basename(os.path.realpath(__file__))
DESCRIPTION = "\n" \
"\n" \
"usage: %s [options]\n" % NAME
EPILOG = "\n" \
"\n" \
"Examples:\n" \
"\tSomething\n" \
"\n"
sys.path.append(os.path.join(os.path.dirname(__file__),
os.pardir,
os.pardir))
from nysa.host.driver.memory import Memory
from nysa.common.status import Status
from nysa.host.platform_scanner import PlatformScanner
#MAX_LONG_SIZE = 0x0800000
#MAX_LONG_SIZE = 0x2000000
#MAX_LONG_SIZE = 0x2000000
#MAX_LONG_SIZE = 0x0004000
#MAX_LONG_SIZE = 0x0000100
MAX_LONG_SIZE = 0x0002000
#MAX_LONG_SIZE = 0x0001000
class Test (object):
def __init__(self, name = None):
self.s = Status()
self.s.set_level("fatal")
plat = ["", None, None]
pscanner = PlatformScanner()
platform_dict = pscanner.get_platforms()
platform_names = platform_dict.keys()
if "sim" in platform_names:
#If sim is in the platforms, move it to the end
platform_names.remove("sim")
platform_names.append("sim")
urn = None
if name is not None and name in platform_names:
self.s.Debug("Platform: %s" % str(name))
platform_instance = platform_dict[name](self.s)
#self.s.Verbose("Platform Instance: %s" % str(platform_instance))
instances_dict = platform_instance.scan()
for iname in instances_dict:
#s.Verbose("Found Platform Item: %s" % str(platform_item))
n = instances_dict[iname]
plat = ["", None, None]
if n is not None:
self.s.Important("Found a nysa instance: %s" % iname)
n.read_sdb()
#import pdb; pdb.set_trace()
if n.is_device_in_platform(Memory):
plat = [name, iname, n]
break
continue
#self.s.Verbose("\t%s" % psi)
else:
for platform_name in platform_names:
if plat[1] is not None:
break
self.s.Debug("Platform: %s" % str(platform_name))
platform_instance = platform_dict[platform_name](self.s)
#self.s.Verbose("Platform Instance: %s" % str(platform_instance))
instances_dict = platform_instance.scan()
for name in instances_dict:
#s.Verbose("Found Platform Item: %s" % str(platform_item))
n = instances_dict[name]
plat = ["", None, None]
if n is not None:
self.s.Important("Found a nysa instance: %s" % name)
n.read_sdb()
#import pdb; pdb.set_trace()
if n.is_device_in_platform(Memory):
plat = [platform_name, name, n]
break
continue
#self.s.Verbose("\t%s" % psi)
if plat[1] is None:
return
self.n = plat[2]
self.urn = self.n.find_device(Memory)[0]
self.s.set_level("verbose")
self.s.Important("Using Platform: %s" % plat[0])
self.s.Important("Instantiated a Memory Device: %s" % self.urn)
self.memory = Memory(self.n, self.urn)
def _test_small_memory_rw_at_beginning(self):
if self.single_rw_start() == "Failed":
print "Failed memory write and read at beginning"
def _test_small_memory_rw_at_end(self):
if self.single_rw_end() == "Failed":
print "Failed memory write and read at end"
def single_rw_start(self):
status = "Passed"
#self.clear_memory()
size = self.n.get_device_size(self.urn)
print "size: 0x%08X" % size
print ( "Test Single Read/Write at Beginning")
data_out = Array('B', [0xAA, 0xBB, 0xCC, 0xDD, 0x55, 0x66, 0x77, 0x88])
self.n.write_memory(0, data_out)
print "Wrote second part!"
data_in = self.n.read_memory(0, len(data_out)/4)
print "length: data_out: %d, data_in: %d" % (len(data_out), len(data_in))
print "data out: %s" % str(data_out)
print "data_in: %s" % str(data_in)
for i in range (len(data_out)):
if data_in[i] != data_out[i]:
status = "Failed"
print "Error at: 0x%02X OUT: 0x%02X IN: 0x%02X" % (i, data_out[i], data_in[i])
#print "ERROR at: [{0:>2}] OUT: {1:>8} IN: {2:>8}".format(str(i), hex(data_out[i]), hex(data_in[i]))
return status
def single_rw_end(self):
status = "Passed"
#self.clear_memory()
size = self.n.get_device_size(self.urn)
print ( "Test Single Read/Write at End")
data_out = Array('B', [0xAA, 0xBB, 0xCC, 0xDD, 0x55, 0x66, 0x77, 0x88])
self.n.write_memory((size - 16), data_out)
print "Reading from location: 0x%08X" % (size - 16)
data_in = self.n.read_memory((size - 16), 2)
print "data out: %s" % str(data_out)
print "data_in: %s" % str(data_in)
for i in range (len(data_out)):
if data_in[i] != data_out[i]:
print "Error at: 0x%02X OUT: 0x%02X IN: 0x%02X" % (i, data_out[i], data_in[i])
status = "Failed"
return status
def test_long_burst(self):
status = "Passed"
fail = False
fail_count = 0
position = 0
#self.clear_memory()
total_size = self.n.get_device_size(self.urn)
total_size = MAX_LONG_SIZE * 2
size = 0
if total_size > MAX_LONG_SIZE:
print("Memory Size: 0x%08X is larger than read/write size" % total_size)
print("\tBreaking transaction into 0x%08X chunks" % MAX_LONG_SIZE)
size = MAX_LONG_SIZE
else:
size = total_size
#Write Data Out
while position < total_size:
data_out = Array('B')
for i in range (0, size):
data_out.append((i % 0x100))
self.n.write_memory(position, data_out)
#Increment the position
prev_pos = position
if position + size > total_size:
size = total_size - position
position += size
print("Wrote: 0x%08X - 0x%08X" % (prev_pos, position))
#time.sleep(0.1)
position = 0
size = total_size
if total_size > MAX_LONG_SIZE:
print("Memory Size: 0x%08X is larger than read/write size" % total_size)
print("\tBreaking transaction into 0x%08X chunks" % MAX_LONG_SIZE)
size = MAX_LONG_SIZE
while (position < total_size) and fail_count < 257:
data_in = self.n.read_memory(position, size / 4)
if size != len(data_in):
print( "Data in length not equal to data_out length")
print( "\toutgoing: %d" % size)
print( "\tincomming: %d" % len(data_in))
dout = data_out.tolist()
din = data_in.tolist()
for i in range(len(data_out)):
out_val = dout[i]
in_val = din[i]
if out_val != in_val:
fail = True
status = "Failed"
print("Mismatch @ 0x%08X: Write: (Hex): 0x%08X Read (Hex): 0x%08X" % (position + i, data_out[i], data_in[i]))
if fail_count >= 16:
break
fail_count += 1
prev_pos = position
if (position + size) > total_size:
size = total_size - position
position += size
print("Read: 0x%08X - 0x%08X" % (prev_pos, position))
return status
def clear_memory(self):
total_size = self.n.get_device_size(self.urn)
position = 0
size = 0
print ( "Clearing Memory")
print ( "Memory Size: 0x%08X" % size)
if total_size > MAX_LONG_SIZE:
print("Memory Size: 0x%08X is larger than read/write size" % total_size)
print("\tBreaking transaction into 0x%08X chunks" % MAX_LONG_SIZE)
size = MAX_LONG_SIZE
else:
size = total_size
while position < total_size:
data_out = Array('B')
for i in range (0, size):
data_out.append(0x00)
self.n.write_memory(position, data_out)
#Increment the position
prev_pos = position
if position + size > total_size:
size = total_size - position
position += size
#print ("Cleared: 0x%08X - 0x%08X" % (prev_pos, position))
#print "Clear Finished"
def main(argv):
#Parse out the commandline arguments
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
description=DESCRIPTION,
epilog=EPILOG
)
parser.add_argument("name",
type=str,
nargs='?',
default="any",
help="Specify a board to ping, if there is only one board attached leave blank (ignoring SIM)")
parser.add_argument("-t", "--test",
nargs=1,
default=["something"])
parser.add_argument("-d", "--debug",
action="store_true",
help="Enable Debug Messages")
args = parser.parse_args()
print "Running Script: %s" % NAME
test = Test(args.name)
test.single_rw_start()
test.single_rw_end()
#test.clear_memory()
test.test_long_burst()
if args.debug:
print "test: %s" % str(args.test[0])
if __name__ == "__main__":
main(sys.argv)
| #!/usr/bin/python
import json
import sys
import os
import time
import argparse
from array import array as Array
NAME = os.path.basename(os.path.realpath(__file__))
DESCRIPTION = "\n" \
"\n" \
"usage: %s [options]\n" % NAME
EPILOG = "\n" \
"\n" \
"Examples:\n" \
"\tSomething\n" \
"\n"
sys.path.append(os.path.join(os.path.dirname(__file__),
os.pardir,
os.pardir))
from nysa.host.driver.memory import Memory
from nysa.common.status import Status
from nysa.host.platform_scanner import PlatformScanner
#MAX_LONG_SIZE = 0x0800000
#MAX_LONG_SIZE = 0x2000000
#MAX_LONG_SIZE = 0x2000000
#MAX_LONG_SIZE = 0x0004000
#MAX_LONG_SIZE = 0x0000100
MAX_LONG_SIZE = 0x0002000
#MAX_LONG_SIZE = 0x0001000
class Test (object):
def __init__(self, name = None):
self.s = Status()
self.s.set_level("fatal")
plat = ["", None, None]
pscanner = PlatformScanner()
platform_dict = pscanner.get_platforms()
platform_names = platform_dict.keys()
if "sim" in platform_names:
#If sim is in the platforms, move it to the end
platform_names.remove("sim")
platform_names.append("sim")
urn = None
if name is not None and name in platform_names:
self.s.Debug("Platform: %s" % str(name))
platform_instance = platform_dict[name](self.s)
#self.s.Verbose("Platform Instance: %s" % str(platform_instance))
instances_dict = platform_instance.scan()
for iname in instances_dict:
#s.Verbose("Found Platform Item: %s" % str(platform_item))
n = instances_dict[iname]
plat = ["", None, None]
if n is not None:
self.s.Important("Found a nysa instance: %s" % iname)
n.read_sdb()
#import pdb; pdb.set_trace()
if n.is_device_in_platform(Memory):
plat = [name, iname, n]
break
continue
#self.s.Verbose("\t%s" % psi)
else:
for platform_name in platform_names:
if plat[1] is not None:
break
self.s.Debug("Platform: %s" % str(platform_name))
platform_instance = platform_dict[platform_name](self.s)
#self.s.Verbose("Platform Instance: %s" % str(platform_instance))
instances_dict = platform_instance.scan()
for name in instances_dict:
#s.Verbose("Found Platform Item: %s" % str(platform_item))
n = instances_dict[name]
plat = ["", None, None]
if n is not None:
self.s.Important("Found a nysa instance: %s" % name)
n.read_sdb()
#import pdb; pdb.set_trace()
if n.is_device_in_platform(Memory):
plat = [platform_name, name, n]
break
continue
#self.s.Verbose("\t%s" % psi)
if plat[1] is None:
return
self.n = plat[2]
self.urn = self.n.find_device(Memory)[0]
self.s.set_level("verbose")
self.s.Important("Using Platform: %s" % plat[0])
self.s.Important("Instantiated a Memory Device: %s" % self.urn)
self.memory = Memory(self.n, self.urn)
def _test_small_memory_rw_at_beginning(self):
if self.single_rw_start() == "Failed":
print "Failed memory write and read at beginning"
def _test_small_memory_rw_at_end(self):
if self.single_rw_end() == "Failed":
print "Failed memory write and read at end"
def single_rw_start(self):
status = "Passed"
#self.clear_memory()
size = self.n.get_device_size(self.urn)
print "size: 0x%08X" % size
print ( "Test Single Read/Write at Beginning")
data_out = Array('B', [0xAA, 0xBB, 0xCC, 0xDD, 0x55, 0x66, 0x77, 0x88])
self.n.write_memory(0, data_out)
print "Wrote second part!"
data_in = self.n.read_memory(0, len(data_out)/4)
print "length: data_out: %d, data_in: %d" % (len(data_out), len(data_in))
print "data out: %s" % str(data_out)
print "data_in: %s" % str(data_in)
for i in range (len(data_out)):
if data_in[i] != data_out[i]:
status = "Failed"
print "Error at: 0x%02X OUT: 0x%02X IN: 0x%02X" % (i, data_out[i], data_in[i])
#print "ERROR at: [{0:>2}] OUT: {1:>8} IN: {2:>8}".format(str(i), hex(data_out[i]), hex(data_in[i]))
return status
def single_rw_end(self):
status = "Passed"
#self.clear_memory()
size = self.n.get_device_size(self.urn)
print ( "Test Single Read/Write at End")
data_out = Array('B', [0xAA, 0xBB, 0xCC, 0xDD, 0x55, 0x66, 0x77, 0x88])
self.n.write_memory((size - 16), data_out)
print "Reading from location: 0x%08X" % (size - 16)
data_in = self.n.read_memory((size - 16), 2)
print "data out: %s" % str(data_out)
print "data_in: %s" % str(data_in)
for i in range (len(data_out)):
if data_in[i] != data_out[i]:
print "Error at: 0x%02X OUT: 0x%02X IN: 0x%02X" % (i, data_out[i], data_in[i])
status = "Failed"
return status
def test_long_burst(self):
status = "Passed"
fail = False
fail_count = 0
position = 0
#self.clear_memory()
total_size = self.n.get_device_size(self.urn)
total_size = MAX_LONG_SIZE * 2
size = 0
if total_size > MAX_LONG_SIZE:
print("Memory Size: 0x%08X is larger than read/write size" % total_size)
print("\tBreaking transaction into 0x%08X chunks" % MAX_LONG_SIZE)
size = MAX_LONG_SIZE
else:
size = total_size
#Write Data Out
while position < total_size:
data_out = Array('B')
for i in range (0, size):
data_out.append((i % 0x100))
self.n.write_memory(position, data_out)
#Increment the position
prev_pos = position
if position + size > total_size:
size = total_size - position
position += size
print("Wrote: 0x%08X - 0x%08X" % (prev_pos, position))
#time.sleep(0.1)
position = 0
size = total_size
if total_size > MAX_LONG_SIZE:
print("Memory Size: 0x%08X is larger than read/write size" % total_size)
print("\tBreaking transaction into 0x%08X chunks" % MAX_LONG_SIZE)
size = MAX_LONG_SIZE
while (position < total_size) and fail_count < 257:
data_in = self.n.read_memory(position, size / 4)
if size != len(data_in):
print( "Data in length not equal to data_out length")
print( "\toutgoing: %d" % size)
print( "\tincomming: %d" % len(data_in))
dout = data_out.tolist()
din = data_in.tolist()
for i in range(len(data_out)):
out_val = dout[i]
in_val = din[i]
if out_val != in_val:
fail = True
status = "Failed"
print("Mismatch @ 0x%08X: Write: (Hex): 0x%08X Read (Hex): 0x%08X" % (position + i, data_out[i], data_in[i]))
if fail_count >= 16:
break
fail_count += 1
prev_pos = position
if (position + size) > total_size:
size = total_size - position
position += size
print("Read: 0x%08X - 0x%08X" % (prev_pos, position))
return status
def clear_memory(self):
total_size = self.n.get_device_size(self.urn)
position = 0
size = 0
print ( "Clearing Memory")
print ( "Memory Size: 0x%08X" % size)
if total_size > MAX_LONG_SIZE:
print("Memory Size: 0x%08X is larger than read/write size" % total_size)
print("\tBreaking transaction into 0x%08X chunks" % MAX_LONG_SIZE)
size = MAX_LONG_SIZE
else:
size = total_size
while position < total_size:
data_out = Array('B')
for i in range (0, size):
data_out.append(0x00)
self.n.write_memory(position, data_out)
#Increment the position
prev_pos = position
if position + size > total_size:
size = total_size - position
position += size
#print ("Cleared: 0x%08X - 0x%08X" % (prev_pos, position))
#print "Clear Finished"
def main(argv):
#Parse out the commandline arguments
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
description=DESCRIPTION,
epilog=EPILOG
)
parser.add_argument("name",
type=str,
nargs='?',
default="any",
help="Specify a board to ping, if there is only one board attached leave blank (ignoring SIM)")
parser.add_argument("-t", "--test",
nargs=1,
default=["something"])
parser.add_argument("-d", "--debug",
action="store_true",
help="Enable Debug Messages")
args = parser.parse_args()
print "Running Script: %s" % NAME
test = Test(args.name)
test.single_rw_start()
test.single_rw_end()
#test.clear_memory()
test.test_long_burst()
if args.debug:
print "test: %s" % str(args.test[0])
if __name__ == "__main__":
main(sys.argv) | en | 0.267763 | #!/usr/bin/python #MAX_LONG_SIZE = 0x0800000 #MAX_LONG_SIZE = 0x2000000 #MAX_LONG_SIZE = 0x2000000 #MAX_LONG_SIZE = 0x0004000 #MAX_LONG_SIZE = 0x0000100 #MAX_LONG_SIZE = 0x0001000 #If sim is in the platforms, move it to the end #self.s.Verbose("Platform Instance: %s" % str(platform_instance)) #s.Verbose("Found Platform Item: %s" % str(platform_item)) #import pdb; pdb.set_trace() #self.s.Verbose("\t%s" % psi) #self.s.Verbose("Platform Instance: %s" % str(platform_instance)) #s.Verbose("Found Platform Item: %s" % str(platform_item)) #import pdb; pdb.set_trace() #self.s.Verbose("\t%s" % psi) #self.clear_memory() #print "ERROR at: [{0:>2}] OUT: {1:>8} IN: {2:>8}".format(str(i), hex(data_out[i]), hex(data_in[i])) #self.clear_memory() #self.clear_memory() #Write Data Out #Increment the position #time.sleep(0.1) #Increment the position #print ("Cleared: 0x%08X - 0x%08X" % (prev_pos, position)) #print "Clear Finished" #Parse out the commandline arguments #test.clear_memory() | 2.258103 | 2 |
tf-mnist/webapp/config.py | silpa10/MLEngProj | 15 | 6620333 | <gh_stars>10-100
bind = '0.0.0.0:80'
workers = 3
accesslog = '-'
errorlog = '-'
| bind = '0.0.0.0:80'
workers = 3
accesslog = '-'
errorlog = '-' | none | 1 | 0.901497 | 1 | |
app/models.py | seanziegler/GatorLF | 0 | 6620334 | <filename>app/models.py
from app import db
Class User(db.Model):
id = db.Column(db.Integer, primary_key = True)
username = db.Column(db.String(80), unique = True, nullable = False)
email = db.Column(db.String(120), unique = True, nullable = False)
Class Item(db.Model):
id = db.Column(db.Integer, primary_key = True)
title = db.Column(db.String(120), nullable = False)
location = db.Column(db.String(120), nullable = False)
lostBy = db.Column(db.Integer, db.ForeignKey('User.id'), nullable = False)
active = db.Column(db.Boolean, default = True, nullable = False)
date = db.Column(db.DateTime, nullable = False)
Class Lost(Item):
pass
Class Found(Item):
pass
| <filename>app/models.py
from app import db
Class User(db.Model):
id = db.Column(db.Integer, primary_key = True)
username = db.Column(db.String(80), unique = True, nullable = False)
email = db.Column(db.String(120), unique = True, nullable = False)
Class Item(db.Model):
id = db.Column(db.Integer, primary_key = True)
title = db.Column(db.String(120), nullable = False)
location = db.Column(db.String(120), nullable = False)
lostBy = db.Column(db.Integer, db.ForeignKey('User.id'), nullable = False)
active = db.Column(db.Boolean, default = True, nullable = False)
date = db.Column(db.DateTime, nullable = False)
Class Lost(Item):
pass
Class Found(Item):
pass
| none | 1 | 2.647606 | 3 | |
MAIN/STM32F405_C/NORMAL/V38/uOTA.py | ozturkahmetcevdet/VSenst | 0 | 6620335 | <reponame>ozturkahmetcevdet/VSenst<gh_stars>0
uOTALoop = True
uOTAFileName = ""
uf = None
def GetFileName(data):
global uOTAFileName
global uf
IsFileNameExist = False
splitData = data.decode('utf-8').split('@')
for item in splitData:
if item == "FName":
IsFileNameExist = True
elif IsFileNameExist:
uOTAFileName = item
try:
uf = open(uOTAFileName, 'w')
except OSError as err:
print("OS error: {0}".format(err))
except ValueError:
print("Could not open file. ---{}".format(uOTAFileName))
except:
print("Unexpected error!")
raise
def IsFileReadFinish(data):
return data == b'uOTA end\r\n'
def ReadAndSaveFile(data):
global uOTALoop
global uOTAFileName
global uf
if data != None:
if uOTAFileName == "":
GetFileName(data)
elif uOTAFileName != "":
if IsFileReadFinish(data):
uf.close()
uOTALoop = False
else:
uf.write(data.decode('utf-8'))
| uOTALoop = True
uOTAFileName = ""
uf = None
def GetFileName(data):
global uOTAFileName
global uf
IsFileNameExist = False
splitData = data.decode('utf-8').split('@')
for item in splitData:
if item == "FName":
IsFileNameExist = True
elif IsFileNameExist:
uOTAFileName = item
try:
uf = open(uOTAFileName, 'w')
except OSError as err:
print("OS error: {0}".format(err))
except ValueError:
print("Could not open file. ---{}".format(uOTAFileName))
except:
print("Unexpected error!")
raise
def IsFileReadFinish(data):
return data == b'uOTA end\r\n'
def ReadAndSaveFile(data):
global uOTALoop
global uOTAFileName
global uf
if data != None:
if uOTAFileName == "":
GetFileName(data)
elif uOTAFileName != "":
if IsFileReadFinish(data):
uf.close()
uOTALoop = False
else:
uf.write(data.decode('utf-8')) | none | 1 | 3.126556 | 3 | |
todolist/taskslist/urls.py | codrelphi/djangoApps | 0 | 6620336 | <filename>todolist/taskslist/urls.py
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("addtask", views.addTask, name="addtask"),
path("delete_task/<int:task_id>", views.delete_task, name="delete_task")
]
| <filename>todolist/taskslist/urls.py
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("addtask", views.addTask, name="addtask"),
path("delete_task/<int:task_id>", views.delete_task, name="delete_task")
]
| none | 1 | 1.919915 | 2 | |
cls_tool/news/views.py | NadiaRom/manipulative_news_methodology | 38 | 6620337 | <filename>cls_tool/news/views.py
from django.shortcuts import render
from . import models, forms
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect, JsonResponse
from django.forms.models import model_to_dict
@login_required
def classify(request):
if request.method == 'POST':
form = forms.NewClassify(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/classifier/')
else:
explanations = ';;'.join([t.description for t in models.FakeType.objects.all()])
classified_new = models.Article.objects.filter(bee=request.user
).exclude(html_id__in=models.Classified.objects.all(
).values('article')
).order_by('?'
).first()
form = forms.NewClassify(initial={'article': classified_new})
feedback = forms.FeedbackForm(initial={'article': classified_new})
done_counter = models.Classified.objects.filter(article__bee=request.user).count()
return render(request, 'classifier.html', {'cls_new': classified_new,
'form': form,
'type_explanations': explanations,
'feedback': feedback,
'done_counter': done_counter,
})
@login_required
def edit(request):
selected_type = request.GET.get('type')
print(request.GET.get('types'))
types = models.FakeType.objects.all()
if not selected_type or selected_type == 'all':
classified_before = models.Classified.objects.filter(article__bee=request.user
).order_by('-classified_at')
else:
classified_before = models.Classified.objects.filter(article__bee=request.user
).filter(types__label=selected_type
).order_by('-classified_at')
paginator = Paginator(classified_before, 15)
page = request.GET.get('page')
try:
done = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
done = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
done = paginator.page(paginator.num_pages)
return render(request, 'list_done.html', {'done': done,
'types': types,
'selected_type': selected_type})
@login_required
def edit_done(request, pk):
article = models.Classified.objects.get(article__html_id=pk)
if request.method == 'POST':
form = forms.NewClassify(request.POST, instance=article)
if form.is_valid():
form.save()
return HttpResponseRedirect('/classifier/done/')
else:
explanations = ';;'.join([t.description for t in models.FakeType.objects.all()])
feedback = forms.FeedbackForm(initial={'article': article.article})
form = forms.NewClassify(instance=article, data=model_to_dict(article))
return render(request, 'edit_done.html', {'form': form,
'cls_article': article,
'type_explanations': explanations,
'feedback': feedback,
})
@login_required
def feedback(request):
if request.method == 'POST':
feedback = forms.FeedbackForm(request.POST)
if feedback.is_valid():
feedback.save()
return JsonResponse({'ok': True})
| <filename>cls_tool/news/views.py
from django.shortcuts import render
from . import models, forms
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect, JsonResponse
from django.forms.models import model_to_dict
@login_required
def classify(request):
if request.method == 'POST':
form = forms.NewClassify(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/classifier/')
else:
explanations = ';;'.join([t.description for t in models.FakeType.objects.all()])
classified_new = models.Article.objects.filter(bee=request.user
).exclude(html_id__in=models.Classified.objects.all(
).values('article')
).order_by('?'
).first()
form = forms.NewClassify(initial={'article': classified_new})
feedback = forms.FeedbackForm(initial={'article': classified_new})
done_counter = models.Classified.objects.filter(article__bee=request.user).count()
return render(request, 'classifier.html', {'cls_new': classified_new,
'form': form,
'type_explanations': explanations,
'feedback': feedback,
'done_counter': done_counter,
})
@login_required
def edit(request):
selected_type = request.GET.get('type')
print(request.GET.get('types'))
types = models.FakeType.objects.all()
if not selected_type or selected_type == 'all':
classified_before = models.Classified.objects.filter(article__bee=request.user
).order_by('-classified_at')
else:
classified_before = models.Classified.objects.filter(article__bee=request.user
).filter(types__label=selected_type
).order_by('-classified_at')
paginator = Paginator(classified_before, 15)
page = request.GET.get('page')
try:
done = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
done = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
done = paginator.page(paginator.num_pages)
return render(request, 'list_done.html', {'done': done,
'types': types,
'selected_type': selected_type})
@login_required
def edit_done(request, pk):
article = models.Classified.objects.get(article__html_id=pk)
if request.method == 'POST':
form = forms.NewClassify(request.POST, instance=article)
if form.is_valid():
form.save()
return HttpResponseRedirect('/classifier/done/')
else:
explanations = ';;'.join([t.description for t in models.FakeType.objects.all()])
feedback = forms.FeedbackForm(initial={'article': article.article})
form = forms.NewClassify(instance=article, data=model_to_dict(article))
return render(request, 'edit_done.html', {'form': form,
'cls_article': article,
'type_explanations': explanations,
'feedback': feedback,
})
@login_required
def feedback(request):
if request.method == 'POST':
feedback = forms.FeedbackForm(request.POST)
if feedback.is_valid():
feedback.save()
return JsonResponse({'ok': True})
| en | 0.67353 | # If page is not an integer, deliver first page. # If page is out of range (e.g. 9999), deliver last page of results. | 2.011377 | 2 |
tests/OLD/cnn/test_conv_3.py | KonduitAI/ImportTests | 6 | 6620338 | <filename>tests/OLD/cnn/test_conv_3.py
import tensorflow as tf
from tests.cnn.image_input import ImageInput
from tfoptests.persistor import TensorFlowPersistor
def test_conv_3():
# [batch, in_height, in_width, in_channels].
image_input = ImageInput(seed=713, batch_size=4, image_h=128, image_w=128, image_c=4)
in_node = image_input.get_placeholder("image", data_type=tf.float32)
# [filter_height, filter_width, in_channels, out_channels]. in_channels must match between input and filter.
filter_one = tf.Variable(tf.random_uniform([4, 5, image_input.image_c]), name="filter1")
dilation_one = tf.nn.dilation2d(in_node, filter=filter_one, strides=[1, 2, 3, 1], rates=[1, 5, 7, 1],
padding='SAME',
name="dilation_one")
filter_two = tf.Variable(tf.random_uniform([11, 7, 4]), name="filter2")
dilation_two = tf.nn.dilation2d(dilation_one, filter=filter_two, strides=[1, 3, 2, 1], rates=[1, 2, 3, 1],
padding='VALID',
name="output")
out_node = tf.identity(dilation_two, name="output")
placeholders = [in_node]
predictions = [out_node]
tfp = TensorFlowPersistor(save_dir="conv_3")
predictions_after_freeze = tfp \
.set_placeholders(placeholders) \
.set_output_tensors(predictions) \
.set_test_data(image_input.get_test_data()) \
.build_save_frozen_graph()
print(predictions_after_freeze[0].shape)
if __name__ == '__main__':
test_conv_3()
| <filename>tests/OLD/cnn/test_conv_3.py
import tensorflow as tf
from tests.cnn.image_input import ImageInput
from tfoptests.persistor import TensorFlowPersistor
def test_conv_3():
# [batch, in_height, in_width, in_channels].
image_input = ImageInput(seed=713, batch_size=4, image_h=128, image_w=128, image_c=4)
in_node = image_input.get_placeholder("image", data_type=tf.float32)
# [filter_height, filter_width, in_channels, out_channels]. in_channels must match between input and filter.
filter_one = tf.Variable(tf.random_uniform([4, 5, image_input.image_c]), name="filter1")
dilation_one = tf.nn.dilation2d(in_node, filter=filter_one, strides=[1, 2, 3, 1], rates=[1, 5, 7, 1],
padding='SAME',
name="dilation_one")
filter_two = tf.Variable(tf.random_uniform([11, 7, 4]), name="filter2")
dilation_two = tf.nn.dilation2d(dilation_one, filter=filter_two, strides=[1, 3, 2, 1], rates=[1, 2, 3, 1],
padding='VALID',
name="output")
out_node = tf.identity(dilation_two, name="output")
placeholders = [in_node]
predictions = [out_node]
tfp = TensorFlowPersistor(save_dir="conv_3")
predictions_after_freeze = tfp \
.set_placeholders(placeholders) \
.set_output_tensors(predictions) \
.set_test_data(image_input.get_test_data()) \
.build_save_frozen_graph()
print(predictions_after_freeze[0].shape)
if __name__ == '__main__':
test_conv_3()
| en | 0.746635 | # [batch, in_height, in_width, in_channels]. # [filter_height, filter_width, in_channels, out_channels]. in_channels must match between input and filter. | 2.437519 | 2 |
indel_analysis/compute_indels/run_example.py | kaskamal/SelfTarget | 20 | 6620339 | import io, os, sys, csv, shutil
from selftarget.util import setRunLocal, setPythonCmd, setPearExe, setIndelMapExe, runPerSubdir, runSubdir
from selftarget.util import setIndelGenI1Exe, setIndelMhExe, getIndelGenI1Exe, getIndelMhExe
from selftarget.data import setHighDataDir, getHighDataDir
from run_all_pear import runAllPear
from run_all_partition import runAllPartition
from run_all_map import runAllMap
from run_all_split_null_mappings import runAllSplitNullMappings
from run_all_mapped_split import runAllMappedSplit
from run_all_compile_nulls import runAllCompileNulls
from run_all_indelmap import runAllIndelMap
sys.path.append('..')
from combine_results_files import combineAllFiles
sys.path.append('../microhomology')
from run_all_collect_mh_frequencies_by_len import runAllCollectMHFrequenciesByLen
sys.path.append('../microhomology_mismatch')
from fetch_mh_mismatch_frequencies import fetchMhMismatchFrequencies
def printStatus(status):
print('\n### ',status,' ###\n ')
#----------------------------------------------------------------------
# Copy all example data to results directory since script runs in place
#----------------------------------------------------------------------
shutil.copytree('/data/indel_processing_example', '/results/indel_processing_example')
setRunLocal(True)
if not os.path.isdir('/results/indel_processing_example'): os.mkdir('/results/indel_processing_example')
setHighDataDir('/results/indel_processing_example/')
setPythonCmd('python')
setPearExe('/usr/local/bin/pear')
setIndelMapExe('/usr/local/bin/indelmap')
setIndelGenI1Exe('/usr/local/bin/indelgen_i1')
setIndelMhExe('/usr/local/bin/indelmh')
#----------------------------------------------------------------
# Processing of raw reads to produce descriptions of indels
#----------------------------------------------------------------
#Note: This provides a demonstration on a cut-down data set of just 4 oligos.
# In practice, the dataset was much too be large to be run in one script like this.
# Instead individual steps were performed by calling each script in turn from the
# command line to set off parallel jobs on a compute cluster.
printStatus('Combine paired-end reads')
runAllPear() #Combines paired-end reads
printStatus('Divide reads')
runAllPartition(nump=1) #Divides reads into smaller files (for parallel processing, in this case leave as one)
printStatus('Map reads to oligos')
runAllMap() #Maps reads to gRNA-targets (oligos)
printStatus('Re-organise mappings for plasmid library')
runAllSplitNullMappings() #Copies gRNA-target (oligo) mappings for plasmid library (NULL) into per-oligo files
printStatus('Re-organise reads for all samples')
runAllMappedSplit() #Copies mapped reads into per-oligo files
printStatus('Compile expanded template set from plasmid library')
runAllCompileNulls() #Processes mappings of plasmid library to form expanded set of oligo templates (accounting for synthesis mutations)
printStatus('Re-map reads to expanded template set')
runAllIndelMap() #Re-map all reads against expanded set of oligo templates, and format into summary files
printStatus('Indel summaries complete.')
#----------------------------------------------------------------
# Further processing of indels to compute summary information
#----------------------------------------------------------------
## I1
printStatus('I1')
cmd = getIndelGenI1Exe() + ' ' + getHighDataDir() + 'ST_June_2017/data/exp_target_pam_new.fasta'
print(cmd); os.system(cmd)
runPerSubdir('../i1/compile_i1.py', 'out_i1', None, extra_args=(getHighDataDir() + ' '))
combineAllFiles(getHighDataDir() + '/i1_summaries',True)
## Indel Category, Size and Most Common Indel Details
printStatus('Indel Details')
mis_dir = getHighDataDir() + '/more_indel_summaries'
runPerSubdir('../indel_details/compile_indel_details.py', 'out_details', None, extra_args=(getHighDataDir() + ' '))
idx, dirnames = 0, [mis_dir + '/' + x for x in os.listdir(mis_dir)]
idx = runSubdir(idx, dirnames, 'All', '../indel_details/compile_pie_summaries_per_oligo.py', 'out_pie_oligo', None, extra_args=(getHighDataDir() + ' '))
combineAllFiles(mis_dir,True)
## Microhomology
printStatus('Microhomology')
cmd = getIndelMhExe() + ' ' + getHighDataDir() + 'ST_June_2017/data/exp_target_pam_new.fasta ' + getHighDataDir() + 'ST_June_2017/data/exp_target_new_mh_indels.txt'
print(cmd); os.system(cmd)
runPerSubdir('../microhomology/fetch_mh_indel_frequencies.py', 'out_mh_indel', None, extra_args=(getHighDataDir() + ' ') )
runAllCollectMHFrequenciesByLen(input_dir=getHighDataDir() + '/mh_indel_frequencies', highdir=getHighDataDir(), scriptloc='../microhomology')
## Mismatch Microhomology:
printStatus('Mismatch-Microhomology')
print(getHighDataDir())
fetchMhMismatchFrequencies(getHighDataDir() + '/ST_June_2017/data/K562_800x_LV7A_DPI7', outdir= getHighDataDir() + '/mh_mismatch_indel_frequencies')
| import io, os, sys, csv, shutil
from selftarget.util import setRunLocal, setPythonCmd, setPearExe, setIndelMapExe, runPerSubdir, runSubdir
from selftarget.util import setIndelGenI1Exe, setIndelMhExe, getIndelGenI1Exe, getIndelMhExe
from selftarget.data import setHighDataDir, getHighDataDir
from run_all_pear import runAllPear
from run_all_partition import runAllPartition
from run_all_map import runAllMap
from run_all_split_null_mappings import runAllSplitNullMappings
from run_all_mapped_split import runAllMappedSplit
from run_all_compile_nulls import runAllCompileNulls
from run_all_indelmap import runAllIndelMap
sys.path.append('..')
from combine_results_files import combineAllFiles
sys.path.append('../microhomology')
from run_all_collect_mh_frequencies_by_len import runAllCollectMHFrequenciesByLen
sys.path.append('../microhomology_mismatch')
from fetch_mh_mismatch_frequencies import fetchMhMismatchFrequencies
def printStatus(status):
print('\n### ',status,' ###\n ')
#----------------------------------------------------------------------
# Copy all example data to results directory since script runs in place
#----------------------------------------------------------------------
shutil.copytree('/data/indel_processing_example', '/results/indel_processing_example')
setRunLocal(True)
if not os.path.isdir('/results/indel_processing_example'): os.mkdir('/results/indel_processing_example')
setHighDataDir('/results/indel_processing_example/')
setPythonCmd('python')
setPearExe('/usr/local/bin/pear')
setIndelMapExe('/usr/local/bin/indelmap')
setIndelGenI1Exe('/usr/local/bin/indelgen_i1')
setIndelMhExe('/usr/local/bin/indelmh')
#----------------------------------------------------------------
# Processing of raw reads to produce descriptions of indels
#----------------------------------------------------------------
#Note: This provides a demonstration on a cut-down data set of just 4 oligos.
# In practice, the dataset was much too be large to be run in one script like this.
# Instead individual steps were performed by calling each script in turn from the
# command line to set off parallel jobs on a compute cluster.
printStatus('Combine paired-end reads')
runAllPear() #Combines paired-end reads
printStatus('Divide reads')
runAllPartition(nump=1) #Divides reads into smaller files (for parallel processing, in this case leave as one)
printStatus('Map reads to oligos')
runAllMap() #Maps reads to gRNA-targets (oligos)
printStatus('Re-organise mappings for plasmid library')
runAllSplitNullMappings() #Copies gRNA-target (oligo) mappings for plasmid library (NULL) into per-oligo files
printStatus('Re-organise reads for all samples')
runAllMappedSplit() #Copies mapped reads into per-oligo files
printStatus('Compile expanded template set from plasmid library')
runAllCompileNulls() #Processes mappings of plasmid library to form expanded set of oligo templates (accounting for synthesis mutations)
printStatus('Re-map reads to expanded template set')
runAllIndelMap() #Re-map all reads against expanded set of oligo templates, and format into summary files
printStatus('Indel summaries complete.')
#----------------------------------------------------------------
# Further processing of indels to compute summary information
#----------------------------------------------------------------
## I1
printStatus('I1')
cmd = getIndelGenI1Exe() + ' ' + getHighDataDir() + 'ST_June_2017/data/exp_target_pam_new.fasta'
print(cmd); os.system(cmd)
runPerSubdir('../i1/compile_i1.py', 'out_i1', None, extra_args=(getHighDataDir() + ' '))
combineAllFiles(getHighDataDir() + '/i1_summaries',True)
## Indel Category, Size and Most Common Indel Details
printStatus('Indel Details')
mis_dir = getHighDataDir() + '/more_indel_summaries'
runPerSubdir('../indel_details/compile_indel_details.py', 'out_details', None, extra_args=(getHighDataDir() + ' '))
idx, dirnames = 0, [mis_dir + '/' + x for x in os.listdir(mis_dir)]
idx = runSubdir(idx, dirnames, 'All', '../indel_details/compile_pie_summaries_per_oligo.py', 'out_pie_oligo', None, extra_args=(getHighDataDir() + ' '))
combineAllFiles(mis_dir,True)
## Microhomology
printStatus('Microhomology')
cmd = getIndelMhExe() + ' ' + getHighDataDir() + 'ST_June_2017/data/exp_target_pam_new.fasta ' + getHighDataDir() + 'ST_June_2017/data/exp_target_new_mh_indels.txt'
print(cmd); os.system(cmd)
runPerSubdir('../microhomology/fetch_mh_indel_frequencies.py', 'out_mh_indel', None, extra_args=(getHighDataDir() + ' ') )
runAllCollectMHFrequenciesByLen(input_dir=getHighDataDir() + '/mh_indel_frequencies', highdir=getHighDataDir(), scriptloc='../microhomology')
## Mismatch Microhomology:
printStatus('Mismatch-Microhomology')
print(getHighDataDir())
fetchMhMismatchFrequencies(getHighDataDir() + '/ST_June_2017/data/K562_800x_LV7A_DPI7', outdir= getHighDataDir() + '/mh_mismatch_indel_frequencies')
| en | 0.678686 | ### ',status,' ###\n ') #---------------------------------------------------------------------- # Copy all example data to results directory since script runs in place #---------------------------------------------------------------------- #---------------------------------------------------------------- # Processing of raw reads to produce descriptions of indels #---------------------------------------------------------------- #Note: This provides a demonstration on a cut-down data set of just 4 oligos. # In practice, the dataset was much too be large to be run in one script like this. # Instead individual steps were performed by calling each script in turn from the # command line to set off parallel jobs on a compute cluster. #Combines paired-end reads #Divides reads into smaller files (for parallel processing, in this case leave as one) #Maps reads to gRNA-targets (oligos) #Copies gRNA-target (oligo) mappings for plasmid library (NULL) into per-oligo files #Copies mapped reads into per-oligo files #Processes mappings of plasmid library to form expanded set of oligo templates (accounting for synthesis mutations) #Re-map all reads against expanded set of oligo templates, and format into summary files #---------------------------------------------------------------- # Further processing of indels to compute summary information #---------------------------------------------------------------- ## I1 ## Indel Category, Size and Most Common Indel Details ## Microhomology ## Mismatch Microhomology: | 1.920561 | 2 |
Lib/test/test_shadowstr_jy.py | jeff5/jython-whinchat | 577 | 6620340 | # Made for Jython
# Tests of built-in type shadowstr
import os
import sys
from test import string_tests
from test.test_support import run_unittest, is_jython
from test.test_str import StrTest
import unittest
from org.python.core import PyShadowString
# Ideally we would test shadowstr is a str but the tests need to sub-class it
class StrTestCase(
string_tests.CommonTest,
string_tests.MixinStrUnicodeUserStringTest,
string_tests.MixinStrUserStringTest,
):
# A PyShadowString should pass the tests for str too.
type2test = PyShadowString
class ShadowStrTestCase(unittest.TestCase):
def setUp(self):
self.ss = PyShadowString("hello", "bonjour")
# The Java class of a python module may be <module>$py
CCLASS = r"test\.test_shadowstr_jy\$py" # compiled (e.g. regrtest)
# Or it may be org.python.pycode._pyx<n>
PCLASS = r"org\.python\.pycode\._pyx\d+" # .py at the prompt
def check_first_eq(self):
self.assertTrue(self.ss == "hello")
self.assertFalse(self.ss == "bonjour")
self.assertTrue("hello" == self.ss)
self.assertFalse("bonjour" == self.ss)
# shadowstring-shadowstring comparisons
tt = PyShadowString("hello", "goodbye")
self.assertTrue(self.ss == tt) # primary==primary
tt = PyShadowString("adieu", "hello")
self.assertFalse(self.ss == tt) # primary==shadow
self.assertFalse(tt == self.ss) # shadow==primary
tt = PyShadowString("adieu", "bonjour")
self.assertFalse(self.ss == tt) # shadow==shadow
def check_both_eq(self):
self.assertTrue(self.ss == "hello")
self.assertTrue(self.ss == "bonjour")
self.assertTrue("hello" == self.ss)
self.assertTrue("bonjour" == self.ss)
# shadowstring-shadowstring comparisons
tt = PyShadowString("hello", "goodbye")
for c, m in self.ss.gettargets(): tt.addtarget(c, m)
self.assertTrue(self.ss == tt) # primary==primary
tt = PyShadowString("goodbye", "hello")
for c, m in self.ss.gettargets(): tt.addtarget(c, m)
self.assertTrue(self.ss == tt) # primary==shadow
self.assertTrue(tt == self.ss) # shadow==primary
tt = PyShadowString("adieu", "bonjour")
for c, m in self.ss.gettargets(): tt.addtarget(c, m)
self.assertTrue(self.ss == tt) # shadow==shadow
def test_eq(self):
# Test recognition unconditionally
self.check_first_eq()
self.ss.addtarget(None) # match any
self.check_both_eq()
def test_eq_class(self):
# Test recognition of class context only
self.check_first_eq()
self.ss.addtarget(self.CCLASS)
self.ss.addtarget(self.PCLASS)
self.check_both_eq()
def test_eq_method(self):
# Test recognition of method context only
self.check_first_eq()
# The Java method name of a python function is name$<n>
self.ss.addtarget(None, r"test_eq_method\$\d+") # method only
self.check_both_eq()
def test_eq_class_method(self):
# Test recognition of class and method context
self.check_first_eq()
# Match this method in this module
method = r"test_eq_class_method\$\d+"
self.ss.addtarget(self.CCLASS, method)
self.ss.addtarget(self.PCLASS, method)
self.check_both_eq()
def check_first_startswith(self):
self.assertTrue(self.ss.startswith("hel"))
self.assertFalse(self.ss.startswith("bon"))
def check_both_startswith(self):
self.assertTrue(self.ss.startswith("hel"))
self.assertTrue(self.ss.startswith("bon"))
def test_startswith(self):
# Test recognition unconditionally
self.check_first_startswith()
self.ss.addtarget(None) # match any
self.check_both_startswith()
def test_startswith_class(self):
# Test recognition of class context only
self.check_first_startswith()
self.ss.addtarget(self.CCLASS) # class only
self.ss.addtarget(self.PCLASS) # class only
self.check_both_startswith()
def test_startswith_method(self):
# Test recognition of method context only
self.check_first_startswith()
self.ss.addtarget(None, r"test_startswith_method\$\d+") # method only
self.check_both_startswith()
def test_startswith_class_method(self):
# Test recognition of class and method context
self.check_first_startswith()
# Match this method in this module
method = r"test_startswith_class_method\$\d+"
self.ss.addtarget(self.CCLASS, method)
self.ss.addtarget(self.PCLASS, method)
self.check_both_startswith()
def test_slice(self):
# Test slicing goes through to the constituent strings consistently
def check(m, n):
tt = self.ss[m:n]
self.assertEqual(tt, "hello"[m:n])
self.assertEqual(tt, "bonjour"[m:n])
self.assertEqual(self.ss.gettargets(), tt.gettargets())
# Match this method in this module
method = r"test_slice\$\d+"
self.ss.addtarget(self.CCLASS, method)
self.ss.addtarget(self.PCLASS, method)
check(None, 3)
check(1, 5)
check(-3, None)
check(None, None)
def test_main():
run_unittest(
StrTestCase,
ShadowStrTestCase,
)
if __name__ == "__main__":
test_main()
| # Made for Jython
# Tests of built-in type shadowstr
import os
import sys
from test import string_tests
from test.test_support import run_unittest, is_jython
from test.test_str import StrTest
import unittest
from org.python.core import PyShadowString
# Ideally we would test shadowstr is a str but the tests need to sub-class it
class StrTestCase(
string_tests.CommonTest,
string_tests.MixinStrUnicodeUserStringTest,
string_tests.MixinStrUserStringTest,
):
# A PyShadowString should pass the tests for str too.
type2test = PyShadowString
class ShadowStrTestCase(unittest.TestCase):
def setUp(self):
self.ss = PyShadowString("hello", "bonjour")
# The Java class of a python module may be <module>$py
CCLASS = r"test\.test_shadowstr_jy\$py" # compiled (e.g. regrtest)
# Or it may be org.python.pycode._pyx<n>
PCLASS = r"org\.python\.pycode\._pyx\d+" # .py at the prompt
def check_first_eq(self):
self.assertTrue(self.ss == "hello")
self.assertFalse(self.ss == "bonjour")
self.assertTrue("hello" == self.ss)
self.assertFalse("bonjour" == self.ss)
# shadowstring-shadowstring comparisons
tt = PyShadowString("hello", "goodbye")
self.assertTrue(self.ss == tt) # primary==primary
tt = PyShadowString("adieu", "hello")
self.assertFalse(self.ss == tt) # primary==shadow
self.assertFalse(tt == self.ss) # shadow==primary
tt = PyShadowString("adieu", "bonjour")
self.assertFalse(self.ss == tt) # shadow==shadow
def check_both_eq(self):
self.assertTrue(self.ss == "hello")
self.assertTrue(self.ss == "bonjour")
self.assertTrue("hello" == self.ss)
self.assertTrue("bonjour" == self.ss)
# shadowstring-shadowstring comparisons
tt = PyShadowString("hello", "goodbye")
for c, m in self.ss.gettargets(): tt.addtarget(c, m)
self.assertTrue(self.ss == tt) # primary==primary
tt = PyShadowString("goodbye", "hello")
for c, m in self.ss.gettargets(): tt.addtarget(c, m)
self.assertTrue(self.ss == tt) # primary==shadow
self.assertTrue(tt == self.ss) # shadow==primary
tt = PyShadowString("adieu", "bonjour")
for c, m in self.ss.gettargets(): tt.addtarget(c, m)
self.assertTrue(self.ss == tt) # shadow==shadow
def test_eq(self):
# Test recognition unconditionally
self.check_first_eq()
self.ss.addtarget(None) # match any
self.check_both_eq()
def test_eq_class(self):
# Test recognition of class context only
self.check_first_eq()
self.ss.addtarget(self.CCLASS)
self.ss.addtarget(self.PCLASS)
self.check_both_eq()
def test_eq_method(self):
# Test recognition of method context only
self.check_first_eq()
# The Java method name of a python function is name$<n>
self.ss.addtarget(None, r"test_eq_method\$\d+") # method only
self.check_both_eq()
def test_eq_class_method(self):
# Test recognition of class and method context
self.check_first_eq()
# Match this method in this module
method = r"test_eq_class_method\$\d+"
self.ss.addtarget(self.CCLASS, method)
self.ss.addtarget(self.PCLASS, method)
self.check_both_eq()
def check_first_startswith(self):
self.assertTrue(self.ss.startswith("hel"))
self.assertFalse(self.ss.startswith("bon"))
def check_both_startswith(self):
self.assertTrue(self.ss.startswith("hel"))
self.assertTrue(self.ss.startswith("bon"))
def test_startswith(self):
# Test recognition unconditionally
self.check_first_startswith()
self.ss.addtarget(None) # match any
self.check_both_startswith()
def test_startswith_class(self):
# Test recognition of class context only
self.check_first_startswith()
self.ss.addtarget(self.CCLASS) # class only
self.ss.addtarget(self.PCLASS) # class only
self.check_both_startswith()
def test_startswith_method(self):
# Test recognition of method context only
self.check_first_startswith()
self.ss.addtarget(None, r"test_startswith_method\$\d+") # method only
self.check_both_startswith()
def test_startswith_class_method(self):
# Test recognition of class and method context
self.check_first_startswith()
# Match this method in this module
method = r"test_startswith_class_method\$\d+"
self.ss.addtarget(self.CCLASS, method)
self.ss.addtarget(self.PCLASS, method)
self.check_both_startswith()
def test_slice(self):
# Test slicing goes through to the constituent strings consistently
def check(m, n):
tt = self.ss[m:n]
self.assertEqual(tt, "hello"[m:n])
self.assertEqual(tt, "bonjour"[m:n])
self.assertEqual(self.ss.gettargets(), tt.gettargets())
# Match this method in this module
method = r"test_slice\$\d+"
self.ss.addtarget(self.CCLASS, method)
self.ss.addtarget(self.PCLASS, method)
check(None, 3)
check(1, 5)
check(-3, None)
check(None, None)
def test_main():
run_unittest(
StrTestCase,
ShadowStrTestCase,
)
if __name__ == "__main__":
test_main()
| en | 0.704904 | # Made for Jython # Tests of built-in type shadowstr # Ideally we would test shadowstr is a str but the tests need to sub-class it # A PyShadowString should pass the tests for str too. # The Java class of a python module may be <module>$py # compiled (e.g. regrtest) # Or it may be org.python.pycode._pyx<n> # .py at the prompt # shadowstring-shadowstring comparisons # primary==primary # primary==shadow # shadow==primary # shadow==shadow # shadowstring-shadowstring comparisons # primary==primary # primary==shadow # shadow==primary # shadow==shadow # Test recognition unconditionally # match any # Test recognition of class context only # Test recognition of method context only # The Java method name of a python function is name$<n> # method only # Test recognition of class and method context # Match this method in this module # Test recognition unconditionally # match any # Test recognition of class context only # class only # class only # Test recognition of method context only # method only # Test recognition of class and method context # Match this method in this module # Test slicing goes through to the constituent strings consistently # Match this method in this module | 2.991902 | 3 |
rplugin/python3/lista/matcher/fuzzy.py | gitter-badger/lista.nvim | 0 | 6620341 | import re
from . import AbstractMatcher, escape_vim_patterns
class Matcher(AbstractMatcher):
name = 'fuzzy'
def highlight_pattern(self, query):
chars = map(escape_vim_patterns, list(query))
chars = map(lambda x: '%s[^%s]\\{-}' % (x, x), chars)
return ''.join(chars)
def filter(self, query, indices, candidates):
chars = map(re.escape, list(query))
chars = map(lambda x: '%s[^%s]*?' % (x, x), chars)
pattern = ''.join(chars)
if self.nvim.eval('&ignorecase'):
pattern = re.compile(pattern.lower())
indices[:] = [
i for i in indices
if pattern.search(candidates[i].lower())
]
else:
pattern = re.compile(pattern)
indices[:] = [
i for i in indices
if pattern.search(candidates[i])
]
| import re
from . import AbstractMatcher, escape_vim_patterns
class Matcher(AbstractMatcher):
name = 'fuzzy'
def highlight_pattern(self, query):
chars = map(escape_vim_patterns, list(query))
chars = map(lambda x: '%s[^%s]\\{-}' % (x, x), chars)
return ''.join(chars)
def filter(self, query, indices, candidates):
chars = map(re.escape, list(query))
chars = map(lambda x: '%s[^%s]*?' % (x, x), chars)
pattern = ''.join(chars)
if self.nvim.eval('&ignorecase'):
pattern = re.compile(pattern.lower())
indices[:] = [
i for i in indices
if pattern.search(candidates[i].lower())
]
else:
pattern = re.compile(pattern)
indices[:] = [
i for i in indices
if pattern.search(candidates[i])
]
| none | 1 | 2.921945 | 3 | |
tasks/scheduled.py | tomcooperca/mlb-slack-tracker | 0 | 6620342 | from sched import scheduler
class ScheduledTaskExecutor():
def __init__(self, scheduler):
self.scheduler = scheduler
# self.thread = Thread()
# def run_scheduled(self):
# self.thread.run(scheduler.run())
| from sched import scheduler
class ScheduledTaskExecutor():
def __init__(self, scheduler):
self.scheduler = scheduler
# self.thread = Thread()
# def run_scheduled(self):
# self.thread.run(scheduler.run())
| en | 0.363495 | # self.thread = Thread() # def run_scheduled(self): # self.thread.run(scheduler.run()) | 2.696868 | 3 |
scripts/hello_world_RubyCodes14.py | Joshua-Ogbonna/codeclannigeria-hacktoberfest | 7 | 6620343 | <gh_stars>1-10
# LANGUAGE: Python
# ENV: Python 3
# AUTHOR: <NAME>
# GITHUB: https://github.com/RubyCodes14
print("Hello World!")
input("")
| # LANGUAGE: Python
# ENV: Python 3
# AUTHOR: <NAME>
# GITHUB: https://github.com/RubyCodes14
print("Hello World!")
input("") | en | 0.621473 | # LANGUAGE: Python # ENV: Python 3 # AUTHOR: <NAME> # GITHUB: https://github.com/RubyCodes14 | 2.177232 | 2 |
momentum_srsi.py | EmreMicrosoft/piyasa-indikatorleri | 0 | 6620344 | <gh_stars>0
# SRSI (Stochastic Relative Strength Index)
# https://school.stockcharts.com/doku.php?id=technical_indicators:stochrsi
# https://www.investopedia.com/terms/s/stochrsi.asp
# StochRSI osilatörü, genelleştirilmiş bir fiyat değişikliği analizinden ziyade
# belirli bir menkul kıymetin tarihsel performansına uyumlu daha hassas bir gösterge
# oluşturmak için her iki momentum göstergesinden de yararlanmak üzere geliştirilmiştir.
# Argümanlar:
# close(pandas.Series): veri kümesi 'Kapat' sütunu.
# window(int): n periyodu.
# smooth1(int): Stokastik RSI'nin hareketli ortalaması.
# smooth2(int): hareketli ortalama %K
# fillna(bool): True ise, nan değerlerini doldur.
import pandas as pd
from _utilities import IndicatorMixin
from momentum_rsi import RSIIndicator
class StochRSIIndicator(IndicatorMixin):
def __init__(
self,
close: pd.Series,
window: int = 14,
smooth1: int = 3,
smooth2: int = 3,
fillna: bool = False,
):
self._close = close
self._window = window
self._smooth1 = smooth1
self._smooth2 = smooth2
self._fillna = fillna
self._run()
def _run(self):
self._rsi = RSIIndicator(
close=self._close, window=self._window, fillna=self._fillna).rsi()
lowest_low_rsi = self._rsi.rolling(self._window).min()
self._stochrsi = (self._rsi - lowest_low_rsi) / (
self._rsi.rolling(self._window).max() - lowest_low_rsi)
self._stochrsi_k = self._stochrsi.rolling(self._smooth1).mean()
def stochrsi(self):
stochrsi_series = self._check_fillna(self._stochrsi)
return pd.Series(stochrsi_series, name="stochrsi")
def stochrsi_k(self):
stochrsi_k_series = self._check_fillna(self._stochrsi_k)
return pd.Series(stochrsi_k_series, name="stochrsi_k")
def stochrsi_d(self):
stochrsi_d_series = self._stochrsi_k.rolling(self._smooth2).mean()
stochrsi_d_series = self._check_fillna(stochrsi_d_series)
return pd.Series(stochrsi_d_series, name="stochrsi_d") | # SRSI (Stochastic Relative Strength Index)
# https://school.stockcharts.com/doku.php?id=technical_indicators:stochrsi
# https://www.investopedia.com/terms/s/stochrsi.asp
# StochRSI osilatörü, genelleştirilmiş bir fiyat değişikliği analizinden ziyade
# belirli bir menkul kıymetin tarihsel performansına uyumlu daha hassas bir gösterge
# oluşturmak için her iki momentum göstergesinden de yararlanmak üzere geliştirilmiştir.
# Argümanlar:
# close(pandas.Series): veri kümesi 'Kapat' sütunu.
# window(int): n periyodu.
# smooth1(int): Stokastik RSI'nin hareketli ortalaması.
# smooth2(int): hareketli ortalama %K
# fillna(bool): True ise, nan değerlerini doldur.
import pandas as pd
from _utilities import IndicatorMixin
from momentum_rsi import RSIIndicator
class StochRSIIndicator(IndicatorMixin):
def __init__(
self,
close: pd.Series,
window: int = 14,
smooth1: int = 3,
smooth2: int = 3,
fillna: bool = False,
):
self._close = close
self._window = window
self._smooth1 = smooth1
self._smooth2 = smooth2
self._fillna = fillna
self._run()
def _run(self):
self._rsi = RSIIndicator(
close=self._close, window=self._window, fillna=self._fillna).rsi()
lowest_low_rsi = self._rsi.rolling(self._window).min()
self._stochrsi = (self._rsi - lowest_low_rsi) / (
self._rsi.rolling(self._window).max() - lowest_low_rsi)
self._stochrsi_k = self._stochrsi.rolling(self._smooth1).mean()
def stochrsi(self):
stochrsi_series = self._check_fillna(self._stochrsi)
return pd.Series(stochrsi_series, name="stochrsi")
def stochrsi_k(self):
stochrsi_k_series = self._check_fillna(self._stochrsi_k)
return pd.Series(stochrsi_k_series, name="stochrsi_k")
def stochrsi_d(self):
stochrsi_d_series = self._stochrsi_k.rolling(self._smooth2).mean()
stochrsi_d_series = self._check_fillna(stochrsi_d_series)
return pd.Series(stochrsi_d_series, name="stochrsi_d") | tr | 0.916259 | # SRSI (Stochastic Relative Strength Index) # https://school.stockcharts.com/doku.php?id=technical_indicators:stochrsi # https://www.investopedia.com/terms/s/stochrsi.asp # StochRSI osilatörü, genelleştirilmiş bir fiyat değişikliği analizinden ziyade # belirli bir menkul kıymetin tarihsel performansına uyumlu daha hassas bir gösterge # oluşturmak için her iki momentum göstergesinden de yararlanmak üzere geliştirilmiştir. # Argümanlar: # close(pandas.Series): veri kümesi 'Kapat' sütunu. # window(int): n periyodu. # smooth1(int): Stokastik RSI'nin hareketli ortalaması. # smooth2(int): hareketli ortalama %K # fillna(bool): True ise, nan değerlerini doldur. | 2.631069 | 3 |
code/pyseg/scripts/tests/mcf_synthetic_test.py | anmartinezs/pyseg_system | 12 | 6620345 | <filename>code/pyseg/scripts/tests/mcf_synthetic_test.py
"""
Tests for testing bio-material tracking by GraphMCF
"""
__author__ = '<NAME>'
import time
import sys
from pyseg.scripts import mcf_graph
from pyseg.factory import Grid3D
from pyseg.factory import unpickle_obj
from pyseg.globals import *
import pyseg.disperse_io as disperse_io
from matplotlib import pyplot as plt, rcParams
import multiprocessing as mp
### INPUT SETTINGS ##############
# Short version is 'False' (default) takes few minutes but is enough for testing
# functionality, long version 'True' produces stronger statistics but takes a few
# hours and require high memory resources
try:
if sys.argv[1] == 'do_long':
do_long = True
else:
do_long = False
except IndexError:
do_long = False
ROOT_DIR = os.path.split(os.path.abspath(__file__))[0] + '/../../../tests/'
MCF_OUT_DIR = ROOT_DIR + '/../../data/synthetic_grid'
#################################
rcParams['axes.labelsize'] = 14
rcParams['xtick.labelsize'] = 14
rcParams['ytick.labelsize'] = 14
# mcf_graph configuration
PAIR_PROP = STR_FIELD_VALUE
#### Grid 3D test variables
G3_SKIP = True
G3_RESOLUTION = 1
G3_NSIG_PER = 0.05
G3_PERSISTENCE = 0.01
G3_NOISE_MODE = 'normal'
# np.linspace(0.03, 1.0, 15)[::-1]# (1.3, 1., 0.6, 0.3, 0.1, 0.01) # (0.3, 0.1)
if do_long:
G3_L = (6, 6, 3)
G3_STD_NOISE = np.linspace(0.03, 1.0, 15)[::-1]
G3_NUM_REP = 10
G3_NPR = 10
else:
G3_L = (3, 3, 3) # (3, 3, 2)
G3_STD_NOISE = np.linspace(0.03, 1.0, 10)[::-1]
G3_NUM_REP = 3
G3_NPR = 3
G3_SP = 8 # 4
G3_EV = 0.3 # 0.5
G3_GBP_CUT = 0.3
G3_FEAT = 0.05
G3_EPS = 3
# For picking
G3_GRAPHMCF_PKL = True # True
G3_EDG_VER_RATIO = 6.0
G3_RES_PER = 1.2
# For DoG
DOG_SG1 = 1.5
DOG_K = 1.1
#################################################################################################
# Parallel process for computing the graph
#################################################################################################
def pr_mcf_graph(pr_id, ids, std, mcf_out_dir, res, dims, eps, sp, ev, nsig_per, res_per, ev_ratio):
# To avoid repeated simulations
if pr_id < -1:
np.random.seed(0)
else:
np.random.seed(pr_id)
for idx in ids:
g3_tomo_file = MCF_OUT_DIR + '/grid_noise_std_' + str(std) + '_it_' + str(idx) + '.fits'
g3_mask_file = MCF_OUT_DIR + '/grid_mask_std_' + str(std) + '_it_' + str(idx) + '_mask.fits'
# g3_graph_pkl = MCF_OUT_DIR + '/grid_graph_std_' + str(G3_STD_NOISE[j]) + '_it_' + str(i) + '.pkl'
g3_graph_vtp = MCF_OUT_DIR + '/grid_graph_skel_' + str(std) + '_it_' + str(idx) + '.vtp'
g3_graph_sch = MCF_OUT_DIR + '/grid_graph_sch_' + str(std) + '_it_' + str(idx) + '.vtp'
g3_grid_pkl = MCF_OUT_DIR + '/grid_' + str(std) + '_it_' + str(idx) + '.pkl'
mcf_out_dir2 = MCF_OUT_DIR + '/graph_' + str(std) + '_it_' + str(idx)
if os.path.exists(mcf_out_dir2):
clean_dir(mcf_out_dir2)
else:
os.makedirs(mcf_out_dir2)
g3_graph_pkl = mcf_out_dir2 + '/' + os.path.splitext(os.path.split(g3_tomo_file)[1])[0] + '.pkl'
grid = Grid3D()
grid.set_parameters(dims, sp, (thick, thick), ev)
grid.build()
grid.add_noise(G3_NOISE_MODE, G3_STD_NOISE[std])
grid.save_tomo(g3_tomo_file)
grid.save_mask(g3_mask_file)
grid.pickle(g3_grid_pkl)
thick2 = 1
main_args = ['-i', g3_tomo_file, '-o', mcf_out_dir2, '-m', g3_mask_file,
'-r', str(res), '-N', str(nsig_per), '-S', 3,
'-s', 0.5 * thick2] # , '-v']
mcf_graph.main(main_args)
# Load GraphMCF
print('\tPROCESS[' + str(pr_id) + ']: Unpickling the graph: ' + g3_graph_pkl)
graph_mcf = unpickle_obj(g3_graph_pkl)
# Make topological simplification until fitting the number of features times residues percentage
print('\tPROCESS[' + str(pr_id) + ']: Simplifying the graph...')
graph_mcf.topological_simp(0, n=grid.get_num_features()*res_per, prop_ref=STR_FIELD_VALUE)
# Filter edges until fitting the number of edges
# n_edges = float(len(graph_mcf.get_vertices_list())) * ev_ratio
# i_edges = len(graph_mcf.get_edges_list())
# if n_edges < i_edges:
n_edges = int(math.ceil(grid.get_num_edges()*res_per))
print('\t\t-Number of edges to keep: ' + str(n_edges))
graph_mcf.threshold_edges_n(n_edges, STR_FIELD_VALUE, mode='low')
# else:
# print 'WARNING [process:' + str(pr_id) + ']: Graph cannot be simplify to ' + str(n_edges) + \
# ' edges, since it has only ' + str(i_edges)
disperse_io.save_vtp(graph_mcf.get_vtp(av_mode=True, edges=True), g3_graph_vtp)
disperse_io.save_vtp(graph_mcf.get_scheme_vtp(nodes=True, edges=True), g3_graph_sch)
graph_mcf.pickle(g3_graph_pkl)
if pr_id < 0:
return -1
else:
print('\tFinishing PROCESS[' + str(pr_id) + '] successfully!')
return pr_id
#################################################################################################
# Main Routine
#################################################################################################
print('Evaluating GraphMCF performance with synthetic data.')
print('\tAuthor: ' + __author__)
print('\tDate: ' + time.strftime("%c") + '\n')
print('Running main loop:')
hold_snr = (-1) * np.zeros(shape=(G3_NUM_REP, len(G3_STD_NOISE)), dtype=np.float)
hold_t_p = (-1) * np.zeros(shape=(G3_NUM_REP, len(G3_STD_NOISE)), dtype=np.float)
hold_f_p = (-1) * np.ones(shape=(G3_NUM_REP, len(G3_STD_NOISE)), dtype=np.float)
hold_f_n = (-1) * np.ones(shape=(G3_NUM_REP, len(G3_STD_NOISE)), dtype=np.float)
hold_p_e = (-1) * np.zeros(shape=(G3_NUM_REP, len(G3_STD_NOISE)), dtype=np.float)
hold_pp_e = (-1) * np.zeros(shape=(G3_NUM_REP, len(G3_STD_NOISE)), dtype=np.float)
hold_b_e = (-1) * np.zeros(shape=(G3_NUM_REP, len(G3_STD_NOISE)), dtype=np.float)
hold_snr = np.zeros(shape=(G3_NUM_REP, len(G3_STD_NOISE)), dtype=np.float)
thick = G3_SP * G3_FEAT
thick2 = 2 * math.ceil(thick * G3_RESOLUTION)
# Noise loop for computing the graphs
for j in range(len(G3_STD_NOISE)):
print('\tProcessing noise entry: ' + str(j) + ' of ' + str(len(G3_STD_NOISE)))
if G3_GRAPHMCF_PKL:
print('\tGenerating grids and graphs...')
# MULTIPROCESSING
if G3_NPR <= 1:
pr_mcf_graph(0, list(range(G3_NUM_REP)), j, MCF_OUT_DIR, G3_RESOLUTION, G3_L, G3_EPS, G3_SP, G3_EV,
G3_NSIG_PER, G3_RES_PER, G3_EDG_VER_RATIO)
else:
processes = list()
spl_ids = np.array_split(list(range(G3_NUM_REP)), G3_NPR)
for pr_id, ids in zip(list(range(G3_NPR)), spl_ids):
pr = mp.Process(target=pr_mcf_graph, args=(pr_id, ids, j, MCF_OUT_DIR, G3_RESOLUTION,
G3_L, G3_EPS, G3_SP,
G3_EV, G3_NSIG_PER, G3_RES_PER, G3_EDG_VER_RATIO))
pr.start()
processes.append(pr)
pr_results = list()
for pr in processes:
pr.join()
pr_results.append(pr.exitcode)
# for pr_id in range(len(processes)):
# if pr_id != pr_results[pr_id]:
# error_msg = 'Process ' + str(pr_id) + ' exited unexpectedly!'
# sys.exit(-1)
print('\t\t-All processes are finished!')
else:
print('\t\t-WARNING: tomograms are loaded from a previous running instance so some settings may not fit!')
print('\tGraphs computed!')
# Repetitions loop
for i in range(G3_NUM_REP):
# Paths
g3_tomo_file = MCF_OUT_DIR + '/grid_noise_std_' + str(j) + '_it_' + str(i) + '.fits'
g3_grid_pkl = MCF_OUT_DIR + '/grid_' + str(j) + '_it_' + str(i) + '.pkl'
mcf_out_dir2 = MCF_OUT_DIR + '/graph_' + str(j) + '_it_' + str(i)
g3_graph_pkl = mcf_out_dir2 + '/' + os.path.splitext(os.path.split(g3_tomo_file)[1])[0] + '.pkl'
# Synthetic phantom generation
print('\tLoading the grid with STD=' + str(G3_STD_NOISE[j]) + ' and repetition ' + str(i) + '.')
grid = unpickle_obj(g3_grid_pkl)
hold_snr[i, j] = grid.get_snr()
# Noise loop for data analysis
for j in range(len(G3_STD_NOISE)):
# Repetitions loop
for i in range(G3_NUM_REP):
# Paths
g3_tomo_file = MCF_OUT_DIR + '/grid_noise_std_' + str(j) + '_it_' + str(i) + '.fits'
g3_mask_file = MCF_OUT_DIR + '/grid_mask_std_' + str(j) + '_it_' + str(i) + '_mask.fits'
g3_graph_vtp = MCF_OUT_DIR + '/grid_graph_skel_' + str(j) + '_it_' + str(i) + '.vtp'
g3_graph_sch = MCF_OUT_DIR + '/grid_graph_sch_' + str(j) + '_it_' + str(i) + '.vtp'
g3_grid_pkl = MCF_OUT_DIR + '/grid_' + str(j) + '_it_' + str(i) + '.pkl'
mcf_out_dir2 = MCF_OUT_DIR + '/graph_' + str(j) + '_it_' + str(i)
g3_graph_pkl = mcf_out_dir2 + '/' + os.path.splitext(os.path.split(g3_tomo_file)[1])[0] + '.pkl'
g3_dog_file = MCF_OUT_DIR + '/grid_noise_std_' + str(j) + '_it_' + str(i) + '_dog.mrc'
# print '\tComputing DoG metrics...'
# n_points_dog = grid.get_num_features() * G3_RES_PER
# g3_tomo_dog = dog_operator(lin_map(g3_tomo_file, lb=1, ub=0), DOG_SG1, DOG_K)
# disperse_io.save_numpy(g3_tomo_dog, g3_dog_file)
# g3_dog_peaks = find_region_peaks_by_num(g3_tomo_dog, n_points_dog)
# labels_dog, v_tps_dog = list(), list()
# gxs, gys, gzs = grid.get_grid_points()
# grid_vs = -1 * np.ones(shape=gxs.shape, dtype=np.int)
# good_picks_dog, bad_picks_dog, fp_picks_dog, tot_picks_dog = 0., 0., 0., float(np.asarray(gxs.shape).prod())
# for x in range(gxs.shape[0]):
# for y in range(gys.shape[1]):
# for z in range(gzs.shape[2]):
# hold_min = np.finfo(np.float).max
# g_point = np.asarray((gxs[x, y, z], gys[x, y, z], gzs[x, y, z]), dtype=np.float32)
# pick_found = False
# for point in g3_dog_peaks:
# dst = g_point - point
# dst = math.sqrt((dst*dst).sum())
# if hold_min > dst:
# if dst < G3_EPS:
# grid_vs[x, y, z] = int(v.get_id())
# pick_found = True
# hold_min = dst
# if pick_found:
# good_picks_dog += 1
# else:
# bad_picks_dog += 1
# # Computing the false positives
# for point in g3_dog_peaks:
# if not grid.in_feature(point, G3_EPS):
# fp_picks_dog += 1
print('\tUnpickling GraphMCF...')
graph_mcf = unpickle_obj(g3_graph_pkl)
# Getting the starting points for tracing
labels, v_tps = list(), list()
vertices = graph_mcf.get_vertices_list()
n_points = float(len(vertices))
# points = np.zeros(shape=(n_points, 3), dtype=np.float)
gxs, gys, gzs = grid.get_grid_points()
grid_vs = -1 * np.ones(shape=gxs.shape, dtype=np.int)
good_picks, bad_picks, fp_picks, tot_picks = 0., 0., 0., float(np.asarray(gxs.shape).prod())
for x in range(gxs.shape[0]):
for y in range(gys.shape[1]):
for z in range(gzs.shape[2]):
labels.append(str(x) + '_' + str(y) + '_' + str(z))
hold_min = np.finfo(np.float).max
g_point = np.asarray((gxs[x, y, z], gys[x, y, z], gzs[x, y, z]), dtype=np.float32)
pick_found = False
for v in vertices:
point = np.asarray(graph_mcf.get_vertex_coords(v), dtype=np.float32)
dst = g_point - point
dst = math.sqrt((dst*dst).sum())
if hold_min > dst:
if dst < G3_EPS:
grid_vs[x, y, z] = int(v.get_id())
pick_found = True
hold_min = dst
if pick_found:
v_tps.append(grid_vs[x, y, z])
good_picks += 1
else:
bad_picks += 1
# Computing the false positives
v_fps = list()
for v in vertices:
point = np.asarray(graph_mcf.get_vertex_coords(v), dtype=np.float32)
if not grid.in_feature(point, G3_EPS):
fp_picks += 1
v_fps.append(int(v.get_id()))
# Trace the path to closest neighbours
pairs = list()
graph_mcf.compute_graph_gt()
tot_path, good_path, bad_path = 0., 0., 0.
for x in range(gxs.shape[0]):
for y in range(gys.shape[1]):
for z in range(gzs.shape[2]):
# Get starting vertex and neighbours (target vertices)
v = grid_vs[x, y, z]
lbl = str(x) + '_' + str(y) + '_' + str(z)
if v != -1:
if x == 0:
nx0 = None
else:
nx0 = grid_vs[x-1, y, z]
if x == gxs.shape[0] - 1:
nx1 = None
else:
nx1 = grid_vs[x+1, y, z]
if y == 0:
ny0 = None
else:
ny0 = grid_vs[x, y-1, z]
if y == gys.shape[1] - 1:
ny1 = None
else:
ny1 = grid_vs[x, y+1, z]
if z == 0:
nz0 = None
else:
nz0 = grid_vs[x, y, z-1]
if z == gzs.shape[2] - 1:
nz1 = None
else:
nz1 = grid_vs[x, y, z+1]
# Check paths
neighbours = [nx0, nx1, ny0, ny1, nz0, nz1]
for t in v_tps:
if not ((str(v) + '_' + str(t)) in pairs):
pairs.append(str(v) + '_' + str(t))
pairs.append(str(t) + '_' + str(v))
if t in neighbours:
tot_path += 1
# Computing the arc path
v_path, e_path = graph_mcf.find_shortest_path(v, t, prop_key=SGT_EDGE_LENGTH)
found = False
if v_path is not None:
if len(v_path) > 2:
for p in v_path[1:-1]:
if p in neighbours:
found = True
break
else:
found = True
if not found:
good_path += 1
else:
v_path, e_path = graph_mcf.find_shortest_path(v, t, prop_key=SGT_EDGE_LENGTH)
found = True
if v_path is not None:
if len(v_path) >= 2:
for p in v_path[1:]:
hold_point = graph_mcf.get_vertex_coords(graph_mcf.get_vertex(p))
if not grid.in_grid(hold_point):
found = False
break
if (p in neighbours) or (p in v_tps):
break
# if found:
# for e in e_path:
# hold_point = graph_mcf.get_edge_coords(graph_mcf.get_edge(e))
# if not grid.in_grid(hold_point):
# found = False
# break
if not found:
bad_path += 1
if good_picks > tot_picks:
good_picks = tot_picks
if bad_picks > tot_picks:
bad_picks = tot_picks
if tot_picks <= 0:
hold_t_p[i, j] = 0
hold_f_n[i, j] = 0
else:
hold_t_p[i, j] = good_picks / tot_picks
hold_f_n[i, j] = bad_picks / tot_picks
if n_points <= 0:
hold_f_p[i, j] = 0
else:
hold_f_p[i, j] = fp_picks / n_points
if tot_path <= 0:
hold_p_e[i, j] = 0
hold_pp_e[i, j] = 0
hold_b_e[i, j] = 0
else:
# hold_p_e[i, j] = good_path / tot_path
hold_pp_e[i, j] = good_path / tot_path
hold_p_e[i, j] = good_path / grid.get_num_edges()
# if (bad_path_fp+good_path_fp) > 0:
if bad_path > 0:
# hold_b_e[i, j] = bad_path_fp / (bad_path_fp + good_path_fp)
hold_b_e[i, j] = bad_path / grid.get_num_edges()
else:
hold_b_e[i, j] = 0
# Printing the result
print('')
print('\tRESULTS: ')
print('\tSNR: [' + str(hold_snr[:, j].min()) + ', ' + str(hold_snr[:, j].mean()) + ', ' + str(hold_snr[:, j].max()) + ']')
print('\tTrue positive picked: [' + str(hold_t_p[:, j].min()) + ', ' + str(hold_t_p[:, j].mean()) + ', ' + str(hold_t_p[:, j].max()) + ']')
print('\tFalse positive picked: [' + str(hold_f_p[:, j].min()) + ', ' + str(hold_f_p[:, j].mean()) + ', ' + str(hold_f_p[:, j].max()) + ']')
print('\tFalse negative picked: [' + str(hold_f_n[:, j].min()) + ', ' + str(hold_f_n[:, j].mean()) + ', ' + str(hold_f_n[:, j].max()) + ']')
print('\tFraction of correctly tracked paths over corrected ground truth: [' + str(hold_pp_e[:, j].min()) + ', ' + str(hold_pp_e[:, j].mean()) + ', ' + str(hold_pp_e[:, j].max()) + ']')
print('\tFraction of correctly tracked paths: [' + str(hold_p_e[:, j].min()) + ', ' + str(hold_p_e[:, j].mean()) + ', ' + str(hold_p_e[:, j].max()) + ']')
print('\tFraction of bad tracked paths: [' + str(hold_b_e[:, j].min()) + ', ' + str(hold_b_e[:, j].mean()) + ', ' + str(hold_b_e[:, j].max()) + ']')
# Storing the results
np.savez(MCF_OUT_DIR + '/grid3d_arrays.npz', hold_snr, hold_t_p, hold_p_e, hold_f_p, hold_f_n, hold_b_e)
# Plotting the results
snr_mean = np.mean(hold_snr, axis=0)
fig = plt.figure()
ax = fig.add_subplot(111)
plt.errorbar(snr_mean, np.mean(hold_t_p, axis=0), yerr=np.std(hold_t_p, axis=0)/math.sqrt(G3_NUM_REP), color='blue', linestyle='-', linewidth=1.5, label='TP')
# plt.plot(snr_mean, np.mean(hold_t_p, axis=0), color='blue', linestyle='-', linewidth=2, label='TP')
# plt.fill_between(snr_mean, np.mean(hold_t_p, axis=0)-.5*np.std(hold_t_p, axis=0)/math.sqrt(G3_NUM_REP), np.mean(hold_t_p, axis=0)+.5*np.std(hold_t_p, axis=0)/math.sqrt(G3_NUM_REP), alpha=0.5, color='blue', edgecolor='w')
plt.errorbar(snr_mean, np.mean(hold_pp_e, axis=0), yerr=np.std(hold_pp_e, axis=0)/math.sqrt(G3_NUM_REP), color='red', linestyle='-.', linewidth=1.5, label='TP arcs corrected')
plt.errorbar(snr_mean, np.mean(hold_p_e, axis=0), yerr=np.std(hold_p_e, axis=0)/math.sqrt(G3_NUM_REP), color='red', linestyle='-', linewidth=1.5, label='TP arcs')
# plt.plot(snr_mean, np.mean(hold_p_e, axis=0), color='red', linestyle='-', linewidth=2, label='TP arcs')
# plt.fill_between(snr_mean, np.mean(hold_p_e, axis=0)-.5*np.std(hold_p_e, axis=0)/math.sqrt(G3_NUM_REP), np.mean(hold_p_e, axis=0)+.5*np.std(hold_p_e, axis=0)/math.sqrt(G3_NUM_REP), alpha=0.5, color='red', edgecolor='w')
plt.errorbar(snr_mean, np.mean(hold_f_p, axis=0), yerr=np.std(hold_f_p, axis=0)/math.sqrt(G3_NUM_REP), color='yellow', linestyle='-', linewidth=1.5, label='FP')
# plt.plot(snr_mean, np.mean(hold_f_p, axis=0), color='yellow', linestyle='-', linewidth=2, label='FP')
# plt.fill_between(snr_mean, np.mean(hold_f_p, axis=0)-.5*np.std(hold_f_p, axis=0)/math.sqrt(G3_NUM_REP), np.mean(hold_f_p, axis=0)+.5*np.std(hold_f_p, axis=0)/math.sqrt(G3_NUM_REP), alpha=0.5, color='yellow', edgecolor='w')
plt.errorbar(snr_mean, np.mean(hold_f_n, axis=0), yerr=np.std(hold_f_n, axis=0)/math.sqrt(G3_NUM_REP), color='cyan', linestyle='-', linewidth=1.5, label='FN')
# plt.plot(snr_mean, np.mean(hold_f_n, axis=0), color='cyan', linestyle='-', linewidth=2, label='FN')
# plt.fill_between(snr_mean, np.mean(hold_f_n, axis=0)-0.5*np.std(hold_f_n, axis=0)/math.sqrt(G3_NUM_REP), np.mean(hold_f_n, axis=0)+0.5*np.std(hold_f_n, axis=0)/math.sqrt(G3_NUM_REP), alpha=0.5, color='cyan', edgecolor='w')
plt.errorbar(snr_mean, np.mean(hold_b_e, axis=0), yerr=np.std(hold_b_e, axis=0)/math.sqrt(G3_NUM_REP), color='magenta', linestyle='-', linewidth=1.5, label='FP arcs')
# plt.plot(snr_mean, np.mean(hold_b_e, axis=0), color='magenta', linestyle='-', linewidth=2, label='FP arcs')
# plt.fill_between(snr_mean, np.mean(hold_b_e, axis=0)-0.5*np.std(hold_b_e, axis=0)/math.sqrt(G3_NUM_REP), np.mean(hold_b_e, axis=0)+0.5*np.std(hold_b_e, axis=0)/math.sqrt(G3_NUM_REP), alpha=0.5, color='magenta', edgecolor='w')
plt.plot(snr_mean, np.ones(shape=hold_p_e.shape[1]), color='black', linestyle='--', linewidth=1)
plt.plot(snr_mean, np.zeros(shape=hold_p_e.shape[1]), color='black', linestyle='--', linewidth=1)
plt.ylim((-0.1, 1.1))
plt.xlim((snr_mean[0], snr_mean[-1]))
ax.set_xscale('log')
plt.xlabel('SNR')
plt.legend(loc=7)
# ref_FR_ssup_mb.sh
plt.tight_layout()
out_fig = MCF_OUT_DIR + '/test_grid_conn.png'
print('Saving output figure in: ' + out_fig)
plt.savefig(out_fig, dpi=600)
plt.close()
print('Terminated successfully. (' + time.strftime("%c") + ')')
| <filename>code/pyseg/scripts/tests/mcf_synthetic_test.py
"""
Tests for testing bio-material tracking by GraphMCF
"""
__author__ = '<NAME>'
import time
import sys
from pyseg.scripts import mcf_graph
from pyseg.factory import Grid3D
from pyseg.factory import unpickle_obj
from pyseg.globals import *
import pyseg.disperse_io as disperse_io
from matplotlib import pyplot as plt, rcParams
import multiprocessing as mp
### INPUT SETTINGS ##############
# Short version is 'False' (default) takes few minutes but is enough for testing
# functionality, long version 'True' produces stronger statistics but takes a few
# hours and require high memory resources
try:
if sys.argv[1] == 'do_long':
do_long = True
else:
do_long = False
except IndexError:
do_long = False
ROOT_DIR = os.path.split(os.path.abspath(__file__))[0] + '/../../../tests/'
MCF_OUT_DIR = ROOT_DIR + '/../../data/synthetic_grid'
#################################
rcParams['axes.labelsize'] = 14
rcParams['xtick.labelsize'] = 14
rcParams['ytick.labelsize'] = 14
# mcf_graph configuration
PAIR_PROP = STR_FIELD_VALUE
#### Grid 3D test variables
G3_SKIP = True
G3_RESOLUTION = 1
G3_NSIG_PER = 0.05
G3_PERSISTENCE = 0.01
G3_NOISE_MODE = 'normal'
# np.linspace(0.03, 1.0, 15)[::-1]# (1.3, 1., 0.6, 0.3, 0.1, 0.01) # (0.3, 0.1)
if do_long:
G3_L = (6, 6, 3)
G3_STD_NOISE = np.linspace(0.03, 1.0, 15)[::-1]
G3_NUM_REP = 10
G3_NPR = 10
else:
G3_L = (3, 3, 3) # (3, 3, 2)
G3_STD_NOISE = np.linspace(0.03, 1.0, 10)[::-1]
G3_NUM_REP = 3
G3_NPR = 3
G3_SP = 8 # 4
G3_EV = 0.3 # 0.5
G3_GBP_CUT = 0.3
G3_FEAT = 0.05
G3_EPS = 3
# For picking
G3_GRAPHMCF_PKL = True # True
G3_EDG_VER_RATIO = 6.0
G3_RES_PER = 1.2
# For DoG
DOG_SG1 = 1.5
DOG_K = 1.1
#################################################################################################
# Parallel process for computing the graph
#################################################################################################
def pr_mcf_graph(pr_id, ids, std, mcf_out_dir, res, dims, eps, sp, ev, nsig_per, res_per, ev_ratio):
# To avoid repeated simulations
if pr_id < -1:
np.random.seed(0)
else:
np.random.seed(pr_id)
for idx in ids:
g3_tomo_file = MCF_OUT_DIR + '/grid_noise_std_' + str(std) + '_it_' + str(idx) + '.fits'
g3_mask_file = MCF_OUT_DIR + '/grid_mask_std_' + str(std) + '_it_' + str(idx) + '_mask.fits'
# g3_graph_pkl = MCF_OUT_DIR + '/grid_graph_std_' + str(G3_STD_NOISE[j]) + '_it_' + str(i) + '.pkl'
g3_graph_vtp = MCF_OUT_DIR + '/grid_graph_skel_' + str(std) + '_it_' + str(idx) + '.vtp'
g3_graph_sch = MCF_OUT_DIR + '/grid_graph_sch_' + str(std) + '_it_' + str(idx) + '.vtp'
g3_grid_pkl = MCF_OUT_DIR + '/grid_' + str(std) + '_it_' + str(idx) + '.pkl'
mcf_out_dir2 = MCF_OUT_DIR + '/graph_' + str(std) + '_it_' + str(idx)
if os.path.exists(mcf_out_dir2):
clean_dir(mcf_out_dir2)
else:
os.makedirs(mcf_out_dir2)
g3_graph_pkl = mcf_out_dir2 + '/' + os.path.splitext(os.path.split(g3_tomo_file)[1])[0] + '.pkl'
grid = Grid3D()
grid.set_parameters(dims, sp, (thick, thick), ev)
grid.build()
grid.add_noise(G3_NOISE_MODE, G3_STD_NOISE[std])
grid.save_tomo(g3_tomo_file)
grid.save_mask(g3_mask_file)
grid.pickle(g3_grid_pkl)
thick2 = 1
main_args = ['-i', g3_tomo_file, '-o', mcf_out_dir2, '-m', g3_mask_file,
'-r', str(res), '-N', str(nsig_per), '-S', 3,
'-s', 0.5 * thick2] # , '-v']
mcf_graph.main(main_args)
# Load GraphMCF
print('\tPROCESS[' + str(pr_id) + ']: Unpickling the graph: ' + g3_graph_pkl)
graph_mcf = unpickle_obj(g3_graph_pkl)
# Make topological simplification until fitting the number of features times residues percentage
print('\tPROCESS[' + str(pr_id) + ']: Simplifying the graph...')
graph_mcf.topological_simp(0, n=grid.get_num_features()*res_per, prop_ref=STR_FIELD_VALUE)
# Filter edges until fitting the number of edges
# n_edges = float(len(graph_mcf.get_vertices_list())) * ev_ratio
# i_edges = len(graph_mcf.get_edges_list())
# if n_edges < i_edges:
n_edges = int(math.ceil(grid.get_num_edges()*res_per))
print('\t\t-Number of edges to keep: ' + str(n_edges))
graph_mcf.threshold_edges_n(n_edges, STR_FIELD_VALUE, mode='low')
# else:
# print 'WARNING [process:' + str(pr_id) + ']: Graph cannot be simplify to ' + str(n_edges) + \
# ' edges, since it has only ' + str(i_edges)
disperse_io.save_vtp(graph_mcf.get_vtp(av_mode=True, edges=True), g3_graph_vtp)
disperse_io.save_vtp(graph_mcf.get_scheme_vtp(nodes=True, edges=True), g3_graph_sch)
graph_mcf.pickle(g3_graph_pkl)
if pr_id < 0:
return -1
else:
print('\tFinishing PROCESS[' + str(pr_id) + '] successfully!')
return pr_id
#################################################################################################
# Main Routine
#################################################################################################
print('Evaluating GraphMCF performance with synthetic data.')
print('\tAuthor: ' + __author__)
print('\tDate: ' + time.strftime("%c") + '\n')
print('Running main loop:')
hold_snr = (-1) * np.zeros(shape=(G3_NUM_REP, len(G3_STD_NOISE)), dtype=np.float)
hold_t_p = (-1) * np.zeros(shape=(G3_NUM_REP, len(G3_STD_NOISE)), dtype=np.float)
hold_f_p = (-1) * np.ones(shape=(G3_NUM_REP, len(G3_STD_NOISE)), dtype=np.float)
hold_f_n = (-1) * np.ones(shape=(G3_NUM_REP, len(G3_STD_NOISE)), dtype=np.float)
hold_p_e = (-1) * np.zeros(shape=(G3_NUM_REP, len(G3_STD_NOISE)), dtype=np.float)
hold_pp_e = (-1) * np.zeros(shape=(G3_NUM_REP, len(G3_STD_NOISE)), dtype=np.float)
hold_b_e = (-1) * np.zeros(shape=(G3_NUM_REP, len(G3_STD_NOISE)), dtype=np.float)
hold_snr = np.zeros(shape=(G3_NUM_REP, len(G3_STD_NOISE)), dtype=np.float)
thick = G3_SP * G3_FEAT
thick2 = 2 * math.ceil(thick * G3_RESOLUTION)
# Noise loop for computing the graphs
for j in range(len(G3_STD_NOISE)):
print('\tProcessing noise entry: ' + str(j) + ' of ' + str(len(G3_STD_NOISE)))
if G3_GRAPHMCF_PKL:
print('\tGenerating grids and graphs...')
# MULTIPROCESSING
if G3_NPR <= 1:
pr_mcf_graph(0, list(range(G3_NUM_REP)), j, MCF_OUT_DIR, G3_RESOLUTION, G3_L, G3_EPS, G3_SP, G3_EV,
G3_NSIG_PER, G3_RES_PER, G3_EDG_VER_RATIO)
else:
processes = list()
spl_ids = np.array_split(list(range(G3_NUM_REP)), G3_NPR)
for pr_id, ids in zip(list(range(G3_NPR)), spl_ids):
pr = mp.Process(target=pr_mcf_graph, args=(pr_id, ids, j, MCF_OUT_DIR, G3_RESOLUTION,
G3_L, G3_EPS, G3_SP,
G3_EV, G3_NSIG_PER, G3_RES_PER, G3_EDG_VER_RATIO))
pr.start()
processes.append(pr)
pr_results = list()
for pr in processes:
pr.join()
pr_results.append(pr.exitcode)
# for pr_id in range(len(processes)):
# if pr_id != pr_results[pr_id]:
# error_msg = 'Process ' + str(pr_id) + ' exited unexpectedly!'
# sys.exit(-1)
print('\t\t-All processes are finished!')
else:
print('\t\t-WARNING: tomograms are loaded from a previous running instance so some settings may not fit!')
print('\tGraphs computed!')
# Repetitions loop
for i in range(G3_NUM_REP):
# Paths
g3_tomo_file = MCF_OUT_DIR + '/grid_noise_std_' + str(j) + '_it_' + str(i) + '.fits'
g3_grid_pkl = MCF_OUT_DIR + '/grid_' + str(j) + '_it_' + str(i) + '.pkl'
mcf_out_dir2 = MCF_OUT_DIR + '/graph_' + str(j) + '_it_' + str(i)
g3_graph_pkl = mcf_out_dir2 + '/' + os.path.splitext(os.path.split(g3_tomo_file)[1])[0] + '.pkl'
# Synthetic phantom generation
print('\tLoading the grid with STD=' + str(G3_STD_NOISE[j]) + ' and repetition ' + str(i) + '.')
grid = unpickle_obj(g3_grid_pkl)
hold_snr[i, j] = grid.get_snr()
# Noise loop for data analysis
for j in range(len(G3_STD_NOISE)):
# Repetitions loop
for i in range(G3_NUM_REP):
# Paths
g3_tomo_file = MCF_OUT_DIR + '/grid_noise_std_' + str(j) + '_it_' + str(i) + '.fits'
g3_mask_file = MCF_OUT_DIR + '/grid_mask_std_' + str(j) + '_it_' + str(i) + '_mask.fits'
g3_graph_vtp = MCF_OUT_DIR + '/grid_graph_skel_' + str(j) + '_it_' + str(i) + '.vtp'
g3_graph_sch = MCF_OUT_DIR + '/grid_graph_sch_' + str(j) + '_it_' + str(i) + '.vtp'
g3_grid_pkl = MCF_OUT_DIR + '/grid_' + str(j) + '_it_' + str(i) + '.pkl'
mcf_out_dir2 = MCF_OUT_DIR + '/graph_' + str(j) + '_it_' + str(i)
g3_graph_pkl = mcf_out_dir2 + '/' + os.path.splitext(os.path.split(g3_tomo_file)[1])[0] + '.pkl'
g3_dog_file = MCF_OUT_DIR + '/grid_noise_std_' + str(j) + '_it_' + str(i) + '_dog.mrc'
# print '\tComputing DoG metrics...'
# n_points_dog = grid.get_num_features() * G3_RES_PER
# g3_tomo_dog = dog_operator(lin_map(g3_tomo_file, lb=1, ub=0), DOG_SG1, DOG_K)
# disperse_io.save_numpy(g3_tomo_dog, g3_dog_file)
# g3_dog_peaks = find_region_peaks_by_num(g3_tomo_dog, n_points_dog)
# labels_dog, v_tps_dog = list(), list()
# gxs, gys, gzs = grid.get_grid_points()
# grid_vs = -1 * np.ones(shape=gxs.shape, dtype=np.int)
# good_picks_dog, bad_picks_dog, fp_picks_dog, tot_picks_dog = 0., 0., 0., float(np.asarray(gxs.shape).prod())
# for x in range(gxs.shape[0]):
# for y in range(gys.shape[1]):
# for z in range(gzs.shape[2]):
# hold_min = np.finfo(np.float).max
# g_point = np.asarray((gxs[x, y, z], gys[x, y, z], gzs[x, y, z]), dtype=np.float32)
# pick_found = False
# for point in g3_dog_peaks:
# dst = g_point - point
# dst = math.sqrt((dst*dst).sum())
# if hold_min > dst:
# if dst < G3_EPS:
# grid_vs[x, y, z] = int(v.get_id())
# pick_found = True
# hold_min = dst
# if pick_found:
# good_picks_dog += 1
# else:
# bad_picks_dog += 1
# # Computing the false positives
# for point in g3_dog_peaks:
# if not grid.in_feature(point, G3_EPS):
# fp_picks_dog += 1
print('\tUnpickling GraphMCF...')
graph_mcf = unpickle_obj(g3_graph_pkl)
# Getting the starting points for tracing
labels, v_tps = list(), list()
vertices = graph_mcf.get_vertices_list()
n_points = float(len(vertices))
# points = np.zeros(shape=(n_points, 3), dtype=np.float)
gxs, gys, gzs = grid.get_grid_points()
grid_vs = -1 * np.ones(shape=gxs.shape, dtype=np.int)
good_picks, bad_picks, fp_picks, tot_picks = 0., 0., 0., float(np.asarray(gxs.shape).prod())
for x in range(gxs.shape[0]):
for y in range(gys.shape[1]):
for z in range(gzs.shape[2]):
labels.append(str(x) + '_' + str(y) + '_' + str(z))
hold_min = np.finfo(np.float).max
g_point = np.asarray((gxs[x, y, z], gys[x, y, z], gzs[x, y, z]), dtype=np.float32)
pick_found = False
for v in vertices:
point = np.asarray(graph_mcf.get_vertex_coords(v), dtype=np.float32)
dst = g_point - point
dst = math.sqrt((dst*dst).sum())
if hold_min > dst:
if dst < G3_EPS:
grid_vs[x, y, z] = int(v.get_id())
pick_found = True
hold_min = dst
if pick_found:
v_tps.append(grid_vs[x, y, z])
good_picks += 1
else:
bad_picks += 1
# Computing the false positives
v_fps = list()
for v in vertices:
point = np.asarray(graph_mcf.get_vertex_coords(v), dtype=np.float32)
if not grid.in_feature(point, G3_EPS):
fp_picks += 1
v_fps.append(int(v.get_id()))
# Trace the path to closest neighbours
pairs = list()
graph_mcf.compute_graph_gt()
tot_path, good_path, bad_path = 0., 0., 0.
for x in range(gxs.shape[0]):
for y in range(gys.shape[1]):
for z in range(gzs.shape[2]):
# Get starting vertex and neighbours (target vertices)
v = grid_vs[x, y, z]
lbl = str(x) + '_' + str(y) + '_' + str(z)
if v != -1:
if x == 0:
nx0 = None
else:
nx0 = grid_vs[x-1, y, z]
if x == gxs.shape[0] - 1:
nx1 = None
else:
nx1 = grid_vs[x+1, y, z]
if y == 0:
ny0 = None
else:
ny0 = grid_vs[x, y-1, z]
if y == gys.shape[1] - 1:
ny1 = None
else:
ny1 = grid_vs[x, y+1, z]
if z == 0:
nz0 = None
else:
nz0 = grid_vs[x, y, z-1]
if z == gzs.shape[2] - 1:
nz1 = None
else:
nz1 = grid_vs[x, y, z+1]
# Check paths
neighbours = [nx0, nx1, ny0, ny1, nz0, nz1]
for t in v_tps:
if not ((str(v) + '_' + str(t)) in pairs):
pairs.append(str(v) + '_' + str(t))
pairs.append(str(t) + '_' + str(v))
if t in neighbours:
tot_path += 1
# Computing the arc path
v_path, e_path = graph_mcf.find_shortest_path(v, t, prop_key=SGT_EDGE_LENGTH)
found = False
if v_path is not None:
if len(v_path) > 2:
for p in v_path[1:-1]:
if p in neighbours:
found = True
break
else:
found = True
if not found:
good_path += 1
else:
v_path, e_path = graph_mcf.find_shortest_path(v, t, prop_key=SGT_EDGE_LENGTH)
found = True
if v_path is not None:
if len(v_path) >= 2:
for p in v_path[1:]:
hold_point = graph_mcf.get_vertex_coords(graph_mcf.get_vertex(p))
if not grid.in_grid(hold_point):
found = False
break
if (p in neighbours) or (p in v_tps):
break
# if found:
# for e in e_path:
# hold_point = graph_mcf.get_edge_coords(graph_mcf.get_edge(e))
# if not grid.in_grid(hold_point):
# found = False
# break
if not found:
bad_path += 1
if good_picks > tot_picks:
good_picks = tot_picks
if bad_picks > tot_picks:
bad_picks = tot_picks
if tot_picks <= 0:
hold_t_p[i, j] = 0
hold_f_n[i, j] = 0
else:
hold_t_p[i, j] = good_picks / tot_picks
hold_f_n[i, j] = bad_picks / tot_picks
if n_points <= 0:
hold_f_p[i, j] = 0
else:
hold_f_p[i, j] = fp_picks / n_points
if tot_path <= 0:
hold_p_e[i, j] = 0
hold_pp_e[i, j] = 0
hold_b_e[i, j] = 0
else:
# hold_p_e[i, j] = good_path / tot_path
hold_pp_e[i, j] = good_path / tot_path
hold_p_e[i, j] = good_path / grid.get_num_edges()
# if (bad_path_fp+good_path_fp) > 0:
if bad_path > 0:
# hold_b_e[i, j] = bad_path_fp / (bad_path_fp + good_path_fp)
hold_b_e[i, j] = bad_path / grid.get_num_edges()
else:
hold_b_e[i, j] = 0
# Printing the result
print('')
print('\tRESULTS: ')
print('\tSNR: [' + str(hold_snr[:, j].min()) + ', ' + str(hold_snr[:, j].mean()) + ', ' + str(hold_snr[:, j].max()) + ']')
print('\tTrue positive picked: [' + str(hold_t_p[:, j].min()) + ', ' + str(hold_t_p[:, j].mean()) + ', ' + str(hold_t_p[:, j].max()) + ']')
print('\tFalse positive picked: [' + str(hold_f_p[:, j].min()) + ', ' + str(hold_f_p[:, j].mean()) + ', ' + str(hold_f_p[:, j].max()) + ']')
print('\tFalse negative picked: [' + str(hold_f_n[:, j].min()) + ', ' + str(hold_f_n[:, j].mean()) + ', ' + str(hold_f_n[:, j].max()) + ']')
print('\tFraction of correctly tracked paths over corrected ground truth: [' + str(hold_pp_e[:, j].min()) + ', ' + str(hold_pp_e[:, j].mean()) + ', ' + str(hold_pp_e[:, j].max()) + ']')
print('\tFraction of correctly tracked paths: [' + str(hold_p_e[:, j].min()) + ', ' + str(hold_p_e[:, j].mean()) + ', ' + str(hold_p_e[:, j].max()) + ']')
print('\tFraction of bad tracked paths: [' + str(hold_b_e[:, j].min()) + ', ' + str(hold_b_e[:, j].mean()) + ', ' + str(hold_b_e[:, j].max()) + ']')
# Storing the results
np.savez(MCF_OUT_DIR + '/grid3d_arrays.npz', hold_snr, hold_t_p, hold_p_e, hold_f_p, hold_f_n, hold_b_e)
# Plotting the results
snr_mean = np.mean(hold_snr, axis=0)
fig = plt.figure()
ax = fig.add_subplot(111)
plt.errorbar(snr_mean, np.mean(hold_t_p, axis=0), yerr=np.std(hold_t_p, axis=0)/math.sqrt(G3_NUM_REP), color='blue', linestyle='-', linewidth=1.5, label='TP')
# plt.plot(snr_mean, np.mean(hold_t_p, axis=0), color='blue', linestyle='-', linewidth=2, label='TP')
# plt.fill_between(snr_mean, np.mean(hold_t_p, axis=0)-.5*np.std(hold_t_p, axis=0)/math.sqrt(G3_NUM_REP), np.mean(hold_t_p, axis=0)+.5*np.std(hold_t_p, axis=0)/math.sqrt(G3_NUM_REP), alpha=0.5, color='blue', edgecolor='w')
plt.errorbar(snr_mean, np.mean(hold_pp_e, axis=0), yerr=np.std(hold_pp_e, axis=0)/math.sqrt(G3_NUM_REP), color='red', linestyle='-.', linewidth=1.5, label='TP arcs corrected')
plt.errorbar(snr_mean, np.mean(hold_p_e, axis=0), yerr=np.std(hold_p_e, axis=0)/math.sqrt(G3_NUM_REP), color='red', linestyle='-', linewidth=1.5, label='TP arcs')
# plt.plot(snr_mean, np.mean(hold_p_e, axis=0), color='red', linestyle='-', linewidth=2, label='TP arcs')
# plt.fill_between(snr_mean, np.mean(hold_p_e, axis=0)-.5*np.std(hold_p_e, axis=0)/math.sqrt(G3_NUM_REP), np.mean(hold_p_e, axis=0)+.5*np.std(hold_p_e, axis=0)/math.sqrt(G3_NUM_REP), alpha=0.5, color='red', edgecolor='w')
plt.errorbar(snr_mean, np.mean(hold_f_p, axis=0), yerr=np.std(hold_f_p, axis=0)/math.sqrt(G3_NUM_REP), color='yellow', linestyle='-', linewidth=1.5, label='FP')
# plt.plot(snr_mean, np.mean(hold_f_p, axis=0), color='yellow', linestyle='-', linewidth=2, label='FP')
# plt.fill_between(snr_mean, np.mean(hold_f_p, axis=0)-.5*np.std(hold_f_p, axis=0)/math.sqrt(G3_NUM_REP), np.mean(hold_f_p, axis=0)+.5*np.std(hold_f_p, axis=0)/math.sqrt(G3_NUM_REP), alpha=0.5, color='yellow', edgecolor='w')
plt.errorbar(snr_mean, np.mean(hold_f_n, axis=0), yerr=np.std(hold_f_n, axis=0)/math.sqrt(G3_NUM_REP), color='cyan', linestyle='-', linewidth=1.5, label='FN')
# plt.plot(snr_mean, np.mean(hold_f_n, axis=0), color='cyan', linestyle='-', linewidth=2, label='FN')
# plt.fill_between(snr_mean, np.mean(hold_f_n, axis=0)-0.5*np.std(hold_f_n, axis=0)/math.sqrt(G3_NUM_REP), np.mean(hold_f_n, axis=0)+0.5*np.std(hold_f_n, axis=0)/math.sqrt(G3_NUM_REP), alpha=0.5, color='cyan', edgecolor='w')
plt.errorbar(snr_mean, np.mean(hold_b_e, axis=0), yerr=np.std(hold_b_e, axis=0)/math.sqrt(G3_NUM_REP), color='magenta', linestyle='-', linewidth=1.5, label='FP arcs')
# plt.plot(snr_mean, np.mean(hold_b_e, axis=0), color='magenta', linestyle='-', linewidth=2, label='FP arcs')
# plt.fill_between(snr_mean, np.mean(hold_b_e, axis=0)-0.5*np.std(hold_b_e, axis=0)/math.sqrt(G3_NUM_REP), np.mean(hold_b_e, axis=0)+0.5*np.std(hold_b_e, axis=0)/math.sqrt(G3_NUM_REP), alpha=0.5, color='magenta', edgecolor='w')
plt.plot(snr_mean, np.ones(shape=hold_p_e.shape[1]), color='black', linestyle='--', linewidth=1)
plt.plot(snr_mean, np.zeros(shape=hold_p_e.shape[1]), color='black', linestyle='--', linewidth=1)
plt.ylim((-0.1, 1.1))
plt.xlim((snr_mean[0], snr_mean[-1]))
ax.set_xscale('log')
plt.xlabel('SNR')
plt.legend(loc=7)
# ref_FR_ssup_mb.sh
plt.tight_layout()
out_fig = MCF_OUT_DIR + '/test_grid_conn.png'
print('Saving output figure in: ' + out_fig)
plt.savefig(out_fig, dpi=600)
plt.close()
print('Terminated successfully. (' + time.strftime("%c") + ')')
| en | 0.457819 | Tests for testing bio-material tracking by GraphMCF ### INPUT SETTINGS ############## # Short version is 'False' (default) takes few minutes but is enough for testing # functionality, long version 'True' produces stronger statistics but takes a few # hours and require high memory resources ################################# # mcf_graph configuration #### Grid 3D test variables # np.linspace(0.03, 1.0, 15)[::-1]# (1.3, 1., 0.6, 0.3, 0.1, 0.01) # (0.3, 0.1) # (3, 3, 2) # 4 # 0.5 # For picking # True # For DoG ################################################################################################# # Parallel process for computing the graph ################################################################################################# # To avoid repeated simulations # g3_graph_pkl = MCF_OUT_DIR + '/grid_graph_std_' + str(G3_STD_NOISE[j]) + '_it_' + str(i) + '.pkl' # , '-v'] # Load GraphMCF # Make topological simplification until fitting the number of features times residues percentage # Filter edges until fitting the number of edges # n_edges = float(len(graph_mcf.get_vertices_list())) * ev_ratio # i_edges = len(graph_mcf.get_edges_list()) # if n_edges < i_edges: # else: # print 'WARNING [process:' + str(pr_id) + ']: Graph cannot be simplify to ' + str(n_edges) + \ # ' edges, since it has only ' + str(i_edges) ################################################################################################# # Main Routine ################################################################################################# # Noise loop for computing the graphs # MULTIPROCESSING # for pr_id in range(len(processes)): # if pr_id != pr_results[pr_id]: # error_msg = 'Process ' + str(pr_id) + ' exited unexpectedly!' # sys.exit(-1) # Repetitions loop # Paths # Synthetic phantom generation # Noise loop for data analysis # Repetitions loop # Paths # print '\tComputing DoG metrics...' # n_points_dog = grid.get_num_features() * G3_RES_PER # g3_tomo_dog = dog_operator(lin_map(g3_tomo_file, lb=1, ub=0), DOG_SG1, DOG_K) # disperse_io.save_numpy(g3_tomo_dog, g3_dog_file) # g3_dog_peaks = find_region_peaks_by_num(g3_tomo_dog, n_points_dog) # labels_dog, v_tps_dog = list(), list() # gxs, gys, gzs = grid.get_grid_points() # grid_vs = -1 * np.ones(shape=gxs.shape, dtype=np.int) # good_picks_dog, bad_picks_dog, fp_picks_dog, tot_picks_dog = 0., 0., 0., float(np.asarray(gxs.shape).prod()) # for x in range(gxs.shape[0]): # for y in range(gys.shape[1]): # for z in range(gzs.shape[2]): # hold_min = np.finfo(np.float).max # g_point = np.asarray((gxs[x, y, z], gys[x, y, z], gzs[x, y, z]), dtype=np.float32) # pick_found = False # for point in g3_dog_peaks: # dst = g_point - point # dst = math.sqrt((dst*dst).sum()) # if hold_min > dst: # if dst < G3_EPS: # grid_vs[x, y, z] = int(v.get_id()) # pick_found = True # hold_min = dst # if pick_found: # good_picks_dog += 1 # else: # bad_picks_dog += 1 # # Computing the false positives # for point in g3_dog_peaks: # if not grid.in_feature(point, G3_EPS): # fp_picks_dog += 1 # Getting the starting points for tracing # points = np.zeros(shape=(n_points, 3), dtype=np.float) # Computing the false positives # Trace the path to closest neighbours # Get starting vertex and neighbours (target vertices) # Check paths # Computing the arc path # if found: # for e in e_path: # hold_point = graph_mcf.get_edge_coords(graph_mcf.get_edge(e)) # if not grid.in_grid(hold_point): # found = False # break # hold_p_e[i, j] = good_path / tot_path # if (bad_path_fp+good_path_fp) > 0: # hold_b_e[i, j] = bad_path_fp / (bad_path_fp + good_path_fp) # Printing the result # Storing the results # Plotting the results # plt.plot(snr_mean, np.mean(hold_t_p, axis=0), color='blue', linestyle='-', linewidth=2, label='TP') # plt.fill_between(snr_mean, np.mean(hold_t_p, axis=0)-.5*np.std(hold_t_p, axis=0)/math.sqrt(G3_NUM_REP), np.mean(hold_t_p, axis=0)+.5*np.std(hold_t_p, axis=0)/math.sqrt(G3_NUM_REP), alpha=0.5, color='blue', edgecolor='w') # plt.plot(snr_mean, np.mean(hold_p_e, axis=0), color='red', linestyle='-', linewidth=2, label='TP arcs') # plt.fill_between(snr_mean, np.mean(hold_p_e, axis=0)-.5*np.std(hold_p_e, axis=0)/math.sqrt(G3_NUM_REP), np.mean(hold_p_e, axis=0)+.5*np.std(hold_p_e, axis=0)/math.sqrt(G3_NUM_REP), alpha=0.5, color='red', edgecolor='w') # plt.plot(snr_mean, np.mean(hold_f_p, axis=0), color='yellow', linestyle='-', linewidth=2, label='FP') # plt.fill_between(snr_mean, np.mean(hold_f_p, axis=0)-.5*np.std(hold_f_p, axis=0)/math.sqrt(G3_NUM_REP), np.mean(hold_f_p, axis=0)+.5*np.std(hold_f_p, axis=0)/math.sqrt(G3_NUM_REP), alpha=0.5, color='yellow', edgecolor='w') # plt.plot(snr_mean, np.mean(hold_f_n, axis=0), color='cyan', linestyle='-', linewidth=2, label='FN') # plt.fill_between(snr_mean, np.mean(hold_f_n, axis=0)-0.5*np.std(hold_f_n, axis=0)/math.sqrt(G3_NUM_REP), np.mean(hold_f_n, axis=0)+0.5*np.std(hold_f_n, axis=0)/math.sqrt(G3_NUM_REP), alpha=0.5, color='cyan', edgecolor='w') # plt.plot(snr_mean, np.mean(hold_b_e, axis=0), color='magenta', linestyle='-', linewidth=2, label='FP arcs') # plt.fill_between(snr_mean, np.mean(hold_b_e, axis=0)-0.5*np.std(hold_b_e, axis=0)/math.sqrt(G3_NUM_REP), np.mean(hold_b_e, axis=0)+0.5*np.std(hold_b_e, axis=0)/math.sqrt(G3_NUM_REP), alpha=0.5, color='magenta', edgecolor='w') # ref_FR_ssup_mb.sh | 1.711053 | 2 |
code_search/utils.py | novoselrok/codesnippetsearch | 70 | 6620346 | import os
import itertools
from typing import Iterable, Dict, List
from multiprocessing import Pool
from code_search import shared
def add_bool_arg(parser, name, default=False):
group = parser.add_mutually_exclusive_group(required=False)
group.add_argument('--' + name, dest=name, action='store_true')
group.add_argument('--no-' + name, dest=name, action='store_false')
parser.set_defaults(**{name: default})
def flatten(iterable: Iterable[Iterable]) -> Iterable:
return itertools.chain.from_iterable(iterable)
def len_generator(generator):
return sum(1 for _ in generator)
def get_values_sorted_by_key(dict_: Dict[int, str]) -> List[str]:
return [value for _, value in sorted(dict_.items())]
def _multiprocess_map_method(args):
obj, method_name, arg = args
method = getattr(obj, method_name)
method(*arg)
def map_method(obj, method_name: str, args: Iterable, num_processes=4):
if num_processes > 1:
with Pool(num_processes) as p:
p.map(_multiprocess_map_method, ((obj, method_name, arg) for arg in args))
else:
list(map(lambda arg: getattr(obj, method_name)(*arg), args))
def get_repository_directory(organization: str, name: str):
return os.path.join(shared.REPOSITORIES_DIR, organization, name)
| import os
import itertools
from typing import Iterable, Dict, List
from multiprocessing import Pool
from code_search import shared
def add_bool_arg(parser, name, default=False):
group = parser.add_mutually_exclusive_group(required=False)
group.add_argument('--' + name, dest=name, action='store_true')
group.add_argument('--no-' + name, dest=name, action='store_false')
parser.set_defaults(**{name: default})
def flatten(iterable: Iterable[Iterable]) -> Iterable:
return itertools.chain.from_iterable(iterable)
def len_generator(generator):
return sum(1 for _ in generator)
def get_values_sorted_by_key(dict_: Dict[int, str]) -> List[str]:
return [value for _, value in sorted(dict_.items())]
def _multiprocess_map_method(args):
obj, method_name, arg = args
method = getattr(obj, method_name)
method(*arg)
def map_method(obj, method_name: str, args: Iterable, num_processes=4):
if num_processes > 1:
with Pool(num_processes) as p:
p.map(_multiprocess_map_method, ((obj, method_name, arg) for arg in args))
else:
list(map(lambda arg: getattr(obj, method_name)(*arg), args))
def get_repository_directory(organization: str, name: str):
return os.path.join(shared.REPOSITORIES_DIR, organization, name)
| none | 1 | 2.634106 | 3 | |
screw-api/screw_handler.py | CM-Kajiwara/screw-demo-app | 0 | 6620347 | import json
import logging
import os
from sagemaker.predictor import RealTimePredictor
from sagemaker.predictor import json_deserializer
from screw_predictor import ScrewPredictor
import base64
# endpoint = 'object-detection-2018-08-14-01-19-44-959'
endpoint = os.getenv('OBJECT_DETECTION_ENDPOINT','object-detection-2018-08-14-01-19-44-959')
object_predictor = ScrewPredictor(endpoint,content_type='image/jpeg',deserializer=json_deserializer)
threshold = 0.4
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def list_screw_detections_handler(event, context):
logger.info(json.dumps(event))
result = object_predictor.predict(base64.b64decode(event['body']),thresh=threshold)
logger.info(json.dumps(result))
response = {
"statusCode": 200,
"headers": {
"Access-Control-Allow-Origin": "*"
},
"body": json.dumps(result)
}
logger.info(response)
return response | import json
import logging
import os
from sagemaker.predictor import RealTimePredictor
from sagemaker.predictor import json_deserializer
from screw_predictor import ScrewPredictor
import base64
# endpoint = 'object-detection-2018-08-14-01-19-44-959'
endpoint = os.getenv('OBJECT_DETECTION_ENDPOINT','object-detection-2018-08-14-01-19-44-959')
object_predictor = ScrewPredictor(endpoint,content_type='image/jpeg',deserializer=json_deserializer)
threshold = 0.4
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def list_screw_detections_handler(event, context):
logger.info(json.dumps(event))
result = object_predictor.predict(base64.b64decode(event['body']),thresh=threshold)
logger.info(json.dumps(result))
response = {
"statusCode": 200,
"headers": {
"Access-Control-Allow-Origin": "*"
},
"body": json.dumps(result)
}
logger.info(response)
return response | en | 0.27058 | # endpoint = 'object-detection-2018-08-14-01-19-44-959' | 1.887908 | 2 |
Bones/MyRegistrationLib/mypqWidget.py | aledelmo/3DSlicer_Plugins | 0 | 6620348 | <reponame>aledelmo/3DSlicer_Plugins
class myypqWidget(object):
"""
A "QWidget"-like widget class that manages provides some
helper functionality (signals, slots...)
"""
def __init__(self):
self.connections = {} # list of slots per signal
def connect(self, signal, slot):
"""pseudo-connect - signal is arbitrary string and slot if callable"""
if not self.connections.has_key(signal):
self.connections[signal] = []
self.connections[signal].append(slot)
def disconnect(self, signal, slot):
"""pseudo-disconnect - remove the connection if it exists"""
if self.connections.has_key(signal):
if slot in self.connections[signal]:
self.connections[signal].remove(slot)
def emit(self, signal, args):
"""pseudo-emit - calls any slots connected to signal"""
if self.connections.has_key(signal):
for slot in self.connections[signal]:
slot(*args)
| class myypqWidget(object):
"""
A "QWidget"-like widget class that manages provides some
helper functionality (signals, slots...)
"""
def __init__(self):
self.connections = {} # list of slots per signal
def connect(self, signal, slot):
"""pseudo-connect - signal is arbitrary string and slot if callable"""
if not self.connections.has_key(signal):
self.connections[signal] = []
self.connections[signal].append(slot)
def disconnect(self, signal, slot):
"""pseudo-disconnect - remove the connection if it exists"""
if self.connections.has_key(signal):
if slot in self.connections[signal]:
self.connections[signal].remove(slot)
def emit(self, signal, args):
"""pseudo-emit - calls any slots connected to signal"""
if self.connections.has_key(signal):
for slot in self.connections[signal]:
slot(*args) | en | 0.740468 | A "QWidget"-like widget class that manages provides some helper functionality (signals, slots...) # list of slots per signal pseudo-connect - signal is arbitrary string and slot if callable pseudo-disconnect - remove the connection if it exists pseudo-emit - calls any slots connected to signal | 3.309823 | 3 |
src/harrastuspassi/harrastuspassi/migrations/0010_category_name_not_unique.py | savilmik/harrastuspassi-backend | 2 | 6620349 | <filename>src/harrastuspassi/harrastuspassi/migrations/0010_category_name_not_unique.py<gh_stars>1-10
# Generated by Django 2.2.4 on 2019-10-14 09:42
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('harrastuspassi', '0009_hobbycategory_data_source'),
]
operations = [
migrations.AlterField(
model_name='hobbycategory',
name='name',
field=models.CharField(max_length=256),
),
]
| <filename>src/harrastuspassi/harrastuspassi/migrations/0010_category_name_not_unique.py<gh_stars>1-10
# Generated by Django 2.2.4 on 2019-10-14 09:42
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('harrastuspassi', '0009_hobbycategory_data_source'),
]
operations = [
migrations.AlterField(
model_name='hobbycategory',
name='name',
field=models.CharField(max_length=256),
),
]
| en | 0.767181 | # Generated by Django 2.2.4 on 2019-10-14 09:42 | 1.479341 | 1 |
data_builder.py | C5Team3/data-science | 0 | 6620350 | # This script build two playlists type
# 1. A new playlist based on the user's playing history
# 2. A new playlist based on the all user's playing history
from datetime import datetime
from playlist_builder import get_playlist
from recommendation_finder import get_recommendation
from seeds_generator import get_seeds_to_recommendation
def create_playlist_user(uid):
"""Build a playlist for a user"""
playlist = {}
playlist['type'] = 'user-playlist'
playlist['title'] = None
playlist['user_id'] = uid
playlist['date'] = datetime.now()
seeds = get_seeds_to_recommendation(uid)
recommendation = get_recommendation(seeds)
tracks_playlist = get_playlist(recommendation)
playlist['tracks'] = tracks_playlist
# Update Title-Playlist
artist = tracks_playlist[0]['artist_name']
track = tracks_playlist[0]['track_title']
playlist['title'] = "Playlist: {} - {}".format(artist, track)
return playlist
def create_playlist_general():
"""Build a playlist to all users"""
playlist = {}
playlist['type'] = 'general-playlist'
playlist['title'] = None
playlist['date'] = datetime.now()
seeds = get_seeds_to_recommendation()
recommendation = get_recommendation(seeds)
tracks_playlist = get_playlist(recommendation)
playlist['tracks'] = tracks_playlist
# Update Title-Playlist
artist = tracks_playlist[0]['artist_name']
track = tracks_playlist[0]['track_title']
playlist['title'] = "Playlist: {} - {}".format(artist, track)
return playlist
| # This script build two playlists type
# 1. A new playlist based on the user's playing history
# 2. A new playlist based on the all user's playing history
from datetime import datetime
from playlist_builder import get_playlist
from recommendation_finder import get_recommendation
from seeds_generator import get_seeds_to_recommendation
def create_playlist_user(uid):
"""Build a playlist for a user"""
playlist = {}
playlist['type'] = 'user-playlist'
playlist['title'] = None
playlist['user_id'] = uid
playlist['date'] = datetime.now()
seeds = get_seeds_to_recommendation(uid)
recommendation = get_recommendation(seeds)
tracks_playlist = get_playlist(recommendation)
playlist['tracks'] = tracks_playlist
# Update Title-Playlist
artist = tracks_playlist[0]['artist_name']
track = tracks_playlist[0]['track_title']
playlist['title'] = "Playlist: {} - {}".format(artist, track)
return playlist
def create_playlist_general():
"""Build a playlist to all users"""
playlist = {}
playlist['type'] = 'general-playlist'
playlist['title'] = None
playlist['date'] = datetime.now()
seeds = get_seeds_to_recommendation()
recommendation = get_recommendation(seeds)
tracks_playlist = get_playlist(recommendation)
playlist['tracks'] = tracks_playlist
# Update Title-Playlist
artist = tracks_playlist[0]['artist_name']
track = tracks_playlist[0]['track_title']
playlist['title'] = "Playlist: {} - {}".format(artist, track)
return playlist
| en | 0.91205 | # This script build two playlists type # 1. A new playlist based on the user's playing history # 2. A new playlist based on the all user's playing history Build a playlist for a user # Update Title-Playlist Build a playlist to all users # Update Title-Playlist | 3.199139 | 3 |