content
stringlengths 5
1.05M
|
---|
# -*- coding: utf-8 -*-
# legume. Copyright 2009-2013 Dale Reidy. All rights reserved.
# See LICENSE for details.
__docformat__ = 'restructuredtext'
'''
A message class is a subclass of legume.messages.BaseMessage with two
class attributes defined:
* MessageTypeID - An integer uniquely identifying the message type. The
allowed range for application messages is 1 to BASE_MESSAGETYPEID_SYSTEM-1.
* MessageValues - A dictionary of the values stored within the message where
the key is the name of the message value, and the value is the type.
Type names available for MessageValues:
* 'int' - An integer
* 'string n' - A string where n is the maximum string length, eg 'string 18'
* 'float' - A double precision floating point.
* 'bool' - A boolean (a 1 byte short)
An example message definition::
class ChatMessage(legume.messages.BaseMessage):
MessageTypeID = 1
MessageValues = {
'sender_name':'string 24',
'message':'string 256',
'channel':'string 24'
}
# Adding a message to a new message_factory
message_factory = legume.messages.MessageFactory()
message_factory.add(ChatMessage)
# and/or add it to the global message factory
legume.messages.message_factory.add(ChatMessage)
How to use this message definition::
# Note how this client uses the packet_factory the
# ChatMessage message was added to.
client = legume.Client(packet_factory)
# ..snip..
# Create the message
cm = ChatMessage()
cm.sender_name.value = 'JoeUser'
cm.message.value = 'This is a test message.'
cm.channel.value = 'newbies'
# send the message to the server
client.send_message(cm)
'''
import struct
import logging
import string
from legume.netshared import MessageError, PROTOCOL_VERSION
BASE_MESSAGETYPEID_SYSTEM = 1
BASE_MESSAGETYPEID_USER = 20
def isValidIdentifier(identifier):
return not (' ' in identifier or identifier[0] not in string.ascii_letters)
class MessageValue(object):
VALID_TYPE_NAMES = ['int', 'string', 'float', 'bool',
'uchar', 'char', 'short', 'varstring']
def __init__(self, name, typename, value=None, max_length=None, message=None):
'''
Create a new packet type.
The name parameter must be a valid python class attribute identifier.
Typename can be one of 'int', 'string', 'float' or 'bool'.
Value must be of the specified type.
max_length is only required for string values.
'''
if not isValidIdentifier(name):
raise MessageError('%s is not a valid name' % name)
self.name = name
self.typename = typename
self._value = value
self.max_length = max_length # only required for string
if self.max_length is not None:
self.max_length = int(self.max_length)
if self.typename == 'string' and self.max_length is None:
raise MessageError('String value requires a max_length attribute')
elif self.max_length is not None and self.max_length < 1:
raise MessageError('Max length must be None or > 0')
elif self.typename not in self.VALID_TYPE_NAMES:
raise MessageError('%s is not a valid type name' % self.typename)
elif self.name == '':
raise MessageError('A value name is required')
if message is not None and message.UseDefaultValues:
self.set_default_value()
def set_default_value(self):
if self.typename == 'int':
self._value = 0
elif self.typename == 'short':
self._value = 0
elif self.typename == 'string':
self._value = ""
elif self.typename == 'varstring':
self._value = ""
elif self.typename == 'float':
self._value = 0.0
elif self.typename == 'bool':
self._value = False
elif self.typename == 'uchar':
self._value = ""
else:
raise MessageError('Cant set default value for type "%s"' %
self.typename)
def get_message_values(self):
if self.typename == 'varstring':
return [len(self.value), self._value]
else:
return [self._value]
def get_value(self):
return self._value
def set_value(self, value):
if self.typename == 'string':
if len(value) > self.max_length:
raise MessageError('String value is too long.')
self._value = value.replace('\0', '')
else:
self._value = value
value = property(get_value, set_value)
def get_format_string(self):
'''
Returns the string necessary for encoding this value using struct.
'''
if self.typename == 'int':
return 'i'
elif self.typename == 'short':
return 'H'
elif self.typename == 'string':
return str(self.max_length)+'s'
elif self.typename == 'float':
return 'd'
elif self.typename == 'bool':
return 'b'
elif self.typename == 'varstring':
return 'H'+str(len(self._value))+'s'
elif self.typename == 'uchar':
return 'B'
else:
raise MessageError('Cant get format string for type "%s"' %
self.typename)
def read_from_byte_buffer(self, byteBuffer):
if self.typename == 'int':
self._value = byteBuffer.read_struct('i')[0]
elif self.typename == 'short':
self._value = byteBuffer.read_struct('H')[0]
elif self.typename == 'string':
self._value = byteBuffer.read_struct(str(self.max_length)+'s')[0]
self._value = self._value.replace(b'\0', b'').decode('utf-8')
elif self.typename == 'float':
self._value = byteBuffer.read_struct('d')[0]
elif self.typename == 'bool':
self._value = byteBuffer.read_struct('b')[0]
elif self.typename == 'varstring':
length = byteBuffer.read_struct('H')[0]
self._value = byteBuffer.read_struct(str(length)+'s')[0].decode('utf-8')
elif self.typename == 'uchar':
self._value = byteBuffer.read_struct('B')[0]
else:
raise MessageError('Cant get read from byteBuffer for type "%s"' %
self.typename)
class BaseMessage(object):
'''
Data packets must inherit from this base class. A subclass must have a
static property called MessageTypeID set to a integer value to uniquely
identify the packet within a single PacketFactory.
'''
HEADER_FORMAT = 'B'
MessageTypeID = None
MessageValues = None
UseDefaultValues = True
_log = logging.getLogger('legume.BaseMessage')
def __init__(self, *values):
self._message_type_id = self.MessageTypeID
if self.MessageTypeID is None:
raise MessageError('%s does not have a MessageTypeID' %
self.__class__.__name__)
self.value_names = []
if len(values) > 0:
for value in values:
self._add_value(value)
elif self.MessageValues is not None:
for mvname, mvtype in self.MessageValues.items():
if mvtype[:6] == 'string':
valuetype, param = mvtype.split(' ')
else:
valuetype = mvtype
param = None
new_value = MessageValue(mvname, valuetype, None, param, self)
self._add_value(new_value)
self.set_message_values_to_defaults()
def _add_value(self, value):
self.value_names.append(value.name)
self.__dict__[value.name] = value
def get_header_format(self):
'''
Returns the header format as a struct compatible string.
'''
return self.HEADER_FORMAT
def get_header_values(self):
'''
Returns a list containing the values used to construct
the packet header.
'''
return [self._message_type_id]
def get_data_format(self):
'''
Returns a struct compatible format string of the packet data
'''
format = []
for valuename in self.value_names:
value = self.__dict__[valuename]
if not isinstance(value, MessageValue):
raise MessageError(
'Overwritten message value! Use msgval.value = xyz')
format.append(value.get_format_string())
return ''.join(format)
def get_message_values(self):
'''
Returns a list containing the header+packet values used
to construct the packet
'''
values = self.get_header_values()
for name in self.value_names:
self._log.debug('Packet value %s = %s' %
(name, self.__dict__[name].get_message_values()))
values.extend(self.__dict__[name].get_message_values())
self._log.debug('Packetvalues = %s' % values)
return values
def get_message_format(self):
'''
Returns a struct compatible format string of the message
header and data
'''
return self.get_header_format() + self.get_data_format()
def get_packet_bytes(self):
'''
Returns a string containing the header and data. This
string can be passed to .loadFromString(...).
'''
message_values = self.get_message_values()
encoded = []
for value in message_values:
if type(value) == str:
encoded.append(value.encode('utf-8'))
else:
encoded.append(value)
packet_bytes = struct.pack(
'!'+self.get_message_format(),
*encoded)
self._log.debug('MESSAGE STRING LENGTH=%s' % len(packet_bytes))
return packet_bytes
@staticmethod
def read_header_from_byte_buffer(byteBuffer):
'''
Read a packet header from an instance of ByteBuffer. This
method will return a tuple containing the header
values.
'''
return byteBuffer.read_struct(BaseMessage.HEADER_FORMAT)
def set_message_values_to_defaults(self):
'''
Override this method to assign default values.
'''
pass
def read_from_byte_buffer(self, byteBuffer):
'''
Reconstitute the packet from a ByteBuffer instance
'''
for name in self.value_names:
self.__dict__[name].read_from_byte_buffer(byteBuffer)
class ConnectRequest(BaseMessage):
'''
A connection request packet - sent by a client to the server.
'''
MessageTypeID = BASE_MESSAGETYPEID_SYSTEM+1
MessageValues = {
'protocol':'uchar'
}
def load_default_values(self):
self.protocol.value = PROTOCOL_VERSION
class ConnectRequestRejected(BaseMessage):
'''
A connection request rejection packet - sent by the server back to
a client.
'''
MessageTypeID = BASE_MESSAGETYPEID_SYSTEM+2
class ConnectRequestAccepted(BaseMessage):
'''
A connection request accepted packet - sent by the server back to
a client.
'''
MessageTypeID = BASE_MESSAGETYPEID_SYSTEM+3
class KeepAliveRequest(BaseMessage):
'''
This is sent by the server to keep the connection alive.
'''
MessageTypeID = BASE_MESSAGETYPEID_SYSTEM+4
MessageValues = {
'id':'short'
}
class KeepAliveResponse(BaseMessage):
'''
A clients response to the receipt of a KeepAliveRequest message.
'''
MessageTypeID = BASE_MESSAGETYPEID_SYSTEM+5
MessageValues = {
'id':'short'
}
class Disconnected(BaseMessage):
'''
This message is sent by either the client or server to indicate to the
other end of the connection that the link is closed. In cases where
the connection is severed due to software crash, this message will
not be sent, and the socket will eventually disconnect due to a timeout.
'''
MessageTypeID = BASE_MESSAGETYPEID_SYSTEM+6
class MessageAck(BaseMessage):
'''
Sent by either a client or server to acknowledge receipt of an
in-order or reliable message.
'''
MessageTypeID = BASE_MESSAGETYPEID_SYSTEM+7
MessageValues = {
'message_to_ack':'int'
}
class Ping(BaseMessage):
MessageTypeID = BASE_MESSAGETYPEID_SYSTEM+8
MessageValues = {
'id':'short'
}
class Pong(BaseMessage):
MessageTypeID = BASE_MESSAGETYPEID_SYSTEM+9
MessageValues = {
'id':'short'
}
class MessageFactoryItem(object):
def __init__(self, message_name, message_type_id, message_factory):
self.message_name = message_name
self.message_type_id = message_type_id
self.message_factory = message_factory
class MessageFactory(object):
def __init__(self):
self._factories_by_name = {}
self._factories_by_id = {}
self.add(*list(messages.values()))
def add(self, *message_classes):
'''
Add message class(es) to the message factory.
The parameters to this method must be subclasses of BaseMessage.
A MessageError will be raised if a message already exists in
this factory with an identical name or MessageTypeID.
'''
for message_class in message_classes:
if message_class.__name__ in self._factories_by_name:
raise MessageError('Message type already in factory')
if message_class.MessageTypeID in self._factories_by_id:
raise MessageError('message %s has same Id as message %s' % (
message_class.__name__,
self._factories_by_id[
message_class.MessageTypeID].message_name))
messsage_factory_item = MessageFactoryItem(
message_class.__name__,
message_class.MessageTypeID,
message_class)
self._factories_by_name[message_class.__name__] = messsage_factory_item
self._factories_by_id[message_class.MessageTypeID] = messsage_factory_item
def get_by_id(self, id):
'''
Obtain a message class by specifying the packets MessageTypeID.
If the message cannot be found a MessageError exception is raised.
'''
try:
return self._factories_by_id[id].message_factory
except KeyError as e:
raise MessageError('No message exists with ID %s' % str(id))
def get_by_name(self, name):
'''
Obtain a message class by specifying the packets name.
If the message cannot be found a MessageError exception is raised.
'''
try:
return self._factories_by_name[name].message_factory
except KeyError as e:
raise MessageError('No message exists with name %s' % str(name))
def is_a(self, message_instance, message_name):
'''
Determine if message_instance is an instance of the named message class.
Example:
>>> tp = TestPacket1()
>>> message_factory.is_a(tp, 'TestPacket1')
True
'''
return isinstance(message_instance, self.get_by_name(message_name))
messages = {
'ConnectRequest':ConnectRequest,
'ConnectRequestRejected':ConnectRequestRejected,
'ConnectRequestAccepted':ConnectRequestAccepted,
'KeepAliveRequest':KeepAliveRequest,
'KeepAliveResponse':KeepAliveResponse,
'Disconnected':Disconnected,
'MessageAck':MessageAck,
'Pong':Pong,
'Ping':Ping
}
# The default global packet factory.
message_factory = MessageFactory() |
import torch
import torch.nn as nn
from model.spectrogram import Spectrogram
class Encoder(nn.Module):
"""
Encodes the waveforms into the latent representation
"""
def __init__(self, N, kernel_size, stride, layers, num_mels, sampling_rate):
"""
Arguments:
N {int} -- Dimension of the output latent representation
kernel_size {int} -- Base convolutional kernel size
stride {int} -- Stride of the convolutions
layers {int} -- Number of parallel convolutions with different kernel sizes
num_mels {int} -- Number of mel filters in the mel spectrogram
sampling_rate {int} -- Sampling rate of the input
"""
super(Encoder, self).__init__()
K = sampling_rate//8000
self.spectrogram = Spectrogram(n_fft=1024*K, hop=256*K, mels=num_mels, sr=sampling_rate)
self.filters = nn.ModuleList([])
filter_width = num_mels
for l in range(layers):
n = N // 4
k = kernel_size * (2**l)
self.filters.append(nn.Conv1d(1, n, kernel_size=k, stride=stride, bias=False, padding=(k-stride)//2))
filter_width += n
self.nonlinearity = nn.ReLU()
self.bottleneck = nn.Sequential(
nn.Conv1d(filter_width, N, kernel_size=1, stride=1, bias=False),
nn.ReLU(),
nn.Conv1d(N, N, kernel_size=1, stride=1, bias=False),
)
def forward(self, signal):
"""
Arguments:
signal {torch.tensor} -- mixed signal of shape (B, 1, T)
Returns:
torch.tensor -- latent representation of shape (B, N, T)
"""
convoluted_x = []
for filter in self.filters:
x = filter(signal).unsqueeze(-2) # shape: (B, N^, 1, T')
convoluted_x.append(x)
x = torch.cat(convoluted_x, dim=-2) # shape: (B, N^, L, T')
x = x.view(x.shape[0], x.shape[1]*x.shape[2], x.shape[3]) # shape: (B, N', T')
x = self.nonlinearity(x) # shape: (B, N', T')
spectrogram = self.spectrogram(signal, x.shape[-1]) # shape: (B, mel, T')
x = torch.cat([x, spectrogram], dim=1) # shape: (B, N*, T')
return self.bottleneck(x) # shape: (B, N, T)
|
from bitmovin_api_sdk.encoding.encodings.muxings.progressive_webm.information.information_api import InformationApi
|
class Type:
def __init__(self, name):
self.name = name
def __and__(self,other):
return Union_Type(self,other)
def __or__(self,other):
return Option_Type(self,other)
def __repr__(self):
return self.name
class Union_Type(Type):
def __init__(self,*args):
self.args = [x for xs in args for x in (xs.args if type(xs) is Union_Type else (xs,))]
def __repr__(self):
return "("+",".join(map(str,self.args))+")"
class Option_Type(Type):
def __init__(self,*args):
self.args = {x for xs in args for x in (xs.args if type(xs) is Option_Type else (xs,))}
def __repr__(self):
return "("+"|".join(map(str,self.args))+")"
none = Type("none")
auto = Type("auto")
Auto = "auto"
integer = Type("integer")
string = Type("string")
tensor = Type("tensor")
activation = Type("activation")
|
import numpy as np
import pandas as pd
import math
from sklearn.cross_validation import train_test_split
import scipy.sparse as sparse
from scipy.sparse.linalg import spsolve
from numpy.linalg import norm,cholesky
from sklearn.metrics import mean_squared_error,mean_absolute_error
# import data
data = pd.read_table(r'D:\360MoveData\Users\HP\Desktop\prostate.data.txt')
factors = [
'lcavol',
'lweight',
'age',
'lbph',
'svi',
'lcp',
'gleason',
'pgg45'
]
X = data [factors]
Y = data['lpsa']
def Standard_error(sample):
std = np.std(sample,ddof=0)
standard_error = std/math.sqrt(len(sample))
return standard_error
X_train, X_test, y_train, y_test = train_test_split(X, Y,test_size=0.2, random_state=1)
def lasso_admm(X,y,alpha=5,rho=1.,rel_par=1.,QUIET=True,\
MAX_ITER=100,ABSTOL=1e-3,RELTOL= 1e-2):
#Data preprocessing
m,n = X.shape
#save a matrix-vector multiply
Xty = X.T.dot(y)
#ADMM solver
x = np.zeros((n,1))
z = np.zeros((n,1))
u = np.zeros((n,1))
# cache the (Cholesky) factorization
L,U = factor(X,rho)
# Saving state
h = {}
h['objval'] = np.zeros(MAX_ITER)
h['r_norm'] = np.zeros(MAX_ITER)
h['s_norm'] = np.zeros(MAX_ITER)
h['eps_pri'] = np.zeros(MAX_ITER)
h['eps_dual'] = np.zeros(MAX_ITER)
for k in range(MAX_ITER):
# x-update
tmp_variable = np.array(Xty)+rho*(z-u)[0] #(temporary value)
if m>=n:
x = spsolve(U,spsolve(L,tmp_variable))[...,np.newaxis]
else:
ULXq = spsolve(U,spsolve(L,X.dot(tmp_variable)))[...,np.newaxis]
x = (tmp_variable*1./rho)-((X.T.dot(ULXq))*1./(rho**2))
# z-update with relaxation
zold = np.copy(z)
x_hat = rel_par*x+(1.-rel_par)*zold
z = shrinkage(x_hat+u,alpha*1./rho)
# u-update
u+=(x_hat-z)
# diagnostics, reporting, termination checks
h['objval'][k] = objective(X,y,alpha,x,z)
h['r_norm'][k] = norm(x-z)
h['s_norm'][k] = norm(-rho*(z-zold))
h['eps_pri'][k] = np.sqrt(n)*ABSTOL+\
RELTOL*np.maximum(norm(x),norm(-z))
h['eps_dual'][k] = np.sqrt(n)*ABSTOL+\
RELTOL*norm(rho*u)
if (h['r_norm'][k]<h['eps_pri'][k]) and (h['s_norm'][k]<h['eps_dual'][k]):
break
return z.ravel(),h
def objective(X,y,alpha,x,z):
return .5*np.square(X.dot(x)-y).sum().sum()+alpha*norm(z,1)
def shrinkage(x,kappa):
return np.maximum(0.,x-kappa)-np.maximum(0.,-x-kappa)
def factor(X,rho):
m,n = X.shape
if m>=n:
L = cholesky(X.T.dot(X)+rho*sparse.eye(n))
else:
L = cholesky(sparse.eye(m)+1./rho*(X.dot(X.T)))
L = sparse.csc_matrix(L)
U = sparse.csc_matrix(L.T)
return L,U
coefficients=lasso_admm(X_train,y_train,alpha=0.0058)
y_test_predict=X_test.dot(coefficients[0])
# model evaluation (MSE,MAE,std_error)
mse_predict = round(mean_squared_error(y_test,y_test_predict),4)
mae_predict = round(mean_absolute_error(y_test,y_test_predict),4)
std_error = round(Standard_error(y_test_predict),4)
coef = []
for i in range(8):
coef.append((factors[i],round(coefficients[0][i],4)))
print ('Estimated coefficients are:'+str(coef))
print ('Std Error is:'+str(std_error))
print ('MSE is:'+str(mse_predict))
print ('MAE is:'+str(mae_predict))
|
# -*- coding: utf-8 -*-
from copy import deepcopy
import numpy as np
from scipy.integrate import simps
from .scattering_factors import scattering_factor_param, calculate_coherent_scattering_factor, \
calculate_incoherent_scattered_intensity
from .soller_correction import SollerCorrection
from .pattern import Pattern
def calculate_atomic_number_sum(composition):
"""
Calculates the sum of the atomic number of all elements in the composition
:param composition: composition as a dictionary with the elements as keys and the abundances as values
:return: sum of the atomic numbers
"""
z_tot = 0
for element, n in composition.items():
z_tot += scattering_factor_param['Z'][element] * n
return z_tot
def calculate_effective_form_factors(composition, q):
"""
Calculates the effective form factor as defined in Eq. 10 in Eggert et al. (2002)
:param composition: composition as a dictionary with the elements as keys and the abundances as values
:param q: Q value or numpy array with a unit of A^-1
:return: effective form factors numpy array
"""
z_tot = calculate_atomic_number_sum(composition)
f_effective = 0
for element, n in composition.items():
f_effective += calculate_coherent_scattering_factor(element, q) * n
return f_effective / float(z_tot)
def calculate_incoherent_scattering(composition, q):
"""
Calculates the not normalized incoherent scattering contribution from a specific composition.
:param composition:
:param q: Q value or numpy array with a unit of A^-1
:return: incoherent scattering numpy array
"""
inc = 0
for element, n in composition.items():
inc += calculate_incoherent_scattered_intensity(element, q) * n
return inc
def calculate_j(incoherent_scattering, z_tot, f_effective):
"""
Calculates the J parameter as described in equation (35) from Eggert et al. 2002.
:param incoherent_scattering: Q dependent incoherent scattering
:param z_tot: sum of atomic numbers for the material
:param f_effective: Q dependent effective form factor
:return: J numpy array with the same q as incoherent scattering and f_effective
"""
return incoherent_scattering / (z_tot * f_effective) ** 2
def calculate_kp(element, f_effective, q):
"""
Calculates the average effective atomic number (averaged over the whole Q range).
:param element: elemental symbol
:param f_effective: effective form factor
:param q: Q value or numpy array with a unit of A^-1
:return: average effective atomic number
:rtype: float
"""
kp = np.mean(calculate_coherent_scattering_factor(element, q) / f_effective)
return kp
def calculate_s_inf(composition, z_tot, f_effective, q):
"""
Calculates S_inf as described in equation (19) from Eggert et al. 2002
:param composition: composition as a dictionary with the elements as keys and the abundances as values
:param z_tot: sum of atomic numbers for the material
:param f_effective: Q dependent effective form factor
:param q: q numpy array with units of A^-1
:return: S_inf value
"""
sum_kp_squared = 0
for element, n in composition.items():
sum_kp_squared += n * calculate_kp(element, f_effective, q) ** 2
return sum_kp_squared / z_tot ** 2
def calculate_alpha(sample_pattern, z_tot, f_effective, s_inf, j, atomic_density):
"""
Calculates the normalization factor alpha after equation (34) from Eggert et al. 2002.
:param sample_pattern: Background subtracted sample pattern
:param z_tot: sum opf atomic numbers for the material
:param f_effective: Q dependent effective form factor
:param s_inf: S_inf value (equ. (19) from Eggert et al. 2002)
:param j: J value (equ. (35) from Eggert et al. 2002)
:param atomic_density: number density in atoms/Angstrom^3
:return: normalization factor alpha
"""
q, intensity = sample_pattern.data
integral_1 = simps((j + s_inf) * q ** 2, q)
integral_2 = simps((intensity / f_effective ** 2) * q ** 2, q)
alpha = z_tot ** 2 * (-2 * np.pi ** 2 * atomic_density + integral_1) / integral_2
return alpha
def calculate_coherent_scattering(sample_pattern, alpha, N, incoherent_scattering):
"""
Calculates the coherent Scattering Intensity Pattern
:param sample_pattern: Background subtracted sample pattern
:param alpha: normalization factor alpha (after equ. (34) from Eggert et al. 2002)
:param N: Number of atoms
:param incoherent_scattering: incoherent scattering intensity
:return: Coherent Scattering Pattern
:rtype: Pattern
"""
q, intensity = sample_pattern.data
coherent_intensity = N * (alpha * intensity - incoherent_scattering)
return Pattern(q, coherent_intensity)
def calculate_sq(coherent_pattern, N, z_tot, f_effective):
"""
Calculates the Structure Factor based on equation (18) in Eggert et al. 2002
:param coherent_pattern: coherent pattern
:param N: number of atoms for structural unit, e.g. 3 for SiO2
:param z_tot: sum opf atomic numbers for the material
:param f_effective: Q dependent effective form factor
:return: S(q) pattern
:rtype: Pattern
"""
q, coherent_intensity = coherent_pattern.data
sq_intensity = coherent_intensity / (N * z_tot ** 2 * f_effective ** 2)
return Pattern(q, sq_intensity)
def calculate_fr(iq_pattern, r=None, use_modification_fcn=False):
"""
Calculates F(r) from a given interference function i(Q) for r values.
If r is none a range from 0 to 10 with step 0.01 is used. A Lorch modification function of the form:
m = sin(q*pi/q_max)/(q*pi/q_max)
can be used to address issues with a low q_max. This will broaden the sharp peaks in f(r)
:param iq_pattern: interference function i(q) = S(Q)-S_inf with lim_inf i(Q)=0 and unit(q)=A^-1
:type iq_pattern: Pattern
:param r: numpy array giving the r-values for which F(r) will be calculated,
default is 0 to 10 with 0.01 as a step. units should be in Angstrom.
:param use_modification_fcn: boolean flag whether to use the Lorch modification function
:return: F(r) pattern
:rtype: Pattern
"""
if r is None:
r = np.arange(0, 10, 0.01)
q, iq = iq_pattern.data
if use_modification_fcn:
modification = np.sin(q * np.pi / np.max(q)) / (q * np.pi / np.max(q))
else:
modification = 1
fr = 2.0 / np.pi * simps(modification * q * (iq) * \
np.array(np.sin(np.outer(q.T, r))).T, q)
return Pattern(r, fr)
def optimize_iq(iq_pattern, r_cutoff, iterations, atomic_density, j, s_inf=1, use_modification_fcn=False,
attenuation_factor=1, fcn_callback=None, callback_period=2):
"""
Performs an optimization of the structure factor based on an r_cutoff value as described in Eggert et al. 2002 PRB,
65, 174105. This basically does back and forward transforms between S(Q) and f(r) until the region below the
r_cutoff value is a flat line without any oscillations.
:param iq_pattern:
original i(Q) pattern = S(Q)-S_inf
:param r_cutoff:
cutoff value below which there is no signal expected (below the first peak in g(r))
:param iterations:
number of back and forward transforms
:param atomic_density:
density in atoms/A^3
:param j:
J value (equ. (35) from Eggert et al. 2002)
:param s_inf:
S_inf value (equ. (19) from Eggert et al. 2002, defaults to 1, which is the value for mon-atomic substances
:param use_modification_fcn:
Whether or not to use the Lorch modification function during the Fourier transform.
Warning: When using the Lorch modification function usually more iterations are needed to get to the
wanted result.
:param attenuation_factor:
Sometimes the initial change during back and forward transformations results in a run
away, by setting the attenuation factor to higher than one can help for this situation, it basically reduces
the amount of change during each iteration.
:param fcn_callback:
Function which will be called at an iteration period defined by the callback_period parameter.
The function should take 3 arguments: sq_pattern, fr_pattern and gr_pattern. Additionally the function
should return a boolean value, where True continues the optimization and False will stop the optimization
procedure
:param callback_period:
determines how frequently the fcn_callback will be called.
:return:
optimized S(Q) pattern
"""
r = np.arange(0, r_cutoff, 0.02)
iq_pattern = deepcopy(iq_pattern)
for iteration in range(iterations):
fr_pattern = calculate_fr(iq_pattern, r, use_modification_fcn)
q, iq_int = iq_pattern.data
r, fr_int = fr_pattern.data
delta_fr = fr_int + 4 * np.pi * r * atomic_density
in_integral = np.array(np.sin(np.outer(q.T, r))) * delta_fr
integral = np.trapz(in_integral, r) / attenuation_factor
iq_optimized = iq_int - 1. / q * (iq_int / (s_inf + j) + 1) * integral
iq_pattern = Pattern(q, iq_optimized)
if fcn_callback is not None and iteration % callback_period == 0:
fr_pattern = calculate_fr(iq_pattern, use_modification_fcn=use_modification_fcn)
gr_pattern = calculate_gr_raw(fr_pattern, atomic_density)
fcn_callback(iq_pattern, fr_pattern, gr_pattern)
return iq_pattern
def calculate_chi2_map(data_pattern, bkg_pattern, composition,
densities, bkg_scalings, r_cutoff, iterations=2):
"""
Calculates a chi2 2d array for an array of densities and background scalings.
:param data_pattern: original data pattern
:param bkg_pattern: original background pattern
:param composition: composition as a dictionary with the elements as keys and the abundances as values
:param densities: 1-dimensional array of densities for which to calculate chi2
:param bkg_scalings: 1-dimensional array of background scalings for which to calculate chi2
:param r_cutoff: cutoff value below which there is no signal expected (below the first peak in g(r))
:param iterations: number of iterations for optimization, described in equations 47-49 in Eggert et al. 2002
:return: 2-dimensional array of chi2 values
"""
N = sum([composition[x] for x in composition])
q = data_pattern.extend_to(0, 0).x
inc = calculate_incoherent_scattering(composition, q)
f_eff = calculate_effective_form_factors(composition, q)
z_tot = calculate_atomic_number_sum(composition)
s_inf = calculate_s_inf(composition, z_tot, f_eff, q)
j = calculate_j(inc, z_tot, f_eff)
chi2 = np.zeros((len(densities), len(bkg_scalings)))
for n1, density in enumerate(densities):
for n2, bkg_scaling in enumerate(bkg_scalings):
# density = params['density'].value
# bkg_scaling = params['bkg_scaling'].value
r = np.arange(0, r_cutoff, 0.02)
sample_pattern = data_pattern - bkg_scaling * bkg_pattern
sample_pattern = sample_pattern.extend_to(0, 0)
alpha = calculate_alpha(sample_pattern, z_tot, f_eff, s_inf, j, density)
coherent_pattern = calculate_coherent_scattering(sample_pattern, alpha, N, inc)
sq_pattern = calculate_sq(coherent_pattern, N, z_tot, f_eff)
iq_pattern = Pattern(sq_pattern.x, sq_pattern.y - s_inf)
delta_fr = np.zeros(r.shape)
for iteration in range(iterations):
fr_pattern = calculate_fr(iq_pattern, r)
q, iq_int = iq_pattern.data
r, fr_int = fr_pattern.data
delta_fr = fr_int + 4 * np.pi * r * density
in_integral = np.array(np.sin(np.outer(q.T, r))) * delta_fr
integral = np.trapz(in_integral, r)
iq_optimized = iq_int - 1. / q * (iq_int / (s_inf + j) + 1) * integral
iq_pattern = Pattern(q, iq_optimized)
chi2[n1, n2] = np.sum(delta_fr ** 2)
return chi2
def optimize_density_and_bkg_scaling(data_pattern, bkg_pattern, composition,
initial_density, initial_bkg_scaling, r_cutoff, iterations=2,
use_modification_fcn=False):
"""
This function tries to find the optimum density in background scaling with the given parameters. The equations
behind the optimization are presented equ (47-50) in the Eggert et al. 2002 paper.
:param data_pattern: original data pattern
:param bkg_pattern: original background pattern
:param composition: composition as a dictionary with the elements as keys and the abundances as values
:param initial_density: density starting point for the optimization procedure
:param initial_bkg_scaling: background scaling starting point for the optimization procedure
:param r_cutoff: cutoff value below which there is no signal expected (below the first peak in g(r))
:param iterations: number of iterations for optimization, described in equations 47-49 in Eggert et al. 2002
:param use_modification_fcn: Whether or not to use the Lorch modification function during the Fourier transform.
:return: tuple with optimized parameters (density, density_error, bkg_scaling, bkg_scaling_error)
"""
N = sum([composition[x] for x in composition])
q = data_pattern.extend_to(0, 0).x
inc = calculate_incoherent_scattering(composition, q)
f_eff = calculate_effective_form_factors(composition, q)
z_tot = calculate_atomic_number_sum(composition)
s_inf = calculate_s_inf(composition, z_tot, f_eff, q)
j = calculate_j(inc, z_tot, f_eff)
def optimization_fcn(x):
density = x['density'].value
bkg_scaling = x['bkg_scaling'].value
r = np.arange(0, r_cutoff, 0.02)
sample_pattern = data_pattern - bkg_scaling * bkg_pattern
sample_pattern = sample_pattern.extend_to(0, 0)
alpha = calculate_alpha(sample_pattern, z_tot, f_eff, s_inf, j, density)
coherent_pattern = calculate_coherent_scattering(sample_pattern, alpha, N, inc)
sq_pattern = calculate_sq(coherent_pattern, N, z_tot, f_eff)
iq_pattern = Pattern(sq_pattern.x, sq_pattern.y - s_inf)
fr_pattern = calculate_fr(iq_pattern, r, use_modification_fcn=use_modification_fcn)
q, iq_int = iq_pattern.data
r, fr_int = fr_pattern.data
delta_fr = fr_int + 4 * np.pi * r * density
for iteration in range(iterations):
in_integral = np.array(np.sin(np.outer(q.T, r))) * delta_fr
integral = np.trapz(in_integral, r)
iq_optimized = iq_int - 1. / q * (iq_int / (s_inf + j) + 1) * integral
iq_pattern = Pattern(q, iq_optimized)
fr_pattern = calculate_fr(iq_pattern, r)
q, iq_int = iq_pattern.data
r, fr_int = fr_pattern.data
delta_fr = fr_int + 4 * np.pi * r * density
return delta_fr
from lmfit import Parameters, minimize, report_fit
params = Parameters()
params.add('density', value=initial_density, )
params.add('bkg_scaling', value=initial_bkg_scaling)
result = minimize(optimization_fcn, params)
return result.params['density'].value, result.params['density'].stderr, \
result.params['bkg_scaling'].value, result.params['density'].stderr
def optimize_soller_dac(data_pattern, bkg_pattern, composition, initial_density, initial_bkg_scaling,
initial_thickness, sample_thickness, wavelength,
initial_carbon_content=1, r_cutoff=2.28, iterations=1,
use_modification_fcn=False, vary=(True, True, True)):
"""
Optimizes density, background scaling and diamond content for a list of sample thickness with a given initial
gasket thickness in the diamond anvil cell (DAC). The calculation is done by utilizing the soller slit transfer
function and assuming that the DAC has been centered to the rotation center of the soller slit.
:param data_pattern: original data pattern
:param bkg_pattern: original background pattern
:param composition: composition as a dictionary with the elements as keys and the abundances as values
:param initial_density: density starting point for the optimization procedure
:param initial_bkg_scaling: background scaling starting point for the optimization procedure
:param initial_thickness: gasket thickness with which the background was measured.
:param sample_thickness: sample thickness for which the sample was measured
:param wavelength: wavelength of the radiation used - needed for calculation of soller slit transfer function in
q-space
:param initial_carbon_content: carbon content starting point for the optimization
:param r_cutoff: cutoff value below which there is no signal expected (below the first peak in g(r)
:param iterations: number of iterations for optimization, described in equations 47-49 in Eggert et al. 2002
:param use_modification_fcn: Whether or not to use the Lorch modification function during the Fourier transform.
:param vary: 3 boolean flags whether to vary: density, bkg_scaling, carbon_content during the optimization
:return:
"""
N = sum([composition[x] for x in composition])
q = data_pattern.extend_to(0, 0).x
inc = calculate_incoherent_scattering(composition, q)
f_eff = calculate_effective_form_factors(composition, q)
z_tot = calculate_atomic_number_sum(composition)
s_inf = calculate_s_inf(composition, z_tot, f_eff, q)
j = calculate_j(inc, z_tot, f_eff)
tth = 2 * np.arcsin(data_pattern.x * wavelength / (4 * np.pi)) / np.pi * 180
soller = SollerCorrection(tth, initial_thickness)
def optimization_fcn(params):
diamond_content = params['diamond_content'].value
bkg_scaling = params['bkg_scaling'].value
density = params['density'].value
q, data_int = data_pattern.data
_, bkg_int = bkg_pattern.data
sample_transfer, diamond_transfer = soller.transfer_function_dac(sample_thickness, initial_thickness)
diamond_background = diamond_content * Pattern(q,
calculate_incoherent_scattering({'C': 1},
q) / diamond_transfer)
sample_pattern = data_pattern - bkg_scaling * bkg_pattern
sample_pattern = sample_pattern - diamond_background
sample_pattern = Pattern(q, sample_pattern.y * sample_transfer)
sample_pattern = sample_pattern.extend_to(0, 0)
alpha = calculate_alpha(sample_pattern, z_tot, f_eff, s_inf, j, density)
coherent_pattern = calculate_coherent_scattering(sample_pattern, alpha, N, inc)
sq_pattern = calculate_sq(coherent_pattern, N, z_tot, f_eff)
iq_pattern = Pattern(sq_pattern.x, sq_pattern.y - s_inf)
r = np.arange(0, r_cutoff, 0.02)
fr_pattern = calculate_fr(iq_pattern, r, use_modification_fcn=use_modification_fcn)
q, iq_int = iq_pattern.data
r, fr_int = fr_pattern.data
delta_fr = fr_int + 4 * np.pi * r * density
for iteration in range(iterations):
in_integral = np.array(np.sin(np.outer(q.T, r))) * delta_fr
integral = np.trapz(in_integral, r)
iq_optimized = iq_int - 1. / q * (iq_int / (s_inf + j) + 1) * integral
iq_pattern = Pattern(q, iq_optimized)
fr_pattern = calculate_fr(iq_pattern, r)
q, iq_int = iq_pattern.data
r, fr_int = fr_pattern.data
delta_fr = fr_int + 4 * np.pi * r * density
return delta_fr
from lmfit import Parameters, minimize, report_fit
params = Parameters()
params.add('density', value=initial_density, min=0, vary=vary[0])
params.add('bkg_scaling', value=initial_bkg_scaling, vary=vary[1])
params.add('diamond_content', value=initial_carbon_content, min=0, vary=vary[2])
result = minimize(optimization_fcn, params)
report_fit(result)
return result.chisqr, \
result.params['density'].value, result.params['density'].stderr,\
result.params['bkg_scaling'].value, result.params['bkg_scaling'].stderr,\
result.params['diamond_content'].value, result.params['diamond_content'].stderr
|
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator 2.3.33.0
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.serialization import Model
class PythonSection(Model):
"""PythonSection.
:param interpreter_path: The python interpreter path to use if an
environment build is not required. The path specified gets used to call
the user script.
:type interpreter_path: str
:param user_managed_dependencies: True means that AzureML reuses an
existing python environment; False means that AzureML will create a python
environment based on the Conda dependencies specification.
:type user_managed_dependencies: bool
:param conda_dependencies:
:type conda_dependencies: object
:param base_conda_environment:
:type base_conda_environment: str
"""
_attribute_map = {
'interpreter_path': {'key': 'interpreterPath', 'type': 'str'},
'user_managed_dependencies': {'key': 'userManagedDependencies', 'type': 'bool'},
'conda_dependencies': {'key': 'condaDependencies', 'type': 'object'},
'base_conda_environment': {'key': 'baseCondaEnvironment', 'type': 'str'},
}
def __init__(self, interpreter_path=None, user_managed_dependencies=None, conda_dependencies=None, base_conda_environment=None):
super(PythonSection, self).__init__()
self.interpreter_path = interpreter_path
self.user_managed_dependencies = user_managed_dependencies
self.conda_dependencies = conda_dependencies
self.base_conda_environment = base_conda_environment
|
#!/usr/bin/env python
from resource_management.core.logger import Logger
import base64
import urllib2
import ambari_simplejson as json
from resource_management.core.source import Template
class RangerPolicyUpdate:
def create_policy_if_needed(self):
service_name = self.get_service()
Logger.info("Ranger Hdfs service name : {0}".format(service_name))
if service_name:
if self.check_if_policy_does_not_exist(service_name):
self.create_policy(service_name)
else:
Logger.info("Policy already exists.")
else:
Logger.error("Ranger hdfs service not found")
def get_service(self):
try:
url = self.ranger_url + "/service/public/v2/api/service?serviceType=hdfs"
Logger.info("Getting ranger service name for hdfs. Url : {0}".format(url))
request = urllib2.Request(url, None, self.headers)
result = urllib2.urlopen(request, timeout=20)
response_code = result.getcode()
if response_code == 200:
response = json.loads(result.read())
if (len(response) > 0):
return response[0]['name']
else:
return None
except urllib2.HTTPError as e:
Logger.error(
"Error during Ranger service authentication. Http status code - {0}. {1}".format(e.code, e.read()))
return None
except urllib2.URLError as e:
Logger.error("Error during Ranger service authentication. {0}".format(e.reason))
return None
except Exception as e:
Logger.error("Error occured when connecting Ranger admin. {0} ".format(e))
return None
def check_if_policy_does_not_exist(self, service_name):
try:
url = self.ranger_url + "/service/public/v2/api/service/" + \
service_name + "/policy?policyName=dpprofiler-audit-read"
Logger.info("Checking ranger policy. Url : {0}".format(url))
request = urllib2.Request(url, None, self.headers)
result = urllib2.urlopen(request, timeout=20)
response_code = result.getcode()
if response_code == 200:
response = json.loads(result.read())
return (len(response) == 0)
except urllib2.HTTPError as e:
Logger.error(
"Error during Ranger service authentication. Http status code - {0}. {1}".format(e.code, e.read()))
return False
except urllib2.URLError as e:
Logger.error("Error during Ranger service authentication. {0}".format(e.reason))
return False
except Exception as e:
Logger.error("Error occured when connecting Ranger admin. {0}".format(e))
return False
def create_policy(self, service_name):
try:
variable = {
'ranger_audit_hdfs_path': self.ranger_audit_hdfs_path,
'dpprofiler_user': self.dpprofiler_user,
'service_name': service_name
}
self.env.set_params(variable)
data = Template("dpprofiler_ranger_policy.json").get_content()
url = self.ranger_url + "/service/public/v2/api/policy"
Logger.info("Creating ranger policy. Url : {0}".format(url))
Logger.info("data: {0}".format(data))
request = urllib2.Request(url, data, self.headers)
result = urllib2.urlopen(request, timeout=20)
response_code = result.getcode()
Logger.info("Response code for create policy : {0}".format(response_code))
if response_code == 200:
response = json.loads(result.read())
return response
except urllib2.HTTPError as e:
Logger.error(
"Error during Ranger service authentication. Http status code - {0}. {1}".format(e.code, e.read()))
return None
except urllib2.URLError as e:
Logger.error("Error during Ranger service authentication. {0}".format(e.reason))
return None
except Exception as e:
Logger.error("Error occured when connecting Ranger admin. {0}".format(e))
return None
def __init__(self, ranger_url, username, password, ranger_audit_hdfs_path, dpprofiler_user, env):
self.ranger_url = ranger_url
self.ranger_audit_hdfs_path = ranger_audit_hdfs_path
self.dpprofiler_user = dpprofiler_user
self.env = env
username_password = '{0}:{1}'.format(username, password)
base_64_string = base64.encodestring(username_password).replace('\n', '')
self.headers = {"Content-Type": "application/json", "Accept": "application/json", \
"Authorization": "Basic {0}".format(base_64_string)}
|
# -*- coding: utf-8 -*-
"""
Kernel k-means
==============
This example uses Global Alignment kernel (GAK, [1]) at the core of a kernel
:math:`k`-means algorithm [2] to perform time series clustering.
Note that, contrary to :math:`k`-means, a centroid cannot be computed when
using kernel :math:`k`-means. However, one can still report cluster
assignments, which is what is provided here: each subfigure represents the set
of time series from the training set that were assigned to the considered
cluster.
[1] M. Cuturi, "Fast global alignment kernels," ICML 2011.
[2] I. S. Dhillon, Y. Guan, B. Kulis. Kernel k-means, Spectral Clustering and \
Normalized Cuts. KDD 2004.
"""
# Author: Romain Tavenard
# License: BSD 3 clause
import numpy
import matplotlib.pyplot as plt
from tslearn.clustering import GlobalAlignmentKernelKMeans
from tslearn.metrics import sigma_gak
from tslearn.datasets import CachedDatasets
from tslearn.preprocessing import TimeSeriesScalerMeanVariance
seed = 0
numpy.random.seed(seed)
X_train, y_train, X_test, y_test = CachedDatasets().load_dataset("Trace")
# Keep first 3 classes
X_train = X_train[y_train < 4]
numpy.random.shuffle(X_train)
# Keep only 50 time series
X_train = TimeSeriesScalerMeanVariance().fit_transform(X_train[:50])
sz = X_train.shape[1]
gak_km = GlobalAlignmentKernelKMeans(n_clusters=3,
sigma=sigma_gak(X_train),
n_init=20,
verbose=True,
random_state=seed)
y_pred = gak_km.fit_predict(X_train)
plt.figure()
for yi in range(3):
plt.subplot(3, 1, 1 + yi)
for xx in X_train[y_pred == yi]:
plt.plot(xx.ravel(), "k-")
plt.xlim(0, sz)
plt.ylim(-4, 4)
plt.title("Cluster %d" % (yi + 1))
plt.tight_layout()
plt.show()
|
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 19 15:52:33 2018
@author: dalonlobo
"""
from __future__ import absolute_import, division, \
print_function, unicode_literals
import os
import sys
import argparse
import logging
import pandas as pd
from pysrt.srtfile import SubRipFile
from pysrt.srtitem import SubRipItem
from pysrt.srtitem import SubRipTime
logger = logging.getLogger("__main__")
def create_srt(split_df, cris_stt_df):
abs_path = os.path.dirname(split_df)
df1 = pd.read_csv(split_df)
df2 = pd.read_excel(cris_stt_df)
df1.rename(columns={'wav_filename': 'wav_name'}, inplace=True)
# This df3 contains all the info for srt creation
df3 = pd.merge(df1, df2, how='inner', on='wav_name')
print("Creating the srt:")
new_srt = SubRipFile()
for index, row in df3.iterrows():
text = str(row['transcripts'] if \
type(row['transcripts']) != float \
else "")
new_srt.append(SubRipItem(index=index+1,
start=SubRipTime(milliseconds=row['start']),
end=SubRipTime(milliseconds=row['end']),
text=text[:-1] if text.endswith(".") else text
))
new_srt.save(os.path.join(abs_path, "stt_converted.srt"))
print("successfully written")
if __name__ == "__main__":
"""
Create srt files
"""
logs_path = os.path.basename(__file__) + ".logs"
logging.basicConfig(filename=logs_path,
filemode='a',
format='%(asctime)s [%(name)s:%(levelname)s] [%(filename)s:%(funcName)s] #%(lineno)d: %(message)s',
datefmt='%H:%M:%S',
level=logging.DEBUG)
logger = logging.getLogger(__name__)
print("Logs are in ", os.path.abspath(logs_path), file=sys.stderr)
print("Run the following command to view logs:\n", file=sys.stderr)
print("tail -f {}".format(os.path.abspath(logs_path)), file=sys.stderr)
parser = argparse.ArgumentParser(description="mp4 to wav")
parser.add_argument('--srcpath', type=str,
help='Path to the folder mp4 files')
# Remove the below line
# args = parser.parse_args(["--srcpath", "Videos"])
# Uncomment the below line
args = parser.parse_args()
srcpath = os.path.abspath(args.srcpath)
logger.debug("Reading the files: \n")
for dirs in os.listdir(srcpath):
vid_directory = os.path.join(srcpath, dirs)
if not os.path.isdir(vid_directory):
continue # If its not directory, just continue
split_df = os.path.join(vid_directory, "split_df.csv")
cris_stt_df = os.path.join(vid_directory, "cris_stt_df.xlsx")
print("Reading files:")
print(split_df, cris_stt_df, sep="\n")
create_srt(split_df, cris_stt_df)
logger.info("All srt converted")
print("All srt converted", file=sys.stderr)
logger.info("#########################")
logger.info(".....Exiting program.....")
logger.info("#########################")
print(".....Exiting program.....", file=sys.stderr)
|
#!/usr/bin/python
# Given a username and plaintext password,
# authenticate against the db user records
import sys
from grinbase.model.users import Users
from grinlib import lib
# User to authenticate
username = sys.argv[1]
password = sys.argv[2]
# Initialize a db connection
database = lib.get_db()
# Lookup / authenticate
theUserRecord = Users.get(username, password)
# Print the results
if theUserRecord is None:
print("Failed to find or autenticate user: {}".format(username))
else:
print("Success, {} has id {}".format(username, theUserRecord.id))
|
# Copyright (C) Microsoft Corporation. All rights reserved.
# This program is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import ocslog
import pre_settings
from utils_print import *
from pre_settings import *
from ocsaudit_log import *
from controls.utils import *
from controls.sys_works import *
from models.powermeter import *
from argparse import ArgumentParser
from models.rack_manager import getrackmanager
#######################################################
# Rack manager show/set functions
#######################################################
def rackmanager_parse_show_commands(command_args):
"""
Display commands for rack manager
ocscli show rackmanager <command> <parameters>
Command options:
"Info",
"PortStatus",
"LEDStatus",
"Relay",
"TFTPStatus",
"TFTPList",
"NFSStatus",
"SessionList",
"Log",
"Time",
"Type",
"ScanDevice",
"FWUpdate"
"""
try:
parser = ArgumentParser(prog = 'show manager', description = "Manager show commands")
subparser = parser.add_subparsers(title = "Commands", metavar = '', dest = 'command')
rackmanager_showcommand_options(subparser)
args = parse_args_retain_case(parser, command_args)
get_rm_cmd = repr(pre_settings.command_name_enum.get_rm_state)
if pre_settings.is_get_rm_call == True:
ocsaudit_log_command("", cmd_type.type_show, cmd_interface.interface_ocscli,
"manager " + str(args.command)," ".join(command_args[1:]))
rackmanager_showcommands(args)
else:
permission = pre_settings.pre_check_manager(get_rm_cmd, 0)
if (permission == False):
return
else:
ocsaudit_log_command("", cmd_type.type_show, cmd_interface.interface_ocscli,
"manager " + args.command, " ".join(command_args[1:]))
rackmanager_showcommands(args)
except Exception,e: print(e)
def rackmanager_parse_set_commands(command_args):
"""
Set commands for rack manager
ocscli set rackmanager <command> <parameters>
Command options:
"LEDOn",
"LEDOff",
"RelayOn",
"RelayOff",
"TFTPStart",
"TFTPStop",
"TFTPGet",
"TFTPPut",
"TFTPDelete",
"NFSStart",
"NFSStop",
"FwUpdate",
"ClearLog",
"SessionKill",
"Time"
"""
try:
parser = ArgumentParser(prog = 'set manager', description = "Manager set commands")
subparser = parser.add_subparsers(title = "Commands", metavar = '', dest = 'command')
rackmanager_setcommand_options(subparser)
args = parse_args_retain_case(parser, command_args)
set_rm_cmd = repr(pre_settings.command_name_enum.set_rm_state)
if pre_settings.is_set_rm_call == True:
ocsaudit_log_command("", cmd_type.type_set, cmd_interface.interface_ocscli,
"manager " + str(args.command), " ".join(command_args[1:]))
rackmanager_setcommands(args)
else:
permission = pre_settings.pre_check_manager(set_rm_cmd, 0)
if (permission == False):
return
else:
ocsaudit_log_command("", cmd_type.type_set, cmd_interface.interface_ocscli,
"manager " + str(args.command), " ".join(command_args[1:]))
rackmanager_setcommands(args)
except Exception, e:
ocslog.log_exception()
print "rackmanager_parse_set_commands - Exception: {0}".format(e)
def rackmanager_showcommand_options(subparsers):
try:
# ScanDevice command
subparsers.add_parser("scandevice", help = "This command displays rack manager system information")
# Type command
type_parser = subparsers.add_parser("type", help = "This command displays manager type")
# Time command
subparsers.add_parser("time", help = "This command displays manager system time and date in UTC")
# A info command
info_parser = subparsers.add_parser('info', help = "This command shows info.")
info_parser.add_argument ("-s", "--server", action = "store_true", help = "Returns server information")
info_parser.add_argument ("-m", "--manager", action = "store_true", help = "Returns manager info")
info_parser.add_argument ("-p", "--power", action = "store_true", help = "Returns manager power/PSU info")
# A health command
health_parser = subparsers.add_parser('health', help = "This command shows manager health.")
health_parser.add_argument('-s', "--server", action = "store_true", help="Returns server health")
health_parser.add_argument('-m', "--memory", action = "store_true", help="Returns Memory Usage")
health_parser.add_argument('-p', "--power", action = "store_true", help="Returns power/PSU health")
health_parser.add_argument('-r', "--sensor", action = "store_true", help="Returns Sensor reading")
# A tftp server commands
tftpstatus_parser = subparsers.add_parser('tftp', help = "This command shows TFTP server info")
tftp_subparser = tftpstatus_parser.add_subparsers (help = "TFTP action", dest = "tftp")
tftp_subparser.add_parser ("status", help = "This command shows TFTP server status")
tftp_subparser.add_parser ("list", help = "This command list files under TFTP location")
# A nfs server commands
nfsstatus_parser = subparsers.add_parser('nfs', help = "This command shows NFS server info")
nfs_subparser = nfsstatus_parser.add_subparsers (help = "NFS action", dest = "nfs")
nfs_subparser.add_parser ("status", help = "This command shows NFS service status")
# Manager session commands
session_parser = subparsers.add_parser('session', help = "This command shows manager open ssh session")
session_subparser = session_parser.add_subparsers (help = "session action", dest = "session")
session_subparser.add_parser ("list", help = "This command shows active manager ssh sessions")
# A attentionledstatus command
subparsers.add_parser('led', help = "This command shows attention led status.")
# Show manager version command
subparsers.add_parser('version', help = "This command shows manager version.")
# A managerInventory command
subparsers.add_parser('inventory', help = "This command shows manger inventory details")
# Log command
log_parser = subparsers.add_parser('log', help = "This command prints chassis log contents")
log_parser.add_argument('-b', dest = 'starttime', help = "Start time to filter by", required = False)
log_parser.add_argument('-e', dest = 'endtime', help = "End time to filter by", required = False)
log_parser.add_argument('-s', dest = 'startid', help = "Start message ID to filter by", required = False)
log_parser.add_argument('-f', dest = 'endid', help = "End message ID to filter by", required = False)
log_parser.add_argument('-l', dest = 'loglevel', help = "Log level to filter by {0-2}", required = False)
log_parser.add_argument('-c', dest = 'component', help = "Component to filter by {0-5}", required = False)
log_parser.add_argument('-i', dest = 'deviceid', help = "Device ID to filter by {1-48}", required = False)
log_parser.add_argument('-p', dest = 'portid', help = "Port ID to filter by {1-48}", required = False)
# NTP service command
ntp_parser = subparsers.add_parser ("ntp", help = "This command shows NTP service info.")
ntp_subparser = ntp_parser.add_subparsers (help ="NTP action", dest ="ntp")
ntp_subparser.add_parser ("status", help = "This command shows NTP service status.")
ntp_subparser.add_parser ("server", help = "This command show the current NTP server.")
# Remote ITP service command
itp_parser = subparsers.add_parser ("itp", help = "This command shows remote ITP service info.")
itp_subparser = itp_parser.add_subparsers (help ="ITP action", dest ="itp")
itp_subparser.add_parser ("status", help = "This command shows ITP service status.")
# PowerMeter Display Commands
powermeter_parser = subparsers.add_parser("powermeter", help = "This command shows powermeter info")
powermeter_subparser = powermeter_parser.add_subparsers(help = "PowerMeter display commands", dest = "powermeter")
powermeter_subparser.add_parser('limit', help = "This command shows power limit policy")
powermeter_subparser.add_parser('alert', help = "This command shows power alert policy")
powermeter_subparser.add_parser('reading', help = "This command shows power reading")
powermeter_subparser.add_parser('version', help = "This command shows PRU version")
# OcsPower Display Commands
ocspower_parser = subparsers.add_parser("power", help = "This command shows ocspower info")
ocspower_subparser = ocspower_parser.add_subparsers(help = "OcsPower display commands", dest = "ocspower")
ocspower_subparser.add_parser('status', help = "This command shows power status")
ocspower_subparser.add_parser('reading', help = "This command shows power reading")
# Throttle control command
throttle_parser = subparsers.add_parser ("throttle", help = "This command shows throttle control status.")
throttle_subparser = throttle_parser.add_subparsers (help ="Throttle display commands", dest ="throttle")
throttle_subparser.add_parser ("local", help = "This command shows local throttle control status.")
# A portstatus command
portstatus_parser = subparsers.add_parser('port', help="This command shows the power port state.")
requiredNamed = portstatus_parser.add_argument_group('required arguments')
requiredNamed.add_argument('-i', dest='port_id', type = int, help='portid (1-48 or 0 for all)', required=True)
# FWUpdate command
fwupdate_parser = subparsers.add_parser('fwupdate', help = "This command shows FWupdate related info")
fwupdate_subparser = fwupdate_parser.add_subparsers (help = "FWUpdate info", dest = "fwupdate")
fwupdate_subparser.add_parser ("status", help = "This command shows status of the most recent firmware update")
fwupdate_subparser.add_parser ("list", help = "This command lists versions of available packages")
if (str(pre_settings.manager_mode) == str(pre_settings.rm_mode_enum.pmdu_rackmanager) or \
str(pre_settings.manager_mode) == str(pre_settings.rm_mode_enum.tfb_dev_benchtop) or \
str(pre_settings.manager_mode) == str(pre_settings.rm_mode_enum.standalone_rackmanager)):
# A showrelay command
relaystatus_parser = subparsers.add_parser('relay', help="This command shows manager relay status.")
requiredNamed = relaystatus_parser.add_argument_group('required arguments')
requiredNamed.add_argument('-p', dest='port_id', choices=['1','2','3','4'], help='portid (1-4)', required=True)
# A showrowfru command
fru_parser = subparsers.add_parser('fru', help="This command shows manager FRU details.")
requiredNamed = fru_parser.add_argument_group('required arguments')
requiredNamed.add_argument('-b', dest='boardname', choices=['mb','pib','acdc'], help='RM board names', default = 'mb')
elif (str(pre_settings.manager_mode) == str(pre_settings.rm_mode_enum.rowmanager)):
# A showrowfru command
fru_parser = subparsers.add_parser('fru', help="This command shows manager FRU details.")
requiredNamed = fru_parser.add_argument_group('required arguments')
requiredNamed.add_argument('-b', dest='boardname', choices=['mb','pib'], help='Row Manger board names', default = 'mb')
# Row manager throttle status
throttle_subparser.add_parser ("row", help = "This command shows row throttle control status.")
#Show boot strap
bootstrp_parser = subparsers.add_parser('boot', help= "This commad shows row manager boot strap status")
strap_subparser = bootstrp_parser.add_subparsers (help ="Boot strap action", dest ="boot")
strap_subparser.add_parser ("strap", help = "This command shows boot strap status.")
requiredNamed = bootstrp_parser.add_argument_group('required arguments')
requiredNamed.add_argument('-i', dest='port_id', type = int, help='portid (1-24)', required=True)
else:
print("unknown mode:",pre_settings.manager_mode)
return None
except Exception, e:
print ("rackmanager_showcommand_options() Exception {0}".format(e))
def rackmanager_setcommand_options(subparsers):
try:
# Time command
time_parser = subparsers.add_parser("time", help = "This command sets manager system time and date")
time_parser.add_argument("-y", dest = "year", type = int, help = "4-digit Year")
time_parser.add_argument("-m", dest = "month", type = int, help = "Numerical Month (1-12)")
time_parser.add_argument("-d", dest = "day", type = int, help = "Numerical Day (1-31)")
time_parser.add_argument("-r", dest = "hour", type = int, help = "Hour (0-23)")
time_parser.add_argument("-n", dest = "min", type = int, help = "Minute (0-59)")
time_parser.add_argument("-s", dest = "sec", type = int, help = "Second (0-59)")
# TFTP server commands
tftp_parser = subparsers.add_parser('tftp', help = "This command executes TFTP server actions")
tftp_subparser = tftp_parser.add_subparsers (help = "TFTP action", dest = "tftp")
tftp_subparser.add_parser ("start", help = "This command starts the TFTP server")
tftp_subparser.add_parser ("stop", help = "This command stop the TFTP server")
tftpdelete_subparser = tftp_subparser.add_parser('delete', help = "This command deletes a file from local TFTP server")
tftpdelete_subparser.add_argument('-f', dest = 'file', type = str, help = 'file to delete', required = True)
tftpget_subparser = tftp_subparser.add_parser('get', help = "This command gets file from TFTP server")
tftpget_subparser.add_argument('-s', dest = 'server', type = str, help = 'TFTP server address', required = True)
tftpget_subparser.add_argument('-f', dest = 'file', type = str, help = 'remote file name with path relative to TFTP root', required = True)
tftpput_subparser = tftp_subparser.add_parser('put', help = "This command puts file to TFTP server")
tftpput_subparser.add_argument('-s', dest = 'server', type = str, help = 'TFTP server address', required = True)
tftpput_subparser.add_argument('-f', dest = 'file', type = str, help = 'remote file name with path relative to TFTP root', required = True)
tftpput_subparser.add_argument('-t', dest = 'target', type = str, help = 'Manager target (auditlog or debuglog or telemetrylog)', required = True)
# Manager session commands
session_parser = subparsers.add_parser('session', help = "This command executes Manager session actions")
session_subparser = session_parser.add_subparsers (help = "session action", dest = "session")
sessionkill_subparser = session_subparser.add_parser ("kill", help = "This command kill the specified manager session")
sessionkill_subparser.add_argument('-s', dest = 'sessionid', type = str, help = 'Manager SSH session id', required = True)
# PowerMeter Action Commands
powermeter_parser = subparsers.add_parser("powermeter", help = "This command executes PowerMeter actions")
powermeter_subparser = powermeter_parser.add_subparsers(help = "PowerMeter action commands", dest = "powermeter")
powermeter_subparser.add_parser('clearmax', help = "This command clears max power")
powermeter_subparser.add_parser('clearfaults', help = "This command clears power faults")
powermeter_limit = powermeter_subparser.add_parser('limit', help = "This command sets the power limit")
powermeter_limit.add_argument('-p', dest = 'powerlimit', metavar = 'powerlimit', type = int, help = 'power limit in watts', required = True)
powermeter_alert = powermeter_subparser.add_parser('alert', help = "This command sets the alert policy")
powermeter_alert.add_argument('-e', dest = 'policy', metavar = 'poweralertpolicy', type = int, help = 'poweralertpolicy (0:disable, 1:enable)', required = True)
powermeter_alert.add_argument('-d', dest = 'dcthrottlepolicy', metavar = 'dcthrottlealertpolicy', type = int, help = 'dcthrottlealertpolicy (0:disable, 1:enable)', required = True)
powermeter_alert.add_argument('-p', dest = 'powerlimit', metavar = 'powerlimit', type = int, help = 'power limit in watts', required= True)
# OcsPower Action Commands
ocspower_parser = subparsers.add_parser("power", help = "This command executes OcsPower actions")
ocspower_subparser = ocspower_parser.add_subparsers(help = "OcsPower action commands", dest = "ocspower")
ocspower_subparser.add_parser('clearfaults', help = "This command clears power faults")
# NFS server commands
nfs_parser = subparsers.add_parser('nfs', help = "This command executes NFS server actions")
nfs_subparser = nfs_parser.add_subparsers (help = "NFS action", dest = "nfs")
nfs_subparser.add_parser ("start", help = "This command starts the NFS server")
nfs_subparser.add_parser ("stop", help = "This command stop the NFS server")
# A attentionledon/off command
attentionledon_parser = subparsers.add_parser('led', help = "Manager attention led commands.")
led_subparser = attentionledon_parser.add_subparsers (help ="LED action", dest ="led")
led_subparser.add_parser ("on", help = "This command sets attention led on.")
led_subparser.add_parser("off", help = "This command sets attention led off.")
# A Setporton / off command
port_parser = subparsers.add_parser('port', help='Manager port command')
set_subparser = port_parser.add_subparsers(help = "portaction", dest = "port")
port_on_subparser = set_subparser.add_parser("on", help = "This command turns the AC outlet power ON for the server/Rack")
requiredNamed = port_on_subparser.add_argument_group('required arguments')
requiredNamed.add_argument('-i', dest='port_id', metavar='port-id', type =int, help='port-id (1 to 48)', required=True)
# A setpoweroff command
setportoff_parser = set_subparser.add_parser('off', help='This command turns the AC outlet power OFF for the server/Rack')
requiredNamed = setportoff_parser.add_argument_group('required arguments')
requiredNamed.add_argument('-i', dest='port_id', metavar='port-id', type =int, help='port-id (1 to 48)', required=True)
# FWUpdate command
fwupdate_parser = subparsers.add_parser('fwupdate', help = 'This command starts a FW update using provided patch file')
fwupdate_parser.add_argument('-f', dest = 'file', help = 'Update file path', required = True)
# Clear Log command
log_parser = subparsers.add_parser('log', help = "This command executes log actions")
log_subparser = log_parser.add_subparsers (help = "Log action", dest = "log")
log_subparser.add_parser ("clear", help = "This command clears all log entries")
# NTP service commands
ntp_parser = subparsers.add_parser ("ntp", help = "This command controls the NTP service.")
ntp_subparser = ntp_parser.add_subparsers (help ="NTP action", dest ="ntp")
ntp_subparser.add_parser ("start", help = "This command starts the NTP service.")
ntp_subparser.add_parser ("stop", help = "This command stops the NTP service.")
ntp_subparser.add_parser ("restart", help = "This command restarts the NTP service.")
ntp_subparser.add_parser ("enable", help = "This command will enable the NTP service.")
ntp_subparser.add_parser ("disable", help = "This command will disable the NTP service.")
server_parser = ntp_subparser.add_parser ("server", help = "This command sets the NTP server.")
server_parser.add_argument ("-s", dest = "server", help = "NTP server address", required = True)
# Remate ITP service commands
itp_parser = subparsers.add_parser ("itp", help = "This command controls the remote ITP service.")
itp_subparser = itp_parser.add_subparsers (help ="ITP action", dest ="itp")
itp_subparser.add_parser ("start", help = "This command starts the ITP service.")
itp_subparser.add_parser ("stop", help = "This command stops the ITP service.")
itp_subparser.add_parser ("restart", help = "This command restarts the ITP service.")
itp_subparser.add_parser ("enable", help = "This command will enable the ITP service.")
itp_subparser.add_parser ("disable", help = "This command will disable the ITP service.")
# Change the hostname
hostname_parser = subparsers.add_parser ("hostname", help = "This command sets the hostname.")
hostname_parser.add_argument ("-n", dest = "hostname", help = "Hostname", required = True)
# Throttle control commands
throttle_parser = subparsers.add_parser ("throttle", help = "This command controls the throttle configuration.")
throttle_subparser = throttle_parser.add_subparsers (help = "Throttle action", dest = "throttle")
local_parser = throttle_subparser.add_parser ("local", help = "This command controls local throttle configuration.")
local_subparser = local_parser.add_subparsers (help = "Local throttle action", dest = "gpio")
throttle_arg = local_subparser.add_parser ("bypass", help = "This command controls the local throttle bypass.")
requiredNamed = throttle_arg.add_argument_group ("required arguments")
requiredNamed.add_argument ("-e", dest = "state", choices = [0, 1], type = int, help = "Disable (0)/Enable (1)", required = True)
throttle_arg = local_subparser.add_parser ("enable", help = "This command controls the local throttle output enable.")
requiredNamed = throttle_arg.add_argument_group ("required arguments")
requiredNamed.add_argument ("-e", dest = "state", choices = [0, 1], type = int, help = "Disable (0)/Enable (1)", required = True)
if (str(pre_settings.manager_mode) == str(pre_settings.rm_mode_enum.pmdu_rackmanager) or \
str(pre_settings.manager_mode) == str(pre_settings.rm_mode_enum.tfb_dev_benchtop) or \
str(pre_settings.manager_mode) == str(pre_settings.rm_mode_enum.standalone_rackmanager)):
# A setrelayon/off command
relay_parser = subparsers.add_parser('relay', help="Manager relay commands.")
set_relay_subparser = relay_parser.add_subparsers (help ="relay action", dest ="relay")
relayon_parser = set_relay_subparser.add_parser("on", help = "This command turns Rack Manger AC socket ON.")
requiredNamed = relayon_parser.add_argument_group('required arguments')
requiredNamed.add_argument('-p', dest='port_id', choices=['1','2','3','4'], help='portid (1-4)', required=True)
relayoff_parser = set_relay_subparser.add_parser('off', help="This command turns Rack Manger AC socket OFF.")
requiredNamed = relayoff_parser.add_argument_group('required arguments')
requiredNamed.add_argument('-p', dest='port_id', choices=['1','2','3','4'], help='portid (1-4)', required=True)
# A writefru command
writefru_parser = subparsers.add_parser('fru', help="This command is used to update the Rack Manger FRU information.")
requiredNamed = writefru_parser.add_argument_group('required arguments')
requiredNamed.add_argument('-b', dest='boardname', choices=['mb','pib','acdc'], help='Rack Manager board name', required=True)
requiredNamed.add_argument('-f', dest='filename', help='fru file path', required=True)
elif (str(pre_settings.manager_mode) == str(pre_settings.rm_mode_enum.rowmanager)):
# A writefru command
writefru_parser = subparsers.add_parser('fru', help="This command is used to update the Row Manger FRU information.")
requiredNamed = writefru_parser.add_argument_group('required arguments')
requiredNamed.add_argument('-b', dest='boardname', choices=['mb','pib'], help='Row Manager board name', required=True)
requiredNamed.add_argument('-f', dest='filename', help='fru file path', required=True)
# Row manager throttle control
row_parser = throttle_subparser.add_parser ("row", help = "This command controls row throttle configuration.")
row_subparser = row_parser.add_subparsers (help = "Row throttle action", dest = "gpio")
throttle_arg = row_subparser.add_parser ("bypass", help = "This command controls the row throttle bypass.")
requiredNamed = throttle_arg.add_argument_group ("required arguments")
requiredNamed.add_argument ("-e", dest = "state", choices = [0, 1], type = int, help = "Disable (0)/Enable (1)", required = True)
throttle_arg = row_subparser.add_parser ("enable", help = "This command controls the row throttle output enable.")
requiredNamed = throttle_arg.add_argument_group ("required arguments")
requiredNamed.add_argument ("-e", dest = "state", choices = [0, 1], type = int, help = "Disable (0)/Enable (1)", required = True)
#set boot strap
bootstrp_parser = subparsers.add_parser('recovery', help= "This commad turns Rack Manager ON or OFF")
requiredNamed = bootstrp_parser.add_argument_group('required arguments')
requiredNamed.add_argument('-i', dest='port_id', type = int, help='portid (1-24)', required=True)
set_reset_subparser = bootstrp_parser.add_subparsers (help ="reset action", dest ="reset")
set_reset_subparser.add_parser("on", help = "This command turns OFF Rack Manger.")
set_reset_subparser.add_parser("off", help = "This command turns ON Rack Manger.")
else:
print("unknow mode:",pre_settings.manager_mode)
return None
except Exception, e:
print ("rackmanager_setcommand_options() Exception {0}".format(e))
def rackmanager_showcommands(args):
try:
rackmanager = getrackmanager()
manager_mode = get_mode()
request = {}
request["action"] = args.command
request["mode"] = "display"
if(args.command == "port" or args.command == "relay"):
request["port_id"] = args.port_id
elif args.command == "inventory":
if manager_mode == None:
print_response(set_failure_dict("Invalid manager mode",completion_code.failure))
return
request["rm_mode"] = manager_mode
elif(args.command == "log"):
if args.starttime:
request['starttime'] = args.starttime
if args.endtime:
request['endtime'] = args.endtime
if args.startid:
request['startid'] = args.startid
if args.endid:
request['endid'] = args.endid
if args.component:
request['component'] = args.component
if args.loglevel:
request['loglevel'] = args.loglevel
if args.deviceid:
request['deviceid'] = args.deviceid
if args.portid:
request['port_id'] = args.portid
elif args.command == "info":
if manager_mode == None:
print_response(set_failure_dict("Invalid manager mode",completion_code.failure))
return
request["server"] = args.server
request["manager"] = args.manager
request["power"] = args.power
request["rm_mode"] = manager_mode
elif args.command == "health":
if manager_mode == None:
print_response(set_failure_dict("Invalid manager mode",completion_code.failure))
return
request["server"] = args.server
request["memory"] = args.memory
request["power"] = args.power
request["sensor"] = args.sensor
request["rm_mode"] = manager_mode
elif(args.command == "fru") or (args.command == "info"):
board_name = mode_request()
if board_name == None:
print_response(set_failure_dict("board_name is empty",completion_code.failure))
return
if args.command == "fru":
request["boardname"] = board_name + '_' + args.boardname
else:
if board_name == "rm":
request["boardname"] = "Rack"
else:
request["boardname"] = "Row"
elif (args.command == "ntp"):
request["action"] = args.command + args.ntp.lower()
elif (args.command == "nfs"):
request["action"] = args.command + args.nfs.lower()
elif (args.command == "tftp"):
request["action"] = args.command + args.tftp.lower()
elif (args.command == "itp"):
request["action"] = args.command + args.itp.lower()
elif (args.command == "throttle"):
request["action"] = args.command + args.throttle.lower()
elif (args.command == "session"):
request["action"] = args.command + args.session.lower()
elif (args.command == "boot"):
request["action"] = args.command + args.boot.lower()
request["port_id"] = args.port_id
elif (args.command == "fwupdate"):
request["action"] = args.command + args.fwupdate.lower()
if args.command == "powermeter":
powermeter = get_powermeter()
request["action"] = args.powermeter.lower()
info = powermeter.doWorks(request)
elif args.command == "power":
request["action"] = "manager" + args.ocspower.lower()
info = system_ocspower_display(-1, request)
else:
info = rackmanager.doWorks(request)
if (args.command == "info" and args.manager == False and args.power == False) or \
(args.command == "info" and args.server == True and args.manager == True and args.power == True) or \
(args.command == "health" and args.memory == False and args.power == False and args.sensor == False) or \
(args.command == "health" and args.server == True and args.memory == True and args.power == True and args.sensor == True):
print_health_info(args,info)
elif (args.command == "port" and args.port_id == 0):
print_all_port_info(info)
elif args.command == "inventory":
if (completion_code.cc_key in info.keys()) and (info[completion_code.cc_key] == completion_code.success):
info.pop(completion_code.cc_key, None)
print_inventory_data(info)
print completion_code.cc_key + ":" + completion_code.success
else:
print_response(info)
else:
print_response(info)
except Exception, e:
print_response(set_failure_dict(("rackmanager_showcommands() - Exception {0}".format(e)), completion_code.failure))
def print_inventory_data(info):
try:
inventory_list = []
for k, v in info.iteritems():
if isinstance(v, dict):
inventory_list.append(v.values())
print ("| Slot Id | Port State | Port Present | BMC SW Port | MAC1 | GUID ")
for item in inventory_list:
print"|",item[0]," "*(6-len(str(item[0]))),"|", \
item[1]," "*(9-len(item[1])),"|", \
item[2]," "*(11-len(item[2])),"|", \
item[3]," "*(10-len(str(item[3]))),"|", \
item[4]," "*(12-len(item[4])),"|", \
item[5]," "*(12-len(item[5]))
except Exception, e:
print_response(set_failure_dict(("exception ", e),completion_code.failure))
def print_all_port_info(info):
try:
for key in info:
info[key].pop(completion_code.cc_key, None)
port_id = "Port Id: {0}".format(key)
result = "".join(str(key) + ':' + ' ' + str(value) + tab for key,value in info[key].items())
print port_id + "\t" + result
print completion_code.cc_key + ": {0}".format(completion_code.success)
except Exception, e:
print_response(set_failure_dict(("exception ", e),completion_code.failure))
def print_health_info(args,info):
try:
if type(info) == str:
print_response(set_failure_dict(info, completion_code.failure))
completioncode = ""
if (args.command == "info" and args.server == True and args.manager == False and args.power == False) or \
(args.command == "health" and args.server == True and args.memory == False and args.power == False and args.sensor == False):
try:
for key in info:
if key == completion_code.desc:
print_response(info)
return
if key == completion_code.cc_key:
completioncode = info[key]
continue
guid = info[key].pop('GUID', None)
mac = info[key].pop('MAC', None)
result = "".join(str(key) + ':' + ' ' + str(value) + tab for key,value in info[key].items())
print result
if guid != None and mac != None:
print "GUID" + ':' + guid + tab + "MAC" + ': ' + mac
print'\n'
except Exception, e:
print_response(set_failure_dict(("exception ", e),completion_code.failure))
print completion_code.cc_key + ": {0}".format(completioncode)
return
elif args.command == "info" or args.command == "health":
if completion_code.cc_key in info:
completioncode = info.pop(completion_code.cc_key,None)
server_coll = {}
if args.command == "info":
server_coll = info.pop('Server Info', None)
print_response(info)
print tab + "Server Info:"
if args.command == "health":
server_coll = info.pop('Server State', None)
print_response(info)
print tab + "Server State:"
for key in server_coll:
if key == completion_code.desc:
print_response(server_coll);
else:
guid = server_coll[key].pop('GUID', None)
mac = server_coll[key].pop('MAC', None)
result = "".join(tab + str(key) + ':' + ' ' + str(value) + tab for key,value in server_coll[key].items())
print result
if guid != None and mac != None:
print tab + "GUID" + ':' + guid + tab + "MAC" + ': ' + mac
print'\n'
print tab + completion_code.cc_key + ": {0}".format(completioncode)
return
except Exception,e:
print_response(set_failure_dict(("exception to print", e), completion_code.failure))
def rackmanager_setcommands(args):
try:
rackmanager = getrackmanager()
request = {}
request["action"] = args.command
request["mode"] = "action"
if args.command == "relay":
request["action"] = args.command + args.relay.lower()
request['port_id'] = args.port_id
elif args.command == "port":
request["action"] = args.command + args.port.lower()
request['port_id'] = args.port_id
elif args.command == "fru":
board_name = mode_request()
if board_name == None:
print_response(set_failure_dict("board_name is empty", completion_code.failure))
return
request["boardname"] = board_name + '_' + args.boardname
request['file'] = args.filename
elif args.command == "ntp":
request["action"] = args.command + args.ntp.lower()
if args.ntp == "server":
request["server"] = args.server
elif args.command == "hostname":
request["hostname"] = args.hostname
elif args.command == "led":
request["action"] = args.command + args.led.lower()
elif args.command == "fwupdate":
request["file"] = args.file
elif args.command == "nfs":
request["action"] = args.command + args.nfs.lower()
elif args.command == "tftp":
request["action"] = args.command + args.tftp.lower()
elif args.command == "session":
request["action"] = args.command + args.session.lower()
elif args.command == "itp":
request["action"] = args.command + args.itp.lower()
elif args.command == "log":
request["action"] = args.log.lower() + args.command
elif args.command == "throttle":
request["action"] = args.command + args.throttle.lower() + args.gpio.lower()
request["enable"] = True if (args.state == 1) else False
elif args.command == "recovery":
request["action"] = args.command + args.recovery.lower()
request['port_id'] = args.port_id
elif request["action"] == "time":
if args.year:
request["year"] = args.year
if args.month:
request["month"] = args.month
if args.day:
request["day"] = args.day
if args.hour:
request["hour"] = args.hour
if args.min:
request["min"] = args.min
if args.sec:
request["sec"] = args.sec
if request["action"] == "tftpget":
request["server"] = args.server
request["file"] = args.file
elif request["action"] == "tftpput":
request["server"] = args.server
request["file"] = args.file
request["target"] = args.target
elif request["action"] == "tftpdelete":
request["file"] = args.file
elif request["action"] == "sessionkill":
request["sessionid"] = args.sessionid
if args.command == "powermeter":
powermeter = get_powermeter()
request["action"] = args.powermeter.lower()
if args.powermeter == "alert":
request["policy"] = args.policy
request["dcthrottlepolicy"] = args.dcthrottlepolicy
request["powerlimit"] = args.powerlimit
elif args.powermeter == "limit":
request["powerlimit"] = args.powerlimit
info = powermeter.doWorks(request)
elif args.command == "power":
request["action"] = "manager" + args.ocspower.lower()
info = system_ocspower_action(-1, request)
else:
info = rackmanager.doWorks(request)
print_response(info)
except Exception, e:
print_response(set_failure_dict(("rackmanager_setcommands() - Exception {0}".format(e)), completion_code.failure))
|
import math
import glob
import os
import sys
import cv2
import numpy as np
class PreProcess():
def deskew(self, img):
gray = cv2.bitwise_not(img)
# threshold the image, setting all foreground pixels to
# 255 and all background pixels to 0
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
# grab the (x, y) coordinates of all pixel values that
# are greater than zero, then use these coordinates to
# compute a rotated bounding box that contains all
# coordinates
coords = np.column_stack(np.where(thresh > 0))
angle = cv2.minAreaRect(coords)[-1]
# the `cv2.minAreaRect` function returns values in the
# range [-90, 0); as the rectangle rotates clockwise the
# returned angle trends to 0 -- in this special case we
# need to add 90 degrees to the angle
if angle < -45:
angle = -(90 + angle)
# otherwise, just take the inverse of the angle to make
# it positive
else:
angle = -angle
# rotate the image to deskew it
(h, w) = img.shape[:2]
center = (w // 2, h // 2)
M = cv2.getRotationMatrix2D(center, angle, 1.0)
rotated = cv2.warpAffine(img, M, (w, h), flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE)
return rotated, angle |
import logging
import vivisect
import vivisect.exc as v_exc
import vivisect.impemu.monitor as viv_monitor
import vivisect.analysis.generic.codeblocks as viv_cb
import envi
import envi.archs.arm as e_arm
from envi.archs.arm.regs import *
from envi.archs.arm.const import *
from vivisect.const import *
logger = logging.getLogger(__name__)
class AnalysisMonitor(viv_monitor.AnalysisMonitor):
def __init__(self, vw, fva, verbose=True):
viv_monitor.AnalysisMonitor.__init__(self, vw, fva)
self.retbytes = None
self.badops = vw.arch.archGetBadOps()
self.last_lr_pc = 0
self.strictops = False
self.returns = False
self.infloops = []
self.switchcases = 0
def prehook(self, emu, op, starteip):
try:
tmode = emu.getFlag(PSR_T_bit)
self.last_tmode = tmode
if op in self.badops:
emu.stopEmu()
raise v_exc.BadOpBytes(op.va)
viv_monitor.AnalysisMonitor.prehook(self, emu, op, starteip)
loctup = emu.vw.getLocation(starteip)
if loctup is None:
# logger.debug("emulation: prehook: new LOC_OP fva: 0x%x starteip: 0x%x flags: 0x%x", self.fva, starteip, op.iflags)
arch = (envi.ARCH_ARMV7, envi.ARCH_THUMB)[(starteip & 1) | tmode]
emu.vw.makeCode(starteip & -2, arch=arch)
elif loctup[2] != LOC_OP:
logger.info("ARG! emulation found opcode in an existing NON-OPCODE location (0x%x): 0x%x: %s", loctup[0], op.va, op)
emu.stopEmu()
elif loctup[0] != starteip:
logger.info("ARG! emulation found opcode in a location at the wrong address (0x%x): 0x%x: %s", loctup[0], op.va, op)
emu.stopEmu()
if op.iflags & envi.IF_RET:
self.returns = True
if len(op.opers):
if hasattr(op.opers, 'imm'):
self.retbytes = op.opers[0].imm
# ARM gives us nice switchcase handling instructions
# FIXME: wrap TB-handling into getBranches(emu) which is called by checkBranches during emulation
if op.opcode in (INS_TBH, INS_TBB):
if emu.vw.getVaSetRow('SwitchCases', op.va) is None:
base, tbl = analyzeTB(emu, op, starteip, self)
if None not in (base, tbl):
count = len(tbl)
self.switchcases += 1
emu.vw.setVaSetRow('SwitchCases', (op.va, op.va, count))
elif op.opcode == INS_MOV:
if len(op.opers) >= 2:
oper0 = op.opers[0]
oper1 = op.opers[1]
if isinstance(oper0, e_arm.ArmRegOper) and oper0.reg == REG_LR:
if isinstance(oper1, e_arm.ArmRegOper) and oper1.reg == REG_PC:
self.last_lr_pc = starteip
elif op.opcode == INS_BX:
if starteip - self.last_lr_pc <= 4:
# this is a call. the compiler updated lr
logger.info("CALL by mov lr, pc; bx <foo> at 0x%x", starteip)
tgtva = op.opers[-1].getOperValue(op)
self.vw.makeFunction(tgtva)
elif op.opcode == INS_ADD and op.opers[0].reg == REG_PC:
# simple branch code
if emu.vw.getVaSetRow('SwitchCases', op.va) is None:
base, tbl = analyzeADDPC(emu, op, starteip, self)
if None not in (base, tbl):
count = len(tbl)
self.switchcases += 1
emu.vw.setVaSetRow('SwitchCases', (op.va, op.va, count))
elif op.opcode == INS_SUB and isinstance(op.opers[0], e_arm.ArmRegOper) and op.opers[0].reg == REG_PC:
# simple branch code
if emu.vw.getVaSetRow('SwitchCases', op.va) is None:
base, tbl = analyzeSUBPC(emu, op, starteip, self)
if None not in (base, tbl):
count = len(tbl)
self.switchcases += 1
emu.vw.setVaSetRow('SwitchCases', (op.va, op.va, count))
if op.iflags & envi.IF_BRANCH:
try:
tgt = op.getOperValue(0, emu)
if tgt == op.va:
logger.info("0x%x: +++++++++++++++ infinite loop +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++", op.va)
if op.va not in self.infloops:
self.infloops.append(op.va)
if 'InfiniteLoops' not in self.vw.getVaSetNames():
self.vw.addVaSet('InfiniteLoops', (('va', vivisect.VASET_ADDRESS, 'function', vivisect.VASET_STRING)))
self.vw.setVaSetRow('InfiniteLoops', (op.va, self.fva))
except Exception as e:
self.logAnomaly(emu, self.fva, "0x%x: (%r) ERROR: %s" % (op.va, op, e))
logger.info("0x%x: (%r) ERROR: %s", op.va, op, e)
except v_exc.BadOpBytes:
raise
except Exception as e:
self.logAnomaly(emu, self.fva, "0x%x: (%r) ERROR: %s" % (op.va, op, e))
logger.warning("0x%x: (%r) ERROR: %s", op.va, op, e)
def posthook(self, emu, op, starteip):
if op.opcode == INS_BLX:
emu.setFlag(PSR_T_bit, self.last_tmode)
argnames = {
0: ('r0', 0),
1: ('r1', 1),
2: ('r2', 2),
3: ('r3', 3),
}
def archargname(idx):
ret = argnames.get(idx)
if ret is None:
name = 'arg%d' % idx
else:
name, idx = ret
return name
def buildFunctionApi(vw, fva, emu, emumon):
argc = 0
funcargs = []
callconv = vw.getMeta('DefaultCall')
undefregs = set(emu.getUninitRegUse())
for argnum in range(len(argnames), 0, -1):
argname, argid = argnames[argnum-1]
if argid in undefregs:
argc = argnum
break
if callconv == 'armcall':
if emumon.stackmax > 0:
targc = (emumon.stackmax >> 3) + 6
if targc > 40:
emumon.logAnomaly(emu, fva, 'Crazy Stack Offset Touched: 0x%.8x' % emumon.stackmax)
else:
argc = targc
funcargs = [('int', archargname(i)) for i in range(argc)]
api = ('int', None, callconv, None, funcargs)
vw.setFunctionApi(fva, api)
return api
def analyzeFunction(vw, fva):
emu = vw.getEmulator(va=fva)
emumon = AnalysisMonitor(vw, fva)
emu.setEmulationMonitor(emumon)
loc = vw.getLocation(fva)
if loc is not None:
lva, lsz, lt, lti = loc
if lt == LOC_OP:
if (lti & envi.ARCH_MASK) != envi.ARCH_ARMV7:
emu.setFlag(PSR_T_bit, 1)
else:
logger.warning("NO LOCATION at FVA: 0x%x", fva)
emu.runFunction(fva, maxhit=1)
# Do we already have API info in meta?
# NOTE: do *not* use getFunctionApi here, it will make one!
api = vw.getFunctionMeta(fva, 'api')
if api is None:
api = buildFunctionApi(vw, fva, emu, emumon)
rettype,retname,callconv,callname,callargs = api
argc = len(callargs)
cc = emu.getCallingConvention(callconv)
if cc is None:
return
stcount = cc.getNumStackArgs(emu, argc)
stackidx = argc - stcount
baseoff = cc.getStackArgOffset(emu, argc)
# Register our stack args as function locals
for i in range(stcount):
vw.setFunctionLocal(fva, baseoff + ( i * 4 ), LSYM_FARG, i+stackidx)
emumon.addAnalysisResults(vw, emu)
# handle infinite loops (actually, while 1;)
# switch-cases may have updated codeflow. reanalyze
viv_cb.analyzeFunction(vw, fva)
# logger.debug("-- Arm EMU fmod: 0x%x" % fva)
# TODO: incorporate some of emucode's analysis but for function analysis... if it makes sense.
def analyzeTB(emu, op, starteip, amon):
######################### FIXME: ADD THIS TO getBranches(emu)
### DEBUGGING
#raw_input("\n\n\nPRESS ENTER TO START TB: 0x%x" % op.va)
logger.debug("\n\nTB at 0x%x", starteip)
tsize = op.opers[0].tsize
tbl = []
basereg = op.opers[0].base_reg
if basereg != REG_PC:
base = emu.getRegister(basereg)
else:
base = op.opers[0].va
logger.debug("\nbase: 0x%x", base)
val0 = emu.readMemValue(base, tsize)
if val0 > 0x100 + base:
logger.debug("ummmm.. Houston we got a problem. first option is a long ways beyond BASE")
va = base
while va < base + val0:
nextoff = emu.readMemValue(va, tsize) * 2
logger.debug("0x%x: -> 0x%x", va, nextoff + base)
if nextoff == 0:
logging.debug("Terminating TB at 0-offset")
break
if nextoff > 0x500:
logging.debug("Terminating TB at LARGE - offset (may be too restrictive): 0x%x", nextoff)
break
loc = emu.vw.getLocation(va)
if loc is not None:
logger.debug("Terminating TB at Location/Reference")
logger.debug("%x, %d, %x, %r", loc)
break
tbl.append((va, nextoff))
va += tsize
logger.debug("%s: \n\t", op.mnem + '\n\t'.join(['0x%x (0x%x)' % (x, base + x) for v,x in tbl]))
###
# for workspace emulation analysis, let's check the index register for sanity.
idxreg = op.opers[0].offset_reg
idx = emu.getRegister(idxreg)
if idx > 0x40000000:
emu.setRegister(idxreg, 0) # args handed in can be replaced with index 0
jmptblbase = op.opers[0]._getOperBase(emu)
jmptblval = emu.getOperAddr(op, 0)
jmptbltgt = (emu.getOperValue(op, 0) * 2) + base
logger.debug("0x%x: %r\njmptblbase: 0x%x\njmptblval: 0x%x\njmptbltgt: 0x%x", op.va, op, jmptblbase, jmptblval, jmptbltgt)
#raw_input("PRESS ENTER TO CONTINUE")
# make numbers and xrefs and names
emu.vw.addXref(op.va, base, REF_DATA)
emu.vw.makeName(op.va, 'br_tbl_%x' % op.va)
case = 0
for ova, nextoff in tbl:
nexttgt = base + nextoff
emu.vw.makeNumber(ova, 2)
# check for loc first?
if nexttgt & 1:
nexttgt &= -2
arch = envi.ARCH_THUMB
else:
arch = envi.ARCH_ARMV7
emu.vw.makeCode(nexttgt, arch=arch)
# check xrefs fist?
emu.vw.addXref(op.va, nexttgt, REF_CODE)
curname = emu.vw.getName(nexttgt)
if curname is None:
emu.vw.makeName(nexttgt, "case_%x_%x_%x" % (case, op.va, nexttgt))
else:
emu.vw.vprint("case_%x_%x_%x conflicts with existing name: %r" % (case, op.va, nexttgt, curname))
case += 1
return base, tbl
def analyzeADDPC(emu, op, starteip, emumon):
count = None
reg = op.opers[-1].reg
cb = emu.vw.getCodeBlock(op.va)
if cb is None:
return None, None
cbva, cbsz, cbfva = cb
off = 0
while off < cbsz:
top = emu.vw.parseOpcode(cbva+off)
if top.opcode == INS_CMP:
# make sure this is a comparison for this register.
# the comparison should be the size of the switch-case
for opidx in range(len(top.opers)):
oper = top.opers[opidx]
if isinstance(oper, e_arm.ArmRegOper):
if oper.reg != reg:
continue
#logger.debug("cmp op: ", top)
cntoidx = (1,0)[opidx]
cntoper = top.opers[cntoidx]
#logger.debug("cntoper: %d, %r %r" % (cntoidx, cntoper, vars(cntoper)))
count = cntoper.getOperValue(top, emu)
#logger.debug("count = ", count)
off += len(top)
if not count or count is None or count > 10000:
return None, None
#logger.debug("Making ADDPC SwitchCase (count=%d):" % count)
# wire up the switch-cases, name each one, etc...
tbl = []
for x in range(count):
base = op.opers[-2].getOperValue(op, emu)
base_reg = op.opers[-1].reg
emu.setRegister(base_reg, x)
idx = op.opers[-1].getOperValue(op, emu)
nexttgt = base + idx
#logger.debug("x=%x, base=%x, idx=%x (%x) %r %r %d" % (x,base,idx, nexttgt, op, op.opers, emu.getRegister(op.opers[-1].reg)))
tbl.append((base+idx, x))
emu.vw.makeCode(nexttgt)
emu.vw.addXref(starteip, nexttgt, REF_CODE)
curname = emu.vw.getName(nexttgt)
if curname is None:
emu.vw.makeName(nexttgt, "case_%x_%x_%x" % (x, starteip, nexttgt))
else:
emu.vw.vprint("case_%x_%x_%x conflicts with existing name: %r" % (x, starteip, nexttgt, curname))
return base, tbl
def analyzeSUBPC(emu, op, starteip, emumon):
count = None
cb = emu.vw.getCodeBlock(op.va)
if cb is None:
return None, None
off = 0
reg = op.opers[1].reg
cbva, cbsz, cbfva = cb
while off < cbsz:
top = emu.vw.parseOpcode(cbva+off)
if top.opcode == INS_CMP:
# make sure this is a comparison for this register.
# the comparison should be the size of the switch-case
for opidx in range(len(top.opers)):
oper = top.opers[opidx]
if isinstance(oper, e_arm.ArmRegOper):
if oper.reg != reg:
continue
#logger.debug("cmp op: ", top)
cntoidx = (1,0)[opidx]
cntoper = top.opers[cntoidx]
#logger.debug("cntoper: %d, %r %r" % (cntoidx, cntoper, vars(cntoper)))
count = cntoper.getOperValue(top, emu)
#logger.debug("count = ", count)
off += len(top)
if not count or count is None or count > 10000:
return None, None
#logger.debug("Making SUBPC SwitchCase (count=%d):" % count)
# wire up the switch-cases, name each one, etc...
tbl = []
base = op.opers[-2].getOperValue(op, emu)
base_reg = op.opers[1].reg
for x in range(count):
emu.setRegister(base_reg, x)
idx = op.opers[-1].getOperValue(op, emu)
nexttgt = base - idx
#logger.debug("x=%x, base=%x, idx=%x (%x) %r %r %d" % (x,base,idx, nexttgt, op, op.opers, emu.getRegister(op.opers[-1].reg)))
tbl.append((base+idx, x))
emu.vw.makeCode(nexttgt)
emu.vw.addXref(starteip, nexttgt, REF_CODE)
curname = emu.vw.getName(nexttgt)
if curname is None:
emu.vw.makeName(nexttgt, "case_%x_%x_%x" % (x, starteip, nexttgt))
else:
emu.vw.vprint("case_%x_%x_%x conflicts with existing name: %r" % (x, starteip, nexttgt, curname))
return base, tbl
|
# This file is part of the Data Cleaning Library (openclean).
#
# Copyright (C) 2018-2021 New York University.
#
# openclean is released under the Revised BSD License. See file LICENSE for
# full license details.
"""Unit tests for the mapping operator."""
from openclean.function.value.mapping import mapping, Standardize
def test_simple_mapping(employees):
"""Test creating a mapping over a single column."""
names = mapping(employees, 'Name', str.upper)
assert len(names) == 7
for key, value in names.items():
assert key.upper() == value
def test_value_standardization():
"""Test standardizing values in a list using a mapping dictionary."""
values = ['A', 'B', 'C', 'D']
result = Standardize({'A': 'B', 'B': 'C'}).prepare(values).apply(values)
assert result == ['B', 'C', 'C', 'D']
|
import datetime
import db_helpers
class Event:
def __init__(self, email, event_type, timestamp):
self.email = email
self.event_type = event_type
self.timestamp = timestamp
def create_event(db, email, event_type):
event_timestamp = datetime.datetime.utcnow().isoformat()
# put together the query
q_str = db_helpers.insert_into_string(
TABLE_NAME,
[FIELD_EMAIL, FIELD_EVENTTYPE, FIELD_TIMESTAMP])
c = db.cursor()
c.execute(q_str, [email, event_type, event_timestamp])
db.commit()
########
# Defs #
########
TABLE_NAME = 'km_events'
FIELD_EVENTID = 'event_id'
FIELD_EMAIL = 'email'
FIELD_EVENTTYPE = 'event_type'
FIELD_TIMESTAMP = 'event_timestamp'
|
import sys
#This is a table lookup for all "flush" hands (e.g. both
#flushes and straight-flushes. entries containing a zero
#mean that combination is not possible with a five-card
#flush hand.
flushes=[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 1599, 0, 0, 0, 0, 0, 0, 0, 1598, 0, 0, 0, 1597, 0, 1596,
8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1595, 0, 0, 0,
0, 0, 0, 0, 1594, 0, 0, 0, 1593, 0, 1592, 1591, 0, 0, 0, 0, 0, 0,
0, 0, 1590, 0, 0, 0, 1589, 0, 1588, 1587, 0, 0, 0, 0, 1586, 0,
1585, 1584, 0, 0, 1583, 1582, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 1581, 0, 0, 0, 0, 0, 0, 0, 1580, 0, 0, 0,
1579, 0, 1578, 1577, 0, 0, 0, 0, 0, 0, 0, 0, 1576, 0, 0, 0, 1575,
0, 1574, 1573, 0, 0, 0, 0, 1572, 0, 1571, 1570, 0, 0, 1569, 1568,
0, 1567, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1566, 0, 0, 0, 1565, 0,
1564, 1563, 0, 0, 0, 0, 1562, 0, 1561, 1560, 0, 0, 1559, 1558, 0,
1557, 0, 0, 0, 0, 0, 0, 1556, 0, 1555, 1554, 0, 0, 1553, 1552, 0,
1551, 0, 0, 0, 0, 1550, 1549, 0, 1548, 0, 0, 0, 6, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1547, 0, 0, 0,
0, 0, 0, 0, 1546, 0, 0, 0, 1545, 0, 1544, 1543, 0, 0, 0, 0, 0, 0,
0, 0, 1542, 0, 0, 0, 1541, 0, 1540, 1539, 0, 0, 0, 0, 1538, 0,
1537, 1536, 0, 0, 1535, 1534, 0, 1533, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 1532, 0, 0, 0, 1531, 0, 1530, 1529, 0, 0, 0, 0, 1528, 0, 1527,
1526, 0, 0, 1525, 1524, 0, 1523, 0, 0, 0, 0, 0, 0, 1522, 0, 1521,
1520, 0, 0, 1519, 1518, 0, 1517, 0, 0, 0, 0, 1516, 1515, 0, 1514,
0, 0, 0, 1513, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1512, 0,
0, 0, 1511, 0, 1510, 1509, 0, 0, 0, 0, 1508, 0, 1507, 1506, 0, 0,
1505, 1504, 0, 1503, 0, 0, 0, 0, 0, 0, 1502, 0, 1501, 1500, 0, 0,
1499, 1498, 0, 1497, 0, 0, 0, 0, 1496, 1495, 0, 1494, 0, 0, 0,
1493, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1492, 0, 1491, 1490, 0, 0,
1489, 1488, 0, 1487, 0, 0, 0, 0, 1486, 1485, 0, 1484, 0, 0, 0,
1483, 0, 0, 0, 0, 0, 0, 0, 0, 1482, 1481, 0, 1480, 0, 0, 0, 1479,
0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1478, 0, 0, 0, 0,
0, 0, 0, 1477, 0, 0, 0, 1476, 0, 1475, 1474, 0, 0, 0, 0, 0, 0, 0,
0, 1473, 0, 0, 0, 1472, 0, 1471, 1470, 0, 0, 0, 0, 1469, 0, 1468,
1467, 0, 0, 1466, 1465, 0, 1464, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1463, 0, 0, 0, 1462, 0, 1461, 1460, 0, 0, 0, 0, 1459, 0, 1458,
1457, 0, 0, 1456, 1455, 0, 1454, 0, 0, 0, 0, 0, 0, 1453, 0, 1452,
1451, 0, 0, 1450, 1449, 0, 1448, 0, 0, 0, 0, 1447, 1446, 0, 1445,
0, 0, 0, 1444, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1443, 0,
0, 0, 1442, 0, 1441, 1440, 0, 0, 0, 0, 1439, 0, 1438, 1437, 0, 0,
1436, 1435, 0, 1434, 0, 0, 0, 0, 0, 0, 1433, 0, 1432, 1431, 0, 0,
1430, 1429, 0, 1428, 0, 0, 0, 0, 1427, 1426, 0, 1425, 0, 0, 0,
1424, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1423, 0, 1422, 1421, 0, 0,
1420, 1419, 0, 1418, 0, 0, 0, 0, 1417, 1416, 0, 1415, 0, 0, 0,
1414, 0, 0, 0, 0, 0, 0, 0, 0, 1413, 1412, 0, 1411, 0, 0, 0, 1410,
0, 0, 0, 0, 0, 0, 0, 1409, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 1408, 0, 0, 0, 1407, 0, 1406, 1405, 0,
0, 0, 0, 1404, 0, 1403, 1402, 0, 0, 1401, 1400, 0, 1399, 0, 0, 0,
0, 0, 0, 1398, 0, 1397, 1396, 0, 0, 1395, 1394, 0, 1393, 0, 0, 0,
0, 1392, 1391, 0, 1390, 0, 0, 0, 1389, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 1388, 0, 1387, 1386, 0, 0, 1385, 1384, 0, 1383, 0, 0, 0, 0,
1382, 1381, 0, 1380, 0, 0, 0, 1379, 0, 0, 0, 0, 0, 0, 0, 0, 1378,
1377, 0, 1376, 0, 0, 0, 1375, 0, 0, 0, 0, 0, 0, 0, 1374, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1373, 0, 1372, 1371,
0, 0, 1370, 1369, 0, 1368, 0, 0, 0, 0, 1367, 1366, 0, 1365, 0, 0,
0, 1364, 0, 0, 0, 0, 0, 0, 0, 0, 1363, 1362, 0, 1361, 0, 0, 0,
1360, 0, 0, 0, 0, 0, 0, 0, 1359, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 1358, 1357, 0, 1356, 0, 0, 0, 1355, 0, 0, 0, 0, 0,
0, 0, 1354, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1353, 0, 0, 0, 0, 0, 0, 0, 1352, 0, 0, 0, 1351, 0, 1350, 1349, 0,
0, 0, 0, 0, 0, 0, 0, 1348, 0, 0, 0, 1347, 0, 1346, 1345, 0, 0, 0,
0, 1344, 0, 1343, 1342, 0, 0, 1341, 1340, 0, 1339, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 1338, 0, 0, 0, 1337, 0, 1336, 1335, 0, 0, 0, 0,
1334, 0, 1333, 1332, 0, 0, 1331, 1330, 0, 1329, 0, 0, 0, 0, 0, 0,
1328, 0, 1327, 1326, 0, 0, 1325, 1324, 0, 1323, 0, 0, 0, 0, 1322,
1321, 0, 1320, 0, 0, 0, 1319, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 1318, 0, 0, 0, 1317, 0, 1316, 1315, 0, 0, 0, 0, 1314, 0,
1313, 1312, 0, 0, 1311, 1310, 0, 1309, 0, 0, 0, 0, 0, 0, 1308, 0,
1307, 1306, 0, 0, 1305, 1304, 0, 1303, 0, 0, 0, 0, 1302, 1301, 0,
1300, 0, 0, 0, 1299, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1298, 0, 1297,
1296, 0, 0, 1295, 1294, 0, 1293, 0, 0, 0, 0, 1292, 1291, 0, 1290,
0, 0, 0, 1289, 0, 0, 0, 0, 0, 0, 0, 0, 1288, 1287, 0, 1286, 0, 0,
0, 1285, 0, 0, 0, 0, 0, 0, 0, 1284, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1283, 0, 0, 0, 1282, 0, 1281,
1280, 0, 0, 0, 0, 1279, 0, 1278, 1277, 0, 0, 1276, 1275, 0, 1274,
0, 0, 0, 0, 0, 0, 1273, 0, 1272, 1271, 0, 0, 1270, 1269, 0, 1268,
0, 0, 0, 0, 1267, 1266, 0, 1265, 0, 0, 0, 1264, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 1263, 0, 1262, 1261, 0, 0, 1260, 1259, 0, 1258, 0, 0,
0, 0, 1257, 1256, 0, 1255, 0, 0, 0, 1254, 0, 0, 0, 0, 0, 0, 0, 0,
1253, 1252, 0, 1251, 0, 0, 0, 1250, 0, 0, 0, 0, 0, 0, 0, 1249, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1248, 0, 1247,
1246, 0, 0, 1245, 1244, 0, 1243, 0, 0, 0, 0, 1242, 1241, 0, 1240,
0, 0, 0, 1239, 0, 0, 0, 0, 0, 0, 0, 0, 1238, 1237, 0, 1236, 0, 0,
0, 1235, 0, 0, 0, 0, 0, 0, 0, 1234, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 1233, 1232, 0, 1231, 0, 0, 0, 1230, 0, 0, 0, 0,
0, 0, 0, 1229, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1228,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1227, 0, 0, 0,
1226, 0, 1225, 1224, 0, 0, 0, 0, 1223, 0, 1222, 1221, 0, 0, 1220,
1219, 0, 1218, 0, 0, 0, 0, 0, 0, 1217, 0, 1216, 1215, 0, 0, 1214,
1213, 0, 1212, 0, 0, 0, 0, 1211, 1210, 0, 1209, 0, 0, 0, 1208, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 1207, 0, 1206, 1205, 0, 0, 1204, 1203,
0, 1202, 0, 0, 0, 0, 1201, 1200, 0, 1199, 0, 0, 0, 1198, 0, 0, 0,
0, 0, 0, 0, 0, 1197, 1196, 0, 1195, 0, 0, 0, 1194, 0, 0, 0, 0, 0,
0, 0, 1193, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1192, 0, 1191, 1190, 0, 0, 1189, 1188, 0, 1187, 0, 0, 0, 0, 1186,
1185, 0, 1184, 0, 0, 0, 1183, 0, 0, 0, 0, 0, 0, 0, 0, 1182, 1181,
0, 1180, 0, 0, 0, 1179, 0, 0, 0, 0, 0, 0, 0, 1178, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1177, 1176, 0, 1175, 0, 0, 0,
1174, 0, 0, 0, 0, 0, 0, 0, 1173, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 1172, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1171, 0,
1170, 1169, 0, 0, 1168, 1167, 0, 1166, 0, 0, 0, 0, 1165, 1164, 0,
1163, 0, 0, 0, 1162, 0, 0, 0, 0, 0, 0, 0, 0, 1161, 1160, 0, 1159,
0, 0, 0, 1158, 0, 0, 0, 0, 0, 0, 0, 1157, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 1156, 1155, 0, 1154, 0, 0, 0, 1153, 0, 0,
0, 0, 0, 0, 0, 1152, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1151, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1150, 1149, 0, 1148, 0, 0, 0,
1147, 0, 0, 0, 0, 0, 0, 0, 1146, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 1145, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 1144, 0, 0, 0, 0, 0, 0, 0, 1143, 0, 0, 0, 1142,
0, 1141, 1140, 0, 0, 0, 0, 0, 0, 0, 0, 1139, 0, 0, 0, 1138, 0,
1137, 1136, 0, 0, 0, 0, 1135, 0, 1134, 1133, 0, 0, 1132, 1131, 0,
1130, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1129, 0, 0, 0, 1128, 0, 1127,
1126, 0, 0, 0, 0, 1125, 0, 1124, 1123, 0, 0, 1122, 1121, 0, 1120,
0, 0, 0, 0, 0, 0, 1119, 0, 1118, 1117, 0, 0, 1116, 1115, 0, 1114,
0, 0, 0, 0, 1113, 1112, 0, 1111, 0, 0, 0, 1110, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 1109, 0, 0, 0, 1108, 0, 1107, 1106, 0, 0,
0, 0, 1105, 0, 1104, 1103, 0, 0, 1102, 1101, 0, 1100, 0, 0, 0, 0,
0, 0, 1099, 0, 1098, 1097, 0, 0, 1096, 1095, 0, 1094, 0, 0, 0, 0,
1093, 1092, 0, 1091, 0, 0, 0, 1090, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1089, 0, 1088, 1087, 0, 0, 1086, 1085, 0, 1084, 0, 0, 0, 0, 1083,
1082, 0, 1081, 0, 0, 0, 1080, 0, 0, 0, 0, 0, 0, 0, 0, 1079, 1078,
0, 1077, 0, 0, 0, 1076, 0, 0, 0, 0, 0, 0, 0, 1075, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1074, 0, 0, 0,
1073, 0, 1072, 1071, 0, 0, 0, 0, 1070, 0, 1069, 1068, 0, 0, 1067,
1066, 0, 1065, 0, 0, 0, 0, 0, 0, 1064, 0, 1063, 1062, 0, 0, 1061,
1060, 0, 1059, 0, 0, 0, 0, 1058, 1057, 0, 1056, 0, 0, 0, 1055, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 1054, 0, 1053, 1052, 0, 0, 1051, 1050,
0, 1049, 0, 0, 0, 0, 1048, 1047, 0, 1046, 0, 0, 0, 1045, 0, 0, 0,
0, 0, 0, 0, 0, 1044, 1043, 0, 1042, 0, 0, 0, 1041, 0, 0, 0, 0, 0,
0, 0, 1040, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1039, 0, 1038, 1037, 0, 0, 1036, 1035, 0, 1034, 0, 0, 0, 0, 1033,
1032, 0, 1031, 0, 0, 0, 1030, 0, 0, 0, 0, 0, 0, 0, 0, 1029, 1028,
0, 1027, 0, 0, 0, 1026, 0, 0, 0, 0, 0, 0, 0, 1025, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1024, 1023, 0, 1022, 0, 0, 0,
1021, 0, 0, 0, 0, 0, 0, 0, 1020, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 1019, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1018, 0, 0, 0, 1017, 0, 1016, 1015, 0, 0, 0, 0, 1014, 0, 1013,
1012, 0, 0, 1011, 1010, 0, 1009, 0, 0, 0, 0, 0, 0, 1008, 0, 1007,
1006, 0, 0, 1005, 1004, 0, 1003, 0, 0, 0, 0, 1002, 1001, 0, 1000,
0, 0, 0, 999, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 998, 0, 997, 996, 0,
0, 995, 994, 0, 993, 0, 0, 0, 0, 992, 991, 0, 990, 0, 0, 0, 989,
0, 0, 0, 0, 0, 0, 0, 0, 988, 987, 0, 986, 0, 0, 0, 985, 0, 0, 0,
0, 0, 0, 0, 984, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 983, 0, 982, 981, 0, 0, 980, 979, 0, 978, 0, 0, 0, 0, 977,
976, 0, 975, 0, 0, 0, 974, 0, 0, 0, 0, 0, 0, 0, 0, 973, 972, 0,
971, 0, 0, 0, 970, 0, 0, 0, 0, 0, 0, 0, 969, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 968, 967, 0, 966, 0, 0, 0, 965, 0, 0,
0, 0, 0, 0, 0, 964, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
963, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 962, 0, 961, 960, 0, 0,
959, 958, 0, 957, 0, 0, 0, 0, 956, 955, 0, 954, 0, 0, 0, 953, 0,
0, 0, 0, 0, 0, 0, 0, 952, 951, 0, 950, 0, 0, 0, 949, 0, 0, 0, 0,
0, 0, 0, 948, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
947, 946, 0, 945, 0, 0, 0, 944, 0, 0, 0, 0, 0, 0, 0, 943, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 942, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 941, 940, 0, 939, 0, 0, 0, 938, 0, 0, 0, 0, 0, 0, 0,
937, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 936, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 935, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 934, 0, 0, 0, 933, 0, 932,
931, 0, 0, 0, 0, 930, 0, 929, 928, 0, 0, 927, 926, 0, 925, 0, 0,
0, 0, 0, 0, 924, 0, 923, 922, 0, 0, 921, 920, 0, 919, 0, 0, 0, 0,
918, 917, 0, 916, 0, 0, 0, 915, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
914, 0, 913, 912, 0, 0, 911, 910, 0, 909, 0, 0, 0, 0, 908, 907,
0, 906, 0, 0, 0, 905, 0, 0, 0, 0, 0, 0, 0, 0, 904, 903, 0, 902,
0, 0, 0, 901, 0, 0, 0, 0, 0, 0, 0, 900, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 899, 0, 898, 897, 0, 0, 896, 895,
0, 894, 0, 0, 0, 0, 893, 892, 0, 891, 0, 0, 0, 890, 0, 0, 0, 0,
0, 0, 0, 0, 889, 888, 0, 887, 0, 0, 0, 886, 0, 0, 0, 0, 0, 0, 0,
885, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 884, 883, 0,
882, 0, 0, 0, 881, 0, 0, 0, 0, 0, 0, 0, 880, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 879, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
878, 0, 877, 876, 0, 0, 875, 874, 0, 873, 0, 0, 0, 0, 872, 871,
0, 870, 0, 0, 0, 869, 0, 0, 0, 0, 0, 0, 0, 0, 868, 867, 0, 866,
0, 0, 0, 865, 0, 0, 0, 0, 0, 0, 0, 864, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 863, 862, 0, 861, 0, 0, 0, 860, 0, 0, 0,
0, 0, 0, 0, 859, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
858, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 857, 856, 0, 855, 0, 0, 0,
854, 0, 0, 0, 0, 0, 0, 0, 853, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 852, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 851, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 850, 0, 849,
848, 0, 0, 847, 846, 0, 845, 0, 0, 0, 0, 844, 843, 0, 842, 0, 0,
0, 841, 0, 0, 0, 0, 0, 0, 0, 0, 840, 839, 0, 838, 0, 0, 0, 837,
0, 0, 0, 0, 0, 0, 0, 836, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 835, 834, 0, 833, 0, 0, 0, 832, 0, 0, 0, 0, 0, 0, 0,
831, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 830, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 829, 828, 0, 827, 0, 0, 0, 826, 0, 0, 0, 0,
0, 0, 0, 825, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 824,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 823, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 822, 821, 0, 820, 0, 0, 0, 819, 0, 0,
0, 0, 0, 0, 0, 818, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
817, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 816, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
10, 0, 0, 0, 0, 0, 0, 0, 815, 0, 0, 0, 814, 0, 813, 812, 0, 0, 0,
0, 0, 0, 0, 0, 811, 0, 0, 0, 810, 0, 809, 808, 0, 0, 0, 0, 807,
0, 806, 805, 0, 0, 804, 803, 0, 802, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 801, 0, 0, 0, 800, 0, 799, 798, 0, 0, 0, 0, 797, 0, 796, 795,
0, 0, 794, 793, 0, 792, 0, 0, 0, 0, 0, 0, 791, 0, 790, 789, 0, 0,
788, 787, 0, 786, 0, 0, 0, 0, 785, 784, 0, 783, 0, 0, 0, 782, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 781, 0, 0, 0, 780, 0, 779,
778, 0, 0, 0, 0, 777, 0, 776, 775, 0, 0, 774, 773, 0, 772, 0, 0,
0, 0, 0, 0, 771, 0, 770, 769, 0, 0, 768, 767, 0, 766, 0, 0, 0, 0,
765, 764, 0, 763, 0, 0, 0, 762, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
761, 0, 760, 759, 0, 0, 758, 757, 0, 756, 0, 0, 0, 0, 755, 754,
0, 753, 0, 0, 0, 752, 0, 0, 0, 0, 0, 0, 0, 0, 751, 750, 0, 749,
0, 0, 0, 748, 0, 0, 0, 0, 0, 0, 0, 747, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 746, 0, 0, 0, 745, 0,
744, 743, 0, 0, 0, 0, 742, 0, 741, 740, 0, 0, 739, 738, 0, 737,
0, 0, 0, 0, 0, 0, 736, 0, 735, 734, 0, 0, 733, 732, 0, 731, 0, 0,
0, 0, 730, 729, 0, 728, 0, 0, 0, 727, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 726, 0, 725, 724, 0, 0, 723, 722, 0, 721, 0, 0, 0, 0, 720,
719, 0, 718, 0, 0, 0, 717, 0, 0, 0, 0, 0, 0, 0, 0, 716, 715, 0,
714, 0, 0, 0, 713, 0, 0, 0, 0, 0, 0, 0, 712, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 711, 0, 710, 709, 0, 0, 708,
707, 0, 706, 0, 0, 0, 0, 705, 704, 0, 703, 0, 0, 0, 702, 0, 0, 0,
0, 0, 0, 0, 0, 701, 700, 0, 699, 0, 0, 0, 698, 0, 0, 0, 0, 0, 0,
0, 697, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 696, 695,
0, 694, 0, 0, 0, 693, 0, 0, 0, 0, 0, 0, 0, 692, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 691, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 690, 0, 0, 0, 689, 0, 688, 687, 0, 0, 0, 0, 686,
0, 685, 684, 0, 0, 683, 682, 0, 681, 0, 0, 0, 0, 0, 0, 680, 0,
679, 678, 0, 0, 677, 676, 0, 675, 0, 0, 0, 0, 674, 673, 0, 672,
0, 0, 0, 671, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 670, 0, 669, 668, 0,
0, 667, 666, 0, 665, 0, 0, 0, 0, 664, 663, 0, 662, 0, 0, 0, 661,
0, 0, 0, 0, 0, 0, 0, 0, 660, 659, 0, 658, 0, 0, 0, 657, 0, 0, 0,
0, 0, 0, 0, 656, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 655, 0, 654, 653, 0, 0, 652, 651, 0, 650, 0, 0, 0, 0, 649,
648, 0, 647, 0, 0, 0, 646, 0, 0, 0, 0, 0, 0, 0, 0, 645, 644, 0,
643, 0, 0, 0, 642, 0, 0, 0, 0, 0, 0, 0, 641, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 640, 639, 0, 638, 0, 0, 0, 637, 0, 0,
0, 0, 0, 0, 0, 636, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
635, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 634, 0, 633, 632, 0, 0,
631, 630, 0, 629, 0, 0, 0, 0, 628, 627, 0, 626, 0, 0, 0, 625, 0,
0, 0, 0, 0, 0, 0, 0, 624, 623, 0, 622, 0, 0, 0, 621, 0, 0, 0, 0,
0, 0, 0, 620, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
619, 618, 0, 617, 0, 0, 0, 616, 0, 0, 0, 0, 0, 0, 0, 615, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 614, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 613, 612, 0, 611, 0, 0, 0, 610, 0, 0, 0, 0, 0, 0, 0,
609, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 608, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 607, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 606, 0, 0, 0, 605, 0, 604,
603, 0, 0, 0, 0, 602, 0, 601, 600, 0, 0, 599, 598, 0, 597, 0, 0,
0, 0, 0, 0, 596, 0, 595, 594, 0, 0, 593, 592, 0, 591, 0, 0, 0, 0,
590, 589, 0, 588, 0, 0, 0, 587, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
586, 0, 585, 584, 0, 0, 583, 582, 0, 581, 0, 0, 0, 0, 580, 579,
0, 578, 0, 0, 0, 577, 0, 0, 0, 0, 0, 0, 0, 0, 576, 575, 0, 574,
0, 0, 0, 573, 0, 0, 0, 0, 0, 0, 0, 572, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 571, 0, 570, 569, 0, 0, 568, 567,
0, 566, 0, 0, 0, 0, 565, 564, 0, 563, 0, 0, 0, 562, 0, 0, 0, 0,
0, 0, 0, 0, 561, 560, 0, 559, 0, 0, 0, 558, 0, 0, 0, 0, 0, 0, 0,
557, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 556, 555, 0,
554, 0, 0, 0, 553, 0, 0, 0, 0, 0, 0, 0, 552, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 551, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
550, 0, 549, 548, 0, 0, 547, 546, 0, 545, 0, 0, 0, 0, 544, 543,
0, 542, 0, 0, 0, 541, 0, 0, 0, 0, 0, 0, 0, 0, 540, 539, 0, 538,
0, 0, 0, 537, 0, 0, 0, 0, 0, 0, 0, 536, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 535, 534, 0, 533, 0, 0, 0, 532, 0, 0, 0,
0, 0, 0, 0, 531, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
530, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 529, 528, 0, 527, 0, 0, 0,
526, 0, 0, 0, 0, 0, 0, 0, 525, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 524, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 523, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 522, 0, 521,
520, 0, 0, 519, 518, 0, 517, 0, 0, 0, 0, 516, 515, 0, 514, 0, 0,
0, 513, 0, 0, 0, 0, 0, 0, 0, 0, 512, 511, 0, 510, 0, 0, 0, 509,
0, 0, 0, 0, 0, 0, 0, 508, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 507, 506, 0, 505, 0, 0, 0, 504, 0, 0, 0, 0, 0, 0, 0,
503, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 502, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 501, 500, 0, 499, 0, 0, 0, 498, 0, 0, 0, 0,
0, 0, 0, 497, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 496,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 495, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 494, 493, 0, 492, 0, 0, 0, 491, 0, 0,
0, 0, 0, 0, 0, 490, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
489, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 488, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 487, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 486, 0, 0, 0, 485, 0,
484, 483, 0, 0, 0, 0, 482, 0, 481, 480, 0, 0, 479, 478, 0, 477,
0, 0, 0, 0, 0, 0, 476, 0, 475, 474, 0, 0, 473, 472, 0, 471, 0, 0,
0, 0, 470, 469, 0, 468, 0, 0, 0, 467, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 466, 0, 465, 464, 0, 0, 463, 462, 0, 461, 0, 0, 0, 0, 460,
459, 0, 458, 0, 0, 0, 457, 0, 0, 0, 0, 0, 0, 0, 0, 456, 455, 0,
454, 0, 0, 0, 453, 0, 0, 0, 0, 0, 0, 0, 452, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 451, 0, 450, 449, 0, 0, 448,
447, 0, 446, 0, 0, 0, 0, 445, 444, 0, 443, 0, 0, 0, 442, 0, 0, 0,
0, 0, 0, 0, 0, 441, 440, 0, 439, 0, 0, 0, 438, 0, 0, 0, 0, 0, 0,
0, 437, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 436, 435,
0, 434, 0, 0, 0, 433, 0, 0, 0, 0, 0, 0, 0, 432, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 431, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 430, 0, 429, 428, 0, 0, 427, 426, 0, 425, 0, 0, 0, 0, 424,
423, 0, 422, 0, 0, 0, 421, 0, 0, 0, 0, 0, 0, 0, 0, 420, 419, 0,
418, 0, 0, 0, 417, 0, 0, 0, 0, 0, 0, 0, 416, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 415, 414, 0, 413, 0, 0, 0, 412, 0, 0,
0, 0, 0, 0, 0, 411, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
410, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 409, 408, 0, 407, 0, 0, 0,
406, 0, 0, 0, 0, 0, 0, 0, 405, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 404, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 403, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 402, 0, 401,
400, 0, 0, 399, 398, 0, 397, 0, 0, 0, 0, 396, 395, 0, 394, 0, 0,
0, 393, 0, 0, 0, 0, 0, 0, 0, 0, 392, 391, 0, 390, 0, 0, 0, 389,
0, 0, 0, 0, 0, 0, 0, 388, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 387, 386, 0, 385, 0, 0, 0, 384, 0, 0, 0, 0, 0, 0, 0,
383, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 382, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 381, 380, 0, 379, 0, 0, 0, 378, 0, 0, 0, 0,
0, 0, 0, 377, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 376,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 375, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 374, 373, 0, 372, 0, 0, 0, 371, 0, 0,
0, 0, 0, 0, 0, 370, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
369, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 368, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 367, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 366, 0, 365, 364, 0, 0, 363, 362,
0, 361, 0, 0, 0, 0, 360, 359, 0, 358, 0, 0, 0, 357, 0, 0, 0, 0,
0, 0, 0, 0, 356, 355, 0, 354, 0, 0, 0, 353, 0, 0, 0, 0, 0, 0, 0,
352, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 351, 350, 0,
349, 0, 0, 0, 348, 0, 0, 0, 0, 0, 0, 0, 347, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 346, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 345,
344, 0, 343, 0, 0, 0, 342, 0, 0, 0, 0, 0, 0, 0, 341, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 340, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
339, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
338, 337, 0, 336, 0, 0, 0, 335, 0, 0, 0, 0, 0, 0, 0, 334, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 333, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 332, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 331, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
330, 329, 0, 328, 0, 0, 0, 327, 0, 0, 0, 0, 0, 0, 0, 326, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 325, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 324, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 323, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
#This is a table lookup for all non-flush hands consisting
#of five unique ranks (i.e. either Straights or High Card
#hands). it's similar to the above "flushes" array.
unique5=[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 1608, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 7462, 0, 0, 0, 0, 0, 0, 0, 7461, 0, 0, 0, 7460, 0,
7459, 1607, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7458,
0, 0, 0, 0, 0, 0, 0, 7457, 0, 0, 0, 7456, 0, 7455, 7454, 0, 0, 0,
0, 0, 0, 0, 0, 7453, 0, 0, 0, 7452, 0, 7451, 7450, 0, 0, 0, 0,
7449, 0, 7448, 7447, 0, 0, 7446, 7445, 0, 1606, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7444, 0, 0, 0, 0, 0, 0, 0,
7443, 0, 0, 0, 7442, 0, 7441, 7440, 0, 0, 0, 0, 0, 0, 0, 0, 7439,
0, 0, 0, 7438, 0, 7437, 7436, 0, 0, 0, 0, 7435, 0, 7434, 7433, 0,
0, 7432, 7431, 0, 7430, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7429, 0, 0,
0, 7428, 0, 7427, 7426, 0, 0, 0, 0, 7425, 0, 7424, 7423, 0, 0,
7422, 7421, 0, 7420, 0, 0, 0, 0, 0, 0, 7419, 0, 7418, 7417, 0, 0,
7416, 7415, 0, 7414, 0, 0, 0, 0, 7413, 7412, 0, 7411, 0, 0, 0,
1605, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 7410, 0, 0, 0, 0, 0, 0, 0, 7409, 0, 0, 0, 7408, 0, 7407,
7406, 0, 0, 0, 0, 0, 0, 0, 0, 7405, 0, 0, 0, 7404, 0, 7403, 7402,
0, 0, 0, 0, 7401, 0, 7400, 7399, 0, 0, 7398, 7397, 0, 7396, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 7395, 0, 0, 0, 7394, 0, 7393, 7392, 0, 0,
0, 0, 7391, 0, 7390, 7389, 0, 0, 7388, 7387, 0, 7386, 0, 0, 0, 0,
0, 0, 7385, 0, 7384, 7383, 0, 0, 7382, 7381, 0, 7380, 0, 0, 0, 0,
7379, 7378, 0, 7377, 0, 0, 0, 7376, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 7375, 0, 0, 0, 7374, 0, 7373, 7372, 0, 0, 0, 0, 7371,
0, 7370, 7369, 0, 0, 7368, 7367, 0, 7366, 0, 0, 0, 0, 0, 0, 7365,
0, 7364, 7363, 0, 0, 7362, 7361, 0, 7360, 0, 0, 0, 0, 7359, 7358,
0, 7357, 0, 0, 0, 7356, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7355, 0,
7354, 7353, 0, 0, 7352, 7351, 0, 7350, 0, 0, 0, 0, 7349, 7348, 0,
7347, 0, 0, 0, 7346, 0, 0, 0, 0, 0, 0, 0, 0, 7345, 7344, 0, 7343,
0, 0, 0, 7342, 0, 0, 0, 0, 0, 0, 0, 1604, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7341, 0, 0, 0, 0, 0, 0, 0, 7340, 0, 0, 0, 7339, 0, 7338, 7337, 0,
0, 0, 0, 0, 0, 0, 0, 7336, 0, 0, 0, 7335, 0, 7334, 7333, 0, 0, 0,
0, 7332, 0, 7331, 7330, 0, 0, 7329, 7328, 0, 7327, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 7326, 0, 0, 0, 7325, 0, 7324, 7323, 0, 0, 0, 0,
7322, 0, 7321, 7320, 0, 0, 7319, 7318, 0, 7317, 0, 0, 0, 0, 0, 0,
7316, 0, 7315, 7314, 0, 0, 7313, 7312, 0, 7311, 0, 0, 0, 0, 7310,
7309, 0, 7308, 0, 0, 0, 7307, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 7306, 0, 0, 0, 7305, 0, 7304, 7303, 0, 0, 0, 0, 7302, 0,
7301, 7300, 0, 0, 7299, 7298, 0, 7297, 0, 0, 0, 0, 0, 0, 7296, 0,
7295, 7294, 0, 0, 7293, 7292, 0, 7291, 0, 0, 0, 0, 7290, 7289, 0,
7288, 0, 0, 0, 7287, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7286, 0, 7285,
7284, 0, 0, 7283, 7282, 0, 7281, 0, 0, 0, 0, 7280, 7279, 0, 7278,
0, 0, 0, 7277, 0, 0, 0, 0, 0, 0, 0, 0, 7276, 7275, 0, 7274, 0, 0,
0, 7273, 0, 0, 0, 0, 0, 0, 0, 7272, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7271, 0, 0, 0, 7270, 0, 7269,
7268, 0, 0, 0, 0, 7267, 0, 7266, 7265, 0, 0, 7264, 7263, 0, 7262,
0, 0, 0, 0, 0, 0, 7261, 0, 7260, 7259, 0, 0, 7258, 7257, 0, 7256,
0, 0, 0, 0, 7255, 7254, 0, 7253, 0, 0, 0, 7252, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 7251, 0, 7250, 7249, 0, 0, 7248, 7247, 0, 7246, 0, 0,
0, 0, 7245, 7244, 0, 7243, 0, 0, 0, 7242, 0, 0, 0, 0, 0, 0, 0, 0,
7241, 7240, 0, 7239, 0, 0, 0, 7238, 0, 0, 0, 0, 0, 0, 0, 7237, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7236, 0, 7235,
7234, 0, 0, 7233, 7232, 0, 7231, 0, 0, 0, 0, 7230, 7229, 0, 7228,
0, 0, 0, 7227, 0, 0, 0, 0, 0, 0, 0, 0, 7226, 7225, 0, 7224, 0, 0,
0, 7223, 0, 0, 0, 0, 0, 0, 0, 7222, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 7221, 7220, 0, 7219, 0, 0, 0, 7218, 0, 0, 0, 0,
0, 0, 0, 7217, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1603,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 7216, 0, 0, 0, 0, 0, 0, 0, 7215, 0, 0, 0, 7214, 0, 7213,
7212, 0, 0, 0, 0, 0, 0, 0, 0, 7211, 0, 0, 0, 7210, 0, 7209, 7208,
0, 0, 0, 0, 7207, 0, 7206, 7205, 0, 0, 7204, 7203, 0, 7202, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 7201, 0, 0, 0, 7200, 0, 7199, 7198, 0, 0,
0, 0, 7197, 0, 7196, 7195, 0, 0, 7194, 7193, 0, 7192, 0, 0, 0, 0,
0, 0, 7191, 0, 7190, 7189, 0, 0, 7188, 7187, 0, 7186, 0, 0, 0, 0,
7185, 7184, 0, 7183, 0, 0, 0, 7182, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 7181, 0, 0, 0, 7180, 0, 7179, 7178, 0, 0, 0, 0, 7177,
0, 7176, 7175, 0, 0, 7174, 7173, 0, 7172, 0, 0, 0, 0, 0, 0, 7171,
0, 7170, 7169, 0, 0, 7168, 7167, 0, 7166, 0, 0, 0, 0, 7165, 7164,
0, 7163, 0, 0, 0, 7162, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7161, 0,
7160, 7159, 0, 0, 7158, 7157, 0, 7156, 0, 0, 0, 0, 7155, 7154, 0,
7153, 0, 0, 0, 7152, 0, 0, 0, 0, 0, 0, 0, 0, 7151, 7150, 0, 7149,
0, 0, 0, 7148, 0, 0, 0, 0, 0, 0, 0, 7147, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7146, 0, 0, 0, 7145, 0,
7144, 7143, 0, 0, 0, 0, 7142, 0, 7141, 7140, 0, 0, 7139, 7138, 0,
7137, 0, 0, 0, 0, 0, 0, 7136, 0, 7135, 7134, 0, 0, 7133, 7132, 0,
7131, 0, 0, 0, 0, 7130, 7129, 0, 7128, 0, 0, 0, 7127, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 7126, 0, 7125, 7124, 0, 0, 7123, 7122, 0, 7121,
0, 0, 0, 0, 7120, 7119, 0, 7118, 0, 0, 0, 7117, 0, 0, 0, 0, 0, 0,
0, 0, 7116, 7115, 0, 7114, 0, 0, 0, 7113, 0, 0, 0, 0, 0, 0, 0,
7112, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7111,
0, 7110, 7109, 0, 0, 7108, 7107, 0, 7106, 0, 0, 0, 0, 7105, 7104,
0, 7103, 0, 0, 0, 7102, 0, 0, 0, 0, 0, 0, 0, 0, 7101, 7100, 0,
7099, 0, 0, 0, 7098, 0, 0, 0, 0, 0, 0, 0, 7097, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7096, 7095, 0, 7094, 0, 0, 0, 7093,
0, 0, 0, 0, 0, 0, 0, 7092, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 7091, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7090,
0, 0, 0, 7089, 0, 7088, 7087, 0, 0, 0, 0, 7086, 0, 7085, 7084, 0,
0, 7083, 7082, 0, 7081, 0, 0, 0, 0, 0, 0, 7080, 0, 7079, 7078, 0,
0, 7077, 7076, 0, 7075, 0, 0, 0, 0, 7074, 7073, 0, 7072, 0, 0, 0,
7071, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7070, 0, 7069, 7068, 0, 0,
7067, 7066, 0, 7065, 0, 0, 0, 0, 7064, 7063, 0, 7062, 0, 0, 0,
7061, 0, 0, 0, 0, 0, 0, 0, 0, 7060, 7059, 0, 7058, 0, 0, 0, 7057,
0, 0, 0, 0, 0, 0, 0, 7056, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 7055, 0, 7054, 7053, 0, 0, 7052, 7051, 0, 7050, 0,
0, 0, 0, 7049, 7048, 0, 7047, 0, 0, 0, 7046, 0, 0, 0, 0, 0, 0, 0,
0, 7045, 7044, 0, 7043, 0, 0, 0, 7042, 0, 0, 0, 0, 0, 0, 0, 7041,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7040, 7039, 0,
7038, 0, 0, 0, 7037, 0, 0, 0, 0, 0, 0, 0, 7036, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 7035, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 7034, 0, 7033, 7032, 0, 0, 7031, 7030, 0, 7029, 0, 0, 0, 0,
7028, 7027, 0, 7026, 0, 0, 0, 7025, 0, 0, 0, 0, 0, 0, 0, 0, 7024,
7023, 0, 7022, 0, 0, 0, 7021, 0, 0, 0, 0, 0, 0, 0, 7020, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7019, 7018, 0, 7017, 0, 0,
0, 7016, 0, 0, 0, 0, 0, 0, 0, 7015, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 7014, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7013, 7012, 0,
7011, 0, 0, 0, 7010, 0, 0, 0, 0, 0, 0, 0, 7009, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 7008, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1602,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7007, 0, 0, 0, 0, 0, 0, 0,
7006, 0, 0, 0, 7005, 0, 7004, 7003, 0, 0, 0, 0, 0, 0, 0, 0, 7002,
0, 0, 0, 7001, 0, 7000, 6999, 0, 0, 0, 0, 6998, 0, 6997, 6996, 0,
0, 6995, 6994, 0, 6993, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6992, 0, 0,
0, 6991, 0, 6990, 6989, 0, 0, 0, 0, 6988, 0, 6987, 6986, 0, 0,
6985, 6984, 0, 6983, 0, 0, 0, 0, 0, 0, 6982, 0, 6981, 6980, 0, 0,
6979, 6978, 0, 6977, 0, 0, 0, 0, 6976, 6975, 0, 6974, 0, 0, 0,
6973, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6972, 0, 0, 0,
6971, 0, 6970, 6969, 0, 0, 0, 0, 6968, 0, 6967, 6966, 0, 0, 6965,
6964, 0, 6963, 0, 0, 0, 0, 0, 0, 6962, 0, 6961, 6960, 0, 0, 6959,
6958, 0, 6957, 0, 0, 0, 0, 6956, 6955, 0, 6954, 0, 0, 0, 6953, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 6952, 0, 6951, 6950, 0, 0, 6949, 6948,
0, 6947, 0, 0, 0, 0, 6946, 6945, 0, 6944, 0, 0, 0, 6943, 0, 0, 0,
0, 0, 0, 0, 0, 6942, 6941, 0, 6940, 0, 0, 0, 6939, 0, 0, 0, 0, 0,
0, 0, 6938, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 6937, 0, 0, 0, 6936, 0, 6935, 6934, 0, 0, 0, 0, 6933,
0, 6932, 6931, 0, 0, 6930, 6929, 0, 6928, 0, 0, 0, 0, 0, 0, 6927,
0, 6926, 6925, 0, 0, 6924, 6923, 0, 6922, 0, 0, 0, 0, 6921, 6920,
0, 6919, 0, 0, 0, 6918, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6917, 0,
6916, 6915, 0, 0, 6914, 6913, 0, 6912, 0, 0, 0, 0, 6911, 6910, 0,
6909, 0, 0, 0, 6908, 0, 0, 0, 0, 0, 0, 0, 0, 6907, 6906, 0, 6905,
0, 0, 0, 6904, 0, 0, 0, 0, 0, 0, 0, 6903, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6902, 0, 6901, 6900, 0, 0, 6899,
6898, 0, 6897, 0, 0, 0, 0, 6896, 6895, 0, 6894, 0, 0, 0, 6893, 0,
0, 0, 0, 0, 0, 0, 0, 6892, 6891, 0, 6890, 0, 0, 0, 6889, 0, 0, 0,
0, 0, 0, 0, 6888, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6887, 6886, 0, 6885, 0, 0, 0, 6884, 0, 0, 0, 0, 0, 0, 0, 6883, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6882, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6881, 0, 0, 0, 6880, 0, 6879, 6878,
0, 0, 0, 0, 6877, 0, 6876, 6875, 0, 0, 6874, 6873, 0, 6872, 0, 0,
0, 0, 0, 0, 6871, 0, 6870, 6869, 0, 0, 6868, 6867, 0, 6866, 0, 0,
0, 0, 6865, 6864, 0, 6863, 0, 0, 0, 6862, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 6861, 0, 6860, 6859, 0, 0, 6858, 6857, 0, 6856, 0, 0, 0, 0,
6855, 6854, 0, 6853, 0, 0, 0, 6852, 0, 0, 0, 0, 0, 0, 0, 0, 6851,
6850, 0, 6849, 0, 0, 0, 6848, 0, 0, 0, 0, 0, 0, 0, 6847, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6846, 0, 6845, 6844,
0, 0, 6843, 6842, 0, 6841, 0, 0, 0, 0, 6840, 6839, 0, 6838, 0, 0,
0, 6837, 0, 0, 0, 0, 0, 0, 0, 0, 6836, 6835, 0, 6834, 0, 0, 0,
6833, 0, 0, 0, 0, 0, 0, 0, 6832, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 6831, 6830, 0, 6829, 0, 0, 0, 6828, 0, 0, 0, 0, 0,
0, 0, 6827, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6826, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6825, 0, 6824, 6823, 0, 0, 6822,
6821, 0, 6820, 0, 0, 0, 0, 6819, 6818, 0, 6817, 0, 0, 0, 6816, 0,
0, 0, 0, 0, 0, 0, 0, 6815, 6814, 0, 6813, 0, 0, 0, 6812, 0, 0, 0,
0, 0, 0, 0, 6811, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6810, 6809, 0, 6808, 0, 0, 0, 6807, 0, 0, 0, 0, 0, 0, 0, 6806, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6805, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 6804, 6803, 0, 6802, 0, 0, 0, 6801, 0, 0, 0, 0, 0, 0,
0, 6800, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6799, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 6798, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6797, 0, 0, 0, 6796, 0,
6795, 6794, 0, 0, 0, 0, 6793, 0, 6792, 6791, 0, 0, 6790, 6789, 0,
6788, 0, 0, 0, 0, 0, 0, 6787, 0, 6786, 6785, 0, 0, 6784, 6783, 0,
6782, 0, 0, 0, 0, 6781, 6780, 0, 6779, 0, 0, 0, 6778, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 6777, 0, 6776, 6775, 0, 0, 6774, 6773, 0, 6772,
0, 0, 0, 0, 6771, 6770, 0, 6769, 0, 0, 0, 6768, 0, 0, 0, 0, 0, 0,
0, 0, 6767, 6766, 0, 6765, 0, 0, 0, 6764, 0, 0, 0, 0, 0, 0, 0,
6763, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6762,
0, 6761, 6760, 0, 0, 6759, 6758, 0, 6757, 0, 0, 0, 0, 6756, 6755,
0, 6754, 0, 0, 0, 6753, 0, 0, 0, 0, 0, 0, 0, 0, 6752, 6751, 0,
6750, 0, 0, 0, 6749, 0, 0, 0, 0, 0, 0, 0, 6748, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6747, 6746, 0, 6745, 0, 0, 0, 6744,
0, 0, 0, 0, 0, 0, 0, 6743, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 6742, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6741, 0, 6740,
6739, 0, 0, 6738, 6737, 0, 6736, 0, 0, 0, 0, 6735, 6734, 0, 6733,
0, 0, 0, 6732, 0, 0, 0, 0, 0, 0, 0, 0, 6731, 6730, 0, 6729, 0, 0,
0, 6728, 0, 0, 0, 0, 0, 0, 0, 6727, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 6726, 6725, 0, 6724, 0, 0, 0, 6723, 0, 0, 0, 0,
0, 0, 0, 6722, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6721,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6720, 6719, 0, 6718, 0, 0, 0, 6717,
0, 0, 0, 0, 0, 0, 0, 6716, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 6715, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6714, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6713, 0, 6712, 6711,
0, 0, 6710, 6709, 0, 6708, 0, 0, 0, 0, 6707, 6706, 0, 6705, 0, 0,
0, 6704, 0, 0, 0, 0, 0, 0, 0, 0, 6703, 6702, 0, 6701, 0, 0, 0,
6700, 0, 0, 0, 0, 0, 0, 0, 6699, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 6698, 6697, 0, 6696, 0, 0, 0, 6695, 0, 0, 0, 0, 0,
0, 0, 6694, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6693, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 6692, 6691, 0, 6690, 0, 0, 0, 6689, 0,
0, 0, 0, 0, 0, 0, 6688, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 6687, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6686, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6685, 6684, 0, 6683, 0, 0, 0,
6682, 0, 0, 0, 0, 0, 0, 0, 6681, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 6680, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6679, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1601, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 1609, 0, 0, 0, 0, 0, 0, 0, 6678, 0, 0, 0, 6677, 0,
6676, 6675, 0, 0, 0, 0, 0, 0, 0, 0, 6674, 0, 0, 0, 6673, 0, 6672,
6671, 0, 0, 0, 0, 6670, 0, 6669, 6668, 0, 0, 6667, 6666, 0, 6665,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6664, 0, 0, 0, 6663, 0, 6662, 6661,
0, 0, 0, 0, 6660, 0, 6659, 6658, 0, 0, 6657, 6656, 0, 6655, 0, 0,
0, 0, 0, 0, 6654, 0, 6653, 6652, 0, 0, 6651, 6650, 0, 6649, 0, 0,
0, 0, 6648, 6647, 0, 6646, 0, 0, 0, 6645, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 6644, 0, 0, 0, 6643, 0, 6642, 6641, 0, 0, 0, 0,
6640, 0, 6639, 6638, 0, 0, 6637, 6636, 0, 6635, 0, 0, 0, 0, 0, 0,
6634, 0, 6633, 6632, 0, 0, 6631, 6630, 0, 6629, 0, 0, 0, 0, 6628,
6627, 0, 6626, 0, 0, 0, 6625, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6624,
0, 6623, 6622, 0, 0, 6621, 6620, 0, 6619, 0, 0, 0, 0, 6618, 6617,
0, 6616, 0, 0, 0, 6615, 0, 0, 0, 0, 0, 0, 0, 0, 6614, 6613, 0,
6612, 0, 0, 0, 6611, 0, 0, 0, 0, 0, 0, 0, 6610, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6609, 0, 0, 0,
6608, 0, 6607, 6606, 0, 0, 0, 0, 6605, 0, 6604, 6603, 0, 0, 6602,
6601, 0, 6600, 0, 0, 0, 0, 0, 0, 6599, 0, 6598, 6597, 0, 0, 6596,
6595, 0, 6594, 0, 0, 0, 0, 6593, 6592, 0, 6591, 0, 0, 0, 6590, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 6589, 0, 6588, 6587, 0, 0, 6586, 6585,
0, 6584, 0, 0, 0, 0, 6583, 6582, 0, 6581, 0, 0, 0, 6580, 0, 0, 0,
0, 0, 0, 0, 0, 6579, 6578, 0, 6577, 0, 0, 0, 6576, 0, 0, 0, 0, 0,
0, 0, 6575, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6574, 0, 6573, 6572, 0, 0, 6571, 6570, 0, 6569, 0, 0, 0, 0, 6568,
6567, 0, 6566, 0, 0, 0, 6565, 0, 0, 0, 0, 0, 0, 0, 0, 6564, 6563,
0, 6562, 0, 0, 0, 6561, 0, 0, 0, 0, 0, 0, 0, 6560, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6559, 6558, 0, 6557, 0, 0, 0,
6556, 0, 0, 0, 0, 0, 0, 0, 6555, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 6554, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6553, 0, 0, 0, 6552, 0, 6551, 6550, 0, 0, 0, 0, 6549, 0, 6548,
6547, 0, 0, 6546, 6545, 0, 6544, 0, 0, 0, 0, 0, 0, 6543, 0, 6542,
6541, 0, 0, 6540, 6539, 0, 6538, 0, 0, 0, 0, 6537, 6536, 0, 6535,
0, 0, 0, 6534, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6533, 0, 6532, 6531,
0, 0, 6530, 6529, 0, 6528, 0, 0, 0, 0, 6527, 6526, 0, 6525, 0, 0,
0, 6524, 0, 0, 0, 0, 0, 0, 0, 0, 6523, 6522, 0, 6521, 0, 0, 0,
6520, 0, 0, 0, 0, 0, 0, 0, 6519, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 6518, 0, 6517, 6516, 0, 0, 6515, 6514, 0,
6513, 0, 0, 0, 0, 6512, 6511, 0, 6510, 0, 0, 0, 6509, 0, 0, 0, 0,
0, 0, 0, 0, 6508, 6507, 0, 6506, 0, 0, 0, 6505, 0, 0, 0, 0, 0, 0,
0, 6504, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6503,
6502, 0, 6501, 0, 0, 0, 6500, 0, 0, 0, 0, 0, 0, 0, 6499, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6498, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 6497, 0, 6496, 6495, 0, 0, 6494, 6493, 0, 6492, 0, 0,
0, 0, 6491, 6490, 0, 6489, 0, 0, 0, 6488, 0, 0, 0, 0, 0, 0, 0, 0,
6487, 6486, 0, 6485, 0, 0, 0, 6484, 0, 0, 0, 0, 0, 0, 0, 6483, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6482, 6481, 0, 6480,
0, 0, 0, 6479, 0, 0, 0, 0, 0, 0, 0, 6478, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 6477, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6476,
6475, 0, 6474, 0, 0, 0, 6473, 0, 0, 0, 0, 0, 0, 0, 6472, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6471, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 6470, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 6469, 0, 0, 0, 6468, 0, 6467, 6466, 0, 0, 0,
0, 6465, 0, 6464, 6463, 0, 0, 6462, 6461, 0, 6460, 0, 0, 0, 0, 0,
0, 6459, 0, 6458, 6457, 0, 0, 6456, 6455, 0, 6454, 0, 0, 0, 0,
6453, 6452, 0, 6451, 0, 0, 0, 6450, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6449, 0, 6448, 6447, 0, 0, 6446, 6445, 0, 6444, 0, 0, 0, 0, 6443,
6442, 0, 6441, 0, 0, 0, 6440, 0, 0, 0, 0, 0, 0, 0, 0, 6439, 6438,
0, 6437, 0, 0, 0, 6436, 0, 0, 0, 0, 0, 0, 0, 6435, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6434, 0, 6433, 6432, 0, 0,
6431, 6430, 0, 6429, 0, 0, 0, 0, 6428, 6427, 0, 6426, 0, 0, 0,
6425, 0, 0, 0, 0, 0, 0, 0, 0, 6424, 6423, 0, 6422, 0, 0, 0, 6421,
0, 0, 0, 0, 0, 0, 0, 6420, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 6419, 6418, 0, 6417, 0, 0, 0, 6416, 0, 0, 0, 0, 0, 0, 0,
6415, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6414, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 6413, 0, 6412, 6411, 0, 0, 6410, 6409,
0, 6408, 0, 0, 0, 0, 6407, 6406, 0, 6405, 0, 0, 0, 6404, 0, 0, 0,
0, 0, 0, 0, 0, 6403, 6402, 0, 6401, 0, 0, 0, 6400, 0, 0, 0, 0, 0,
0, 0, 6399, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6398,
6397, 0, 6396, 0, 0, 0, 6395, 0, 0, 0, 0, 0, 0, 0, 6394, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6393, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 6392, 6391, 0, 6390, 0, 0, 0, 6389, 0, 0, 0, 0, 0, 0, 0,
6388, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6387, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 6386, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 6385, 0, 6384, 6383, 0, 0, 6382, 6381, 0,
6380, 0, 0, 0, 0, 6379, 6378, 0, 6377, 0, 0, 0, 6376, 0, 0, 0, 0,
0, 0, 0, 0, 6375, 6374, 0, 6373, 0, 0, 0, 6372, 0, 0, 0, 0, 0, 0,
0, 6371, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6370,
6369, 0, 6368, 0, 0, 0, 6367, 0, 0, 0, 0, 0, 0, 0, 6366, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6365, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 6364, 6363, 0, 6362, 0, 0, 0, 6361, 0, 0, 0, 0, 0, 0, 0,
6360, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6359, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 6358, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 6357, 6356, 0, 6355, 0, 0, 0, 6354, 0, 0, 0, 0,
0, 0, 0, 6353, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6352,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 6351, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 6350, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6349, 0, 0, 0, 6348, 0, 6347,
6346, 0, 0, 0, 0, 6345, 0, 6344, 6343, 0, 0, 6342, 6341, 0, 6340,
0, 0, 0, 0, 0, 0, 6339, 0, 6338, 6337, 0, 0, 6336, 6335, 0, 6334,
0, 0, 0, 0, 6333, 6332, 0, 6331, 0, 0, 0, 6330, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 6329, 0, 6328, 6327, 0, 0, 6326, 6325, 0, 6324, 0, 0,
0, 0, 6323, 6322, 0, 6321, 0, 0, 0, 6320, 0, 0, 0, 0, 0, 0, 0, 0,
6319, 6318, 0, 6317, 0, 0, 0, 6316, 0, 0, 0, 0, 0, 0, 0, 6315, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6314, 0, 6313,
6312, 0, 0, 6311, 6310, 0, 6309, 0, 0, 0, 0, 6308, 6307, 0, 6306,
0, 0, 0, 6305, 0, 0, 0, 0, 0, 0, 0, 0, 6304, 6303, 0, 6302, 0, 0,
0, 6301, 0, 0, 0, 0, 0, 0, 0, 6300, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 6299, 6298, 0, 6297, 0, 0, 0, 6296, 0, 0, 0, 0,
0, 0, 0, 6295, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6294,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6293, 0, 6292, 6291, 0, 0,
6290, 6289, 0, 6288, 0, 0, 0, 0, 6287, 6286, 0, 6285, 0, 0, 0,
6284, 0, 0, 0, 0, 0, 0, 0, 0, 6283, 6282, 0, 6281, 0, 0, 0, 6280,
0, 0, 0, 0, 0, 0, 0, 6279, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 6278, 6277, 0, 6276, 0, 0, 0, 6275, 0, 0, 0, 0, 0, 0, 0,
6274, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6273, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 6272, 6271, 0, 6270, 0, 0, 0, 6269, 0, 0, 0,
0, 0, 0, 0, 6268, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6267, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6266, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6265, 0, 6264, 6263, 0, 0,
6262, 6261, 0, 6260, 0, 0, 0, 0, 6259, 6258, 0, 6257, 0, 0, 0,
6256, 0, 0, 0, 0, 0, 0, 0, 0, 6255, 6254, 0, 6253, 0, 0, 0, 6252,
0, 0, 0, 0, 0, 0, 0, 6251, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 6250, 6249, 0, 6248, 0, 0, 0, 6247, 0, 0, 0, 0, 0, 0, 0,
6246, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6245, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 6244, 6243, 0, 6242, 0, 0, 0, 6241, 0, 0, 0,
0, 0, 0, 0, 6240, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6239, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6238, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6237, 6236, 0, 6235, 0, 0, 0,
6234, 0, 0, 0, 0, 0, 0, 0, 6233, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 6232, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6231, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6230, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6229, 0, 6228, 6227, 0,
0, 6226, 6225, 0, 6224, 0, 0, 0, 0, 6223, 6222, 0, 6221, 0, 0, 0,
6220, 0, 0, 0, 0, 0, 0, 0, 0, 6219, 6218, 0, 6217, 0, 0, 0, 6216,
0, 0, 0, 0, 0, 0, 0, 6215, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 6214, 6213, 0, 6212, 0, 0, 0, 6211, 0, 0, 0, 0, 0, 0, 0,
6210, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6209, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 6208, 6207, 0, 6206, 0, 0, 0, 6205, 0, 0, 0,
0, 0, 0, 0, 6204, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
6203, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6202, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6201, 6200, 0, 6199, 0, 0, 0,
6198, 0, 0, 0, 0, 0, 0, 0, 6197, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 6196, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6195, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6194, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6193, 6192, 0, 6191, 0, 0, 0,
6190, 0, 0, 0, 0, 0, 0, 0, 6189, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 6188, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6187, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6186, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1600]
#This is a table for all prime products for the hands
#that are not considered in the previous lookup tables.
#Once the prime product is found in this array, the index of
#this value is used to find the hand value in the following
#table
products = [48, 72, 80, 108, 112, 120, 162, 168, 176, 180, 200, 208, 252,
264, 270, 272, 280, 300, 304, 312, 368, 378, 392, 396, 405, 408,
420, 440, 450, 456, 464, 468, 496, 500, 520, 552, 567, 588, 592,
594, 612, 616, 630, 656, 660, 675, 680, 684, 696, 700, 702, 728,
744, 750, 760, 780, 828, 882, 888, 891, 918, 920, 924, 945, 952,
968, 980, 984, 990, 1020, 1026, 1044, 1050, 1053, 1064, 1092,
1100, 1116, 1125, 1140, 1144, 1160, 1170, 1240, 1242, 1250, 1288,
1300, 1323, 1332, 1352, 1372, 1377, 1380, 1386, 1428, 1452, 1470,
1476, 1480, 1485, 1496, 1530, 1539, 1540, 1566, 1575, 1596, 1624,
1638, 1640, 1650, 1672, 1674, 1700, 1710, 1716, 1736, 1740, 1750,
1755, 1768, 1820, 1860, 1863, 1875, 1900, 1932, 1950, 1976, 1998,
2024, 2028, 2058, 2070, 2072, 2079, 2142, 2156, 2178, 2205, 2214,
2220, 2244, 2295, 2296, 2300, 2312, 2349, 2380, 2392, 2394, 2420,
2436, 2450, 2457, 2460, 2475, 2508, 2511, 2548, 2550, 2552, 2565,
2574, 2584, 2604, 2610, 2625, 2652, 2660, 2728, 2750, 2790, 2850,
2860, 2888, 2898, 2900, 2925, 2964, 2997, 3016, 3036, 3042, 3087,
3100, 3105, 3108, 3128, 3213, 3220, 3224, 3234, 3250, 3256, 3267,
3321, 3330, 3332, 3366, 3380, 3388, 3430, 3444, 3450, 3465, 3468,
3496, 3588, 3591, 3608, 3630, 3654, 3675, 3690, 3700, 3724, 3740,
3762, 3822, 3825, 3828, 3848, 3850, 3861, 3876, 3906, 3915, 3944,
3978, 4004, 4060, 4092, 4095, 4100, 4125, 4180, 4185, 4216, 4232,
4250, 4264, 4275, 4332, 4340, 4347, 4350, 4375, 4408, 4420, 4446,
4508, 4524, 4550, 4554, 4563, 4650, 4662, 4692, 4712, 4732, 4750,
4802, 4836, 4851, 4875, 4884, 4940, 4995, 4998, 5032, 5049, 5060,
5070, 5082, 5145, 5166, 5175, 5180, 5202, 5236, 5244, 5324, 5336,
5355, 5382, 5390, 5412, 5445, 5481, 5535, 5550, 5576, 5586, 5624,
5643, 5684, 5704, 5733, 5740, 5742, 5750, 5772, 5775, 5780, 5814,
5852, 5859, 5916, 5950, 5967, 5980, 5985, 6050, 6076, 6125, 6138,
6150, 6188, 6232, 6292, 6324, 6348, 6370, 6375, 6380, 6396, 6435,
6460, 6498, 6525, 6612, 6650, 6669, 6728, 6762, 6786, 6808, 6820,
6825, 6831, 6875, 6916, 6975, 6993, 7038, 7068, 7084, 7098, 7125,
7150, 7192, 7203, 7220, 7245, 7250, 7252, 7254, 7326, 7436, 7497,
7540, 7544, 7546, 7548, 7605, 7623, 7688, 7749, 7750, 7803, 7820,
7866, 7986, 8004, 8036, 8050, 8060, 8073, 8085, 8092, 8118, 8125,
8140, 8228, 8325, 8330, 8364, 8372, 8379, 8415, 8436, 8450, 8470,
8526, 8556, 8575, 8584, 8613, 8625, 8658, 8670, 8721, 8740, 8788,
8874, 8918, 8925, 8932, 9009, 9020, 9044, 9075, 9114, 9135, 9176,
9196, 9207, 9225, 9250, 9310, 9348, 9350, 9405, 9438, 9486, 9512,
9522, 9548, 9555, 9594, 9620, 9625, 9724, 9747, 9765, 9860, 9918,
9945, 9975, 10092, 10108, 10143, 10150, 10168, 10179, 10212,
10250, 10450, 10540, 10556, 10557, 10580, 10602, 10625, 10647,
10660, 10725, 10788, 10830, 10850, 10868, 10875, 10878, 10881,
10948, 10952, 10989, 11020, 11050, 11115, 11132, 11154, 11270,
11284, 11316, 11319, 11322, 11375, 11385, 11396, 11492, 11532,
11625, 11655, 11662, 11780, 11781, 11799, 11830, 11858, 11875,
11979, 12005, 12006, 12054, 12075, 12136, 12138, 12177, 12236,
12342, 12350, 12495, 12546, 12580, 12628, 12650, 12654, 12675,
12705, 12716, 12789, 12834, 12844, 12876, 12915, 12950, 12987,
13005, 13034, 13156, 13167, 13182, 13310, 13311, 13340, 13377,
13448, 13455, 13468, 13475, 13671, 13764, 13794, 13804, 13875,
13923, 13940, 13965, 14014, 14022, 14025, 14036, 14060, 14157,
14210, 14212, 14229, 14260, 14268, 14283, 14350, 14355, 14375,
14391, 14450, 14535, 14756, 14812, 14875, 14877, 14924, 14950,
15004, 15028, 15125, 15138, 15162, 15190, 15225, 15252, 15318,
15345, 15375, 15428, 15548, 15561, 15580, 15675, 15730, 15778,
15870, 15884, 15903, 15925, 15939, 15950, 16150, 16182, 16245,
16275, 16317, 16428, 16492, 16562, 16575, 16588, 16625, 16698,
16731, 16796, 16820, 16905, 16965, 16974, 16983, 17020, 17050,
17204, 17238, 17298, 17493, 17595, 17612, 17732, 17745, 17787,
17875, 17908, 17980, 18009, 18050, 18081, 18125, 18130, 18135,
18204, 18207, 18315, 18326, 18513, 18525, 18590, 18634, 18676,
18772, 18819, 18837, 18850, 18860, 18865, 18975, 18981, 19074,
19220, 19228, 19251, 19266, 19314, 19375, 19425, 19516, 19550,
19551, 19604, 19652, 19665, 19684, 19773, 19844, 19894, 19964,
19965, 20090, 20097, 20125, 20150, 20172, 20230, 20295, 20332,
20349, 20350, 20482, 20570, 20646, 20691, 20825, 20956, 21021,
21033, 21054, 21125, 21164, 21175, 21266, 21315, 21402, 21460,
21483, 21525, 21645, 21658, 21675, 21692, 21812, 21850, 21879,
21964, 21970, 22022, 22185, 22218, 22295, 22425, 22506, 22542,
22550, 22707, 22724, 22743, 22785, 22878, 22940, 22977, 22990,
23125, 23188, 23275, 23276, 23322, 23375, 23452, 23548, 23595,
23667, 23715, 23751, 23780, 23805, 23826, 23828, 23925, 23985,
24050, 24206, 24225, 24244, 24273, 24453, 24548, 24633, 24642,
24650, 24794, 24795, 24843, 25012, 25025, 25047, 25172, 25230,
25270, 25375, 25382, 25389, 25420, 25461, 25575, 25625, 25636,
25641, 25857, 25916, 25947, 26026, 26125, 26350, 26404, 26411,
26450, 26505, 26588, 26650, 26862, 26908, 27075, 27125, 27195,
27306, 27380, 27404, 27436, 27489, 27508, 27531, 27550, 27625,
27676, 27716, 27830, 27885, 27951, 28126, 28158, 28175, 28275,
28305, 28322, 28413, 28611, 28652, 28730, 28798, 28830, 28899,
28971, 29155, 29282, 29302, 29325, 29348, 29406, 29450, 29478,
29575, 29601, 29645, 29716, 29766, 29841, 30015, 30044, 30135,
30225, 30258, 30303, 30340, 30345, 30525, 30628, 30668, 30723,
30758, 30855, 30875, 30932, 30969, 31059, 31213, 31262, 31365,
31372, 31434, 31450, 31581, 31625, 31635, 31654, 31790, 31899,
31977, 32085, 32103, 32110, 32116, 32186, 32375, 32487, 32585,
32708, 32725, 32775, 32946, 32955, 33033, 33201, 33212, 33275,
33292, 33327, 33350, 33418, 33524, 33579, 33620, 33759, 33813,
33825, 34276, 34317, 34485, 34606, 34684, 34713, 34850, 34914,
34983, 35035, 35055, 35090, 35150, 35322, 35378, 35525, 35588,
35650, 35739, 35836, 35875, 35972, 36075, 36125, 36244, 36309,
36556, 36575, 36822, 36946, 36963, 36975, 37004, 37030, 37076,
37107, 37191, 37323, 37375, 37444, 37468, 37510, 37518, 37570,
37791, 37845, 37905, 37975, 38073, 38295, 38318, 38332, 38675,
38709, 38870, 38950, 38962, 39039, 39325, 39445, 39494, 39525,
39556, 39627, 39675, 39710, 39875, 39882, 39886, 39897, 39975,
40052, 40204, 40222, 40293, 40362, 40375, 40455, 40508, 40817,
40898, 40959, 41070, 41154, 41262, 41325, 41405, 41492, 41503,
41574, 41745, 41876, 42021, 42050, 42189, 42237, 42284, 42435,
42476, 42483, 42550, 42625, 42772, 42826, 43095, 43197, 43225,
43245, 43263, 43732, 43911, 43923, 43953, 44109, 44175, 44198,
44217, 44252, 44275, 44289, 44506, 44649, 44764, 44770, 44919,
44950, 44954, 45125, 45254, 45325, 45356, 45387, 45619, 45747,
45815, 46137, 46475, 46585, 46748, 46893, 46930, 47068, 47125,
47138, 47150, 47151, 47175, 47212, 47396, 47481, 47619, 47685,
47804, 48050, 48165, 48279, 48285, 48314, 48334, 48484, 48668,
48807, 48875, 49010, 49036, 49049, 49077, 49126, 49130, 49419,
49610, 49735, 49818, 49972, 50025, 50127, 50225, 50286, 50375,
50430, 50468, 50575, 50578, 50692, 50875, 51129, 51205, 51425,
51615, 51646, 51842, 51909, 52173, 52234, 52275, 52316, 52325,
52371, 52390, 52514, 52598, 52635, 52725, 52767, 52972, 52983,
53067, 53165, 53428, 53475, 53482, 53505, 53613, 53650, 53754,
53958, 53998, 54145, 54188, 54418, 54549, 54625, 54910, 54925,
55055, 55223, 55233, 55419, 55506, 55545, 55594, 55796, 55825,
55924, 56265, 56277, 56355, 56375, 56525, 56637, 57122, 57188,
57195, 57350, 57475, 57477, 57498, 57681, 57722, 57868, 57967,
58190, 58305, 58311, 58425, 58443, 58870, 59204, 59241, 59409,
59450, 59565, 59644, 59675, 59774, 59823, 59829, 60125, 60236,
60306, 60333, 60515, 60543, 60775, 61132, 61226, 61347, 61364,
61370, 61605, 61625, 61642, 61659, 61731, 61828, 61893, 61985,
62271, 62361, 62530, 62678, 62814, 63075, 63175, 63206, 63426,
63455, 63550, 63825, 63916, 64124, 64141, 64158, 64239, 64467,
64676, 65065, 65219, 65348, 65366, 65596, 65598, 65702, 65875,
65975, 66033, 66092, 66125, 66297, 66470, 66625, 66748, 66759,
66861, 67146, 67155, 67270, 67425, 67431, 67599, 67881, 67925,
68265, 68306, 68324, 68425, 68450, 68590, 68614, 68770, 68782,
68875, 68894, 68913, 69003, 69290, 69454, 69575, 69597, 69629,
69874, 69938, 70315, 70395, 70525, 70587, 70602, 70642, 70707,
70725, 70805, 71094, 71188, 71225, 71668, 71687, 71825, 71995,
72075, 72261, 72358, 72471, 72501, 72964, 73002, 73036, 73205,
73255, 73346, 73515, 73593, 73625, 73689, 73695, 73964, 74415,
74431, 74698, 74727, 74907, 74958, 75429, 75645, 75803, 75850,
75867, 76342, 76475, 76874, 76895, 77077, 77121, 77198, 77372,
77469, 77763, 77996, 78039, 78155, 78166, 78292, 78351, 78585,
78625, 78771, 78884, 78897, 78925, 79135, 79475, 80073, 80142,
80223, 80275, 80465, 80475, 80631, 80852, 80937, 80997, 81466,
81548, 81549, 81627, 82225, 82251, 82365, 82418, 82522, 82654,
82708, 83030, 83259, 83375, 83391, 83398, 83421, 83486, 83545,
83810, 84050, 84175, 84249, 84303, 84721, 85514, 85683, 85782,
85918, 86025, 86247, 86275, 86428, 86515, 86583, 86756, 86779,
87125, 87172, 87285, 87362, 87412, 87542, 87725, 87875, 88102,
88305, 88412, 88445, 88806, 88825, 88837, 89001, 89125, 89175,
89590, 89661, 89930, 90117, 90354, 90364, 90459, 91091, 91143,
91234, 91839, 92046, 92055, 92225, 92365, 92414, 92463, 92510,
92575, 93058, 93092, 93275, 93357, 93775, 93795, 93925, 94017,
94178, 94221, 94622, 94809, 95139, 95325, 95571, 95795, 95830,
95874, 96026, 96237, 96278, 96425, 96596, 97006, 97175, 97375,
97405, 97526, 97556, 97682, 98022, 98049, 98394, 98397, 98441,
98494, 98553, 98716, 98735, 99127, 99275, 99567, 99705, 99715,
100510, 100555, 100719, 100793, 100905, 101062, 102051, 102245,
102459, 102487, 102557, 102675, 102885, 102921, 103075, 103155,
103156, 103173, 103246, 103341, 103675, 103935, 104044, 104181,
104284, 104690, 104811, 104907, 104975, 105125, 105154, 105183,
105524, 105710, 105754, 105903, 105963, 106227, 106375, 106641,
106782, 106930, 107065, 107525, 107559, 107653, 107822, 108086,
108537, 109089, 109142, 109174, 109330, 109388, 109417, 109503,
109554, 110019, 110075, 110331, 110495, 110789, 110825, 110946,
111265, 111476, 111910, 111925, 112047, 112375, 112385, 112406,
112437, 112651, 113135, 113553, 113775, 114057, 114308, 114513,
115258, 115292, 115311, 115797, 116058, 116242, 116402, 116522,
116725, 116932, 116963, 117249, 117325, 117334, 117438, 117670,
117711, 117845, 117875, 118490, 119119, 119164, 119187, 119306,
120125, 120175, 120213, 120785, 120802, 120835, 121121, 121670,
121923, 121975, 122018, 122199, 122525, 122815, 122825, 123025,
123627, 123783, 123823, 123981, 124025, 124468, 124545, 124558,
124775, 124930, 125097, 125229, 125426, 125541, 125715, 125829,
125902, 125948, 126075, 126445, 127075, 127426, 127534, 127738,
127756, 128018, 128271, 128673, 128877, 128986, 129115, 129311,
129514, 129605, 130134, 130203, 130585, 130975, 131043, 131118,
131285, 131313, 131495, 132153, 132158, 132275, 132618, 133052,
133133, 133209, 133342, 133570, 133705, 134113, 134125, 134162,
134199, 134385, 134895, 134995, 135014, 135531, 135575, 136045,
136214, 136325, 136367, 136851, 137275, 137547, 137566, 137924,
138069, 138229, 138621, 138765, 138985, 139113, 139564, 139587,
139601, 139638, 140714, 140777, 141267, 141933, 142025, 142228,
142538, 142766, 142805, 142970, 143143, 143375, 143745, 143811,
144039, 144279, 144305, 144417, 144925, 145475, 145509, 145521,
146234, 146289, 146334, 146523, 146566, 146575, 147033, 147175,
147436, 147591, 147706, 147741, 147994, 148010, 148625, 148666,
148707, 148925, 149435, 149702, 149891, 150183, 150590, 150765,
150898, 151294, 151525, 151593, 152218, 152438, 153062, 153065,
153410, 153425, 153729, 154105, 154652, 154693, 154869, 155771,
156066, 156325, 156426, 156674, 156695, 157035, 157325, 157339,
157604, 157731, 158015, 158389, 158565, 158631, 158804, 158875,
159562, 159790, 160173, 160225, 160395, 161161, 161253, 161414,
161733, 161975, 162129, 162578, 163370, 163415, 163713, 163761,
163990, 163995, 164169, 164255, 164331, 164738, 164983, 165025,
165886, 166175, 166419, 166634, 167042, 167214, 167865, 168175,
168609, 168674, 169099, 169169, 169756, 170126, 170338, 170765,
171125, 171275, 171462, 171475, 171535, 171925, 171941, 171955,
172235, 172546, 172822, 172887, 172975, 173225, 173635, 174087,
174097, 174363, 174603, 174685, 174783, 174845, 174902, 175491,
175972, 176001, 176157, 176505, 176605, 177023, 177489, 177735,
177970, 178126, 178334, 178746, 178802, 178959, 179075, 180154,
180761, 180895, 181203, 181447, 181917, 182505, 182590, 182666,
182819, 183027, 183365, 183425, 183483, 183799, 184093, 184382,
184910, 185725, 186093, 186238, 186694, 186702, 186745, 186837,
186998, 187187, 187395, 187775, 188108, 188139, 188518, 188853,
188922, 188993, 189625, 190333, 190463, 190855, 191139, 191301,
191425, 191607, 191634, 191675, 192027, 192185, 192995, 193325,
193430, 193479, 194271, 194463, 194579, 194996, 195201, 195415,
195730, 196075, 196137, 196677, 197098, 197846, 198237, 198927,
199082, 199927, 200013, 200158, 200355, 200725, 201243, 202027,
202521, 202612, 203203, 203319, 203522, 203665, 204321, 204425,
205751, 205942, 206045, 206305, 206349, 206635, 206886, 207214,
207575, 208075, 208444, 208495, 208658, 208715, 209209, 209457,
209525, 210125, 210749, 210826, 211071, 212602, 213342, 213785,
213807, 214149, 214225, 214291, 214455, 214774, 214795, 215747,
215878, 216775, 216890, 217217, 217341, 217558, 217906, 218405,
218530, 218855, 219351, 219373, 219501, 219849, 220255, 221030,
221122, 221221, 221559, 221991, 222015, 222111, 222425, 222999,
223706, 223975, 224516, 224553, 224825, 224939, 225446, 225885,
225998, 226347, 226525, 226941, 228085, 228206, 228327, 228475,
228657, 228718, 228781, 229586, 229593, 229957, 230115, 230318,
231035, 231275, 231725, 231978, 232101, 232562, 232645, 232730,
232934, 233206, 233818, 234025, 234099, 234175, 234639, 235011,
235246, 235445, 235543, 235586, 236406, 236555, 237429, 237614,
238206, 239071, 239343, 239575, 239685, 240065, 240149, 240526,
240695, 240737, 240994, 241129, 242121, 242515, 243089, 243815,
243867, 243890, 244205, 244559, 244783, 245055, 245985, 246123,
246202, 246235, 247107, 247225, 247247, 248788, 248829, 248897,
249067, 249158, 249951, 250325, 250563, 250821, 251275, 252586,
252655, 253011, 253175, 253253, 254634, 255189, 255507, 255626,
256711, 257193, 258115, 258819, 258874, 259233, 259259, 259325,
259407, 259666, 260110, 260642, 260678, 260710, 261326, 261443,
261725, 262353, 262885, 263097, 263302, 264275, 264385, 265475,
265727, 265837, 266955, 267189, 267197, 267325, 267501, 267674,
268119, 268203, 269059, 269555, 270193, 270215, 270231, 270802,
272194, 272855, 272935, 273325, 273581, 273885, 273999, 274022,
274846, 275684, 276573, 276575, 277365, 277574, 278018, 278179,
278369, 278690, 279357, 279775, 280041, 280053, 280497, 281015,
282302, 282777, 283383, 283475, 284053, 284258, 284954, 285131,
285770, 287287, 287451, 287638, 287738, 288145, 288463, 288827,
289289, 290145, 290605, 290966, 291005, 291305, 291893, 292175,
292201, 292494, 293335, 293595, 293854, 294151, 294175, 295075,
295647, 296225, 296769, 296989, 297910, 298265, 298623, 298775,
299299, 299367, 300237, 300713, 302005, 303025, 303646, 303862,
303918, 304175, 304606, 305045, 305283, 305762, 305767, 305942,
306397, 306475, 307582, 308074, 308357, 308913, 309442, 310329,
310821, 311170, 311395, 312325, 312666, 312987, 313565, 314019,
314041, 314171, 314534, 314755, 314870, 315425, 315514, 316239,
316342, 316825, 317471, 318478, 318565, 318734, 318835, 318903,
319319, 319345, 319390, 320013, 320045, 322161, 322465, 323449,
323785, 323817, 324818, 325335, 325622, 325703, 325822, 326337,
326859, 326975, 327795, 328757, 329623, 330395, 331075, 331177,
331298, 331545, 331683, 331731, 333355, 333925, 335405, 335559,
335699, 336091, 336743, 336774, 336973, 337502, 337535, 338169,
338675, 338997, 339031, 339521, 340442, 340535, 341341, 341446,
341734, 341887, 342309, 343077, 343915, 344379, 344729, 344810,
345477, 347282, 347633, 347967, 348725, 348843, 349095, 349401,
349525, 349809, 350727, 350987, 351538, 351785, 352869, 353379,
353717, 354609, 355570, 355946, 356345, 356421, 356915, 357309,
357425, 359414, 359513, 360778, 360789, 361361, 361491, 361675,
362674, 363562, 364021, 364154, 364994, 365585, 365835, 366415,
367114, 368039, 369265, 369303, 369985, 370025, 370139, 371665,
371722, 372775, 373182, 373737, 374255, 375193, 375683, 376475,
377245, 377377, 378235, 378301, 378879, 378917, 380494, 380545,
381095, 381938, 381951, 381997, 382075, 382109, 382655, 383439,
383525, 384307, 384659, 384826, 385526, 386425, 386630, 387686,
388311, 388531, 389499, 390165, 390166, 390963, 391017, 391065,
391534, 391685, 391989, 393421, 394010, 394953, 395937, 397010,
397822, 397969, 398866, 398905, 399475, 400078, 400673, 400775,
401511, 401698, 401882, 402866, 403403, 403535, 404225, 406203,
406334, 406445, 406802, 406847, 407407, 407827, 408291, 408425,
409975, 410669, 410839, 411033, 411845, 412114, 412269, 413075,
413526, 413678, 414715, 415454, 416361, 416585, 417027, 417074,
417175, 417571, 417605, 418035, 419881, 421685, 422807, 423243,
423453, 424390, 424589, 424762, 424879, 425258, 425315, 425546,
425845, 426374, 426387, 427025, 427063, 427431, 428655, 429598,
429913, 430606, 431365, 431457, 431607, 432055, 435638, 435953,
436449, 437255, 438741, 438991, 440657, 440781, 440818, 443989,
444925, 445315, 445835, 445991, 446369, 446865, 447005, 447083,
447146, 447811, 447925, 448063, 450262, 450385, 451451, 453299,
453871, 454138, 454181, 454597, 455469, 455793, 455877, 456025,
456475, 456665, 456909, 458643, 458689, 458913, 458983, 459173,
460955, 461373, 462111, 462275, 462346, 462553, 462722, 464163,
465595, 466697, 466735, 466755, 467495, 468999, 469567, 470327,
471295, 471801, 472305, 472549, 473271, 474513, 474734, 476749,
477158, 477717, 478101, 479085, 480491, 480766, 481481, 481574,
482734, 483575, 484561, 485537, 486098, 486266, 487227, 487475,
487490, 488433, 488733, 489325, 490637, 491878, 492499, 492745,
493025, 494615, 496223, 496947, 497705, 497798, 498883, 499681,
500395, 501787, 502918, 503234, 505161, 505325, 506253, 506530,
507566, 508079, 508277, 508805, 508898, 509675, 510663, 511819,
512006, 512169, 512601, 512746, 512981, 514786, 514855, 516925,
516971, 517215, 517979, 518035, 519622, 520331, 520421, 520923,
521110, 521594, 521645, 523957, 527065, 527307, 528143, 529529,
531505, 532763, 533355, 533533, 533919, 535717, 536393, 536558,
536935, 537251, 539121, 539695, 540175, 541167, 541282, 541717,
542087, 542225, 542659, 543286, 543895, 544011, 544765, 544825,
545054, 545343, 546231, 546325, 547491, 548359, 550671, 551614,
552575, 552805, 555458, 555611, 555814, 555841, 557566, 557583,
558467, 559265, 559682, 559773, 561290, 562438, 563615, 563914,
564775, 564949, 564995, 567853, 568178, 569023, 570515, 570741,
571795, 572242, 572663, 572907, 573562, 573965, 574678, 575795,
576583, 577239, 578289, 578347, 579945, 580601, 581405, 581529,
581647, 581825, 582335, 582958, 583015, 583219, 584545, 584647,
585249, 585599, 587301, 588115, 588965, 590359, 591015, 593021,
593929, 594035, 594146, 594473, 595441, 595515, 596183, 596733,
598299, 600117, 600281, 600457, 600691, 601315, 602485, 602547,
602823, 603725, 603911, 604299, 604877, 605098, 607202, 609501,
609725, 610203, 612157, 613118, 614422, 615043, 615505, 616975,
618171, 618233, 620194, 620289, 620517, 620806, 620977, 621970,
622895, 623162, 623181, 623441, 624169, 625611, 625807, 628694,
630539, 631465, 633919, 634114, 634933, 636585, 637143, 637887,
638319, 639065, 639331, 639561, 640211, 640871, 644397, 644725,
645337, 645909, 647185, 648907, 649078, 649165, 650275, 651605,
651695, 651775, 651833, 653315, 653429, 653457, 654493, 655402,
656183, 656903, 657662, 658255, 659525, 659813, 661227, 662966,
663803, 664411, 665482, 669185, 670719, 671099, 675393, 676286,
677005, 677846, 680485, 680846, 681207, 682486, 683501, 683675,
684574, 685055, 685069, 687115, 687242, 687401, 689210, 689843,
692461, 692714, 693519, 693842, 693935, 694083, 695045, 696725,
696787, 700553, 700843, 701437, 702559, 702658, 704099, 705686,
705755, 708883, 709142, 709423, 709631, 710645, 712101, 712327,
712385, 714425, 715737, 719095, 719345, 720575, 720797, 721149,
722361, 724101, 724594, 725249, 726869, 727415, 729147, 729399,
729554, 730303, 730639, 730825, 731235, 733381, 734635, 734638,
735034, 737426, 737817, 737891, 742577, 743002, 743774, 744107,
744775, 746697, 748867, 749177, 751502, 751709, 754354, 754377,
754851, 755573, 756613, 757393, 758582, 759115, 759655, 759795,
761349, 761453, 761515, 762671, 763347, 764405, 764855, 768009,
768955, 769119, 770185, 772179, 773605, 773927, 774566, 774706,
775489, 777925, 779433, 781665, 782254, 782391, 782971, 783959,
785213, 785519, 785806, 786335, 787175, 788785, 789061, 790855,
790993, 791282, 792281, 793117, 796195, 796835, 798475, 798721,
800513, 803551, 804287, 804837, 806113, 809042, 809627, 811923,
812045, 812383, 813967, 814055, 814555, 814929, 815269, 816221,
817581, 817663, 818363, 818662, 823361, 824182, 824551, 827421,
828134, 828245, 828269, 828971, 829226, 829939, 830297, 830414,
831575, 831649, 832117, 833187, 833721, 836349, 836969, 837199,
838409, 839523, 839914, 841841, 841935, 843479, 843657, 843755,
845871, 850586, 851105, 852267, 853615, 854335, 858363, 858458,
859027, 860343, 861707, 862017, 862025, 866723, 866822, 868205,
870758, 872053, 872275, 873422, 874437, 876826, 877591, 877933,
878845, 884051, 884374, 885391, 886414, 887777, 888925, 889778,
889865, 891219, 893809, 894179, 894691, 896506, 898535, 898909,
900358, 901945, 906059, 906685, 907647, 908831, 908905, 910385,
910803, 912247, 912373, 912485, 914641, 916487, 917662, 917785,
918731, 919677, 921475, 921557, 921633, 924482, 926497, 926782,
927707, 927979, 929305, 930291, 931209, 932955, 933658, 934743,
935693, 936859, 943041, 947546, 947807, 949003, 950521, 951142,
951171, 951235, 952679, 954845, 955451, 959077, 960089, 961961,
962065, 963815, 964894, 966329, 966575, 969215, 971509, 971618,
973063, 973617, 975415, 978835, 979693, 980837, 983103, 983411,
985025, 986493, 988057, 988418, 989417, 990437, 990698, 990847,
992525, 994449, 994555, 994903, 997165, 997339, 997694, 998223,
998963, 1000195, 1004245, 1004663, 1004705, 1005238, 1006733,
1007083, 1007165, 1012894, 1013173, 1014101, 1014429, 1015835,
1016738, 1016769, 1017005, 1018381, 1021269, 1023729, 1024309,
1024426, 1026817, 1026861, 1028489, 1030285, 1030863, 1032226,
1033815, 1034195, 1036849, 1037153, 1038635, 1039071, 1040763,
1042685, 1049191, 1053987, 1056757, 1057978, 1058529, 1058743,
1059022, 1060975, 1061905, 1062761, 1063145, 1063517, 1063713,
1063865, 1065935, 1066121, 1067857, 1070167, 1070558, 1070797,
1072478, 1073995, 1076515, 1076537, 1078259, 1083047, 1083121,
1084039, 1085773, 1085926, 1086891, 1088153, 1089095, 1094331,
1094951, 1095274, 1096381, 1099825, 1100869, 1101957, 1102045,
1102551, 1103414, 1104299, 1105819, 1106139, 1106959, 1107197,
1114366, 1114503, 1114673, 1115569, 1115661, 1117865, 1119371,
1121549, 1121894, 1123343, 1125655, 1127253, 1131531, 1132058,
1132681, 1133407, 1135234, 1135345, 1136863, 1137873, 1139677,
1140377, 1146442, 1147619, 1155865, 1156805, 1157819, 1159171,
1159543, 1161849, 1162059, 1162213, 1169311, 1171001, 1172354,
1173381, 1175675, 1178709, 1181257, 1182446, 1183301, 1186835,
1186923, 1187329, 1191547, 1192895, 1195061, 1196069, 1196506,
1196569, 1198483, 1199266, 1201915, 1203935, 1206835, 1208938,
1209271, 1210547, 1211573, 1213511, 1213526, 1213563, 1213682,
1215245, 1215487, 1215665, 1216171, 1218725, 1225367, 1227993,
1229695, 1230383, 1234838, 1236273, 1239953, 1242201, 1242989,
1243839, 1244495, 1245621, 1245811, 1255133, 1255501, 1257295,
1257949, 1257962, 1258085, 1259871, 1262723, 1263661, 1266325,
1266749, 1267474, 1268915, 1269359, 1272245, 1272467, 1274539,
1275879, 1277479, 1279091, 1280015, 1281137, 1281865, 1281974,
1282633, 1284899, 1285999, 1286965, 1287687, 1292669, 1293853,
1294033, 1295723, 1299055, 1300233, 1301027, 1302775, 1303985,
1306137, 1306877, 1310133, 1310278, 1314542, 1315239, 1316978,
1322893, 1325467, 1326561, 1329621, 1331729, 1334667, 1336783,
1338623, 1339634, 1340003, 1341395, 1344718, 1344759, 1346891,
1349341, 1349834, 1350537, 1351166, 1353205, 1354111, 1354886,
1356277, 1356901, 1358215, 1362635, 1365581, 1368334, 1370369,
1370386, 1372019, 1376493, 1379035, 1381913, 1386723, 1388645,
1389223, 1389535, 1390173, 1392377, 1393915, 1396031, 1399205,
1400273, 1400487, 1403207, 1403225, 1405943, 1406095, 1406587,
1409785, 1410031, 1412327, 1414127, 1414562, 1416389, 1420445,
1421319, 1422169, 1423807, 1426713, 1428163, 1430605, 1431382,
1432417, 1433531, 1433729, 1433905, 1436695, 1437293, 1442399,
1442926, 1446071, 1447341, 1447873, 1448161, 1448402, 1454089,
1457395, 1457427, 1459354, 1459759, 1465399, 1466641, 1468987,
1469194, 1472207, 1482627, 1483339, 1485365, 1486047, 1486667,
1488403, 1489411, 1492309, 1496541, 1497067, 1497238, 1503593,
1507121, 1507857, 1508638, 1511653, 1512118, 1512745, 1514071,
1515839, 1516262, 1518005, 1519341, 1519817, 1524733, 1525107,
1526657, 1529099, 1531309, 1532795, 1533433, 1536055, 1536639,
1542863, 1544491, 1548339, 1550485, 1552015, 1552661, 1554925,
1557905, 1563419, 1565011, 1566461, 1567247, 1571735, 1575917,
1582009, 1582559, 1583023, 1585285, 1586126, 1586899, 1586967,
1588533, 1589483, 1600313, 1602403, 1604986, 1605837, 1608717,
1612682, 1616197, 1616402, 1617122, 1618211, 1619527, 1622695,
1628889, 1629887, 1635622, 1638505, 1639187, 1641809, 1642911,
1644155, 1655121, 1657415, 1657466, 1661569, 1663705, 1670053,
1671241, 1671549, 1675333, 1681691, 1682681, 1682841, 1685509,
1687829, 1689569, 1690715, 1691701, 1692197, 1694173, 1694407,
1694615, 1698087, 1698619, 1701343, 1701931, 1702115, 1702851,
1706215, 1709659, 1711435, 1711463, 1718105, 1719663, 1721573,
1722202, 1723025, 1727878, 1729937, 1731785, 1734605, 1735327,
1739881, 1742293, 1750507, 1751629, 1753037, 1756645, 1758531,
1760213, 1761319, 1764215, 1769261, 1771774, 1772855, 1773593,
1773669, 1776481, 1778498, 1781143, 1786499, 1790921, 1791946,
1792021, 1794611, 1794759, 1798899, 1801751, 1804231, 1804786,
1806091, 1807117, 1811485, 1812446, 1813407, 1818677, 1820289,
1820523, 1822139, 1823885, 1825579, 1826246, 1834963, 1836595,
1837585, 1843565, 1847042, 1847677, 1849243, 1852201, 1852257,
1852462, 1856261, 1857505, 1859435, 1869647, 1870297, 1872431,
1877953, 1878755, 1879537, 1885885, 1886943, 1891279, 1894487,
1896455, 1901211, 1901501, 1907689, 1908386, 1910051, 1916291,
1920983, 1922961, 1924814, 1929254, 1930649, 1933459, 1936415,
1936765, 1939751, 1944103, 1945349, 1951481, 1952194, 1955635,
1956449, 1957703, 1958887, 1964515, 1965417, 1968533, 1971813,
1973699, 1975103, 1975467, 1976777, 1978205, 1979939, 1980218,
1982251, 1984279, 1987453, 1988623, 1994707, 1999283, 1999591,
1999898, 2002481, 2002847, 2007467, 2009451, 2011373, 2017077,
2019127, 2019719, 2022605, 2024751, 2026749, 2032329, 2040353,
2044471, 2046655, 2048449, 2050841, 2052501, 2055579, 2056223,
2060455, 2062306, 2066801, 2070107, 2070335, 2071771, 2073065,
2076035, 2079511, 2092717, 2099785, 2100659, 2111317, 2114698,
2116543, 2117843, 2120393, 2121843, 2125207, 2126465, 2132273,
2132902, 2137822, 2141737, 2145913, 2146145, 2146981, 2147073,
2150477, 2153437, 2155657, 2164389, 2167055, 2167957, 2170679,
2172603, 2172821, 2176895, 2181067, 2183555, 2188021, 2189031,
2192065, 2193763, 2200429, 2203791, 2204534, 2207161, 2209339,
2210351, 2210935, 2212873, 2215457, 2215763, 2216035, 2219399,
2221271, 2224445, 2234837, 2237411, 2238067, 2241265, 2242454,
2245857, 2250895, 2257333, 2262957, 2266627, 2268177, 2271773,
2274393, 2275229, 2284997, 2285258, 2289443, 2293907, 2294155,
2301817, 2302658, 2304323, 2311205, 2313649, 2316955, 2320381,
2329187, 2330038, 2334145, 2336191, 2338919, 2340503, 2343314,
2345057, 2357381, 2359379, 2362789, 2363153, 2363486, 2367001,
2368333, 2368865, 2372461, 2377855, 2379189, 2382961, 2386241,
2388701, 2396009, 2397106, 2399567, 2405347, 2407479, 2412235,
2416193, 2419023, 2422109, 2424499, 2424603, 2425683, 2428447,
2429045, 2442862, 2444923, 2445773, 2453433, 2459303, 2461462,
2466827, 2469901, 2471045, 2473211, 2476441, 2476745, 2481997,
2482597, 2486199, 2494235, 2497759, 2501369, 2501917, 2505919,
2513095, 2519959, 2532235, 2536079, 2541845, 2542903, 2544971,
2551594, 2553439, 2561065, 2571233, 2572619, 2580565, 2580991,
2581934, 2582827, 2583303, 2585843, 2589151, 2591817, 2592629,
2598977, 2600507, 2603209, 2611037, 2612233, 2614447, 2618629,
2618998, 2624369, 2630257, 2631218, 2636953, 2640239, 2641171,
2644213, 2644945, 2647555, 2648657, 2655037, 2657661, 2667747,
2673539, 2674463, 2676395, 2678741, 2681195, 2681869, 2687919,
2688907, 2700451, 2705329, 2707063, 2707179, 2709239, 2710981,
2711471, 2714815, 2718669, 2732561, 2733511, 2737889, 2738185,
2739369, 2750321, 2758535, 2760953, 2764177, 2766049, 2767787,
2769487, 2770563, 2771431, 2778693, 2785915, 2791613, 2792387,
2798939, 2804735, 2816033, 2820103, 2827442, 2830145, 2831323,
2831647, 2838085, 2857921, 2861062, 2862579, 2865317, 2866105,
2868767, 2884637, 2886689, 2887221, 2893757, 2893881, 2898469,
2902291, 2904739, 2906449, 2915674, 2922029, 2926703, 2928291,
2930885, 2937874, 2939699, 2951069, 2951897, 2956115, 2970327,
2977051, 2986159, 2988073, 2991265, 2997383, 2997797, 2998165,
2999847, 3004603, 3005249, 3007693, 3022345, 3022438, 3025541,
3027973, 3033815, 3033877, 3034205, 3047653, 3055019, 3056977,
3066613, 3068891, 3078251, 3082729, 3085771, 3087095, 3090277,
3093409, 3093459, 3095309, 3101527, 3102449, 3114223, 3120469,
3124979, 3130231, 3137771, 3140486, 3144905, 3147331, 3151253,
3154591, 3159637, 3160729, 3168685, 3170366, 3172047, 3192101,
3197207, 3199353, 3204935, 3206269, 3206733, 3211817, 3230882,
3234199, 3235687, 3243737, 3246473, 3255482, 3267803, 3268967,
3271021, 3275695, 3276971, 3286355, 3292445, 3295331, 3299179,
3306801, 3307837, 3308987, 3316411, 3328039, 3328997, 3332849,
3339611, 3346109, 3349085, 3361795, 3363681, 3372149, 3374585,
3377129, 3377543, 3377915, 3379321, 3381487, 3387215, 3390361,
3400663, 3411067, 3414433, 3415997, 3420835, 3424361, 3425965,
3427391, 3427887, 3445403, 3453839, 3453987, 3457817, 3459463,
3467443, 3479998, 3487583, 3487627, 3491929, 3494413, 3495057,
3502969, 3514971, 3516263, 3518333, 3531359, 3536405, 3537193,
3542851, 3545129, 3545229, 3558583, 3569929, 3578455, 3585491,
3595659, 3604711, 3607315, 3607426, 3610477, 3612791, 3614693,
3617141, 3621005, 3624179, 3628411, 3637933, 3646313, 3648385,
3651583, 3655847, 3660151, 3662497, 3664293, 3665441, 3672985,
3683017, 3692193, 3693157, 3702923, 3706577, 3719573, 3728153,
3735407, 3743095, 3744653, 3746953, 3748322, 3753673, 3765157,
3771595, 3779309, 3779831, 3780295, 3789227, 3790655, 3800741,
3809927, 3816131, 3817879, 3827227, 3827391, 3833459, 3856214,
3860173, 3861949, 3864619, 3872901, 3881273, 3900281, 3915083,
3926629, 3928497, 3929941, 3933137, 3946813, 3946827, 3962203,
3965315, 3973319, 3985267, 3993743, 3997418, 4012465, 4012547,
4024823, 4031261, 4031705, 4035239, 4039951, 4040509, 4041005,
4042687, 4042805, 4050553, 4055843, 4081181, 4086511, 4089055,
4090757, 4093379, 4103239, 4121741, 4131833, 4133261, 4138561,
4143665, 4148947, 4153546, 4170751, 4172201, 4180963, 4187771,
4197431, 4219007, 4221811, 4231283, 4241163, 4247341, 4247887,
4260113, 4260883, 4273102, 4274803, 4277489, 4291593, 4302397,
4305505, 4309279, 4314311, 4319695, 4321933, 4325633, 4352051,
4358341, 4373511, 4375681, 4392287, 4395859, 4402867, 4405999,
4406811, 4416787, 4425499, 4429435, 4433549, 4436159, 4446245,
4449731, 4458389, 4459939, 4467073, 4479865, 4486909, 4502641,
4509973, 4511965, 4531115, 4533001, 4533657, 4554737, 4560743,
4565615, 4567277, 4574953, 4585973, 4586959, 4600897, 4602578,
4609423, 4617605, 4617931, 4619527, 4621643, 4631155, 4632959,
4672841, 4678223, 4688719, 4706513, 4709861, 4710729, 4721393,
4721519, 4724419, 4729081, 4739311, 4742101, 4755549, 4757297,
4767521, 4770965, 4775147, 4777721, 4780723, 4789169, 4793269,
4796351, 4803821, 4812035, 4821877, 4822543, 4823135, 4829513,
4834531, 4846323, 4864057, 4871087, 4875277, 4880485, 4883223,
4884763, 4890467, 4893779, 4903301, 4930783, 4936409, 4940377,
4950545, 4950967, 4951969, 4955143, 4999745, 5009837, 5034679,
5035589, 5047141, 5050241, 5069407, 5084651, 5097301, 5100154,
5107739, 5135119, 5142179, 5143333, 5155765, 5161217, 5178013,
5211503, 5219997, 5222587, 5231281, 5240333, 5258773, 5271649,
5276851, 5280233, 5286745, 5292413, 5296877, 5306917, 5316979,
5321303, 5323153, 5332255, 5343161, 5343899, 5344555, 5357183,
5382871, 5389969, 5397691, 5411139, 5436299, 5448839, 5459441,
5487317, 5511335, 5517163, 5528809, 5538101, 5551441, 5570917,
5579977, 5590127, 5592059, 5606135, 5617451, 5621447, 5622483,
5634343, 5635211, 5644387, 5651522, 5656597, 5657407, 5659927,
5677243, 5690267, 5699369, 5713145, 5724677, 5748431, 5756645,
5761691, 5768419, 5783557, 5784321, 5787191, 5801131, 5818879,
5824621, 5825095, 5827289, 5837009, 5841557, 5852327, 5858285,
5888069, 5891843, 5896579, 5897657, 5898629, 5908715, 5920039,
5964803, 5972593, 5975653, 5992765, 5996127, 5998331, 6009133,
6024007, 6024083, 6027707, 6047573, 6068777, 6107155, 6129013,
6153655, 6159049, 6166241, 6170417, 6182423, 6201209, 6224743,
6226319, 6229171, 6230319, 6243787, 6244423, 6247789, 6268121,
6271811, 6298177, 6305431, 6315517, 6316751, 6322079, 6343561,
6378985, 6387767, 6391861, 6409653, 6412009, 6424717, 6439537,
6447947, 6454835, 6464647, 6468037, 6483617, 6485011, 6503453,
6528799, 6534047, 6547495, 6578045, 6580783, 6583811, 6585001,
6591499, 6595963, 6608797, 6649159, 6658769, 6674393, 6675251,
6679351, 6704017, 6709469, 6725897, 6736849, 6752389, 6791609,
6832679, 6876857, 6883643, 6903867, 6918791, 6930763, 6958627,
6971107, 6979061, 6982823, 6999643, 7005547, 7039139, 7048421,
7050857, 7058519, 7065853, 7068605, 7119281, 7132231, 7139269,
7152655, 7166363, 7172191, 7206529, 7218071, 7229981, 7243379,
7289185, 7292311, 7296893, 7344685, 7358377, 7359707, 7367987,
7379021, 7395949, 7401443, 7424087, 7431413, 7434817, 7451873,
7453021, 7464397, 7465157, 7482377, 7517179, 7525837, 7534519,
7537123, 7556095, 7563113, 7620301, 7624109, 7650231, 7653043,
7685899, 7715869, 7777289, 7780091, 7795229, 7800127, 7829729,
7848589, 7851215, 7858097, 7867273, 7872601, 7877647, 7887919,
7888933, 7903283, 7925915, 7936093, 7947563, 7966211, 7979183,
7998403, 8026447, 8054141, 8059303, 8077205, 8080567, 8084707,
8115389, 8138705, 8155133, 8155351, 8176753, 8201599, 8234809,
8238581, 8258753, 8272201, 8297509, 8316649, 8329847, 8332831,
8339441, 8389871, 8401553, 8420933, 8448337, 8452891, 8477283,
8480399, 8516807, 8544523, 8550017, 8553401, 8560357, 8609599,
8615117, 8642273, 8675071, 8699995, 8707621, 8717789, 8723693,
8740667, 8773921, 8782579, 8804429, 8806759, 8827423, 8869751,
8890211, 8894171, 8907509, 8909119, 8930579, 8992813, 8995921,
9001687, 9018565, 9035849, 9036769, 9099743, 9116063, 9166493,
9194653, 9209263, 9230371, 9303983, 9309829, 9370805, 9379019,
9389971, 9411631, 9414613, 9472111, 9478093, 9485801, 9503329,
9523541, 9536099, 9549761, 9613007, 9622493, 9640535, 9649489,
9659011, 9732047, 9744757, 9781739, 9806147, 9828767, 9855703,
9872267, 9896047, 9926323, 9965009, 9968453, 9993545, 10013717,
10044353, 10050791, 10060709, 10083499, 10158731, 10170301,
10188541, 10193761, 10204859, 10232447, 10275973, 10282559,
10309819, 10314971, 10316297, 10354117, 10383865, 10405103,
10432409, 10482433, 10496123, 10506613, 10511293, 10553113,
10578533, 10586477, 10610897, 10631543, 10652251, 10657993,
10682755, 10692677, 10737067, 10754551, 10773529, 10784723,
10891199, 10896779, 10938133, 10991701, 10999439, 11096281,
11137363, 11173607, 11194313, 11231207, 11233237, 11308087,
11342683, 11366807, 11386889, 11393027, 11394187, 11430103,
11473481, 11473589, 11484911, 11506445, 11516531, 11528497,
11529979, 11560237, 11630839, 11647649, 11648281, 11692487,
11730961, 11731109, 11758021, 11780899, 11870599, 11950639,
12005773, 12007943, 12023777, 12041003, 12124937, 12166747,
12178753, 12179993, 12264871, 12311417, 12333497, 12404509,
12447641, 12488149, 12511291, 12540151, 12568919, 12595651,
12625991, 12664619, 12689261, 12713977, 12726523, 12750385,
12774821, 12815209, 12823423, 12836077, 12853003, 12871417,
12888227, 12901781, 12999173, 12999337, 13018667, 13055191,
13119127, 13184083, 13306099, 13404989, 13435741, 13438339,
13482071, 13496749, 13538041, 13590803, 13598129, 13642381,
13707797, 13739417, 13745537, 13759819, 13791559, 13863863,
13895843, 13902787, 13955549, 13957343, 13990963, 14033767,
14088461, 14128805, 14200637, 14223761, 14329471, 14332061,
14365121, 14404489, 14466563, 14471699, 14537411, 14575951,
14638717, 14686963, 14742701, 14854177, 14955857, 14967277,
15060079, 15068197, 15117233, 15145247, 15231541, 15247367,
15320479, 15340681, 15355819, 15362659, 15405791, 15464257,
15523091, 15538409, 15550931, 15581189, 15699857, 15735841,
15745927, 15759439, 15878603, 15881473, 15999503, 16036207,
16109023, 16158307, 16221281, 16267463, 16360919, 16398659,
16414841, 16460893, 16585361, 16593649, 16623409, 16656623,
16782571, 16831853, 16895731, 16976747, 16999133, 17023487,
17102917, 17145467, 17218237, 17272673, 17349337, 17389357,
17437013, 17529601, 17546899, 17596127, 17598389, 17769851,
17850539, 17905151, 17974933, 18129667, 18171487, 18240449,
18285733, 18327913, 18378373, 18457339, 18545843, 18588623,
18596903, 18738539, 18809653, 18812071, 18951881, 18999031,
19060859, 19096181, 19139989, 19424693, 19498411, 19572593,
19591907, 19645847, 19780327, 19805323, 19840843, 19870597,
19918169, 20089631, 20262569, 20309309, 20375401, 20413159,
20452727, 20607379, 20615771, 20755039, 20764327, 20843129,
20922427, 20943073, 21000733, 21001829, 21160633, 21209177,
21240983, 21303313, 21688549, 21709951, 21875251, 21925711,
21946439, 21985799, 22135361, 22186421, 22261483, 22365353,
22450231, 22453117, 22619987, 22772507, 22844503, 22998827,
23207189, 23272297, 23383889, 23437829, 23448269, 23502061,
23716519, 24033257, 24240143, 24319027, 24364093, 24528373,
24584953, 24783229, 24877283, 24880481, 24971929, 24996571,
25054231, 25065391, 25314179, 25352141, 25690723, 25788221,
25983217, 26169397, 26280467, 26480567, 26694131, 26782109,
26795437, 26860699, 26948111, 26998049, 27180089, 27462497,
27566719, 27671597, 27698903, 27775163, 27909803, 27974183,
28050847, 28092913, 28306813, 28713161, 28998521, 29343331,
29579983, 29692241, 29834617, 29903437, 29916757, 30118477,
30259007, 30663121, 30693379, 30927079, 30998419, 31083371,
31860737, 31965743, 32515583, 32777819, 32902213, 33059981,
33136241, 33151001, 33388541, 33530251, 33785551, 33978053,
34170277, 34270547, 34758037, 35305141, 35421499, 35609059,
35691199, 36115589, 36321367, 36459209, 36634033, 36734893,
36998113, 37155143, 37438043, 37864361, 37975471, 38152661,
39121913, 39458687, 39549707, 40019977, 40594469, 40783879,
40997909, 41485399, 42277273, 42599173, 43105703, 43351309,
43724491, 43825351, 44346461, 45192947, 45537047, 45970307,
46847789, 47204489, 47765779, 48037937, 48451463, 48677533,
49140673, 50078671, 50459971, 52307677, 52929647, 53689459,
53939969, 54350669, 55915103, 57962561, 58098991, 58651771,
59771317, 60226417, 61959979, 64379963, 64992503, 66233081,
66737381, 71339959, 73952233, 76840601, 79052387, 81947069,
85147693, 87598591, 94352849, 104553157]
#This is a table lookup for the hand values for the
#hands not considered in the first two table lookups.
#The index is found using the previous table and the
#prime product value of the hand.
values = [166, 322, 165, 310, 164, 2467, 154, 2466, 163, 3325, 321, 162,
3324, 2464, 2401, 161, 2465, 3314, 160, 2461, 159, 2400, 320,
3323, 153, 2457, 6185, 2463, 3303, 2452, 158, 3322, 157, 298,
2460, 2446, 152, 3292, 156, 2398, 3321, 2462, 5965, 155, 6184,
309, 2456, 3320, 2439, 3313, 2395, 2459, 2431, 2335, 2451, 6181,
3319, 3281, 2422, 151, 2391, 2445, 6183, 2399, 2455, 319, 3291,
2412, 5964, 6175, 2386, 3318, 5745, 150, 2450, 6180, 3312, 3317,
297, 6165, 2458, 2438, 5961, 2430, 2380, 142, 2444, 3311, 308,
3316, 318, 286, 149, 6150, 5963, 6174, 3259, 5525, 3315, 2421,
2397, 2454, 5955, 148, 6182, 2373, 3302, 6164, 2437, 5960, 2411,
5744, 2449, 2365, 3310, 5945, 6178, 2429, 6129, 2334, 2394, 2453,
6179, 6101, 147, 141, 3309, 6149, 5741, 2448, 2356, 2443, 3215,
2269, 5930, 2420, 2396, 5954, 3290, 3248, 3280, 2346, 6065, 6172,
2390, 2410, 3308, 317, 146, 6173, 2442, 5944, 3258, 6128, 3270,
2393, 6020, 3301, 6162, 145, 3289, 5735, 2436, 2385, 5958, 2447,
6100, 5909, 2333, 6169, 6163, 2428, 2332, 5881, 5725, 6177, 316,
5929, 3307, 3300, 6159, 144, 2435, 6147, 3204, 285, 3306, 2379,
6064, 2441, 2389, 6148, 2427, 5524, 2329, 2419, 307, 143, 5845,
3288, 5952, 3214, 3257, 2268, 6019, 5710, 5962, 3160, 2440, 6144,
2384, 2409, 5305, 5908, 3269, 5800, 3305, 3287, 6171, 5942, 5521,
3299, 6126, 2418, 5743, 2392, 6155, 5880, 2372, 2434, 5949, 6176,
6127, 6098, 5959, 3304, 2331, 6161, 2364, 2426, 315, 2325, 2408,
3298, 3094, 6099, 2378, 5689, 140, 2433, 6168, 5939, 3286, 6123,
5740, 5927, 306, 5661, 5844, 6140, 2425, 3213, 2320, 130, 6095,
3279, 2328, 6062, 6158, 2355, 5515, 2417, 2388, 6146, 5085, 5304,
2267, 5799, 3297, 6063, 3149, 6170, 6135, 274, 2432, 5953, 5924,
5523, 6017, 3247, 2371, 2345, 5625, 2407, 5505, 2416, 2383, 3285,
2424, 3278, 6018, 5906, 2314, 6059, 5742, 3159, 5935, 6160, 2363,
6119, 5734, 2387, 6143, 5943, 3237, 3284, 296, 5878, 5580, 6167,
2406, 3256, 6091, 3017, 5520, 2324, 6125, 6014, 5957, 6154, 3083,
3296, 6114, 5724, 2382, 314, 5490, 5903, 2415, 6097, 5739, 2377,
139, 6157, 3295, 2354, 5920, 6086, 6145, 5084, 2319, 5738, 2423,
129, 3093, 5928, 2307, 3283, 5875, 5842, 3212, 3277, 6122, 2405,
2266, 6055, 3203, 3246, 313, 2344, 2299, 305, 6139, 5915, 2203,
6108, 3282, 5709, 6094, 2376, 5522, 3158, 5797, 138, 6061, 3255,
3294, 5514, 6010, 6142, 3276, 5951, 6050, 3193, 5303, 5469, 6080,
284, 2414, 2370, 2313, 5839, 4865, 2381, 6134, 262, 5899, 2263,
5733, 6124, 5956, 6016, 6153, 3236, 5441, 5907, 2413, 3254, 2362,
3293, 2290, 5504, 6005, 5732, 5941, 5301, 5871, 2404, 3006, 6096,
5519, 5794, 6058, 2330, 6166, 304, 5879, 6118, 5894, 5948, 5723,
2929, 3092, 3275, 5688, 2403, 2369, 6044, 2280, 5722, 6090, 6121,
2375, 3016, 5866, 137, 3202, 6013, 5737, 6073, 4645, 5660, 6156,
2306, 5405, 2361, 6138, 312, 2353, 6113, 5729, 5938, 3253, 5081,
5489, 6093, 5999, 2265, 5835, 2327, 5926, 6060, 3211, 2830, 2298,
5843, 2259, 6085, 5950, 2374, 5083, 3226, 136, 273, 128, 5888,
5360, 5708, 2402, 4864, 2343, 6133, 5295, 5719, 5513, 5790, 6054,
6015, 5707, 5830, 3192, 5302, 3157, 3274, 5860, 3210, 6037, 5798,
5624, 2352, 3148, 2254, 6141, 5940, 2137, 2202, 2368, 6107, 2262,
311, 5923, 6057, 3268, 3273, 6029, 5285, 6117, 2289, 5947, 6009,
5503, 5518, 5785, 5731, 3252, 6049, 3245, 5468, 6152, 2360, 6079,
5992, 303, 5579, 5905, 135, 2342, 3138, 5934, 6089, 3015, 2323,
2367, 6012, 5704, 3251, 3156, 295, 2918, 4644, 5440, 5687, 5984,
5824, 5877, 2279, 6112, 3209, 5937, 6004, 5721, 5300, 2248, 4425,
3091, 2359, 3267, 5925, 5686, 5715, 5853, 3082, 5659, 3272, 2720,
6084, 3182, 5728, 6120, 2318, 5270, 3201, 6151, 2928, 5488, 5902,
5779, 2351, 6043, 5658, 6137, 5075, 2819, 2258, 5919, 6053, 6092,
5082, 3225, 2326, 3250, 6072, 2366, 3072, 3271, 134, 5404, 5874,
5975, 3147, 5841, 5512, 3244, 5718, 5080, 2200, 6106, 3090, 2341,
5922, 5683, 5998, 2264, 5706, 2350, 4861, 2829, 6132, 2358, 5065,
5817, 133, 5623, 6008, 5700, 2253, 3208, 250, 5914, 6048, 261,
3249, 2241, 6078, 2201, 5359, 5904, 2312, 5655, 2599, 4863, 5796,
6136, 5933, 5622, 5502, 5294, 5809, 3243, 3266, 3207, 5517, 2340,
5249, 294, 6056, 3235, 2233, 5467, 5772, 6036, 5876, 5578, 5838,
5509, 3137, 6116, 6003, 5695, 5946, 3155, 2136, 5298, 5898, 4424,
2261, 5703, 5221, 4855, 5577, 302, 6131, 3081, 5439, 5764, 6028,
2349, 5284, 132, 6088, 3265, 3014, 5050, 2322, 6011, 2927, 5299,
2247, 5870, 5901, 5991, 3005, 4641, 6042, 5685, 5793, 5619, 5499,
5714, 6111, 2357, 5936, 3089, 5918, 2709, 5679, 5487, 5893, 3181,
3206, 5736, 3242, 6071, 4205, 4643, 2305, 2224, 5873, 5983, 2339,
5657, 131, 6115, 5840, 3200, 6083, 301, 5078, 2317, 5651, 5997,
127, 2995, 5865, 3154, 5574, 5185, 2828, 3071, 2297, 5403, 5755,
2719, 6087, 238, 5511, 3013, 5913, 5674, 2321, 6052, 3205, 5269,
5079, 2199, 2214, 4635, 3264, 5682, 5834, 3127, 5795, 3146, 6110,
5074, 5292, 3985, 3199, 2348, 2257, 118, 5484, 5699, 6105, 5029,
5646, 2071, 3191, 5921, 3224, 6130, 5140, 2240, 5887, 6035, 5358,
5654, 2588, 5837, 5974, 4862, 5621, 6082, 6007, 5501, 2134, 5293,
2316, 6047, 2347, 5897, 126, 5466, 5789, 6077, 5001, 5615, 3241,
2311, 5829, 5495, 4860, 2232, 5932, 5859, 2338, 5064, 6027, 5282,
2288, 5508, 2252, 6051, 5730, 5694, 4845, 2135, 5297, 5869, 3088,
272, 5990, 3004, 5668, 5438, 3153, 5792, 2598, 3240, 3145, 5576,
6002, 2337, 5283, 2197, 6104, 5892, 5570, 4421, 3198, 5516, 5784,
5248, 5610, 4204, 3061, 3263, 5982, 5640, 3080, 3152, 2278, 3012,
5618, 293, 6006, 5498, 6046, 5720, 4625, 5463, 300, 5678, 2926,
4423, 6076, 5864, 5486, 5900, 2310, 6041, 6109, 5220, 4965, 4854,
5931, 2917, 4642, 3262, 2223, 5823, 5480, 2718, 5727, 5917, 5049,
5565, 5267, 5077, 3234, 2246, 5435, 5650, 6070, 5833, 2994, 4640,
2304, 4830, 5402, 5872, 5573, 6081, 3011, 5072, 3239, 3984, 2315,
5852, 6001, 125, 3171, 2336, 3765, 2005, 4415, 5673, 3180, 5996,
283, 4920, 5268, 3087, 5886, 2907, 2213, 3079, 2827, 5778, 5973,
3126, 5604, 2296, 3151, 5475, 5073, 5291, 5717, 2818, 5912, 2925,
5788, 117, 5483, 3197, 5645, 5357, 249, 6040, 5705, 5828, 4858,
3238, 3086, 5184, 5858, 5633, 5062, 292, 2193, 3261, 6103, 299,
124, 5916, 5510, 2133, 3190, 2198, 6069, 5465, 4634, 2597, 2303,
5399, 5559, 3196, 5614, 6034, 3150, 5494, 5836, 4859, 6045, 2808,
5063, 5281, 5816, 5459, 2131, 6075, 226, 5896, 2309, 5028, 5995,
2260, 5783, 5246, 2070, 3144, 5139, 2239, 4610, 2826, 5667, 5437,
3260, 4809, 2295, 3545, 6026, 3136, 2188, 6102, 2287, 5911, 5500,
3233, 5808, 5431, 2984, 2196, 5868, 5354, 5569, 5989, 5702, 3003,
5000, 5218, 4852, 5247, 5609, 5791, 6000, 2916, 3060, 2231, 3085,
5639, 5289, 5771, 5822, 5597, 4781, 4405, 5454, 5507, 6074, 5047,
5891, 2308, 4844, 260, 5296, 123, 3078, 5462, 4201, 4422, 4638,
6033, 5684, 5981, 5219, 3195, 4853, 2277, 5713, 5851, 106, 2924,
5763, 5589, 3232, 5479, 3764, 5895, 5426, 6039, 282, 4420, 5048,
5863, 5564, 5266, 4203, 3084, 5434, 5777, 5552, 4639, 6025, 5656,
5279, 3143, 5401, 2286, 2717, 4390, 5071, 5497, 2817, 5726, 6068,
2182, 3170, 3010, 4624, 2708, 2302, 5395, 5867, 237, 5988, 3002,
5485, 5832, 3194, 4964, 5182, 4589, 2906, 3070, 5069, 3981, 2222,
5544, 5603, 2923, 5994, 2256, 4745, 5474, 5890, 6038, 5076, 271,
2825, 5448, 3009, 4195, 4632, 2294, 5681, 5885, 5980, 291, 5356,
4829, 2276, 5972, 4857, 5910, 4561, 5183, 3983, 5632, 5061, 5815,
2192, 5716, 5754, 5350, 6067, 5698, 2698, 2004, 5026, 4414, 2068,
2301, 5390, 5862, 5787, 4919, 5137, 3231, 5827, 122, 5420, 3116,
2212, 4633, 5653, 5857, 3544, 5059, 5398, 5558, 3125, 4700, 2716,
5620, 5993, 2251, 3189, 5290, 2807, 5807, 5264, 5458, 2130, 6032,
1939, 2824, 116, 5482, 4998, 5027, 5831, 2293, 5245, 2069, 2596,
5138, 121, 2127, 3077, 5770, 3975, 3142, 2587, 2255, 5535, 2187,
5345, 5693, 4842, 2132, 3223, 5782, 2175, 2922, 5430, 2983, 6024,
5884, 5464, 5275, 3008, 5353, 4999, 2285, 5217, 5971, 4851, 5575,
5493, 3135, 5762, 4525, 5288, 3188, 5280, 5596, 3141, 5987, 3001,
5453, 4418, 6031, 5786, 5046, 5701, 5826, 4843, 2896, 2167, 4849,
6066, 4609, 2915, 2300, 4637, 5384, 5856, 2122, 5436, 4808, 2577,
5617, 5821, 5889, 2250, 5044, 105, 4185, 4622, 5588, 2707, 5677,
5979, 2195, 5425, 3007, 2245, 2275, 6023, 4419, 3050, 2595, 4962,
3230, 2284, 5413, 4202, 2823, 3059, 4480, 5712, 120, 5850, 2292,
5551, 4780, 5278, 4404, 5861, 3761, 5986, 3000, 3179, 5781, 5243,
2181, 4369, 4623, 5649, 5461, 5339, 5394, 4200, 2993, 4827, 2715,
5572, 5776, 3229, 4963, 3134, 5181, 2797, 3076, 5260, 5068, 2816,
5543, 5753, 5478, 3763, 4170, 2002, 3140, 4412, 5672, 5978, 4917,
3187, 2274, 5265, 5215, 214, 3105, 3965, 5447, 4341, 2914, 119,
2158, 4631, 6030, 5433, 281, 3069, 5820, 4828, 5400, 4389, 5070,
3075, 3222, 3982, 2116, 5883, 3169, 5349, 115, 2244, 2697, 2003,
5025, 5644, 4413, 5970, 2067, 4629, 5389, 5680, 4918, 2714, 5136,
2921, 4588, 5419, 3115, 5711, 290, 5377, 5849, 6022, 3980, 5255,
2586, 5058, 5814, 2283, 3139, 3755, 4744, 5473, 5697, 5825, 259,
5023, 2065, 5263, 5855, 2148, 5055, 4194, 5985, 2238, 225, 3950,
4997, 5613, 5775, 5355, 2249, 5652, 3541, 4856, 2822, 4560, 3228,
2126, 2291, 5060, 5369, 2815, 3221, 2191, 5806, 5534, 5882, 2594,
5344, 4995, 5969, 4841, 2174, 4149, 4607, 5179, 5332, 5666, 5977,
2230, 5274, 3068, 4806, 4305, 3543, 5769, 5397, 2273, 4699, 5506,
202, 5780, 5239, 289, 5692, 3074, 5457, 4839, 2129, 2194, 1938,
5854, 5568, 3039, 4417, 3186, 5244, 248, 5608, 2895, 2166, 280,
4848, 3227, 2920, 4608, 5324, 5638, 3974, 5383, 2121, 4778, 5813,
4807, 5761, 4402, 2713, 2576, 2186, 5696, 2109, 5211, 2061, 2593,
2973, 5043, 2913, 4621, 5134, 5429, 2237, 4198, 2982, 4260, 5819,
5352, 3185, 3049, 3535, 5216, 4961, 4850, 5412, 5040, 5616, 3929,
6021, 5496, 3073, 5234, 4524, 5287, 2243, 2282, 2687, 5805, 4779,
4403, 5452, 4619, 2706, 5676, 5045, 2101, 5563, 3220, 5242, 3133,
5848, 4959, 2919, 2999, 2229, 5338, 4199, 4636, 5768, 5968, 4826,
2221, 3745, 4387, 3178, 2796, 5259, 5691, 2821, 5206, 4835, 104,
4184, 3168, 2281, 3762, 2912, 2001, 5774, 5424, 4411, 5648, 2992,
4916, 5818, 4824, 5214, 1873, 3104, 4586, 5571, 2814, 2905, 5976,
2998, 5035, 2157, 3978, 4479, 2272, 5315, 5760, 5602, 5277, 4742,
2242, 5752, 3760, 4388, 1999, 4409, 5671, 2115, 5175, 4914, 4192,
2180, 4368, 3067, 5847, 5393, 2592, 2211, 4628, 3124, 3730, 3184,
4121, 4558, 5180, 4587, 5631, 3177, 2820, 5376, 5067, 2190, 3979,
5254, 2712, 2271, 4615, 4169, 2705, 5675, 4743, 5481, 5773, 5228,
5022, 5643, 2064, 2092, 3964, 5446, 2147, 5054, 4340, 4193, 5812,
4630, 2813, 2566, 2220, 5557, 4697, 3132, 2585, 5019, 94, 3901,
4559, 2806, 5368, 5130, 2236, 2128, 2711, 5170, 1936, 5348, 288,
5647, 3525, 236, 5024, 2991, 3219, 2066, 5388, 5200, 4820, 4994,
5612, 3183, 5135, 2911, 5492, 4606, 5178, 5418, 5331, 3114, 3972,
5804, 5967, 4805, 2997, 3542, 5057, 2185, 5751, 4698, 3754, 4991,
1995, 1807, 2962, 5238, 5670, 2082, 2228, 5262, 4838, 279, 5767,
1937, 3949, 4604, 2210, 3038, 4996, 5665, 5811, 3218, 3123, 4803,
3540, 5690, 5846, 5014, 2056, 4085, 2125, 5323, 4522, 5286, 3973,
5595, 5966, 4777, 5125, 4401, 3709, 2235, 2270, 114, 3176, 5343,
2108, 5210, 5642, 2060, 3510, 5567, 2972, 4840, 2173, 5607, 4148,
5133, 4197, 5759, 3058, 2591, 2996, 5273, 4304, 5637, 5803, 2584,
4775, 4399, 5039, 2812, 4986, 103, 5233, 4182, 4523, 5587, 2686,
2227, 4618, 190, 5460, 5766, 2885, 4416, 2100, 5611, 5491, 5164,
2894, 2165, 4958, 4847, 4040, 4477, 3066, 5550, 2590, 5382, 3028,
2120, 5276, 2704, 3131, 287, 5477, 3758, 4386, 4955, 3865, 5042,
5205, 4834, 5562, 2179, 4183, 4366, 4620, 2219, 4600, 5664, 4259,
5432, 5758, 5193, 4799, 3048, 3534, 4960, 4823, 3217, 213, 4585,
5411, 3928, 4384, 5066, 5034, 3977, 4478, 5810, 5542, 5314, 4167,
3130, 2710, 4741, 2990, 270, 5008, 3759, 2050, 1998, 5566, 4408,
5241, 5119, 5174, 5606, 4913, 3962, 2234, 4338, 4191, 3057, 4367,
4583, 5337, 2904, 5636, 3489, 5750, 2786, 4825, 3744, 4771, 1990,
4395, 5601, 2703, 5669, 2910, 4557, 4739, 2795, 5472, 4910, 3820,
5258, 5802, 4950, 3681, 2209, 4614, 2696, 4168, 2000, 3175, 4189,
4410, 247, 4980, 2218, 5227, 4915, 3216, 5213, 2091, 1872, 3103,
2226, 3113, 3963, 4339, 5765, 4555, 2156, 2565, 5630, 5056, 2589,
4696, 113, 5476, 3752, 5018, 5641, 93, 2811, 2989, 4815, 2114,
5129, 5561, 5261, 3645, 5169, 1935, 3947, 3174, 2583, 4627, 5199,
3538, 4819, 5396, 5556, 5749, 5157, 3729, 82, 4694, 4120, 4380,
2124, 3065, 3971, 5375, 5757, 4905, 2805, 5253, 5533, 5456, 258,
3753, 4990, 2208, 3129, 1994, 1933, 201, 2961, 3122, 5021, 2172,
2063, 2081, 4146, 4579, 2146, 5053, 2903, 5272, 3948, 4603, 4302,
3969, 178, 4802, 5600, 3539, 5149, 4735, 112, 5471, 3900, 5013,
3064, 2055, 2909, 4521, 5367, 4595, 5124, 2702, 5663, 5428, 2874,
2043, 2981, 3524, 5351, 2582, 4944, 5112, 4993, 278, 2164, 4846,
4147, 4605, 4551, 5177, 5330, 2217, 5629, 2119, 3461, 4804, 4303,
4519, 2189, 2575, 5594, 4774, 3128, 4398, 5451, 1806, 5237, 4985,
5605, 5041, 5801, 4181, 3056, 4837, 5635, 4257, 4973, 1741, 224,
2035, 3037, 2884, 2951, 3047, 3532, 3173, 5555, 5104, 4690, 2225,
5163, 3926, 2908, 4476, 4084, 5322, 2804, 3425, 3027, 4776, 5748,
5455, 102, 4179, 4400, 3708, 5586, 1984, 3757, 1929, 5662, 5423,
4794, 2107, 4899, 5209, 4954, 5240, 2059, 3509, 2810, 2971, 4365,
5132, 2207, 4196, 4599, 2775, 4258, 4474, 3121, 3742, 5192, 4798,
5549, 3533, 2184, 277, 5038, 5560, 5257, 2676, 3927, 4383, 5756,
5232, 3063, 2685, 4166, 5427, 235, 111, 3600, 2980, 4363, 4617,
5007, 5634, 2049, 5392, 3172, 4766, 2099, 5212, 1870, 4375, 3102,
5118, 3961, 4957, 4337, 2155, 4039, 4582, 4515, 3167, 2581, 5593,
2785, 3743, 4770, 5541, 1989, 4394, 5450, 4164, 4385, 4738, 4909,
2113, 2809, 3864, 4574, 5204, 4949, 4833, 2701, 2902, 3959, 5445,
4335, 4188, 4626, 4979, 5599, 4937, 2026, 5470, 3727, 4118, 4822,
1871, 4584, 5095, 2216, 5033, 4554, 3976, 3062, 5252, 5313, 4175,
5585, 3380, 3751, 4740, 5422, 5347, 2695, 1997, 5020, 4407, 2062,
4814, 5387, 4546, 5173, 4912, 2940, 2700, 2145, 5628, 5052, 4190,
3946, 2988, 5417, 269, 4470, 4788, 5548, 3488, 4929, 3537, 3166,
5156, 3728, 3898, 81, 4693, 4119, 3749, 4556, 4379, 2215, 3819,
4904, 5747, 3680, 1977, 2178, 4359, 4613, 2901, 3522, 5391, 5554,
1932, 3944, 4892, 2016, 4992, 5226, 5598, 4145, 4730, 2090, 2555,
3055, 5176, 2206, 4578, 2803, 2987, 3120, 2123, 4301, 2564, 4760,
3968, 5540, 1675, 1924, 4695, 4160, 5148, 5017, 4734, 1804, 5532,
5236, 92, 3899, 5342, 5128, 4836, 5746, 4594, 3644, 110, 3955,
5444, 1969, 5168, 4143, 1934, 4331, 2873, 5627, 3036, 2042, 3523,
4884, 2183, 4299, 5198, 4943, 5111, 4818, 4082, 2205, 4550, 3970,
2580, 3119, 2979, 4518, 3706, 5346, 2694, 4989, 1993, 2106, 5208,
1805, 2960, 2058, 3507, 5386, 5553, 2970, 4685, 2080, 5131, 2893,
109, 4510, 5416, 3112, 4256, 4972, 189, 5592, 2802, 4602, 2034,
2950, 5381, 3531, 5449, 2118, 4801, 5103, 4689, 2574, 1918, 5037,
2665, 3925, 5012, 5231, 2054, 4083, 4520, 2579, 276, 3165, 5123,
4178, 3707, 4616, 1983, 1928, 3940, 2098, 4254, 4793, 4898, 3508,
268, 3529, 4956, 4568, 4037, 2900, 5410, 101, 2863, 3923, 2774,
5584, 3460, 4473, 3741, 2986, 5421, 4724, 2978, 4773, 5531, 4397,
5341, 2675, 4984, 3862, 5203, 4832, 4180, 2171, 4139, 4465, 2699,
5547, 4362, 1740, 1960, 5271, 5336, 2883, 4295, 5591, 4765, 4821,
3739, 1869, 4374, 4875, 3054, 4540, 5162, 5626, 5032, 4038, 2794,
4475, 4753, 2204, 2177, 4514, 3424, 4354, 3026, 3118, 3756, 4163,
1996, 4406, 4953, 5172, 3863, 4911, 4573, 2892, 2163, 1867, 4364,
3101, 3958, 4598, 5539, 4334, 3486, 108, 5380, 2985, 100, 4155,
5191, 4936, 4797, 5583, 4679, 2025, 3726, 2573, 4117, 3053, 5094,
3817, 2801, 4382, 2764, 5443, 3678, 2112, 4326, 4174, 4612, 4165,
70, 2578, 3599, 1950, 5006, 4250, 5546, 5225, 2048, 3046, 2544,
2089, 5117, 4545, 3960, 3724, 5409, 2939, 4115, 4336, 3919, 4581,
275, 4469, 4787, 5374, 3487, 3117, 2784, 4928, 2176, 2693, 4769,
4348, 1988, 5016, 4393, 91, 3897, 5385, 3748, 4737, 4908, 5127,
3818, 3164, 5415, 4948, 3642, 246, 5167, 3679, 223, 1976, 4358,
3521, 107, 5051, 5335, 4187, 4978, 3943, 4891, 5538, 5197, 2015,
4817, 3735, 2852, 4729, 212, 2554, 2793, 3895, 4504, 5256, 4553,
5590, 4759, 5366, 4717, 177, 1923, 3935, 5442, 3379, 3750, 4320,
4159, 4988, 1992, 1803, 2959, 3519, 2079, 4813, 3163, 1863, 257,
3643, 3954, 1968, 4142, 3945, 4601, 4330, 2154, 5329, 4883, 5530,
4800, 4298, 3536, 5340, 4533, 5155, 2692, 80, 4692, 2899, 5011,
4378, 2053, 4081, 3052, 1801, 2170, 99, 4134, 4903, 5582, 5122,
3705, 4709, 5414, 3111, 4290, 1931, 3506, 3035, 4684, 3720, 4144,
4111, 4577, 4459, 4509, 3458, 5373, 5545, 4079, 4300, 5321, 3967,
4672, 5251, 1674, 4772, 4396, 3703, 1917, 2753, 5147, 2664, 4733,
2800, 4983, 2891, 2105, 2162, 2057, 3504, 267, 1911, 4593, 5379,
1738, 2144, 2117, 2872, 3939, 2882, 2041, 2572, 4253, 4942, 5110,
5529, 5161, 3528, 4567, 4036, 3891, 3051, 5036, 4549, 2862, 3922,
3422, 3025, 5365, 5537, 3459, 2169, 4517, 4664, 4128, 4245, 4723,
2684, 3045, 3515, 4284, 4952, 200, 3861, 5408, 2097, 3914, 2977,
1903, 4138, 4464, 4597, 3162, 5328, 4034, 4255, 4971, 1739, 1959,
5190, 2033, 4796, 4294, 2949, 3530, 3738, 5102, 4874, 4688, 4539,
3924, 4381, 1797, 4497, 5235, 2898, 4752, 3423, 3859, 4353, 2890,
2161, 4831, 5334, 3597, 4177, 2691, 1982, 5005, 1927, 2047, 2654,
5378, 256, 4792, 4897, 2571, 5116, 2792, 2976, 3110, 1866, 4580,
4075, 5320, 3485, 2773, 5031, 2783, 4472, 3740, 4154, 4768, 1987,
4678, 5312, 4392, 3699, 4736, 4239, 4907, 3816, 4489, 2674, 98,
5207, 1858, 234, 245, 3500, 5581, 4947, 2969, 2763, 3677, 4325,
5407, 2153, 3161, 69, 3908, 4186, 3598, 4977, 1949, 4361, 4249,
3483, 4764, 2543, 1868, 4373, 3723, 4452, 2111, 4114, 4552, 3918,
2897, 5230, 3814, 4513, 3377, 2683, 5528, 3675, 4347, 4655, 4611,
5333, 4162, 4812, 3715, 97, 4106, 2168, 2799, 2841, 4572, 3641,
5372, 2088, 2791, 4030, 3957, 5250, 1894, 4333, 2563, 4935, 3734,
5154, 2024, 3725, 2851, 79, 4691, 4116, 4377, 5015, 4444, 5093,
90, 3894, 5536, 4902, 4503, 3855, 5202, 1852, 2143, 3100, 4173,
4716, 3934, 3378, 3639, 4319, 2152, 1930, 3518, 3886, 2889, 2160,
4816, 4313, 1862, 4544, 4576, 2938, 5364, 2975, 2110, 3966, 4468,
4786, 1672, 5311, 2570, 4927, 5146, 2533, 4732, 4532, 3896, 3747,
4987, 1991, 1800, 2958, 2798, 4133, 4592, 2643, 5171, 5327, 4100,
2078, 2690, 4708, 1975, 2871, 4357, 2040, 1884, 4289, 5371, 3520,
3942, 3044, 4890, 3479, 4941, 5109, 2014, 1792, 5406, 3109, 3719,
4728, 2742, 4110, 2553, 4548, 4458, 3457, 5010, 3810, 2052, 4078,
4516, 4758, 4671, 3671, 1673, 1922, 2142, 3034, 4158, 3702, 2752,
1802, 5224, 3503, 96, 4070, 1910, 5319, 3880, 2689, 3953, 2974,
1967, 4970, 1737, 4141, 4329, 2032, 5363, 2948, 3694, 2562, 3455,
4882, 4297, 5101, 4687, 2790, 2104, 3108, 89, 3495, 3890, 2968,
4080, 3421, 4982, 4435, 5126, 5527, 4176, 4663, 3704, 4127, 3635,
1981, 5166, 4244, 5326, 1926, 1735, 3514, 4791, 4896, 4283, 3505,
266, 5196, 1845, 3099, 4683, 3913, 1902, 1786, 2151, 5229, 4277,
4508, 2772, 4033, 4471, 2682, 3419, 3024, 1916, 2663, 2096, 233,
2673, 1796, 4496, 255, 4951, 95, 4025, 3858, 5526, 3596, 4360,
4064, 5318, 3938, 2653, 4596, 4763, 4252, 211, 4372, 3688, 2159,
4795, 4093, 3527, 4566, 4035, 3850, 5370, 2103, 5201, 2051, 4269,
4074, 2522, 2861, 4512, 3921, 2967, 2569, 5121, 3698, 4722, 4161,
3594, 4238, 5004, 4488, 2046, 1857, 3860, 3499, 4571, 2141, 5030,
4137, 3956, 4232, 4463, 3907, 4332, 5310, 188, 3043, 3451, 1958,
4934, 4293, 2023, 2681, 3482, 2888, 265, 3737, 4767, 4873, 3873,
1986, 5092, 4391, 4538, 4451, 5362, 3107, 2095, 4906, 4751, 3813,
4172, 2568, 4352, 3376, 4946, 3674, 4019, 3474, 4654, 1731, 2881,
4976, 3714, 4105, 4543, 2840, 2937, 5160, 3805, 5325, 1865, 4224,
4029, 4467, 4785, 3666, 1893, 3844, 3484, 3042, 3415, 3023, 4926,
4153, 4677, 2789, 3374, 3746, 1779, 5223, 4443, 3815, 2087, 3854,
2762, 4811, 3676, 1851, 1974, 4324, 4356, 68, 2561, 3638, 3033,
2688, 3941, 1948, 4889, 4248, 2013, 5309, 5189, 58, 3098, 2542,
3885, 4727, 2552, 4312, 2150, 3722, 4057, 5317, 78, 3106, 4113,
3917, 4376, 4757, 3630, 5165, 1671, 1921, 4901, 2632, 4157, 4346,
2532, 3590, 199, 2102, 5195, 2045, 3468, 222, 2642, 5115, 3640,
4099, 3952, 1966, 4140, 4328, 1883, 4575, 3799, 4881, 4296, 3478,
3660, 2782, 1837, 3733, 3097, 1985, 1669, 2850, 1791, 2957, 2887,
2741, 2149, 4731, 2077, 3893, 5222, 4502, 3809, 2680, 2086, 3670,
4715, 3933, 4591, 2567, 4318, 2870, 2560, 2094, 2039, 3517, 4682,
4940, 2140, 5009, 1861, 4012, 88, 4069, 3879, 4507, 4547, 5120,
4215, 3693, 3454, 3624, 3041, 2731, 3370, 1915, 2662, 4531, 3494,
5361, 3837, 1799, 5194, 4810, 4434, 4132, 3634, 4707, 3446, 3937,
4288, 4251, 4969, 1734, 2031, 2947, 3526, 1844, 4565, 5153, 2886,
3718, 2139, 4981, 77, 4686, 4109, 1785, 2956, 2860, 3920, 4457,
4276, 3456, 5308, 4077, 2076, 4670, 3418, 4721, 1726, 176, 1771,
2880, 3701, 2751, 1980, 1925, 2788, 5159, 4790, 4895, 3502, 4024,
4136, 4462, 1909, 3032, 3410, 1736, 244, 4063, 1957, 2511, 4292,
2771, 3040, 1665, 3736, 4872, 3687, 4092, 4537, 5145, 1828, 5316,
3096, 3889, 3792, 3849, 4750, 4268, 2521, 264, 3420, 4351, 3653,
4590, 4662, 4126, 4243, 46, 254, 5188, 2038, 3593, 3440, 2966,
3513, 4282, 2085, 5108, 4762, 1864, 3912, 4371, 1901, 4231, 3031,
2559, 4032, 3450, 4152, 4676, 3585, 4511, 5003, 87, 3872, 1720,
4049, 2787, 2879, 1795, 4495, 5114, 2761, 2679, 4323, 3617, 3857,
5158, 4570, 67, 3595, 4018, 1947, 3473, 4247, 2093, 1730, 2781,
2652, 2030, 3404, 232, 2965, 2946, 2541, 4933, 5100, 2022, 1818,
3095, 3721, 4112, 3804, 3916, 4223, 2138, 4945, 4073, 3665, 3843,
3414, 4345, 4171, 3697, 4975, 1979, 3373, 1778, 221, 4237, 3829,
5187, 4789, 4487, 2075, 1856, 3498, 2678, 4542, 3906, 2936, 253,
3365, 4466, 3732, 4784, 57, 2849, 3481, 4925, 3579, 4004, 5002,
3892, 4450, 2044, 4056, 4501, 2672, 5307, 3629, 3812, 5113, 4714,
2631, 3932, 3375, 4317, 3673, 1973, 3589, 4653, 4355, 3516, 3467,
1762, 5152, 2780, 4888, 3713, 4761, 76, 2012, 4104, 1860, 4370,
2839, 4726, 263, 4900, 4028, 3433, 3798, 1892, 3030, 3659, 4756,
1836, 4530, 1668, 1920, 4156, 3784, 4974, 1798, 4442, 4131, 2621,
5306, 3853, 4569, 1850, 4706, 4287, 1713, 3637, 3951, 1965, 2878,
1660, 4327, 2084, 5144, 4880, 2021, 3359, 3717, 2964, 3884, 4108,
4311, 4011, 4456, 5091, 2558, 4076, 3397, 3022, 4669, 4214, 1670,
2869, 3623, 86, 3700, 2730, 3369, 2750, 2531, 1752, 4939, 5107,
3836, 3501, 3609, 5151, 1908, 2641, 4541, 4681, 4098, 187, 2935,
3445, 1882, 4506, 3029, 5186, 4783, 3477, 2083, 1790, 3888, 2740,
1914, 2661, 3995, 2557, 3808, 4661, 4125, 3669, 4242, 3572, 4968,
1725, 1972, 85, 1770, 2955, 243, 3512, 4281, 3936, 2074, 5099,
2011, 1654, 2963, 3911, 2610, 5143, 1900, 4725, 2551, 4068, 3878,
4564, 4031, 3409, 2510, 2859, 2779, 3692, 4755, 3453, 1978, 1664,
1919, 2868, 4720, 2037, 1827, 4894, 1794, 4494, 3493, 3791, 4938,
5106, 3856, 4433, 3652, 2677, 3633, 2770, 1964, 4135, 4461, 2651,
45, 2954, 3439, 1733, 1956, 2073, 4291, 1843, 2671, 4871, 2500,
1784, 4536, 4072, 4275, 4749, 3352, 3584, 3696, 3417, 4350, 4236,
4967, 1719, 2029, 4048, 4486, 1855, 2945, 3497, 3775, 5098, 4680,
3616, 4023, 1705, 3905, 210, 4505, 4062, 3403, 3480, 5150, 4151,
3686, 75, 4675, 4091, 1817, 4449, 1913, 252, 3848, 3389, 3021,
4893, 4267, 3811, 2520, 2556, 2760, 3672, 4322, 4652, 66, 4932,
2769, 3592, 84, 1946, 3828, 3712, 4246, 4103, 2838, 5090, 2540,
4563, 4027, 1696, 4230, 2670, 1891, 2877, 2858, 3915, 3449, 1647,
3364, 5142, 4719, 3578, 3871, 4344, 4003, 4441, 2489, 3020, 3852,
1849, 2934, 3564, 3636, 2867, 4460, 4017, 2036, 3472, 1729, 4924,
1955, 1761, 2953, 5105, 3883, 3731, 4310, 2072, 2848, 4535, 3803,
4222, 3432, 2778, 3664, 175, 4748, 3842, 4500, 1971, 3413, 4349,
2530, 4713, 3931, 4887, 3372, 83, 1777, 4316, 3783, 4931, 2020,
2620, 2550, 2640, 4097, 3555, 5089, 1859, 1881, 4966, 1712, 2028,
1659, 220, 3476, 4150, 56, 5097, 4674, 1789, 3358, 2739, 4529,
4055, 3807, 3396, 198, 3628, 3344, 2759, 3668, 1963, 4130, 2630,
4321, 231, 65, 4705, 3588, 4879, 1945, 4286, 4782, 1751, 2952,
3466, 4923, 3608, 251, 4067, 3877, 3716, 4107, 2768, 3797, 4455,
3691, 34, 3452, 2876, 3658, 74, 4668, 1835, 4343, 1667, 3492,
2669, 2749, 4886, 2010, 3994, 4432, 3335, 3019, 3632, 2549, 3571,
1907, 1732, 4754, 1842, 1653, 1912, 2660, 2847, 2609, 1783, 4010,
4274, 3887, 4499, 1639, 4213, 3416, 5141, 4712, 3622, 3930, 73,
4660, 2729, 4124, 3368, 4315, 4241, 4878, 3511, 3835, 4280, 4562,
4022, 209, 242, 3910, 4061, 3444, 1899, 1686, 4930, 2875, 2019,
3685, 4090, 4528, 5088, 3847, 2499, 4266, 2519, 1793, 4493, 1630,
4129, 3018, 3351, 2777, 1724, 4704, 1954, 1769, 3591, 4285, 2650,
4870, 3774, 4534, 219, 2659, 4229, 2866, 1704, 2027, 4454, 3408,
2944, 3448, 2509, 4071, 4922, 5096, 4667, 1663, 3870, 3695, 2748,
1826, 3790, 4235, 3388, 4485, 1854, 3651, 3496, 1970, 4016, 1906,
3471, 2478, 1728, 44, 2857, 3904, 4885, 3438, 2009, 4718, 2548,
3802, 4221, 2767, 1695, 241, 4448, 3663, 3841, 2943, 3412, 1646,
64, 2776, 3583, 4659, 4123, 1944, 3371, 4240, 1776, 2668, 1718,
72, 4651, 4047, 2539, 4279, 2488, 3711, 4869, 4102, 3615, 3563,
3909, 1962, 2837, 1898, 4026, 4747, 4877, 3402, 55, 1890, 4342,
1816, 4054, 197, 4492, 4440, 3627, 2629, 3851, 1848, 1620, 3587,
2667, 3465, 2649, 3827, 2846, 4673, 3882, 3554, 4498, 4309, 3796,
2865, 2018, 2758, 3657, 3363, 1834, 4314, 1666, 63, 2658, 5087,
3577, 71, 2529, 4002, 4234, 4484, 1853, 2538, 3343, 2639, 4096,
3903, 1880, 1760, 4527, 3475, 2933, 4009, 1788, 4447, 2856, 2738,
3431, 4212, 4921, 33, 3806, 2017, 3621, 22, 2942, 2728, 3367,
3667, 5086, 4650, 3782, 3834, 3710, 2619, 4101, 230, 2836, 3334,
4453, 3443, 4066, 3876, 1711, 2864, 1953, 2008, 1889, 1658, 3690,
4711, 4868, 2747, 2547, 3357, 2932, 4439, 3491, 4746, 3395, 1638,
1905, 2766, 4431, 1847, 1723, 1768, 3631, 1750, 186, 3607, 3881,
1961, 1841, 4308, 3407, 2508, 1782, 4876, 1685, 4273, 2007, 4122,
2941, 1662, 4703, 2546, 2528, 1825, 4278, 3789, 3993, 2757, 3650,
1629, 1897, 2638, 4095, 4021, 3570, 43, 1943, 3437, 1879, 4060,
4666, 2537, 1652, 2608, 3684, 1787, 4491, 229, 4089, 2737, 3846,
2765, 4265, 2518, 3582, 1904, 2657, 240, 1717, 4046, 2666, 3614,
4065, 3875, 2477, 4228, 3401, 3689, 3447, 4658, 2845, 1815, 4233,
4483, 208, 3869, 3490, 2931, 2498, 4430, 4710, 3902, 3350, 1896,
2656, 4015, 3826, 3470, 1727, 3773, 1840, 4446, 1703, 1781, 1952,
3801, 4272, 4220, 3362, 3662, 3840, 4867, 3411, 2006, 4526, 3576,
4001, 2648, 2545, 2855, 1775, 3387, 2835, 4020, 4702, 1619, 1888,
4059, 1759, 3683, 54, 4088, 4438, 2930, 3430, 1694, 3845, 1951,
4053, 1846, 4264, 2517, 4665, 1645, 3626, 4866, 2628, 2746, 3781,
3586, 2756, 2618, 2487, 3464, 4307, 62, 3562, 1710, 1942, 4227,
1657, 3795, 2536, 239, 3356, 3656, 1833, 4649, 3868, 174, 3394,
2637, 4094, 4657, 2834, 21, 1878, 4014, 3469, 1749, 1887, 185,
196, 3606, 2736, 61, 3553, 3800, 1941, 4008, 4219, 3661, 3839,
207, 2535, 4211, 3620, 2727, 3366, 1774, 4490, 3992, 2854, 3833,
3874, 3342, 4306, 3569, 2647, 3442, 1651, 53, 2607, 2527, 4052,
4429, 32, 3625, 228, 2844, 2627, 1722, 1877, 2655, 1767, 4482,
1839, 3463, 4701, 1780, 3333, 4271, 2735, 3794, 3406, 2507, 3655,
1832, 1661, 4445, 2497, 1824, 2853, 3788, 1637, 3349, 3649, 4058,
2745, 4648, 42, 3682, 3436, 4087, 3772, 218, 2755, 1702, 4007,
4263, 2516, 60, 1684, 1940, 4210, 3619, 3581, 2726, 2534, 4437,
3386, 1716, 4045, 3832, 4656, 1838, 1628, 4226, 3613, 195, 3441,
4270, 3400, 3867, 1895, 1693, 1814, 1644, 4013, 2526, 1721, 1766,
2843, 2486, 3825, 2636, 2754, 4086, 3561, 4218, 59, 2646, 3838,
2476, 3405, 4262, 227, 2506, 3361, 173, 1773, 217, 3575, 1823,
4000, 3787, 3648, 4225, 41, 4481, 52, 3435, 1758, 4051, 3866,
3552, 2645, 2626, 3429, 3580, 2842, 3462, 1715, 4044, 3780, 4428,
3341, 2617, 3612, 4647, 3793, 1618, 4217, 1709, 3654, 2744, 1831,
3399, 1656, 206, 3355, 1813, 1772, 1886, 31, 3393, 4436, 3824,
1748, 51, 4006, 3332, 3605, 4646, 4050, 4209, 3618, 2725, 3360,
2625, 2833, 3574, 3999, 3831, 1885, 2515, 1636, 3991, 2525, 20,
3568, 2743, 1757, 2635, 1830, 1650, 1876, 2606, 1683, 3428, 184,
1765, 2734, 3779, 1627, 2616, 2524, 4005, 2505, 1708, 1655, 4208,
2634, 1822, 2724, 3354, 3786, 1875, 3647, 3830, 2496, 3392, 40,
3348, 3434, 194, 1747, 4427, 3604, 3771, 2475, 1701, 2644, 50,
1714, 4043, 1764, 2832, 3990, 3611, 3385, 216, 3567, 3398, 2504,
4426, 1812, 1649, 2605, 1821, 3785, 1692, 3646, 1829, 1643, 3823,
39, 4261, 2514, 2485, 1617, 3560, 2523, 3573, 3998, 2831, 183,
4042, 2495, 1874, 3610, 2723, 3347, 1756, 2733, 2513, 3770, 1811,
3427, 1700, 3551, 3778, 4216, 2615, 3822, 3384, 19, 1707, 3340,
1763, 172, 3353, 2633, 3997, 3391, 1691, 215, 1642, 30, 1820,
1746, 2732, 3603, 1755, 2484, 2624, 3559, 3331, 38, 3426, 3989,
3777, 2614, 49, 3566, 1635, 1706, 4041, 1648, 2604, 2623, 2512,
3550, 3390, 1682, 1810, 1745, 4207, 3602, 205, 3339, 1626, 3821,
2494, 3988, 3346, 29, 3565, 3996, 3769, 4206, 171, 1699, 2603,
193, 3330, 2474, 1754, 3383, 2503, 1634, 48, 3776, 2613, 1690,
37, 182, 2493, 1641, 1681, 3345, 2483, 2502, 3558, 3768, 1625,
1698, 1819, 1616, 1744, 3601, 3382, 47, 3987, 3549, 2622, 1689,
2722, 2473, 1640, 2602, 3338, 2482, 3557, 1809, 18, 28, 1753,
2492, 3329, 2501, 3548, 2721, 1615, 204, 3767, 1697, 1633, 36,
3337, 3381, 1680, 1743, 27, 2612, 1688, 1624, 170, 3328, 17,
1808, 2481, 3556, 35, 1632, 2601, 2472, 1679, 3986, 3547, 1623,
192, 203, 3336, 3766, 181, 26, 1614, 2471, 2491, 3327, 1742,
1687, 1631, 2480, 2611, 1678, 16, 1613, 180, 1622, 191, 3546,
2490, 2470, 15, 2600, 25, 3326, 169, 24, 1612, 2479, 1677, 1621,
1676, 14, 168, 2469, 2468, 1611, 23, 1610, 13, 179, 12, 167, 11]
def binary_search(list_to_search, val):
first = 0
last = len(list_to_search)-1
index = -1
while (first <= last) and (index == -1):
mid = (first+last)//2
if list_to_search[mid] == val:
index = mid
else:
if val<list_to_search[mid]:
last = mid -1
else:
first = mid +1
return index
def encode_card(text):
"""
Function encodes a card (eg.: "4D") into a number such that its
binary representation follows the schema:
+--------+--------+--------+--------+
|xxxbbbbb|bbbbbbbb|cdhsrrrr|xxpppppp|
+--------+--------+--------+--------+
b = bit turned depending on rank of card
cdhs = suit of card (bit turned on based on suit of card)
r = rank of card (two=0, three=1, ..., ace=12)
p = prime number of rank (two=2, three=3, four=5, ..., ace=41)
"""
prime_number_dict = {"2":2, "3":3, "4":5, "5":7, "6":11, "7":13, "8":17,
"9":19, "T":23, "J":29, "Q":31, "K":37, "A":41}
card_number_dict = {"2":0, "3":1, "4":2, "5":3, "6":4, "7":5, "8":6,
"9":7, "T":8, "J":9, "Q":10, "K":11, "A":12}
card_suit_dict = {"C":8, "D":4, "H":2, "S":1}
card_bit_dict = {"2":1, "3":2, "4":4, "5":8, "6":16, "7":32, "8":64,
"9":128, "T":256, "J":512, "Q":1024, "K":2048, "A":4096}
card_number = "2"
card_suit = "C"
try:
card_prime_number = prime_number_dict[text[0]]
card_number = card_number_dict[text[0]]
card_suit = card_suit_dict[text[1]]
card_bit = card_bit_dict[text[0]]
except:
print("Oops!",sys.exc_info()[0],"occurred.")
return (card_bit<<16)+(card_suit<<12)+(card_number<<8)+card_prime_number
def evaluate_hand(hand):
cards=[]
hand_value = 0
for card in hand:
cards.append(encode_card(card))
is_flush = cards[0]&cards[1]&cards[2]&cards[3]&cards[4]&int(0xF000)
if (is_flush):
hand_value = flushes[(cards[0]|cards[1]|cards[2]|cards[3]|cards[4])>>16]
else:
hand_value = unique5[(cards[0]|cards[1]|cards[2]|cards[3]|cards[4])>>16]
if hand_value!=0:
hand_final_value = hand_value
else:
prime_mult = (cards[0]&int(0xFF))*(cards[1]&int(0xFF))*(cards[2]&int(0xFF))*(cards[3]&int(0xFF))*(cards[4]&int(0xFF))
hand_final_value = values[binary_search(products, prime_mult)]
return hand_final_value
class PokerHand:
def __init__(self, cards):
self.cards = cards.split()
def hand_value(self):
hand_final_value = evaluate_hand(self.cards)
return hand_final_value
def compare_with(self,new_poker_hand):
first_value = self.hand_value()
second_value = new_poker_hand.hand_value()
if (first_value <= second_value):
return "WIN"
else:
return "LOSS"
def printing_hand(self):
print(self.cards)
return 0
if __name__ == '__main__':
print("The following two hands will be compared: ")
print("First hand: TC TH 5C 5H KH")
print("Second hand: 9C 9H 5C 5H AC")
print("The expected result is WIN (First hand wins over the second)")
result_test = PokerHand("TC TH 5C 5H KH").compare_with(PokerHand("9C 9H 5C 5H AC"))
print("The calculated result is: {}".format(result_test))
|
# Generated by Django 3.1.3 on 2021-01-16 17:48
import authentication.validators
from django.db import migrations, models
import django_countries.fields
class Migration(migrations.Migration):
dependencies = [
('authentication', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='user',
name='avatar',
field=models.ImageField(blank=True, upload_to='assets/avatars/'),
),
migrations.AlterField(
model_name='user',
name='country',
field=django_countries.fields.CountryField(blank=True, max_length=2),
),
migrations.AlterField(
model_name='user',
name='rating',
field=models.PositiveSmallIntegerField(default=0, validators=[authentication.validators.rating_validator], verbose_name='Rating'),
),
]
|
from hpc.autoscale.ccbindings.mock import MockClusterBinding
from hpc.autoscale.node.nodemanager import new_node_manager
def test_basic() -> None:
binding = MockClusterBinding()
binding.add_nodearray("hpc", {"ncpus": "node.vcpu_count"})
binding.add_bucket("hpc", "Standard_F4", max_count=100, available_count=100)
node_mgr = new_node_manager({"_mock_bindings": binding})
bucket = node_mgr.get_buckets()[0]
assert 100 == bucket.available_count
bucket.decrement(5)
assert 95 == bucket.available_count
bucket.rollback()
assert 100 == bucket.available_count
bucket.decrement(5)
assert 95 == bucket.available_count
bucket.commit()
assert 95 == bucket.available_count
bucket.decrement(5)
assert 90 == bucket.available_count
bucket.rollback()
assert 95 == bucket.available_count
|
"""Unit test package for geojson_fixer."""
|
from jivago.serialization.serialization_exception import SerializationException
class MissingKeyException(SerializationException):
pass
|
#!/usr/bin/python -tt
# -*- coding: utf-8 -*-
'''
Copyright 2014-2015 Teppo Perä
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
'''
from .singleton import Singleton
from .inspector import Inspector
from .factory import Factory
from .magic import type_safe, type_converted
from .utils import flatten, is_sysname, get_func_name
__all__ = ["Singleton", "Inspector", "Factory", "flatten", "type_safe",
"type_converted", "is_sysname", "errors", "get_func_name"]
|
from flask_jwt_extended import (create_access_token, create_refresh_token,
jwt_required, jwt_refresh_token_required, get_jwt_identity, get_raw_jwt)
from flask import Flask, Blueprint, jsonify, request, make_response, current_app
from disasterpets.Pets.models import Pets, PetsJoin
from disasterpets import bcrypt, db, jwt
from flask_restful import Resource
from disasterpets.Pets.schema import PetsSchema, BreedSchema, GenderSchema, PetStatusSchema, AnimalSchema, AlteredSchema
from disasterpets.Pets.models import Pets, PetsJoin, Breeds, Gender, AlteredStatus, PetStatus, Animals
from disasterpets.Pictures.models import PetImageJoin
from disasterpets.Pictures.schema import PetsImageJoinSchema
class PetMatchAPI(Resource):
def get(self):
searchingfor = request.get_json()
#pets_schema = PetsSchema(many=True)
imagejoin_schema = PetsImageJoinSchema(many = True)
breeds_schema = BreedSchema(many=True)
genders_schema = GenderSchema(many = True)
petstat_schema = PetStatusSchema(many =True)
animals_schema = AnimalSchema(many=True)
altered_schema = AlteredSchema(many=True)
try:
if searchingfor == None:
searchingfor = PetImageJoin.query.all()
jresults = imagejoin_schema.dump(searchingfor)
allbreeds = Breeds.query.all()
breedresult = breeds_schema.dump(allbreeds)
allgenders = Gender.query.all()
genderesults = genders_schema.dump(allgenders)
allpetstat = PetStatus.query.all()
statusresults = petstat_schema.dump(allpetstat)
allanimals = Animals.query.all()
animalresults = animals_schema.dump(allanimals)
altered = AlteredStatus.query.all()
alteredresults = altered_schema.dump(altered)
responseObject = {
'status' : 'success',
'message': 'successfully Pulled!',
'pets': jresults,
'breeds': breedresult,
'genders': genderesults,
'animal': animalresults,
'status': statusresults,
'altered': alteredresults
}
return make_response(jsonify(responseObject)), 201
except Exception as e:
print(e)
responseObject = {
'status' : 'failed',
'message': 'something went wrong try again'
}
return make_response(jsonify(responseObject)), 404
|
from random import randint
from time import sleep
def sorteia(lista):
print(f'Sorteando 5 valores da lista: ', end='')
for cont in range(0, 5):
num = randint(1, 10)
lista.append(num)
print(f'{num} ', end='', flush=True)
sleep(0.5)
print('PRONTO!')
def soma_par(lista):
soma = 0
for valor in lista:
if valor % 2 == 0:
soma += valor
print(f'Somando so valores pares de {lista}, temos {soma}')
numeros = list()
sorteia(numeros)
soma_par(numeros)
|
from .StoreStrategy import StoreStrategy
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2018-03-06 22:43
from __future__ import unicode_literals
from django.db import migrations
results = ['passed', 'failed', 'errored', 'skipped',
'aborted', 'not run', 'blocked']
def populate_result_types(apps, schema_editor):
Result = apps.get_model('network_ui_test', 'Result')
for result in results:
Result.objects.get_or_create(name=result)
class Migration(migrations.Migration):
dependencies = [
('network_ui_test', '0001_initial'),
]
operations = [
migrations.RunPython(
code=populate_result_types,
),
]
|
import argparse
import random
import numpy as np
import torch
def setup():
parser = argparse.ArgumentParser()
parser.add_argument('--config_path', type=str,
default="/app/config.yml")
parser.add_argument('--batch-size', type=int, default=64, metavar='N',
help='input batch size for training (default: 64)')
parser.add_argument('--lr', type=float, default=1.0, metavar='LR',
help='learning rate (default: 1.0)')
parser.add_argument('--gpu-num', type=int, default=0,
help='GPU number')
parser.add_argument('--ix-sched', type=int, default=0,
help='Index of first scheduler in experiment')
parser.add_argument('--schedulers', action='store_true', default=False,
help='Whether to loop over schedulers in experiment')
parser.add_argument('--start-with', type=str, default="MADGRAD",
help='First optimizer, all previous will be skipped')
args = parser.parse_args()
use_cuda = torch.cuda.is_available()
seed = 2020
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
np.random.seed(seed)
random.seed(seed)
torch.backends.cudnn.deterministic = True
args.device = torch.device(f"cuda:{args.gpu_num}" if use_cuda else "cpu")
return args
|
from Redy.Typing import *
from Redy.Magic.Classic import record
def format_ast(self: 'AST', i: int):
if isinstance(self, Named):
content = self.format(i)
elif isinstance(self, Nested):
content = self.format(i)
else:
content = (' ' * i) + str(self)
return content
class AST:
pass
class Nested(AST, List[AST]):
def format(self, i=0):
return '\n'.join(format_ast(each, i + 1) for each in self)
def __str__(self):
return self.format(0)
@record
class Named(AST):
name: str
content: AST
@property
def item(self):
return self.content
def format(self, i=0):
named_indent_num = i + len(self.name) + 1
indent = ' ' * i
content = format_ast(self.content, named_indent_num)
return f'{indent}{self.name}[\n{content}\n{indent}]'
def __str__(self):
return self.format(0)
|
from nuaal.connections.api.apic_em import ApicEmBase
from nuaal.utils import get_logger
class ApicEmPnpClient:
def __init__(self, apic=None, DEBUG=False):
"""
:param apic:
:param DEBUG:
"""
self.apic = apic
self.DEBUG = DEBUG
self.logger = get_logger(name="ApicEmPnpClient", DEBUG=self.DEBUG)
if not isinstance(self.apic, ApicEmBase):
self.logger.critical(msg="Given 'apic' is not an instance of 'ApicEmBase' class.")
def template_get(self, id=None, filename=None):
pass
|
"""Test the change password view using flask's test_client()."""
from flask import url_for, get_flashed_messages
from flask_login import current_user
def test_requires_login(client, auth):
"""Check the change password view requires login."""
with client:
response = client.get("/auth/change-password")
assert not current_user.is_authenticated
assert "302" in response.status
redirect = url_for('auth.login', _external=True)
redirect += "?next=%2Fauth%2Fchange-password"
assert redirect == response.location
def test_change_password(client, auth):
"""Check the change password route works."""
with client:
auth.register()
auth.login(follow_redirects=True)
assert current_user.is_authenticated
assert current_user.verify_password('cat')
response = client.post(
'/auth/change-password',
data={
'old_password': 'cat',
'password': 'dog',
'password2': 'dog',
},
)
assert current_user.is_authenticated
assert "302" in response.status
assert url_for('main.home', _external=True) == response.location
assert get_flashed_messages() == ['Your password has been updated.']
assert current_user.verify_password('dog')
def test_change_password_no_old_password(client, auth):
"""Check the change password route fails without old password."""
with client:
auth.register()
auth.login(follow_redirects=True)
response = client.post(
'/auth/change-password',
data={
'password': 'dog',
'password2': 'dog',
},
)
assert current_user.is_authenticated
assert "200" in response.status
assert get_flashed_messages() == []
assert b"This field is required." in response.data
assert current_user.verify_password('cat')
def test_change_password_wrong_old_password(client, auth):
"""Check the change password route fails with wrong old password."""
with client:
auth.register()
auth.login(follow_redirects=True)
response = client.post(
'/auth/change-password',
data={
'old_password': 'rabbit',
'password': 'dog',
'password2': 'dog',
},
)
assert current_user.is_authenticated
assert "200" in response.status
assert get_flashed_messages() == ['Invalid password.']
assert current_user.verify_password('cat')
|
# encoding=utf-8
import bisect
x = list(range(10**6))
# i = x.index(991234)
i = bisect.bisect_left(x,991234)
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2014 The Plaso Project Authors.
# Please see the AUTHORS file for details on individual authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This file contains the Task Scheduler Registry keys plugins."""
import logging
import construct
from plaso.events import windows_events
from plaso.events import time_events
from plaso.parsers import winreg
from plaso.parsers.winreg_plugins import interface
class TaskCacheEvent(time_events.FiletimeEvent):
"""Convenience class for a Task Cache event."""
DATA_TYPE = 'task_scheduler:task_cache:entry'
def __init__(
self, timestamp, timestamp_description, task_name, task_identifier):
"""Initializes the event.
Args:
timestamp: The FILETIME value for the timestamp.
timestamp_description: The usage string for the timestamp value.
task_name: String containing the name of the task.
task_identifier: String containing the identifier of the task.
"""
super(TaskCacheEvent, self).__init__(timestamp, timestamp_description)
self.offset = 0
self.task_name = task_name
self.task_identifier = task_identifier
class TaskCachePlugin(interface.KeyPlugin):
"""Plugin that parses a Task Cache key."""
NAME = 'winreg_task_cache'
DESCRIPTION = u'Parser for Task Scheduler cache Registry data.'
REG_TYPE = 'SOFTWARE'
REG_KEYS = [
u'\\Microsoft\\Windows NT\\CurrentVersion\\Schedule\\TaskCache']
URL = [
u'https://code.google.com/p/winreg-kb/wiki/TaskSchedulerKeys']
_DYNAMIC_INFO_STRUCT = construct.Struct(
'dynamic_info_record',
construct.ULInt32('version'),
construct.ULInt64('last_registered_time'),
construct.ULInt64('launch_time'),
construct.Padding(8))
_DYNAMIC_INFO_STRUCT_SIZE = _DYNAMIC_INFO_STRUCT.sizeof()
def _GetIdValue(self, key):
"""Retrieves the Id value from Task Cache Tree key.
Args:
key: A Windows Registry key (instance of WinRegKey).
Yields:
A tuple containing a Windows Registry Key (instance of WinRegKey) and
a Windows Registry value (instance of WinRegValue).
"""
id_value = key.GetValue(u'Id')
if id_value:
yield key, id_value
for sub_key in key.GetSubkeys():
for value_key, id_value in self._GetIdValue(sub_key):
yield value_key, id_value
def GetEntries(
self, parser_context, key=None, registry_type=None, **unused_kwargs):
"""Parses a Task Cache Registry key.
Args:
parser_context: A parser context object (instance of ParserContext).
key: Optional Registry key (instance of winreg.WinRegKey).
The default is None.
registry_type: Optional Registry type string. The default is None.
"""
tasks_key = key.GetSubkey(u'Tasks')
tree_key = key.GetSubkey(u'Tree')
if not tasks_key or not tree_key:
logging.warning(u'Task Cache is missing a Tasks or Tree sub key.')
return
task_guids = {}
for sub_key in tree_key.GetSubkeys():
for value_key, id_value in self._GetIdValue(sub_key):
# The GUID is in the form {%GUID%} and stored an UTF-16 little-endian
# string and should be 78 bytes in size.
if len(id_value.raw_data) != 78:
logging.warning(
u'[{0:s}] unsupported Id value data size.'.format(self.NAME))
continue
task_guids[id_value.data] = value_key.name
for sub_key in tasks_key.GetSubkeys():
dynamic_info_value = sub_key.GetValue(u'DynamicInfo')
if not dynamic_info_value:
continue
if len(dynamic_info_value.raw_data) != self._DYNAMIC_INFO_STRUCT_SIZE:
logging.warning(
u'[{0:s}] unsupported DynamicInfo value data size.'.format(
self.NAME))
continue
dynamic_info = self._DYNAMIC_INFO_STRUCT.parse(
dynamic_info_value.raw_data)
name = task_guids.get(sub_key.name, sub_key.name)
text_dict = {}
text_dict[u'Task: {0:s}'.format(name)] = u'[ID: {0:s}]'.format(
sub_key.name)
event_object = windows_events.WindowsRegistryEvent(
key.last_written_timestamp, key.path, text_dict, offset=key.offset,
registry_type=registry_type)
parser_context.ProduceEvent(event_object, plugin_name=self.NAME)
if dynamic_info.last_registered_time:
# Note this is likely either the last registered time or
# the update time.
event_object = TaskCacheEvent(
dynamic_info.last_registered_time, u'Last registered time', name,
sub_key.name)
parser_context.ProduceEvent(event_object, plugin_name=self.NAME)
if dynamic_info.launch_time:
# Note this is likely the launch time.
event_object = TaskCacheEvent(
dynamic_info.launch_time, u'Launch time', name, sub_key.name)
parser_context.ProduceEvent(event_object, plugin_name=self.NAME)
# TODO: Add support for the Triggers value.
winreg.WinRegistryParser.RegisterPlugin(TaskCachePlugin)
|
"""Tests for parser components"""
__docformat__ = 'restructuredtext'
from io import StringIO
from unittest.mock import patch
from datalad.tests.utils_pytest import (
assert_equal,
assert_in,
assert_raises,
)
from ..parser import (
fail_with_short_help,
setup_parser,
)
def test_fail_with_short_help():
out = StringIO()
with assert_raises(SystemExit) as cme:
fail_with_short_help(exit_code=3, out=out)
assert_equal(cme.value.code, 3)
assert_equal(out.getvalue(), "")
out = StringIO()
with assert_raises(SystemExit) as cme:
fail_with_short_help(msg="Failed badly", out=out)
assert_equal(cme.value.code, 1)
assert_equal(out.getvalue(), "error: Failed badly\n")
# Suggestions, hint, etc
out = StringIO()
with assert_raises(SystemExit) as cme:
fail_with_short_help(
msg="Failed badly",
known=["mother", "mutter", "father", "son"],
provided="muther",
hint="You can become one",
exit_code=0, # no one forbids
what="parent",
out=out)
assert_equal(cme.value.code, 0)
assert_equal(out.getvalue(),
"error: Failed badly\n"
"datalad: Unknown parent 'muther'. See 'datalad --help'.\n\n"
"Did you mean any of these?\n"
" mutter\n"
" mother\n"
" father\n"
"Hint: You can become one\n")
def check_setup_parser(args, exit_code=None):
parser = None
with patch('sys.stderr', new_callable=StringIO) as cmerr:
with patch('sys.stdout', new_callable=StringIO) as cmout:
if exit_code is not None:
with assert_raises(SystemExit) as cm:
setup_parser(args)
else:
parser = setup_parser(args)
if exit_code is not None:
assert_equal(cm.value.code, exit_code)
stdout = cmout.getvalue()
stderr = cmerr.getvalue()
return {'parser': parser, 'out': stdout, 'err': stderr}
def test_setup():
# insufficient arguments
check_setup_parser([], 2)
assert_in('too few arguments', check_setup_parser(['datalad'], 2)['err'])
assert_in('.', check_setup_parser(['datalad', '--version'], 0)['out'])
parser = check_setup_parser(['datalad', 'wtf'])['parser']
# check into the guts of argparse to check that really only a single
# subparser was constructed
assert_equal(
list(parser._positionals._group_actions[0].choices.keys()),
['wtf']
)
|
"""p2 ui General View tests"""
from django.contrib.auth.models import User
from django.shortcuts import reverse
from django.test import TestCase
class GeneralViewTests(TestCase):
"""Test general views"""
def setUp(self):
self.user, _ = User.objects.get_or_create(
username='p2-unittest')
self.client.force_login(self.user)
def test_general_index_view(self):
"""Test index view (authenticated)"""
response = self.client.get(reverse('p2_ui:index'))
self.assertEqual(response.status_code, 200)
|
import argparse
from yolo import YOLO
from PIL import Image
parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)
test_file = '../../DataSets/labels/HeadsTesting_modif.csv'
predictions_file = '../../DataSets/detections/heads_labels_predicted_tinyYolo_adaptedAnchors.csv'
def center(box):
print(box)
x_cent = round((box[2]-box[0])/2)
y_cent = round((box[3]-box[1])/2)
return (x_cent, y_cent)
def detect_img(yolo,img_path):
try:
image = Image.open(img_path)
except:
print('Open Error! Try again!')
else:
response = yolo.detect_image(image)
print(response)
r_image = response[0]
out_boxes = response[1]
out_scores = response[2]
out_classes = response[3]
elapsed = response[4]
#r_image.show()
print('boxes: {} | scores:{} | classes:{}'.format(str(out_boxes), str(out_scores), str(out_classes)))
return out_boxes, out_scores, out_classes, elapsed
if __name__ == '__main__':
# class YOLO defines the default value, so suppress any default here
parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)
'''
Command line options
'''
parser.add_argument(
'--model', type=str,
help='path to model weight file, default ' + YOLO.get_defaults("model_path")
)
parser.add_argument(
'--anchors', type=str,
help='path to anchor definitions, default ' + YOLO.get_defaults("anchors_path")
)
parser.add_argument(
'--classes', type=str,
help='path to class definitions, default ' + YOLO.get_defaults("classes_path")
)
parser.add_argument(
'--gpu_num', type=int,
help='Number of GPU to use, default ' + str(YOLO.get_defaults("gpu_num"))
)
parser.add_argument(
'--image', default=False, action="store_true",
help='Image detection mode, will ignore all positional arguments'
)
'''
Command line positional arguments -- for video detection mode
'''
parser.add_argument(
"--input", nargs='?', type=str,required=False,default='./path2your_video',
help = "Video input path"
)
parser.add_argument(
"--output", nargs='?', type=str, default="",
help = "[Optional] Video output path"
)
FLAGS = parser.parse_args()
yolov3 = YOLO(**vars(FLAGS))
with open(test_file) as fp:
with open(predictions_file, 'w') as fp_pred:
line = fp.readline()
cnt = 1
while line:
#print("Line {}: {}".format(cnt, line.strip()))
elements = line.strip().split(' ')
print("File path: {}".format(elements[0]))
response = detect_img(yolov3,elements[0])
print(response)
if len(response[1]) == 0: # if it doesn't recognize any head
result = '{}\n'.format(elements[0])
fp_pred.write(result)
else: # if it does recognize one or more heads
out_boxes = response[0]
out_scores = response[1]
out_classes = response[2]
elapsed = response[3]
for b, s, c in zip(out_boxes, out_scores, out_classes):
result = '{};{};{};{};{};{}\n'.format(elements[0], b, s, c, center(b), elapsed)
print(result)
fp_pred.write(result)
line = fp.readline()
cnt += 1
yolov3.close_session()
print('Test finished correctly') |
"""
@file
@brief Modified converter from
`XGBoost.py <https://github.com/onnx/onnxmltools/blob/master/onnxmltools/convert/
xgboost/operator_converters/XGBoost.py>`_.
"""
import json
import numpy
from xgboost import XGBClassifier
class XGBConverter:
"common methods for converters"
@staticmethod
def get_xgb_params(xgb_node):
"""
Retrieves parameters of a model.
"""
return xgb_node.get_xgb_params()
@staticmethod
def validate(xgb_node):
"validates the model"
params = XGBConverter.get_xgb_params(xgb_node)
try:
if "objective" not in params:
raise AttributeError('ojective')
except AttributeError as e:
raise RuntimeError('Missing attribute in XGBoost model ' + str(e))
@staticmethod
def common_members(xgb_node, inputs):
"common to regresssor and classifier"
params = XGBConverter.get_xgb_params(xgb_node)
objective = params["objective"]
base_score = params["base_score"]
booster = xgb_node.get_booster()
# The json format was available in October 2017.
# XGBoost 0.7 was the first version released with it.
js_tree_list = booster.get_dump(with_stats=True, dump_format='json')
js_trees = [json.loads(s) for s in js_tree_list]
return objective, base_score, js_trees
@staticmethod
def _get_default_tree_attribute_pairs(is_classifier):
attrs = {}
for k in {'nodes_treeids', 'nodes_nodeids',
'nodes_featureids', 'nodes_modes', 'nodes_values',
'nodes_truenodeids', 'nodes_falsenodeids', 'nodes_missing_value_tracks_true'}:
attrs[k] = []
if is_classifier:
for k in {'class_treeids', 'class_nodeids', 'class_ids', 'class_weights'}:
attrs[k] = []
else:
for k in {'target_treeids', 'target_nodeids', 'target_ids', 'target_weights'}:
attrs[k] = []
return attrs
@staticmethod
def _add_node(attr_pairs, is_classifier, tree_id, tree_weight, node_id,
feature_id, mode, value, true_child_id, false_child_id, weights, weight_id_bias,
missing, hitrate):
if isinstance(feature_id, str):
# Something like f0, f1...
if feature_id[0] == "f":
try:
feature_id = int(feature_id[1:])
except ValueError:
raise RuntimeError(
"Unable to interpret '{0}'".format(feature_id))
else:
try:
feature_id = int(feature_id)
except ValueError:
raise RuntimeError(
"Unable to interpret '{0}'".format(feature_id))
# Split condition for sklearn
# * if X_ptr[X_sample_stride * i + X_fx_stride * node.feature] <= node.threshold:
# * https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tree/_tree.pyx#L946
# Split condition for xgboost
# * if (fvalue < split_value)
# * https://github.com/dmlc/xgboost/blob/master/include/xgboost/tree_model.h#L804
attr_pairs['nodes_treeids'].append(tree_id)
attr_pairs['nodes_nodeids'].append(node_id)
attr_pairs['nodes_featureids'].append(feature_id)
attr_pairs['nodes_modes'].append(mode)
attr_pairs['nodes_values'].append(float(value))
attr_pairs['nodes_truenodeids'].append(true_child_id)
attr_pairs['nodes_falsenodeids'].append(false_child_id)
attr_pairs['nodes_missing_value_tracks_true'].append(missing)
if 'nodes_hitrates' in attr_pairs:
attr_pairs['nodes_hitrates'].append(hitrate)
if mode == 'LEAF':
if is_classifier:
for i, w in enumerate(weights):
attr_pairs['class_treeids'].append(tree_id)
attr_pairs['class_nodeids'].append(node_id)
attr_pairs['class_ids'].append(i + weight_id_bias)
attr_pairs['class_weights'].append(float(tree_weight * w))
else:
for i, w in enumerate(weights):
attr_pairs['target_treeids'].append(tree_id)
attr_pairs['target_nodeids'].append(node_id)
attr_pairs['target_ids'].append(i + weight_id_bias)
attr_pairs['target_weights'].append(float(tree_weight * w))
@staticmethod
def _fill_node_attributes(treeid, tree_weight, jsnode, attr_pairs, is_classifier, remap):
if 'children' in jsnode:
XGBConverter._add_node(attr_pairs=attr_pairs, is_classifier=is_classifier,
tree_id=treeid, tree_weight=tree_weight,
value=jsnode['split_condition'], node_id=remap[jsnode['nodeid']],
feature_id=jsnode['split'],
mode='BRANCH_LT', # 'BRANCH_LEQ' --> is for sklearn
# ['children'][0]['nodeid'],
true_child_id=remap[jsnode['yes']],
# ['children'][1]['nodeid'],
false_child_id=remap[jsnode['no']],
weights=None, weight_id_bias=None,
# ['children'][0]['nodeid'],
missing=jsnode.get(
'missing', -1) == jsnode['yes'],
hitrate=jsnode.get('cover', 0))
for ch in jsnode['children']:
if 'children' in ch or 'leaf' in ch:
XGBConverter._fill_node_attributes(
treeid, tree_weight, ch, attr_pairs, is_classifier, remap)
else:
raise RuntimeError(
"Unable to convert this node {0}".format(ch))
else:
weights = [jsnode['leaf']]
weights_id_bias = 0
XGBConverter._add_node(attr_pairs=attr_pairs, is_classifier=is_classifier,
tree_id=treeid, tree_weight=tree_weight,
value=0., node_id=remap[jsnode['nodeid']],
feature_id=0, mode='LEAF',
true_child_id=0, false_child_id=0,
weights=weights, weight_id_bias=weights_id_bias,
missing=False, hitrate=jsnode.get('cover', 0))
@staticmethod
def _remap_nodeid(jsnode, remap=None):
if remap is None:
remap = {}
nid = jsnode['nodeid']
remap[nid] = len(remap)
if 'children' in jsnode:
for ch in jsnode['children']:
XGBConverter._remap_nodeid(ch, remap)
return remap
@staticmethod
def fill_tree_attributes(js_xgb_node, attr_pairs, tree_weights, is_classifier):
"fills tree attributes"
if not isinstance(js_xgb_node, list):
raise TypeError("js_xgb_node must be a list")
for treeid, (jstree, w) in enumerate(zip(js_xgb_node, tree_weights)):
remap = XGBConverter._remap_nodeid(jstree)
XGBConverter._fill_node_attributes(
treeid, w, jstree, attr_pairs, is_classifier, remap)
class XGBRegressorConverter(XGBConverter):
"converter class"
@staticmethod
def validate(xgb_node):
return XGBConverter.validate(xgb_node)
@staticmethod
def _get_default_tree_attribute_pairs(): # pylint: disable=W0221
attrs = XGBConverter._get_default_tree_attribute_pairs(False)
attrs['post_transform'] = 'NONE'
attrs['n_targets'] = 1
return attrs
@staticmethod
def convert(scope, operator, container):
"converter method"
xgb_node = operator.raw_operator
inputs = operator.inputs
objective, base_score, js_trees = XGBConverter.common_members(
xgb_node, inputs)
if objective in ["reg:gamma", "reg:tweedie"]:
raise RuntimeError(
"Objective '{}' not supported.".format(objective))
booster = xgb_node.get_booster()
if booster is None:
raise RuntimeError("The model was probably not trained.")
attr_pairs = XGBRegressorConverter._get_default_tree_attribute_pairs()
attr_pairs['base_values'] = [base_score]
XGBConverter.fill_tree_attributes(
js_trees, attr_pairs, [1 for _ in js_trees], False)
# add nodes
if container.dtype == numpy.float64:
container.add_node('TreeEnsembleRegressorDouble', operator.input_full_names,
operator.output_full_names,
name=scope.get_unique_operator_name(
'TreeEnsembleRegressorDouble'),
op_domain='mlprodict', **attr_pairs)
else:
container.add_node('TreeEnsembleRegressor', operator.input_full_names,
operator.output_full_names,
name=scope.get_unique_operator_name(
'TreeEnsembleRegressor'),
op_domain='ai.onnx.ml', **attr_pairs)
class XGBClassifierConverter(XGBConverter):
"converter for XGBClassifier"
@staticmethod
def validate(xgb_node):
return XGBConverter.validate(xgb_node)
@staticmethod
def _get_default_tree_attribute_pairs(): # pylint: disable=W0221
attrs = XGBConverter._get_default_tree_attribute_pairs(True)
# attrs['nodes_hitrates'] = []
return attrs
@staticmethod
def convert(scope, operator, container):
"convert method"
xgb_node = operator.raw_operator
inputs = operator.inputs
objective, base_score, js_trees = XGBConverter.common_members(
xgb_node, inputs)
if base_score is None:
raise RuntimeError("base_score cannot be None")
params = XGBConverter.get_xgb_params(xgb_node)
attr_pairs = XGBClassifierConverter._get_default_tree_attribute_pairs()
XGBConverter.fill_tree_attributes(
js_trees, attr_pairs, [1 for _ in js_trees], True)
if len(attr_pairs['class_treeids']) == 0:
raise RuntimeError("XGBoost model is empty.")
ncl = (max(attr_pairs['class_treeids']) + 1) // params['n_estimators']
if ncl <= 1:
ncl = 2
# See https://github.com/dmlc/xgboost/blob/master/src/common/math.h#L23.
attr_pairs['post_transform'] = "LOGISTIC"
attr_pairs['class_ids'] = [0 for v in attr_pairs['class_treeids']]
else:
# See https://github.com/dmlc/xgboost/blob/master/src/common/math.h#L35.
attr_pairs['post_transform'] = "SOFTMAX"
# attr_pairs['base_values'] = [base_score for n in range(ncl)]
attr_pairs['class_ids'] = [v %
ncl for v in attr_pairs['class_treeids']]
class_labels = list(range(ncl))
attr_pairs['classlabels_int64s'] = class_labels
# add nodes
if objective == "binary:logistic":
ncl = 2
container.add_node('TreeEnsembleClassifier', operator.input_full_names,
operator.output_full_names,
name=scope.get_unique_operator_name(
'TreeEnsembleClassifier'),
op_domain='ai.onnx.ml', **attr_pairs)
elif objective == "multi:softprob":
ncl = len(js_trees) // params['n_estimators']
container.add_node('TreeEnsembleClassifier', operator.input_full_names,
operator.output_full_names,
name=scope.get_unique_operator_name(
'TreeEnsembleClassifier'),
op_domain='ai.onnx.ml', **attr_pairs)
elif objective == "reg:logistic":
ncl = len(js_trees) // params['n_estimators']
if ncl == 1:
ncl = 2
container.add_node('TreeEnsembleClassifier', operator.input_full_names,
operator.output_full_names,
name=scope.get_unique_operator_name(
'TreeEnsembleClassifier'),
op_domain='ai.onnx.ml', **attr_pairs)
else:
raise RuntimeError("Unexpected objective: {0}".format(objective))
def convert_xgboost(scope, operator, container):
"""
This converters reuses the code from
`XGBoost.py <https://github.com/onnx/onnxmltools/blob/master/onnxmltools/convert/
xgboost/operator_converters/XGBoost.py>`_ and makes
some modifications. It implements converters
for models in :epkg:`xgboost`.
"""
xgb_node = operator.raw_operator
if isinstance(xgb_node, XGBClassifier):
cls = XGBClassifierConverter
else:
cls = XGBRegressorConverter
cls.convert(scope, operator, container)
|
#!/usr/bin/env python3
from __future__ import unicode_literals, print_function
import codecs
import os
import re
import sys
def generate_and_write_bindings(source_dir, output_dir):
binding_params = [
("writer", { 'ignore': ['new', 'ref', 'unref', 'init', 'clear', 'reset',
'set_target_cpu', 'set_target_abi', 'set_target_os',
'cur', 'offset', 'flush', 'get_cpu_register_for_nth_argument'] }),
("relocator", { 'ignore': ['new', 'ref', 'unref', 'init', 'clear', 'reset',
'read_one', 'is_eob_instruction', 'eob', 'eoi', 'can_relocate'] }),
]
flavor_combos = [
("x86", "x86"),
("arm", "arm"),
("arm", "thumb"),
("arm64", "arm64"),
("mips", "mips"),
]
tsds = {}
docs = {}
for name, options in binding_params:
for filename, code in generate_umbrellas(name, flavor_combos).items():
with codecs.open(os.path.join(output_dir, filename), "w", 'utf-8') as f:
f.write(code)
for arch, flavor in flavor_combos:
api_header_path = os.path.join(source_dir, "arch-" + arch, "gum{0}{1}.h".format(flavor, name))
with codecs.open(api_header_path, "r", 'utf-8') as f:
api_header = f.read().replace("\r", "")
bindings = generate_bindings(name, arch, flavor, api_header, options)
for filename, code in bindings.code.items():
with codecs.open(os.path.join(output_dir, filename), "w", 'utf-8') as f:
f.write(code)
tsds.update(bindings.tsds)
docs.update(bindings.docs)
tsd_sections = []
doc_sections = []
for arch, flavor in flavor_combos:
for name, options in binding_params:
tsd_sections.append(tsds["{0}-{1}.d.ts".format(flavor, name)])
doc_sections.append(docs["{0}-{1}.md".format(flavor, name)])
if flavor != "arm":
tsd_sections.append(tsds["{0}-enums.d.ts".format(arch)])
doc_sections.append(docs["{0}-enums.md".format(arch)])
tsd_source = "\n\n".join(tsd_sections)
with codecs.open(os.path.join(output_dir, "api-types.d.ts"), "w", 'utf-8') as f:
f.write(tsd_source)
api_reference = "\n\n".join(doc_sections)
with codecs.open(os.path.join(output_dir, "api-reference.md"), "w", 'utf-8') as f:
f.write(api_reference)
def generate_umbrellas(name, flavor_combos):
umbrellas = {}
for runtime in ["quick", "v8"]:
for section in ["", "-fields", "-methods", "-init", "-dispose"]:
filename, code = generate_umbrella(runtime, name, section, flavor_combos)
umbrellas[filename] = code
return umbrellas
def generate_umbrella(runtime, name, section, flavor_combos):
lines = []
arch_defines = {
"x86": "HAVE_I386",
"arm": "HAVE_ARM",
"arm64": "HAVE_ARM64",
"mips": "HAVE_MIPS",
}
current_arch = None
for arch, flavor in flavor_combos:
if arch != current_arch:
if current_arch is not None:
lines.extend([
"#endif",
"",
])
lines.extend([
"#ifdef " + arch_defines[arch],
"",
])
current_arch = arch
lines.append("# include \"gum{0}code{1}{2}-{3}.inc\"".format(runtime, name, section, flavor))
if section == "-methods":
if flavor == "thumb":
lines.extend(generate_alias_definitions("special", runtime, name, flavor))
else:
lines.extend(generate_alias_definitions("default", runtime, name, flavor))
if flavor != "arm":
lines.extend(generate_alias_definitions("special", runtime, name, flavor))
lines.append("#endif")
filename = "gum{0}code{1}{2}.inc".format(runtime, name, section)
code = "\n".join(lines)
return (filename, code)
def generate_alias_definitions(alias, runtime, name, flavor):
alias_function_prefix = "gum_{0}_{1}_{2}".format(runtime, alias, name)
wrapper_function_prefix = "gum_{0}_{1}_{2}".format(runtime, flavor, name)
impl_function_prefix = "gum_{0}_{1}".format(flavor, name)
params = {
"name_uppercase": name.upper(),
"alias_class_name": to_camel_case("{0}_{1}".format(flavor, name), start_high=True),
"alias_field_prefix": "{0}_{1}".format(flavor, name),
"alias_struct_name": to_camel_case(alias_function_prefix, start_high=True),
"alias_function_prefix": alias_function_prefix,
"wrapper_macro_prefix": "GUM_{0}_{1}_{2}".format(runtime.upper(), alias.upper(), name.upper()),
"wrapper_struct_name": to_camel_case(wrapper_function_prefix, start_high=True),
"wrapper_function_prefix": wrapper_function_prefix,
"impl_struct_name": to_camel_case(impl_function_prefix, start_high=True),
"persistent_suffix": "_persistent" if runtime == "v8" else ""
}
return """
#define {wrapper_macro_prefix}_CLASS_NAME "{alias_class_name}"
#define {wrapper_macro_prefix}_FIELD {alias_field_prefix}
typedef {wrapper_struct_name} {alias_struct_name};
typedef {impl_struct_name} {alias_struct_name}Impl;
#define _{alias_function_prefix}_new{persistent_suffix} _{wrapper_function_prefix}_new{persistent_suffix}
#define _{alias_function_prefix}_release{persistent_suffix} _{wrapper_function_prefix}_release{persistent_suffix}
#define _{alias_function_prefix}_init _{wrapper_function_prefix}_init
#define _{alias_function_prefix}_finalize _{wrapper_function_prefix}_finalize
#define _{alias_function_prefix}_reset _{wrapper_function_prefix}_reset
""".format(**params).split("\n")
class Bindings(object):
def __init__(self, code, tsds, docs):
self.code = code
self.tsds = tsds
self.docs = docs
def generate_bindings(name, arch, flavor, api_header, options):
api = parse_api(name, arch, flavor, api_header, options)
code = {}
code.update(generate_quick_bindings(name, arch, flavor, api))
code.update(generate_v8_bindings(name, arch, flavor, api))
tsds = generate_tsds(name, arch, flavor, api)
docs = generate_docs(name, arch, flavor, api)
return Bindings(code, tsds, docs)
def generate_quick_bindings(name, arch, flavor, api):
component = Component(name, arch, flavor, "quick")
return {
"gumquickcode{0}-{1}.inc".format(name, flavor): generate_quick_wrapper_code(component, api),
"gumquickcode{0}-fields-{1}.inc".format(name, flavor): generate_quick_fields(component),
"gumquickcode{0}-methods-{1}.inc".format(name, flavor): generate_quick_methods(component),
"gumquickcode{0}-init-{1}.inc".format(name, flavor): generate_quick_init_code(component),
"gumquickcode{0}-dispose-{1}.inc".format(name, flavor): generate_quick_dispose_code(component),
}
def generate_quick_wrapper_code(component, api):
lines = [
"/* Auto-generated, do not edit. */",
"",
"#include <string.h>",
]
conversion_decls, conversion_code = generate_conversion_methods(component, generate_quick_enum_parser)
if len(conversion_decls) > 0:
lines.append("")
lines.extend(conversion_decls)
lines.append("")
lines.extend(generate_quick_base_methods(component))
for method in api.instance_methods:
args = method.args
is_put_array = method.is_put_array
if method.is_put_call:
array_item_type = "GumArgument"
array_item_parse_logic = generate_quick_parse_call_arg_array_element(component)
elif method.is_put_regs:
array_item_type = api.native_register_type
array_item_parse_logic = generate_quick_parse_register_array_element(component)
lines.extend([
"GUMJS_DEFINE_FUNCTION ({0}_{1})".format(component.gumjs_function_prefix, method.name),
"{",
" {0} * parent;".format(component.module_struct_name),
" {0} * self;".format(component.wrapper_struct_name),
])
for arg in args:
type_raw = arg.type_raw
if type_raw == "$array":
type_raw = "JSValue"
lines.append(" {0} {1};".format(type_raw, arg.name_raw))
converter = arg.type_converter
if converter is not None:
if converter == "bytes":
lines.extend([
" const guint8 * {0};".format(arg.name),
" gsize {0}_size;".format(arg.name)
])
elif converter == "label":
lines.append(" gconstpointer {0};".format(arg.name))
else:
lines.append(" {0} {1};".format(arg.type, arg.name))
if is_put_array:
lines.extend([
" guint items_length, items_index;",
" {0} * items;".format(array_item_type),
" JSValue element_val = JS_NULL;",
" const char * element_str = NULL;",
])
if method.return_type == "void":
return_capture = ""
else:
lines.append(" {0} result;".format(method.return_type))
return_capture = "result = "
lines.extend([
"",
" parent = gumjs_get_parent_module (core);",
"",
" if (!_{0}_get (ctx, this_val, parent, &self))".format(component.wrapper_function_prefix),
" goto propagate_exception;",
])
if len(args) > 0:
arglist_signature = "".join([arg.type_format for arg in args])
arglist_pointers = ", ".join(["&" + arg.name_raw for arg in args])
lines.extend([
"",
" if (!_gum_quick_args_parse (args, \"{0}\", {1}))".format(arglist_signature, arglist_pointers),
" goto propagate_exception;",
])
args_needing_conversion = [arg for arg in args if arg.type_converter is not None]
if len(args_needing_conversion) > 0:
lines.append("")
for arg in args_needing_conversion:
converter = arg.type_converter
if converter == "label":
lines.append(" {value} = {wrapper_function_prefix}_resolve_label (self, {value_raw});".format(
value=arg.name,
value_raw=arg.name_raw,
wrapper_function_prefix=component.wrapper_function_prefix))
elif converter == "address":
lines.append(" {value} = GUM_ADDRESS ({value_raw});".format(
value=arg.name,
value_raw=arg.name_raw))
elif converter == "bytes":
lines.append(" {value} = g_bytes_get_data ({value_raw}, &{value}_size);".format(
value=arg.name,
value_raw=arg.name_raw))
else:
lines.append(" if (!gum_parse_{arch}_{type} (ctx, {value_raw}, &{value}))\n goto propagate_exception;".format(
value=arg.name,
value_raw=arg.name_raw,
arch=component.arch,
type=arg.type_converter))
if is_put_array:
lines.extend(generate_quick_parse_array_elements(array_item_type, array_item_parse_logic).split("\n"))
impl_function_name = "{0}_{1}".format(component.impl_function_prefix, method.name)
arglist = ["self->impl"]
if method.needs_calling_convention_arg:
arglist.append("GUM_CALL_CAPI")
for arg in args:
if arg.type_converter == "bytes":
arglist.extend([arg.name, arg.name + "_size"])
else:
arglist.append(arg.name)
if is_put_array:
impl_function_name += "_array"
arglist.insert(len(arglist) - 1, "items_length")
lines.extend([
"",
" {0}{1} ({2});".format(return_capture, impl_function_name, ", ".join(arglist))
])
error_targets = []
if method.return_type == "gboolean" and method.name.startswith("put_"):
lines.extend([
"",
" if (!result)",
" goto invalid_argument;",
"",
" return JS_UNDEFINED;",
])
error_targets.extend([
"invalid_argument:",
" {",
" _gum_quick_throw_literal (ctx, \"invalid argument\");",
" goto propagate_exception;",
" }",
])
elif method.return_type == "void":
lines.append("")
lines.append(" return JS_UNDEFINED;")
else:
lines.append("")
if method.return_type == "gboolean":
lines.append(" return JS_NewBool (ctx, result);")
elif method.return_type == "guint":
lines.append(" return JS_NewInt64 (ctx, result);")
elif method.return_type == "gpointer":
lines.append(" return _gum_quick_native_pointer_new (ctx, result, core);")
elif method.return_type == "GumAddress":
lines.append(" return _gum_quick_native_pointer_new (ctx, GSIZE_TO_POINTER (result), core);")
elif method.return_type == "cs_insn *":
if component.flavor == "x86":
target = "GSIZE_TO_POINTER (result->address)"
else:
target = "self->impl->input_start + (result->address -\n (self->impl->input_pc - self->impl->inpos))"
if component.flavor == "thumb":
target = "GSIZE_TO_POINTER (GPOINTER_TO_SIZE ({0}) | 1)".format(target)
lines.extend([
" if (result != NULL)",
" {",
" return _gum_quick_instruction_new (ctx, result, FALSE,",
" {0},".format(target),
" self->impl->capstone, parent->instruction, NULL);",
" }",
" else",
" {",
" return JS_NULL;",
" }",
])
else:
raise ValueError("Unsupported return type: {0}".format(method.return_type))
lines.append("")
lines.extend(error_targets)
lines.extend([
"propagate_exception:",
" {",
])
if is_put_array:
lines.extend([
" JS_FreeCString (ctx, element_str);",
" JS_FreeValue (ctx, element_val);",
"",
])
lines.extend([
" return JS_EXCEPTION;",
" }",
"}",
""
])
prefix = component.gumjs_function_prefix
lines.extend([
"static const JSClassDef {0}_def =".format(prefix),
"{",
" .class_name = \"{0}\",".format(component.gumjs_class_name),
" .finalizer = {0}_finalize,".format(prefix),
"};",
"",
"static const JSCFunctionListEntry {0}_entries[] =".format(prefix),
"{",
])
if component.name == "writer":
lines.extend([
" JS_CGETSET_DEF (\"base\", {0}_get_base, NULL),".format(prefix),
" JS_CGETSET_DEF (\"code\", {0}_get_code, NULL),".format(prefix),
" JS_CGETSET_DEF (\"pc\", {0}_get_pc, NULL),".format(prefix),
" JS_CGETSET_DEF (\"offset\", {0}_get_offset, NULL),".format(prefix),
" JS_CFUNC_DEF (\"reset\", 0, {0}_reset),".format(prefix),
" JS_CFUNC_DEF (\"dispose\", 0, {0}_dispose),".format(prefix),
" JS_CFUNC_DEF (\"flush\", 0, {0}_flush),".format(prefix),
])
elif component.name == "relocator":
lines.extend([
" JS_CGETSET_DEF (\"input\", {0}_get_input, NULL),".format(prefix),
" JS_CGETSET_DEF (\"eob\", {0}_get_eob, NULL),".format(prefix),
" JS_CGETSET_DEF (\"eoi\", {0}_get_eoi, NULL),".format(prefix),
" JS_CFUNC_DEF (\"reset\", 0, {0}_reset),".format(prefix),
" JS_CFUNC_DEF (\"dispose\", 0, {0}_dispose),".format(prefix),
" JS_CFUNC_DEF (\"readOne\", 0, {0}_read_one),".format(prefix),
])
for method in api.instance_methods:
lines.append(" JS_CFUNC_DEF (\"{0}\", 0, {1}_{2}),".format(
method.name_js,
component.gumjs_function_prefix,
method.name
))
lines.extend([
"};",
""
])
lines.extend(conversion_code)
return "\n".join(lines)
def generate_quick_parse_array_elements(item_type, parse_item):
return """
if (!_gum_quick_array_get_length (ctx, items_value, core, &items_length))
goto propagate_exception;
items = g_newa ({item_type}, items_length);
for (items_index = 0; items_index != items_length; items_index++)
{{
{item_type} * item = &items[items_index];
element_val = JS_GetPropertyUint32 (ctx, items_value, items_index);
if (JS_IsException (element_val))
goto propagate_exception;
{parse_item}
JS_FreeValue (ctx, element_val);
element_val = JS_NULL;
}}""".format(item_type=item_type, parse_item=parse_item)
def generate_quick_parse_call_arg_array_element(component):
return """
if (JS_IsString (element_val))
{{
{register_type} r;
element_str = JS_ToCString (ctx, element_val);
if (element_str == NULL)
goto propagate_exception;
if (!gum_parse_{arch}_register (ctx, element_str, &r))
goto propagate_exception;
item->type = GUM_ARG_REGISTER;
item->value.reg = r;
JS_FreeCString (ctx, element_str);
element_str = NULL;
}}
else
{{
gpointer ptr;
if (!_gum_quick_native_pointer_parse (ctx, element_val, core, &ptr))
goto propagate_exception;
item->type = GUM_ARG_ADDRESS;
item->value.address = GUM_ADDRESS (ptr);
}}""".format(arch=component.arch, register_type=component.register_type)
def generate_quick_parse_register_array_element(component):
return """
if (!JS_IsString (element_val))
goto invalid_argument;
{{
{register_type} reg;
element_str = JS_ToCString (ctx, element_val);
if (element_str == NULL)
goto propagate_exception;
if (!gum_parse_{arch}_register (ctx, element_str, ®))
goto propagate_exception;
*item = reg;
JS_FreeCString (ctx, element_str);
element_str = NULL;
}}""".format(arch=component.arch, register_type=component.register_type)
def generate_quick_fields(component):
return """ JSClassID {flavor}_{name}_class;
JSValue {flavor}_{name}_proto;""".format(**component.__dict__)
def generate_quick_methods(component):
params = dict(component.__dict__)
extra_fields = ""
if component.name == "writer":
extra_fields = "\n GHashTable * labels;"
if component.name == "relocator":
extra_fields = "\n GumQuickInstructionValue * input;"
params["extra_fields"] = extra_fields
template = """\
#include <gum/arch-{arch}/gum{flavor}{name}.h>
typedef struct _{wrapper_struct_name} {wrapper_struct_name};
struct _{wrapper_struct_name}
{{
JSValue wrapper;
{impl_struct_name} * impl;{extra_fields}
JSContext * ctx;
}};
G_GNUC_INTERNAL JSValue _gum_quick_{flavor}_{name}_new (JSContext * ctx, {impl_struct_name} * impl, {module_struct_name} * parent, {wrapper_struct_name} ** {flavor}_{name});
G_GNUC_INTERNAL gboolean _gum_quick_{flavor}_{name}_get (JSContext * ctx, JSValue val, {module_struct_name} * parent, {wrapper_struct_name} ** writer);
G_GNUC_INTERNAL void _gum_quick_{flavor}_{name}_init ({wrapper_struct_name} * self, JSContext * ctx, {module_struct_name} * parent);
G_GNUC_INTERNAL void _gum_quick_{flavor}_{name}_finalize ({wrapper_struct_name} * self);
G_GNUC_INTERNAL void _gum_quick_{flavor}_{name}_reset ({wrapper_struct_name} * self, {impl_struct_name} * impl);
"""
return template.format(**params)
def generate_quick_init_code(component):
return """\
_gum_quick_create_class (ctx, &{gumjs_function_prefix}_def, core,
&self->{gumjs_field_prefix}_class, &proto);
self->{gumjs_field_prefix}_proto = JS_DupValue (ctx, proto);
ctor = JS_NewCFunction2 (ctx, {gumjs_function_prefix}_construct,
{gumjs_function_prefix}_def.class_name, 0, JS_CFUNC_constructor, 0);
JS_SetConstructor (ctx, ctor, proto);
JS_SetPropertyFunctionList (ctx, proto, {gumjs_function_prefix}_entries,
G_N_ELEMENTS ({gumjs_function_prefix}_entries));
JS_DefinePropertyValueStr (ctx, ns, {gumjs_function_prefix}_def.class_name, ctor,
JS_PROP_C_W_E);
""".format(**component.__dict__)
def generate_quick_dispose_code(component):
return """\
JS_FreeValue (ctx, self->{gumjs_field_prefix}_proto);
self->{gumjs_field_prefix}_proto = JS_NULL;
""".format(**component.__dict__)
def generate_quick_base_methods(component):
if component.name == "writer":
return generate_quick_writer_base_methods(component)
elif component.name == "relocator":
return generate_quick_relocator_base_methods(component)
def generate_quick_writer_base_methods(component):
template = """\
static {wrapper_struct_name} * {wrapper_function_prefix}_alloc (JSContext * ctx, {module_struct_name} * module);
static void {wrapper_function_prefix}_dispose ({wrapper_struct_name} * self);
static gboolean {gumjs_function_prefix}_parse_constructor_args (GumQuickArgs * args,
gpointer * code_address, GumAddress * pc, gboolean * pc_specified);
JSValue
_gum_quick_{flavor}_writer_new (
JSContext * ctx,
{impl_struct_name} * impl,
{module_struct_name} * parent,
{wrapper_struct_name} ** writer)
{{
JSValue wrapper;
{wrapper_struct_name} * w;
wrapper = JS_NewObjectClass (ctx, parent->{flavor}_writer_class);
w = {wrapper_function_prefix}_alloc (ctx, parent);
w->impl = (impl != NULL) ? {impl_function_prefix}_ref (impl) : NULL;
JS_SetOpaque (wrapper, w);
if (writer != NULL)
*writer = w;
return wrapper;
}}
gboolean
_gum_quick_{flavor}_writer_get (
JSContext * ctx,
JSValue val,
{module_struct_name} * parent,
{wrapper_struct_name} ** writer)
{{
{wrapper_struct_name} * w;
if (!_gum_quick_unwrap (ctx, val, parent->{flavor}_writer_class, parent->core,
(gpointer *) &w))
return FALSE;
if (w->impl == NULL)
{{
_gum_quick_throw_literal (ctx, "invalid operation");
return FALSE;
}}
*writer = w;
return TRUE;
}}
void
_{wrapper_function_prefix}_init (
{wrapper_struct_name} * self,
JSContext * ctx,
{module_struct_name} * parent)
{{
self->wrapper = JS_NULL;
self->impl = NULL;
self->ctx = ctx;
self->labels = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
}}
void
_{wrapper_function_prefix}_finalize ({wrapper_struct_name} * self)
{{
_gum_quick_{flavor}_writer_reset (self, NULL);
g_hash_table_unref (self->labels);
}}
void
_{wrapper_function_prefix}_reset (
{wrapper_struct_name} * self,
{impl_struct_name} * impl)
{{
if (impl != NULL)
{impl_function_prefix}_ref (impl);
if (self->impl != NULL)
{impl_function_prefix}_unref (self->impl);
self->impl = impl;
g_hash_table_remove_all (self->labels);
}}
static {wrapper_struct_name} *
{wrapper_function_prefix}_alloc (JSContext * ctx,
{module_struct_name} * module)
{{
{wrapper_struct_name} * writer;
writer = g_slice_new ({wrapper_struct_name});
_{wrapper_function_prefix}_init (writer, ctx, module);
return writer;
}}
static void
{wrapper_function_prefix}_dispose ({wrapper_struct_name} * self)
{{
_{wrapper_function_prefix}_reset (self, NULL);
}}
static void
{wrapper_function_prefix}_free ({wrapper_struct_name} * self)
{{
_{wrapper_function_prefix}_finalize (self);
g_slice_free ({wrapper_struct_name}, self);
}}
{label_resolver}
GUMJS_DEFINE_CONSTRUCTOR ({gumjs_function_prefix}_construct)
{{
{module_struct_name} * parent;
JSValue wrapper;
gpointer code_address;
GumAddress pc;
gboolean pc_specified;
JSValue proto;
{wrapper_struct_name} * writer;
parent = gumjs_get_parent_module (core);
if (!{gumjs_function_prefix}_parse_constructor_args (args, &code_address, &pc,
&pc_specified))
return JS_EXCEPTION;
proto = JS_GetProperty (ctx, new_target,
GUM_QUICK_CORE_ATOM (core, prototype));
wrapper = JS_NewObjectProtoClass (ctx, proto, parent->{flavor}_writer_class);
JS_FreeValue (ctx, proto);
if (JS_IsException (wrapper))
return JS_EXCEPTION;
writer = {wrapper_function_prefix}_alloc (ctx, parent);
writer->wrapper = wrapper;
writer->impl = {impl_function_prefix}_new (code_address);
if (pc_specified)
writer->impl->pc = pc;
JS_SetOpaque (wrapper, writer);
return wrapper;
}}
GUMJS_DEFINE_FUNCTION ({gumjs_function_prefix}_reset)
{{
{module_struct_name} * parent;
{wrapper_struct_name} * self;
gpointer code_address;
GumAddress pc;
gboolean pc_specified;
parent = gumjs_get_parent_module (core);
if (!_{wrapper_function_prefix}_get (ctx, this_val, parent, &self))
return JS_EXCEPTION;
if (!{gumjs_function_prefix}_parse_constructor_args (args, &code_address, &pc,
&pc_specified))
return JS_EXCEPTION;
{impl_function_prefix}_reset (self->impl, code_address);
if (pc_specified)
self->impl->pc = pc;
g_hash_table_remove_all (self->labels);
return JS_UNDEFINED;
}}
static gboolean
{gumjs_function_prefix}_parse_constructor_args (
GumQuickArgs * args,
gpointer * code_address,
GumAddress * pc,
gboolean * pc_specified)
{{
JSContext * ctx = args->ctx;
JSValue options;
options = JS_NULL;
if (!_gum_quick_args_parse (args, "p|O", code_address, &options))
return FALSE;
*pc = 0;
*pc_specified = FALSE;
if (!JS_IsNull (options))
{{
GumQuickCore * core = args->core;
JSValue val;
val = JS_GetProperty (ctx, options, GUM_QUICK_CORE_ATOM (core, pc));
if (JS_IsException (val))
return FALSE;
if (!JS_IsUndefined (val))
{{
gboolean valid;
gpointer p;
valid = _gum_quick_native_pointer_get (ctx, val, core, &p);
JS_FreeValue (ctx, val);
if (!valid)
return FALSE;
*pc = GUM_ADDRESS (p);
*pc_specified = TRUE;
}}
}}
return TRUE;
}}
GUMJS_DEFINE_FUNCTION ({gumjs_function_prefix}_dispose)
{{
{module_struct_name} * parent;
{wrapper_struct_name} * self;
parent = gumjs_get_parent_module (core);
if (!_{wrapper_function_prefix}_get (ctx, this_val, parent, &self))
return JS_EXCEPTION;
{wrapper_function_prefix}_dispose (self);
return JS_UNDEFINED;
}}
GUMJS_DEFINE_FINALIZER ({gumjs_function_prefix}_finalize)
{{
{wrapper_struct_name} * w;
w = JS_GetOpaque (val, gumjs_get_parent_module (core)->{flavor}_writer_class);
if (w == NULL)
return;
{wrapper_function_prefix}_free (w);
}}
GUMJS_DEFINE_FUNCTION ({gumjs_function_prefix}_flush)
{{
{module_struct_name} * parent;
{wrapper_struct_name} * self;
gboolean success;
parent = gumjs_get_parent_module (core);
if (!_{wrapper_function_prefix}_get (ctx, this_val, parent, &self))
return JS_EXCEPTION;
success = {impl_function_prefix}_flush (self->impl);
if (!success)
return _gum_quick_throw_literal (ctx, "unable to resolve references");
return JS_UNDEFINED;
}}
GUMJS_DEFINE_GETTER ({gumjs_function_prefix}_get_base)
{{
{module_struct_name} * parent;
{wrapper_struct_name} * self;
parent = gumjs_get_parent_module (core);
if (!_{wrapper_function_prefix}_get (ctx, this_val, parent, &self))
return JS_EXCEPTION;
return _gum_quick_native_pointer_new (ctx, self->impl->base, core);
}}
GUMJS_DEFINE_GETTER ({gumjs_function_prefix}_get_code)
{{
{module_struct_name} * parent;
{wrapper_struct_name} * self;
parent = gumjs_get_parent_module (core);
if (!_{wrapper_function_prefix}_get (ctx, this_val, parent, &self))
return JS_EXCEPTION;
return _gum_quick_native_pointer_new (ctx, self->impl->code, core);
}}
GUMJS_DEFINE_GETTER ({gumjs_function_prefix}_get_pc)
{{
{module_struct_name} * parent;
{wrapper_struct_name} * self;
parent = gumjs_get_parent_module (core);
if (!_{wrapper_function_prefix}_get (ctx, this_val, parent, &self))
return JS_EXCEPTION;
return _gum_quick_native_pointer_new (ctx, GSIZE_TO_POINTER (self->impl->pc),
core);
}}
GUMJS_DEFINE_GETTER ({gumjs_function_prefix}_get_offset)
{{
{module_struct_name} * parent;
{wrapper_struct_name} * self;
parent = gumjs_get_parent_module (core);
if (!_{wrapper_function_prefix}_get (ctx, this_val, parent, &self))
return JS_EXCEPTION;
return JS_NewInt32 (ctx, {impl_function_prefix}_offset (self->impl));
}}
"""
params = dict(component.__dict__)
params["label_resolver"] = """static gconstpointer
{wrapper_function_prefix}_resolve_label ({wrapper_struct_name} * self,
const gchar * str)
{{
gchar * label = g_hash_table_lookup (self->labels, str);
if (label != NULL)
return label;
label = g_strdup (str);
g_hash_table_add (self->labels, label);
return label;
}}""".format(**params)
return template.format(**params).split("\n")
def generate_quick_relocator_base_methods(component):
template = """\
static {wrapper_struct_name} * {wrapper_function_prefix}_alloc (JSContext * ctx, {module_struct_name} * module);
static void {wrapper_function_prefix}_dispose ({wrapper_struct_name} * self);
static gboolean {gumjs_function_prefix}_parse_constructor_args (GumQuickArgs * args,
gconstpointer * input_code, {writer_wrapper_struct_name} ** writer, {module_struct_name} * parent);
JSValue
_gum_quick_{flavor}_relocator_new (
JSContext * ctx,
{impl_struct_name} * impl,
{module_struct_name} * parent,
{wrapper_struct_name} ** relocator)
{{
JSValue wrapper;
{wrapper_struct_name} * r;
wrapper = JS_NewObjectClass (ctx, parent->{flavor}_relocator_class);
r = {wrapper_function_prefix}_alloc (ctx, parent);
r->impl = (impl != NULL) ? {impl_function_prefix}_ref (impl) : NULL;
JS_SetOpaque (wrapper, r);
if (relocator != NULL)
*relocator = r;
return wrapper;
}}
gboolean
_gum_quick_{flavor}_relocator_get (
JSContext * ctx,
JSValue val,
{module_struct_name} * parent,
{wrapper_struct_name} ** relocator)
{{
{wrapper_struct_name} * r;
if (!_gum_quick_unwrap (ctx, val, parent->{flavor}_relocator_class, parent->core,
(gpointer *) &r))
return FALSE;
if (r->impl == NULL)
{{
_gum_quick_throw_literal (ctx, "invalid operation");
return FALSE;
}}
*relocator = r;
return TRUE;
}}
void
_{wrapper_function_prefix}_init (
{wrapper_struct_name} * self,
JSContext * ctx,
{module_struct_name} * parent)
{{
self->wrapper = JS_NULL;
self->impl = NULL;
_gum_quick_instruction_new (ctx, NULL, TRUE, NULL, 0, parent->instruction,
&self->input);
self->ctx = ctx;
}}
void
_{wrapper_function_prefix}_finalize ({wrapper_struct_name} * self)
{{
_{wrapper_function_prefix}_reset (self, NULL);
JS_FreeValue (self->ctx, self->input->wrapper);
}}
void
_{wrapper_function_prefix}_reset (
{wrapper_struct_name} * self,
{impl_struct_name} * impl)
{{
if (impl != NULL)
{impl_function_prefix}_ref (impl);
if (self->impl != NULL)
{impl_function_prefix}_unref (self->impl);
self->impl = impl;
self->input->insn = NULL;
}}
static {wrapper_struct_name} *
{wrapper_function_prefix}_alloc (JSContext * ctx,
{module_struct_name} * parent)
{{
{wrapper_struct_name} * relocator;
relocator = g_slice_new ({wrapper_struct_name});
_{wrapper_function_prefix}_init (relocator, ctx, parent);
return relocator;
}}
static void
{wrapper_function_prefix}_dispose ({wrapper_struct_name} * self)
{{
_{wrapper_function_prefix}_reset (self, NULL);
}}
static void
{wrapper_function_prefix}_free ({wrapper_struct_name} * self)
{{
_{wrapper_function_prefix}_finalize (self);
g_slice_free ({wrapper_struct_name}, self);
}}
GUMJS_DEFINE_CONSTRUCTOR ({gumjs_function_prefix}_construct)
{{
{module_struct_name} * parent;
JSValue wrapper;
gconstpointer input_code;
{writer_wrapper_struct_name} * writer;
JSValue proto;
{wrapper_struct_name} * relocator;
parent = gumjs_get_parent_module (core);
if (!{gumjs_function_prefix}_parse_constructor_args (args, &input_code, &writer,
parent))
return JS_EXCEPTION;
proto = JS_GetProperty (ctx, new_target,
GUM_QUICK_CORE_ATOM (core, prototype));
wrapper = JS_NewObjectProtoClass (ctx, proto, parent->{flavor}_relocator_class);
JS_FreeValue (ctx, proto);
if (JS_IsException (wrapper))
return JS_EXCEPTION;
relocator = {wrapper_function_prefix}_alloc (ctx, parent);
relocator->wrapper = wrapper;
relocator->impl = {impl_function_prefix}_new (input_code, writer->impl);
JS_SetOpaque (wrapper, relocator);
return wrapper;
}}
GUMJS_DEFINE_FUNCTION ({gumjs_function_prefix}_reset)
{{
{module_struct_name} * parent;
{wrapper_struct_name} * self;
gconstpointer input_code;
{writer_wrapper_struct_name} * writer;
parent = gumjs_get_parent_module (core);
if (!_{wrapper_function_prefix}_get (ctx, this_val, parent, &self))
return JS_EXCEPTION;
if (!{gumjs_function_prefix}_parse_constructor_args (args, &input_code, &writer,
parent))
return JS_EXCEPTION;
{impl_function_prefix}_reset (self->impl, input_code, writer->impl);
self->input->insn = NULL;
return JS_UNDEFINED;
}}
static gboolean
{gumjs_function_prefix}_parse_constructor_args (
GumQuickArgs * args,
gconstpointer * input_code,
{writer_wrapper_struct_name} ** writer,
{module_struct_name} * parent)
{{
JSValue writer_object;
if (!_gum_quick_args_parse (args, "pO", input_code, &writer_object))
return FALSE;
if (!_gum_quick_{flavor}_writer_get (args->ctx, writer_object, parent->writer,
writer))
return FALSE;
return TRUE;
}}
GUMJS_DEFINE_FUNCTION ({gumjs_function_prefix}_dispose)
{{
{module_struct_name} * parent;
{wrapper_struct_name} * self;
parent = gumjs_get_parent_module (core);
if (!_{wrapper_function_prefix}_get (ctx, this_val, parent, &self))
return JS_EXCEPTION;
{wrapper_function_prefix}_dispose (self);
return JS_UNDEFINED;
}}
GUMJS_DEFINE_FINALIZER ({gumjs_function_prefix}_finalize)
{{
{wrapper_struct_name} * r;
r = JS_GetOpaque (val, gumjs_get_parent_module (core)->{flavor}_relocator_class);
if (r == NULL)
return;
{wrapper_function_prefix}_free (r);
}}
GUMJS_DEFINE_FUNCTION ({gumjs_function_prefix}_read_one)
{{
{module_struct_name} * parent;
{wrapper_struct_name} * self;
guint n_read;
parent = gumjs_get_parent_module (core);
if (!_{wrapper_function_prefix}_get (ctx, this_val, parent, &self))
return JS_EXCEPTION;
n_read = {impl_function_prefix}_read_one (self->impl, &self->input->insn);
if (n_read != 0)
{{
self->input->target = {get_input_target_expression};
}}
return JS_NewInt32 (ctx, n_read);
}}
GUMJS_DEFINE_GETTER ({gumjs_function_prefix}_get_input)
{{
{module_struct_name} * parent;
{wrapper_struct_name} * self;
parent = gumjs_get_parent_module (core);
if (!_{wrapper_function_prefix}_get (ctx, this_val, parent, &self))
return JS_EXCEPTION;
if (self->input->insn == NULL)
return JS_NULL;
return JS_DupValue (ctx, self->input->wrapper);
}}
GUMJS_DEFINE_GETTER ({gumjs_function_prefix}_get_eob)
{{
{module_struct_name} * parent;
{wrapper_struct_name} * self;
parent = gumjs_get_parent_module (core);
if (!_{wrapper_function_prefix}_get (ctx, this_val, parent, &self))
return JS_EXCEPTION;
return JS_NewBool (ctx, {impl_function_prefix}_eob (self->impl));
}}
GUMJS_DEFINE_GETTER ({gumjs_function_prefix}_get_eoi)
{{
{module_struct_name} * parent;
{wrapper_struct_name} * self;
parent = gumjs_get_parent_module (core);
if (!_{wrapper_function_prefix}_get (ctx, this_val, parent, &self))
return JS_EXCEPTION;
return JS_NewBool (ctx, {impl_function_prefix}_eoi (self->impl));
}}
"""
if component.flavor == "x86":
target = "GSIZE_TO_POINTER (self->input->insn->address)"
else:
target = "self->impl->input_start +\n (self->input->insn->address -\n (self->impl->input_pc - self->impl->inpos))"
if component.flavor == "thumb":
target = "GSIZE_TO_POINTER (GPOINTER_TO_SIZE ({0}) | 1)".format(target)
params = {
"writer_wrapper_struct_name": component.wrapper_struct_name.replace("Relocator", "Writer"),
"get_input_target_expression": target,
}
params.update(component.__dict__)
return template.format(**params).split("\n")
def generate_quick_enum_parser(name, type, prefix, values):
common_decls, common_code = generate_enum_parser(name, type, prefix, values)
params = {
'name': name,
'result_identifier': name.split("_")[-1].replace("register", "reg"),
'description': name.replace("_", " "),
'type': type,
}
decls = [
"static gboolean gum_parse_{name} (JSContext * ctx, const gchar * name, {type} * {result_identifier});".format(**params)
] + common_decls
code = """\
static gboolean
gum_parse_{name} (
JSContext * ctx,
const gchar * name,
{type} * {result_identifier})
{{
if (!gum_try_parse_{name} (name, {result_identifier}))
{{
_gum_quick_throw_literal (ctx, "invalid {description}");
return FALSE;
}}
return TRUE;
}}
""".format(**params).split("\n") + common_code
return (decls, code)
def generate_v8_bindings(name, arch, flavor, api):
component = Component(name, arch, flavor, "v8")
return {
"gumv8code{0}-{1}.inc".format(name, flavor): generate_v8_wrapper_code(component, api),
"gumv8code{0}-fields-{1}.inc".format(name, flavor): generate_v8_fields(component),
"gumv8code{0}-methods-{1}.inc".format(name, flavor): generate_v8_methods(component),
"gumv8code{0}-init-{1}.inc".format(name, flavor): generate_v8_init_code(component),
"gumv8code{0}-dispose-{1}.inc".format(name, flavor): generate_v8_dispose_code(component),
}
def generate_v8_wrapper_code(component, api):
lines = [
"/* Auto-generated, do not edit. */",
"",
"#include <string>",
"#include <string.h>",
]
conversion_decls, conversion_code = generate_conversion_methods(component, generate_v8_enum_parser)
if len(conversion_decls) > 0:
lines.append("")
lines.extend(conversion_decls)
lines.append("")
lines.extend(generate_v8_base_methods(component))
for method in api.instance_methods:
args = method.args
is_put_array = method.is_put_array
if method.is_put_call:
array_item_type = "GumArgument"
array_item_parse_logic = generate_v8_parse_call_arg_array_element(component, api)
elif method.is_put_regs:
array_item_type = api.native_register_type
array_item_parse_logic = generate_v8_parse_register_array_element(component, api)
lines.extend([
"GUMJS_DEFINE_CLASS_METHOD ({0}_{1}, {2})".format(component.gumjs_function_prefix, method.name, component.wrapper_struct_name),
"{",
" if (!{0}_check (self, isolate))".format(component.wrapper_function_prefix),
" return;",
])
if len(args) > 0:
lines.append("")
for arg in args:
type_raw = arg.type_raw_for_cpp()
if type_raw == "$array":
type_raw = "Local<Array>"
lines.append(" {0} {1};".format(type_raw, arg.name_raw_for_cpp()))
arglist_signature = "".join([arg.type_format_for_cpp() for arg in args])
arglist_pointers = ", ".join(["&" + arg.name_raw_for_cpp() for arg in args])
lines.extend([
" if (!_gum_v8_args_parse (args, \"{0}\", {1}))".format(arglist_signature, arglist_pointers),
" return;",
])
args_needing_conversion = [arg for arg in args if arg.type_converter_for_cpp() is not None]
if len(args_needing_conversion) > 0:
lines.append("")
for arg in args_needing_conversion:
converter = arg.type_converter_for_cpp()
if converter == "label":
lines.append(" auto {value} = {wrapper_function_prefix}_resolve_label (self, {value_raw});".format(
value=arg.name,
value_raw=arg.name_raw_for_cpp(),
wrapper_function_prefix=component.wrapper_function_prefix))
elif converter == "address":
lines.append(" auto {value} = GUM_ADDRESS ({value_raw});".format(
value=arg.name,
value_raw=arg.name_raw_for_cpp()))
elif converter == "bytes":
lines.extend([
" gsize {0}_size;".format(arg.name),
" auto {value} = (const guint8 *) g_bytes_get_data ({value_raw}, &{value}_size);".format(
value=arg.name,
value_raw=arg.name_raw_for_cpp()),
])
else:
lines.extend([
" {0} {1};".format(arg.type, arg.name),
" if (!gum_parse_{arch}_{type} (isolate, {value_raw}, &{value}))".format(
value=arg.name,
value_raw=arg.name_raw_for_cpp(),
arch=component.arch,
type=arg.type_converter_for_cpp()),
" return;",
])
if is_put_array:
lines.extend(generate_v8_parse_array_elements(array_item_type, array_item_parse_logic).split("\n"))
impl_function_name = "{0}_{1}".format(component.impl_function_prefix, method.name)
arglist = ["self->impl"]
if method.needs_calling_convention_arg:
arglist.append("GUM_CALL_CAPI")
for arg in args:
if arg.type_converter_for_cpp() == "bytes":
arglist.extend([arg.name, arg.name + "_size"])
else:
arglist.append(arg.name)
if is_put_array:
impl_function_name += "_array"
arglist.insert(len(arglist) - 1, "items_length")
if method.return_type == "void":
return_capture = ""
else:
return_capture = "auto result = "
lines.extend([
"",
" {0}{1} ({2});".format(return_capture, impl_function_name, ", ".join(arglist))
])
if method.return_type == "gboolean" and method.name.startswith("put_"):
lines.extend([
" if (!result)",
" _gum_v8_throw_ascii_literal (isolate, \"invalid argument\");",
])
elif method.return_type != "void":
lines.append("")
if method.return_type == "gboolean":
lines.append(" info.GetReturnValue ().Set (!!result);")
elif method.return_type == "guint":
lines.append(" info.GetReturnValue ().Set ((uint32_t) result);")
elif method.return_type == "gpointer":
lines.append(" info.GetReturnValue ().Set (_gum_v8_native_pointer_new (result, core));")
elif method.return_type == "GumAddress":
lines.append(" info.GetReturnValue ().Set (_gum_v8_native_pointer_new (GSIZE_TO_POINTER (result), core));")
elif method.return_type == "cs_insn *":
if component.flavor == "x86":
target = "GSIZE_TO_POINTER (result->address)"
else:
target = "self->impl->input_start + (result->address - (self->impl->input_pc - self->impl->inpos))"
if component.flavor == "thumb":
target = "GSIZE_TO_POINTER (GPOINTER_TO_SIZE ({0}) | 1)".format(target)
lines.extend([
" if (result != NULL)",
" {",
" info.GetReturnValue ().Set (_gum_v8_instruction_new (self->impl->capstone, result, FALSE,",
" {0}, module->instruction));".format(target),
" }",
" else",
" {",
" info.GetReturnValue ().SetNull ();"
" }",
])
else:
raise ValueError("Unsupported return type: {0}".format(method.return_type))
args_needing_cleanup = [arg for arg in args if arg.type_converter_for_cpp() == "bytes"]
if len(args_needing_cleanup) > 0:
lines.append("")
for arg in args_needing_cleanup:
lines.append(" g_bytes_unref ({0});".format(arg.name_raw_for_cpp()))
lines.extend([
"}",
""
])
lines.extend([
"static const GumV8Function {0}_functions[] =".format(component.gumjs_function_prefix),
"{",
" {{ \"reset\", {0}_reset }},".format(component.gumjs_function_prefix),
" {{ \"dispose\", {0}_dispose }},".format(component.gumjs_function_prefix),
])
if component.name == "writer":
lines.append(" {{ \"flush\", {0}_flush }},".format(component.gumjs_function_prefix))
elif component.name == "relocator":
lines.append(" {{ \"readOne\", {0}_read_one }},".format(component.gumjs_function_prefix))
for method in api.instance_methods:
lines.append(" {{ \"{0}\", {1}_{2} }},".format(
method.name_js,
component.gumjs_function_prefix,
method.name
))
lines.extend([
"",
" { NULL, NULL }",
"};",
""
])
lines.extend(conversion_code)
return "\n".join(lines)
def generate_v8_parse_array_elements(item_type, parse_item):
return """
auto context = isolate->GetCurrentContext ();
uint32_t items_length = items_value->Length ();
auto items = g_newa ({item_type}, items_length);
for (uint32_t items_index = 0; items_index != items_length; items_index++)
{{
{item_type} * item = &items[items_index];
{parse_item}
}}""".format(item_type=item_type, parse_item=parse_item)
def generate_v8_parse_call_arg_array_element(component, api):
return """
auto value = items_value->Get (context, items_index).ToLocalChecked ();
if (value->IsString ())
{{
item->type = GUM_ARG_REGISTER;
String::Utf8Value value_as_utf8 (isolate, value);
{native_register_type} value_as_reg;
if (!gum_parse_{arch}_register (isolate, *value_as_utf8, &value_as_reg))
return;
item->value.reg = value_as_reg;
}}
else
{{
item->type = GUM_ARG_ADDRESS;
gpointer ptr;
if (!_gum_v8_native_pointer_parse (value, &ptr, core))
return;
item->value.address = GUM_ADDRESS (ptr);
}}""".format(arch=component.arch, native_register_type=api.native_register_type)
def generate_v8_parse_register_array_element(component, api):
return """
auto value = items_value->Get (context, items_index).ToLocalChecked ();
if (!value->IsString ())
{{
_gum_v8_throw_ascii_literal (isolate, "expected an array with register names");
return;
}}
String::Utf8Value value_as_utf8 (isolate, value);
{native_register_type} value_as_reg;
if (!gum_parse_{arch}_register (isolate, *value_as_utf8, &value_as_reg))
return;
*item = value_as_reg;""".format(arch=component.arch, native_register_type=api.native_register_type)
def generate_v8_fields(component):
return """\
GHashTable * {flavor}_{name}s;
GumPersistent<v8::FunctionTemplate>::type * {flavor}_{name};""".format(**component.__dict__)
def generate_v8_methods(component):
params = dict(component.__dict__)
if component.name == "writer":
extra_fields = "\n GHashTable * labels;"
elif component.name == "relocator":
extra_fields = "\n GumV8InstructionValue * input;"
params["extra_fields"] = extra_fields
template = """\
#include <gum/arch-{arch}/gum{flavor}{name}.h>
struct {wrapper_struct_name}
{{
GumPersistent<v8::Object>::type * object;
{impl_struct_name} * impl;{extra_fields}
{module_struct_name} * module;
}};
G_GNUC_INTERNAL gboolean _gum_v8_{flavor}_writer_get (v8::Local<v8::Value> value,
{impl_struct_name} ** writer, {module_struct_name} * module);
G_GNUC_INTERNAL {wrapper_struct_name} * _{wrapper_function_prefix}_new_persistent ({module_struct_name} * module);
G_GNUC_INTERNAL void _{wrapper_function_prefix}_release_persistent ({wrapper_struct_name} * {name});
G_GNUC_INTERNAL void _{wrapper_function_prefix}_init ({wrapper_struct_name} * self, {module_struct_name} * module);
G_GNUC_INTERNAL void _{wrapper_function_prefix}_finalize ({wrapper_struct_name} * self);
G_GNUC_INTERNAL void _{wrapper_function_prefix}_reset ({wrapper_struct_name} * self, {impl_struct_name} * impl);"""
return template.format(**params)
def generate_v8_init_code(component):
return """\
auto {flavor}_{name} = _gum_v8_create_class ("{gumjs_class_name}",
{gumjs_function_prefix}_construct, scope, module, isolate);
_gum_v8_class_add ({flavor}_{name}, {gumjs_function_prefix}_values, module,
isolate);
_gum_v8_class_add ({flavor}_{name}, {gumjs_function_prefix}_functions, module,
isolate);
self->{flavor}_{name} =
new GumPersistent<FunctionTemplate>::type (isolate, {flavor}_{name});
self->{flavor}_{name}s = g_hash_table_new_full (NULL, NULL, NULL,
(GDestroyNotify) {wrapper_function_prefix}_free);
""".format(**component.__dict__)
def generate_v8_dispose_code(component):
return """\
g_hash_table_unref (self->{flavor}_{name}s);
self->{flavor}_{name}s = NULL;
delete self->{flavor}_{name};
self->{flavor}_{name} = nullptr;
""".format(**component.__dict__)
def generate_v8_base_methods(component):
if component.name == "writer":
return generate_v8_writer_base_methods(component)
elif component.name == "relocator":
return generate_v8_relocator_base_methods(component)
def generate_v8_writer_base_methods(component):
template = """\
static {wrapper_struct_name} * {wrapper_function_prefix}_alloc (GumV8CodeWriter * module);
static void {wrapper_function_prefix}_dispose ({wrapper_struct_name} * self);
static void {wrapper_function_prefix}_mark_weak ({wrapper_struct_name} * self);
static void {wrapper_function_prefix}_on_weak_notify (
const WeakCallbackInfo<{wrapper_struct_name}> & info);
static gboolean {gumjs_function_prefix}_parse_constructor_args (const GumV8Args * args,
gpointer * code_address, GumAddress * pc, gboolean * pc_specified);
static gboolean {wrapper_function_prefix}_check ({wrapper_struct_name} * self,
Isolate * isolate);
gboolean
_gum_v8_{flavor}_writer_get (
v8::Local<v8::Value> value,
{impl_struct_name} ** writer,
{module_struct_name} * module)
{{
auto isolate = module->core->isolate;
auto writer_class = Local<FunctionTemplate>::New (isolate,
*module->{flavor}_writer);
if (!writer_class->HasInstance (value))
{{
_gum_v8_throw_ascii_literal (isolate, "expected {flavor} writer");
return FALSE;
}}
auto wrapper = ({wrapper_struct_name} *)
value.As<Object> ()->GetAlignedPointerFromInternalField (0);
if (!{wrapper_function_prefix}_check (wrapper, isolate))
return FALSE;
*writer = wrapper->impl;
return TRUE;
}}
{wrapper_struct_name} *
_{wrapper_function_prefix}_new_persistent (GumV8CodeWriter * module)
{{
auto isolate = module->core->isolate;
auto context = isolate->GetCurrentContext ();
auto writer = {wrapper_function_prefix}_alloc (module);
auto writer_class = Local<FunctionTemplate>::New (isolate,
*module->{flavor}_writer);
auto writer_value = External::New (isolate, writer);
Local<Value> argv[] = {{ writer_value }};
auto object = writer_class->GetFunction (context).ToLocalChecked ()
->NewInstance (context, G_N_ELEMENTS (argv), argv).ToLocalChecked ();
writer->object = new GumPersistent<Object>::type (isolate, object);
return writer;
}}
void
_{wrapper_function_prefix}_release_persistent ({wrapper_struct_name} * writer)
{{
{wrapper_function_prefix}_dispose (writer);
{wrapper_function_prefix}_mark_weak (writer);
}}
void
_{wrapper_function_prefix}_init (
{wrapper_struct_name} * self,
{module_struct_name} * module)
{{
self->object = nullptr;
self->impl = NULL;
self->labels = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
self->module = module;
}}
void
_{wrapper_function_prefix}_finalize ({wrapper_struct_name} * self)
{{
_{wrapper_function_prefix}_reset (self, NULL);
g_hash_table_unref (self->labels);
delete self->object;
}}
void
_{wrapper_function_prefix}_reset (
{wrapper_struct_name} * self,
{impl_struct_name} * impl)
{{
if (impl != NULL)
{impl_function_prefix}_ref (impl);
if (self->impl != NULL)
{impl_function_prefix}_unref (self->impl);
self->impl = impl;
g_hash_table_remove_all (self->labels);
}}
static {wrapper_struct_name} *
{wrapper_function_prefix}_alloc (GumV8CodeWriter * module)
{{
{wrapper_struct_name} * writer;
writer = g_slice_new ({wrapper_struct_name});
_{wrapper_function_prefix}_init (writer, module);
return writer;
}}
static void
{wrapper_function_prefix}_dispose ({wrapper_struct_name} * self)
{{
_{wrapper_function_prefix}_reset (self, NULL);
}}
static void
{wrapper_function_prefix}_free ({wrapper_struct_name} * self)
{{
_{wrapper_function_prefix}_finalize (self);
g_slice_free ({wrapper_struct_name}, self);
}}
static void
{wrapper_function_prefix}_mark_weak ({wrapper_struct_name} * self)
{{
self->object->SetWeak (self, {wrapper_function_prefix}_on_weak_notify,
WeakCallbackType::kParameter);
g_hash_table_add (self->module->{flavor}_{name}s, self);
}}
{label_resolver}
static void
{wrapper_function_prefix}_on_weak_notify (
const WeakCallbackInfo<{wrapper_struct_name}> & info)
{{
HandleScope handle_scope (info.GetIsolate ());
auto self = info.GetParameter ();
g_hash_table_remove (self->module->{flavor}_{name}s, self);
}}
static gboolean
{wrapper_function_prefix}_check (
{wrapper_struct_name} * self,
Isolate * isolate)
{{
if (self->impl == NULL)
{{
_gum_v8_throw_ascii_literal (isolate, "invalid operation");
return FALSE;
}}
return TRUE;
}}
GUMJS_DEFINE_CONSTRUCTOR ({gumjs_function_prefix}_construct)
{{
if (!info.IsConstructCall ())
{{
_gum_v8_throw_ascii_literal (isolate,
"use constructor syntax to create a new instance");
return;
}}
{wrapper_struct_name} * writer;
if (info.Length () == 1 && info[0]->IsExternal ())
{{
writer = ({wrapper_struct_name} *) info[0].As<External> ()->Value ();
}}
else
{{
gpointer code_address;
GumAddress pc;
gboolean pc_specified;
if (!{gumjs_function_prefix}_parse_constructor_args (args, &code_address, &pc,
&pc_specified))
return;
writer = {wrapper_function_prefix}_alloc (module);
writer->object = new GumPersistent<Object>::type (isolate, wrapper);
{wrapper_function_prefix}_mark_weak (writer);
writer->impl = {impl_function_prefix}_new (code_address);
if (pc_specified)
writer->impl->pc = pc;
}}
wrapper->SetAlignedPointerInInternalField (0, writer);
}}
GUMJS_DEFINE_CLASS_METHOD ({gumjs_function_prefix}_reset, {wrapper_struct_name})
{{
if (!{wrapper_function_prefix}_check (self, isolate))
return;
gpointer code_address;
GumAddress pc;
gboolean pc_specified;
if (!{gumjs_function_prefix}_parse_constructor_args (args, &code_address, &pc,
&pc_specified))
return;
{impl_function_prefix}_reset (self->impl, code_address);
if (pc_specified)
self->impl->pc = pc;
g_hash_table_remove_all (self->labels);
}}
static gboolean
{gumjs_function_prefix}_parse_constructor_args (
const GumV8Args * args,
gpointer * code_address,
GumAddress * pc,
gboolean * pc_specified)
{{
auto isolate = args->core->isolate;
Local<Object> options;
if (!_gum_v8_args_parse (args, "p|O", code_address, &options))
return FALSE;
*pc = 0;
*pc_specified = FALSE;
if (!options.IsEmpty ())
{{
auto context = isolate->GetCurrentContext ();
Local<Value> pc_value;
if (!options->Get (context, _gum_v8_string_new_ascii (isolate, "pc"))
.ToLocal (&pc_value))
{{
return FALSE;
}}
if (!pc_value->IsUndefined ())
{{
gpointer raw_value;
if (!_gum_v8_native_pointer_get (pc_value, &raw_value, args->core))
return FALSE;
*pc = GUM_ADDRESS (raw_value);
*pc_specified = TRUE;
}}
}}
return TRUE;
}}
GUMJS_DEFINE_CLASS_METHOD ({gumjs_function_prefix}_dispose, {wrapper_struct_name})
{{
{wrapper_function_prefix}_dispose (self);
}}
GUMJS_DEFINE_CLASS_METHOD ({gumjs_function_prefix}_flush, {wrapper_struct_name})
{{
if (!{wrapper_function_prefix}_check (self, isolate))
return;
auto success = {impl_function_prefix}_flush (self->impl);
if (!success)
_gum_v8_throw_ascii_literal (isolate, "unable to resolve references");
}}
GUMJS_DEFINE_CLASS_GETTER ({gumjs_function_prefix}_get_base, {wrapper_struct_name})
{{
if (!{wrapper_function_prefix}_check (self, isolate))
return;
info.GetReturnValue ().Set (
_gum_v8_native_pointer_new (self->impl->base, core));
}}
GUMJS_DEFINE_CLASS_GETTER ({gumjs_function_prefix}_get_code, {wrapper_struct_name})
{{
if (!{wrapper_function_prefix}_check (self, isolate))
return;
info.GetReturnValue ().Set (
_gum_v8_native_pointer_new (self->impl->code, core));
}}
GUMJS_DEFINE_CLASS_GETTER ({gumjs_function_prefix}_get_pc, {wrapper_struct_name})
{{
if (!{wrapper_function_prefix}_check (self, isolate))
return;
info.GetReturnValue ().Set (
_gum_v8_native_pointer_new (GSIZE_TO_POINTER (self->impl->pc), core));
}}
GUMJS_DEFINE_CLASS_GETTER ({gumjs_function_prefix}_get_offset, {wrapper_struct_name})
{{
if (!{wrapper_function_prefix}_check (self, isolate))
return;
info.GetReturnValue ().Set ({impl_function_prefix}_offset (self->impl));
}}
static const GumV8Property {gumjs_function_prefix}_values[] =
{{
{{ "base", {gumjs_function_prefix}_get_base, NULL }},
{{ "code", {gumjs_function_prefix}_get_code, NULL }},
{{ "pc", {gumjs_function_prefix}_get_pc, NULL }},
{{ "offset", {gumjs_function_prefix}_get_offset, NULL }},
{{ NULL, NULL, NULL }}
}};
"""
params = dict(component.__dict__)
params["label_resolver"] = """
static gconstpointer
{wrapper_function_prefix}_resolve_label ({wrapper_struct_name} * self,
const std::string & str)
{{
gchar * label = (gchar *) g_hash_table_lookup (self->labels, str.c_str ());
if (label != NULL)
return label;
label = g_strdup (str.c_str ());
g_hash_table_add (self->labels, label);
return label;
}}
""".format(**params)
return template.format(**params).split("\n")
def generate_v8_relocator_base_methods(component):
template = """\
static {wrapper_struct_name} * {wrapper_function_prefix}_alloc (GumV8CodeRelocator * module);
static void {wrapper_function_prefix}_dispose ({wrapper_struct_name} * self);
static void {wrapper_function_prefix}_mark_weak ({wrapper_struct_name} * self);
static void {wrapper_function_prefix}_on_weak_notify (
const WeakCallbackInfo<{wrapper_struct_name}> & info);
static gboolean {wrapper_function_prefix}_check ({wrapper_struct_name} * self,
Isolate * isolate);
static gboolean {gumjs_function_prefix}_parse_constructor_args (const GumV8Args * args,
gconstpointer * input_code, {writer_impl_struct_name} ** writer,
GumV8CodeRelocator * module);
gboolean
_gum_v8_{flavor}_relocator_get (
v8::Local<v8::Value> value,
{impl_struct_name} ** relocator,
{module_struct_name} * module)
{{
auto isolate = module->core->isolate;
auto relocator_class = Local<FunctionTemplate>::New (isolate,
*module->{flavor}_relocator);
if (!relocator_class->HasInstance (value))
{{
_gum_v8_throw_ascii_literal (isolate, "expected {flavor} relocator");
return FALSE;
}}
auto relocator_wrapper = ({wrapper_struct_name} *)
value.As<Object> ()->GetAlignedPointerFromInternalField (0);
if (!{wrapper_function_prefix}_check (relocator_wrapper, isolate))
return FALSE;
*relocator = relocator_wrapper->impl;
return TRUE;
}}
{wrapper_struct_name} *
_{wrapper_function_prefix}_new_persistent (GumV8CodeRelocator * module)
{{
auto isolate = module->core->isolate;
auto context = isolate->GetCurrentContext ();
auto relocator = {wrapper_function_prefix}_alloc (module);
auto relocator_class = Local<FunctionTemplate>::New (isolate,
*module->{flavor}_relocator);
auto relocator_value = External::New (isolate, relocator);
Local<Value> argv[] = {{ relocator_value }};
auto object = relocator_class->GetFunction (context).ToLocalChecked ()
->NewInstance (context, G_N_ELEMENTS (argv), argv).ToLocalChecked ();
relocator->object = new GumPersistent<Object>::type (isolate, object);
return relocator;
}}
void
_{wrapper_function_prefix}_release_persistent ({wrapper_struct_name} * relocator)
{{
{wrapper_function_prefix}_dispose (relocator);
{wrapper_function_prefix}_mark_weak (relocator);
}}
void
_{wrapper_function_prefix}_init (
{wrapper_struct_name} * self,
{module_struct_name} * module)
{{
self->object = nullptr;
self->impl = NULL;
self->input = _gum_v8_instruction_new_persistent (module->instruction);
self->module = module;
}}
void
_{wrapper_function_prefix}_finalize ({wrapper_struct_name} * self)
{{
_{wrapper_function_prefix}_reset (self, NULL);
_gum_v8_instruction_release_persistent (self->input);
delete self->object;
}}
void
_{wrapper_function_prefix}_reset (
{wrapper_struct_name} * self,
{impl_struct_name} * impl)
{{
if (impl != NULL)
{impl_function_prefix}_ref (impl);
if (self->impl != NULL)
{impl_function_prefix}_unref (self->impl);
self->impl = impl;
self->input->insn = NULL;
}}
static {wrapper_struct_name} *
{wrapper_function_prefix}_alloc (GumV8CodeRelocator * module)
{{
{wrapper_struct_name} * relocator;
relocator = g_slice_new ({wrapper_struct_name});
_{wrapper_function_prefix}_init (relocator, module);
return relocator;
}}
static void
{wrapper_function_prefix}_dispose ({wrapper_struct_name} * self)
{{
_{wrapper_function_prefix}_reset (self, NULL);
}}
static void
{wrapper_function_prefix}_free ({wrapper_struct_name} * self)
{{
_{wrapper_function_prefix}_finalize (self);
g_slice_free ({wrapper_struct_name}, self);
}}
static void
{wrapper_function_prefix}_mark_weak ({wrapper_struct_name} * self)
{{
self->object->SetWeak (self, {wrapper_function_prefix}_on_weak_notify,
WeakCallbackType::kParameter);
g_hash_table_add (self->module->{flavor}_{name}s, self);
}}
static void
{wrapper_function_prefix}_on_weak_notify (
const WeakCallbackInfo<{wrapper_struct_name}> & info)
{{
HandleScope handle_scope (info.GetIsolate ());
auto self = info.GetParameter ();
g_hash_table_remove (self->module->{flavor}_{name}s, self);
}}
static gboolean
{wrapper_function_prefix}_check (
{wrapper_struct_name} * self,
Isolate * isolate)
{{
if (self->impl == NULL)
{{
_gum_v8_throw_ascii_literal (isolate, "invalid operation");
return FALSE;
}}
return TRUE;
}}
GUMJS_DEFINE_CONSTRUCTOR ({gumjs_function_prefix}_construct)
{{
if (!info.IsConstructCall ())
{{
_gum_v8_throw_ascii_literal (isolate,
"use constructor syntax to create a new instance");
return;
}}
{wrapper_struct_name} * relocator;
if (info.Length () == 1 && info[0]->IsExternal ())
{{
relocator = ({wrapper_struct_name} *) info[0].As<External> ()->Value ();
}}
else
{{
gconstpointer input_code;
{writer_impl_struct_name} * writer;
if (!{gumjs_function_prefix}_parse_constructor_args (args, &input_code, &writer, module))
return;
relocator = {wrapper_function_prefix}_alloc (module);
relocator->object = new GumPersistent<Object>::type (isolate, wrapper);
{wrapper_function_prefix}_mark_weak (relocator);
relocator->impl = {impl_function_prefix}_new (input_code, writer);
}}
wrapper->SetAlignedPointerInInternalField (0, relocator);
}}
GUMJS_DEFINE_CLASS_METHOD ({gumjs_function_prefix}_reset, {wrapper_struct_name})
{{
if (!{wrapper_function_prefix}_check (self, isolate))
return;
gconstpointer input_code;
{writer_impl_struct_name} * writer;
if (!{gumjs_function_prefix}_parse_constructor_args (args, &input_code, &writer, module))
return;
{impl_function_prefix}_reset (self->impl, input_code, writer);
self->input->insn = NULL;
}}
static gboolean
{gumjs_function_prefix}_parse_constructor_args (
const GumV8Args * args,
gconstpointer * input_code,
{writer_impl_struct_name} ** writer,
{module_struct_name} * module)
{{
Local<Object> writer_object;
if (!_gum_v8_args_parse (args, "pO", input_code, &writer_object))
return FALSE;
if (!_gum_v8_{flavor}_writer_get (writer_object, writer, module->writer))
return FALSE;
return TRUE;
}}
GUMJS_DEFINE_CLASS_METHOD ({gumjs_function_prefix}_dispose, {wrapper_struct_name})
{{
{wrapper_function_prefix}_dispose (self);
}}
GUMJS_DEFINE_CLASS_METHOD ({gumjs_function_prefix}_read_one, {wrapper_struct_name})
{{
if (!{wrapper_function_prefix}_check (self, isolate))
return;
uint32_t n_read = {impl_function_prefix}_read_one (self->impl, &self->input->insn);
if (n_read != 0)
{{
self->input->target = {get_input_target_expression};
}}
info.GetReturnValue ().Set (n_read);
}}
GUMJS_DEFINE_CLASS_GETTER ({gumjs_function_prefix}_get_input, {wrapper_struct_name})
{{
if (!{wrapper_function_prefix}_check (self, isolate))
return;
if (self->input->insn != NULL)
{{
info.GetReturnValue ().Set (
Local<Object>::New (isolate, *self->input->object));
}}
else
{{
info.GetReturnValue ().SetNull ();
}}
}}
GUMJS_DEFINE_CLASS_GETTER ({gumjs_function_prefix}_get_eob, {wrapper_struct_name})
{{
if (!{wrapper_function_prefix}_check (self, isolate))
return;
info.GetReturnValue ().Set (!!{impl_function_prefix}_eob (self->impl));
}}
GUMJS_DEFINE_CLASS_GETTER ({gumjs_function_prefix}_get_eoi, {wrapper_struct_name})
{{
if (!{wrapper_function_prefix}_check (self, isolate))
return;
info.GetReturnValue ().Set (!!{impl_function_prefix}_eoi (self->impl));
}}
static const GumV8Property {gumjs_function_prefix}_values[] =
{{
{{ "input", {gumjs_function_prefix}_get_input, NULL }},
{{ "eob", {gumjs_function_prefix}_get_eob, NULL }},
{{ "eoi", {gumjs_function_prefix}_get_eoi, NULL }},
{{ NULL, NULL, NULL }}
}};
"""
if component.flavor == "x86":
target = "GSIZE_TO_POINTER (self->input->insn->address)"
else:
target = "self->impl->input_start + (self->input->insn->address - (self->impl->input_pc - self->impl->inpos))"
if component.flavor == "thumb":
target = "GSIZE_TO_POINTER (GPOINTER_TO_SIZE ({0}) | 1)".format(target)
params = {
"writer_impl_struct_name": to_camel_case('gum_{0}_writer'.format(component.flavor), start_high=True),
"get_input_target_expression": target,
}
params.update(component.__dict__)
return template.format(**params).split("\n")
def generate_v8_enum_parser(name, type, prefix, values):
common_decls, common_code = generate_enum_parser(name, type, prefix, values)
params = {
'name': name,
'description': name.replace("_", " "),
'type': type,
}
decls = [
"static gboolean gum_parse_{name} (Isolate * isolate, const std::string & name, {type} * value);".format(**params)
] + common_decls
code = """\
static gboolean
gum_parse_{name} (
Isolate * isolate,
const std::string & name,
{type} * value)
{{
if (!gum_try_parse_{name} (name.c_str (), value))
{{
_gum_v8_throw_literal (isolate, "invalid {description}");
return FALSE;
}}
return TRUE;
}}
""".format(**params).split("\n") + common_code
return (decls, code)
arch_names = {
"x86": "x86",
"arm": "ARM",
"arm64": "AArch64",
"mips": "MIPS",
}
writer_enums = {
"x86": [
("x86_register", "GumCpuReg", "GUM_REG_", [
"xax", "xcx", "xdx", "xbx", "xsp", "xbp", "xsi", "xdi",
"eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi",
"rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi",
"r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15",
"r8d", "r9d", "r10d", "r11d", "r12d", "r13d", "r14d", "r15d",
"xip", "eip", "rip",
]),
("x86_instruction_id", "x86_insn", "X86_INS_", [
"jo", "jno", "jb", "jae", "je", "jne", "jbe", "ja", "js", "jns",
"jp", "jnp", "jl", "jge", "jle", "jg", "jcxz", "jecxz", "jrcxz",
]),
("x86_branch_hint", "GumBranchHint", "GUM_", [
"no-hint", "likely", "unlikely",
]),
("x86_pointer_target", "GumPtrTarget", "GUM_PTR_", [
"byte", "dword", "qword",
]),
],
"arm": [
("arm_register", "arm_reg", "ARM_REG_", [
"r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7",
"r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15",
"sp", "lr", "sb", "sl", "fp", "ip", "pc",
]),
("arm_system_register", "arm_sysreg", "ARM_SYSREG_", [
"apsr-nzcvq",
]),
("arm_condition_code", "arm_cc", "ARM_CC_", [
"eq", "ne", "hs", "lo", "mi", "pl", "vs", "vc",
"hi", "ls", "ge", "lt", "gt", "le", "al",
]),
("arm_shifter", "arm_shifter", "ARM_SFT_", [
"asr", "lsl", "lsr", "ror", "rrx", "asr-reg", "lsl-reg", "lsr-reg",
"ror-reg", "rrx-reg",
]),
],
"thumb": [],
"arm64": [
("arm64_register", "arm64_reg", "ARM64_REG_", [
"x0", "x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8", "x9",
"x10", "x11", "x12", "x13", "x14", "x15", "x16", "x17", "x18", "x19",
"x20", "x21", "x22", "x23", "x24", "x25", "x26", "x27", "x28", "x29",
"x30",
"w0", "w1", "w2", "w3", "w4", "w5", "w6", "w7", "w8", "w9",
"w10", "w11", "w12", "w13", "w14", "w15", "w16", "w17", "w18", "w19",
"w20", "w21", "w22", "w23", "w24", "w25", "w26", "w27", "w28", "w29",
"w30",
"sp", "lr", "fp",
"wsp", "wzr", "xzr", "nzcv", "ip0", "ip1",
"s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7", "s8", "s9",
"s10", "s11", "s12", "s13", "s14", "s15", "s16", "s17", "s18", "s19",
"s20", "s21", "s22", "s23", "s24", "s25", "s26", "s27", "s28", "s29",
"s30", "s31",
"d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9",
"d10", "d11", "d12", "d13", "d14", "d15", "d16", "d17", "d18", "d19",
"d20", "d21", "d22", "d23", "d24", "d25", "d26", "d27", "d28", "d29",
"d30", "d31",
"q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9",
"q10", "q11", "q12", "q13", "q14", "q15", "q16", "q17", "q18", "q19",
"q20", "q21", "q22", "q23", "q24", "q25", "q26", "q27", "q28", "q29",
"q30", "q31",
]),
("arm64_condition_code", "arm64_cc", "ARM64_CC_", [
"eq", "ne", "hs", "lo", "mi", "pl", "vs", "vc",
"hi", "ls", "ge", "lt", "gt", "le", "al", "nv",
]),
("arm64_index_mode", "GumArm64IndexMode", "GUM_INDEX_", [
"post-adjust", "signed-offset", "pre-adjust",
]),
],
"mips": [
("mips_register", "mips_reg", "MIPS_REG_", [
"v0", "v1", "a0", "a1", "a2", "a3",
"t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7",
"s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7",
"t8", "t9",
"k0", "k1",
"gp", "sp", "fp", "s8", "ra",
"hi", "lo", "zero", "at",
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
"10", "11", "12", "13", "14", "15", "16", "17", "18", "19",
"20", "21", "22", "23", "24", "25", "26", "27", "28", "29",
"30", "31",
]),
],
}
def generate_conversion_methods(component, generate_parser):
decls = []
code = []
if component.name == "writer":
for enum in writer_enums[component.flavor]:
d, c = generate_parser(*enum)
decls += d
code += c
return (decls, code)
def generate_enum_parser(name, type, prefix, values):
decls = [
"static gboolean gum_try_parse_{name} (const gchar * name, {type} * value);".format(name=name, type=type)
]
statements = []
for i, value in enumerate(values):
statements.extend([
"{0}if (strcmp (name, \"{1}\") == 0)".format(" else " if i > 0 else "", value),
" *value = {0}{1};".format(prefix, value.upper().replace("-", "_")),
])
code = """\
static gboolean
gum_try_parse_{name} (
const gchar * name,
{type} * value)
{{
{statements}
else
return FALSE;
return TRUE;
}}
""".format(
name=name,
type=type,
statements="\n".join(statements),
)
return (decls, code.split("\n"))
def generate_tsds(name, arch, flavor, api):
tsds = {}
tsds.update(generate_class_type_definitions(name, arch, flavor, api))
tsds.update(generate_enum_type_definitions(name, arch, flavor, api))
return tsds
def generate_class_type_definitions(name, arch, flavor, api):
lines = []
class_name = to_camel_case("{0}_{1}".format(flavor, name), start_high=True)
writer_class_name = to_camel_case("{0}_writer".format(flavor, "writer"), start_high=True)
params = {
"arch": arch,
"arch_name": arch_names[arch],
"arch_namespace": arch.title(),
"class_name": class_name,
"writer_class_name": writer_class_name,
}
if name == "writer":
class_description = "Generates machine code for {0}.".format(arch)
else:
class_description = "Relocates machine code for {0}.".format(arch)
lines.extend([
"/**",
" * " + class_description,
" */",
"declare class {0} {{".format(class_name),
])
if name == "writer":
lines.extend("""\
/**
* Creates a new code writer for generating {arch_name} machine code
* written directly to memory at `codeAddress`.
*
* @param codeAddress Memory address to write generated code to.
* @param options Options for customizing code generation.
*/
constructor(codeAddress: NativePointerValue, options?: {class_name}Options);
/**
* Recycles instance.
*/
reset(codeAddress: NativePointerValue, options?: {class_name}Options): void;
/**
* Eagerly cleans up memory.
*/
dispose(): void;
/**
* Resolves label references and writes pending data to memory. You
* should always call this once you've finished generating code. It
* is usually also desirable to do this between pieces of unrelated
* code, e.g. when generating multiple functions in one go.
*/
flush(): void;
/**
* Memory location of the first byte of output.
*/
base: NativePointer;
/**
* Memory location of the next byte of output.
*/
code: NativePointer;
/**
* Program counter at the next byte of output.
*/
pc: NativePointer;
/**
* Current offset in bytes.
*/
offset: number;""".format(**params).split("\n"))
elif name == "relocator":
lines.extend("""\
/**
* Creates a new code relocator for copying {arch_name} instructions
* from one memory location to another, taking care to adjust
* position-dependent instructions accordingly.
*
* @param inputCode Source address to copy instructions from.
* @param output {writer_class_name} pointed at the desired target memory
* address.
*/
constructor(inputCode: NativePointerValue, output: {writer_class_name});
/**
* Recycles instance.
*/
reset(inputCode: NativePointerValue, output: {writer_class_name}): void;
/**
* Eagerly cleans up memory.
*/
dispose(): void;
/**
* Latest `Instruction` read so far. Starts out `null` and changes
* on every call to `readOne()`.
*/
input: Instruction | null;
/**
* Indicates whether end-of-block has been reached, i.e. we've
* reached a branch of any kind, like CALL, JMP, BL, RET.
*/
eob: boolean;
/**
* Indicates whether end-of-input has been reached, e.g. we've
* reached JMP/B/RET, an instruction after which there may or may
* not be valid code.
*/
eoi: boolean;
/**
* Reads the next instruction into the relocator's internal buffer
* and returns the number of bytes read so far, including previous
* calls.
*
* You may keep calling this method to keep buffering, or immediately
* call either `writeOne()` or `skipOne()`. Or, you can buffer up
* until the desired point and then call `writeAll()`.
*
* Returns zero when end-of-input is reached, which means the `eoi`
* property is now `true`.
*/
readOne(): number;""".format(**params).split("\n"))
for method in api.instance_methods:
arg_names = [arg.name_js for arg in method.args]
description = ""
if method.name.startswith("put_"):
if method.name == "put_label":
description = """Puts a label at the current position, where `id` is an identifier
* that may be referenced in past and future `put*Label()` calls"""
elif method.name.startswith("put_call") and "_with_arguments" in method.name:
description = """Puts code needed for calling a C function with the specified `args`"""
arg_names[-1] = "args"
elif method.name.startswith("put_call") and "_with_aligned_arguments" in method.name:
description = """Like `putCallWithArguments()`, but also
* ensures that the argument list is aligned on a 16 byte boundary"""
arg_names[-1] = "args"
elif method.name == "put_branch_address":
description = "Puts code needed for branching/jumping to the given address"
elif method.name in ("put_push_regs", "put_pop_regs"):
if method.name.startswith("put_push_"):
mnemonic = "PUSH"
else:
mnemonic = "POP"
description = """Puts a {mnemonic} instruction with the specified registers""".format(mnemonic=mnemonic)
arg_names[-1] = "regs"
elif method.name == "put_push_all_x_registers":
description = """Puts code needed for pushing all X registers on the stack"""
elif method.name == "put_push_all_q_registers":
description = """Puts code needed for pushing all Q registers on the stack"""
elif method.name == "put_pop_all_x_registers":
description = """Puts code needed for popping all X registers off the stack"""
elif method.name == "put_pop_all_q_registers":
description = """Puts code needed for popping all Q registers off the stack"""
elif method.name == "put_prologue_trampoline":
description = "Puts a minimal sized trampoline for vectoring to the given address"
elif method.name == "put_ldr_reg_ref":
description = """Puts an LDR instruction with a dangling data reference,
* returning an opaque ref value that should be passed to `putLdrRegValue()`
* at the desired location"""
elif method.name == "put_ldr_reg_value":
description = """Puts the value and updates the LDR instruction
* from a previous `putLdrRegRef()`"""
elif method.name == "put_breakpoint":
description = "Puts an OS/architecture-specific breakpoint instruction"
elif method.name == "put_padding":
description = "Puts `n` guard instruction"
elif method.name == "put_nop_padding":
description = "Puts `n` NOP instructions"
elif method.name == "put_instruction":
description = "Puts a raw instruction"
elif method.name == "put_instruction_wide":
description = "Puts a raw Thumb-2 instruction"
elif method.name == "put_u8":
description = "Puts a uint8"
elif method.name == "put_s8":
description = "Puts an int8"
elif method.name == "put_bytes":
description = "Puts raw data"
elif method.name.endswith("no_auth"):
opcode = method.name.split("_")[1].upper()
description = """Puts {0} instruction expecting a raw pointer without
* any authentication bits""".format(make_indefinite(opcode))
else:
types = set(["reg", "imm", "offset", "indirect", "short", "near", "ptr", "base", "index", "scale", "address", "label", "u8", "i32", "u32", "u64"])
opcode = " ".join(filter(lambda token: token not in types, method.name.split("_")[1:])).upper()
description = "Puts {0} instruction".format(make_indefinite(opcode))
if method.name.endswith("_label"):
description += """ referencing `labelId`, defined by a past
* or future `putLabel()`"""
elif method.name == "skip":
description = "Skips `nBytes`"
elif method.name == "peek_next_write_insn":
description = "Peeks at the next `Instruction` to be written or skipped".format(**params)
elif method.name == "peek_next_write_source":
description = "Peeks at the address of the next instruction to be written or skipped"
elif method.name.startswith("skip_one"):
description = "Skips the instruction that would have been written next"
if method.name.endswith("_no_label"):
description += """,
* but without a label for internal use. This breaks relocation of branches to
* locations inside the relocated range, and is an optimization for use-cases
* where all branches are rewritten (e.g. Frida's Stalker)"""
elif method.name.startswith("write_one"):
description = "Writes the next buffered instruction"
if method.name.endswith("_no_label"):
description += """, but without a
* label for internal use. This breaks relocation of branches to locations
* inside the relocated range, and is an optimization for use-cases where all
* branches are rewritten (e.g. Frida's Stalker)"""
elif method.name == "copy_one":
description = """Copies out the next buffered instruction without advancing the
* output cursor, allowing the same instruction to be written out
* multiple times"""
elif method.name.startswith("write_all"):
description = "Writes all buffered instructions"
elif method.name == "can_branch_directly_between":
description = """Determines whether a direct branch is possible between the two
* given memory locations"""
elif method.name == "commit_label":
description = """Commits the first pending reference to the given label, returning
* `true` on success. Returns `false` if the given label hasn't been
* defined yet, or there are no more pending references to it"""
elif method.name == "sign":
description = "Signs the given pointer value"
p = {}
p.update(params)
p.update({
"method_name": method.name_js,
"method_arglist": ", ".join([n + ": " + t for n, t in zip(arg_names, [arg.type_ts for arg in method.args])]),
"method_return_type": method.return_type_ts,
"method_description": description,
})
lines.extend("""\
/**
* {method_description}.
*/
{method_name}({method_arglist}): {method_return_type};""".format(**p).split("\n"))
lines.append("}")
if name == "writer":
lines.extend("""
interface {class_name}Options {{
/**
* Specifies the initial program counter, which is useful when
* generating code to a scratch buffer. This is essential when using
* `Memory.patchCode()` on iOS, which may provide you with a
* temporary location that later gets mapped into memory at the
* intended memory location.
*/
pc?: NativePointer;
}}""".format(**params).split("\n"))
if flavor != "thumb":
lines.extend([
"",
"type {arch_namespace}CallArgument = {arch_namespace}Register | number | UInt64 | Int64 | NativePointerValue;".format(**params),
])
return {
"{0}-{1}.d.ts".format(flavor, name): "\n".join(lines),
}
def generate_enum_type_definitions(name, arch, flavor, api):
lines = []
for name, type, prefix, values in writer_enums[arch]:
name_ts = to_camel_case(name, start_high=True)
name_components = name.replace("_", " ").title().split(" ")
if len(lines) > 0:
lines.append("")
values_ts = " | ".join(["\"{0}\"".format(val) for val in values])
raw_decl = "type {0} = {1};".format(name_ts, values_ts)
lines.extend(reflow_enum_declaration(raw_decl))
return {
"{0}-enums.d.ts".format(arch): "\n".join(lines),
}
def reflow_enum_declaration(decl):
if len(decl.split(" | ")) <= 3:
return [decl]
first_line, rest = decl.split(" = ", 1)
values = rest.rstrip(";").split(" | ")
return [first_line + " ="] + [" | {0}".format(val) for val in values] + [" ;"]
def generate_docs(name, arch, flavor, api):
docs = {}
docs.update(generate_class_api_reference(name, arch, flavor, api))
docs.update(generate_enum_api_reference(name, arch, flavor, api))
return docs
def generate_class_api_reference(name, arch, flavor, api):
lines = []
class_name = to_camel_case("{0}_{1}".format(flavor, name), start_high=True)
writer_class_name = to_camel_case("{0}_writer".format(flavor, "writer"), start_high=True)
params = {
"arch": arch,
"arch_name": arch_names[arch],
"class_name": class_name,
"writer_class_name": writer_class_name,
"writer_class_link_indefinite": "{0} [{1}](#{2})".format(
make_indefinite_qualifier(writer_class_name),
writer_class_name,
writer_class_name.lower()),
"instruction_link": "[Instruction](#instruction)",
}
lines.extend([
"## {0}".format(class_name),
"",
])
if name == "writer":
lines.extend("""\
+ `new {class_name}(codeAddress[, {{ pc: ptr('0x1234') }}])`: create a new code
writer for generating {arch_name} machine code written directly to memory at
`codeAddress`, specified as a NativePointer.
The second argument is an optional options object where the initial program
counter may be specified, which is useful when generating code to a scratch
buffer. This is essential when using `Memory.patchCode()` on iOS, which may
provide you with a temporary location that later gets mapped into memory at
the intended memory location.
- `reset(codeAddress[, {{ pc: ptr('0x1234') }}])`: recycle instance
- `dispose()`: eagerly clean up memory
- `flush()`: resolve label references and write pending data to memory. You
should always call this once you've finished generating code. It is usually
also desirable to do this between pieces of unrelated code, e.g. when
generating multiple functions in one go.
- `base`: memory location of the first byte of output, as a NativePointer
- `code`: memory location of the next byte of output, as a NativePointer
- `pc`: program counter at the next byte of output, as a NativePointer
- `offset`: current offset as a JavaScript Number
""".format(**params).split("\n"))
elif name == "relocator":
lines.extend("""\
+ `new {class_name}(inputCode, output)`: create a new code relocator for
copying {arch_name} instructions from one memory location to another, taking
care to adjust position-dependent instructions accordingly.
The source address is specified by `inputCode`, a NativePointer.
The destination is given by `output`, {writer_class_link_indefinite} pointed
at the desired target memory address.
- `reset(inputCode, output)`: recycle instance
- `dispose()`: eagerly clean up memory
- `input`: latest {instruction_link} read so far. Starts out `null`
and changes on every call to `readOne()`.
- `eob`: boolean indicating whether end-of-block has been reached, i.e. we've
reached a branch of any kind, like CALL, JMP, BL, RET.
- `eoi`: boolean indicating whether end-of-input has been reached, e.g. we've
reached JMP/B/RET, an instruction after which there may or may not be valid
code.
- `readOne()`: read the next instruction into the relocator's internal buffer
and return the number of bytes read so far, including previous calls.
You may keep calling this method to keep buffering, or immediately call
either `writeOne()` or `skipOne()`. Or, you can buffer up until the desired
point and then call `writeAll()`.
Returns zero when end-of-input is reached, which means the `eoi` property is
now `true`.
""".format(**params).split("\n"))
for method in api.instance_methods:
arg_names = [arg.name_js for arg in method.args]
description = ""
if method.name.startswith("put_"):
if method.name == "put_label":
description = """put a label at the current position, where `id` is a string
that may be referenced in past and future `put*Label()` calls"""
elif method.name.startswith("put_call") and "_with_arguments" in method.name:
description = """put code needed for calling a C
function with the specified `args`, specified as a JavaScript array where
each element is either a string specifying the register, or a Number or
NativePointer specifying the immediate value."""
arg_names[-1] = "args"
elif method.name.startswith("put_call") and "_with_aligned_arguments" in method.name:
description = """like above, but also
ensures that the argument list is aligned on a 16 byte boundary"""
arg_names[-1] = "args"
elif method.name == "put_branch_address":
description = """put code needed for branching/jumping to the
given address"""
elif method.name in ("put_push_regs", "put_pop_regs"):
if method.name.startswith("put_push_"):
mnemonic = "PUSH"
else:
mnemonic = "POP"
description = """put a {mnemonic} instruction with the specified registers,
specified as a JavaScript array where each element is a string specifying
the register name.""".format(mnemonic=mnemonic)
arg_names[-1] = "regs"
elif method.name == "put_push_all_x_registers":
description = """put code needed for pushing all X registers on the stack"""
elif method.name == "put_push_all_q_registers":
description = """put code needed for pushing all Q registers on the stack"""
elif method.name == "put_pop_all_x_registers":
description = """put code needed for popping all X registers off the stack"""
elif method.name == "put_pop_all_q_registers":
description = """put code needed for popping all Q registers off the stack"""
elif method.name == "put_prologue_trampoline":
description = """put a minimal sized trampoline for
vectoring to the given address"""
elif method.name == "put_ldr_reg_ref":
description = """put an LDR instruction with a dangling data reference,
returning an opaque ref value that should be passed to `putLdrRegValue()`
at the desired location"""
elif method.name == "put_ldr_reg_value":
description = """put the value and update the LDR instruction
from a previous `putLdrRegRef()`"""
elif method.name == "put_breakpoint":
description = "put an OS/architecture-specific breakpoint instruction"
elif method.name == "put_padding":
description = "put `n` guard instruction"
elif method.name == "put_nop_padding":
description = "put `n` NOP instructions"
elif method.name == "put_instruction":
description = "put a raw instruction as a JavaScript Number"
elif method.name == "put_instruction_wide":
description = "put a raw Thumb-2 instruction from\n two JavaScript Number values"
elif method.name == "put_u8":
description = "put a uint8"
elif method.name == "put_s8":
description = "put an int8"
elif method.name == "put_bytes":
description = "put raw data from the provided ArrayBuffer"
elif method.name.endswith("no_auth"):
opcode = method.name.split("_")[1].upper()
description = """put {0} instruction expecting a raw pointer
without any authentication bits""".format(make_indefinite(opcode))
else:
types = set(["reg", "imm", "offset", "indirect", "short", "near", "ptr", "base", "index", "scale", "address", "label", "u8", "i32", "u32", "u64"])
opcode = " ".join(filter(lambda token: token not in types, method.name.split("_")[1:])).upper()
description = "put {0} instruction".format(make_indefinite(opcode))
if method.name.endswith("_label"):
description += """
referencing `labelId`, defined by a past or future `putLabel()`"""
elif method.name == "skip":
description = "skip `nBytes`"
elif method.name == "peek_next_write_insn":
description = "peek at the next {instruction_link} to be\n written or skipped".format(**params)
elif method.name == "peek_next_write_source":
description = "peek at the address of the next instruction to be\n written or skipped"
elif method.name.startswith("skip_one"):
description = "skip the instruction that would have been written next"
if method.name.endswith("_no_label"):
description += """,
but without a label for internal use. This breaks relocation of branches to
locations inside the relocated range, and is an optimization for use-cases
where all branches are rewritten (e.g. Frida's Stalker)."""
elif method.name.startswith("write_one"):
description = "write the next buffered instruction"
if method.name.endswith("_no_label"):
description += """, but without a
label for internal use. This breaks relocation of branches to locations
inside the relocated range, and is an optimization for use-cases where all
branches are rewritten (e.g. Frida's Stalker)."""
elif method.name == "copy_one":
description = """copy out the next buffered instruction without advancing the
output cursor, allowing the same instruction to be written out multiple
times"""
elif method.name.startswith("write_all"):
description = "write all buffered instructions"
elif method.name == "can_branch_directly_between":
description = """determine whether a direct branch is
possible between the two given memory locations"""
elif method.name == "commit_label":
description = """commit the first pending reference to the given label,
returning `true` on success. Returns `false` if the given label hasn't been
defined yet, or there are no more pending references to it."""
elif method.name == "sign":
description = "sign the given pointer value"
p = {}
p.update(params)
p.update({
"method_name": method.name_js,
"method_arglist": ", ".join(arg_names),
"method_description": description,
})
lines.extend("""\
- `{method_name}({method_arglist})`: {method_description}
""".format(**p).split("\n"))
return {
"{0}-{1}.md".format(flavor, name): "\n".join(lines),
}
def generate_enum_api_reference(name, arch, flavor, api):
lines = [
"## {0} enum types".format(arch_names[arch]),
"",
]
for name, type, prefix, values in writer_enums[arch]:
display_name = to_camel_case("_".join(name.split("_")[1:]), start_high=True)
lines.extend(reflow_enum_bulletpoint("- {0}: `{1}`".format(display_name, "` `".join(values))))
lines.append("")
return {
"{0}-enums.md".format(arch): "\n".join(lines),
}
def reflow_enum_bulletpoint(bulletpoint):
result = [bulletpoint]
indent = 3 * " "
while True:
last_line = result[-1]
if len(last_line) < 80:
break
cutoff_index = last_line.rindex("` `", 0, 81) + 1
before = last_line[:cutoff_index]
after = indent + last_line[cutoff_index:]
result[-1] = before
result.append(after)
return result
def make_indefinite(noun):
return make_indefinite_qualifier(noun) + " " + noun
def make_indefinite_qualifier(noun):
noun_lc = noun.lower()
exceptions = [
"ld",
"lf",
"rd",
"x",
]
for prefix in exceptions:
if noun_lc.startswith(prefix):
return "an"
return "an" if noun_lc[0] in ("a", "e", "i", "o", "u") else "a"
class Component(object):
def __init__(self, name, arch, flavor, namespace):
self.name = name
self.arch = arch
self.flavor = flavor
self.wrapper_struct_name = to_camel_case("gum_{0}_{1}_{2}".format(namespace, flavor, name), start_high=True)
self.wrapper_function_prefix = "gum_{0}_{1}_{2}".format(namespace, flavor, name)
self.impl_struct_name = to_camel_case("gum_{0}_{1}".format(flavor, name), start_high=True)
self.impl_function_prefix = "gum_{0}_{1}".format(flavor, name)
self.gumjs_class_name = flavor.title() + name.title()
self.gumjs_field_prefix = "{0}_{1}".format(flavor, name)
self.gumjs_function_prefix = "gumjs_{0}_{1}".format(flavor, name)
self.module_struct_name = to_camel_case("gum_{0}_code_{1}".format(namespace, name), start_high=True)
self.register_type = "GumCpuReg" if arch == "x86" else arch + "_reg"
class Api(object):
def __init__(self, static_methods, instance_methods):
self.static_methods = static_methods
self.instance_methods = instance_methods
native_register_type = None
for method in instance_methods:
reg_types = [arg.type for arg in method.args if arg.type_converter == "register"]
if len(reg_types) > 0:
native_register_type = reg_types[0]
break
self.native_register_type = native_register_type
class Method(object):
def __init__(self, name, return_type, args):
is_put_array = name.startswith("put_") and name.endswith("_array")
if is_put_array:
name = name[:-6]
is_put_call = is_put_array and name.startswith("put_call_")
is_put_regs = is_put_array and "_regs" in name
self.name = name
self.name_js = to_camel_case(name, start_high=False)
self.is_put_array = is_put_array
if is_put_array:
args.pop(len(args) - 2)
self.is_put_call = is_put_call
if is_put_call:
self.needs_calling_convention_arg = args[0].type == "GumCallingConvention"
if self.needs_calling_convention_arg:
args.pop(0)
else:
self.needs_calling_convention_arg = False
self.is_put_regs = is_put_regs
self.return_type = return_type
if return_type == "void" or (return_type == "gboolean" and name.startswith("put_")):
self.return_type_ts = "void"
elif return_type == "gboolean":
self.return_type_ts = "boolean"
elif return_type == "guint":
self.return_type_ts = "number"
elif return_type in ("gpointer", "GumAddress"):
self.return_type_ts = "NativePointer"
elif return_type == "cs_insn *":
self.return_type_ts = "Instruction | null"
else:
raise ValueError("Unsupported return type: {0}".format(return_type))
self.args = args
class MethodArgument(object):
def __init__(self, type, name, arch):
self.type = type
name_raw = None
converter = None
if type in ("GumCpuReg", "arm_reg", "arm64_reg", "mips_reg"):
self.type_raw = "const gchar *"
self.type_format = "s"
self.type_ts = to_camel_case("x86_register" if type == "GumCpuReg" else type.replace("_reg", "_register"), start_high=True)
converter = "register"
elif type in ("arm_sysreg",):
self.type_raw = "const gchar *"
self.type_format = "s"
self.type_ts = "ArmSystemRegister"
converter = "system_register"
elif type in ("gint", "gint8", "gint16", "gint32"):
self.type_raw = "gint"
self.type_format = "i"
self.type_ts = "number"
elif type in ("guint", "guint8", "guint16", "guint32"):
self.type_raw = "guint"
self.type_format = "u"
self.type_ts = "number"
elif type == "gint64":
self.type_raw = type
self.type_format = "q"
self.type_ts = "number | Int64"
elif type == "guint64":
self.type_raw = type
self.type_format = "Q"
self.type_ts = "number | UInt64"
elif type == "gssize":
self.type_raw = type
self.type_format = "z"
self.type_ts = "number | Int64 | UInt64"
elif type == "gsize":
self.type_raw = type
self.type_format = "Z"
self.type_ts = "number | Int64 | UInt64"
elif type in ("gpointer", "gconstpointer", "gconstpointer *"):
self.type_raw = type
self.type_format = "p"
self.type_ts = "NativePointerValue"
elif type == "GumAddress":
self.type_raw = "gpointer"
self.type_format = "p"
self.type_ts = "NativePointerValue"
converter = "address"
elif type == "$label":
self.type_raw = "const gchar *"
self.type_format = "s"
self.type_ts = "string"
converter = "label"
elif type == "$array":
self.type_raw = "GBytes *"
self.type_format = "B~"
self.type_ts = "ArrayBuffer | number[] | string"
converter = "bytes"
elif type == "x86_insn":
self.type_raw = "const gchar *"
self.type_format = "s"
self.type_ts = "X86InstructionId"
converter = "instruction_id"
elif type == "GumCallingConvention":
self.type_raw = "const gchar *"
self.type_format = "s"
self.type_ts = "CallingConvention"
converter = "calling_convention"
elif type in ("const GumArgument *", "const arm_reg *"):
self.type_raw = "$array"
self.type_format = "A"
if type == "const GumArgument *":
self.type_ts = arch.title() + "CallArgument[]"
else:
self.type_ts = "ArmRegister[]"
name = "items"
name_raw = "items_value"
elif type == "GumBranchHint":
self.type_raw = "const gchar *"
self.type_format = "s"
self.type_ts = "X86BranchHint"
converter = "branch_hint"
elif type == "GumPtrTarget":
self.type_raw = "const gchar *"
self.type_format = "s"
self.type_ts = "X86PointerTarget"
converter = "pointer_target"
elif type in ("arm_cc", "arm64_cc"):
self.type_raw = "const gchar *"
self.type_format = "s"
self.type_ts = "ArmConditionCode" if type == "arm_cc" else "Arm64ConditionCode"
converter = "condition_code"
elif type == "arm_shifter":
self.type_raw = "const gchar *"
self.type_format = "s"
self.type_ts = "ArmShifter"
converter = "shifter"
elif type == "GumArm64IndexMode":
self.type_raw = "const gchar *"
self.type_format = "s"
self.type_ts = "Arm64IndexMode"
converter = "index_mode"
elif type == "GumRelocationScenario":
self.type_raw = "const gchar *"
self.type_format = "s"
self.type_ts = "RelocationScenario"
converter = "relocator_scenario"
else:
raise ValueError("Unhandled type: {0}".format(type))
self.type_converter = converter
if name_raw is None:
name_raw = name if converter is None else "raw_{0}".format(name)
self.name = name
self.name_js = to_camel_case(name, start_high=False)
self.name_raw = name_raw
def name_raw_for_cpp(self):
if self.type == "$label":
return "raw_{0}".format(self.name)
return self.name_raw
def type_raw_for_cpp(self):
if self.type_format == "s":
return "std::string"
return self.type_raw
def type_format_for_cpp(self):
if self.type_format == "s":
return "S"
return self.type_format
def type_converter_for_cpp(self):
if self.type == "$label":
return "label"
return self.type_converter
def parse_api(name, arch, flavor, api_header, options):
static_methods = []
instance_methods = []
self_type = "{0} * ".format(to_camel_case("gum_{0}_{1}".format(flavor, name), start_high=True))
ignored_methods = set(options.get('ignore', []))
put_methods = [(m.group(2), m.group(1), m.group(3)) for m in re.finditer(r"GUM_API ([\w *]+) gum_{0}_{1}_([\w]+) \(([^)]+)\);".format(flavor, name), api_header)]
for method_name, return_type, raw_arglist in put_methods:
if method_name in ignored_methods:
continue
raw_args = [raw_arg.strip() for raw_arg in raw_arglist.replace("\n", " ").split(", ")]
if raw_args[-1] == "...":
continue
is_static = not raw_args[0].startswith(self_type)
if not is_static:
raw_args = raw_args[1:]
if not is_static and method_name == "put_bytes":
args = [MethodArgument("$array", "data", arch)]
else:
args = [parse_arg(raw_arg, arch) for raw_arg in raw_args]
method = Method(method_name, return_type, args)
if is_static:
static_methods.append(method)
else:
instance_methods.append(method)
return Api(static_methods, instance_methods)
def parse_arg(raw_arg, arch):
tokens = raw_arg.split(" ")
raw_type = " ".join(tokens[0:-1])
name = tokens[-1]
if raw_type == "gconstpointer":
if name in ("id", "label_id"):
return MethodArgument("$label", name, arch)
return MethodArgument(raw_type, name, arch)
return MethodArgument(raw_type, name, arch)
def to_camel_case(name, start_high):
result = ""
uppercase_next = start_high
for c in name:
if c == "_":
uppercase_next = True
elif uppercase_next:
result += c.upper()
uppercase_next = False
else:
result += c.lower()
return result
if __name__ == '__main__':
source_dir = sys.argv[1]
output_dir = sys.argv[2]
generate_and_write_bindings(source_dir, output_dir)
|
#!/usr/bin/env python3
# Useful for importing any python modules I have in the "modules" directory.
# http://stackoverflow.com/a/35259170/2752888
import os
import sys
sys.path.append(os.path.join(os.path.dirname(sys.path[0]),'modules'))
import random_alleles as ra
from zk_utils import *
import argparse
import inspect
parser = argparse.ArgumentParser(
formatter_class = argparse.ArgumentDefaultsHelpFormatter,
fromfile_prefix_chars = '@'
)
parser.convert_arg_line_to_args = convert_arg_line_to_args
parser.add_argument(
"--murate",
type = float,
nargs = "+",
help = "mutation rate per locus",
default = [1e-05]*10
)
parser.add_argument(
"--popfile",
type = str,
help = "relative path to last saved simulation pop file."
)
# Setting up options
import simuOpt
simuOpt.setOptions(optimized = True,
gui = False,
debug = 'DBG_WARNING',
alleleType = 'long',
quiet = False,
numThreads = 0)
import simuPOP as sim
from simuPOP.utils import export
from simuPOP.utils import saveCSV
from simuPOP.sampling import drawRandomSample
from simuPOP.sampling import drawRandomSamples
'''
A wrapper to generate a mixed mating scheme with a rate of sexual reproduction.
Parameters:
sexrate a rate of sexual reproduction between 0 and 1
Output:
a simuPOP Mating scheme
Examples:
mix_mating(0.5)
'''
def mix_mating(sexrate):
# Mating Schemes
# ==========================================================================
# There are options here are things to do during mating:
# 1. Tag the parents (which fills mother_idx and father_idx)
# 2. Count the reproductive events
rand_mate = sim.RandomMating(
numOffspring=(sim.UNIFORM_DISTRIBUTION, 1, 3),
ops = [
# sim.Stat(numOfMales = True, popSize = True),
# sim.IfElse('numOfMales == popSize or numOfMales == 0',
# sim.CloneGenoTransmitter(),
# sim.MendelianGenoTransmitter()
# ),
sim.MendelianGenoTransmitter(),
sim.PedigreeTagger(infoFields=['mother_id', 'father_id']),
sim.PyTagger(update_sex_proj),
sim.IdTagger()
],
subPops = 0,
weight = sexrate
)
clone_mate = sim.HomoMating(
chooser = sim.RandomParentChooser(),
generator = sim.OffspringGenerator(
ops = [
sim.CloneGenoTransmitter(),
sim.PedigreeTagger(infoFields=['mother_id', 'father_id']),
sim.PyTagger(update_sex_proj)
],
numOffspring=(sim.UNIFORM_DISTRIBUTION, 1, 3)
),
subPops = 0,
weight = 1 - sexrate
)
return(sim.HeteroMating([rand_mate, clone_mate]))
# ==============================================================================
# MAIN PROGRAM
# ==============================================================================
if __name__ == '__main__':
pars = parser.parse_args()
infile = os.path.abspath(pars.popfile)
the_path = os.path.dirname(infile)
the_dataset = os.path.basename(infile)
a, seed, b, sex, c, gen, d, rep = the_dataset.split(".p")[0].split("_")
# seed_0_sex_0.0001_gen_10000_rep_06.pop
GENRATIONS = 10000 - int(gen)
sexrate = float(sex)
cwd = os.getcwd()
os.chdir(the_path)
pop = sim.loadPopulation(the_dataset)
sim.IdTagger().reset(1) # IdTagger must be reset before evolving.
nloc = sum(list(pop.numLoci()))
clonemate = sim.HomoMating(
chooser = sim.RandomParentChooser(),
generator = sim.OffspringGenerator(
ops = [
sim.CloneGenoTransmitter(),
sim.PedigreeTagger(infoFields=['mother_id', 'father_id']),
sim.PyTagger(update_sex_proj)
],
numOffspring = (sim.UNIFORM_DISTRIBUTION, 1, 3)
)
)
EVOL = dict()
STEPS = 1000
head, foot = r"'", r"\n'"
popsize = r"Pop Size: {}"
males = r"Males: {}"
generations = r"Gen: {:05d}"
# Joining the statistics together with pipes.
stats = " | ".join([head, popsize, males, generations, foot])
# Heterozygosity must be evaluate for each locus. This is a quick and dirty
# method of acheiving display of heterozygosity at each locus.
# locrange = map(str, range(nloc))
# lochet = '], heteroFreq['.join(locrange)
# The string for the evaluation of the stats.
# stateval = " % (popSize, numOfMales, heteroFreq["+lochet+"], gen, rep)"
# stateval = " % "
stateval = ".format("
stateval += "popSize, "
stateval += "numOfMales, "
stateval += "gen"
stateval += ")"
# Stat and PyEval are both classes, so they can be put into variables. These
# will be evaluated as the program runs.
statargs = sim.Stat(
popSize = True,
numOfMales = True,
step = STEPS
)
evalargs = sim.PyEval(stats + stateval, step = STEPS)
EVOL['postOps'] = [
statargs,
evalargs#,
# sim.PyOperator(func = reassign_parents, step = STEPS),
]
seedf = "seed_" + seed
sexf = "_sex_" + sex
sexseed = seedf + sexf
outfile = "!'"+ sexseed + "_gen_{:05d}_rep_"+rep+".pop'"
outfile = outfile + ".format(gen)"
EVOL['postOps'] += [sim.SavePopulation(output = outfile, step = STEPS)]
EVOL['finalOps'] = sim.SavePopulation(output = outfile)
GENERATIONS = 10000 - int(gen)
print(GENERATIONS)
EVOL['gen'] = GENERATIONS
preclone = [
sim.Stat(numOfMales = True, popSize = True),
sim.StepwiseMutator(rates = pars.murate, loci = range(nloc)),
sim.IdTagger(),
]
if sexrate == 0.0:
EVOL['matingScheme'] = clonemate
EVOL['preOps'] = preclone
else:
EVOL['matingScheme'] = mix_mating(sexrate)
EVOL['preOps'] = [
sim.Stat(numOfMales = True, popSize = True),
sim.TerminateIf('numOfMales == 0 or numOfMales == popSize'),
sim.StepwiseMutator(rates = pars.murate, loci = range(nloc)),
sim.IdTagger(),
]
res = pop.evolve(**EVOL)
if (res < GENERATIONS):
EVOL['matingScheme'] = clonemate
EVOL['preOps'] = preclone
EVOL['gen'] = GENERATIONS - res
pop.evolve(**EVOL)
os.chdir(cwd)
|
from django.utils.translation import gettext_lazy
try:
from pretix.base.plugins import PluginConfig
except ImportError:
raise RuntimeError("Please use pretix 2.7 or above to run this plugin!")
__version__ = "1.2.0"
class PluginApp(PluginConfig):
name = "pretix_cinesend"
verbose_name = "CineSend"
class PretixPluginMeta:
name = gettext_lazy("CineSend")
author = "pretix team"
description = gettext_lazy("Connects pretix to CineSend")
visible = True
version = __version__
category = "INTEGRATION"
compatibility = "pretix>=3.14.0"
def ready(self):
from . import signals, tasks # NOQA
default_app_config = "pretix_cinesend.PluginApp"
|
# -*- coding: utf-8 -*-
import unittest
import six
from xml.etree import ElementTree
if six.PY3:
from urllib.parse import parse_qs, urlparse
else:
from urlparse import parse_qs, urlparse
class AlipayTests(unittest.TestCase):
def Alipay(self, *a, **kw):
from alipay import Alipay
return Alipay(*a, **kw)
def WapAlipay(self, *a, **kw):
from alipay import WapAlipay
return WapAlipay(*a, **kw)
def setUp(self):
self.alipay = self.Alipay(pid='pid', key='key',
seller_email='[email protected]')
self.wapalipay = self.WapAlipay(pid='pid', key='key',
seller_email='[email protected]')
def test_create_direct_pay_by_user_url(self):
params = {'out_trade_no': '1',
'subject': 'test',
'price': '0.01',
'quantity': 1}
self.assertIn('create_direct_pay_by_user',
self.alipay.create_direct_pay_by_user_url(**params))
def test_create_direct_pay_by_user_url_with_unicode(self):
params = {'out_trade_no': '1',
'subject': u'测试',
'price': '0.01',
'quantity': 1}
self.assertIn('create_direct_pay_by_user',
self.alipay.create_direct_pay_by_user_url(**params))
def test_create_partner_trade_by_buyer_url(self):
params = {'out_trade_no': '1',
'subject': 'test',
'logistics_type': 'POST',
'logistics_fee': '0',
'logistics_payment': 'SELLER_PAY',
'price': '0.01',
'quantity': 1}
self.assertIn('create_partner_trade_by_buyer',
self.alipay.create_partner_trade_by_buyer_url(**params))
def test_create_batch_trans_notify_url(self):
batch_list = ({'account': '[email protected]',
'name': u'姓名',
'fee': '0.01',
'note': 'test'},
{'account': '[email protected]',
'name': u'姓名',
'fee': '0.01',
'note': 'test'})
params = {'batch_list': batch_list,
'account_name': 'test_name',
'batch_no': 'test_no',
'notify_url': 'www.test.com'}
self.assertIn('batch_trans_notify',
self.alipay.create_batch_trans_notify_url(**params))
def test_trade_create_by_buyer_url(self):
params = {'out_trade_no': '1',
'subject': 'test',
'logistics_type': 'POST',
'logistics_fee': '0',
'logistics_payment': 'SELLER_PAY',
'price': '0.01',
'quantity': 1}
self.assertIn('trade_create_by_buyer',
self.alipay.trade_create_by_buyer_url(**params))
def test_create_forex_trade_url(self):
params = {'out_trade_no': '1',
'subject': 'test',
'logistics_type': 'POST',
'logistics_fee': '0',
'logistics_payment': 'SELLER_PAY',
'price': '0.01',
'quantity': 1}
self.assertIn('create_forex_trade',
self.alipay.create_forex_trade_url(**params))
def test_create_forex_trade_wap_url(self):
params = {'out_trade_no': '1',
'subject': 'test',
'logistics_type': 'POST',
'logistics_fee': '0',
'logistics_payment': 'SELLER_PAY',
'price': '0.01',
'quantity': 1}
self.assertIn('create_forex_trade_wap',
self.alipay.create_forex_trade_wap_url(**params))
def test_send_goods_confirm_by_platform(self):
params = {
'trade_no': 1,
'logistics_name': 'XXXX',
'transport_type': 'EXPRESS',
'invoice_no': 'AAAAA'
}
self.assertIn('send_goods_confirm_by_platform',
self.alipay.send_goods_confirm_by_platform(**params))
def test_add_alipay_qrcode(self):
import json
params = {
'biz_data': json.dumps({
'goods_info': {
'id': '123456',
'name': u'测试',
'price': '0.01'
},
'need_address': 'F',
'trade_type': '1'
}, ensure_ascii=False),
'biz_type': '10'
}
self.assertIn('alipay.mobile.qrcode.manage',
self.alipay.add_alipay_qrcode_url(**params))
def test_raise_missing_parameter_in_create_direct_pay_by_user_url(self):
from .exceptions import MissingParameter
params = {'out_trade_no': '1',
'price': '0.01',
'quantity': 1}
self.assertRaises(MissingParameter,
self.alipay.create_direct_pay_by_user_url, **params)
def test_raise_parameter_value_error_in_create_direct_pay_by_user_url(self
):
from .exceptions import ParameterValueError
params = {'out_trade_no': '1',
'subject': 'test',
'quantity': 1}
self.assertRaises(ParameterValueError,
self.alipay.create_direct_pay_by_user_url,
**params)
def test_raise_parameter_value_error_when_initializing(self):
from .exceptions import ParameterValueError
self.assertRaises(ParameterValueError,
self.Alipay, pid='pid', key='key')
def test_create_wap_direct_pay_by_user_url(self):
params = {'out_trade_no': '1',
'subject': u'测试',
'total_fee': '0.01',
'seller_account_name': self.wapalipay.seller_email,
'call_back_url': 'http://mydomain.com/alipay/callback'}
url = self.wapalipay.create_direct_pay_token_url(**params)
self.assertIn('alipay.wap.trade.create.direct', url)
params = parse_qs(urlparse(url).query, keep_blank_values=True)
self.assertIn('req_data', params)
self.assertIn('sec_id', params)
tree = ElementTree.ElementTree(
ElementTree.fromstring(params['req_data'][0]))
self.assertEqual(self.wapalipay.TOKEN_ROOT_NODE, tree.getroot().tag)
def test_wap_notimplemented_pay(self):
params = {}
self.assertRaises(NotImplementedError,
self.wapalipay.trade_create_by_buyer_url, **params)
self.assertRaises(NotImplementedError,
self.wapalipay.create_partner_trade_by_buyer_url,
**params)
def test_wap_unauthorization_token(self):
from .exceptions import TokenAuthorizationError
params = {'out_trade_no': '1',
'subject': u'测试',
'total_fee': '0.01',
'seller_account_name': self.wapalipay.seller_email,
'call_back_url': 'http://mydomain.com/alipay/callback'}
self.assertRaises(TokenAuthorizationError,
self.wapalipay.create_direct_pay_by_user_url,
**params)
def test_wap_notifyurl(self):
'''valid MD5 sign
invalid notify id but should not throw any exception
sec_id=MD5&v=1.0¬ify_data=<notify><payment_type>1</payment_type><subject>测试</subject><trade_no>2014080239826696</trade_no><buyer_email>[email protected]</buyer_email><gmt_create>2014-08-02 14:49:13</gmt_create><notify_type>trade_status_sync</notify_type><quantity>1</quantity><out_trade_no>BD8Y9JQ2LT8MVXLMT34RTUWEMMBAXMIGBVQGF5CQNZHPYPQHSD4MEI56NQD2OLNV</out_trade_no><notify_time>2014-08-02 15:14:25</notify_time><seller_id>2088411445328172</seller_id><trade_status>TRADE_FINISHED</trade_status><is_total_fee_adjust>N</is_total_fee_adjust><total_fee>0.03</total_fee><gmt_payment>2014-08-02 14:49:27</gmt_payment><seller_email>[email protected]</seller_email><gmt_close>2014-08-02 14:49:27</gmt_close><price>0.03</price><buyer_id>2088002293077967</buyer_id><notify_id>6a40ac71fcf17d99b5274b0c6c8970ea7c</notify_id><use_coupon>N</use_coupon></notify>&service=alipay.wap.trade.create.direct&sign=1f0a524dc51ed5bfc7ee2bac62e39534
'''
params = {'sec_id': 'MD5', 'v': '1.0',
'notify_data': u'<notify><payment_type>1</payment_type><subject>测试</subject><trade_no>2014080239826696</trade_no><buyer_email>[email protected]</buyer_email><gmt_create>2014-08-02 14:49:13</gmt_create><notify_type>trade_status_sync</notify_type><quantity>1</quantity><out_trade_no>BD8Y9JQ2LT8MVXLMT34RTUWEMMBAXMIGBVQGF5CQNZHPYPQHSD4MEI56NQD2OLNV</out_trade_no><notify_time>2014-08-02 15:14:25</notify_time><seller_id>2088411445328172</seller_id><trade_status>TRADE_FINISHED</trade_status><is_total_fee_adjust>N</is_total_fee_adjust><total_fee>0.03</total_fee><gmt_payment>2014-08-02 14:49:27</gmt_payment><seller_email>[email protected]</seller_email><gmt_close>2014-08-02 14:49:27</gmt_close><price>0.03</price><buyer_id>2088002293077967</buyer_id><notify_id>6a40ac71fcf17d99b5274b0c6c8970ea7c</notify_id><use_coupon>N</use_coupon></notify>',
'service': 'alipay.wap.trade.create.direct',
'sign': '1f0a524dc51ed5bfc7ee2bac62e39534'}
rt = self.wapalipay.verify_notify(**params)
self.assertFalse(rt)
def test_single_trade_query(self):
''' single_trade_query will response a ILLEGAL_PARTNER error xml document, like:
<?xml version="1.0" encoding="utf-8"?>
<alipay><is_success>F</is_success><error>ILLEGAL_PARTNER</error></alipay>
'''
self.assertIn('ILLEGAL_PARTNER', self.alipay.single_trade_query(out_trade_no='2015102012')) |
class ChainException(Exception):
pass
class PeerNotFoundException(ChainException):
pass
|
from praw.models import MoreComments
from ... import IntegrationTest
class TestMore(IntegrationTest):
def setup(self):
super(TestMore, self).setup()
# Responses do not decode well on travis so manually renable gzip.
self.reddit._core._requestor._http.headers['Accept-Encoding'] = 'gzip'
def test_comments(self):
data = {'count': 9, 'name': 't1_cu5tt8h', 'id': 'cu5tt8h',
'parent_id': 't3_3hahrw', 'children': [
'cu5tt8h', 'cu5v9yd', 'cu5twf5', 'cu5tkk4', 'cu5tead',
'cu5rxpy', 'cu5oufs', 'cu5tpek', 'cu5pbdh']}
with self.recorder.use_cassette(
'TestMore.test_comments',
match_requests_on=['uri', 'method', 'body']):
more = MoreComments(self.reddit, data)
more.submission = self.reddit.submission('3hahrw')
assert len(more.comments()) == 7
def test_comments__continue_thread_type(self):
data = {'count': 0, 'name': 't1__', 'id': '_',
'parent_id': 't1_cu5v5h7', 'children': []}
with self.recorder.use_cassette(
'TestMore.test_comments__continue_thread_type',
match_requests_on=['uri', 'method', 'body']):
more = MoreComments(self.reddit, data)
more.submission = self.reddit.submission('3hahrw')
assert len(more.comments()) == 1
|
# -*- coding: utf-8 -*-
# vispy: gallery 5:105:5
# -----------------------------------------------------------------------------
# Copyright (c) Vispy Development Team. All Rights Reserved.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
# -----------------------------------------------------------------------------
# Author: Nicolas P .Rougier
# Date: 04/03/2014
# Abstract: Show post-processing technique using framebuffer
# Keywords: framebuffer, gloo, cube, post-processing
# -----------------------------------------------------------------------------
"""
Show post-processing using a FrameBuffer
========================================
"""
import numpy as np
from vispy import app
from vispy.geometry import create_cube
from vispy.util.transforms import perspective, translate, rotate
from vispy.gloo import (Program, VertexBuffer, IndexBuffer, Texture2D, clear,
FrameBuffer, RenderBuffer, set_viewport, set_state)
cube_vertex = """
uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;
attribute vec3 position;
attribute vec2 texcoord;
attribute vec3 normal; // not used in this example
attribute vec4 color; // not used in this example
varying vec2 v_texcoord;
void main()
{
gl_Position = projection * view * model * vec4(position,1.0);
v_texcoord = texcoord;
}
"""
cube_fragment = """
uniform sampler2D texture;
varying vec2 v_texcoord;
void main()
{
float r = texture2D(texture, v_texcoord).r;
gl_FragColor = vec4(r,r,r,1);
}
"""
quad_vertex = """
attribute vec2 position;
attribute vec2 texcoord;
varying vec2 v_texcoord;
void main()
{
gl_Position = vec4(position, 0.0, 1.0);
v_texcoord = texcoord;
}
"""
quad_fragment = """
uniform sampler2D texture;
varying vec2 v_texcoord;
void main()
{
vec2 d = 5.0 * vec2(sin(v_texcoord.y*50.0),0)/512.0;
// Inverse video
if( v_texcoord.x > 0.5 ) {
gl_FragColor.rgb = 1.0-texture2D(texture, v_texcoord+d).rgb;
} else {
gl_FragColor = texture2D(texture, v_texcoord);
}
}
"""
def checkerboard(grid_num=8, grid_size=32):
row_even = grid_num // 2 * [0, 1]
row_odd = grid_num // 2 * [1, 0]
Z = np.row_stack(grid_num // 2 * (row_even, row_odd)).astype(np.uint8)
return 255 * Z.repeat(grid_size, axis=0).repeat(grid_size, axis=1)
class Canvas(app.Canvas):
def __init__(self):
app.Canvas.__init__(self, title='Framebuffer post-processing',
keys='interactive', size=(512, 512))
# Build cube data
# --------------------------------------
vertices, indices, _ = create_cube()
vertices = VertexBuffer(vertices)
self.indices = IndexBuffer(indices)
# Build program
# --------------------------------------
view = translate((0, 0, -7))
self.phi, self.theta = 60, 20
model = rotate(self.theta, (0, 0, 1)).dot(rotate(self.phi, (0, 1, 0)))
self.cube = Program(cube_vertex, cube_fragment)
self.cube.bind(vertices)
self.cube["texture"] = checkerboard()
self.cube["texture"].interpolation = 'linear'
self.cube['model'] = model
self.cube['view'] = view
color = Texture2D((512, 512, 3), interpolation='linear')
self.framebuffer = FrameBuffer(color, RenderBuffer((512, 512)))
self.quad = Program(quad_vertex, quad_fragment, count=4)
self.quad['texcoord'] = [(0, 0), (0, 1), (1, 0), (1, 1)]
self.quad['position'] = [(-1, -1), (-1, +1), (+1, -1), (+1, +1)]
self.quad['texture'] = color
# OpenGL and Timer initalization
# --------------------------------------
set_state(clear_color=(.3, .3, .35, 1), depth_test=True)
self.timer = app.Timer('auto', connect=self.on_timer, start=True)
self._set_projection(self.physical_size)
self.show()
def on_draw(self, event):
with self.framebuffer:
set_viewport(0, 0, 512, 512)
clear(color=True, depth=True)
set_state(depth_test=True)
self.cube.draw('triangles', self.indices)
set_viewport(0, 0, *self.physical_size)
clear(color=True)
set_state(depth_test=False)
self.quad.draw('triangle_strip')
def on_resize(self, event):
self._set_projection(event.physical_size)
def _set_projection(self, size):
width, height = size
set_viewport(0, 0, width, height)
projection = perspective(30.0, width / float(height), 2.0, 10.0)
self.cube['projection'] = projection
def on_timer(self, event):
self.theta += .5
self.phi += .5
model = rotate(self.theta, (0, 0, 1)).dot(rotate(self.phi, (0, 1, 0)))
self.cube['model'] = model
self.update()
if __name__ == '__main__':
canvas = Canvas()
app.run()
|
from abc import ABC
import tensorflow_datasets as tfds
from tqdm import tqdm
import numpy as np
class DS(ABC):
def __init__(self, variants):
"""
:param variants: Possible variants to load
"""
self.variants = variants
def load(self, name, split='train'):
"""
Load dataset from tensorflow_datasets
:param name: name dataset
:return:
"""
ds = tfds.load(name, split=split, shuffle_files=True)
x_data = []
y_data = []
for i in tqdm(tfds.as_numpy(ds)):
x_data.append(i['image'])
y_data.append(i['label'])
x_data = np.array(x_data).astype(float)
y_data = np.array(y_data)
return x_data, y_data
|
import numpy as np
import pytest
import gbpy.pad_dump_file as pad
import gbpy.util_funcs as uf
import byxtal.lattice as gbl
@pytest.mark.parametrize('filename0, element, num_GBregion, actual_min_z_gbreg, actual_max_z_gbreg,'
'actual_w_bottom_SC, actual_w_top_SC',
[("tests/data/dump_2", "Al", 51, -3.06795, 1.44512, 116.85, 118.462)])
# ("tests/data/dump_1", "Al", 138, -2.811127714, 2.811127714, 94, 91.5),
def test_GB_finder(filename0, element, num_GBregion, actual_min_z_gbreg, actual_max_z_gbreg,
actual_w_bottom_SC, actual_w_top_SC):
l1 = gbl.Lattice(str(element))
data = uf.compute_ovito_data(filename0)
non_p = uf.identify_pbc(data)
GbRegion, GbIndex, GbWidth, w_bottom_SC, w_top_SC = pad.GB_finder(data, l1, non_p, 'ptm', '.1')
assert np.abs((actual_w_bottom_SC - w_bottom_SC)/actual_w_bottom_SC) < .5
assert np.abs((actual_w_top_SC - w_top_SC)/actual_w_top_SC) < .5
assert np.abs(GbRegion[0] - actual_min_z_gbreg) < 1e-3
assert np.abs(GbRegion[1] - actual_max_z_gbreg) < 1e-3
assert np.shape(GbIndex)[0] == num_GBregion
|
#!/bin/python3
from recognize import *
from os import system
def main():
R = Recognizer('_model')
system('clear')
R.start()
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
print()
post('Пока')
|
# -*- coding: utf-8 -*-
import json
from pprint import pprint
from tgolosbase.api import Api
print('connect')
b4 = Api()
print('try call')
account = 'ksantoprotein'
wif = '5...'
password = 'P5...'
tx = b4.account_update_password(account, password, wif)
pprint(tx)
input()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@author: Salvatore Anzalone
@organization: CHArt - Université Paris 8
"""
from Box2D import b2
from Box2D import (b2Body, b2World, b2Vec2)
import numpy as np
"""
Vehicle based on Chris Campbell's tutorial from iforce2d.net:
http://www.iforce2d.net/b2dtut/top-down-car
"""
class Tire():
def __init__(self, car, max_forward_speed=50.0,
max_backward_speed=-25, max_drive_force=150,
turn_torque=15, max_lateral_impulse=3,
dimensions=(0.5, 1.25), density=1.0,
position=(0, 0), angle=0.0):
world = car.b2body.world
self.current_traction = 1
self.turn_torque = turn_torque
self.max_forward_speed = max_forward_speed
self.max_backward_speed = max_backward_speed
self.max_drive_force = max_drive_force
self.max_lateral_impulse = max_lateral_impulse
self.ground_areas = []
self.body = world.CreateDynamicBody(position=position, angle=angle)
self.body.CreatePolygonFixture(box=dimensions, density=density)
self.body.userData = {'obj': self}
@property
def forward_velocity(self):
body = self.body
current_normal = body.GetWorldVector((0, 1))
return current_normal.dot(body.linearVelocity) * current_normal
@property
def lateral_velocity(self):
body = self.body
right_normal = body.GetWorldVector((1, 0))
return right_normal.dot(body.linearVelocity) * right_normal
def update_friction(self):
impulse = -self.lateral_velocity * self.body.mass
if impulse.length > self.max_lateral_impulse:
impulse *= self.max_lateral_impulse / impulse.length
self.body.ApplyLinearImpulse(self.current_traction * impulse,
self.body.worldCenter, True)
aimp = 0.1 * self.current_traction * \
self.body.inertia * -self.body.angularVelocity
self.body.ApplyAngularImpulse(aimp, True)
current_forward_normal = self.forward_velocity
current_forward_speed = current_forward_normal.Normalize()
drag_force_magnitude = -2 * current_forward_speed
self.body.ApplyForce(self.current_traction * drag_force_magnitude * current_forward_normal,
self.body.worldCenter, True)
def update_drive(self, desired_speed):
# find the current speed in the forward direction
current_forward_normal = self.body.GetWorldVector((0, 1))
current_speed = self.forward_velocity.dot(current_forward_normal)
# apply necessary force
force = 0.0
if desired_speed > current_speed:
force = self.max_drive_force
elif desired_speed < current_speed:
force = -self.max_drive_force
else:
return
self.body.ApplyForce(self.current_traction * force * current_forward_normal,
self.body.worldCenter, True)
class Vehicle():
__default_vertices = [(1.5, 0.0),
(3.0, 2.5),
(2.8, 5.5),
(1.0, 9.0),
(-1.0, 9.0),
(-2.8, 5.5),
(-3.0, 2.5),
(-1.5, 0.0),
]
__default_tires_anchors = [
(-4., 3.5),
(+4., 3.5)
]
def __init__(self, world, vertices=None,
tires_anchors=None, density=1, position=(0, 0), angle=0.0,
**tire_kws):
self.vertices = vertices
if self.vertices is None:
self.vertices = Vehicle.__default_vertices
self.world = world
self.b2body = world.b2world.CreateDynamicBody(position=position, angle=angle)
self.b2body.CreatePolygonFixture(vertices=self.vertices, density=density)
self.b2body.userData = {'obj': self}
self.tires_anchors = tires_anchors
if self.tires_anchors is None:
self.tires_anchors = Vehicle.__default_tires_anchors
self.tires = [Tire(self,
position=self.b2body.transform * self.tires_anchors[i],
angle=angle,
**tire_kws) for i in range(len(self.tires_anchors))]
joints = self.joints = []
for tire, anchor in zip(self.tires, self.tires_anchors):
j = world.b2world.CreateRevoluteJoint(bodyA=self.b2body,
bodyB=tire.body,
localAnchorA=anchor,
# center of tire
localAnchorB=(0, 0),
enableMotor=False,
maxMotorTorque=1000,
enableLimit=True,
lowerAngle=0,
upperAngle=0,
)
joints.append(j)
def step(self, fw):
for tire in self.tires:
tire.update_friction()
def draw(self, fw):
transform = self.b2body.transform
vertices = [transform * v for v in self.vertices]
fw.DrawPolygon( vertices, (255, 255, 255, 255))
for tire in self.tires:
for fixture in tire.body.fixtures:
transform = tire.body.transform
vertices = [transform * v for v in fixture.shape.vertices]
fw.DrawPolygon( vertices, (255, 255, 255, 255))
|
"""
pytest files
"""
|
from sqlalchemy.dialects.mssql.base import MSDialect, MSSQLCompiler, MSIdentifierPreparer, MSExecutionContext
from sqlalchemy import util
from .connector import PyTDSConnector
_server_side_id = util.counter()
class SSCursor(object):
def __init__(self, c):
self._c = c
self._name = None
self._nrows = 0
self._row = 0
def execute(self, statement, parameters):
_name = 'tc%08X' % _server_side_id()
sql = 'DECLARE ' + _name + ' CURSOR GLOBAL SCROLL STATIC READ_ONLY FOR ' + statement
#print(sql, parameters)
self._c.execute(sql, parameters)
self._name = _name
sql = 'OPEN ' + _name
self._c.execute(sql)
self._c.execute('SELECT @@CURSOR_ROWS AS nrows')
self._nrows = self._c.fetchone()[0]
return self.fetchone()
def close(self):
sql = 'CLOSE '+self._name
self._c.execute(sql)
sql = 'DEALLOCATE '+self._name
self._c.execute(sql)
self._c.close()
self._name = None
self._nrows = 0
self._row = 0
def fetchone(self):
if not (0 <= self._row < self._nrows):
return None
sql = 'FETCH ABSOLUTE %d FROM %s' % (self._row+1, self._name)
self._c.execute(sql)
return self._c.fetchone()
def movefirst(self):
value = 0
if value >= 0 and value < self._nrows:
self._row = value
return True
return False
def moveprev(self):
value = self._row - 1
if value >= 0 and value < self._nrows:
self._row = value
return True
return False
def movenext(self):
value = self._row + 1
if value >= 0 and value < self._nrows:
self._row = value
return True
return False
def movelast(self):
value = self._nrows - 1
if value >= 0 and value < self._nrows:
self._row = value
return True
return False
def goto(self, value):
if value >= 0 and value < self._nrows:
self._row = value
return True
return False
def __getattr__(self, name):
#print('getattr(%s)' %name)
return getattr(self._c, name)
class MSSQLCompiler_pytds(MSSQLCompiler):
pass
class MSSQLIdentifierPreparer_pytds(MSIdentifierPreparer):
pass
class MSExecutionContext_pytds(MSExecutionContext):
_embedded_scope_identity = False
def pre_exec(self):
super(MSExecutionContext_pytds, self).pre_exec()
if self._select_lastrowid and \
self.dialect.use_scope_identity and \
len(self.parameters[0]):
self._embedded_scope_identity = True
self.statement += "; select scope_identity()"
def post_exec(self):
if self._embedded_scope_identity:
while True:
try:
row = self.cursor.fetchall()[0]
break
except self.dialect.dbapi.Error as e:
self.cursor.nextset()
self._lastrowid = int(row[0])
self.cursor.lastrowid = int(row[0])
self._select_lastrowid = False
super(MSExecutionContext_pytds, self).post_exec()
def create_cursor(self):
usess = self.execution_options.get('stream_results', None)
if usess:
self._is_server_side = True
return SSCursor(self._dbapi_connection.cursor())
else:
self._is_server_side = False
return self._dbapi_connection.cursor()
class MSDialect_pytds(PyTDSConnector, MSDialect):
execution_ctx_cls = MSExecutionContext_pytds
statement_compiler = MSSQLCompiler_pytds
preparer = MSSQLIdentifierPreparer_pytds
supports_server_side_cursors = True
supports_statement_cache = True
def __init__(self, server_side_cursors=False, **params):
super(MSDialect_pytds, self).__init__(**params)
self.use_scope_identity = True
self.server_side_cursors = server_side_cursors
def set_isolation_level(self, connection, level):
if level == 'AUTOCOMMIT':
connection.autocommit(True)
else:
connection.autocommit(False)
super(MSDialect_pytds, self).set_isolation_level(connection,
level)
|
"""Abstracte Factory."""
class Dog(object):
def speak(self):
return "Woooof"
def __str__(self):
return self.__class__.__name__
class DogFactory(object):
def get_pet(self):
return Dog()
def get_food(self):
return "Dog Food..!"
class PetStore(object):
def __init__(self, pet_factory=None):
self._pet_factory = pet_factory
def show_pet(self):
pet = self._pet_factory.get_pet()
pet_food = self._pet_factory.get_food()
print(f"Our pet is {pet}")
print(f"Our pet food {pet_food}")
factory = DogFactory()
shop = PetStore(pet_factory=factory)
shop.show_pet()
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import re
import django.core.validators
import tablemanager.models
class Migration(migrations.Migration):
dependencies = [
('tablemanager', '0003_publish_geoserver_setting'),
]
operations = [
migrations.CreateModel(
name='Application',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('name', models.CharField(db_index=True, max_length=255, validators=[django.core.validators.RegexValidator(re.compile('^[a-z0-9_]+$'), 'Slug can only contain lowercase letters, numbers and underscores', 'invalid')])),
('description', models.TextField(blank=True)),
],
options={
},
bases=(models.Model,),
),
migrations.AddField(
model_name='publish',
name='applications',
field=models.ManyToManyField(help_text='The applications which can list this layer.', to='tablemanager.Application', blank=True),
preserve_default=True,
),
]
|
import time
import requests
import re
import pymysql
import urllib3
from fake_useragent import UserAgent
from scrapy import Selector
urllib3.disable_warnings()
db = pymysql.connect("localhost", "root", "", "miraihyoka")
cursor = db.cursor()
def spider():
domain = "https://www.animenewsnetwork.com/encyclopedia/ratings-anime.php?top50=best_bayesian&n=7000"
s = requests.session()
s.keep_alive = False
s.DEFAULT_RETRIES = 5
headers=get_header()
result = s.get(domain, headers=headers, verify=False).text
sel = Selector(text=result)
# print(result)
results = sel.xpath('//tr[@bgcolor="#EEEEEE"]/td[@class="t"]/a/@href').extract()
# url=sel.xpath("//*[@id='#area5114']").extract()
print(results)
for url in results[2772:]:
headers = get_header()
url='https://www.animenewsnetwork.com' + url
print(url)
details_page = s.get(url, headers=headers, verify=False).text
# print(details_page)
sel = Selector(text=details_page)
pat = 'Bayesian estimate:</b> (.*) \\(.*\\),'
rate=re.compile(pat).findall(details_page)[0]
# rate = sel.xpath("//span[@itemprop='ratingValue']/text()").extract()[0]
# float(rate)
print(rate)
try:
name_en = sel.xpath('//*[@id="page_header"]/text()').extract()[0]
pat = '(.*)\s\\('
try:
name_en = re.compile(pat).findall(name_en)[0]
except:
pass
name_en = name_en.replace('`', '\'')
print(name_en)
except:
name_en = ''
try:
name_jp = sel.xpath('//div[@id="infotype-2"]/div[contains(text(),"(Japanese)")][last()]/text()').extract()[0]
pat = '(.*)\s\\('
try:
name_jp = re.compile(pat).findall(name_jp)[0]
except:
pass
name_jp = name_jp.replace('`', '\'')
print(name_jp)
except:
name_jp = ''
sql = 'insert into ann(name_en,name_jp,rate,url) value (%s,%s,%s,%s)'
args = (name_en, name_jp, rate, url)
db.ping(reconnect=True)
cursor.execute(sql, args)
db.commit()
time.sleep(1)
def get_header():
headers = {
'sec-ch-ua': '"Google Chrome";v="87", " Not;A Brand";v="99", "Chromium";v="87"',
'accept': 'application/json, text/plain, */*',
'user-agent': str(UserAgent().random),
'sec-fetch-site': 'same-site',
'sec-fetch-mode': 'cors',
'sec-fetch-dest': 'empty',
'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,zh-TW;q=0.7',
'keep-live': 'false',
}
return headers
if __name__ == '__main__':
spider()
db.close()
|
#!/home/samhattangady/anaconda3/bin/python
import time
import sys
import pygame
import argparse
import datetime
# Function to print current time
def print_time():
print('{0:02d}:{1:02d}'.format(datetime.datetime.now().hour, datetime.datetime.now().minute), end='\t')
# Function is used to return the cursor to
# overwrite the old messages
def erase_line(chars):
print('\b' * chars, end=' ')
sys.stdout.flush()
# Function to print number of minutes remaining
# Currently uses sleep. To add further functionality, we will
# have to change that, and use multithreading to listen for keypresses
def countdown(minutes):
while minutes > 0:
message = '\bTime remaining: {0} minutes'.format(minutes)
print(message, end=' ')
sys.stdout.flush()
time.sleep(60)
minutes -= 1
erase_line(len(message))
print(' ' * (len(message) + 2), end=' ')
erase_line(len(message) + 2)
return
# Function for the working cycles
def start_pomodoro(cycle, work_length):
minutes = work_length
print_time()
print('Pomodoro number {0}: '.format(cycle), end=' ')
countdown(minutes)
play_sound(1)
print('Completed')
return
# Function for the break cycles
def start_break(minutes):
print_time()
print('Break! Relax... ', end=' ')
countdown(minutes)
play_sound(3)
print('Okay. Back to work')
return
# Function to play sound
def play_sound(n):
while n > 0:
pygame.mixer.music.play()
time.sleep(0.2)
n -= 1
return
def main():
pygame.init()
pygame.mixer.music.load("sound.wav")
parser = argparse.ArgumentParser(description='A pomodoro timer in your terminal')
parser.add_argument('-w', '--work_length', help='Length of working session in minutes. Default is 25')
parser.add_argument('-b', '--break_length', help='Length of break in minutes. Default is 5 mins')
parser.add_argument('-n', '--number_of_cycles', help='Number of cycles. Default is 4')
args = parser.parse_args()
work_length = int(args.work_length) if args.work_length else 25
break_length = int(args.break_length) if args.break_length else 5
number_of_cycles = int(args.number_of_cycles) if args.number_of_cycles else 4
for cycle in range(number_of_cycles):
input("Press enter to begin working...")
start_pomodoro(cycle+1, work_length)
if cycle+1 < number_of_cycles:
input("Press enter to begin break...")
start_break(break_length)
print('Good job!')
if __name__ == '__main__':
main()
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
#
# http://www.apache.org/licenses/LICENSE-2.0
#
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from aliyunsdkcore.request import RpcRequest
from aliyunsdkdg.endpoint import endpoint_data
class ConnectDatabaseRequest(RpcRequest):
def __init__(self):
RpcRequest.__init__(self, 'dg', '2019-03-27', 'ConnectDatabase','dg')
self.set_protocol_type('https')
self.set_method('POST')
if hasattr(self, "endpoint_map"):
setattr(self, "endpoint_map", endpoint_data.getEndpointMap())
if hasattr(self, "endpoint_regional"):
setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional())
def get_DbName(self):
return self.get_body_params().get('DbName')
def set_DbName(self,DbName):
self.add_body_params('DbName', DbName)
def get_Port(self):
return self.get_body_params().get('Port')
def set_Port(self,Port):
self.add_body_params('Port', Port)
def get_DbPassword(self):
return self.get_body_params().get('DbPassword')
def set_DbPassword(self,DbPassword):
self.add_body_params('DbPassword', DbPassword)
def get_Host(self):
return self.get_body_params().get('Host')
def set_Host(self,Host):
self.add_body_params('Host', Host)
def get_DbType(self):
return self.get_body_params().get('DbType')
def set_DbType(self,DbType):
self.add_body_params('DbType', DbType)
def get_DbUserName(self):
return self.get_body_params().get('DbUserName')
def set_DbUserName(self,DbUserName):
self.add_body_params('DbUserName', DbUserName)
def get_GatewayId(self):
return self.get_body_params().get('GatewayId')
def set_GatewayId(self,GatewayId):
self.add_body_params('GatewayId', GatewayId) |
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
def plot1D(x, y):
plt.plot(x, y)
plt.grid(True)
#plt.xlim([0, np.max(x)])
#plt.ylim([0, np.max(y)])
plt.show()
def plot2D(x, y, z):
plt.contourf(x, y, z)
#plt.imshow(z, vmin=np.min(z), vmax=np.max(z),
# origin="lower", extent=[0, 1, 0, 1])
plt.grid(True)
plt.colorbar()
plt.show()
def plot3D(x, y, z):
ax = plt.gca(projection='3d')
ax.plot_surface(x, y, z)
#ax.set_zlim([0, np.max(z)+ 10])
plt.show()
def quiver(x, y, u, v):
plt.figure(figsize=(8, 8))
plt.quiver(x, y, u, v)
plt.show()
def compare(x, y1, y2, y3):
plt.plot(x, y1, label="Solution")
plt.plot(x, y2, label="Lax-Friedrichs")
plt.plot(x, y3, label="Rusanov")
plt.legend()
plt.grid(True)
plt.show() |
from django.forms import ModelForm
from django.contrib.auth.forms import UserCreationForm
from django import forms
# from django.contrib.auth.models import User
from .models import CustomUser
from django.contrib import messages
class CustomUserCreationForm(UserCreationForm):
def clean_email(self):
demail = self.cleaned_data['email']
if "amrita.edu" not in demail:
raise forms.ValidationError("You must be use collage Email ID")
message = "You already Booked the Room One can Book Only one Room"
messages.error(request, message)
return redirect('register_page')
return demail
class Meta:
model = CustomUser
fields = ['username', 'email', 'password1', 'password2']
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from builtins import object
from builtins import range
from daglet._utils import get_hash_int, get_hash
from functools import reduce
from past.builtins import basestring
from textwrap import dedent
import copy
import daglet
import operator
import subprocess
def test__get_hash():
assert get_hash(None) == '6adf97f83acf6453d4a6a4b1070f3754'
assert get_hash(5) == 'e4da3b7fbbce2345d7772b0674a318d5'
assert get_hash({'a': 'b'}) == '31ee3af152948dc06066ec1a7a4c5f31'
def test__vertex_parents():
v1 = daglet.Vertex()
v2 = daglet.Vertex()
v3 = v1.vertex('v3')
v4 = v1.vertex('v4')
v5 = v2.vertex('v5')
assert v1.parents == []
assert v3.vertex().parents == [v3]
assert v4.vertex().parents == [v4]
assert daglet.Vertex(parents=[v3, v5]).parents == sorted([v3, v5])
assert daglet.Vertex(parents=[v5, v3]).parents == sorted([v3, v5])
def test__vertex_label():
assert daglet.Vertex().label == None
assert daglet.Vertex('v1').label == 'v1'
def test__vertex_hash():
v1 = daglet.Vertex('v1')
v2 = daglet.Vertex('v2', [v1])
assert isinstance(hash(v1), int)
assert hash(v1) == 352423289548818779
assert hash(v2) == 5230371954595182985
assert hash(v1) == hash(daglet.Vertex('v1'))
assert hash(v2) != hash(v1)
assert hash(v1) != hash(daglet.Vertex('v3'))
def test__vertex_extra_hash():
assert daglet.Vertex().extra_hash == None
assert daglet.Vertex(extra_hash=5).extra_hash == 5
def test__vertex_eq():
assert daglet.Vertex() == daglet.Vertex()
assert daglet.Vertex('v1') == daglet.Vertex('v1')
assert daglet.Vertex('v1') != daglet.Vertex('v2')
assert not (daglet.Vertex('v1') != daglet.Vertex('v1'))
assert daglet.Vertex(extra_hash=1) == daglet.Vertex(extra_hash=1)
assert daglet.Vertex(extra_hash=1) != daglet.Vertex(extra_hash=2)
assert daglet.Vertex().vertex() == daglet.Vertex().vertex()
assert daglet.Vertex().vertex() != daglet.Vertex()
assert daglet.Vertex().vertex('v1') == daglet.Vertex().vertex('v1')
assert daglet.Vertex().vertex('v1') != daglet.Vertex().vertex('v2')
assert daglet.Vertex('v1').vertex() == daglet.Vertex('v1').vertex()
assert daglet.Vertex('v1').vertex() != daglet.Vertex('v2').vertex()
v1 = daglet.Vertex('v1')
v2 = daglet.Vertex('v2')
assert daglet.Vertex(parents=[v1, v2]) == daglet.Vertex(parents=[v1, v2])
assert daglet.Vertex(parents=[v1, v2]) == daglet.Vertex(parents=[v2, v1])
def test__vertex_cmp():
v1 = daglet.Vertex('v1')
v2 = daglet.Vertex('v2')
vs = sorted([v1, v2])
assert vs == sorted([v2, v1])
va = vs[0]
vb = vs[1]
assert hash(va) < hash(vb)
assert va < vb
assert not (vb < va)
assert va <= vb
assert not (vb <= va)
assert va <= va
assert va == va
assert not (va == vb)
assert va != vb
assert not (va != va)
assert vb >= va
assert not (va >= vb)
assert vb >= vb
assert vb > va
assert not (va > vb)
def test__vertex_short_hash():
h1 = daglet.Vertex('v1').short_hash
h2 = daglet.Vertex('v1').short_hash
h3 = daglet.Vertex('v2').short_hash
assert isinstance(h1, basestring)
assert int(h1, base=16)
assert len(h1) == 8
assert h1 == h2
assert h1 != h3
def test__vertex_get_repr():
v1 = daglet.Vertex('v1')
v2 = daglet.Vertex('v2', parents=[v1])
v3 = v2.vertex('v3')
assert v1.get_repr() == repr(v1)
assert repr(v1) == "daglet.Vertex('{}') <{}>".format('v1', v1.short_hash)
assert repr(v3) == "daglet.Vertex('{}', ...) <{}>".format('v3', v3.short_hash)
assert v3.get_repr(include_hash=False) == "daglet.Vertex('{}', ...)".format('v3')
assert daglet.Vertex().get_repr(include_hash=False) == 'daglet.Vertex()'
assert daglet.Vertex(extra_hash=5).get_repr(include_hash=False) == 'daglet.Vertex(...)'
assert v2.vertex().get_repr(include_hash=False) == 'daglet.Vertex(...)'
assert daglet.Vertex(0).get_repr(include_hash=False) == 'daglet.Vertex(0)'
def test__vertex_clone():
assert daglet.Vertex().clone(label='v2').label == 'v2'
def test__vertex_transplant():
v2 = daglet.Vertex('v2')
assert daglet.Vertex().transplant([v2]).parents == [v2]
def test__toposort():
get_parents = lambda x: x.parents
v1 = daglet.Vertex()
v2 = v1.vertex()
assert daglet.toposort([], get_parents) == []
assert daglet.toposort([v1], get_parents) == [v1]
assert daglet.toposort([v2], get_parents) == [v1, v2]
v3 = daglet.Vertex('v3')
v4 = v3.vertex('v4')
v5 = v3.vertex('v5')
v6 = v5.vertex('v6')
v7 = v5.vertex('v7')
v8 = daglet.Vertex('v8')
v9 = daglet.Vertex('v9', [v4, v6, v7])
v10 = daglet.Vertex('v10', [v3, v8])
v11 = daglet.Vertex('v11')
sorted_vertices = daglet.toposort([v4, v9, v10, v11], get_parents)
assert sorted_vertices == [v11, v8, v3, v10, v5, v7, v4, v6, v9]
def test__transform():
get_parents = lambda x: x.parents
v1 = daglet.Vertex()
v2 = v1.vertex()
assert daglet.transform([], get_parents) == ({}, {})
assert daglet.transform([v1], get_parents) == ({v1: None}, {})
assert daglet.transform([v2], get_parents) == ({v1: None, v2: None}, {(v1, v2): None})
vertex_dummy_func = lambda obj, parent_values: (obj, parent_values)
edge_dummy_func = lambda parent, child, parent_value: 'test'
assert daglet.transform([v2], get_parents, vertex_dummy_func, edge_dummy_func) == (
{
v1: (v1, []),
v2: (v2, ['test'])
},
{
(v1, v2): 'test'
}
)
v3 = daglet.Vertex('v3')
v4 = v3.vertex('v4')
v5 = v3.vertex('v5')
v6 = v5.vertex('v6')
v7 = v5.vertex('v7')
v8 = daglet.Vertex('v8')
v9 = daglet.Vertex('v9', [v4, v6, v7])
v10 = daglet.Vertex('v10', [v3, v8])
v11 = daglet.Vertex('v11')
vertex_rank_func = lambda obj, parent_ranks: max(parent_ranks) + 1 if len(parent_ranks) else 0
vertex_map, edge_map = daglet.transform([v4, v9, v10, v11], get_parents, vertex_rank_func)
assert vertex_map == {
v3: 0,
v4: 1,
v5: 1,
v6: 2,
v7: 2,
v8: 0,
v9: 3,
v10: 1,
v11: 0,
}
assert edge_map == {
(v3, v4): 0,
(v3, v5): 0,
(v3, v10): 0,
(v4, v9): 1,
(v5, v6): 1,
(v5, v7): 1,
(v6, v9): 2,
(v7, v9): 2,
(v8, v10): 0,
}
debug = False
if debug:
vertex_labels = {
v3: 'v3',
v4: 'v4',
v5: 'v5',
v6: 'v6',
v7: 'v7',
v8: 'v8',
v9: 'v9',
v10: 'v10',
v11: 'v11',
}
vertex_colors = {
v3: 'red',
v4: 'yellow',
v5: 'purple',
v6: 'purple',
v7: 'lightblue',
v8: 'green',
v9: 'white',
v11: 'orange',
}
daglet.view([v4, v9, v10, v11], get_parents, vertex_label_func=vertex_labels.get,
vertex_color_func=vertex_colors.get)
def test__example__git():
REPO_DIR = '.'
def get_parent_hashes(commit_hash):
return (subprocess
.check_output(['git', 'rev-list', '--parents', '-n1', commit_hash], cwd=REPO_DIR)
.decode()
.strip()
.split(' ')[1:]
)
def get_commit_message(commit_hash):
return subprocess.check_output(['git', 'log', '-n1', '--pretty=short', commit_hash], cwd=REPO_DIR)
class Commit(object):
def __init__(self, commit_hash, parents):
self.commit_hash = commit_hash
self.parents = parents
self.log = get_commit_message(commit_hash)
vertex_map = daglet.transform_vertices(['HEAD'], get_parent_hashes, Commit)
assert 'HEAD' in vertex_map
assert all(isinstance(x, basestring) for x in vertex_map.keys())
assert all(isinstance(x, Commit) for x in vertex_map.values())
debug = False
if debug:
daglet.view(
vertex_map.values(),
rankdir=None,
parent_func=lambda x: x.parents,
vertex_label_func=lambda x: x.log,
vertex_color_func=lambda x: 'lightblue',
)
def test__example__vdom():
class TextBuffer(object):
def __init__(self, row_count, col_count):
self.rows = [' ' * col_count] * row_count
@property
def row_count(self):
return len(self.rows)
@property
def col_count(self):
return len(self.rows[0])
@property
def text(self):
return '\n'.join(self.rows)
def draw_text(self, row, col, text):
assert len(text.split('\n')) == 1 # FIXME
if 0 <= row < len(self.rows):
start = self.rows[row][:col]
end = self.rows[row][col+len(text):]
self.rows[row] = '{}{}{}'.format(start, text, end)[:self.col_count]
def draw_border(self, row, col, row_count, col_count):
V_CHAR = u'\u2502'
TL_CHAR = u'\u250c'
TR_CHAR = u'\u2510'
H_CHAR = u'\u2500'
BL_CHAR = u'\u2514'
BR_CHAR = u'\u2518'
self.draw_text(row, col, u'{}{}{}'.format(TL_CHAR, H_CHAR * (col_count - 2), TR_CHAR))
for row2 in range(row + 1, row + row_count - 1):
self.draw_text(row2, col, V_CHAR)
self.draw_text(row2, col + col_count - 1, V_CHAR)
self.draw_text(row + row_count - 1, col, u'{}{}{}'.format(BL_CHAR, H_CHAR * (col_count - 2), BR_CHAR))
def draw_buf(self, row, col, buf):
for row2 in range(buf.row_count):
self.draw_text(row + row2, col, buf.rows[row2])
class Component(object):
def __init__(self, props={}, children=[]):
self.props = props
self.children = children
def __hash__(self):
child_hashes = [hash(x) for x in self.children]
return get_hash_int([self.props, self.__class__.__name__, child_hashes])
def __eq__(self, other):
return hash(self) == hash(other)
def expand(self):
return self._expand()
def collapse(self, children):
return self._collapse(children)
def textify(self, child_bufs):
return self._textify(child_bufs)
def _expand(self):
return self.children
def _collapse(self, children):
collapsed = copy.copy(self)
collapsed.children = children
return collapsed
def _textify(self, child_bufs):
raise NotImplementedError()
class Div(Component):
def __init__(self, props, children):
super(Div, self).__init__(props, children)
def _textify(self, child_bufs):
child_bufs = child_bufs or []
row_count = reduce(operator.add, [x.row_count for x in child_bufs]) + 2
col_count = max([x.col_count for x in child_bufs]) + 4
buf = TextBuffer(row_count, col_count)
row = 1
for child_buf in child_bufs:
buf.draw_buf(row, 2, child_buf)
row += child_buf.row_count
buf.draw_border(0, 0, row_count, col_count)
return buf
class Text(Component):
def __init__(self, text):
super(Text, self).__init__({'text': text})
def _textify(self, child_bufs):
buf = TextBuffer(1, len(self.props['text']))
buf.draw_text(0, 0, self.props['text'])
return buf
class CompositeComponent(Component):
def render(self):
raise NotImplementedError()
def _expand(self):
return [self.render()]
def _collapse(self, children):
assert len(children) == 1
return children[0]
subpage_render_count = [0]
class SubPage(CompositeComponent):
def render(self):
subpage_render_count[0] += 1
out = Div({}, [
Text('# sub page #'),
])
return out
class MainPage(CompositeComponent):
def __init__(self, text):
super(MainPage, self).__init__({'text': text})
def render(self):
return Div({}, [
Div({}, [
Text('# main page #'),
Text('sub item'),
Text(self.props['text']),
]),
SubPage(),
Text('sub sub item'),
])
assert subpage_render_count[0] == 0
# Create initial vdom.
root = MainPage('some text')
vdom = daglet.transform_vertices([root], Component.expand, Component.collapse)
# FIXME: combine `toposort` and `transform` so that the parent_func only gets hit once; expect only one render.
assert subpage_render_count[0] == 2
# Turn vdom into text.
rendered_root = vdom[root]
buf_map = daglet.transform_vertices([rendered_root], lambda x: x.children, Component.textify)
buf = buf_map[rendered_root]
assert buf.text == dedent("""\
┌───────────────────┐
│ ┌───────────────┐ │
│ │ # main page # │ │
│ │ sub item │ │
│ │ some text │ │
│ └───────────────┘ │
│ ┌──────────────┐ │
│ │ # sub page # │ │
│ └──────────────┘ │
│ sub sub item │
└───────────────────┘"""
)
# Create new vdom incrementally.
root2 = MainPage('some other text')
vdom2 = daglet.transform_vertices([root2], Component.expand, Component.collapse, vertex_map=vdom)
assert subpage_render_count[0] == 2
# Turn vdom into text again, incrementally. Only redraw changed portions.
rendered_root2 = vdom2[root2]
buf_map2 = daglet.transform_vertices([rendered_root2], lambda x: x.children, Component.textify, vertex_map=buf_map)
buf2 = buf_map2[rendered_root2]
assert buf2.text == dedent("""\
┌─────────────────────┐
│ ┌─────────────────┐ │
│ │ # main page # │ │
│ │ sub item │ │
│ │ some other text │ │
│ └─────────────────┘ │
│ ┌──────────────┐ │
│ │ # sub page # │ │
│ └──────────────┘ │
│ sub sub item │
└─────────────────────┘"""
)
|
#!/usr/bin/env python
# Import relevant packages
import os, math, sys, argparse
# Main function
def main():
# Version info
vers = "Noise insertion script - v1.0 - Adds white noise to resistors based on temperature"
# Initiate the parser
parser = argparse.ArgumentParser(description=vers)
# Add possible parser arguments
parser.add_argument("input", help="the CIR input file")
parser.add_argument("-b", "--bandwidth", help="noise effective bandwidth. Default is 1 THz", default=1E12)
parser.add_argument("-t", "--temperature", help="temperature at which noise will be calculated. Default is 4.2 Kelvin", default=4.2)
parser.add_argument("-o", "--output", help="the output file name. Default is <name>_noise.cir")
parser.add_argument("-v", "--version", action='version', help="show script version", version=vers)
# Read arguments from the command line
args = parser.parse_args()
if(args.output == None):
args.output = os.path.splitext(args.input)[0] + "_noise" + os.path.splitext(args.input)[1]
T = float(args.temperature)
B = float(args.bandwidth)
Boltzmann = 1.38064852E-23
netlist_file = open(args.input, "r")
netlist = []
i = 0
while True:
i += 1
line = netlist_file.readline()
if not line:
break
line = line.rstrip('\n')
netlist.append(line)
tokens = line.split()
if tokens[0][0] == 'R':
R = float(tokens[3])
currentsource = []
currentsource.append("INOISE_" + tokens[0])
currentsource.append(tokens[1])
currentsource.append(tokens[2])
noise = math.sqrt(4 * Boltzmann * T / R)
currentsource.append("NOISE(" + str(noise) + " 0 " + str(1/B) + ")")
netlist.append("\t".join(currentsource))
netlist_file.close()
with open(args.output, 'w') as filehandle:
filehandle.writelines("%s\n" % line for line in netlist)
if __name__ == '__main__':
main() |
# pylint: skip-file
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
|
import configparser
import platform
linux_database_config_path = '/config/database.ini'
windows_database_config_path = 'D:\\database.ini'
def get_db_config():
config = configparser.ConfigParser()
config.sections()
if 'linux' in platform.system().lower():
config.read(linux_database_config_path)
else:
config.read(windows_database_config_path)
return {
'host': config['DATABASE']['host'],
'port': int(config['DATABASE']['port']),
'user': config['DATABASE']['user'],
'password': config['DATABASE']['password']
}
def get_crawl_mode():
config = configparser.ConfigParser()
config.sections()
config.read("config.ini")
return config['CRAWL_MODE']['crawl_mode']
if __name__ == '__main__':
print(get_db_config())
# print(get_crawl_mode())
|
#打开邮件样本
with open('E:\lessons\ML wu.n.g\coursera-ml-py-master\coursera-ml-py-master\machine-learning-ex6\ex6\emailSample1.txt'
, 'r'
) as f:
email = f.read()
print(email)
#处理邮件的方法,常将url,email address , dollars 等标准化,忽略其内容
'''
1. Lower-casing: 把整封邮件转化为小写。
2. Stripping HTML: 移除所有HTML标签,只保留内容。
3. Normalizing URLs: 将所有的URL替换为字符串 “httpaddr”.
4. Normalizing Email Addresses: 所有的地址替换为 “emailaddr”
5. Normalizing Dollars: 所有dollar符号($)替换为“dollar”.
6. Normalizing Numbers: 所有数字替换为“number”
7. Word Stemming(词干提取): 将所有单词还原为词源。例如,“discount”, “discounts”, “discounted” and “discounting”都替换为“discount”。
8. Removal of non-words: 移除所有非文字类型,所有的空格(tabs, newlines, spaces)调整为一个空格.
'''
import numpy as np
import matplotlib.pyplot as plt
from scipy.io import loadmat
from sklearn import svm
import pandas as pd
import re #regular expresion for e-mail processing
#英文分词算法 Porter stemmer
#from stemming.porter2 import stem
#英文分词算法
import nltk, nltk.stem.porter
#process the email(Exclude word stemming and removal of non-words)
def processEmaill(email):
#小写
emali = email.lower()
#移除html标签,[^],我认为有加号
email = re.sub('<[^<>]+>', ' ', email)
#匹配//后面不是空白字符的内容,遇到空白字符则停止 \s空白字符
email = re.sub('(http|https)://[^\s]*', 'httpaddr', email)
# '+' 和 '*'的区别
email = re.sub('[^\s]+@[^\s]+', 'emailaddr', email)
email = re.sub('[\$]+', 'dollar', email)
email = re.sub('[\d]+', 'number', email)
return email
#====================stem and removal of non-words
def emali2TokenList(email):
stemmer = nltk.stem.porter.PorterStemmer()
email = processEmaill(email)
#将邮件分为各个单词
tokens = re.split('[ \@\$\/\#\.\-\:\&\*\+\=\[\]\?\!\(\)\{\}\,\'\"\>\_\<\;\%]', email)
#遍历每个分割出来的内容
tokenlist = []
for token in tokens:
#删除任何非字母数字的字符
token = re.sub('[^a-zA-Z0-9]', '', token)
# Porter stem 提取词根
stemmed = stemmer.stem(token)
#去除空字符串''
if not len(token):
continue
tokenlist.append(stemmed)
return tokenlist
#===================Vocabulary List
def get_vocab_list():
vocab_dict = {}
with open('E:\lessons\ML wu.n.g\coursera-ml-py-master\coursera-ml-py-master\machine-learning-ex6\ex6\\vocab.txt') as f:
for line in f:
(val, key) = line.split()
vocab_dict[int(val)] = key
return vocab_dict
vocab = get_vocab_list()
print(vocab[9])
def email2VocabIndices(token, vocab):
#提取存在单词索引
#!!!!! 注意key的初始值 (报错key error)
index = [i for i in range(1, 1899) if vocab[i] in token]
return index
with open('E:\lessons\ML wu.n.g\coursera-ml-py-master\coursera-ml-py-master\machine-learning-ex6\ex6\spamSample1.txt', 'r') as emailpath:
path = emailpath.read()
#rint('len(vocab)=',len(vocab))
processEmaill(path)
token = emali2TokenList(path) #list
#print(token)
indices = email2VocabIndices(path, vocab)
#print(indices)
#==========================extracting features from Emails
def email2FeatureVector(email, vocab):
# 将email转化为词向量,n是vocab的长度。存在单词的相应位置的值置为1,其余为0
df = pd.read_table('E:\lessons\ML wu.n.g\coursera-ml-py-master\coursera-ml-py-master\machine-learning-ex6\ex6\spamSample1.txt'
, names = ['words'])
#change to form of array
voc = df.as_matrix()
print(voc)
#init the vector
vector = np.zeros(len(vocab))
voc_indices = email2VocabIndices(email, vocab)
#有单词的地方0置为1
for i in voc_indices:
vector[i] = 1
return vector
vector = email2FeatureVector(path, vocab)
print('length of vector = {}\nnum of non-zero = {}'.format(len(vector), int(vector.sum())))
print(vector)
#=======================traiining svm
'''Training set'''
mat1 = loadmat('E:\lessons\ML wu.n.g\coursera-ml-py-master\coursera-ml-py-master\machine-learning-ex6\ex6\spamTrain.mat')
X, y = mat1['X'], mat1['y'] #x(4000, 1899), y(4000, 1)
#print(X.shape, y.shape)
''' Test set'''
mat2 = loadmat('E:\lessons\ML wu.n.g\coursera-ml-py-master\coursera-ml-py-master\machine-learning-ex6\ex6\spamTest.mat')
Xtest, ytest = mat2['Xtest'], mat2['ytest']
clf = svm.SVC(C = 0.1, kernel = 'linear')
clf.fit(X,y.flatten())
predTrain = clf.score(X, y)
predTest = clf.score(Xtest, ytest)
print(predTest,predTrain)
|
"""
In Counting sort, the frequencies of distinct elements of the array to be sorted is counted
and stored in an auxiliary array, by mapping its value as an index of the auxiliary array.
Initialize the auxillary array Aux[] as 0.
Note: The size of this array should be ≥max(A[]).
Traverse array A and store the count of occurrence of each element in the appropriate
index of the Aux array, which means, execute Aux[A[i]]++ for each i, where i ranges
from [0,N−1].
Initialize the empty array sortedA[]
Traverse array Aux and copy i into sortedA for Aux[i] number of times where 0≤i≤max(A[]).
The array O(N) time and the resulting sorted array is also computed in O(N) time.
Aux[] is traversed in O(K) time. Therefore, the overall time complexity of counting
sort algorithm is O(N+K).
"""
def max_val(a1):
# a1.sort()
# return a1[-1]
# return sorted(a1)[-1]
n = a1[0]
for i in range(len(a1)):
if n < a1[i]:
n = a1[i]
return n
def count_sort(arr_param):
# finds the maximum value in array
p = max_val(arr_param) + 1
# initialize auxiliary array of size p
aux = [0] * p
c_sorted = [0] * len(arr_param)
# store the frequency of array elements in aux array
for j in arr_param:
aux[j] += 1
sort_id = 0
for q in range(len(aux)):
tmp = aux[q]
while tmp > 0:
c_sorted[sort_id] = q
sort_id += 1
tmp -= 1
return c_sorted
arr = []
print("Counting Sort\n")
m = int(input("Enter the number of elements>>"))
for k in range(m):
arr.append(int(input()))
# count_sort(arr)
# print("Unsorted Array:\n", arr)
print("Sorted array:\n", count_sort(arr))
|
import ipaddress
import re
from collections import defaultdict
from boardfarm.lib.linux_nw_utility import NwDnsLookup
from boardfarm.lib.regexlib import (
AllValidIpv6AddressesRegex,
ValidIpv4AddressRegex,
)
class DNS:
"""To get the dns IPv4 and IPv6"""
def __init__(self, device, device_options, aux_options, aux_url=None):
self.device = device
self.device_options = device_options
self.aux_options = aux_options
self.aux_url = aux_url
self.dnsv4 = defaultdict(list)
self.dnsv6 = defaultdict(list)
self.auxv4 = None
self.auxv6 = None
self.hosts_v4 = defaultdict(list)
self.hosts_v6 = defaultdict(list)
self._add_dns_hosts()
self._add_dnsv6_hosts()
if self.aux_options:
self._add_aux_hosts()
self._add_auxv6_hosts()
self.hosts_v4.update(self.dnsv4)
self.hosts_v6.update(self.dnsv6)
self.nslookup = NwDnsLookup(device)
def _add_dns_hosts(self):
if self.device_options:
final = None
if "wan-static-ip:" in self.device_options:
final = str(
re.search(
"wan-static-ip:" + "(" + ValidIpv4AddressRegex + ")",
self.device_options,
).group(1)
)
elif hasattr(self.device, "ipaddr"):
final = str(self.device.ipaddr)
if final == "localhost":
if hasattr(self.device, "gw"):
final = str(self.device.gw)
elif hasattr(self.device, "iface_dut"):
final = self.device.get_interface_ipaddr(self.device.iface_dut)
else:
final = None
if final:
self.dnsv4[self.device.name + ".boardfarm.com"].append(final)
def _add_dnsv6_hosts(self):
gwv6 = getattr(self.device, "gwv6", None)
if gwv6:
self.dnsv6[self.device.name + ".boardfarm.com"].append(str(gwv6))
def _add_aux_hosts(self):
self.auxv4 = ipaddress.IPv4Address(
re.search(
"wan-static-ip:" + "(" + ValidIpv4AddressRegex + ")",
self.aux_options,
).group(1)
)
self.dnsv4[self.device.name + ".boardfarm.com"].append(str(self.auxv4))
if self.aux_url:
self.dnsv4[self.aux_url].append(str(self.auxv4))
def _add_auxv6_hosts(self):
self.auxv6 = ipaddress.IPv6Address(
re.search(
"wan-static-ipv6:" + "(" + AllValidIpv6AddressesRegex + ")",
self.aux_options,
).group(1)
)
self.dnsv6[self.device.name + ".boardfarm.com"].append(str(self.auxv6))
if self.aux_url:
self.dnsv6[self.aux_url].append(str(self.auxv6))
def configure_hosts(
self,
reachable_ipv4: int,
unreachable_ipv4: int,
reachable_ipv6: int,
unreachable_ipv6: int,
):
"""
Method to create the given number of reachable and unreachable ACS domain IP's
:param reachable_ipv4: no.of reachable IPv4 address for acs url
:type reachable_ipv4: int
:param unreachable_ipv4: no.of unreachable IPv4 address for acs url
:type unreachable_ipv4: int
:param reachable_ipv6: no.of reachable IPv6 address for acs url
:type reachable_ipv6: int
:param unreachable_ipv6: no.of unreachable IPv6 address for acs url
:type unreachable_ipv6: int
"""
val_v4 = self.hosts_v4[self.device.name + ".boardfarm.com"][:reachable_ipv4]
val_v6 = self.hosts_v6[self.device.name + ".boardfarm.com"][:reachable_ipv6]
self.hosts_v4[self.device.name + ".boardfarm.com"] = val_v4
self.hosts_v6[self.device.name + ".boardfarm.com"] = val_v6
for val in range(unreachable_ipv4):
ipv4 = self.auxv4 + (val + 1)
self.hosts_v4[self.device.name + ".boardfarm.com"].append(str(ipv4))
for val in range(unreachable_ipv6):
ipv6 = self.auxv6 + (val + 1)
self.hosts_v6[self.device.name + ".boardfarm.com"].append(str(ipv6))
|
import asyncio
import re
from urllib.parse import urlparse
import time
import discord
import dns.resolver
from discord.ext import commands, tasks
from ink.core.command import squidcommand
from ink.core.context import Context
from ink.utils.db import RedisDict
from emoji import UNICODE_EMOJI
import numpy
import unicodedata
import json
import itertools
def grouper(n, iterable):
it = iter(iterable)
while True:
chunk = tuple(itertools.islice(it, n))
if not chunk:
return
yield chunk
def better_round(num: int, base: int = 5) -> int:
return base * round(num / base)
def principal_period(s):
i = (s + s).find(s, 1, -1)
return None if i == -1 else s[:i]
ZALGO_CHAR_CATEGORIES = ["Mn", "Me"]
def is_zalgo(s):
if len(s) == 0:
return False
word_scores = []
for word in s.split():
cats = [unicodedata.category(c) for c in word]
score = sum([cats.count(banned) for banned in ZALGO_CHAR_CATEGORIES]) / len(
word
)
word_scores.append(score)
total_score = numpy.percentile(word_scores, 75)
return total_score
class AutoModCheckFailure(commands.CommandError):
def __init__(self, check: str, context: commands.Context, message: str):
self.check = check
self.context = context
self.message = message
link_crazy = re.compile(
r"(?i)\b((?:https?:(?:/{1,3}|[a-z0-9%])|[a-z0-9.\-]+[.](?:com|net|org|edu|gov|mil|aero|asia|biz|cat|coop|info|int|jobs|mobi|museum|name|post|pro|tel|travel|xxx|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cs|cu|cv|cx|cy|cz|dd|de|dj|dk|dm|do|dz|ec|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|Ja|sk|sl|sm|sn|so|sr|ss|st|su|sv|sx|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw|dev|xyz|app)/)(?:[^\s()<>{}\[\]]+|\([^\s()]*?\([^\s()]+\)[^\s()]*?\)|\([^\s]+?\))+(?:\([^\s()]*?\([^\s()]+\)[^\s()]*?\)|\([^\s]+?\)|[^\s`!()\[\]{};:'"
+ '"'
+ r".,<>?«»“”‘’])|(?:(?<!@)[a-z0-9]+(?:[.\-][a-z0-9]+)*[.](?:com|net|org|edu|gov|mil|aero|asia|biz|cat|coop|info|int|jobs|mobi|museum|name|post|pro|tel|travel|xxx|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cs|cu|cv|cx|cy|cz|dd|de|dj|dk|dm|do|dz|ec|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|Ja|sk|sl|sm|sn|so|sr|ss|st|su|sv|sx|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)\b/?(?!@)))"
)
emoji_crazy = re.compile(
r"<(?P<animated>a?):(?P<name>[a-zA-Z0-9_]{2,32}):(?P<id>[0-9]{18,22})>"
)
invite_crazy = re.compile(
r"(https?://)?(www.)?(discord.(gg|io|me|li)|discordapp.com/invite)/[^\s/]+?(?=\b)"
)
def repeated_text(s):
# size of string
n = len(s)
m = dict()
for i in range(n):
string = ""
for j in range(i, n):
string += s[j]
if string in m.keys():
m[string] += 1
else:
m[string] = 1
# to store maximum freqency
maxi = 0
# To store string which has
# maximum frequency
maxi_str = ""
for i in m:
if m[i] > maxi:
maxi = m[i]
maxi_str = i
elif m[i] == maxi:
ss = i
if len(ss) > len(maxi_str):
maxi_str = ss
# return substring which has maximum freq
return maxi_str
class AutoMod(commands.Cog):
def __init__(self, bot):
self.bot: commands.AutoShardedBot = bot
self.message_purge_loop.start()
def cog_unload(self):
self.message_purge_loop.stop()
@tasks.loop(seconds=0.2)
async def message_purge_loop(self):
for channel in await self.bot.redis.smembers("purge:channels"):
data = await self.bot.redis.smembers(f"purge:{channel}")
await self.bot.redis.srem(f"purge:{channel}", *data)
await self.bot.redis.srem("purge:channels", channel)
if chn := self.bot.get_channel(int(channel)):
chunks = [discord.Object(id=int(i)) for i in data]
print(chunks)
for chunk in grouper(100, chunks):
print(
"deleting chunk of",
len(chunk),
"in",
chn.name,
"(",
chn.id,
")",
)
await chn.delete_messages(chunk)
@message_purge_loop.before_loop
async def waiter(self):
await self.bot.wait_until_ready()
@squidcommand("automod")
async def automod_cmd(self, ctx, check: str, choice: bool, action: str):
checks = [
"links",
"caps",
"mentions",
"emojis",
"spam",
"repeated_text",
"newlines",
"images",
"zalgo",
"all",
]
if check not in checks:
yield "invalid choice"
return
if check == "all":
async with ctx.storage as s:
for i in checks:
s[f"check_{i}"] = {"actions": {action: True}}
if choice:
async with ctx.storage as s:
s[f"check_{check}"] = {"actions": {action: True}}
else:
await ctx.storage.clear()
yield await ctx.storage.keys()
async def mass_delete_handle(self, ctx: Context):
await self.bot.redis.sadd("purge:channels", str(ctx.channel.id))
await self.bot.redis.sadd(f"purge:{ctx.channel.id}", str(ctx.message.id))
async def handle_checkfailure(self, error: AutoModCheckFailure, actions: dict):
print(
f"{error.check} check failed with message: {error.message}\n Message Content: {error.context.message.content}"
)
coros = []
ctx = error.context
for action, values in actions.items():
if action == "delete":
if ctx.channel.permissions_for(ctx.me).manage_messages:
coros.append(self.mass_delete_handle(ctx))
# await ctx.message.add_reaction("✅")
# if ctx.channel.permissions_for(ctx.me).send_messages and ctx.channel.permissions_for(ctx.me).embed_links:
# coros.append(ctx.send(embed=discord.Embed(color=self.bot.color, title=f"Automod {error.check}", description='\u200b' + error.message).set_author(icon_url=ctx.author.avatar.url, name=ctx.message.content[:10] + ('...' if len(ctx.message.content) > 10 else '')), delete_after=3))
if action == "infraction":
self.bot.dispatch(
"member_infraction", ctx.author, values.get("infractions", 1)
)
if action == "kick":
if (
ctx.me.guild_permissions.kick_members
and ctx.me.top_role > ctx.author.top_role
):
coros.append(
ctx.author.kick(
reason=f"Automod Check [{error.check}]:\n{error.message}"
)
)
if action == "ban":
if (
ctx.me.guild_permissions.ban_members
and ctx.me.top_role > ctx.author.top_role
):
coros.append(
ctx.author.ban(
reason=f"Automod Check [{error.check}]:\n{error.message}"
)
)
if action == "quarantine":
self.bot.dispatch("member_quarantine", ctx.author, values)
if coros:
resp = await asyncio.gather(*coros, return_exceptions=True)
print(resp)
async def validate_bypass(self, ctx: commands.Context, bypass: dict):
for check, group in bypass.items():
if check == "role":
id = group.get("id")
if id in [i.id for i in ctx.author.roles]:
return True
if check == "permissions":
if getattr(
ctx.channel.permissions_for(ctx.author), group.get("id"), False
):
return True
if check == "member":
if ctx.author.id == group.get("id"):
return True
if check == "channel":
if ctx.channel.id == group.get("id"):
return True
return False
# Checks
async def check_links(self, context: commands.Context, data: dict):
amount = data.get("amount", 1)
per = data.get("per", 5)
links = link_crazy.findall(context.message.content)
linkCount = 0
for link in set(links):
p = urlparse(link)
link = p.netloc or link.split("/")[0]
try:
dns.resolver.resolve(link)
except Exception as exc:
print("link failed", exc)
# not a link
continue
else:
linkCount += 1
if not linkCount:
return
key = f"check_links:{context.guild.id}:{context.author.id}:bucket-{better_round(int(time.time()), base=per)}" # implementing efficient caching
actualLinks = int((await self.bot.redis.get(key)) or 0) + linkCount
await self.bot.redis.set(key, actualLinks, expire=per * 2)
if actualLinks >= amount:
raise AutoModCheckFailure("links", context, f"Link detected ({link})")
async def check_invites(self, context: commands.Context, data: dict):
amount = data.get("amount", 1)
per = data.get("per", 5)
invites = invite_crazy.findall(context.message.content)
if not invites:
return
key = f"check_invites:{context.guild.id}:{context.author.id}:bucket-{better_round(int(time.time()), base=per)}" # implementing efficient caching
invites = int((await self.bot.redis.get(key)) or 0) + len(set(invites))
if invites:
await self.bot.redis.set(key, invites, expire=per * 2)
if invites >= amount:
raise AutoModCheckFailure("invite", context, f"Invite")
async def check_caps(self, context: commands.Context, data: dict):
percent = data.get("percent", 70)
if not context.message.content:
return
caps = int(
100
* (
len([i for i in context.message.content if i.isupper()])
/ len(context.message.content)
)
)
if caps > percent and len(context.message.content) > 3:
print(caps, "%")
raise AutoModCheckFailure(
"caps", context, f"Excessive use of caps ({caps}%)"
)
async def check_zalgo(self, context: commands.Context, data: dict):
percent = data.get("percent", 70)
async def check_zalgo(self, context: commands.Context, data: dict):
percent = data.get("percent", 70)
async def check_newlines(self, context: commands.Context, data: dict):
amount = data.get("amount", 15)
per = data.get("per", 3)
key = f"check_newlines:{context.guild.id}:{context.author.id}:bucket-{better_round(int(time.time()), base=per)}" # implementing efficient caching
newlines = int(
(await self.bot.redis.get(key)) or 0
) + context.message.content.strip().count("\n")
if newlines:
await self.bot.redis.set(key, newlines, expire=per * 2)
if newlines > amount:
raise AutoModCheckFailure(
"newlines", context, f"Too many newlines ({newlines}/{per}s)"
)
async def check_mentions(self, context: commands.Context, data: dict):
if not context.message.mentions:
return
amount = data.get("amount", 5)
per = data.get("per", 5)
key = f"check_mentions:{context.guild.id}:{context.author.id}:bucket-{better_round(int(time.time()), base=per)}" # implementing efficient caching
mentions = int((await self.bot.redis.get(key)) or 0) + len(
context.message.mentions
)
if mentions:
await self.bot.redis.set(key, mentions, expire=per * 2)
print("user mentions", mentions)
if mentions > amount:
raise AutoModCheckFailure(
"mentions", context, f"Too many mentions [{mentions}]"
)
async def check_emojis(self, context: commands.Context, data: dict):
amount = data.get("amount", 7)
per = data.get("per", 5)
key = f"check_emojis:{context.guild.id}:{context.author.id}:bucket-{better_round(int(time.time()), base=per)}"
emoji_count = sum(
1 for _ in emoji_crazy.finditer(context.message.content)
) + len([i for i in context.message.content if i in UNICODE_EMOJI["en"]])
if not emoji_count:
return
emojis = max(int((await self.bot.redis.get(key)) or 0), 0) + emoji_count
await self.bot.redis.set(key, emojis, expire=per * 2)
print("emoji count", emojis)
if emojis > amount:
raise AutoModCheckFailure("emojis", context, f"Too many emojis [{emojis}]")
async def check_spam(self, context: commands.Context, data: dict):
amount = data.get("amount", 5)
per = data.get("per", 3)
key = f"check_spam:{context.guild.id}:{context.author.id}:bucket-{better_round(int(time.time()), base=per)}"
messages = max(int((await self.bot.redis.get(key)) or 0), 0) + 1
await self.bot.redis.set(key, messages, expire=per * 2)
if messages > amount:
raise AutoModCheckFailure(
"spam", context, f"Sending messages too quickly ({messages:,}/{per:,}s)"
)
async def check_images(self, context: commands.Context, data: dict):
amount = data.get("amount", 3)
per = data.get("per", 8)
if not context.message.attachments:
return
key = f"check_images:{context.guild.id}:{context.author.id}:bucket-{better_round(int(time.time()), base=per)}"
images = max(int((await self.bot.redis.get(key)) or 0), 0) + len(
context.message.attachments
)
await self.bot.redis.set(key, images, expire=per * 2)
if images > amount:
raise AutoModCheckFailure(
"images", context, f"Sending images too quickly ({images:,}/{per:,}s)"
)
async def check_repeated_text(self, context: commands.Context, data: dict):
amount = data.get("amount", 3)
per = data.get("per", 30)
# multiple messages
key = f"check_repeated_text:{context.guild.id}:bucket-{better_round(int(time.time()), base=per)}"
await self.bot.redis.hincrby(key, context.message.content.strip(), 1)
await self.bot.redis.expire(key, per + 1)
amn = int(await self.bot.redis.hget(key, context.message.content.strip()))
c = context.message.content.strip().lower()
if amn > amount:
print("repeated text:", amn, c)
t = context.message.content[:8] + ("..." if len(c) >= 8 else "")
raise AutoModCheckFailure(
"repeated_text", context, f"Repeated text [{t}] ({amn}/{per}s)"
)
# # single message
repeated = repeated_text(c)
if len(repeated.strip()) <= 1:
return # useless
if repeated and (amn := c.count(repeated)) > amount:
print("repeated second check", "[", repeated, "]", context.message.content)
t = context.message.content[:8] + (
"..." if len(context.message.content) >= 8 else ""
)
raise AutoModCheckFailure(
"repeated_text", context, f"Repeated text [{t}] ({amn}/{per}s)"
)
@commands.Cog.listener("on_context")
async def automod(self, ctx: Context) -> None:
if not ctx.message.guild:
return
if ctx.message.author.bot:
return
ctx._storage = RedisDict(
self.bot.redis, prefix=f"storage:{self.qualified_name}:{ctx.guild.id}"
)
checkNames = await ctx.storage.keys()
checks = {}
for checkName in filter(lambda x: x.startswith("check_"), checkNames):
if check := getattr(self, checkName, None):
checks[checkName] = check
for checkName, check in checks.items():
checkData = await ctx.storage[checkName]
bypass = await self.validate_bypass(ctx, checkData.get("bypass", {}))
if bypass:
continue
try:
await check(ctx, checkData)
except AutoModCheckFailure as exception:
await self.handle_checkfailure(exception, checkData.get("actions"))
break
@squidcommand("check")
@commands.guild_only()
async def checkmessage(self, ctx, message: discord.Message):
if message.author.bot:
yield "Cannot check bot messages"
return
alt_ctx = await ctx.bot.get_context(message)
checkNames = await ctx.storage.keys()
checks = {}
for checkName in filter(lambda x: x.startswith("check_"), checkNames):
if check := getattr(self, checkName, None):
checks[checkName] = check
passed = []
failed = []
for checkName, check in checks.items():
checkData = await ctx.storage[checkName]
bypass = await self.validate_bypass(ctx, checkData.get("bypass", {}))
if bypass:
passed.append(checkName)
continue
try:
await check(alt_ctx, checkData)
except AutoModCheckFailure as exception:
failed.append((checkName, exception))
else:
passed.append(checkName)
yield discord.Embed(
title="Checks Complete",
description="```diff\n# Passed\n+"
+ "\n+".join(passed)
+ ("\n-" if failed else "")
+ "\n-".join([f"{name}: {e.message}" for (name, e) in failed])
+ "\n```",
)
|
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Important security settings
ALLOWED_HOSTS = []
DEBUG = False
SECRET_KEY = os.environ['SECRET_KEY']
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'debug_toolbar',
)
# Middleware
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
# URLs
ROOT_URLCONF = 'knyght.urls'
# Templates
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
# WSGI
WSGI_APPLICATION = 'knyght.wsgi.application'
# Database
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'knyght.db'),
}
}
# Internationalization
LANGUAGE_CODE = 'en-gb'
TIME_ZONE = 'Europe/London'
USE_I18N = False
USE_L10N = True
USE_TZ = True
# Static files
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
# Debug toolbar
def show_toolbar(request):
return request.user.is_superuser
DEBUG_TOOLBAR_CONFIG = {
'SHOW_TOOLBAR_CALLBACK': 'knyght.settings.show_toolbar',
}
DEBUG_TOOLBAR_PATCH_SETTINGS = False
|
import FWCore.ParameterSet.Config as cms
process = cms.Process("GeometryXMLWriter")
process.source = cms.Source("EmptyIOVSource",
lastValue = cms.uint64(1),
timetype = cms.string('runnumber'),
firstValue = cms.uint64(1),
interval = cms.uint64(1)
)
process.DDDetectorESProducer = cms.ESSource("DDDetectorESProducer",
confGeomXMLFiles = cms.FileInPath('Geometry/CMSCommonData/data/dd4hep/cmsExtendedGeometry2021.xml'),
appendToDataLabel = cms.string('make-payload')
)
process.DDCompactViewESProducer = cms.ESProducer("DDCompactViewESProducer",
appendToDataLabel = cms.string('make-payload')
)
process.BigXMLWriter = cms.EDAnalyzer("OutputDD4hepToDDL",
fileName = cms.untracked.string("./geSingleBigFile.xml")
)
process.maxEvents = cms.untracked.PSet(
input = cms.untracked.int32(1)
)
process.p1 = cms.Path(process.BigXMLWriter)
|
from typing import TYPE_CHECKING
from datetime import datetime
import uuid
from sqlalchemy import Column, Integer, String, Boolean, DateTime
from sqlalchemy.orm import relationship
from sqlalchemy.sql.schema import ForeignKey
from fastapi_utils.guid_type import GUID
from app.db.base_class import Base
class User(Base):
nickname = Column(String(20), unique=True, index=True, nullable=False)
hashed_password = Column(String(200), nullable=False)
|
# import dash
# from dash import dcc
# from dash import html
# from dash.dependencies import Output, Input, State
# import dash_bootstrap_components as dbc
# # import dash_datetimepicker as dash_dt
# # import plotly.express as px
# # import plotly.graph_objects as go
# import pandas as pd
# from dtools import wdr_ticker, wdr_multi_ticker, indexed_vals, ext_str_lst
# from d_charts import quant_chart, pwe_line_chart, pwe_hist, calc_interval, pwe_return_dist_chart, pwe_box, pwe_heatmap # single_line_chart
# from pwe.analysis import Security
# from pwe.pwetools import str_to_dt, to_utc
# from sqlalch import all_tickers
# from ntwrkx import plot_mst
# from datetime import datetime, timedelta
# # import pytz
# from werkzeug.security import generate_password_hash, check_password_hash
# import warnings
# import os
# from flask_login import login_user, logout_user, current_user, LoginManager, UserMixin
# import configparser
# from sqlalch import init_engine, db_connect # db_session
# from models import auth_uri, db_auth, Users
# try:
# from secret_settings import SECRET_KEY
# except ModuleNotFoundError:
# pass
# warnings.filterwarnings("ignore")
# engine = init_engine(auth_uri)
# conn = db_connect(engine)
# config = configparser.ConfigParser()
# labels, symbols = all_tickers()
# # Define Dash App — https://www.bootstrapcdn.com/bootswatch/
# app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP], # LUX, BOOTSTRAP
# meta_tags=[{'name': 'viewport',
# 'content': 'width=device-width, initial-scale=1.0'}] # meta tags for mobile view
# )
# server = app.server
# app.config.suppress_callback_exceptions = True
# # Config auth db
# try:
# cookie_key = os.getenv('SECRET_KEY')
# if not cookie_key:
# cookie_key = SECRET_KEY
# except:
# cookie_key = SECRET_KEY
# server.config.update(
# # SECRET_KEY=os.urandom(12).hex(),
# SECRET_KEY=cookie_key,
# SQLALCHEMY_DATABASE_URI=auth_uri,
# SQLALCHEMY_TRACK_MODIFICATIONS=False
# )
# db_auth.init_app(server)
# # Setup LoginManager for server
# login_manager = LoginManager()
# login_manager.session_protection = "strong"
# login_manager.init_app(server)
# login_manager.login_view = '/login'
# # Define User
# class Users(UserMixin, Users):
# pass
# create = html.Div(
# [dbc.Row(
# dbc.Col(
# [html.H1('Create PWE Markets Account'),
# dcc.Location(id='create_user', refresh=True),
# dcc.Input(id="username", type="text",
# placeholder="user name", maxLength=15),
# dcc.Input(id="password", type="password", placeholder="password"),
# dcc.Input(id="email", type="email",
# placeholder="email", maxLength=50),
# html.Button('Create User', id='submit-val',
# n_clicks=0, className="create_user_button"),
# html.Div(id='container-button-basic')],
# xs=7, sm=5, md=7, lg=8, xl=7, xxl=5),
# className="g-3", justify='center', align='center', style={"height": "61.8vh"})
# ])
# create_success = html.P(
# '''Account successfully created.''', id='create_success')
# login = html.Div(
# [dbc.Row(
# dbc.Col(
# [dcc.Location(id='url_login', refresh=True),
# html.H2('''Please log in to continue:''', id='h1'),
# dcc.Input(placeholder='Enter your username', type='text',
# id='uname-box', className='uname_box'),
# dcc.Input(placeholder='Enter your password',
# type='password', id='pwd-box', className='pwd_box'),
# html.Button(children='Login', n_clicks=0, type='submit',
# id='login-button', className='login_button'),
# html.Div(children='', id='login-text')],
# xs=6, sm=6, md=7, lg=8, xl=4, xxl=3),
# className="g-3", justify='center', align='center', style={"height": "61.8vh"})
# ])
# success = html.Div(
# [dbc.Row(
# dbc.Col(
# [dcc.Location(id='url_login_success', refresh=True),
# html.Div(
# [html.H2('Login successful.'),
# html.Br(),
# html.P('Select a dashboard'),
# dcc.Link('PWE Markets Dashboard',
# href='/markets', className='nav_href', id='markets_href')
# ]),
# html.Div(
# [html.Br(),
# html.Button(id='back-button', children='Go back',
# n_clicks=0, className='back_button')
# ])], xs=6, sm=6, md=6, lg=5, xl=4, xxl=2),
# className="g-3", justify='center', align='center', style={"height": "61.8vh"})
# ])
# failed = html.Div(
# [dcc.Location(id='url_login_f', refresh=True),
# html.Div(
# [html.H2('Log in Failed. Please try again.'),
# html.Br(),
# html.Div([login]),
# html.Br(),
# html.Button(id='back-button', children='Go back', n_clicks=0)
# ])
# ])
# logout = html.Div(
# [dbc.Row(
# dbc.Col(
# [dcc.Location(id='url_logout', refresh=True),
# html.Br(),
# html.Div(
# html.H2('You have been logged out. Click below to log back in.')),
# html.Br(),
# html.Div(
# [login]),
# html.Button(id='back-button', children='Go back', n_clicks=0)],
# xs=8, sm=8, md=8, lg=8, xl=8, xxl=6),
# className="g-3", justify='center', align='center', style={"height": "61.8vh"})
# ])
# data = html.Div([dcc.Dropdown(
# id='test_dropdown',
# options=[{'label': i, 'value': i} for i in ['Day 1', 'Day 2']],
# value='Day 1'), html.Br(), html.Div([dcc.Graph(id='test_graph')])
# ])
# # spinner = html.Div(
# # [dbc.Spinner(id='load_spinner', children="url_markets", color="primary", type="border", fullscreen=True, # size="lg",
# # spinner_style={"width": "10rem", "height": "10rem"}, spinnerClassName="load_spinner"),
# # ]
# # )
# # # Dash Layout — https://hackerthemes.com/bootstrap-cheatsheet/
# # app.layout = dbc.Container([
# markets = html.Div([dcc.Location(id='url_markets', refresh=True),
# dbc.Row([
# dbc.Col(html.H1("PWE Markets Dashboard",
# className='text-center text-primary mb-4 header-1'),
# width={"size": 10, "order": 1, "offset": 1}),
# dbc.Col(html.Button('Log Out', id='log-out-btn',
# n_clicks=0, className="logout_btn"), width={"size": 1, "order": 2}),
# ]),
# dbc.Row([
# dbc.Col([
# html.Div(id="sec-alert", children=[]),
# dcc.Dropdown(id='sec-drpdwn', multi=False, value=None,
# options=[{'label': x, 'value': y}
# for x, y in zip(labels, symbols)], searchable=True, placeholder='Select security...',
# # persistence_type= session, memory
# persistence=True, persistence_type='session',
# ),
# dcc.Store(id='intermediate-value1'),
# # html.Div(
# # [dash_dt.DashDatetimepicker(id="dt-picker-range", utc=True, locale="en-GB"), html.Div(id="output-dt-picker-range")]
# # ),
# dcc.DatePickerRange(
# id='dt-picker-range', # ID for callback
# calendar_orientation='horizontal', # vertical or horizontal
# day_size=39, # Size of calendar image. Default is 39
# # text that appears when no end date chosen
# end_date_placeholder_text="End Date",
# with_portal=False, # If True, calendar opens in a full screen overlay portal
# # Display of calendar when open (0 = Sunday)
# first_day_of_week=0,
# reopen_calendar_on_clear=True,
# # True or False for direction of calendar (right to left)
# is_RTL=False,
# clearable=True, # Whether the calendar is clearable
# number_of_months_shown=1, # Number of months displayed in dropdown
# min_date_allowed=datetime(1900, 1, 1),
# max_date_allowed=datetime.now().date(),
# initial_visible_month=datetime(
# 2021, 1, 1), # Default visible month
# start_date=(datetime.utcnow() - \
# timedelta(days=365)).date(),
# end_date=datetime.now().date(),
# display_format='D MMM YYYY', # Do
# # How calendar headers are displayed on open.
# month_format='MMMM, YYYY',
# # Minimum allowable days between start and end.
# minimum_nights=1,
# # Whether the user's selected dates will be cached.
# persistence=True,
# # What will be cached
# persisted_props=['start_date'],
# persistence_type='session', # session, local, or memory. Default is 'local'
# updatemode='singledate' # singledate or bothdates. Select when callback is triggered
# ),
# dcc.Checklist(id='candle_checklist',
# options=[
# {'label': 'Legend',
# 'value': 'showlegend'},
# {'label': 'Volume',
# 'value': 'showvol'},
# {'label': 'Boll. Bands',
# 'value': 'showboll'},
# {'label': 'RSI', 'value': 'showrsi'},
# {'label': 'AMA', 'value': 'showama'},
# {'label': 'Kalman Filter',
# 'value': 'showkal'},
# ],
# value=['showvol'],
# labelStyle={'display': 'inline-block', "margin-left": "6.18px",
# "margin-right": "3.82px", "color": "rgb(51, 51, 51)"},
# inputStyle={
# 'background-color': 'rgb(220, 187, 166)'},
# className='candle_checklist', inputClassName="checkbox", persistence=True, persistence_type='session',
# ),
# dcc.Graph(id='cand-fig', figure={}, config={'scrollZoom': False, 'doubleClick': 'reset',
# # 'modeBarButtonsToRemove': ['pan2d','select2d'], modeBarButtonsToAdd
# 'showTips': True, 'displayModeBar': 'hover', 'watermark': False, 'displaylogo': False})
# ], # width={'size':5, 'offset':1, 'order':1},
# xs=12, sm=12, md=12, lg=5, xl=5
# ),
# dbc.Col([
# html.Div(id="multi-sec-alert", children=[]),
# dcc.Dropdown(id='sec-drpdwn2', multi=True, value=[],
# options=[{'label': x, 'value': x}
# for x in symbols], placeholder='Select security...',
# persistence=True, persistence_type='session',
# ),
# dcc.Store(id='intermediate-value2'),
# dcc.Store(id='avlbl-sec-list'),
# dcc.Graph(id='line-fig', figure={}, config={'scrollZoom': False, 'doubleClick': 'reset',
# 'showTips': True, 'displayModeBar': 'hover', 'watermark': False, 'displaylogo': False}),
# ], # width={'size':5, 'offset':0, 'order':2},
# xs=12, sm=12, md=12, lg=5, xl=5
# ),
# ], className="g-3", justify='center'), # justify: start_date,center,end_date,between,around
# dbc.Row([
# dbc.Col([
# dcc.Graph(id='sec-hist', figure={}, config={'scrollZoom': False, 'doubleClick': 'reset',
# 'showTips': True, 'displayModeBar': 'hover', 'watermark': False, 'displaylogo': False}),
# ], # width={'size':5, 'offset':1},
# xs=12, sm=12, md=12, lg=5, xl=5
# ),
# dbc.Col([
# html.Div([
# dcc.Input(id="mst_corr_thrsld", type="number", placeholder="0.05", value=float(0.05), debounce=True, required=False, min=float(0.0), max=float(1.0), step=float(0.05),
# # pattern='/^\d+$/',
# inputMode='numeric', persistence=True, persistence_type='session', className='mst_corr_thrsld',
# style={'display': 'inline-block', "margin-left": "6.18px", "margin-right": "2.36px"}),
# html.P('minimum correlation threshold', id="mst_corr_thrsld_text", lang="en", className="mst_corr_thrsld_text",
# title="Set the minimum correlation threshold to reduce number of graph edges in the minimum spanning tree (between 0 and 1).",
# style={'display': 'inline-block', "margin-left": "6.18px", "margin-right": "3.82px"})
# ]),
# dcc.Graph(id='corr-mst', figure={}, config={'scrollZoom': False, 'doubleClick': 'reset',
# 'showTips': True, 'displayModeBar': 'hover', 'watermark': False, 'displaylogo': False}),
# ], # width={'size':5, 'offset':0, 'order':2},
# xs=12, sm=12, md=12, lg=5, xl=5
# ),
# ], align="center", justify='center'), # Vertical: start_date, center, end_date
# dbc.Row([
# dbc.Col([
# html.Div([
# dcc.Input(id="vol_window", type="number", placeholder="30", value=30, debounce=True, required=False, min=2, max=10000000000, step=1,
# inputMode='numeric', pattern='/^\d+$/', persistence=True, persistence_type='session', className='vol_window',
# style={'display': 'inline-block', "margin-left": "6.18px", "margin-right": "2.36px"}),
# html.P('period rolling window', id="vol_window_text", lang="en", className="vol_window_text",
# title="Number of periods in the rolling window used to calculate the realised volatility.",
# style={'display': 'inline-block', "margin-left": "6.18px", "margin-right": "3.82px"})
# ]),
# dcc.Graph(id='real-vol', figure={}, config={'scrollZoom': False, 'doubleClick': 'reset',
# 'showTips': True, 'displayModeBar': 'hover', 'watermark': False, 'displaylogo': False}),
# ], # width={'size':5, 'offset':1},
# xs=12, sm=12, md=12, lg=5, xl=5
# ),
# dbc.Col([
# dcc.Graph(id='box-plt', figure={}, config={'scrollZoom': False, 'doubleClick': 'reset',
# 'showTips': True, 'displayModeBar': 'hover', 'watermark': False, 'displaylogo': False}),
# ], # width={'size':5, 'offset':0, 'order':2},
# xs=12, sm=12, md=12, lg=5, xl=5
# ),
# ], align="center", justify='center'), # Vertical: start_date, center, end_date
# dbc.Row([
# dbc.Col([
# html.Div([
# dcc.Input(id="yz_window", type="number", placeholder="30", value=30, debounce=True, required=False, min=2, max=10000000000, step=1,
# inputMode='numeric', pattern='/^\d+$/', persistence=True, persistence_type='session', className='yz_window',
# style={'display': 'inline-block', "margin-left": "6.18px", "margin-right": "2.36px"}),
# html.P('period rolling window', id="yz_window_text", lang="en", className="yz_window_text",
# title="Number of periods in the rolling window used to calculate Yang-Zhang Volatility Estimator.",
# style={'display': 'inline-block', "margin-left": "6.18px", "margin-right": "3.82px"})
# ]),
# dcc.Graph(id='yz-vol', figure={}, config={'scrollZoom': False, 'doubleClick': 'reset',
# 'showTips': True, 'displayModeBar': 'hover', 'watermark': False, 'displaylogo': False}),
# ], # width={'size':5, 'offset':1},
# xs=12, sm=12, md=12, lg=5, xl=5
# ),
# dbc.Col([
# dcc.Graph(id='heatmap', figure={}, config={'scrollZoom': False, 'doubleClick': 'reset',
# 'showTips': True, 'displayModeBar': 'hover', 'watermark': False, 'displaylogo': False}),
# ], # width={'size':5, 'offset':0, 'order':2},
# xs=12, sm=12, md=12, lg=5, xl=5
# ),
# ], align="center", justify='center'), # Vertical: start_date, center, end_date
# ]) # , fluid=True)
# # app.layout = dbc.Container([
# # dcc.Location(id='url', refresh=False),
# # html.Div(id='page-content', className='content')
# # ], fluid=True)
# app.layout = dbc.Container([
# html.Div(
# [dbc.Spinner(id='load_spinner', children=[
# dcc.Location(id='url', refresh=False),
# html.Div(id='page-content', className='content')
# ], color="rgb(220, 187, 166)", type="border", fullscreen=True, # size="lg",
# spinner_style={"width": "3rem", "height": "3rem"}, spinnerClassName="load_spinner"),
# ]
# )], fluid=True)
# app.validation_layout = html.Div([
# create,
# create_success,
# login,
# success,
# failed,
# logout,
# markets,
# ])
# # Callbacks (connect components)
# # --------------------------------------------
# # callback for reloading user object
# @ login_manager.user_loader
# def load_user(user_id):
# print("LOADED USER ID:", user_id)
# return Users.query.get(int(user_id))
# # return Users.query.filter_by(id=user.id).first()
# @ app.callback(
# Output('page-content', 'children'),
# [Input('url', 'pathname')])
# def display_page(pathname):
# if pathname == '/':
# if current_user.is_authenticated:
# return markets
# else:
# return login
# elif pathname == '/login':
# if current_user.is_authenticated:
# return markets
# else:
# return login
# elif pathname == '/create_account':
# return create
# elif pathname == '/success':
# if current_user.is_authenticated:
# return success
# else:
# return failed
# elif pathname == '/markets':
# if current_user.is_authenticated:
# return markets
# else:
# return login
# elif pathname == '/data':
# if current_user.is_authenticated:
# return data
# else:
# return login
# elif pathname == '/logout':
# if current_user.is_authenticated:
# logout_user()
# return logout
# else:
# return logout
# else:
# return '404'
# # @app.callback(
# # Output("load_spinner", "children"),
# # Input("markets_href", "is_loading")
# # )
# # test callback for sample chart page
# @ app.callback(
# [Output('test_graph', 'figure')], [Input('test_dropdown', 'value')])
# def update_graph(dropdown_value):
# if dropdown_value == 'Day 1':
# return [{'layout': {'title': 'Graph for Security 1'}, 'data': [{'x': [1, 2, 3, 4], 'y': [4, 1, 2, 1]}]}]
# else:
# return [{'layout': {'title': 'Graph for Security 2'}, 'data': [{'x': [1, 2, 3, 4], 'y': [2, 3, 2, 4]}]}]
# # Load single security dataframe
# @ app.callback(
# [Output('intermediate-value1', 'data'),
# Output("sec-alert", "children")],
# [Input('sec-drpdwn', 'value'),
# Input('dt-picker-range', 'start_date'),
# Input('dt-picker-range', 'end_date')]
# )
# def get_data1(sltd_sec, start_date, end_date):
# if sltd_sec:
# if len(sltd_sec) > 0:
# start_date = str_to_dt(start_date, dayfirst=False)
# if start_date.tzinfo == None:
# start_date = to_utc(start_date)
# if start_date:
# print("START DATE:", start_date)
# end_date = str_to_dt(end_date)
# if end_date.tzinfo == None:
# end_date = to_utc(end_date)
# if end_date:
# print("END DATE:", end_date)
# alert = dbc.Alert(f"No data available for {sltd_sec}", color="dark", # dark danger
# dismissable=True, duration=6000, class_name="sec-alert", fade=True)
# # use dismissable or duration=5000 for alert to close in x milliseconds
# try:
# df1 = wdr_ticker(sltd_sec, start_date,
# end_date, source='stooq', save_csv=True)
# if df1.empty:
# return dash.no_update, alert
# except:
# print("Error reading data from API")
# return dash.no_update, alert
# # html.Div(f"No data available for {sltd_sec}")
# json1 = df1.to_json(date_format='iso', orient='split')
# return json1, dash.no_update
# elif (not sltd_sec) or (len(sltd_sec) == 0):
# raise dash.exceptions.PreventUpdate
# # return dash.no_update, alert
# # Load multi-security dataframe
# @ app.callback(
# [Output('intermediate-value2', 'data'),
# Output('avlbl-sec-list', 'data'),
# Output("multi-sec-alert", 'children')],
# [Input('sec-drpdwn2', 'value'),
# Input('dt-picker-range', 'start_date'),
# Input('dt-picker-range', 'end_date')]
# )
# def get_data2(sltd_sec, start_date, end_date):
# if sltd_sec:
# if len(sltd_sec) > 0:
# print(sltd_sec)
# start_date = str_to_dt(start_date, dayfirst=False)
# if start_date.tzinfo == None:
# start_date = to_utc(start_date)
# if start_date:
# print("START DATE:", start_date)
# end_date = str_to_dt(end_date)
# if end_date.tzinfo == None:
# end_date = to_utc(end_date)
# if end_date:
# print("END DATE:", end_date)
# try:
# df2, missing_secs = wdr_multi_ticker(sltd_sec, start_date,
# end_date, source='stooq', price='Close', save_csv=True)
# print(missing_secs)
# if missing_secs:
# avlbl_sec_lst = [
# x for x in sltd_sec if x not in missing_secs]
# print(avlbl_sec_lst)
# else:
# avlbl_sec_lst = sltd_sec
# alert = dbc.Alert(f"No data available for {ext_str_lst(missing_secs)}", color="dark", # dark danger
# dismissable=True, duration=6000, class_name="sec-alert", fade=True)
# if df2.empty:
# return dash.no_update, avlbl_sec_lst, alert
# else:
# json2 = df2.to_json(date_format='iso', orient='split')
# if missing_secs:
# return json2, avlbl_sec_lst, alert
# except:
# print("Error reading data from API")
# raise dash.exceptions.PreventUpdate
# return json2, avlbl_sec_lst, dash.no_update
# elif (not sltd_sec) or (len(sltd_sec) == 0):
# raise dash.exceptions.PreventUpdate
# # Candle chart
# @ app.callback(
# Output('cand-fig', 'figure'),
# [Input('sec-drpdwn', 'value'),
# Input('intermediate-value1', 'data'),
# Input('candle_checklist', 'value')
# # Input('dt-picker-range', 'start_date'),
# # Input('dt-picker-range', 'end_date')
# ]
# )
# def update_graph(sltd_sec, json1, quant_studies):
# if sltd_sec:
# if len(sltd_sec) > 0:
# if json1 != None:
# df1 = pd.read_json(json1, orient='split')
# if not df1.empty:
# # df1['DateTime'] = pd.to_datetime(df1['DateTime'])
# ticker = sltd_sec
# start_date = df1.index.min()
# auto_start = start_date
# end_date = df1.index.max()
# auto_end = end_date
# # plt_int = single_line_chart(df['Close'], start_date=start_date, end_date=end_date, kind='scatter',
# # title=f'{ticker} - {srt_start}:{srt_end}', ticker=ticker, yTitle='USD', showlegend=False,
# # theme='white', auto_start=srt_start, auto_end=None, connectgaps=False, annots=None, annot_col=None)
# # if 'showlegend' in quant_studies:
# # showlegend = True
# # else:
# # showlegend = False
# showlegend = True if 'showlegend' in quant_studies else False
# showvol = True if 'showvol' in quant_studies else False
# showboll = True if 'showboll' in quant_studies else False
# showrsi = True if 'showrsi' in quant_studies else False
# showama = True if 'showama' in quant_studies else False
# showkal = True if 'showkal' in quant_studies else False
# plt_int = quant_chart(df1, start_date, end_date, ticker=ticker, title=None, theme='white', auto_start=auto_start, auto_end=auto_end,
# asPlot=False, asFigure=True, showlegend=showlegend, boll_std=2, boll_periods=20, showboll=showboll, showrsi=showrsi,
# rsi_periods=14, showama=showama, ama_periods=9, showvol=showvol, show_range=False, annots=None, textangle=0,
# file_tag=None, support=None, resist=None, annot_font_size=6, title_dates=False, title_time=False,
# chart_ticker=True, top_margin=0.9, spacing=0.08, range_fontsize=9.8885, title_x=0.5,
# title_y=0.933, arrowhead=6, arrowlen=-50, showkal=showkal)
# return plt_int
# else:
# raise dash.exceptions.PreventUpdate
# else:
# raise dash.exceptions.PreventUpdate
# elif (not sltd_sec) or (len(sltd_sec) == 0):
# raise dash.exceptions.PreventUpdate
# # Line chart - multiple
# @ app.callback(
# Output('line-fig', 'figure'),
# [
# # Input('sec-drpdwn2', 'value'),
# Input('intermediate-value2', 'data'),
# Input('avlbl-sec-list', 'data'),
# # Input('dt-picker-range', 'start_date'),
# # Input('dt-picker-range', 'end_date')
# ]
# )
# def update_graph(json2, avlbl_sec_lst):
# if avlbl_sec_lst:
# if len(avlbl_sec_lst) > 0:
# if json2 != None:
# df2 = pd.read_json(json2, orient='split')
# if not df2.empty:
# df2 = indexed_vals(df2)
# start_date = df2.index.min()
# auto_start = start_date
# end_date = df2.index.max()
# auto_end = end_date
# symbol = ''
# if len(avlbl_sec_lst) > 7:
# showlegend = False
# # title = ''
# title = 'Performance Comparison'
# else:
# showlegend = True
# title = f'{ext_str_lst(avlbl_sec_lst)}'
# comp_lc1 = pwe_line_chart(df2, columns=avlbl_sec_lst, start_date=start_date, end_date=end_date,
# kind='scatter', title=title, ticker=symbol,
# yTitle='Indexed Returns', asPlot=False, asFigure=True, showlegend=showlegend,
# theme='white', auto_start=auto_start, auto_end=auto_end, connectgaps=False,
# file_tag=None, chart_ticker=False, annots=None)
# return comp_lc1
# else:
# raise dash.exceptions.PreventUpdate
# else:
# raise dash.exceptions.PreventUpdate
# elif (not avlbl_sec_lst) or (len(avlbl_sec_lst) == 0):
# raise dash.exceptions.PreventUpdate
# # Histogram
# @ app.callback(
# Output('sec-hist', 'figure'),
# [Input('sec-drpdwn', 'value'),
# Input('intermediate-value1', 'data'),
# # Input('dt-picker-range', 'start_date'),
# # Input('dt-picker-range', 'end_date')
# ]
# )
# def update_graph(sltd_sec, json1):
# if sltd_sec:
# if len(sltd_sec) > 0:
# if json1 != None:
# df3 = pd.read_json(json1, orient='split')
# if not df3.empty:
# ticker = sltd_sec
# df3.name = ticker
# Sec = Security(df3)
# Sec.get_returns(price='Close')
# chart_interval, interval = calc_interval(Sec.df)
# bins = int(Sec.df['Price_Returns'].count()/2)
# hist = pwe_hist(Sec.df, tseries='Price_Returns', start_date=None, end_date=None, title='Returns',
# ticker=ticker, yTitle=None, xTitle=None, asPlot=False, asFigure=True, theme='white', showlegend=False,
# decimals=2, orientation='v', textangle=0, file_tag=None, interval=chart_interval,
# bins=bins, histnorm='probability', histfunc='count', yaxis_tickformat='', xaxis_tickformat='.2%')
# return hist
# else:
# raise dash.exceptions.PreventUpdate
# else:
# raise dash.exceptions.PreventUpdate
# elif (not sltd_sec) or (len(sltd_sec) == 0):
# raise dash.exceptions.PreventUpdate
# # Correlations Network - Minimum Spanning Tree
# @ app.callback(
# Output('corr-mst', 'figure'),
# [
# # Input('sec-drpdwn2', 'value'),
# Input('intermediate-value2', 'data'),
# Input('avlbl-sec-list', 'data'),
# Input('mst_corr_thrsld', 'value'),
# # Input('dt-picker-range', 'start_date'),
# # Input('dt-picker-range', 'end_date')
# ]
# )
# def update_graph(json2, avlbl_sec_lst, corr_thrsld):
# if avlbl_sec_lst:
# if len(avlbl_sec_lst) > 0:
# if json2 != None:
# try:
# corr_thrsld = float(corr_thrsld)
# except:
# raise dash.exceptions.PreventUpdate
# if (corr_thrsld <= 1) and (corr_thrsld >= 0):
# df4 = pd.read_json(json2, orient='split')
# if not df4.empty:
# df4 = df4.pct_change().fillna(0).add(1).cumprod().mul(100)
# chart_interval, interval = calc_interval(df4)
# df4.name = "MST"
# Sec = Security(df4)
# trading_periods = 252
# ann_factor, t, p = Sec.get_ann_factor(
# interval, trading_periods, 24)
# MST = plot_mst(df4, ann_factor=ann_factor, corr_threshold=corr_thrsld,
# node_size_factor=10, savefig=False)
# return MST
# else:
# raise dash.exceptions.PreventUpdate
# else:
# raise dash.exceptions.PreventUpdate
# else:
# raise dash.exceptions.PreventUpdate
# elif (not avlbl_sec_lst) or (len(avlbl_sec_lst) == 0):
# raise dash.exceptions.PreventUpdate
# # Realised Volatility
# @ app.callback(
# Output('real-vol', 'figure'),
# [Input('sec-drpdwn', 'value'),
# Input('intermediate-value1', 'data'),
# Input('vol_window', 'value'),
# # Input('dt-picker-range', 'start_date'),
# # Input('dt-picker-range', 'end_date')
# ]
# )
# def update_graph(sltd_sec, json1, vol_window):
# if sltd_sec:
# if len(sltd_sec) > 0:
# if json1 != None:
# df5 = pd.read_json(json1, orient='split')
# if not df5.empty:
# ticker = sltd_sec
# df5.name = ticker
# Sec = Security(df5)
# Sec.get_returns(price='Close')
# chart_intrv, interval = calc_interval(Sec.df)
# # vol_window = 30
# trading_periods = 252
# Sec.get_vol(window=vol_window, returns='Price_Returns',
# trading_periods=trading_periods, interval=interval)
# ann_factor, t, p = Sec.get_ann_factor(
# interval, trading_periods, 24)
# start_date = Sec.df.index[Sec.df[f'Ann_Vol_{vol_window}_{p}'] > 0][0]
# auto_start = start_date
# end_date = Sec.df.index.max()
# auto_end = end_date
# vol_fig = pwe_return_dist_chart(Sec.df, start_date, end_date, tseries=f'Ann_Vol_{vol_window}_{p}', kind='scatter',
# title=f'Annualized {vol_window} {p} Volatility', ticker=f'{ticker} Vol.', yTitle=f'{ticker} Vol.',
# asPlot=False, asFigure=True, showlegend=False, theme='white', auto_start=auto_start, auto_end=auto_end,
# connectgaps=False, tickformat='.0%', decimals=2)
# return vol_fig
# else:
# raise dash.exceptions.PreventUpdate
# else:
# raise dash.exceptions.PreventUpdate
# elif (not sltd_sec) or (len(sltd_sec) == 0):
# raise dash.exceptions.PreventUpdate
# # Multi-Asset Box Plot
# @ app.callback(
# Output('box-plt', 'figure'),
# [
# # Input('sec-drpdwn2', 'value'),
# Input('intermediate-value2', 'data'),
# Input('avlbl-sec-list', 'data'),
# # Input('dt-picker-range', 'start_date'),
# # Input('dt-picker-range', 'end_date')
# ]
# )
# def update_graph(json2, avlbl_sec_lst):
# if avlbl_sec_lst:
# if len(avlbl_sec_lst) > 0:
# if json2 != None:
# df6 = pd.read_json(json2, orient='split')
# if not df6.empty:
# df6 = df6.pct_change()
# chart_interval, interval = calc_interval(df6)
# if interval in ['hourly', 'minutes', 'seconds']:
# title_time = True
# else:
# title_time = False
# if len(df6.columns) < 4:
# ticker = ext_str_lst(df6.columns)
# chart_ticker = True
# else:
# ticker = ''
# chart_ticker = False
# box_fig = pwe_box(df6, title=f'{chart_interval} Returns', ticker=ticker, yTitle='Returns (%)', xTitle='Returns Distribution',
# asPlot=True, theme='white', showlegend=False, decimals=2, orientation='v', textangle=0, file_tag=None,
# chart_ticker=chart_ticker, interval='Daily', yaxis_tickformat='.2%', xaxis_tickformat='.2%',
# linecolor=None, title_dates='Yes', title_time=title_time)
# return box_fig
# else:
# raise dash.exceptions.PreventUpdate
# else:
# raise dash.exceptions.PreventUpdate
# elif (not avlbl_sec_lst) or (len(avlbl_sec_lst) == 0):
# raise dash.exceptions.PreventUpdate
# # Yang-Zhang Volatility Estimator
# @ app.callback(
# Output('yz-vol', 'figure'),
# [Input('sec-drpdwn', 'value'),
# Input('intermediate-value1', 'data'),
# Input('yz_window', 'value'),
# # Input('dt-picker-range', 'start_date'),
# # Input('dt-picker-range', 'end_date')
# ]
# )
# def update_graph(sltd_sec, json1, yz_window):
# if sltd_sec:
# if len(sltd_sec) > 0:
# if json1 != None:
# df7 = pd.read_json(json1, orient='split')
# if not df7.empty:
# ticker = sltd_sec
# df7.name = ticker
# Sec = Security(df7)
# Sec.get_returns(price='Close')
# chart_intrv, interval = calc_interval(Sec.df)
# trading_periods = 252
# Sec.YangZhang_estimator(
# window=yz_window, trading_periods=trading_periods, clean=True, interval=interval)
# ann_factor, t, p = Sec.get_ann_factor(
# interval, trading_periods, 24)
# start_date = Sec.df.index[Sec.df[f'YangZhang{yz_window}_{p}_Ann'] > 0][0]
# auto_start = start_date
# end_date = Sec.df.index.max()
# auto_end = end_date
# vz_fig = pwe_return_dist_chart(Sec.df, start_date, end_date, tseries=f'YangZhang{yz_window}_{p}_Ann', kind='scatter',
# title=f'Annualized Yang-Zhang {yz_window} {p} Vol.',
# ticker=f'{ticker} YZ Vol.', yTitle=f'{ticker} YZ Vol.',
# asPlot=False, asFigure=True, showlegend=False, theme='white',
# auto_start=auto_start, auto_end=auto_end,
# connectgaps=False, tickformat='.0%', decimals=2)
# return vz_fig
# else:
# raise dash.exceptions.PreventUpdate
# else:
# raise dash.exceptions.PreventUpdate
# elif (not sltd_sec) or (len(sltd_sec) == 0):
# raise dash.exceptions.PreventUpdate
# # Correlation Matrix Heatmap
# @ app.callback(
# Output('heatmap', 'figure'),
# [
# # Input('sec-drpdwn2', 'value'),
# Input('intermediate-value2', 'data'),
# Input('avlbl-sec-list', 'data'),
# # Input('dt-picker-range', 'start_date'),
# # Input('dt-picker-range', 'end_date')
# ]
# )
# def update_graph(json2, avlbl_sec_lst):
# if avlbl_sec_lst:
# if len(avlbl_sec_lst) > 0:
# if json2 != None:
# df8 = pd.read_json(json2, orient='split')
# if not df8.empty:
# df_corr = df8.pct_change().corr()
# chart_intrv, interval = calc_interval(df8)
# if interval in ['hourly', 'minutes', 'seconds']:
# title_time = True
# else:
# title_time = False
# if len(df8.columns) < 4:
# ticker = ext_str_lst(df8.columns)
# chart_ticker = True
# else:
# ticker = ''
# chart_ticker = False
# start_date = df8.index.min()
# end_date = df8.index.max()
# hmap_fig = pwe_heatmap(df_corr, start_date=start_date, end_date=end_date, title='Correlation Heatmap', ticker=ticker, yTitle=None,
# xTitle=None, asPlot=False, asFigure=True, theme='white', showlegend=False, decimals=2, textangle=0, file_tag=None,
# interval='Daily', linecolor=None, title_dates=True, colorscale=["rgb(100, 100, 111)", "rgb(255, 255, 255)", 'rgb(220, 187, 166)'],
# title_time=title_time, chart_ticker=chart_ticker, top_margin=0.9, spacing=0.08, title_x=0.5, title_y=0.933)
# return hmap_fig
# else:
# raise dash.exceptions.PreventUpdate
# else:
# raise dash.exceptions.PreventUpdate
# elif (not avlbl_sec_lst) or (len(avlbl_sec_lst) == 0):
# raise dash.exceptions.PreventUpdate
# @ app.callback(
# [Output('container-button-basic', "children")],
# [Input('submit-val', 'n_clicks')],
# [State('username', 'value'),
# State('password', 'value'),
# State('email', 'value')])
# def insert_users(n_clicks, un, pw, em):
# if n_clicks > 0:
# if un is not None and pw is not None and em is not None:
# hashed_password = generate_password_hash(pw, method='sha256')
# user = Users(username=un)
# exist_user = Users.query.filter_by(username=user.username).first()
# if exist_user:
# return [html.Div([html.H2('An account for this username already exists.'), dcc.Link('Click here to Log In', href='/login')])]
# else:
# user.password = hashed_password
# user.email = em
# try:
# db_auth.session.add(user)
# db_auth.session.commit()
# except:
# db_auth.session.rollback()
# raise
# finally:
# db_auth.session.close()
# return [login]
# else:
# return [html.Div([html.H2('Already have an account?'), dcc.Link('Click here to Log In', href='/login', className='nav_href')])]
# else:
# # raise dash.exceptions.PreventUpdate
# return [html.Div([html.H2('Already have an account?'), dcc.Link('Click here to Log In', href='/login', className='nav_href')])]
# @ app.callback(
# [Output('url_login', 'pathname'),
# Output('login-text', 'children')],
# [Input('login-button', 'n_clicks')],
# [State('uname-box', 'value'),
# State('pwd-box', 'value')])
# def successful(n_clicks, input_unmae, input_pass):
# if n_clicks > 0:
# user = Users.query.filter_by(username=input_unmae).first()
# if user:
# if check_password_hash(user.password, input_pass):
# login_user(user, remember=True, duration=timedelta(days=7))
# # return '/success', dash.no_update
# print("Login form submission")
# return '/success', dash.no_update
# else:
# return dash.no_update, 'Incorrect password. Please try again.'
# else:
# return dash.no_update, [html.Div([html.H2('No account for this username exists.'), dcc.Link(
# 'Would you like to create one?', href='/create_account')])]
# else:
# # raise dash.exceptions.PreventUpdate
# return dash.no_update, dash.no_update
# # @app.callback(
# # Output('login-text', 'children'),
# # [Input('login-button', 'n_clicks')],
# # [State('uname-box', 'value'),
# # State('pwd-box', 'value')])
# # def update_output(n_clicks, input1, input2):
# # if n_clicks > 0:
# # user = Users.query.filter_by(username=input1).first()
# # if user:
# # if check_password_hash(user.password, input2):
# # return ''
# # else:
# # return 'Incorrect username or password'
# # else:
# # return 'Incorrect username or password'
# # else:
# # return ''
# @ app.callback(
# Output('url_login_success', 'pathname'),
# [Input('back-button', 'n_clicks')])
# def logout_dashboard(n_clicks):
# if n_clicks > 0:
# return '/'
# @ app.callback(
# Output('url_login_f', 'pathname'),
# [Input('back-button', 'n_clicks')])
# def logout_dashboard(n_clicks):
# if n_clicks > 0:
# return '/'
# @ app.callback(
# Output('url_markets', 'pathname'),
# [Input('log-out-btn', 'n_clicks')])
# def logout_nav(n_clicks):
# if n_clicks > 0:
# return '/logout'
# if __name__ == '__main__':
# app.run_server(debug=True, port=8000)
# # app.run_server(debug=True)
|
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
from tkinter import scrolledtext
from tkinter import messagebox
from PIL import ImageTk, Image
import requests
import pickle
import numpy as np
import base64
from io import BytesIO
import json
import matplotlib.pyplot as plt
import matplotlib
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import os
matplotlib.use("TkAgg")
# ---------------------------Login Screen--------------------------------
def login_window():
# Initialize global variables
global login_screen
global username
global url
url = "http://127.0.0.1:5000"
# Login command
def validateLogin():
r = requests.post("http://127.0.0.1:5000/api/login",
json=username.get())
if r.status_code == 200:
print("{} is logged in".format(username.get()))
login_screen.withdraw()
data_interface_window(username.get())
return
else:
username_not_recognized()
# New user command
def validateNewUser():
r = requests.post("http://127.0.0.1:5000/api/new_user",
json=username.get())
if r.status_code == 200:
print("{} is a new user".format(username.get()))
login_screen.withdraw()
data_interface_window(username.get())
return
else:
username_already_exists()
# Screen layout
login_screen = Tk()
login_screen.title("Login")
login_screen.geometry('300x200')
login_screen.grid_columnconfigure(0, weight=1)
login_screen.grid_columnconfigure(1, weight=1)
login_screen.grid_rowconfigure(0, weight=3)
login_screen.grid_rowconfigure(3, weight=1)
login_screen.grid_rowconfigure(5, weight=3)
usernameLabel = Label(login_screen, text="Enter Username:")
usernameLabel.grid(row=1, column=0, columnspan=2)
username = StringVar()
usernameEntry = Entry(login_screen, textvariable=username)
usernameEntry.grid(row=2, column=0, columnspan=2)
loginButton = Button(login_screen, text="Login", command=validateLogin)
loginButton.grid(row=4, column=0)
newButton = Button(login_screen, text="New User", command=validateNewUser)
newButton.grid(row=4, column=1)
login_screen.mainloop()
return
# -------------------------Invalid Login Screen-----------------------------
def username_not_recognized():
# Screen closed upon clicking "Ok" button
def exit():
invalid_screen.destroy()
return
# Screen layout
invalid_screen = Toplevel(login_screen)
invalid_screen.title("Invalid")
invalid_screen.geometry('200x100')
Label(invalid_screen, text="Username not recognized.").pack()
Button(invalid_screen, text="Ok", command=exit).pack()
# -----------------------Invalid Registration Screen---------------------------
def username_already_exists():
# Screen closed upon clicking "Ok" button
def exit():
invalid_screen.destroy()
return
# Screen layout
invalid_screen = Toplevel(login_screen)
invalid_screen.title("Invalid")
invalid_screen.geometry('200x100')
Label(invalid_screen, text="Username already exists.").pack()
Button(invalid_screen, text="Ok", command=exit).pack()
# ------------------------------Main UI Window---------------------------------
def data_interface_window(username='NA'):
# Set-up UI window
global window
window = Toplevel(login_screen)
window.title("{}'s Image Processing " # Sets window title
"Application.".format(username))
window.geometry('500x500') # Sets window size
# Create tab control
tab_control = ttk.Notebook(window)
tab_control.pack(expand=1, fill="both")
upload_tab = ttk.Frame(tab_control)
display_tab = ttk.Frame(tab_control)
download_tab = ttk.Frame(tab_control)
metrics_tab = ttk.Frame(tab_control)
# Label tabs
tab_control.add(upload_tab, text="Upload")
tab_control.add(display_tab, text="Display")
tab_control.add(download_tab, text="Download")
tab_control.add(metrics_tab, text="User Metrics")
# ----------------------------Upload tab--------------------------------
def sort_files(new_files, out_files):
# Returns sorted list of all elements with no repeated elements
for filepath in new_files:
if filepath not in all_files:
out_files.append(filepath)
# Returns all files wanting to read as tuple of string paths
return sorted(out_files)
# Appends only new files selected to display window
def display_files(root_box, files):
# Deletes current box and displays new files in alphabetical order
root_box.delete('1.0', END)
for filename in sorted(files):
head, tail = os.path.split(filename)
root_box.insert(END, tail+'\n')
return
# Function to choose files wanted to open
def choose_files(out_files):
# Open file selection box
ftypes = [('.png (Portable Graphics Format)', '*.png'),
('.jpeg (Joint Photographic Experts Group)', '*jpeg'),
('.tiff (Tagged Image File Format)', '*.tiff'),
('.zip (Compressed File Format)', '*.zip')]
new_files = filedialog.askopenfilenames(filetypes=ftypes)
# Sort for non-repeated list of files
out_files = sort_files(new_files, out_files) # Sorts files.
# Display all files selected
display_files(file_display, out_files) # Displays image names
# Allow selection of upload button as files are selected
if out_files:
upload_btn.config(state='normal',
bg='white',
fg='black')
return out_files
# Reset all files chosen upon upload
def reset_selection(files):
removable_files = tuple(files)
for filepath in removable_files:
files.remove(filepath)
# Function if select upload files button
def upload_files(files, processing):
# Submit post request to validate files to upload
# (including processing) and presence in dictionary
new_url = url + "/api/validate_images"
validate_dict = {"username": username,
"filepaths": files,
"processing": processing.get()}
r = requests.post(new_url, json=validate_dict)
out_dict = r.json()
if r.status_code != 200:
return
# Parse through dictionary to isolate files to upload.
present_images = out_dict["present"]
new_images = out_dict["not present"]
# Call function to display top level tab of files present and those
# uploading.
# If Continue button, move forward and delete display/reset file
# selection/disable upload. If not, simply return.
flag = False
for values in present_images.values():
if len(values) > 0:
flag = True
if flag:
images_already_present(present_images)
# For filepath not present - submit post request of files.
new_url = url + "/api/upload_images"
store_dict = {"username": username,
"images": new_images}
r = requests.post(new_url, json=store_dict)
status = r.json()
print(status)
# Reset GUI file download display and file selection
file_display.delete('1.0', END)
reset_selection(files)
upload_btn.config(state='disabled',
bg='grey',
fg='black')
return
# Choose File Section
all_files = [] # Stores all filepaths of files wanting to upload.
file_display = scrolledtext.ScrolledText(upload_tab, # Display files
width=50,
height=5)
file_display.grid(column=1, row=1) # Location to display files
file_btn = Button(upload_tab, # Choose files button
text="Choose Files",
bg="white",
fg="black",
command=lambda: choose_files(all_files))
file_btn.grid(column=2, row=1) # Choose file button location
# Choose Processing Type Section
processing_type = StringVar() # Variable for processing type
processing_type.set('_histogramEqualized')
hist_process = Radiobutton(upload_tab,
text='Histogram Equalization',
variable=processing_type,
value='_histogramEqualized')
hist_process.grid(column=1,
row=2,
sticky=W,
pady=5,
padx=100)
cont_stretch = Radiobutton(upload_tab,
text='Contrast Stretching',
variable=processing_type,
value='_contrastStretched')
cont_stretch.grid(column=1,
row=3,
sticky=W,
pady=5,
padx=100)
log_comp = Radiobutton(upload_tab,
text='Log Compression',
variable=processing_type,
value='_logCompressed')
log_comp.grid(column=1,
row=4,
sticky=W,
pady=5,
padx=100)
inv_img = Radiobutton(upload_tab,
text='Invert Image',
variable=processing_type,
value='_invertedImage')
inv_img.grid(column=1,
row=5,
sticky=W,
pady=5,
padx=100)
# Upload Selection Section
upload_btn = Button(upload_tab,
text="Upload Files",
bg="grey", # Set to grey when disabled
fg="black",
command=lambda: upload_files(all_files,
processing_type),
state="disabled")
upload_btn.grid(column=1, # Choose file button location
row=6,
sticky=W,
pady=5,
padx=100)
# ----------------------------Display tab---------------------------------
def left_display(): # find the picture according to the name
# Only dummy variables are used now, but should be easy to
# find image metrics if given image name
if image_name_1.get() == '':
messagebox.showerror("Error", "Please select an option first")
return
fetch_image_url = "http://127.0.0.1:5000/api/fetch_image/"\
+ username + "/" + image_name_1.get().strip("")
print(fetch_image_url)
image_file = requests.get(fetch_image_url)
image_file = image_file.json()
fetch_metrics_url = "http://127.0.0.1:5000/api/get_image_metrics/"\
+ username + "/" + image_name_1.get()
print(fetch_metrics_url)
image_metrics = requests.get(fetch_metrics_url)
image_metrics = image_metrics.json()
cpu = ttk.Label(display_tab, text="CPU Time: "
"{}".format(image_metrics[0]))
size = ttk.Label(display_tab, text="Size: "
"{}".format(image_metrics[1]))
timestamp = ttk.Label(display_tab, text="Timestamp: "
"{}".format(image_metrics[2]))
timestamp.grid(column=0, row=5, pady=5)
cpu.grid(column=0, row=6, pady=5)
size.grid(column=0, row=7, pady=5)
size_format = image_metrics[1]
size_list = size_format.split("x")
image_file = np.asarray(image_file)
image_file = image_file.astype(np.uint8)
# print(image_file)
reshape_arg = (int(size_list[1]), int(size_list[0]), int(size_list[2]))
image_file = image_file.reshape(reshape_arg)
histo_url = "http://127.0.0.1:5000/api/histo/"\
+ username + "/" + image_name_1.get().strip("")
histo = requests.get(histo_url)
histo = histo.json()
red = histo[0]
green = histo[1]
blue = histo[2]
figure = Figure(figsize=(0.5, 0.5), dpi=100)
plot = figure.add_subplot(1, 1, 1)
plot.bar(np.arange(0, len(red)), red)
canvas = FigureCanvasTkAgg(figure, display_tab)
canvas.get_tk_widget().grid(row=8, column=0)
figure2 = Figure(figsize=(0.5, 0.5), dpi=100)
plot2 = figure2.add_subplot(1, 1, 1)
plot2.bar(np.arange(0, len(green)), green)
canvas = FigureCanvasTkAgg(figure2, display_tab)
canvas.get_tk_widget().grid(row=9, column=0)
figure3 = Figure(figsize=(0.5, 0.5), dpi=100)
plot3 = figure3.add_subplot(1, 1, 1)
plot3.bar(np.arange(0, len(blue)), blue)
canvas = FigureCanvasTkAgg(figure3, display_tab)
canvas.get_tk_widget().grid(row=10, column=0)
image_display = Image.fromarray(image_file, 'RGB')
image_display = image_display.resize((100, 100), Image.ANTIALIAS)
render = ImageTk.PhotoImage(image_display)
img = Label(display_tab, image=render)
img.image = render
img.grid(column=0, row=4, pady=5)
return
def right_display(): # find the picture according to the name
if image_name_2.get() == '':
messagebox.showerror("Error", "Please select an option first")
return
fetch_image_url = "http://127.0.0.1:5000/api/fetch_image/"\
+ username + "/" + image_name_2.get()
image_file = requests.get(fetch_image_url)
image_file = image_file.json()
fetch_metrics_url = "http://127.0.0.1:5000/api/get_image_metrics/"\
+ username + "/" + image_name_2.get()
image_metrics = requests.get(fetch_metrics_url)
image_metrics = image_metrics.json()
cpu = ttk.Label(display_tab, text="CPU Time: "
"{}".format(image_metrics[0]))
size = ttk.Label(display_tab, text="Size: "
"{}".format(image_metrics[1]))
timestamp = ttk.Label(display_tab, text="Timestamp: "
"{}".format(image_metrics[2]))
timestamp.grid(column=2, row=5, pady=5)
cpu.grid(column=2, row=6, pady=5)
size.grid(column=2, row=7, pady=5)
size_format = image_metrics[1]
size_list = size_format.split("x")
image_file = np.asarray(image_file)
image_file = image_file.astype(np.uint8)
reshape_arg = (int(size_list[1]), int(size_list[0]), int(size_list[2]))
image_file = image_file.reshape(reshape_arg)
histo_url = "http://127.0.0.1:5000/api/histo/"\
+ username + "/" + image_name_2.get().strip("")
histo = requests.get(histo_url)
histo = histo.json()
red = histo[0]
green = histo[1]
blue = histo[2]
figure = Figure(figsize=(0.5, 0.5), dpi=100)
plot = figure.add_subplot(1, 1, 1)
plot.bar(np.arange(0, len(red)), red)
canvas = FigureCanvasTkAgg(figure, display_tab)
canvas.get_tk_widget().grid(row=8, column=2)
figure2 = Figure(figsize=(0.5, 0.5), dpi=100)
plot2 = figure2.add_subplot(1, 1, 1)
plot2.bar(np.arange(0, len(green)), green)
canvas = FigureCanvasTkAgg(figure2, display_tab)
canvas.get_tk_widget().grid(row=9, column=2)
figure3 = Figure(figsize=(0.5, 0.5), dpi=100)
plot3 = figure3.add_subplot(1, 1, 1)
plot3.bar(np.arange(0, len(blue)), blue)
canvas = FigureCanvasTkAgg(figure3, display_tab)
canvas.get_tk_widget().grid(row=10, column=2)
image_display = Image.fromarray(image_file, 'RGB')
image_display = image_display.resize((100, 100), Image.ANTIALIAS)
render = ImageTk.PhotoImage(image_display)
img = Label(display_tab, image=render)
img.image = render
img.grid(column=2, row=4, pady=5)
return
def refresh_list2():
get_image_list_url = "http://127.0.0.1:5000/api/get_all_images/"\
+ username
image_list = requests.get(get_image_list_url)
image_list = image_list.json()
display_sel_2['values'] = image_list
return
def refresh_list1():
get_image_list_url = "http://127.0.0.1:5000/api/get_all_images/"\
+ username
image_list = requests.get(get_image_list_url)
image_list = image_list.json()
# image_list = image_list.strip('][').split(',')
display_sel_1['values'] = image_list
return
ttk.Separator(display_tab, orient=VERTICAL).grid(column=1, row=1,
rowspan=10, sticky='ns')
choice_1 = ttk.Label(display_tab, text="Choose picture 1 from below")
choice_1.grid(column=0, row=1, padx=50, pady=5)
choice_2 = ttk.Label(display_tab, text="Choose picture 2 from below")
choice_2.grid(column=2, row=1, padx=50, pady=5)
image_name_1 = StringVar()
display_sel_1 = ttk.Combobox(display_tab, textvariable=image_name_1,
postcommand=refresh_list1)
display_sel_1.grid(column=0, row=2, pady=5)
# display_sel_1['values'] = image_list
display_sel_1.state(['readonly'])
image_name_2 = StringVar()
display_sel_2 = ttk.Combobox(display_tab, textvariable=image_name_2,
postcommand=refresh_list2)
display_sel_2.grid(column=2, row=2, pady=5)
# display_sel_2['values'] = image_list
display_sel_2.state(['readonly'])
ok_btn_left = ttk.Button(display_tab, text='ok', command=left_display)
ok_btn_left.grid(column=0, row=3, pady=5)
ok_btn_right = ttk.Button(display_tab, text='ok', command=right_display)
ok_btn_right.grid(column=2, row=3, pady=5)
# ----------------------------Download tab--------------------------------
# ----------------------------User Metrics tab----------------------------
# Command for Display Current User Metrics button
def button_action():
r = requests.get("http://127.0.0.1:5000/api/user_metrics/"
"{}".format(username))
metrics = r.json()
total_uploads = metrics["total_uploads"]
total_hist_equal = metrics["total_hist_equal"]
total_contrast_stretch = metrics["total_contrast_stretch"]
total_log_comp = metrics["total_log_comp"]
total_inv_img = metrics["total_inv_img"]
upload_num.config(text=total_uploads)
hist_num.config(text=total_hist_equal)
contrast_num.config(text=total_contrast_stretch)
log_num.config(text=total_log_comp)
invert_num.config(text=total_inv_img)
return
def on_tab_selected(event):
selected_tab = event.widget.select()
tab_text = event.widget.tab(selected_tab, "text")
if tab_text == "User Metrics":
print("Selected User Metrics tab")
metrics_tab.grid_columnconfigure(0, weight=1)
metrics_tab.grid_columnconfigure(1, weight=2)
metrics_tab.grid_rowconfigure(0, weight=3)
metrics_tab.grid_rowconfigure(2, weight=1)
metrics_tab.grid_rowconfigure(8, weight=3)
# Screen layout
button = ttk.Button(metrics_tab, text="Display Current User Metrics",
command=button_action)
button.grid(row=1, column=0, columnspan=2)
upload_label = ttk.Label(metrics_tab,
text="Total number of uploads by user: ")
upload_label.grid(row=3, column=0, sticky=E)
upload_num = ttk.Label(metrics_tab, text="")
upload_num.grid(row=3, column=1, sticky=W)
hist_label = ttk.Label(metrics_tab,
text="# of times Histogram Equalization "
"performed: ")
hist_label.grid(row=4, column=0, sticky=E)
hist_num = ttk.Label(metrics_tab, text="")
hist_num.grid(row=4, column=1, sticky=W)
contrast_label = ttk.Label(metrics_tab,
text="# of times Contrast Stretching "
"performed: ")
contrast_label.grid(row=5, column=0, sticky=E)
contrast_num = ttk.Label(metrics_tab, text="")
contrast_num.grid(row=5, column=1, sticky=W)
log_label = ttk.Label(metrics_tab,
text="# of times Log Compression performed: ")
log_label.grid(row=6, column=0, sticky=E)
log_num = ttk.Label(metrics_tab, text="")
log_num.grid(row=6, column=1, sticky=W)
invert_label = ttk.Label(metrics_tab,
text="# of times Image Inversion performed: ")
invert_label.grid(row=7, column=0, sticky=E)
invert_num = ttk.Label(metrics_tab, text="")
invert_num.grid(row=7, column=1, sticky=W)
# Run Window until close
window.mainloop()
return
def images_already_present(present_images):
# Screen closed upon clicking "Ok" button
def exit():
present_images_screen.destroy()
return
# Screen layout
present_images_screen = Toplevel(window)
present_images_screen.title("Invalid Image Upload")
present_images_screen.geometry('600x500')
present_images_screen.grid_columnconfigure(0, weight=1)
present_images_screen.grid_columnconfigure(1, weight=1)
# present_images_screen.grid_rowconfigure(3, weight=1)
note1 = Label(present_images_screen,
text="These processed images already exist in the database.")
note1.grid(row=0, column=0, columnspan=2)
note2 = Label(present_images_screen,
text="The matching requests will not be sent to the server.")
note2.grid(row=1, column=0, columnspan=2)
Label(present_images_screen, text="").grid(row=2, column=0)
Button(present_images_screen, text="Ok", command=exit).grid(row=3,
column=0,
columnspan=2)
Label(present_images_screen, text="").grid(row=4, column=0, columnspan=2)
category_L = Label(present_images_screen, text="UPLOADED FILES:")
category_L.grid(row=5, column=0)
category_R = Label(present_images_screen,
text="LIST OF PROCESSED FILENAMES:")
category_R.grid(row=5, column=1)
Label(present_images_screen, text="").grid(row=6, column=0)
current_row = 7
for filepath in present_images.keys():
head, tail = os.path.split(filepath)
name_list = present_images.get(filepath)
num_rows = len(name_list)
Label(present_images_screen,
text=tail).grid(row=current_row, column=0, rowspan=num_rows)
for name in name_list:
Label(present_images_screen,
text=name).grid(row=current_row, column=1)
current_row += 1
Label(present_images_screen,
text="").grid(row=current_row, column=0)
current_row += 1
if __name__ == "__main__":
login_window()
|
# coding: utf-8
# Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
from oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel # noqa: F401
from oci.decorators import init_model_state_from_kwargs
@init_model_state_from_kwargs
class CreateDatabaseDetails(object):
"""
Details for creating a database.
**Warning:** Oracle recommends that you avoid using any confidential information when you supply string values using the API.
"""
#: A constant which can be used with the db_workload property of a CreateDatabaseDetails.
#: This constant has a value of "OLTP"
DB_WORKLOAD_OLTP = "OLTP"
#: A constant which can be used with the db_workload property of a CreateDatabaseDetails.
#: This constant has a value of "DSS"
DB_WORKLOAD_DSS = "DSS"
def __init__(self, **kwargs):
"""
Initializes a new CreateDatabaseDetails object with values from keyword arguments.
The following keyword arguments are supported (corresponding to the getters/setters of this class):
:param db_name:
The value to assign to the db_name property of this CreateDatabaseDetails.
:type db_name: str
:param db_unique_name:
The value to assign to the db_unique_name property of this CreateDatabaseDetails.
:type db_unique_name: str
:param pdb_name:
The value to assign to the pdb_name property of this CreateDatabaseDetails.
:type pdb_name: str
:param admin_password:
The value to assign to the admin_password property of this CreateDatabaseDetails.
:type admin_password: str
:param character_set:
The value to assign to the character_set property of this CreateDatabaseDetails.
:type character_set: str
:param ncharacter_set:
The value to assign to the ncharacter_set property of this CreateDatabaseDetails.
:type ncharacter_set: str
:param db_workload:
The value to assign to the db_workload property of this CreateDatabaseDetails.
Allowed values for this property are: "OLTP", "DSS"
:type db_workload: str
:param db_backup_config:
The value to assign to the db_backup_config property of this CreateDatabaseDetails.
:type db_backup_config: DbBackupConfig
:param freeform_tags:
The value to assign to the freeform_tags property of this CreateDatabaseDetails.
:type freeform_tags: dict(str, str)
:param defined_tags:
The value to assign to the defined_tags property of this CreateDatabaseDetails.
:type defined_tags: dict(str, dict(str, object))
"""
self.swagger_types = {
'db_name': 'str',
'db_unique_name': 'str',
'pdb_name': 'str',
'admin_password': 'str',
'character_set': 'str',
'ncharacter_set': 'str',
'db_workload': 'str',
'db_backup_config': 'DbBackupConfig',
'freeform_tags': 'dict(str, str)',
'defined_tags': 'dict(str, dict(str, object))'
}
self.attribute_map = {
'db_name': 'dbName',
'db_unique_name': 'dbUniqueName',
'pdb_name': 'pdbName',
'admin_password': 'adminPassword',
'character_set': 'characterSet',
'ncharacter_set': 'ncharacterSet',
'db_workload': 'dbWorkload',
'db_backup_config': 'dbBackupConfig',
'freeform_tags': 'freeformTags',
'defined_tags': 'definedTags'
}
self._db_name = None
self._db_unique_name = None
self._pdb_name = None
self._admin_password = None
self._character_set = None
self._ncharacter_set = None
self._db_workload = None
self._db_backup_config = None
self._freeform_tags = None
self._defined_tags = None
@property
def db_name(self):
"""
**[Required]** Gets the db_name of this CreateDatabaseDetails.
The database name. The name must begin with an alphabetic character and can contain a maximum of eight alphanumeric characters. Special characters are not permitted.
:return: The db_name of this CreateDatabaseDetails.
:rtype: str
"""
return self._db_name
@db_name.setter
def db_name(self, db_name):
"""
Sets the db_name of this CreateDatabaseDetails.
The database name. The name must begin with an alphabetic character and can contain a maximum of eight alphanumeric characters. Special characters are not permitted.
:param db_name: The db_name of this CreateDatabaseDetails.
:type: str
"""
self._db_name = db_name
@property
def db_unique_name(self):
"""
Gets the db_unique_name of this CreateDatabaseDetails.
The `DB_UNIQUE_NAME` of the Oracle Database being backed up.
:return: The db_unique_name of this CreateDatabaseDetails.
:rtype: str
"""
return self._db_unique_name
@db_unique_name.setter
def db_unique_name(self, db_unique_name):
"""
Sets the db_unique_name of this CreateDatabaseDetails.
The `DB_UNIQUE_NAME` of the Oracle Database being backed up.
:param db_unique_name: The db_unique_name of this CreateDatabaseDetails.
:type: str
"""
self._db_unique_name = db_unique_name
@property
def pdb_name(self):
"""
Gets the pdb_name of this CreateDatabaseDetails.
The name of the pluggable database. The name must begin with an alphabetic character and can contain a maximum of eight alphanumeric characters. Special characters are not permitted. Pluggable database should not be same as database name.
:return: The pdb_name of this CreateDatabaseDetails.
:rtype: str
"""
return self._pdb_name
@pdb_name.setter
def pdb_name(self, pdb_name):
"""
Sets the pdb_name of this CreateDatabaseDetails.
The name of the pluggable database. The name must begin with an alphabetic character and can contain a maximum of eight alphanumeric characters. Special characters are not permitted. Pluggable database should not be same as database name.
:param pdb_name: The pdb_name of this CreateDatabaseDetails.
:type: str
"""
self._pdb_name = pdb_name
@property
def admin_password(self):
"""
**[Required]** Gets the admin_password of this CreateDatabaseDetails.
A strong password for SYS, SYSTEM, and PDB Admin. The password must be at least nine characters and contain at least two uppercase, two lowercase, two numbers, and two special characters. The special characters must be _, \\#, or -.
:return: The admin_password of this CreateDatabaseDetails.
:rtype: str
"""
return self._admin_password
@admin_password.setter
def admin_password(self, admin_password):
"""
Sets the admin_password of this CreateDatabaseDetails.
A strong password for SYS, SYSTEM, and PDB Admin. The password must be at least nine characters and contain at least two uppercase, two lowercase, two numbers, and two special characters. The special characters must be _, \\#, or -.
:param admin_password: The admin_password of this CreateDatabaseDetails.
:type: str
"""
self._admin_password = admin_password
@property
def character_set(self):
"""
Gets the character_set of this CreateDatabaseDetails.
The character set for the database. The default is AL32UTF8. Allowed values are:
AL32UTF8, AR8ADOS710, AR8ADOS720, AR8APTEC715, AR8ARABICMACS, AR8ASMO8X, AR8ISO8859P6, AR8MSWIN1256, AR8MUSSAD768, AR8NAFITHA711, AR8NAFITHA721, AR8SAKHR706, AR8SAKHR707, AZ8ISO8859P9E, BG8MSWIN, BG8PC437S, BLT8CP921, BLT8ISO8859P13, BLT8MSWIN1257, BLT8PC775, BN8BSCII, CDN8PC863, CEL8ISO8859P14, CL8ISO8859P5, CL8ISOIR111, CL8KOI8R, CL8KOI8U, CL8MACCYRILLICS, CL8MSWIN1251, EE8ISO8859P2, EE8MACCES, EE8MACCROATIANS, EE8MSWIN1250, EE8PC852, EL8DEC, EL8ISO8859P7, EL8MACGREEKS, EL8MSWIN1253, EL8PC437S, EL8PC851, EL8PC869, ET8MSWIN923, HU8ABMOD, HU8CWI2, IN8ISCII, IS8PC861, IW8ISO8859P8, IW8MACHEBREWS, IW8MSWIN1255, IW8PC1507, JA16EUC, JA16EUCTILDE, JA16SJIS, JA16SJISTILDE, JA16VMS, KO16KSC5601, KO16KSCCS, KO16MSWIN949, LA8ISO6937, LA8PASSPORT, LT8MSWIN921, LT8PC772, LT8PC774, LV8PC1117, LV8PC8LR, LV8RST104090, N8PC865, NE8ISO8859P10, NEE8ISO8859P4, RU8BESTA, RU8PC855, RU8PC866, SE8ISO8859P3, TH8MACTHAIS, TH8TISASCII, TR8DEC, TR8MACTURKISHS, TR8MSWIN1254, TR8PC857, US7ASCII, US8PC437, UTF8, VN8MSWIN1258, VN8VN3, WE8DEC, WE8DG, WE8ISO8859P1, WE8ISO8859P15, WE8ISO8859P9, WE8MACROMAN8S, WE8MSWIN1252, WE8NCR4970, WE8NEXTSTEP, WE8PC850, WE8PC858, WE8PC860, WE8ROMAN8, ZHS16CGB231280, ZHS16GBK, ZHT16BIG5, ZHT16CCDC, ZHT16DBT, ZHT16HKSCS, ZHT16MSWIN950, ZHT32EUC, ZHT32SOPS, ZHT32TRIS
:return: The character_set of this CreateDatabaseDetails.
:rtype: str
"""
return self._character_set
@character_set.setter
def character_set(self, character_set):
"""
Sets the character_set of this CreateDatabaseDetails.
The character set for the database. The default is AL32UTF8. Allowed values are:
AL32UTF8, AR8ADOS710, AR8ADOS720, AR8APTEC715, AR8ARABICMACS, AR8ASMO8X, AR8ISO8859P6, AR8MSWIN1256, AR8MUSSAD768, AR8NAFITHA711, AR8NAFITHA721, AR8SAKHR706, AR8SAKHR707, AZ8ISO8859P9E, BG8MSWIN, BG8PC437S, BLT8CP921, BLT8ISO8859P13, BLT8MSWIN1257, BLT8PC775, BN8BSCII, CDN8PC863, CEL8ISO8859P14, CL8ISO8859P5, CL8ISOIR111, CL8KOI8R, CL8KOI8U, CL8MACCYRILLICS, CL8MSWIN1251, EE8ISO8859P2, EE8MACCES, EE8MACCROATIANS, EE8MSWIN1250, EE8PC852, EL8DEC, EL8ISO8859P7, EL8MACGREEKS, EL8MSWIN1253, EL8PC437S, EL8PC851, EL8PC869, ET8MSWIN923, HU8ABMOD, HU8CWI2, IN8ISCII, IS8PC861, IW8ISO8859P8, IW8MACHEBREWS, IW8MSWIN1255, IW8PC1507, JA16EUC, JA16EUCTILDE, JA16SJIS, JA16SJISTILDE, JA16VMS, KO16KSC5601, KO16KSCCS, KO16MSWIN949, LA8ISO6937, LA8PASSPORT, LT8MSWIN921, LT8PC772, LT8PC774, LV8PC1117, LV8PC8LR, LV8RST104090, N8PC865, NE8ISO8859P10, NEE8ISO8859P4, RU8BESTA, RU8PC855, RU8PC866, SE8ISO8859P3, TH8MACTHAIS, TH8TISASCII, TR8DEC, TR8MACTURKISHS, TR8MSWIN1254, TR8PC857, US7ASCII, US8PC437, UTF8, VN8MSWIN1258, VN8VN3, WE8DEC, WE8DG, WE8ISO8859P1, WE8ISO8859P15, WE8ISO8859P9, WE8MACROMAN8S, WE8MSWIN1252, WE8NCR4970, WE8NEXTSTEP, WE8PC850, WE8PC858, WE8PC860, WE8ROMAN8, ZHS16CGB231280, ZHS16GBK, ZHT16BIG5, ZHT16CCDC, ZHT16DBT, ZHT16HKSCS, ZHT16MSWIN950, ZHT32EUC, ZHT32SOPS, ZHT32TRIS
:param character_set: The character_set of this CreateDatabaseDetails.
:type: str
"""
self._character_set = character_set
@property
def ncharacter_set(self):
"""
Gets the ncharacter_set of this CreateDatabaseDetails.
The national character set for the database. The default is AL16UTF16. Allowed values are:
AL16UTF16 or UTF8.
:return: The ncharacter_set of this CreateDatabaseDetails.
:rtype: str
"""
return self._ncharacter_set
@ncharacter_set.setter
def ncharacter_set(self, ncharacter_set):
"""
Sets the ncharacter_set of this CreateDatabaseDetails.
The national character set for the database. The default is AL16UTF16. Allowed values are:
AL16UTF16 or UTF8.
:param ncharacter_set: The ncharacter_set of this CreateDatabaseDetails.
:type: str
"""
self._ncharacter_set = ncharacter_set
@property
def db_workload(self):
"""
Gets the db_workload of this CreateDatabaseDetails.
The database workload type.
Allowed values for this property are: "OLTP", "DSS"
:return: The db_workload of this CreateDatabaseDetails.
:rtype: str
"""
return self._db_workload
@db_workload.setter
def db_workload(self, db_workload):
"""
Sets the db_workload of this CreateDatabaseDetails.
The database workload type.
:param db_workload: The db_workload of this CreateDatabaseDetails.
:type: str
"""
allowed_values = ["OLTP", "DSS"]
if not value_allowed_none_or_none_sentinel(db_workload, allowed_values):
raise ValueError(
"Invalid value for `db_workload`, must be None or one of {0}"
.format(allowed_values)
)
self._db_workload = db_workload
@property
def db_backup_config(self):
"""
Gets the db_backup_config of this CreateDatabaseDetails.
:return: The db_backup_config of this CreateDatabaseDetails.
:rtype: DbBackupConfig
"""
return self._db_backup_config
@db_backup_config.setter
def db_backup_config(self, db_backup_config):
"""
Sets the db_backup_config of this CreateDatabaseDetails.
:param db_backup_config: The db_backup_config of this CreateDatabaseDetails.
:type: DbBackupConfig
"""
self._db_backup_config = db_backup_config
@property
def freeform_tags(self):
"""
Gets the freeform_tags of this CreateDatabaseDetails.
Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace.
For more information, see `Resource Tags`__.
Example: `{\"Department\": \"Finance\"}`
__ https://docs.cloud.oracle.com/Content/General/Concepts/resourcetags.htm
:return: The freeform_tags of this CreateDatabaseDetails.
:rtype: dict(str, str)
"""
return self._freeform_tags
@freeform_tags.setter
def freeform_tags(self, freeform_tags):
"""
Sets the freeform_tags of this CreateDatabaseDetails.
Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace.
For more information, see `Resource Tags`__.
Example: `{\"Department\": \"Finance\"}`
__ https://docs.cloud.oracle.com/Content/General/Concepts/resourcetags.htm
:param freeform_tags: The freeform_tags of this CreateDatabaseDetails.
:type: dict(str, str)
"""
self._freeform_tags = freeform_tags
@property
def defined_tags(self):
"""
Gets the defined_tags of this CreateDatabaseDetails.
Defined tags for this resource. Each key is predefined and scoped to a namespace.
For more information, see `Resource Tags`__.
__ https://docs.cloud.oracle.com/Content/General/Concepts/resourcetags.htm
:return: The defined_tags of this CreateDatabaseDetails.
:rtype: dict(str, dict(str, object))
"""
return self._defined_tags
@defined_tags.setter
def defined_tags(self, defined_tags):
"""
Sets the defined_tags of this CreateDatabaseDetails.
Defined tags for this resource. Each key is predefined and scoped to a namespace.
For more information, see `Resource Tags`__.
__ https://docs.cloud.oracle.com/Content/General/Concepts/resourcetags.htm
:param defined_tags: The defined_tags of this CreateDatabaseDetails.
:type: dict(str, dict(str, object))
"""
self._defined_tags = defined_tags
def __repr__(self):
return formatted_flat_dict(self)
def __eq__(self, other):
if other is None:
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not self == other
|
from .processor import Processor
class ColorMeanProcessor(Processor):
channel_dict = dict(r=0, g=1, b=2)
channel_dict_reverse = {0: "r", 1: "g", 2: "b"}
def __init__(self, channel="g", winsize=1):
Processor.__init__(self)
if channel not in self.channel_dict.keys():
raise KeyError("channel has to be one of "
"{}".format(set(self.channel_dict.keys())))
self.channel = self.channel_dict[channel]
self.winsize = winsize
self._tmp = []
def calculate(self, roi_pixels):
rgb = self.spatial_pooling(roi_pixels, append_rgb=False)
self._tmp.append(rgb[self.channel])
return self.moving_average_update(0, self._tmp, self.winsize)
def __str__(self):
if self.name is None:
channel = self.channel_dict_reverse[self.channel]
return "ColorMean(winsize={},c={})".format(self.winsize, channel)
return self.name
|
# Generated by Django 3.0.8 on 2020-07-13 07:03
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('sites', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='project',
name='profile',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='project', to='sites.Profile'),
),
]
|
"""
This file contains the implementation of the main class object: anaRDPacct --- an analytical moment accountant
that keeps track the effects of a hetereogeneous sequence of randomized algorithms using the RDP technique.
In particular it supports amplification of RDP by subsampling without replacement and the amplification of RDP
by poisson sampling, but unfortunately not (yet) together.
"""
import numpy as np
from scipy.optimize import minimize_scalar
import sys
sys.path.append('..')
import autodp
from autodp import utils, rdp_bank
from autodp.privacy_calibrator import subsample_epsdelta
import scipy
import math
def general_upperbound(func, mm, prob):
"""
:param func:
:param mm: alpha in RDP
:param prob: sample probability
:return: the upperbound in theorem 1 in 2019 ICML,could be applied for general case(including poisson distribution)
k_approx = 100 k approximation is applied here
"""
def cgf(x):
return (x - 1) * func(x)
if np.isinf(func(mm)):
return np.inf
if mm == 1 or mm == 0:
return 0
cur_k = np.minimum(50, mm - 1) # choose small k-approx for general upperbound (here is 50) in case of scipy-accuracy
log_term_1 = mm * np.log(1 - prob)
#logBin = utils.get_binom_coeffs(mm)
log_term_2 = np.log(3) - func(mm) + mm * utils.stable_logsumexp_two(np.log(1 - prob), np.log(prob) + func(mm))
neg_term_3 = [np.log(scipy.special.comb(mm,l)) + np.log(3) + (mm - l) * np.log(1 - prob) + l * np.log(prob) +
utils.stable_log_diff_exp((l - 1) * func(mm), cgf(l))[1] for l in
range(3, cur_k + 1)]
neg_term_4 = np.log(mm*(mm - 1)/2) + 2 * np.log(prob) + (mm - 2) * np.log(
1 - prob) + utils.stable_log_diff_exp(np.log(3) + func(mm), func(2))[1]
neg_term_5 = np.log(2) + np.log(prob) + np.log(mm) + (mm - 1) * np.log(1 - prob)
neg_term_6 = mm * np.log(1 - prob) + np.log(3) - func(mm)
pos_term = utils.stable_logsumexp([log_term_1, log_term_2])
neg_term_3.append(neg_term_4)
neg_term_3.append(neg_term_5)
neg_term_3.append(neg_term_6)
neg_term = utils.stable_logsumexp(neg_term_3)
bound = utils.stable_log_diff_exp(pos_term, neg_term)[1]
return bound
def fast_subsampled_cgf_upperbound(func, mm, prob, deltas_local):
# evaulate the fast CGF bound for the subsampled mechanism
# func evaluates the RDP of the base mechanism
# mm is alpha. NOT lambda.
return np.inf
if np.isinf(func(mm)):
return np.inf
if mm == 1:
return 0
secondterm = np.minimum(np.minimum((2) * np.log(np.exp(func(np.inf)) - 1)
+ np.minimum(func(2), np.log(4)),
np.log(2) + func(2)),
np.log(4) + 0.5 * deltas_local[int(2 * np.floor(2 / 2.0)) - 1]
+ 0.5 * deltas_local[int(2 * np.ceil(2 / 2.0)) - 1]
) + 2 * np.log(prob) + np.log(mm) + np.log(mm - 1) - np.log(2)
if mm == 2:
return utils.stable_logsumexp([0, secondterm])
# approximate the remaining terms using a geometric series
logratio1 = np.log(prob) + np.log(mm) + func(mm)
logratio2 = logratio1 + np.log(np.exp(func(np.inf)) - 1)
logratio = np.minimum(logratio1, logratio2)
if logratio1 > logratio2:
coeff = 1
else:
coeff = 2
if mm == 3:
return utils.stable_logsumexp([0, secondterm, np.log(coeff) + 3 * logratio])
# Calculate the sum of the geometric series starting from the third term. This is a total of mm-2 terms.
if logratio < 0:
geometric_series_bound = np.log(coeff) + 3 * logratio - np.log(1 - np.exp(logratio)) \
+ np.log(1 - np.exp((mm - 2) * logratio))
elif logratio > 0:
geometric_series_bound = np.log(coeff) + 3 * logratio + (mm-2) * logratio - np.log(np.exp(logratio) - 1)
else:
geometric_series_bound = np.log(coeff) + np.log(mm - 2)
# we will approximate using (1+h)^mm
logh1 = np.log(prob) + func(mm - 1)
logh2 = logh1 + np.log(np.exp(func(np.inf)) - 1)
binomial_series_bound1 = np.log(2) + mm * utils.stable_logsumexp_two(0, logh1)
binomial_series_bound2 = mm * utils.stable_logsumexp_two(0, logh2)
tmpsign, binomial_series_bound1 \
= utils.stable_sum_signed(True, binomial_series_bound1, False, np.log(2)
+ utils.stable_logsumexp([0, logh1 + np.log(mm), 2 * logh1 + np.log(mm)
+ np.log(mm - 1) - np.log(2)]))
tmpsign, binomial_series_bound2 \
= utils.stable_sum_signed(True, binomial_series_bound2, False,
utils.stable_logsumexp([0, logh2 + np.log(mm), 2 * logh2 + np.log(mm)
+ np.log(mm - 1) - np.log(2)]))
remainder = np.min([geometric_series_bound, binomial_series_bound1, binomial_series_bound2])
return utils.stable_logsumexp([0, secondterm, remainder])
def fast_poission_subsampled_cgf_upperbound(func, mm, prob):
# evaulate the fast CGF bound for the subsampled mechanism
# func evaluates the RDP of the base mechanism
# mm is alpha. NOT lambda.
if np.isinf(func(mm)):
return np.inf
if mm == 1:
return 0
# Bound #1: log [ (1-\gamma + \gamma e^{func(mm)})^mm ]
bound1 = mm * utils.stable_logsumexp_two(np.log(1-prob), np.log(prob) + func(mm))
# Bound #2: log [ (1-gamma)^alpha E [ 1 + gamma/(1-gamma) E[p/q]]^mm ]
# log[ (1-gamma)^\alpha { 1 + alpha gamma / (1-gamma) + gamma^2 /(1-gamma)^2 * alpha(alpha-1) /2 e^eps(2))
# + alpha \choose 3 * gamma^3 / (1-gamma)^3 / e^(-2 eps(alpha)) * (1 + gamma /(1-gamma) e^{eps(alpha)}) ^ (alpha - 3) }
# ]
if mm >= 3:
bound2 = utils.stable_logsumexp([mm * np.log(1-prob), (mm-1) * np.log(1-prob) + np.log(mm) + np.log(prob),
(mm-2)*np.log(1-prob) + 2 * np.log(prob) + np.log(mm) + np.log(mm-1) + func(2),
np.log(mm) + np.log(mm-1) + np.log(mm-2) - np.log(3*2) + 3 * np.log(prob)
+ (mm-3)*np.log(1-prob) + 2 * func(mm) +
(mm-3) * utils.stable_logsumexp_two(0, np.log(prob) - np.log(1-prob) + func(mm))])
else:
bound2 = bound1
#print('www={} func={} mm={}'.format(np.exp(func(mm))-1),func, mm)
#print('bound1 ={} bound2 ={}'.format(bound1,bound2))
return np.minimum(bound1,bound2)
def fast_k_subsample_upperbound(func, mm, prob, k):
"""
:param func:
:param mm:
:param prob: sample probability
:param k: approximate term
:return: k-term approximate upper bound in therorem 11 in ICML-19
"""
def cgf(x):
return (x - 1) * func(x)
if np.isinf(func(mm)):
return np.inf
if mm == 1:
return 0
#logBin = utils.get_binom_coeffs(mm)
cur_k = np.minimum(k, mm - 1)
if (2 * cur_k) >= mm:
exact_term_1 = (mm - 1) * np.log(1 - prob) + np.log(mm * prob - prob + 1)
exact_term_2 = [np.log(scipy.special.comb(mm,l)) + (mm - l) * np.log(1 - prob) + l * np.log(prob) + cgf(l) for l in
range(2, mm + 1)]
exact_term_2.append(exact_term_1)
bound = utils.stable_logsumexp(exact_term_2)
return bound
s, mag1 = utils.stable_log_diff_exp(0, -func(mm - cur_k))
new_log_term_1 = np.log(1 - prob) * mm + mag1
new_log_term_2 = -func(mm - cur_k) + mm * utils.stable_logsumexp_two(np.log(1 - prob),
np.log(prob) + func(mm - cur_k))
new_log_term_3 = [np.log(scipy.special.comb(mm,l)) + (mm - l) * np.log(1 - prob) + l * np.log(prob) +
utils.stable_log_diff_exp((l - 1) * func(mm - cur_k), cgf(l))[1] for l in
range(2, cur_k + 1)]
if len(new_log_term_3) > 0:
new_log_term_3 = utils.stable_logsumexp(new_log_term_3)
else:
return utils.stable_logsumexp_two(new_log_term_1, new_log_term_2)
new_log_term_4 = [np.log(scipy.special.comb(mm,mm-l)) + (mm - l) * np.log(1 - prob) + l * np.log(prob) +
utils.stable_log_diff_exp(cgf(l), (l - 1) * func(mm - cur_k))[1] for l in
range(mm - cur_k + 1, mm + 1)]
new_log_term_4.append(new_log_term_1)
new_log_term_4.append(new_log_term_2)
new_log_term_4 = utils.stable_logsumexp(new_log_term_4)
s, new_log_term_5 = utils.stable_log_diff_exp(new_log_term_4, new_log_term_3)
new_bound = new_log_term_5
return new_bound
class anaRDPacct:
"""A class that keeps track of the analytical expression of the RDP --- 1/(alpha-1)*CGF of the privacy loss R.V."""
def __init__(self, m=100, tol=0.1, m_max=500, m_lin_max=10000, approx = False, verbose=False):
# m_max indicates the number that we calculate binomial coefficients exactly up to.
# beyond that we use Stirling approximation.
# ------ Class Attributes -----------
self.m = m # default number of binomial coefficients to precompute
self.m_max = m_max # An upper bound of the quadratic dependence
self.m_lin_max = m_lin_max # An upper bound of the linear dependence.
self.verbose = verbose
self.approx = approx
self.lambs = np.linspace(1, self.m, self.m).astype(int) # Corresponds to \alpha = 2,3,4,5,.... for RDP
self.alphas = np.linspace(1, self.m, self.m).astype(int)
self.RDPs_int = np.zeros_like(self.alphas, float)
self.n=0
self.RDPs = [] # analytical CGFs
self.coeffs = []
self.RDP_inf = .0 # This is effectively for pure DP.
self.logBinomC = utils.get_binom_coeffs(self.m + 1) # The logBinomC is only needed for subsampling mechanisms.
self.idxhash = {} # save the index of previously used algorithms
self.cache = {} # dictionary to save results from previously seen algorithms
self.deltas_cache = {} # dictionary to save results of all discrete derivative path
self.evalRDP = lambda x: 0
self.flag = True # a flag indicating whether evalCGF is out of date
self.flag_subsample = False # a flag to indicate whether we need to expand the logBinomC.
self.tol = tol
# ---------- Methods ------------
def build_zeroth_oracle(self):
self.evalRDP = lambda x: sum([c * item(x) for (c, item) in zip(self.coeffs, self.RDPs)])
def plot_rdp(self):
if not self.flag:
self.build_zeroth_oracle()
self.flag = True
import matplotlib.pyplot as plt
plt.figure(num=None, figsize=(12, 8), dpi=80, facecolor='w', edgecolor='k')
x = range(0,self.m,1)
y = [self.evalRDP(item) for item in x]
plt.loglog(x, y)
plt.show()
def plot_cgf_int(self):
import matplotlib.pyplot as plt
plt.figure(num=None, figsize=(12, 8), dpi=80, facecolor='w', edgecolor='k')
plt.plot(self.alphas, self.RDPs_int)
plt.xlabel(r'$\lambda$')
plt.ylabel('CGF')
plt.show()
def plot_rdp_int(self):
import matplotlib.pyplot as plt
plt.figure(num=None, figsize=(12, 8), dpi=80, facecolor='w', edgecolor='k')
plt.loglog(self.alphas, self.RDPs_int)
if not self.flag:
self.build_zeroth_oracle()
self.flag = True
x = range(1,self.m_lin_max,1)
y = [self.evalRDP(item) for item in x]
plt.loglog(x, y)
plt.xlabel(r'$\alpha$')
plt.ylabel(r'RDP $\epsilon$')
plt.show()
def get_rdp(self,alphas):
# alphas is a numpy array or a list of numbers
# we will return a numpy array of the corresponding RDP
if not self.flag:
self.build_zeroth_oracle()
self.flag = True
alphas = np.array(alphas)
assert(np.all(alphas >= 1))
rdp_list = []
for alpha in alphas:
rdp_list.append(self.evalRDP(alpha))
return np.array(rdp_list)
def get_eps(self, delta): # minimize over \lambda
if not self.flag:
self.build_zeroth_oracle()
self.flag = True
if delta<0 or delta > 1:
print("Error! delta is a probability and must be between 0 and 1")
if delta == 0:
return self.RDP_inf
else:
def fun(x): # the input the RDP's \alpha
if x <= 1:
return np.inf
else:
return np.log(1 / delta)/(x-1) + self.evalRDP(x)
def fun_int(i): # the input is RDP's \alpha in integer
if i <= 1 | i >= len(self.RDPs_int):
return np.inf
else:
return np.log(1 / delta) / (i-1) + self.RDPs_int[i - 1]
# When do we have computational constraints?
# Only when we have subsampled items.
# First check if the forward difference is positive at self.m, or if it is infinite
while (self.m<self.m_max) and (not np.isposinf(fun(self.m))) and (fun_int(self.m-1)-fun_int(self.m-2) < 0):
# If so, double m, expand logBimomC until the forward difference is positive
if self.flag_subsample:
# The following line is m^2 time.
self.logBinomC = utils.get_binom_coeffs(self.m*2+1)
# Update deltas_caches
for key, val in self.deltas_cache.items():
if type(key) is tuple:
func_tmp = key[0]
else:
func_tmp = key
cgf = lambda x: x*func_tmp(x+1)
deltas,signs_deltas = utils.get_forward_diffs(cgf,self.m*2)
self.deltas_cache[key] = [deltas, signs_deltas]
new_alphas = range(self.m + 1, self.m * 2 + 1, 1)
self.alphas = np.concatenate((self.alphas, np.array(new_alphas))) # array of integers
self.m = self.m * 2
mm = np.max(self.alphas)
rdp_int_new = np.zeros_like(self.alphas, float)
for key,val in self.cache.items():
idx = self.idxhash[key]
rdp = self.RDPs[idx]
newarray = np.zeros_like(self.alphas, float)
for j in range(2,mm+1,1):
newarray[j-1] = rdp(1.0*j)
newarray[0]=newarray[1]
coeff = self.coeffs[idx]
rdp_int_new += newarray * coeff
self.cache[key] = newarray
self.RDPs_int = rdp_int_new
# # update the integer CGF and the cache for each function
# rdp_int_new = np.zeros_like(self.RDPs_int)
# for key,val in self.cache.items():
# idx = self.idxhash[key]
# rdp = self.RDPs[idx]
# newarray = np.zeros_like(self.RDPs_int)
# for j in range(self.m):
# newarray[j] = rdp(1.0*(j+self.m+1))
#
# coeff = self.coeffs[idx]
# rdp_int_new += newarray * coeff
# self.cache[key] = np.concatenate((val, newarray))
#
# # update the corresponding quantities
# self.RDPs_int = np.concatenate((self.RDPs_int, rdp_int_new))
#self.m = self.m*2
bestint = np.argmin(np.log(1 / delta)/(self.alphas[1:]-1) + self.RDPs_int[1:]) + 1
if bestint == self.m-1:
if self.verbose:
print('Warning: Reach quadratic upper bound: m_max.')
# In this case, we matches the maximum qudaratic upper bound
# Fix it by calling O(1) upper bounds and do logarithmic search
cur = fun(bestint)
while (not np.isposinf(cur)) and fun(bestint-1)-fun(bestint-2) < -1e-8:
bestint = bestint*2
cur = fun(bestint)
if bestint > self.m_lin_max and self.approx ==True:
print('Warning: Reach linear upper bound: m_lin_max.')
return cur
results = minimize_scalar(fun, method='Bounded', bounds=[self.m-1, bestint + 2],
options={'disp': False})
if results.success:
return results.fun
else:
return None
#return fun(bestint)
if bestint == 0:
if self.verbose:
print('Warning: Smallest alpha = 1.')
# find the best integer alpha.
bestalpha = self.alphas[bestint]
results = minimize_scalar(fun, method='Bounded',bounds=[bestalpha-1, bestalpha+1],
options={'disp':False})
# the while loop above ensures that bestint+2 is at most m, and also bestint is at least 0.
if results.success:
return results.fun
else:
# There are cases when certain \delta is not feasible.
# For example, let p and q be uniform the privacy R.V. is either 0 or \infty and unless all \infty
# events are taken cared of by \delta, \epsilon cannot be < \infty
return -1
def compose_mechanism(self, func, coeff=1.0):
self.flag = False
if func in self.idxhash:
self.coeffs[self.idxhash[func]] += coeff
# also update the integer CGFs
self.RDPs_int += self.cache[func] * coeff
else:
# book keeping
self.idxhash[func] = self.n
self.n += 1
self.coeffs.append(coeff)
# update the analytical
self.RDPs.append(func)
# also update the integer results
if func in self.cache:
tmp = self.cache[func]
else:
tmp = np.zeros_like(self.RDPs_int, float)
for i in range(self.m):
tmp[i] = func(i+1)
self.cache[func] = tmp # save in cache
self.RDPs_int += tmp * coeff
self.RDP_inf += func(np.inf) * coeff
#795010
#imple 100
def compose_subsampled_mechanism(self, func, prob, coeff=1.0):
# This function is for subsample without replacements.
self.flag = False
self.flag_subsample = True
if (func, prob) in self.idxhash:
idx = self.idxhash[(func, prob)]
# update the coefficients of each function
self.coeffs[idx] += coeff
# also update the integer CGFs
self.RDPs_int += self.cache[(func, prob)] * coeff
else:
def cgf(x):
return x * func(x+1)
# we need forward differences of thpe exp(cgf)
# The following line is the numericall y stable way of implementing it.
# The output is in polar form with logarithmic magnitude
deltas, signs_deltas = utils.get_forward_diffs(cgf,self.m)
#deltas1, signs_deltas1 = get_forward_diffs_direct(func, self.m)
#tmp = deltas-deltas1
self.deltas_cache[(func,prob)] = [deltas,signs_deltas]
def subsample_func_int(x):
# This function evaluates teh CGF at alpha = x, i.e., lamb = x- 1
deltas_local, signs_deltas_local = self.deltas_cache[(func,prob)]
if np.isinf(func(x)):
return np.inf
mm = int(x)
fastupperbound = fast_subsampled_cgf_upperbound(func, mm, prob, deltas_local)
fastupperbound2 = general_upperbound(func, mm, prob)
if self.approx ==True:
if fastupperbound2 <0:
print('general rdp is negative',x)
return fastupperbound2
if mm <= self.alphas[-1]: # compute the bound exactly. Requires book keeping of O(x^2)
moments = [ np.minimum(np.minimum((j)*np.log(np.exp(func(np.inf))-1) + np.minimum(cgf(j-1),np.log(4)),
np.log(2) + cgf(j-1)),
np.log(4) + 0.5*deltas_local[int(2*np.floor(j/2.0))-1]
+ 0.5*deltas_local[int(2*np.ceil(j/2.0))-1]) + j*np.log(prob)
+self.logBinomC[int(mm), j] for j in range(2,int(mm+1),1)]
return np.minimum(fastupperbound, utils.stable_logsumexp([0]+moments))
elif mm <= self.m_lin_max: # compute the bound with stirling approximation. Everything is O(x) now.
moment_bound = lambda j: np.minimum(j * np.log(np.exp(func(np.inf)) - 1)
+ np.minimum(cgf(j - 1), np.log(4)), np.log(2)
+ cgf(j - 1)) + j * np.log(prob) + utils.logcomb(mm, j)
moments = [moment_bound(j) for j in range(2,mm+1,1)]
return np.minimum(fastupperbound, utils.stable_logsumexp([0]+ moments))
else: # Compute the O(1) upper bound
return fastupperbound
def subsample_func(x):
# This function returns the RDP at alpha = x
# RDP with the linear interpolation upper bound of the CGF
epsinf, tmp = subsample_epsdelta(func(np.inf),0,prob)
if np.isinf(x):
return epsinf
if prob == 1.0:
return func(x)
if (x >= 1.0) and (x <= 2.0):
return np.minimum(epsinf, subsample_func_int(2.0) / (2.0-1))
if np.equal(np.mod(x, 1), 0):
return np.minimum(epsinf, subsample_func_int(x) / (x-1) )
xc = math.ceil(x)
xf = math.floor(x)
return np.minimum(
epsinf,
((x-xf)*subsample_func_int(xc) + (1-(x-xf))*subsample_func_int(xf)) / (x-1)
)
# book keeping
self.idxhash[(func, prob)] = self.n # save the index
self.n += 1 # increment the number of unique mechanisms
self.coeffs.append(coeff) # Update the coefficient
self.RDPs.append(subsample_func) # update the analytical functions
# also update the integer results up to m_max.
if (func,prob) in self.cache:
results = self.cache[(func,prob)]
else:
results = np.zeros_like(self.RDPs_int, float)
# m = np.max(self.lambs)
mm = np.max(self.alphas)
for alpha in range(2, mm+1):
results[alpha-1] = subsample_func(alpha)
results[0] = results[1] # Provide the trivial upper bound of RDP at alpha = 1 --- the KL privacy.
self.cache[(func,prob)] = results # save in cache
self.RDPs_int += results * coeff
# update the pure DP
eps, delta = subsample_epsdelta(func(np.inf), 0, prob)
self.RDP_inf += eps * coeff
# mm = np.max(self.alphas)
#
# jvec = np.arange(2, mm+1) #
# logterm3plus = np.zeros_like(results)
# for j in jvec:
# logterm3plus[j-2] = (np.minimum(np.minimum(j * np.log(np.exp(func(np.inf)) - 1)
# + np.minimum(np.log(4),cgf(j-1)), np.log(2) + cgf(j-1)),
# np.log(4) + 0.5 * deltas[int(2 * np.floor(j / 2.0))-1]
# + 0.5 * deltas[int(2 * np.ceil(j / 2.0))-1])
# + j * np.log(prob))
#
# for alpha in range(2, mm+1):
# if np.isinf(logterm3plus[alpha-1]):
# results[alpha-1] = np.inf
# else:
# tmp = utils.stable_logsumexp(logterm3plus[0:alpha-1] + self.logBinomC[alpha, 2:(alpha+1)])
# results[alpha-1] = utils.stable_logsumexp_two(0, tmp) / (1.0*alpha-1)
#
# results[0] = results[1] # Provide the trivial upper bound of RDP at alpha = 1 --- the KL privacy.
#
# self.cache[(func,prob)] = results # save in cache
# self.RDPs_int += results
#
# # For debugging: The following 'results1' should be the same as 'results' above.
# # results1 = np.zeros_like(self.RDPs_int, float)
# # for j in range(self.m):
# # results1[j] = subsample_func(j+1)
#
# eps, delta = subsample_epsdelta(func(np.inf), 0, prob)
# self.RDP_inf += eps
def compose_poisson_subsampled_mechanisms(self, func, prob, coeff=1.0):
# This function implements the lower bound for subsampled RDP.
# It is also the exact formula of poission_subsampled RDP for many mechanisms including Gaussian mech.
#
# At the moment, we do not support mixing poisson subsampling and standard subsampling.
# TODO: modify the caching identifies so that we can distinguish different types of subsampling
#
self.flag = False
self.flag_subsample = True
if (func, prob) in self.idxhash:
idx = self.idxhash[(func, prob)] # TODO: this is really where it needs to be changed.
# update the coefficients of each function
self.coeffs[idx] += coeff
# also update the integer CGFs
self.RDPs_int += self.cache[(func, prob)] * coeff
else: # compute an easy to compute upper bound of it.
def cgf(x):
return x * func(x+1)
def subsample_func_int(x):
# This function evaluates teh CGF at alpha = x, i.e., lamb = x- 1
if np.isinf(func(x)):
return np.inf
mm = int(x)
#
fastbound = fast_poission_subsampled_cgf_upperbound(func, mm, prob)
k = self.alphas[-1]
fastbound_k = fast_k_subsample_upperbound(func, mm, prob,k)
if self.approx == True:
return fastbound_k
#fastbound = min(fastbound, fastbound_k)
if x <= self.alphas[-1]: # compute the bound exactly.
moments = [cgf(j-1) +j*np.log(prob) + (mm-j) * np.log(1-prob)
+ self.logBinomC[mm, j] for j in range(2,mm+1,1)]
return utils.stable_logsumexp([(mm-1)*np.log(1-prob)+np.log(1+(mm-1)*prob)]+moments)
elif mm <= self.m_lin_max:
moments = [cgf(j-1) +j*np.log(prob) + (mm-j) * np.log(1-prob)
+ utils.logcomb(mm,j) for j in range(2,mm+1,1)]
return utils.stable_logsumexp([(mm-1)*np.log(1-prob)+np.log(1+(mm-1)*prob)] + moments)
else:
return fastbound
def subsample_func(x): # linear interpolation upper bound
# This function implements the RDP at alpha = x
if np.isinf(func(x)):
return np.inf
if prob == 1.0:
return func(x)
epsinf, tmp = subsample_epsdelta(func(np.inf),0,prob)
if np.isinf(x):
return epsinf
if (x >= 1.0) and (x <= 2.0):
return np.minimum(epsinf, subsample_func_int(2.0) / (2.0-1))
if np.equal(np.mod(x, 1), 0):
return np.minimum(epsinf, subsample_func_int(x) / (x-1) )
xc = math.ceil(x)
xf = math.floor(x)
return np.minimum(
epsinf,
((x-xf)*subsample_func_int(xc) + (1-(x-xf))*subsample_func_int(xf)) / (x-1)
)
# book keeping
self.idxhash[(func, prob)] = self.n # save the index
self.n += 1 # increment the number of unique mechanisms
self.coeffs.append(coeff) # Update the coefficient
self.RDPs.append(subsample_func) # update the analytical functions
# also update the integer results, with a vectorized computation.
# TODO: pre-computing subsampled RDP for integers is error-prone (implement the same thing twice)
# TODO: and its benefits are not clear. We should consider removing it and simply call the lambda function.
#
if (func,prob) in self.cache:
results = self.cache[(func,prob)]
else:
results = np.zeros_like(self.RDPs_int, float)
mm = np.max(self.alphas) # evaluate the RDP up to order mm
jvec = np.arange(2, mm + 1)
logterm3plus = np.zeros_like(results) # This saves everything from j=2 to j = m+1
for j in jvec:
logterm3plus[j-2] = cgf(j-1) + j * np.log(prob) #- np.log(1-prob))
for alpha in range(2, mm+1):
if np.isinf(logterm3plus[alpha-1]):
results[alpha-1] = np.inf
else:
tmp = utils.stable_logsumexp(logterm3plus[0:alpha-1] + self.logBinomC[alpha , 2:(alpha + 1)]
+ (alpha+1-jvec[0:alpha-1])*np.log(1-prob))
results[alpha-1] = utils.stable_logsumexp_two((alpha-1)*np.log(1-prob)
+ np.log(1+(alpha-1)*prob), tmp) / (1.0*alpha-1)
results[0] = results[1] # Provide the trivial upper bound of RDP at alpha = 1 --- the KL privacy.
self.cache[(func,prob)] = results # save in cache
self.RDPs_int += results * coeff
# update the pure DP tracker
eps, delta = subsample_epsdelta(func(np.inf), 0, prob)
self.RDP_inf += eps * coeff
def compose_poisson_subsampled_mechanisms1(self, func, prob, coeff=1.0):
# This function implements the general amplification bounds for Poisson sampling.
# No additional assumptions are needed.
# At the moment, we do not support mixing poisson subsampling and standard subsampling.
#
self.flag = False
self.flag_subsample = True
if (func, prob) in self.idxhash:
idx = self.idxhash[(func, prob)]
# update the coefficients of each function
self.coeffs[idx] += coeff
# also update the integer CGFs
self.RDPs_int += self.cache[(func, prob)] * coeff
else: # compute an easy to compute upper bound of it.
cgf = lambda x: x*func(x+1)
def subsample_func_int(x):
# This function evaluates the CGF at alpha = x, i.e., lamb = x- 1
if np.isinf(func(x)):
return np.inf
if prob == 1.0:
return func(x)
mm = int(x)
fastbound = fast_poission_subsampled_cgf_upperbound(func, mm, prob)
if x <= self.alphas[-1]: # compute the bound exactly.
moments = [cgf(1) + 2*np.log(prob) + (mm-2) * np.log(1 - prob) + self.logBinomC[mm, 2]]
moments = moments + [cgf(j-1+1) +j*np.log(prob) + (mm-j) * np.log(1 - prob)
+ self.logBinomC[mm, j] for j in range(3,mm+1,1)]
return utils.stable_logsumexp([(mm-1)*np.log(1-prob)+np.log(1+(mm-1)*prob)]+moments)
elif mm <= self.m_lin_max:
moments = [cgf(1) + 2*np.log(prob) + (mm-2) * np.log(1 - prob) + utils.logcomb(mm, 2)]
moments = moments + [cgf(j-1+1) +j*np.log(prob) + (mm-j) * np.log(1 - prob)
+ utils.logcomb(mm, j) for j in range(3,mm+1,1)]
return utils.stable_logsumexp([(mm-1)*np.log(1-prob)+np.log(1+(mm-1)*prob)]+moments)
else:
return fastbound
def subsample_func(x): # linear interpolation upper bound
epsinf, tmp = subsample_epsdelta(func(np.inf),0,prob)
if np.isinf(x):
return epsinf
if (x >= 1.0) and (x <= 2.0):
return np.minimum(epsinf, subsample_func_int(2.0) / (2.0-1))
if np.equal(np.mod(x, 1), 0):
return np.minimum(epsinf, subsample_func_int(x) / (x-1) )
xc = math.ceil(x)
xf = math.floor(x)
return np.minimum(
epsinf,
((x-xf)*subsample_func_int(xc) + (1-(x-xf))*subsample_func_int(xf)) / (x-1)
)
# book keeping
self.idxhash[(func, prob)] = self.n # save the index
self.n += 1 # increment the number of unique mechanisms
self.coeffs.append(coeff) # Update the coefficient
self.RDPs.append(subsample_func) # update the analytical functions
# also update the integer results
if (func,prob) in self.cache:
results = self.cache[(func,prob)]
else:
results = np.zeros_like(self.RDPs_int, float)
mm = np.max(self.alphas) # evaluate the RDP up to order mm
for alpha in range(2, mm+1):
results[alpha-1] = subsample_func_int(alpha)
results[0] = results[1] # Provide the trivial upper bound of RDP at alpha = 1 --- the KL privacy.
self.cache[(func,prob)] = results # save in cache
self.RDPs_int += results * coeff
# update the pure DP tracker
eps, delta = subsample_epsdelta(func(np.inf), 0, prob)
self.RDP_inf += eps * coeff
# TODO: 1. Modularize the several Poission sampling versions. 2. Support both sampling schemes together.
|
import bson
import ujson
from bson import ObjectId
from .utils import db
def lambda_handler(event, context):
try:
object_id = event["pathParameters"]["Id"]
except TypeError:
object_id = None
mongo = db.MongoDBConnection()
with mongo:
database = mongo.connection['myDB']
collection = database['registrations']
try:
collection.delete_one({"_id": ObjectId(object_id)})
except bson.errors.InvalidId:
return {
"statusCode": 400,
"body": ujson.dumps({
"message": "Error ! Invalid ObjectId",
"data": None
})
}
return {
"statusCode": 204,
"body": ujson.dumps({
"message": "Data Deleted !",
"data": None
})
} |
import wx, wx.html
from wx.lib.expando import ExpandoTextCtrl
#from gui.uberwidgets.formattedinput import FormattedInput
#from gui.uberwidgets.SizerBar import SizerBar
import gettext
gettext.install('Digsby', unicode=True)
from gui.skin import skininit
from gui.uberwidgets.formattedinput import FormattedInput
class P(wx.Panel):
def __init__(self,parent):
wx.Panel.__init__(self,parent,-1)
self.Sizer=wx.BoxSizer(wx.VERTICAL)
from util import trace
trace(ExpandoTextCtrl)
#profile = ExpandoTextCtrl(self,style= wx.TE_MULTILINE|wx.TE_CHARWRAP|wx.TE_PROCESS_ENTER|wx.NO_BORDER|wx.WANTS_CHARS|wx.TE_NOHIDESEL|wx.TE_RICH)
profile=FormattedInput(self)
self.Sizer.Add(profile,0)
self.Layout()
class F(wx.Frame):
def __init__(self):
wx.Frame.__init__(self,None,-1,"Profile Box Test")
self.Sizer =wx.BoxSizer(wx.VERTICAL)
p=P(self)
self.Sizer.Add(p,1,wx.EXPAND)
class A(wx.App):
def OnInit(self):
# self.Bind(wx.EVT_KEY_DOWN,self.OnKeyDown)
skininit('../../../res')
f=F()
f.Bind(wx.EVT_CLOSE, lambda e: self.ExitMainLoop())
wx.CallAfter(f.Show)
# pref=PreF()
# pref.Show(True)
return True
if __name__=='__main__':
#a = A( 0 )
#from util import profile
#profile(a.MainLoop)
from tests.testapp import testapp
a = testapp('../../../../')
f = F()
# inp = FormattedInput(f)
# s.Add(inp, 0, wx.EXPAND)
# def doit(e):
# inp.Fit()
#inp.bemote.Bind(wx.EVT_BUTTON, doit)
f.Show()
a.MainLoop()
|
import logging
from datetime import datetime, timezone
from typing import Any, Dict, Union
from .exceptions import NotFoundException, ServerFailureException
from .utils import BaseDict
_LOGGER = logging.getLogger(__name__)
STATUS = {
0: "OFFLINE",
1: "DISCONNECTED",
2: "AWAITING_START",
3: "CHARGING",
4: "COMPLETED",
5: "ERROR",
6: "READY_TO_CHARGE",
}
NODE_TYPE = {1: "Master", 2: "Extender"}
PHASE_MODE = {1: "Locked to single phase", 2: "Auto", 3: "Locked to three phase"}
REASON_FOR_NO_CURRENT = {
# Work-in-progress, must be taken with a pinch of salt, as per now just reverse engineering of observations until API properly documented
None: "No reason",
0: "No reason, charging or ready to charge",
1: "Charger paused",
2: "Charger paused",
3: "Charger paused",
4: "Charger paused",
5: "Charger paused",
6: "Charger paused",
9: "Error no current",
50: "Secondary unit not requesting current or no car connected",
51: "Charger paused",
52: "Charger paused",
53: "Charger disabled",
54: "Waiting for schedule/auth",
55: "Pending auth",
}
class ChargerState(BaseDict):
""" Charger state with integer enum values converted to human readable string values"""
def __init__(self, state: Dict[str, Any], raw=False):
if not raw:
data = {
**state,
"chargerOpMode": STATUS[state["chargerOpMode"]],
"reasonForNoCurrent": f"({state['reasonForNoCurrent']}) {REASON_FOR_NO_CURRENT.get(state['reasonForNoCurrent'], 'Unknown')}",
}
else:
data = {
**state,
"reasonForNoCurrent": "none" if state["reasonForNoCurrent"] is None else state["reasonForNoCurrent"],
}
super().__init__(data)
class ChargerConfig(BaseDict):
""" Charger config with integer enum values converted to human readable string values"""
def __init__(self, config: Dict[str, Any], raw=False):
if not raw:
data = {
**config,
"localNodeType": NODE_TYPE[config["localNodeType"]],
"phaseMode": PHASE_MODE[config["phaseMode"]],
}
else:
data = {**config}
super().__init__(data)
class ChargerSchedule(BaseDict):
""" Charger charging schedule/plan """
def __init__(self, schedule: Dict[str, Any]):
data = {
"id": schedule.get("id"),
"chargeStartTime": schedule.get("chargeStartTime"),
"chargeStopTime": schedule.get("chargeStopTime"),
"repeat": schedule.get("repeat"),
"isEnabled": schedule.get("isEnabled"),
}
super().__init__(data)
class ChargerWeeklySchedule(BaseDict):
""" Charger charging schedule/plan """
def __init__(self, schedule: Dict[str, Any]):
days = schedule.get("days")
data = {
"isEnabled": schedule.get("isEnabled"),
"MondayStartTime": "-",
"MondayStopTime": "-",
"TuesdayStartTime": "-",
"TuesdayStopTime": "-",
"WednesdayStartTime": "-",
"WednesdayStopTime": "-",
"ThursdayStartTime": "-",
"ThursdayStopTime": "-",
"FridayStartTime": "-",
"FridayStopTime": "-",
"SaturdayStartTime": "-",
"SaturdayStopTime": "-",
"SundayStartTime": "-",
"SundayStopTime": "-",
"days": days,
}
if data["isEnabled"]:
tzinfo = datetime.utcnow().astimezone().tzinfo
for day in days:
ranges = day["ranges"]
for times in ranges:
start = (
datetime.strptime(times["startTime"], "%H:%MZ")
.replace(tzinfo=timezone.utc)
.astimezone(tzinfo)
.strftime("%H:%M")
)
stop = (
datetime.strptime(times["stopTime"], "%H:%MZ")
.replace(tzinfo=timezone.utc)
.astimezone(tzinfo)
.strftime("%H:%M")
)
if day["dayOfWeek"] == 0:
data["MondayStartTime"] = start
data["MondayStopTime"] = stop
elif day["dayOfWeek"] == 1:
data["TuesdayStartTime"] = start
data["TuesdayStopTime"] = stop
elif day["dayOfWeek"] == 2:
data["WednesdayStartTime"] = start
data["WednesdayStopTime"] = stop
elif day["dayOfWeek"] == 3:
data["ThursdayStartTime"] = start
data["ThursdayStopTime"] = stop
elif day["dayOfWeek"] == 4:
data["FridayStartTime"] = start
data["FridayStopTime"] = stop
elif day["dayOfWeek"] == 5:
data["SaturdayStartTime"] = start
data["SaturdayStopTime"] = stop
elif day["dayOfWeek"] == 6:
data["SundayStartTime"] = start
data["SundayStopTime"] = stop
super().__init__(data)
class ChargerSession(BaseDict):
""" Charger charging session """
def __init__(self, session: Dict[str, Any]):
data = {
"carConnected": session.get("carConnected"),
"carDisconnected": session.get("carDisconnected"),
"kiloWattHours": float(session.get("kiloWattHours")),
}
super().__init__(data)
class Charger(BaseDict):
def __init__(self, entries: Dict[str, Any], easee: Any, site: Any = None, circuit: Any = None):
super().__init__(entries)
self.id: str = entries["id"]
self.name: str = entries["name"]
self.site = site
self.circuit = circuit
self.easee = easee
async def get_consumption_between_dates(self, from_date: datetime, to_date):
""" Gets consumption between two dates """
try:
value = await (
await self.easee.get(
f"/api/sessions/charger/{self.id}/total/{from_date.isoformat()}/{to_date.isoformat()}"
)
).text()
return float(value)
except (ServerFailureException):
return None
async def get_sessions_between_dates(self, from_date: datetime, to_date):
""" Gets charging sessions between two dates """
try:
sessions = await (
await self.easee.get(
f"/api/sessions/charger/{self.id}/sessions/{from_date.isoformat()}/{to_date.isoformat()}"
)
).json()
sessions = [ChargerSession(session) for session in sessions]
sessions.sort(key=lambda x: x["carConnected"], reverse=True)
return sessions
except (ServerFailureException):
return None
async def get_config(self, from_cache=False, raw=False) -> ChargerConfig:
""" get config for charger """
try:
config = await (await self.easee.get(f"/api/chargers/{self.id}/config")).json()
return ChargerConfig(config, raw)
except (ServerFailureException):
return None
async def get_state(self, raw=False) -> ChargerState:
""" get state for charger """
try:
state = await (await self.easee.get(f"/api/chargers/{self.id}/state")).json()
return ChargerState(state, raw)
except (ServerFailureException):
return None
async def start(self):
"""Start charging session"""
try:
return await self.easee.post(f"/api/chargers/{self.id}/commands/start_charging")
except (ServerFailureException):
return None
async def pause(self):
"""Pause charging session"""
try:
return await self.easee.post(f"/api/chargers/{self.id}/commands/pause_charging")
except (ServerFailureException):
return None
async def resume(self):
"""Resume charging session"""
try:
return await self.easee.post(f"/api/chargers/{self.id}/commands/resume_charging")
except (ServerFailureException):
return None
async def stop(self):
"""Stop charging session"""
try:
return await self.easee.post(f"/api/chargers/{self.id}/commands/stop_charging")
except (ServerFailureException):
return None
async def toggle(self):
"""Toggle charging session start/stop/pause/resume """
try:
return await self.easee.post(f"/api/chargers/{self.id}/commands/toggle_charging")
except (ServerFailureException):
return None
async def get_basic_charge_plan(self) -> ChargerSchedule:
"""Get and return charger basic charge plan setting from cloud """
try:
plan = await self.easee.get(f"/api/chargers/{self.id}/basic_charge_plan")
plan = await plan.json()
return ChargerSchedule(plan)
except (NotFoundException):
_LOGGER.debug("No scheduled charge plan")
return None
except (ServerFailureException):
return None
# TODO: document types
async def set_basic_charge_plan(self, id, chargeStartTime, chargeStopTime, repeat=True):
"""Set and post charger basic charge plan setting to cloud """
json = {
"id": id,
"chargeStartTime": str(chargeStartTime),
"chargeStopTime": str(chargeStopTime),
"repeat": repeat,
"isEnabled": True,
}
try:
return await self.easee.post(f"/api/chargers/{self.id}/basic_charge_plan", json=json)
except (ServerFailureException):
return None
async def get_weekly_charge_plan(self) -> ChargerWeeklySchedule:
"""Get and return charger basic charge plan setting from cloud """
try:
plan = await self.easee.get(f"/api/chargers/{self.id}/weekly_charge_plan")
plan = await plan.json()
_LOGGER.debug(plan)
return ChargerWeeklySchedule(plan)
except (NotFoundException):
_LOGGER.debug("No scheduled charge plan")
return None
except (ServerFailureException):
return None
# TODO: document types
async def set_weekly_charge_plan(self, day, chargeStartTime, chargeStopTime, enabled=True):
"""Set and post charger basic charge plan setting to cloud """
json = {
"isEnabled": enabled,
"days": [
{
"dayOfWeek": day,
"ranges": [
{
"startTime": str(chargeStartTime),
"stopTime": str(chargeStopTime),
}
],
}
],
}
try:
return await self.easee.post(f"/api/chargers/{self.id}/weekly_charge_plan", json=json)
except (ServerFailureException):
return None
async def enable_charger(self, enable: bool):
"""Enable and disable charger in charger settings """
json = {"enabled": enable}
try:
return await self.easee.post(f"/api/chargers/{self.id}/settings", json=json)
except (ServerFailureException):
return None
async def enable_idle_current(self, enable: bool):
"""Enable and disable idle current in charger settings """
json = {"enableIdleCurrent": enable}
try:
return await self.easee.post(f"/api/chargers/{self.id}/settings", json=json)
except (ServerFailureException):
return None
async def limitToSinglePhaseCharging(self, enable: bool):
"""Limit to single phase charging in charger settings """
json = {"limitToSinglePhaseCharging": enable}
try:
return await self.easee.post(f"/api/chargers/{self.id}/settings", json=json)
except (ServerFailureException):
return None
async def phaseMode(self, mode: int = 2):
"""Set charging phase mode, 1 = always 1-phase, 2 = auto, 3 = always 3-phase """
json = {"phaseMode": mode}
try:
return await self.easee.post(f"/api/chargers/{self.id}/settings", json=json)
except (ServerFailureException):
return None
async def lockCablePermanently(self, enable: bool):
"""Lock and unlock cable permanently in charger settings """
json = {"lockCablePermanently": enable}
try:
return await self.easee.post(f"/api/chargers/{self.id}/settings", json=json)
except (ServerFailureException):
return None
async def smartButtonEnabled(self, enable: bool):
"""Enable and disable smart button in charger settings """
json = {"smartButtonEnabled": enable}
try:
return await self.easee.post(f"/api/chargers/{self.id}/settings", json=json)
except (ServerFailureException):
return None
async def delete_basic_charge_plan(self):
"""Delete charger basic charge plan setting from cloud """
try:
return await self.easee.delete(f"/api/chargers/{self.id}/basic_charge_plan")
except (ServerFailureException):
return None
async def override_schedule(self):
"""Override scheduled charging and start charging"""
try:
return await self.easee.post(f"/api/chargers/{self.id}/commands/override_schedule")
except (ServerFailureException):
return None
async def smart_charging(self, enable: bool):
"""Set charger smart charging setting"""
json = {"smartCharging": enable}
try:
return await self.easee.post(f"/api/chargers/{self.id}/settings", json=json)
except (ServerFailureException):
return None
async def reboot(self):
"""Reboot charger"""
try:
return await self.easee.post(f"/api/chargers/{self.id}/commands/reboot")
except (ServerFailureException):
return None
async def update_firmware(self):
"""Update charger firmware"""
try:
return await self.easee.post(f"/api/chargers/{self.id}/commands/update_firmware")
except (ServerFailureException):
return None
async def set_dynamic_charger_circuit_current(self, currentP1: int, currentP2: int = None, currentP3: int = None, timeToLive: int = 0):
""" Set dynamic current on circuit level. timeToLive specifies, in minutes, for how long the new dynamic current is valid. timeToLive = 0 means that the new dynamic current is valid until changed the next time. The dynamic current is always reset to default when the charger is restarted."""
if self.circuit is not None:
return await self.circuit.set_dynamic_current(currentP1, currentP2, currentP3, timeToLive)
else:
_LOGGER.info("Circuit info must be initialized for dynamic current to be set")
async def set_max_charger_circuit_current(self, currentP1: int, currentP2: int = None, currentP3: int = None):
""" Set circuit max current for charger """
if self.circuit is not None:
return await self.circuit.set_max_current(currentP1, currentP2, currentP3)
else:
_LOGGER.info("Circuit info must be initialized for max current to be set")
async def set_max_offline_charger_circuit_current(
self, currentP1: int, currentP2: int = None, currentP3: int = None
):
""" Set circuit max offline current for charger, fallback value for limit if charger is offline """
if self.circuit is not None:
return await self.circuit.set_max_offline_current(currentP1, currentP2, currentP3)
else:
_LOGGER.info("Circuit info must be initialized for offline current to be set")
async def set_dynamic_charger_current(self, current: int):
""" Set charger dynamic current """
json = {"dynamicChargerCurrent": current}
try:
return await self.easee.post(f"/api/chargers/{self.id}/settings", json=json)
except (ServerFailureException):
return None
async def set_max_charger_current(self, current: int):
""" Set charger max current """
json = {"maxChargerCurrent": current}
try:
return await self.easee.post(f"/api/chargers/{self.id}/settings", json=json)
except (ServerFailureException):
return None
async def set_access(self, access: Union[int, str]):
""" Set the level of access for a changer """
json = {
1: 1,
2: 2,
3: 3,
"open_for_all": 1,
"easee_account_required": 2,
"whitelist": 3,
}
try:
return await self.easee.put(f"/api/chargers/{self.id}/access", json=json[access])
except (ServerFailureException):
return None
async def delete_access(self):
""" Revert permissions overridden on a charger level"""
try:
return await self.easee.delete(f"/api/chargers/{self.id}/access")
except (ServerFailureException):
return None
|
import unittest
from unittest.mock import MagicMock, patch
from unit_tests.data import \
test_process_message_data_valid, \
test_process_message_no_feature_collection
from maintain_feeder.utilities.local_land_charge import process_land_charge
from maintain_feeder.models import LocalLandChargeHistory, LocalLandCharge
from maintain_feeder.exceptions import ApplicationError
message = MagicMock()
class TestLocalLandCharge(unittest.TestCase):
def setUp(self):
self.merge_called_with = None
def mock_convert(self, charge, version):
return charge
def mock_merge(self, obj):
self.merge_called_with = obj
return obj
@patch('maintain_feeder.utilities.local_land_charge.session')
def test_process_land_charge_prev_version(self, mock_session):
mock_session.query.return_value.filter.return_value.first.return_value = MagicMock()
process_land_charge(MagicMock(), test_process_message_data_valid.process_message_valid)
mock_session.add.assert_called_with(Any(LocalLandChargeHistory))
mock_session.merge.assert_not_called()
mock_session.commit.assert_called()
@patch('maintain_feeder.utilities.local_land_charge.session')
def test_process_land_charge_ok(self, mock_session):
mock_session.query.return_value.filter.return_value.first.return_value = None
mock_session.merge = self.mock_merge
process_land_charge(MagicMock(), test_process_message_data_valid.process_message_valid)
mock_session.add.assert_called_with(Any(LocalLandChargeHistory))
self.assertTrue(isinstance(self.merge_called_with, LocalLandCharge))
mock_session.commit.assert_called()
@patch('maintain_feeder.utilities.local_land_charge.session')
def test_process_land_charge_vary(self, mock_session):
mock_session.query.return_value.filter.return_value.first.return_value = None
mock_session.merge = self.mock_merge
process_land_charge(MagicMock(), test_process_message_data_valid.process_message_valid_vary)
mock_session.add.assert_called_with(Any(LocalLandChargeHistory))
self.assertTrue(isinstance(self.merge_called_with, LocalLandCharge))
mock_session.commit.assert_called()
@patch('maintain_feeder.utilities.local_land_charge.session')
def test_process_land_charge_invalid_geo(self, mock_session):
mock_session.query.return_value.filter.return_value.first.return_value = None
mock_session.merge = self.mock_merge
with self.assertRaises(ApplicationError) as exc:
process_land_charge(
MagicMock(), test_process_message_no_feature_collection.process_message_no_feature_collection)
mock_session.add.assert_called_with(Any(LocalLandChargeHistory))
self.assertTrue(isinstance(self.merge_called_with, LocalLandCharge))
mock_session.commit.assert_not_called()
mock_session.rollback.assert_called()
self.assertEqual(str(exc.exception), "No FeatureCollection found in entry")
class Any(object):
def __init__(self, cls):
self.cls = cls
def __eq__(self, other):
return isinstance(other, self.cls)
|
"""Unit tests for the parameter model."""
from external.data_model.parameters import IntegerParameter
from .meta.base import MetaModelTestCase
class IntegerParameterTest(MetaModelTestCase):
"""Integer parameter unit tests."""
MODEL = IntegerParameter
def test_check_unit(self):
"""Test that a parameter with the integer type also has a unit."""
self.check_validation_error(
"Parameter Parameter has no unit",
name="Parameter",
type="integer",
metrics=[],
)
|
from Houdini.Handlers import Handlers, XT
class Waddle(object):
def __init__(self, id, seats, game, room):
self.id = id
self.seats = seats
self.game = game
self.room = room
self.penguins = [None] * seats
def add(self, penguin):
seatId = self.penguins.index(None)
self.penguins[seatId] = penguin
penguin.sendXt("jw", seatId)
self.room.sendXt("uw", self.id, seatId, penguin.user.Username)
penguin.waddle = self
if self.penguins.count(None) == 0:
self.game(list(self.penguins), self.seats)
self.reset()
def remove(self, penguin):
seatId = self.getSeatId(penguin)
self.penguins[seatId] = None
self.room.sendXt("uw", self.id, seatId)
penguin.waddle = None
def reset(self):
for seatId, penguin in enumerate(self.penguins):
if penguin:
self.penguins[seatId] = None
self.room.sendXt("uw", self.id, seatId)
def getSeatId(self, penguin):
return self.penguins.index(penguin)
def WaddleHandler(*waddle):
def handlerFunction(function):
def handler(penguin, data):
if penguin.waddle and type(penguin.waddle) in waddle:
function(penguin, data)
return function
return handler
return handlerFunction
def leaveWaddle(self):
if self.waddle:
self.waddle.remove(self)
@Handlers.Handle(XT.GetWaddlePopulation)
def handleGetWaddlePopulation(self, data):
try:
waddles = []
for waddleId in data.Waddles:
waddle = self.room.waddles[int(waddleId)]
penguinNames = ",".join((penguin.user.Username if penguin else str() for penguin in waddle.penguins))
waddles.append(waddleId + "|" + penguinNames)
self.sendXt("gw", "%".join(waddles))
except KeyError:
self.logger.warn("Waddle does not exist!")
@Handlers.Handle(XT.JoinWaddle)
def handleJoinWaddle(self, data):
try:
if not self.waddle:
waddle = self.room.waddles[data.WaddleId]
waddle.add(self)
except KeyError:
self.logger.warn("{} Tried to join a waddle which does not exist!"
.format(self.user.Username))
@Handlers.Handle(XT.LeaveWaddle)
def handleLeaveWaddle(self, data):
if self.waddle:
self.waddle.remove(self)
|
# Copyright 2013 IBM Corp.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from nova import db
from nova.objects import instance
from nova.objects import security_group
from nova.tests.unit.objects import test_objects
fake_secgroup = {
'created_at': None,
'updated_at': None,
'deleted_at': None,
'deleted': None,
'id': 1,
'name': 'fake-name',
'description': 'fake-desc',
'user_id': 'fake-user',
'project_id': 'fake-project',
}
class _TestSecurityGroupObject(object):
def _fix_deleted(self, db_secgroup):
# NOTE(danms): Account for the difference in 'deleted'
return dict(db_secgroup.items(), deleted=False)
def test_get(self):
self.mox.StubOutWithMock(db, 'security_group_get')
db.security_group_get(self.context, 1).AndReturn(fake_secgroup)
self.mox.ReplayAll()
secgroup = security_group.SecurityGroup.get(self.context, 1)
self.assertEqual(self._fix_deleted(fake_secgroup),
dict(secgroup.items()))
self.assertEqual(secgroup.obj_what_changed(), set())
self.assertRemotes()
def test_get_by_name(self):
self.mox.StubOutWithMock(db, 'security_group_get_by_name')
db.security_group_get_by_name(self.context, 'fake-project',
'fake-name').AndReturn(fake_secgroup)
self.mox.ReplayAll()
secgroup = security_group.SecurityGroup.get_by_name(self.context,
'fake-project',
'fake-name')
self.assertEqual(self._fix_deleted(fake_secgroup),
dict(secgroup.items()))
self.assertEqual(secgroup.obj_what_changed(), set())
self.assertRemotes()
def test_in_use(self):
self.mox.StubOutWithMock(db, 'security_group_in_use')
db.security_group_in_use(self.context, 123).AndReturn(True)
self.mox.ReplayAll()
secgroup = security_group.SecurityGroup()
secgroup.id = 123
self.assertTrue(secgroup.in_use(self.context))
self.assertRemotes()
def test_save(self):
self.mox.StubOutWithMock(db, 'security_group_update')
updated_secgroup = dict(fake_secgroup, project_id='changed')
db.security_group_update(self.context, 1,
{'description': 'foobar'}).AndReturn(
updated_secgroup)
self.mox.ReplayAll()
secgroup = security_group.SecurityGroup._from_db_object(
self.context, security_group.SecurityGroup(), fake_secgroup)
secgroup.description = 'foobar'
secgroup.save(self.context)
self.assertEqual(self._fix_deleted(updated_secgroup),
dict(secgroup.items()))
self.assertEqual(secgroup.obj_what_changed(), set())
self.assertRemotes()
def test_save_no_changes(self):
self.mox.StubOutWithMock(db, 'security_group_update')
self.mox.ReplayAll()
secgroup = security_group.SecurityGroup._from_db_object(
self.context, security_group.SecurityGroup(), fake_secgroup)
secgroup.save(self.context)
def test_refresh(self):
updated_secgroup = dict(fake_secgroup, description='changed')
self.mox.StubOutWithMock(db, 'security_group_get')
db.security_group_get(self.context, 1).AndReturn(updated_secgroup)
self.mox.ReplayAll()
secgroup = security_group.SecurityGroup._from_db_object(
self.context, security_group.SecurityGroup(), fake_secgroup)
secgroup.refresh(self.context)
self.assertEqual(self._fix_deleted(updated_secgroup),
dict(secgroup.items()))
self.assertEqual(secgroup.obj_what_changed(), set())
self.assertRemotes()
class TestSecurityGroupObject(test_objects._LocalTest,
_TestSecurityGroupObject):
pass
class TestSecurityGroupObjectRemote(test_objects._RemoteTest,
_TestSecurityGroupObject):
pass
fake_secgroups = [
dict(fake_secgroup, id=1, name='secgroup1'),
dict(fake_secgroup, id=2, name='secgroup2'),
]
class _TestSecurityGroupListObject(object):
def test_get_all(self):
self.mox.StubOutWithMock(db, 'security_group_get_all')
db.security_group_get_all(self.context).AndReturn(fake_secgroups)
self.mox.ReplayAll()
secgroup_list = security_group.SecurityGroupList.get_all(self.context)
for i in range(len(fake_secgroups)):
self.assertIsInstance(secgroup_list[i],
security_group.SecurityGroup)
self.assertEqual(fake_secgroups[i]['id'],
secgroup_list[i]['id'])
self.assertEqual(secgroup_list[i]._context, self.context)
def test_get_by_project(self):
self.mox.StubOutWithMock(db, 'security_group_get_by_project')
db.security_group_get_by_project(self.context,
'fake-project').AndReturn(
fake_secgroups)
self.mox.ReplayAll()
secgroup_list = security_group.SecurityGroupList.get_by_project(
self.context, 'fake-project')
for i in range(len(fake_secgroups)):
self.assertIsInstance(secgroup_list[i],
security_group.SecurityGroup)
self.assertEqual(fake_secgroups[i]['id'],
secgroup_list[i]['id'])
def test_get_by_instance(self):
inst = instance.Instance()
inst.uuid = 'fake-inst-uuid'
self.mox.StubOutWithMock(db, 'security_group_get_by_instance')
db.security_group_get_by_instance(self.context,
'fake-inst-uuid').AndReturn(
fake_secgroups)
self.mox.ReplayAll()
secgroup_list = security_group.SecurityGroupList.get_by_instance(
self.context, inst)
for i in range(len(fake_secgroups)):
self.assertIsInstance(secgroup_list[i],
security_group.SecurityGroup)
self.assertEqual(fake_secgroups[i]['id'],
secgroup_list[i]['id'])
class TestSecurityGroupListObject(test_objects._LocalTest,
_TestSecurityGroupListObject):
pass
class TestSecurityGroupListObjectRemote(test_objects._RemoteTest,
_TestSecurityGroupListObject):
pass
|
# coding=utf-8
# Copyright 2017 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
from pants.base.deprecated import deprecated_module
from pants.java.jar.exclude import Exclude
deprecated_module('1.5.0.dev0', 'Use pants.backend.jvm.exclude instead')
Exclude = Exclude
|
# qlearningAgents.py
# ------------------
# based on http://inst.eecs.berkeley.edu/~cs188/sp09/pacman.html
from game import *
from learningAgents import ReinforcementAgent
from scipy.spatial import distance
from featureExtractors import *
import numpy as np
import random
import util
import math
from collections import defaultdict
class QLearningAgent(ReinforcementAgent):
"""
Q-Learning Agent
Instance variables you have access to
- self.epsilon (exploration prob)
- self.alpha (learning rate)
- self.discount (discount rate aka gamma)
Functions you should use
- self.getLegalActions(state)
which returns legal actions for a state
- self.getQValue(state,action)
which returns Q(state,action)
- self.setQValue(state,action,value)
which sets Q(state,action) := value
!!!Important!!!
NOTE: please avoid using self._qValues directly to make code cleaner
"""
def __init__(self, **args):
"We initialize agent and Q-values here."
ReinforcementAgent.__init__(self, **args)
self._qValues = defaultdict(lambda: defaultdict(lambda: 0))
def extractFeatures(self, state):
pos = state.getPacmanPosition()
hasWall = state.hasWall(*pos)
ghostPos = tuple(state.getGhostPositions())
capsulesPos = tuple(state.getCapsules())
return pos, hasWall, ghostPos, capsulesPos
def getQValue(self, state, action):
"""
Returns Q(state,action)
"""
state_features = self.extractFeatures(state)
return self._qValues[state_features][action]
def setQValue(self, state, action, value):
"""
Sets the Qvalue for [state,action] to the given value
"""
state_features = self.extractFeatures(state)
self._qValues[state_features][action] = value
#---------------------#start of your code#---------------------#
def getValue(self, state):
"""
Returns max_action Q(state,action)
where the max is over legal actions.
"""
possibleActions = self.getLegalActions(state)
# If there are no legal actions, return 0.0
if len(possibleActions) == 0:
return 0.0
value = max([self.getQValue(state, action) for action in possibleActions])
return value
def getPolicy(self, state):
"""
Compute the best action to take in a state.
"""
possibleActions = self.getLegalActions(state)
# If there are no legal actions, return None
if len(possibleActions) == 0:
return None
best_action = None
best_action_indx = np.argmax([self.getQValue(state, action) for action in possibleActions])
best_action = possibleActions[best_action_indx]
return best_action
def getAction(self, state):
"""
Compute the action to take in the current state, including exploration.
With probability self.epsilon, we should take a random action.
otherwise - the best policy action (self.getPolicy).
HINT: You might want to use util.flipCoin(prob)
HINT: To pick randomly from a list, use random.choice(list)
"""
# Pick Action
possibleActions = self.getLegalActions(state)
action = None
# If there are no legal actions, return None
if len(possibleActions) == 0:
return None
# agent parameters:
epsilon = self.epsilon
prob = random.random()
action = random.choice(possibleActions) if prob < epsilon else self.getPolicy(state)
return action
def update(self, state, action, nextState, reward):
"""
You should do your Q-Value update here
NOTE: You should never call this function,
it will be called on your behalf
"""
# agent parameters
gamma = self.discount
learning_rate = self.alpha
Q_value = self.getQValue(state, action)
Q_value = (1-learning_rate)*Q_value + learning_rate*(reward + gamma*self.getValue(nextState))
self.setQValue(state, action, Q_value)
#---------------------#end of your code#---------------------#
class PacmanQAgent(QLearningAgent):
"Exactly the same as QLearningAgent, but with different default parameters"
def __init__(self, epsilon=0.25, gamma=0.8, alpha=0.5, numTraining=0, **args):
"""
These default parameters can be changed from the pacman.py command line.
For example, to change the exploration rate, try:
python pacman.py -p PacmanQLearningAgent -a epsilon=0.1
alpha - learning rate
epsilon - exploration rate
gamma - discount factor
numTraining - number of training episodes, i.e. no learning after these many episodes
"""
args['epsilon'] = epsilon
args['gamma'] = gamma
args['alpha'] = alpha
args['numTraining'] = numTraining
self.index = 0 # This is always Pacman
QLearningAgent.__init__(self, **args)
def getAction(self, state):
"""
Simply calls the getAction method of QLearningAgent and then
informs parent of action for Pacman. Do not change or remove this
method.
"""
action = QLearningAgent.getAction(self, state)
self.doAction(state, action)
return action
class ApproximateQAgent(PacmanQAgent):
pass
|
from dissect.utils.utils import Factorization
from dissect.traits.trait_interface import compute_results
from dissect.utils.custom_curve import CustomCurve
TRAIT_TIMEOUT = 20
def a25_curve_function(curve: CustomCurve, deg):
"""Computation of the trace in an extension together with its factorization"""
trace = curve.extended_trace(deg)
f = Factorization(trace, timeout_duration=TRAIT_TIMEOUT)
num_of_factors = f.timeout_message() if f.timeout() else len(list(set(f.factorization())))
curve_results = {
"trace": curve.trace(),
"trace_factorization": f.factorization(),
"number_of_factors": num_of_factors,
}
return curve_results
def compute_a25_results(curve_list, desc="", verbose=False):
compute_results(curve_list, "a25", a25_curve_function, desc=desc, verbose=verbose)
|
from fastapi import FastAPI
from yamldb import YamlDB
from cloudmesh.common.util import path_expand
import yamldb
from cloudmesh.common.util import path_expand
from pathlib import Path
from pprint import pprint
app = FastAPI()
filename = path_expand("~/.cloudmesh/catalog/data.yml")
print (filename)
print(yamldb.__version__)
db = yamldb.YamlDB(filename=filename)
#
# PATH NEEDS TO BE DONE DIFFERENTLY, probably as parameter to start.
# see also load command
source = path_expand("~/Desktop/cm/nist/catalog")
def _find_sources_from_dir(source=None):
source = Path(source).resolve()
result = Path(source).rglob('*.yaml')
return result
files = _find_sources_from_dir(source=source)
for file in files:
db.update(file)
@app.get("/")
def read_root():
return {"Cloudmesh Catalog": "running"}
@app.get("/list")
def list_db():
return db
@app.get("/load/{directory}")
def load(directory: str):
return {"Cloudmesh Catalog": directory}
@app.get("/items/{item_id}")
def read_item(item_id: int):
return {"item_id": item_id}
|
from app import db
class Face:
def __init__(self, rep, identity):
self.rep = rep
self.identity = identity
def __repr__(self):
return "{{identity: {}, rep[0:5]: {}}}".format(
str(self.identity),
self.rep[0:5]
)
class FaceImage(db.Model):
id = db.Column(db.Integer, primary_key=True)
phash = db.Column(db.String(128))
identity = db.Column(db.Integer)
rep = db.Column(db.Text)
def __init__(self, phash, identity, rep):
self.phash = phash
self.identity = identity
self.rep = rep
@property
def serialize(self):
"""Return object data in easily serializeable format"""
return {
'id': self.id,
'phash': self.phash,
'identity': self.identity,
'rep': self.rep,
}
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(128))
first_name = db.Column(db.String(128))
last_name = db.Column(db.String(128))
def __init__(self, username, first_name, last_name):
self.username = username
self.first_name = first_name
self.last_name = last_name
@property
def serialize(self):
"""Return object data in easily serializeable format"""
return {
'id': self.id,
'username': self.username,
'first_name': self.first_name,
'last_name': self.last_name,
# This is an example how to deal with Many2Many relations
# 'many2many' : self.serialize_many2many
}
# @property
# def serialize_many2many(self):
# """
# Return object's relations in easily serializeable format.
# NB! Calls many2many's serialize property.
# """
# return [ item.serialize for item in self.many2many] |
import codecs
import hashlib
import os
import sys
import inspect
import traceback
import sj
import typing
from mitmproxy import http
from mitmproxy import ctx
from mitmproxy.script import concurrent
from subprocess import CalledProcessError, Popen, PIPE, STDOUT
p = Popen(['mitmdump --version'], stdout=PIPE, stdin=PIPE, stderr=STDOUT, shell=True)
stdout = p.communicate()[0]
mitmversion = stdout.decode()[9:] # remove "mitmdump "
filename = inspect.getframeinfo(inspect.currentframe()).filename
JALANGI_HOME = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(filename)), os.pardir))
WORKING_DIR = os.getcwd()
sys.path.insert(0, JALANGI_HOME+'/scripts')
print('Jalangi home is ' + JALANGI_HOME)
print('Current working directory is ' + WORKING_DIR)
global jalangiArgs
jalangiArgs = ''
global useCache
useCache = True
ignore = []
# For enabling/disabling instrumentation cache (enabled by default)
if '--no-cache' in sys.argv:
print('Cache disabled.')
useCache = False
sys.argv.remove('--no-cache')
elif '--cache' in sys.argv:
sys.argv.remove('--cache')
# For not invoking jalangi for certain URLs
ignoreIdx = sys.argv.index('--ignore') if '--ignore' in sys.argv else -1
while ignoreIdx >= 0:
sys.argv.pop(ignoreIdx)
ignore.append(sys.argv[ignoreIdx])
sys.argv.pop(ignoreIdx)
ignoreIdx = sys.argv.index('--ignore') if '--ignore' in sys.argv else -1
def mapper(p):
path = os.path.abspath(os.path.join(WORKING_DIR, p))
return path if not p.startswith('--') and (os.path.isfile(path) or os.path.isdir(path)) else p
jalangiArgs = sys.argv[-1]
def processFile (flow, content, ext):
try:
url = flow.request.scheme + '://' + flow.request.host + ':' + str(flow.request.port) + flow.request.path
name = os.path.splitext(flow.request.path_components[-1])[0] if hasattr(flow.request,'path_components') and len(flow.request.path_components) else 'index'
hash = hashlib.md5(content.encode('utf-8')).hexdigest()
fileName = 'cache/' + flow.request.host + '/' + hash + '/' + name + '.' + ext
instrumentedFileName = 'cache/' + flow.request.host + '/' + hash + '/' + name + '_jalangi_.' + ext
if not os.path.exists('cache/' + flow.request.host + '/' + hash):
os.makedirs('cache/' + flow.request.host + '/' + hash)
if not useCache or not os.path.isfile(instrumentedFileName):
print('Instrumenting: ' + fileName + ' from ' + url)
with open(fileName, 'w') as file:
file.write(content)
sub_env = { 'JALANGI_URL': url }
sj.execute(sj.INSTRUMENTATION_SCRIPT + ' ' + jalangiArgs + ' ' + fileName + ' --out ' + instrumentedFileName + ' --outDir ' + os.path.dirname(instrumentedFileName), None, sub_env)
else:
print('Already instrumented: ' + fileName + ' from ' + url)
with open (instrumentedFileName, 'r') as file:
data = file.read()
return data
except:
print('Exception in processFile() @ proxy.py')
exc_type, exc_value, exc_traceback = sys.exc_info()
lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
print(''.join(lines))
return content
# Example usage: "proxy.py --no-cache --ignore http://cdn.com/jalangi --inlineIID --inlineSource --noResultsGUI --analysis ..."
@concurrent
def response(flow):
# Do not invoke jalangi if the domain is ignored
for path in ignore:
if flow.request.url.startswith(path):
return
# Do not invoke jalangi if the requested URL contains the query parameter noInstr
# (e.g. https://cdn.com/jalangi/jalangi.min.js?noInstr=true)
#if LooseVersion(mitmversion) >= LooseVersion("0.17") and
if flow.request.query and flow.request.query.get('noInstr', None):
return
try:
flow.response.decode()
content_type = None
csp_key = None
for key in flow.response.headers.keys():
if key.lower() == "content-type":
content_type = flow.response.headers[key].lower()
elif key.lower() == "content-security-policy":
csp_key = key
if content_type:
#print("here", content_type)
if content_type.find('javascript') >= 0:
flow.response.text = processFile(flow, flow.response.text, 'js')
if content_type.find('html') >= 0:
flow.response.text = processFile(flow, flow.response.text, 'html')
if content_type.find('mvc') >= 0:
flow.response.text = processFile(flow, flow.response.text, 'html')
# Disable the content security policy since it may prevent jalangi from executing
if csp_key:
flow.response.headers.pop(csp_key, None)
except:
print('Exception in response() @ proxy.py')
exc_type, exc_value, exc_traceback = sys.exc_info()
lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
print(''.join(lines))
|
description = 'Slit 5 devices in the SINQ AMOR.'
group = 'lowlevel'
pvprefix = 'SQ:AMOR:motc:'
devices = dict(
d5v=device('nicos_ess.devices.epics.motor.EpicsMotor',
epicstimeout=3.0,
description='Slit 5 vertical motor',
motorpv=pvprefix + 'd5v',
errormsgpv=pvprefix + 'd5v-MsgTxt',
),
d5h=device('nicos_ess.devices.epics.motor.EpicsMotor',
epicstimeout=3.0,
description='Slit 5 horizontal motor',
motorpv=pvprefix + 'd5h',
errormsgpv=pvprefix + 'd5h-MsgTxt',
),
)
|
# -*- coding: utf-8 -*-
from django.db import models, migrations
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('configuration', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='OperationalSlot',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('identifier', models.CharField(unique=True, max_length=150, verbose_name=b'Unique identifier for this slot')),
('start', models.DateTimeField(verbose_name=b'Slot start')),
('end', models.DateTimeField(verbose_name=b'Slot end')),
('state', models.CharField(default='FREE', max_length=10, verbose_name=b'String that indicates the current state of the slot', choices=[('FREE', b'Slot not assigned for operation'), ('SELECTED', b'Slot chosen for reservation'), ('RESERVED', b'Slot confirmed by GroundStation'), ('DENIED', b'Slot petition denied'), ('CANCELED', b'Slot reservation canceled'), ('REMOVED', b'Slot removed due to a policy change')])),
('gs_notified', models.BooleanField(default=False, verbose_name=b'Flag that indicates whether the changes in the status of the slot need already to be notified to the compatible GroundStation.')),
('sc_notified', models.BooleanField(default=False, verbose_name=b'Flag that indicates whether the changes in the status of the slot need already to be notified to the compatible Spacecraft.')),
('availability_slot', models.ForeignKey(on_delete=django.db.models.deletion.SET_NULL, verbose_name=b'Availability slot that generates this OperationalSlot', blank=True, to='configuration.AvailabilitySlot', null=True)),
('groundstation_channel', models.ForeignKey(on_delete=django.db.models.deletion.SET_NULL, verbose_name=b'GroundStationChannel that this slot belongs to', blank=True, to='configuration.GroundStationChannel', null=True)),
('spacecraft_channel', models.ForeignKey(on_delete=django.db.models.deletion.SET_NULL, verbose_name=b'SpacecraftChannel that this slot belongs to', blank=True, to='configuration.SpacecraftChannel', null=True)),
],
options={
},
bases=(models.Model,),
),
]
|
# Copyright (c) 2018 MetPy Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
"""Test packaging details."""
from metpy.calc import tke
from metpy.interpolate import interpolate_to_grid
from metpy.io import Level2File
from metpy.plots import StationPlot
def test_modules_set():
"""Test that functions from each subpackage have correct module set."""
assert Level2File.__module__ == 'metpy.io'
assert StationPlot.__module__ == 'metpy.plots'
assert interpolate_to_grid.__module__ == 'metpy.interpolate'
assert tke.__module__ == 'metpy.calc'
|
import time
from random import randint
for i in range(1,85):
print('')
space = ''
for i in range(1,1000):
count = randint(1, 100)
while(count > 0):
space += ' '
count -= 1
if(i%10==0):
print(space + '🎂Happy Birthday!')
elif(i%9 == 0):
print(space + "🎂")
elif(i%5==0):
print(space +"💛")
elif(i%8==0):
print(space + "🎉")
elif(i%7==0):
print(space + "🍫")
elif(i%6==0):
print(space + "Happy Birthday!💖")
else:
print(space + "🔸")
space = ''
time.sleep(0.2)
|
# Standard library imports.
import unittest
# Library imports.
import numpy as np
# Local library imports.
from pysph.base.particle_array import ParticleArray
from pysph.base.cython_generator import KnownType
from pysph.sph.acceleration_eval_cython_helper import (get_all_array_names,
get_known_types_for_arrays)
class TestGetAllArrayNames(unittest.TestCase):
def test_that_all_properties_are_found(self):
x = np.linspace(0, 1, 10)
pa = ParticleArray(name='f', x=x)
result = get_all_array_names([pa])
self.assertEqual(len(result), 3)
self.assertEqual(result['DoubleArray'], set(('x',)))
self.assertEqual(result['IntArray'], set(('pid', 'tag')))
self.assertEqual(result['UIntArray'], set(('gid',)))
def test_that_all_properties_are_found_with_multiple_arrays(self):
x = np.linspace(0, 1, 10)
pa1 = ParticleArray(name='f', x=x)
pa2 = ParticleArray(name='b', y=x)
result = get_all_array_names([pa1, pa2])
self.assertEqual(len(result), 3)
self.assertEqual(result['DoubleArray'], set(('x', 'y')))
self.assertEqual(result['IntArray'], set(('pid', 'tag')))
self.assertEqual(result['UIntArray'], set(('gid',)))
class TestGetKnownTypesForAllArrays(unittest.TestCase):
def test_that_all_types_are_detected_correctly(self):
x = np.linspace(0, 1, 10)
pa = ParticleArray(name='f', x=x)
pa.remove_property('pid')
info = get_all_array_names([pa])
result = get_known_types_for_arrays(info)
expect = {'d_gid': KnownType("unsigned int*"),
'd_tag': KnownType("int*"),
'd_x': KnownType("double*"),
's_gid': KnownType("unsigned int*"),
's_tag': KnownType("int*"),
's_x': KnownType("double*")}
for key in expect:
self.assertEqual(repr(result[key]), repr(expect[key]))
|
from pandas import DataFrame
import sqlalchemy
import constants
import json
import logging
import os
from helpers import omit
from functools import reduce
from operator import concat
from pydash import flatten, flatten_deep
logging.basicConfig(
level=logging.INFO,
format='[%(module)s-l.%(lineno)s]%(asctime)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
def check_exists_and_save(obj, path):
logging.info(f'Verificando se o arquivo {path} existe')
if not os.path.isfile(path):
logging.info('Arquivo não existe, criando...')
save_to_json(obj=obj, path=path)
def save_to_json(obj, path):
with open(path, 'w') as fp:
json.dump(obj, fp, indent=2)
def main():
logging.info('Iniciando processamento de JSON de dados para SQL')
logging.info('Verificando primeiro se json de dados existe')
if not os.path.exists(constants.JSON_OUTPUT_PATH):
logging.info('Arquivo não existe')
return None
logging.info('Verificando se diretorio de output dos JSONs existe')
if not os.path.isdir(constants.ELECTIONS_OUTPUT):
logging.info('Diretorio de output dos JSONs nao existe, criando um')
os.makedirs(constants.ELECTIONS_OUTPUT)
with open(constants.JSON_OUTPUT_PATH) as _json:
elections = json.load(_json)
elections_to_save = []
for election in elections:
_path_year = f"{constants.ELECTIONS_OUTPUT}/{election['year']}"
logging.info(f'Verificando se o diretório {_path_year} existe')
if not os.path.isdir(_path_year):
logging.info('Diretorio não existe, criando...')
os.makedirs(_path_year)
elections_to_save.append(omit(obj=election, _key='states'))
states = election['states']
for state in states:
sigla = str(state['sigla']).lower()
_path_state = f"{_path_year}/{sigla}.json"
check_exists_and_save(obj=state, path=_path_state)
logging.info('')
path = f"{constants.ELECTIONS_OUTPUT}/elections.json"
check_exists_and_save(obj=elections_to_save, path=path)
if __name__ == "__main__":
main()
|
import datetime
class TestRecord(object):
def __init__(self, init_total_record: bool = False):
self.init_total_record = init_total_record
self.total_record_list = list()
def clean_record(self):
self.total_record_list = list()
test_record = TestRecord()
def record_total(function_name: str, local_param, program_exception: str = None):
if not test_record.init_total_record:
pass
else:
test_record.total_record_list.append(
{
"function_name": function_name,
"local_param": local_param,
"time": str(datetime.datetime.now()),
"program_exception": repr(program_exception)
}
)
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.10 on 2018-08-03 16:54
from __future__ import unicode_literals
from django.db import migrations
def populate_names(apps, schema_editor):
def get_name(doc, fields):
return " ".join(filter(None, (doc.get(x, None) for x in fields)))
matches = apps.get_model("tasks", "AdHocMatch")
for m in matches.objects.filter(dataset_id="cvk_2015"):
m.name_in_dataset = get_name(m.matched_json, ["name"])
m.save()
class Migration(migrations.Migration):
dependencies = [
('tasks', '0049_adhocmatch_name_in_dataset'),
]
operations = [
migrations.RunPython(populate_names, reverse_code=migrations.RunPython.noop),
]
|
from affine import Affine
import numpy as np
import pytest
from datacube.utils.geometry import gbox as gbx
from datacube.utils import geometry
from datacube.utils.geometry import GeoBox
epsg3857 = geometry.CRS('EPSG:3857')
def test_gbox_ops():
s = GeoBox(1000, 100, Affine(10, 0, 12340, 0, -10, 316770), epsg3857)
assert s.shape == (100, 1000)
d = gbx.flipy(s)
assert d.shape == s.shape
assert d.crs is s.crs
assert d.resolution == (-s.resolution[0], s.resolution[1])
assert d.extent.contains(s.extent)
d = gbx.flipx(s)
assert d.shape == s.shape
assert d.crs is s.crs
assert d.resolution == (s.resolution[0], -s.resolution[1])
assert d.extent.contains(s.extent)
assert gbx.flipy(gbx.flipy(s)).affine == s.affine
assert gbx.flipx(gbx.flipx(s)).affine == s.affine
d = gbx.zoom_out(s, 2)
assert d.shape == (50, 500)
assert d.crs is s.crs
assert d.extent.contains(s.extent)
assert d.resolution == (s.resolution[0]*2, s.resolution[1]*2)
d = gbx.zoom_out(s, 2*max(s.shape))
assert d.shape == (1, 1)
assert d.crs is s.crs
assert d.extent.contains(s.extent)
d = gbx.zoom_out(s, 1.33719)
assert d.crs is s.crs
assert d.extent.contains(s.extent)
assert all(ds < ss for ds, ss in zip(d.shape, s.shape))
d = gbx.zoom_to(s, s.shape)
assert d == s
d = gbx.zoom_to(s, (1, 3))
assert d.shape == (1, 3)
assert d.extent == s.extent
d = gbx.zoom_to(s, (10000, 10000))
assert d.shape == (10000, 10000)
assert d.extent == s.extent
d = gbx.pad(s, 1)
assert d.crs is s.crs
assert d.resolution == s.resolution
assert d.extent.contains(s.extent)
assert s.extent.contains(d.extent) is False
assert d[1:-1, 1:-1].affine == s.affine
assert d[1:-1, 1:-1].shape == s.shape
d = gbx.pad_wh(s, 10)
assert d == s
d = gbx.pad_wh(s, 100, 8)
assert d.width == s.width
assert d.height % 8 == 0
assert 0 < d.height - s.height < 8
assert d.affine == s.affine
assert d.crs is s.crs
d = gbx.pad_wh(s, 13, 17)
assert d.affine == s.affine
assert d.crs is s.crs
assert d.height % 17 == 0
assert d.width % 13 == 0
assert 0 < d.height - s.height < 17
assert 0 < d.width - s.width < 13
d = gbx.translate_pix(s, 1, 2)
assert d.crs is s.crs
assert d.resolution == s.resolution
assert d.extent != s.extent
assert s[2:3, 1:2].extent == d[:1, :1].extent
d = gbx.translate_pix(s, -10, -2)
assert d.crs is s.crs
assert d.resolution == s.resolution
assert d.extent != s.extent
assert s[:1, :1].extent == d[2:3, 10:11].extent
d = gbx.translate_pix(s, 0.1, 0)
assert d.crs is s.crs
assert d.shape == s.shape
assert d.resolution == s.resolution
assert d.extent != s.extent
assert d.extent.contains(s[:, 1:].extent)
d = gbx.translate_pix(s, 0, -0.5)
assert d.crs is s.crs
assert d.shape == s.shape
assert d.resolution == s.resolution
assert d.extent != s.extent
assert s.extent.contains(d[1:, :].extent)
d = gbx.affine_transform_pix(s, Affine(1, 0, 0,
0, 1, 0))
assert d.crs is s.crs
assert d.shape == s.shape
assert d.resolution == s.resolution
assert d.extent == s.extent
d = gbx.affine_transform_pix(s, Affine.rotation(10))
assert d.crs is s.crs
assert d.shape == s.shape
assert d.extent != s.extent
for deg in (33, -33, 20, 90, 180):
d = gbx.rotate(s, 33)
assert d.crs is s.crs
assert d.shape == s.shape
assert d.extent != s.extent
np.testing.assert_almost_equal(d.extent.area, s.extent.area, 1e-5)
assert s[49:52, 499:502].extent.contains(d[50:51, 500:501].extent), "Check that center pixel hasn't moved"
def test_gbox_tiles():
A = Affine.identity()
H, W = (300, 200)
h, w = (10, 20)
gbox = GeoBox(W, H, A, epsg3857)
tt = gbx.GeoboxTiles(gbox, (h, w))
assert tt.shape == (300/10, 200/20)
assert tt.base is gbox
assert tt[0, 0] == gbox[0:h, 0:w]
assert tt[0, 1] == gbox[0:h, w:w+w]
assert tt[0, 0] is tt[0, 0] # Should cache exact same object
assert tt[4, 1].shape == (h, w)
H, W = (11, 22)
h, w = (10, 9)
gbox = GeoBox(W, H, A, epsg3857)
tt = gbx.GeoboxTiles(gbox, (h, w))
assert tt.shape == (2, 3)
assert tt[1, 2] == gbox[10:11, 18:22]
for idx in [tt.shape, (-1, 0), (0, -1), (-33, 1)]:
with pytest.raises(IndexError):
tt[idx]
with pytest.raises(IndexError):
tt.chunk_shape(idx)
cc = np.zeros(tt.shape, dtype='int32')
for idx in tt.tiles(gbox.extent):
cc[idx] += 1
np.testing.assert_array_equal(cc, np.ones(tt.shape))
assert list(tt.tiles(gbox[:h, :w].extent)) == [(0, 0)]
(H, W) = (11, 22)
(h, w) = (10, 20)
tt = gbx.GeoboxTiles(GeoBox(W, H, A, epsg3857), (h, w))
assert tt.chunk_shape((0, 0)) == (h, w)
assert tt.chunk_shape((0, 1)) == (h, 2)
assert tt.chunk_shape((1, 1)) == (1, 2)
assert tt.chunk_shape((1, 0)) == (1, w)
|
class Solution:
def mySqrt(self, x: int) -> int:
if x == 0:
return 0
if x == 1:
return 1
pivot = x // 2
left, right = 0, pivot
while left <= right:
mid = (left + right) // 2
nxt = (mid + 1) * (mid + 1)
prev = (mid - 1) * (mid - 1)
pwr = mid * mid
if (pwr == x) or ((pwr < x) and (prev < x) and (nxt > x)):
return mid
elif mid * mid < x:
left = mid + 1
else:
right = mid - 1
return -1
s = Solution()
print(s.mySqrt(8))
print(s.mySqrt(10)) |
from functools import lru_cache
from corehq.apps.change_feed import topics
from corehq.apps.change_feed.consumer.feed import KafkaChangeFeed, KafkaCheckpointEventHandler
from corehq.apps.export.models.new import LedgerSectionEntry
from corehq.apps.locations.models import SQLLocation
from corehq.elastic import get_es_new
from corehq.form_processor.backends.sql.dbaccessors import LedgerReindexAccessor
from corehq.form_processor.change_publishers import change_meta_from_ledger_v1
from corehq.form_processor.utils.general import should_use_sql_backend
from corehq.pillows.mappings.ledger_mapping import LEDGER_INDEX_INFO
from corehq.util.doc_processor.sql import SqlDocumentProvider
from corehq.util.quickcache import quickcache
from pillowtop.checkpoints.manager import get_checkpoint_for_elasticsearch_pillow
from pillowtop.feed.interface import Change
from pillowtop.pillow.interface import ConstructedPillow
from pillowtop.processors.elastic import ElasticProcessor
from pillowtop.reindexer.change_providers.django_model import DjangoModelChangeProvider
from pillowtop.reindexer.reindexer import (
ElasticPillowReindexer, ResumableBulkElasticPillowReindexer, ReindexerFactory
)
@quickcache(['case_id'])
def _location_id_for_case(case_id):
try:
return SQLLocation.objects.get(supply_point_id=case_id).location_id
except SQLLocation.DoesNotExist:
return None
def _prepare_ledger_for_es(ledger):
from corehq.apps.commtrack.models import CommtrackConfig
commtrack_config = CommtrackConfig.for_domain(ledger['domain'])
if commtrack_config and commtrack_config.use_auto_consumption:
daily_consumption = _get_daily_consumption_for_ledger(ledger)
ledger['daily_consumption'] = daily_consumption
if not ledger.get('location_id') and ledger.get('case_id'):
ledger['location_id'] = _location_id_for_case(ledger['case_id'])
_update_ledger_section_entry_combinations(ledger)
return ledger
def _get_daily_consumption_for_ledger(ledger):
from corehq.apps.commtrack.consumption import get_consumption_for_ledger_json
daily_consumption = get_consumption_for_ledger_json(ledger)
if should_use_sql_backend(ledger['domain']):
from corehq.form_processor.backends.sql.dbaccessors import LedgerAccessorSQL
ledger_value = LedgerAccessorSQL.get_ledger_value(
ledger['case_id'], ledger['section_id'], ledger['entry_id']
)
ledger_value.daily_consumption = daily_consumption
LedgerAccessorSQL.save_ledger_values([ledger_value])
else:
from corehq.apps.commtrack.models import StockState
StockState.objects.filter(pk=ledger['_id']).update(daily_consumption=daily_consumption)
return daily_consumption
def _update_ledger_section_entry_combinations(ledger):
current_combos = _get_ledger_section_combinations(ledger['domain'])
if (ledger['section_id'], ledger['entry_id']) in current_combos:
return
# use get_or_create because this may be created by another parallel process
LedgerSectionEntry.objects.get_or_create(
domain=ledger['domain'],
section_id=ledger['section_id'],
entry_id=ledger['entry_id'],
)
# clear the lru_cache so that next time a ledger is saved, we get the combinations
_get_ledger_section_combinations.cache_clear()
@lru_cache()
def _get_ledger_section_combinations(domain):
return list(LedgerSectionEntry.objects.filter(domain=domain).values_list('section_id', 'entry_id').all())
def get_ledger_to_elasticsearch_pillow(pillow_id='LedgerToElasticsearchPillow', num_processes=1,
process_num=0, **kwargs):
assert pillow_id == 'LedgerToElasticsearchPillow', 'Pillow ID is not allowed to change'
checkpoint = get_checkpoint_for_elasticsearch_pillow(pillow_id, LEDGER_INDEX_INFO, [topics.LEDGER])
processor = ElasticProcessor(
elasticsearch=get_es_new(),
index_info=LEDGER_INDEX_INFO,
doc_prep_fn=_prepare_ledger_for_es
)
change_feed = KafkaChangeFeed(
topics=[topics.LEDGER], client_id='ledgers-to-es', num_processes=num_processes, process_num=process_num
)
return ConstructedPillow(
name=pillow_id,
checkpoint=checkpoint,
change_feed=change_feed,
processor=processor,
change_processed_event_handler=KafkaCheckpointEventHandler(
checkpoint=checkpoint, checkpoint_frequency=100, change_feed=change_feed
),
)
class LedgerV2ReindexerFactory(ReindexerFactory):
slug = 'ledger-v2'
arg_contributors = [
ReindexerFactory.resumable_reindexer_args,
ReindexerFactory.elastic_reindexer_args,
ReindexerFactory.domain_arg,
]
def build(self):
domain = self.options.pop('domain', None)
iteration_key = "SqlCaseToElasticsearchPillow_{}_reindexer_{}".format(
LEDGER_INDEX_INFO.index, domain or 'all'
)
doc_provider = SqlDocumentProvider(iteration_key, LedgerReindexAccessor(domain=domain))
return ResumableBulkElasticPillowReindexer(
doc_provider,
elasticsearch=get_es_new(),
index_info=LEDGER_INDEX_INFO,
doc_transform=_prepare_ledger_for_es,
**self.options
)
class LedgerV1ReindexerFactory(ReindexerFactory):
slug = 'ledger-v1'
arg_contributors = [
ReindexerFactory.elastic_reindexer_args,
]
def build(self):
from corehq.apps.commtrack.models import StockState
return ElasticPillowReindexer(
pillow_or_processor=get_ledger_to_elasticsearch_pillow(),
change_provider=DjangoModelChangeProvider(StockState, _ledger_v1_to_change),
elasticsearch=get_es_new(),
index_info=LEDGER_INDEX_INFO,
**self.options
)
def _ledger_v1_to_change(stock_state):
return Change(
id=stock_state.pk,
sequence_id=None,
document=stock_state.to_json(),
deleted=False,
metadata=change_meta_from_ledger_v1(stock_state),
document_store=None,
)
|
import csv
import os
import copy
import torch
import numpy as np
from torch.utils.data import Dataset
CLASSES = [
'epidural',
'intraparenchymal',
'intraventricular',
'subarachnoid',
'subdural',
'any'
]
def read_rsna_kaggle_label_csv(file):
data = {}
with open(file) as f:
reader = csv.reader(f)
next(reader) # skip header
for row in reader:
field = row[0].split('_')
image_id = field[0] + '_' + field[1]
cls = field[2]
proba = float(row[1])
if image_id not in data.keys():
data[image_id] = {}
data[image_id][cls] = proba
return data
def label_dict_to_array(label_dictionary):
label_array = []
for cls in CLASSES:
label_array.append(label_dictionary[cls])
return np.asarray(label_array)
class RSNAIntracranialHemorrhageDetection(Dataset):
"""
This object implements the capability of reading the Kaggle RSNA Intracranial Hemorrhage Detection dataset.
Further information about this dataset can be found on the official website
https://www.kaggle.com/c/rsna-intracranial-hemorrhage-detection/overview
Through this module, users are able to make use of the challenge data by simply specifying the directory where
the data is locally stored. Therefore it is necessary to first download the data, store or unpack it in a specific
directory and then instantiate an object of type RSNAIntracranialHemorrhageDetection which will parse said
directory and make the data available to Eisen.
.. note::
This dataset will return data points in form of a dictionary having keys: 'image' and during training
'label' as well.
.. code-block:: python
from eisen.datasets import RSNAIntracranialHemorrhageDetection
dset = RSNAIntracranialHemorrhageDetection('/data/root/path', True)
"""
def __init__(self, data_dir, training, transform=None):
"""
:param data_dir: The dataset root path directory where the challenge dataset is stored
:type data_dir: str
:param training: Boolean indicating whether training or test data should be loaded
:type training: bool
:param transform: a transform object (can be the result of a composition of transforms)
:type transform: callable
.. code-block:: python
from eisen.datasets import RSNAIntracranialHemorrhageDetection
dset = RSNAIntracranialHemorrhageDetection(
data_dir='/data/root/path',
training=True
)
<json>
[
{"name": "training", "type": "bool", "value": ""}
]
</json>
"""
self.data_dir = data_dir
self.training = training
self.transform = transform
self.data = []
if self.training:
train_dir = os.path.join(self.data_dir, 'stage_2_train')
labels = read_rsna_kaggle_label_csv(os.path.join(data_dir, 'stage_2_train.csv'))
images = [o for o in os.listdir(train_dir) if 'dcm' in o]
for image in images:
image_id = os.path.splitext(image)[0]
label_array = label_dict_to_array(labels[image_id])
item = {
'image': os.path.join('stage_2_train', image),
'label': label_array
}
self.data.append(item)
else:
test_dir = os.path.join(self.data_dir, 'stage_2_test')
images = [o for o in os.listdir(test_dir) if 'dcm' in o]
for image in images:
item = {
'image': os.path.join('stage_2_test', image),
}
self.data.append(item)
def __len__(self):
return len(self.data)
def __getitem__(self, idx):
if torch.is_tensor(idx):
idx = idx.tolist()
item = copy.deepcopy(self.data[idx])
if self.transform:
item = self.transform(item)
return item
|
class Usuario:
def __init__(self, nome, espaco, cdusuario):
self.nome = nome
self.espaco = espaco
self.cdUsuario = cdUsuario
def byteParaMega(self):
return float(self.espaco) / (1024*1024)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.