text stringlengths 0 1.05M | meta dict |
|---|---|
from fractions import Fraction
print(Fraction(1, 3))
# 1/3
print(Fraction(2, 6))
# 1/3
print(Fraction(3))
# 3
print(Fraction(0.25))
# 1/4
print(Fraction(0.33))
# 5944751508129055/18014398509481984
print(Fraction('2/5'))
# 2/5
print(Fraction('16/48'))
# 1/3
a = Fraction(1, 3)
print(a)
# 1/3
print(a.numerator)
print(type(a.numerator))
# 1
# <class 'int'>
print(a.denominator)
print(type(a.denominator))
# 3
# <class 'int'>
# a.numerator = 7
# AttributeError: can't set attribute
result = Fraction(1, 6) ** 2 + Fraction(1, 3) / Fraction(1, 2)
print(result)
print(type(result))
# 25/36
# <class 'fractions.Fraction'>
print(Fraction(7, 13) > Fraction(8, 15))
# True
a_f = float(a)
print(a_f)
print(type(a_f))
# 0.3333333333333333
# <class 'float'>
b = a + 0.1
print(b)
print(type(b))
# 0.43333333333333335
# <class 'float'>
a_s = str(a)
print(a_s)
print(type(a_s))
# 1/3
# <class 'str'>
pi = Fraction(3.14159265359)
print(pi)
# 3537118876014453/1125899906842624
print(pi.limit_denominator(10))
print(pi.limit_denominator(100))
print(pi.limit_denominator(1000))
# 22/7
# 311/99
# 355/113
e = Fraction(2.71828182846)
print(e)
# 6121026514870223/2251799813685248
print(e.limit_denominator(10))
print(e.limit_denominator(100))
print(e.limit_denominator(1000))
# 19/7
# 193/71
# 1457/536
a = Fraction(0.565656565656)
print(a)
# 636872674577009/1125899906842624
print(a.limit_denominator())
# 56/99
a = Fraction(0.3333)
print(a)
# 6004199023210345/18014398509481984
print(a.limit_denominator())
print(a.limit_denominator(100))
# 3333/10000
# 1/3
| {
"repo_name": "nkmk/python-snippets",
"path": "notebook/fractions_test.py",
"copies": "1",
"size": "1561",
"license": "mit",
"hash": 4026253584713573400,
"line_mean": 14.0096153846,
"line_max": 62,
"alpha_frac": 0.6931454196,
"autogenerated": false,
"ratio": 2.2821637426900585,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.3475309162290059,
"avg_score": null,
"num_lines": null
} |
from fractions import Fraction
# Waits for user to type something then stores it as a
# Stores input as a string
a = input()
print a
# Converts a to an int or a float respectively.
# int(a) won't accept an a that is a float i.e 2.0 or a fractional number (3/4)
print int(a) + 1
print float(a) + 1
# Executes the try block unless there is a Value Error then it goes to the except block
try:
a = float(input('Enter a number: '))
print a
except ValueError:
print('You entered an invalid number')
# Converts the input to int immediately
a = int(input())
print a
print a + 1
# .is_interger() returns true for floating point numbers if the number ends with .0
print 1.1.is_integer()
print 1.0.is_integer()
# Asks for a fraction then converts it to a Fraction object
a = Fraction(input('Enter a fraction: '))
# Will return invalid fraction for x/0 fractions
try:
a = Fraction(input('Enter a fraction: '))
except ZeroDivisionError:
print ('Invalid fraction')
# Will convert a string like 2+3j into a complex number
try:
z = complex(input('Enter a complex number: '))
except ValueError:
print('Invalid complex number!') | {
"repo_name": "NTomtishen/src",
"path": "GettingUserInput.py",
"copies": "1",
"size": "1124",
"license": "cc0-1.0",
"hash": 3918735568987901400,
"line_mean": 26.4390243902,
"line_max": 87,
"alpha_frac": 0.7268683274,
"autogenerated": false,
"ratio": 3.437308868501529,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4664177195901529,
"avg_score": null,
"num_lines": null
} |
from fractions import Fraction, _RATIONAL_FORMAT
from decimal import Decimal
import numbers
Rational = numbers.Rational
class AAFFraction(Fraction):
"""
Subclass of fractions.Fraction from the standard library. Behaves exactly the same, except
doesn't round to the Greatest Common Divisor at the end.
"""
def __new__(cls, numerator=0, denominator=None):
self = super(AAFFraction, cls).__new__(cls)
if denominator is None:
if isinstance(numerator, Rational):
self._numerator = numerator.numerator
self._denominator = numerator.denominator
return self
elif isinstance(numerator, float):
# Exact conversion from float
value = Fraction.from_float(numerator)
self._numerator = value._numerator
self._denominator = value._denominator
return self
elif isinstance(numerator, Decimal):
value = Fraction.from_decimal(numerator)
self._numerator = value._numerator
self._denominator = value._denominator
return self
elif isinstance(numerator, str):
# Handle construction from strings.
m = _RATIONAL_FORMAT.match(numerator)
if m is None:
raise ValueError('Invalid literal for Fraction: %r' %
numerator)
numerator = int(m.group('num') or '0')
denom = m.group('denom')
if denom:
denominator = int(denom)
else:
denominator = 1
decimal = m.group('decimal')
if decimal:
scale = 10**len(decimal)
numerator = numerator * scale + int(decimal)
denominator *= scale
exp = m.group('exp')
if exp:
exp = int(exp)
if exp >= 0:
numerator *= 10**exp
else:
denominator *= 10**-exp
if m.group('sign') == '-':
numerator = -numerator
else:
raise TypeError("argument should be a string "
"or a Rational instance")
elif (isinstance(numerator, Rational) and
isinstance(denominator, Rational)):
numerator, denominator = (
numerator.numerator * denominator.denominator,
denominator.numerator * numerator.denominator
)
else:
raise TypeError("both arguments should be "
"Rational instances")
if denominator == 0:
raise ZeroDivisionError('Fraction(%s, 0)' % numerator)
# don't find the gcd
#g = gcd(numerator, denominator)
self._numerator = numerator
self._denominator = denominator
return self | {
"repo_name": "wjt/pyaaf",
"path": "aaf/fraction_util.py",
"copies": "1",
"size": "3126",
"license": "mit",
"hash": -5543872765249963000,
"line_mean": 36.2261904762,
"line_max": 94,
"alpha_frac": 0.4993602047,
"autogenerated": false,
"ratio": 5.810408921933085,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.6809769126633086,
"avg_score": null,
"num_lines": null
} |
from fractions import Fraction
from timeit import timeit
def intPow(x, y):
if x == y == 0:
raise ValueError("Can't raise 0 to 0")
if x == 0 and y < 0:
raise ValueError("Can't raise 0 to negative power")
if x == 0:
return 0
negative = y < 0
y = abs(y)
dynamic = {0: 1, 1: x, 2: x*x, 3: x*x*x}
if y in dynamic:
return dynamic[y]
def rec(xr, yr):
a = yr / 2
if yr % 2 == 0:
b = a
else:
b = a + 1
if a in dynamic:
a = dynamic[a]
else:
a = rec(xr, a)
if b in dynamic:
b = dynamic[b]
else:
b = rec(xr, b)
dynamic[yr] = a * b
return dynamic[yr]
res = rec(x, y)
if negative:
return 1./res
return res
def floatPow(x, y, digits):
f = Fraction(y).limit_denominator()
A = float(intPow(x, f.numerator))
n = f.denominator
eps = 0.1 ** digits
x = 1
while True:
deltaX = ((A / intPow(x, n-1)) - x) / n
x += deltaX
if abs(deltaX) < eps:
break
return x
x, y, digits = 2, 3.14, 10
def customPow():
return intPow(x, int(y)) * floatPow(x, y - int(y), digits)
tries = 100
print "Builtin: {0:.20f}s\nMine: {0:.20f}s".format(timeit("{}**{}".format(x, y), number=tries) / tries,
timeit(customPow, number=tries) / tries)
| {
"repo_name": "BranislavBajuzik/muni",
"path": "IV122/02/C.py",
"copies": "1",
"size": "1530",
"license": "unlicense",
"hash": -7238659482744023000,
"line_mean": 20.8358208955,
"line_max": 106,
"alpha_frac": 0.4490196078,
"autogenerated": false,
"ratio": 3.311688311688312,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.42607079194883113,
"avg_score": null,
"num_lines": null
} |
from fractions import Fraction
def answer(pegs):
# your code here
# This code is based off even and odd case formulas
# if n is even,
# r0 = -2(p0 - 2(p1 + ... - pn-1) + pn)
#
# if n is odd,
# r0 = -2/3(p0 - 2(p1 + ... - pn-1) + pn)
length = len(pegs)
# If invalid parameter
if ((not pegs) or length == 1):
return [-1, 1]
# If the length is odd or even
if length % 2 == 0:
even = True
else:
even = False
# Set result equal to first peg
result = pegs[0]
if even: result -= pegs[length - 1]
else: result += pegs[length - 1]
# Done if length = 2
if length > 2:
# Add the rest of the pegs
for i in range(1, length - 1):
# Alternate signs
result += (-1)**i * 2 * pegs[i]
# Python2 doesn't support true division!
result *= -2
if even: result = float(result)/3
# Convert to fraction and limit denominator
frac = Fraction(result).limit_denominator()
# Check if impossible
curr_radius = frac
for i in range(0, length - 2):
dist = pegs[i+1] - pegs[i]
next_radius = dist - curr_radius
if (curr_radius < 1 or next_radius < 1):
return [-1, -1]
else:
curr_radius = next_radius
return([frac.numerator, frac.denominator]) | {
"repo_name": "kyle8998/Practice-Coding-Questions",
"path": "Google_Foobar/Gearing_Up_For_Destruction/answer.py",
"copies": "1",
"size": "1459",
"license": "unlicense",
"hash": -8134319196513770000,
"line_mean": 25.0555555556,
"line_max": 55,
"alpha_frac": 0.4982864976,
"autogenerated": false,
"ratio": 3.6843434343434343,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.46826299319434345,
"avg_score": null,
"num_lines": null
} |
from fractions import Fraction
# reduces a variable out of a system of equations
def reduce(pos, eqtn1, eqtn2):
(poly1, val1) = eqtn1
(poly2, val2) = eqtn2
scale = poly1[pos]/poly2[pos]
polynomial = []
value = val1 - val2*scale
for i in range(len(poly1)):
c = poly1[i] - scale*poly2[i]
polynomial.append(c)
return (polynomial, value)
# produces all possible reductions on a group
def simplify(pos, group):
equations = []
for i in range(1, len(group)):
(eqtn1, eqtn2) = group[i-1:i+1]
eqtn = reduce(pos, eqtn1, eqtn2)
equations.append(eqtn)
return equations
# inserts a known value into an equation
def solve(pos, value, group):
for i in range(len(group)):
eqtn = group[i]
(poly, val) = eqtn
val -= poly[pos]*value
poly[pos] = 0;
eqtn = (poly, val)
group[i] = eqtn
points = []
print("Use the form (x1, y1), (x2, y2), ...")
string = input("Enter the points of the function: ")
split = string.split("), (")
split[0] = split[0][1:]
split[-1] = split[-1][:-1]
for i in split:
(xstr, ystr) = i.split(", ")
x = int(xstr)
y = int(ystr)
points.append((x, y))
# generate each of the initial equations
equations = []
for point in points:
(x, y) = point
polynomial = []
for i in range(len(points)):
polynomial.append(Fraction(x**(i)))
eqtn = (polynomial, y)
equations.append(eqtn)
# find all of the intermittent equations
groups = [equations]
i = 0
while (len(groups[-1]) > 1):
group = simplify(i, groups[-1])
i += 1
groups.append(group)
group = []
for i in groups:
group.append(i[0])
group = group[::-1]
# find the values of the coefficients
solution = [0] * len(points)
pos = len(points) - 1
for i in range(len(group)):
(poly, val) = group[i]
val /= poly[pos]
poly[pos] = 1
solution[pos] = val
group[i] = (poly, val)
solve(pos, val, group)
pos -= 1
# print out the solution
print("f(x) = ", end = ' ')
start = False # used for formating
for i in range(len(solution)):
coeff = solution[i]
exp = i
if coeff == 0 and exp != 0:
continue
if start:
print(" + ", end = '')
if i == 0:
print(coeff, end = '')
start = True
elif i == 1:
print(coeff, "x", sep = '', end = '')
start = True
else:
print(coeff, "x^", i, sep = '', end = '')
start = True
| {
"repo_name": "jonathancary1/equation-solver",
"path": "solver.py",
"copies": "1",
"size": "2596",
"license": "mit",
"hash": 5427974850741751000,
"line_mean": 20.9734513274,
"line_max": 52,
"alpha_frac": 0.5331278891,
"autogenerated": false,
"ratio": 3.17359413202934,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.420672202112934,
"avg_score": null,
"num_lines": null
} |
from fractions import gcd
from collections import defaultdict
import math
from itertools import count
import numpy as np
from prime_numbers import coprime, all_prime_divisors, primesfrom2to
from utils import infinite_product, PHI, is_int, fast_2matrix_expon_mod_m
def pythagorean_triples():
"""
returns (a,b,c) s.t. a**2 + b**2 == c**2
"""
def _gen_k():
for k in count(start=1):
yield k
def _gen_m_n():
for m in count(start=1):
if m % 2 == 0:
gen_n = xrange(1, m, 2)
else:
gen_n = xrange(1, m)
for n in gen_n:
if (m - n) % 2 == 1 and coprime(m, n):
yield (m, n)
for (k, (m, n)) in infinite_product(_gen_k(), _gen_m_n()):
a = k*(m**2 - n**2)
b = 2*k*m*n
c = k*(m**2 + n**2)
assert a**2 + b**2 == c**2 # yess so glad I wrote this assert - self documenting
yield a, b, c
def primitive_pythagorean_triples():
def _gen_m_n():
for m in count(start=1):
if m % 2 == 0:
gen_n = xrange(1, m, 2)
else:
gen_n = xrange(1, m)
for n in gen_n:
if (m - n) % 2 == 1 and coprime(m, n):
yield (m, n)
for (m, n) in _gen_m_n():
a = (m**2 - n**2)
b = 2*m*n
c = (m**2 + n**2)
assert a**2 + b**2 == c**2
yield a, b, c
def totient_function(n, prime_cache=None):
if n % 2 == 0:
return 2 * totient_function(n / 2) if (n / 2) % 2 == 0 else totient_function(n / 2)
numerator = 1
denominator = 1
for p in all_prime_divisors(n, prime_cache):
numerator *= p - 1
denominator *= p
return n * numerator / denominator
class TotientDict(dict):
def __init__(self, max_value, *args):
dict.__init__(self, args)
self.max_value = max_value
def __getitem__(self, key):
if key > self.max_value:
raise KeyError
mod4 = key % 4
if key == 1:
val = 1
elif mod4 == 2:
val = self[key/2]
elif mod4 == 0:
val = 2 * self[key/2]
else:
val = dict.__getitem__(self, key)
return val
def totient_lookup(up_to):
PRIMES = primesfrom2to(up_to)
totients = TotientDict(up_to)
totients[1] = 1
for p in PRIMES:
if p == 2:
continue # TotientDict handles this
for pn in xrange(p, up_to, 2*p):
totients[pn] = totients.get(pn, pn)/p * (p - 1)
return totients
def lcm(*args):
def _lcm(a, b):
return a * b // gcd(a, b)
return reduce(_lcm, args)
def mobius_lookup(up_to):
sqrt_up_to = int(math.sqrt(up_to))
mu = defaultdict(lambda: 1)
mu[1] = 1
for i in xrange(2, sqrt_up_to+1):
if mu[i] == 1:
for j in xrange(i, up_to, i):
mu[j] *= -i
for j in xrange(i**2, up_to, i**2):
mu[j] = 0
for i in xrange(2, up_to):
if mu[i] == i:
mu[i] = 1
elif mu[i] == -i:
mu[i] = -1
elif mu[i] < 0:
mu[i] = 1
elif mu[i] > 0:
mu[i] = -1
return mu
def xgcd(a, b):
"""Extended GCD:
Returns (gcd, x, y) where gcd is the greatest common divisor of a and b
with the sign of b if b is nonzero, and with the sign of a if b is 0.
The numbers x,y are such that gcd = ax+by."""
prevx, x = 1, 0
prevy, y = 0, 1
while b:
q, r = divmod(a, b)
x, prevx = prevx - q*x, x
y, prevy = prevy - q*y, y
a, b = b, r
gcd_ = a
return gcd_, prevx, prevy
def modular_multiplicate_inverse(n, p):
# solves n*x = 1 mod(p)
# ex: 3*x = 1 mod 5 return x = 2
assert gcd(n, p) == 1, 'inputs must be coprime or no solution exists.'
sol = xgcd(n, p)[1]
if sol < 0:
return p + sol
else:
return sol
def chinese_remainder_solver(input):
"""
Finds the unique solution to
x = a1 mod(m1)
x = a2 mod(m2)
...
x = an mod(mn)
where m1,m2,.. are pairwise coprime
input is a list of the form [(a1, m1), (a2, m2), ...]
returns x, lcm(m1,m2,...)
"""
def binary_chinese_remainder_solver((a1, m1), (a2, m2)):
(_gcd, n1, n2) = xgcd(m1, m2)
assert _gcd == 1, "m1 and m2 should be coprime (gcd == 1)"
return (a1*n2*m2 + a2*m1*n1, m1*m2)
sol, lcm = reduce(binary_chinese_remainder_solver, input)
return sol % lcm, lcm
def linear_congruence_solver(a, b, m):
"""
solves ax = b mod m
"""
def solutions(sol_mod_m, m):
while True:
yield sol_mod_m
sol_mod_m += m
g = gcd(a, m)
if g == 1:
inverse_a = modular_multiplicate_inverse(a, m)
return solutions(b * inverse_a % m, m)
elif b % g == 0:
return linear_congruence_solver(a/g, b/g, m/g)
else:
return iter([])
class Fibonacci():
def __init__(self):
self._cache = {}
self._n = 0
self._fib_generator = self.fib_generator()
def fib(self, k):
if k in self._cache:
return self._cache[k]
for fib in self._fib_generator:
self._n += 1
self._cache[self._n] = fib
if self._n == k:
break
return fib
@staticmethod
def fib_generator():
yield 1
yield 1
fib_1 = fib_2 = 1
while True:
fib = fib_1 + fib_2
yield fib
fib_2 = fib_1
fib_1 = fib
@staticmethod
def fib_pair_generator():
yield (1, 1)
fib_1 = fib_2 = 1
while True:
fib = fib_1 + fib_2
yield (fib_1, fib)
fib_2 = fib_1
fib_1 = fib
def index(self, n):
v = np.log(n * np.sqrt(5) + 0.5)/np.log(PHI)
# for large values the above becomes unstable
if abs(v - np.round(v)) < 1e-8:
return int(np.round(v))
else:
return int(np.floor(v))
def find_largest_fib_below_n(self, n):
return self.fib(self.index(n))
def zeckendorf(self, n):
if n == 0:
return []
else:
largest_fib_below_n = self.find_largest_fib_below_n(n)
return [largest_fib_below_n] + self.zeckendorf(n - largest_fib_below_n)
def zeckendorf_digit(self, n):
base = ['0'] * (self.index(n) - 1)
zeckendorf_fibs = self.zeckendorf(n)
for fib in zeckendorf_fibs:
base[self.index(n) - self.index(fib)] = '1'
return ''.join(base)
def zeckendorf_digit_to_decimal(self, z):
running_sum = 0
for i, char in enumerate(reversed(z), start=1):
if char == '1':
running_sum += self.fib(i+1)
return running_sum
def fib_mod_m(self, k, mod):
"""
Can compute arbitrarily large Fib numbers, mod m, using
fast matrix multiplication. Backed by a cache too.
"""
FIBMATRIX = ((1, 1), (1, 0))
return fast_2matrix_expon_mod_m(FIBMATRIX, k, mod)[0][1]
def linear_diophantine_solver(a, b, c):
"""
solves a*x + b*y = c for (x,y)
If a single solution exists, then an infinite number of solutions exists, indexed
by an integer k. This functions returns a _function_ that accepts k
"""
class NoSolution(Exception):
pass
if c % gcd(a, b) != 0:
raise NoSolution()
# find single solution
gcd_, x, y = xgcd(a, b)
x = x * abs(c)
y = y * abs(c)
u, v = a / gcd_, b / gcd_
return lambda k: (x + k * v, y - k * u)
def diophantine_count(a, n):
# from https://math.stackexchange.com/questions/30638/count-the-number-of-positive-solutions-for-a-linear-diophantine-equation
"""Computes the number of nonnegative solutions (x) of the linear
Diophantine equation
a[0] * x[0] + ... a[N-1] * x[N-1] = n
Theory: For natural numbers a[0], a[2], ..., a[N - 1], n, and j,
let p(a, n, j) be the number of nonnegative solutions.
Then one has:
p(a, m, j) = sum p(a[1:], m - k * a[0], j - 1), where the sum is taken
over 0 <= k <= floor(m // a[0])
Examples
--------
>>> diophantine_count([3, 2, 1, 1], 47)
3572
>>> diophantine_count([3, 2, 1, 1], 40)
2282
"""
def p(a, m, j):
if j == 0:
return int(m == 0)
else:
return sum([p(a[1:], m - k * a[0], j - 1)
for k in xrange(1 + m // a[0])])
return p(a, n, len(a))
| {
"repo_name": "CamDavidsonPilon/projecteuler-utils",
"path": "number_theory.py",
"copies": "1",
"size": "8661",
"license": "mit",
"hash": 3774467902481795000,
"line_mean": 24.4735294118,
"line_max": 130,
"alpha_frac": 0.4949774853,
"autogenerated": false,
"ratio": 2.9844934527911784,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.8978689365547114,
"avg_score": 0.00015631450881255308,
"num_lines": 340
} |
from fractions import gcd
from functools import reduce
from operator import mul
def pythag_triple_summing_to_s(s):
"""Finds the list of all pythagorean triples summing to n."""
# All PPTs can be generated using coprime (m, n) of opposite
# parity with m > n. The triple for (m, n) is as follows:
# a = m^2 - n^2
# b = 2mn
# c = m^2 + n^2
# Thus a+b+c = 2m^2 + 2mn = 2m(m+n). Note that as m and/or n increase,
# so does the sum a+b+c.
triples = []
m = 2
while 2*m*(m+1) <= s:
n = 1 if m % 2 == 0 else 2 # opposite parity
while n < m and 2*m*(m+n) <= s:
if gcd(m, n) == 1 and s % (2*m*(m+n)) == 0:
k = s // (2*m*(m+n))
a = k * (m*m - n*n)
b = k * 2*m*n
c = k * (m*m + n*n)
triples.append((a, b, c))
n += 2
m += 1
return triples
def answer():
return reduce(mul, pythag_triple_summing_to_s(1000)[0])
if __name__ == '__main__':
print(answer())
| {
"repo_name": "peterstace/project-euler",
"path": "OLD_PY_CODE/project_euler_py/pe0009.py",
"copies": "1",
"size": "1032",
"license": "unlicense",
"hash": -514503525803918850,
"line_mean": 30.2727272727,
"line_max": 74,
"alpha_frac": 0.4815891473,
"autogenerated": false,
"ratio": 2.811989100817439,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.3793578248117439,
"avg_score": null,
"num_lines": null
} |
from fractions import gcd
from itertools import combinations
from number_theory import isqrt, perfect_square
def integer_120_triangles(side_limit):
"""
Generates all primitive integer length triangles with a 120
degree angle.
These are the integer solutions to the equation:
a^2 + b^2 - 2*a*b*cos(120) == c*c
a^2 + b^2 + a*b == c*c
"""
m = 4
while m*m + m + 1 <= 3 * side_limit:
n_start = m % 3
n_start = 3 if n_start == 0 else n_start
for n in range(n_start, m, 3):
if gcd(m, n) != 1: continue
a = (m*m - n*n) // 3
b = (2*m*n + n*n) // 3
c = (m*m + n*n + m*n) // 3
if c > side_limit: break
yield (a, b, c)
m += 1
SIZE = 120000
distinct_pqr = set()
db = dict()
for a, b, c in integer_120_triangles(SIZE):
a, b, c = sorted((a, b, c))
for k in range(1, SIZE // c + 1):
db.setdefault(a*k, []).append((a*k, b*k, c*k))
for short_side in db:
for (a1, b1, c1), (a2, b2, c2) in combinations(db[short_side], 2):
pqr_sum = a1 + b1 + b2
if pqr_sum > SIZE: continue
possible_square = b1*b1 + b2*b2 + b1*b2
if perfect_square(possible_square):
c3 = isqrt(possible_square)
print("TRIANGLE:{},{},{} PQR:{},{},{} SUM:{}".format(c1, c2, c3,
a1, b1, b2, pqr_sum))
distinct_pqr.add(pqr_sum)
print("ANSWER:", sum(distinct_pqr))
| {
"repo_name": "peterstace/project-euler",
"path": "OLD_PY_CODE/project_euler_old_old/143/143.py",
"copies": "1",
"size": "1463",
"license": "unlicense",
"hash": 2656384855227454000,
"line_mean": 30.8043478261,
"line_max": 76,
"alpha_frac": 0.5174299385,
"autogenerated": false,
"ratio": 2.8188824662813103,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.383631240478131,
"avg_score": null,
"num_lines": null
} |
from fractions import gcd
from itertools import starmap, cycle
import utilities
import base64
import string
import hashlib
# Set the output width for formatted strings
row_format ="{:>30}" * 2
# Parent class for all defined ciphers
class Cipher():
socket = ''
def __init__(self, socket):
self.socket = socket
def cipherGreeting(self):
self.socket.send(row_format.format("Explain", "Encrypt!") + "\n")
self.socket.send(row_format.format("-------", "--------") + "\n")
self.socket.send(row_format.format("a", "b") + "\n")
self.socket.send("Enter choice (q to exit to main menu): ")
choice = 't'
while len(choice):
choice = self.socket.recv(2048).strip()
if choice == 'a':
self.explain()
elif choice == 'b':
self.encrypt()
elif choice == 'q':
return
def shell(self):
while True:
self.socket.send(">>")
input = self.socket.recv(2048).strip().split()
if (input == []):
continue
elif (input[0] == 'q'):
break
elif (input[0] == 'bin'):
self.socket.send("bin(\'" + input[1].strip() + "\') = " + str(int(''.join(format(ord(x), 'b') for x in input[1].strip()), 2)) + "\n")
elif (input[0] == 'pow'):
self.socket.send(str(int(input[1]) ** int(input[2])) + "\n")
elif (input[0] == 'inverse'):
u = utilities.Utilities()
self.socket.send(str(u.inverse(int(input[1]), int(input[2]))) + "\n")
elif (input[0] == 'gcd'):
self.socket.send(str(gcd(int(input[1]), int(input[2]))) + "\n")
elif (input[0] == 'mul'):
self.socket.send(str(int(input[1]) * int(input[2])) + "\n")
# not an encryption scheme; just trollin'
# https://en.wikipedia.org/wiki/Base64
class Base64(Cipher):
def explain(self):
self.socket.send("A binary system uses two symbols to encode data.\nA base64 system uses 64 symbols.\n\n")
self.socket.send("Moving from left to right in the bit-sequence corresponding to the plaintext, a 24-bit group is formed by joining three 8-bit groups. This is now treated as 4 6-bit groups joined together.\nEach of these groups is translated into a character based on the following table:\n")
self.socket.send(row_format.format("Value", "Character" + "\n"))
self.socket.send(row_format.format("-----", "---------" + "\n"))
self.socket.send(row_format.format("0-25", "A-Z" + "\n"))
self.socket.send(row_format.format("26-51", "a-z" + "\n"))
self.socket.send(row_format.format("52-61", "0-9" + "\n"))
self.socket.send(row_format.format("62", "+" + "\n"))
self.socket.send(row_format.format("63", "/" + "\n"))
self.socket.send(row_format.format("pad", "=" + "\n\n"))
self.socket.send("For example, the text 'IEEE' would become 'SUVFRQo=' on passing through base64.\n")
self.socket.recv(2048)
self.cipherGreeting()
def encrypt(self):
self.socket.send("Enter plaintext: ")
ptext = self.socket.recv(2048)
self.socket.send("Ciphertext: " + base64.b64encode(ptext))
self.socket.recv(2048)
self.cipherGreeting()
# https://en.wikipedia.org/wiki/Bacon's_cipher
class BaconCipher(Cipher):
def explain(self):
self.socket.send("In this method each letter in the message is represented as a code consisting of only two characters, say 'a' and 'b'.\n")
self.socket.send("The code is generated on the lines of binary representation; only here we use 'a' and 'b' instead of zeroes and ones. Let us number all the letters from 'a' to 'z' starting with 0. A is 0, B is 1...\n")
self.socket.send("Once we have numbered the letters we write the 5-bit binary equivalents for the same with 'a' in place of zeroes and 'b' in the place of ones.\n")
self.socket.send("For example, B --> 00001 --> aaaab.\n")
self.socket.send("This is done for all letters in the message. Thus, 'IEEE' becomes 'abaaa aabaa aabaa aabaa'\n")
self.socket.send("We can use a phrase of the same character length to hide this message. A capital letter in the phrase would stand for 'a', a lowercase one for 'b'.\n")
self.socket.send("In such a scenario, the actual phrase is meaningless; only the capitalization is meaningful and is used to translate the phrase into a string of 'a's and 'b's.\n")
self.socket.recv(2048)
self.cipherGreeting()
def encrypt(self):
self.socket.send("Whoops! You're going to have to do this one by hand. :)\n")
self.socket.recv(2048)
self.cipherGreeting()
# https://en.wikipedia.org/wiki/Diffie-Hellman_key_exchange
class DiffieHelman(Cipher):
def explain(self):
self.socket.send("You might be wondering how to securely communicate a key to your team. This is where the Diffie Helman Key Exchange comes into play.\n")
self.socket.send("The sender and recipient, Alice and Bob, decide on a prime number 'p' and a base number 'g'. It doesn't matter if others see this.\n")
self.socket.send("Alice has a secret number 'a', and Bob has a secret number 'b'.\n")
self.socket.send("Alice computes A = (g ** a) mod p. This is sent to Bob.\nBob computes B = (g ** b) mod p and sends it to Alice.\n")
self.socket.send("Alice finds (B ** a) mod p, and Bob finds (A ** b) mod p. This value is the same for both!\nWhy? Because ([(g ** a) mod p] ** b) mod p is the same as ([(g ** b) mod p] ** a) mod p.\n")
self.socket.send("Thus, Alice and Bob now have a shared secret key that no one else knows!\n")
self.socket.recv(2048)
self.cipherGreeting()
def encrypt(self):
self.socket.send("This is the same 'shell' we saw under RSA, and you can use the same functions as were present there.\nHave fun!\n")
self.shell()
self.socket.recv(2048)
self.cipherGreeting()
# https://en.wikipedia.org/wiki/Dvorak_encoding
class DvorakCipher(Cipher):
def explain(self):
self.socket.send("Dvorak encoding is a type of encoding based on the differences of layout of a Qwerty keyboard and a Dvorak keyboard.\n")
self.socket.send("It's used to encode plaintext documents in a non-standard way.\n")
self.socket.send("Ultimately, you can do one of two things: replace a QWERTY character with it's corresponding Dvorak one (QwDv), or vice-versa (DvQw).\n")
self.socket.send("Under DvQw, \"axje.uidchtnmbrl'poygk,qf;\" gets translated to \"abcdefghijklmnopqrstuvwxyz\".\n")
self.socket.send("Here, we've implemented only one of the schemes. I wonder which one?\n")
self.socket.recv(2048)
self.cipherGreeting()
def encrypt(self):
qwerty = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
dvorak = "axje.uidchtnmbrl'poygk,qf;AXJE>UIDCHTNMBRL\"POYGK<QF:"
table = string.maketrans(qwerty, dvorak)
self.socket.send("Enter plaintext: ")
ptext = self.socket.recv(2048)
self.socket.send("Ciphertext: " + ptext.translate(table))
self.socket.recv(2048)
self.cipherGreeting()
# https://en.wikipedia.org/wiki/MD5
class MD5(Cipher):
def explain(self):
self.socket.send("MD5 is a hash function that yields a 128-bit hash value, represented as a 32-digit hexadecimal number.\n")
self.socket.send("The input message is split into 512-bit blocks after padding accordingly.\n")
self.socket.send("The main algorithm works on a 128-bit state, divided into four 32-bit words, each initialized to a certain constant.\n")
self.socket.send("Each 512-bit block is then used to modify the state in four rounds of sixteen operations (nonlinear, modular addition and left rotation) each.\n")
self.socket.send("A hash function is a function that maps a data set of variable size to a smaller data set of fixed size.\nIdeally, it is impossible to change a message without changing its hash, and it is impossible to find two messages with the same hash.\n")
self.socket.recv(2048)
self.cipherGreeting()
def encrypt(self):
self.socket.send("Enter plaintext: ")
ptext = self.socket.recv(2048)
h = hashlib.md5()
h.update(ptext)
#Do I print Ciphertext here, or Hash Value? :S
self.socket.send("Ciphertext: " + h.hexdigest())
self.socket.recv(2048)
self.cipherGreeting()
# https://en.wikipedia.org/wiki/RSA_(cryptosystem)
class RSA(Cipher):
def explain(self):
self.socket.send("The RSA cryptosystem is based on asymmetric key cryptography.\nThis means that the keys used for encryption and decryption are different.\n")
self.socket.send("We have three main stages:\n(a) Encryption\n(b) Decryption\n(c) Key Generation\n\n")
self.socket.send("(a) Encryption\ny = (x ** e) mod n\nHere, x is the binary value of the plaintext, y is the ciphertext. '**' refers to exponentiation.\nThe pair (n, e) is referred to as the public key, and 'e' is the public exponent or encrypting exponent.\n\n")
self.socket.send("(b) Decryption\nx = (y ** d) mod n\nHere, x, y and n are the same, and d is the private exponent/key or decrypting exponent.\n\n")
self.socket.send("CONSTRAINTS:\n1. It must be computationally infeasible to obtain the private key from the public key (n, e)\n2. Encryption and decryption should be easy given the parameters. Fast exponentiation is necessary.\n3. We cannot encrypt more than L bits of plaintext, where L is the bit size of n.\n")
self.socket.send("4. Given n, there should be many possible values for e and d. Otherwise, we can brute force the private key.\n\n")
self.socket.send("(c) Key Generation\nThis is how n, e and d are obtained.\n1. Choose two prime numbers, p and q.\n2. n = p * q\n3. Compute the Euler totient phi(n) (henceforth P) as P = (p - 1) * (q - 1)\n")
self.socket.send("4. Choose 'e' such that 0 < e < P and GCD(e, P) is 1.\nMathematically speaking, e and P are relatively prime.\n")
self.socket.send("5. Compute private key d as (d * e) is congruent to 1 mod P.\nOn rearranging, d = t mod P, where t is the inverse of e.\n")
self.socket.recv(2048)
self.cipherGreeting()
def encrypt(self):
self.socket.send("Here, we will provide a 'shell' where you can find some of the functions mentioned in the explanation already implemented for you. All you need to do is call them! Of course, you'll have to do some things by hand. You're welcome!\n")
self.socket.send("Functions available:\n'mul a b' - multiply two numbers\n'gcd a b' - return gcd of a and b\n'inverse e P' - return 't'; refer to explanation\n'pow a b' - return a raised to b\n'bin s' - returns binary value of string s\n")
self.socket.send("Enter 'q' to go back.\n")
self.shell()
self.socket.recv(2048)
self.cipherGreeting()
# https://en.wikipedia.org/wiki/Caesar_cipher
class ShiftCipher(Cipher):
def explain(self):
self.socket.send("The shift cipher is a type of substitution cipher.\n")
self.socket.send("Every letter in the plaintext gets replaced by another letter at a fixed distance 'k' from the letter. Here, 'k' is our 'key', and is constant for all letters in the plaintext.\n")
self.socket.send("For example, a plaintext of 'ieee' with key 'k' = 3 would be encrypted as 'lhhh'.\n\n")
self.socket.recv(2048)
self.cipherGreeting()
def encrypt(self):
self.socket.send("Whoops! You're going to have to do this one by hand. :)\n")
self.socket.recv(2048)
self.cipherGreeting()
# https://en.wikipedia.org/wiki/Vigenère_cipher
class VigenereCipher(Cipher):
def explain(self):
self.socket.send("The Vigenere cipher is a type of polyalphabetic substitution cipher.\n")
self.socket.send("Every letter in the plaintext is cyclically shifted to the right by the value of the corresponding key letter.\n")
self.socket.send("By value of a letter, we mean A is 0, B is 1, and so on.\n")
self.socket.send("The key doesn't have to be as long as the plaintext: just keep repeating it.\n")
self.socket.send("For example, if the plaintext is COMPSOC and the key is IEEE, C is shifted to the right I (8) times, giving you K.\n")
self.socket.send("C is encrypted with I, O with E, M with E, P with E, and then S with I and so on, giving you the ciphertext KSQTASG.\n")
self.socket.recv(2048)
self.cipherGreeting()
def encrypt(self):
self.socket.send("Enter plaintext: ")
ptext = self.socket.recv(2048)
self.socket.send("Enter key: ")
key = self.socket.recv(2048)
#removing special characters and converting the strings to uppercase:
ptext = filter(lambda _: _.isalpha(), ptext.upper())
key = filter(lambda _: _.isalpha(), key.upper())
#char-by-char encryption:
def enc(c,k): return chr(((ord(k) + ord(c)) % 26) + ord('A'))
self.socket.send("Ciphertext: " + "".join(starmap(enc, zip(ptext, cycle(key)))).lower())
self.socket.recv(2048)
self.cipherGreeting()
# https://en.wikipedia.org/wiki/XOR_cipher
class XORCipher(Cipher):
def explain(self):
formatter = "{:>20}" * 5
self.socket.send("A two-input XOR outputs '0' when both inputs are identical and '1' otherwise.\nAlso, if x XOR y equals z, then z XOR y equals x.\n")
self.socket.send("This property makes the encryption and decryption procedures identical.\nIn this cipher, all the letters in the alphabet (and a few digits) are represented in binary as follows:\n")
self.socket.send("A 00000 (0)\nB 00001 (1)\n...\nZ 11001 (25)\n1 11010 (26)\n...\n6 11111 (31)\n")
self.socket.send("A 5-bit key is chosen and XORed with each of the symbols in the plaintext to get the ciphertext, and vice-versa.\nFor example,\n")
self.socket.send(formatter.format("Message", "N", "I", "T", "K") + "\n")
self.socket.send(formatter.format("Binary", "01101", "01000", "10011", "01010") + "\n")
self.socket.send(formatter.format("Chosen key", "10110", "10110", "10110", "10110") + "\n")
self.socket.send(formatter.format("After XOR", "11011", "11110", "00101", "11100") + "\n")
self.socket.send(formatter.format("Ciphertext", "2", "5", "F", "3") + "\n")
self.socket.send(formatter.format("Corresponding Binary", "11011", "11110", "00101", "11100") + "\n")
self.socket.send(formatter.format("Chosen key", "10110", "10110", "10110", "10110") + "\n")
self.socket.send(formatter.format("After XOR", "01101", "01000", "10011", "01010") + "\n")
self.socket.send(formatter.format("Decrypted message", "N", "I", "T", "K") + "\n")
self.socket.recv(2048)
self.cipherGreeting()
def encrypt(self):
self.socket.send("Whoops! You're going to have to do this one by hand. :)\n")
self.socket.recv(2048)
self.cipherGreeting()
| {
"repo_name": "IEEE-NITK/EaaS",
"path": "src/cipher.py",
"copies": "1",
"size": "15312",
"license": "mit",
"hash": 6887514613805403000,
"line_mean": 58.3449612403,
"line_max": 325,
"alpha_frac": 0.6396708249,
"autogenerated": false,
"ratio": 3.486111111111111,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4625781936011111,
"avg_score": null,
"num_lines": null
} |
from fractions import gcd
from random import randint
def brent(N):
# brent returns a divisor not guaranteed to be prime, returns n if n prime
if N%2==0: return 2
y,c,m = randint(1, N-1),randint(1, N-1),randint(1, N-1)
g,r,q = 1,1,1
while g==1:
x = y
for i in range(r):
y = ((y*y)%N+c)%N
k = 0
while (k<r and g==1):
ys = y
for i in range(min(m,r-k)):
y = ((y*y)%N+c)%N
q = q*(abs(x-y))%N
g = gcd(q,N)
k = k + m
r = r*2
if g==N:
while True:
ys = ((ys*ys)%N+c)%N
g = gcd(abs(x-ys),N)
if g>1: break
return g
def factorize(n1):
if n1<=0: return []
if n1==1: return [1]
n=n1
b=[]
p=0
mx=1000000
while n % 2 ==0 : b.append(2);n//=2
while n % 3 ==0 : b.append(3);n//=3
i=5
inc=2
#use trial division for factors below 1M
while i <=mx:
while n % i ==0 : b.append(i); n//=i
i+=inc
inc=6-inc
#use brent for factors >1M
while n>mx:
p1=n
#iterate until n=brent(n) => n is prime
while p1!=p:
p=p1
p1=brent(p)
b.append(p1);n//=p1
if n!=1:b.append(n)
b.sort()
return b
from functools import reduce
from sys import argv
def main():
if len(argv)==2:
n=int(argv[1])
else:
n=int(eval(input(" Integer to factorize? ")))
li=factorize(n)
print (n,"= ",li)
print ("n - product of factors = ",n - reduce(lambda x,y :x*y ,li))
if __name__ == "__main__":
main()
| {
"repo_name": "ActiveState/code",
"path": "recipes/Python/579049_Prime_factors_integer_Brent/recipe-579049.py",
"copies": "1",
"size": "1585",
"license": "mit",
"hash": 8761009667609239000,
"line_mean": 21.6428571429,
"line_max": 77,
"alpha_frac": 0.4757097792,
"autogenerated": false,
"ratio": 2.7094017094017095,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.368511148860171,
"avg_score": null,
"num_lines": null
} |
from fractions import gcd
from random import randrange
from collections import namedtuple
from math import log
from binascii import hexlify, unhexlify
def is_prime(n, k=30):
# http://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test
if n <= 3:
return n == 2 or n == 3
neg_one = n - 1
# write n-1 as 2^s*d where d is odd
s, d = 0, neg_one
while not d & 1:
s, d = s+1, d>>1
assert 2 ** s * d == neg_one and d & 1
for i in xrange(k):
a = randrange(2, neg_one)
x = pow(a, d, n)
if x in (1, neg_one):
continue
for r in xrange(1, s):
x = x ** 2 % n
if x == 1:
return False
if x == neg_one:
break
else:
return False
return True
def randprime(N=10**8):
p = 1
while not is_prime(p):
p = randrange(N)
return p
def multinv(modulus, value):
'''Multiplicative inverse in a given modulus
>>> multinv(191, 138)
18
>>> multinv(191, 38)
186
>>> multinv(120, 23)
47
'''
# http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm
x, lastx = 0, 1
a, b = modulus, value
while b:
a, q, b = b, a // b, a % b
x, lastx = lastx - q * x, x
result = (1 - lastx * modulus) // value
if result < 0:
result += modulus
assert 0 <= result < modulus and value * result % modulus == 1
return result
KeyPair = namedtuple('KeyPair', 'public private')
Key = namedtuple('Key', 'exponent modulus')
def keygen(N, public=None):
''' Generate public and private keys from primes up to N.
Optionally, specify the public key exponent (65537 is popular choice).
>>> pubkey, privkey = keygen(2**64)
>>> msg = 123456789012345
>>> coded = pow(msg, *pubkey)
>>> plain = pow(coded, *privkey)
>>> assert msg == plain
'''
# http://en.wikipedia.org/wiki/RSA
prime1 = randprime(N)
prime2 = randprime(N)
composite = prime1 * prime2
totient = (prime1 - 1) * (prime2 - 1)
if public is None:
while True:
private = randrange(totient)
if gcd(private, totient) == 1:
break
public = multinv(totient, private)
else:
private = multinv(totient, public)
assert public * private % totient == gcd(public, totient) == gcd(private, totient) == 1
assert pow(pow(1234567, public, composite), private, composite) == 1234567
return KeyPair(Key(public, composite), Key(private, composite))
def encode(msg, pubkey, verbose=False):
chunksize = int(log(pubkey.modulus, 256))
outchunk = chunksize + 1
outfmt = '%%0%dx' % (outchunk * 2,)
bmsg = msg.encode()
result = []
for start in range(0, len(bmsg), chunksize):
chunk = bmsg[start:start+chunksize]
chunk += b'\x00' * (chunksize - len(chunk))
plain = int(hexlify(chunk), 16)
coded = pow(plain, *pubkey)
bcoded = unhexlify((outfmt % coded).encode())
if verbose: print('Encode:', chunksize, chunk, plain, coded, bcoded)
result.append(bcoded)
return b''.join(result)
def decode(bcipher, privkey, verbose=False):
chunksize = int(log(pubkey.modulus, 256))
outchunk = chunksize + 1
outfmt = '%%0%dx' % (chunksize * 2,)
result = []
for start in range(0, len(bcipher), outchunk):
bcoded = bcipher[start: start + outchunk]
coded = int(hexlify(bcoded), 16)
plain = pow(coded, *privkey)
chunk = unhexlify((outfmt % plain).encode())
if verbose: print('Decode:', chunksize, chunk, plain, coded, bcoded)
result.append(chunk)
return b''.join(result).rstrip(b'\x00').decode()
if __name__ == '__main__':
import doctest
print(doctest.testmod())
pubkey, privkey = keygen(2 ** 64)
msg = 'the quick brown fox jumped over the lazy dog'
h = encode(msg, pubkey, 1)
p = decode(h, privkey, 1)
print('-' * 20)
print(repr(msg))
print(h)
print(repr(p))
| {
"repo_name": "ActiveState/code",
"path": "recipes/Python/577737_Public_Key_Encryption_RSA/recipe-577737.py",
"copies": "1",
"size": "4087",
"license": "mit",
"hash": 6274474385554986000,
"line_mean": 28.8321167883,
"line_max": 91,
"alpha_frac": 0.5678982138,
"autogenerated": false,
"ratio": 3.4058333333333333,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.44737315471333333,
"avg_score": null,
"num_lines": null
} |
from fractions import gcd
from random import randrange, random
from collections import namedtuple
from math import log
from binascii import hexlify, unhexlify
def is_prime(n, k=30):
if n <= 3:
return n == 2 or n == 3
neg_one = n - 1
s, d = 0, neg_one
while not d & 1:
s, d = s+1, d>>1
assert 2 ** s * d == neg_one and d & 1
for i in xrange(k):
a = randrange(2, neg_one)
x = pow(a, d, n)
if x in (1, neg_one):
continue
for r in xrange(1, s):
x = x ** 2 % n
if x == 1:
return False
if x == neg_one:
break
else:
return False
return True
def randprime(N=10**8):
p = 1
while not is_prime(p):
p = randrange(N)
return p
def multinv(modulus, value):
x, lastx = 0, 1
a, b = modulus, value
while b:
a, q, b = b, a // b, a % b
x, lastx = lastx - q * x, x
result = (1 - lastx * modulus) // value
if result < 0:
result += modulus
assert 0 <= result < modulus and value * result % modulus == 1
return result
KeyPair = namedtuple('KeyPair', 'public private')
Key = namedtuple('Key', 'exponent modulus')
def keygen(N, public=None):
prime1 = randprime(N)
prime2 = randprime(N)
composite = prime1 * prime2
totient = (prime1 - 1) * (prime2 - 1)
if public is None:
while True:
private = randrange(totient)
if gcd(private, totient) == 1:
break
public = multinv(totient, private)
else:
private = multinv(totient, public)
assert public * private % totient == gcd(public, totient) == gcd(private, totient) == 1
assert pow(pow(1234567, public, composite), private, composite) == 1234567
return KeyPair(Key(public, composite), Key(private, composite))
def signature(msg, privkey):
# f=open('signedfile','w')
coded = pow(int(msg), *privkey)% privkey[1]
# print "Blinded Signed Message "+str(coded)
# f.write(str(coded))
return coded
def blindingfactor(N):
b=random()*(N-1)
r=int(b)
while (gcd(r,N)!=1):
r=r+1
return r
def blind(msg,pubkey):
# f=open('blindmsg','w')
r=blindingfactor(pubkey[1])
m=int(msg)
blindmsg=(pow(r,*pubkey)*m)% pubkey[1]
# print "Blinded Message "+str(blindmsg)
# f.write(str(blindmsg))
return r, blindmsg
def unblind(msg,r,pubkey):
# f=open('unblindsigned','w')
bsm=int(msg)
ubsm=(bsm*multinv(pubkey[1],r))% pubkey[1]
# print "Unblinded Signed Message "+str(ubsm)
# f.write(str(ubsm))
return ubsm
def verify(msg,r,pubkey):
# print "Message After Verification "+str(pow(int(msg),*pubkey)%pubkey[1])
return pow(int(msg),*pubkey)%pubkey[1]
if __name__ == '__main__':
# bob wants to send msg after blinding it
verified = []
repetitions = 1000
next_percent = .1
for i in range(repetitions):
pubkey, privkey = keygen(2 ** 256)
msg='25770183113924073453606000342737120404436189449536418046283318993427598671872'
msg=msg.rstrip()
# print "Original Message "+str(msg)
r, blindmsg=blind(msg,pubkey)
#Alice receives the blind message and signs it
m=blindmsg
signed = signature(m, privkey)
#Bob recieves the signed message and unblinds it
signedmsg=signed
unblinded = unblind(signedmsg,r,pubkey)
#verifier verefies the message
ubsignedmsg=unblinded
# print 'Verified:', verify(ubsignedmsg,r,pubkey) == long(msg)
verified.append(long(verify(ubsignedmsg,r,pubkey)) == long(msg))
if float(i) / repetitions > next_percent:
print next_percent
next_percent += .1
success = verified.count(True)
print 'Success:', success
print 'Failure:', len(verified) - success | {
"repo_name": "kelleyb/CryptoProject",
"path": "blind_signature.py",
"copies": "1",
"size": "3908",
"license": "mit",
"hash": -4842708028764394000,
"line_mean": 27.3260869565,
"line_max": 91,
"alpha_frac": 0.5834186285,
"autogenerated": false,
"ratio": 3.2377796188898094,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4321198247389809,
"avg_score": null,
"num_lines": null
} |
from fractions import gcd
def answer():
def ppts(s):
"""Finds the list of all pythagorean triples summing <= s."""
# All PPTs can be generated using coprime (m, n) of opposite
# parity with m > n. The triple for (m, n) is as follows:
# a = m^2 - n^2
# b = 2mn
# c = m^2 + n^2
# Thus a+b+c = 2m^2 + 2mn = 2m(m+n). Note that as m and/or n increase,
# so does the sum a+b+c.
m = 2
while 2*m*(m+1) <= s:
n = 1 if m % 2 == 0 else 2 # opposite parity
while n < m and 2*m*(m+n) <= s:
if gcd(m, n) == 1:
a = m*m - n*n
b = 2*m*n
c = m*m + n*n
side_sum = a + b + c
k = 1
while side_sum <= s:
yield (a*k, b*k, c*k)
k += 1
side_sum = (a + b + c) * k
n += 2
m += 1
counter = dict()
for a, b, c in ppts(1000):
side_sum = a + b + c
if side_sum not in counter:
counter[side_sum] = 1
else:
counter[side_sum] += 1
return max((value, key) for (key, value) in counter.items())[1]
if __name__ == '__main__':
print(answer())
| {
"repo_name": "peterstace/project-euler",
"path": "OLD_PY_CODE/project_euler_py/pe0039.py",
"copies": "1",
"size": "1325",
"license": "unlicense",
"hash": 7954583874122867000,
"line_mean": 31.3170731707,
"line_max": 78,
"alpha_frac": 0.3916981132,
"autogenerated": false,
"ratio": 3.3042394014962593,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9156180262487146,
"avg_score": 0.007951450441822714,
"num_lines": 41
} |
from fractions import gcd
def calculateSteps(target, container1, container2):
if target > container1 and target > container2:
print -1
else:
if target % gcd(container1, container2) != 0:
print -1
else:
result = {}
class Container:
def __init__(self):
self.weight = 0
self.size = 0
def fill(self):
self.weight = self.size
def empty(self):
self.weight = 0
def transferTo(self, other_container):
if(self.weight > other_container.size - other_container.weight):
self.weight -= other_container.size - other_container.weight
other_container.weight = other_container.size
else:
other_container.weight += self.weight
self.empty()
def runSequence(sequence):
cycle = 0
for i in xrange(len(sequence)):
if big_container.weight == target or small_container.weight == target:
break
sequence[i]()
if i == (len(sequence) -1):
runSequence(sequence)
cycle +=1
if cycle == 1000:
break
return
def First(target, big_container, small_container):
first = {'count':0}
def seq1():
while(big_container.weight >= small_container.size):
big_init = big_container.weight
big_container.transferTo(small_container)
big_diff = big_init - big_container.weight
first['count'] += 1
if big_container.weight == target or small_container.weight == target:
break
small_container.empty()
first['count'] += 1
def seq2():
big_init = big_container.weight
big_container.transferTo(small_container)
big_diff = big_init - big_container.weight
first['count'] += 1
def seq3():
big_container.fill()
first['count'] += 1
sequence = [seq1, seq2, seq3]
big_container.empty()
small_container.empty()
big_container.fill()
first['count'] += 1
runSequence(sequence)
return first
def Second(target, big_container, small_container):
second = {'count': 0}
def seq1():
while(big_container.weight != big_container.size):
small_container.fill()
second['count'] += 1
print "Fill the " + str(small_container.size) + "L bucket with " + str(small_container.size) + "L of water"
if big_container.weight == target or small_container.weight == target:
break
small_container_init = small_container.weight
small_container.transferTo(big_container)
second['count'] += 1
print "Transfer the " + str(small_container.size) + "L bucket to " + str(big_container.size) + "L of water"
small_container_diff = small_container_init - small_container.weight
if big_container.weight == target or small_container.weight == target:
break
def seq2():
big_container.empty()
second['count'] += 1
print "Empty the " + str(big_container.size) + "L of water"
def seq3():
small_container_init = small_container.weight
small_container.transferTo(big_container)
small_container_diff = small_container_init - small_container.weight
second['count'] += 1
sequence = [seq1, seq2, seq3]
small_container.empty()
big_container.empty()
runSequence(sequence)
return second
small_container = Container()
big_container = Container()
if container1 > container2:
big_container.size = container1
small_container.size = container2
else:
big_container.size = container2
small_container.size = container1
first = First(target, big_container, small_container) # large to small
second = Second(target, big_container, small_container) # small to large
print first
print second
print min(first['count'], second['count'])
calculateSteps(5, 2, 3)
#
## Uncomment below lines to accept input from external source
#
#queries = int(raw_input())
#for query in xrange(queries):
# container1 = int(raw_input())
# container2 = int(raw_input())
# target = int(raw_input())
# calculateSteps(target, container1, container2)
#
| {
"repo_name": "prabhugs/scripts",
"path": "bucket.py",
"copies": "1",
"size": "4012",
"license": "mit",
"hash": -2081578368676693200,
"line_mean": 23.7654320988,
"line_max": 113,
"alpha_frac": 0.6455633101,
"autogenerated": false,
"ratio": 3.397121083827265,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4542684393927265,
"avg_score": null,
"num_lines": null
} |
from fractions import gcd
class Fraction:
def __init__(self, nominator, denominator):
self.nominator = nominator
self.denominator = denominator
# least common multiple
@staticmethod
def lcm(a, b):
absolute_value = abs(a * b)
greatest_common_divisor = gcd(a, b)
return absolute_value // greatest_common_divisor
@staticmethod
def new_nominator_fractions(a, b):
least_cm = a.lcm(a.denominator, b.denominator)
new_self_nominator = (least_cm // a.denominator) * a.nominator
new_other_nominator = (least_cm // b.denominator) * b.nominator
return (new_self_nominator, new_other_nominator)
def __add__(self, other):
least_cm = self.lcm(self.denominator, other.denominator)
to_sum = self.new_nominator_fractions(self, other)
new_nominator = to_sum[0] + to_sum[1]
return Fraction(new_nominator, least_cm)
def __sub__(self, other):
least_cm = self.lcm(self.denominator, other.denominator)
to_sub = self.new_nominator_fractions(self, other)
new_nominator = to_sub[0] - to_sub[1]
return Fraction(new_nominator, least_cm)
def __lt__(self, other):
to_sub = self.new_nominator_fractions(self, other)
if to_sub[0] < to_sub[1]:
return True
return False
def __gt__(self, other):
to_sub = self.new_nominator_fractions(self, other)
if to_sub[0] > to_sub[1]:
return True
return False
def __eq__(self, other):
to_sub = self.new_nominator_fractions(self, other)
if to_sub[0] == to_sub[1]:
return True
return False
def __str__(self):
return "{} / {}".format(self.nominator, self.denominator)
a = Fraction(2, 3)
b = Fraction(4, 6)
print(a == b)
| {
"repo_name": "stoilov/Programming101",
"path": "week1/1-Python-OOP-problems-set/Fraction_class.py",
"copies": "1",
"size": "1835",
"license": "mit",
"hash": 880556407394470800,
"line_mean": 28.126984127,
"line_max": 71,
"alpha_frac": 0.5967302452,
"autogenerated": false,
"ratio": 3.3485401459854014,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.44452703911854013,
"avg_score": null,
"num_lines": null
} |
from fractions import gcd
'''
Note: we represent the matrix
[a+b a]
[a b]
with the pair (a,b)
'''
def mmul((a,b),(c,d),m):
'''
Multiply the matrices (a,b) and (c,d), i.e.
[a+b a] [c+d c]
[a b] and [c d]
'''
bd = b*d
return (
((a+b)*(c+d) - bd) % m,
(a*c + bd) % m,
)
def mpow(b,e,m):
''' raise the matrix b to the power e, modulo m '''
if e == 0:
return 0, 1
if e == 1:
return b
if e & 1:
return mmul(mpow(b,e-1,m), b, m)
return mpow(mmul(b,b,m), e>>1, m)
def Fm(n,m):
''' Find F(n) and F(n+1) modulo m '''
b,d = mpow((1,0), n, m)
return b, (b+d) % m
def Gm(a0,a1,n,m):
''' Find a0*F(n) + a1*F(n+1) modulo m '''
f0, f1 = Fm(n,m)
return (a0*f0 + a1*f1) % m
def answer(n, m, a0=0, a1=0, a2=0, b0=0, b1=0, b2=0):
if a2 or b2:
return answer(n, m, a0=a0+a2, a1=a1+a2, b0=b0+b2, b1=b1+b2)
if b1:
q, r = divmod(a1, b1)
return answer(n, m, a0=b0, a1=b1, b0=a0 - q*b0, b1=r)
# adjust sign
if b0 < 0:
b0 = -b0
if a1 == 0:
# easy case
f0, f1 = Fm(n,m)
return gcd(a0,b0) * f0 % m
if b0 == 0:
# another easy case
return Gm(a0,a1,n,m)
# general case
f0, f1 = Fm(n, a1*b0)
g = gcd(a1, f0)
return gcd(a0*f0 + a1*f1, g*b0) % m
z = input()
for cas in xrange(z):
n, a0, a1, a2, b0, b1, b2, m = map(int, raw_input().strip().split())
print answer(n, m, a0, a1, a2, b0, b1, b2)
| {
"repo_name": "atupal/oj",
"path": "hackerrank/contests/algorithms/infinitum11/refer_h.py",
"copies": "1",
"size": "1523",
"license": "mit",
"hash": 8367642447096526000,
"line_mean": 20.1527777778,
"line_max": 72,
"alpha_frac": 0.4576493762,
"autogenerated": false,
"ratio": 2.092032967032967,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.3049682343232967,
"avg_score": null,
"num_lines": null
} |
from fragment_capping.helpers.molecule import molecule_from_pdb_str, Molecule, Atom
PDBS = {
'ethanol': '''HEADER UNCLASSIFIED 21-Sep-17
TITLE ALL ATOM STRUCTURE FOR MOLECULE LIG
AUTHOR GROMOS AUTOMATIC TOPOLOGY BUILDER REVISION 2017-09-18 11:12:19
AUTHOR 2 http://compbio.biosci.uq.edu.au/atb
HETATM 1 H1 X5VY 0 -1.341 -0.944 0.839 1.00 0.00 H
HETATM 2 C1 X5VY 0 -1.282 -0.256 -0.015 1.00 0.00 C
HETATM 3 H3 X5VY 0 -2.159 0.402 0.024 1.00 0.00 H
HETATM 4 H2 X5VY 0 -1.332 -0.847 -0.936 1.00 0.00 H
HETATM 5 C2 X5VY 0 0.004 0.563 0.032 1.00 0.00 C
HETATM 6 H5 X5VY 0 0.052 1.246 -0.824 1.00 0.00 H
HETATM 7 H4 X5VY 0 0.028 1.180 0.943 1.00 0.00 H
HETATM 8 O1 X5VY 0 1.182 -0.244 -0.061 1.00 0.00 O
HETATM 9 H6 X5VY 0 1.199 -0.816 0.724 1.00 0.00 H
CONECT 1 2
CONECT 2 1 3 4 5
CONECT 3 2
CONECT 4 2
CONECT 5 2 6 7 8
CONECT 6 5
CONECT 7 5
CONECT 8 5 9
CONECT 9 8
END''',
'CHEMBL485374': '''HEADER UNCLASSIFIED 21-Sep-17
TITLE ALL ATOM STRUCTURE FOR MOLECULE UNL
AUTHOR GROMOS AUTOMATIC TOPOLOGY BUILDER REVISION 2017-09-18 11:12:19
AUTHOR 2 http://compbio.biosci.uq.edu.au/atb
HETATM 1 H1 DFWA 0 7.498 -0.961 -0.141 1.00 0.00 H
HETATM 2 C1 DFWA 0 6.425 -1.166 -0.104 1.00 0.00 C
HETATM 3 H3 DFWA 0 6.238 -1.814 0.760 1.00 0.00 H
HETATM 4 H2 DFWA 0 6.144 -1.721 -1.013 1.00 0.00 H
HETATM 5 N1 DFWA 0 5.719 0.097 0.038 1.00 0.00 N
HETATM 6 H4 DFWA 0 6.182 0.888 -0.390 1.00 0.00 H
HETATM 7 C2 DFWA 0 4.336 0.170 0.026 1.00 0.00 C
HETATM 8 C15 DFWA 0 3.517 -0.966 0.207 1.00 0.00 C
HETATM 9 H16 DFWA 0 3.965 -1.946 0.331 1.00 0.00 H
HETATM 10 C14 DFWA 0 2.131 -0.849 0.221 1.00 0.00 C
HETATM 11 H15 DFWA 0 1.542 -1.752 0.364 1.00 0.00 H
HETATM 12 C5 DFWA 0 1.483 0.392 0.058 1.00 0.00 C
HETATM 13 C6 DFWA 0 0.030 0.562 0.040 1.00 0.00 C
HETATM 14 H7 DFWA 0 -0.298 1.597 -0.064 1.00 0.00 H
HETATM 15 C7 DFWA 0 -0.911 -0.407 0.115 1.00 0.00 C
HETATM 16 H8 DFWA 0 -0.587 -1.446 0.178 1.00 0.00 H
HETATM 17 C8 DFWA 0 -2.365 -0.233 0.083 1.00 0.00 C
HETATM 18 C13 DFWA 0 -3.192 -1.361 -0.088 1.00 0.00 C
HETATM 19 H14 DFWA 0 -2.732 -2.343 -0.181 1.00 0.00 H
HETATM 20 C12 DFWA 0 -4.577 -1.258 -0.162 1.00 0.00 C
HETATM 21 H13 DFWA 0 -5.182 -2.152 -0.301 1.00 0.00 H
HETATM 22 C11 DFWA 0 -5.208 -0.006 -0.047 1.00 0.00 C
HETATM 23 N2 DFWA 0 -6.600 0.104 -0.043 1.00 0.00 N
HETATM 24 H12 DFWA 0 -7.086 -0.644 -0.526 1.00 0.00 H
HETATM 25 H11 DFWA 0 -6.954 1.009 -0.334 1.00 0.00 H
HETATM 26 C10 DFWA 0 -4.394 1.130 0.138 1.00 0.00 C
HETATM 27 H10 DFWA 0 -4.860 2.108 0.241 1.00 0.00 H
HETATM 28 C9 DFWA 0 -3.011 1.015 0.208 1.00 0.00 C
HETATM 29 H9 DFWA 0 -2.423 1.916 0.364 1.00 0.00 H
HETATM 30 C4 DFWA 0 2.315 1.519 -0.119 1.00 0.00 C
HETATM 31 H6 DFWA 0 1.856 2.498 -0.252 1.00 0.00 H
HETATM 32 C3 DFWA 0 3.698 1.420 -0.132 1.00 0.00 C
HETATM 33 H5 DFWA 0 4.305 2.312 -0.272 1.00 0.00 H
CONECT 1 2
CONECT 2 1 3 4 5
CONECT 3 2
CONECT 4 2
CONECT 5 2 6 7
CONECT 6 5
CONECT 7 5 8 32
CONECT 8 7 9 10
CONECT 9 8
CONECT 10 8 11 12
CONECT 11 10
CONECT 12 10 13 30
CONECT 13 12 14 15
CONECT 14 13
CONECT 15 13 16 17
CONECT 16 15
CONECT 17 15 18 28
CONECT 18 17 19 20
CONECT 19 18
CONECT 20 18 21 22
CONECT 21 20
CONECT 22 20 23 26
CONECT 23 22 24 25
CONECT 24 23
CONECT 25 23
CONECT 26 22 27 28
CONECT 27 26
CONECT 28 17 26 29
CONECT 29 28
CONECT 30 12 31 32
CONECT 31 30
CONECT 32 7 30 33
CONECT 33 32
END''',
'warfarin': '''HEADER UNCLASSIFIED 31-Aug-17
TITLE ALL ATOM STRUCTURE FOR MOLECULE WR0
AUTHOR GROMOS AUTOMATIC TOPOLOGY BUILDER REVISION 2017-07-03 14:53:07
AUTHOR 2 http://compbio.biosci.uq.edu.au/atb
HETATM 1 H16 AOOI 0 1.659 -3.906 2.643 1.00 0.00 H
HETATM 2 C14 AOOI 0 1.470 -3.838 1.570 1.00 0.00 C
HETATM 3 H14 AOOI 0 2.216 -4.415 1.013 1.00 0.00 H
HETATM 4 H15 AOOI 0 0.490 -4.283 1.351 1.00 0.00 H
HETATM 5 C13 AOOI 0 1.449 -2.394 1.132 1.00 0.00 C
HETATM 6 O4 AOOI 0 1.357 -1.493 1.963 1.00 0.00 O
HETATM 7 C12 AOOI 0 1.545 -2.133 -0.358 1.00 0.00 C
HETATM 8 H12 AOOI 0 2.555 -2.439 -0.668 1.00 0.00 H
HETATM 9 H13 AOOI 0 0.875 -2.837 -0.869 1.00 0.00 H
HETATM 10 C7 AOOI 0 1.236 -0.708 -0.875 1.00 0.00 C
HETATM 11 H11 AOOI 0 1.338 -0.813 -1.962 1.00 0.00 H
HETATM 12 C2 AOOI 0 -0.237 -0.338 -0.694 1.00 0.00 C
HETATM 13 C6 AOOI 0 -1.102 -0.728 -1.794 1.00 0.00 C
HETATM 14 O3 AOOI 0 -0.749 -1.333 -2.798 1.00 0.00 O
HETATM 15 C3 AOOI 0 -0.781 0.308 0.394 1.00 0.00 C
HETATM 16 O1 AOOI 0 -0.092 0.661 1.485 1.00 0.00 O
HETATM 17 H1 AOOI 0 0.699 0.070 1.581 1.00 0.00 H
HETATM 18 C4 AOOI 0 -2.188 0.668 0.417 1.00 0.00 C
HETATM 19 C11 AOOI 0 -2.797 1.349 1.488 1.00 0.00 C
HETATM 20 H5 AOOI 0 -2.188 1.643 2.336 1.00 0.00 H
HETATM 21 C10 AOOI 0 -4.156 1.634 1.455 1.00 0.00 C
HETATM 22 H4 AOOI 0 -4.620 2.160 2.284 1.00 0.00 H
HETATM 23 C9 AOOI 0 -4.932 1.233 0.355 1.00 0.00 C
HETATM 24 H3 AOOI 0 -5.997 1.448 0.335 1.00 0.00 H
HETATM 25 C1 AOOI 0 -4.352 0.554 -0.711 1.00 0.00 C
HETATM 26 H2 AOOI 0 -4.932 0.230 -1.569 1.00 0.00 H
HETATM 27 C5 AOOI 0 -2.983 0.280 -0.671 1.00 0.00 C
HETATM 28 O2 AOOI 0 -2.447 -0.399 -1.730 1.00 0.00 O
HETATM 29 C8 AOOI 0 2.237 0.391 -0.488 1.00 0.00 C
HETATM 30 C15 AOOI 0 1.995 1.712 -0.903 1.00 0.00 C
HETATM 31 H6 AOOI 0 1.068 1.948 -1.419 1.00 0.00 H
HETATM 32 C19 AOOI 0 3.447 0.123 0.166 1.00 0.00 C
HETATM 33 H10 AOOI 0 3.681 -0.880 0.505 1.00 0.00 H
HETATM 34 C18 AOOI 0 4.380 1.137 0.405 1.00 0.00 C
HETATM 35 H9 AOOI 0 5.309 0.898 0.917 1.00 0.00 H
HETATM 36 C17 AOOI 0 4.124 2.443 -0.013 1.00 0.00 C
HETATM 37 H8 AOOI 0 4.850 3.232 0.172 1.00 0.00 H
HETATM 38 C16 AOOI 0 2.922 2.726 -0.667 1.00 0.00 C
HETATM 39 H7 AOOI 0 2.706 3.739 -1.000 1.00 0.00 H
CONECT 1 2
CONECT 2 1 3 4 5
CONECT 3 2
CONECT 4 2
CONECT 5 2 6 7
CONECT 6 5
CONECT 7 5 8 9 10
CONECT 8 7
CONECT 9 7
CONECT 10 7 11 12 29
CONECT 11 10
CONECT 12 10 13 15
CONECT 13 12 14 28
CONECT 14 13
CONECT 15 12 16 18
CONECT 16 15 17
CONECT 17 16
CONECT 18 15 19 27
CONECT 19 18 20 21
CONECT 20 19
CONECT 21 19 22 23
CONECT 22 21
CONECT 23 21 24 25
CONECT 24 23
CONECT 25 23 26 27
CONECT 26 25
CONECT 27 18 25 28
CONECT 28 13 27
CONECT 29 10 30 32
CONECT 30 29 31 38
CONECT 31 30
CONECT 32 29 33 34
CONECT 33 32
CONECT 34 32 35 36
CONECT 35 34
CONECT 36 34 37 38
CONECT 37 36
CONECT 38 30 36 39
CONECT 39 38
END''',
'MZM': '''COMPND MZM
AUTHOR GENERATED BY OPEN BABEL 2.3.90
HETATM 1 N UNL 1 50.656 41.062 91.081 1.00 0.00 N
HETATM 2 S UNL 1 52.283 41.131 90.895 1.00 0.00 S
HETATM 3 O UNL 1 52.893 41.831 91.982 1.00 0.00 O
HETATM 4 O UNL 1 52.865 39.834 90.926 1.00 0.00 O
HETATM 5 C UNL 1 52.669 41.983 89.411 1.00 0.00 C
HETATM 6 S UNL 1 53.358 43.339 89.326 1.00 0.00 S
HETATM 7 C UNL 1 53.456 43.700 87.843 1.00 0.00 C
HETATM 8 N UNL 1 52.884 42.625 87.127 1.00 0.00 N
HETATM 9 C UNL 1 52.777 42.542 85.721 1.00 0.00 C
HETATM 10 N UNL 1 52.379 41.528 88.122 1.00 0.00 N
HETATM 11 N UNL 1 54.022 44.867 87.242 1.00 0.00 N
HETATM 12 C UNL 1 54.606 45.978 87.928 1.00 0.00 C
HETATM 13 O UNL 1 54.669 46.032 89.135 1.00 0.00 O
HETATM 14 C UNL 1 55.159 47.148 87.142 1.00 0.00 C
HETATM 15 H UNL 1 50.437 40.576 91.927 1.00 0.00 H
HETATM 16 H UNL 1 50.286 41.990 91.124 1.00 0.00 H
HETATM 17 H UNL 1 52.289 41.596 85.445 1.00 0.00 H
HETATM 18 H UNL 1 52.178 43.386 85.349 1.00 0.00 H
HETATM 19 H UNL 1 53.781 42.580 85.274 1.00 0.00 H
HETATM 20 H UNL 1 55.553 47.904 87.837 1.00 0.00 H
HETATM 21 H UNL 1 55.968 46.798 86.484 1.00 0.00 H
HETATM 22 H UNL 1 54.358 47.592 86.533 1.00 0.00 H
CONECT 1 15 16 2
CONECT 2 4 1 3 5
CONECT 3 2
CONECT 4 2
CONECT 5 2 6 10
CONECT 6 5 7
CONECT 7 6 8 11
CONECT 8 7 10 9
CONECT 9 8 17 18 19
CONECT 10 8 5
CONECT 11 7 12
CONECT 12 11 13 14
CONECT 13 12
CONECT 14 12 20 21 22
CONECT 15 1
CONECT 16 1
CONECT 17 9
CONECT 18 9
CONECT 19 9
CONECT 20 14
CONECT 21 14
CONECT 22 14
MASTER 0 0 0 0 0 0 0 0 22 0 22 0
END''',
'methylazide': '''HEADER UNCLASSIFIED 04-Apr-16
TITLE ALL ATOM STRUCTURE FOR MOLECULE UNK
AUTHOR GROMOS AUTOMATIC TOPOLOGY BUILDER REVISION 2016-03-31 14:08:37
AUTHOR 2 http://compbio.biosci.uq.edu.au/atb
HETATM 1 N3 _JR3 0 -1.670 -0.314 0.022 1.00 0.00 N
HETATM 2 N2 _JR3 0 -0.592 0.068 0.000 1.00 0.00 N
HETATM 3 N1 _JR3 0 0.512 0.614 -0.024 1.00 0.00 N
HETATM 4 C1 _JR3 0 1.686 -0.290 -0.003 1.00 0.00 C
HETATM 5 H1 _JR3 0 2.566 0.353 0.015 1.00 0.00 H
HETATM 6 H2 _JR3 0 1.683 -0.925 0.889 1.00 0.00 H
HETATM 7 H3 _JR3 0 1.717 -0.919 -0.900 1.00 0.00 H
CONECT 1 2
CONECT 2 1 3
CONECT 3 2 4
CONECT 4 3 5 6 7
CONECT 5 4
CONECT 6 4
CONECT 7 4
END''',
}
OPTIONS = {
'warfarin': {'total_number_hydrogens': 16, 'net_charge': 0},
}
if __name__ == '__main__':
for (molecule_name, pdb_str) in PDBS.items():
molecule = molecule_from_pdb_str(pdb_str, name=molecule_name)
if molecule.name in {'warfarin'}:
print(molecule.get_all_tautomers(**OPTIONS[molecule_name] if molecule_name in OPTIONS else {}))
else:
print(molecule.assign_bond_orders_and_charges_with_ILP(enforce_octet_rule=True))
print(molecule.write_graph(molecule_name, output_size=(int(2100 / 1.5), int(2970 / 1.5))))
if molecule_name == 'warfarin':
print(molecule)
print()
molecule = Molecule([Atom(index=1, element='C', valence=3, capped=True, coordinates=None), Atom(index=2, element='C', valence=3, capped=True, coordinates=None)], [(1,2)])
print(molecule.get_all_tautomers())
print(molecule.write_graph('ethene', output_size=(200, 200)))
molecule = Molecule([Atom(index=1, element='H', valence=1, capped=True, coordinates=None), Atom(index=2, element='O', valence=1, capped=True, coordinates=None)], [(1, 2)], netcharge=0, name='hydroxyl_radical')
print(molecule.assign_bond_orders_and_charges_with_ILP())
print(molecule.write_graph('', output_size=(200, 200)))
| {
"repo_name": "bertrand-caron/fragment_capping",
"path": "test_pdb.py",
"copies": "1",
"size": "14937",
"license": "mit",
"hash": -4169751144348392400,
"line_mean": 53.9154411765,
"line_max": 213,
"alpha_frac": 0.4397134632,
"autogenerated": false,
"ratio": 2.4386938775510205,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.33784073407510207,
"avg_score": null,
"num_lines": null
} |
from Fragment import *
from Matchset import *
from Neighbour import *
from GetCandidateMatchSet import GetCandidateMatchSet
from GetNeighbourhood import GetNeighbourhood
from GetGlobalConsistency import GetGlobalConsistency
from merge import getMergedFragment
from merge import *
from SmithWaterman import *
from transform import *
#to do list : complete MergeFragment() function
def GetMergedImage(F,countdown):
L = len(F)
W = L #number of unmerged fragments
iter=0
while (W!=1):
countdown.updatenumber(W)
print W
# print F
TF = []
F1 = []
F2 = []
for k in range(0,W):
F1.append(0)
F2.append(0)
# for i in range(0,W):
# TF.append(F[i].turning_angles)
# print "Before Candidate MatchSet"
M=None
M = GetCandidateMatchSet(F,iter)
iter+=1
# print "After Candidate MatchSet"
N = len(M)
if N == 0:
break
# for i in range(0,N):
# A = M[i]
# frag1 = A.fragment_1
# frag2 = A.fragment_2
# imagename1 = "Matchset_"+str(i+1)+"_fragment1"
# imagename2 = "Matchset_"+str(i+1)+"_fragment2"
# displayPartOfFragment(imagename1,A.fragment_1,A.match_1_start,A.match_1_end,700,700)
# displayPartOfFragment(imagename2,A.fragment_2,A.match_2_start,A.match_2_end,700,700)
# waitForESC()
# cv2.destroyAllWindows()
#G_list = GetNeighbourhood(M)
# print M
# print G_list
# print "After Nbr"
#x = GetGlobalConsistency(M,G_list)
#print x
# print "After glob cons"
print "N=" + str(len(M))
for i in range(0,N):
print("Merge")
print (M[i].i)
print (M[i].j)
if 1:
if F2[M[i].i] == 0 and F2[M[i].j] == 0:
try:
new_mergedfrag = getMergedFragment(M[i].fragment_1,M[i].fragment_2,M[i].match_1_start,M[i].match_1_end
,M[i].match_2_start,M[i].match_2_end,1)
#displayContour("mergeFragment"+str(i)+"dsfsdf",new_mergedfrag.points)
img=createFinalImage(new_mergedfrag,"tempname.png")
contour=getContour(img)
new_mergedfrag.points=contour
displayContour("Merged",new_mergedfrag.points)
# print(new_mergedfrag.points)
TF.append(getTurning(getN2FrmN12(new_mergedfrag)))
F2[M[i].i] = 1
F2[M[i].j] = 1
F[M[i].i] = None
F[M[i].j] = None
except:
pass
# print(getList(M[i].fragment_1))
# F.remove(F[M[i].i])
# print F
# print M[i].j
# if(M[i].j > M[i].i):
# F.remove(F[(M[i].j)-1])
# else:
# F.remove(F[(M[i].j)])
# F[M[i].i]=None
# F[M[i].j]=None
# print F1
for k in range(0,W):
if(F[k] is not None):
TF.append(F[k])
for i in range(0,len(TF)):
frag=TF[i]
#displayContour("Fragment"+str(i)+"dsfsdf",get1N2(frag.points))
# x=cv2.waitKey(0)
# if(x==27):
# cv2.destroyAllWindows()
# Frag=[]
# for x in F:
# if x!=None:
# Frag.append(x)
# F=Frag
F = TF
W = len(F)
return F
| {
"repo_name": "raltgz/OpenSoft14",
"path": "src/GetMergedImage.py",
"copies": "2",
"size": "3885",
"license": "apache-2.0",
"hash": 3652255582509922000,
"line_mean": 32.5,
"line_max": 126,
"alpha_frac": 0.4504504505,
"autogenerated": false,
"ratio": 3.462566844919786,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.49130172954197865,
"avg_score": null,
"num_lines": null
} |
from fragstats import *
## TODO 4/23/15-- break this hard-coded monster up into functions
## there is a lot of repeated pieces of code - tighten it up, shrink it
def summarize_fragstats(fragstats_df, extensive=False, g4=False, timecheck=False):
## fragstats_df is dataframe from make_fragstats_dataframe()
has2d = fragstats_df['has2d'] == 1
hascomp = fragstats_df['hascomp'] == 1
no2d = fragstats_df['has2d'] == 0
temponly = fragstats_df['hascomp'] == 0
n_molecules = len(fragstats_df['name'])
n_temp_only = sum(temponly)
n_comp = sum(hascomp)
n_no_2d = sum(no2d)
n_comp_has2d = sum(hascomp[has2d]) ## should be same as number with 2D
n_comp_no2d = sum(hascomp[no2d])
n_2d = sum(has2d)
print "n_molecules\t" + str(n_molecules)
print "n_template_only\t" + str(n_temp_only)
print "pct_template_only\t" + str(100.0*n_temp_only/n_molecules)
print "n_has_comp\t" + str(n_comp)
print "pct_has_comp\t" + str(100.0*n_comp/n_molecules)
print "n_has_2d\t" + str(n_2d)
print "pct_has_2d\t" + str(100.0*n_2d/n_molecules)
print "n_does_NOT_have_2d\t" + str(n_no_2d)
print "pct_does_NOT_have_2d\t" + str(100.0*n_no_2d/n_molecules)
print "pct_of_molecules_that_do_NOT_have_2D_because_template_only", 100.0*n_temp_only/n_no_2d
print "pct_of_molecules_that_do_NOT_have_2D_that_DO_have_comlement", 100.0*n_comp_no2d/n_no_2d
print "n_with_comp_that_DO_have_2D", n_comp_has2d, "(should be same as num with 2D)"
print "n_with_comp_that_do_NOT_have_2D", n_comp_no2d
print "pct_of_molecules_with_comp_that_DO_have_2D", 100.0*n_comp_has2d/n_comp
print "pct_of_molecules_with_comp_that_do_NOT_have_2D", 100.0*n_comp_no2d/n_comp
print
## MOLECULE
sum_molecule_lengths = sum(fragstats_df['fragsize'])
print "sum_molecule_lengths\t" + str(sum_molecule_lengths)
x = [25,50,75]
molecule_nx_values = NX(list(fragstats_df['fragsize']),x)
for e in x:
print "Molecule N%s\t%d" % (str(e), molecule_nx_values[e])
print "mean_molecule_size", np.mean(fragstats_df['fragsize'])
print "median_molecule_size", np.median(fragstats_df['fragsize'])
print "max_molecule_size", max(fragstats_df['fragsize'])
print "min_molecule_size", min(fragstats_df['fragsize'])
n_molecules_gt_10kb = sum(fragstats_df['fragsize'] > 10e3)
print "n_molecules_gt_10kb", n_molecules_gt_10kb
print "pct_molecules_gt_10kb", 100.0*n_molecules_gt_10kb/n_molecules
sum_molecules_gt_10kb = sum(fragstats_df['fragsize'][fragstats_df['fragsize'] > 10e3])
print "sum_molecules_gt_10kb", sum_molecules_gt_10kb
print "pct_summed_molecules_from_molecules_gt_10kb", 100.0*sum_molecules_gt_10kb/sum_molecule_lengths
n_molecules_gt_50kb = sum(fragstats_df['fragsize'] > 50e3)
print "n_molecules_gt_50kb", n_molecules_gt_50kb
print "pct_molecules_gt_50kb", 100.0*n_molecules_gt_50kb/n_molecules
sum_molecules_gt_50kb = sum(fragstats_df['fragsize'][fragstats_df['fragsize'] > 50e3])
print "sum_molecules_gt_50kb", sum_molecules_gt_50kb
print "pct_summed_molecules_from_molecules_gt_50kb", 100.0*sum_molecules_gt_50kb/sum_molecule_lengths
n_molecules_gt_100kb = sum(fragstats_df['fragsize'] > 100e3)
print "n_molecules_gt_100kb", n_molecules_gt_100kb
print "pct_molecules_gt_100kb", 100.0*n_molecules_gt_100kb/n_molecules
sum_molecules_gt_100kb = sum(fragstats_df['fragsize'][fragstats_df['fragsize'] > 100e3])
print "sum_molecules_gt_100kb", sum_molecules_gt_100kb
print "pct_summed_molecules_from_molecules_gt_100kb", 100.0*sum_molecules_gt_100kb/sum_molecule_lengths
print
## HQ 2D
q_2d_ge_9 = fragstats_df['meanscore2d'] >= 9
sum_HQ_2d_lengths = sum(fragstats_df['seqlen2d'][has2d][q_2d_ge_9])
print "sum_HQ_(Q>=9)_2d_lengths\t" + str(sum_HQ_2d_lengths)
twod_HQ_nx_values = NX(list(fragstats_df['seqlen2d'][has2d][q_2d_ge_9]),x)
for e in x:
print "HQ_2D N%s\t%d" % (str(e), twod_HQ_nx_values[e])
mean_HQ_2d_length = fragstats_df['seqlen2d'][has2d][q_2d_ge_9].mean()
print ("\t").join([str(e) for e in ["mean_HQ_2d_length", mean_HQ_2d_length]])
median_HQ_2d_length = fragstats_df['seqlen2d'][has2d][q_2d_ge_9].median()
print ("\t").join([str(e) for e in ["median_HQ_2d_length", median_HQ_2d_length]])
print
## 2D
sum_2d_lengths = sum(fragstats_df['seqlen2d'][has2d])
print "sum_2d_lengths\t" + str(sum_2d_lengths)
twod_nx_values = NX(list(fragstats_df['seqlen2d'][has2d]),x)
for e in x:
print "2D N%s\t%d" % (str(e), twod_nx_values[e])
mean_2d_length = fragstats_df['seqlen2d'][has2d].mean()
print ("\t").join([str(e) for e in ["mean_2d_length", mean_2d_length]])
median_2d_length = fragstats_df['seqlen2d'][has2d].median()
print ("\t").join([str(e) for e in ["median_2d_length", median_2d_length]])
print
## 1D
sum_1d_lengths = sum(fragstats_df['seqlentemp'].append(fragstats_df['seqlencomp'][hascomp]))
print "sum_1d_lengths\t" + str(sum_1d_lengths)
oned_nx_values = NX(list(fragstats_df['seqlentemp'].append(fragstats_df['seqlencomp'][hascomp])),x)
for e in x:
print "1D N%s\t%d" % (str(e), oned_nx_values[e])
mean_1d_length = fragstats_df['seqlentemp'].append(fragstats_df['seqlencomp'][hascomp]).mean()
print ("\t").join([str(e) for e in ["mean_1d_length", mean_1d_length]])
median_1d_length = fragstats_df['seqlentemp'].append(fragstats_df['seqlencomp'][hascomp]).median()
print ("\t").join([str(e) for e in ["median_1d_length", median_1d_length]])
print
## Template
sum_temp_lengths = sum(fragstats_df['seqlentemp'])
print "sum_template_lengths\t" + str(sum_temp_lengths)
temp_nx_values = NX(list(fragstats_df['seqlentemp']),x)
for e in x:
print "Template N%s\t%d" % (str(e), temp_nx_values[e])
mean_temp_length = fragstats_df['seqlentemp'].mean()
print ("\t").join([str(e) for e in ["mean_template_length", mean_temp_length]])
median_temp_length = fragstats_df['seqlentemp'].median()
print ("\t").join([str(e) for e in ["median_template_length", median_temp_length]])
print
## Complement
sum_comp_lengths = sum(fragstats_df['seqlencomp'][hascomp])
print "sum_complement_lengths\t" + str(sum_comp_lengths)
comp_nx_values = NX(list(fragstats_df['seqlencomp'][hascomp]),x)
for e in x:
print "Complement N%s\t%d" % (str(e), comp_nx_values[e])
mean_comp_length = fragstats_df['seqlencomp'][hascomp].mean()
print ("\t").join([str(e) for e in ["mean_complement_length", mean_comp_length]])
median_comp_length = fragstats_df['seqlencomp'][hascomp].median()
print ("\t").join([str(e) for e in ["median_complement_length", median_comp_length]])
print
## Max, Min, and Q filtering:
print ("\t").join(["metric", "length", "Q", "name", "read_type"])
## 2D -- TODO -- dont need to use logical indices after getting index (e.g. idxmax()) -- see 1D/T/C approach below
min_2d_length_index = fragstats_df['fragsize'][has2d].idxmin()
min_2d_length = fragstats_df['fragsize'][has2d][min_2d_length_index]
min_2d_Q = fragstats_df['meanscore2d'][has2d][min_2d_length_index]
min_2d_name = fragstats_df['name'][has2d][min_2d_length_index]
print ("\t").join([str(e) for e in ["min_2d_length", min_2d_length, min_2d_Q, min_2d_name, "2D"]])
max_2d_length_index = fragstats_df['fragsize'][has2d].idxmax()
max_2d_length = fragstats_df['fragsize'][has2d][max_2d_length_index]
max_2d_Q = fragstats_df['meanscore2d'][has2d][max_2d_length_index]
max_2d_name = fragstats_df['name'][has2d][max_2d_length_index]
print ("\t").join([str(e) for e in ["max_2d_length", max_2d_length, max_2d_Q, max_2d_name, "2D"]])
## q_2d_ge_9 = fragstats_df['meanscore2d'] >= 9
max_2d_Q_ge_9_index = fragstats_df['fragsize'][has2d][q_2d_ge_9].idxmax()
max_2d_Q_ge_9_length = fragstats_df['fragsize'][has2d][q_2d_ge_9][max_2d_Q_ge_9_index]
max_2d_Q_ge_9_Q = fragstats_df['meanscore2d'][has2d][q_2d_ge_9][max_2d_Q_ge_9_index]
max_2d_Q_ge_9_name = fragstats_df['name'][has2d][q_2d_ge_9][max_2d_Q_ge_9_index]
print ("\t").join([str(e) for e in ["max_2d_length_Q_ge_9", max_2d_Q_ge_9_length, max_2d_Q_ge_9_Q, max_2d_Q_ge_9_name, "2D"]])
q_2d_ge_8_5 = fragstats_df['meanscore2d'] >= 8.5
max_2d_Q_ge_8_5_index = fragstats_df['fragsize'][has2d][q_2d_ge_8_5].idxmax()
max_2d_Q_ge_8_5_length = fragstats_df['fragsize'][has2d][q_2d_ge_8_5][max_2d_Q_ge_8_5_index]
max_2d_Q_ge_8_5_Q = fragstats_df['meanscore2d'][has2d][q_2d_ge_8_5][max_2d_Q_ge_8_5_index]
max_2d_Q_ge_8_5_name = fragstats_df['name'][has2d][q_2d_ge_8_5][max_2d_Q_ge_8_5_index]
print ("\t").join([str(e) for e in ["max_2d_length_Q_ge_8.5", max_2d_Q_ge_8_5_length, max_2d_Q_ge_8_5_Q, max_2d_Q_ge_8_5_name, "2D"]])
q_2d_ge_8 = fragstats_df['meanscore2d'] >= 8
max_2d_Q_ge_8_index = fragstats_df['fragsize'][has2d][q_2d_ge_8].idxmax()
max_2d_Q_ge_8_length = fragstats_df['fragsize'][has2d][q_2d_ge_8][max_2d_Q_ge_8_index]
max_2d_Q_ge_8_Q = fragstats_df['meanscore2d'][has2d][q_2d_ge_8][max_2d_Q_ge_8_index]
max_2d_Q_ge_8_name = fragstats_df['name'][has2d][q_2d_ge_8][max_2d_Q_ge_8_index]
print ("\t").join([str(e) for e in ["max_2d_length_Q_ge_8", max_2d_Q_ge_8_length, max_2d_Q_ge_8_Q, max_2d_Q_ge_8_name, "2D"]])
q_2d_ge_7_5 = fragstats_df['meanscore2d'] >= 7.5
max_2d_Q_ge_7_5_index = fragstats_df['fragsize'][has2d][q_2d_ge_7_5].idxmax()
max_2d_Q_ge_7_5_length = fragstats_df['fragsize'][has2d][q_2d_ge_7_5][max_2d_Q_ge_7_5_index]
max_2d_Q_ge_7_5_Q = fragstats_df['meanscore2d'][has2d][q_2d_ge_7_5][max_2d_Q_ge_7_5_index]
max_2d_Q_ge_7_5_name = fragstats_df['name'][has2d][q_2d_ge_7_5][max_2d_Q_ge_7_5_index]
print ("\t").join([str(e) for e in ["max_2d_length_Q_ge_7.5", max_2d_Q_ge_7_5_length, max_2d_Q_ge_7_5_Q, max_2d_Q_ge_7_5_name, "2D"]])
print
## 1D, Template, Complement
#min
min_template_length_index = fragstats_df['seqlentemp'].idxmin()
min_complement_length_index = fragstats_df['seqlencomp'][hascomp].idxmin()
min_template_length = fragstats_df['seqlentemp'][min_template_length_index]
min_complement_length = fragstats_df['seqlencomp'][hascomp][min_complement_length_index]
min_template_Q = fragstats_df['meanscoretemp'][min_template_length_index]
min_complement_Q = fragstats_df['meanscorecomp'][hascomp][min_complement_length_index]
min_template_name = fragstats_df['name'][min_template_length_index]
min_complement_name = fragstats_df['name'][hascomp][min_complement_length_index]
#max
max_template_length_index = fragstats_df['seqlentemp'].idxmax()
max_complement_length_index = fragstats_df['seqlencomp'][hascomp].idxmax()
max_template_length = fragstats_df['seqlentemp'][max_template_length_index]
max_complement_length = fragstats_df['seqlencomp'][hascomp][max_complement_length_index]
max_template_Q = fragstats_df['meanscoretemp'][max_template_length_index]
max_complement_Q = fragstats_df['meanscorecomp'][hascomp][max_complement_length_index]
max_template_name = fragstats_df['name'][max_template_length_index]
max_complement_name = fragstats_df['name'][hascomp][max_complement_length_index]
#max, Q >= 4
q_template_ge_4 = fragstats_df['meanscoretemp'] >= 4
q_complement_ge_4 = fragstats_df['meanscorecomp'] >= 4
max_template_length_Q_ge_4_index = fragstats_df['seqlentemp'][q_template_ge_4].idxmax()
max_complement_length_Q_ge_4_index = fragstats_df['seqlencomp'][hascomp][q_complement_ge_4].idxmax()
max_template_Q_ge_4_length = fragstats_df['seqlentemp'][max_template_length_Q_ge_4_index]
max_complement_Q_ge_4_length = fragstats_df['seqlencomp'][hascomp][max_complement_length_Q_ge_4_index]
max_template_Q_ge_4_Q = fragstats_df['meanscoretemp'][max_template_length_Q_ge_4_index]
max_complement_Q_ge_4_Q = fragstats_df['meanscorecomp'][hascomp][max_complement_length_Q_ge_4_index]
max_template_Q_ge_4_name = fragstats_df['name'][max_template_length_Q_ge_4_index]
max_complement_Q_ge_4_name = fragstats_df['name'][hascomp][max_complement_length_Q_ge_4_index]
#max, Q >= 3.5
q_template_ge_3_5 = fragstats_df['meanscoretemp'] >= 3.5
q_complement_ge_3_5 = fragstats_df['meanscorecomp'] >= 3.5
max_template_length_Q_ge_3_5_index = fragstats_df['seqlentemp'][q_template_ge_3_5].idxmax()
max_complement_length_Q_ge_3_5_index = fragstats_df['seqlencomp'][hascomp][q_complement_ge_3_5].idxmax()
max_template_Q_ge_3_5_length = fragstats_df['seqlentemp'][max_template_length_Q_ge_3_5_index]
max_complement_Q_ge_3_5_length = fragstats_df['seqlencomp'][hascomp][max_complement_length_Q_ge_3_5_index]
max_template_Q_ge_3_5_Q = fragstats_df['meanscoretemp'][max_template_length_Q_ge_3_5_index]
max_complement_Q_ge_3_5_Q = fragstats_df['meanscorecomp'][hascomp][max_complement_length_Q_ge_3_5_index]
max_template_Q_ge_3_5_name = fragstats_df['name'][max_template_length_Q_ge_3_5_index]
max_complement_Q_ge_3_5_name = fragstats_df['name'][hascomp][max_complement_length_Q_ge_3_5_index]
#max, Q >= 3
q_template_ge_3 = fragstats_df['meanscoretemp'] >= 3
q_complement_ge_3 = fragstats_df['meanscorecomp'] >= 3
max_template_length_Q_ge_3_index = fragstats_df['seqlentemp'][q_template_ge_3].idxmax()
max_complement_length_Q_ge_3_index = fragstats_df['seqlencomp'][hascomp][q_complement_ge_3].idxmax()
max_template_Q_ge_3_length = fragstats_df['seqlentemp'][max_template_length_Q_ge_3_index]
max_complement_Q_ge_3_length = fragstats_df['seqlencomp'][hascomp][max_complement_length_Q_ge_3_index]
max_template_Q_ge_3_Q = fragstats_df['meanscoretemp'][max_template_length_Q_ge_3_index]
max_complement_Q_ge_3_Q = fragstats_df['meanscorecomp'][hascomp][max_complement_length_Q_ge_3_index]
max_template_Q_ge_3_name = fragstats_df['name'][max_template_length_Q_ge_3_index]
max_complement_Q_ge_3_name = fragstats_df['name'][hascomp][max_complement_length_Q_ge_3_index]
#max, Q >= 2.5
q_template_ge_2_5 = fragstats_df['meanscoretemp'] >= 2.5
q_complement_ge_2_5 = fragstats_df['meanscorecomp'] >= 2.5
max_template_length_Q_ge_2_5_index = fragstats_df['seqlentemp'][q_template_ge_2_5].idxmax()
max_complement_length_Q_ge_2_5_index = fragstats_df['seqlencomp'][hascomp][q_complement_ge_2_5].idxmax()
max_template_Q_ge_2_5_length = fragstats_df['seqlentemp'][max_template_length_Q_ge_2_5_index]
max_complement_Q_ge_2_5_length = fragstats_df['seqlencomp'][hascomp][max_complement_length_Q_ge_2_5_index]
max_template_Q_ge_2_5_Q = fragstats_df['meanscoretemp'][max_template_length_Q_ge_2_5_index]
max_complement_Q_ge_2_5_Q = fragstats_df['meanscorecomp'][hascomp][max_complement_length_Q_ge_2_5_index]
max_template_Q_ge_2_5_name = fragstats_df['name'][max_template_length_Q_ge_2_5_index]
max_complement_Q_ge_2_5_name = fragstats_df['name'][hascomp][max_complement_length_Q_ge_2_5_index]
# 1D
if min_template_length < min_complement_length:
print ("\t").join([str(e) for e in ["min_1d_length", min_template_length, min_template_Q, min_template_name, "template"]])
else:
print ("\t").join([str(e) for e in ["min_complement_length", min_complement_length, min_complement_Q, min_complement_name, "complement"]])
if max_template_length > max_complement_length:
print ("\t").join([str(e) for e in ["max_1d_length", max_template_length, max_template_Q, max_template_name, "template"]])
else:
print ("\t").join([str(e) for e in ["max_complement_length", max_complement_length, max_complement_Q, max_complement_name, "complement"]])
if max_template_Q_ge_4_length > max_complement_Q_ge_4_length:
print ("\t").join([str(e) for e in ["max_1d_Q_ge_4_length", max_template_Q_ge_4_length, max_template_Q_ge_4_Q, max_template_Q_ge_4_name, "template"]])
else:
print ("\t").join([str(e) for e in ["max_complement_Q_ge_4_length", max_complement_Q_ge_4_length, max_complement_Q_ge_4_Q, max_complement_Q_ge_4_name, "complement"]])
if max_template_Q_ge_3_5_length > max_complement_Q_ge_3_5_length:
print ("\t").join([str(e) for e in ["max_1d_Q_ge_3.5_length", max_template_Q_ge_3_5_length, max_template_Q_ge_3_5_Q, max_template_Q_ge_3_5_name, "template"]])
else:
print ("\t").join([str(e) for e in ["max_complement_Q_ge_3.5_length", max_complement_Q_ge_3_5_length, max_complement_Q_ge_3_5_Q, max_complement_Q_ge_3_5_name, "complement"]])
if max_template_Q_ge_3_length > max_complement_Q_ge_3_length:
print ("\t").join([str(e) for e in ["max_1d_Q_ge_3_length", max_template_Q_ge_3_length, max_template_Q_ge_3_Q, max_template_Q_ge_3_name, "template"]])
else:
print ("\t").join([str(e) for e in ["max_complement_Q_ge_3_length", max_complement_Q_ge_3_length, max_complement_Q_ge_3_Q, max_complement_Q_ge_3_name, "complement"]])
if max_template_Q_ge_2_5_length > max_complement_Q_ge_2_5_length:
print ("\t").join([str(e) for e in ["max_1d_Q_ge_2.5_length", max_template_Q_ge_2_5_length, max_template_Q_ge_2_5_Q, max_template_Q_ge_2_5_name, "template"]])
else:
print ("\t").join([str(e) for e in ["max_complement_Q_ge_2.5_length", max_complement_Q_ge_2_5_length, max_complement_Q_ge_2_5_Q, max_complement_Q_ge_2_5_name, "complement"]])
print
# Template
print ("\t").join([str(e) for e in ["min_template_length", min_template_length, min_template_Q, min_template_name, "template"]])
print ("\t").join([str(e) for e in ["max_template_length", max_template_length, max_template_Q, max_template_name, "template"]])
print ("\t").join([str(e) for e in ["max_template_Q_ge_4_length", max_template_Q_ge_4_length, max_template_Q_ge_4_Q, max_template_Q_ge_4_name, "template"]])
print ("\t").join([str(e) for e in ["max_template_Q_ge_3.5_length", max_template_Q_ge_3_5_length, max_template_Q_ge_3_5_Q, max_template_Q_ge_3_5_name, "template"]])
print ("\t").join([str(e) for e in ["max_template_Q_ge_3_length", max_template_Q_ge_3_length, max_template_Q_ge_3_Q, max_template_Q_ge_3_name, "template"]])
print ("\t").join([str(e) for e in ["max_template_Q_ge_2.5_length", max_template_Q_ge_2_5_length, max_template_Q_ge_2_5_Q, max_template_Q_ge_2_5_name, "template"]])
print
# Complement
print ("\t").join([str(e) for e in ["min_complement_length", min_complement_length, min_complement_Q, min_complement_name, "complement"]])
print ("\t").join([str(e) for e in ["max_complement_length", max_complement_length, max_complement_Q, max_complement_name, "complement"]])
print ("\t").join([str(e) for e in ["max_complement_Q_ge_4_length", max_complement_Q_ge_4_length, max_complement_Q_ge_4_Q, max_complement_Q_ge_4_name, "complement"]])
print ("\t").join([str(e) for e in ["max_complement_Q_ge_3.5_length", max_complement_Q_ge_3_5_length, max_complement_Q_ge_3_5_Q, max_complement_Q_ge_3_5_name, "complement"]])
print ("\t").join([str(e) for e in ["max_complement_Q_ge_3_length", max_complement_Q_ge_3_length, max_complement_Q_ge_3_Q, max_complement_Q_ge_3_name, "complement"]])
print ("\t").join([str(e) for e in ["max_complement_Q_ge_2.5_length", max_complement_Q_ge_2_5_length, max_complement_Q_ge_2_5_Q, max_complement_Q_ge_2_5_name, "complement"]])
print
## longest 10
## 2D
top10 = fragstats_df.sort(["seqlen2d","meanscore2d"], ascending=False)[:10][["seqlen2d","meanscore2d","name"]]
seqlens = list(top10["seqlen2d"])
meanscores = list(top10["meanscore2d"])
names = list(top10["name"])
print ("\t").join(["rank", "length", "Q", "name", "read_type", "analysis"])
for i in range(len(names)):
print ("\t").join([str(e) for e in [i+1, seqlens[i], meanscores[i], names[i], "2D", "Top_10_2D_reads"]])
print
## Template
top10 = fragstats_df.sort(["seqlentemp","meanscoretemp"], ascending=False)[:10][["seqlentemp","meanscoretemp","name"]]
seqlens = list(top10["seqlentemp"])
meanscores = list(top10["meanscoretemp"])
names = list(top10["name"])
print ("\t").join(["rank", "length", "Q", "name", "read_type", "analysis"])
for i in range(len(names)):
print ("\t").join([str(e) for e in [i+1, seqlens[i], meanscores[i], names[i], "template", "Top_10_Template_reads"]])
print
## Complement
top10 = fragstats_df.sort(["seqlencomp","meanscorecomp"], ascending=False)[:10][["seqlencomp","meanscorecomp","name"]]
seqlens = list(top10["seqlencomp"])
meanscores = list(top10["meanscorecomp"])
names = list(top10["name"])
print ("\t").join(["rank", "length", "Q", "name", "read_type", "analysis"])
for i in range(len(names)):
print ("\t").join([str(e) for e in [i+1, seqlens[i], meanscores[i], names[i], "complement", "Top_10_Complement_reads"]])
print
## Q score distribution
## 2D
mean_2d_Q = fragstats_df['meanscore2d'][has2d].mean()
median_2d_Q = fragstats_df['meanscore2d'][has2d].median()
std_2d_Q = fragstats_df['meanscore2d'][has2d].std()
min_2d_Q_idx = fragstats_df['meanscore2d'][has2d].idxmin()
max_2d_Q_idx = fragstats_df['meanscore2d'][has2d].idxmax()
min_2d_Q = fragstats_df['meanscore2d'][min_2d_Q_idx]
max_2d_Q = fragstats_df['meanscore2d'][max_2d_Q_idx]
min_2d_Q_length = fragstats_df['seqlen2d'][min_2d_Q_idx]
max_2d_Q_length = fragstats_df['seqlen2d'][max_2d_Q_idx]
min_2d_Q_name = fragstats_df['name'][min_2d_Q_idx]
max_2d_Q_name = fragstats_df['name'][max_2d_Q_idx]
## Template
mean_temp_Q = fragstats_df['meanscoretemp'].mean()
median_temp_Q = fragstats_df['meanscoretemp'].median()
std_temp_Q = fragstats_df['meanscoretemp'].std()
min_temp_Q_idx = fragstats_df['meanscoretemp'].idxmin()
max_temp_Q_idx = fragstats_df['meanscoretemp'].idxmax()
min_temp_Q = fragstats_df['meanscoretemp'][min_temp_Q_idx]
max_temp_Q = fragstats_df['meanscoretemp'][max_temp_Q_idx]
min_temp_Q_length = fragstats_df['seqlentemp'][min_temp_Q_idx]
max_temp_Q_length = fragstats_df['seqlentemp'][max_temp_Q_idx]
min_temp_Q_name = fragstats_df['name'][min_temp_Q_idx]
max_temp_Q_name = fragstats_df['name'][max_temp_Q_idx]
## Complement
mean_comp_Q = fragstats_df['meanscorecomp'][hascomp].mean()
median_comp_Q = fragstats_df['meanscorecomp'][hascomp].median()
std_comp_Q = fragstats_df['meanscorecomp'][hascomp].std()
min_comp_Q_idx = fragstats_df['meanscorecomp'][hascomp].idxmin()
max_comp_Q_idx = fragstats_df['meanscorecomp'][hascomp].idxmax()
min_comp_Q = fragstats_df['meanscorecomp'][min_comp_Q_idx]
max_comp_Q = fragstats_df['meanscorecomp'][max_comp_Q_idx]
min_comp_Q_length = fragstats_df['seqlencomp'][min_comp_Q_idx]
max_comp_Q_length = fragstats_df['seqlencomp'][max_comp_Q_idx]
min_comp_Q_name = fragstats_df['name'][min_comp_Q_idx]
max_comp_Q_name = fragstats_df['name'][max_comp_Q_idx]
## 1D
mean_1d_Q = fragstats_df['meanscoretemp'].append(fragstats_df['meanscorecomp'][hascomp]).mean()
median_1d_Q = fragstats_df['meanscoretemp'].append(fragstats_df['meanscorecomp'][hascomp]).median()
std_1d_Q = fragstats_df['meanscoretemp'].append(fragstats_df['meanscorecomp'][hascomp]).std()
if min_temp_Q < min_comp_Q:
min_1d_Q_idx = min_temp_Q_idx
min_1d_Q = min_temp_Q
min_1d_Q_length = min_temp_Q_length
min_1d_Q_name = min_temp_Q_name
min_1d_read_type = "template"
else:
min_1d_Q_idx = min_comp_Q_idx
min_1d_Q = min_comp_Q
min_1d_Q_length = min_comp_Q_length
min_1d_Q_name = min_comp_Q_name
min_1d_read_type = "complement"
if max_temp_Q > max_comp_Q:
max_1d_Q_idx = max_temp_Q_idx
max_1d_Q = max_temp_Q
max_1d_Q_length = max_temp_Q_length
max_1d_Q_name = max_temp_Q_name
max_1d_read_type = "template"
else:
max_1d_Q_idx = max_comp_Q_idx
max_1d_Q = max_comp_Q
max_1d_Q_length = max_comp_Q_length
max_1d_Q_name = max_comp_Q_name
max_1d_read_type = "complement"
## print ("\t").join(["read_type", "mean_Q", "median_Q", "std_dev_Q", "min_Q", "max_Q", "read_length_min_Q", "read_length_max_Q", "read_name_min_Q", "read_name_max_Q"])
## print ("\t").join([str(e) for e in ["2D", mean_2d_Q, median_2d_Q, std_2d_Q, min_2d_Q, max_2d_Q]])
## print ("\t").join([str(e) for e in ["1D", mean_1d_Q, median_1d_Q, std_1d_Q, min_1d_Q, max_1d_Q]])
## print ("\t").join([str(e) for e in ["Template", mean_temp_Q, median_temp_Q, std_temp_Q, min_temp_Q, max_temp_Q]])
## print ("\t").join([str(e) for e in ["Complement", mean_comp_Q, median_comp_Q, std_comp_Q, min_comp_Q, max_comp_Q]])
## print
print ("\t").join(["metric", "Q", "length", "read_type", "name"])
print ("\t").join([str(e) for e in ["median_Q_2d", median_2d_Q, "-", "2D", "-"]])
print ("\t").join([str(e) for e in ["mean_Q_2d", mean_2d_Q, "-", "2D", "-"]])
print ("\t").join([str(e) for e in ["std_dev_Q_2d", std_2d_Q, "-", "2D", "-"]])
print ("\t").join([str(e) for e in ["min_Q_2d", min_2d_Q, min_2d_Q_length, "2D", min_2d_Q_name]])
print ("\t").join([str(e) for e in ["max_Q_2d", max_2d_Q, max_2d_Q_length, "2D", max_2d_Q_name]])
print
print ("\t").join(["metric", "Q", "length", "read_type", "name"])
print ("\t").join([str(e) for e in ["median_Q_1d", median_1d_Q, "-", "1D", "-"]])
print ("\t").join([str(e) for e in ["mean_Q_1d", mean_1d_Q, "-", "1D", "-"]])
print ("\t").join([str(e) for e in ["std_dev_Q_1d", std_1d_Q, "-", "1D", "-"]])
print ("\t").join([str(e) for e in ["min_Q_1d", min_1d_Q, min_1d_Q_length, min_1d_read_type, min_1d_Q_name]])
print ("\t").join([str(e) for e in ["max_Q_1d", max_1d_Q, max_1d_Q_length, max_1d_read_type, max_1d_Q_name]])
print
print ("\t").join(["metric", "Q", "length", "read_type", "name"])
print ("\t").join([str(e) for e in ["median_Q_template", median_temp_Q, "-", "template", "-"]])
print ("\t").join([str(e) for e in ["mean_Q_template", mean_temp_Q, "-", "template", "-"]])
print ("\t").join([str(e) for e in ["std_dev_Q_template", std_temp_Q, "-", "template", "-"]])
print ("\t").join([str(e) for e in ["min_Q_template", min_temp_Q, min_temp_Q_length, "template", min_temp_Q_name]])
print ("\t").join([str(e) for e in ["max_Q_template", max_temp_Q, max_temp_Q_length, "template", max_temp_Q_name]])
print
print ("\t").join(["metric", "Q", "length", "read_type", "name"])
print ("\t").join([str(e) for e in ["median_Q_complement", median_comp_Q, "-", "complement", "-"]])
print ("\t").join([str(e) for e in ["mean_Q_complement", mean_comp_Q, "-", "complement", "-"]])
print ("\t").join([str(e) for e in ["std_dev_Q_complement", std_comp_Q, "-", "complement", "-"]])
print ("\t").join([str(e) for e in ["min_Q_complement", min_comp_Q, min_comp_Q_length, "complement", min_comp_Q_name]])
print ("\t").join([str(e) for e in ["max_Q_complement", max_comp_Q, max_comp_Q_length, "complement", max_comp_Q_name]])
print
## RATIO
print "Template:Complement events ratio stats:"
mean_tc_ratio_hascomp = fragstats_df['log2_tc_ratio'][fragstats_df['hascomp'] == 1].mean()
min_tc_ratio_hascomp = fragstats_df['log2_tc_ratio'][fragstats_df['hascomp'] == 1].min()
max_tc_ratio_hascomp = fragstats_df['log2_tc_ratio'][fragstats_df['hascomp'] == 1].max()
mean_tc_ratio_has2d = fragstats_df['log2_tc_ratio'][fragstats_df['has2d'] == 1].mean()
min_tc_ratio_has2d = fragstats_df['log2_tc_ratio'][fragstats_df['has2d'] == 1].min()
max_tc_ratio_has2d = fragstats_df['log2_tc_ratio'][fragstats_df['has2d'] == 1].max()
mean_tc_ratio_hascomp_no2d = fragstats_df['log2_tc_ratio'][fragstats_df['hascomp'] == 1][fragstats_df['has2d'] == 0].mean()
min_tc_ratio_hascomp_no2d = fragstats_df['log2_tc_ratio'][fragstats_df['hascomp'] == 1][fragstats_df['has2d'] == 0].min()
max_tc_ratio_hascomp_no2d = fragstats_df['log2_tc_ratio'][fragstats_df['hascomp'] == 1][fragstats_df['has2d'] == 0].max()
print "mean_log2_tc_ratio_hascomp\t" + str(mean_tc_ratio_hascomp)
print "min_log2_tc_ratio_hascomp\t" + str(min_tc_ratio_hascomp)
print "max_log2_tc_ratio_hascomp\t" + str(max_tc_ratio_hascomp)
print "mean_log2_tc_ratio_has2d\t" + str(mean_tc_ratio_has2d)
print "min_log2_tc_ratio_has2d\t" + str(min_tc_ratio_has2d)
print "max_log2_tc_ratio_has2d\t" + str(max_tc_ratio_has2d)
print "mean_log2_tc_ratio_hascomp_no2d\t" + str(mean_tc_ratio_hascomp_no2d)
print "min_log2_tc_ratio_hascomp_no2d\t" + str(min_tc_ratio_hascomp_no2d)
print "max_log2_tc_ratio_hascomp_no2d\t" + str(max_tc_ratio_hascomp_no2d)
print
if extensive:
#slope
mean_slope = fragstats_df['slope'].mean()
median_slope = fragstats_df['slope'].median()
sd_slope = fragstats_df['slope'].std()
min_slope_idx = fragstats_df['slope'].idxmin()
max_slope_idx = fragstats_df['slope'].idxmax()
print "median_slope", median_slope
print "mean_slope", mean_slope
print "sd_slope", sd_slope
print
print ("\t").join(["#metric", "slope_value", "numevents_from_molecule", "seq_len_2d", "seq_len_template", "seq_len_complement", "Q_2d", "Q_template", "Q_complement", "name"])
print "min_slope", fragstats_df['slope'][min_slope_idx], fragstats_df['numevents'][min_slope_idx], nonetodash(fragstats_df['seqlen2d'][min_slope_idx]), nonetodash(fragstats_df['seqlentemp'][min_slope_idx]), nonetodash(fragstats_df['seqlencomp'][min_slope_idx]), nonetodash(fragstats_df['meanscore2d'][min_slope_idx]), nonetodash(fragstats_df['meanscoretemp'][min_slope_idx]), nonetodash(fragstats_df['meanscorecomp'][min_slope_idx]), fragstats_df['name'][min_slope_idx]
print "max_slope", fragstats_df['slope'][max_slope_idx], fragstats_df['numevents'][max_slope_idx], nonetodash(fragstats_df['seqlen2d'][max_slope_idx]), nonetodash(fragstats_df['seqlentemp'][max_slope_idx]), nonetodash(fragstats_df['seqlencomp'][max_slope_idx]), nonetodash(fragstats_df['meanscore2d'][max_slope_idx]), nonetodash(fragstats_df['meanscoretemp'][max_slope_idx]), nonetodash(fragstats_df['meanscorecomp'][max_slope_idx]), fragstats_df['name'][max_slope_idx]
print
# t moves -- NOTE: sum(all moves) = num_called_events
# thus, 100*moves_x/num_called_events is percent of given move x
med_pct_tevents_move_0 = 100.0*(fragstats_df['tmove_0']/fragstats_df['numcalledeventstemp']).median()
mean_pct_tevents_move_0 = 100.0*(fragstats_df['tmove_0']/fragstats_df['numcalledeventstemp']).mean()
std_pct_tevents_move_0 = 100.0*(fragstats_df['tmove_0']/fragstats_df['numcalledeventstemp']).std()
minidx_pct_tevents_move_0 = (fragstats_df['tmove_0']/fragstats_df['numcalledeventstemp']).idxmin()
maxidx_pct_tevents_move_0 = (fragstats_df['tmove_0']/fragstats_df['numcalledeventstemp']).idxmax()
min_pct_tevents_move_0 = 100.0*(fragstats_df['tmove_0']/fragstats_df['numcalledeventstemp']).min()
max_pct_tevents_move_0 = 100.0*(fragstats_df['tmove_0']/fragstats_df['numcalledeventstemp']).max()
med_pct_tevents_move_1 = 100.0*(fragstats_df['tmove_1']/fragstats_df['numcalledeventstemp']).median()
mean_pct_tevents_move_1 = 100.0*(fragstats_df['tmove_1']/fragstats_df['numcalledeventstemp']).mean()
std_pct_tevents_move_1 = 100.0*(fragstats_df['tmove_1']/fragstats_df['numcalledeventstemp']).std()
minidx_pct_tevents_move_1 = (fragstats_df['tmove_1']/fragstats_df['numcalledeventstemp']).idxmin()
maxidx_pct_tevents_move_1 = (fragstats_df['tmove_1']/fragstats_df['numcalledeventstemp']).idxmax()
min_pct_tevents_move_1 = 100.0*(fragstats_df['tmove_1']/fragstats_df['numcalledeventstemp']).min()
max_pct_tevents_move_1 = 100.0*(fragstats_df['tmove_1']/fragstats_df['numcalledeventstemp']).max()
med_pct_tevents_move_2 = 100.0*(fragstats_df['tmove_2']/fragstats_df['numcalledeventstemp']).median()
mean_pct_tevents_move_2 = 100.0*(fragstats_df['tmove_2']/fragstats_df['numcalledeventstemp']).mean()
std_pct_tevents_move_2 = 100.0*(fragstats_df['tmove_2']/fragstats_df['numcalledeventstemp']).std()
minidx_pct_tevents_move_2 = (fragstats_df['tmove_2']/fragstats_df['numcalledeventstemp']).idxmin()
maxidx_pct_tevents_move_2 = (fragstats_df['tmove_2']/fragstats_df['numcalledeventstemp']).idxmax()
min_pct_tevents_move_2 = 100.0*(fragstats_df['tmove_2']/fragstats_df['numcalledeventstemp']).min()
max_pct_tevents_move_2 = 100.0*(fragstats_df['tmove_2']/fragstats_df['numcalledeventstemp']).max()
med_pct_tevents_move_3 = 100.0*(fragstats_df['tmove_3']/fragstats_df['numcalledeventstemp']).median()
mean_pct_tevents_move_3 = 100.0*(fragstats_df['tmove_3']/fragstats_df['numcalledeventstemp']).mean()
std_pct_tevents_move_3 = 100.0*(fragstats_df['tmove_3']/fragstats_df['numcalledeventstemp']).std()
minidx_pct_tevents_move_3 = (fragstats_df['tmove_3']/fragstats_df['numcalledeventstemp']).idxmin()
maxidx_pct_tevents_move_3 = (fragstats_df['tmove_3']/fragstats_df['numcalledeventstemp']).idxmax()
min_pct_tevents_move_3 = 100.0*(fragstats_df['tmove_3']/fragstats_df['numcalledeventstemp']).min()
max_pct_tevents_move_3 = 100.0*(fragstats_df['tmove_3']/fragstats_df['numcalledeventstemp']).max()
med_pct_tevents_move_4 = 100.0*(fragstats_df['tmove_4']/fragstats_df['numcalledeventstemp']).median()
mean_pct_tevents_move_4 = 100.0*(fragstats_df['tmove_4']/fragstats_df['numcalledeventstemp']).mean()
std_pct_tevents_move_4 = 100.0*(fragstats_df['tmove_4']/fragstats_df['numcalledeventstemp']).std()
minidx_pct_tevents_move_4 = (fragstats_df['tmove_4']/fragstats_df['numcalledeventstemp']).idxmin()
maxidx_pct_tevents_move_4 = (fragstats_df['tmove_4']/fragstats_df['numcalledeventstemp']).idxmax()
min_pct_tevents_move_4 = 100.0*(fragstats_df['tmove_4']/fragstats_df['numcalledeventstemp']).min()
max_pct_tevents_move_4 = 100.0*(fragstats_df['tmove_4']/fragstats_df['numcalledeventstemp']).max()
med_pct_tevents_move_5 = 100.0*(fragstats_df['tmove_5']/fragstats_df['numcalledeventstemp']).median()
mean_pct_tevents_move_5 = 100.0*(fragstats_df['tmove_5']/fragstats_df['numcalledeventstemp']).mean()
std_pct_tevents_move_5 = 100.0*(fragstats_df['tmove_5']/fragstats_df['numcalledeventstemp']).std()
minidx_pct_tevents_move_5 = (fragstats_df['tmove_5']/fragstats_df['numcalledeventstemp']).idxmin()
maxidx_pct_tevents_move_5 = (fragstats_df['tmove_5']/fragstats_df['numcalledeventstemp']).idxmax()
min_pct_tevents_move_5 = 100.0*(fragstats_df['tmove_5']/fragstats_df['numcalledeventstemp']).min()
max_pct_tevents_move_5 = 100.0*(fragstats_df['tmove_5']/fragstats_df['numcalledeventstemp']).max()
# c moves -- add hascomp?
med_pct_cevents_move_0 = 100.0*(fragstats_df['cmove_0']/fragstats_df['numcalledeventscomp']).median()
mean_pct_cevents_move_0 = 100.0*(fragstats_df['cmove_0']/fragstats_df['numcalledeventscomp']).mean()
std_pct_cevents_move_0 = 100.0*(fragstats_df['cmove_0']/fragstats_df['numcalledeventscomp']).std()
minidx_pct_cevents_move_0 = (fragstats_df['cmove_0']/fragstats_df['numcalledeventscomp']).idxmin()
maxidx_pct_cevents_move_0 = (fragstats_df['cmove_0']/fragstats_df['numcalledeventscomp']).idxmax()
min_pct_cevents_move_0 = 100.0*(fragstats_df['cmove_0']/fragstats_df['numcalledeventscomp']).min()
max_pct_cevents_move_0 = 100.0*(fragstats_df['cmove_0']/fragstats_df['numcalledeventscomp']).max()
med_pct_cevents_move_1 = 100.0*(fragstats_df['cmove_1']/fragstats_df['numcalledeventscomp']).median()
mean_pct_cevents_move_1 = 100.0*(fragstats_df['cmove_1']/fragstats_df['numcalledeventscomp']).mean()
std_pct_cevents_move_1 = 100.0*(fragstats_df['cmove_1']/fragstats_df['numcalledeventscomp']).std()
minidx_pct_cevents_move_1 = (fragstats_df['cmove_1']/fragstats_df['numcalledeventscomp']).idxmin()
maxidx_pct_cevents_move_1 = (fragstats_df['cmove_1']/fragstats_df['numcalledeventscomp']).idxmax()
min_pct_cevents_move_1 = 100.0*(fragstats_df['cmove_1']/fragstats_df['numcalledeventscomp']).min()
max_pct_cevents_move_1 = 100.0*(fragstats_df['cmove_1']/fragstats_df['numcalledeventscomp']).max()
med_pct_cevents_move_2 = 100.0*(fragstats_df['cmove_2']/fragstats_df['numcalledeventscomp']).median()
mean_pct_cevents_move_2 = 100.0*(fragstats_df['cmove_2']/fragstats_df['numcalledeventscomp']).mean()
std_pct_cevents_move_2 = 100.0*(fragstats_df['cmove_2']/fragstats_df['numcalledeventscomp']).std()
minidx_pct_cevents_move_2 = (fragstats_df['cmove_2']/fragstats_df['numcalledeventscomp']).idxmin()
maxidx_pct_cevents_move_2 = (fragstats_df['cmove_2']/fragstats_df['numcalledeventscomp']).idxmax()
min_pct_cevents_move_2 = 100.0*(fragstats_df['cmove_2']/fragstats_df['numcalledeventscomp']).min()
max_pct_cevents_move_2 = 100.0*(fragstats_df['cmove_2']/fragstats_df['numcalledeventscomp']).max()
med_pct_cevents_move_3 = 100.0*(fragstats_df['cmove_3']/fragstats_df['numcalledeventscomp']).median()
mean_pct_cevents_move_3 = 100.0*(fragstats_df['cmove_3']/fragstats_df['numcalledeventscomp']).mean()
std_pct_cevents_move_3 = 100.0*(fragstats_df['cmove_3']/fragstats_df['numcalledeventscomp']).std()
minidx_pct_cevents_move_3 = (fragstats_df['cmove_3']/fragstats_df['numcalledeventscomp']).idxmin()
maxidx_pct_cevents_move_3 = (fragstats_df['cmove_3']/fragstats_df['numcalledeventscomp']).idxmax()
min_pct_cevents_move_3 = 100.0*(fragstats_df['cmove_3']/fragstats_df['numcalledeventscomp']).min()
max_pct_cevents_move_3 = 100.0*(fragstats_df['cmove_3']/fragstats_df['numcalledeventscomp']).max()
med_pct_cevents_move_4 = 100.0*(fragstats_df['cmove_4']/fragstats_df['numcalledeventscomp']).median()
mean_pct_cevents_move_4 = 100.0*(fragstats_df['cmove_4']/fragstats_df['numcalledeventscomp']).mean()
std_pct_cevents_move_4 = 100.0*(fragstats_df['cmove_4']/fragstats_df['numcalledeventscomp']).std()
minidx_pct_cevents_move_4 = (fragstats_df['cmove_4']/fragstats_df['numcalledeventscomp']).idxmin()
maxidx_pct_cevents_move_4 = (fragstats_df['cmove_4']/fragstats_df['numcalledeventscomp']).idxmax()
min_pct_cevents_move_4 = 100.0*(fragstats_df['cmove_4']/fragstats_df['numcalledeventscomp']).min()
max_pct_cevents_move_4 = 100.0*(fragstats_df['cmove_4']/fragstats_df['numcalledeventscomp']).max()
med_pct_cevents_move_5 = 100.0*(fragstats_df['cmove_5']/fragstats_df['numcalledeventscomp']).median()
mean_pct_cevents_move_5 = 100.0*(fragstats_df['cmove_5']/fragstats_df['numcalledeventscomp']).mean()
std_pct_cevents_move_5 = 100.0*(fragstats_df['cmove_5']/fragstats_df['numcalledeventscomp']).std()
minidx_pct_cevents_move_5 = (fragstats_df['cmove_5']/fragstats_df['numcalledeventscomp']).idxmin()
maxidx_pct_cevents_move_5 = (fragstats_df['cmove_5']/fragstats_df['numcalledeventscomp']).idxmax()
min_pct_cevents_move_5 = 100.0*(fragstats_df['cmove_5']/fragstats_df['numcalledeventscomp']).min()
max_pct_cevents_move_5 = 100.0*(fragstats_df['cmove_5']/fragstats_df['numcalledeventscomp']).max()
print ("\t").join(["metric", "median", "mean", "std_dev", "min", "max"])
print ("\t").join([str(e) for e in ["template_0_moves", med_pct_tevents_move_0, mean_pct_tevents_move_0, std_pct_tevents_move_0, min_pct_tevents_move_0, max_pct_tevents_move_0]])
print ("\t").join([str(e) for e in ["template_1_moves", med_pct_tevents_move_1, mean_pct_tevents_move_1, std_pct_tevents_move_1, min_pct_tevents_move_1, max_pct_tevents_move_1]])
print ("\t").join([str(e) for e in ["template_2_moves", med_pct_tevents_move_2, mean_pct_tevents_move_2, std_pct_tevents_move_2, min_pct_tevents_move_2, max_pct_tevents_move_2]])
print ("\t").join([str(e) for e in ["template_3_moves", med_pct_tevents_move_3, mean_pct_tevents_move_3, std_pct_tevents_move_3, min_pct_tevents_move_3, max_pct_tevents_move_3]])
print ("\t").join([str(e) for e in ["template_4_moves", med_pct_tevents_move_4, mean_pct_tevents_move_4, std_pct_tevents_move_4, min_pct_tevents_move_4, max_pct_tevents_move_4]])
print ("\t").join([str(e) for e in ["template_5_moves", med_pct_tevents_move_5, mean_pct_tevents_move_5, std_pct_tevents_move_5, min_pct_tevents_move_5, max_pct_tevents_move_5]])
print ("\t").join([str(e) for e in ["complement_0_moves", med_pct_cevents_move_0, mean_pct_cevents_move_0, std_pct_cevents_move_0, min_pct_cevents_move_0, max_pct_cevents_move_0]])
print ("\t").join([str(e) for e in ["complement_1_moves", med_pct_cevents_move_1, mean_pct_cevents_move_1, std_pct_cevents_move_1, min_pct_cevents_move_1, max_pct_cevents_move_1]])
print ("\t").join([str(e) for e in ["complement_2_moves", med_pct_cevents_move_2, mean_pct_cevents_move_2, std_pct_cevents_move_2, min_pct_cevents_move_2, max_pct_cevents_move_2]])
print ("\t").join([str(e) for e in ["complement_3_moves", med_pct_cevents_move_3, mean_pct_cevents_move_3, std_pct_cevents_move_3, min_pct_cevents_move_3, max_pct_cevents_move_3]])
print ("\t").join([str(e) for e in ["complement_4_moves", med_pct_cevents_move_4, mean_pct_cevents_move_4, std_pct_cevents_move_4, min_pct_cevents_move_4, max_pct_cevents_move_4]])
print ("\t").join([str(e) for e in ["complement_5_moves", med_pct_cevents_move_5, mean_pct_cevents_move_5, std_pct_cevents_move_5, min_pct_cevents_move_5, max_pct_cevents_move_5]])
print
print minidx_pct_tevents_move_0, maxidx_pct_tevents_move_0
minidx_pct_tevents_move_0, maxidx_pct_tevents_move_0 = int(minidx_pct_tevents_move_0), int(maxidx_pct_tevents_move_0)
print ("\t").join(["#metric", "strand", "value", "numevents_from_molecule", "seq_len_2d", "seq_len_template", "seq_len_complement", "Q_2d", "Q_template", "Q_complement", "name"])
print "min_pct_0_moves", "template", min_pct_tevents_move_0, fragstats_df['numevents'][minidx_pct_tevents_move_0], nonetodash(fragstats_df['seqlen2d'][minidx_pct_tevents_move_0]), nonetodash(fragstats_df['seqlentemp'][minidx_pct_tevents_move_0]), nonetodash(fragstats_df['seqlencomp'][minidx_pct_tevents_move_0]), nonetodash(fragstats_df['meanscore2d'][minidx_pct_tevents_move_0]), nonetodash(fragstats_df['meanscoretemp'][minidx_pct_tevents_move_0]), nonetodash(fragstats_df['meanscorecomp'][minidx_pct_tevents_move_0]), fragstats_df['name'][minidx_pct_tevents_move_0]
print "max_pct_0_moves", "template", max_pct_tevents_move_0, fragstats_df['numevents'][maxidx_pct_tevents_move_0], nonetodash(fragstats_df['seqlen2d'][maxidx_pct_tevents_move_0]), nonetodash(fragstats_df['seqlentemp'][maxidx_pct_tevents_move_0]), nonetodash(fragstats_df['seqlencomp'][maxidx_pct_tevents_move_0]), nonetodash(fragstats_df['meanscore2d'][maxidx_pct_tevents_move_0]), nonetodash(fragstats_df['meanscoretemp'][maxidx_pct_tevents_move_0]), nonetodash(fragstats_df['meanscorecomp'][maxidx_pct_tevents_move_0]), fragstats_df['name'][maxidx_pct_tevents_move_0]
print "min_pct_1_moves", "template", min_pct_tevents_move_1, fragstats_df['numevents'][minidx_pct_tevents_move_1], nonetodash(fragstats_df['seqlen2d'][minidx_pct_tevents_move_1]), nonetodash(fragstats_df['seqlentemp'][minidx_pct_tevents_move_1]), nonetodash(fragstats_df['seqlencomp'][minidx_pct_tevents_move_1]), nonetodash(fragstats_df['meanscore2d'][minidx_pct_tevents_move_1]), nonetodash(fragstats_df['meanscoretemp'][minidx_pct_tevents_move_1]), nonetodash(fragstats_df['meanscorecomp'][minidx_pct_tevents_move_1]), fragstats_df['name'][minidx_pct_tevents_move_1]
print "max_pct_1_moves", "template", max_pct_tevents_move_1, fragstats_df['numevents'][maxidx_pct_tevents_move_1], nonetodash(fragstats_df['seqlen2d'][maxidx_pct_tevents_move_1]), nonetodash(fragstats_df['seqlentemp'][maxidx_pct_tevents_move_1]), nonetodash(fragstats_df['seqlencomp'][maxidx_pct_tevents_move_1]), nonetodash(fragstats_df['meanscore2d'][maxidx_pct_tevents_move_1]), nonetodash(fragstats_df['meanscoretemp'][maxidx_pct_tevents_move_1]), nonetodash(fragstats_df['meanscorecomp'][maxidx_pct_tevents_move_1]), fragstats_df['name'][maxidx_pct_tevents_move_1]
print "min_pct_2_moves", "template", min_pct_tevents_move_2, fragstats_df['numevents'][minidx_pct_tevents_move_2], nonetodash(fragstats_df['seqlen2d'][minidx_pct_tevents_move_2]), nonetodash(fragstats_df['seqlentemp'][minidx_pct_tevents_move_2]), nonetodash(fragstats_df['seqlencomp'][minidx_pct_tevents_move_2]), nonetodash(fragstats_df['meanscore2d'][minidx_pct_tevents_move_2]), nonetodash(fragstats_df['meanscoretemp'][minidx_pct_tevents_move_2]), nonetodash(fragstats_df['meanscorecomp'][minidx_pct_tevents_move_2]), fragstats_df['name'][minidx_pct_tevents_move_2]
print "max_pct_2_moves", "template", max_pct_tevents_move_2, fragstats_df['numevents'][maxidx_pct_tevents_move_2], nonetodash(fragstats_df['seqlen2d'][maxidx_pct_tevents_move_2]), nonetodash(fragstats_df['seqlentemp'][maxidx_pct_tevents_move_2]), nonetodash(fragstats_df['seqlencomp'][maxidx_pct_tevents_move_2]), nonetodash(fragstats_df['meanscore2d'][maxidx_pct_tevents_move_2]), nonetodash(fragstats_df['meanscoretemp'][maxidx_pct_tevents_move_2]), nonetodash(fragstats_df['meanscorecomp'][maxidx_pct_tevents_move_2]), fragstats_df['name'][maxidx_pct_tevents_move_2]
print "min_pct_3_moves", "template", min_pct_tevents_move_3, fragstats_df['numevents'][minidx_pct_tevents_move_3], nonetodash(fragstats_df['seqlen2d'][minidx_pct_tevents_move_3]), nonetodash(fragstats_df['seqlentemp'][minidx_pct_tevents_move_3]), nonetodash(fragstats_df['seqlencomp'][minidx_pct_tevents_move_3]), nonetodash(fragstats_df['meanscore2d'][minidx_pct_tevents_move_3]), nonetodash(fragstats_df['meanscoretemp'][minidx_pct_tevents_move_3]), nonetodash(fragstats_df['meanscorecomp'][minidx_pct_tevents_move_3]), fragstats_df['name'][minidx_pct_tevents_move_3]
print "max_pct_3_moves", "template", max_pct_tevents_move_3, fragstats_df['numevents'][maxidx_pct_tevents_move_3], nonetodash(fragstats_df['seqlen2d'][maxidx_pct_tevents_move_3]), nonetodash(fragstats_df['seqlentemp'][maxidx_pct_tevents_move_3]), nonetodash(fragstats_df['seqlencomp'][maxidx_pct_tevents_move_3]), nonetodash(fragstats_df['meanscore2d'][maxidx_pct_tevents_move_3]), nonetodash(fragstats_df['meanscoretemp'][maxidx_pct_tevents_move_3]), nonetodash(fragstats_df['meanscorecomp'][maxidx_pct_tevents_move_3]), fragstats_df['name'][maxidx_pct_tevents_move_3]
print "min_pct_4_moves", "template", min_pct_tevents_move_4, fragstats_df['numevents'][minidx_pct_tevents_move_4], nonetodash(fragstats_df['seqlen2d'][minidx_pct_tevents_move_4]), nonetodash(fragstats_df['seqlentemp'][minidx_pct_tevents_move_4]), nonetodash(fragstats_df['seqlencomp'][minidx_pct_tevents_move_4]), nonetodash(fragstats_df['meanscore2d'][minidx_pct_tevents_move_4]), nonetodash(fragstats_df['meanscoretemp'][minidx_pct_tevents_move_4]), nonetodash(fragstats_df['meanscorecomp'][minidx_pct_tevents_move_4]), fragstats_df['name'][minidx_pct_tevents_move_4]
print "max_pct_4_moves", "template", max_pct_tevents_move_4, fragstats_df['numevents'][maxidx_pct_tevents_move_4], nonetodash(fragstats_df['seqlen2d'][maxidx_pct_tevents_move_4]), nonetodash(fragstats_df['seqlentemp'][maxidx_pct_tevents_move_4]), nonetodash(fragstats_df['seqlencomp'][maxidx_pct_tevents_move_4]), nonetodash(fragstats_df['meanscore2d'][maxidx_pct_tevents_move_4]), nonetodash(fragstats_df['meanscoretemp'][maxidx_pct_tevents_move_4]), nonetodash(fragstats_df['meanscorecomp'][maxidx_pct_tevents_move_4]), fragstats_df['name'][maxidx_pct_tevents_move_4]
print "min_pct_5_moves", "template", min_pct_tevents_move_5, fragstats_df['numevents'][minidx_pct_tevents_move_5], nonetodash(fragstats_df['seqlen2d'][minidx_pct_tevents_move_5]), nonetodash(fragstats_df['seqlentemp'][minidx_pct_tevents_move_5]), nonetodash(fragstats_df['seqlencomp'][minidx_pct_tevents_move_5]), nonetodash(fragstats_df['meanscore2d'][minidx_pct_tevents_move_5]), nonetodash(fragstats_df['meanscoretemp'][minidx_pct_tevents_move_5]), nonetodash(fragstats_df['meanscorecomp'][minidx_pct_tevents_move_5]), fragstats_df['name'][minidx_pct_tevents_move_5]
print "max_pct_5_moves", "template", max_pct_tevents_move_5, fragstats_df['numevents'][maxidx_pct_tevents_move_5], nonetodash(fragstats_df['seqlen2d'][maxidx_pct_tevents_move_5]), nonetodash(fragstats_df['seqlentemp'][maxidx_pct_tevents_move_5]), nonetodash(fragstats_df['seqlencomp'][maxidx_pct_tevents_move_5]), nonetodash(fragstats_df['meanscore2d'][maxidx_pct_tevents_move_5]), nonetodash(fragstats_df['meanscoretemp'][maxidx_pct_tevents_move_5]), nonetodash(fragstats_df['meanscorecomp'][maxidx_pct_tevents_move_5]), fragstats_df['name'][maxidx_pct_tevents_move_5]
print "min_pct_0_moves", "complement", min_pct_cevents_move_0, fragstats_df['numevents'][minidx_pct_cevents_move_0], nonetodash(fragstats_df['seqlen2d'][minidx_pct_cevents_move_0]), nonetodash(fragstats_df['seqlentemp'][minidx_pct_cevents_move_0]), nonetodash(fragstats_df['seqlencomp'][minidx_pct_cevents_move_0]), nonetodash(fragstats_df['meanscore2d'][minidx_pct_cevents_move_0]), nonetodash(fragstats_df['meanscoretemp'][minidx_pct_cevents_move_0]), nonetodash(fragstats_df['meanscorecomp'][minidx_pct_cevents_move_0]), fragstats_df['name'][minidx_pct_cevents_move_0]
print "max_pct_0_moves", "complement", max_pct_cevents_move_0, fragstats_df['numevents'][maxidx_pct_cevents_move_0], nonetodash(fragstats_df['seqlen2d'][maxidx_pct_cevents_move_0]), nonetodash(fragstats_df['seqlentemp'][maxidx_pct_cevents_move_0]), nonetodash(fragstats_df['seqlencomp'][maxidx_pct_cevents_move_0]), nonetodash(fragstats_df['meanscore2d'][maxidx_pct_cevents_move_0]), nonetodash(fragstats_df['meanscoretemp'][maxidx_pct_cevents_move_0]), nonetodash(fragstats_df['meanscorecomp'][maxidx_pct_cevents_move_0]), fragstats_df['name'][maxidx_pct_cevents_move_0]
print "min_pct_1_moves", "complement", min_pct_cevents_move_1, fragstats_df['numevents'][minidx_pct_cevents_move_1], nonetodash(fragstats_df['seqlen2d'][minidx_pct_cevents_move_1]), nonetodash(fragstats_df['seqlentemp'][minidx_pct_cevents_move_1]), nonetodash(fragstats_df['seqlencomp'][minidx_pct_cevents_move_1]), nonetodash(fragstats_df['meanscore2d'][minidx_pct_cevents_move_1]), nonetodash(fragstats_df['meanscoretemp'][minidx_pct_cevents_move_1]), nonetodash(fragstats_df['meanscorecomp'][minidx_pct_cevents_move_1]), fragstats_df['name'][minidx_pct_cevents_move_1]
print "max_pct_1_moves", "complement", max_pct_cevents_move_1, fragstats_df['numevents'][maxidx_pct_cevents_move_1], nonetodash(fragstats_df['seqlen2d'][maxidx_pct_cevents_move_1]), nonetodash(fragstats_df['seqlentemp'][maxidx_pct_cevents_move_1]), nonetodash(fragstats_df['seqlencomp'][maxidx_pct_cevents_move_1]), nonetodash(fragstats_df['meanscore2d'][maxidx_pct_cevents_move_1]), nonetodash(fragstats_df['meanscoretemp'][maxidx_pct_cevents_move_1]), nonetodash(fragstats_df['meanscorecomp'][maxidx_pct_cevents_move_1]), fragstats_df['name'][maxidx_pct_cevents_move_1]
print "min_pct_2_moves", "complement", min_pct_cevents_move_2, fragstats_df['numevents'][minidx_pct_cevents_move_2], nonetodash(fragstats_df['seqlen2d'][minidx_pct_cevents_move_2]), nonetodash(fragstats_df['seqlentemp'][minidx_pct_cevents_move_2]), nonetodash(fragstats_df['seqlencomp'][minidx_pct_cevents_move_2]), nonetodash(fragstats_df['meanscore2d'][minidx_pct_cevents_move_2]), nonetodash(fragstats_df['meanscoretemp'][minidx_pct_cevents_move_2]), nonetodash(fragstats_df['meanscorecomp'][minidx_pct_cevents_move_2]), fragstats_df['name'][minidx_pct_cevents_move_2]
print "max_pct_2_moves", "complement", max_pct_cevents_move_2, fragstats_df['numevents'][maxidx_pct_cevents_move_2], nonetodash(fragstats_df['seqlen2d'][maxidx_pct_cevents_move_2]), nonetodash(fragstats_df['seqlentemp'][maxidx_pct_cevents_move_2]), nonetodash(fragstats_df['seqlencomp'][maxidx_pct_cevents_move_2]), nonetodash(fragstats_df['meanscore2d'][maxidx_pct_cevents_move_2]), nonetodash(fragstats_df['meanscoretemp'][maxidx_pct_cevents_move_2]), nonetodash(fragstats_df['meanscorecomp'][maxidx_pct_cevents_move_2]), fragstats_df['name'][maxidx_pct_cevents_move_2]
print "min_pct_3_moves", "complement", min_pct_cevents_move_3, fragstats_df['numevents'][minidx_pct_cevents_move_3], nonetodash(fragstats_df['seqlen2d'][minidx_pct_cevents_move_3]), nonetodash(fragstats_df['seqlentemp'][minidx_pct_cevents_move_3]), nonetodash(fragstats_df['seqlencomp'][minidx_pct_cevents_move_3]), nonetodash(fragstats_df['meanscore2d'][minidx_pct_cevents_move_3]), nonetodash(fragstats_df['meanscoretemp'][minidx_pct_cevents_move_3]), nonetodash(fragstats_df['meanscorecomp'][minidx_pct_cevents_move_3]), fragstats_df['name'][minidx_pct_cevents_move_3]
print "max_pct_3_moves", "complement", max_pct_cevents_move_3, fragstats_df['numevents'][maxidx_pct_cevents_move_3], nonetodash(fragstats_df['seqlen2d'][maxidx_pct_cevents_move_3]), nonetodash(fragstats_df['seqlentemp'][maxidx_pct_cevents_move_3]), nonetodash(fragstats_df['seqlencomp'][maxidx_pct_cevents_move_3]), nonetodash(fragstats_df['meanscore2d'][maxidx_pct_cevents_move_3]), nonetodash(fragstats_df['meanscoretemp'][maxidx_pct_cevents_move_3]), nonetodash(fragstats_df['meanscorecomp'][maxidx_pct_cevents_move_3]), fragstats_df['name'][maxidx_pct_cevents_move_3]
print "min_pct_4_moves", "complement", min_pct_cevents_move_4, fragstats_df['numevents'][minidx_pct_cevents_move_4], nonetodash(fragstats_df['seqlen2d'][minidx_pct_cevents_move_4]), nonetodash(fragstats_df['seqlentemp'][minidx_pct_cevents_move_4]), nonetodash(fragstats_df['seqlencomp'][minidx_pct_cevents_move_4]), nonetodash(fragstats_df['meanscore2d'][minidx_pct_cevents_move_4]), nonetodash(fragstats_df['meanscoretemp'][minidx_pct_cevents_move_4]), nonetodash(fragstats_df['meanscorecomp'][minidx_pct_cevents_move_4]), fragstats_df['name'][minidx_pct_cevents_move_4]
print "max_pct_4_moves", "complement", max_pct_cevents_move_4, fragstats_df['numevents'][maxidx_pct_cevents_move_4], nonetodash(fragstats_df['seqlen2d'][maxidx_pct_cevents_move_4]), nonetodash(fragstats_df['seqlentemp'][maxidx_pct_cevents_move_4]), nonetodash(fragstats_df['seqlencomp'][maxidx_pct_cevents_move_4]), nonetodash(fragstats_df['meanscore2d'][maxidx_pct_cevents_move_4]), nonetodash(fragstats_df['meanscoretemp'][maxidx_pct_cevents_move_4]), nonetodash(fragstats_df['meanscorecomp'][maxidx_pct_cevents_move_4]), fragstats_df['name'][maxidx_pct_cevents_move_4]
print "min_pct_5_moves", "complement", min_pct_cevents_move_5, fragstats_df['numevents'][minidx_pct_cevents_move_5], nonetodash(fragstats_df['seqlen2d'][minidx_pct_cevents_move_5]), nonetodash(fragstats_df['seqlentemp'][minidx_pct_cevents_move_5]), nonetodash(fragstats_df['seqlencomp'][minidx_pct_cevents_move_5]), nonetodash(fragstats_df['meanscore2d'][minidx_pct_cevents_move_5]), nonetodash(fragstats_df['meanscoretemp'][minidx_pct_cevents_move_5]), nonetodash(fragstats_df['meanscorecomp'][minidx_pct_cevents_move_5]), fragstats_df['name'][minidx_pct_cevents_move_5]
print "max_pct_5_moves", "complement", max_pct_cevents_move_5, fragstats_df['numevents'][maxidx_pct_cevents_move_5], nonetodash(fragstats_df['seqlen2d'][maxidx_pct_cevents_move_5]), nonetodash(fragstats_df['seqlentemp'][maxidx_pct_cevents_move_5]), nonetodash(fragstats_df['seqlencomp'][maxidx_pct_cevents_move_5]), nonetodash(fragstats_df['meanscore2d'][maxidx_pct_cevents_move_5]), nonetodash(fragstats_df['meanscoretemp'][maxidx_pct_cevents_move_5]), nonetodash(fragstats_df['meanscorecomp'][maxidx_pct_cevents_move_5]), fragstats_df['name'][maxidx_pct_cevents_move_5]
if g4:
g4intemp = fragstats_df['numG4intemp'] >= 1
g4incomp = fragstats_df['numG4incomp'] >= 1
g4in2d = fragstats_df['numG4in2d'] >= 1
## Q score distribution for reads with G4 motif in specific read
## 2D -- G4 in 2D
print "Q score distribution for reads with G4 motif in specific read type:"
mean_2d_Q = fragstats_df['meanscore2d'][g4in2d].mean()
median_2d_Q = fragstats_df['meanscore2d'][g4in2d].median()
std_2d_Q = fragstats_df['meanscore2d'][g4in2d].std()
min_2d_Q_idx = fragstats_df['meanscore2d'][g4in2d].idxmin()
max_2d_Q_idx = fragstats_df['meanscore2d'][g4in2d].idxmax()
min_2d_Q = fragstats_df['meanscore2d'][min_2d_Q_idx]
max_2d_Q = fragstats_df['meanscore2d'][max_2d_Q_idx]
min_2d_Q_length = fragstats_df['seqlen2d'][min_2d_Q_idx]
max_2d_Q_length = fragstats_df['seqlen2d'][max_2d_Q_idx]
min_2d_Q_name = fragstats_df['name'][min_2d_Q_idx]
max_2d_Q_name = fragstats_df['name'][max_2d_Q_idx]
## Template -- G4 in temp
mean_temp_Q = fragstats_df['meanscoretemp'][g4intemp].mean()
median_temp_Q = fragstats_df['meanscoretemp'][g4intemp].median()
std_temp_Q = fragstats_df['meanscoretemp'][g4intemp].std()
min_temp_Q_idx = fragstats_df['meanscoretemp'][g4intemp].idxmin()
max_temp_Q_idx = fragstats_df['meanscoretemp'][g4intemp].idxmax()
min_temp_Q = fragstats_df['meanscoretemp'][min_temp_Q_idx]
max_temp_Q = fragstats_df['meanscoretemp'][max_temp_Q_idx]
min_temp_Q_length = fragstats_df['seqlentemp'][min_temp_Q_idx]
max_temp_Q_length = fragstats_df['seqlentemp'][max_temp_Q_idx]
min_temp_Q_name = fragstats_df['name'][min_temp_Q_idx]
max_temp_Q_name = fragstats_df['name'][max_temp_Q_idx]
## Complement -- G4 in comp
mean_comp_Q = fragstats_df['meanscorecomp'][g4incomp].mean()
median_comp_Q = fragstats_df['meanscorecomp'][g4incomp].median()
std_comp_Q = fragstats_df['meanscorecomp'][g4incomp].std()
min_comp_Q_idx = fragstats_df['meanscorecomp'][g4incomp].idxmin()
max_comp_Q_idx = fragstats_df['meanscorecomp'][g4incomp].idxmax()
min_comp_Q = fragstats_df['meanscorecomp'][min_comp_Q_idx]
max_comp_Q = fragstats_df['meanscorecomp'][max_comp_Q_idx]
min_comp_Q_length = fragstats_df['seqlencomp'][min_comp_Q_idx]
max_comp_Q_length = fragstats_df['seqlencomp'][max_comp_Q_idx]
min_comp_Q_name = fragstats_df['name'][min_comp_Q_idx]
max_comp_Q_name = fragstats_df['name'][max_comp_Q_idx]
print ("\t").join(["metric", "Q", "length", "read_type", "name"])
print ("\t").join([str(e) for e in ["median_Q_2d", median_2d_Q, "-", "2D", "-"]])
print ("\t").join([str(e) for e in ["mean_Q_2d", mean_2d_Q, "-", "2D", "-"]])
print ("\t").join([str(e) for e in ["std_dev_Q_2d", std_2d_Q, "-", "2D", "-"]])
print ("\t").join([str(e) for e in ["min_Q_2d", min_2d_Q, min_2d_Q_length, "2D", min_2d_Q_name]])
print ("\t").join([str(e) for e in ["max_Q_2d", max_2d_Q, max_2d_Q_length, "2D", max_2d_Q_name]])
print
print ("\t").join(["metric", "Q", "length", "read_type", "name"])
print ("\t").join([str(e) for e in ["median_Q_template", median_temp_Q, "-", "template", "-"]])
print ("\t").join([str(e) for e in ["mean_Q_template", mean_temp_Q, "-", "template", "-"]])
print ("\t").join([str(e) for e in ["std_dev_Q_template", std_temp_Q, "-", "template", "-"]])
print ("\t").join([str(e) for e in ["min_Q_template", min_temp_Q, min_temp_Q_length, "template", min_temp_Q_name]])
print ("\t").join([str(e) for e in ["max_Q_template", max_temp_Q, max_temp_Q_length, "template", max_temp_Q_name]])
print
print ("\t").join(["metric", "Q", "length", "read_type", "name"])
print ("\t").join([str(e) for e in ["median_Q_complement", median_comp_Q, "-", "complement", "-"]])
print ("\t").join([str(e) for e in ["mean_Q_complement", mean_comp_Q, "-", "complement", "-"]])
print ("\t").join([str(e) for e in ["std_dev_Q_complement", std_comp_Q, "-", "complement", "-"]])
print ("\t").join([str(e) for e in ["min_Q_complement", min_comp_Q, min_comp_Q_length, "complement", min_comp_Q_name]])
print ("\t").join([str(e) for e in ["max_Q_complement", max_comp_Q, max_comp_Q_length, "complement", max_comp_Q_name]])
print
## Q score distribution for reads with G4 motif in at least 1 read type
hasg4 = g4intemp | g4incomp | g4in2d ## intemp or incomp or in2d
print "Q score distribution for reads with G4 motif in any read type:"
## 2D -- G4 in Template OR Complement OR 2D
mean_2d_Q = fragstats_df['meanscore2d'][hasg4].mean()
median_2d_Q = fragstats_df['meanscore2d'][hasg4].median()
std_2d_Q = fragstats_df['meanscore2d'][hasg4].std()
min_2d_Q_idx = fragstats_df['meanscore2d'][hasg4].idxmin()
max_2d_Q_idx = fragstats_df['meanscore2d'][hasg4].idxmax()
min_2d_Q = fragstats_df['meanscore2d'][min_2d_Q_idx]
max_2d_Q = fragstats_df['meanscore2d'][max_2d_Q_idx]
min_2d_Q_length = fragstats_df['seqlen2d'][min_2d_Q_idx]
max_2d_Q_length = fragstats_df['seqlen2d'][max_2d_Q_idx]
min_2d_Q_name = fragstats_df['name'][min_2d_Q_idx]
max_2d_Q_name = fragstats_df['name'][max_2d_Q_idx]
## Template -- G4 in Template OR Complement OR 2D
mean_temp_Q = fragstats_df['meanscoretemp'][hasg4].mean()
median_temp_Q = fragstats_df['meanscoretemp'][hasg4].median()
std_temp_Q = fragstats_df['meanscoretemp'][hasg4].std()
min_temp_Q_idx = fragstats_df['meanscoretemp'][hasg4].idxmin()
max_temp_Q_idx = fragstats_df['meanscoretemp'][hasg4].idxmax()
min_temp_Q = fragstats_df['meanscoretemp'][min_temp_Q_idx]
max_temp_Q = fragstats_df['meanscoretemp'][max_temp_Q_idx]
min_temp_Q_length = fragstats_df['seqlentemp'][min_temp_Q_idx]
max_temp_Q_length = fragstats_df['seqlentemp'][max_temp_Q_idx]
min_temp_Q_name = fragstats_df['name'][min_temp_Q_idx]
max_temp_Q_name = fragstats_df['name'][max_temp_Q_idx]
## Complement -- G4 in Template OR Complement OR 2D
mean_comp_Q = fragstats_df['meanscorecomp'][hasg4].mean()
median_comp_Q = fragstats_df['meanscorecomp'][hasg4].median()
std_comp_Q = fragstats_df['meanscorecomp'][hasg4].std()
min_comp_Q_idx = fragstats_df['meanscorecomp'][hasg4].idxmin()
max_comp_Q_idx = fragstats_df['meanscorecomp'][hasg4].idxmax()
min_comp_Q = fragstats_df['meanscorecomp'][min_comp_Q_idx]
max_comp_Q = fragstats_df['meanscorecomp'][max_comp_Q_idx]
min_comp_Q_length = fragstats_df['seqlencomp'][min_comp_Q_idx]
max_comp_Q_length = fragstats_df['seqlencomp'][max_comp_Q_idx]
min_comp_Q_name = fragstats_df['name'][min_comp_Q_idx]
max_comp_Q_name = fragstats_df['name'][max_comp_Q_idx]
print ("\t").join(["metric", "Q", "length", "read_type", "name"])
print ("\t").join([str(e) for e in ["median_Q_2d", median_2d_Q, "-", "2D", "-"]])
print ("\t").join([str(e) for e in ["mean_Q_2d", mean_2d_Q, "-", "2D", "-"]])
print ("\t").join([str(e) for e in ["std_dev_Q_2d", std_2d_Q, "-", "2D", "-"]])
print ("\t").join([str(e) for e in ["min_Q_2d", min_2d_Q, min_2d_Q_length, "2D", min_2d_Q_name]])
print ("\t").join([str(e) for e in ["max_Q_2d", max_2d_Q, max_2d_Q_length, "2D", max_2d_Q_name]])
print
print ("\t").join(["metric", "Q", "length", "read_type", "name"])
print ("\t").join([str(e) for e in ["median_Q_template", median_temp_Q, "-", "template", "-"]])
print ("\t").join([str(e) for e in ["mean_Q_template", mean_temp_Q, "-", "template", "-"]])
print ("\t").join([str(e) for e in ["std_dev_Q_template", std_temp_Q, "-", "template", "-"]])
print ("\t").join([str(e) for e in ["min_Q_template", min_temp_Q, min_temp_Q_length, "template", min_temp_Q_name]])
print ("\t").join([str(e) for e in ["max_Q_template", max_temp_Q, max_temp_Q_length, "template", max_temp_Q_name]])
print
print ("\t").join(["metric", "Q", "length", "read_type", "name"])
print ("\t").join([str(e) for e in ["median_Q_complement", median_comp_Q, "-", "complement", "-"]])
print ("\t").join([str(e) for e in ["mean_Q_complement", mean_comp_Q, "-", "complement", "-"]])
print ("\t").join([str(e) for e in ["std_dev_Q_complement", std_comp_Q, "-", "complement", "-"]])
print ("\t").join([str(e) for e in ["min_Q_complement", min_comp_Q, min_comp_Q_length, "complement", min_comp_Q_name]])
print ("\t").join([str(e) for e in ["max_Q_complement", max_comp_Q, max_comp_Q_length, "complement", max_comp_Q_name]])
print
if timecheck:
n_time_errors = sum(fragstats_df['timeerror'])
pct_time_errors = 100.0*n_time_errors/n_molecules
def nonetodash(x):
if not x:
return "-"
elif np.isnan(x):
return "-"
else:
return x
def run(parser, args):
fragstats_df = make_fragstats_dataframe(args.fragfile, extensive=args.extensive, g4=args.quadruplex, timecheck=args.checktime)
summarize_fragstats(fragstats_df, extensive=args.extensive, g4=args.quadruplex, timecheck=args.checktime)
| {
"repo_name": "JohnUrban/poreminion",
"path": "poreminion/fragsummary.py",
"copies": "1",
"size": "65966",
"license": "mit",
"hash": -1780729879530802700,
"line_mean": 82.5012658228,
"line_max": 579,
"alpha_frac": 0.6632962435,
"autogenerated": false,
"ratio": 2.573981582643983,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.3737277826143983,
"avg_score": null,
"num_lines": null
} |
from frame_buffer import FrameBuffer
from functools import partial
from replay_memory import ReplayMemory
from six.moves import range, zip, zip_longest
from stats import Stats
import itertools
import logging
import random
import tensorflow as tf
import utils
class DQNAgent:
# Reward penalty on failure for each environment
FAILURE_PENALTY = {
# 'CartPole-v0': -100,
}
def __init__(self, env, network, session, replay_memory, config,
enable_summary=True):
self.env = env
self.network = network
self.session = session
self.replay_memory = replay_memory
self.config = config
self.training_steps = 0 # Keeps count of learning updates
self.stats = Stats()
self.random_action_prob = config.init_random_action_prob
self.random_action_prob_decay = utils.decay_per_step(
init_val=self.config.init_random_action_prob,
min_val=self.config.min_random_action_prob,
steps=self.config.random_action_explore_steps,
)
self.summary_writer = None
if enable_summary:
self.summary_writer = tf.train.SummaryWriter(config.logdir, session.graph)
self.frame_buffer = FrameBuffer(
frames_per_state=config.frames_per_state,
preprocessor=self._get_frame_resizer(env, config),
)
# Prefill the replay memory with experiences based on random actions
self._prefill_replay_memory(self.config.replay_start_size)
# Initialize the target network
self._update_target_network()
def train(self, num_episodes, max_steps_per_episode, supervisor=None):
"""
Train the DQN for the configured number of episodes.
"""
for episode in range(num_episodes):
# Train an episode
reward, steps = self.train_episode(max_steps_per_episode)
# Update stats
self.stats.log_episode(reward, steps)
mean_reward = self.stats.last_100_mean_reward()
logging.info(
'Episode = %d, steps = %d, reward = %d, training steps = %d, '
'last-100 mean reward = %.2f' %
(episode, steps, reward, self.training_steps, mean_reward))
if supervisor and supervisor.should_stop():
logging.warning('Received signal to stop. Exiting train loop.')
break
def train_episode(self, max_steps):
"""
Run one episode of the gym environment, add transitions to replay memory,
and train minibatches from replay memory against the target network.
"""
self.frame_buffer.clear()
observation = self.env.reset()
self.frame_buffer.append(observation)
state = self.frame_buffer.get_state()
total_reward = steps = 0
done = False
while not done and (steps < max_steps):
# Pick the next action and execute it
action = self._pick_action(state)
observation, reward, done, _ = self.env.step(action)
total_reward += reward
steps += 1
# Punish hard on failure
if done:
reward = self.FAILURE_PENALTY.get(self.env.spec.id, reward)
# TODO: Implement reward clipping
# Add the transition to replay memory and update the current state
self.frame_buffer.append(observation)
next_state = self.frame_buffer.get_state()
self.replay_memory.add(state, action, reward, next_state, done)
state = next_state
# Train a minibatch and update the target network if needed
if steps % self.config.update_freq == 0:
self._train_minibatch(self.config.minibatch_size)
return total_reward, steps
def _train_minibatch(self, minibatch_size):
if self.replay_memory.size() < minibatch_size:
return
# Sample a minibatch from replay memory
non_terminal_minibatch, terminal_minibatch = \
self.replay_memory.get_minibatch(minibatch_size)
non_terminal_minibatch, terminal_minibatch = \
list(non_terminal_minibatch), list(terminal_minibatch)
# Compute max q-values for the non-terminal next states based
# on the target network
next_states = list(ReplayMemory.get_next_states(non_terminal_minibatch))
q_values = self._predict_q_values(next_states, use_target_network=True)
max_q_values = q_values.max(axis=1)
# Gradient descent
feed_dict = self._get_minibatch_feed_dict(
max_q_values,
non_terminal_minibatch,
terminal_minibatch,
)
if self._should_log_summary():
_, summary = self.session.run(
[self.network.train_op, self.network.summary_op],
feed_dict=feed_dict,
)
self.summary_writer.add_summary(summary, self.training_steps)
else:
self.session.run(self.network.train_op, feed_dict=feed_dict)
self.training_steps += 1
# Update the target network if needed
self._update_target_network()
def _pick_action(self, state):
"""
Pick the next action given the current state.
Based on a biased dice roll, either a random action, or the
action corresponding to the max q-value obtained by executing
forward-prop is chosen.
@return: action
"""
if self._roll_random_action_dice():
return self.env.action_space.sample()
# Run forward prop and return the action with max q-value
q_values = self._predict_q_values([state])
return q_values.argmax()
def _roll_random_action_dice(self):
"""
Roll the dice based on the configured probability, as well as decay
the probability.
@return: True if random action should be chosen, False otherwise.
"""
self._decay_random_action_prob()
return random.random() < self.random_action_prob
def _decay_random_action_prob(self):
if self.random_action_prob > self.config.min_random_action_prob:
self.random_action_prob -= self.random_action_prob_decay
def _predict_q_values(self, states, use_target_network=False):
"""
Run forward-prop through the network and fetch the q-values.
If use_target_network is True, then the target network's params
will be used for forward-prop.
@return: Numpy array of q-values for each state
"""
q_output = self.network.target_q_output if use_target_network \
else self.network.q_output
feed_dict = {
self.network.x_placeholder: states,
}
return self.session.run(q_output, feed_dict=feed_dict)
def _prefill_replay_memory(self, prefill_size):
"""
Prefill the replay memory by picking actions via uniform random policy,
executing them, and adding the experiences to the memory.
"""
terminal = True
while self.replay_memory.size() < prefill_size:
# Reset the environment and the frame buffer between gameplays
if terminal:
self.frame_buffer.clear()
observation = self.env.reset()
self.frame_buffer.append(observation)
state = self.frame_buffer.get_state()
# Sample a random action and execute it
action = self.env.action_space.sample()
observation, reward, terminal, _ = self.env.step(action)
# Pre-populate replay memory with the experience
self.frame_buffer.append(observation)
next_state = self.frame_buffer.get_state()
self.replay_memory.add(state, action, reward, next_state, terminal)
state = next_state
def _update_target_network(self):
"""
Update the target network by capturing the current state of the
network params.
"""
if self.training_steps % self.config.target_update_freq == 0:
logging.info('Updating target network')
self.session.run(self.network.target_update_ops)
def _get_minibatch_feed_dict(self, target_q_values,
non_terminal_minibatch, terminal_minibatch):
"""
Helper to construct the feed_dict for train_op. Takes the non-terminal and
terminal minibatches as well as the max q-values computed from the target
network for non-terminal states. Computes the expected q-values based on
discounted future reward.
@return: feed_dict to be used for train_op
"""
assert len(target_q_values) == len(non_terminal_minibatch)
states = []
expected_q = []
actions = []
# Compute expected q-values to plug into the loss function
minibatch = itertools.chain(non_terminal_minibatch, terminal_minibatch)
for item, target_q in zip_longest(minibatch, target_q_values, fillvalue=0):
state, action, reward, _, _ = item
states.append(state)
# target_q will be 0 for terminal states due to fillvalue in zip_longest
expected_q.append(reward + self.config.reward_discount * target_q)
actions.append(utils.one_hot(action, self.env.action_space.n))
return {
self.network.x_placeholder: states,
self.network.q_placeholder: expected_q,
self.network.action_placeholder: actions,
}
def _should_log_summary(self):
if self.summary_writer is None:
return False
summary_freq = self.config.summary_freq
return summary_freq > 0 and (self.training_steps % summary_freq == 0)
@classmethod
def _get_frame_resizer(cls, env, config):
"""
Returns a lambda that takes a screen frame and resizes it to the
configured width and height. If the state doesn't need to be resized
for the environment, returns an identity function.
@return: lambda (frame -> resized_frame)
"""
width, height = config.resize_width, config.resize_height
if width > 0 and height > 0:
return partial(utils.resize_image, width=width, height=height)
return lambda x: x
@classmethod
def get_input_shape(cls, env, config):
"""
Return the shape of the input to the network based on the environment,
config, and whether screen frames need to be resized or not.
"""
width, height = config.resize_width, config.resize_height
if width > 0 and height > 0:
return (width, height, config.frames_per_state)
return env.observation_space.shape
| {
"repo_name": "viswanathgs/dist-dqn",
"path": "src/dqn_agent.py",
"copies": "1",
"size": "9891",
"license": "mit",
"hash": 2090276046441375700,
"line_mean": 33.7052631579,
"line_max": 80,
"alpha_frac": 0.6749570316,
"autogenerated": false,
"ratio": 3.8292682926829267,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9963018298605077,
"avg_score": 0.008241405135570022,
"num_lines": 285
} |
from ._frame import Command
from ._base import ResponseException, Functionality, Irq
try:
from enum import Enum
except ImportError:
from enum34 import Enum
class DigitalInputs(Functionality):
"""Attributes and methods needed for operating the digital inputs channels.
Args:
i2c_hat (:obj:`raspihats.i2c_hats._base.I2CHat`): I2CHat instance
labels (:obj:`list` of :obj:`str`): Labels of digital input channels
Attributes:
channels (:obj:`list` of :obj:`bool`): List like object, provides access to digital inputs channels.
r_counters (:obj:`list` of :obj:`int`): List like object, provides access to raising edge digital input counters.
f_counters (:obj:`list` of :obj:`int`): List like object, provides access to falling edge digital input counters.
"""
def __init__(self, i2c_hat, labels):
Functionality.__init__(self, i2c_hat, labels)
outer_instance = self
class IRQReg(object):
"""IRQ registers"""
@property
def rising_edge_control(self):
""":obj:`int`: The value of all IRQ Control reg, 1 bit represents 1 channel."""
return i2c_hat.irq.get_reg(Irq.RegName.DI_RISING_EDGE_CONTROL.value)
@rising_edge_control.setter
def rising_edge_control(self, value):
outer_instance._validate_value(value)
i2c_hat.irq.set_reg(Irq.RegName.DI_RISING_EDGE_CONTROL.value, value)
@property
def falling_edge_control(self):
""":obj:`int`: The value of all IRQ Control reg, 1 bit represents 1 channel."""
return i2c_hat.irq.get_reg(Irq.RegName.DI_FALLING_EDGE_CONTROL.value)
@falling_edge_control.setter
def falling_edge_control(self, value):
outer_instance._validate_value(value)
i2c_hat.irq.set_reg(Irq.RegName.DI_FALLING_EDGE_CONTROL.value, value)
@property
def capture(self):
""":obj:`int`: The value of all IRQ Control reg, 1 bit represents 1 channel."""
return i2c_hat.irq.get_reg(Irq.RegName.DI_CAPTURE.value)
@capture.setter
def capture(self, value):
if value != 0:
raise Exception("Value " + str(value) + " not allowed, only 0 is allowed, use 0 to clear the DI IRQ Capture Queue")
i2c_hat.irq.set_reg(Irq.RegName.DI_CAPTURE.value, value)
class Channels(object):
def __getitem__(self, index):
index = outer_instance._validate_channel_index(index)
request = outer_instance._i2c_hat._request_frame_(Command.DI_GET_CHANNEL_STATE, [index])
response = outer_instance._i2c_hat._transfer_(request, 2)
data = response.data
if len(data) != 2 or data[0] != index:
raise ResponseException('Invalid data')
return data[1] > 0
def __len__(self):
return len(outer_instance.labels)
class Counters(object):
def __init__(self, counter_type):
self.__counter_type = counter_type
def __getitem__(self, index):
index = outer_instance._validate_channel_index(index)
request = outer_instance._i2c_hat._request_frame_(Command.DI_GET_COUNTER, [index, self.__counter_type])
response = outer_instance._i2c_hat._transfer_(request, 6)
data = response.data
if (len(data) != 1 + 1 + 4) or (index != data[0]) or (self.__counter_type != data[1]):
raise ResponseException('Invalid data')
return data[2] + (data[3] << 8) + (data[4] << 16) + (data[5] << 24)
def __setitem__(self, index, value):
index = outer_instance._validate_channel_index(index)
if value != 0:
raise ValueError("only '0' is valid, it will reset the counter")
request = outer_instance._i2c_hat._request_frame_(Command.DI_RESET_COUNTER, [index, self.__counter_type])
response = outer_instance._i2c_hat._transfer_(request, 2)
data = response.data
if (len(data) != 2) or (index != data[0]) or (self.__counter_type != data[1]):
raise ResponseException('Invalid data')
def __len__(self):
return len(outer_instance.labels)
self.channels = Channels()
self.r_counters = Counters(1)
self.f_counters = Counters(0)
self.irq_reg = IRQReg()
@property
def value(self):
""":obj:`int`: The value of all the digital inputs, 1 bit represents 1 channel."""
return self._i2c_hat._get_u32_value_(Command.DI_GET_ALL_CHANNEL_STATES)
def reset_counters(self):
"""Resets all digital input channel counters of all types(falling and rising edge).
Raises:
:obj:`raspihats.i2c_hats._base.ResponseException`: If the response hasn't got the expected format
"""
request = self._i2c_hat._request_frame_(Command.DI_RESET_ALL_COUNTERS)
response = self._i2c_hat._transfer_(request, 0)
data = response.data
if len(data) != 0:
raise ResponseException('Invalid data')
class DigitalOutputs(Functionality):
"""Attributes and methods needed for operating the digital outputs channels.
Args:
i2c_hat (:obj:`raspihats.i2c_hats._base.I2CHat`): I2CHat instance
labels (:obj:`list` of :obj:`str`): Labels of digital output channels
Attributes:
channels (:obj:`list` of :obj:`bool`): List like object, provides single channel access to digital outputs.
"""
def __init__(self, i2c_hat, labels):
Functionality.__init__(self, i2c_hat, labels)
outer_instance = self
class Channels(object):
def __getitem__(self, index):
index = outer_instance._validate_channel_index(index)
request = outer_instance._i2c_hat._request_frame_(Command.DQ_GET_CHANNEL_STATE, [index])
response = outer_instance._i2c_hat._transfer_(request, 2)
data = response.data
if len(data) != 2 or data[0] != index:
raise ResponseException('unexpected format')
return data[1] > 0
def __setitem__(self, index, value):
index = outer_instance._validate_channel_index(index)
value = int(value)
if not (0 <= value <= 1):
raise ValueError("'" + str(value) + "' is not a valid value, use: 0 or 1, True or False")
data = [index, value]
request = outer_instance._i2c_hat._request_frame_(Command.DQ_SET_CHANNEL_STATE, data)
response = outer_instance._i2c_hat._transfer_(request, 2)
if data != response.data:
raise ResponseException('unexpected format')
def __len__(self):
return len(outer_instance.labels)
self.channels = Channels()
@property
def value(self):
""":obj:`int`: The value of all the digital outputs, 1 bit represents 1 channel."""
return self._i2c_hat._get_u32_value_(Command.DQ_GET_ALL_CHANNEL_STATES)
@value.setter
def value(self, value):
self._validate_value(value)
self._i2c_hat._set_u32_value_(Command.DQ_SET_ALL_CHANNEL_STATES, value)
@property
def power_on_value(self):
""":obj:`int`: Power On Value, this is loaded to outputs at power on."""
return self._i2c_hat._get_u32_value_(Command.DQ_GET_POWER_ON_VALUE)
@power_on_value.setter
def power_on_value(self, value):
self._validate_value(value)
self._i2c_hat._set_u32_value_(Command.DQ_SET_POWER_ON_VALUE, value)
@property
def safety_value(self):
""":obj:`int`: Safety Value, this is loaded to outputs at Cwdt Timeout."""
return self._i2c_hat._get_u32_value_(Command.DQ_GET_SAFETY_VALUE)
@safety_value.setter
def safety_value(self, value):
self._validate_value(value)
self._i2c_hat._set_u32_value_(Command.DQ_SET_SAFETY_VALUE, value)
| {
"repo_name": "raspihats/raspihats",
"path": "raspihats/i2c_hats/_digital.py",
"copies": "1",
"size": "8309",
"license": "mit",
"hash": -601586602694910100,
"line_mean": 41.6102564103,
"line_max": 135,
"alpha_frac": 0.5850282826,
"autogenerated": false,
"ratio": 3.8378752886836027,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4922903571283602,
"avg_score": null,
"num_lines": null
} |
from frame import Frame
from block import Block
from types import FunctionType
import operator
# Comparison operators are defined in cpython/Include/object.h
CMP_OPS = [
operator.lt,
operator.le,
operator.eq,
operator.ne,
operator.gt,
operator.ge,
lambda x, y: x in y,
lambda x, y: x not in y,
lambda x, y: x is y,
lambda x, y: x is not y,
lambda x, y: issubclass(x, y)
]
BIN_OPS = {
"ADD": operator.add,
"SUBTRACT": operator.sub,
"MULTIPLY": operator.mul,
"POWER": operator.pow,
"FLOOR_DIVIDE": operator.floordiv,
"TRUE_DIVIDE": operator.truediv,
"MODULO": operator.mod,
"SUBSCR": operator.getitem,
"LSHIFT": operator.lshift,
"RSHIFT": operator.rshift,
"AND": operator.and_,
"XOR": operator.xor,
"OR": operator.or_
}
HAS_POS_ARG_DEFS = 1
HAS_KW_ARG_DEFS = 2
class VirtualMachineError(Exception):
pass
class VirtualMachine():
def __init__(self):
self.frames = []
self.current_frame = None
self.return_value = None
def push_frame(self, frame):
self.frames.append(frame)
self.current_frame = self.frames[-1]
def run_code(self, code):
self.push_frame(Frame(code, "__main__"))
self.run_frame(self.current_frame)
return self.return_value
def run_frame(self, frame):
control_code = None
while not control_code:
instr, arg = frame.get_next_instr()
func, arg = self.get_func_and_arg(instr, arg)
# print(instr, arg)
if func:
control_code = func(arg)
else:
print(instr, arg)
print(self.current_frame.stack)
raise VirtualMachineError("Unsupported Instruction: " + instr)
return control_code
def get_func_and_arg(self, instr, arg):
if instr.startswith("INPLACE") or instr.startswith("BINARY"):
func = self.binary_operation
op = "_".join(instr.split("_")[1:])
arg = BIN_OPS[op]
return func, arg
else:
return getattr(self, "instr_{}".format(instr), None), arg
############################################################################
def instr_RETURN_VALUE(self, arg):
self.return_value = self.current_frame.stack.pop()
return "RETURN"
def instr_STORE_FAST(self, arg):
val = self.current_frame.stack.pop()
self.current_frame.locals[arg] = val
def instr_LOAD_FAST(self, arg):
val = self.current_frame.locals[arg]
self.current_frame.stack.append(val)
def instr_STORE_NAME(self, arg):
val = self.current_frame.stack.pop()
self.current_frame.locals[arg] = val
def instr_LOAD_NAME(self, arg):
if arg in self.current_frame.built_ins:
val = self.current_frame.built_ins[arg]
elif arg in self.current_frame.locals:
val = self.current_frame.locals[arg]
else:
raise VirtualMachineError("instr_LOAD_NAME name not found: " + arg)
self.current_frame.stack.append(val)
def instr_LOAD_GLOBAL(self, arg):
if arg in self.current_frame.built_ins:
val = self.current_frame.built_ins[arg]
else:
raise VirtualMachineError("instr_LOAD_GLOBAL name not found: " + arg)
self.current_frame.stack.append(val)
def instr_LOAD_CONST(self, arg):
self.current_frame.stack.append(arg)
def instr_LOAD_ATTR(self, arg):
obj = self.current_frame.stack.pop()
self.current_frame.stack.append(getattr(obj, arg))
def instr_IMPORT_NAME(self, arg):
from_list = self.current_frame.stack.pop()
level = self.current_frame.stack.pop()
# TODO: Implement my own import functionality?
mod = __import__(arg, globals=globals(), locals=locals(), fromlist=from_list, level=level)
self.current_frame.stack.append(mod)
def instr_IMPORT_FROM(self, arg):
module = self.current_frame.stack[-1]
attr = getattr(module, arg)
self.current_frame.stack.append(attr)
def instr_IMPORT_STAR(self, arg):
module = self.current_frame.stack[-1]
symbols = [symbol for symbol in dir(module) if not symbol.startswith('_')]
for symbol in symbols:
member = getattr(module, symbol)
self.current_frame.locals[symbol] = member
def instr_LOAD_BUILD_CLASS(self, arg):
class_builder = __builtins__['__build_class__']
self.current_frame.stack.append(class_builder)
def instr_COMPARE_OP(self, arg):
func = CMP_OPS[arg]
b = self.current_frame.stack.pop()
a = self.current_frame.stack.pop()
self.current_frame.stack.append(func(a, b))
def instr_POP_JUMP_IF_FALSE(self, arg):
if not self.current_frame.stack.pop():
self.current_frame.instr_pointer = arg
def instr_SETUP_LOOP(self, arg):
start = self.current_frame.instr_pointer
end = self.current_frame.instr_pointer + arg
self.current_frame.blocks.append(Block(start, end))
def instr_BREAK_LOOP(self, arg):
end = self.current_frame.blocks[-1].end
self.current_frame.instr_pointer = end
def instr_POP_BLOCK(self, arg):
self.current_frame.blocks.pop()
def instr_POP_TOP(self, arg):
self.current_frame.stack.pop()
def instr_JUMP_ABSOLUTE(self, arg):
self.current_frame.instr_pointer = arg
def instr_BUILD_CONST_KEY_MAP(self, arg):
key_map = {}
keys = self.current_frame.stack.pop()
for key in reversed(keys):
key_map[key] = self.current_frame.stack.pop()
self.current_frame.stack.append(key_map)
def instr_MAKE_FUNCTION(self, arg):
name = self.current_frame.stack.pop()
code = self.current_frame.stack.pop()
arg_defs = None
if arg & HAS_POS_ARG_DEFS:
arg_defs = self.current_frame.stack.pop()
# TODO: Replace with custom function creation/execution, create new frame, etc.
func = FunctionType(code, self.current_frame.built_ins, name=name, argdefs=arg_defs)
if arg & HAS_KW_ARG_DEFS:
kw_arg_defs = self.current_frame.stack.pop()
# TODO: Fix this hack
func.__kwdefaults__ = kw_arg_defs
self.current_frame.stack.append(func)
def instr_CALL_FUNCTION(self, arg):
pos_args = self._parse_pos_args(arg)
func = self.current_frame.stack.pop()
self.current_frame.stack.append(func(*pos_args))
def instr_CALL_FUNCTION_KW(self, arg):
kw_args = {}
kws = self.current_frame.stack.pop()
num_kws = len(kws)
for kw in reversed(kws):
kw_args[kw] = self.current_frame.stack.pop()
num_pos_args = arg - num_kws
pos_args = self._parse_pos_args(num_pos_args)
func = self.current_frame.stack.pop()
self.current_frame.stack.append(func(*pos_args, **kw_args))
def _parse_pos_args(self, num):
# Quote from docs: "The positional arguments are on the stack, with the right-most argument on top."
args = []
for i in range(num):
args.append(self.current_frame.stack.pop())
return reversed(args)
# The following method handles all binary operations.
# It also handles all inplace operations, as they are basically just
# a special case of the binary operations
def binary_operation(self, func):
b = self.current_frame.stack.pop()
a = self.current_frame.stack.pop()
self.current_frame.stack.append(func(a, b))
| {
"repo_name": "mjpatter88/mjpython",
"path": "src/virtual_machine.py",
"copies": "1",
"size": "7665",
"license": "mit",
"hash": 2874090087558433000,
"line_mean": 32.1818181818,
"line_max": 108,
"alpha_frac": 0.6033920417,
"autogenerated": false,
"ratio": 3.5884831460674156,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9686950794480063,
"avg_score": 0.0009848786574705444,
"num_lines": 231
} |
from frame import Frame
from collections import namedtuple
from dis import dis
Block = namedtuple("Block", "type, handler, stack_height")
class VirtualMachineError(Exception):
pass
class VirtualMachine(object):
def __init__(self):
self.frames = []
self.frame = None
self.return_value = None
self.last_exception = None
def run_code(self, code, global_names=None, local_names=None):
frame = self.make_frame(code, global_names=global_names, local_names=local_names)
self.run_frame(frame)
def make_frame(self, code, callargs={}, global_names=None, local_names=None):
# This namespace manipulation seems weird and wrong
if global_names is not None and local_names is not None:
local_names = global_names
elif self.frames:
global_names = self.frame.global_names
local_names = {}
else:
global_names = local_names = {
'__builtins__': __builtins__,
'__name__': '__main__',
'__doc__': None,
'__package__': None,
}
local_names.update(callargs)
frame = Frame(code, global_names, local_names, self.frame)
return frame
def push_frame(self, frame):
self.frames.append(frame)
self.frame = frame
def pop_frame(self):
self.frames.pop()
if self.frames:
self.frame = self.frames[-1]
else:
self.frame = None
def top(self):
return self.frame.stack[-1]
def pop(self):
return self.frame.stack.pop()
def push(self, *vals):
self.frame.stack.extend(vals)
def popn(self, n):
"""Pop a number of values from the value stack.
A list of `n` values is returned, the deepest value first.
"""
if n:
ret = self.frame.stack[-n:]
self.frame.stack[-n:] = []
return ret
else:
return []
def parse_byte_and_args(self):
f = self.frame
opoffset = f.last_instruction
byteCode = f.code_obj.co_code[opoffset]
f.last_instruction += 1
byte_name = dis.opname[byteCode]
if byteCode >= dis.HAVE_ARGUMENT:
# index into the bytecode
arg = f.code_obj.co_code[f.last_instruction:f.last_instruction+2]
f.last_instruction += 2 # advance the instruction pointer
arg_val = arg[0] + (arg[1] * 256)
if byteCode in dis.hasconst: # Look up a constant
arg = f.code_obj.co_consts[arg_val]
elif byteCode in dis.hasname: # Look up a name
arg = f.code_obj.co_names[arg_val]
elif byteCode in dis.haslocal: # Look up a local name
arg = f.code_obj.co_varnames[arg_val]
elif byteCode in dis.hasjrel: # Calculate a relative jump
arg = f.last_instruction + arg_val
else:
arg = arg_val
argument = [arg]
else:
argument = []
return byte_name, argument
def dispatch(self, byte_name, argument):
""" Dispatch by bytename to the corresponding methods.
Exceptions are caught and set on the virtual machine."""
# When later unwinding the block stack,
# we need to keep track of why we are doing it.
why = None
try:
bytecode_fn = getattr(self, 'byte_%s' % byte_name, None)
if bytecode_fn is None:
if byte_name.startswith('UNARY_'):
self.unaryOperator(byte_name[6:])
elif byte_name.startswith('BINARY_'):
self.binaryOperator(byte_name[7:])
else:
raise VirtualMachineError(
"unsupported bytecode type: %s" % byte_name
)
else:
why = bytecode_fn(*argument)
except:
# deal with exceptions encountered while executing the op.
self.last_exception = sys.exc_info()[:2] + (None,)
why = 'exception'
return why
# Block stack manipulation
def push_block(self, b_type, handler=None):
stack_height = len(self.frame.stack)
self.frame.block_stack.append(Block(b_type, handler, stack_height))
def pop_block(self):
return self.frame.block_stack.pop()
def unwind_block(self, block):
"""Unwind the values on the data stack corresponding to a given block."""
if block.type == 'except-handler':
# The exception itself is on the stack as type, value, and traceback.
offset = 3
else:
offset = 0
while len(self.frame.stack) > block.level + offset:
self.pop()
if block.type == 'except-handler':
traceback, value, exctype = self.popn(3)
self.last_exception = exctype, value, traceback
def manage_block_stack(self, why):
""" """
frame = self.frame
block = frame.block_stack[-1]
if block.type == 'loop' and why == 'continue':
self.jump(self.return_value)
why = None
return why
self.pop_block()
self.unwind_block(block)
if block.type == 'loop' and why == 'break':
why = None
self.jump(block.handler)
return why
if (block.type in ['setup-except', 'finally'] and why == 'exception'):
self.push_block('except-handler')
exctype, value, tb = self.last_exception
self.push(tb, value, exctype)
self.push(tb, value, exctype) # yes, twice
why = None
self.jump(block.handler)
return why
elif block.type == 'finally':
if why in ('return', 'continue'):
self.push(self.return_value)
self.push(why)
why = None
self.jump(block.handler)
return why
return why
## Stack manipulation
def byte_LOAD_CONST(self, const):
self.push(const)
def byte_POP_TOP(self):
self.pop()
## Names
def byte_LOAD_NAME(self, name):
frame = self.frame
if name in frame.f_locals:
val = frame.f_locals[name]
elif name in frame.f_globals:
val = frame.f_globals[name]
elif name in frame.f_builtins:
val = frame.f_builtins[name]
else:
raise NameError("name '%s' is not defined" % name)
self.push(val)
def byte_STORE_NAME(self, name):
self.frame.f_locals[name] = self.pop()
def byte_LOAD_FAST(self, name):
if name in self.frame.f_locals:
val = self.frame.f_locals[name]
else:
raise UnboundLocalError(
"local variable '%s' referenced before assignment" % name
)
self.push(val)
def byte_STORE_FAST(self, name):
self.frame.f_locals[name] = self.pop()
def byte_LOAD_GLOBAL(self, name):
f = self.frame
if name in f.f_globals:
val = f.f_globals[name]
elif name in f.f_builtins:
val = f.f_builtins[name]
else:
raise NameError("global name '%s' is not defined" % name)
self.push(val)
## Operators
BINARY_OPERATORS = {
'POWER': pow,
'MULTIPLY': operator.mul,
'FLOOR_DIVIDE': operator.floordiv,
'TRUE_DIVIDE': operator.truediv,
'MODULO': operator.mod,
'ADD': operator.add,
'SUBTRACT': operator.sub,
'SUBSCR': operator.getitem,
'LSHIFT': operator.lshift,
'RSHIFT': operator.rshift,
'AND': operator.and_,
'XOR': operator.xor,
'OR': operator.or_,
}
def binaryOperator(self, op):
x, y = self.popn(2)
self.push(self.BINARY_OPERATORS[op](x, y))
COMPARE_OPERATORS = [
operator.lt,
operator.le,
operator.eq,
operator.ne,
operator.gt,
operator.ge,
lambda x, y: x in y,
lambda x, y: x not in y,
lambda x, y: x is y,
lambda x, y: x is not y,
lambda x, y: issubclass(x, Exception) and issubclass(x, y),
]
def byte_COMPARE_OP(self, opnum):
x, y = self.popn(2)
self.push(self.COMPARE_OPERATORS[opnum](x, y))
## Attributes and indexing
def byte_LOAD_ATTR(self, attr):
obj = self.pop()
val = getattr(obj, attr)
self.push(val)
def byte_STORE_ATTR(self, name):
val, obj = self.popn(2)
setattr(obj, name, val)
## Building
def byte_BUILD_LIST(self, count):
elts = self.popn(count)
self.push(elts)
def byte_BUILD_MAP(self, size):
self.push({})
def byte_STORE_MAP(self):
the_map, val, key = self.popn(3)
the_map[key] = val
self.push(the_map)
def byte_LIST_APPEND(self, count):
val = self.pop()
the_list = self.frame.stack[-count] # peek
the_list.append(val)
## Jumps
def byte_JUMP_FORWARD(self, jump):
self.jump(jump)
def byte_JUMP_ABSOLUTE(self, jump):
self.jump(jump)
def byte_POP_JUMP_IF_TRUE(self, jump):
val = self.pop()
if val:
self.jump(jump)
def byte_POP_JUMP_IF_FALSE(self, jump):
val = self.pop()
if not val:
self.jump(jump)
## Blocks
def byte_SETUP_LOOP(self, dest):
self.push_block('loop', dest)
def byte_GET_ITER(self):
self.push(iter(self.pop()))
def byte_FOR_ITER(self, jump):
iterobj = self.top()
try:
v = next(iterobj)
self.push(v)
except StopIteration:
self.pop()
self.jump(jump)
def byte_BREAK_LOOP(self):
return 'break'
def byte_POP_BLOCK(self):
self.pop_block()
## Functions
def byte_MAKE_FUNCTION(self, argc):
name = self.pop()
code = self.pop()
defaults = self.popn(argc)
globs = self.frame.f_globals
fn = Function(name, code, globs, defaults, None, self)
self.push(fn)
def byte_CALL_FUNCTION(self, arg):
lenKw, lenPos = divmod(arg, 256) # KWargs not supported here
posargs = self.popn(lenPos)
func = self.pop()
frame = self.frame
retval = func(*posargs)
self.push(retval)
def byte_RETURN_VALUE(self):
self.return_value = self.pop()
return "return"
def run_frame(self, frame):
"""Run a frame until it returns (somehow).
Exceptions are raised, the return value is returned.
"""
self.push_frame(frame)
while True:
byte_name, arguments = self.parse_byte_and_args()
why = self.dispatch(byte_name, arguments)
# Deal with any block management we need to do
while why and frame.block_stack:
why = self.manage_block_stack(why)
if why:
break
self.pop_frame()
if why == 'exception':
exc, val, tb = self.last_exception
e = exc(val)
e.__traceback__ = tb
raise e
return self.return_value
| {
"repo_name": "doubledherin/my_compiler",
"path": "virtual_machine.py",
"copies": "1",
"size": "11483",
"license": "mit",
"hash": 5826576555742240000,
"line_mean": 28.5192802057,
"line_max": 89,
"alpha_frac": 0.5338326221,
"autogenerated": false,
"ratio": 3.8702392989551737,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9894346226068853,
"avg_score": 0.001945138997264104,
"num_lines": 389
} |
from frame import Frame, OPCODE_TEXT, OPCODE_BINARY
__all__ = ['Message', 'TextMessage', 'BinaryMessage']
class Message(object):
def __init__(self, opcode, payload):
self.opcode = opcode
self.payload = payload
def frame(self, mask=False):
return Frame(self.opcode, self.payload, mask=mask)
def fragment(self, fragment_size, mask=False):
return self.frame().fragment(fragment_size, mask)
def __str__(self):
return '<%s opcode=0x%X size=%d>' \
% (self.__class__.__name__, self.opcode, len(self.payload))
class TextMessage(Message):
def __init__(self, payload):
super(TextMessage, self).__init__(OPCODE_TEXT, unicode(payload))
def frame(self, mask=False):
return Frame(self.opcode, self.payload.encode('utf-8'), mask=mask)
def __str__(self):
if len(self.payload) > 30:
return '<TextMessage "%s"... size=%d>' \
% (self.payload[:30], len(self.payload))
return '<TextMessage "%s" size=%d>' % (self.payload, len(self.payload))
class BinaryMessage(Message):
def __init__(self, payload):
super(BinaryMessage, self).__init__(OPCODE_BINARY, bytearray(payload))
def create_message(opcode, payload):
if opcode == OPCODE_TEXT:
return TextMessage(payload.decode('utf-8'))
if opcode == OPCODE_BINARY:
return BinaryMessage(payload)
return Message(opcode, payload)
| {
"repo_name": "taddeus/wspy",
"path": "message.py",
"copies": "1",
"size": "1452",
"license": "bsd-3-clause",
"hash": -1310995241239097000,
"line_mean": 28.04,
"line_max": 79,
"alpha_frac": 0.6143250689,
"autogenerated": false,
"ratio": 3.751937984496124,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9866263053396125,
"avg_score": 0,
"num_lines": 50
} |
from ..frame import H2OFrame
import urllib
from h2o import expr
class TransformAttributeError(AttributeError):
def __init__(self,obj,method):
super(AttributeError, self).__init__("No {} method for {}".format(method,obj.__class__.__name__))
class H2OTransformer(object):
"""H2O Transforms
H2O Transforms implement the following methods
* fit
* transform
* fit_transform
* inverse_transform
* export
"""
# def __init__(self):
# self.parms=None
def fit(self,X,y=None,**params): raise TransformAttributeError(self,"fit")
def transform(self,X,y=None,**params): raise TransformAttributeError(self,"transform")
def inverse_transform(self,X,y=None,**params): raise TransformAttributeError(self,"inverse_transform")
def export(self,X,y,**params): raise TransformAttributeError(self,"export")
def fit_transform(self, X, y=None, **params):
return self.fit(X, y, **params).transform(X, **params)
def get_params(self, deep=True):
"""
Get parameters for this estimator.
:param deep: (Optional) boolean; if True, return parameters of all subobjects that are estimators.
:return: A dict of parameters.
"""
out = dict()
for key,value in self.parms.iteritems():
if deep and isinstance(value, H2OTransformer):
deep_items = value.get_params().items()
out.update((key + '__' + k, val) for k, val in deep_items)
out[key] = value
return out
def set_params(self, **params):
self.parms.update(params)
return self
@staticmethod
def _dummy_frame():
fr = H2OFrame._expr(expr.ExprNode())
fr._ex._children = None
fr._ex._cache.dummy_fill()
return fr
def to_rest(self, args):
return urllib.quote("{}__{}__{}__{}__{}".format(*args)) | {
"repo_name": "madmax983/h2o-3",
"path": "h2o-py/h2o/transforms/transform_base.py",
"copies": "1",
"size": "1800",
"license": "apache-2.0",
"hash": 681776940703868700,
"line_mean": 30.5964912281,
"line_max": 104,
"alpha_frac": 0.6461111111,
"autogenerated": false,
"ratio": 3.7037037037037037,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.48498148148037035,
"avg_score": null,
"num_lines": null
} |
from ..frame import H2OFrame
import urllib
class TransformAttributeError(AttributeError):
def __init__(self,obj,method):
super(AttributeError, self).__init__("No {} method for {}".format(method,obj.__class__.__name__))
class H2OTransformer(object):
"""H2O Transforms
H2O Transforms implement the following methods
* fit
* transform
* fit_transform
* inverse_transform
* export
"""
# def __init__(self):
# self.parms=None
def fit(self,X,y=None,**params): raise TransformAttributeError(self,"fit")
def transform(self,X,y=None,**params): raise TransformAttributeError(self,"transform")
def inverse_transform(self,X,y=None,**params): raise TransformAttributeError(self,"inverse_transform")
def export(self,X,y,**params): raise TransformAttributeError(self,"export")
def fit_transform(self, X, y=None, **params):
return self.fit(X, y, **params).transform(X, **params)
def get_params(self, deep=True):
"""
Get parameters for this estimator.
:param deep: (Optional) boolean; if True, return parameters of all subobjects that are estimators.
:return: A dict of parameters.
"""
out = dict()
for key,value in self.parms.iteritems():
if deep and isinstance(value, H2OTransformer):
deep_items = value.get_params().items()
out.update((key + '__' + k, val) for k, val in deep_items)
out[key] = value
return out
def set_params(self, **params):
self.parms.update(params)
return self
@staticmethod
def _dummy_frame():
dummy = H2OFrame()
dummy._id = "py_dummy"
return dummy
def to_rest(self, args):
return urllib.quote("{}__{}__{}__{}__{}".format(*args)) | {
"repo_name": "pchmieli/h2o-3",
"path": "h2o-py/h2o/transforms/transform_base.py",
"copies": "1",
"size": "1732",
"license": "apache-2.0",
"hash": 41652200475688020,
"line_mean": 30.5090909091,
"line_max": 104,
"alpha_frac": 0.6443418014,
"autogenerated": false,
"ratio": 3.7408207343412525,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.48851625357412526,
"avg_score": null,
"num_lines": null
} |
from ..frame import H2OFrame
class TransformAttributeError(AttributeError):
def __init__(self,obj,method):
super(AttributeError, self).__init__("No {} method for {}".format(method,obj.__class__.__name__))
class H2OTransformer(object):
"""H2O Transforms
H2O Transforms implement the following methods
* fit
* transform
* fit_transform
* inverse_transform
* export
"""
# def __init__(self):
# self.parms=None
def fit(self,X,y=None,**params): raise TransformAttributeError(self,"fit")
def transform(self,X,y=None,**params): raise TransformAttributeError(self,"transform")
def inverse_transform(self,X,y=None,**params): raise TransformAttributeError(self,"inverse_transform")
def export(self,X,y,**params): raise TransformAttributeError(self,"export")
def fit_transform(self, X, y=None, **params):
return self.fit(X, y, **params).transform(X)
def get_params(self, deep=True):
"""
Get parameters for this estimator.
:param deep: (Optional) boolean; if True, return parameters of all subobjects that are estimators.
:return: A dict of parameters.
"""
out = dict()
for key,value in self.parms.iteritems():
if deep and isinstance(value, H2OTransformer):
deep_items = value.get_params().items()
out.update((key + '__' + k, val) for k, val in deep_items)
out[key] = value
return out
def set_params(self, **params):
self.parms.update(params)
return self
@staticmethod
def _dummy_frame():
dummy = H2OFrame()
dummy._id = "py_dummy"
dummy._computed = True
return dummy
def to_rest(self, args):
return "{}__{}__{}__{}".format(*args) | {
"repo_name": "datachand/h2o-3",
"path": "h2o-py/h2o/transforms/transform_base.py",
"copies": "3",
"size": "1717",
"license": "apache-2.0",
"hash": -5932748628720131000,
"line_mean": 30.2363636364,
"line_max": 104,
"alpha_frac": 0.6429819453,
"autogenerated": false,
"ratio": 3.7489082969432315,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.01695509789995609,
"num_lines": 55
} |
from frame import makeFrame, parseFrame
from settings import TYPE
from settings import ConnectReturn as CR
from binascii import hexlify, unhexlify
frames = []
frames.append(hexlify(makeFrame(TYPE.CONNECT, 1,1,1, name = "daiki", passwd = "10!", will = 1,
willTopic = "will/u", willMessage = "willwill", clean = 1, cliID = "daiki-aminaka")))
frames.append(hexlify(makeFrame(TYPE.CONNACK, 1,1,1, code = CR.ACCEPTED)))
frames.append(hexlify(makeFrame(TYPE.PUBLISH, 1,1,1, topic = "a/u", message = "publishMesse", messageID = 15)))
frames.append(hexlify(makeFrame(TYPE.PUBACK, 1,1,1, messageID = 15)))
frames.append(hexlify(makeFrame(TYPE.PUBREC, 1,1,1, messageID = 15)))
frames.append(hexlify(makeFrame(TYPE.PUBREL, 1,1,1, messageID = 15)))
frames.append(hexlify(makeFrame(TYPE.PUBCOMP, 1,1,1, messageID = 15)))
frames.append(hexlify(makeFrame(TYPE.SUBSCRIBE, 1,1,1, messageID = 15, topics = [["d/a", 1], ["d/c", 2], ["d/k", 0]])))
frames.append(hexlify(makeFrame(TYPE.SUBACK, 1,1,1, messageID = 15, qosList = [1,2,0])))
frames.append(hexlify(makeFrame(TYPE.UNSUBSCRIBE, 1,1,1, messageID = 15, topics = ["d/a", "d/c", "d/k"])))
frames.append(hexlify(makeFrame(TYPE.UNSUBACK, 1,1,1, messageID = 15)))
frames.append(hexlify(makeFrame(TYPE.PINGREQ, 1,1,1)))
frames.append(hexlify(makeFrame(TYPE.PINGRESP, 1,1,1)))
frames.append(hexlify(makeFrame(TYPE.DISCONNECT, 1,1,1)))
for frame in frames:
parseFrame(unhexlify(frame))
| {
"repo_name": "ami-GS/pyMQTT",
"path": "test.py",
"copies": "1",
"size": "1454",
"license": "mit",
"hash": -194186739418457020,
"line_mean": 57.16,
"line_max": 119,
"alpha_frac": 0.7015130674,
"autogenerated": false,
"ratio": 2.817829457364341,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4019342524764341,
"avg_score": null,
"num_lines": null
} |
from frame import *
from scipy.interpolate import interp1d
import numpy as np
class FeaturedFrame(Frame):
def __init__(self, frame):
super(FeaturedFrame, self).__init__(frame.get_frame_data(), frame.get_size(), frame.get_overlap(),
frame.get_raw_data())
self.features = dict()
self.derivatives = dict()
self.coefficients = dict()
self.peaks = dict()
def add_feature(self, name, value):
self.features[name] = value
def get_feature(self, name):
return self.features[name]
def add_coefficients(self, name, value):
self.coefficients[name] = value
def get_coefficients(self, name):
return self.coefficients[name]
def add_derivative(self, name, value):
self.derivatives[name] = value
def get_derivative(self, name):
return self.derivatives[name]
def add_peaks(self, name, value):
self.peaks[name] = value
def get_peaks(self, name):
return self.peaks[name]
def get_function(self, type):
if type == 'x':
x = self.get_x_data()
t = np.linspace(0, len(x)-1, len(x))
f = interp1d(t, x)
elif type == 'y':
y = self.get_y_data()
t = np.linspace(0, len(y)-1, len(y))
f = interp1d(t, y)
elif type == 'z':
z = self.get_z_data()
t = np.linspace(0, len(z)-1, len(z))
f = interp1d(t, z)
elif type == 'x_der':
x = self.get_derivative('x')
t = np.linspace(1, len(x)-2, len(x))
f = interp1d(t, x)
elif type == 'y_der':
y = self.get_derivative('y')
t = np.linspace(1, len(y)-2, len(y))
f = interp1d(t, y)
elif type == 'z_der':
z = self.get_derivative('z')
t = np.linspace(1, len(z)-2, len(z))
f = interp1d(t, z)
elif type == 'x_der2':
x = self.get_derivative('x2')
t = np.linspace(1, len(x)-2, len(x))
f = interp1d(t, x)
elif type == 'y_der2':
y = self.get_derivative('y2')
t = np.linspace(1, len(y)-2, len(y))
f = interp1d(t, y)
elif type == 'z_der2':
z = self.get_derivative('z2')
t = np.linspace(1, len(z)-2, len(z))
f = interp1d(t, z)
else:
raise AttributeError("Wrong attribute: "+str(type))
return f
def get_all_features(self):
return self.features
def get_flat_features(self):
feats = list()
for value in self.features.itervalues():
feats.append(value)
for value in self.coefficients.itervalues():
# nb of coeffs to use
coeffs = value[:5]
for c in coeffs:
feats.append(c)
return feats
| {
"repo_name": "BavoGoosens/Gaiter",
"path": "data_utils/featured_frame.py",
"copies": "1",
"size": "2909",
"license": "mit",
"hash": 5795349417348631000,
"line_mean": 28.9896907216,
"line_max": 106,
"alpha_frac": 0.5049845308,
"autogenerated": false,
"ratio": 3.479665071770335,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4484649602570335,
"avg_score": null,
"num_lines": null
} |
from frame_list import FrameList
class Video:
"""Encapsulates a video and its frames."""
def __init__(self, filename):
"""
Args:
filename: The video's filename.
"""
self.filename = filename
self.frames = FrameList(self)
self.__start = 0
def __len__(self):
"""
Returns:
The video file's number of frames.
"""
return len(self.frames)
class IdenticalFrameFinder:
"""A class for finding frames in two videos that result in the same hash."""
FPS = 24
INTERVAL = 15*FPS
def __init__(self, video1, video2):
"""
Args:
video1: An instance of Video.
video2: An instance of Video.
"""
self.video1 = {'video': video1, 'identical': -1}
self.video2 = {'video': video2, 'identical': -1}
def find(self):
"""Run the finder.
Returns:
A tuple of frame numbers from the two videos that share hash value.
"""
# TODO Fix this method.
for video1_slice in self.__list_of_frame_slices(self.video1['video']):
video1_hash_set = self.video1['video'].frames[video1_slice]
for video2_slice in self.__list_of_frame_slices(self.video2['video']):
video2_hash_set = self.video1['video'].frames[video2_slice]
frame1, frame2 = self.__get_identical_frame_from_hash_sets(video1_hash_set, video2_hash_set)
return frame1, frame2
return -1, -1
@staticmethod
def __list_of_frame_slices(video):
"""Get a list of slices of frames that should be checked.
Args:
video: An instance of Video.
Returns:
A list of slices.
"""
return [
slice(
start,
start + IdenticalFrameFinder.INTERVAL + 10,
10
) for start in range(
0,
int(0.3 * len(video)),
IdenticalFrameFinder.INTERVAL*2
)
]
@staticmethod
def __get_identical_frame_from_hash_sets(hash_set1, hash_set2):
"""Compare two lists of hashes and find similar hashes.
Args:
hash_set1: A list of tuples of the frame number and hash, for example:
[(100, 2932982313), (110, 3493429832)]
hash_set2: The same as hash_set1.
Returns:
A tuple of frame numbers whose hashes are more or less the same.
"""
for hash1 in hash_set1:
for hash2 in hash_set2:
if abs(hash1[1] - hash2[1]) < 1e15:
return hash1[0], hash2[0]
return -1, -1 | {
"repo_name": "matachi/identify-tv-series-intros",
"path": "video.py",
"copies": "1",
"size": "2729",
"license": "mit",
"hash": 4377079632053054000,
"line_mean": 29.3333333333,
"line_max": 108,
"alpha_frac": 0.5305972884,
"autogenerated": false,
"ratio": 4.019145802650957,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5049743091050958,
"avg_score": null,
"num_lines": null
} |
from framenet import loadXMLAttributes, getNoneTextChildNodes
class Frame(dict):
"""
The frame class
"""
def __init__(self):
"""
Constructor, doesn't do much.
"""
dict.__init__(self)
self['definition'] = None
self['fes'] = {}
self['lexunits'] = {}
self['semtypes'] = None
pass
def loadXMLNode(self, frameNode):
"""
"""
loadXMLAttributes(self, frameNode.attributes)
goodNodes = getNoneTextChildNodes(frameNode)
for node in goodNodes:
if node.nodeName == 'definition':
if not self.loadFrameDefinition(node):
print >> sys.stderr, 'Unable to read definition node for frame:', self['ID']
elif node.nodeName == 'fes':
if not self.loadFrameFes(node):
print >> sys.stderr, 'Unable to read a fes node for frame:', self['ID']
elif node.nodeName == 'lexunits':
if not self.loadFrameLexunits(node):
print >> sys.stderr, 'Unable to read a lexunits node for frame:', self['ID']
elif node.nodeName == 'semTypes':
if not self.loadFrameSemtypes(node):
print >> sys.stderr, 'Unable to read a semtypes node for frame:', self['ID']
else:
print >> sys.stderr, 'Have no idea how to deal with node type:', node.nodeName
return False
return True
def loadFrameDefinition(self, node):
"""
"""
if len(node.childNodes) == 0:
return True
try:
self['definition'] = node.childNodes[0].nodeValue
except:
print >> sys.stderr, 'There is no definition!'
return False
return True
def loadFrameFes(self, node):
"""
"""
feNodes = getNoneTextChildNodes(node)
fes = {}
for feNode in feNodes:
fe = self.loadFrameFe(feNode)
if fe == None:
print >> sys.stderr, 'Got a bad fe'
return False
fes[fe['ID']] = fe
return True
def loadFrameFe(self, feNode):
"""
"""
goodNodes = getNoneTextChildNodes(feNode)
fe = {}
fe = loadXMLAttributes(fe, feNode.attributes)
fe['semtypes'] = {}
for gn in goodNodes:
if gn.nodeName == 'definition':
if not fe.has_key('definition'):
try:
fe['definition'] = gn.childNodes[0].nodeValue
except:
fe['definition'] = None
else:
print >> sys.stderr, 'Error , fe already have a definition:', fe['definition']
return None
elif gn.nodeName == 'semTypes':
goodSemTypeNodes = getNoneTextChildNodes(gn)
for gsn in goodSemTypeNodes:
semType = {}
loadXMLAttributes(semType, gsn.attributes)
fe['semtypes'][semType['ID']] = semType
else:
print >> sys.stderr, 'In loadFrameFe, found this node:', gn.nodeName
return None
return fe
def loadFrameLexunits(self, node):
"""
"""
goodNodes = getNoneTextChildNodes(node)
i = 0
for gn in goodNodes:
lu = self.loadFrameLexicalUnit(gn)
if lu == None:
print >> sys.stderr, 'The lu No.' + str(i), 'is bad'
return False
i += 1
self['lexunits'][lu['ID']] = lu
return True
def loadFrameLexicalUnit(self, lexunitNode):
"""
"""
lexunit = {}
loadXMLAttributes(lexunit, lexunitNode.attributes)
goodNodes = getNoneTextChildNodes(lexunitNode)
for gn in goodNodes:
if gn.nodeName == 'definition':
try:
lexunit['definition'] = gn.childNodes[0].nodeValue
except:
lexunit['definition'] = None
elif gn.nodeName == 'annotation':
annoNodes = getNoneTextChildNodes(gn)
anno = {}
for an in annoNodes:
try:
anno[str(an.nodeName)] = an.childNodes[0].nodeValue
try:
n = int(anno[str(an.nodeName)])
anno[str(an.nodeName)] = n
except:
pass
except:
anno[str(an.nodeName)] = None
print >> sys.stderr, 'Warning!! unable to retrieve', an.nodeName, 'for annotation'
lexunit['annotation'] = anno
elif gn.nodeName == 'lexemes':
goodSemTypeNodes = getNoneTextChildNodes(gn)
lexemes = {}
for gsn in goodSemTypeNodes:
lexeme = {}
loadXMLAttributes(lexeme, gsn.attributes)
# store the actual word
lexeme['lexeme'] = gsn.childNodes[0].nodeValue
lexemes[lexeme['ID']] = lexeme
lexunit['lexeme'] = lexemes
elif gn.nodeName == 'semTypes':
goodSemTypeNodes = getNoneTextChildNodes(gn)
semTypes = {}
for gsn in goodSemTypeNodes:
semType = {}
loadXMLAttributes(semType, gsn.attributes)
semTypes[semType['ID']] = semType
lexunit['semtypes'] = semTypes
else:
print >> sys.stderr, 'Error, encounted the node:', gn.nodeName, 'in', lexunitNode.nodeName, 'lexunit'
return None
return lexunit
def loadFrameSemtypes(self, node):
"""
"""
goodSemTypeNodes = getNoneTextChildNodes(node)
semTypes = {}
for gsn in goodSemTypeNodes:
semType = {}
loadXMLAttributes(semType, gsn.attributes)
semTypes[semType['ID']] = semType
self['semtypes'] = semTypes
return True
#----------------------------------------------------------------------------
| {
"repo_name": "dasmith/FrameNet-python",
"path": "framenet/frame.py",
"copies": "1",
"size": "6422",
"license": "mit",
"hash": -8464974267298070000,
"line_mean": 29.7272727273,
"line_max": 117,
"alpha_frac": 0.4775770788,
"autogenerated": false,
"ratio": 4.650253439536567,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5627830518336567,
"avg_score": null,
"num_lines": null
} |
from framer import template
from framer.util import cstring, unindent
T_SHORT = "T_SHORT"
T_INT = "T_INT"
T_LONG = "T_LONG"
T_FLOAT = "T_FLOAT"
T_DOUBLE = "T_DOUBLE"
T_STRING = "T_STRING"
T_OBJECT = "T_OBJECT"
T_CHAR = "T_CHAR"
T_BYTE = "T_BYTE"
T_UBYTE = "T_UBYTE"
T_UINT = "T_UINT"
T_ULONG = "T_ULONG"
T_STRING_INPLACE = "T_STRING_INPLACE"
T_OBJECT_EX = "T_OBJECT_EX"
RO = READONLY = "READONLY"
READ_RESTRICTED = "READ_RESTRICTED"
WRITE_RESTRICTED = "WRITE_RESTRICTED"
RESTRICT = "RESTRICTED"
c2t = {"int" : T_INT,
"unsigned int" : T_UINT,
"long" : T_LONG,
"unsigned long" : T_LONG,
"float" : T_FLOAT,
"double" : T_DOUBLE,
"char *" : T_CHAR,
"PyObject *" : T_OBJECT,
}
class member(object):
def __init__(self, cname=None, type=None, flags=None, doc=None):
self.type = type
self.flags = flags
self.cname = cname
self.doc = doc
self.name = None
self.struct = None
def register(self, name, struct):
self.name = name
self.struct = struct
self.initvars()
def initvars(self):
v = self.vars = {}
v["PythonName"] = self.name
if self.cname is not None:
v["CName"] = self.cname
else:
v["CName"] = self.name
v["Flags"] = self.flags or "0"
v["Type"] = self.get_type()
if self.doc is not None:
v["Docstring"] = cstring(unindent(self.doc))
v["StructName"] = self.struct.name
def get_type(self):
"""Deduce type code from struct specification if not defined"""
if self.type is not None:
return self.type
ctype = self.struct.get_type(self.name)
return c2t[ctype]
def dump(self, f):
if self.doc is None:
print >> f, template.memberdef_def % self.vars
else:
print >> f, template.memberdef_def_doc % self.vars
| {
"repo_name": "mollstam/UnrealPy",
"path": "UnrealPyEmbed/Development/Python/2015.08.07-Python2710-x64-Source-vs2015/Python27/Source/Python-2.7.10/Tools/framer/framer/member.py",
"copies": "50",
"size": "1933",
"license": "mit",
"hash": -8502403472369238000,
"line_mean": 25.4794520548,
"line_max": 71,
"alpha_frac": 0.5618210036,
"autogenerated": false,
"ratio": 3.048895899053628,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": null,
"num_lines": null
} |
from framer import template
from framer.util import cstring, unindent
T_SHORT = "T_SHORT"
T_INT = "T_INT"
T_LONG = "T_LONG"
T_FLOAT = "T_FLOAT"
T_DOUBLE = "T_DOUBLE"
T_STRING = "T_STRING"
T_OBJECT = "T_OBJECT"
T_CHAR = "T_CHAR"
T_BYTE = "T_BYTE"
T_UBYTE = "T_UBYTE"
T_UINT = "T_UINT"
T_ULONG = "T_ULONG"
T_STRING_INPLACE = "T_STRING_INPLACE"
T_OBJECT_EX = "T_OBJECT_EX"
RO = READONLY = "READONLY"
READ_RESTRICTED = "READ_RESTRICTED"
WRITE_RESTRICTED = "WRITE_RESTRICTED"
RESTRICT = "RESTRICTED"
c2t = {"int" : T_INT,
"unsigned int" : T_UINT,
"long" : T_LONG,
"unsigned long" : T_LONG,
"float" : T_FLOAT,
"double" : T_DOUBLE,
"char *" : T_CHAR,
"PyObject *" : T_OBJECT,
}
class member(object):
def __init__(self, cname=None, type=None, flags=None, doc=None):
self.type = type
self.flags = flags
self.cname = cname
self.doc = doc
self.name = None
self.struct = None
def register(self, name, struct):
self.name = name
self.struct = struct
self.initvars()
def initvars(self):
v = self.vars = {}
v["PythonName"] = self.name
if self.cname is not None:
v["CName"] = self.cname
else:
v["CName"] = self.name
v["Flags"] = self.flags or "0"
v["Type"] = self.get_type()
if self.doc is not None:
v["Docstring"] = cstring(unindent(self.doc))
v["StructName"] = self.struct.name
def get_type(self):
"""Deduce type code from struct specification if not defined"""
if self.type is not None:
return self.type
ctype = self.struct.get_type(self.name)
return c2t[ctype]
def dump(self, f):
if self.doc is None:
print >> f, template.memberdef_def % self.vars
else:
print >> f, template.memberdef_def_doc % self.vars
| {
"repo_name": "MattDevo/edk2",
"path": "AppPkg/Applications/Python/Python-2.7.2/Tools/framer/framer/member.py",
"copies": "6",
"size": "2006",
"license": "bsd-2-clause",
"hash": 4900622804668418000,
"line_mean": 25.4794520548,
"line_max": 71,
"alpha_frac": 0.5413758724,
"autogenerated": false,
"ratio": 3.0814132104454686,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.004459331229395029,
"num_lines": 73
} |
from framework.auth.core import _get_current_user
from website.files.models.base import File, Folder, FileNode, FileVersion
__all__ = ('DataverseFile', 'DataverseFolder', 'DataverseFileNode')
class DataverseFileNode(FileNode):
provider = 'dataverse'
class DataverseFolder(DataverseFileNode, Folder):
pass
class DataverseFile(DataverseFileNode, File):
version_identifier = 'version'
def update(self, revision, data, user=None):
"""Note: Dataverse only has psuedo versions, don't save them
Dataverse requires a user for the weird check below
and Django dies when _get_current_user is called
"""
self.name = data['name']
self.materialized_path = data['materialized']
self.save()
version = FileVersion(identifier=revision)
version.update_metadata(data, save=False)
user = user or _get_current_user()
if not user or not self.node.can_edit(user=user):
try:
# Users without edit permission can only see published files
if not data['extra']['hasPublishedVersion']:
# Blank out name and path for the render
# Dont save because there's no reason to persist the change
self.name = ''
self.materialized_path = ''
return (version, '<div class="alert alert-info" role="alert">This file does not exist.</div>')
except (KeyError, IndexError):
pass
return version
| {
"repo_name": "zamattiac/osf.io",
"path": "website/files/models/dataverse.py",
"copies": "39",
"size": "1543",
"license": "apache-2.0",
"hash": 3693805418283804000,
"line_mean": 34.0681818182,
"line_max": 114,
"alpha_frac": 0.6215165262,
"autogenerated": false,
"ratio": 4.371104815864022,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": null,
"num_lines": null
} |
from framework.auth import Auth
from website.archiver import (
StatResult, AggregateStatResult,
ARCHIVER_NETWORK_ERROR,
ARCHIVER_SIZE_EXCEEDED,
)
from website.archiver.model import ArchiveJob
from website import mails
from website import settings
from website.project.model import NodeLog
def send_archiver_success_mail(dst):
user = dst.creator
mails.send_mail(
to_addr=user.username,
mail=mails.ARCHIVE_SUCCESS,
user=user,
src=dst,
mimetype='html',
)
def send_archiver_size_exceeded_mails(src, user, stat_result):
mails.send_mail(
to_addr=settings.SUPPORT_EMAIL,
mail=mails.ARCHIVE_SIZE_EXCEEDED_DESK,
user=user,
src=src,
stat_result=stat_result
)
mails.send_mail(
to_addr=user.username,
mail=mails.ARCHIVE_SIZE_EXCEEDED_USER,
user=user,
src=src,
mimetype='html',
)
def send_archiver_copy_error_mails(src, user, results):
mails.send_mail(
to_addr=settings.SUPPORT_EMAIL,
mail=mails.ARCHIVE_COPY_ERROR_DESK,
user=user,
src=src,
results=results,
)
mails.send_mail(
to_addr=user.username,
mail=mails.ARCHIVE_COPY_ERROR_USER,
user=user,
src=src,
results=results,
mimetype='html',
)
def send_archiver_uncaught_error_mails(src, user, results):
mails.send_mail(
to_addr=settings.SUPPORT_EMAIL,
mail=mails.ARCHIVE_UNCAUGHT_ERROR_DESK,
user=user,
src=src,
results=results,
)
mails.send_mail(
to_addr=user.username,
mail=mails.ARCHIVE_UNCAUGHT_ERROR_USER,
user=user,
src=src,
results=results,
mimetype='html',
)
def handle_archive_fail(reason, src, dst, user, result):
if reason == ARCHIVER_NETWORK_ERROR:
send_archiver_copy_error_mails(src, user, result)
elif reason == ARCHIVER_SIZE_EXCEEDED:
send_archiver_size_exceeded_mails(src, user, result)
else: # reason == ARCHIVER_UNCAUGHT_ERROR
send_archiver_uncaught_error_mails(src, user, result)
delete_registration_tree(dst.root)
def archive_provider_for(node, user):
"""A generic function to get the archive provider for some node, user pair.
:param node: target node
:param user: target user (currently unused, but left in for future-proofing
the code for use with archive providers other than OSF Storage)
"""
return node.get_addon(settings.ARCHIVE_PROVIDER)
def has_archive_provider(node, user):
"""A generic function for checking whether or not some node, user pair has
an attached provider for archiving
:param node: target node
:param user: target user (currently unused, but left in for future-proofing
the code for use with archive providers other than OSF Storage)
"""
return node.has_addon(settings.ARCHIVE_PROVIDER)
def link_archive_provider(node, user):
"""A generic function for linking some node, user pair with the configured
archive provider
:param node: target node
:param user: target user (currently unused, but left in for future-proofing
the code for use with archive providers other than OSF Storage)
"""
addon = node.get_or_add_addon(settings.ARCHIVE_PROVIDER, auth=Auth(user))
addon.on_add()
node.save()
def delete_registration_tree(node):
node.is_deleted = True
if not getattr(node.embargo, 'for_existing_registration', False):
node.registered_from = None
node.save()
node.update_search()
for child in node.nodes_primary:
delete_registration_tree(child)
def aggregate_file_tree_metadata(addon_short_name, fileobj_metadata, user):
"""Recursively traverse the addon's file tree and collect metadata in AggregateStatResult
:param src_addon: AddonNodeSettings instance of addon being examined
:param fileobj_metadata: file or folder metadata of current point of reference
in file tree
:param user: archive initatior
:return: top-most recursive call returns AggregateStatResult containing addon file tree metadata
"""
disk_usage = fileobj_metadata.get('size')
if fileobj_metadata['kind'] == 'file':
result = StatResult(
target_name=fileobj_metadata['name'],
target_id=fileobj_metadata['path'].lstrip('/'),
disk_usage=disk_usage or 0,
)
return result
else:
return AggregateStatResult(
target_id=fileobj_metadata['path'].lstrip('/'),
target_name=fileobj_metadata['name'],
targets=[aggregate_file_tree_metadata(addon_short_name, child, user) for child in fileobj_metadata.get('children', [])],
)
def before_archive(node, user):
link_archive_provider(node, user)
job = ArchiveJob(
src_node=node.registered_from,
dst_node=node,
initiator=user
)
job.set_targets()
def add_archive_success_logs(node, user):
src = node.registered_from
src.add_log(
action=NodeLog.PROJECT_REGISTERED,
params={
'parent_node': src.parent_id,
'node': src._primary_key,
'registration': node._primary_key,
},
auth=Auth(user),
log_date=node.registered_date,
save=False
)
src.save()
def archive_success(node, user):
add_archive_success_logs(node, user)
for child in node.get_descendants_recursive(include=lambda n: n.primary):
add_archive_success_logs(child, user)
| {
"repo_name": "HarryRybacki/osf.io",
"path": "website/archiver/utils.py",
"copies": "5",
"size": "5565",
"license": "apache-2.0",
"hash": 27255303790770110,
"line_mean": 28.9193548387,
"line_max": 132,
"alpha_frac": 0.6555256065,
"autogenerated": false,
"ratio": 3.7050599201065246,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.00035710788821828,
"num_lines": 186
} |
from Framework.BancoDeDados import BancoDeDados
from Database.Models.Ass_aluno_turma import Ass_aluno_turma as ModelAss_aluno_turma
class Ass_aluno_turma(object):
def pegarAss_aluno_turmas(self, condicao, valores):
associacoes = []
for associacao in BancoDeDados().consultarMultiplos("SELECT * FROM ass_aluno_turma %s" % (condicao), valores):
associacoes.append(ModelAss_aluno_turma(associacao))
return associacoes
def pegarAss_aluno_turma(self, condicao, valores):
return ModelAss_aluno_turma(BancoDeDados().consultarUnico("SELECT * FROM ass_aluno_turma %s" % (condicao), valores))
def inserirAss_aluno_turma(self, associacao):
BancoDeDados().executar("INSERT INTO ass_aluno_turma (id_turma,id_aluno) VALUES (%s,%s) RETURNING id", (associacao.id_turma,associacao.id_aluno))
associacao.id = BancoDeDados().pegarUltimoIDInserido()
return associacao
def removerAss_aluno_turma(self, associacao):
BancoDeDados().executar("DELETE FROM ass_aluno_turma WHERE id = %s", (str(associacao.id),))
def alterarAss_aluno_turma(self, associacao):
SQL = "UPDATE ass_aluno_turma SET id_turma=%s, id_aluno = %s WHERE id = %s"
BancoDeDados().executar(SQL, (associacao.id_turma,associacao.id_aluno,associacao.id))
| {
"repo_name": "AEDA-Solutions/matweb",
"path": "backend/Database/Controllers/Ass_aluno_turma.py",
"copies": "1",
"size": "1237",
"license": "mit",
"hash": -2439363257332973600,
"line_mean": 46.5769230769,
"line_max": 147,
"alpha_frac": 0.7518189167,
"autogenerated": false,
"ratio": 2.420743639921722,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.36725625566217224,
"avg_score": null,
"num_lines": null
} |
from Framework.BancoDeDados import BancoDeDados
from Database.Models.Ass_disc_pre import Ass_disc_pre as ModelAss_disc_pre
class Ass_disc_pre(object):
def pegarAss_disc_pres(self, condicao, valores):
associacoes = []
for associacao in BancoDeDados().consultarMultiplos("SELECT * FROM ass_disc_pre %s" % (condicao), valores):
associacoes.append(ModelAss_disc_pre(associacao))
return associacoes
def pegarAss_disc_pre(self, condicao, valores):
return ModelAss_disc_pre(BancoDeDados().consultarUnico("SELECT * FROM ass_disc_pre %s" % (condicao), valores))
def inserirAss_disc_pre(self, associacao):
BancoDeDados().executar("INSERT INTO ass_disc_pre (id_disciplina,id_prereq) VALUES (%s,%s) RETURNING id", (associacao.id_disciplina,associacao.id_prereq))
associacao.id = BancoDeDados().pegarUltimoIDInserido()
return associacao
def removerAss_disc_pre(self, associacao):
BancoDeDados().executar("DELETE FROM ass_disc_pre WHERE id = %s", (str(associacao.id),))
def alterarAss_disc_pre(self, associacao):
SQL = "UPDATE ass_disc_pre SET id_disciplina=%s, id_prereq = %s WHERE id = %s"
BancoDeDados().executar(SQL, (associacao.id_disciplina,associacao.id_prereq,associacao.id))
| {
"repo_name": "AEDA-Solutions/matweb",
"path": "backend/Database/Controllers/Ass_disc_pre.py",
"copies": "1",
"size": "1213",
"license": "mit",
"hash": -3178394860206995500,
"line_mean": 45.6538461538,
"line_max": 156,
"alpha_frac": 0.7469084913,
"autogenerated": false,
"ratio": 2.5974304068522485,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.7990595787159194,
"avg_score": 0.17074862219861092,
"num_lines": 26
} |
from Framework.BancoDeDados import BancoDeDados
from Database.Models.Ass_oferta_turma import Ass_oferta_turma as ModelAss_oferta_turma
class Ass_oferta_turma(object):
def pegarAss_oferta_turmas(self, condicao, valores):
associacoes = []
for associacao in BancoDeDados().consultarMultiplos("SELECT * FROM ass_oferta_turma %s" % (condicao), valores):
associacoes.append(ModelAss_oferta_turma(associacao))
return associacoes
def pegarAss_oferta_turma(self, condicao, valores):
return ModelAss_oferta_turma(BancoDeDados().consultarUnico("SELECT * FROM ass_oferta_turma %s" % (condicao), valores))
def inserirAss_oferta_turma(self, associacao):
BancoDeDados().executar("INSERT INTO ass_oferta_turma (id_turma,id_oferta) VALUES (%s,%s) RETURNING id", (associacao.id_turma,associacao.id_oferta))
associacao.id = BancoDeDados().pegarUltimoIDInserido()
return associacao
def removerAss_oferta_turma(self, associacao):
BancoDeDados().executar("DELETE FROM ass_oferta_turma WHERE id = %s", (str(associacao.id),))
def alterarAss_oferta_turma(self, associacao):
SQL = "UPDATE ass_oferta_turma SET id_turma=%s, id_oferta = %s WHERE id = %s"
BancoDeDados().executar(SQL, (associacao.id_turma,associacao.id_oferta,associacao.id))
| {
"repo_name": "AEDA-Solutions/matweb",
"path": "backend/Database/Controllers/Ass_oferta_turma.py",
"copies": "1",
"size": "1257",
"license": "mit",
"hash": 749441608622810400,
"line_mean": 47.3461538462,
"line_max": 150,
"alpha_frac": 0.7557677009,
"autogenerated": false,
"ratio": 2.459882583170254,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.37156502840702543,
"avg_score": null,
"num_lines": null
} |
from Framework.BancoDeDados import BancoDeDados
from Database.Models.Ass_periodo_disciplina import Ass_periodo_disciplina as ModelAss_periodo_disciplina
from Database.Models.Fluxo import Fluxo
class Ass_periodo_disciplina(object):
def pegarAss_periodo_disciplinas(self, condicao, valores):
associacoes = []
for associacao in BancoDeDados().consultarMultiplos("SELECT * FROM ass_periodo_disciplina %s" % (condicao), valores):
associacoes.append(ModelAss_periodo_disciplina(associacao))
return associacoes
def pegarAss_periodo_disciplina(self, condicao, valores):
return ModelAss_periodo_disciplina(BancoDeDados().consultarUnico("SELECT * FROM ass_periodo_disciplina %s" % (condicao), valores))
def inserirAss_periodo_disciplina(self, associacao):
BancoDeDados().executar("INSERT INTO ass_periodo_disciplina (id_disciplina,id_periodo) VALUES (%s,%s) RETURNING id", (associacao.id_disciplina,associacao.id_periodo))
associacao.id = BancoDeDados().pegarUltimoIDInserido()
return associacao
def removerAss_periodo_disciplina(self, associacao):
BancoDeDados().executar("DELETE FROM ass_periodo_disciplina WHERE id = %s", (str(associacao.id),))
def alterarAss_periodo_disciplina(self, associacao):
SQL = "UPDATE ass_periodo_disciplina SET id_disciplina=%s, id_periodo = %s WHERE id = %s"
BancoDeDados().executar(SQL, (associacao.id_disciplina,associacao.id_periodo,associacao.id))
def pegarResumoAss(self, condicao, valores):
associacoes = []
for associacao in BancoDeDados().consultarMultiplos("select periodo.id as id_periodo, (select nome from disciplina where id=ass_periodo_disciplina.id_disciplina) as nome_disciplina, ass_periodo_disciplina.id_disciplina, (select creditos from disciplina where id=ass_periodo_disciplina.id_disciplina) as creditos_disciplina from periodo inner join ass_periodo_disciplina on ass_periodo_disciplina.id_periodo=periodo.id %s" % (condicao),(valores)):
associacoes.append(Fluxo(associacao))
return associacoes | {
"repo_name": "AEDA-Solutions/matweb",
"path": "backend/Database/Controllers/Ass_periodo_disciplina.py",
"copies": "1",
"size": "1995",
"license": "mit",
"hash": 1959288499231076400,
"line_mean": 59.4848484848,
"line_max": 448,
"alpha_frac": 0.7844611529,
"autogenerated": false,
"ratio": 2.6181102362204722,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.8101423823281518,
"avg_score": 0.1602295131677908,
"num_lines": 33
} |
from Framework.BancoDeDados import BancoDeDados
from Database.Models.Ass_turma_prof import Ass_turma_prof as ModelAss_turma_prof
class Ass_turma_prof(object):
def pegarAss_turma_profs(self, condicao, valores):
associacoes = []
for associacao in BancoDeDados().consultarMultiplos("SELECT * FROM ass_turma_prof %s" % (condicao), valores):
associacoes.append(ModelAss_turma_prof(associacao))
return associacoes
def pegarAss_turma_prof(self, condicao, valores):
return ModelAss_turma_prof(BancoDeDados().consultarUnico("SELECT * FROM ass_turma_prof %s" % (condicao), valores))
def inserirAss_turma_prof(self, associacao):
BancoDeDados().executar("INSERT INTO ass_turma_prof (id_turma,id_prof) VALUES (%s,%s) RETURNING id", (associacao.id_turma,associacao.id_prof))
associacao.id = BancoDeDados().pegarUltimoIDInserido()
return associacao
def removerAss_turma_prof(self, associacao):
BancoDeDados().executar("DELETE FROM ass_turma_prof WHERE id = %s", (str(associacao.id),))
def alterarAss_turma_prof(self, associacao):
SQL = "UPDATE ass_turma_prof SET id_turma=%s, id_prof = %s WHERE id = %s"
BancoDeDados().executar(SQL, (associacao.id_turma,associacao.id_prof,associacao.id))
| {
"repo_name": "AEDA-Solutions/matweb",
"path": "backend/Database/Controllers/Ass_turma_prof.py",
"copies": "1",
"size": "1217",
"license": "mit",
"hash": 4478418217580472000,
"line_mean": 45.8076923077,
"line_max": 144,
"alpha_frac": 0.7477403451,
"autogenerated": false,
"ratio": 2.5783898305084745,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.7972541890073699,
"avg_score": 0.170717657106955,
"num_lines": 26
} |
from Framework.BancoDeDados import BancoDeDados
from Database.Models.Curriculo_disciplina import Curriculo_disciplina as ModelCurriculo_disciplina
class Curriculo_disciplina(object):
def pegarCurriculo_disciplina(self, condicao, valores):
curriculo_disciplinas = []
for curriculo_disciplina in BancoDeDados().consultarMultiplos("SELECT * FROM curriculo_disciplina %s" % (condicao), valores):
curriculo_disciplinas.append(ModelCurriculo_disciplina(curriculo_disciplina))
return curriculo_disciplinas
def pegarCurriculo_disciplina(self, condicao, valores):
return ModelCurriculo_disciplina(BancoDeDados().consultarUnico("SELECT * FROM curriculo_disciplina %s" % (condicao), valores))
def inserirCurriculo_disciplina(self, curriculo_disciplina):
BancoDeDados().executar("INSERT INTO curriculo_disciplina (obrigatorio,ciclo,grupo,id_disciplina,id_curriculo) VALUES (%s,%s,%s,%s,%s) RETURNING id", (curriculo_disciplina.obrigatorio,curriculo_disciplina.ciclo,curriculo_disciplina.grupo,curriculo_disciplina.id_disciplina,curriculo_disciplina.id_curriculo))
curriculo_disciplina.id = BancoDeDados().pegarUltimoIDInserido()
return curriculo_disciplina
def removerCurriculo_disciplina(self, curriculo_disciplina):
BancoDeDados().executar("DELETE FROM curriculo_disciplina WHERE id = %s", (str(curriculo_disciplina.id)))
def alterarCurriculo_disciplina(self, curriculo_disciplina):
SQL = "UPDATE curriculo_disciplina SET obrigatorio = %s, ciclo = %s, grupo = %s, id_disciplina = %s, id_curriculo = %s WHERE id = %s"
BancoDeDados().executar(SQL, (curriculo_disciplina.obrigatorio,curriculo_disciplina.ciclo,curriculo_disciplina.grupo,curriculo_disciplina.id_disciplina,curriculo_disciplina.id_curriculo))
| {
"repo_name": "AEDA-Solutions/matweb",
"path": "backend/Database/Controllers/Curriculo_disciplina.py",
"copies": "1",
"size": "1737",
"license": "mit",
"hash": -7681278459616296000,
"line_mean": 65.8076923077,
"line_max": 310,
"alpha_frac": 0.7990788716,
"autogenerated": false,
"ratio": 2.4464788732394367,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.7845206807176661,
"avg_score": 0.1800701875325552,
"num_lines": 26
} |
from Framework.BancoDeDados import BancoDeDados
from Database.Models.Curriculo import Curriculo as ModelCurriculo
class Curriculo(object):
def pegarCurriculos(self, condicao, valores):
curriculos = []
for curriculo in BancoDeDados().consultarMultiplos("SELECT * FROM curriculo %s" % (condicao), valores):
curriculos.append(ModelCurriculo(curriculo))
return curriculos
def pegarCurriculo(self, condicao, valores):
return ModelCurriculo(BancoDeDados().consultarUnico("SELECT * FROM curriculo %s" % (condicao), valores))
def inserirCurriculo(self, curriculo):
BancoDeDados().executar("INSERT INTO curriculo (id_curso,id_escopo_disciplina,id_disciplina) VALUES (%s,%s,%s) RETURNING id", (curriculo.id_curso,curriculo.id_escopo_disciplina,curriculo.id_disciplina))
curriculo.id = BancoDeDados().pegarUltimoIDInserido()
return curriculo
def removerCurriculo(self, curriculo):
BancoDeDados().executar("DELETE FROM curriculo WHERE id = %s", (str(curriculo.id)))
def alterarCurriculo(self, curriculo):
SQL = "UPDATE curriculo SET id_curso = %s, id_escopo_disciplina = %s, id_disciplina = %s WHERE id = %s"
BancoDeDados().executar(SQL, (curriculo.id_curso,curriculo.id_escopo_disciplina,curriculo.id_disciplina,curriculo.id_nivel))
| {
"repo_name": "AEDA-Solutions/matweb",
"path": "backend/Database/Controllers/Curriculo.py",
"copies": "1",
"size": "1264",
"license": "mit",
"hash": 3706906588792377300,
"line_mean": 47.6153846154,
"line_max": 204,
"alpha_frac": 0.7650316456,
"autogenerated": false,
"ratio": 2.5229540918163673,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.3787985737416367,
"avg_score": null,
"num_lines": null
} |
from Framework.BancoDeDados import BancoDeDados
from Database.Models.Curso import Curso as ModelCurso
class Curso(object):
def pegarCursos(self, condicao, valores):
cursos = []
for curso in BancoDeDados().consultarMultiplos("SELECT * FROM curso %s" % (condicao), valores):
cursos.append(ModelCurso(curso))
return cursos
def pegarCurso(self, condicao, valores):
return ModelCurso(BancoDeDados().consultarUnico("SELECT * FROM curso %s" % (condicao), valores))
def inserirCurso(self, curso):
BancoDeDados().executar("INSERT INTO curso (nome,codigo,id_campus,id_grau,permanencia_minima,permanencia_maxima,creditos_formatura,creditos_optativos_concentracao,creditos_optativos_conexa,creditos_livres_maximo,mec,credito_periodo_minimo,credito_periodo_maximo,turno) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s) RETURNING id", (curso.nome,curso.codigo,curso.id_campus,curso.id_grau,curso.permanencia_minima,curso.permanencia_maxima,curso.creditos_formatura,curso.creditos_optativos_concentracao,curso.creditos_optativos_conexa,curso.creditos_livres_maximo, curso.mec,curso.credito_perido_minimo,curso.credito_perido_maximo,curso.turno))
curso.id = BancoDeDados().pegarUltimoIDInserido()
return curso
def removerCurso(self, curso):
BancoDeDados().executar("DELETE FROM curso WHERE id = %s", (str(curso.id)))
def alterarCurso(self, curso):
SQL = "UPDATE curso SET nome = %s, codigo = %s, id_grau = %s, id_campus = %s, permanencia_minima = %s, permanencia_maxima = %s, creditos_formatura = %s, creditos_optativos_concentracao = %s, creditos_optativos_conexa = %s, creditos_livres_maximo = %s, mec = %s, credito_periodo_minimo = %s, credito_periodo_maximo = %s, turno = %s WHERE id = %s"
BancoDeDados().executar(SQL, (curso.nome,curso.codigo,curso.id_campus,curso.id_grau,curso.permanencia_minima,curso.permanencia_maxima,curso.creditos_formatura,curso.creditos_optativos_concentracao,curso.creditos_optativos_conexa,curso.creditos_livres_maximo,curso.mec,curso.credito_periodo_minimo,credito_periodo_maximo,curso.turno,curso.id))
| {
"repo_name": "AEDA-Solutions/matweb",
"path": "backend/Database/Controllers/Curso.py",
"copies": "1",
"size": "2066",
"license": "mit",
"hash": 5796986953110401000,
"line_mean": 78.4615384615,
"line_max": 646,
"alpha_frac": 0.766214908,
"autogenerated": false,
"ratio": 2.2579234972677598,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.352413840526776,
"avg_score": null,
"num_lines": null
} |
from Framework.BancoDeDados import BancoDeDados
from Database.Models.Departamento import Departamento as ModelDepartamento
class Departamento(object):
def pegarDepartamentos(self, condicao, valores):
departamentos = []
for departamento in BancoDeDados().consultarMultiplos("SELECT * FROM departamento %s" % (condicao), valores):
departamentos.append(ModelDepartamento(departamento))
return departamentos
def pegarDepartamento(self, condicao, valores):
return ModelDepartamento(BancoDeDados().consultarUnico("SELECT * FROM departamento %s" % (condicao), valores))
def inserirDepartamento(self, departamento):
BancoDeDados().executar("INSERT INTO departamento (nome,codigo,sigla,id_campus) VALUES (%s,%s,%s,%s) RETURNING id", (departamento.nome,departamento.codigo,departamento.sigla,departamento.id_campus))
departamento.id = BancoDeDados().pegarUltimoIDInserido()
return departamento
def removerDepartamento(self, departamento):
BancoDeDados().executar("DELETE FROM departamento WHERE id = %s", (str(departamento.id),))
def alterarDepartamento(self, departamento):
SQL = "UPDATE departamento SET nome = %s, codigo = %s, sigla = %s, id_campus = %s WHERE id = %s"
BancoDeDados().executar(SQL, (departamento.nome,departamento.codigo,departamento.sigla,departamento.id_campus,departamento.id))
| {
"repo_name": "AEDA-Solutions/matweb",
"path": "backend/Database/Controllers/Departamento.py",
"copies": "1",
"size": "1333",
"license": "mit",
"hash": 3837283289547098600,
"line_mean": 50.2692307692,
"line_max": 200,
"alpha_frac": 0.7756939235,
"autogenerated": false,
"ratio": 2.788702928870293,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4064396852370293,
"avg_score": null,
"num_lines": null
} |
from Framework.BancoDeDados import BancoDeDados
from Database.Models.Disciplina import Disciplina as ModelDisciplina
class Disciplina(object):
def pegarDisciplinas(self, condicao, valores):
disciplinas = []
for disciplina in BancoDeDados().consultarMultiplos("SELECT * FROM disciplina %s" % (condicao), valores):
disciplinas.append(ModelDisciplina(disciplina))
return disciplinas
def pegarDisciplina(self, condicao, valores):
return ModelDisciplina(BancoDeDados().consultarUnico("SELECT * FROM disciplina %s" % (condicao), valores))
def inserirDisciplina(self, disciplina):
BancoDeDados().executar("INSERT INTO disciplina (nome,codigo,id_departamento,creditos) VALUES (%s,%s,%s,%s) RETURNING id", (disciplina.nome,disciplina.codigo,disciplina.id_departamento,disciplina.creditos))
disciplina.id = BancoDeDados().pegarUltimoIDInserido()
return disciplina
def removerDisciplina(self, disciplina):
BancoDeDados().executar("DELETE FROM disciplina WHERE id = %s", (str(disciplina.id),))
def alterarDisciplina(self, disciplina):
SQL = "UPDATE disciplina SET nome = %s, codigo = %s, id_departamento = %s, creditos = %s WHERE id = %s"
BancoDeDados().executar(SQL, (disciplina.nome,disciplina.codigo,disciplina.id_departamento,disciplina.creditos,disciplina.id))
| {
"repo_name": "AEDA-Solutions/matweb",
"path": "backend/Database/Controllers/Disciplina.py",
"copies": "1",
"size": "1296",
"license": "mit",
"hash": -8394590215750439000,
"line_mean": 48.8461538462,
"line_max": 208,
"alpha_frac": 0.7700617284,
"autogenerated": false,
"ratio": 2.5362035225048922,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.7886473671464862,
"avg_score": 0.18395831588800604,
"num_lines": 26
} |
from Framework.BancoDeDados import BancoDeDados
from Database.Models.Escopo_disciplina import Escopo_disciplina as ModelEscopo_disciplina
class Escopo_disciplina(object):
def pegarMultiplosEscopo_disciplina(self, condicao, valores):
escopo_disciplina = []
for escopo in BancoDeDados().consultarMultiplos("SELECT * FROM escopo_disciplina %s" % (condicao), valores):
escopo_disciplina.append(ModelEscopo_disciplina(escopo))
return escopo_disciplina
def pegarEscopo_disciplina(self, condicao, valores):
return ModelEscopo_disciplina(BancoDeDados().consultarUnico("SELECT * FROM escopo_disciplina %s" % (condicao), valores))
def inserirEscopo_disciplina(self, escopo_disciplina):
BancoDeDados().executar("INSERT INTO escopo_disciplina ( nome ) VALUES ( %s ) RETURNING id", (escopo_disciplina.nome,))
escopo_disciplina.id = BancoDeDados().pegarUltimoIDInserido()
return escopo_disciplina
def removerEscopo_disciplina(self, escopo_disciplina):
BancoDeDados().executar("DELETE FROM escopo_disciplina WHERE id = %s", (str(escopo_disciplina.id),))
def alterarEscopo_disciplina(self, escopo_disciplina):
SQL = "UPDATE escopo_disciplina SET nome = %s WHERE id = %s"
BancoDeDados().executar(SQL, (escopo_disciplina.nome,escopo_disciplina.id))
| {
"repo_name": "AEDA-Solutions/matweb",
"path": "backend/Database/Controllers/Escopo_disciplina.py",
"copies": "1",
"size": "1274",
"license": "mit",
"hash": 3876588573413833000,
"line_mean": 48,
"line_max": 122,
"alpha_frac": 0.773155416,
"autogenerated": false,
"ratio": 2.412878787878788,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.7848141327859633,
"avg_score": 0.16757857520383102,
"num_lines": 26
} |
from Framework.BancoDeDados import BancoDeDados
from Database.Models.Fluxo import Fluxo as ModelFluxo
class Fluxo(object):
def pegarFluxo(self, condicao, valores):
fluxos = []
for fluxo in BancoDeDados().consultarMultiplos("SELECT * FROM fluxo %s" % (condicao), valores):
fluxos.append(ModelFluxo(fluxo))
return fluxos
def pegarFluxo(self, condicao, valores):
return ModelFluxo(BancoDeDados().consultarUnico("SELECT * FROM fluxo %s" % (condicao), valores))
def inserirFluxo(self, fluxo):
BancoDeDados().executar("INSERT INTO fluxo (periodo_inicio, periodo_fim, id_curso, id_opcao) VALUES (%s,%s,%s,%s) RETURNING id", (fluxo.periodo_inicio,fluxo.periodo_fim,fluxo.id_curso,fluxo.id_opcao))
fluxo.id = BancoDeDados().pegarUltimoIDInserido()
return fluxo
def removerFluxo(self, fluxo):
BancoDeDados().executar("DELETE FROM fluxo WHERE id = %s", (str(fluxo.id)))
def alterarFluxo(self, fluxo):
SQL = "UPDATE fluxo SET periodo_inicio = %s, periodo_fim = %s, id_curso = %s, id_opcao = %s WHERE id = %s"
BancoDeDados().executar(SQL, (fluxo.periodo_inicio,fluxo.periodo_fim,fluxo.id_curso,fluxo.id_opcao))
| {
"repo_name": "AEDA-Solutions/matweb",
"path": "backend/Database/Controllers/Fluxo.py",
"copies": "1",
"size": "1140",
"license": "mit",
"hash": 857239905055652200,
"line_mean": 42.8461538462,
"line_max": 202,
"alpha_frac": 0.7280701754,
"autogenerated": false,
"ratio": 2.441113490364026,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.7733172181650656,
"avg_score": 0.18720229682267409,
"num_lines": 26
} |
from Framework.BancoDeDados import BancoDeDados
from Database.Models.Horario import Horario as ModelHorario
class Horario(object):
def pegarHorarios(self, condicao, valores):
horarios = []
for horario in BancoDeDados().consultarMultiplos("SELECT * FROM horario %s" % (condicao), valores):
horarios.append(ModelHorario(horario))
return horarios
def pegarHorario(self, condicao, valores):
return ModelHorario(BancoDeDados().consultarUnico("SELECT * FROM horario %s" % (condicao), valores))
def inserirHorario(self, horario):
BancoDeDados().executar("INSERT INTO horario (inicio,fim,dia) VALUES (%s,%s,%s) RETURNING id", (horario.inicio,horario.fim,horario.dia))
horario.id = BancoDeDados().pegarUltimoIDInserido()
return horario
def removerHorario(self, horario):
BancoDeDados().executar("DELETE FROM horario WHERE id = %s", (str(horario.id)))
def alterarHorario(self, horario):
SQL = "UPDATE horario SET inicio = %s, fim = %s, dia = %s WHERE id = %s"
BancoDeDados().executar(SQL, (horario.inicio,horario.fim,horario.dia,horario.id))
| {
"repo_name": "AEDA-Solutions/matweb",
"path": "backend/Database/Controllers/Horario.py",
"copies": "1",
"size": "1075",
"license": "mit",
"hash": -8794042782464386000,
"line_mean": 40.3461538462,
"line_max": 138,
"alpha_frac": 0.7386046512,
"autogenerated": false,
"ratio": 2.541371158392435,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.7912179725050041,
"avg_score": 0.1735592169084788,
"num_lines": 26
} |
from Framework.BancoDeDados import BancoDeDados
from Database.Models.Matricula import Matricula as ModelMatricula
class Matricula(object):
def pegarMatriculas(self, condicao, valores):
matriculas = []
for curso in BancoDeDados().consultarMultiplos("SELECT * FROM matricula %s" % (condicao), valores):
matriculas.append(ModelMatricula(matricula))
return matriculas
def pegarMatricula(self, condicao, valores):
return ModelMatricula(BancoDeDados().consultarUnico("SELECT * FROM matricula %s" % (condicao), valores))
def inserirMatricula(self, matricula):
BancoDeDados().executar("INSERT INTO matricula (id_disciplina,id_turma,id_usuario,status) VALUES (%s,%s,%s,%s) RETURNING id", (matricula.id_disciplina,matricula.id_turma,matricula.id_usuario,matricula.status))
matricula.id = BancoDeDados().pegarUltimoIDInserido()
return matricula
def removerMatricula(self, matricula):
BancoDeDados().executar("DELETE FROM matricula WHERE id = %s", (str(matricula.id)))
def alterarMatricula(self, matricula):
SQL = "UPDATE matricula SET id_disciplina = %s, id_turma = %s, id_usuario = %s, status = %s WHERE id = %s"
BancoDeDados().executar(SQL, (matricula.id_disciplina,matricula.id_turma,matricula.id_usuario,matricula.status,matricula.id))
| {
"repo_name": "AEDA-Solutions/matweb",
"path": "backend/Database/Controllers/Matricula.py",
"copies": "1",
"size": "1270",
"license": "mit",
"hash": 4243086258105785000,
"line_mean": 49.8,
"line_max": 211,
"alpha_frac": 0.7606299213,
"autogenerated": false,
"ratio": 2.5760649087221097,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.383669483002211,
"avg_score": null,
"num_lines": null
} |
from Framework.BancoDeDados import BancoDeDados
from Database.Models.Oferta import Oferta as ModelOferta
class Oferta(object):
def pegarOfertass(self, condicao, valores):
ofertas = []
for oferta in BancoDeDados().consultarMultiplos("SELECT * FROM oferta %s" % (condicao), valores):
ofertas.append(ModelOferta(oferta))
return ofertas
def pegarOferta(self, condicao, valores):
return ModelOferta(BancoDeDados().consultarUnico("SELECT * FROM oferta %s" % (condicao), valores))
def inserirOferta(self, oferta):
BancoDeDados().executar("INSERT INTO oferta (creditos,id_disciplina,id_ementa) VALUES (%s,%s,%s) RETURNING id", (oferta.creditos,oferta.id_disciplina,oferta.id_ementa))
oferta.id = BancoDeDados().pegarUltimoIDInserido()
return oferta
def removerOferta(self, oferta):
BancoDeDados().executar("DELETE FROM oferta WHERE id = %s", (str(oferta.id),))
def alterarOferta(self, oferta):
SQL = "UPDATE oferta SET creditos = %s, id_disciplina = %s, id_ementa = %s WHERE id = %s"
BancoDeDados().executar(SQL, (oferta.creditos,oferta.id_disciplina,oferta.id_ementa,oferta.id))
| {
"repo_name": "AEDA-Solutions/matweb",
"path": "backend/Database/Controllers/Oferta.py",
"copies": "1",
"size": "1115",
"license": "mit",
"hash": 2247761858371273000,
"line_mean": 41.8846153846,
"line_max": 170,
"alpha_frac": 0.7399103139,
"autogenerated": false,
"ratio": 2.372340425531915,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.36122507394319153,
"avg_score": null,
"num_lines": null
} |
from Framework.BancoDeDados import BancoDeDados
from Database.Models.Periodo import Periodo as ModelPeriodo
class Periodo(object):
def pegarPeriodos(self, condicao, valores):
periodos = []
for periodo in BancoDeDados().consultarMultiplos("SELECT * FROM periodo %s" % (condicao), valores):
periodos.append(ModelPeriodo(periodo))
return periodos
def pegarPeriodo(self, condicao, valores):
return ModelPeriodo(BancoDeDados().consultarUnico("SELECT * FROM periodo %s" % (condicao), valores))
def inserirPeriodo(self, periodo):
BancoDeDados().executar("INSERT INTO periodo (id_curso,periodo,creditos) VALUES (%s,%s,%s) RETURNING id", (periodo.id_curso,periodo.periodo,periodo.creditos))
periodo.id = BancoDeDados().pegarUltimoIDInserido()
return periodo
def removerPeriodo(self, periodo):
BancoDeDados().executar("DELETE FROM periodo WHERE id = %s", (str(periodo.id),))
def alterarPeriodo(self, periodo):
SQL = "UPDATE periodo SET id_curso = %s, periodo = %s, creditos = %s WHERE id = %s"
BancoDeDados().executar(SQL, (periodo.id_curso,periodo.periodo,periodo.creditos,periodo.id))
| {
"repo_name": "AEDA-Solutions/matweb",
"path": "backend/Database/Controllers/Periodo.py",
"copies": "1",
"size": "1119",
"license": "mit",
"hash": -2361849517818275000,
"line_mean": 42.0384615385,
"line_max": 160,
"alpha_frac": 0.745308311,
"autogenerated": false,
"ratio": 2.6963855421686747,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.3941693853168674,
"avg_score": null,
"num_lines": null
} |
from Framework.BancoDeDados import BancoDeDados
from Database.Models.Predio import Predio as ModelPredio
class Predio(object):
def pegarPredios(self, condicao, valores):
predios = []
for predio in BancoDeDados().consultarMultiplos("SELECT * FROM predio %s" % (condicao), valores):
predios.append(ModelPredio(predio))
return predios
def pegarPredio(self, condicao, valores):
return ModelPredio(BancoDeDados().consultarUnico("SELECT * FROM predio %s" % (condicao), valores))
def inserirPredio(self, predio):
BancoDeDados().executar("INSERT INTO predio (nome, sigla, latitude, longitude, id_campus) VALUES (%s,%s,%s,%s,%s) RETURNING id", (predio.nome,predio.sigla,predio.latitude,predio.longitude,predio.id_campus))
predio.id = BancoDeDados().pegarUltimoIDInserido()
return predio
def removerPredio(self, predio):
BancoDeDados().executar("DELETE FROM predio WHERE id = %s", (str(predio.id)))
def alterarPredio(self, predio):
SQL = "UPDATE predio SET nome = %s, sigla = %s, latitude = %s, longitude = %s, id_campus = %s WHERE id = %s"
BancoDeDados().executar(SQL, (predio.nome,predio.sigla,predio.latitude,predio.longitude,predio.id_campus,predio.id))
| {
"repo_name": "AEDA-Solutions/matweb",
"path": "backend/Database/Controllers/Predio.py",
"copies": "1",
"size": "1191",
"license": "mit",
"hash": 6000355473129657000,
"line_mean": 44.8076923077,
"line_max": 208,
"alpha_frac": 0.7355163728,
"autogenerated": false,
"ratio": 2.6704035874439462,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.8035810500889089,
"avg_score": 0.17402189187097156,
"num_lines": 26
} |
from Framework.BancoDeDados import BancoDeDados
from Database.Models.Prereq import Prereq as ModelPrereq
class Prereq(object):
def pegarPrereqs(self, condicao, valores):
prereqs = []
for prereq in BancoDeDados().consultarMultiplos("SELECT * FROM prereq %s" % (condicao), valores):
prereqs.append(ModelPrereq(prereq))
return prereqs
def pegarPrereq(self, condicao, valores):
return ModelPrereq(BancoDeDados().consultarUnico("SELECT * FROM prereq %s" % (condicao), valores))
def inserirPrereq(self, prereq):
BancoDeDados().executar("INSERT INTO prereq (grupo, id_disc_pre ) VALUES (%s,%s) RETURNING id", (prereq.grupo,prereq.id_disc_pre))
prereq.id = BancoDeDados().pegarUltimoIDInserido()
return prereq
def removerPrereq(self, prereq):
BancoDeDados().executar("DELETE FROM prereq WHERE id = %s", (str(prereq.id)))
def alterarPrereq(self, prereq):
SQL = "UPDATE prereq SET grupo = %s, id_disc_pre = %s WHERE id = %s"
BancoDeDados().executar(SQL, (prereq.grupo,prereq.id_disc_pre,prereq.id)) | {
"repo_name": "AEDA-Solutions/matweb",
"path": "backend/Database/Controllers/Prereq.py",
"copies": "1",
"size": "1031",
"license": "mit",
"hash": 1201934056806937000,
"line_mean": 38.6923076923,
"line_max": 132,
"alpha_frac": 0.731328807,
"autogenerated": false,
"ratio": 2.610126582278481,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.7974341208779017,
"avg_score": 0.173422836099893,
"num_lines": 26
} |
from Framework.BancoDeDados import BancoDeDados
from Database.Models.Professor import Professor as ModelProfessor
class Professor(object):
def pegarProfessors(self, condicao, valores):
professors = []
for professor in BancoDeDados().consultarMultiplos("SELECT * FROM professor %s" % (condicao), valores):
professors.append(ModelProfessor(professor))
return professors
def pegarProfessor(self, condicao, valores):
return ModelProfessor(BancoDeDados().consultarUnico("SELECT * FROM professor %s" % (condicao), valores))
def inserirProfessor(self, professor):
BancoDeDados().executar("INSERT INTO professor (nome) VALUES (%s) RETURNING id", (professor.nome,))
professor.id = BancoDeDados().pegarUltimoIDInserido()
return professor
def removerProfessor(self, professor):
BancoDeDados().executar("DELETE FROM professor WHERE id = %s", (str(professor.id),))
def alterarProfessor(self, professor):
SQL = "UPDATE professor SET nome = %s WHERE id = %s"
BancoDeDados().executar(SQL, (professor.nome,professor.id))
| {
"repo_name": "AEDA-Solutions/matweb",
"path": "backend/Database/Controllers/Professor.py",
"copies": "1",
"size": "1047",
"license": "mit",
"hash": -2753391772296741400,
"line_mean": 39.2692307692,
"line_max": 106,
"alpha_frac": 0.7545367717,
"autogenerated": false,
"ratio": 2.528985507246377,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.3783522278946377,
"avg_score": null,
"num_lines": null
} |
from Framework.BancoDeDados import BancoDeDados
from Database.Models.Registro import Registro_login as ModelRegistro
class Registro_login(object):
def pegarRegistro(self, condicao, valores):
registro = []
for registro in BancoDeDados().consultarMultiplos("SELECT * FROM registro_login %s" % (condicao), valores):
registro.append(ModelRegistro(registro))
return registro
def pegarRegistro(self, condicao, valores):
return ModelRegistro(BancoDeDados().consultarUnico("SELECT * FROM registro_login %s" % (condicao), valores))
def inserirRegistro(self, registro):
BancoDeDados().executar("INSERT INTO registro_login (id, token, id_usuario, ip, entrada) VALUES (%s,%s,%s,%s,%s) RETURNING id", (registro.id, registro.token, registro.id_usuario, registro.ip, registro.entrada))
registro.id = BancoDeDados().pegarUltimoIDInserido()
return registro
def removerRegistro(self, registro):
BancoDeDados().executar("DELETE FROM registro_login WHERE id = %s", (str(registro.id)))
def alterarRegistro(self, registro):
SQL = "UPDATE registro_login SET token = %s, id_usuario = %s, ip = %s, entrada = %s WHERE id = %s"
BancoDeDados().executar(SQL, (registro.token, registro.id_usuario, registro.ip, registro.entrada, registro.id))
| {
"repo_name": "AEDA-Solutions/matweb",
"path": "backend/Database/Controllers/Registro_login.py",
"copies": "1",
"size": "1256",
"license": "mit",
"hash": 3792869921205075000,
"line_mean": 47.3076923077,
"line_max": 212,
"alpha_frac": 0.7436305732,
"autogenerated": false,
"ratio": 2.6837606837606836,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.3927391256960684,
"avg_score": null,
"num_lines": null
} |
from Framework.BancoDeDados import BancoDeDados
from Database.Models.RegistroLogin import RegistroLogin as ModelRegistroLogin
class RegistroLogin(object):
def pegarRegistro(self, condicao, valores):
registro = []
for registro in BancoDeDados().consultarMultiplos("SELECT * FROM registro_login %s" % (condicao), valores):
registro.append(ModelRegistro(registro))
return registro
def pegarRegistro(self, condicao, valores):
return ModelRegistro(BancoDeDados().consultarUnico("SELECT * FROM registro_login %s" % (condicao), valores))
def inserirRegistro(self, registro):
BancoDeDados().executar("INSERT INTO registro_login (token, id_usuario, ip) VALUES (%s,%s,%s) RETURNING id", (registro.token, registro.id_usuario, registro.ip))
registro.id = BancoDeDados().pegarUltimoIDInserido()
return registro
def removerRegistro(self, registro):
BancoDeDados().executar("DELETE FROM registro_login WHERE id = %s", (str(registro.id)))
def alterarRegistro(self, registro):
SQL = "UPDATE registro_login SET token = %s, id_usuario = %s, ip = %s, entrada = %s WHERE id = %s"
BancoDeDados().executar(SQL, (registro.token, registro.id_usuario, registro.ip, registro.entrada, registro.id))
| {
"repo_name": "AEDA-Solutions/matweb",
"path": "backend/Database/Controllers/RegistroLogin.py",
"copies": "1",
"size": "1214",
"license": "mit",
"hash": 5814592693820910000,
"line_mean": 45.6923076923,
"line_max": 162,
"alpha_frac": 0.7479406919,
"autogenerated": false,
"ratio": 2.7219730941704037,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.39699137860704037,
"avg_score": null,
"num_lines": null
} |
from Framework.BancoDeDados import BancoDeDados
from Database.Models.Resp_sala import Resp_sala as ModelResp_sala
class Resp_sala(object):
def pegarMultiplosResp_sala(self, condicao, valores):
resps_sala = []
for resp_sala in BancoDeDados().consultarMultiplos("SELECT * FROM resp_sala %s" % (condicao), valores):
resps_sala.append(ModelResp_sala(resp_sala))
return resps_sala
def pegarResp_sala(self, condicao, valores):
return ModelResp_sala(BancoDeDados().consultarUnico("SELECT * FROM resp_sala %s" % (condicao), valores))
def inserirResp_sala(self, resp_sala):
BancoDeDados().executar("INSERT INTO resp_sala ( nome ) VALUES ( %s ) RETURNING id", (resp_sala.nome,))
resp_sala.id = BancoDeDados().pegarUltimoIDInserido()
return resp_sala
def removerResp_sala(self, resp_sala):
BancoDeDados().executar("DELETE FROM resp_sala WHERE id = %s", (str(resp_sala.id)))
def alterarResp_sala(self, resp_sala):
SQL = "UPDATE resp_sala SET nome = %s WHERE id = %s"
BancoDeDados().executar(SQL, (resp_sala.nome,resp_sala.id))
| {
"repo_name": "AEDA-Solutions/matweb",
"path": "backend/Database/Controllers/Resp_sala.py",
"copies": "1",
"size": "1058",
"license": "mit",
"hash": 1907575052547631600,
"line_mean": 39.6923076923,
"line_max": 106,
"alpha_frac": 0.7258979206,
"autogenerated": false,
"ratio": 2.5011820330969265,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.3727079953696926,
"avg_score": null,
"num_lines": null
} |
from Framework.BancoDeDados import BancoDeDados
from Database.Models.Sala import Sala as ModelSala
class Sala(object):
def pegarSalas(self, condicao, valores):
salas = []
for sala in BancoDeDados().consultarMultiplos("SELECT * FROM sala %s" % (condicao), valores):
salas.append(ModelSala(sala))
return salas
def pegarSala(self, condicao, valores):
return ModelSala(BancoDeDados().consultarUnico("SELECT * FROM sala %s" % (condicao), valores))
def inserirSala(self, sala):
BancoDeDados().executar("INSERT INTO sala (id_resp_sala,codigo,id_predio) VALUES (%s,%s,%s) RETURNING id", (sala.id_resp_sala,sala.codigo,sala.id_predio))
sala.id = BancoDeDados().pegarUltimoIDInserido()
return sala
def removerSala(self, sala):
BancoDeDados().executar("DELETE FROM sala WHERE id = %s", (str(sala.id),))
def alterarSala(self, sala):
SQL = "UPDATE sala SET id_resp_sala = %s, codigo = %s, id_predio = %s WHERE id = %s"
BancoDeDados().executar(SQL, (sala.id_resp_sala,sala.codigo,sala.id_predio,sala.id))
| {
"repo_name": "AEDA-Solutions/matweb",
"path": "backend/Database/Controllers/Sala.py",
"copies": "1",
"size": "1034",
"license": "mit",
"hash": 2310484503710601000,
"line_mean": 38.7692307692,
"line_max": 156,
"alpha_frac": 0.7156673114,
"autogenerated": false,
"ratio": 2.421545667447307,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.3637212978847307,
"avg_score": null,
"num_lines": null
} |
from Framework.BancoDeDados import BancoDeDados
from Database.Models.Turma import Turma as ModelTurma
class Turma(object):
def pegarTurmas(self, condicao, valores):
turmas = []
for turma in BancoDeDados().consultarMultiplos("SELECT * FROM turma %s" % (condicao), valores):
turmas.append(ModelTurma(turma))
return turmas
def pegarTurma(self, condicao, valores):
return ModelTurma(BancoDeDados().consultarUnico("SELECT * FROM turma %s" % (condicao), valores))
def inserirTurma(self, turma):
BancoDeDados().executar("INSERT INTO turma (letra,id_disciplina,id_professor,vagas,ocupadas,restantes,turno) VALUES (%s,%s,%s,%s,%s,%s,%s) RETURNING id", (turma.letra,turma.id_disciplina,turma.id_professor,turma.vagas,turma.ocupadas,turma.restantes,turma.turno))
turma.id = BancoDeDados().pegarUltimoIDInserido()
return turma
def removerTurma(self, turma):
BancoDeDados().executar("DELETE FROM turma WHERE id = %s", (str(turma.id)))
def alterarTurma(self, turma):
SQL = "UPDATE turma SET letra = %s, id_disciplina = %s, id_professor = %s, vagas = %s, ocupadas = %s, restantes = %s, turno = %s WHERE id = %s"
BancoDeDados().executar(SQL, (turma.letra,turma.id_disciplina,turma.id_professor,turma.vagas,turma.ocupadas,turma.restantes,turma.turno,turma.id))
| {
"repo_name": "AEDA-Solutions/matweb",
"path": "backend/Database/Controllers/Turma.py",
"copies": "1",
"size": "1287",
"license": "mit",
"hash": 2114747320501727500,
"line_mean": 48.5,
"line_max": 264,
"alpha_frac": 0.735042735,
"autogenerated": false,
"ratio": 2.314748201438849,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.3549790936438849,
"avg_score": null,
"num_lines": null
} |
from Framework.BancoDeDados import BancoDeDados
from Database.Models.Usuario import Usuario as ModelUsuario
class Usuario(object):
def pegarUsuarios(self, condicao, valores):
usuarios = []
for usuario in BancoDeDados().consultarMultiplos("SELECT * FROM usuario %s" % (condicao), valores):
usuarios.append(ModelUsuario(usuario))
return usuarios
def pegarUsuario(self, condicao, valores):
usuario = BancoDeDados().consultarUnico("SELECT * FROM usuario %s" % (condicao), valores)
if usuario is not None:
return ModelUsuario(usuario)
else:
return None
def inserirUsuario(self, usuario):
BancoDeDados().executar("INSERT INTO usuario (matricula, nome, cpf, perfil, email, sexo, nome_pai, nome_mae, ano_conclusao, identidade, senha, id_curso) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s) RETURNING id", (usuario.matricula, usuario.nome, usuario.cpf, usuario.perfil, usuario.email, usuario.sexo, usuario.nome_pai, usuario.nome_mae, usuario.ano_conclusao, usuario.identidade, usuario.senha, usuario.id_curso))
usuario.id = BancoDeDados().pegarUltimoIDInserido()
return usuario
def removerUsuario(self, usuario):
BancoDeDados().executar("DELETE FROM usuario WHERE id = %s", (str(usuario.id),))
def alterarUsuario(self, usuario):
SQL = "UPDATE usuario SET matricula = %s, nome = %s, cpf = %s, perfil = %s, email = %s, sexo = %s, nome_pai = %s, nome_mae = %s, ano_conclusao = %s, identidade = %s, senha = %s, id_curso = %s WHERE id = %s"
BancoDeDados().executar(SQL, (usuario.matricula, usuario.nome, usuario.cpf, usuario.perfil, usuario.email, usuario.sexo, usuario.nome_pai, usuario.nome_mae, usuario.ano_conclusao, usuario.identidade, usuario.senha, usuario.id_curso, usuario.id))
| {
"repo_name": "AEDA-Solutions/matweb",
"path": "backend/Database/Controllers/Usuario.py",
"copies": "1",
"size": "1725",
"license": "mit",
"hash": 1644292641504850200,
"line_mean": 56.5,
"line_max": 419,
"alpha_frac": 0.7257971014,
"autogenerated": false,
"ratio": 2.324797843665768,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.3550594945065768,
"avg_score": null,
"num_lines": null
} |
from framework.basicstimuli import BasicStimuli
from psychopy import visual,core,event # import some libraries from PsychoPy
from serial import *
import io, os, glob
import matplotlib.pyplot as plt
from pylab import *
class Main(BasicStimuli):
def __init__(self):
BasicStimuli.__init__(self)
def define_path(self):
os.chdir("C:\\Users\\villa_000\\Dropbox\\python\\RSVP\\image1")
# read data from text file
def read_data(self):
# data=[]
# f=io.open('RSVP.txt','r')
# data0=f.readlines()
# for i in range(0,len(data0)):
# if data0[i]!='\n':# remove blank newlines
# data.append(data0[i])
# for i in range(0,len(data)):
# data[i]=data[i].replace('\n','')
# num=sum(1 for _ in data)
# f.close()
f=open('RSVP.txt','rb')
data=[]
marker=[]
for columns in (raw.strip().split() for raw in f):
data.append(columns[0])
marker.append(columns[1])
data.remove(data[0])
marker.remove(marker[0])
num=len(data)
return data,marker,num # returns data text file and number images
# def trigger(marker):
# port=parallel.ParallelPort(address=0x0378)
# trigger_port=port.setData( int("00000000",2) ),port.setData( int("00000001",2) )#pin2 low pin2 high
# return trigger_port
def win_display(self):
win=visual.Window([1000,800])
return win
def RSVP_paradigm(sefl,data,ti,win,marker):
# data is text file, ti is time interval between each image
result=[] # define output
message = visual.TextStim(win, text='Loading images.....')
message.draw()
win.update()
image_list=[] # preload image list
# preload images
for i in range(0,len(data)):
image_list.append(visual.ImageStim(win,data[i],size=(2,2)))
# -----------------------------------------fixation----------------------------
message1 = visual.TextStim(win, text='Attention please')
message1.draw()
win.update()
core.wait(1.0)
fixation = visual.ShapeStim(win,
vertices=((0, -0.2), (0, 0.2), (0,0), (-0.2,0), (0.2, 0)),
lineWidth=5,
closeShape=False,
lineColor='white')
fixation.draw()
win.update()
core.wait(3.0)
onsetTime=core.getTime()
#----------------------------------------define timing------------------------
image_time=[] # interval between two stimuli
RT=[] # subjective reaction time and the choice of stimuli target
t_remaining=[] # time of code exeuating
# ----------------------------------display stimuli----------------------
for i in range(0,len(data)):
t_start=core.getTime()
image_time.append(core.getTime())
image=image_list[i]
# if marker[i]==True:
# trigger(marker)[1]
# else:
# trigger(marker)[0]
image.draw()
win.flip()
keys = event.getKeys(keyList=['space', 'escape'])
if keys:
RT.append([core.getTime(),i])
t_elipse=core.getTime()
t_remaining.append(t_elipse-t_start)
core.wait(ti-t_remaining[i])
win.close()
# store output
result.append(RT)
result.append(image_time)
result.append(t_remaining)
return result, win
# ----------------------------check the actual time interval------------------------------
def plot_ti(self,ti):
plt.hist(ti)
plt.title('Histogram of actrual time interval')
plt.xlabel('Time interval (s)')
plt.ylabel('Number')
plt.show()
def calculate_ti(self,image_time):
ti=[] # actual time interval
for i in range(1,len(image_time)):
ti.append(image_time[i]-image_time[i-1])
return ti
#------------------------------------------------------------------------------------------
def run(self):
self.define_path()
data,marker,num=self.read_data()
win=self.win_display()
result,win=self.RSVP_paradigm(data,0.1,win,marker)
ti=self.calculate_ti(result[1])
self.plot_ti(ti)
print data, marker # 1 is target, 0 is non-target
# if __name__=='__main__':
# main()
| {
"repo_name": "villawang/SNAP",
"path": "src/modules/RSVP_paradigm.py",
"copies": "1",
"size": "4613",
"license": "bsd-3-clause",
"hash": 6619381154772749000,
"line_mean": 30.2587412587,
"line_max": 113,
"alpha_frac": 0.4936050293,
"autogenerated": false,
"ratio": 3.8441666666666667,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9750420537120557,
"avg_score": 0.017470231769222133,
"num_lines": 143
} |
from framework.brains.surgical.storage import InsecureStorage
from framework.brains.surgical.crypto import Crypto
from framework.brains.surgical.logging import Logging
from datetime import datetime
from blessings import Terminal
t = Terminal()
class SurgicalAPI(object):
def __init__(self, apks):
super(SurgicalAPI, self).__init__()
self.apk = apks
self.storage = InsecureStorage(apks)
self.crypto = Crypto(apks)
self.logging = Logging(apks)
self.functions = [f for f in self.storage, self.crypto, self.logging]
def run_surgical(self):
"""
Helper function for API
"""
print(t.green("[{0}] ".format(datetime.now()) +
t.yellow("Available functions: ")))
for f in self.functions:
print(t.green("[{0}] ".format(datetime.now())) +
f.__getattribute__("name"))
print(t.green("[{0}] ".format(datetime.now()) +
t.yellow("Enter \'quit\' to exit")))
while True:
# Assign target API
# function
#
function = raw_input(t.green("[{0}] ".format(datetime.now()) + t.yellow("Enter function: ")))
if function == "quit":
break
# Match on Class attribute
# and call run() function
# of target class
#
for f in self.functions:
if function == f.__getattribute__("name"):
f.run()
| {
"repo_name": "HackerTool/lobotomy",
"path": "framework/brains/surgical/api.py",
"copies": "4",
"size": "1524",
"license": "mit",
"hash": 5784309029206764000,
"line_mean": 30.1020408163,
"line_max": 105,
"alpha_frac": 0.5419947507,
"autogenerated": false,
"ratio": 4.198347107438017,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.6740341858138017,
"avg_score": null,
"num_lines": null
} |
from _Framework.ButtonElement import ButtonElement, ON_VALUE, OFF_VALUE
class ButtonElementEx(ButtonElement):
"""
A special type of ButtonElement that allows skinning (that can be
overridden when taking control)
"""
default_states = { True: 'DefaultButton.On', False: 'DefaultButton.Disabled' }
def __init__(self, default_states = None, *a, **k):
super(ButtonElementEx, self).__init__(*a, **k)
if default_states is not None:
self.default_states = default_states
self.states = dict(self.default_states)
def set_on_off_values(self, on = None, off = None):
self.states[True] = on or self.default_states[True]
self.states[False] = off or self.default_states[False]
def set_light(self, value):
value = self.states.get(value, value)
super(ButtonElementEx, self).set_light(value)
def send_color(self, color):
color.draw(self)
def send_value(self, value, **k):
if value is ON_VALUE:
self.set_light(True)
elif value is OFF_VALUE:
self.set_light(False)
else:
super(ButtonElementEx, self).send_value(value, **k)
| {
"repo_name": "bvalosek/ableton-live-scripts",
"path": "bvalosek_Midi_Fighter_Twister/ButtonElementEx.py",
"copies": "1",
"size": "1185",
"license": "mit",
"hash": -253015175164474460,
"line_mean": 32.8571428571,
"line_max": 82,
"alpha_frac": 0.6278481013,
"autogenerated": false,
"ratio": 3.6801242236024843,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9640886149912513,
"avg_score": 0.03341723499799412,
"num_lines": 35
} |
from _Framework.ButtonElement import Color, ButtonValue
from Debug import *
debug = initialize_debug()
class MonoColor(Color):
def draw(self, interface):
try:
interface.set_darkened_value(0)
super(MonoColor, self).draw(interface)
except:
super(MonoColor, self).draw(interface)
class BiColor(MonoColor):
def __init__(self, darkened_value = 0, *a, **k):
super(BiColor, self).__init__(*a, **k)
self._darkened_value = darkened_value
def draw(self, interface):
try:
interface.set_darkened_value(self._darkened_value)
interface.send_value(self.midi_value)
except:
debug(interface, 'is not MonoButtonElement, cannot use BiColor')
super(BiColor, self).draw(interface)
class LividRGB:
OFF = MonoColor(0)
WHITE = MonoColor(1)
YELLOW = MonoColor(2)
CYAN = MonoColor(3)
MAGENTA = MonoColor(4)
RED = MonoColor(5)
GREEN = MonoColor(6)
BLUE = MonoColor(7)
class BlinkFast:
WHITE = MonoColor(8)
YELLOW = MonoColor(9)
CYAN = MonoColor(10)
MAGENTA = MonoColor(11)
RED = MonoColor(12)
GREEN = MonoColor(13)
BLUE = MonoColor(14)
class BlinkMedium:
WHITE = MonoColor(15)
YELLOW = MonoColor(16)
CYAN = MonoColor(17)
MAGENTA = MonoColor(18)
RED = MonoColor(19)
GREEN = MonoColor(20)
BLUE = MonoColor(21)
class BlinkSlow:
WHITE = MonoColor(22)
YELLOW = MonoColor(23)
CYAN = MonoColor(24)
MAGENTA = MonoColor(25)
RED = MonoColor(26)
GREEN = MonoColor(27)
BLUE = MonoColor(28)
class BiColor:
class WHITE:
YELLOW = BiColor(1, 16)
CYAN = BiColor(1, 17)
MAGENTA = BiColor(1, 18)
RED = BiColor(1, 19)
GREEN = BiColor(1, 20)
BLUE = BiColor(1, 21)
class YELLOW:
WHITE = BiColor(2, 15)
CYAN = BiColor(2, 17)
MAGENTA = BiColor(2, 18)
RED = BiColor(2, 19)
GREEN = BiColor(2, 20)
BLUE = BiColor(2, 21)
class CYAN:
WHITE = BiColor(3, 15)
YELLOW = BiColor(3, 16)
MAGENTA = BiColor(3, 18)
RED = BiColor(3, 19)
GREEN = BiColor(3, 20)
BLUE = BiColor(3, 21)
class MAGENTA:
WHITE = BiColor(4, 15)
YELLOW = BiColor(4, 16)
CYAN = BiColor(4, 17)
RED = BiColor(4, 19)
GREEN = BiColor(4, 20)
BLUE = BiColor(4, 21)
class RED:
WHITE = BiColor(5, 15)
YELLOW = BiColor(5, 16)
CYAN = BiColor(5, 17)
MAGENTA = BiColor(5, 18)
GREEN = BiColor(5, 20)
BLUE = BiColor(5, 21)
class GREEN:
WHITE = BiColor(6, 15)
YELLOW = BiColor(6, 16)
CYAN = BiColor(6, 17)
MAGENTA = BiColor(6, 18)
RED = BiColor(6, 19)
BLUE = BiColor(6, 21)
class BLUE:
WHITE = BiColor(7, 15)
YELLOW = BiColor(7, 16)
CYAN = BiColor(7, 17)
MAGENTA = BiColor(7, 18)
RED = BiColor(7, 19)
GREEN = BiColor(7, 20)
| {
"repo_name": "LividInstruments/LiveRemoteScripts",
"path": "_Mono_Framework/LividColors.py",
"copies": "1",
"size": "2697",
"license": "mit",
"hash": 92222226236128590,
"line_mean": 18.5434782609,
"line_max": 67,
"alpha_frac": 0.6347793845,
"autogenerated": false,
"ratio": 2.4080357142857145,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.35428150987857143,
"avg_score": null,
"num_lines": null
} |
from _Framework.ButtonElement import Color
from _Framework.Skin import Skin
from Colors import *
class Colors:
class Modes:
Selected = ColorEx(Rgb.GREEN, Animation.PULSE_1_BEAT)
NotSelected = ColorEx(Rgb.GREEN, Brightness.LOW)
class DefaultButton:
On = ColorEx(Rgb.GREEN)
Disabled = ColorEx(Rgb.GREEN, Brightness.LOW)
Off = ColorEx(Rgb.OFF, Brightness.OFF)
class Device:
Lock = ColorEx(Rgb.BLUE, Brightness.LOW)
LockOffset = ColorEx(Rgb.ORANGE, Brightness.LOW)
Unlock = ColorEx(Rgb.RED, Animation.GATE_HALF_BEAT)
NormalParams = ColorEx(Rgb.BLUE, Animation.GATE_HALF_BEAT)
OffsetParams = ColorEx(Rgb.ORANGE, Animation.GATE_QUARTER_BEAT)
Select = ColorEx(Rgb.TEAL, Animation.GATE_HALF_BEAT)
MenuActive = ColorEx(Rgb.PURPLE, Animation.GATE_QUARTER_BEAT)
HalfSnap = ColorEx(Rgb.BLUE, Animation.GATE_HALF_BEAT)
ReverseHalfSnap = ColorEx(Rgb.GREEN, Animation.GATE_HALF_BEAT)
FullSnap = ColorEx(Rgb.PURPLE, Animation.GATE_HALF_BEAT)
def make_default_skin():
return Skin(Colors)
| {
"repo_name": "bvalosek/ableton-live-scripts",
"path": "bvalosek_Midi_Fighter_Twister/SkinDefault.py",
"copies": "1",
"size": "1115",
"license": "mit",
"hash": 5239528496871688000,
"line_mean": 33.84375,
"line_max": 71,
"alpha_frac": 0.6869955157,
"autogenerated": false,
"ratio": 3.029891304347826,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9043226105762112,
"avg_score": 0.03473214285714286,
"num_lines": 32
} |
from _Framework.ButtonElement import Color
from consts import *
class Rgb:
OFF = 0
BLUE = 1
AZURE = 10
TEAL = 20
MINT = 40
GREEN = 52
YELLOW = 61
ORANGE = 68
RED = 85
PINK_RED = 93
PINK = 100
FUCHSIA = 111
PURPLE = 115
class Animation:
NONE = 0
GATE_8_BEATS = 1
GATE_4_BEATS = 2
GATE_2_BEATS = 3
GATE_1_BEAT = 4
GATE_HALF_BEAT = 5
GATE_QUARTER_BEAT = 6
GATE_EIGHTH_BEAT = 7
GATE_SIXTEENTH_BEAT = 8
PULSE_8_BEATS = 10
PULSE_4_BEATS = 11
PULSE_2_BEATS = 12
PULSE_1_BEAT = 13
PULSE_HALF_BEAT = 14
PULSE_QUARTER_BEAT = 15
PULSE_EIGHTH_BEAT = 16
RAINBOW = 127
class Brightness:
OFF = 17
MIN = 18
LOW = 25
MID = 32
MAX = 47
class ColorEx(Color):
def __init__(self, midi_value = Rgb.BLUE, animation = Animation.NONE, *a, **k):
super(ColorEx, self).__init__(midi_value, *a, **k)
self._animation = animation
def draw(self, interface):
interface.send_value(self.midi_value, channel = BUTTON_CHANNEL, force = True)
interface.send_value(self._animation, channel = BUTTON_ANIMATION_CHANNEL, force = True)
| {
"repo_name": "bvalosek/ableton-live-scripts",
"path": "bvalosek_Midi_Fighter_Twister/Colors.py",
"copies": "1",
"size": "1181",
"license": "mit",
"hash": 4524980162870533600,
"line_mean": 20.0892857143,
"line_max": 95,
"alpha_frac": 0.5901778154,
"autogenerated": false,
"ratio": 2.752913752913753,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.38430915683137534,
"avg_score": null,
"num_lines": null
} |
from _Framework.ButtonElement import * # noqa
class ConfigurableButtonElement(ButtonElement):
""" Special button class that can be configured with custom on- and off-values """
def __init__(self, is_momentary, msg_type, channel, identifier):
ButtonElement.__init__(self, is_momentary, msg_type, channel, identifier)
self._on_value = 127
self._off_value = 4
self._is_enabled = True
self._is_notifying = False
self._force_next_value = False
self._pending_listeners = []
def set_on_off_values(self, on_value, off_value):
assert (on_value in range(128))
assert (off_value in range(128))
self.clear_send_cache()
self._on_value = on_value
self._off_value = off_value
def set_force_next_value(self):
self._force_next_value = True
def set_enabled(self, enabled):
self._is_enabled = enabled
def turn_on(self):
self.send_value(self._on_value)
def turn_off(self):
self.send_value(self._off_value)
def reset(self):
self.send_value(4)
def add_value_listener(self, callback, identify_sender=False):
if not self._is_notifying:
ButtonElement.add_value_listener(self, callback, identify_sender)
else:
self._pending_listeners.append((callback, identify_sender))
def receive_value(self, value):
self._is_notifying = True
ButtonElement.receive_value(self, value)
self._is_notifying = False
for listener in self._pending_listeners:
self.add_value_listener(listener[0], listener[1])
self._pending_listeners = []
def send_value(self, value, force=False):
ButtonElement.send_value(self, value, force or self._force_next_value)
self._force_next_value = False
def install_connections(self, install_translation_callback, install_mapping_callback, install_forwarding_callback):
if self._is_enabled:
ButtonElement.install_connections(self, install_translation_callback, install_mapping_callback, install_forwarding_callback)
elif self._msg_channel != self._original_channel or self._msg_identifier != self._original_identifier:
install_translation_callback(self._msg_type, self._original_identifier, self._original_channel, self._msg_identifier, self._msg_channel)
| {
"repo_name": "jim-cooley/abletonremotescripts",
"path": "remote-scripts/samples/Launchpad95/ConfigurableButtonElement.py",
"copies": "1",
"size": "2135",
"license": "apache-2.0",
"hash": 8725274849450769000,
"line_mean": 33.435483871,
"line_max": 139,
"alpha_frac": 0.7320843091,
"autogenerated": false,
"ratio": 3.254573170731707,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4486657479831707,
"avg_score": null,
"num_lines": null
} |
from _Framework.ButtonMatrixElement import ButtonMatrixElement
from _Framework.CompoundComponent import CompoundComponent
from _Framework.SubjectSlot import SubjectEvent, subject_slot, subject_slot_group
from Debug import *
debug = initialize_debug()
class TranslationComponent(CompoundComponent):
def __init__(self, controls = [], user_channel_offset = 1, channel = 0, *a, **k):
super(TranslationComponent, self).__init__()
self._controls = controls
self._user_channel_offset = user_channel_offset
self._channel = channel or 0
self._color = 0
def set_controls(self, controls):
self._controls = controls
def add_control(self, control):
if control:
self._controls.append(control)
def set_channel_selector_buttons(self, buttons):
self._on_channel_seletor_button_value.subject = buttons
self.update_channel_selector_buttons()
def set_channel_selector_control(self, control):
if self._on_channel_selector_control_value.subject:
self._on_channel_selector_control_value.subject.send_value(0)
self._on_channel_selector_control_value.subject = control
self.update_channel_selector_control()
def update_channel_selector_control(self):
control = self._on_channel_selector_control_value.subject
if control:
chan_range = 14 - self._user_channel_offset
value = ((self._channel-self._user_channel_offset)*127)/chan_range
control.send_value( int(value) )
def update_channel_selector_buttons(self):
buttons = self._on_channel_seletor_button_value.subject
if buttons:
for button, coords in buttons.iterbuttons():
if button:
channel = self._channel - self._user_channel_offset
selected = coords[0] + (coords[1]*buttons.width())
if channel == selected:
button.turn_on()
else:
button.turn_off()
@subject_slot('value')
def _on_channel_selector_control_value(self, value, *a, **k):
chan_range = 14 - self._user_channel_offset
channel = int((value*chan_range)/127)+self._user_channel_offset
if channel != self._channel:
self._channel = channel
self.update()
@subject_slot('value')
def _on_channel_seletor_button_value(self, value, x, y, *a, **k):
if value:
x = x + (y*self._on_channel_seletor_button_value.subject.width())
self._channel = min(x+self._user_channel_offset, 14)
self.update()
def update(self):
if self.is_enabled():
for control in self._controls:
control.clear_send_cache()
control.release_parameter()
try:
control.set_light('Translation.Channel_'+str(self._channel)+'.'+str(control.name))
except:
control.send_value(self._color, True)
control.set_channel(self._channel)
control.set_enabled(False)
else:
for control in self._controls:
control.use_default_message()
control.set_enabled(True)
self.update_channel_selector_buttons()
self.update_channel_selector_control()
| {
"repo_name": "LividInstruments/LiveRemoteScripts",
"path": "_Mono_Framework/TranslationComponent.py",
"copies": "1",
"size": "2873",
"license": "mit",
"hash": 1970645993443334100,
"line_mean": 28.9270833333,
"line_max": 87,
"alpha_frac": 0.7069265576,
"autogenerated": false,
"ratio": 3.2426636568848757,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.87769227811514,
"avg_score": 0.13453348666669523,
"num_lines": 96
} |
from _Framework.ButtonMatrixElement import ButtonMatrixElement
from _Framework.ControlSurface import ControlSurface
from _Framework.InputControlElement import MIDI_CC_TYPE
from _Framework.Layer import Layer
from _Framework.ModesComponent import LayerMode
from consts import *
from Colors import *
from BackgroundComponent import BackgroundComponent
from ButtonElementEx import ButtonElementEx
from DeviceComponentEx import DeviceComponentEx
from ModesComponentEx import ModesComponentEx
from SkinDefault import make_default_skin
from SliderElementEx import SliderElementEx
class TwisterControlSurface(ControlSurface):
"""
Custom control for the DJ Tech Tools Midi Fighter Twister controller
"""
def __init__(self, c_instance):
ControlSurface.__init__(self, c_instance)
with self.component_guard():
self._skin = make_default_skin()
self._setup_controls()
self._setup_background()
self._setup_modes()
def _setup_background(self):
background = BackgroundComponent()
background.layer = Layer(priority = -100, knobs = self._knobs, lights = self._buttons)
def _setup_controls(self):
knobs = [ [ self._make_knob(row, col) for col in range(4) ] for row in range(4) ]
buttons = [ [ self._make_button(row, col) for col in range(4) ] for row in range(4) ]
self._knobs = ButtonMatrixElement(knobs)
self._buttons = ButtonMatrixElement(buttons)
def _make_knob(self, row, col):
return SliderElementEx(
msg_type = MIDI_CC_TYPE,
channel = KNOB_CHANNEL,
identifier = row * 4 + col)
def _make_button(self, row, col):
return ButtonElementEx(
msg_type = MIDI_CC_TYPE,
channel = BUTTON_CHANNEL,
identifier = row * 4 + col,
is_momentary = True,
skin = self._skin)
def _setup_modes(self):
self._modes = ModesComponentEx()
mappings = dict()
for n in range(4):
self._create_page(n)
mappings["page{}_mode_button".format(n + 1)] = self._buttons.get_button(n, 0)
self._modes.layer = Layer(priority = 10, **mappings)
self._modes.selected_mode = 'page1_mode'
def _create_page(self, index):
page_num = index + 1
mode_name = "page{}_mode".format(page_num)
msg = lambda: self.show_message("Switched to page {}".format(page_num))
devices = [ DeviceComponentEx(
schedule_message = self.schedule_message,
top_buttons = self._buttons.submatrix[:, 0],
log = self.log_message) for n in range(3) ]
layers = [ Layer(
knobs = self._knobs.submatrix[:, n + 1],
buttons = self._buttons.submatrix[:, n + 1]) for n in range (3) ]
modes = [ LayerMode(devices[n], layers[n]) for n in range(3) ]
self._modes.add_mode(mode_name, modes + [ msg ])
| {
"repo_name": "bvalosek/ableton-live-scripts",
"path": "bvalosek_Midi_Fighter_Twister/TwisterControlSurface.py",
"copies": "1",
"size": "2954",
"license": "mit",
"hash": -6397523640029487000,
"line_mean": 35.4691358025,
"line_max": 94,
"alpha_frac": 0.6296547055,
"autogenerated": false,
"ratio": 3.8018018018018016,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9805250193165824,
"avg_score": 0.02524126282719558,
"num_lines": 81
} |
from _Framework.ButtonSliderElement import ButtonSliderElement
from _Framework.InputControlElement import * # noqa
from consts import * # noqa
import math
SLIDER_MODE_OFF = 0
SLIDER_MODE_ONOFF = 1
SLIDER_MODE_SLIDER = 2
SLIDER_MODE_PRECISION_SLIDER = 3
SLIDER_MODE_SMALL_ENUM = 4
SLIDER_MODE_BIG_ENUM = 5
#TODO: repeat buttons.
# not exact / rounding values in slider and precision slider
class DeviceControllerStrip(ButtonSliderElement):
def __init__(self, buttons, parent):
ButtonSliderElement.__init__(self, buttons)
self._num_buttons = len(buttons)
self._value_map = tuple([float(index) / (self._num_buttons-1) for index in range(self._num_buttons)])
self._precision_mode = False
self._parent = parent
self._enabled = True
def set_enabled(self,enabled):
self._enabled = enabled
def set_precision_mode(self, precision_mode):
self._precision_mode = precision_mode
self.update()
@property
def _value(self):
if self._parameter_to_map_to != None:
return self._parameter_to_map_to.value
else:
return 0
@property
def _max(self):
if self._parameter_to_map_to != None:
return self._parameter_to_map_to.max
else:
return 0
@property
def _min(self):
if self._parameter_to_map_to != None:
return self._parameter_to_map_to.min
else:
return 0
@property
def _range(self):
if self._parameter_to_map_to != None:
return self._parameter_to_map_to.max - self._parameter_to_map_to.min
else:
return 0
@property
def _default_value(self):
if self._parameter_to_map_to != None:
return self._parameter_to_map_to._default_value
else:
return 0
@property
def _is_quantized(self):
if self._parameter_to_map_to != None:
return self._parameter_to_map_to.is_quantized
else:
return false
@property
def _mode(self):
if self._parameter_to_map_to != None:
if self._is_quantized:
if self._range == 1:
return SLIDER_MODE_ONOFF
elif self._range<=self._num_buttons:
return SLIDER_MODE_SMALL_ENUM
else:
return SLIDER_MODE_BIG_ENUM
else:
if self._precision_mode:
return SLIDER_MODE_PRECISION_SLIDER
else:
return SLIDER_MODE_SLIDER
else:
return SLIDER_MODE_OFF
def update(self):
if self._enabled:
if self._mode == SLIDER_MODE_ONOFF:
self._update_onoff()
elif self._mode == SLIDER_MODE_SMALL_ENUM:
self._update_small_enum()
elif self._mode == SLIDER_MODE_BIG_ENUM:
self._update_big_enum()
elif (self._mode == SLIDER_MODE_SLIDER):
self._update_slider()
elif (self._mode == SLIDER_MODE_PRECISION_SLIDER):
self._update_precision_slider()
else:
self._update_off()
def reset(self):
self._update_off()
def reset_if_no_parameter(self):
if self._parameter_to_map_to == None:
self.reset()
def _update_off(self):
v = [0 for index in range(len(self._buttons))]
self._update_buttons(tuple(v))
def _update_onoff(self):
v = [0 for index in range(len(self._buttons))]
if self._value==self._max:
v[0]=RED_FULL
else:
v[0]=RED_THIRD
self._update_buttons(tuple(v))
def _update_small_enum(self):
v = [0 for index in range(len(self._buttons))]
for index in range(int(self._range+1)):
if self._value==index+self._min:
v[index]=AMBER_FULL
else:
v[index]=AMBER_THIRD
self._update_buttons(tuple(v))
def _update_big_enum(self):
v = [0 for index in range(len(self._buttons))]
if self._value>self._min:
v[3]=AMBER_FULL
else:
v[3]=AMBER_THIRD
if self._value<self._max:
v[4]=AMBER_FULL
else:
v[4]=AMBER_THIRD
self._update_buttons(tuple(v))
def _update_slider(self):
v = [0 for index in range(len(self._buttons))]
for index in range(len(self._buttons)):
if self._value >=self._value_map[index]*self._range+self._min:
v[index]=GREEN_FULL
else:
v[index]=GREEN_THIRD
self._update_buttons(tuple(v))
def _update_precision_slider(self):
v = [0 for index in range(len(self._buttons))]
if self._value>self._min:
v[3]=GREEN_FULL
else:
v[3]=GREEN_THIRD
if self._value<self._max:
v[4]=GREEN_FULL
else:
v[4]=GREEN_THIRD
self._update_buttons(tuple(v))
def _update_buttons(self, buttons):
assert isinstance(buttons, tuple)
assert (len(buttons) == len(self._buttons))
for index in range(len(self._buttons)):
self._buttons[index].set_on_off_values(buttons[index],buttons[index])
if buttons[index]>0:
self._buttons[index].turn_on()
else:
self._buttons[index].turn_off()
def _button_value(self, value, sender):
assert isinstance(value, int)
assert (sender in self._buttons)
self._last_sent_value = -1
if (self._parameter_to_map_to != None and self._enabled and ((value != 0) or (not sender.is_momentary()))):
if (value != self._last_sent_value):
index_of_sender = list(self._buttons).index(sender)
if (self._mode == SLIDER_MODE_ONOFF) and index_of_sender==0:
if self._value == self._max:
self._parameter_to_map_to.value = self._min
else:
self._parameter_to_map_to.value = self._max
elif self._mode == SLIDER_MODE_SMALL_ENUM:
self._parameter_to_map_to.value = index_of_sender + self._min
elif self._mode == SLIDER_MODE_BIG_ENUM:
if index_of_sender>=4:
inc = 2**(index_of_sender - 3 -1)
if self._value + inc <= self._max:
self._parameter_to_map_to.value += inc
else:
self._parameter_to_map_to.value = self._max
else:
inc = 2**(4 - index_of_sender -1)
if self._value - inc >= self._min:
self._parameter_to_map_to.value -= inc
else:
self._parameter_to_map_to.value = self._min
elif (self._mode == SLIDER_MODE_SLIDER):
self._parameter_to_map_to.value = self._value_map[index_of_sender]*self._range + self._min
elif (self._mode == SLIDER_MODE_PRECISION_SLIDER):
inc = float(self._range) / 128
if self._range>7 and inc<1:
inc=1
if index_of_sender >= 4:
inc = inc * 2**(index_of_sender - 3-1)
if self._value + inc <= self._max:
self._parameter_to_map_to.value += inc
else:
self._parameter_to_map_to.value = self._max
else:
inc = inc * 2**(4 - index_of_sender-1)
if self._value - inc >= self._min:
self._parameter_to_map_to.value -= inc
else:
self._parameter_to_map_to.value = self._min
self.notify_value(value)
if self._parent is not None:
self._parent._update_OSD()
def _on_parameter_changed(self):
assert (self._parameter_to_map_to != None)
if self._parent is not None:
self._parent._update_OSD()
self.update()
| {
"repo_name": "jim-cooley/abletonremotescripts",
"path": "remote-scripts/samples/Launchpad95/DeviceControllerStrip.py",
"copies": "1",
"size": "6638",
"license": "apache-2.0",
"hash": -8346145583679729000,
"line_mean": 26.2049180328,
"line_max": 109,
"alpha_frac": 0.6402530883,
"autogenerated": false,
"ratio": 2.7832285115303983,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.8444940727318027,
"avg_score": 0.09570817450247442,
"num_lines": 244
} |
from _Framework.ButtonSliderElement import ButtonSliderElement
from _Framework.InputControlElement import * # noqa
SLIDER_MODE_SINGLE = 0
SLIDER_MODE_VOLUME = 1
SLIDER_MODE_PAN = 2
class PreciseButtonSliderElement(ButtonSliderElement):
""" Class representing a set of buttons used as a slider """
def __init__(self, buttons):
ButtonSliderElement.__init__(self, buttons)
num_buttons = len(buttons)
self._disabled = False
self._mode = SLIDER_MODE_VOLUME
self._value_map = tuple([ float(index / num_buttons) for index in range(num_buttons) ])
def set_disabled(self, disabled):
assert isinstance(disabled, type(False))
self._disabled = disabled
def set_mode(self, mode):
assert mode in (SLIDER_MODE_SINGLE, SLIDER_MODE_VOLUME, SLIDER_MODE_PAN)
if (mode != self._mode):
self._mode = mode
def set_value_map(self, map):
assert isinstance(map, (tuple, type(None)))
assert len(map) == len(self._buttons)
self._value_map = map
def send_value(self, value):
if (not self._disabled):
assert (value != None)
assert isinstance(value, int)
assert (value in range(128))
if value != self._last_sent_value:
if self._mode == SLIDER_MODE_SINGLE:
ButtonSliderElement.send_value(self, value)
elif self._mode == SLIDER_MODE_VOLUME:
self._send_value_volume(value)
elif self._mode == SLIDER_MODE_PAN:
self._send_value_pan(value)
else:
assert False
self._last_sent_value = value
def connect_to(self, parameter):
ButtonSliderElement.connect_to(self, parameter)
if self._parameter_to_map_to != None:
self._last_sent_value = -1
self._on_parameter_changed()
def release_parameter(self):
old_param = self._parameter_to_map_to
ButtonSliderElement.release_parameter(self)
if not self._disabled and old_param != None:
for button in self._buttons:
button.reset()
def reset(self):
if not self._disabled and self._buttons != None:
for button in self._buttons:
if button != None:
button.reset()
def _send_value_volume(self, value):
index_to_light = -1
normalised_value = float(value) / 127.0
if normalised_value > 0.0:
for index in range(len(self._value_map)):
if normalised_value <= self._value_map[index]:
index_to_light = index
break
self._send_mask(tuple([ index <= index_to_light for index in range(len(self._buttons)) ]))
def _send_value_pan(self, value):
num_buttons = len(self._buttons)
button_bits = [ False for index in range(num_buttons) ]
normalised_value = float(2 * value / 127.0) - 1.0
if value in (63, 64):
normalised_value = 0.0
if normalised_value < 0.0:
for index in range(len(self._buttons)):
button_bits[index] = self._value_map[index] >= normalised_value
if self._value_map[index] >= 0:
break
elif normalised_value > 0.0:
for index in range(len(self._buttons)):
r_index = len(self._buttons) - 1 - index
button_bits[r_index] = self._value_map[r_index] <= normalised_value
if self._value_map[r_index] <= 0:
break
else:
for index in range(len(self._buttons)):
button_bits[index] = self._value_map[index] == normalised_value
self._send_mask(tuple(button_bits))
def _send_mask(self, mask):
assert isinstance(mask, tuple)
assert (len(mask) == len(self._buttons))
for index in range(len(self._buttons)):
if mask[index]:
self._buttons[index].turn_on()
else:
self._buttons[index].turn_off()
def _button_value(self, value, sender):
assert isinstance(value, int)
assert (sender in self._buttons)
self._last_sent_value = -1
if (self._parameter_to_map_to != None and (not self._disabled) and ((value != 0) or (not sender.is_momentary()))):
index_of_sender = list(self._buttons).index(sender)
# handle precision mode
#if(not self._precision_mode):
if self._parameter_to_map_to != None and self._parameter_to_map_to.is_enabled:
self._parameter_to_map_to.value = self._value_map[index_of_sender]
#else:
# inc = float(self._parameter_to_map_to.max - self._parameter_to_map_to.min) / 64
# if index_of_sender >= 4:
# inc = inc * (index_of_sender - 3)
# if self._parameter_to_map_to.value + inc <= self._parameter_to_map_to.max:
# self._parameter_to_map_to.value = self._parameter_to_map_to.value + inc
# else:
# self._parameter_to_map_to.value = self._parameter_to_map_to.max
# else:
# inc = inc * (4 - index_of_sender)
# if self._parameter_to_map_to.value - inc >= self._parameter_to_map_to.min:
# self._parameter_to_map_to.value = self._parameter_to_map_to.value - inc
# else:
# self._parameter_to_map_to.value = self._parameter_to_map_to.min
self.notify_value(value)
#if self._parent is not None:
# self._parent._update_OSD()
def _on_parameter_changed(self):
assert (self._parameter_to_map_to != None)
param_range = abs(self._parameter_to_map_to.max - self._parameter_to_map_to.min)
param_value = self._parameter_to_map_to.value
param_min = self._parameter_to_map_to.min
param_mid = param_range / 2 + param_min
midi_value = 0
if self._mode == SLIDER_MODE_PAN:
if param_value == param_mid:
midi_value = 64
else:
diff = abs(param_value - param_mid) / param_range * 127
if param_value > param_mid:
midi_value = 64 + int(diff)
else:
midi_value = 63 - int(diff)
else:
midi_value = int(127 * abs(param_value - self._parameter_to_map_to.min) / param_range)
self.send_value(midi_value) | {
"repo_name": "jim-cooley/abletonremotescripts",
"path": "remote-scripts/samples/Launchpad95/PreciseButtonSliderElement.py",
"copies": "1",
"size": "5444",
"license": "apache-2.0",
"hash": -6890916476414788000,
"line_mean": 33.6815286624,
"line_max": 116,
"alpha_frac": 0.6664217487,
"autogenerated": false,
"ratio": 2.8804232804232806,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.40468450291232805,
"avg_score": null,
"num_lines": null
} |
from _Framework.ChannelStripComponent import ChannelStripComponent
TRACK_FOLD_DELAY = 2
class SpecialChannelStripComponent(ChannelStripComponent):
' Subclass of channel strip component using select button for (un)folding tracks '
__module__ = __name__
def __init__(self):
ChannelStripComponent.__init__(self)
self._toggle_fold_ticks_delay = -1
self._register_timer_callback(self._on_timer)
def disconnect(self):
self._unregister_timer_callback(self._on_timer)
ChannelStripComponent.disconnect(self)
def _select_value(self, value):
ChannelStripComponent._select_value(self, value)
if (self.is_enabled() and (self._track != None)):
if (self._track.is_foldable and (self._select_button.is_momentary() and (value != 0))):
self._toggle_fold_ticks_delay = TRACK_FOLD_DELAY
else:
self._toggle_fold_ticks_delay = -1
def _on_timer(self):
if (self.is_enabled() and (self._track != None)):
if (self._toggle_fold_ticks_delay > -1):
assert self._track.is_foldable
if (self._toggle_fold_ticks_delay == 0):
self._track.fold_state = (not self._track.fold_state)
self._toggle_fold_ticks_delay -= 1 | {
"repo_name": "jim-cooley/abletonremotescripts",
"path": "remote-scripts/branches/VCM600_2/SpecialChannelStripComponent.py",
"copies": "1",
"size": "1311",
"license": "apache-2.0",
"hash": 7073927881248054000,
"line_mean": 38.7575757576,
"line_max": 99,
"alpha_frac": 0.6155606407,
"autogenerated": false,
"ratio": 3.9017857142857144,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0023023336816440265,
"num_lines": 33
} |
from _Framework.CompoundComponent import CompoundComponent
from _Framework.DeviceComponent import DeviceComponent
from _Framework.Layer import Layer
from _Framework.ModesComponent import LayerMode, ComponentMode
from _Framework.ModesComponent import ModesComponent
from _Framework.SubjectSlot import subject_slot_group, subject_slot
from ableton.v2.base import liveobj_valid
from random import randint
from BackgroundComponent import BackgroundComponent
from Colors import *
from MenuComponent import MenuComponent
class SnapModes:
HALF = 'Device.HalfSnap'
REVERSE_HALF = 'Device.ReverseHalfSnap'
FULL = 'Device.FullSnap'
class _DeviceComponent(DeviceComponent):
def __init__(self, log = None, *a, **k):
super(_DeviceComponent, self).__init__(*a, **k)
self.log = log
self._param_offset = False
def set_param_offset(self, value):
self._param_offset = value
self.update()
def toggle_param_offset(self):
self.set_param_offset(not self._param_offset)
def _current_bank_details(self):
""" Override default behavior to factor in param_offset """
bank_name, bank = super(_DeviceComponent, self)._current_bank_details()
if bank and len(bank) > 4 and self._param_offset:
bank = bank[4:]
return (bank_name, bank)
def get_parameter(self, idx = 0):
_, bank = self._current_bank_details()
if idx >= len(bank): return None
return bank[idx]
class DeviceComponentEx(CompoundComponent):
"""
Extended DeviceComponent for the Midi Fighter Twister
"""
next_color = 1
def __init__(self, schedule_message, log = None, top_buttons = None, *a, **k):
super(DeviceComponentEx, self).__init__(*a, **k)
self.log = log
self.schedule_message = schedule_message
self._knobs = None
self._buttons = None
self._top_buttons = top_buttons
self._snap_modes = [ SnapModes.REVERSE_HALF ] * 8
self._param_values = [ None ] * 8
self._param_down_values = [ None ] * 8
self._setup_background()
self._setup_device()
self._setup_empty_menu()
self._setup_device_menu()
self._setup_active_menu()
self._setup_top_menu()
self._setup_modes()
def _setup_empty_menu(self):
actions = [
('Device.Lock', self._lock_device, None),
('Device.LockOffset', lambda: self._lock_device(True), None),
(None, None, None),
(None, None, None) ]
self._empty = self.register_component(MenuComponent(
actions = actions,
is_enabled = False))
def _setup_device_menu(self):
fn = lambda n, v: lambda: self._on_param(n, v)
actions = [
(None, fn(n, True), fn(n, False)) for n in range(3) ] + [
(None, lambda: self._modes.push_mode('menu'), None) ]
self._device_buttons = self.register_component(MenuComponent(
actions = actions,
enable_lights = False,
is_enabled = False))
def _setup_active_menu(self):
actions = [
('Device.Unlock', lambda: self._unlock_device(), None),
('Device.NormalParams', lambda: self._toggle_param_offset(), None),
('Device.Select', lambda: self._select_device(), None),
('Device.MenuActive', None, lambda: self._modes.pop_mode('menu')) ]
self._menu = self.register_component(MenuComponent(
actions = actions,
is_enabled = False))
def _setup_top_menu(self):
fn = lambda n: lambda: self._on_toggle_snap_mode(n)
actions = [
(self._snap_modes[n], fn(n), None) for n in range(3) ] + [
('DefaultButton.Off', None, None) ]
self._top_menu = self.register_component(MenuComponent(
layer = Layer(priority = 20, buttons = self._top_buttons),
actions = actions,
is_enabled = False))
def _setup_background(self):
self._background = self.register_component(BackgroundComponent(
is_enabled = False))
color = DeviceComponentEx.next_color
DeviceComponentEx.next_color = (color + 31) % 127
self._background.set_raw([ ColorEx(color) for n in range(4) ])
def _setup_device(self):
self._device = self.register_component(_DeviceComponent(
log = self.log,
is_enabled = False))
def _setup_modes(self):
self._modes = self.register_component(ModesComponent())
self._modes.add_mode('empty', [ ComponentMode(self._empty) ])
self._modes.add_mode('device', [
ComponentMode(self._device_buttons),
ComponentMode(self._device),
ComponentMode(self._background) ])
self._modes.add_mode('menu', [
ComponentMode(self._top_menu),
ComponentMode(self._menu) ])
self._modes.selected_mode = 'empty';
def set_knobs(self, knobs):
self._knobs = knobs
self._device.set_parameter_controls(knobs)
self.update();
def set_buttons(self, buttons):
self._buttons = buttons
self._background.set_lights(buttons)
self._empty.set_buttons(buttons)
self._device_buttons.set_buttons(buttons)
self._menu.set_buttons(buttons)
if buttons == None: self._modes.pop_mode('menu')
self.update();
def update(self):
super(DeviceComponentEx, self).update()
self._check_device()
def _toggle_param_offset(self):
self._device.toggle_param_offset()
self._update_menu_actions()
def _update_menu_actions(self):
pcolor = 'Device.NormalParams' if not self._device._param_offset else 'Device.OffsetParams'
self._menu.update_action(1, (pcolor, self._toggle_param_offset, None))
def _lock_device(self, offset = False):
focused = self.song().appointed_device
self._device.set_param_offset(offset)
self._device.set_lock_to_device(True, focused)
self._modes.push_mode('device')
self._update_menu_actions()
self.update()
def _unlock_device(self):
self._device.set_lock_to_device(False, None)
self._modes.pop_mode('device')
self._modes.pop_mode('menu')
self._device.set_param_offset(False)
self.update()
def _select_device(self):
self.song().view.select_device(self._device._device)
self.update()
def _on_param(self, idx, value = True):
snap_index = idx + (4 if self._device._param_offset else 0)
mode = self._snap_modes[snap_index]
if mode == SnapModes.HALF:
self._on_param_half_snap(idx, value)
elif mode == SnapModes.REVERSE_HALF:
self._on_param_reverse_half_snap(idx, value)
elif mode == SnapModes.FULL:
self._on_param_full_snap(idx, value)
def _on_param_reverse_half_snap(self, idx, value):
""" Restore on rising edge, cache on falling edge """
param = self._device.get_parameter(idx)
cached = self._param_values[idx]
if value:
if cached is not None: self._set_parameter_value(param, cached)
else:
self._param_values[idx] = param.value
def _on_param_half_snap(self, idx, value):
""" Cache on rising edge, restore on falling edge """
param = self._device.get_parameter(idx)
cached = self._param_values[idx]
if value:
self._param_values[idx] = param.value
else:
if cached is not None: self._set_parameter_value(param, cached)
def _on_param_full_snap(self, idx, value):
""" Cache and restore on rising and falling edge"""
param = self._device.get_parameter(idx)
cached = self._param_values[idx]
self._param_values[idx] = param.value
if cached is not None: self._set_parameter_value(param, cached)
def _on_toggle_snap_mode(self, idx):
pass
def _set_parameter_value(self, param, value):
current = param.value
def restore():
param.value = current
param.value = value
param.value = value
self.schedule_message(1, restore)
def _check_device(self):
d = self._device._device
if liveobj_valid(d): return
self._device.set_lock_to_device(False, None)
self._modes.pop_mode('menu')
self._modes.pop_mode('device')
| {
"repo_name": "bvalosek/ableton-live-scripts",
"path": "bvalosek_Midi_Fighter_Twister/DeviceComponentEx.py",
"copies": "1",
"size": "8488",
"license": "mit",
"hash": 616755387393238800,
"line_mean": 34.9661016949,
"line_max": 99,
"alpha_frac": 0.6024976437,
"autogenerated": false,
"ratio": 3.809694793536804,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4912192437236804,
"avg_score": null,
"num_lines": null
} |
from Framework.Controller import Controller
from Database.Controllers.Curso import Curso as BDCurso
from Models.Curso.RespostaListar import RespostaListar
from Models.Curso.RespostaCadastrar import RespostaCadastrar
from Models.Curso.RespostaEditar import RespostaEditar
from Models.Curso.RespostaVer import RespostaVer
from Models.Curso.RespostaDeletar import RespostaDeletar
from Database.Models.Curso import Curso as ModelCurso
class Curso(Controller):
def Listar(self,pedido_listar):
return RespostaListar(BDCurso().pegarCursos("WHERE id_campus = %s AND nome LIKE %s LIMIT %s OFFSET %s",(str(pedido_listar.getIdCampus()),"%"+pedido_listar.getNome().replace(' ','%')+"%",str(pedido_listar.getQuantidade()),(str(pedido_listar.getQuantidade()*pedido_listar.getPagina())))))
def Ver(self, pedido_ver):
return RespostaVer(BDCurso().pegarCurso("WHERE id = %s ", (str(pedido_ver.getId()),)))
def Cadastrar(self,pedido_cadastrar):
curso = ModelCurso()
curso.setNome(pedido_cadastrar.getNome())
curso.setCodigo(pedido_cadastrar.getCodigo())
curso.setId_grau(pedido_cadastrar.getId_grau())
curso.setId_campus(pedido_cadastrar.getId_campus())
curso.setPermanencia_minima(pedido_cadastrar.getPermanencia_minima())
curso.setPermanencia_maxima(pedido_cadastrar.getPermanencia_maxima())
curso.setCreditos_formatura(pedido_cadastrar.getCreditos_formatura())
curso.setCreditos_optativos_concentracao(pedido_cadastrar.getCreditos_optativos_concentracao())
curso.setCreditos_optativos_conexa(pedido_cadastrar.getCreditos_optativos_conexa())
curso.setCreditos_livres_maximo(pedido_cadastrar.getCreditos_livres_maximo())
curso.setMec(pedido_cadastrar.getMec())
return RespostaCadastrar(BDCurso().inserirCurso(curso))
def Editar(self,pedido_editar):
curso = BDCurso().pegarCurso("WHERE id = %s ", (pedido_editar.getId()))
curso.setNome(pedido_editar.getNome())
curso.setCodigo(pedido_editar.getCodigo())
curso.setId_grau(pedido_editar.getId_grau())
curso.setId_campus(pedido_editar.getId_campus())
curso.setPermanencia_minima(pedido_editar.getPermanencia_minima())
curso.setPermanencia_maxima(pedido_editar.getPermanencia_maxima())
curso.setCreditos_formatura(pedido_editar.getCreditos_formatura())
curso.setCreditos_optativos_concentracao(pedido_editar.getCreditos_optativos_concentracao())
curso.setCreditos_optativos_conexa(pedido_editar.getCreditos_optativos_conexa())
curso.setCreditos_livres_maximo(pedido_editar.getCreditos_livres_maximo())
curso.setMec(pedido_editar.getMec())
BDCurso().alterarCurso(curso)
return RespostaEditar("Curso Editado com sucesso!")
def Deletar(self,pedido_deletar):
curso = BDCurso().pegarCurso("WHERE id = %s ", (pedido_deletar.getId()))
BDCurso().removerCurso(curso)
return RespostaDeletar("Curso Removido com sucesso!")
| {
"repo_name": "AEDA-Solutions/matweb",
"path": "backend/Controllers/Curso.py",
"copies": "1",
"size": "2818",
"license": "mit",
"hash": 8580740306548679000,
"line_mean": 52.1698113208,
"line_max": 288,
"alpha_frac": 0.788502484,
"autogenerated": false,
"ratio": 2.3308519437551696,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.8531656405708621,
"avg_score": 0.01753960440930961,
"num_lines": 53
} |
from Framework.Controller import Controller
from Database.Controllers.Matricula import Matricula as BDMatricula
from Models.Matricula.RespostaListar import RespostaListar
from Models.Matricula.RespostaCadastrar import RespostaCadastrar
from Models.Matricula.RespostaEditar import RespostaEditar
from Models.Matricula.RespostaVer import RespostaVer
from Models.Matricula.RespostaDeletar import RespostaDeletar
from Database.Models.Matricula import Matricula as ModelMatricula
class Matricula(Controller):
def Listar(self,pedido_listar):
return RespostaListar(BDMatricula().pegarMatriculas("WHERE id_usuario = %s OR id_disciplina = %s LIKE %s LIMIT %s OFFSET %s",(str(pedido_listar.getIdUsuario()),str(pedido_listar.getIdDisciplina()),"%"+pedido_listar.getNome().replace(' ','%')+"%",str(pedido_listar.getQuantidade()),(str(pedido_listar.getQuantidade()*pedido_listar.getPagina())))))
def Ver(self, pedido_ver):
return RespostaVer(BDMatricula().pegarMatricula("WHERE id = %s ", (str(pedido_ver.getId()),)))
def Cadastrar(self,pedido_cadastrar):
matricula = ModelMatricula()
matricula.setId_usuario(pedido_cadastrar.getId_usuario())
matricula.setId_disciplina(pedido_cadastrar.getId_disciplina())
matricula.setStatus(pedido_cadastrar.getStatus())
return RespostaCadastrar(BDMatricula().inserirMatricula(matricula))
def Editar(self,pedido_editar):
matricula = BDMatricula().pegarMatricula("WHERE id = %s ", (pedido_editar.getId()))
matricula.setId_disciplina(pedido_editar.getId_disciplina())
matricula.setId_usuario(pedido_editar.getId_usuario())
matricula.setStatus(pedido_editar.getStatus())
BDMatricula().alterarMatricula(matricula)
return RespostaEditar("Matricula Editada com sucesso!")
def Deletar(self,pedido_deletar):
matricula = BDMatricula().pegarMatricula("WHERE id = %s ", (pedido_deletar.getId()))
BDMatricula().removerMatricula(matricula)
return RespostaDeletar("Matricula Removida com sucesso!")
| {
"repo_name": "AEDA-Solutions/matweb",
"path": "backend/Controllers/Matricula.py",
"copies": "1",
"size": "1954",
"license": "mit",
"hash": -4131662560048812500,
"line_mean": 51.8108108108,
"line_max": 348,
"alpha_frac": 0.7891504606,
"autogenerated": false,
"ratio": 2.581241743725231,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.878976564387289,
"avg_score": 0.01612531209046816,
"num_lines": 37
} |
from Framework.Controller import Controller
from Database.Controllers.Predio import Predio as BDPredio
from Models.Predio.RespostaListar import RespostaListar
from Models.Predio.RespostaCadastrar import RespostaCadastrar
from Models.Predio.RespostaEditar import RespostaEditar
from Models.Predio.RespostaVer import RespostaVer
from Models.Predio.RespostaDeletar import RespostaDeletar
from Database.Models.Predio import Predio as ModelPredio
class Predio(Controller):
def Listar(self,pedido_listar):
return RespostaListar(BDPredio().pegarPredios("WHERE id_campus = %s AND nome LIKE %s LIMIT %s OFFSET %s",(pedido_listar.getIdCampus(),"%"+pedido_listar.getNome().replace(' ','%')+"%",pedido_listar.getQuantidade(),(pedido_listar.getQuantidade()*pedido_listar.getPagina()))))
def Ver(self, pedido_ver):
return RespostaVer(BDPredio().pegarPredio("WHERE id = %s ", (str(pedido_ver.getId()),)))
def Cadastrar(self,pedido_cadastrar):
predio = ModelPredio()
predio.setNome(pedido_cadastrar.getNome())
predio.setSigla(pedido_cadastrar.getSigla())
predio.setLatitude(pedido_cadastrar.getLatitude())
predio.setLongitude(pedido_cadastrar.getLongitude())
predio.setId_campus(pedido_cadastrar.getId_campus())
return RespostaCadastrar(BDPredio().inserirPredio(predio))
def Editar(self,pedido_editar):
predio = BDPredio().pegarPredio("WHERE id = %s ", (str(pedido_editar.getId()),))
predio.setNome(pedido_editar.getNome())
predio.setSigla(pedido_editar.getSigla())
predio.setLatitude(pedido_editar.getLatitude())
predio.setLongitude(pedido_editar.getLongitude())
BDPredio().alterarPredio(predio)
return RespostaEditar("Predio Editado com sucesso!")
def Deletar(self,pedido_deletar):
predio = BDPredio().pegarPredio("WHERE id = %s ", (str(pedido_deletar.getId()),))
BDPredio().removerPredio(predio)
return RespostaDeletar("Predio Removido com sucesso!")
| {
"repo_name": "AEDA-Solutions/matweb",
"path": "backend/Controllers/Predio.py",
"copies": "1",
"size": "1894",
"license": "mit",
"hash": 394117226411694200,
"line_mean": 47.5641025641,
"line_max": 275,
"alpha_frac": 0.7740232313,
"autogenerated": false,
"ratio": 2.556005398110661,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.3830028629410661,
"avg_score": null,
"num_lines": null
} |
from Framework.Controller import Controller
from Database.Controllers.Sala import Sala as BDSala
from Models.Sala.RespostaListar import RespostaListar
from Models.Sala.RespostaEditar import RespostaEditar
from Models.Sala.RespostaCadastrar import RespostaCadastrar
from Models.Sala.RespostaVer import RespostaVer
from Models.Sala.RespostaDeletar import RespostaDeletar
from Database.Models.Sala import Sala as ModelSala
class Sala(Controller):
def Listar(self,pedido_listar):
return RespostaListar(BDSala().pegarSalas("WHERE id_predio = %s AND codigo LIKE %s LIMIT %s OFFSET %s",(str(pedido_listar.getId_predio()),"%"+(str(pedido_listar.getCodigo())).replace(' ','%')+"%",str(pedido_listar.getQuantidade()),(str(pedido_listar.getQuantidade()*pedido_listar.getPagina())))))
def Ver(self, pedido_ver):
return RespostaVer(BDSala().pegarSala("WHERE id = %s ", (str(pedido_ver.getId()),)))
def Cadastrar(self,pedido_cadastrar):
sala = ModelSala()
sala.setCodigo(pedido_cadastrar.getCodigo())
sala.setId_resp_sala(pedido_cadastrar.getId_resp_sala())
sala.setId_predio(pedido_cadastrar.getId_predio())
return RespostaCadastrar(BDSala().inserirSala(sala))
def Editar(self,pedido_editar):
sala = BDSala().pegarSala("WHERE id = %s ", (str(pedido_editar.getId()),))
sala.setCodigo(pedido_editar.getCodigo())
sala.setId_resp_sala(pedido_editar.getId_resp_sala())
sala.setId_predio(pedido_editar.getId_predio())
BDSala().alterarSala(sala)
return RespostaEditar("Sala Editado com sucesso!")
def Deletar(self,pedido_deletar):
sala = BDSala().pegarSala("WHERE id = %s ", (str(pedido_deletar.getId()),))
BDSala().removerSala(sala)
return RespostaDeletar("Sala Removido com sucesso!")
| {
"repo_name": "AEDA-Solutions/matweb",
"path": "backend/Controllers/Sala.py",
"copies": "1",
"size": "1714",
"license": "mit",
"hash": 5415149377588594000,
"line_mean": 46.6111111111,
"line_max": 298,
"alpha_frac": 0.7572928821,
"autogenerated": false,
"ratio": 2.4485714285714284,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.37058643106714284,
"avg_score": null,
"num_lines": null
} |
from _Framework.ControlSurfaceComponent import ControlSurfaceComponent
from consts import * # noqa
class InstrumentPresetsComponent():
def __init__(self, *a, **k):
self.octave_index_offset = 0
self.is_horizontal = True
self.interval = 3
def _set_scale_mode(self, octave_index_offset, orientation, interval):
self.octave_index_offset = octave_index_offset
self.is_horizontal = (orientation == 'horizontal' or orientation == True)
self.interval = interval
def set_orientation(self, orientation):
self._set_scale_mode(self.octave_index_offset, orientation, self.interval)
def toggle_orientation(self):
if(self.is_horizontal):
self._set_scale_mode(self.octave_index_offset, 'vertical', self.interval)
else:
self._set_scale_mode(self.octave_index_offset, 'horizontal', self.interval)
def set_interval(self, interval):
# 3rd : interval = 2
# 4th : interval = 3
# 6th : interval = 5
if interval == None:
self._set_scale_mode(-2, self.is_horizontal, None)
else:
self._set_scale_mode(0, self.is_horizontal, interval)
def cycle_intervals(self):
if(self.interval == None):
self.set_interval(2)
elif(self.interval == 2):
self.set_interval(3)
elif(self.interval == 3):
self.set_interval(5)
elif(self.interval == 5):
self.set_interval(2)
class Scale(object):
def __init__(self, name, notes, *a, **k):
super(Scale, self).__init__(*a, **k)
self.name = name
self.notes = notes
class Modus(Scale):
def __init__(self, *a, **k):
super(Modus, self).__init__(*a, **k)
def scale(self, base_note):
return Scale(KEY_NAMES[base_note], [base_note + x for x in self.notes])
def scales(self, base_notes):
return [self.scale(b) for b in base_notes]
class MelodicPattern(object):
def __init__(self, steps=[0, 0], scale=range(12), base_note=0, origin=[0, 0], valid_notes=xrange(128), base_note_color=GREEN_HALF, scale_note_color=AMBER_THIRD, scale_highlight_color=GREEN_FULL, foreign_note_color=LED_OFF, invalid_note_color=LED_OFF, chromatic_mode=False, chromatic_gtr_mode=False, diatonic_ns_mode=False, *a, **k):
super(MelodicPattern, self).__init__(*a, **k)
self.steps = steps
self.scale = scale
self.base_note = base_note
self.origin = origin
self.valid_notes = valid_notes
self.base_note_color = base_note_color
self.scale_note_color = scale_note_color
self.scale_highlight_color = scale_highlight_color
self.foreign_note_color = foreign_note_color
self.invalid_note_color = invalid_note_color
self.chromatic_mode = chromatic_mode
self.chromatic_gtr_mode = chromatic_gtr_mode
self.diatonic_ns_mode = diatonic_ns_mode
class NoteInfo:
def __init__(self, index, channel, color):
self.index, self.channel, self.color = index, channel, color
@property
def _extended_scale(self):
if self.chromatic_mode:
first_note = self.scale[0]
return range(first_note, first_note + 12)
else:
return self.scale
def _octave_and_note(self, x, y):
scale = self._extended_scale
scale_size = len(scale)
if self.chromatic_mode:
self.steps[1] = 5
else:
if self.diatonic_ns_mode:
self.steps[1] = scale_size
index = self.steps[0] * (self.origin[0] + x) + self.steps[1] * (self.origin[1] + y)
if self.chromatic_gtr_mode and y > 3:
index = index - 1
octave = index / scale_size
note = scale[index % scale_size]
return (octave, note)
def _color_for_note(self, note):
if note == self.scale[0]:
return self.base_note_color
elif note == self.scale[2] or note == self.scale[4]:
return self.scale_highlight_color
elif note in self.scale:
return self.scale_note_color
else:
return self.foreign_note_color
def note(self, x, y):
octave, note = self._octave_and_note(x, y)
index = 12 * octave + note + self.base_note
if index in self.valid_notes:
return self.NoteInfo(index, x, self._color_for_note(note))
else:
return self.NoteInfo(None, x, self.invalid_note_color)
class ScalesComponent(ControlSurfaceComponent):
def __init__(self, *a, **k):
super(ScalesComponent, self).__init__(*a, **k)
self._modus_list = [Modus(MUSICAL_MODES[v], MUSICAL_MODES[v + 1]) for v in xrange(0, len(MUSICAL_MODES), 2)]
self._modus_names = [MUSICAL_MODES[v] for v in xrange(0, len(MUSICAL_MODES), 2)]
self._selected_modus = 0
self._selected_key = 0
self._is_chromatic = False
self._is_chromatic_gtr = False # variable for chromatic guitar mode
self._is_diatonic = True
self._is_diatonic_ns = False # variable for diatonic non-staggered mode
self._is_drumrack = False
self.is_absolute = False
self.is_quick_scale = False
self.base_note_color = AMBER_THIRD
self.scale_note_color = GREEN_THIRD
self.scale_highlight_color = GREEN_HALF
self._presets = InstrumentPresetsComponent()
self._matrix = None
self._octave_index = 3
# C D E F G A B
self._index = [0, 2, 4, 5, 7, 9, 11]
self._parent = None
self._current_minor_mode = 1
self._minor_modes = [1, 13, 14]
def set_parent(self, parent):
self._parent = parent
def is_diatonic(self):
return not self._is_drumrack and (self._is_diatonic or self._is_diatonic_ns)
def is_chromatic(self):
return not self._is_drumrack and (self._is_chromatic or self._is_chromatic_gtr)
def is_diatonic_ns(self):
return self._is_diatonic_ns
def is_chromatic_gtr(self):
return self._is_chromatic_gtr
def is_drumrack(self):
return self._is_drumrack
def get_base_note_color(self):
return self.base_note_color
def get_scale_note_color(self):
return self.scale_note_color
def get_scale_highlight_color(self):
return self.scale_highlight_color
def set_diatonic(self, interval=-1):
self._is_drumrack = False
self._is_chromatic = False
self._is_chromatic_gtr = False
self._is_diatonic = True
self._is_diatonic_ns = False
if interval != -1:
self._presets.set_interval(interval)
def set_diatonic_ns(self):
self._is_drumrack = False
self._is_chromatic = False
self._is_chromatic_gtr = False
self._is_diatonic = False
self._is_diatonic_ns = True
def set_chromatic(self):
self._is_drumrack = False
self._is_chromatic = True
self._is_chromatic_gtr = False
self._is_diatonic = False
self._is_diatonic_ns = False
def set_chromatic_gtr(self):
self._is_drumrack = False
self._is_chromatic = False
self._is_chromatic_gtr = True
self._is_diatonic = False
self._is_diatonic_ns = False
def set_drumrack(self, value):
self._is_drumrack = value
@property
def notes(self):
return self.modus.scale(self._selected_key).notes
@property
def modus(self):
return self._modus_list[self._selected_modus]
def set_key(self, n):
self._selected_key = n % 12
def set_octave_index(self, n):
self._octave_index = n
def set_selected_modus(self, n):
if n > -1 and n < len(self._modus_list):
self._selected_modus = n
def _set_preset(self, n):
if n > -1 and n < 6:
self._selected_modus = n
def set_matrix(self, matrix):
if matrix:
matrix.reset()
if (matrix != self._matrix):
if (self._matrix != None):
self._matrix.remove_value_listener(self._matrix_value)
self._matrix = matrix
if (self._matrix != None):
self._matrix.add_value_listener(self._matrix_value)
self.update()
def _matrix_value(self, value, x, y, is_momentary): # matrix buttons listener
if self.is_enabled():
if ((value != 0) or (not is_momentary)):
# modes
if y == 0:
if not self.is_drumrack():
if x == 0:
self.is_absolute = not self.is_absolute
if self.is_absolute:
self._parent._parent._parent.show_message("absolute root")
else:
self._parent._parent._parent.show_message("relative root")
if x == 1:
self._presets.toggle_orientation()
if x == 2:
self.set_chromatic_gtr()
self._presets.set_orientation('horizontal')
self._parent._parent._parent.show_message("mode: chromatic gtr")
if x == 3:
self.set_diatonic_ns()
self._presets.set_orientation('horizontal')
self._parent._parent._parent.show_message("mode: diatonic not staggered")
if x == 4:
self.set_diatonic(2)
self._presets.set_orientation('vertical')
self._parent._parent._parent.show_message("mode: diatonic vertical (chords)")
if x == 5:
self.set_diatonic(3)
self._presets.set_orientation('horizontal')
self._parent._parent._parent.show_message("mode: diatonic")
if x == 6:
self.set_chromatic()
self._presets.set_orientation('horizontal')
self._parent._parent._parent.show_message("mode: chromatic")
if x == 7:
self.set_drumrack(True)
self._parent._parent._parent.show_message("mode: drumrack")
keys = ["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"]
# root note
if not self.is_drumrack():
root = -1
selected_key = self._selected_key
selected_modus = self._selected_modus
if y == 1 and x in[0, 1, 3, 4, 5] or y == 2 and x < 7:
root = [0, 2, 4, 5, 7, 9, 11, 12][x]
if y == 1:
root = root + 1
self._parent._parent._parent.show_message("root "+keys[root])
# if root == selected_key:#alternate minor/major
# if selected_modus==0:
# selected_modus = self._current_minor_mode
# elif selected_modus in [1,13,14]:
# self._current_minor_mode = selected_modus
# selected_modus = 0
# elif selected_modus==11:
# selected_modus = 12
# elif selected_modus==12:
# selected_modus = 11
if y == 2 and x == 7: # nav circle of 5th right
root = CIRCLE_OF_FIFTHS[(self.tuple_idx(CIRCLE_OF_FIFTHS, selected_key) + 1 + 12) % 12]
self._parent._parent._parent.show_message("circle of 5ths -> "+keys[selected_key]+" "+str(self._modus_names[selected_modus])+" => "+keys[root]+" "+str(self._modus_names[selected_modus]))
if y == 1 and x == 6: # nav circle of 5th left
root = CIRCLE_OF_FIFTHS[(self.tuple_idx(CIRCLE_OF_FIFTHS, selected_key) - 1 + 12) % 12]
self._parent._parent._parent.show_message("circle of 5ths <- "+keys[selected_key]+" "+str(self._modus_names[selected_modus])+" => "+keys[root]+" "+str(self._modus_names[selected_modus]))
if y == 1 and x == 2: # relative scale
if self._selected_modus == 0:
selected_modus = self._current_minor_mode
root = CIRCLE_OF_FIFTHS[(self.tuple_idx(CIRCLE_OF_FIFTHS, selected_key) + 3) % 12]
elif self._selected_modus in [1, 13, 14]:
self._current_minor_mode = selected_modus
selected_modus = 0
root = CIRCLE_OF_FIFTHS[(self.tuple_idx(CIRCLE_OF_FIFTHS, selected_key) - 3 + 12) % 12]
elif self._selected_modus == 11:
selected_modus = 12
root = CIRCLE_OF_FIFTHS[(self.tuple_idx(CIRCLE_OF_FIFTHS, selected_key) + 3) % 12]
elif self._selected_modus == 12:
selected_modus = 11
root = CIRCLE_OF_FIFTHS[(self.tuple_idx(CIRCLE_OF_FIFTHS, selected_key) - 3 + 12) % 12]
self._parent._parent._parent.show_message("Relative scale : "+keys[root]+" "+str(self._modus_names[selected_modus]))
if root != -1:
self.set_selected_modus(selected_modus)
self.set_key(root)
if y == 1 and x == 7 and not self.is_drumrack():
self.is_quick_scale = not self.is_quick_scale
self._parent._parent._parent.show_message("Quick scale")
# octave
if y == 3:
self._octave_index = x
self._parent._parent._parent.show_message("octave : "+str(self._octave_index))
# modus
if y > 3 and not self.is_drumrack():
self.set_selected_modus((y - 4) * 8 + x)
self._parent._parent._parent.show_message("mode : "+str(self._modus_names[self._selected_modus]))
self.update()
def tuple_idx(self, tuple, obj):
for i in xrange(0, len(tuple)):
if (tuple[i] == obj):
return i
return(False)
def set_osd(self, osd):
self._osd = osd
def _update_OSD(self):
if self._osd != None:
self._osd.attributes[0] = ""
self._osd.attribute_names[0] = ""
self._osd.attributes[1] = MUSICAL_MODES[self._selected_modus * 2]
self._osd.attribute_names[1] = "Scale"
self._osd.attributes[2] = KEY_NAMES[self._selected_key % 12]
self._osd.attribute_names[2] = "Root Note"
self._osd.attributes[3] = self._octave_index
self._osd.attribute_names[3] = "Octave"
self._osd.attributes[4] = " "
self._osd.attribute_names[4] = " "
self._osd.attributes[5] = " "
self._osd.attribute_names[5] = " "
self._osd.attributes[6] = " "
self._osd.attribute_names[6] = " "
self._osd.attributes[7] = " "
self._osd.attribute_names[7] = " "
self._osd.update()
def update(self):
if self.is_enabled():
self._update_OSD()
for button, (x, y) in self._matrix.iterbuttons():
button.use_default_message()
button.set_enabled(True)
button.force_next_send()
self._matrix.get_button(7, 2).set_on_off_values(LED_OFF, LED_OFF)
self._matrix.get_button(7, 2).turn_off()
absolute_button = self._matrix.get_button(0, 0)
orientation_button = self._matrix.get_button(1, 0)
quick_scale_button = self._matrix.get_button(7, 1)
drumrack_button = self._matrix.get_button(7, 0)
drumrack_button.set_on_off_values(RED_FULL, RED_THIRD)
drumrack_button.force_next_send()
chromatic_button = self._matrix.get_button(6, 0)
chromatic_button.set_on_off_values(RED_FULL, RED_THIRD)
chromatic_button.force_next_send()
diatonic_button_4th = self._matrix.get_button(5, 0)
diatonic_button_4th.set_on_off_values(RED_FULL, RED_THIRD)
diatonic_button_4th.force_next_send()
diatonic_button_3rd = self._matrix.get_button(4, 0)
diatonic_button_3rd.set_on_off_values(RED_FULL, RED_THIRD)
diatonic_button_3rd.force_next_send()
chromatic_gtr_button = self._matrix.get_button(2, 0)
chromatic_gtr_button.set_on_off_values(RED_FULL, RED_THIRD)
chromatic_gtr_button.force_next_send()
diatonic_ns_button = self._matrix.get_button(3, 0)
diatonic_ns_button.set_on_off_values(RED_FULL, RED_THIRD)
diatonic_ns_button.force_next_send()
# circle of 5th nav right
button = self._matrix.get_button(7, 2)
button.set_on_off_values(RED_THIRD, RED_THIRD)
button.force_next_send()
button.turn_on()
# circle of 5th nav left
button = self._matrix.get_button(6, 1)
button.set_on_off_values(RED_THIRD, RED_THIRD)
button.force_next_send()
button.turn_on()
# relative scale button
button = self._matrix.get_button(2, 1)
button.set_on_off_values(RED_THIRD, RED_THIRD)
button.force_next_send()
button.turn_on()
# mode buttons
if self.is_drumrack():
drumrack_button.turn_on()
chromatic_gtr_button.turn_off()
diatonic_ns_button.turn_off()
chromatic_button.turn_off()
diatonic_button_4th.turn_off()
diatonic_button_3rd.turn_off()
absolute_button.set_on_off_values(LED_OFF, LED_OFF)
absolute_button.turn_off()
orientation_button.set_on_off_values(LED_OFF, LED_OFF)
orientation_button.turn_off()
quick_scale_button.set_on_off_values(LED_OFF, LED_OFF)
quick_scale_button.turn_off()
else:
quick_scale_button.set_on_off_values(GREEN_FULL, GREEN_THIRD)
if self.is_quick_scale:
quick_scale_button.turn_on()
else:
quick_scale_button.turn_off()
orientation_button.set_on_off_values(AMBER_THIRD, AMBER_FULL)
if self._presets.is_horizontal:
orientation_button.turn_on()
else:
orientation_button.turn_off()
absolute_button.set_on_off_values(AMBER_THIRD, AMBER_FULL)
if self.is_absolute:
absolute_button.turn_on()
else:
absolute_button.turn_off()
drumrack_button.turn_off()
if self.is_chromatic():
if self.is_chromatic_gtr():
chromatic_button.turn_off()
chromatic_gtr_button.turn_on()
else:
chromatic_button.turn_on()
chromatic_gtr_button.turn_off()
diatonic_button_4th.turn_off()
diatonic_button_3rd.turn_off()
diatonic_ns_button.turn_off()
else:
chromatic_button.turn_off()
chromatic_gtr_button.turn_off()
if self.is_diatonic_ns():
diatonic_button_4th.turn_off()
diatonic_button_3rd.turn_off()
diatonic_ns_button.turn_on()
else:
if self._presets.interval == 3:
diatonic_button_4th.turn_on()
diatonic_button_3rd.turn_off()
else:
diatonic_button_4th.turn_off()
diatonic_button_3rd.turn_on()
diatonic_ns_button.turn_off()
# Octave
scene_index = 3
for track_index in range(8):
button = self._matrix.get_button(track_index, scene_index)
button.set_on_off_values(RED_FULL, RED_THIRD)
if track_index == self._octave_index:
button.turn_on()
else:
button.turn_off()
if self.is_drumrack():
# clear scales buttons
for scene_index in range(1, 3):
for track_index in range(8):
button = self._matrix.get_button(track_index, scene_index)
button.set_on_off_values(GREEN_FULL, LED_OFF)
button.turn_off()
for scene_index in range(4, 8):
for track_index in range(8):
button = self._matrix.get_button(track_index, scene_index)
button.set_on_off_values(GREEN_FULL, LED_OFF)
button.turn_off()
else:
# root note button
scene_index = 1
for track_index in [0, 1, 3, 4, 5]:
button = self._matrix.get_button(track_index, scene_index)
if track_index in [0, 1, 3, 4, 5]:
button.set_on_off_values(AMBER_FULL, AMBER_THIRD)
if self._selected_key % 12 == (self._index[track_index] + 1) % 12:
button.turn_on()
else:
button.turn_off()
scene_index = 2
for track_index in range(7):
button = self._matrix.get_button(track_index, scene_index)
button.set_on_off_values(AMBER_FULL, AMBER_THIRD)
if self._selected_key % 12 == self._index[track_index] % 12:
button.turn_on()
else:
button.turn_off()
# modus buttons
for scene_index in range(4):
for track_index in range(8):
button = self._matrix.get_button(track_index, scene_index + 4)
if scene_index * 8 + track_index < len(self._modus_list):
button.set_on_off_values(GREEN_FULL, GREEN_THIRD)
if self._selected_modus == scene_index * 8 + track_index:
button.turn_on()
else:
button.turn_off()
else:
button.set_on_off_values(LED_OFF, LED_OFF)
button.turn_off()
| {
"repo_name": "jim-cooley/abletonremotescripts",
"path": "remote-scripts/samples/Launchpad95/ScaleComponent.py",
"copies": "1",
"size": "18264",
"license": "apache-2.0",
"hash": -1581642452886848800,
"line_mean": 32.0869565217,
"line_max": 333,
"alpha_frac": 0.6512264564,
"autogenerated": false,
"ratio": 2.7021748779405237,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.3853401334340524,
"avg_score": null,
"num_lines": null
} |
from _Framework.ControlSurfaceComponent import ControlSurfaceComponent
from _Framework.SubjectSlot import subject_slot_group, subject_slot
from Colors import *
OFF_COLOR = ColorEx(Rgb.OFF, Brightness.OFF)
class MenuComponent(ControlSurfaceComponent):
"""
A component that allows for a set of buttons to be grabbed and trigger
callbacks when pressed
"""
def __init__(self, enable_lights = True, actions = None, *a, **k):
super(MenuComponent, self).__init__(*a, **k)
self._enable_lights = enable_lights
self._actions = actions
self._buttons = None
def set_buttons(self, buttons):
self._buttons = buttons
self.update()
def on_enabled_changed(self):
self.update()
def update_action(self, index, action):
self._actions[index] = action
self.update()
def update_action_color(self, index, color):
self._actions[index][0] = color
self.update()
@subject_slot_group('value')
def _on_button(self, value, button):
idx = [b for b in self._buttons].index(button)
if len(self._actions) > idx:
_ , down, up = self._actions[idx]
if value and down:
down()
elif not value and up:
up()
def update(self):
if self.is_enabled():
self._on_button.replace_subjects(self._buttons or [ ])
if self._enable_lights:
for action, button in zip(self._actions or [ ], self._buttons or [ ]):
if button:
color, _, _ = action
if color:
button.set_light(color)
else:
OFF_COLOR.draw(button)
else:
self._on_button.replace_subjects([ ])
| {
"repo_name": "bvalosek/ableton-live-scripts",
"path": "bvalosek_Midi_Fighter_Twister/MenuComponent.py",
"copies": "1",
"size": "1841",
"license": "mit",
"hash": 8426564027891804000,
"line_mean": 30.7413793103,
"line_max": 86,
"alpha_frac": 0.5524171646,
"autogenerated": false,
"ratio": 4.232183908045977,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0029176624274758157,
"num_lines": 58
} |
from _Framework.ControlSurfaceComponent import ControlSurfaceComponent
from consts import *
class BackgroundComponent(ControlSurfaceComponent):
"""
A nop component that we just clear everything. Set to a low-priority layer
so that anything not mapped will get grabbed and cleared
The buttons are not actually grabbed, just set_light / send_value push out
to them, so other layers can actually grab them
"""
def __init__(self, raw = None, color = 'DefaultButton.Off', *a, **k):
super(BackgroundComponent, self).__init__(*a, **k)
self._color = color
self._raw = raw
self._lights = None
self._knobs = None
def set_raw(self, raw):
self._raw = raw
self.update()
def set_lights(self, lights):
self._lights = lights
self.update()
def set_knobs(self, knobs):
self._knobs = knobs
self.update()
def on_enabled_changed(self):
self.update()
def update(self):
if self.is_enabled():
for index, light in enumerate(self._lights or [ ]):
if light:
if self._raw:
self._raw[index].draw(light)
else:
light.set_light(self._color)
for knob in self._knobs or []:
if knob:
knob.send_value(0, force = True)
knob.send_value(65, channel = KNOB_ANIMATION_CHANNEL, force = True)
| {
"repo_name": "bvalosek/ableton-live-scripts",
"path": "bvalosek_Midi_Fighter_Twister/BackgroundComponent.py",
"copies": "1",
"size": "1496",
"license": "mit",
"hash": 4910741847936508000,
"line_mean": 30.1666666667,
"line_max": 87,
"alpha_frac": 0.5655080214,
"autogenerated": false,
"ratio": 4.065217391304348,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5130725412704348,
"avg_score": null,
"num_lines": null
} |
from _Framework.ControlSurfaceComponent import ControlSurfaceComponent
class M4LInterface(ControlSurfaceComponent):
def __init__(self):
ControlSurfaceComponent.__init__(self)
self._name = 'OSD'
self._update_listener = None
self._updateML_listener = None
self.mode = ' '
self.clear()
def disconnect(self):
self._updateM4L_listener = None
def set_mode(self, mode):
self.clear()
self.mode = mode
def clear(self):
self.info = [' ', ' ']
self.attributes = [' ' for _ in range(8)]
self.attribute_names = [' ' for _ in range(8)]
def set_update_listener(self, listener):
self._update_listener = listener
def remove_update_listener(self, listener):
self._update_listener = None
def update_has_listener(self):
return self._update_listener is not None
@property
def updateML(self):
return True
def set_updateML_listener(self, listener):
self._updateML_listener = listener
def add_updateML_listener(self, listener):
self._updateML_listener = listener
return
def remove_updateML_listener(self, listener):
self._updateML_listener = None
return
def updateML_has_listener(self, listener):
return self._updateML_listener is not None
def update(self, args=None):
if self.updateML_has_listener(None):
self._updateML_listener()
| {
"repo_name": "jim-cooley/abletonremotescripts",
"path": "remote-scripts/samples/Launchpad95/M4LInterface.py",
"copies": "1",
"size": "1286",
"license": "apache-2.0",
"hash": 2347664051915554000,
"line_mean": 22.3818181818,
"line_max": 70,
"alpha_frac": 0.7130637636,
"autogenerated": false,
"ratio": 3.239294710327456,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9310961312172079,
"avg_score": 0.028279432351075422,
"num_lines": 55
} |
from framework.convenience import ConvenienceFunctions
from framework.deprecated.controllers import VideoScheduler, CheckpointDriving, MathScheduler, AudioRewardLogic, VisualSearchTask
from framework.latentmodule import LatentModule
from framework.ui_elements.ImagePresenter import ImagePresenter
from framework.ui_elements.TextPresenter import TextPresenter
from framework.ui_elements.AudioPresenter import AudioPresenter
from framework.ui_elements.RandomPresenter import RandomPresenter
from framework.ui_elements.EventWatcher import EventWatcher
from direct.gui.DirectGui import DirectButton
from panda3d.core import *
import random
import time
import pickle
# exp structure:
# - the main run consists of numavbouts A/V bouts (60)
# - every rest_every A/V bouts, a pause is inserted (3)
# - the pause takes rest_duration seconds (45..75)
# - each A/V bout contains 6 focus periods (lv,rv,la,ra,lvla,rvra) in some admissible order and balanced in pairs of bouts
# - each focus period contains focus_numstims stimuli (15..40), a fraction being targets (1/3)
# - each stimulus is displayed for stim_duration seconds (0.9s)
# - at the beginning of each focus block there is an extra pull stimulus (0.9s)
# assuming 90 minutes experiment
# Total duration of main block: ~93 minutes on average (with some randomness)
# Total # of stims: 5400
# Total # of targets: 1800
# Targets per modality: 450 (~dual/single)
# Total # of switches: 180
# Switches across modalities: ca. 100
# Switches A->V: ca. 50
# Switches V->A: ca. 50
#
class WarningTask(LatentModule):
"""
A press-when-the-warning-goes-off task that runs in parallel to the rest of the experiment.
"""
def __init__(self,
rewardlogic,
event_interval=lambda: random.uniform(45,85), # interval between two successive events
snd_probability=0.5, # probability that an event is indicated by a sound (instead of a pic)
pic_off='light_off.png', # picture to display for the disabled light
pic_on='light_on.png', # picture to display for the enabled light
snd_on='alert.wav', # sound to play in case of an event
snd_hit='xClick01.wav', # sound when the user correctly detected the warning state
pic_params={'pos':[0,0],'scale':0.2}, # parameters for the picture() command
snd_params={'volume':0.15,'direction':0.0}, # parameters for the sound() command
response_key='space', # key to press in case of an event
timeout=1.5, # response timeout for the user
hit_reward=0, # reward if hit
miss_penalty=-10, # penalty if missed
false_penalty=-5, # penalty for false positives
):
LatentModule.__init__(self)
self.rewardlogic = rewardlogic
self.event_interval = event_interval
self.snd_probability = snd_probability
self.pic_off = pic_off
self.pic_on = pic_on
self.snd_on = snd_on
self.snd_hit = snd_hit
self.pic_params = pic_params
self.snd_params = snd_params
self.response_key = response_key
self.timeout = timeout
self.hit_reward = hit_reward
self.miss_penalty = miss_penalty
self.false_penalty = false_penalty
def run(self):
# pre-cache the media files...
self.precache_picture(self.pic_on)
self.precache_picture(self.pic_off)
self.precache_sound(self.snd_on)
# set up an event watcher (taking care of timeouts and inappropriate responses)
watcher = EventWatcher(eventtype=self.response_key,
handleduration=self.timeout,
defaulthandler=lambda: self.rewardlogic.score_event(self.false_penalty))
while True:
# show the "off" picture for the inter-event interval
self.picture(self.pic_off, self.event_interval(), **self.pic_params)
# start watching for a response
watcher.watch_for(self.correct, self.timeout, lambda: self.rewardlogic.score_event(self.miss_penalty))
if random.random() < self.snd_probability:
# play a sound and continue with the off picture
self.sound(self.snd_on, **self.snd_params)
self.marker(3)
self.picture(self.pic_off, self.timeout, **self.pic_params)
else:
# show the "on" picture
self.marker(4)
self.picture(self.pic_on, self.timeout, **self.pic_params)
self.marker(5)
def correct(self):
# called when the user correctly spots the warning event
self.sound(self.snd_hit,**self.snd_params)
self.rewardlogic.score_event(self.hit_reward)
class HoldTask(LatentModule):
"""
A task that requires pressing and holding one of two buttons for extended periods of time.
"""
def __init__(self,
rewardlogic,
left_button='z',
right_button='3',
nohold_duration=lambda: random.uniform(45,85), # duration of a no-hold period
hold_duration=lambda: random.uniform(30,45), # duration of a hold period
pic='hold.png', # picture to indicate that a button should be held
snd='hold.wav', # sound to indicate that a button should be held
left_pos=[-0.5,-0.92], # position if left
right_pos=[0.5,-0.92], # position if right
pic_params={'scale':0.2}, # parameters for the picture() command
snd_params={'volume':0.1}, # parameters for the sound() command
scoredrain_snd='xTick.wav', # sound to play when the score is trained...
left_dir=-1, # direction of the left "hold" sound
right_dir=+1, # direction of the right "hold" sound
loss_amount=-0.25, # amount of score lost if not held
loss_interval=0.5, # interval at which score is subtracted
):
LatentModule.__init__(self)
self.rewardlogic = rewardlogic
self.left_button = left_button
self.right_button = right_button
self.nohold_duration = nohold_duration
self.hold_duration = hold_duration
self.pic = pic
self.snd = snd
self.left_pos = left_pos
self.right_pos = right_pos
self.pic_params = pic_params
self.snd_params = snd_params
self.scoredrain_snd = scoredrain_snd
self.left_dir = left_dir
self.right_dir = right_dir
self.loss_amount = loss_amount
self.loss_interval = loss_interval
self.should_hold = False
self.left_down = False
self.right_down = False
def run(self):
# set up checks for the appropriate keys
self.accept(self.left_button,self.update_key_status,['left-down'])
self.accept(self.left_button + '-up',self.update_key_status,['left-up'])
self.accept(self.right_button,self.update_key_status,['right-down'])
self.accept(self.right_button + '-up',self.update_key_status,['right-up'])
# start a timer that checks if the appropriate button is down
taskMgr.doMethodLater(self.loss_interval,self.score_drain,'Score drain')
while True:
# no-hold condition: wait for the nohold duration
self.should_hold = False
self.sleep(self.nohold_duration())
# select a side to hold at
if random.choice(['left','right']) == 'left':
self.button = 'left'
pos = self.left_pos
dir = self.left_dir
self.marker(6)
else:
self.button = 'right'
pos = self.right_pos
dir = self.right_dir
self.marker(7)
# hold condition: display the hold picture & play the hold indicator sound...
self.should_hold = True
self.sound(self.snd,direction=dir,**self.snd_params)
self.picture(self.pic,self.hold_duration(),pos=pos,**self.pic_params)
self.marker(8)
def score_drain(self,task):
"""Called periodically to check whether the subject is holding the correct button."""
if self.should_hold:
# subject should hold down a particular button
if self.button == 'left' and (self.right_down or not self.left_down):
self.rewardlogic.score_event(self.loss_amount,nosound=True)
self.marker(9)
self.sound(self.scoredrain_snd)
if self.button == 'right' and (self.left_down or not self.right_down):
self.rewardlogic.score_event(self.loss_amount,nosound=True)
self.marker(10)
self.sound(self.scoredrain_snd)
elif self.left_down or self.right_down:
# subject should hold neither the left nor the right button...
self.rewardlogic.score_event(self.loss_amount,nosound=True)
self.marker(11)
self.sound(self.scoredrain_snd)
return task.again
def update_key_status(self,evt):
"""Called whenever the status of the left or right key changes."""
if evt=='left-up':
self.left_down = False
elif evt=='left-down':
self.left_down = True
if evt=='right-up':
self.right_down = False
elif evt=='right-down':
self.right_down = True
class Main(LatentModule):
"""
DAS1b: Second version of the DAS experiment #1.
"""
def __init__(self):
LatentModule.__init__(self)
# --- default parameters (may also be changed in the study config) ---
# block design
self.randseed = 11115 # some initial randseed for the experiment; note that this should be different for each subject (None = random)
self.numavbouts = 30 # number of A/V bouts in the experiment (x3 is approx. duration in minutes)
self.fraction_words = 0.5 # words versus icons balance
self.rest_every = 3 # number of A/V bouts until a rest block is inserted
self.resttypes = ['rest-movers-vis','rest-movers-mov','rest-math','rest-videos','rest-drive'] # these are the different flavors of the rest condition
self.resttypes_avcompat = ['rest-movers-vis','rest-movers-mov','rest-videos','rest-drive'] # a subset of rest center tasks that may run in parallel to the a/v bouts
# self.fraction_withinmodality_switches = [0.2,0.4] # fraction of within-modality switches (range) -- note: only a few distinct numbers are actually possible here: currently disabled
# keys (for the key labels see http://www.panda3d.org/manual/index.php/Keyboard_Support)
self.lefttarget = 'lcontrol' # left-side target button
self.righttarget = 'rcontrol' # right-side target button
self.lefthold = 'lalt' # left hold button
self.righthold = 'ralt' # right hold button (keypad enter)
self.max_successive_keypresses = 5 # maximum number of successive kbd presses until penalty kicks in
self.max_successive_touches = 5 # maximum number of successive touch presses until penalty kicks in
self.max_successive_sound = 'slap.wav' # this is the right penalty sound!
# score logic setup (parameters to SimpleRewardLogic)
self.score_params = {'initial_score':0, # the initial score
'sound_params':{'direction':-0.7}, # properties of the score response sound
'gain_file':'ding.wav', # sound file per point
'loss_file':'xBuzz01-rev.wav', # sound file for losses
'none_file':'click.wav', # file to play if no reward
'buzz_volume':0.4, # volume of the buzz (multiplied by the amount of loss)
'gain_volume':0.5, # volume of the gain sound
'ding_interval':0.1, # interval at which successive gain sounds are played... (if score is > 1)
'scorefile':'C:\\Studies\\DAS\scoretable.txt'} # this is where the scores are logged
self.loss_nontarget_press = -1 # loss if pressed outside a particular target response window
self.loss_target_miss = -1 # loss if a target was missed
self.gain_target_fav = 1 # gain if a favored target was hit (ck: fav scoring disabled)
self.gain_target_nofav = 1 # gain if a non-favored target was hit (in a dual-modality setup)
self.gain_hiexpense_plus = 1 # additional gain if the high-expense button was used to hit a target
self.gain_cued_plus = 1 # additional gain if the double-pressing was correctly performed in response to a cued target
# screen button layout (parameters to DirectButton)
self.button_left = {'frameSize':(-3.5,3.5,-0.6,1.1),'pos':(-1.1,0,-0.85),'text':"Target",'scale':.075,'text_font':loader.loadFont('arial.ttf')} # parameters of the left target button
self.button_right = {'frameSize':(-3.5,3.5,-0.6,1.1),'pos':(1.1,0,-0.85),'text':"Target",'scale':.075,'text_font':loader.loadFont('arial.ttf')} # parameters of the right target button
self.button_center = {'frameSize':(-3,3,-0.5,1),'pos':(0,0,-0.92),'text':"Warn Off",'scale':.075,'text_font':loader.loadFont('arial.ttf')} # parameters of the center "warning off" button
# visual presenter location layout (parameters to ImagePresenter and TextPresenter, respectively)
self.img_center_params = {'pos':[0,0,0.3],'clearafter':1.5,'scale':0.1}
self.img_left_params = {'pos':[-0.8,0,0.3],'clearafter':0.3,'color':[1, 1, 1, 1],'scale':0.1,'rotation': (lambda: [0,0,random.random()*360])}
self.img_right_params = {'pos':[0.8,0,0.3],'clearafter':0.3,'color':[1, 1, 1, 1],'scale':0.1,'rotation': (lambda: [0,0,random.random()*360])}
self.txt_left_params = {'pos':[-0.8,0.3],'clearafter':0.4,'framecolor':[0, 0, 0, 0],'scale':0.1,'align':'center'}
self.txt_right_params = {'pos':[0.8,0.3],'clearafter':0.4,'framecolor':[0, 0, 0, 0],'scale':0.1,'align':'center'}
# auditory presenter location layout (parameters to AudioPresenter)
self.aud_center_params = {'direction':0.0,'volume':0.5}
self.aud_left_params = {'direction':-2,'volume':0.5}
self.aud_right_params = {'direction':2,'volume':0.5}
# design of the focus blocks (which are scheduled in bouts of length 6):
self.pull_probability = 1 # chance that a pull cue is presented in case of a left/right switch (ck: disabled the no-pull condition)
self.pull_duration = 0.9 # duration for which the pull cue is presented (in s)
self.push_duration = 0.9 # duration for which the push cue is presented (in s)
self.pull_volume = 2 # pull stimuli have a different volume from others (more salient)
self.push_volume = 1 # push stimuli may have a different volume
self.focus_numstims = lambda: random.uniform(15,40) # number of stimuli in a single focus block (for now: 20-40, approx. 10 seconds @ 3Hz)
self.target_probability = 1.0/3 # probability that a given stimulus is a target (rather than a non-target)
self.cue_probability = 0.0 # probability that a given target stimulus is turned into a cue (if there is no outstanding cue at this time)
self.cue_duration = 0.75 # duration of a cue stimulus
self.stim_duration = 0.75 # duration (inter-stimulus interval) for a target/nontarget stimulus
self.target_free_time = 0.75 # duration, after a target, during which no other target may appear
self.speech_offset = 0.2 # time offset for the animate/inanimate speech cues
# response timing
self.response_duration_words = 2.5 # timeout for response in the words condition
self.response_duration_icons = 2.5 # timeout for response in the icons/beeps condition
self.response_dp_duration = 0.25 # time window within which the second press of a double-press action has to occur
# stimulus material
self.animate_words = 'media\\animate.txt' # text file containing a list of animate (target) words
self.inanimate_words = 'media\\inanimate.txt' # text file containing a list of inanimate (non-target) words
self.target_beeps = ['t_t.wav'] # list of target stimuli in the icons/beeps condition
self.nontarget_beeps = ['nt_t.wav'] # list of non-target stimuli in the icons/beeps condition
self.target_pics = ['disc-4-green.png'] # list of target pictures in the icons/beeps condition
self.nontarget_pics = ['disc-3-green.png'] # list of non-target pictures in the icons/beeps condition
self.pull_icon = 'disc-0-red-salient.png' # pull stimulus as icon (red circle)
self.pull_word = '\1salient\1RED!\1salient\1' # pull stimulus as word
self.pull_tone = 'red_t-rev2.wav' # pull stimulus as tone
self.pull_speech_f = 'red_f-rev2.wav' # pull stimulus spoken by a female
self.pull_speech_m = 'red_m-rev2.wav' # pull stimulus spoken by a male
self.cue_icon = 'disc-0-yellow.png' # cue stimulus as icon (yellow circle)
self.cue_word = 'cue' # cue stimulus as word
self.cue_tone = 'cue_t.wav' # cue stimulus as tone
self.cue_speech_f = 'cue_f-rev.wav' # cue stimulus spoken by a female
self.cue_speech_m = 'cue_m-rev.wav' # cue stimulus spoken by a male
# configuration of the warning task
self.warning_params = {'event_interval':lambda: random.uniform(45,85), # interval between two successive events
'snd_probability':0.5, # probability that an event is indicated by a sound (instead of a pic)
'pic_off':'buzzer-grey.png', # picture to display for the disabled light
'pic_on':'buzzer-red-real.png', # picture to display for the enabled light
'snd_on':'xHyprBlip.wav', # sound to play in case of an event
'snd_hit':'xClick01.wav', # sound when the user correctly detected the warning state
'pic_params':{'pos':[0,0.6],'scale':0.1}, # parameters for the picture() command
'snd_params':{'volume':0.1,'direction':0.0}, # parameters for the sound() command
'response_key':'enter', # key to press in case of an event
'timeout':3, # response timeout for the user
'hit_reward':0, # reward if hit
'miss_penalty':-10, # penalty if missed
'false_penalty':-5 # penalty for false positives
}
# configuration of the hold task
self.hold_params = {'left_button':'z', # the left button to hold
'right_button':'3', # the right button to hold
'nohold_duration':lambda: random.uniform(45,85), # duration of a no-hold period
'hold_duration':lambda: random.uniform(25,35), # duration of a hold period
'pic':'hold_down.png', # picture to indicate that a button should be held
'snd':'xBleep.wav', # sound to indicate that a button should be held
'left_pos':[-0.7,-0.9], # position if left
'right_pos':[0.7,-0.9], # position if right
'pic_params':{'scale':0.1}, # parameters for the picture() command
'snd_params':{'volume':0.1}, # parameters for the sound() command
'scoredrain_snd':'xTick-rev.wav', # sound to play when the score is trained...
'left_dir':-1, # direction of the left "hold" sound
'right_dir':+1, # direction of the right "hold" sound
'loss_amount':0.25, # amount of score lost if not held
'loss_interval':0.5, # interval at which score is subtracted
}
# configuration of the rest block
self.rest_duration = lambda: random.uniform(45,75) # duration of a rest block (was: 45-75)
# center tasks
self.movers_vis_params = {'background':'satellite_baseline.png', # background image to use
'frame':[0.35,0.65,0.2,0.6], # the display region in which to draw everything
'frame_boundary':0.2, # (invisible) zone around the display region in which things can move around and spawn
'focused':True,
# parameters of the target/non-target item processes
'clutter_params':{'pixelated':True,
'num_items':140,
'item_speed': lambda: random.uniform(0,0.05), # overall item movement speed; may be callable
'item_diffusion': lambda: random.normalvariate(0,0.005), # item Brownian perturbation process (applied at each frame); may be callable
}, # parameters for the clutter process
'target_params':{'pixelated':True,
'num_items':1,
'item_speed': lambda: random.uniform(0,0.05), # overall item movement speed; may be callable
'item_diffusion': lambda: random.normalvariate(0,0.005), # item Brownian perturbation process (applied at each frame); may be callable
'item_graphics':['tactical\\unit15.png','tactical\\unit15.png','tactical\\unit17.png']}, # parameters for the target process
'intro_text':'Find the helicopter!', # the text that should be displayed before the script starts
# situational control
'target_probability':0.5, # probability of a new situation being a target situation (vs. non-target situation)
'target_duration':lambda: random.uniform(3,6), # duration of a target situation
'nontarget_duration':lambda: random.uniform(10,20),# duration of a non-target situation
# end conditions
'end_trials':1000000, # number of situations to produce (note: this is not the number of targets)
'end_timeout':1000000, # lifetime of this stream, in seconds (the stream ends if the trials are exhausted)
# response control
'response_event':'space', # the event that is generated when the user presses the response button
'loss_misstarget':0, # the loss incurred by missing a target
'loss_nontarget':-2, # the loss incurred by a false detection
'gain_target':4, # the gain incurred by correctly spotting a target
}
self.movers_mov_params = {'background':'satellite_baseline.png', # background image to use
'frame':[0.35,0.65,0.2,0.6], # the display region in which to draw everything
'frame_boundary':0.2, # (invisible) zone around the display region in which things can move around and spawn
'focused':True,
# parameters of the target/non-target item processes
'clutter_params':{'pixelated':True,
'num_items':30}, # parameters for the clutter process
'target_params':{'pixelated':True,
'num_items':1,
'item_speed':lambda: random.uniform(0.1,0.25),
'item_spiral':lambda: [random.uniform(0,3.14),random.uniform(0.0075,0.0095),random.uniform(0.06,0.07)], # perform a spiraling motion with the given radius and angular velocity
}, # parameters for the target process
'intro_text':'Find the spiraling object!', # the text that should be displayed before the script starts
# situational control
'target_probability':0.5, # probability of a new situation being a target situation (vs. non-target situation)
'target_duration':lambda: random.uniform(3,6), # duration of a target situation
'nontarget_duration':lambda: random.uniform(5,15),# duration of a non-target situation
# end conditions
'end_trials':1000000, # number of situations to produce (note: this is not the number of targets)
'end_timeout':1000000, # lifetime of this stream, in seconds (the stream ends if the trials are exhausted)
# response control
'response_event':'space', # the event that is generated when the user presses the response button
'loss_misstarget':0, # the loss incurred by missing a target
'loss_nontarget':-2, # the loss incurred by a false detection
'gain_target':2, # the gain incurred by correctly spotting a target
}
self.math_params = {'difficulty': 2, # difficulty level of the problems (determines the size of involved numbers)
'focused':True,
'problem_interval': lambda: random.uniform(3,12), # delay before a new problem appears after the previous one has been solved
'response_timeout': 10.0, # time within which the subject may respond to a problem
'gain_correct':5,
'loss_incorrect':-3,
'numpad_topleft': [0.9,-0.3], # top-left corner of the numpad
'numpad_gridspacing': [0.21,-0.21], # spacing of the button grid
'numpad_buttonsize': [1,1] # size of the buttons
}
self.video_params = {'files':['big\\forest.mp4'], # the files to play (randomly)
'movie_params': {'pos':[0,-0.2], # misc parameters to the movie() command
'scale':[0.5,0.3],
'aspect':1.12,
'looping':True,
'volume':0.3}}
self.driving_params = {'frame':[0.35,0.65,0.2,0.6], # the display region in which to draw everything
'focused':True,
'show_checkpoints':False,
# media
'envmodel':'big\\citty.egg', # the environment model to use
'trucksound':"Diesel_Truck_idle2.wav",# loopable truck sound....
'trucksound_volume':0.25, # volume of the sound
'trucksound_direction':0, # direction relative to listener
'target_model':"moneybag-rev.egg", # model of the target object
'target_scale':0.01, # scale of the target model
'target_offset':0.2, # y offset for the target object
# checkpoint logic
'points':[[-248.91,-380.77,4.812],[0,0,0]], # the sequence of nav targets...
'radius':10, # proximity to checkpoint at which it is considered reached... (meters)
# end conditions
'end_timeout':100000, # end the task after this time
# movement parameters
'acceleration':0.5, # acceleration during manual driving
'friction':0.95, # friction coefficient
'torque':1, # actually angular velocity during turning
'height':0.7}
# ambience sound setup
self.ambience_sound = 'media\\ambience\\nyc_amb2.wav'
self.ambience_volume = 0.1
# misc parameters
self.developer = False, # if true, some time-consuming instructions are skipped
self.disable_center = False
self.show_tutorial = False # whether to show the tutorial
self.run_main = True # whether to run through the main game
def run(self):
try:
self.marker(12)
# define the "salient" text property (should actually have a card behind this...)
tp_salient = TextProperties()
tp_salient.setTextColor(1, 0.3, 0.3, 1)
tp_salient.setTextScale(1.8)
tpMgr = TextPropertiesManager.getGlobalPtr()
tpMgr.setProperties("salient", tp_salient)
# --- init the block design ---
# init the randseed
if self.randseed is not None:
print "WARNING: Randomization of the experiment is currently bypassed."
random.seed(self.randseed)
self.marker(30000+self.randseed)
if self.numavbouts % 2 != 0:
raise Exception('Number of A/V bouts must be even.')
# init the a/v bout order (lfem stands for "left female voice", rfem for "right female voice")
bouts = ['av-words-lfem']*int(self.fraction_words*self.numavbouts/2) + ['av-words-rfem']*int(self.fraction_words*self.numavbouts/2) + ['av-icons']*int((1-self.fraction_words)*self.numavbouts)
random.shuffle(bouts)
# check if we have previously cached the focus order on disk (as it takes a while to compute it)
cache_file = 'media\\focus_order_' + str(self.randseed) + '_new.dat'
if False: # os.path.exists(cache_file):
focus_order = pickle.load(open(cache_file))
else:
self.write('Calculating the experiment sequence.',0.1,scale=0.04)
# generate the focus transitions for each pair of bouts
valid = {'lv': ['rv','la','lvla'], # set of valid neighbors for each focus condition (symmetric)
'rv': ['lv','ra','rvra'],
'la': ['lv','ra','lvla'],
'ra': ['la','rv','rvra'],
'lvra': ['lv','ra'],
'rvla': ['rv','la'],
'lvla': ['lv','la'],
'rvra': ['rv','ra']}
focus_order = [] # list of focus conditions, per bout
prev = None # end point of the previous bout (before b)
# for each pair of bouts...
for b in range(0,len(bouts),2):
while True:
# generate a radom ordering of the mono conditions (balanced within each bout)
mono1 = ['lv','rv','la','ra']; random.shuffle(mono1)
mono2 = ['lv','rv','la','ra']; random.shuffle(mono2)
order = mono1 + mono2
# generate a random order of dual conditions (balanced within each pair of bouts)
dual = ['lvla','rvra','lvla','rvra']; random.shuffle(dual)
# and a list of insert positions in the first & second half (we only retain the first 2 indices in each after shuffling)
pos1 = [1,2,3,4]; random.shuffle(pos1)
pos2 = [5,6,7,8]; random.shuffle(pos2)
# the following instead allows split-attention modes to appear at the beginning of blocks
# # and a list of insert positions in the first half
# pos1 = [1,2,3,4] if prev is None or len(prev)==4 else [0,1,2,3,4]; random.shuffle(pos1)
# # and a list of insert positions in the second half
# pos2 = [5,6,7,8] if pos1[0]==4 or pos1[1]==4 else [4,5,6,7,8]; random.shuffle(pos2)
# now insert at the respective positions (in reverse order to not mix up insert indices)
order.insert(pos2[1],dual[3])
order.insert(pos2[0],dual[2])
order.insert(pos1[1],dual[1])
order.insert(pos1[0],dual[0])
# now check sequence admissibility (accounting for the previous block if any)
check = order if prev is None else [prev] + order
admissible = True
for c in range(len(check)-1):
if check[c+1] not in valid[check[c]]:
# found an invalid transition
admissible = False
break
# and check the fraction of within-modality switches
#if admissible:
# num_withinmodality = 0
# for c in range(len(check)-1):
# if check[c][0] != check[c+1][0]:
# num_withinmodality += 1
# if (1.0 * num_withinmodality / len(check)) < self.fraction_withinmodality_switches[0] or (1.0 * num_withinmodality / len(check)) > self.fraction_withinmodality_switches[1]:
# admissible = False
if admissible:
break
# append two bouts to the focus_order array
focus_order.append(order[:6])
focus_order.append(order[6:])
# and remember the end point of what we just appended
prev = order[-1]
pickle.dump(focus_order,open(cache_file,'w'))
# insert the rest periods into bouts and focus_order..
insert_pos = range(len(bouts)-2,1,-self.rest_every)
# generate the rest conditions
rests = self.resttypes*(1+len(bouts)/(self.rest_every*len(self.resttypes)))
rests = rests[:len(insert_pos)]
random.shuffle(rests)
# now insert
for k in range(len(insert_pos)):
bouts.insert(insert_pos[k],rests[k])
focus_order.insert(insert_pos[k],[])
# determine the schedule of center task
center_tasks = [None]*len(bouts)
compatible_tasks_needed = 1 # the number of specifically a/v compatible center tasks that will be needed during a/v bout
# a/v bouts after the last rest will need an a/v compatible center task
cur_task = 0
# go backwards and assign the current center task to each of the bouts...
for k in range(len(bouts)-1,-1,-1):
# until we find a rest block, which changes the center task
if bouts[k].find('rest-') >= 0:
cur_task = bouts[k]
else:
# if the center task is incompatible with a/v bouts, ...
if not cur_task in self.resttypes_avcompat and type(cur_task) != int:
# .. we take note that we need another a/v compatible task
cur_task = compatible_tasks_needed
compatible_tasks_needed += 1
center_tasks[k] = cur_task
# now generate a balanced & randomized list of a/v compatible tasks
avcompat = self.resttypes_avcompat * (1+compatible_tasks_needed/(len(self.resttypes_avcompat)))
avcompat = avcompat[:compatible_tasks_needed]
random.shuffle(avcompat)
# ... and use them in the center tasks where needed
for k in range(len(center_tasks)):
if type(center_tasks[k]) == int:
center_tasks[k] = avcompat[center_tasks[k]]
self.marker(13)
# --- pre-load the media files ---
self.sleep(0.5)
# pre-load the target/non-target words (and corresponding sound files)
animate_txt = []
animate_snd_m = []
animate_snd_f = []
with open(self.animate_words) as f:
for line in f:
word = line.strip(); animate_txt.append(word)
file = 'sounds\\' + word + '_m.wav'; animate_snd_m.append(file)
self.precache_sound(file)
file = 'sounds\\' +word + '_f.wav'; animate_snd_f.append(file)
self.precache_sound(file)
inanimate_txt = []
inanimate_snd_m = []
inanimate_snd_f = []
with open(self.inanimate_words) as f:
for line in f:
word = line.strip(); inanimate_txt.append(word)
file = 'sounds\\' +word + '_m.wav'; inanimate_snd_m.append(file)
self.precache_sound(file)
file = 'sounds\\' +word + '_f.wav'; inanimate_snd_f.append(file)
self.precache_sound(file)
# pre-load the target/non-target beeps
for p in self.target_beeps:
self.precache_sound(p)
for p in self.nontarget_beeps:
self.precache_sound(p)
# pre-load the target/non-target pictures
for p in self.target_pics:
self.precache_picture(p)
for p in self.nontarget_pics:
self.precache_picture(p)
self.marker(14)
# initially the target buttons are turned off
btarget_left = None
btarget_right = None
# --- present introductory material ---
while self.show_tutorial:
self.marker(15)
self.write('Welcome to the DAS experiment. Press the space bar to skip ahead.',[1,'space'],wordwrap=23,scale=0.04)
self.write('In this experiment you will be presented a series of stimuli, some of which are "targets", and some of which are "non-targets". In the following, we will go through the various types of target and non-target stimuli.',[1,'space'],wordwrap=23,scale=0.04)
self.write('There are in total 4 kinds of stimuli: spoken words, written words, icons, and tones.',[1,'space'],wordwrap=23,scale=0.04)
self.write('Among the words, you only need to respond to animal words and should ignore the non-animal words.',[1,'space'],wordwrap=23,scale=0.04)
self.write('Here is an example spoken animal (i.e., target) word:',[1,'space'],wordwrap=23,scale=0.04)
self.sound('sounds\\cat_f.wav',volume=1, direction=-1, surround=True,block=True)
self.write('And here is an example spoken non-animal (i.e., non-target) word:',[1,'space'],wordwrap=23,scale=0.04)
self.sound('sounds\\block_f.wav',volume=1, direction=-1, surround=True,block=True)
self.sleep(1)
self.write('Here are the same two words spoken by the male speaker.',[1,'space'],wordwrap=23,scale=0.04)
self.sound('sounds\\cat_m.wav',volume=1, direction=1, surround=True,block=True)
self.sleep(1)
self.sound('sounds\\block_m.wav',volume=1, direction=1, surround=True,block=True)
self.sleep(1)
tmp_left = DirectButton(command=None,rolloverSound=None,clickSound=None,**self.button_left)
tmp_right = DirectButton(command=None,rolloverSound=None,clickSound=None,**self.button_right)
self.write('You respond to these stimuli by either pressing the left (for left stimuli) or right (for right stimuli) Ctrl button on your keyboard, OR the big left/right buttons on the touch screen. You should not use the same button too many times in a row but alternate between the keyboard and the touch screen (there will be a penalty for using only one type of button many times in a row).',[1,'space'],wordwrap=23,scale=0.04)
tmp_left.destroy()
tmp_right.destroy()
self.write('The next type of stimulus is in the form of written words; again, animal words are targets and non-animal words are non-targets. Note that these will only light up for a short period of time.',[1,'space'],wordwrap=23,scale=0.04)
self.write('cat',0.3,pos=[-0.8,0,0.3],fg=[1, 1, 1, 1],scale=0.1,align='center')
self.sleep(1)
self.write('block',0.3,pos=[-0.8,0,0.3],fg=[1, 1, 1, 1],scale=0.1,align='center')
self.sleep(1)
self.write('The other type of visual stimulus are icons. These are small disks (randomly rotated) with a different number of spines. The number of spines determines if the icon is a target or not. There are only two different shapes.',[1,'space'],wordwrap=23,scale=0.04)
self.write('Here is a target.',[1,'space'],wordwrap=23,scale=0.04)
self.picture(self.target_pics[0], 3, pos=[0.8,0,0.3], scale=0.1, color=[1,1,1,1],hpr=[0,0,random.random()*360])
self.write('And here is a non-target.',[1,'space'],wordwrap=23,scale=0.04)
self.picture(self.nontarget_pics[0], 3, pos=[0.8,0,0.3], scale=0.1, color=[1,1,1,1],hpr=[0,0,random.random()*360])
self.write('The actual speed at which they show up is as follows.',[1,'space'],wordwrap=23,scale=0.04)
self.picture(self.target_pics[0], 0.3, pos=[0.8,0,0.3], scale=0.1, color=[1,1,1,1],hpr=[0,0,random.random()*360])
self.sleep(0.3)
self.picture(self.nontarget_pics[0], 0.3, pos=[0.8,0,0.3], scale=0.1, color=[1,1,1,1],hpr=[0,0,random.random()*360])
self.sleep(2)
self.write('Finally, the last type of stimulus are tones; these need to be memoized precisely.',[1,'space'],wordwrap=23,scale=0.04)
self.write('Here is a target.',[1,'space'],wordwrap=23,scale=0.04)
self.sound(self.target_beeps[0],volume=1, direction=1, surround=True,block=True)
self.sleep(1)
self.write('And here is a non-target.',[1,'space'],wordwrap=23,scale=0.04)
self.sound(self.nontarget_beeps[0],volume=1, direction=1, surround=True,block=True)
self.sleep(1)
self.write('Target and non-target will be played again for memoization. You will hear many more non-targets than targets, so listen carefully for their relative difference.',[1,'space'],wordwrap=23,scale=0.04)
self.sound(self.target_beeps[0],volume=1, direction=1, surround=True,block=True)
self.sleep(1)
self.sound(self.nontarget_beeps[0],volume=1, direction=1, surround=True,block=True)
self.sleep(1)
self.write('Finally, and most importantly, there is a special and very noticable "cue event" that may appear among those stimuli.',[1,'space'],wordwrap=23,scale=0.04)
self.write('It tells you to which side (left or right) AND to which modality (auditory or visual) you should attend by responding to targets that occur in that modality and side.',[1,'space'],wordwrap=23,scale=0.04)
self.write('There are four versions of it -- one for each form of stimulus -- which will be played as follows. We will go through the sequence twice.',[1,'space'],wordwrap=23,scale=0.04)
for k in range(2):
self.write('In written word form:',[1,'space'],wordwrap=23,scale=0.04)
self.write(self.pull_word,0.3,pos=[0.8,0,0.3],fg=[1, 1, 1, 1],scale=0.1,align='center')
self.sleep(1)
self.write('In spoken word form:',[1,'space'],wordwrap=23,scale=0.04)
self.sound(self.pull_speech_m,volume=2, direction=1, surround=True,block=True)
self.sleep(1)
self.write('In icon form:',[1,'space'],wordwrap=23,scale=0.04)
self.picture(self.pull_icon, 0.3, pos=[0.8,0,0.3], scale=0.1, color=[1,1,1,1],hpr=[0,0,random.random()*360])
self.sleep(1)
self.write('And in tone form:',[1,'space'],wordwrap=23,scale=0.04)
self.sound(self.pull_tone,volume=2, direction=1, surround=True,block=True)
self.sleep(1)
self.write('Note for comparison the non-target sound:',[1,'space'],wordwrap=23,scale=0.04)
self.sound(self.nontarget_beeps[0],volume=1, direction=1, surround=True,block=True)
self.sleep(3)
self.write('In other words, if you HEAR a cue on the left side (the very high-pitched tone or the girl/man saying "red"), you respond to AUDITORY targets on the LEFT side and ignore the other targets (that is left visual targets, right visual targets, and right auditory targets).',[1,'space'],wordwrap=23,scale=0.04)
self.write('Or if you SEE a cue on that side (the bright circle or the word "RED!"), you respond to VISUAL targets on that side and ignore all other targets (left auditory, right auditory, right visual).',[1,'space'],wordwrap=23,scale=0.04)
self.sleep(1)
self.write('In a fraction of cases, you will BOTH see a cue and hear a cue at the same time on one of the sides (e.g., right). This indicates that you need to respond to both visual AND auditory targets on that side and ignore targets on the other side. The only constellation in which this may happen is either both left visual and auditory, or both right visual and auditory cues.',[1,'space'],wordwrap=23,scale=0.04)
self.write('Consequently, these cues are guiding you around across the two speakers and the two side screens and determine what targets you should subsequently respond to. Responding to targets in the wrong location (or modality) will subtract some score. Note that the cues themselves do not demand a button response.',[1,'space'],wordwrap=23,scale=0.04)
self.write('Therefore - while these cues are quite noticable - you don''t want to miss them too frequently, as you not know what to respond to. Except if you figure it out by trial and error...',[1,'space'],wordwrap=23,scale=0.04)
self.sleep(1)
self.write('Whenever you hear a "Ding" sound, you will know that you earned 10 points. It sounds as follows:',[1,'space'],wordwrap=23,scale=0.04)
self.sound(self.score_params["gain_file"],volume=0.5, direction=-0.7, surround=True,block=True)
self.write('And whenever you hear a "Buzz" sound, you will know that you lost 10 points. It sounds as follows:',[1,'space'],wordwrap=23,scale=0.04)
self.sound(self.score_params["loss_file"],volume=0.4, direction=-0.7, surround=True,block=True)
self.write('It some cases you instead hear a "Click" sound in response to your key presses, which tells you that you neither gained nor lost points. It sounds as follows:',[1,'space'],wordwrap=23,scale=0.04)
self.sound(self.score_params["none_file"],volume=0.5, direction=-0.7, surround=True,block=True)
self.write('This may happen when the positive score for a key press (spotted a target) is canceled out by a negative score at the same time (e.g. by coincidence there was also a target in the other modality that you should not respond to). This is quite rare and not your fault, don''t think about it.',[1,'space'],wordwrap=23,scale=0.04)
self.write('This completes the discussion of the main task of the experiment. We will now go through a series of additional challenges that come up at random times throughout the experiment.',[1,'space'],wordwrap=23,scale=0.04)
# self.write('Also, sometimes you will be asked to hold down a left or right button on your keyboard, and keep holding it until the indicator disappears. This is indicated by the following type of picture.',[1,'space'],wordwrap=23,scale=0.04)
self.write('First and foremost, an event that will occasionally (but rarely) appear is a RED WARNING LIGHT in the upper center of the sceen, or a noticable ALARM SOUND. You must confirm that you noticed this type of event using the "ALARM" key on your keyboard. If you miss it, you lose a lot of score.',[1,'space'],wordwrap=23,scale=0.04)
#self.sleep(1)
#self.sound(self.hold_params['snd'],direction=self.hold_params['left_dir'],**self.hold_params['snd_params'])
#self.picture(self.hold_params['pic'],3,pos=self.hold_params['left_pos'],**self.hold_params['pic_params'])
self.sleep(2)
self.write('And secondly, there is always some action going on in the center of the screen that you may engage in to gain extra score. There will be a message at the beginning of each block which tells you how to interact with it. Most of the time, this is a search task in which you are asked to watch for and spot a relatively rare object, and confirm that you saw it via the "SATELLITE MAP" bar in the middle of the keyboard.',[1,'space'],wordwrap=23,scale=0.04)
self.write('If you miss any of these objects, you will not lose score, so you may disregard them if the main task demands too much attention. However, you can drastically increase your score by trying to accomplish the center-screen task whenever possible.',[1,'space'],wordwrap=23,scale=0.04)
self.write('In some blocks the center task will be relatively dull and does not require any response from you, or in another case you are asked to count the occurrences of an object which you report later to the experimenter.',[1,'space'],wordwrap=23,scale=0.04)
self.sleep(2)
self.write('By the way, there will be occasional resting blocks in which you may relax for a while (or earn some extra score if bored).',[1,'space'],wordwrap=23,scale=0.04)
self.write('After the tutorial the experimenter will ask you to play a training session of the experiment, so that you can familiarize yourself with the routines and ask questions about the experiment logic.',[1,'space'],wordwrap=23,scale=0.04)
self.write('Do you want to see the tutorial again? (y/n).',1.5,wordwrap=23,scale=0.04)
if self.waitfor_multiple(['y','n'])[0] == 'n':
break;
break
if not self.run_main:
self.write('Tutorial finished.\nPlease let the experimenter know when you are ready for the training session.',5,wordwrap=23,scale=0.04)
return
# --- set up persistent entities that stay during the whole experiment ---
# init the reward logic
self.rewardlogic = AudioRewardLogic(**self.score_params)
# init the keyboard shortcuts
self.accept(self.lefttarget,self.response_key,['target-keyboard','l'])
self.accept(self.righttarget,self.response_key,['target-keyboard','r'])
self.accept(self.lefthold,messenger.send,['left-hold'])
self.accept(self.righthold,messenger.send,['right-hold'])
# --- experiment block playback ---
self.marker(16)
no_target_before = time.time() # don't present a target before this time
self.init_response_parameters()
self.write('Press the space bar to start.','space',wordwrap=25,scale=0.04)
self.write('Prepare for the experiment.',3,wordwrap=25,scale=0.04)
for k in [3,2,1]:
self.write(str(k),scale=0.1)
# start some ambience sound loop
self.ambience = self.sound(self.ambience_sound,looping=True,volume=self.ambience_volume,direction=0)
# add a central button that acts as an additional space bar
center_button = DirectButton(command=messenger.send,extraArgs=['space'],rolloverSound=None,clickSound=None,**self.button_center)
# start the warning task
self.warningtask = self.launch(WarningTask(self.rewardlogic,**self.warning_params))
# start the hold task (ck: disabled)
# self.holdtask = self.launch(HoldTask(self.rewardlogic,**self.hold_params))
# for each bout...
prevbout = None # previous bout type
prevcenter = None # previous center task type
self.center = None # center task handle
for k in range(len(bouts)):
# schedule the center task
if not self.disable_center and center_tasks[k] != prevcenter:
# terminate the old center task
if self.center is not None:
self.center.cancel()
# launch a new center task
if center_tasks[k] == 'rest-movers-vis':
self.center = self.launch(VisualSearchTask(rewardlogic=self.rewardlogic,**self.movers_vis_params))
elif center_tasks[k] == 'rest-movers-mov':
self.center = self.launch(VisualSearchTask(rewardlogic=self.rewardlogic,**self.movers_mov_params))
elif center_tasks[k] == 'rest-math':
self.center = self.launch(MathScheduler(rewardhandler=self.rewardlogic,**self.math_params))
elif center_tasks[k] == 'rest-videos':
self.center = self.launch(VideoScheduler(**self.video_params))
elif center_tasks[k] == 'rest-drive':
self.write('Count the number of bags!',10,block=False,scale=0.04,wordwrap=25,pos=[0,0])
self.center = self.launch(CheckpointDriving(**self.driving_params))
else:
print "Unsupported center task; skipping"
prevcenter = center_tasks[k]
if bouts[k][0:3] == 'av-':
# --- got an A/V bout ---
self.marker(17)
# create buttons if necessary
if btarget_left is None:
btarget_left = DirectButton(command=self.response_key,extraArgs=['target-touchscreen','l'],rolloverSound=None,clickSound=None,**self.button_left)
if btarget_right is None:
btarget_right = DirectButton(command=self.response_key,extraArgs=['target-touchscreen','r'],rolloverSound=None,clickSound=None,**self.button_right)
# init visual presenters
words = bouts[k].find('words') >= 0
fem_left = bouts[k].find('lfem') >= 0
self.marker(23 if fem_left else 24)
if words:
self.marker(21)
vis_left = TextPresenter(**self.txt_left_params)
vis_right = TextPresenter(**self.txt_right_params)
vis_left_rnd = RandomPresenter(vis_left,{'target':animate_txt,'nontarget':inanimate_txt})
vis_right_rnd = RandomPresenter(vis_right,{'target':animate_txt,'nontarget':inanimate_txt})
else:
self.marker(22)
vis_left = ImagePresenter(**self.img_left_params)
vis_right = ImagePresenter(**self.img_right_params)
vis_left_rnd = RandomPresenter(vis_left,{'target':self.target_pics,'nontarget':self.nontarget_pics})
vis_right_rnd = RandomPresenter(vis_right,{'target':self.target_pics,'nontarget':self.nontarget_pics})
# init the audio presenters
aud_left = AudioPresenter(**self.aud_left_params)
aud_right = AudioPresenter(**self.aud_right_params)
if words:
aud_left_rnd = RandomPresenter(aud_left,{'target':animate_snd_f if fem_left else animate_snd_m,'nontarget':inanimate_snd_f if fem_left else inanimate_snd_m})
aud_right_rnd = RandomPresenter(aud_right,{'target':animate_snd_m if fem_left else animate_snd_f,'nontarget':inanimate_snd_m if fem_left else inanimate_snd_f})
else:
aud_left_rnd = RandomPresenter(aud_left,{'target':self.target_beeps,'nontarget':self.nontarget_beeps})
aud_right_rnd = RandomPresenter(aud_right,{'target':self.target_beeps,'nontarget':self.nontarget_beeps})
# make a list of all current presenters to choose from when displaying targets/non-targets
presenters = {'lv':vis_left_rnd, 'rv':vis_right_rnd, 'la':aud_left_rnd, 'ra':aud_right_rnd}
# determine response timeout for this block
response_duration = self.response_duration_words if words else self.response_duration_icons
prev_focus = None
outstanding_cue = None
focus_blocks = focus_order[k]
# for each focus block...
for f in range(len(focus_blocks)):
# determine the focus condition
focus = focus_blocks[f]
print 'Focus is now: ',focus
focusmap = {'lv':25,'rv':26,'la':27,'ra':28,'lvla':29,'lvra':30,'rvla':31,'rvra':32}
self.marker(focusmap[focus])
# reset the slap-penalty counters if switching sides
# (these penalize too many successive presses of the same button in a row)
if prev_focus is not None and focus[0] != prev_focus[0]:
self.reset_slap_counters()
# determine the favored position (gives 2 points, the other one gives 1 point)
if len(focus) == 4:
favored_pos = focus[:2] if random.choice([False,True]) else focus[2:]
favormap = {'lv':33,'rv':34,'la':35,'ra':36}
self.marker(favormap[favored_pos])
else:
favored_pos = focus
# if there is an outstanding pre-cue from the previous focus block, and
# the type of pre-cued modality is not contained in the current focus block:
if outstanding_cue is not None and focus.find(outstanding_cue) < 0:
self.marker(37)
# forget about it
outstanding_cue = None
# determine if we should present a "pull" cue:
if prev_focus is not None and len(prev_focus)==2 and len(focus)==2 and prev_focus[1]==focus[1]:
# we do that only in a pure left/right switch, and if we are not at the beginning of a new bout
dopull = random.random() < self.pull_probability
else:
# always give a pull cue
dopull = True
if dopull:
self.marker(38)
# present pull cue & wait for the pull duration
if focus.find('lv') >= 0:
vis_left.submit_wait(self.pull_word if words else self.pull_icon, self)
self.marker(39)
if focus.find('rv') >= 0:
vis_right.submit_wait(self.pull_word if words else self.pull_icon, self)
self.marker(40)
if focus.find('la') >= 0:
aud_left.submit_wait((self.pull_speech_f if fem_left else self.pull_speech_m) if words else self.pull_tone, self)
self.marker(41)
if focus.find('ra') >= 0:
aud_right.submit_wait((self.pull_speech_m if fem_left else self.pull_speech_f) if words else self.pull_tone, self)
self.marker(42)
self.sleep(self.pull_duration)
self.marker(43)
else:
pass
## present push cue & wait (TODO: use other marker #'s)
#self.marker(338)
## present push cue & wait for the duration
#if prev_focus.find('lv') >= 0:
# vis_left.submit_wait(self.pull_word if words else self.pull_icon, self)
# self.marker(339)
#if prev_focus.find('rv') >= 0:
# vis_right.submit_wait(self.pull_word if words else self.pull_icon, self)
# self.marker(340)
#if prev_focus.find('la') >= 0:
# # hack: temporarily change the volume of the audio presenters for the pull cue
# aud_left.submit_wait((self.pull_speech_f if fem_left else self.pull_speech_m) if words else self.pull_tone, self)
# self.marker(341)
#if prev_focus.find('ra') >= 0:
# # hack: temporarily change the volume of the audio presenters for the pull cue
# aud_right.submit_wait((self.pull_speech_m if fem_left else self.pull_speech_f) if words else self.pull_tone, self)
# self.marker(342)
#self.sleep(self.push_duration)
#self.marker(343)
# for each stimulus in this focus block...
numstims = int(self.focus_numstims())
for s in range(numstims):
# show a target or a non-target?
istarget = time.time() > no_target_before and random.random() < self.target_probability
if istarget:
no_target_before = time.time() + self.target_free_time
# turn the target into a cue?
iscue = outstanding_cue is None and random.random() < self.cue_probability
if iscue:
self.marker(44)
# determine where to present the cue (note: we only do that in any of the current focus modalities)
if len(focus) == 4:
# dual focus modality: choose one of the two
outstanding_cue = focus[:2] if random.choice([False,True]) else focus[2:]
else:
outstanding_cue = focus
# display it...
if outstanding_cue == 'lv':
vis_left.submit_wait(self.cue_word if words else self.cue_icon, self)
self.marker(45)
elif outstanding_cue == 'rv':
vis_right.submit_wait(self.cue_word if words else self.cue_icon, self)
self.marker(46)
elif outstanding_cue == 'la':
aud_left.submit_wait((self.cue_speech_f if fem_left else self.cue_speech_m) if words else self.cue_tone, self)
self.marker(47)
elif outstanding_cue == 'ra':
aud_right.submit_wait((self.cue_speech_m if fem_left else self.cue_speech_f) if words else self.cue_tone, self)
self.marker(48)
# and2 wait...
self.sleep(self.cue_duration)
self.marker(49)
elif istarget:
# present a target stimulus
self.marker(50)
pos = random.choice(['lv','rv','la','ra'])
presenters[pos].submit_wait("target",self)
targetmap = {'lv':51,'rv':52,'la':53,'ra':54}
self.marker(targetmap[pos])
# set up response handling
if pos == favored_pos:
reward = self.gain_target_fav
self.marker(55)
elif focus.find(pos) >= 0:
reward = self.gain_target_nofav
self.marker(56)
else:
reward = self.loss_nontarget_press
self.marker(57)
self.expect_response(reward=reward, timeout=response_duration, wascued=(outstanding_cue==pos), side=pos[0])
else:
# present a non-target stimulus
self.marker(58)
pos = random.choice(['lv','rv','la','ra'])
presenters[pos].submit_wait("nontarget",self)
nontargetmap = {'lv':59,'rv':60,'la':61,'ra':62}
self.marker(nontargetmap[pos])
# and wait for the inter-stimulus interval...
self.sleep(self.stim_duration)
self.marker(63)
# focus block completed
prev_focus = focus
# bout completed
self.marker(64)
# destroy presenters...
vis_left.destroy()
vis_right.destroy()
aud_left.destroy()
aud_right.destroy()
pass
elif bouts[k][0:5] == 'rest-':
self.marker(18)
# delete buttons if necessary
if btarget_left is not None:
btarget_left.destroy()
btarget_left = None
if btarget_right is not None:
btarget_right.destroy()
btarget_right = None
self.write("You may now rest for a while...",3,scale=0.04,pos=[0,0.4])
self.show_score()
# main rest block: just sleep and let the center task do the rest
duration = self.rest_duration()
if self.waitfor('f9', duration):
self.rewardlogic.paused = True
self.marker(400)
self.write("Pausing now. Please press f9 again to continue.",10,scale=0.04,pos=[0,0.4],block=False)
self.waitfor('f9', 10000)
self.rewardlogic.paused = False
self.marker(19)
self.sound('nice_bell.wav')
self.write("The rest block has now ended.",2,scale=0.04,pos=[0,0.4])
pass
else:
print "unsupported bout type"
prevbout = bouts[k]
self.write('Experiment finished.\nYou may relax now...',5,pos=[0,0.4],scale=0.04)
self.show_score()
if self.center is not None:
self.center.cancel()
self.warningtask.cancel()
self.holdtask.cancel()
finally:
try:
if btarget_left is not None:
btarget_left.destroy()
if btarget_right is not None:
btarget_right.destroy()
center_button.destroy()
except:
pass
self.marker(20)
def show_score(self):
""" Display the score to the subject & log it."""
self.write("Your score is: " + str(self.rewardlogic.score*10),5,scale=0.1,pos=[0,0.8])
self.rewardlogic.log_score()
def init_response_parameters(self):
"""Initialize data structures to keep track of user responses."""
self.response_outstanding = {'l':False,'r':False}
self.response_window = {'l':None,'r':None}
self.response_reward = {'l':None,'r':None}
self.response_wascued = {'l':None,'r':None}
self.response_dp_window = {'l':None,'r':None}
self.response_dp_was_hiexpense = {'l':None,'r':None}
self.response_dp_reward = {'l':None,'r':None}
self.reset_slap_counters()
def reset_slap_counters(self):
"""Reset the # of same-button presses in a row."""
self.response_numkbd = {'l':0,'r':0}
self.response_numtouch = {'l':0,'r':0}
def expect_response(self,reward,timeout,wascued,side):
"""Set up an expected response for a particular duration (overrides previous expected responses)."""
if self.response_outstanding[side] and self.response_dp_window[side] is not None:
# a previous response was still outstanding: issue a miss penalty...
if self.response_reward[side] > 0:
self.marker(65)
self.rewardlogic.score_event(self.loss_target_miss)
# set up a new response window
self.response_window[side] = time.time() + timeout
self.response_outstanding[side] = True
self.response_reward[side] = reward
self.response_wascued[side] = wascued
taskMgr.doMethodLater(timeout, self.response_timeout, 'EventWatcher.response_timeout()',extraArgs=[side])
def response_key(self,keytype,side):
"""This function is called when the user presses a target button."""
if keytype == 'target-touchscreen':
# keep track of the # of successive presses of that button...
self.response_numkbd[side] = 0
self.response_numtouch[side] += 1
self.marker(66 if side == 'l' else 67)
else:
# keep track of the # of successive presses of that button...
self.response_numtouch[side] = 0
self.response_numkbd[side] += 1
self.marker(68 if side == 'l' else 69)
# double-pressing is disabled for now (too complicated...)
if self.response_dp_window[side] is not None:
if time.time < self.response_dp_window[side]:
# called within a valid double-press situation: score!
if keytype == 'target-touchscreen' and self.response_dp_was_hiexpense[side]:
self.marker(70)
# both key presses were hiexpense
self.response_dp_reward[side] += self.gain_hiexpense_plus
else:
self.marker(71)
# we add the cue gain
self.response_dp_reward[side] += self.gain_cued_plus
self.rewardlogic.score_event(self.response_dp_reward[side])
self.response_dp_window[side] = None
return
else:
self.marker(72)
# called too late: treat it as a normal key-press
self.response_dp_window[side] = None
if self.response_window[side] is None:
# pressed outside a valid response window: baseline loss
self.marker(73)
self.rewardlogic.score_event(self.loss_nontarget_press)
elif time.time() < self.response_window[side]:
# within a valid response window
if not self.response_wascued[side]:
# without a cue: normal response
if keytype == 'target-touchscreen':
if self.response_numtouch[side] > self.max_successive_touches:
self.marker(83)
self.response_reward[side] = self.loss_nontarget_press
self.sound(self.max_successive_sound,volume=0.2)
else:
self.marker(74)
self.response_reward[side] += self.gain_hiexpense_plus
else:
if self.response_numkbd[side] > self.max_successive_keypresses:
self.marker(84)
self.response_reward[side] = self.loss_nontarget_press
self.sound(self.max_successive_sound,volume=0.2)
else:
self.marker(75)
self.rewardlogic.score_event(self.response_reward[side])
else:
self.marker(76)
# with cue; requires special double-press logic
self.response_dp_window[side] = time.time() + self.response_dp_duration
self.response_dp_reward[side] = self.response_reward[side]
self.response_dp_was_hiexpense[side] = (keytype=='target-touchscreen')
taskMgr.doMethodLater(self.response_dp_window[side], self.doublepress_timeout, 'EventWatcher.doublepress_timeout()',extraArgs=[side])
# no response outstanding --> dimantle the timeout
self.response_outstanding[side] = False
# also close the response window
self.response_window[side] = None
def response_timeout(self,side):
"""This function is called when a timeout on an expected response expires."""
if not self.response_outstanding[side]:
# no response outstanding anymore
return
elif time.time() < self.response_window[side]:
# the timer was for a previous response window (which has been overridden since then)
return
else:
# timeout expired!
if self.response_reward[side] > 0:
self.marker(77 if side=='l' else 78)
self.rewardlogic.score_event(self.loss_target_miss)
self.response_window[side] = None
return
def doublepress_timeout(self,side):
"""This function is called when a timeout on the second press of a double-press situation expires."""
if self.response_dp_window[side] is None:
# the timeout was reset in the meantime
return
elif time.time() < self.response_dp_window[side]:
# the timer was for a previous response window (which has been overridden since then)
return
else:
# the double-press opportunity timed out; count the normal score
self.response_dp_window[side] = None
if self.response_dp_was_hiexpense[side]:
self.response_dp_reward[side] += self.gain_hiexpense_plus
self.marker(79 if side == 'l' else 80)
else:
self.marker(81 if side == 'l' else 82)
self.rewardlogic.score_event(self.response_dp_reward[side])
# === DAS Marker Table ===
#- 1: gain sound
#- 2: loss sound
#- 3: auditory warning on
#- 4: visual warning on
#- 5: warning off/expired
#- 6: hold left on
#- 7: hold right on
#- 8: hold off
#- 9: hold score drain tick (for left)
#- 10: hold score drain tick (for right)
#- 11: score drain tick (due to inappropriately held button)
#- 12: experiment launched
#- 13: experiment sequence generated
#- 14: media loaded
#- 15: tutorial started
#- 16: entering block loop
#- 17: a/v bout started
#- 18: rest bout started
#- 19: rest bout ended
#- 20: experiment ended
#- 21: entering words bout
#- 22: entering icons bout
#- 23: female on the left in subsequent bout
#- 24: male on the left in subsequent bout
#- 25: focus block for left visual spot
#- 26: focus block for right visual spot
#- 27: focus block for left auditory spot
#- 28: focus block for right auditory spot
#- 29: focus block for left visual and left auditory spot (dual condition)
#- 30: focus block for left visual and right auditory spot (dual condition)
#- 31: focus block for right visual and left auditory spot (dual condition)
#- 32: focus block for right visual and right auditory spot (dual condition)
#- 33: high-reward position in dual condition is left visual (low-reward is the other)
#- 34: high-reward position in dual condition is right visual (low-reward is the other)
#- 35: high-reward position in dual condition is left auditory (low-reward is the other)
#- 36: high-reward position in dual condition is right auditory (low-reward is the other)
#- 37: outstanding cue erased (due to focus switch to a constellation that does not include the
# cued position)
#- 38: preparing to present pull stimulus
#- 39: pull stimulus on left visual spot
#- 40: pull stimulus on right visual spot
#- 41: pull stimulus on left auditory spot
#- 42: pull stimulus on right auditory spot
#- 43: pull duration expired (note: does not necessarily mean that the stim material was
# finished by then)
#- 44: preparing to present cue stimulus
#- 45: cue stimulus on left visual spot
#- 46: cue stimulus on right visual spot
#- 47: cue stimulus on left auditory spot
#- 48: cue stimulus on right auditory spot
#- 49: cue duration expired (note: dies not necessarily mean that the stim material was finished by
# then)
#- 50: preparing to present target stimulus
#- 51: target stimulus on left visual spot
#- 52: target stimulus on right visual spot
#- 53: target stimulus on left auditory spot
#- 54: target stimulus on right auditory spot
#- 55: high reward if target hit (favored position)
#- 56: low reward if target hit (non-favored position in dual condition)
#- 57: no reward if target hit (but also no loss; one of the unattended positions)
#- 58: preparing to present non-target stimulus
#- 59: non-target stimulus on left visual spot
#- 60: non-target stimulus on right visual spot
#- 61: non-target stimulus on left auditory spot
#- 62: non-target stimulus on right auditory spot
#- 63: inter-stimulus interval expired
#- 64: a/v bout ended
#- 65: target missed because next target is already being displayed on this side
#- 66: left touch screen button pressed
#- 67: right touch screen button pressed
#- 68: left keyboard target button pressed
#- 69: right keyboard target button pressed
#- 70: second press in an expected double-press/cued situation; high-expense button used in
# both cases (= extra reward)
#- 71: second press in an expected double-press/cued situation; no extra reward due to high
# expense (at most one of the two button presses was high-expense)
#- 72: pressed too late in a cued situation (may also be inadvertently)
#- 73: pressed outside a valid target reaction window (--> non-target press)
#- 74: pressed keyboard target within a valid target reaction window, but no cue given
# (standard reward)
#- 75: pressed touchscreen target button within a valid target reaction window, but no cue given
# (high-expense reward)
#- 76: first press in a double-press situation; reward deferred until second press comes in or
# timeout expires (after ~250ms in current settings)
#- 77: target response timeout expired on left side (target miss penalty)
#- 78: target response timeout expired on right side (target miss penalty)
#- 79: timeout for second press in a cued situation expired on left side, first press was a touch
# press; giving deferred high-expense reward
#- 80: timeout for second press in a cued situation expired on right side, first press was a touch
# press; giving deferred high-expense reward
#- 81: timeout for second press in a cued situation expired on left side, first press was a
# keyboard press; giving deferred standard reward
#- 82: timeout for second press in a cued situation expired on right side, first press was a
# keyboard press; giving deferred standard reward
#- 83: touch press for too many successive times
#- 84: kbd press for too many successive times
#
#- 150 +/- 20 score update (offset = score delta)
#
#- 213: EventWatcher initialized
#- 214: EventWatcher watch_for() engaged
#- 215: EventWatcher watch_for() timeout reached, handler called
#- 216: EventWatcher watch_for() timeout reached, no handler called
#- 217: EventWatcher event registered in watch_for() window, event handler called
#- 218: EventWatcher event registered outside watch_for() window, defaulthandler in place
#- 219: EventWatcher event registered outside watch_for() window, no action
#- 220: output displayed on RandomPresenter
#- 221: output displayed on AudioPresenter
#- 222: output displayed on ImagePresenter
#- 223: output removed from ImagePresenter
#- 224: output displayed on ScrollPresenter
#- 225: output removed from ScrollPresenter
#- 226: output displayed on TextPresenter
#- 227: output removed from TextPresenter
#- 228: waiting for event to happen
#- 229: expected event registered (usually: keypress)
#- 230+k: k'th expected events registered (usually: keypress)
#- 244: timed movie displayed
#- 245: timed movie removed
#- 246: timed sound displayed
#- 247: timed sound removed
#- 248: timed picture displayed
#- 249: timed picture removed
#- 250: timed rectangle displayed
#- 251: timed rectangle removed
#- 252: timed crosshair displayed
#- 253: timed crosshair removed
#- 254: timed text displayed
#- 255: timed text removed
#
#- 10000+k k'th message selected on RandomPresenter
#- 20000+k k'th element randomly picked from message's pool in RandomPresenter
#- 30000+k: randseed
| {
"repo_name": "villawang/SNAP",
"path": "src/modules/DAS/DAS1b.py",
"copies": "2",
"size": "88486",
"license": "bsd-3-clause",
"hash": 7309144634149423000,
"line_mean": 63.8724340176,
"line_max": 481,
"alpha_frac": 0.5350224894,
"autogenerated": false,
"ratio": 4.2682938594375575,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.021166684506984546,
"num_lines": 1364
} |
from framework.core.base import BasePage
from framework.pages.mainPage import mainPage
class loginPage (BasePage):
url = "http://twiindan.pythonanywhere.com/admin"
def __init__(self, driver):
super().__init__(driver)
self.driver = driver
loginTextBox = None
passwordTextBox = None
logInButton = None
def locate_elements(self):
self.loginTextBox = self.driver.find_element_by_id("id_username")
self.passwordTextBox = self.driver.find_element_by_id("id_password")
self.logInButton = self.driver.find_element_by_xpath("//input[contains(@value, 'Log in')]")
def fillUsername(self, username=''):
self.loginTextBox.send_keys(username)
def fillPassword(self, password=''):
self.passwordTextBox.send_keys(password)
def submitClick(self):
self.logInButton.click()
return mainPage(self.driver)
def login(self, username='', password=''):
self.loginTextBox.send_keys(username)
self.passwordTextBox.send_keys(password)
self.logInButton.click()
return mainPage(self.driver)
def verifyURL(self):
return self.driver.current_url | {
"repo_name": "twiindan/selenium_lessons",
"path": "04_Selenium/framework/pages/loginPage.py",
"copies": "1",
"size": "1180",
"license": "apache-2.0",
"hash": 6016699044201735000,
"line_mean": 27.8048780488,
"line_max": 99,
"alpha_frac": 0.6677966102,
"autogenerated": false,
"ratio": 3.782051282051282,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9941063736740554,
"avg_score": 0.0017568311021456077,
"num_lines": 41
} |
from framework.core.base import BasePage
class addQuestionPage (BasePage):
questionTextBox = None
showMore = None
todayLink = None
nowLink = None
choiceText1 = None
choiceText2 = None
choiceText3 = None
choiceVotes1 = None
choiceVotes2 = None
choiceVotes3 = None
addChoice = None
saveButton = None
def __init__(self, driver):
super().__init__(driver)
self.driver = driver
def locate_elements(self):
self.questionTextBox = self.driver.find_element_by_id("id_question_text")
self.showMore = self.driver.find_element_by_id("fieldsetcollapser0")
self.todayLink = self.driver.find_element_by_link_text("Today")
self.nowLink = self.driver.find_element_by_link_text("Now")
self.choiceText1 = self.driver.find_element_by_name("choice_set-0-choice_text")
self.choiceText2 = self.driver.find_element_by_name("choice_set-1-choice_text")
self.choiceText3 = self.driver.find_element_by_name("choice_set-2-choice_text")
self.choiceVotes1 = self.driver.find_element_by_name("choice_set-0-votes")
self.choiceVotes2 = self.driver.find_element_by_name("choice_set-1-votes")
self.choiceVotes3 = self.driver.find_element_by_name("choice_set-2-votes")
self.addChoice = self.driver.find_element_by_link_text("Add another Choice")
self.saveButton = self.driver.find_element_by_name("_save")
def setQuestionText(self, question_text=''):
self.questionTextBox.send_keys(question_text)
def setNow(self):
self.showMore.click()
self.todayLink.click()
self.nowLink.click()
def setChoicesText(self, choiceTextvalue1='', choiceTextvalue2='', choiceTextvalue3=''):
self.choiceText1.send_keys(choiceTextvalue1)
self.choiceText2.send_keys(choiceTextvalue2)
self.choiceText3.send_keys(choiceTextvalue3)
def setChoiceVotes(self, choiceVotesValue1=0, choiceVotesValue2=0, choiceVotesValue3=0):
self.choiceVotes1.clear()
self.choiceVotes2.clear()
self.choiceVotes3.clear()
self.choiceVotes1.send_keys(choiceVotesValue1)
self.choiceVotes2.send_keys(choiceVotesValue2)
self.choiceVotes3.send_keys(choiceVotesValue3)
def savePoll(self):
self.saveButton.click()
#return mainPage(self.driver)
| {
"repo_name": "twiindan/selenium_lessons",
"path": "04_Selenium/framework/pages/addQuestionPage.py",
"copies": "1",
"size": "2375",
"license": "apache-2.0",
"hash": 2595344394806407700,
"line_mean": 33.9264705882,
"line_max": 92,
"alpha_frac": 0.6825263158,
"autogenerated": false,
"ratio": 3.392857142857143,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4575383458657143,
"avg_score": null,
"num_lines": null
} |
from framework.core.registry import plugin_registry
from framework.core.util import extract_artifact_id, listify_duplicate_keys
from framework.types import Artifact, Parameterized, Primitive
from framework.types.parameterized import List, ChooseMany
import framework.db as db
import datetime
class Executor(object):
def __init__(self, job):
self.job = job
def __call__(self):
method_uri = self.job.workflow.template # TODO currently the template is just the method
method = plugin_registry.get_plugin(method_uri).get_method(method_uri)
study = self.job.study.id
inputs = listify_duplicate_keys(self.job.inputs)
results = method(study, **inputs)
for i, (result, output) in enumerate(zip(results, method.outputs)):
ordered_result = traverse_result_and_record(result, output)
db.JobOutput(job=self.job, order=i, result=ordered_result).save()
self.job.status = 'completed'
self.job.completed = datetime.datetime.now()
self.job.save()
def traverse_result_and_record(result, type_, order=0, parent=None):
if issubclass(type_, Artifact):
ordered_result = db.OrderedResult(order=order,
parent=parent,
artifact=db.ArtifactProxy.get(db.ArtifactProxy.id == extract_artifact_id(result)))
ordered_result.save()
return ordered_result
if issubclass(type_, Primitive):
ordered_result = db.OrderedResult(order=order,
parent=parent,
primitive=result)
ordered_result.save()
return ordered_result
if type_.name == 'List' or type_.name == 'ChooseMany':
parent = db.OrderedResult(order=order, parent=parent)
parent.save()
for i, r in enumerate(result):
traverse_result_and_record(r, type_.subtype, order=i, parent=parent)
return parent
return traverse_result_and_record(result, type_.subtype, order=order, parent=parent)
| {
"repo_name": "biocore/metoo",
"path": "framework/core/executor.py",
"copies": "1",
"size": "2097",
"license": "bsd-3-clause",
"hash": -4344963456695372000,
"line_mean": 40.1176470588,
"line_max": 124,
"alpha_frac": 0.6313781593,
"autogenerated": false,
"ratio": 4.160714285714286,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.002124698256066891,
"num_lines": 51
} |
from framework.core.util import is_uri, get_feature_from_uri
from framework.types import type_registry, Artifact
from .method import Method
class Plugin(object):
def __init__(self, name, version, author, description):
self.uri = "/system/plugins/%s" % name
self.name = name
self.version = version
self.author = author
self.description = description
self._methods = {}
self._types = set()
def register_method(self, name):
def decorator(function):
fn_name = function.__name__
uri = "%s/methods/%s" % (self.uri, fn_name)
if self.has_method(fn_name):
raise Exception()
self._methods[fn_name] = Method(function, uri, name,
function.__doc__,
function.__annotations__)
return function
return decorator
def register_workflow(self, name):
pass
def register_type(self, cls):
uri = "%s/types/%s" % (self.uri, cls.__name__)
self._types.add(cls)
return type_registry.artifact(uri, cls)
def has_method(self, name):
if is_uri(name, 'methods'):
name = get_feature_from_uri(name, 'methods')
return name in self._methods
def get_method(self, name):
if is_uri(name, 'methods'):
name = get_feature_from_uri(name, 'methods')
if self.has_method(name):
return self._methods[name]
else:
raise Exception()
def get_methods(self):
return self._methods.copy()
def get_types(self):
return list(self._types)
| {
"repo_name": "biocore/metoo",
"path": "framework/core/plugin.py",
"copies": "1",
"size": "1692",
"license": "bsd-3-clause",
"hash": -7046662587699053000,
"line_mean": 30.3333333333,
"line_max": 69,
"alpha_frac": 0.548463357,
"autogenerated": false,
"ratio": 4.167487684729064,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0008417508417508418,
"num_lines": 54
} |
from framework.core.util import is_uri, get_feature_from_uri
class _PluginRegistry(object):
def __init__(self):
self._plugins = {}
def add(self, plugin):
self._plugins[plugin.name] = plugin
def get_plugin_uris(self):
for plugin in self._plugins.values():
yield plugin.uri
def get_plugin(self, name):
if is_uri(name, 'plugins'):
name = get_feature_from_uri(name, 'plugins')
return self._plugins[name]
def get_methods(self, plugin_name=None):
if plugin_name is None:
plugin_names = self._plugins.keys()
else:
plugin_names = [plugin_name]
for name in plugin_names:
for method in self.get_plugin(name).get_methods().values():
yield method
def get_types(self, plugin_name=None):
if plugin_name is None:
plugin_names = self._plugins.keys()
else:
plugin_names = [plugin_name]
for name in plugin_names:
for type_ in self.get_plugin(name).get_types():
yield type_
plugin_registry = _PluginRegistry()
| {
"repo_name": "biocore/metoo",
"path": "framework/core/registry.py",
"copies": "1",
"size": "1138",
"license": "bsd-3-clause",
"hash": 92924277164316770,
"line_mean": 29.7567567568,
"line_max": 71,
"alpha_frac": 0.5764499121,
"autogenerated": false,
"ratio": 3.924137931034483,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5000587843134483,
"avg_score": null,
"num_lines": null
} |
from framework.db import models
from framework.dependency_management.dependency_resolver import BaseComponent, ServiceLocator
from framework.lib import exceptions
def session_required(func):
"""
Inorder to use this decorator on a `method` there is one requirements
+ target_id must be a kwarg of the function
All this decorator does is check if a valid value is passed for target_id
if not get the target_id from target manager and pass it
"""
def wrapped_function(*args, **kwargs):
# True if target_id doesnt exist
if (kwargs.get("session_id", "None") == "None") or (kwargs.get("session_id", True) is None):
kwargs["session_id"] = ServiceLocator.get_component("session_db").get_session_id()
return func(*args, **kwargs)
return wrapped_function
class OWTFSessionDB(BaseComponent):
COMPONENT_NAME = "session_db"
def __init__(self):
self.register_in_service_locator()
self.db = self.get_component("db")
self.config = self.get_component("config")
self._ensure_default_session()
def _ensure_default_session(self):
"""
If there are no sessions, it will be deadly, so if
number of sessions is zero then add a default session
"""
if self.db.session.query(models.Session).count() == 0:
self.add_session("default session")
def set_session(self, session_id):
query = self.db.session.query(models.Session)
session_obj = query.get(session_id)
if session_obj is None:
raise exceptions.InvalidSessionReference("No session with session_id: %s" % str(session_id))
query.update({'active': False})
session_obj.active = True
self.db.session.commit()
def get_session_id(self):
session_id = self.db.session.query(models.Session.id).filter_by(active=True).first()
return session_id
def add_session(self, session_name):
existing_obj = self.db.session.query(models.Session).filter_by(name=session_name).first()
if existing_obj is None:
session_obj = models.Session(name=session_name[:50])
self.db.session.add(session_obj)
self.db.session.commit()
self.set_session(session_obj.id)
else:
raise exceptions.DBIntegrityException("Session already exists with session name: %s" % session_name)
@session_required
def add_target_to_session(self, target_id, session_id=None):
session_obj = self.db.session.query(models.Session).get(session_id)
target_obj = self.db.session.query(models.Target).get(target_id)
if session_obj is None:
raise exceptions.InvalidSessionReference("No session with id: %s" % str(session_id))
if target_obj is None:
raise exceptions.InvalidTargetReference("No target with id: %s" % str(target_id))
if session_obj not in target_obj.sessions:
session_obj.targets.append(target_obj)
self.db.session.commit()
@session_required
def remove_target_from_session(self, target_id, session_id=None):
session_obj = self.db.session.query(models.Session).get(session_id)
target_obj = self.db.session.query(models.Target).get(target_id)
if session_obj is None:
raise exceptions.InvalidSessionReference("No session with id: %s" % str(session_id))
if target_obj is None:
raise exceptions.InvalidTargetReference("No target with id: %s" % str(target_id))
session_obj.targets.remove(target_obj)
# Delete target whole together if present in this session alone
if len(target_obj.sessions) == 0:
self.db.Target.DeleteTarget(ID=target_obj.id)
self.db.session.commit()
def delete_session(self, session_id):
session_obj = self.db.session.query(models.Session).get(session_id)
if session_obj is None:
raise exceptions.InvalidSessionReference("No session with id: %s" % str(session_id))
for target in session_obj.targets:
# Means attached to only this session obj
if len(target.sessions) == 1:
self.db.Target.DeleteTarget(ID=target.id)
self.db.session.delete(session_obj)
self._ensure_default_session() # i.e if there are no sessions, add one
self.db.session.commit()
def derive_session_dict(self, session_obj):
sdict = dict(session_obj.__dict__)
sdict.pop("_sa_instance_state")
return sdict
def derive_session_dicts(self, session_objs):
results = []
for session_obj in session_objs:
if session_obj:
results.append(self.derive_session_dict(session_obj))
return results
def generate_query(self, filter_data=None):
if filter_data is None:
filter_data = {}
query = self.db.session.query(models.Session)
# it doesn't make sense to search in a boolean column :P
if filter_data.get('active', None):
if isinstance(filter_data.get('active'), list):
filter_data['active'] = filter_data['active'][0]
query = query.filter_by(active=self.config.ConvertStrToBool(filter_data['active']))
return query.order_by(models.Session.id)
def get_all(self, filter_data):
session_objs = self.generate_query(filter_data).all()
return self.derive_session_dicts(session_objs)
def get(self, session_id):
session_obj = self.db.session.query(models.Session).get(session_id)
if session_obj is None:
raise exceptions.InvalidSessionReference("No session with id: %s" % str(session_id))
return self.derive_session_dict(session_obj)
| {
"repo_name": "DarKnight--/owtf",
"path": "framework/db/session_manager.py",
"copies": "2",
"size": "5764",
"license": "bsd-3-clause",
"hash": -333923162487421760,
"line_mean": 42.6666666667,
"line_max": 112,
"alpha_frac": 0.6455586398,
"autogenerated": false,
"ratio": 3.8426666666666667,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5488225306466666,
"avg_score": null,
"num_lines": null
} |
from framework.dependency_management.dependency_resolver import BaseComponent
from framework.dependency_management.interfaces import DBConfigInterface
from framework.lib.exceptions import InvalidConfigurationReference
from framework.db import models
from framework.lib.general import cprint
import ConfigParser
import logging
class ConfigDB(BaseComponent, DBConfigInterface):
COMPONENT_NAME = "db_config"
def __init__(self):
self.register_in_service_locator()
self.config = self.get_component("config")
self.db = self.get_component("db")
self.LoadConfigDBFromFile(self.config.get_profile_path('GENERAL_PROFILE'))
def IsConvertable(self, value, conv):
try:
return(conv(value))
except ValueError:
return None
def LoadConfigDBFromFile(self, file_path):
# TODO: Implementy user override mechanism
logging.info("Loading Configuration from: " + file_path + " ..")
config_parser = ConfigParser.RawConfigParser()
config_parser.optionxform = str # Otherwise all the keys are converted to lowercase xD
config_parser.read(file_path)
for section in config_parser.sections():
for key, value in config_parser.items(section):
old_config_obj = self.db.session.query(models.ConfigSetting).get(key)
if not old_config_obj or not old_config_obj.dirty:
if not key.endswith("_DESCRIP"): # _DESCRIP are help values
config_obj = models.ConfigSetting(key=key, value=value, section=section)
# If _DESCRIP at the end, then use it as help text
if config_parser.has_option(section, key + "_DESCRIP"):
config_obj.descrip = config_parser.get(section, key + "_DESCRIP")
self.db.session.merge(config_obj)
self.db.session.commit()
def Get(self, Key):
obj = self.db.session.query(models.ConfigSetting).get(Key)
if obj:
return(self.config.MultipleReplace(obj.value, self.config.GetReplacementDict()))
else:
return(None)
def DeriveConfigDict(self, config_obj):
if config_obj:
config_dict = dict(config_obj.__dict__)
config_dict.pop("_sa_instance_state")
return config_dict
else:
return config_obj
def DeriveConfigDicts(self, config_obj_list):
config_dict_list = []
for config_obj in config_obj_list:
if config_obj:
config_dict_list.append(self.DeriveConfigDict(config_obj))
return config_dict_list
def GenerateQueryUsingSession(self, criteria):
query = self.db.session.query(models.ConfigSetting)
if criteria.get("key", None):
if isinstance(criteria["key"], (str, unicode)):
query = query.filter_by(key=criteria["key"])
if isinstance(criteria["key"], list):
query = query.filter(models.ConfigSetting.key.in_(criteria["key"]))
if criteria.get("section", None):
if isinstance(criteria["section"], (str, unicode)):
query = query.filter_by(section=criteria["section"])
if isinstance(criteria["section"], list):
query = query.filter(models.ConfigSetting.section.in_(criteria["section"]))
if criteria.get('dirty', None):
if isinstance(criteria.get('dirty'), list):
criteria['dirty'] = criteria['dirty'][0]
query = query.filter_by(dirty=self.config.ConvertStrToBool(criteria['dirty']))
return query.order_by(models.ConfigSetting.key)
def GetAll(self, criteria=None):
if not criteria:
criteria = {}
query = self.GenerateQueryUsingSession(criteria)
return self.DeriveConfigDicts(query.all())
def GetAllTools(self):
results = self.db.session.query(models.ConfigSetting).filter(
models.ConfigSetting.key.like("%TOOL_%")).all()
config_dicts = self.DeriveConfigDicts(results)
for config_dict in config_dicts:
config_dict["value"] = self.config.MultipleReplace(
config_dict["value"], self.config.GetReplacementDict())
return(config_dicts)
def GetSections(self):
sections = self.db.session.query(models.ConfigSetting.section).distinct().all()
sections = [i[0] for i in sections]
return sections
def Update(self, key, value):
config_obj = self.db.session.query(models.ConfigSetting).get(key)
if config_obj:
config_obj.value = value
config_obj.dirty = True
self.db.session.merge(config_obj)
self.db.session.commit()
else:
raise InvalidConfigurationReference("No setting exists with key: " + str(key))
def GetReplacementDict(self):
config_dict = {}
config_list = self.db.session.query(models.ConfigSetting.key, models.ConfigSetting.value).all()
for key, value in config_list: # Need a dict
config_dict[key] = value
return config_dict
def GetTcpPorts(self, startport, endport):
return ','.join(self.Get("TCP_PORTS").split(',')[int(startport):int(endport)])
def GetUdpPorts(self, startport, endport):
return ','.join(self.Get("UDP_PORTS").split(',')[int(startport):int(endport)])
| {
"repo_name": "mikefitz888/owtf",
"path": "framework/db/config_manager.py",
"copies": "3",
"size": "5451",
"license": "bsd-3-clause",
"hash": 6014835916611583000,
"line_mean": 42.608,
"line_max": 103,
"alpha_frac": 0.6255732893,
"autogenerated": false,
"ratio": 4.132676269901441,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.001334868685184499,
"num_lines": 125
} |
from framework.dependency_management.dependency_resolver import ServiceLocator
from framework.http.wafbypasser import wafbypasser
def format_args(args):
formatted_args = {
"target": None,
"payloads": None,
"headers": None,
"methods": None,
"data": None,
"contains": None,
"resp_code_det": None,
"reverse": None,
"fuzzing_signature": None,
"accepted_value": None,
"param_name": None,
"param_source": None,
"delay": None,
"follow_cookies": None,
"cookie": None,
"length": None,
"response_time": None,
"mode": None
}
for param, value in dict(args).iteritems():
formatted_args[param.lower()] = value
return formatted_args
DESCRIPTION = "WAF byppaser module plugin"
def run(PluginInfo):
Content = DESCRIPTION + " Results:<br />"
plugin_params = ServiceLocator.get_component("plugin_params")
args = {
'Description': DESCRIPTION,
'Mandatory': {'TARGET': None, 'MODE': None},
'Optional': {
'METHODS': None,
'COOKIE': None,
'HEADERS': None,
'LENGTH': None,
'DATA': None,
'CONTAINS': None,
'RESP_CODE_DET': None,
'RESPONSE_TIME': None,
'REVERSE': None,
'PAYLOADS': None,
'ACCEPTED_VALUE': None,
'PARAM_NAME': None,
'PARAM_SOURCE': None,
'DELAY': None,
'FOLLOW-COOKIES': None,
}
}
for Args in plugin_params.GetArgs(args, PluginInfo):
ret = plugin_params.SetConfig(Args) # Only now, after modifying ATTACHMENT_NAME, update config
wafbps = wafbypasser.WAFBypasser(Core)
wafbps.start(format_args(Args))
return Content
| {
"repo_name": "DarKnight24/owtf",
"path": "plugins/auxiliary/wafbypasser/WAF_Byppaser@OWTF-AWAF-001.py",
"copies": "2",
"size": "1839",
"license": "bsd-3-clause",
"hash": 3663709134520977400,
"line_mean": 28.6612903226,
"line_max": 103,
"alpha_frac": 0.5502990756,
"autogenerated": false,
"ratio": 3.8961864406779663,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5446485516277967,
"avg_score": null,
"num_lines": null
} |
from framework.dependency_management.dependency_resolver import ServiceLocator
from framework.http.wafbypasser import wafbypasser
def format_args(args):
formatted_args = {"target": None,
"payloads": None,
"headers": None,
"methods": None,
"data": None,
"contains": None,
"resp_code_det": None,
"reverse": None,
"fuzzing_signature": None,
"accepted_value": None,
"param_name": None,
"param_source": None,
"delay": None,
"follow_cookies": None,
"cookie": None,
"length": None,
"response_time": None,
"mode": None}
for param, value in dict(args).iteritems():
formatted_args[param.lower()] = value
return formatted_args
DESCRIPTION = "WAF byppaser module plugin"
def run(PluginInfo):
# ServiceLocator.get_component("config").Show()
Content = DESCRIPTION + " Results:<br />"
plugin_params = ServiceLocator.get_component("plugin_params")
for Args in plugin_params.GetArgs({
'Description': DESCRIPTION,
'Mandatory': {
'TARGET': None,
'MODE': None,
},
'Optional': {
'METHODS': None,
'COOKIE': None,
'HEADERS': None,
'LENGTH': None,
'DATA': None,
'CONTAINS': None,
'RESP_CODE_DET': None,
'RESPONSE_TIME': None,
'REVERSE': None,
'PAYLOADS': None,
'ACCEPTED_VALUE': None,
'PARAM_NAME': None,
'PARAM_SOURCE': None,
'DELAY': None,
'FOLLOW-COOKIES': None,
}}, PluginInfo):
ret = plugin_params.SetConfig(
Args) # Only now, after modifying ATTACHMENT_NAME, update config
wafbps = wafbypasser.WAFBypasser(Core)
wafbps.start(format_args(Args))
return Content
| {
"repo_name": "DePierre/owtf",
"path": "plugins/auxiliary/wafbypasser/WAF_Byppaser@OWTF-AWAF-001.py",
"copies": "3",
"size": "2904",
"license": "bsd-3-clause",
"hash": -8642651651912047000,
"line_mean": 43.6769230769,
"line_max": 78,
"alpha_frac": 0.3581267218,
"autogenerated": false,
"ratio": 6.024896265560166,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.7883022987360165,
"avg_score": null,
"num_lines": null
} |
from framework.dependency_management.dependency_resolver import ServiceLocator
DESCRIPTION = "Denial of Service (DoS) Launcher -i.e. for IDS/DoS testing-"
CATEGORIES = ['HTTP_WIN', 'HTTP', 'DHCP', 'NTFS', 'HP', 'MDNS', 'PPTP', 'SAMBA', 'SCADA', 'SMTP', 'SOLARIS', 'SSL',
'SYSLOG', 'TCP', 'WIFI', 'WIN_APPIAN', 'WIN_BROWSER', 'WIN_FTP', 'KAILLERA', 'WIN_LLMNR', 'WIN_NAT',
'WIN_SMB', 'WIN_SMTP', 'WIN_TFTP', 'WIRESHARK']
def run( PluginInfo):
# ServiceLocator.get_component("config").Show()
Content = DESCRIPTION + " Results:<br />"
plugin_params = ServiceLocator.get_component("plugin_params")
config = ServiceLocator.get_component("config")
for Args in plugin_params.GetArgs({
'Description': DESCRIPTION,
'Mandatory': {
'RHOST': config.Get('RHOST_DESCRIP'),
'RPORT': config.Get('RPORT_DESCRIP'),
},
'Optional': {
'CATEGORY': 'Category to use (i.e. ' + ', '.join(
sorted(CATEGORIES)) + ')',
'REPEAT_DELIM': config.Get('REPEAT_DELIM_DESCRIP')
}}, PluginInfo):
plugin_params.SetConfig(Args)
#print "Args="+str(Args)
Content += ServiceLocator.get_component("plugin_helper").DrawCommandDump('Test Command', 'Output',
config.GetResources(
'DoS_' + Args['CATEGORY']),
PluginInfo, "") # No previous output
return Content
| {
"repo_name": "sharad1126/owtf",
"path": "plugins/auxillary/dos/Direct_DoS_Launcher@OWTF-ADoS-001.py",
"copies": "3",
"size": "2290",
"license": "bsd-3-clause",
"hash": 5653375732610430000,
"line_mean": 70.5625,
"line_max": 124,
"alpha_frac": 0.3689956332,
"autogenerated": false,
"ratio": 5.350467289719626,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.7219462922919626,
"avg_score": null,
"num_lines": null
} |
from framework.dependency_management.dependency_resolver import ServiceLocator
DESCRIPTION = "Mounts and/or uploads/downloads files to an SMB share -i.e. for IDS testing-"
def run(PluginInfo):
# ServiceLocator.get_component("config").Show()
Content = DESCRIPTION + " Results:<br />"
Iteration = 1 # Iteration counter initialisation
plugin_params = ServiceLocator.get_component("plugin_params")
config = ServiceLocator.get_component("config")
smb = ServiceLocator.get_component("smb")
for Args in plugin_params.GetArgs({
'Description': DESCRIPTION,
'Mandatory': {
'SMB_HOST': config.Get('SMB_HOST_DESCRIP'),
'SMB_SHARE': config.Get(
'SMB_SHARE_DESCRIP'),
'SMB_MOUNT_POINT': config.Get(
'SMB_MOUNT_POINT_DESCRIP'),
},
'Optional': {
'SMB_USER': config.Get('SMB_USER_DESCRIP'),
'SMB_PASS': config.Get('SMB_PASS_DESCRIP'),
'SMB_DOWNLOAD': config.Get(
'SMB_DOWNLOAD_DESCRIP'),
'SMB_UPLOAD': config.Get(
'SMB_UPLOAD_DESCRIP'),
'REPEAT_DELIM': config.Get(
'REPEAT_DELIM_DESCRIP')
}}, PluginInfo):
plugin_params.SetConfig(Args) # Sets the auxillary plugin arguments as config
smb.Mount(Args, PluginInfo)
smb.Transfer()
if not smb.IsClosed(): # Ensure clean exit if reusing connection
smb.UnMount(PluginInfo)
return Content
| {
"repo_name": "sharad1126/owtf",
"path": "plugins/auxillary/smb/SMB_Handler@OWTF-SMB-001.py",
"copies": "1",
"size": "2712",
"license": "bsd-3-clause",
"hash": -8388434903757482000,
"line_mean": 72.2972972973,
"line_max": 121,
"alpha_frac": 0.3359144543,
"autogenerated": false,
"ratio": 6.614634146341463,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.7450548600641463,
"avg_score": null,
"num_lines": null
} |
from framework.dependency_management.dependency_resolver import ServiceLocator
"""
ACTIVE Plugin for Testing for HTTP Methods and XST (OWASP-CM-008)
"""
from framework.lib.general import get_random_str
DESCRIPTION = "Active probing for HTTP methods"
def run(PluginInfo):
# Transaction = Core.Requester.TRACE(Core.Config.Get('host_name'), '/')
target = ServiceLocator.get_component("target")
URL = target.Get('top_url')
# TODO: PUT not working right yet
# PUT_URL = URL+"/_"+get_random_str(20)+".txt"
# print PUT_URL
# PUT_URL = URL+"/a.txt"
# PUT_URL = URL
plugin_helper = ServiceLocator.get_component("plugin_helper")
Content = plugin_helper.TransactionTableForURL(
True,
URL,
Method='TRACE')
# Content += Core.PluginHelper.TransactionTableForURL(
# True,
# PUT_URL,
# Method='PUT',
# Data=get_random_str(15))
resource = ServiceLocator.get_component("resource")
Content += plugin_helper.CommandDump(
'Test Command',
'Output',
resource.GetResources('ActiveHTTPMethods'),
PluginInfo,
Content)
return Content
| {
"repo_name": "sharad1126/owtf",
"path": "plugins/web/active/HTTP_Methods_and_XST@OWTF-CM-008.py",
"copies": "3",
"size": "1161",
"license": "bsd-3-clause",
"hash": 8750866835066365000,
"line_mean": 28.7692307692,
"line_max": 78,
"alpha_frac": 0.6503014643,
"autogenerated": false,
"ratio": 3.7572815533980584,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5907583017698059,
"avg_score": null,
"num_lines": null
} |
from framework.dependency_management.dependency_resolver import ServiceLocator
DESCRIPTION = "Mounts and/or uploads/downloads files to an SMB share -i.e. for IDS testing-"
def run(PluginInfo):
Content = []
plugin_params = ServiceLocator.get_component("plugin_params")
config = ServiceLocator.get_component("config")
smb = ServiceLocator.get_component("smb")
args = {
'Description': DESCRIPTION,
'Mandatory': {
'SMB_HOST': config.FrameworkConfigGet('SMB_HOST_DESCRIP'),
'SMB_SHARE': config.FrameworkConfigGet('SMB_SHARE_DESCRIP'),
'SMB_MOUNT_POINT': config.FrameworkConfigGet('SMB_MOUNT_POINT_DESCRIP'),
},
'Optional': {
'SMB_USER': config.FrameworkConfigGet('SMB_USER_DESCRIP'),
'SMB_PASS': config.FrameworkConfigGet('SMB_PASS_DESCRIP'),
'SMB_DOWNLOAD': config.FrameworkConfigGet('SMB_DOWNLOAD_DESCRIP'),
'SMB_UPLOAD': config.FrameworkConfigGet('SMB_UPLOAD_DESCRIP'),
'REPEAT_DELIM': config.FrameworkConfigGet('REPEAT_DELIM_DESCRIP')
}
}
for Args in plugin_params.GetArgs(args, PluginInfo):
plugin_params.SetConfig(Args) # Sets the auxiliary plugin arguments as config
smb.Mount(Args, PluginInfo)
smb.Transfer()
if not smb.IsClosed(): # Ensure clean exit if reusing connection
smb.UnMount(PluginInfo)
return Content
| {
"repo_name": "DarKnight--/owtf",
"path": "plugins/auxiliary/smb/SMB_Handler@OWTF-SMB-001.py",
"copies": "2",
"size": "1428",
"license": "bsd-3-clause",
"hash": 271691169827635200,
"line_mean": 39.8,
"line_max": 92,
"alpha_frac": 0.6603641457,
"autogenerated": false,
"ratio": 3.8594594594594596,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0009717613407988335,
"num_lines": 35
} |
from framework.dependency_management.dependency_resolver import ServiceLocator
"""
PASSIVE Plugin for Search engine discovery/reconnaissance (OWASP-IG-002)
"""
DESCRIPTION = "General Google Hacking/Email harvesting, etc"
ATTR = {
'INTERNET_RESOURCES': True,
}
def run(PluginInfo):
# ServiceLocator.get_component("config").Show()
plugin_helper = ServiceLocator.get_component("plugin_helper")
Content = plugin_helper.CommandDump('Test Command', 'Output',
ServiceLocator.get_component(
"resource").GetResources(
'PassiveSearchEngineDiscoveryCmd'),
PluginInfo, [])
Content += plugin_helper.ResourceLinkList('Online Resources',
ServiceLocator.get_component(
"resource").GetResources(
'PassiveSearchEngineDiscoveryLnk'))
return Content
| {
"repo_name": "sharad1126/owtf",
"path": "plugins/web/passive/Search_engine_discovery_reconnaissance@OWTF-IG-002.py",
"copies": "3",
"size": "1296",
"license": "bsd-3-clause",
"hash": 8045047380637889000,
"line_mean": 50.84,
"line_max": 117,
"alpha_frac": 0.4490740741,
"autogenerated": false,
"ratio": 6.230769230769231,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0038927985164276292,
"num_lines": 25
} |
from framework.dependency_management.dependency_resolver import ServiceLocator
"""
PASSIVE Plugin for Testing for Web Application Fingerprint (OWASP-IG-004)
"""
DESCRIPTION = "Third party resources and fingerprinting suggestions"
def run(PluginInfo):
# ServiceLocator.get_component("config").Show()
#Vuln search box to be built in core and reused in different plugins:
plugin_helper = ServiceLocator.get_component("plugin_helper")
Content = plugin_helper.VulnerabilitySearchBox('')
Content += plugin_helper.ResourceLinkList('Online Resources', ServiceLocator.get_component("resource").GetResources('PassiveFingerPrint'))
Content += plugin_helper.SuggestedCommandBox(PluginInfo,
[['All', 'CMS_FingerPrint_All'],
['WordPress',
'CMS_FingerPrint_WordPress'],
['Joomla', 'CMS_FingerPrint_Joomla'],
['Drupal', 'CMS_FingerPrint_Drupal'],
['Mambo', 'CMS_FingerPrint_Mambo']],
'CMS Fingerprint - Potentially useful commands')
return Content
| {
"repo_name": "DePierre/owtf",
"path": "plugins/web/passive/Web_Application_Fingerprint@OWTF-IG-004.py",
"copies": "3",
"size": "1538",
"license": "bsd-3-clause",
"hash": 6542560337844838000,
"line_mean": 60.52,
"line_max": 142,
"alpha_frac": 0.4746423927,
"autogenerated": false,
"ratio": 5.80377358490566,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.043910849909610146,
"num_lines": 25
} |
from framework.dependency_management.dependency_resolver import ServiceLocator
"""
SEMI-PASSIVE Plugin for Testing for Session Management Schema (OWASP-SM-001)
https://www.owasp.org/index.php/Testing_for_Session_Management_Schema_%28OWASP-SM-001%29
"""
import string, re
import cgi, logging
from framework.lib import general
DESCRIPTION = "Normal requests to gather session managament info"
def run(PluginInfo):
# ServiceLocator.get_component("config").Show()
# True = Use Transaction Cache if possible: Visit the start URLs if not already visited
# Step 1 - Find transactions that set cookies
# Step 2 - Request 10 times per URL that sets cookies
# Step 3 - Compare values and calculate randomness
URLList = []
TransactionList = []
Result = ""
return ([])
# TODO: Try to keep up Abe's promise ;)
#return "Some refactoring required, maybe for BSides Vienna 2012 but no promises :)"
transaction = ServiceLocator.get_component("transaction")
for ID in transaction.GrepTransactionIDsForHeaders(
[ServiceLocator.get_component("config").Get('HEADERS_FOR_COOKIES')]): # Transactions with cookies
URL = transaction.GetByID(ID).URL # Limitation: Not Checking POST, normally not a problem ..
if URL not in URLList: # Only if URL not already processed!
URLList.append(URL) # Keep track of processed URLs
AllCookieValues = {}
for i in range(0, 2): # Get more cookies to perform analysis
Transaction = ServiceLocator.get_component("requester").GetTransaction(False, URL)
return Result
| {
"repo_name": "mikefitz888/owtf",
"path": "plugins/web/semi_passive/Session_Management_Schema@OWTF-SM-001.py",
"copies": "3",
"size": "1619",
"license": "bsd-3-clause",
"hash": -3455922087224502300,
"line_mean": 43.9722222222,
"line_max": 110,
"alpha_frac": 0.7059913527,
"autogenerated": false,
"ratio": 4.119592875318066,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.6325584228018066,
"avg_score": null,
"num_lines": null
} |
from framework.dependency_management.dependency_resolver import ServiceLocator
"""
PASSIVE Plugin for Testing for Application Discovery (OWASP-IG-005)
"""
DESCRIPTION = "Third party discovery resources"
def run(PluginInfo):
# ServiceLocator.get_component("config").Show()
# Content = ServiceLocator.get_component("plugin_helper").DrawCommandDump('Test Command', 'Output', ServiceLocator.get_component("config").GetResources('PassiveApplicationDiscoveryCmd'), PluginInfo)
# Content = ServiceLocator.get_component("plugin_helper").DrawResourceLinkList('Online Resources', ServiceLocator.get_component("config").GetResources('PassiveAppDiscovery'))
resource = ServiceLocator.get_component("resource")
Content = ServiceLocator.get_component("plugin_helper").TabbedResourceLinkList([
['DNS', resource.GetResources('PassiveAppDiscoveryDNS')],
['WHOIS', resource.GetResources('PassiveAppDiscoveryWHOIS')],
['DB Lookups', resource.GetResources('PassiveAppDiscoveryDbLookup')],
['Ping', resource.GetResources('PassiveAppDiscoveryPing')],
['Traceroute', resource.GetResources('PassiveAppDiscoveryTraceroute')],
['Misc', resource.GetResources('PassiveAppDiscoveryMisc')]
])
return Content
| {
"repo_name": "DePierre/owtf",
"path": "plugins/web/passive/Application_Discovery@OWTF-IG-005.py",
"copies": "3",
"size": "1675",
"license": "bsd-3-clause",
"hash": -9131970348629850000,
"line_mean": 78.7619047619,
"line_max": 206,
"alpha_frac": 0.5653731343,
"autogenerated": false,
"ratio": 5.5647840531561465,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.007672050672282211,
"num_lines": 21
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.