max_stars_repo_path stringlengths 4 286 | max_stars_repo_name stringlengths 5 119 | max_stars_count int64 0 191k | id stringlengths 1 7 | content stringlengths 6 1.03M | content_cleaned stringlengths 6 1.03M | language stringclasses 111 values | language_score float64 0.03 1 | comments stringlengths 0 556k | edu_score float64 0.32 5.03 | edu_int_score int64 0 5 |
|---|---|---|---|---|---|---|---|---|---|---|
funfolding/__init__.py | jacobbieker/funfolding-test | 0 | 6618851 | <filename>funfolding/__init__.py
from . import binning
from . import model
from . import solution
from . import pipeline
from . import visualization
__all__ = ['binning', 'model', 'solution', 'pipeline', 'visualization']
| <filename>funfolding/__init__.py
from . import binning
from . import model
from . import solution
from . import pipeline
from . import visualization
__all__ = ['binning', 'model', 'solution', 'pipeline', 'visualization']
| none | 1 | 1.333161 | 1 | |
loop_excel_mapper.py | djburks/Enrichment-Pipeline | 0 | 6618852 | <reponame>djburks/Enrichment-Pipeline
import xlsxwriter
import sys
import glob
# Grab files and open workbook.
filelist = glob.glob('*.BP.txt')
workbook = xlsxwriter.Workbook('Combined' + '.xlsx')
# Format presets
header_format = workbook.add_format({
'bold':1})
merge_format = workbook.add_format({
'align':'center',
'valign':'vcenter'})
for f in filelist:
Prefix = f.split('.BP')[0]
BP = Prefix + '.BP.txt'
CC = Prefix + '.CC.txt'
MF = Prefix + '.MF.txt'
worksheet = workbook.add_worksheet(Prefix)
## BP Addition
with open(BP) as infile:
topline = infile.readline()
topline = topline.rstrip()
topline = topline.replace('"','')
bpdata = []
bpdata.append(topline)
for lines in infile:
lines = lines.replace('"','')
lines = lines.rstrip()
fdr = float(lines.split('\t')[-1])
if fdr <= 0.05:
bpdata.append(lines)
worksheet.set_column(0,0,5)
worksheet.set_column(1,1,11)
worksheet.set_column(2,2,44)
worksheet.set_column(3,5,15)
worksheet.set_column(6,6,20)
worksheet.set_column(7,7,20)
top = bpdata[0].split('\t')
col = 1
row = 0
for t in top:
worksheet.write(row,col,t,header_format)
col += 1
row = 1
for b in bpdata[1:]:
col = 0
val = b.split('\t')
for v in val:
worksheet.write(row,col,v)
col += 1
row += 1
worksheet.merge_range('H2:H' + str(len(bpdata)),'Biological Process',merge_format)
## CC Addition
with open(CC) as infile:
topline = infile.readline()
topline = topline.rstrip()
topline = topline.replace('"','')
ccdata = []
ccdata.append(topline)
for lines in infile:
lines = lines.replace('"','')
lines = lines.rstrip()
fdr = float(lines.split('\t')[-1])
if fdr <= 0.05:
ccdata.append(lines)
row += 1
for c in ccdata[1:]:
col = 0
val = c.split('\t')
for v in val:
worksheet.write(row,col,v)
col += 1
row += 1
worksheet.merge_range('H' + str(len(bpdata) + 2) + ':H' + str(len(ccdata) + len(bpdata)),'Cellular Compartment',merge_format)
## MF Addition
with open(MF) as infile:
topline = infile.readline()
topline = topline.rstrip()
topline = topline.replace('"','')
mfdata = []
mfdata.append(topline)
for lines in infile:
lines = lines.replace('"','')
lines = lines.rstrip()
fdr = float(lines.split('\t')[-1])
if fdr <= 0.05:
mfdata.append(lines)
row += 1
for m in mfdata[1:]:
col = 0
val = m.split('\t')
for v in val:
worksheet.write(row,col,v)
col += 1
row += 1
worksheet.merge_range('H' + str(len(bpdata) + len(ccdata) + 2) + ':H' + str(len(ccdata) + len(bpdata) + len(mfdata)),'Molecular Function',merge_format)
workbook.close()
| import xlsxwriter
import sys
import glob
# Grab files and open workbook.
filelist = glob.glob('*.BP.txt')
workbook = xlsxwriter.Workbook('Combined' + '.xlsx')
# Format presets
header_format = workbook.add_format({
'bold':1})
merge_format = workbook.add_format({
'align':'center',
'valign':'vcenter'})
for f in filelist:
Prefix = f.split('.BP')[0]
BP = Prefix + '.BP.txt'
CC = Prefix + '.CC.txt'
MF = Prefix + '.MF.txt'
worksheet = workbook.add_worksheet(Prefix)
## BP Addition
with open(BP) as infile:
topline = infile.readline()
topline = topline.rstrip()
topline = topline.replace('"','')
bpdata = []
bpdata.append(topline)
for lines in infile:
lines = lines.replace('"','')
lines = lines.rstrip()
fdr = float(lines.split('\t')[-1])
if fdr <= 0.05:
bpdata.append(lines)
worksheet.set_column(0,0,5)
worksheet.set_column(1,1,11)
worksheet.set_column(2,2,44)
worksheet.set_column(3,5,15)
worksheet.set_column(6,6,20)
worksheet.set_column(7,7,20)
top = bpdata[0].split('\t')
col = 1
row = 0
for t in top:
worksheet.write(row,col,t,header_format)
col += 1
row = 1
for b in bpdata[1:]:
col = 0
val = b.split('\t')
for v in val:
worksheet.write(row,col,v)
col += 1
row += 1
worksheet.merge_range('H2:H' + str(len(bpdata)),'Biological Process',merge_format)
## CC Addition
with open(CC) as infile:
topline = infile.readline()
topline = topline.rstrip()
topline = topline.replace('"','')
ccdata = []
ccdata.append(topline)
for lines in infile:
lines = lines.replace('"','')
lines = lines.rstrip()
fdr = float(lines.split('\t')[-1])
if fdr <= 0.05:
ccdata.append(lines)
row += 1
for c in ccdata[1:]:
col = 0
val = c.split('\t')
for v in val:
worksheet.write(row,col,v)
col += 1
row += 1
worksheet.merge_range('H' + str(len(bpdata) + 2) + ':H' + str(len(ccdata) + len(bpdata)),'Cellular Compartment',merge_format)
## MF Addition
with open(MF) as infile:
topline = infile.readline()
topline = topline.rstrip()
topline = topline.replace('"','')
mfdata = []
mfdata.append(topline)
for lines in infile:
lines = lines.replace('"','')
lines = lines.rstrip()
fdr = float(lines.split('\t')[-1])
if fdr <= 0.05:
mfdata.append(lines)
row += 1
for m in mfdata[1:]:
col = 0
val = m.split('\t')
for v in val:
worksheet.write(row,col,v)
col += 1
row += 1
worksheet.merge_range('H' + str(len(bpdata) + len(ccdata) + 2) + ':H' + str(len(ccdata) + len(bpdata) + len(mfdata)),'Molecular Function',merge_format)
workbook.close() | en | 0.726855 | # Grab files and open workbook. # Format presets ## BP Addition ## CC Addition ## MF Addition | 2.590896 | 3 |
bugprediction/predict.py | HaaLeo/bug-prediction | 0 | 6618853 | # ------------------------------------------------------------------------------------------------------
# Copyright (c) <NAME>. All rights reserved.
# Licensed under the BSD 3-Clause License. See LICENSE.txt in the project root for license information.
# ------------------------------------------------------------------------------------------------------
from os import path
import logging
from torch import Tensor, load
from torch.autograd import Variable
import numpy as np
from .linear_regression_model import LinearRegressionModel
LOGGER = logging.getLogger(__name__)
def predict(hcm_map, **kwargs):
try:
model = _load_model(**kwargs)
except FileNotFoundError:
LOGGER.warning('No model is available for parameter="%s"', kwargs)
np_list = np.array(list(hcm_map.values())).reshape((-1, 1))
x_input = Variable(Tensor(np_list))
prediction = model.forward(x_input)
return dict(zip(hcm_map.keys(), prediction.flatten().tolist()))
def _load_model(**kwargs):
model = LinearRegressionModel(1, 1)
model_dir = path.normpath(path.join(path.abspath(path.dirname(__file__)), '../resources/models'))
model_name = ''
if kwargs['contribution'] == 'full':
model_name += 'full'
elif kwargs['contribution'] == 'percentage':
model_name += 'weighted'
else:
pass
# Currently only exp decay possible
if kwargs['decay']:
model_name += '_exp_decayed_hcm.pt'
else:
model_name += '_not_decayed_hcm.pt'
model_path = path.join(model_dir, model_name)
model.load_state_dict(load(model_path))
return model
| # ------------------------------------------------------------------------------------------------------
# Copyright (c) <NAME>. All rights reserved.
# Licensed under the BSD 3-Clause License. See LICENSE.txt in the project root for license information.
# ------------------------------------------------------------------------------------------------------
from os import path
import logging
from torch import Tensor, load
from torch.autograd import Variable
import numpy as np
from .linear_regression_model import LinearRegressionModel
LOGGER = logging.getLogger(__name__)
def predict(hcm_map, **kwargs):
try:
model = _load_model(**kwargs)
except FileNotFoundError:
LOGGER.warning('No model is available for parameter="%s"', kwargs)
np_list = np.array(list(hcm_map.values())).reshape((-1, 1))
x_input = Variable(Tensor(np_list))
prediction = model.forward(x_input)
return dict(zip(hcm_map.keys(), prediction.flatten().tolist()))
def _load_model(**kwargs):
model = LinearRegressionModel(1, 1)
model_dir = path.normpath(path.join(path.abspath(path.dirname(__file__)), '../resources/models'))
model_name = ''
if kwargs['contribution'] == 'full':
model_name += 'full'
elif kwargs['contribution'] == 'percentage':
model_name += 'weighted'
else:
pass
# Currently only exp decay possible
if kwargs['decay']:
model_name += '_exp_decayed_hcm.pt'
else:
model_name += '_not_decayed_hcm.pt'
model_path = path.join(model_dir, model_name)
model.load_state_dict(load(model_path))
return model
| en | 0.43431 | # ------------------------------------------------------------------------------------------------------ # Copyright (c) <NAME>. All rights reserved. # Licensed under the BSD 3-Clause License. See LICENSE.txt in the project root for license information. # ------------------------------------------------------------------------------------------------------ # Currently only exp decay possible | 2.64083 | 3 |
invocare/pki/ca.py | jbronn/invocare-pki | 0 | 6618854 | <reponame>jbronn/invocare-pki<filename>invocare/pki/ca.py
import os
import sys
from collections import OrderedDict
from invocare.openssl import openssl_ca, openssl_req
from invoke import task
from .config import OpenSSLConfig
from .keyfile import generate_keyfile, generate_passfile
from .profile import PKIProfile
@task(
help={
'profile': 'The profile to create the intermediate CA under.',
'ca_name': 'The name of the CA to create.',
'days': 'The number of days the CA certificate is valid for.',
}
)
def inter_ca(
ctx,
profile=None,
ca_name=None,
batch=False,
bits=None,
days=None
):
"""
Initializes an intermediate CA in the profile.
"""
profile = PKIProfile.from_context(profile, ctx)
config = ctx.config.get('pki', {})
ca_name = ca_name or config.get('ca_name', None)
if not ca_name in profile.intermediates:
sys.stderr.write('No configuration for "%s" intermediate CA.\n' % ca_name)
sys.exit(os.EX_CONFIG)
if not os.path.isfile(profile.config_file):
sys.stderr.write('PKI profile "%s" has not been initialized.\n' % profile.name)
sys.exit(os.EX_CONFIG)
if not os.path.isfile(os.path.join(profile.dir, 'root', 'ca.crt')):
sys.stderr.write('Root CA for PKI profile "%s" does not exist.\n' % profile.name)
sys.exit(os.EX_CONFIG)
ca_dir = os.path.join(profile.dir, ca_name)
cert_file = os.path.join(ca_dir, 'ca.crt')
crl_file = os.path.join(ca_dir, 'ca.crl')
ca_bundle = os.path.join(ca_dir, 'ca-bundle.crt')
req_dir = os.path.join(profile.dir, 'root', 'reqs')
req_file = os.path.join(req_dir, ca_name + '.csr')
key_file = os.path.join(profile.private, ca_name, 'ca.key')
pass_file = os.path.join(profile.private, ca_name, 'ca.pass')
if not os.path.isfile(key_file):
if not bits:
# Use CA's bit setting, or the policy default.
bits = profile.cfg[ca_name]['default_bits']
if bits.startswith('$'):
bits = profile.cfg['default']['bits']
generate_passfile(ctx, pass_file)
generate_keyfile(ctx, key_file, pass_file, bits=int(bits))
if not os.path.isfile(req_file):
ca_subject = '/'.join([
profile.base_subject(),
'OU=%s' % profile.cfg[ca_name]['org_unit'],
'CN=%s' % profile.cfg[ca_name]['common_name'],
])
openssl_req(
ctx,
key_file,
req_file,
config_file=profile.config_file,
extensions='intermediate_cert',
passin=pass_file,
subj=ca_subject
)
if not os.path.isfile(cert_file):
# Sign intermediate with the Root CA settings.
root_pass = <PASSWORD>(profile.private, 'root', 'ca.pass')
openssl_ca(
ctx,
'sign',
config_file=profile.config_file,
config_name='root',
batch=batch,
days=days or int(profile.cfg['root']['default_days']),
extensions='intermediate_cert',
in_file=req_file,
out_file=cert_file,
passin=root_pass,
)
if os.stat(cert_file).st_size:
os.chmod(cert_file, 0o444)
root_cert_file = os.path.join(
profile.dir, 'root', 'certs', '%s.crt' % ca_name
)
if not os.path.isfile(root_cert_file):
ctx.run('cp -p %s %s' % (cert_file, root_cert_file))
else:
# Clean up if not signed.
os.unlink(cert_file)
return
# Generate a bundle that includes the Root CA.
if not os.path.isfile(ca_bundle):
ctx.run(
'cat %s %s > %s' % (
cert_file,
os.path.join(profile.dir, 'root', 'ca.crt'),
ca_bundle
)
)
os.chmod(ca_bundle, 0o444)
# Generate the initial CRL.
if not os.path.isfile(crl_file):
openssl_ca(
ctx,
'gencrl',
config_file=profile.config_file,
config_name=ca_name,
passin=pass_file,
out_file=crl_file,
)
else:
sys.stderr.write('Intermediate CA certificate already exists for "%s".\n' % ca_name)
return
@task
def root_ca(
ctx,
profile=None,
batch=False,
bits=None,
days=3652,
):
"""
Initializes the root CA for the profile.
"""
profile = PKIProfile.from_context(profile, ctx)
if not os.path.isfile(profile.config_file):
sys.stderr.write('PKI profile "%s" has not been initialized.\n' % profile.name)
sys.exit(os.EX_CONFIG)
ca_dir = os.path.join(profile.dir, 'root')
cert_file = os.path.join(ca_dir, 'ca.crt')
crl_file = os.path.join(ca_dir, 'ca.crl')
key_file = os.path.join(profile.private, 'root', 'ca.key')
pass_file = os.path.join(profile.private, 'root', 'ca.pass')
req_file = os.path.join(ca_dir, 'reqs', 'root.csr')
# Generate the private key and password file for the root CA.
if not os.path.isfile(key_file):
if not bits:
# Use CA's bit setting, or the policy default.
bits = profile.cfg['root']['default_bits']
if bits.startswith('$'):
bits = profile.cfg['default']['bits']
generate_passfile(ctx, pass_file)
generate_keyfile(ctx, key_file, pass_file, bits=int(bits))
# Generate CSR for the Root CA.
if not os.path.isfile(req_file):
root_subject = '/'.join([
profile.base_subject(),
'CN=%s' % profile.cfg['root']['common_name']
])
openssl_req(
ctx,
key_file,
req_file,
config_file=profile.config_file,
extensions=profile.cfg['root']['x509_extensions'],
passin=pass_file,
subj=root_subject,
)
os.chmod(req_file, 0o444)
# Self-sign the Root CA.
if not os.path.isfile(cert_file):
openssl_ca(
ctx,
'selfsign',
config_file=profile.config_file,
config_name='root',
batch=batch,
days=days,
in_file=req_file,
out_file=cert_file,
passin=<PASSWORD>,
)
# Clean up if not signed.
if not os.stat(cert_file).st_size:
os.unlink(cert_file)
return
# Generate the initial CRL.
if not os.path.isfile(crl_file):
openssl_ca(
ctx,
'gencrl',
config_file=profile.config_file,
config_name='root',
passin=<PASSWORD>,
out_file=crl_file,
)
else:
sys.stderr.write('Root CA certificate already exists for the %s profile.\n' % profile.name)
return
@task
def certificate(
ctx,
profile=None,
ca_name=None,
common_name=None,
batch=False,
days=None,
bits=None,
san=None,
):
profile = PKIProfile.from_context(profile, ctx)
config = ctx.config.get('pki', {})
ca_name = ca_name or config.get('ca_name', None)
cert_name = common_name or config.get('common_name', None)
ca_dir = os.path.join(profile.dir, ca_name)
cert_file = os.path.join(ca_dir, 'certs', '%s.crt' % cert_name)
req_conf = os.path.join(ca_dir, 'reqs', '%s.cnf' % cert_name)
req_file = os.path.join(ca_dir, 'reqs', '%s.csr' % cert_name)
key_file = os.path.join(profile.private, ca_name, '%s.key' % cert_name)
pass_file = os.path.join(profile.private, ca_name, 'ca.pass')
# Generate unencrypted private key.
if not os.path.isfile(key_file):
if not bits:
# Use CA's bit setting, or the policy default.
bits = profile.cfg[ca_name]['default_bits']
if bits.startswith('$'):
bits = profile.cfg['default']['bits']
generate_keyfile(ctx, key_file, bits=int(bits))
if not os.path.isfile(req_file):
# Generate config file for CSR request.
with open(req_conf, 'w') as fh:
profile.req_cfg(ca_name, common_name, san).write(fh)
# Generate the CSR.
openssl_req(
ctx,
key_file,
req_file,
config_file=req_conf,
)
if not os.path.isfile(cert_file):
openssl_ca(
ctx,
'sign',
config_file=profile.config_file,
config_name=ca_name,
batch=batch,
days=days or int(profile.cfg[ca_name]['default_days']),
extensions=profile.cfg[ca_name]['x509_extensions'],
in_file=req_file,
out_file=cert_file,
passin=pass_file,
)
if os.stat(cert_file).st_size:
os.chmod(cert_file, 0o444)
else:
# Clean up if not signed.
os.unlink(cert_file)
return
@task(
positional=('profile', 'ca_name'),
)
def revoke(
ctx,
cert_file,
profile=None,
ca_name=None,
batch=False,
reason='unspecified',
):
profile = PKIProfile.from_context(profile, ctx)
config = ctx.config.get('pki', {})
ca_name = ca_name or config.get('ca_name', None)
crl_file = os.path.join(profile.dir, ca_name, 'ca.crl')
pass_file = os.path.join(profile.private, ca_name, 'ca.pass')
openssl_ca(
ctx,
'revoke',
config_file=profile.config_file,
config_name=ca_name,
batch=batch,
in_file=cert_file,
passin=pass_<PASSWORD>,
)
openssl_ca(
ctx,
'gencrl',
config_file=profile.config_file,
config_name=ca_name,
batch=batch,
passin=pass_<PASSWORD>,
out_file=crl_file,
)
| import os
import sys
from collections import OrderedDict
from invocare.openssl import openssl_ca, openssl_req
from invoke import task
from .config import OpenSSLConfig
from .keyfile import generate_keyfile, generate_passfile
from .profile import PKIProfile
@task(
help={
'profile': 'The profile to create the intermediate CA under.',
'ca_name': 'The name of the CA to create.',
'days': 'The number of days the CA certificate is valid for.',
}
)
def inter_ca(
ctx,
profile=None,
ca_name=None,
batch=False,
bits=None,
days=None
):
"""
Initializes an intermediate CA in the profile.
"""
profile = PKIProfile.from_context(profile, ctx)
config = ctx.config.get('pki', {})
ca_name = ca_name or config.get('ca_name', None)
if not ca_name in profile.intermediates:
sys.stderr.write('No configuration for "%s" intermediate CA.\n' % ca_name)
sys.exit(os.EX_CONFIG)
if not os.path.isfile(profile.config_file):
sys.stderr.write('PKI profile "%s" has not been initialized.\n' % profile.name)
sys.exit(os.EX_CONFIG)
if not os.path.isfile(os.path.join(profile.dir, 'root', 'ca.crt')):
sys.stderr.write('Root CA for PKI profile "%s" does not exist.\n' % profile.name)
sys.exit(os.EX_CONFIG)
ca_dir = os.path.join(profile.dir, ca_name)
cert_file = os.path.join(ca_dir, 'ca.crt')
crl_file = os.path.join(ca_dir, 'ca.crl')
ca_bundle = os.path.join(ca_dir, 'ca-bundle.crt')
req_dir = os.path.join(profile.dir, 'root', 'reqs')
req_file = os.path.join(req_dir, ca_name + '.csr')
key_file = os.path.join(profile.private, ca_name, 'ca.key')
pass_file = os.path.join(profile.private, ca_name, 'ca.pass')
if not os.path.isfile(key_file):
if not bits:
# Use CA's bit setting, or the policy default.
bits = profile.cfg[ca_name]['default_bits']
if bits.startswith('$'):
bits = profile.cfg['default']['bits']
generate_passfile(ctx, pass_file)
generate_keyfile(ctx, key_file, pass_file, bits=int(bits))
if not os.path.isfile(req_file):
ca_subject = '/'.join([
profile.base_subject(),
'OU=%s' % profile.cfg[ca_name]['org_unit'],
'CN=%s' % profile.cfg[ca_name]['common_name'],
])
openssl_req(
ctx,
key_file,
req_file,
config_file=profile.config_file,
extensions='intermediate_cert',
passin=pass_file,
subj=ca_subject
)
if not os.path.isfile(cert_file):
# Sign intermediate with the Root CA settings.
root_pass = <PASSWORD>(profile.private, 'root', 'ca.pass')
openssl_ca(
ctx,
'sign',
config_file=profile.config_file,
config_name='root',
batch=batch,
days=days or int(profile.cfg['root']['default_days']),
extensions='intermediate_cert',
in_file=req_file,
out_file=cert_file,
passin=root_pass,
)
if os.stat(cert_file).st_size:
os.chmod(cert_file, 0o444)
root_cert_file = os.path.join(
profile.dir, 'root', 'certs', '%s.crt' % ca_name
)
if not os.path.isfile(root_cert_file):
ctx.run('cp -p %s %s' % (cert_file, root_cert_file))
else:
# Clean up if not signed.
os.unlink(cert_file)
return
# Generate a bundle that includes the Root CA.
if not os.path.isfile(ca_bundle):
ctx.run(
'cat %s %s > %s' % (
cert_file,
os.path.join(profile.dir, 'root', 'ca.crt'),
ca_bundle
)
)
os.chmod(ca_bundle, 0o444)
# Generate the initial CRL.
if not os.path.isfile(crl_file):
openssl_ca(
ctx,
'gencrl',
config_file=profile.config_file,
config_name=ca_name,
passin=pass_file,
out_file=crl_file,
)
else:
sys.stderr.write('Intermediate CA certificate already exists for "%s".\n' % ca_name)
return
@task
def root_ca(
ctx,
profile=None,
batch=False,
bits=None,
days=3652,
):
"""
Initializes the root CA for the profile.
"""
profile = PKIProfile.from_context(profile, ctx)
if not os.path.isfile(profile.config_file):
sys.stderr.write('PKI profile "%s" has not been initialized.\n' % profile.name)
sys.exit(os.EX_CONFIG)
ca_dir = os.path.join(profile.dir, 'root')
cert_file = os.path.join(ca_dir, 'ca.crt')
crl_file = os.path.join(ca_dir, 'ca.crl')
key_file = os.path.join(profile.private, 'root', 'ca.key')
pass_file = os.path.join(profile.private, 'root', 'ca.pass')
req_file = os.path.join(ca_dir, 'reqs', 'root.csr')
# Generate the private key and password file for the root CA.
if not os.path.isfile(key_file):
if not bits:
# Use CA's bit setting, or the policy default.
bits = profile.cfg['root']['default_bits']
if bits.startswith('$'):
bits = profile.cfg['default']['bits']
generate_passfile(ctx, pass_file)
generate_keyfile(ctx, key_file, pass_file, bits=int(bits))
# Generate CSR for the Root CA.
if not os.path.isfile(req_file):
root_subject = '/'.join([
profile.base_subject(),
'CN=%s' % profile.cfg['root']['common_name']
])
openssl_req(
ctx,
key_file,
req_file,
config_file=profile.config_file,
extensions=profile.cfg['root']['x509_extensions'],
passin=pass_file,
subj=root_subject,
)
os.chmod(req_file, 0o444)
# Self-sign the Root CA.
if not os.path.isfile(cert_file):
openssl_ca(
ctx,
'selfsign',
config_file=profile.config_file,
config_name='root',
batch=batch,
days=days,
in_file=req_file,
out_file=cert_file,
passin=<PASSWORD>,
)
# Clean up if not signed.
if not os.stat(cert_file).st_size:
os.unlink(cert_file)
return
# Generate the initial CRL.
if not os.path.isfile(crl_file):
openssl_ca(
ctx,
'gencrl',
config_file=profile.config_file,
config_name='root',
passin=<PASSWORD>,
out_file=crl_file,
)
else:
sys.stderr.write('Root CA certificate already exists for the %s profile.\n' % profile.name)
return
@task
def certificate(
ctx,
profile=None,
ca_name=None,
common_name=None,
batch=False,
days=None,
bits=None,
san=None,
):
profile = PKIProfile.from_context(profile, ctx)
config = ctx.config.get('pki', {})
ca_name = ca_name or config.get('ca_name', None)
cert_name = common_name or config.get('common_name', None)
ca_dir = os.path.join(profile.dir, ca_name)
cert_file = os.path.join(ca_dir, 'certs', '%s.crt' % cert_name)
req_conf = os.path.join(ca_dir, 'reqs', '%s.cnf' % cert_name)
req_file = os.path.join(ca_dir, 'reqs', '%s.csr' % cert_name)
key_file = os.path.join(profile.private, ca_name, '%s.key' % cert_name)
pass_file = os.path.join(profile.private, ca_name, 'ca.pass')
# Generate unencrypted private key.
if not os.path.isfile(key_file):
if not bits:
# Use CA's bit setting, or the policy default.
bits = profile.cfg[ca_name]['default_bits']
if bits.startswith('$'):
bits = profile.cfg['default']['bits']
generate_keyfile(ctx, key_file, bits=int(bits))
if not os.path.isfile(req_file):
# Generate config file for CSR request.
with open(req_conf, 'w') as fh:
profile.req_cfg(ca_name, common_name, san).write(fh)
# Generate the CSR.
openssl_req(
ctx,
key_file,
req_file,
config_file=req_conf,
)
if not os.path.isfile(cert_file):
openssl_ca(
ctx,
'sign',
config_file=profile.config_file,
config_name=ca_name,
batch=batch,
days=days or int(profile.cfg[ca_name]['default_days']),
extensions=profile.cfg[ca_name]['x509_extensions'],
in_file=req_file,
out_file=cert_file,
passin=pass_file,
)
if os.stat(cert_file).st_size:
os.chmod(cert_file, 0o444)
else:
# Clean up if not signed.
os.unlink(cert_file)
return
@task(
positional=('profile', 'ca_name'),
)
def revoke(
ctx,
cert_file,
profile=None,
ca_name=None,
batch=False,
reason='unspecified',
):
profile = PKIProfile.from_context(profile, ctx)
config = ctx.config.get('pki', {})
ca_name = ca_name or config.get('ca_name', None)
crl_file = os.path.join(profile.dir, ca_name, 'ca.crl')
pass_file = os.path.join(profile.private, ca_name, 'ca.pass')
openssl_ca(
ctx,
'revoke',
config_file=profile.config_file,
config_name=ca_name,
batch=batch,
in_file=cert_file,
passin=pass_<PASSWORD>,
)
openssl_ca(
ctx,
'gencrl',
config_file=profile.config_file,
config_name=ca_name,
batch=batch,
passin=pass_<PASSWORD>,
out_file=crl_file,
) | en | 0.785186 | Initializes an intermediate CA in the profile. # Use CA's bit setting, or the policy default. # Sign intermediate with the Root CA settings. # Clean up if not signed. # Generate a bundle that includes the Root CA. # Generate the initial CRL. Initializes the root CA for the profile. # Generate the private key and password file for the root CA. # Use CA's bit setting, or the policy default. # Generate CSR for the Root CA. # Self-sign the Root CA. # Clean up if not signed. # Generate the initial CRL. # Generate unencrypted private key. # Use CA's bit setting, or the policy default. # Generate config file for CSR request. # Generate the CSR. # Clean up if not signed. | 2.147539 | 2 |
server/facenet_training.py | Mobile-and-Ubiquitous-Computing-2020-1/team1 | 3 | 6618855 | <reponame>Mobile-and-Ubiquitous-Computing-2020-1/team1<gh_stars>1-10
"""
main training modeul for facenet
"""
from __future__ import absolute_import, division, print_function
import getpass
import math
import os
import time
import numpy as np
import torch
from absl import app, flags
import tensorflow as tf
from models import CenterLoss, InceptionResNetV1
from utils.data_pipeline import create_data_pipeline
from utils.log import fedex_logger as logging
FLAGS = flags.FLAGS
# flags definition
flags.DEFINE_integer('image_size', 160,
'default image size')
flags.DEFINE_integer('batch_size', 90,
'training batch size')
flags.DEFINE_integer('num_epochs', 300,
'number of training epochs')
flags.DEFINE_float('learning_rate', 0.05,
'train learning rate')
flags.DEFINE_integer('log_frequency', 50,
'logging frequency')
flags.DEFINE_integer('save_frequency', 200,
'saving model frequency')
flags.DEFINE_string('data_dir', '/cmsdata/ssd1/cmslab/vggface2/final',
'root of dataset')
flags.DEFINE_string('model_dir', f'/tmp/{getpass.getuser()}/checkpoints',
'model checkpoint path')
flags.DEFINE_bool('eval', False,
'eval mode')
flags.DEFINE_bool('load_pretrained', False,
'load pretrained weights')
flags.DEFINE_bool('save_tflite', False,
'directly save tflite model')
flags.DEFINE_bool('use_center_loss', False,
'toggle center loss')
def load_pretrained(model):
"""load pretrained weight from pretrained pytorch model"""
# pylint: disable=line-too-long
pretrained_features = './checkpoints/inception_resnet_v1/vggface2_feature_map.pt'
pretrained_classifier = './checkpoints/inception_resnet_v1/vggface2_classifier.pt'
# pylint: enable=line-too-long
pretrained_weights = []
pretrained_weights.extend(list(torch.load(pretrained_features).values()))
pretrained_weights.extend(list(torch.load(pretrained_classifier).values()))
# num_batch_tracked
pretrained_weights = list(filter(lambda x: tuple(x.shape) != (),
pretrained_weights))
weight_iter = iter(pretrained_weights)
for layer in model.layers:
if isinstance(layer, CenterLoss):
# skip; PyTorch module does not have
continue
num_weights = len(layer.get_weights())
pth_weights = []
for _ in range(num_weights):
weight = next(weight_iter).numpy()
if len(weight.shape) == 4:
# conv kernel
weight = np.transpose(weight, (2, 3, 1, 0))
elif len(weight.shape) == 2:
# dense kernel
weight = np.transpose(weight)
pth_weights.append(weight)
layer.set_weights(pth_weights)
def main(args):
# dataset preparation
train_dataset, test_dataset, _, num_classes, num_train, num_test, _ = \
create_data_pipeline(FLAGS.data_dir, FLAGS.batch_size,
FLAGS.image_size)
model = InceptionResNetV1(num_classes=num_classes,
use_center_loss=FLAGS.use_center_loss)
img_size = (None, FLAGS.image_size, FLAGS.image_size, 3)
model.build(img_size)
if FLAGS.load_pretrained:
logging.info('load pretrained model...')
# for center loss variable
try:
model.load_weights(os.path.join(FLAGS.model_dir, 'facenet_ckpt'))
except ValueError:
logging.debug('pretrained checkpoint does not exists, '
'failed to restore center loss variable')
# load_pretrained(model)
logging.info('loading pretrained model finished!')
if FLAGS.save_tflite:
# pylint: disable=protected-access
model._set_inputs(tf.keras.layers.Input(shape=(160, 160, 3), batch_size=1))
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()
with tf.io.gfile.GFile('./tflite-models/facenet.tflite', 'wb') as f:
f.write(tflite_model)
return
loss_metric = tf.keras.metrics.Mean(name='loss', dtype=tf.float32)
center_loss_metric = tf.keras.metrics.Mean(name='center_loss',
dtype=tf.float32)
accuracy_metric = tf.keras.metrics.SparseCategoricalAccuracy(
name='accuracy', dtype=tf.float32)
@tf.function(input_signature=(tf.TensorSpec(img_size, tf.float32),
tf.TensorSpec((None,), tf.int32)))
def eval_step(images, labels):
logits, _ = model(images, training=False)
loss = tf.keras.losses.sparse_categorical_crossentropy(
labels, logits, False)
loss = tf.reduce_mean(loss)
return loss, logits
def eval():
step_per_epoch = math.ceil(num_test / FLAGS.batch_size)
for i, (images, labels) in enumerate(test_dataset):
loss, logits = eval_step(images, labels)
loss_metric.update_state(loss)
accuracy_metric.update_state(labels, logits)
print('Eval %f%%, loss = %f, accuracy = %f' % \
(i / step_per_epoch * 100,
loss_metric.result().numpy(),
accuracy_metric.result().numpy() * 100))
if FLAGS.eval:
eval()
return
# train
step_per_epoch = math.ceil(num_train / FLAGS.batch_size)
lr_scheduler = tf.keras.optimizers.schedules.PiecewiseConstantDecay(
[100 * step_per_epoch, 200 * step_per_epoch],
[FLAGS.learning_rate, FLAGS.learning_rate * 0.1, FLAGS.learning_rate * 0.01]
)
optimizer = tf.keras.optimizers.Adam(learning_rate=lr_scheduler,
beta_1=0.9,
beta_2=0.999,
epsilon=0.1)
@tf.function(input_signature=(tf.TensorSpec(img_size, tf.float32),
tf.TensorSpec((None,), tf.int32)))
def train_step(images, labels):
with tf.GradientTape() as tape:
logits, prelogits = model(images, training=True)
loss = tf.keras.losses.sparse_categorical_crossentropy(
labels, logits, False)
loss = tf.reduce_mean(loss)
if FLAGS.use_center_loss:
# recomputation embedding (for export convenience)
embeddings = model.calculate_embedding(prelogits)
center_loss = model.calculate_center_loss(embeddings, labels)
else:
center_loss = tf.constant(0.0, dtype=tf.float32)
loss = (center_loss * 0.007) + loss
grads = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(zip(grads, model.trainable_variables))
return loss, center_loss, logits
model_dir = FLAGS.model_dir
if not os.path.exists(model_dir):
os.makedirs(model_dir)
global_step = 0
for epoch in range(FLAGS.num_epochs):
loss_metric.reset_states()
center_loss_metric.reset_states()
accuracy_metric.reset_states()
num_images = 0
start = time.time()
for epoch_step, (images, labels) in enumerate(train_dataset):
train_loss, train_center_loss, train_logits = train_step(images, labels)
loss_metric.update_state(train_loss)
center_loss_metric.update_state(train_center_loss)
accuracy_metric.update_state(labels, train_logits)
global_step += 1
num_images += images.shape[0]
if global_step % FLAGS.log_frequency == 0:
end = time.time()
throughput = num_images / (end - start)
logging.debug('Step %d (%f %% of epoch %d): loss = %f, '
'center loss = %f, accuracy = %f, learning rate = %.4f '
'throughput = %.2f',
global_step, (epoch_step / step_per_epoch * 100),
epoch + 1,
loss_metric.result().numpy(),
center_loss_metric.result().numpy(),
accuracy_metric.result().numpy() * 100,
optimizer._decayed_lr(tf.float32), # pylint: disable=protected-access
throughput)
if FLAGS.save_frequency > 0 and global_step % FLAGS.save_frequency == 0:
model.save_weights(os.path.join(model_dir, 'facenet_ckpt'))
if FLAGS.save_frequency > 0 and global_step % 1000 == 0:
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()
with tf.io.gfile.GFile('./tflite-models/facenet.tflite', 'wb') as f:
f.write(tflite_model)
if global_step % FLAGS.log_frequency == 0:
num_images = 0
start = time.time()
# eval and finish
eval()
if __name__ == "__main__":
app.run(main)
| """
main training modeul for facenet
"""
from __future__ import absolute_import, division, print_function
import getpass
import math
import os
import time
import numpy as np
import torch
from absl import app, flags
import tensorflow as tf
from models import CenterLoss, InceptionResNetV1
from utils.data_pipeline import create_data_pipeline
from utils.log import fedex_logger as logging
FLAGS = flags.FLAGS
# flags definition
flags.DEFINE_integer('image_size', 160,
'default image size')
flags.DEFINE_integer('batch_size', 90,
'training batch size')
flags.DEFINE_integer('num_epochs', 300,
'number of training epochs')
flags.DEFINE_float('learning_rate', 0.05,
'train learning rate')
flags.DEFINE_integer('log_frequency', 50,
'logging frequency')
flags.DEFINE_integer('save_frequency', 200,
'saving model frequency')
flags.DEFINE_string('data_dir', '/cmsdata/ssd1/cmslab/vggface2/final',
'root of dataset')
flags.DEFINE_string('model_dir', f'/tmp/{getpass.getuser()}/checkpoints',
'model checkpoint path')
flags.DEFINE_bool('eval', False,
'eval mode')
flags.DEFINE_bool('load_pretrained', False,
'load pretrained weights')
flags.DEFINE_bool('save_tflite', False,
'directly save tflite model')
flags.DEFINE_bool('use_center_loss', False,
'toggle center loss')
def load_pretrained(model):
"""load pretrained weight from pretrained pytorch model"""
# pylint: disable=line-too-long
pretrained_features = './checkpoints/inception_resnet_v1/vggface2_feature_map.pt'
pretrained_classifier = './checkpoints/inception_resnet_v1/vggface2_classifier.pt'
# pylint: enable=line-too-long
pretrained_weights = []
pretrained_weights.extend(list(torch.load(pretrained_features).values()))
pretrained_weights.extend(list(torch.load(pretrained_classifier).values()))
# num_batch_tracked
pretrained_weights = list(filter(lambda x: tuple(x.shape) != (),
pretrained_weights))
weight_iter = iter(pretrained_weights)
for layer in model.layers:
if isinstance(layer, CenterLoss):
# skip; PyTorch module does not have
continue
num_weights = len(layer.get_weights())
pth_weights = []
for _ in range(num_weights):
weight = next(weight_iter).numpy()
if len(weight.shape) == 4:
# conv kernel
weight = np.transpose(weight, (2, 3, 1, 0))
elif len(weight.shape) == 2:
# dense kernel
weight = np.transpose(weight)
pth_weights.append(weight)
layer.set_weights(pth_weights)
def main(args):
# dataset preparation
train_dataset, test_dataset, _, num_classes, num_train, num_test, _ = \
create_data_pipeline(FLAGS.data_dir, FLAGS.batch_size,
FLAGS.image_size)
model = InceptionResNetV1(num_classes=num_classes,
use_center_loss=FLAGS.use_center_loss)
img_size = (None, FLAGS.image_size, FLAGS.image_size, 3)
model.build(img_size)
if FLAGS.load_pretrained:
logging.info('load pretrained model...')
# for center loss variable
try:
model.load_weights(os.path.join(FLAGS.model_dir, 'facenet_ckpt'))
except ValueError:
logging.debug('pretrained checkpoint does not exists, '
'failed to restore center loss variable')
# load_pretrained(model)
logging.info('loading pretrained model finished!')
if FLAGS.save_tflite:
# pylint: disable=protected-access
model._set_inputs(tf.keras.layers.Input(shape=(160, 160, 3), batch_size=1))
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()
with tf.io.gfile.GFile('./tflite-models/facenet.tflite', 'wb') as f:
f.write(tflite_model)
return
loss_metric = tf.keras.metrics.Mean(name='loss', dtype=tf.float32)
center_loss_metric = tf.keras.metrics.Mean(name='center_loss',
dtype=tf.float32)
accuracy_metric = tf.keras.metrics.SparseCategoricalAccuracy(
name='accuracy', dtype=tf.float32)
@tf.function(input_signature=(tf.TensorSpec(img_size, tf.float32),
tf.TensorSpec((None,), tf.int32)))
def eval_step(images, labels):
logits, _ = model(images, training=False)
loss = tf.keras.losses.sparse_categorical_crossentropy(
labels, logits, False)
loss = tf.reduce_mean(loss)
return loss, logits
def eval():
step_per_epoch = math.ceil(num_test / FLAGS.batch_size)
for i, (images, labels) in enumerate(test_dataset):
loss, logits = eval_step(images, labels)
loss_metric.update_state(loss)
accuracy_metric.update_state(labels, logits)
print('Eval %f%%, loss = %f, accuracy = %f' % \
(i / step_per_epoch * 100,
loss_metric.result().numpy(),
accuracy_metric.result().numpy() * 100))
if FLAGS.eval:
eval()
return
# train
step_per_epoch = math.ceil(num_train / FLAGS.batch_size)
lr_scheduler = tf.keras.optimizers.schedules.PiecewiseConstantDecay(
[100 * step_per_epoch, 200 * step_per_epoch],
[FLAGS.learning_rate, FLAGS.learning_rate * 0.1, FLAGS.learning_rate * 0.01]
)
optimizer = tf.keras.optimizers.Adam(learning_rate=lr_scheduler,
beta_1=0.9,
beta_2=0.999,
epsilon=0.1)
@tf.function(input_signature=(tf.TensorSpec(img_size, tf.float32),
tf.TensorSpec((None,), tf.int32)))
def train_step(images, labels):
with tf.GradientTape() as tape:
logits, prelogits = model(images, training=True)
loss = tf.keras.losses.sparse_categorical_crossentropy(
labels, logits, False)
loss = tf.reduce_mean(loss)
if FLAGS.use_center_loss:
# recomputation embedding (for export convenience)
embeddings = model.calculate_embedding(prelogits)
center_loss = model.calculate_center_loss(embeddings, labels)
else:
center_loss = tf.constant(0.0, dtype=tf.float32)
loss = (center_loss * 0.007) + loss
grads = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(zip(grads, model.trainable_variables))
return loss, center_loss, logits
model_dir = FLAGS.model_dir
if not os.path.exists(model_dir):
os.makedirs(model_dir)
global_step = 0
for epoch in range(FLAGS.num_epochs):
loss_metric.reset_states()
center_loss_metric.reset_states()
accuracy_metric.reset_states()
num_images = 0
start = time.time()
for epoch_step, (images, labels) in enumerate(train_dataset):
train_loss, train_center_loss, train_logits = train_step(images, labels)
loss_metric.update_state(train_loss)
center_loss_metric.update_state(train_center_loss)
accuracy_metric.update_state(labels, train_logits)
global_step += 1
num_images += images.shape[0]
if global_step % FLAGS.log_frequency == 0:
end = time.time()
throughput = num_images / (end - start)
logging.debug('Step %d (%f %% of epoch %d): loss = %f, '
'center loss = %f, accuracy = %f, learning rate = %.4f '
'throughput = %.2f',
global_step, (epoch_step / step_per_epoch * 100),
epoch + 1,
loss_metric.result().numpy(),
center_loss_metric.result().numpy(),
accuracy_metric.result().numpy() * 100,
optimizer._decayed_lr(tf.float32), # pylint: disable=protected-access
throughput)
if FLAGS.save_frequency > 0 and global_step % FLAGS.save_frequency == 0:
model.save_weights(os.path.join(model_dir, 'facenet_ckpt'))
if FLAGS.save_frequency > 0 and global_step % 1000 == 0:
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()
with tf.io.gfile.GFile('./tflite-models/facenet.tflite', 'wb') as f:
f.write(tflite_model)
if global_step % FLAGS.log_frequency == 0:
num_images = 0
start = time.time()
# eval and finish
eval()
if __name__ == "__main__":
app.run(main) | en | 0.638226 | main training modeul for facenet # flags definition load pretrained weight from pretrained pytorch model # pylint: disable=line-too-long # pylint: enable=line-too-long # num_batch_tracked # skip; PyTorch module does not have # conv kernel # dense kernel # dataset preparation # for center loss variable # load_pretrained(model) # pylint: disable=protected-access # train # recomputation embedding (for export convenience) # pylint: disable=protected-access # eval and finish | 1.8719 | 2 |
synthrl/common/utils/decoratorutils.py | kupl/synthrl | 7 | 6618856 | <reponame>kupl/synthrl<filename>synthrl/common/utils/decoratorutils.py<gh_stars>1-10
class classproperty:
def __init__(self, getter):
self.getter = getter if isinstance(getter, (classmethod, staticmethod)) else classmethod(getter)
def __get__(self, instance, owner):
return self.getter.__get__(instance, owner)()
| class classproperty:
def __init__(self, getter):
self.getter = getter if isinstance(getter, (classmethod, staticmethod)) else classmethod(getter)
def __get__(self, instance, owner):
return self.getter.__get__(instance, owner)() | none | 1 | 3.074286 | 3 | |
Gradient-Boosting-Mechanism/code.py | hn1201/ga-learner-dsmp-repo | 0 | 6618857 | # --------------
import pandas as pd
from sklearn.model_selection import train_test_split
#path - Path of file
# Code starts here
df = pd.read_csv(path)
print(df.head(2))
X = df.drop(['customerID', 'Churn'], axis = 1)
y = df['Churn'].copy()
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)
# --------------
import numpy as np
from sklearn.preprocessing import LabelEncoder
# Code starts here
X_train['TotalCharges'] = X_train['TotalCharges'].replace(r'^\s+$', np.nan, regex=True)
X_test['TotalCharges'] = X_test['TotalCharges'].replace(r'^\s+$', np.nan, regex=True)
X_train['TotalCharges'] = X_train['TotalCharges'].astype(float)
X_test['TotalCharges'] = X_test['TotalCharges'].astype(float)
X_train['TotalCharges'] = X_train['TotalCharges'].fillna(X_train['TotalCharges'].mean())
X_test['TotalCharges'] = X_test['TotalCharges'].fillna(X_test['TotalCharges'].mean())
#print(X_train.isnull().sum())
le = LabelEncoder()
for col in X_train.columns :
if X_train[col].dtypes == 'object' :
X_train[col] = le.fit_transform(X_train[col])
X_test[col] = le.transform(X_test[col])
y_train.replace({'No' : 0, 'Yes' : 1}, inplace=True)
y_test.replace({'No' : 0, 'Yes' : 1}, inplace=True)
# --------------
from sklearn.ensemble import AdaBoostClassifier
from sklearn.metrics import accuracy_score,classification_report,confusion_matrix
# Code starts here
ada_model = AdaBoostClassifier(random_state=0)
ada_model.fit(X_train, y_train)
y_pred = ada_model.predict(X_test)
ada_score = accuracy_score(y_test, y_pred)
print(ada_score)
ada_cm = confusion_matrix(y_test, y_pred)
ada_cr = classification_report(y_test, y_pred)
print(ada_cm)
print(ada_cr)
# --------------
from xgboost import XGBClassifier
from sklearn.model_selection import GridSearchCV
#Parameter list
parameters={'learning_rate':[0.1,0.15,0.2,0.25,0.3],
'max_depth':range(1,3)}
# Code starts here
xgb_model = XGBClassifier(random_state=0)
xgb_model.fit(X_train, y_train)
y_pred = xgb_model.predict(X_test)
xgb_score = accuracy_score(y_test, y_pred)
print(xgb_score)
xgb_cm = confusion_matrix(y_test, y_pred)
xgb_cr = classification_report(y_test, y_pred)
#print(xgb_cm)
#print(xgb_cr)
clf_model = GridSearchCV(estimator=xgb_model, param_grid=parameters)
clf_model.fit(X_train, y_train)
y_pred = clf_model.predict(X_test)
clf_score = accuracy_score(y_test, y_pred)
clf_cm = confusion_matrix(y_test, y_pred)
clf_cr = classification_report(y_test, y_pred)
print(clf_score)
| # --------------
import pandas as pd
from sklearn.model_selection import train_test_split
#path - Path of file
# Code starts here
df = pd.read_csv(path)
print(df.head(2))
X = df.drop(['customerID', 'Churn'], axis = 1)
y = df['Churn'].copy()
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)
# --------------
import numpy as np
from sklearn.preprocessing import LabelEncoder
# Code starts here
X_train['TotalCharges'] = X_train['TotalCharges'].replace(r'^\s+$', np.nan, regex=True)
X_test['TotalCharges'] = X_test['TotalCharges'].replace(r'^\s+$', np.nan, regex=True)
X_train['TotalCharges'] = X_train['TotalCharges'].astype(float)
X_test['TotalCharges'] = X_test['TotalCharges'].astype(float)
X_train['TotalCharges'] = X_train['TotalCharges'].fillna(X_train['TotalCharges'].mean())
X_test['TotalCharges'] = X_test['TotalCharges'].fillna(X_test['TotalCharges'].mean())
#print(X_train.isnull().sum())
le = LabelEncoder()
for col in X_train.columns :
if X_train[col].dtypes == 'object' :
X_train[col] = le.fit_transform(X_train[col])
X_test[col] = le.transform(X_test[col])
y_train.replace({'No' : 0, 'Yes' : 1}, inplace=True)
y_test.replace({'No' : 0, 'Yes' : 1}, inplace=True)
# --------------
from sklearn.ensemble import AdaBoostClassifier
from sklearn.metrics import accuracy_score,classification_report,confusion_matrix
# Code starts here
ada_model = AdaBoostClassifier(random_state=0)
ada_model.fit(X_train, y_train)
y_pred = ada_model.predict(X_test)
ada_score = accuracy_score(y_test, y_pred)
print(ada_score)
ada_cm = confusion_matrix(y_test, y_pred)
ada_cr = classification_report(y_test, y_pred)
print(ada_cm)
print(ada_cr)
# --------------
from xgboost import XGBClassifier
from sklearn.model_selection import GridSearchCV
#Parameter list
parameters={'learning_rate':[0.1,0.15,0.2,0.25,0.3],
'max_depth':range(1,3)}
# Code starts here
xgb_model = XGBClassifier(random_state=0)
xgb_model.fit(X_train, y_train)
y_pred = xgb_model.predict(X_test)
xgb_score = accuracy_score(y_test, y_pred)
print(xgb_score)
xgb_cm = confusion_matrix(y_test, y_pred)
xgb_cr = classification_report(y_test, y_pred)
#print(xgb_cm)
#print(xgb_cr)
clf_model = GridSearchCV(estimator=xgb_model, param_grid=parameters)
clf_model.fit(X_train, y_train)
y_pred = clf_model.predict(X_test)
clf_score = accuracy_score(y_test, y_pred)
clf_cm = confusion_matrix(y_test, y_pred)
clf_cr = classification_report(y_test, y_pred)
print(clf_score)
| en | 0.330514 | # -------------- #path - Path of file # Code starts here # -------------- # Code starts here #print(X_train.isnull().sum()) # -------------- # Code starts here # -------------- #Parameter list # Code starts here #print(xgb_cm) #print(xgb_cr) | 3.187743 | 3 |
assistant/model/assistantDataLoader.py | nspeer12/speer.ai | 0 | 6618858 | <filename>assistant/model/assistantDataLoader.py
import torch
from torch.utils.data import Dataset, DataLoader
import numpy as np
import math
import pandas as pd
import json
import nltk
nltk.download('wordnet')
from nltk.stem import WordNetLemmatizer
import csv
class assistantDataset(Dataset):
def __init__(self):
# Load data
jsonfile = open('intents.json','r')
jsondata = jsonfile.read()
intents = json.loads(jsondata)
lemmatizer = WordNetLemmatizer()
words = []
classes = []
documents = []
ignore_letters = ['!', '?', ',', '.']
for intent in intents['intents']:
for pattern in intent['patterns']:
word = nltk.word_tokenize(pattern)
words.extend(word)
documents.append((word, intent['tag']))
if intent['tag'] not in classes:
classes.append(intent['tag'])
words = [lemmatizer.lemmatize(w.lower()) for w in words if w not in ignore_letters]
words = sorted(list(set(words)))
classes = sorted(list(set(classes)))
# print(words)
# print(classes)
# print(documents)
word_dict = {}
for i in range(len(words)):
word_dict[words[i]] = i
with open("Assistant_features.csv",'w', newline="") as f:
writer = csv.writer(f)
for word in word_dict.keys():
writer.writerow([word])
with open("Assistant_labels.csv",'w', newline="") as f:
writer = csv.writer(f)
for label in classes:
writer.writerow([label])
x = []
y = []
for doc in documents:
bag = [0] * len(words)
word_patterns = doc[0] # extracts features
word_patterns = [lemmatizer.lemmatize(word.lower()) for word in word_patterns] # makes lower case
for word in word_patterns:
if word in word_dict:
bag[word_dict.get(word)] += 1
label = classes.index(doc[1])
x.append(bag)
y.append(label)
x = np.array(x)
y = np.array(y)
self.x = torch.from_numpy(np.array(x))
self.y = torch.from_numpy(np.array(y))
self.n_samples = len(y)
self.num_features = len(words)
self.num_classes = len(classes)
def __getitem__(self, index):
return self.x[index], self.y[index]
def __len__(self):
return self.n_samples
dataset = assistantDataset()
# first_data = dataset[0]
# features, labels = first_data
# print(features, labels)
# dataloader = DataLoader(dataset=dataset, batch_size = 4, shuffle = True)
# # dataiter = iter(dataloader)
# # data = dataiter.next()
# # features, labels = data
# # print(features, labels)
# # training loop
# num_epochs = 2
# total_samples = len(dataset)
# n_iterations = math.ceil(total_samples / 4)
# print(total_samples, n_iterations)
# for epoch in range(num_epochs):
# for i, (inputs, labels) in enumerate(dataloader):
# # forward, backward, update
# if (i + 1) % 5 == 0:
# print(f'epoch {epoch + 1}/{num_epochs}, step {i+1} / {n_iterations}, inputs {inputs.shape}') | <filename>assistant/model/assistantDataLoader.py
import torch
from torch.utils.data import Dataset, DataLoader
import numpy as np
import math
import pandas as pd
import json
import nltk
nltk.download('wordnet')
from nltk.stem import WordNetLemmatizer
import csv
class assistantDataset(Dataset):
def __init__(self):
# Load data
jsonfile = open('intents.json','r')
jsondata = jsonfile.read()
intents = json.loads(jsondata)
lemmatizer = WordNetLemmatizer()
words = []
classes = []
documents = []
ignore_letters = ['!', '?', ',', '.']
for intent in intents['intents']:
for pattern in intent['patterns']:
word = nltk.word_tokenize(pattern)
words.extend(word)
documents.append((word, intent['tag']))
if intent['tag'] not in classes:
classes.append(intent['tag'])
words = [lemmatizer.lemmatize(w.lower()) for w in words if w not in ignore_letters]
words = sorted(list(set(words)))
classes = sorted(list(set(classes)))
# print(words)
# print(classes)
# print(documents)
word_dict = {}
for i in range(len(words)):
word_dict[words[i]] = i
with open("Assistant_features.csv",'w', newline="") as f:
writer = csv.writer(f)
for word in word_dict.keys():
writer.writerow([word])
with open("Assistant_labels.csv",'w', newline="") as f:
writer = csv.writer(f)
for label in classes:
writer.writerow([label])
x = []
y = []
for doc in documents:
bag = [0] * len(words)
word_patterns = doc[0] # extracts features
word_patterns = [lemmatizer.lemmatize(word.lower()) for word in word_patterns] # makes lower case
for word in word_patterns:
if word in word_dict:
bag[word_dict.get(word)] += 1
label = classes.index(doc[1])
x.append(bag)
y.append(label)
x = np.array(x)
y = np.array(y)
self.x = torch.from_numpy(np.array(x))
self.y = torch.from_numpy(np.array(y))
self.n_samples = len(y)
self.num_features = len(words)
self.num_classes = len(classes)
def __getitem__(self, index):
return self.x[index], self.y[index]
def __len__(self):
return self.n_samples
dataset = assistantDataset()
# first_data = dataset[0]
# features, labels = first_data
# print(features, labels)
# dataloader = DataLoader(dataset=dataset, batch_size = 4, shuffle = True)
# # dataiter = iter(dataloader)
# # data = dataiter.next()
# # features, labels = data
# # print(features, labels)
# # training loop
# num_epochs = 2
# total_samples = len(dataset)
# n_iterations = math.ceil(total_samples / 4)
# print(total_samples, n_iterations)
# for epoch in range(num_epochs):
# for i, (inputs, labels) in enumerate(dataloader):
# # forward, backward, update
# if (i + 1) % 5 == 0:
# print(f'epoch {epoch + 1}/{num_epochs}, step {i+1} / {n_iterations}, inputs {inputs.shape}') | en | 0.489115 | # Load data # print(words) # print(classes) # print(documents) # extracts features # makes lower case # first_data = dataset[0] # features, labels = first_data # print(features, labels) # dataloader = DataLoader(dataset=dataset, batch_size = 4, shuffle = True) # # dataiter = iter(dataloader) # # data = dataiter.next() # # features, labels = data # # print(features, labels) # # training loop # num_epochs = 2 # total_samples = len(dataset) # n_iterations = math.ceil(total_samples / 4) # print(total_samples, n_iterations) # for epoch in range(num_epochs): # for i, (inputs, labels) in enumerate(dataloader): # # forward, backward, update # if (i + 1) % 5 == 0: # print(f'epoch {epoch + 1}/{num_epochs}, step {i+1} / {n_iterations}, inputs {inputs.shape}') | 2.690728 | 3 |
libraries/mosek/9.3/tools/examples/fusion/python/gp1.py | TimDSF/SBSOS_ShapeSegmentation | 0 | 6618859 | <filename>libraries/mosek/9.3/tools/examples/fusion/python/gp1.py
##
# Copyright: Copyright (c) MOSEK ApS, Denmark. All rights reserved.
#
# File: gp1.py
#
# Purpose: Demonstrates how to solve a simple Geometric Program (GP)
# cast into conic form with exponential cones and log-sum-exp.
#
# Example from
# https://gpkit.readthedocs.io/en/latest/examples.html#maximizing-the-volume-of-a-box
#
from numpy import log, exp, array
from mosek.fusion import *
import sys
# Models log(sum(exp(Ax+b))) <= 0.
# Each row of [A b] describes one of the exp-terms
def logsumexp(M, A, x, b):
k = int(A.shape[0])
u = M.variable(k)
M.constraint(Expr.sum(u), Domain.equalsTo(1.0))
M.constraint(Expr.hstack(u,
Expr.constTerm(k, 1.0),
Expr.add(Expr.mul(A, x), b)), Domain.inPExpCone())
# maximize h*w*d
# subjecto to 2*(h*w + h*d) <= Awall
# w*d <= Afloor
# alpha <= h/w <= beta
# gamma <= d/w <= delta
#
# Variable substitutions: h = exp(x), w = exp(y), d = exp(z).
#
# maximize x+y+z
# subject log( exp(x+y+log(2/Awall)) + exp(x+z+log(2/Awall)) ) <= 0
# y+z <= log(Afloor)
# log( alpha ) <= x-y <= log( beta )
# log( gamma ) <= z-y <= log( delta )
def max_volume_box(Aw, Af, alpha, beta, gamma, delta):
with Model('max_vol_box') as M:
xyz = M.variable(3)
M.objective('Objective', ObjectiveSense.Maximize, Expr.sum(xyz))
logsumexp(M, array([[1,1,0],[1,0,1]]), xyz, array([log(2.0/Aw), log(2.0/Aw)]))
M.constraint(Expr.dot([0, 1, 1], xyz), Domain.lessThan(log(Af)))
M.constraint(Expr.dot([1,-1, 0], xyz), Domain.inRange(log(alpha),log(beta)))
M.constraint(Expr.dot([0,-1, 1], xyz), Domain.inRange(log(gamma),log(delta)))
M.setLogHandler(sys.stdout)
M.solve()
return exp(xyz.level())
Aw, Af, alpha, beta, gamma, delta = 200.0, 50.0, 2.0, 10.0, 2.0, 10.0
h,w,d = max_volume_box(Aw, Af, alpha, beta, gamma, delta)
print("h={0:.3f}, w={1:.3f}, d={2:.3f}".format(h, w, d)) | <filename>libraries/mosek/9.3/tools/examples/fusion/python/gp1.py
##
# Copyright: Copyright (c) MOSEK ApS, Denmark. All rights reserved.
#
# File: gp1.py
#
# Purpose: Demonstrates how to solve a simple Geometric Program (GP)
# cast into conic form with exponential cones and log-sum-exp.
#
# Example from
# https://gpkit.readthedocs.io/en/latest/examples.html#maximizing-the-volume-of-a-box
#
from numpy import log, exp, array
from mosek.fusion import *
import sys
# Models log(sum(exp(Ax+b))) <= 0.
# Each row of [A b] describes one of the exp-terms
def logsumexp(M, A, x, b):
k = int(A.shape[0])
u = M.variable(k)
M.constraint(Expr.sum(u), Domain.equalsTo(1.0))
M.constraint(Expr.hstack(u,
Expr.constTerm(k, 1.0),
Expr.add(Expr.mul(A, x), b)), Domain.inPExpCone())
# maximize h*w*d
# subjecto to 2*(h*w + h*d) <= Awall
# w*d <= Afloor
# alpha <= h/w <= beta
# gamma <= d/w <= delta
#
# Variable substitutions: h = exp(x), w = exp(y), d = exp(z).
#
# maximize x+y+z
# subject log( exp(x+y+log(2/Awall)) + exp(x+z+log(2/Awall)) ) <= 0
# y+z <= log(Afloor)
# log( alpha ) <= x-y <= log( beta )
# log( gamma ) <= z-y <= log( delta )
def max_volume_box(Aw, Af, alpha, beta, gamma, delta):
with Model('max_vol_box') as M:
xyz = M.variable(3)
M.objective('Objective', ObjectiveSense.Maximize, Expr.sum(xyz))
logsumexp(M, array([[1,1,0],[1,0,1]]), xyz, array([log(2.0/Aw), log(2.0/Aw)]))
M.constraint(Expr.dot([0, 1, 1], xyz), Domain.lessThan(log(Af)))
M.constraint(Expr.dot([1,-1, 0], xyz), Domain.inRange(log(alpha),log(beta)))
M.constraint(Expr.dot([0,-1, 1], xyz), Domain.inRange(log(gamma),log(delta)))
M.setLogHandler(sys.stdout)
M.solve()
return exp(xyz.level())
Aw, Af, alpha, beta, gamma, delta = 200.0, 50.0, 2.0, 10.0, 2.0, 10.0
h,w,d = max_volume_box(Aw, Af, alpha, beta, gamma, delta)
print("h={0:.3f}, w={1:.3f}, d={2:.3f}".format(h, w, d)) | en | 0.73037 | ## # Copyright: Copyright (c) MOSEK ApS, Denmark. All rights reserved. # # File: gp1.py # # Purpose: Demonstrates how to solve a simple Geometric Program (GP) # cast into conic form with exponential cones and log-sum-exp. # # Example from # https://gpkit.readthedocs.io/en/latest/examples.html#maximizing-the-volume-of-a-box # # Models log(sum(exp(Ax+b))) <= 0. # Each row of [A b] describes one of the exp-terms # maximize h*w*d # subjecto to 2*(h*w + h*d) <= Awall # w*d <= Afloor # alpha <= h/w <= beta # gamma <= d/w <= delta # # Variable substitutions: h = exp(x), w = exp(y), d = exp(z). # # maximize x+y+z # subject log( exp(x+y+log(2/Awall)) + exp(x+z+log(2/Awall)) ) <= 0 # y+z <= log(Afloor) # log( alpha ) <= x-y <= log( beta ) # log( gamma ) <= z-y <= log( delta ) | 2.97175 | 3 |
1.py | atulb07/Dishathon | 0 | 6618860 | <filename>1.py
import numpy as np
import matplotlib.pyplot as plt
d = np.load("data/left/1572814991.npy")
for channel in d[175]:
plt.plot(channel)
plt.show() | <filename>1.py
import numpy as np
import matplotlib.pyplot as plt
d = np.load("data/left/1572814991.npy")
for channel in d[175]:
plt.plot(channel)
plt.show() | none | 1 | 2.66948 | 3 | |
lib/memcached.py | iqtek/amocrm_event_listener | 0 | 6618861 | import memcache
from settings import MEMCACHE as SETTINGS
__all__ = ["Memcached", ]
class Memcache(object):
instance = None
def getConnectin(self):
return memcache.Client(
[SETTINGS["HOST"] +':' + SETTINGS["PORT"]],
#pickler=SimplejsonWrapper,
#unpickler=SimplejsonWrapper
)
def getInstance(self):
if self.instance is None:
self.instance = self.getConnectin()
return self.instance
def reconnect(self):
del self.instance
return self.getInstance()
Memcached = Memcache() | import memcache
from settings import MEMCACHE as SETTINGS
__all__ = ["Memcached", ]
class Memcache(object):
instance = None
def getConnectin(self):
return memcache.Client(
[SETTINGS["HOST"] +':' + SETTINGS["PORT"]],
#pickler=SimplejsonWrapper,
#unpickler=SimplejsonWrapper
)
def getInstance(self):
if self.instance is None:
self.instance = self.getConnectin()
return self.instance
def reconnect(self):
del self.instance
return self.getInstance()
Memcached = Memcache() | da | 0.17005 | #pickler=SimplejsonWrapper, #unpickler=SimplejsonWrapper | 2.866813 | 3 |
openGaussBase/testcase/SQL/DDL/hash_index/Opengauss_Function_DDL_Hash_Index_Case0001.py | opengauss-mirror/Yat | 0 | 6618862 | """
Copyright (c) 2022 Huawei Technologies Co.,Ltd.
openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type : 功能
Case Name : 创建hash索引后,对索引数据进行DML操作,创建逻辑复制槽并解码
Description :
1.修改参数wal_level为logical;
2.重启数据库
3.创建逻辑复制槽
4.建表并创建hash索引
5.读取复制槽解码结果;解码insert语句
6.修改索引数据
7.读取复制槽解码结果;解码update语句
8.查询索引数据
9.删除索引数据
10.读取复制槽解码结果;解码delete语句
11.删除索引后查看解码
12.清理环境
Expect :
1.修改参数wal_level为logical成功
2.重启数据库成功
3.创建逻辑复制槽成功
4.建表并创建hash索引成功
5.解码成功
6.修改索引数据成功
7.解码成功
8.数据量少时查询计划走顺序扫描
9.删除索引数据成功
10.解码成功
11.删除索引不解码
12.清理环境完成
History :
"""
import unittest
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node
class LogicalReplication(unittest.TestCase):
def setUp(self):
self.log = Logger()
self.log.info('-Opengauss_Function_DDL_Hash_Index_Case0001start-')
self.constant = Constant()
self.primary_sh = CommonSH('PrimaryDbUser')
self.primary_node = Node('PrimaryDbUser')
self.slot_name = "slot_hash_index_0001"
self.tb_name = "t_hash_index_0001"
self.id_name = "i_hash_index_0001"
def test_standby(self):
text = '--step1:修改wal_level为logical;expect:修改成功--'
self.log.info(text)
mod_msg = self.primary_sh.execute_gsguc('set',
self.constant.GSGUC_SUCCESS_MSG,
'wal_level =logical')
self.log.info(mod_msg)
self.assertTrue(mod_msg)
text = '--step2:重启数据库;expect:重启成功--'
self.log.info(text)
restart_msg = self.primary_sh.restart_db_cluster()
self.log.info(restart_msg)
status = self.primary_sh.get_db_cluster_status()
self.assertTrue("Degraded" in status or "Normal" in status,
'执行失败:' + text)
text = '--step3:创建逻辑复制槽;expect:创建成功--'
self.log.info(text)
sql_cmd = self.primary_sh.execut_db_sql(f'''select * from \
pg_create_logical_replication_slot('{self.slot_name}', \
'mppdb_decoding');''')
self.log.info(sql_cmd)
self.assertIn(f'{self.slot_name}', sql_cmd, '执行失败:' + text)
text = '--step4:建表并创建hash索引;expect:创建成功--'
self.log.info(text)
create_cmd = self.primary_sh.execut_db_sql(f'''drop table if exists
{self.tb_name};
create table {self.tb_name} (id int, sex varchar(20));
insert into {self.tb_name} values(5, 'XXX');
drop index if exists {self.id_name};
create index {self.id_name} on {self.tb_name} using hash (id);''')
self.log.info(create_cmd)
self.assertIn(self.constant.TABLE_CREATE_SUCCESS, create_cmd,
'执行失败:' + text)
self.assertIn(self.constant.CREATE_INDEX_SUCCESS_MSG, create_cmd,
'执行失败:' + text)
text = '--step5:读取复制槽解码结果;解码insert语句;expect:解码成功--'
self.log.info(text)
sql_cmd = self.primary_sh.execut_db_sql(f'''select * from \
pg_logical_slot_peek_changes('{self.slot_name}', null, 4096);''')
self.log.info(sql_cmd)
self.assertIn('"op_type":"INSERT"', sql_cmd, '执行失败:' + text)
text = '--step6:修改索引数据;expect:修改成功--'
self.log.info(text)
sql_cmd = self.primary_sh.execut_db_sql(f'''update {self.tb_name} \
set id = id*10;''')
self.log.info(sql_cmd)
self.assertIn('UPDATE', sql_cmd, '执行失败:' + text)
text = '--step7:读取复制槽解码结果;解码update语句;expect:解码成功--'
self.log.info(text)
sql_cmd = self.primary_sh.execut_db_sql(f'''select * from \
pg_logical_slot_peek_changes('{self.slot_name}', null, 4096);''')
self.log.info(sql_cmd)
self.assertIn('"op_type":"UPDATE"', sql_cmd, '执行失败:' + text)
text = '--step8:查询索引数据;expect:数据量少时查询计划走顺序扫描--'
self.log.info(text)
sql_cmd = self.primary_sh.execut_db_sql(f'''explain select * from \
{self.tb_name} where id =50;''')
self.log.info(sql_cmd)
self.assertIn('Seq Scan', sql_cmd, '执行失败:' + text)
text = '--step9:删除索引数据;expect:删除成功--'
self.log.info(text)
sql_cmd = self.primary_sh.execut_db_sql(f'''delete from {self.tb_name} \
where id =50;''')
self.log.info(sql_cmd)
text = '--step10:读取复制槽解码结果;解码delete语句;expect:解码成功--'
self.log.info(text)
sql_cmd = self.primary_sh.execut_db_sql(f'''select * from \
pg_logical_slot_peek_changes('{self.slot_name}', null, 4096);''')
self.log.info(sql_cmd)
self.assertIn('"op_type":"DELETE"', sql_cmd, '执行失败:' + text)
text = '--step11:删除索引后查看解码;expect:删除索引不解码;--'
self.log.info(text)
sql_cmd = self.primary_sh.execut_db_sql(f'''drop index {self.id_name};
select * from pg_logical_slot_peek_changes\
('{self.slot_name}', NULL, 4096); ''')
self.log.info(sql_cmd)
self.assertIn(self.constant.DROP_INDEX_SUCCESS_MSG, sql_cmd,
'执行失败:' + text)
self.assertNotIn('"op_type":"DROP"', sql_cmd, '执行失败:' + text)
def tearDown(self):
text = '--step12:清理环境;expect:清理环境完成--'
self.log.info(text)
sql_cmd = self.primary_sh.execut_db_sql(f'''select * from \
pg_drop_replication_slot('{self.slot_name}');\
drop table if exists {self.tb_name};''')
self.log.info(sql_cmd)
restore_cmd = self.primary_sh.execute_gsguc('set',
self.constant.GSGUC_SUCCESS_MSG,
'wal_level=hot_standby')
self.log.info(restore_cmd)
restart_msg = self.primary_sh.restart_db_cluster()
self.log.info(restart_msg)
status = self.primary_sh.get_db_cluster_status()
self.assertTrue("Degraded" in status or "Normal" in status)
self.log.info('-Opengauss_Function_DDL_Hash_Index_Case0001finish--')
| """
Copyright (c) 2022 Huawei Technologies Co.,Ltd.
openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type : 功能
Case Name : 创建hash索引后,对索引数据进行DML操作,创建逻辑复制槽并解码
Description :
1.修改参数wal_level为logical;
2.重启数据库
3.创建逻辑复制槽
4.建表并创建hash索引
5.读取复制槽解码结果;解码insert语句
6.修改索引数据
7.读取复制槽解码结果;解码update语句
8.查询索引数据
9.删除索引数据
10.读取复制槽解码结果;解码delete语句
11.删除索引后查看解码
12.清理环境
Expect :
1.修改参数wal_level为logical成功
2.重启数据库成功
3.创建逻辑复制槽成功
4.建表并创建hash索引成功
5.解码成功
6.修改索引数据成功
7.解码成功
8.数据量少时查询计划走顺序扫描
9.删除索引数据成功
10.解码成功
11.删除索引不解码
12.清理环境完成
History :
"""
import unittest
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node
class LogicalReplication(unittest.TestCase):
def setUp(self):
self.log = Logger()
self.log.info('-Opengauss_Function_DDL_Hash_Index_Case0001start-')
self.constant = Constant()
self.primary_sh = CommonSH('PrimaryDbUser')
self.primary_node = Node('PrimaryDbUser')
self.slot_name = "slot_hash_index_0001"
self.tb_name = "t_hash_index_0001"
self.id_name = "i_hash_index_0001"
def test_standby(self):
text = '--step1:修改wal_level为logical;expect:修改成功--'
self.log.info(text)
mod_msg = self.primary_sh.execute_gsguc('set',
self.constant.GSGUC_SUCCESS_MSG,
'wal_level =logical')
self.log.info(mod_msg)
self.assertTrue(mod_msg)
text = '--step2:重启数据库;expect:重启成功--'
self.log.info(text)
restart_msg = self.primary_sh.restart_db_cluster()
self.log.info(restart_msg)
status = self.primary_sh.get_db_cluster_status()
self.assertTrue("Degraded" in status or "Normal" in status,
'执行失败:' + text)
text = '--step3:创建逻辑复制槽;expect:创建成功--'
self.log.info(text)
sql_cmd = self.primary_sh.execut_db_sql(f'''select * from \
pg_create_logical_replication_slot('{self.slot_name}', \
'mppdb_decoding');''')
self.log.info(sql_cmd)
self.assertIn(f'{self.slot_name}', sql_cmd, '执行失败:' + text)
text = '--step4:建表并创建hash索引;expect:创建成功--'
self.log.info(text)
create_cmd = self.primary_sh.execut_db_sql(f'''drop table if exists
{self.tb_name};
create table {self.tb_name} (id int, sex varchar(20));
insert into {self.tb_name} values(5, 'XXX');
drop index if exists {self.id_name};
create index {self.id_name} on {self.tb_name} using hash (id);''')
self.log.info(create_cmd)
self.assertIn(self.constant.TABLE_CREATE_SUCCESS, create_cmd,
'执行失败:' + text)
self.assertIn(self.constant.CREATE_INDEX_SUCCESS_MSG, create_cmd,
'执行失败:' + text)
text = '--step5:读取复制槽解码结果;解码insert语句;expect:解码成功--'
self.log.info(text)
sql_cmd = self.primary_sh.execut_db_sql(f'''select * from \
pg_logical_slot_peek_changes('{self.slot_name}', null, 4096);''')
self.log.info(sql_cmd)
self.assertIn('"op_type":"INSERT"', sql_cmd, '执行失败:' + text)
text = '--step6:修改索引数据;expect:修改成功--'
self.log.info(text)
sql_cmd = self.primary_sh.execut_db_sql(f'''update {self.tb_name} \
set id = id*10;''')
self.log.info(sql_cmd)
self.assertIn('UPDATE', sql_cmd, '执行失败:' + text)
text = '--step7:读取复制槽解码结果;解码update语句;expect:解码成功--'
self.log.info(text)
sql_cmd = self.primary_sh.execut_db_sql(f'''select * from \
pg_logical_slot_peek_changes('{self.slot_name}', null, 4096);''')
self.log.info(sql_cmd)
self.assertIn('"op_type":"UPDATE"', sql_cmd, '执行失败:' + text)
text = '--step8:查询索引数据;expect:数据量少时查询计划走顺序扫描--'
self.log.info(text)
sql_cmd = self.primary_sh.execut_db_sql(f'''explain select * from \
{self.tb_name} where id =50;''')
self.log.info(sql_cmd)
self.assertIn('Seq Scan', sql_cmd, '执行失败:' + text)
text = '--step9:删除索引数据;expect:删除成功--'
self.log.info(text)
sql_cmd = self.primary_sh.execut_db_sql(f'''delete from {self.tb_name} \
where id =50;''')
self.log.info(sql_cmd)
text = '--step10:读取复制槽解码结果;解码delete语句;expect:解码成功--'
self.log.info(text)
sql_cmd = self.primary_sh.execut_db_sql(f'''select * from \
pg_logical_slot_peek_changes('{self.slot_name}', null, 4096);''')
self.log.info(sql_cmd)
self.assertIn('"op_type":"DELETE"', sql_cmd, '执行失败:' + text)
text = '--step11:删除索引后查看解码;expect:删除索引不解码;--'
self.log.info(text)
sql_cmd = self.primary_sh.execut_db_sql(f'''drop index {self.id_name};
select * from pg_logical_slot_peek_changes\
('{self.slot_name}', NULL, 4096); ''')
self.log.info(sql_cmd)
self.assertIn(self.constant.DROP_INDEX_SUCCESS_MSG, sql_cmd,
'执行失败:' + text)
self.assertNotIn('"op_type":"DROP"', sql_cmd, '执行失败:' + text)
def tearDown(self):
text = '--step12:清理环境;expect:清理环境完成--'
self.log.info(text)
sql_cmd = self.primary_sh.execut_db_sql(f'''select * from \
pg_drop_replication_slot('{self.slot_name}');\
drop table if exists {self.tb_name};''')
self.log.info(sql_cmd)
restore_cmd = self.primary_sh.execute_gsguc('set',
self.constant.GSGUC_SUCCESS_MSG,
'wal_level=hot_standby')
self.log.info(restore_cmd)
restart_msg = self.primary_sh.restart_db_cluster()
self.log.info(restart_msg)
status = self.primary_sh.get_db_cluster_status()
self.assertTrue("Degraded" in status or "Normal" in status)
self.log.info('-Opengauss_Function_DDL_Hash_Index_Case0001finish--')
| en | 0.316879 | Copyright (c) 2022 Huawei Technologies Co.,Ltd. openGauss is licensed under Mulan PSL v2. You can use this software according to the terms and conditions of the Mulan PSL v2. You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2 THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. See the Mulan PSL v2 for more details. Case Type : 功能 Case Name : 创建hash索引后,对索引数据进行DML操作,创建逻辑复制槽并解码 Description : 1.修改参数wal_level为logical; 2.重启数据库 3.创建逻辑复制槽 4.建表并创建hash索引 5.读取复制槽解码结果;解码insert语句 6.修改索引数据 7.读取复制槽解码结果;解码update语句 8.查询索引数据 9.删除索引数据 10.读取复制槽解码结果;解码delete语句 11.删除索引后查看解码 12.清理环境 Expect : 1.修改参数wal_level为logical成功 2.重启数据库成功 3.创建逻辑复制槽成功 4.建表并创建hash索引成功 5.解码成功 6.修改索引数据成功 7.解码成功 8.数据量少时查询计划走顺序扫描 9.删除索引数据成功 10.解码成功 11.删除索引不解码 12.清理环境完成 History : select * from \ pg_create_logical_replication_slot('{self.slot_name}', \ 'mppdb_decoding'); drop table if exists {self.tb_name}; create table {self.tb_name} (id int, sex varchar(20)); insert into {self.tb_name} values(5, 'XXX'); drop index if exists {self.id_name}; create index {self.id_name} on {self.tb_name} using hash (id); select * from \ pg_logical_slot_peek_changes('{self.slot_name}', null, 4096); update {self.tb_name} \ set id = id*10; select * from \ pg_logical_slot_peek_changes('{self.slot_name}', null, 4096); explain select * from \ {self.tb_name} where id =50; delete from {self.tb_name} \ where id =50; select * from \ pg_logical_slot_peek_changes('{self.slot_name}', null, 4096); drop index {self.id_name}; select * from pg_logical_slot_peek_changes\ ('{self.slot_name}', NULL, 4096); select * from \ pg_drop_replication_slot('{self.slot_name}');\ drop table if exists {self.tb_name}; | 1.893997 | 2 |
engine.py | tijsmaas/Graph-WaveNet | 0 | 6618863 | <reponame>tijsmaas/Graph-WaveNet<filename>engine.py
import torch.optim as optim
from model import *
import util
class Trainer():
def __init__(self, model, scaler, lrate, wdecay, clip=3, lr_decay_rate=.97):
self.model = model
self.optimizer = optim.Adam(self.model.parameters(), lr=lrate, weight_decay=wdecay)
self.scaler = scaler
self.clip = clip
self.scheduler = optim.lr_scheduler.LambdaLR(
self.optimizer, lr_lambda=lambda epoch: lr_decay_rate ** epoch)
@classmethod
def from_args(cls, model, scaler, args):
return cls(model, scaler, args.learning_rate, args.weight_decay, clip=args.clip,
lr_decay_rate=args.lr_decay_rate)
def train(self, input, real_val):
self.model.train()
self.optimizer.zero_grad()
input = nn.functional.pad(input,(1,0,0,0))
output = self.model(input).transpose(1,3) # now, output = [batch_size,1,num_nodes, seq_length]
predict = self.scaler.inverse_transform(output)
assert predict.shape[1] == 1
mae, mape, rmse = util.calc_metrics(predict.squeeze(1), real_val, null_val=0.0)
print ('MAPE', mape.item())
mae.backward()
if self.clip is not None:
torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.clip)
self.optimizer.step()
return mae.item(),mape.item(),rmse.item()
def eval(self, input, real_val):
self.model.eval()
input = nn.functional.pad(input,(1,0,0,0))
output = self.model(input).transpose(1,3) # [batch_size,seq_length,num_nodes,1]
real = torch.unsqueeze(real_val,dim=1)
predict = self.scaler.inverse_transform(output)
# predict = torch.clamp(predict, min=0., max=70.)
mae, mape, rmse = [x.item() for x in util.calc_metrics(predict, real, null_val=0.0)]
return mae, mape, rmse
| import torch.optim as optim
from model import *
import util
class Trainer():
def __init__(self, model, scaler, lrate, wdecay, clip=3, lr_decay_rate=.97):
self.model = model
self.optimizer = optim.Adam(self.model.parameters(), lr=lrate, weight_decay=wdecay)
self.scaler = scaler
self.clip = clip
self.scheduler = optim.lr_scheduler.LambdaLR(
self.optimizer, lr_lambda=lambda epoch: lr_decay_rate ** epoch)
@classmethod
def from_args(cls, model, scaler, args):
return cls(model, scaler, args.learning_rate, args.weight_decay, clip=args.clip,
lr_decay_rate=args.lr_decay_rate)
def train(self, input, real_val):
self.model.train()
self.optimizer.zero_grad()
input = nn.functional.pad(input,(1,0,0,0))
output = self.model(input).transpose(1,3) # now, output = [batch_size,1,num_nodes, seq_length]
predict = self.scaler.inverse_transform(output)
assert predict.shape[1] == 1
mae, mape, rmse = util.calc_metrics(predict.squeeze(1), real_val, null_val=0.0)
print ('MAPE', mape.item())
mae.backward()
if self.clip is not None:
torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.clip)
self.optimizer.step()
return mae.item(),mape.item(),rmse.item()
def eval(self, input, real_val):
self.model.eval()
input = nn.functional.pad(input,(1,0,0,0))
output = self.model(input).transpose(1,3) # [batch_size,seq_length,num_nodes,1]
real = torch.unsqueeze(real_val,dim=1)
predict = self.scaler.inverse_transform(output)
# predict = torch.clamp(predict, min=0., max=70.)
mae, mape, rmse = [x.item() for x in util.calc_metrics(predict, real, null_val=0.0)]
return mae, mape, rmse | en | 0.58133 | # now, output = [batch_size,1,num_nodes, seq_length] # [batch_size,seq_length,num_nodes,1] # predict = torch.clamp(predict, min=0., max=70.) | 2.487274 | 2 |
git_docs/ajax_tests.py | matteoferla/PyMOL-to-NGL-transpiler | 11 | 6618864 | import requests
from warnings import warn
class SiteTests:
def __init__(self):
self.url = 'http://0.0.0.0:8088/'
self.headers = {'user-agent': 'my-app/0.0.1'}
def test(self, address, data=None, headers=None, verbose=False):
if not headers:
headers = self.headers
if data:
r = requests.post(self.url + address, data=data, headers=headers)
else:
r = requests.post(self.url + address)
if 'Set-Cookie' in r.headers:
self.headers['Cookie'] = r.headers['Set-Cookie']
if verbose:
print(r.status_code)
print(r.headers)
print(r.content)
if r.status_code != 200:
warn('The site {url} returned a status code {code}. Content: {con}'.format(url=self.url, code = r.status_code, con = r.content))
return r
#register a user.exit
site = SiteTests()
data = {'username': 'crashtest dummy',
'password': '<PASSWORD>!',
'email': '<EMAIL>',
'action': 'register'} #login, logout, register (req. `email`), whoami (debug only), promote (req. `role`), kill, reset
print(site.test('login', data=data).content)
#reply "status" and occasionally username
data['action'] = 'whoami'
print(site.test('login', data=data).content)
############### create a page!
data = {'mode': 'file', #file|mode
'demo_file': 'A.pse', #alt. `file`
'stick': 'hyperball',
'viewport_id': 'viewport',
'uniform_non_carbon': False,
'image': False,
'pdb_string': True
}
r =site.test('convert_pse',data=data)
print(r.content)
| import requests
from warnings import warn
class SiteTests:
def __init__(self):
self.url = 'http://0.0.0.0:8088/'
self.headers = {'user-agent': 'my-app/0.0.1'}
def test(self, address, data=None, headers=None, verbose=False):
if not headers:
headers = self.headers
if data:
r = requests.post(self.url + address, data=data, headers=headers)
else:
r = requests.post(self.url + address)
if 'Set-Cookie' in r.headers:
self.headers['Cookie'] = r.headers['Set-Cookie']
if verbose:
print(r.status_code)
print(r.headers)
print(r.content)
if r.status_code != 200:
warn('The site {url} returned a status code {code}. Content: {con}'.format(url=self.url, code = r.status_code, con = r.content))
return r
#register a user.exit
site = SiteTests()
data = {'username': 'crashtest dummy',
'password': '<PASSWORD>!',
'email': '<EMAIL>',
'action': 'register'} #login, logout, register (req. `email`), whoami (debug only), promote (req. `role`), kill, reset
print(site.test('login', data=data).content)
#reply "status" and occasionally username
data['action'] = 'whoami'
print(site.test('login', data=data).content)
############### create a page!
data = {'mode': 'file', #file|mode
'demo_file': 'A.pse', #alt. `file`
'stick': 'hyperball',
'viewport_id': 'viewport',
'uniform_non_carbon': False,
'image': False,
'pdb_string': True
}
r =site.test('convert_pse',data=data)
print(r.content)
| en | 0.65577 | #register a user.exit #login, logout, register (req. `email`), whoami (debug only), promote (req. `role`), kill, reset #reply "status" and occasionally username ############### create a page! #file|mode #alt. `file` | 2.366089 | 2 |
lprs_test_app_a.py | ContinuumBridge/lprs_test_app | 0 | 6618865 | <reponame>ContinuumBridge/lprs_test_app
#!/usr/bin/env python
# lprs_test_app_a.py
"""
Copyright (c) 2015 ContinuumBridge Limited
"""
import sys
import time
import json
from cbcommslib import CbApp
from cbconfig import *
class App(CbApp):
def __init__(self, argv):
self.appClass = "control"
self.state = "stopped"
self.devices = []
self.idToName = {}
# Super-class init must be called
CbApp.__init__(self, argv)
def setState(self, action):
self.state = action
msg = {"id": self.id,
"status": "state",
"state": self.state}
self.sendManagerMessage(msg)
def reportRSSI(self, rssi):
msg = {"id": self.id,
"status": "user_message",
"body": "LPRS RSSI: " + str(rssi)
}
self.sendManagerMessage(msg)
def onAdaptorService(self, message):
#self.cbLog("debug", "onAdaptorService, message: " + str(message))
for p in message["service"]:
if p["characteristic"] == "rssi":
req = {"id": self.id,
"request": "service",
"service": [
{"characteristic": "rssi",
"interval": 0
}
]
}
self.sendMessage(req, message["id"])
self.setState("running")
def onAdaptorData(self, message):
#self.cbLog("debug", "onAdaptorData, message: " + str(message))
if message["characteristic"] == "rssi":
self.reportRSSI(message["data"])
def onConfigureMessage(self, managerConfig):
self.setState("starting")
if __name__ == '__main__':
App(sys.argv)
| #!/usr/bin/env python
# lprs_test_app_a.py
"""
Copyright (c) 2015 ContinuumBridge Limited
"""
import sys
import time
import json
from cbcommslib import CbApp
from cbconfig import *
class App(CbApp):
def __init__(self, argv):
self.appClass = "control"
self.state = "stopped"
self.devices = []
self.idToName = {}
# Super-class init must be called
CbApp.__init__(self, argv)
def setState(self, action):
self.state = action
msg = {"id": self.id,
"status": "state",
"state": self.state}
self.sendManagerMessage(msg)
def reportRSSI(self, rssi):
msg = {"id": self.id,
"status": "user_message",
"body": "LPRS RSSI: " + str(rssi)
}
self.sendManagerMessage(msg)
def onAdaptorService(self, message):
#self.cbLog("debug", "onAdaptorService, message: " + str(message))
for p in message["service"]:
if p["characteristic"] == "rssi":
req = {"id": self.id,
"request": "service",
"service": [
{"characteristic": "rssi",
"interval": 0
}
]
}
self.sendMessage(req, message["id"])
self.setState("running")
def onAdaptorData(self, message):
#self.cbLog("debug", "onAdaptorData, message: " + str(message))
if message["characteristic"] == "rssi":
self.reportRSSI(message["data"])
def onConfigureMessage(self, managerConfig):
self.setState("starting")
if __name__ == '__main__':
App(sys.argv) | en | 0.315537 | #!/usr/bin/env python # lprs_test_app_a.py Copyright (c) 2015 ContinuumBridge Limited # Super-class init must be called #self.cbLog("debug", "onAdaptorService, message: " + str(message)) #self.cbLog("debug", "onAdaptorData, message: " + str(message)) | 2.220184 | 2 |
lithopsext/core.py | aitorarjona/dd-lithops | 0 | 6618866 | import redis
import cloudpickle
import types
import logging
import queue
import itertools
import msgpack
from functools import reduce
from .utils import extract_redis_config
logger = logging.getLogger('lithops')
TASK_GROUP_GLOBAL = None
def get_group():
if TASK_GROUP_GLOBAL:
return TASK_GROUP_GLOBAL
else:
raise Exception('There is no group for this task!')
class _TaskGroup:
def __init__(self, worker_id, group_id, redis_client):
self._worker_id = worker_id
self._group_id = group_id
self._group_size = -1
self._redis = redis_client
self._redis_pubsub = redis_client.pubsub()
self._transaction_counter = itertools.count(0)
def sync(self, data, reducer=None, initial_value=None, gatherer=None):
sync_key = '_'.join([self._group_id, str(next(self._transaction_counter)).zfill(3), 'sync'])
logger.debug('[{}] Syncing {}'.format(self._worker_id, sync_key))
sync_result = None
if self._worker_id == 0:
if reducer:
accum = reducer(data, initial_value)
reduced = 1
while reduced < self._group_size:
_, raw_value = self._redis.blpop(sync_key)
logger.debug('[{}] Got reduce value'.format(self._worker_id))
value = cloudpickle.loads(raw_value)
# print('Value got is', value)
accum = reducer(value, accum)
reduced += 1
result_pickle = cloudpickle.dumps(accum)
self._redis.set(sync_key + '_result', result_pickle)
self._redis.publish(sync_key + '_topic', msgpack.packb({'result_key': sync_key + '_result'}))
logger.debug('[{}] Notify results of {}'.format(self._worker_id, sync_key))
sync_result = accum
elif gatherer:
pass
# logger.debug('[{}] Reducing partial results of {}'.format(self._worker_id, key))
# all_data_pickle = self._redis.lrange(key, 0, index)
# all_data = [cloudpickle.loads(data_pickle) for data_pickle in all_data_pickle]
# if operation == CollectiveOPs.SUM:
# result = reduce(lambda x, y: x + y, all_data)
# else:
# raise Exception('Unknown operation {}'.format(operation))
# result_pickle = cloudpickle.dumps(result)
# self._redis.set(key + '_result', result_pickle)
# self._redis.publish(key + '_topic', msgpack.packb({'result_key': key + '_result'}))
# logger.debug('[{}] Notify results of {}'.format(self._worker_id, key))
else:
pass
else:
data_pickle = cloudpickle.dumps(data)
self._redis.lpush(sync_key, data_pickle)
self._redis_pubsub.subscribe(sync_key + '_topic')
raw_msg = None
while not raw_msg:
raw_msg = self._redis_pubsub.get_message(ignore_subscribe_messages=True, timeout=5)
# print(raw_msg)
if 'type' not in raw_msg or raw_msg['type'] != 'message':
raise Exception(raw_msg)
msg = msgpack.unpackb(raw_msg['data'])
result_pickle = self._redis.get(msg['result_key'])
sync_result = cloudpickle.loads(result_pickle)
return sync_result
def _task_worker(id, data_partition, group_id):
logger.debug('[{}] Worker {} of group {} start'.format(id, id, group_id))
redis_conf = extract_redis_config()
red = redis.Redis(**redis_conf)
red_pubsub = red.pubsub()
q = queue.Queue()
task_group_proxy = _TaskGroup(worker_id=id, group_id=group_id, redis_client=red)
logger.debug('[{}] Getting data chunk {}'.format(id, data_partition.key))
data_chunk = data_partition.get()
func_cache = {}
logger.debug('[{}] Getting task log'.format(id))
tasks_packd = red.lrange(group_id + '_tasklog', 0, -1)
tasks = [msgpack.unpackb(task_packd) for task_packd in tasks_packd]
logger.debug('[{}] Restored {} tasks'.format(id, len(tasks)))
for task in tasks:
q.put(task)
def event_handler(raw_msg):
if 'type' not in raw_msg or raw_msg['type'] != 'message':
raise Exception(raw_msg)
msg = msgpack.unpackb(raw_msg['data'])
logger.debug('[{}] Received message! {}'.format(id, msg))
q.put(msg)
logger.debug('[{}] Subscribe to topic {}'.format(id, group_id))
red_pubsub.subscribe(**{group_id + '_chan': event_handler})
red_pubsub.run_in_thread(sleep_time=1)
worker_loop = True
while worker_loop:
try:
msg = q.get(timeout=20)
if msg['action'] == 'task':
task = types.SimpleNamespace(**msg)
if task.func_key in func_cache:
f = func_cache[task.func_key]
else:
func_pickle = red.hget(group_id, task.func_key)
f = cloudpickle.loads(func_pickle)
func_cache[task.func_key] = f
task_group_proxy._group_size = task.group_size
args_pickle = red.hget(group_id, task.args_key)
func_args = cloudpickle.loads(args_pickle)
func_args['kwargs']['compute_group'] = task_group_proxy
logger.debug('[{}] Going to execute task {}'.format(id, task.task_id))
result = f(data_chunk, *func_args['args'], **func_args['kwargs'])
result_pickle = cloudpickle.dumps(result)
pipe = red.pipeline()
pipe.incr(task.task_join_counter, 1).hset(task.task_id, id, result_pickle)
cnt, _ = pipe.execute()
if cnt == task.group_size:
red.lpush(task.task_join_bl, cnt)
else:
logger.debug('Message is {}, terminating worker'.format(msg))
worker_loop = False
except queue.Empty as e:
print('empty message')
worker_loop = False
logger.debug('[{}] Worker {} of group {} end'.format(id, id, group_id))
| import redis
import cloudpickle
import types
import logging
import queue
import itertools
import msgpack
from functools import reduce
from .utils import extract_redis_config
logger = logging.getLogger('lithops')
TASK_GROUP_GLOBAL = None
def get_group():
if TASK_GROUP_GLOBAL:
return TASK_GROUP_GLOBAL
else:
raise Exception('There is no group for this task!')
class _TaskGroup:
def __init__(self, worker_id, group_id, redis_client):
self._worker_id = worker_id
self._group_id = group_id
self._group_size = -1
self._redis = redis_client
self._redis_pubsub = redis_client.pubsub()
self._transaction_counter = itertools.count(0)
def sync(self, data, reducer=None, initial_value=None, gatherer=None):
sync_key = '_'.join([self._group_id, str(next(self._transaction_counter)).zfill(3), 'sync'])
logger.debug('[{}] Syncing {}'.format(self._worker_id, sync_key))
sync_result = None
if self._worker_id == 0:
if reducer:
accum = reducer(data, initial_value)
reduced = 1
while reduced < self._group_size:
_, raw_value = self._redis.blpop(sync_key)
logger.debug('[{}] Got reduce value'.format(self._worker_id))
value = cloudpickle.loads(raw_value)
# print('Value got is', value)
accum = reducer(value, accum)
reduced += 1
result_pickle = cloudpickle.dumps(accum)
self._redis.set(sync_key + '_result', result_pickle)
self._redis.publish(sync_key + '_topic', msgpack.packb({'result_key': sync_key + '_result'}))
logger.debug('[{}] Notify results of {}'.format(self._worker_id, sync_key))
sync_result = accum
elif gatherer:
pass
# logger.debug('[{}] Reducing partial results of {}'.format(self._worker_id, key))
# all_data_pickle = self._redis.lrange(key, 0, index)
# all_data = [cloudpickle.loads(data_pickle) for data_pickle in all_data_pickle]
# if operation == CollectiveOPs.SUM:
# result = reduce(lambda x, y: x + y, all_data)
# else:
# raise Exception('Unknown operation {}'.format(operation))
# result_pickle = cloudpickle.dumps(result)
# self._redis.set(key + '_result', result_pickle)
# self._redis.publish(key + '_topic', msgpack.packb({'result_key': key + '_result'}))
# logger.debug('[{}] Notify results of {}'.format(self._worker_id, key))
else:
pass
else:
data_pickle = cloudpickle.dumps(data)
self._redis.lpush(sync_key, data_pickle)
self._redis_pubsub.subscribe(sync_key + '_topic')
raw_msg = None
while not raw_msg:
raw_msg = self._redis_pubsub.get_message(ignore_subscribe_messages=True, timeout=5)
# print(raw_msg)
if 'type' not in raw_msg or raw_msg['type'] != 'message':
raise Exception(raw_msg)
msg = msgpack.unpackb(raw_msg['data'])
result_pickle = self._redis.get(msg['result_key'])
sync_result = cloudpickle.loads(result_pickle)
return sync_result
def _task_worker(id, data_partition, group_id):
logger.debug('[{}] Worker {} of group {} start'.format(id, id, group_id))
redis_conf = extract_redis_config()
red = redis.Redis(**redis_conf)
red_pubsub = red.pubsub()
q = queue.Queue()
task_group_proxy = _TaskGroup(worker_id=id, group_id=group_id, redis_client=red)
logger.debug('[{}] Getting data chunk {}'.format(id, data_partition.key))
data_chunk = data_partition.get()
func_cache = {}
logger.debug('[{}] Getting task log'.format(id))
tasks_packd = red.lrange(group_id + '_tasklog', 0, -1)
tasks = [msgpack.unpackb(task_packd) for task_packd in tasks_packd]
logger.debug('[{}] Restored {} tasks'.format(id, len(tasks)))
for task in tasks:
q.put(task)
def event_handler(raw_msg):
if 'type' not in raw_msg or raw_msg['type'] != 'message':
raise Exception(raw_msg)
msg = msgpack.unpackb(raw_msg['data'])
logger.debug('[{}] Received message! {}'.format(id, msg))
q.put(msg)
logger.debug('[{}] Subscribe to topic {}'.format(id, group_id))
red_pubsub.subscribe(**{group_id + '_chan': event_handler})
red_pubsub.run_in_thread(sleep_time=1)
worker_loop = True
while worker_loop:
try:
msg = q.get(timeout=20)
if msg['action'] == 'task':
task = types.SimpleNamespace(**msg)
if task.func_key in func_cache:
f = func_cache[task.func_key]
else:
func_pickle = red.hget(group_id, task.func_key)
f = cloudpickle.loads(func_pickle)
func_cache[task.func_key] = f
task_group_proxy._group_size = task.group_size
args_pickle = red.hget(group_id, task.args_key)
func_args = cloudpickle.loads(args_pickle)
func_args['kwargs']['compute_group'] = task_group_proxy
logger.debug('[{}] Going to execute task {}'.format(id, task.task_id))
result = f(data_chunk, *func_args['args'], **func_args['kwargs'])
result_pickle = cloudpickle.dumps(result)
pipe = red.pipeline()
pipe.incr(task.task_join_counter, 1).hset(task.task_id, id, result_pickle)
cnt, _ = pipe.execute()
if cnt == task.group_size:
red.lpush(task.task_join_bl, cnt)
else:
logger.debug('Message is {}, terminating worker'.format(msg))
worker_loop = False
except queue.Empty as e:
print('empty message')
worker_loop = False
logger.debug('[{}] Worker {} of group {} end'.format(id, id, group_id))
| en | 0.386963 | # print('Value got is', value) # logger.debug('[{}] Reducing partial results of {}'.format(self._worker_id, key)) # all_data_pickle = self._redis.lrange(key, 0, index) # all_data = [cloudpickle.loads(data_pickle) for data_pickle in all_data_pickle] # if operation == CollectiveOPs.SUM: # result = reduce(lambda x, y: x + y, all_data) # else: # raise Exception('Unknown operation {}'.format(operation)) # result_pickle = cloudpickle.dumps(result) # self._redis.set(key + '_result', result_pickle) # self._redis.publish(key + '_topic', msgpack.packb({'result_key': key + '_result'})) # logger.debug('[{}] Notify results of {}'.format(self._worker_id, key)) # print(raw_msg) | 2.160216 | 2 |
dockerfiles/eti/scripts/config.py | fabelx/play-with-docker | 0 | 6618867 | import re
from pathlib import Path
HEADERS = {
'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:89.0) Gecko/20100101 Firefox/89.0',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.5',
'Referer': 'https://gist.github.com/cqr-cryeye/4f0210d3752eb01b8e3e1ec3cc28ec4e/revisions',
'DNT': '1',
'Connection': 'keep-alive',
'Upgrade-Insecure-Requests': '1',
'Cache-Control': 'max-age=0',
'TE': 'Trailers',
}
GIST_URL = 'https://gist.github.com/'
BASE_URL = f'{GIST_URL}cqr-cryeye/4f0210d3752eb01b8e3e1ec3cc28ec4e/'
DOCKER_STACKS_PATH = Path('docker-stacks')
HASH_TABLE_PATH = Path('hash_table.json')
APP_PID_PATH = Path('app.pid')
pattern = re.compile(r'cqr-cryeye/4f0210d3752eb01b8e3e1ec3cc28ec4e/archive/(?P<hash>[\w]+).zip')
| import re
from pathlib import Path
HEADERS = {
'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:89.0) Gecko/20100101 Firefox/89.0',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.5',
'Referer': 'https://gist.github.com/cqr-cryeye/4f0210d3752eb01b8e3e1ec3cc28ec4e/revisions',
'DNT': '1',
'Connection': 'keep-alive',
'Upgrade-Insecure-Requests': '1',
'Cache-Control': 'max-age=0',
'TE': 'Trailers',
}
GIST_URL = 'https://gist.github.com/'
BASE_URL = f'{GIST_URL}cqr-cryeye/4f0210d3752eb01b8e3e1ec3cc28ec4e/'
DOCKER_STACKS_PATH = Path('docker-stacks')
HASH_TABLE_PATH = Path('hash_table.json')
APP_PID_PATH = Path('app.pid')
pattern = re.compile(r'cqr-cryeye/4f0210d3752eb01b8e3e1ec3cc28ec4e/archive/(?P<hash>[\w]+).zip')
| none | 1 | 1.937289 | 2 | |
Firmware/Robotv4_Firmware/Roboclaw/roboclaw_bareminimum.py | maxdodson/Scenery-Robot-v4 | 10 | 6618868 | from roboclaw import Roboclaw
#Windows comport name
rc = Roboclaw("COM3",115200)
#Linux comport name
#rc = Roboclaw("/dev/ttyACM0",115200)
rc.Open()
| from roboclaw import Roboclaw
#Windows comport name
rc = Roboclaw("COM3",115200)
#Linux comport name
#rc = Roboclaw("/dev/ttyACM0",115200)
rc.Open()
| en | 0.398126 | #Windows comport name #Linux comport name #rc = Roboclaw("/dev/ttyACM0",115200) | 1.813676 | 2 |
p002.py | janhenke/project-euler | 0 | 6618869 | #! /usr/bin/env python3
"""Solves problem 002 from the Project Euler website"""
from common.fibonacci import fibonacci_numbers_below
def solve():
"""Solve the problem and return the result"""
fibs = fibonacci_numbers_below(4000000)
result = 0
for x in fibs:
if x % 2 == 0:
result += x
return result
if __name__ == '__main__':
print(solve())
| #! /usr/bin/env python3
"""Solves problem 002 from the Project Euler website"""
from common.fibonacci import fibonacci_numbers_below
def solve():
"""Solve the problem and return the result"""
fibs = fibonacci_numbers_below(4000000)
result = 0
for x in fibs:
if x % 2 == 0:
result += x
return result
if __name__ == '__main__':
print(solve())
| en | 0.649272 | #! /usr/bin/env python3 Solves problem 002 from the Project Euler website Solve the problem and return the result | 3.598656 | 4 |
presetMaker.py | puffyboa/game-of-life | 1 | 6618870 | from tkinter import*
GRID = [10,10]
TILESIZE = 40
def tileMap(coords,tilesize,tag):
canvas.delete(tag)
for x in range(GRID[0]):
for y in range(GRID[1]):
if [x,y] in Coordinates:
canvas.create_rectangle(x * tilesize, y * tilesize, (x * tilesize) + tilesize,
(y * tilesize) + tilesize,fill='black', outline='', tags=tag)
else:
canvas.create_rectangle(x * tilesize, y * tilesize, (x * tilesize) + tilesize,
(y * tilesize) + tilesize, fill='', outline='light grey', tags=tag)
def click(event):
global Coordinates
if [int(event.x/TILESIZE),int(event.y/TILESIZE)] not in Coordinates:
Coordinates.append([int(event.x / TILESIZE), int(event.y / TILESIZE)])
tileMap(Coordinates, TILESIZE, 'tilemap')
canvas.update()
def delete(event):
for i in range(len(Coordinates)):
if Coordinates[i] == [int(event.x/TILESIZE), int(event.y/TILESIZE)]:
del Coordinates[i]
break
tileMap(Coordinates, TILESIZE, 'tilemap')
canvas.update()
def done(event):
global Coordinates
rows = []
for y in range(GRID[1]):
rows.append([])
for x in range(GRID[0]):
if [x,y] in Coordinates:
rows[-1].append(1)
else:
rows[-1].append(0)
rows = [str(r)+',' for r in rows]
print('['+'\n'.join(rows)[:-1]+']')
Coordinates = []
tk = Tk()
canvas = Canvas(tk,width=int(GRID[0]*TILESIZE),height=int(GRID[1]*TILESIZE))
canvas.pack()
tileMap(Coordinates, TILESIZE, 'tilemap')
canvas.bind('<B1-Motion>',click)
canvas.bind('<B3-Motion>',delete)
canvas.bind_all('<Return>',done)
mainloop() | from tkinter import*
GRID = [10,10]
TILESIZE = 40
def tileMap(coords,tilesize,tag):
canvas.delete(tag)
for x in range(GRID[0]):
for y in range(GRID[1]):
if [x,y] in Coordinates:
canvas.create_rectangle(x * tilesize, y * tilesize, (x * tilesize) + tilesize,
(y * tilesize) + tilesize,fill='black', outline='', tags=tag)
else:
canvas.create_rectangle(x * tilesize, y * tilesize, (x * tilesize) + tilesize,
(y * tilesize) + tilesize, fill='', outline='light grey', tags=tag)
def click(event):
global Coordinates
if [int(event.x/TILESIZE),int(event.y/TILESIZE)] not in Coordinates:
Coordinates.append([int(event.x / TILESIZE), int(event.y / TILESIZE)])
tileMap(Coordinates, TILESIZE, 'tilemap')
canvas.update()
def delete(event):
for i in range(len(Coordinates)):
if Coordinates[i] == [int(event.x/TILESIZE), int(event.y/TILESIZE)]:
del Coordinates[i]
break
tileMap(Coordinates, TILESIZE, 'tilemap')
canvas.update()
def done(event):
global Coordinates
rows = []
for y in range(GRID[1]):
rows.append([])
for x in range(GRID[0]):
if [x,y] in Coordinates:
rows[-1].append(1)
else:
rows[-1].append(0)
rows = [str(r)+',' for r in rows]
print('['+'\n'.join(rows)[:-1]+']')
Coordinates = []
tk = Tk()
canvas = Canvas(tk,width=int(GRID[0]*TILESIZE),height=int(GRID[1]*TILESIZE))
canvas.pack()
tileMap(Coordinates, TILESIZE, 'tilemap')
canvas.bind('<B1-Motion>',click)
canvas.bind('<B3-Motion>',delete)
canvas.bind_all('<Return>',done)
mainloop() | none | 1 | 3.400728 | 3 | |
unibit_api_v1/stockprice.py | liuzulin/python-unibit | 31 | 6618871 | from .unibit import UniBit as ub
class StockPrice(ub):
def getPricesRealTime(self, ticker, size=None, datatype='json'):
""" Get real time stock prices
Keyword Arguments:
ticker: Company ticker
datatype: Data type of response. Either 'json' or 'csv'
size: Integer (n) which will have the response return the latest n prices.
If unspecified, all real time results will be returned, going back 1 month.
"""
endpoints = ['realtimestock']
return self.make_request(endpoints=endpoints, ticker=ticker, data={'datatype': datatype, 'size': size})
def getPricesHistorical(self, ticker, range, interval, datatype='json'):
""" Get real time stock prices
Keyword Arguments:
ticker: Company ticker
date_range: Range to grab historical prices,
either 1m, 3m, 1y, 3y, 5y, 10y, or 20y
interval: A positive number (n). If passed, chart data will
return every nth element as defined by Interval
datatype: Data type of response. Either 'json' or 'csv'
"""
if range not in ['1m', '3m', '1y', '3y', '5y', '10y', '20y']:
raise ValueError('Unsupported range value')
if (not isinstance(interval, int) or interval <= 0):
raise ValueError('Interval must be a positive integer')
endpoints = ['historicalstockprice']
return self.make_request(endpoints=endpoints, ticker=ticker,
data={'range': range, 'interval': interval, 'datatype': datatype})
| from .unibit import UniBit as ub
class StockPrice(ub):
def getPricesRealTime(self, ticker, size=None, datatype='json'):
""" Get real time stock prices
Keyword Arguments:
ticker: Company ticker
datatype: Data type of response. Either 'json' or 'csv'
size: Integer (n) which will have the response return the latest n prices.
If unspecified, all real time results will be returned, going back 1 month.
"""
endpoints = ['realtimestock']
return self.make_request(endpoints=endpoints, ticker=ticker, data={'datatype': datatype, 'size': size})
def getPricesHistorical(self, ticker, range, interval, datatype='json'):
""" Get real time stock prices
Keyword Arguments:
ticker: Company ticker
date_range: Range to grab historical prices,
either 1m, 3m, 1y, 3y, 5y, 10y, or 20y
interval: A positive number (n). If passed, chart data will
return every nth element as defined by Interval
datatype: Data type of response. Either 'json' or 'csv'
"""
if range not in ['1m', '3m', '1y', '3y', '5y', '10y', '20y']:
raise ValueError('Unsupported range value')
if (not isinstance(interval, int) or interval <= 0):
raise ValueError('Interval must be a positive integer')
endpoints = ['historicalstockprice']
return self.make_request(endpoints=endpoints, ticker=ticker,
data={'range': range, 'interval': interval, 'datatype': datatype})
| en | 0.621717 | Get real time stock prices Keyword Arguments: ticker: Company ticker datatype: Data type of response. Either 'json' or 'csv' size: Integer (n) which will have the response return the latest n prices. If unspecified, all real time results will be returned, going back 1 month. Get real time stock prices Keyword Arguments: ticker: Company ticker date_range: Range to grab historical prices, either 1m, 3m, 1y, 3y, 5y, 10y, or 20y interval: A positive number (n). If passed, chart data will return every nth element as defined by Interval datatype: Data type of response. Either 'json' or 'csv' | 3.213149 | 3 |
vk_videos.py | MasterScott/vk_scripts | 0 | 6618872 | #!/usr/bin/python3
import requests
import json
from bs4 import BeautifulSoup
token = '<PASSWORD>'
owner_id = 415577518
v = 5.63
def write_json(data, filename):
with open(filename, 'w') as file:
json.dump(data, file, indent=2, ensure_ascii=False)
def download_file(url):
r = requests.get(url, stream=True)
filename = url.split('/')[-1]
with open(filename, 'bw') as file:
for chunk in r.iter_content(1024000):
file.write(chunk)
def parse_playlist():
return requests.get('https://api.vk.com/method/video.getAlbums?', params={'owner_id': owner_id, 'need_system': True,'count': 100, 'access_token': token, 'v': v})
def parse_videos(album_id):
return requests.get('https://api.vk.com/method/video.get?', params={'owner_id': owner_id, 'album_id': album_id, 'count': 1, 'access_token': token, 'v': v})
def get_url(url):
html = requests.get(url).text
soup = BeautifulSoup(html, 'lxml')
video_url = soup.find('div', id='page_wrap').find('source').get('src').split('?')[0]
download_file(video_url)
def main():
playlist = parse_playlist()
write_json(playlist.json()['response'], 'video_playlists.json')
videos = parse_videos(-2).json()['response']['items']
write_json(videos, 'videos.json')
for video in videos:
if 'vk.com' in video['player']:
url = video['player']
get_url(url)
if __name__ == '__main__':
main()
| #!/usr/bin/python3
import requests
import json
from bs4 import BeautifulSoup
token = '<PASSWORD>'
owner_id = 415577518
v = 5.63
def write_json(data, filename):
with open(filename, 'w') as file:
json.dump(data, file, indent=2, ensure_ascii=False)
def download_file(url):
r = requests.get(url, stream=True)
filename = url.split('/')[-1]
with open(filename, 'bw') as file:
for chunk in r.iter_content(1024000):
file.write(chunk)
def parse_playlist():
return requests.get('https://api.vk.com/method/video.getAlbums?', params={'owner_id': owner_id, 'need_system': True,'count': 100, 'access_token': token, 'v': v})
def parse_videos(album_id):
return requests.get('https://api.vk.com/method/video.get?', params={'owner_id': owner_id, 'album_id': album_id, 'count': 1, 'access_token': token, 'v': v})
def get_url(url):
html = requests.get(url).text
soup = BeautifulSoup(html, 'lxml')
video_url = soup.find('div', id='page_wrap').find('source').get('src').split('?')[0]
download_file(video_url)
def main():
playlist = parse_playlist()
write_json(playlist.json()['response'], 'video_playlists.json')
videos = parse_videos(-2).json()['response']['items']
write_json(videos, 'videos.json')
for video in videos:
if 'vk.com' in video['player']:
url = video['player']
get_url(url)
if __name__ == '__main__':
main()
| fr | 0.386793 | #!/usr/bin/python3 | 2.82637 | 3 |
authentik/stages/user_login/models.py | BeryJu/passbook | 15 | 6618873 | """login stage models"""
from django.db import models
from django.utils.translation import gettext_lazy as _
from django.views import View
from rest_framework.serializers import BaseSerializer
from authentik.flows.models import Stage
from authentik.lib.utils.time import timedelta_string_validator
class UserLoginStage(Stage):
"""Attaches the currently pending user to the current session."""
session_duration = models.TextField(
default="seconds=0",
validators=[timedelta_string_validator],
help_text=_(
"Determines how long a session lasts. Default of 0 means "
"that the sessions lasts until the browser is closed. "
"(Format: hours=-1;minutes=-2;seconds=-3)"
),
)
@property
def serializer(self) -> BaseSerializer:
from authentik.stages.user_login.api import UserLoginStageSerializer
return UserLoginStageSerializer
@property
def type(self) -> type[View]:
from authentik.stages.user_login.stage import UserLoginStageView
return UserLoginStageView
@property
def component(self) -> str:
return "ak-stage-user-login-form"
class Meta:
verbose_name = _("User Login Stage")
verbose_name_plural = _("User Login Stages")
| """login stage models"""
from django.db import models
from django.utils.translation import gettext_lazy as _
from django.views import View
from rest_framework.serializers import BaseSerializer
from authentik.flows.models import Stage
from authentik.lib.utils.time import timedelta_string_validator
class UserLoginStage(Stage):
"""Attaches the currently pending user to the current session."""
session_duration = models.TextField(
default="seconds=0",
validators=[timedelta_string_validator],
help_text=_(
"Determines how long a session lasts. Default of 0 means "
"that the sessions lasts until the browser is closed. "
"(Format: hours=-1;minutes=-2;seconds=-3)"
),
)
@property
def serializer(self) -> BaseSerializer:
from authentik.stages.user_login.api import UserLoginStageSerializer
return UserLoginStageSerializer
@property
def type(self) -> type[View]:
from authentik.stages.user_login.stage import UserLoginStageView
return UserLoginStageView
@property
def component(self) -> str:
return "ak-stage-user-login-form"
class Meta:
verbose_name = _("User Login Stage")
verbose_name_plural = _("User Login Stages")
| en | 0.922981 | login stage models Attaches the currently pending user to the current session. | 2.274812 | 2 |
tests/test_changelib.py | nilamo/pursuedpybear | 211 | 6618874 | <filename>tests/test_changelib.py<gh_stars>100-1000
import pytest
import ppb.changelib
def test_renamed_function():
arg = None
def func(p):
"""
a docstring
"""
nonlocal arg
arg = p
oldfunc = ppb.changelib.renamed('oldfunc', func, version='1.0')
with pytest.deprecated_call():
oldfunc("hello")
assert oldfunc.__name__ == 'oldfunc'
assert 'deprecated' in oldfunc.__doc__
assert 'func' in oldfunc.__doc__
assert arg == "hello"
def test_renamed_function_nodoc():
def func(p): pass
oldfunc = ppb.changelib.renamed('oldfunc', func, version='1.0')
assert oldfunc.__name__ == 'oldfunc'
assert 'deprecated' in oldfunc.__doc__
assert 'func' in oldfunc.__doc__
def test_renamed_class():
class Foo:
"""
a class
"""
oldfoo = ppb.changelib.renamed('oldfoo', Foo, version='1.0')
with pytest.deprecated_call():
inst = oldfoo()
assert oldfoo.__name__ == 'oldfoo'
assert 'deprecated' in oldfoo.__doc__
assert 'Foo' in oldfoo.__doc__
assert isinstance(inst, Foo)
| <filename>tests/test_changelib.py<gh_stars>100-1000
import pytest
import ppb.changelib
def test_renamed_function():
arg = None
def func(p):
"""
a docstring
"""
nonlocal arg
arg = p
oldfunc = ppb.changelib.renamed('oldfunc', func, version='1.0')
with pytest.deprecated_call():
oldfunc("hello")
assert oldfunc.__name__ == 'oldfunc'
assert 'deprecated' in oldfunc.__doc__
assert 'func' in oldfunc.__doc__
assert arg == "hello"
def test_renamed_function_nodoc():
def func(p): pass
oldfunc = ppb.changelib.renamed('oldfunc', func, version='1.0')
assert oldfunc.__name__ == 'oldfunc'
assert 'deprecated' in oldfunc.__doc__
assert 'func' in oldfunc.__doc__
def test_renamed_class():
class Foo:
"""
a class
"""
oldfoo = ppb.changelib.renamed('oldfoo', Foo, version='1.0')
with pytest.deprecated_call():
inst = oldfoo()
assert oldfoo.__name__ == 'oldfoo'
assert 'deprecated' in oldfoo.__doc__
assert 'Foo' in oldfoo.__doc__
assert isinstance(inst, Foo)
| en | 0.469872 | a docstring a class | 2.074928 | 2 |
scripts/vectorize.py | mogproject/tutte-polyn | 0 | 6618875 | <gh_stars>0
#!/usr/bin/env python3
"""
Converts output from the tuttepoly program into coefficient vectors for each graph.
"""
__author__ = '<NAME>'
__version__ = '0.0.1'
__license__ = 'Apache License, Version 2.0'
# imports standard libraries
import sys
import argparse
def get_parser():
"""Argument parser."""
parser = argparse.ArgumentParser(description='<program description>')
parser.add_argument('-n', type=int, required=True, help='number of vertices')
parser.add_argument('path', help='input file path')
return parser
def parse_tp_line(line):
assert(line[:3] == 'TP[')
tokens = line.split(':=')
gid = int(tokens[0][3:-2])
terms = tokens[1].rstrip(':\n').split('+')
elems = [term.strip().split('*') for term in terms]
ret = []
for elem in elems:
dx, dy = 0, 0
for e in elem[1:]:
if e[0] == 'x':
dx = int(e[2:]) if e[1:2] == '^' else 1
elif e[0] == 'y':
dy = int(e[2:]) if e[1:2] == '^' else 1
ret += [(int(elem[0]), dx, dy)]
return gid, ret
def parse_graph_line(line):
assert(line[:2] == 'G[')
tokens = line.split(':=')
gid = int(tokens[0][2:-2])
edges = tokens[1].strip().rstrip('\}').lstrip('\{').split(',')
ret = []
for edge in edges:
vs = edge.split('--')
ret += [(int(vs[0]), int(vs[1]))]
return gid, ret
def main(args):
"""Entry point of the program. """
nx = args.n # max degree of x: n - 1
ny = 1 + (args.n - 1) * (args.n - 2) // 2 # max degree of y: n - 1 choose 2
with open(args.path) as f:
for line in f:
if line[0] == 'T':
parsed = parse_tp_line(line)
vec = [0 for i in range(nx * ny)]
for c, dx, dy in parsed[1]:
assert(dx < nx)
assert(dy < ny)
vec[dy * nx + dx] = c
print('%d: %s' % (parsed[0], ' '.join(map(str, vec))))
if __name__ == '__main__':
main(get_parser().parse_args())
| #!/usr/bin/env python3
"""
Converts output from the tuttepoly program into coefficient vectors for each graph.
"""
__author__ = '<NAME>'
__version__ = '0.0.1'
__license__ = 'Apache License, Version 2.0'
# imports standard libraries
import sys
import argparse
def get_parser():
"""Argument parser."""
parser = argparse.ArgumentParser(description='<program description>')
parser.add_argument('-n', type=int, required=True, help='number of vertices')
parser.add_argument('path', help='input file path')
return parser
def parse_tp_line(line):
assert(line[:3] == 'TP[')
tokens = line.split(':=')
gid = int(tokens[0][3:-2])
terms = tokens[1].rstrip(':\n').split('+')
elems = [term.strip().split('*') for term in terms]
ret = []
for elem in elems:
dx, dy = 0, 0
for e in elem[1:]:
if e[0] == 'x':
dx = int(e[2:]) if e[1:2] == '^' else 1
elif e[0] == 'y':
dy = int(e[2:]) if e[1:2] == '^' else 1
ret += [(int(elem[0]), dx, dy)]
return gid, ret
def parse_graph_line(line):
assert(line[:2] == 'G[')
tokens = line.split(':=')
gid = int(tokens[0][2:-2])
edges = tokens[1].strip().rstrip('\}').lstrip('\{').split(',')
ret = []
for edge in edges:
vs = edge.split('--')
ret += [(int(vs[0]), int(vs[1]))]
return gid, ret
def main(args):
"""Entry point of the program. """
nx = args.n # max degree of x: n - 1
ny = 1 + (args.n - 1) * (args.n - 2) // 2 # max degree of y: n - 1 choose 2
with open(args.path) as f:
for line in f:
if line[0] == 'T':
parsed = parse_tp_line(line)
vec = [0 for i in range(nx * ny)]
for c, dx, dy in parsed[1]:
assert(dx < nx)
assert(dy < ny)
vec[dy * nx + dx] = c
print('%d: %s' % (parsed[0], ' '.join(map(str, vec))))
if __name__ == '__main__':
main(get_parser().parse_args()) | en | 0.673728 | #!/usr/bin/env python3 Converts output from the tuttepoly program into coefficient vectors for each graph. # imports standard libraries Argument parser. Entry point of the program. # max degree of x: n - 1 # max degree of y: n - 1 choose 2 | 2.995815 | 3 |
pyramid_oereb/contrib/__init__.py | arnaud-morvan/pyramid_oereb | 2 | 6618876 | <reponame>arnaud-morvan/pyramid_oereb<gh_stars>1-10
# -*- coding: utf-8 -*-
import logging
log = logging.getLogger(__name__)
def eliminate_duplicated_document_records(main_document_records, plr_document_records):
""" Filtering of document records that are associated to a plr.
Document records associated to a plr are eliminated if a record associated to a theme exists
for the same document. Document records associated to a theme have priority.
Records are considered to handle the same document if:
- indices are equal, and
- document_type codes are equal, and
- official_numbers correspond
Correct data is expected.
"""
# basic rules (one or the other source does not provide any document records)
if main_document_records is None and len(plr_document_records) > 0:
return plr_document_records
if main_document_records is not None and len(plr_document_records) == 0:
return main_document_records
# list which indicates duplicated documents
plr_document_is_duplicated_list = [False] * len(plr_document_records)
# document per document comparison
for doc1 in main_document_records:
for index2, doc2 in enumerate(plr_document_records):
if plr_document_is_duplicated_list[index2] is False:
# comparison of indices
if doc1.index != doc2.index:
continue
# comparison of document_type
if doc1.document_type.code != doc2.document_type.code:
continue
# comparison of number
# - Note: official number is NOT mandatory
# - possibility of not corresponding languages
docs_have_same_number = False
if doc1.official_number is not None and doc2.official_number is not None:
for key, value in doc1.official_number.items():
if doc2.official_number.get(key):
if doc2.official_number.get(key) == value:
docs_have_same_number = True
break
if docs_have_same_number:
plr_document_is_duplicated_list[index2] = True
unique_document_indexes = [i for i, val in enumerate(plr_document_is_duplicated_list) if val is False]
unique_document_records = [plr_document_records[i] for i in unique_document_indexes]
# logging message if document record was removed
if len(unique_document_records) != len(plr_document_records):
dupl_doc_indexes = [i for i, val in enumerate(plr_document_is_duplicated_list) if val is True]
for i in dupl_doc_indexes:
log.info(
'''PLR document record removed from extract as it is already provided by the main doc records
(title: {title}, number: {number}, index: {index})'''.format(
title=plr_document_records[i].title,
number=plr_document_records[i].official_number,
index=plr_document_records[i].index
)
)
return main_document_records + unique_document_records
| # -*- coding: utf-8 -*-
import logging
log = logging.getLogger(__name__)
def eliminate_duplicated_document_records(main_document_records, plr_document_records):
""" Filtering of document records that are associated to a plr.
Document records associated to a plr are eliminated if a record associated to a theme exists
for the same document. Document records associated to a theme have priority.
Records are considered to handle the same document if:
- indices are equal, and
- document_type codes are equal, and
- official_numbers correspond
Correct data is expected.
"""
# basic rules (one or the other source does not provide any document records)
if main_document_records is None and len(plr_document_records) > 0:
return plr_document_records
if main_document_records is not None and len(plr_document_records) == 0:
return main_document_records
# list which indicates duplicated documents
plr_document_is_duplicated_list = [False] * len(plr_document_records)
# document per document comparison
for doc1 in main_document_records:
for index2, doc2 in enumerate(plr_document_records):
if plr_document_is_duplicated_list[index2] is False:
# comparison of indices
if doc1.index != doc2.index:
continue
# comparison of document_type
if doc1.document_type.code != doc2.document_type.code:
continue
# comparison of number
# - Note: official number is NOT mandatory
# - possibility of not corresponding languages
docs_have_same_number = False
if doc1.official_number is not None and doc2.official_number is not None:
for key, value in doc1.official_number.items():
if doc2.official_number.get(key):
if doc2.official_number.get(key) == value:
docs_have_same_number = True
break
if docs_have_same_number:
plr_document_is_duplicated_list[index2] = True
unique_document_indexes = [i for i, val in enumerate(plr_document_is_duplicated_list) if val is False]
unique_document_records = [plr_document_records[i] for i in unique_document_indexes]
# logging message if document record was removed
if len(unique_document_records) != len(plr_document_records):
dupl_doc_indexes = [i for i, val in enumerate(plr_document_is_duplicated_list) if val is True]
for i in dupl_doc_indexes:
log.info(
'''PLR document record removed from extract as it is already provided by the main doc records
(title: {title}, number: {number}, index: {index})'''.format(
title=plr_document_records[i].title,
number=plr_document_records[i].official_number,
index=plr_document_records[i].index
)
)
return main_document_records + unique_document_records | en | 0.874891 | # -*- coding: utf-8 -*- Filtering of document records that are associated to a plr. Document records associated to a plr are eliminated if a record associated to a theme exists for the same document. Document records associated to a theme have priority. Records are considered to handle the same document if: - indices are equal, and - document_type codes are equal, and - official_numbers correspond Correct data is expected. # basic rules (one or the other source does not provide any document records) # list which indicates duplicated documents # document per document comparison # comparison of indices # comparison of document_type # comparison of number # - Note: official number is NOT mandatory # - possibility of not corresponding languages # logging message if document record was removed PLR document record removed from extract as it is already provided by the main doc records (title: {title}, number: {number}, index: {index}) | 3.103202 | 3 |
fourth-year/AI/main_assignment/processing.py | JulianGR/university | 0 | 6618877 | if __name__ == '__main__':
file = open('f2_l-d_kp_20_878.txt', 'r')
linesfile = file.readlines()
resulttoken0 = []
resulttoken1 = []
for x in linesfile:
resulttoken0.append(int(x.split()[0]))
resulttoken1.append(int(x.split()[1]))
file.close()
print('column 0 ( values ): ' + str(resulttoken0))
print('column 1 ( weights ): ' + str(resulttoken1))
| if __name__ == '__main__':
file = open('f2_l-d_kp_20_878.txt', 'r')
linesfile = file.readlines()
resulttoken0 = []
resulttoken1 = []
for x in linesfile:
resulttoken0.append(int(x.split()[0]))
resulttoken1.append(int(x.split()[1]))
file.close()
print('column 0 ( values ): ' + str(resulttoken0))
print('column 1 ( weights ): ' + str(resulttoken1))
| none | 1 | 2.602429 | 3 | |
src/ctgView.py | keebah/carreraTrackGenerator | 0 | 6618878 | # -*- coding: utf-8 -*-
"""
GUI for the carrera Track Generator
"""
from .ctgModel import ctgModel
from .ctgCtrl import ctgCtrl
from PyQt5.QtWidgets import (QMainWindow, QFileDialog)
import json
import matplotlib
matplotlib.use('Qt5Agg')
from .gui.TrackPlotter import TrackPlotter
from .gui.MenuBar import MenuBar
from .gui.MainGUI import MainGUI
class ctgView(QMainWindow):
def __init__(self):
super().__init__()
self.ctgCtrl = ctgCtrl()
self.ctgModel = self.ctgCtrl.ctgModel
self.ctgModel.tracks[0]["coords"] = self.ctgModel.drawTrack(self.ctgModel.tracks[0]["layout"])
l,r,c = self.ctgModel.calculateLength(self.ctgModel.tracks[0])
self.ctgModel.tracks[0]["length"] = {'left': l, 'right': r, 'center': c}
self.ctgModel.tracks[1]["coords"] = self.ctgModel.drawTrack(self.ctgModel.tracks[1]["layout"])
l,r,c = self.ctgModel.calculateLength(self.ctgModel.tracks[1])
self.ctgModel.tracks[1]["length"] = {'left': l, 'right': r, 'center': c}
self.ctgModel.tracks[2]["coords"] = self.ctgModel.drawTrack(self.ctgModel.tracks[2]["layout"])
l,r,c = self.ctgModel.calculateLength(self.ctgModel.tracks[2])
self.ctgModel.tracks[2]["length"] = {'left': l, 'right': r, 'center': c}
print(self.ctgModel.checkValid(self.ctgModel.tracks[0], True))
print(self.ctgModel.checkValid(self.ctgModel.tracks[1], True))
print(self.ctgModel.checkValid(self.ctgModel.tracks[2], True))
self.gui = {}
self.currentTrack = {"name": "", "length": {"left", "right", "center"}}
self.initUI()
return
def initUI(self):
QMainWindow.__init__(self)
self.setGeometry(300, 400, 1024, 768)
self.setWindowTitle('Carrera Track Generator')
# register windows
self.windows = {"trackplt": TrackPlotter(self)}
# menubar
MenuBar(self)
# main window ocntent
self.setCentralWidget(MainGUI(self))
self.show()
return
def trackListClicked(self):
idx = self.gui["trackList"].currentIndex().row()
self.currentTrack = self.ctgModel.tracks[idx]
self.gui["trackProps"].updateLabels()
return
def toggleWindow(self, window):
if window.isVisible():
window.hide()
else:
window.show()
return
def findTrack(self):
self.ctgCtrl.findTrack()
self.gui["trackList"].insertItem(len(self.ctgModel.tracks),
self.ctgModel.tracks[len(self.ctgModel.tracks)-1]["name"])
def designTrack(self, option):
self.currentTrack = self.ctgCtrl.designTrack(self.currentTrack, option)
self.windows["trackplt"].clearMap()
self.windows["trackplt"].plotMap()
self.gui["trackProps"].updateLabels()
def exportTrack(self):
name = QFileDialog.getSaveFileName(self, 'Save File')
with open(name[0], 'w') as outfile:
json.dump(self.currentTrack, outfile)
return | # -*- coding: utf-8 -*-
"""
GUI for the carrera Track Generator
"""
from .ctgModel import ctgModel
from .ctgCtrl import ctgCtrl
from PyQt5.QtWidgets import (QMainWindow, QFileDialog)
import json
import matplotlib
matplotlib.use('Qt5Agg')
from .gui.TrackPlotter import TrackPlotter
from .gui.MenuBar import MenuBar
from .gui.MainGUI import MainGUI
class ctgView(QMainWindow):
def __init__(self):
super().__init__()
self.ctgCtrl = ctgCtrl()
self.ctgModel = self.ctgCtrl.ctgModel
self.ctgModel.tracks[0]["coords"] = self.ctgModel.drawTrack(self.ctgModel.tracks[0]["layout"])
l,r,c = self.ctgModel.calculateLength(self.ctgModel.tracks[0])
self.ctgModel.tracks[0]["length"] = {'left': l, 'right': r, 'center': c}
self.ctgModel.tracks[1]["coords"] = self.ctgModel.drawTrack(self.ctgModel.tracks[1]["layout"])
l,r,c = self.ctgModel.calculateLength(self.ctgModel.tracks[1])
self.ctgModel.tracks[1]["length"] = {'left': l, 'right': r, 'center': c}
self.ctgModel.tracks[2]["coords"] = self.ctgModel.drawTrack(self.ctgModel.tracks[2]["layout"])
l,r,c = self.ctgModel.calculateLength(self.ctgModel.tracks[2])
self.ctgModel.tracks[2]["length"] = {'left': l, 'right': r, 'center': c}
print(self.ctgModel.checkValid(self.ctgModel.tracks[0], True))
print(self.ctgModel.checkValid(self.ctgModel.tracks[1], True))
print(self.ctgModel.checkValid(self.ctgModel.tracks[2], True))
self.gui = {}
self.currentTrack = {"name": "", "length": {"left", "right", "center"}}
self.initUI()
return
def initUI(self):
QMainWindow.__init__(self)
self.setGeometry(300, 400, 1024, 768)
self.setWindowTitle('Carrera Track Generator')
# register windows
self.windows = {"trackplt": TrackPlotter(self)}
# menubar
MenuBar(self)
# main window ocntent
self.setCentralWidget(MainGUI(self))
self.show()
return
def trackListClicked(self):
idx = self.gui["trackList"].currentIndex().row()
self.currentTrack = self.ctgModel.tracks[idx]
self.gui["trackProps"].updateLabels()
return
def toggleWindow(self, window):
if window.isVisible():
window.hide()
else:
window.show()
return
def findTrack(self):
self.ctgCtrl.findTrack()
self.gui["trackList"].insertItem(len(self.ctgModel.tracks),
self.ctgModel.tracks[len(self.ctgModel.tracks)-1]["name"])
def designTrack(self, option):
self.currentTrack = self.ctgCtrl.designTrack(self.currentTrack, option)
self.windows["trackplt"].clearMap()
self.windows["trackplt"].plotMap()
self.gui["trackProps"].updateLabels()
def exportTrack(self):
name = QFileDialog.getSaveFileName(self, 'Save File')
with open(name[0], 'w') as outfile:
json.dump(self.currentTrack, outfile)
return | en | 0.499758 | # -*- coding: utf-8 -*- GUI for the carrera Track Generator # register windows # menubar # main window ocntent | 2.432614 | 2 |
backendModels/apps.py | MellaLee/hello-vue-django | 0 | 6618879 | <gh_stars>0
from django.apps import AppConfig
class BackendmodelsConfig(AppConfig):
name = 'backendModels'
| from django.apps import AppConfig
class BackendmodelsConfig(AppConfig):
name = 'backendModels' | none | 1 | 1.159264 | 1 | |
sinal/urls.py | vaniala/tradutortcc | 0 | 6618880 | <reponame>vaniala/tradutortcc<filename>sinal/urls.py
from django.conf.urls import url
from sinal.views import index, exibir, RegistrarSinalView, lista_sinais, editar
urlpatterns = [
url(r'^$', index, name='index'),
url(r'^sinais/(?P<sinal_id>\d+)$', exibir, name='exibir'),
url(r'^registrar/$', RegistrarSinalView.as_view(), name='registrar'),
url(r'^editar/(?P<sinal_id>\d+)$', editar, name='editar'),
# url(r'^delete/(?P<sinal_id>\d+)$', DeletarSinal.as_view(), name='server_delete'),
url(r'^sinais/$', lista_sinais, name='lista_sinais')
] | from django.conf.urls import url
from sinal.views import index, exibir, RegistrarSinalView, lista_sinais, editar
urlpatterns = [
url(r'^$', index, name='index'),
url(r'^sinais/(?P<sinal_id>\d+)$', exibir, name='exibir'),
url(r'^registrar/$', RegistrarSinalView.as_view(), name='registrar'),
url(r'^editar/(?P<sinal_id>\d+)$', editar, name='editar'),
# url(r'^delete/(?P<sinal_id>\d+)$', DeletarSinal.as_view(), name='server_delete'),
url(r'^sinais/$', lista_sinais, name='lista_sinais')
] | en | 0.719538 | # url(r'^delete/(?P<sinal_id>\d+)$', DeletarSinal.as_view(), name='server_delete'), | 1.728891 | 2 |
src/evaluate_ner.py | salesforce/MoFE | 7 | 6618881 | <gh_stars>1-10
"""
Copyright (c) 2021, salesforce.com, inc.
All rights reserved.
SPDX-License-Identifier: BSD-3-Clause
For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
"""
import spacy
import nltk
import argparse
def process_file(fname):
return [elem.strip() for elem in open(fname, 'r')]
def parse_args():
parser = argparse.ArgumentParser(description="NER Precision/ Recall Evaluation")
parser.add_argument("--source_doc", default="data/xsum/train.source", help="Source Articles")
parser.add_argument("--target_summary", default="data/xsum/train.target", help="Target Summaries")
parser.add_argument("--predict_summary", default="data/xsum/train.target", help="Predicted Summaries")
args = parser.parse_args()
return args
if __name__ == '__main__':
nlp = spacy.load("en_core_web_lg")
nltk.download('stopwords')
sws = set(nltk.corpus.stopwords.words('english'))
args = parse_args()
text_target = process_file(args.target_summary)
text_source = process_file(args.source_doc)
text_predict = process_file(args.predict_summary)
assert len(text_target) == len(text_predict) == len(text_source)
print("Total Samples: {0} and {1} and {2}".format(len(text_target), len(text_predict), len(text_source)))
docs_target = nlp.pipe(text_target,
disable=["tok2vec", "tagger", "parser", "attribute_ruler", "lemmatizer"])
docs_source = nlp.pipe(text_source,
disable=["tok2vec", "tagger", "parser", "attribute_ruler", "lemmatizer"])
docs_predict = nlp.pipe(text_predict,
disable=["tok2vec", "tagger", "parser", "attribute_ruler", "lemmatizer"])
tot_prd_micro, tp_prd_src_micro, tp_prd_tgt_micro, tot_tgt_micro = 0., 0., 0., 0.
tgt_macro_p, tgt_macro_r, tgt_macro_f, src_macro_p = 0., 0., 0., 0.
for tgt, src, prd in zip(docs_target, docs_source, docs_predict):
target_entity = set([x.text.lower() for x in tgt if x.ent_type_ != '' and x.text.lower() not in sws])
source_entity = set([x.text.lower() for x in src if x.ent_type_ != '' and x.text.lower() not in sws])
predict_entity = set([x.text.lower() for x in prd if x.ent_type_ != '' and x.text.lower() not in sws])
src_overlap = len(source_entity.intersection(predict_entity))
tgt_overlap = len(target_entity.intersection(predict_entity))
tot_prd_micro += len(predict_entity)
tot_tgt_micro += len(target_entity)
tp_prd_tgt_micro += tgt_overlap
tp_prd_src_micro += src_overlap
macro_p = tgt_overlap/(0.0001+len(predict_entity))
macro_r = tgt_overlap/(0.0001+len(target_entity))
tgt_macro_f += 2*macro_p*macro_r/(0.0001+(macro_r+macro_p))
tgt_macro_p += macro_p
tgt_macro_r += macro_r
src_macro_p += src_overlap/(0.0001+len(predict_entity))
micro_tgt_rec = tp_prd_tgt_micro/tot_tgt_micro
micro_tgt_prec = tp_prd_tgt_micro/tot_prd_micro
micro_src_prec = tp_prd_src_micro/tot_prd_micro
print(f'Micro: Target P {micro_tgt_prec}, R {micro_tgt_rec}, '
f'F1 {2*micro_tgt_prec*micro_tgt_rec/(micro_tgt_prec+micro_tgt_rec)}; '
f'Source P {micro_src_prec} | Macro: Target P {tgt_macro_p/len(text_target)}, '
f'R {tgt_macro_r/len(text_target)}, F1 {tgt_macro_f/len(text_target)}; '
f'Source P {src_macro_p/len(text_target)}, #OVERLAPPING ENTITY WITH SOURCE {tp_prd_src_micro}') | """
Copyright (c) 2021, salesforce.com, inc.
All rights reserved.
SPDX-License-Identifier: BSD-3-Clause
For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
"""
import spacy
import nltk
import argparse
def process_file(fname):
return [elem.strip() for elem in open(fname, 'r')]
def parse_args():
parser = argparse.ArgumentParser(description="NER Precision/ Recall Evaluation")
parser.add_argument("--source_doc", default="data/xsum/train.source", help="Source Articles")
parser.add_argument("--target_summary", default="data/xsum/train.target", help="Target Summaries")
parser.add_argument("--predict_summary", default="data/xsum/train.target", help="Predicted Summaries")
args = parser.parse_args()
return args
if __name__ == '__main__':
nlp = spacy.load("en_core_web_lg")
nltk.download('stopwords')
sws = set(nltk.corpus.stopwords.words('english'))
args = parse_args()
text_target = process_file(args.target_summary)
text_source = process_file(args.source_doc)
text_predict = process_file(args.predict_summary)
assert len(text_target) == len(text_predict) == len(text_source)
print("Total Samples: {0} and {1} and {2}".format(len(text_target), len(text_predict), len(text_source)))
docs_target = nlp.pipe(text_target,
disable=["tok2vec", "tagger", "parser", "attribute_ruler", "lemmatizer"])
docs_source = nlp.pipe(text_source,
disable=["tok2vec", "tagger", "parser", "attribute_ruler", "lemmatizer"])
docs_predict = nlp.pipe(text_predict,
disable=["tok2vec", "tagger", "parser", "attribute_ruler", "lemmatizer"])
tot_prd_micro, tp_prd_src_micro, tp_prd_tgt_micro, tot_tgt_micro = 0., 0., 0., 0.
tgt_macro_p, tgt_macro_r, tgt_macro_f, src_macro_p = 0., 0., 0., 0.
for tgt, src, prd in zip(docs_target, docs_source, docs_predict):
target_entity = set([x.text.lower() for x in tgt if x.ent_type_ != '' and x.text.lower() not in sws])
source_entity = set([x.text.lower() for x in src if x.ent_type_ != '' and x.text.lower() not in sws])
predict_entity = set([x.text.lower() for x in prd if x.ent_type_ != '' and x.text.lower() not in sws])
src_overlap = len(source_entity.intersection(predict_entity))
tgt_overlap = len(target_entity.intersection(predict_entity))
tot_prd_micro += len(predict_entity)
tot_tgt_micro += len(target_entity)
tp_prd_tgt_micro += tgt_overlap
tp_prd_src_micro += src_overlap
macro_p = tgt_overlap/(0.0001+len(predict_entity))
macro_r = tgt_overlap/(0.0001+len(target_entity))
tgt_macro_f += 2*macro_p*macro_r/(0.0001+(macro_r+macro_p))
tgt_macro_p += macro_p
tgt_macro_r += macro_r
src_macro_p += src_overlap/(0.0001+len(predict_entity))
micro_tgt_rec = tp_prd_tgt_micro/tot_tgt_micro
micro_tgt_prec = tp_prd_tgt_micro/tot_prd_micro
micro_src_prec = tp_prd_src_micro/tot_prd_micro
print(f'Micro: Target P {micro_tgt_prec}, R {micro_tgt_rec}, '
f'F1 {2*micro_tgt_prec*micro_tgt_rec/(micro_tgt_prec+micro_tgt_rec)}; '
f'Source P {micro_src_prec} | Macro: Target P {tgt_macro_p/len(text_target)}, '
f'R {tgt_macro_r/len(text_target)}, F1 {tgt_macro_f/len(text_target)}; '
f'Source P {src_macro_p/len(text_target)}, #OVERLAPPING ENTITY WITH SOURCE {tp_prd_src_micro}') | en | 0.61995 | Copyright (c) 2021, salesforce.com, inc. All rights reserved. SPDX-License-Identifier: BSD-3-Clause For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause #OVERLAPPING ENTITY WITH SOURCE {tp_prd_src_micro}') | 2.391341 | 2 |
parc/pracCode_24060/Baek_4881proto.py | KwanHoo/Data-Structure__Algorithm | 0 | 6618882 | <filename>parc/pracCode_24060/Baek_4881proto.py
# 백준
# 4881번 : 자리수의 제곱
import sys
##* 89, 1
##* 0< a,b < 10^9
# 1.숫자 제곱 합 함수
def square_fun(number):
str_num = list(number) # map -> list
# print(str_num[0][0]) # 첫째 자리
# print(str_num[0]) # 넘버
# print(str_num) # 리스트
sum_next = 0
# breakPoint = True
while str_num.count(str_num[-1]) < 2:
if str_num.count(str_num[-1]) <2:
# breakPoint = False
break
for i in str_num[-1]:
temp_num = int(i) * int(i)
sum_next += temp_num
str_num.append(str(sum_next))
# print(str_num) # 제곱합한 숫자 리스트에 추가, 루프 리스트 리턴
return str_num
# 수열 길이
def count_list_fun(list_l):
# temp = list_l.split(',')
# length = len(temp)
length = len(list_l)
return length
# 재귀
def loop_fun(list_n):
list_length = 0
# loop_escape = False
while True:
added_next = square_fun(list_n)
# for i in added_next:
# if i == added_next[-1]:
# list_length = count_list_fun(added_next)
# loop_escape = True
# break
# if loop_escape == True:
# break
if added_next[-1] in list_n:
list_length = count_list_fun(added_next)
break
return list_length
def compare_fun(A, B):
pass
##! 0 0 입력일경우 종료
if __name__ == '__main__':
while True:
a, b = map(str, sys.stdin.readline().split()) # str
if a == 0 and b == 0:
break
else:
A_list = loop_fun(a) # 제곱합 루프
B_list = loop_fun(b) #
print(a, b, compare_fun(A_list, B_list))
# a = map(str, sys.stdin.readline().split()) # str
# A_list = square_fun(a)
# print(A_list)
| <filename>parc/pracCode_24060/Baek_4881proto.py
# 백준
# 4881번 : 자리수의 제곱
import sys
##* 89, 1
##* 0< a,b < 10^9
# 1.숫자 제곱 합 함수
def square_fun(number):
str_num = list(number) # map -> list
# print(str_num[0][0]) # 첫째 자리
# print(str_num[0]) # 넘버
# print(str_num) # 리스트
sum_next = 0
# breakPoint = True
while str_num.count(str_num[-1]) < 2:
if str_num.count(str_num[-1]) <2:
# breakPoint = False
break
for i in str_num[-1]:
temp_num = int(i) * int(i)
sum_next += temp_num
str_num.append(str(sum_next))
# print(str_num) # 제곱합한 숫자 리스트에 추가, 루프 리스트 리턴
return str_num
# 수열 길이
def count_list_fun(list_l):
# temp = list_l.split(',')
# length = len(temp)
length = len(list_l)
return length
# 재귀
def loop_fun(list_n):
list_length = 0
# loop_escape = False
while True:
added_next = square_fun(list_n)
# for i in added_next:
# if i == added_next[-1]:
# list_length = count_list_fun(added_next)
# loop_escape = True
# break
# if loop_escape == True:
# break
if added_next[-1] in list_n:
list_length = count_list_fun(added_next)
break
return list_length
def compare_fun(A, B):
pass
##! 0 0 입력일경우 종료
if __name__ == '__main__':
while True:
a, b = map(str, sys.stdin.readline().split()) # str
if a == 0 and b == 0:
break
else:
A_list = loop_fun(a) # 제곱합 루프
B_list = loop_fun(b) #
print(a, b, compare_fun(A_list, B_list))
# a = map(str, sys.stdin.readline().split()) # str
# A_list = square_fun(a)
# print(A_list)
| ko | 0.713626 | # 백준 # 4881번 : 자리수의 제곱 ##* 89, 1 ##* 0< a,b < 10^9 # 1.숫자 제곱 합 함수 # map -> list # print(str_num[0][0]) # 첫째 자리 # print(str_num[0]) # 넘버 # print(str_num) # 리스트 # breakPoint = True # breakPoint = False # print(str_num) # 제곱합한 숫자 리스트에 추가, 루프 리스트 리턴 # 수열 길이 # temp = list_l.split(',') # length = len(temp) # 재귀 # loop_escape = False # for i in added_next: # if i == added_next[-1]: # list_length = count_list_fun(added_next) # loop_escape = True # break # if loop_escape == True: # break ##! 0 0 입력일경우 종료 # str # 제곱합 루프 # # a = map(str, sys.stdin.readline().split()) # str # A_list = square_fun(a) # print(A_list) | 3.47633 | 3 |
torch_geometric/nn/dense/dense_graph_conv.py | mwussow/pytorch_geometric | 9 | 6618883 | <gh_stars>1-10
import torch
from torch.nn import Parameter
from ..inits import uniform
class DenseGraphConv(torch.nn.Module):
r"""See :class:`torch_geometric.nn.conv.GraphConv`.
"""
def __init__(self, in_channels, out_channels, aggr='add', bias=True):
assert aggr in ['add', 'mean', 'max']
super(DenseGraphConv, self).__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.aggr = aggr
self.weight = Parameter(torch.Tensor(in_channels, out_channels))
self.lin = torch.nn.Linear(in_channels, out_channels, bias=bias)
self.reset_parameters()
def reset_parameters(self):
uniform(self.in_channels, self.weight)
self.lin.reset_parameters()
def forward(self, x, adj, mask=None):
r"""
Args:
x (Tensor): Node feature tensor :math:`\mathbf{X} \in \mathbb{R}^{B
\times N \times F}`, with batch-size :math:`B`, (maximum)
number of nodes :math:`N` for each graph, and feature
dimension :math:`F`.
adj (Tensor): Adjacency tensor :math:`\mathbf{A} \in \mathbb{R}^{B
\times N \times N}`. The adjacency tensor is broadcastable in
the batch dimension, resulting in a shared adjacency matrix for
the complete batch.
mask (BoolTensor, optional): Mask matrix
:math:`\mathbf{M} \in {\{ 0, 1 \}}^{B \times N}` indicating
the valid nodes for each graph. (default: :obj:`None`)
"""
x = x.unsqueeze(0) if x.dim() == 2 else x
adj = adj.unsqueeze(0) if adj.dim() == 2 else adj
B, N, _ = adj.size()
out = torch.matmul(adj, x)
out = torch.matmul(out, self.weight)
if self.aggr == 'mean':
out = out / adj.sum(dim=-1, keepdim=True).clamp(min=1)
elif self.aggr == 'max':
out = out.max(dim=-1)[0]
out = out + self.lin(x)
if mask is not None:
out = out * mask.view(B, N, 1).to(x.dtype)
return out
def __repr__(self):
return '{}({}, {})'.format(self.__class__.__name__, self.in_channels,
self.out_channels)
| import torch
from torch.nn import Parameter
from ..inits import uniform
class DenseGraphConv(torch.nn.Module):
r"""See :class:`torch_geometric.nn.conv.GraphConv`.
"""
def __init__(self, in_channels, out_channels, aggr='add', bias=True):
assert aggr in ['add', 'mean', 'max']
super(DenseGraphConv, self).__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.aggr = aggr
self.weight = Parameter(torch.Tensor(in_channels, out_channels))
self.lin = torch.nn.Linear(in_channels, out_channels, bias=bias)
self.reset_parameters()
def reset_parameters(self):
uniform(self.in_channels, self.weight)
self.lin.reset_parameters()
def forward(self, x, adj, mask=None):
r"""
Args:
x (Tensor): Node feature tensor :math:`\mathbf{X} \in \mathbb{R}^{B
\times N \times F}`, with batch-size :math:`B`, (maximum)
number of nodes :math:`N` for each graph, and feature
dimension :math:`F`.
adj (Tensor): Adjacency tensor :math:`\mathbf{A} \in \mathbb{R}^{B
\times N \times N}`. The adjacency tensor is broadcastable in
the batch dimension, resulting in a shared adjacency matrix for
the complete batch.
mask (BoolTensor, optional): Mask matrix
:math:`\mathbf{M} \in {\{ 0, 1 \}}^{B \times N}` indicating
the valid nodes for each graph. (default: :obj:`None`)
"""
x = x.unsqueeze(0) if x.dim() == 2 else x
adj = adj.unsqueeze(0) if adj.dim() == 2 else adj
B, N, _ = adj.size()
out = torch.matmul(adj, x)
out = torch.matmul(out, self.weight)
if self.aggr == 'mean':
out = out / adj.sum(dim=-1, keepdim=True).clamp(min=1)
elif self.aggr == 'max':
out = out.max(dim=-1)[0]
out = out + self.lin(x)
if mask is not None:
out = out * mask.view(B, N, 1).to(x.dtype)
return out
def __repr__(self):
return '{}({}, {})'.format(self.__class__.__name__, self.in_channels,
self.out_channels) | en | 0.515575 | See :class:`torch_geometric.nn.conv.GraphConv`. Args: x (Tensor): Node feature tensor :math:`\mathbf{X} \in \mathbb{R}^{B \times N \times F}`, with batch-size :math:`B`, (maximum) number of nodes :math:`N` for each graph, and feature dimension :math:`F`. adj (Tensor): Adjacency tensor :math:`\mathbf{A} \in \mathbb{R}^{B \times N \times N}`. The adjacency tensor is broadcastable in the batch dimension, resulting in a shared adjacency matrix for the complete batch. mask (BoolTensor, optional): Mask matrix :math:`\mathbf{M} \in {\{ 0, 1 \}}^{B \times N}` indicating the valid nodes for each graph. (default: :obj:`None`) | 2.764294 | 3 |
src/bench_embedings.py | kibernetika-ai/facenet | 4 | 6618884 | <gh_stars>1-10
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import math
import sys
import numpy as np
import time
import facenet
from ml_serving.drivers import driver
def main(args):
dataset = facenet.get_dataset(args.data_dir)
# Check that there are at least one training image per class
for cls in dataset:
assert len(cls.image_paths) > 0, 'There must be at least one image for each class in the dataset'
paths, labels = facenet.get_image_paths_and_labels(dataset)
print('Number of classes: %d' % len(dataset))
print('Number of images: %d' % len(paths))
# Load the model
print('Loading feature extraction model')
# Load driver
drv = driver.load_driver(args.driver)
# Instantinate driver
serving = drv()
serving.load_model(
args.model,
inputs='input:0,phase_train:0',
outputs='embeddings:0',
device=args.device,
flexible_batch_size=True,
)
# Run forward pass to calculate embeddings
print('Calculating features for images')
nrof_images = len(paths)
nrof_batches_per_epoch = int(math.ceil(1.0 * nrof_images / args.batch_size))
embeddings_size = nrof_images
emb_array = np.zeros((embeddings_size, 512))
start_time = time.time()
for j in range(100):
for i in range(nrof_batches_per_epoch):
start_index = i * args.batch_size
end_index = min((i + 1) * args.batch_size, nrof_images)
paths_batch = paths[start_index:end_index]
images = facenet.load_data(paths_batch, False, False, args.image_size)
if serving.driver_name == 'tensorflow':
feed_dict = {'input:0': images, 'phase_train:0': False}
elif serving.driver_name == 'openvino':
input_name = list(serving.inputs.keys())[0]
# Transpose image for channel first format
images = images.transpose([0, 3, 1, 2])
feed_dict = {input_name: images}
else:
raise RuntimeError('Driver %s currently not supported' % serving.driver_name)
outputs = serving.predict(feed_dict)
end_time = time.time()
nrof_batches_per_epoch *= 100
print("Duration: {} sec/sample batch count:{}".format((end_time-start_time)/nrof_batches_per_epoch,nrof_batches_per_epoch))
print("Speed: {} sample/sec batch count:{}".format(nrof_batches_per_epoch/(end_time-start_time),nrof_batches_per_epoch))
def parse_arguments(argv):
parser = argparse.ArgumentParser()
parser.add_argument(
'data_dir',
type=str,
help='Path to the data directory containing aligned LFW face patches.'
)
parser.add_argument(
'--model',
type=str,
help='Path to .xml openVINO IR file',
required=True,
)
parser.add_argument(
'--device',
help='Device for openVINO.',
default="CPU",
choices=["CPU", "MYRIAD"]
)
parser.add_argument(
'--driver',
help='Driver for inference.',
default="tensorflow",
)
parser.add_argument(
'--batch_size',
type=int,
help='Number of images to process in a batch.',
default=1
)
parser.add_argument(
'--image_size',
type=int,
help='Image size (height, width) in pixels.',
default=160
)
return parser.parse_args(argv)
if __name__ == '__main__':
main(parse_arguments(sys.argv[1:]))
| from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import math
import sys
import numpy as np
import time
import facenet
from ml_serving.drivers import driver
def main(args):
dataset = facenet.get_dataset(args.data_dir)
# Check that there are at least one training image per class
for cls in dataset:
assert len(cls.image_paths) > 0, 'There must be at least one image for each class in the dataset'
paths, labels = facenet.get_image_paths_and_labels(dataset)
print('Number of classes: %d' % len(dataset))
print('Number of images: %d' % len(paths))
# Load the model
print('Loading feature extraction model')
# Load driver
drv = driver.load_driver(args.driver)
# Instantinate driver
serving = drv()
serving.load_model(
args.model,
inputs='input:0,phase_train:0',
outputs='embeddings:0',
device=args.device,
flexible_batch_size=True,
)
# Run forward pass to calculate embeddings
print('Calculating features for images')
nrof_images = len(paths)
nrof_batches_per_epoch = int(math.ceil(1.0 * nrof_images / args.batch_size))
embeddings_size = nrof_images
emb_array = np.zeros((embeddings_size, 512))
start_time = time.time()
for j in range(100):
for i in range(nrof_batches_per_epoch):
start_index = i * args.batch_size
end_index = min((i + 1) * args.batch_size, nrof_images)
paths_batch = paths[start_index:end_index]
images = facenet.load_data(paths_batch, False, False, args.image_size)
if serving.driver_name == 'tensorflow':
feed_dict = {'input:0': images, 'phase_train:0': False}
elif serving.driver_name == 'openvino':
input_name = list(serving.inputs.keys())[0]
# Transpose image for channel first format
images = images.transpose([0, 3, 1, 2])
feed_dict = {input_name: images}
else:
raise RuntimeError('Driver %s currently not supported' % serving.driver_name)
outputs = serving.predict(feed_dict)
end_time = time.time()
nrof_batches_per_epoch *= 100
print("Duration: {} sec/sample batch count:{}".format((end_time-start_time)/nrof_batches_per_epoch,nrof_batches_per_epoch))
print("Speed: {} sample/sec batch count:{}".format(nrof_batches_per_epoch/(end_time-start_time),nrof_batches_per_epoch))
def parse_arguments(argv):
parser = argparse.ArgumentParser()
parser.add_argument(
'data_dir',
type=str,
help='Path to the data directory containing aligned LFW face patches.'
)
parser.add_argument(
'--model',
type=str,
help='Path to .xml openVINO IR file',
required=True,
)
parser.add_argument(
'--device',
help='Device for openVINO.',
default="CPU",
choices=["CPU", "MYRIAD"]
)
parser.add_argument(
'--driver',
help='Driver for inference.',
default="tensorflow",
)
parser.add_argument(
'--batch_size',
type=int,
help='Number of images to process in a batch.',
default=1
)
parser.add_argument(
'--image_size',
type=int,
help='Image size (height, width) in pixels.',
default=160
)
return parser.parse_args(argv)
if __name__ == '__main__':
main(parse_arguments(sys.argv[1:])) | en | 0.90686 | # Check that there are at least one training image per class # Load the model # Load driver # Instantinate driver # Run forward pass to calculate embeddings # Transpose image for channel first format | 2.447632 | 2 |
tests/test_app.py | kevincon/utilityknife | 21 | 6618885 | <reponame>kevincon/utilityknife
import pytest
def test_index(selenium, base_url):
selenium.get(base_url)
assert 'Utility Knife' == selenium.title
| import pytest
def test_index(selenium, base_url):
selenium.get(base_url)
assert 'Utility Knife' == selenium.title | none | 1 | 2.066842 | 2 | |
test/util.py | brabadu/grab | 1 | 6618886 | import os
import shutil
import tempfile
import functools
TEST_DIR = os.path.dirname(os.path.realpath(__file__))
# Global variable which is used in all tests to build
# Grab instance with specific transport layer
GRAB_TRANSPORT = None
def prepare_test_environment():
global TMP_DIR, TMP_FILE
TMP_DIR = tempfile.mkdtemp()
TMP_FILE = os.path.join(TMP_DIR, '__temp')
def clear_test_environment():
remove_directory(TMP_DIR)
def remove_directory(path):
for root, dirs, files in os.walk(path):
for fname in files:
os.unlink(os.path.join(root, fname))
for _dir in dirs:
shutil.rmtree(os.path.join(root, _dir))
def ignore_transport(transport):
"""
If test function is wrapped into this decorator then
it should not be tested if test is performed for
specified transport
"""
def wrapper(func):
@functools.wraps(func)
def test_method(*args, **kwargs):
if GRAB_TRANSPORT == transport:
return
else:
func(*args, **kwargs)
return test_method
return wrapper
def only_transport(transport):
"""
If test function is wrapped into this decorator then
it should be called only for specified transport.
"""
def wrapper(func):
@functools.wraps(func)
def test_method(*args, **kwargs):
if GRAB_TRANSPORT == transport:
func(*args, **kwargs)
else:
return
return test_method
return wrapper
| import os
import shutil
import tempfile
import functools
TEST_DIR = os.path.dirname(os.path.realpath(__file__))
# Global variable which is used in all tests to build
# Grab instance with specific transport layer
GRAB_TRANSPORT = None
def prepare_test_environment():
global TMP_DIR, TMP_FILE
TMP_DIR = tempfile.mkdtemp()
TMP_FILE = os.path.join(TMP_DIR, '__temp')
def clear_test_environment():
remove_directory(TMP_DIR)
def remove_directory(path):
for root, dirs, files in os.walk(path):
for fname in files:
os.unlink(os.path.join(root, fname))
for _dir in dirs:
shutil.rmtree(os.path.join(root, _dir))
def ignore_transport(transport):
"""
If test function is wrapped into this decorator then
it should not be tested if test is performed for
specified transport
"""
def wrapper(func):
@functools.wraps(func)
def test_method(*args, **kwargs):
if GRAB_TRANSPORT == transport:
return
else:
func(*args, **kwargs)
return test_method
return wrapper
def only_transport(transport):
"""
If test function is wrapped into this decorator then
it should be called only for specified transport.
"""
def wrapper(func):
@functools.wraps(func)
def test_method(*args, **kwargs):
if GRAB_TRANSPORT == transport:
func(*args, **kwargs)
else:
return
return test_method
return wrapper
| en | 0.820674 | # Global variable which is used in all tests to build # Grab instance with specific transport layer If test function is wrapped into this decorator then it should not be tested if test is performed for specified transport If test function is wrapped into this decorator then it should be called only for specified transport. | 2.562429 | 3 |
codeninja/admin/__init__.py | Deathnerd/iamacodeninja | 0 | 6618887 | __author__ = 'Deathnerd'
| __author__ = 'Deathnerd'
| none | 1 | 1.001558 | 1 | |
1sem_project/download_htmls.py | sergy2710/spheremail | 0 | 6618888 | from bs4 import BeautifulSoup
import requests
import pandas as pd
import numpy as np
import re
import time
import os
from get_proxy import Proxy
def ok_html(html):
if html is not None:
try:
soup = BeautifulSoup(html.text, 'html.parser')
elem = soup.find(class_='title-info-metadata-item').text
except:
elem = None
else:
elem = None
return elem is not None
if not os.path.exists("htmls"):
os.makedirs("htmls")
columns = ['url',]
downloaded_htmls = []
try:
df = pd.DataFrame.from_csv('downloaded_htmls.csv')
for i in df['url']:
downloaded_htmls.append(str(i))
except:
df = pd.DataFrame(columns=columns)
print('{} htmls in a database'.format(len(downloaded_htmls)))
with open('failed_download.txt', 'a+') as failedfile:
with open('urls.txt', 'r') as ifile:
prefix = ifile.readline()[:-1]
page_num = 0
for suffix in ifile:
page_num += 1
print('page {}'.format(page_num))
suffix = suffix[:-1]
url = prefix + suffix
print('downloading {}'.format(url))
if url in downloaded_htmls:
print('downloaded before')
else:
counter = 1
proxies = Proxy().get_proxies()
try:
html = requests.get(url, proxies=next(proxies))
except:
html = None
while (not ok_html(html)) & (counter < 10):
counter += 1
try:
html = requests.get(url, proxies=next(proxies))
except:
html = None
if counter < 10:
file_html = open('htmls/' + suffix + '.html', 'w+', encoding='utf-8')
file_html.write(html.text)
file_html.close()
downloaded_htmls.append(url)
data = {el: '' for el in columns}
data['url'] = url
ser = pd.Series(name=page_num, data=data, index=columns)
df = df.append(ser)
df.to_csv('downloaded_htmls.csv')
print('success\n')
time.sleep(1)
else:
failedfile.write(url + '\n')
print('failed')
time.sleep(1)
df.to_csv('downloaded_htmls.csv')
| from bs4 import BeautifulSoup
import requests
import pandas as pd
import numpy as np
import re
import time
import os
from get_proxy import Proxy
def ok_html(html):
if html is not None:
try:
soup = BeautifulSoup(html.text, 'html.parser')
elem = soup.find(class_='title-info-metadata-item').text
except:
elem = None
else:
elem = None
return elem is not None
if not os.path.exists("htmls"):
os.makedirs("htmls")
columns = ['url',]
downloaded_htmls = []
try:
df = pd.DataFrame.from_csv('downloaded_htmls.csv')
for i in df['url']:
downloaded_htmls.append(str(i))
except:
df = pd.DataFrame(columns=columns)
print('{} htmls in a database'.format(len(downloaded_htmls)))
with open('failed_download.txt', 'a+') as failedfile:
with open('urls.txt', 'r') as ifile:
prefix = ifile.readline()[:-1]
page_num = 0
for suffix in ifile:
page_num += 1
print('page {}'.format(page_num))
suffix = suffix[:-1]
url = prefix + suffix
print('downloading {}'.format(url))
if url in downloaded_htmls:
print('downloaded before')
else:
counter = 1
proxies = Proxy().get_proxies()
try:
html = requests.get(url, proxies=next(proxies))
except:
html = None
while (not ok_html(html)) & (counter < 10):
counter += 1
try:
html = requests.get(url, proxies=next(proxies))
except:
html = None
if counter < 10:
file_html = open('htmls/' + suffix + '.html', 'w+', encoding='utf-8')
file_html.write(html.text)
file_html.close()
downloaded_htmls.append(url)
data = {el: '' for el in columns}
data['url'] = url
ser = pd.Series(name=page_num, data=data, index=columns)
df = df.append(ser)
df.to_csv('downloaded_htmls.csv')
print('success\n')
time.sleep(1)
else:
failedfile.write(url + '\n')
print('failed')
time.sleep(1)
df.to_csv('downloaded_htmls.csv')
| none | 1 | 2.834432 | 3 | |
dynamo_charlotte_IDE.py | jc-juarez/dynamocharlotte_ide | 1 | 6618889 | <filename>dynamo_charlotte_IDE.py<gh_stars>1-10
from tkinter import *
import sys
import dynamocharlotte as dc
window = Tk()
window.title("Dynamo Charlotte IDE")
def runMyCode():
code = textEditor.get('1.0', END)
dc.run(code)
textEditor = Text()
textEditor.pack()
menuBar = Menu(window)
runBar = Menu(menuBar, tearoff=0)
runBar.add_command(label = "Run", command = runMyCode)
menuBar.add_cascade(label = "Run", menu = runBar)
window.config(menu = menuBar)
window.mainloop() | <filename>dynamo_charlotte_IDE.py<gh_stars>1-10
from tkinter import *
import sys
import dynamocharlotte as dc
window = Tk()
window.title("Dynamo Charlotte IDE")
def runMyCode():
code = textEditor.get('1.0', END)
dc.run(code)
textEditor = Text()
textEditor.pack()
menuBar = Menu(window)
runBar = Menu(menuBar, tearoff=0)
runBar.add_command(label = "Run", command = runMyCode)
menuBar.add_cascade(label = "Run", menu = runBar)
window.config(menu = menuBar)
window.mainloop() | none | 1 | 2.916007 | 3 | |
projects/mqtt-simple-test/publish.py | basavyr/mqtt-python-workflows | 0 | 6618890 | import paho.mqtt.client as mqtt
client=mqtt.Client()
local='127.0.0.1'
host0='0.0.0.0'
client.connect(local, 1883,60)
client.connect(host0, 1883,60)
client.publish("test/","mmm")
| import paho.mqtt.client as mqtt
client=mqtt.Client()
local='127.0.0.1'
host0='0.0.0.0'
client.connect(local, 1883,60)
client.connect(host0, 1883,60)
client.publish("test/","mmm")
| none | 1 | 2.123056 | 2 | |
tools/accessibility/codereview/download_issue.py | chromium/chromium | 14,668 | 6618891 | #!/usr/bin/env python
# Copyright (c) 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Downloads a patch and changed files from Rietveld.
Prints the patch of the most recent patchset to stdout.
"""
try:
import base64
import fix_encoding
import gerrit_util
import git_cl
import optparse
import os.path
# import StringIO
import sys
import tarfile
#import urllib2
from third_party import colorama
except ImportError as e:
print(e)
print('Perhaps you\'re missing depot_tools in your PYTHONPATH.')
import sys
sys.exit(1)
def Progress(message):
print(message, file=sys.stderr)
def DieWithError(message):
print(message, file=sys.stderr)
sys.exit(1)
def main(argv):
parser = optparse.OptionParser()
parser.set_usage('%prog [options] issue_number')
parser.description = __doc__.strip()
options, args = parser.parse_args(argv)
if len(args) != 1:
parser.print_help()
return 0
change_id = ""
try:
issue = int(args[0])
except ValueError:
try:
change_id = str(args[0])
except ValueError:
DieWithError('Invalid issue number or change id')
if not change_id:
HOST_ = "chromium-review.googlesource.com"
change_id = gerrit_util.GetChange(HOST_, issue)["change_id"]
else:
HOST_ = "googleplex-android-review.git.corp.google.com"
query = gerrit_util.GetChangeCurrentRevision(HOST_, change_id)[0]
current_revision_id = query["current_revision"]
current_revision = query["revisions"][current_revision_id]
patchset = current_revision["_number"]
ref = current_revision["ref"]
# Fetch the current branch.
Progress("Fetching... " + ref)
git_cl.RunGit(
["fetch", "https://chromium.googlesource.com/chromium/src", ref])
print('Issue: %d, patchset: %d\n' % (issue, patchset))
print()
print(git_cl.RunGit(["show", "FETCH_HEAD"]))
git_cl.RunGit(["checkout", "FETCH_HEAD"])
Progress("finished")
Progress("Run git checkout FETCH_HEAD, to start reviewing.")
if __name__ == '__main__':
# These affect sys.stdout so do it outside of main() to simplify mocks in
# unit testing.
fix_encoding.fix_encoding()
colorama.init()
sys.exit(main(sys.argv[1:]))
| #!/usr/bin/env python
# Copyright (c) 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Downloads a patch and changed files from Rietveld.
Prints the patch of the most recent patchset to stdout.
"""
try:
import base64
import fix_encoding
import gerrit_util
import git_cl
import optparse
import os.path
# import StringIO
import sys
import tarfile
#import urllib2
from third_party import colorama
except ImportError as e:
print(e)
print('Perhaps you\'re missing depot_tools in your PYTHONPATH.')
import sys
sys.exit(1)
def Progress(message):
print(message, file=sys.stderr)
def DieWithError(message):
print(message, file=sys.stderr)
sys.exit(1)
def main(argv):
parser = optparse.OptionParser()
parser.set_usage('%prog [options] issue_number')
parser.description = __doc__.strip()
options, args = parser.parse_args(argv)
if len(args) != 1:
parser.print_help()
return 0
change_id = ""
try:
issue = int(args[0])
except ValueError:
try:
change_id = str(args[0])
except ValueError:
DieWithError('Invalid issue number or change id')
if not change_id:
HOST_ = "chromium-review.googlesource.com"
change_id = gerrit_util.GetChange(HOST_, issue)["change_id"]
else:
HOST_ = "googleplex-android-review.git.corp.google.com"
query = gerrit_util.GetChangeCurrentRevision(HOST_, change_id)[0]
current_revision_id = query["current_revision"]
current_revision = query["revisions"][current_revision_id]
patchset = current_revision["_number"]
ref = current_revision["ref"]
# Fetch the current branch.
Progress("Fetching... " + ref)
git_cl.RunGit(
["fetch", "https://chromium.googlesource.com/chromium/src", ref])
print('Issue: %d, patchset: %d\n' % (issue, patchset))
print()
print(git_cl.RunGit(["show", "FETCH_HEAD"]))
git_cl.RunGit(["checkout", "FETCH_HEAD"])
Progress("finished")
Progress("Run git checkout FETCH_HEAD, to start reviewing.")
if __name__ == '__main__':
# These affect sys.stdout so do it outside of main() to simplify mocks in
# unit testing.
fix_encoding.fix_encoding()
colorama.init()
sys.exit(main(sys.argv[1:]))
| en | 0.825546 | #!/usr/bin/env python # Copyright (c) 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. Downloads a patch and changed files from Rietveld. Prints the patch of the most recent patchset to stdout. # import StringIO #import urllib2 # Fetch the current branch. # These affect sys.stdout so do it outside of main() to simplify mocks in # unit testing. | 2.165563 | 2 |
mmdet/core/box.py | jahongir7174/VIPriors | 3 | 6618892 | <filename>mmdet/core/box.py
import mmcv
import numpy as np
import torch
from mmdet.core import builder, util
class AssignResult(util.NiceRepr):
def __init__(self, num_gts, gt_inds, max_overlaps, labels=None):
self.num_gts = num_gts
self.gt_inds = gt_inds
self.max_overlaps = max_overlaps
self.labels = labels
# Interface for possible user-defined properties
self._extra_properties = {}
@property
def num_preds(self):
"""int: the number of predictions in this assignment"""
return len(self.gt_inds)
def set_extra_property(self, key, value):
"""Set user-defined new property."""
assert key not in self.info
self._extra_properties[key] = value
def get_extra_property(self, key):
"""Get user-defined property."""
return self._extra_properties.get(key, None)
@property
def info(self):
"""dict: a dictionary of info about the object"""
basic_info = {
'num_gts': self.num_gts,
'num_preds': self.num_preds,
'gt_inds': self.gt_inds,
'max_overlaps': self.max_overlaps,
'labels': self.labels,
}
basic_info.update(self._extra_properties)
return basic_info
def __nice__(self):
"""str: a "nice" summary string describing this assign result"""
parts = []
parts.append(f'num_gts={self.num_gts!r}')
if self.gt_inds is None:
parts.append(f'gt_inds={self.gt_inds!r}')
else:
parts.append(f'gt_inds.shape={tuple(self.gt_inds.shape)!r}')
if self.max_overlaps is None:
parts.append(f'max_overlaps={self.max_overlaps!r}')
else:
parts.append('max_overlaps.shape='
f'{tuple(self.max_overlaps.shape)!r}')
if self.labels is None:
parts.append(f'labels={self.labels!r}')
else:
parts.append(f'labels.shape={tuple(self.labels.shape)!r}')
return ', '.join(parts)
@classmethod
def random(cls, **kwargs):
from mmdet.core.util import ensure_rng
rng = ensure_rng(kwargs.get('rng', None))
num_gts = kwargs.get('num_gts', None)
num_preds = kwargs.get('num_preds', None)
p_ignore = kwargs.get('p_ignore', 0.3)
p_assigned = kwargs.get('p_assigned', 0.7)
p_use_label = kwargs.get('p_use_label', 0.5)
num_classes = kwargs.get('p_use_label', 3)
if num_gts is None:
num_gts = rng.randint(0, 8)
if num_preds is None:
num_preds = rng.randint(0, 16)
if num_gts == 0:
max_overlaps = torch.zeros(num_preds, dtype=torch.float32)
gt_inds = torch.zeros(num_preds, dtype=torch.int64)
if p_use_label is True or p_use_label < rng.rand():
labels = torch.zeros(num_preds, dtype=torch.int64)
else:
labels = None
else:
import numpy as np
# Create an overlap for each predicted box
max_overlaps = torch.from_numpy(rng.rand(num_preds))
# Construct gt_inds for each predicted box
is_assigned = torch.from_numpy(rng.rand(num_preds) < p_assigned)
# maximum number of assignments constraints
n_assigned = min(num_preds, min(num_gts, is_assigned.sum()))
assigned_idxs = np.where(is_assigned)[0]
rng.shuffle(assigned_idxs)
assigned_idxs = assigned_idxs[0:n_assigned]
assigned_idxs.sort()
is_assigned[:] = 0
is_assigned[assigned_idxs] = True
is_ignore = torch.from_numpy(
rng.rand(num_preds) < p_ignore) & is_assigned
gt_inds = torch.zeros(num_preds, dtype=torch.int64)
true_idxs = np.arange(num_gts)
rng.shuffle(true_idxs)
true_idxs = torch.from_numpy(true_idxs)
gt_inds[is_assigned] = true_idxs[:n_assigned]
gt_inds = torch.from_numpy(
rng.randint(1, num_gts + 1, size=num_preds))
gt_inds[is_ignore] = -1
gt_inds[~is_assigned] = 0
max_overlaps[~is_assigned] = 0
if p_use_label is True or p_use_label < rng.rand():
if num_classes == 0:
labels = torch.zeros(num_preds, dtype=torch.int64)
else:
labels = torch.from_numpy(
# remind that we set FG labels to [0, num_class-1]
# since mmdet v2.0
# BG cat_id: num_class
rng.randint(0, num_classes, size=num_preds))
labels[~is_assigned] = 0
else:
labels = None
self = cls(num_gts, gt_inds, max_overlaps, labels)
return self
def add_gt_(self, gt_labels):
"""Add ground truth as assigned results.
Args:
gt_labels (torch.Tensor): Labels of gt boxes
"""
self_inds = torch.arange(
1, len(gt_labels) + 1, dtype=torch.long, device=gt_labels.device)
self.gt_inds = torch.cat([self_inds, self.gt_inds])
self.max_overlaps = torch.cat(
[self.max_overlaps.new_ones(len(gt_labels)), self.max_overlaps])
if self.labels is not None:
self.labels = torch.cat([gt_labels, self.labels])
@builder.BBOX_ASSIGNERS.register_module()
class MaxIoUAssigner:
def __init__(self,
pos_iou_thr,
neg_iou_thr,
min_pos_iou=.0,
gt_max_assign_all=True,
ignore_iof_thr=-1,
ignore_wrt_candidates=True,
match_low_quality=True,
gpu_assign_thr=-1,
iou_calculator=dict(type='BoxOverlaps2D')):
self.pos_iou_thr = pos_iou_thr
self.neg_iou_thr = neg_iou_thr
self.min_pos_iou = min_pos_iou
self.gt_max_assign_all = gt_max_assign_all
self.ignore_iof_thr = ignore_iof_thr
self.ignore_wrt_candidates = ignore_wrt_candidates
self.gpu_assign_thr = gpu_assign_thr
self.match_low_quality = match_low_quality
self.iou_calculator = builder.build_iou_calculator(iou_calculator)
def assign(self, bboxes, gt_bboxes, gt_bboxes_ignore=None, gt_labels=None):
assign_on_cpu = True if (self.gpu_assign_thr > 0) and (gt_bboxes.shape[0] > self.gpu_assign_thr) else False
# compute overlap and assign gt on CPU when number of GT is large
if assign_on_cpu:
device = bboxes.device
bboxes = bboxes.cpu()
gt_bboxes = gt_bboxes.cpu()
if gt_bboxes_ignore is not None:
gt_bboxes_ignore = gt_bboxes_ignore.cpu()
if gt_labels is not None:
gt_labels = gt_labels.cpu()
overlaps = self.iou_calculator(gt_bboxes, bboxes)
if (self.ignore_iof_thr > 0 and gt_bboxes_ignore is not None
and gt_bboxes_ignore.numel() > 0 and bboxes.numel() > 0):
if self.ignore_wrt_candidates:
ignore_overlaps = self.iou_calculator(
bboxes, gt_bboxes_ignore, mode='iof')
ignore_max_overlaps, _ = ignore_overlaps.max(dim=1)
else:
ignore_overlaps = self.iou_calculator(
gt_bboxes_ignore, bboxes, mode='iof')
ignore_max_overlaps, _ = ignore_overlaps.max(dim=0)
overlaps[:, ignore_max_overlaps > self.ignore_iof_thr] = -1
assign_result = self.assign_wrt_overlaps(overlaps, gt_labels)
if assign_on_cpu:
assign_result.gt_inds = assign_result.gt_inds.to(device)
assign_result.max_overlaps = assign_result.max_overlaps.to(device)
if assign_result.labels is not None:
assign_result.labels = assign_result.labels.to(device)
return assign_result
def assign_wrt_overlaps(self, overlaps, gt_labels=None):
num_gts, num_bboxes = overlaps.size(0), overlaps.size(1)
# 1. assign -1 by default
assigned_gt_inds = overlaps.new_full((num_bboxes,), -1, dtype=torch.long)
if num_gts == 0 or num_bboxes == 0:
# No ground truth or boxes, return empty assignment
max_overlaps = overlaps.new_zeros((num_bboxes,))
if num_gts == 0:
# No truth, assign everything to background
assigned_gt_inds[:] = 0
if gt_labels is None:
assigned_labels = None
else:
assigned_labels = overlaps.new_full((num_bboxes,), -1, dtype=torch.long)
return AssignResult(num_gts,
assigned_gt_inds,
max_overlaps,
labels=assigned_labels)
# for each anchor, which gt best overlaps with it
# for each anchor, the max iou of all gts
max_overlaps, argmax_overlaps = overlaps.max(dim=0)
# for each gt, which anchor best overlaps with it
# for each gt, the max iou of all proposals
gt_max_overlaps, gt_argmax_overlaps = overlaps.max(dim=1)
# 2. assign negative: below
# the negative inds are set to be 0
if isinstance(self.neg_iou_thr, float):
assigned_gt_inds[(max_overlaps >= 0) & (max_overlaps < self.neg_iou_thr)] = 0
elif isinstance(self.neg_iou_thr, tuple):
assert len(self.neg_iou_thr) == 2
assigned_gt_inds[(max_overlaps >= self.neg_iou_thr[0]) & (max_overlaps < self.neg_iou_thr[1])] = 0
# 3. assign positive: above positive IoU threshold
pos_inds = max_overlaps >= self.pos_iou_thr
assigned_gt_inds[pos_inds] = argmax_overlaps[pos_inds] + 1
if self.match_low_quality:
for i in range(num_gts):
if gt_max_overlaps[i] >= self.min_pos_iou:
if self.gt_max_assign_all:
max_iou_inds = overlaps[i, :] == gt_max_overlaps[i]
assigned_gt_inds[max_iou_inds] = i + 1
else:
assigned_gt_inds[gt_argmax_overlaps[i]] = i + 1
if gt_labels is not None:
assigned_labels = assigned_gt_inds.new_full((num_bboxes,), -1)
pos_inds = torch.nonzero(assigned_gt_inds > 0, as_tuple=False).squeeze()
if pos_inds.numel() > 0:
assigned_labels[pos_inds] = gt_labels[assigned_gt_inds[pos_inds] - 1]
else:
assigned_labels = None
return AssignResult(num_gts, assigned_gt_inds, max_overlaps, labels=assigned_labels)
@mmcv.jit(coderize=True)
def bbox2delta(proposals, gt, means=(0., 0., 0., 0.), stds=(1., 1., 1., 1.)):
assert proposals.size() == gt.size()
proposals = proposals.float()
gt = gt.float()
px = (proposals[..., 0] + proposals[..., 2]) * 0.5
py = (proposals[..., 1] + proposals[..., 3]) * 0.5
pw = proposals[..., 2] - proposals[..., 0]
ph = proposals[..., 3] - proposals[..., 1]
gx = (gt[..., 0] + gt[..., 2]) * 0.5
gy = (gt[..., 1] + gt[..., 3]) * 0.5
gw = gt[..., 2] - gt[..., 0]
gh = gt[..., 3] - gt[..., 1]
dx = (gx - px) / pw
dy = (gy - py) / ph
dw = torch.log(gw / pw)
dh = torch.log(gh / ph)
deltas = torch.stack([dx, dy, dw, dh], dim=-1)
means = deltas.new_tensor(means).unsqueeze(0)
stds = deltas.new_tensor(stds).unsqueeze(0)
deltas = deltas.sub_(means).div_(stds)
return deltas
@mmcv.jit(coderize=True)
def delta2bbox(rois,
deltas,
means=(0., 0., 0., 0.),
stds=(1., 1., 1., 1.),
max_shape=None,
wh_ratio_clip=16 / 1000,
clip_border=True,
add_ctr_clamp=False,
ctr_clamp=32):
means = deltas.new_tensor(means).view(1,
-1).repeat(1,
deltas.size(-1) // 4)
stds = deltas.new_tensor(stds).view(1, -1).repeat(1, deltas.size(-1) // 4)
denorm_deltas = deltas * stds + means
dx = denorm_deltas[..., 0::4]
dy = denorm_deltas[..., 1::4]
dw = denorm_deltas[..., 2::4]
dh = denorm_deltas[..., 3::4]
x1, y1 = rois[..., 0], rois[..., 1]
x2, y2 = rois[..., 2], rois[..., 3]
# Compute center of each roi
px = ((x1 + x2) * 0.5).unsqueeze(-1).expand_as(dx)
py = ((y1 + y2) * 0.5).unsqueeze(-1).expand_as(dy)
# Compute width/height of each roi
pw = (x2 - x1).unsqueeze(-1).expand_as(dw)
ph = (y2 - y1).unsqueeze(-1).expand_as(dh)
dx_width = pw * dx
dy_height = ph * dy
max_ratio = np.abs(np.log(wh_ratio_clip))
if add_ctr_clamp:
dx_width = torch.clamp(dx_width, max=ctr_clamp, min=-ctr_clamp)
dy_height = torch.clamp(dy_height, max=ctr_clamp, min=-ctr_clamp)
dw = torch.clamp(dw, max=max_ratio)
dh = torch.clamp(dh, max=max_ratio)
else:
dw = dw.clamp(min=-max_ratio, max=max_ratio)
dh = dh.clamp(min=-max_ratio, max=max_ratio)
# Use exp(network energy) to enlarge/shrink each roi
gw = pw * dw.exp()
gh = ph * dh.exp()
# Use network energy to shift the center of each roi
gx = px + dx_width
gy = py + dy_height
# Convert center-xy/width/height to top-left, bottom-right
x1 = gx - gw * 0.5
y1 = gy - gh * 0.5
x2 = gx + gw * 0.5
y2 = gy + gh * 0.5
bboxes = torch.stack([x1, y1, x2, y2], dim=-1).view(deltas.size())
if clip_border and max_shape is not None:
if not isinstance(max_shape, torch.Tensor):
max_shape = x1.new_tensor(max_shape)
max_shape = max_shape[..., :2].type_as(x1)
if max_shape.ndim == 2:
assert bboxes.ndim == 3
assert max_shape.size(0) == bboxes.size(0)
min_xy = x1.new_tensor(0)
max_xy = torch.cat(
[max_shape] * (deltas.size(-1) // 2),
dim=-1).flip(-1).unsqueeze(-2)
bboxes = torch.where(bboxes < min_xy, min_xy, bboxes)
bboxes = torch.where(bboxes > max_xy, max_xy, bboxes)
return bboxes
@builder.BBOX_CODERS.register_module()
class DeltaXYWHBBoxCoder:
def __init__(self,
target_means=(0., 0., 0., 0.),
target_stds=(1., 1., 1., 1.),
clip_border=True,
add_ctr_clamp=False,
ctr_clamp=32):
super().__init__()
self.means = target_means
self.stds = target_stds
self.clip_border = clip_border
self.add_ctr_clamp = add_ctr_clamp
self.ctr_clamp = ctr_clamp
def encode(self, bboxes, gt_bboxes):
"""Get box regression transformation deltas that can be used to
transform the ``bboxes`` into the ``gt_bboxes``.
Args:
bboxes (torch.Tensor): Source boxes, e.g., object proposals.
gt_bboxes (torch.Tensor): Target of the transformation, e.g.,
ground-truth boxes.
Returns:
torch.Tensor: Box transformation deltas
"""
assert bboxes.size(0) == gt_bboxes.size(0)
assert bboxes.size(-1) == gt_bboxes.size(-1) == 4
encoded_bboxes = bbox2delta(bboxes, gt_bboxes, self.means, self.stds)
return encoded_bboxes
def decode(self,
bboxes,
pred_bboxes,
max_shape=None,
wh_ratio_clip=16 / 1000):
"""Apply transformation `pred_bboxes` to `boxes`.
Args:
bboxes (torch.Tensor): Basic boxes. Shape (B, N, 4) or (N, 4)
pred_bboxes (Tensor): Encoded offsets with respect to each roi.
Has shape (B, N, num_classes * 4) or (B, N, 4) or
(N, num_classes * 4) or (N, 4). Note N = num_anchors * W * H
when rois is a grid of anchors.Offset encoding follows [1]_.
max_shape (Sequence[int] or torch.Tensor or Sequence[
Sequence[int]],optional): Maximum bounds for boxes, specifies
(H, W, C) or (H, W). If bboxes shape is (B, N, 4), then
the max_shape should be a Sequence[Sequence[int]]
and the length of max_shape should also be B.
wh_ratio_clip (float, optional): The allowed ratio between
width and height.
Returns:
torch.Tensor: Decoded boxes.
"""
assert pred_bboxes.size(0) == bboxes.size(0)
if pred_bboxes.ndim == 3:
assert pred_bboxes.size(1) == bboxes.size(1)
decoded_bboxes = delta2bbox(bboxes, pred_bboxes, self.means, self.stds,
max_shape, wh_ratio_clip, self.clip_border,
self.add_ctr_clamp, self.ctr_clamp)
return decoded_bboxes
def cast_tensor_type(x, scale=1., dtype=None):
if dtype == 'fp16':
# scale is for preventing overflows
x = (x / scale).half()
return x
def fp16_clamp(x, min=None, max=None):
if not x.is_cuda and x.dtype == torch.float16:
# clamp for cpu float16, tensor fp16 has no clamp implementation
return x.float().clamp(min, max).half()
return x.clamp(min, max)
def bbox_overlaps(bboxes1, bboxes2, mode='iou', is_aligned=False, eps=1e-6):
assert mode in ['iou', 'iof', 'giou'], f'Unsupported mode {mode}'
# Either the boxes are empty or the length of boxes' last dimension is 4
assert (bboxes1.size(-1) == 4 or bboxes1.size(0) == 0)
assert (bboxes2.size(-1) == 4 or bboxes2.size(0) == 0)
# Batch dim must be the same
# Batch dim: (B1, B2, ... Bn)
assert bboxes1.shape[:-2] == bboxes2.shape[:-2]
batch_shape = bboxes1.shape[:-2]
rows = bboxes1.size(-2)
cols = bboxes2.size(-2)
if is_aligned:
assert rows == cols
if rows * cols == 0:
if is_aligned:
return bboxes1.new(batch_shape + (rows,))
else:
return bboxes1.new(batch_shape + (rows, cols))
area1 = (bboxes1[..., 2] - bboxes1[..., 0]) * (
bboxes1[..., 3] - bboxes1[..., 1])
area2 = (bboxes2[..., 2] - bboxes2[..., 0]) * (
bboxes2[..., 3] - bboxes2[..., 1])
if is_aligned:
lt = torch.max(bboxes1[..., :2], bboxes2[..., :2]) # [B, rows, 2]
rb = torch.min(bboxes1[..., 2:], bboxes2[..., 2:]) # [B, rows, 2]
wh = fp16_clamp(rb - lt, min=0)
overlap = wh[..., 0] * wh[..., 1]
if mode in ['iou', 'giou']:
union = area1 + area2 - overlap
else:
union = area1
if mode == 'giou':
enclosed_lt = torch.min(bboxes1[..., :2], bboxes2[..., :2])
enclosed_rb = torch.max(bboxes1[..., 2:], bboxes2[..., 2:])
else:
lt = torch.max(bboxes1[..., :, None, :2],
bboxes2[..., None, :, :2]) # [B, rows, cols, 2]
rb = torch.min(bboxes1[..., :, None, 2:],
bboxes2[..., None, :, 2:]) # [B, rows, cols, 2]
wh = fp16_clamp(rb - lt, min=0)
overlap = wh[..., 0] * wh[..., 1]
if mode in ['iou', 'giou']:
union = area1[..., None] + area2[..., None, :] - overlap
else:
union = area1[..., None]
if mode == 'giou':
enclosed_lt = torch.min(bboxes1[..., :, None, :2],
bboxes2[..., None, :, :2])
enclosed_rb = torch.max(bboxes1[..., :, None, 2:],
bboxes2[..., None, :, 2:])
eps = union.new_tensor([eps])
union = torch.max(union, eps)
ious = overlap / union
if mode in ['iou', 'iof']:
return ious
# calculate gious
enclose_wh = fp16_clamp(enclosed_rb - enclosed_lt, min=0)
enclose_area = enclose_wh[..., 0] * enclose_wh[..., 1]
enclose_area = torch.max(enclose_area, eps)
gious = ious - (enclose_area - union) / enclose_area
return gious
@builder.IOU_CALCULATORS.register_module()
class BoxOverlaps2D:
def __init__(self, scale=1., dtype=None):
self.scale = scale
self.dtype = dtype
def __call__(self, bboxes1, bboxes2, mode='iou', is_aligned=False):
assert bboxes1.size(-1) in [0, 4, 5]
assert bboxes2.size(-1) in [0, 4, 5]
if bboxes2.size(-1) == 5:
bboxes2 = bboxes2[..., :4]
if bboxes1.size(-1) == 5:
bboxes1 = bboxes1[..., :4]
if self.dtype == 'fp16':
# change tensor type to save cpu and cuda memory and keep speed
bboxes1 = cast_tensor_type(bboxes1, self.scale, self.dtype)
bboxes2 = cast_tensor_type(bboxes2, self.scale, self.dtype)
overlaps = bbox_overlaps(bboxes1, bboxes2, mode, is_aligned)
if not overlaps.is_cuda and overlaps.dtype == torch.float16:
# resume cpu float32
overlaps = overlaps.float()
return overlaps
return bbox_overlaps(bboxes1, bboxes2, mode, is_aligned)
def __repr__(self):
"""str: a string describing the module"""
repr_str = self.__class__.__name__ + f'(' \
f'scale={self.scale}, dtype={self.dtype})'
return repr_str
class SamplingResult(util.NiceRepr):
def __init__(self, pos_inds, neg_inds, bboxes, gt_bboxes, assign_result,
gt_flags):
self.pos_inds = pos_inds
self.neg_inds = neg_inds
self.pos_bboxes = bboxes[pos_inds]
self.neg_bboxes = bboxes[neg_inds]
self.pos_is_gt = gt_flags[pos_inds]
self.num_gts = gt_bboxes.shape[0]
self.pos_assigned_gt_inds = assign_result.gt_inds[pos_inds] - 1
if gt_bboxes.numel() == 0:
# hack for index error case
assert self.pos_assigned_gt_inds.numel() == 0
self.pos_gt_bboxes = torch.empty_like(gt_bboxes).view(-1, 4)
else:
if len(gt_bboxes.shape) < 2:
gt_bboxes = gt_bboxes.view(-1, 4)
self.pos_gt_bboxes = gt_bboxes[self.pos_assigned_gt_inds, :]
if assign_result.labels is not None:
self.pos_gt_labels = assign_result.labels[pos_inds]
else:
self.pos_gt_labels = None
@property
def bboxes(self):
"""torch.Tensor: concatenated positive and negative boxes"""
return torch.cat([self.pos_bboxes, self.neg_bboxes])
def to(self, device):
_dict = self.__dict__
for key, value in _dict.items():
if isinstance(value, torch.Tensor):
_dict[key] = value.to(device)
return self
def __nice__(self):
data = self.info.copy()
data['pos_bboxes'] = data.pop('pos_bboxes').shape
data['neg_bboxes'] = data.pop('neg_bboxes').shape
parts = [f"'{k}': {v!r}" for k, v in sorted(data.items())]
body = ' ' + ',\n '.join(parts)
return '{\n' + body + '\n}'
@property
def info(self):
"""Returns a dictionary of info about the object."""
return {
'pos_inds': self.pos_inds,
'neg_inds': self.neg_inds,
'pos_bboxes': self.pos_bboxes,
'neg_bboxes': self.neg_bboxes,
'pos_is_gt': self.pos_is_gt,
'num_gts': self.num_gts,
'pos_assigned_gt_inds': self.pos_assigned_gt_inds,
}
@classmethod
def random(cls, rng=None, **kwargs):
from mmdet.core.util import ensure_rng
rng = ensure_rng(rng)
# make probabalistic?
num = 32
pos_fraction = 0.5
neg_pos_ub = -1
assign_result = AssignResult.random(rng=rng, **kwargs)
# Note we could just compute an assignment
bboxes = util.random_boxes(assign_result.num_preds, rng=rng)
gt_bboxes = util.random_boxes(assign_result.num_gts, rng=rng)
if rng.rand() > 0.2:
# sometimes algorithms squeeze their data, be robust to that
gt_bboxes = gt_bboxes.squeeze()
bboxes = bboxes.squeeze()
if assign_result.labels is None:
gt_labels = None
else:
gt_labels = None # todo
if gt_labels is None:
add_gt_as_proposals = False
else:
add_gt_as_proposals = True # make probabalistic?
sampler = RandomSampler(
num,
pos_fraction,
neg_pos_ub=neg_pos_ub,
add_gt_as_proposals=add_gt_as_proposals,
rng=rng)
self = sampler.sample(assign_result, bboxes, gt_bboxes, gt_labels)
return self
@builder.BBOX_SAMPLERS.register_module()
class RandomSampler:
def __init__(self,
num,
pos_fraction,
neg_pos_ub=-1,
add_gt_as_proposals=True,
**kwargs):
self.num = num
self.pos_fraction = pos_fraction
self.neg_pos_ub = neg_pos_ub
self.add_gt_as_proposals = add_gt_as_proposals
self.pos_sampler = self
self.neg_sampler = self
from mmdet.core.util import ensure_rng
super().__init__()
self.rng = ensure_rng(kwargs.get('rng', None))
def sample(self,
assign_result,
bboxes,
gt_bboxes,
gt_labels=None,
**kwargs):
if len(bboxes.shape) < 2:
bboxes = bboxes[None, :]
bboxes = bboxes[:, :4]
gt_flags = bboxes.new_zeros((bboxes.shape[0],), dtype=torch.uint8)
if self.add_gt_as_proposals and len(gt_bboxes) > 0:
if gt_labels is None:
raise ValueError('gt_labels must be given when add_gt_as_proposals is True')
bboxes = torch.cat([gt_bboxes, bboxes], dim=0)
assign_result.add_gt_(gt_labels)
gt_ones = bboxes.new_ones(gt_bboxes.shape[0], dtype=torch.uint8)
gt_flags = torch.cat([gt_ones, gt_flags])
num_expected_pos = int(self.num * self.pos_fraction)
pos_inds = self.pos_sampler._sample_pos(assign_result, num_expected_pos, bboxes=bboxes, **kwargs)
# We found that sampled indices have duplicated items occasionally.
# (may be a bug of PyTorch)
pos_inds = pos_inds.unique()
num_sampled_pos = pos_inds.numel()
num_expected_neg = self.num - num_sampled_pos
if self.neg_pos_ub >= 0:
_pos = max(1, num_sampled_pos)
neg_upper_bound = int(self.neg_pos_ub * _pos)
if num_expected_neg > neg_upper_bound:
num_expected_neg = neg_upper_bound
neg_inds = self.neg_sampler._sample_neg(
assign_result, num_expected_neg, bboxes=bboxes, **kwargs)
neg_inds = neg_inds.unique()
sampling_result = SamplingResult(pos_inds, neg_inds, bboxes, gt_bboxes,
assign_result, gt_flags)
return sampling_result
def random_choice(self, gallery, num):
assert len(gallery) >= num
is_tensor = isinstance(gallery, torch.Tensor)
if not is_tensor:
if torch.cuda.is_available():
device = torch.cuda.current_device()
else:
device = 'cpu'
gallery = torch.tensor(gallery, dtype=torch.long, device=device)
perm = torch.randperm(gallery.numel())[:num].to(device=gallery.device)
rand_inds = gallery[perm]
if not is_tensor:
rand_inds = rand_inds.cpu().numpy()
return rand_inds
def _sample_pos(self, assign_result, num_expected, **kwargs):
pos_inds = torch.nonzero(assign_result.gt_inds > 0, as_tuple=False)
if pos_inds.numel() != 0:
pos_inds = pos_inds.squeeze(1)
if pos_inds.numel() <= num_expected:
return pos_inds
else:
return self.random_choice(pos_inds, num_expected)
def _sample_neg(self, assign_result, num_expected, **kwargs):
neg_inds = torch.nonzero(assign_result.gt_inds == 0, as_tuple=False)
if neg_inds.numel() != 0:
neg_inds = neg_inds.squeeze(1)
if len(neg_inds) <= num_expected:
return neg_inds
else:
return self.random_choice(neg_inds, num_expected)
| <filename>mmdet/core/box.py
import mmcv
import numpy as np
import torch
from mmdet.core import builder, util
class AssignResult(util.NiceRepr):
def __init__(self, num_gts, gt_inds, max_overlaps, labels=None):
self.num_gts = num_gts
self.gt_inds = gt_inds
self.max_overlaps = max_overlaps
self.labels = labels
# Interface for possible user-defined properties
self._extra_properties = {}
@property
def num_preds(self):
"""int: the number of predictions in this assignment"""
return len(self.gt_inds)
def set_extra_property(self, key, value):
"""Set user-defined new property."""
assert key not in self.info
self._extra_properties[key] = value
def get_extra_property(self, key):
"""Get user-defined property."""
return self._extra_properties.get(key, None)
@property
def info(self):
"""dict: a dictionary of info about the object"""
basic_info = {
'num_gts': self.num_gts,
'num_preds': self.num_preds,
'gt_inds': self.gt_inds,
'max_overlaps': self.max_overlaps,
'labels': self.labels,
}
basic_info.update(self._extra_properties)
return basic_info
def __nice__(self):
"""str: a "nice" summary string describing this assign result"""
parts = []
parts.append(f'num_gts={self.num_gts!r}')
if self.gt_inds is None:
parts.append(f'gt_inds={self.gt_inds!r}')
else:
parts.append(f'gt_inds.shape={tuple(self.gt_inds.shape)!r}')
if self.max_overlaps is None:
parts.append(f'max_overlaps={self.max_overlaps!r}')
else:
parts.append('max_overlaps.shape='
f'{tuple(self.max_overlaps.shape)!r}')
if self.labels is None:
parts.append(f'labels={self.labels!r}')
else:
parts.append(f'labels.shape={tuple(self.labels.shape)!r}')
return ', '.join(parts)
@classmethod
def random(cls, **kwargs):
from mmdet.core.util import ensure_rng
rng = ensure_rng(kwargs.get('rng', None))
num_gts = kwargs.get('num_gts', None)
num_preds = kwargs.get('num_preds', None)
p_ignore = kwargs.get('p_ignore', 0.3)
p_assigned = kwargs.get('p_assigned', 0.7)
p_use_label = kwargs.get('p_use_label', 0.5)
num_classes = kwargs.get('p_use_label', 3)
if num_gts is None:
num_gts = rng.randint(0, 8)
if num_preds is None:
num_preds = rng.randint(0, 16)
if num_gts == 0:
max_overlaps = torch.zeros(num_preds, dtype=torch.float32)
gt_inds = torch.zeros(num_preds, dtype=torch.int64)
if p_use_label is True or p_use_label < rng.rand():
labels = torch.zeros(num_preds, dtype=torch.int64)
else:
labels = None
else:
import numpy as np
# Create an overlap for each predicted box
max_overlaps = torch.from_numpy(rng.rand(num_preds))
# Construct gt_inds for each predicted box
is_assigned = torch.from_numpy(rng.rand(num_preds) < p_assigned)
# maximum number of assignments constraints
n_assigned = min(num_preds, min(num_gts, is_assigned.sum()))
assigned_idxs = np.where(is_assigned)[0]
rng.shuffle(assigned_idxs)
assigned_idxs = assigned_idxs[0:n_assigned]
assigned_idxs.sort()
is_assigned[:] = 0
is_assigned[assigned_idxs] = True
is_ignore = torch.from_numpy(
rng.rand(num_preds) < p_ignore) & is_assigned
gt_inds = torch.zeros(num_preds, dtype=torch.int64)
true_idxs = np.arange(num_gts)
rng.shuffle(true_idxs)
true_idxs = torch.from_numpy(true_idxs)
gt_inds[is_assigned] = true_idxs[:n_assigned]
gt_inds = torch.from_numpy(
rng.randint(1, num_gts + 1, size=num_preds))
gt_inds[is_ignore] = -1
gt_inds[~is_assigned] = 0
max_overlaps[~is_assigned] = 0
if p_use_label is True or p_use_label < rng.rand():
if num_classes == 0:
labels = torch.zeros(num_preds, dtype=torch.int64)
else:
labels = torch.from_numpy(
# remind that we set FG labels to [0, num_class-1]
# since mmdet v2.0
# BG cat_id: num_class
rng.randint(0, num_classes, size=num_preds))
labels[~is_assigned] = 0
else:
labels = None
self = cls(num_gts, gt_inds, max_overlaps, labels)
return self
def add_gt_(self, gt_labels):
"""Add ground truth as assigned results.
Args:
gt_labels (torch.Tensor): Labels of gt boxes
"""
self_inds = torch.arange(
1, len(gt_labels) + 1, dtype=torch.long, device=gt_labels.device)
self.gt_inds = torch.cat([self_inds, self.gt_inds])
self.max_overlaps = torch.cat(
[self.max_overlaps.new_ones(len(gt_labels)), self.max_overlaps])
if self.labels is not None:
self.labels = torch.cat([gt_labels, self.labels])
@builder.BBOX_ASSIGNERS.register_module()
class MaxIoUAssigner:
def __init__(self,
pos_iou_thr,
neg_iou_thr,
min_pos_iou=.0,
gt_max_assign_all=True,
ignore_iof_thr=-1,
ignore_wrt_candidates=True,
match_low_quality=True,
gpu_assign_thr=-1,
iou_calculator=dict(type='BoxOverlaps2D')):
self.pos_iou_thr = pos_iou_thr
self.neg_iou_thr = neg_iou_thr
self.min_pos_iou = min_pos_iou
self.gt_max_assign_all = gt_max_assign_all
self.ignore_iof_thr = ignore_iof_thr
self.ignore_wrt_candidates = ignore_wrt_candidates
self.gpu_assign_thr = gpu_assign_thr
self.match_low_quality = match_low_quality
self.iou_calculator = builder.build_iou_calculator(iou_calculator)
def assign(self, bboxes, gt_bboxes, gt_bboxes_ignore=None, gt_labels=None):
assign_on_cpu = True if (self.gpu_assign_thr > 0) and (gt_bboxes.shape[0] > self.gpu_assign_thr) else False
# compute overlap and assign gt on CPU when number of GT is large
if assign_on_cpu:
device = bboxes.device
bboxes = bboxes.cpu()
gt_bboxes = gt_bboxes.cpu()
if gt_bboxes_ignore is not None:
gt_bboxes_ignore = gt_bboxes_ignore.cpu()
if gt_labels is not None:
gt_labels = gt_labels.cpu()
overlaps = self.iou_calculator(gt_bboxes, bboxes)
if (self.ignore_iof_thr > 0 and gt_bboxes_ignore is not None
and gt_bboxes_ignore.numel() > 0 and bboxes.numel() > 0):
if self.ignore_wrt_candidates:
ignore_overlaps = self.iou_calculator(
bboxes, gt_bboxes_ignore, mode='iof')
ignore_max_overlaps, _ = ignore_overlaps.max(dim=1)
else:
ignore_overlaps = self.iou_calculator(
gt_bboxes_ignore, bboxes, mode='iof')
ignore_max_overlaps, _ = ignore_overlaps.max(dim=0)
overlaps[:, ignore_max_overlaps > self.ignore_iof_thr] = -1
assign_result = self.assign_wrt_overlaps(overlaps, gt_labels)
if assign_on_cpu:
assign_result.gt_inds = assign_result.gt_inds.to(device)
assign_result.max_overlaps = assign_result.max_overlaps.to(device)
if assign_result.labels is not None:
assign_result.labels = assign_result.labels.to(device)
return assign_result
def assign_wrt_overlaps(self, overlaps, gt_labels=None):
num_gts, num_bboxes = overlaps.size(0), overlaps.size(1)
# 1. assign -1 by default
assigned_gt_inds = overlaps.new_full((num_bboxes,), -1, dtype=torch.long)
if num_gts == 0 or num_bboxes == 0:
# No ground truth or boxes, return empty assignment
max_overlaps = overlaps.new_zeros((num_bboxes,))
if num_gts == 0:
# No truth, assign everything to background
assigned_gt_inds[:] = 0
if gt_labels is None:
assigned_labels = None
else:
assigned_labels = overlaps.new_full((num_bboxes,), -1, dtype=torch.long)
return AssignResult(num_gts,
assigned_gt_inds,
max_overlaps,
labels=assigned_labels)
# for each anchor, which gt best overlaps with it
# for each anchor, the max iou of all gts
max_overlaps, argmax_overlaps = overlaps.max(dim=0)
# for each gt, which anchor best overlaps with it
# for each gt, the max iou of all proposals
gt_max_overlaps, gt_argmax_overlaps = overlaps.max(dim=1)
# 2. assign negative: below
# the negative inds are set to be 0
if isinstance(self.neg_iou_thr, float):
assigned_gt_inds[(max_overlaps >= 0) & (max_overlaps < self.neg_iou_thr)] = 0
elif isinstance(self.neg_iou_thr, tuple):
assert len(self.neg_iou_thr) == 2
assigned_gt_inds[(max_overlaps >= self.neg_iou_thr[0]) & (max_overlaps < self.neg_iou_thr[1])] = 0
# 3. assign positive: above positive IoU threshold
pos_inds = max_overlaps >= self.pos_iou_thr
assigned_gt_inds[pos_inds] = argmax_overlaps[pos_inds] + 1
if self.match_low_quality:
for i in range(num_gts):
if gt_max_overlaps[i] >= self.min_pos_iou:
if self.gt_max_assign_all:
max_iou_inds = overlaps[i, :] == gt_max_overlaps[i]
assigned_gt_inds[max_iou_inds] = i + 1
else:
assigned_gt_inds[gt_argmax_overlaps[i]] = i + 1
if gt_labels is not None:
assigned_labels = assigned_gt_inds.new_full((num_bboxes,), -1)
pos_inds = torch.nonzero(assigned_gt_inds > 0, as_tuple=False).squeeze()
if pos_inds.numel() > 0:
assigned_labels[pos_inds] = gt_labels[assigned_gt_inds[pos_inds] - 1]
else:
assigned_labels = None
return AssignResult(num_gts, assigned_gt_inds, max_overlaps, labels=assigned_labels)
@mmcv.jit(coderize=True)
def bbox2delta(proposals, gt, means=(0., 0., 0., 0.), stds=(1., 1., 1., 1.)):
assert proposals.size() == gt.size()
proposals = proposals.float()
gt = gt.float()
px = (proposals[..., 0] + proposals[..., 2]) * 0.5
py = (proposals[..., 1] + proposals[..., 3]) * 0.5
pw = proposals[..., 2] - proposals[..., 0]
ph = proposals[..., 3] - proposals[..., 1]
gx = (gt[..., 0] + gt[..., 2]) * 0.5
gy = (gt[..., 1] + gt[..., 3]) * 0.5
gw = gt[..., 2] - gt[..., 0]
gh = gt[..., 3] - gt[..., 1]
dx = (gx - px) / pw
dy = (gy - py) / ph
dw = torch.log(gw / pw)
dh = torch.log(gh / ph)
deltas = torch.stack([dx, dy, dw, dh], dim=-1)
means = deltas.new_tensor(means).unsqueeze(0)
stds = deltas.new_tensor(stds).unsqueeze(0)
deltas = deltas.sub_(means).div_(stds)
return deltas
@mmcv.jit(coderize=True)
def delta2bbox(rois,
deltas,
means=(0., 0., 0., 0.),
stds=(1., 1., 1., 1.),
max_shape=None,
wh_ratio_clip=16 / 1000,
clip_border=True,
add_ctr_clamp=False,
ctr_clamp=32):
means = deltas.new_tensor(means).view(1,
-1).repeat(1,
deltas.size(-1) // 4)
stds = deltas.new_tensor(stds).view(1, -1).repeat(1, deltas.size(-1) // 4)
denorm_deltas = deltas * stds + means
dx = denorm_deltas[..., 0::4]
dy = denorm_deltas[..., 1::4]
dw = denorm_deltas[..., 2::4]
dh = denorm_deltas[..., 3::4]
x1, y1 = rois[..., 0], rois[..., 1]
x2, y2 = rois[..., 2], rois[..., 3]
# Compute center of each roi
px = ((x1 + x2) * 0.5).unsqueeze(-1).expand_as(dx)
py = ((y1 + y2) * 0.5).unsqueeze(-1).expand_as(dy)
# Compute width/height of each roi
pw = (x2 - x1).unsqueeze(-1).expand_as(dw)
ph = (y2 - y1).unsqueeze(-1).expand_as(dh)
dx_width = pw * dx
dy_height = ph * dy
max_ratio = np.abs(np.log(wh_ratio_clip))
if add_ctr_clamp:
dx_width = torch.clamp(dx_width, max=ctr_clamp, min=-ctr_clamp)
dy_height = torch.clamp(dy_height, max=ctr_clamp, min=-ctr_clamp)
dw = torch.clamp(dw, max=max_ratio)
dh = torch.clamp(dh, max=max_ratio)
else:
dw = dw.clamp(min=-max_ratio, max=max_ratio)
dh = dh.clamp(min=-max_ratio, max=max_ratio)
# Use exp(network energy) to enlarge/shrink each roi
gw = pw * dw.exp()
gh = ph * dh.exp()
# Use network energy to shift the center of each roi
gx = px + dx_width
gy = py + dy_height
# Convert center-xy/width/height to top-left, bottom-right
x1 = gx - gw * 0.5
y1 = gy - gh * 0.5
x2 = gx + gw * 0.5
y2 = gy + gh * 0.5
bboxes = torch.stack([x1, y1, x2, y2], dim=-1).view(deltas.size())
if clip_border and max_shape is not None:
if not isinstance(max_shape, torch.Tensor):
max_shape = x1.new_tensor(max_shape)
max_shape = max_shape[..., :2].type_as(x1)
if max_shape.ndim == 2:
assert bboxes.ndim == 3
assert max_shape.size(0) == bboxes.size(0)
min_xy = x1.new_tensor(0)
max_xy = torch.cat(
[max_shape] * (deltas.size(-1) // 2),
dim=-1).flip(-1).unsqueeze(-2)
bboxes = torch.where(bboxes < min_xy, min_xy, bboxes)
bboxes = torch.where(bboxes > max_xy, max_xy, bboxes)
return bboxes
@builder.BBOX_CODERS.register_module()
class DeltaXYWHBBoxCoder:
def __init__(self,
target_means=(0., 0., 0., 0.),
target_stds=(1., 1., 1., 1.),
clip_border=True,
add_ctr_clamp=False,
ctr_clamp=32):
super().__init__()
self.means = target_means
self.stds = target_stds
self.clip_border = clip_border
self.add_ctr_clamp = add_ctr_clamp
self.ctr_clamp = ctr_clamp
def encode(self, bboxes, gt_bboxes):
"""Get box regression transformation deltas that can be used to
transform the ``bboxes`` into the ``gt_bboxes``.
Args:
bboxes (torch.Tensor): Source boxes, e.g., object proposals.
gt_bboxes (torch.Tensor): Target of the transformation, e.g.,
ground-truth boxes.
Returns:
torch.Tensor: Box transformation deltas
"""
assert bboxes.size(0) == gt_bboxes.size(0)
assert bboxes.size(-1) == gt_bboxes.size(-1) == 4
encoded_bboxes = bbox2delta(bboxes, gt_bboxes, self.means, self.stds)
return encoded_bboxes
def decode(self,
bboxes,
pred_bboxes,
max_shape=None,
wh_ratio_clip=16 / 1000):
"""Apply transformation `pred_bboxes` to `boxes`.
Args:
bboxes (torch.Tensor): Basic boxes. Shape (B, N, 4) or (N, 4)
pred_bboxes (Tensor): Encoded offsets with respect to each roi.
Has shape (B, N, num_classes * 4) or (B, N, 4) or
(N, num_classes * 4) or (N, 4). Note N = num_anchors * W * H
when rois is a grid of anchors.Offset encoding follows [1]_.
max_shape (Sequence[int] or torch.Tensor or Sequence[
Sequence[int]],optional): Maximum bounds for boxes, specifies
(H, W, C) or (H, W). If bboxes shape is (B, N, 4), then
the max_shape should be a Sequence[Sequence[int]]
and the length of max_shape should also be B.
wh_ratio_clip (float, optional): The allowed ratio between
width and height.
Returns:
torch.Tensor: Decoded boxes.
"""
assert pred_bboxes.size(0) == bboxes.size(0)
if pred_bboxes.ndim == 3:
assert pred_bboxes.size(1) == bboxes.size(1)
decoded_bboxes = delta2bbox(bboxes, pred_bboxes, self.means, self.stds,
max_shape, wh_ratio_clip, self.clip_border,
self.add_ctr_clamp, self.ctr_clamp)
return decoded_bboxes
def cast_tensor_type(x, scale=1., dtype=None):
if dtype == 'fp16':
# scale is for preventing overflows
x = (x / scale).half()
return x
def fp16_clamp(x, min=None, max=None):
if not x.is_cuda and x.dtype == torch.float16:
# clamp for cpu float16, tensor fp16 has no clamp implementation
return x.float().clamp(min, max).half()
return x.clamp(min, max)
def bbox_overlaps(bboxes1, bboxes2, mode='iou', is_aligned=False, eps=1e-6):
assert mode in ['iou', 'iof', 'giou'], f'Unsupported mode {mode}'
# Either the boxes are empty or the length of boxes' last dimension is 4
assert (bboxes1.size(-1) == 4 or bboxes1.size(0) == 0)
assert (bboxes2.size(-1) == 4 or bboxes2.size(0) == 0)
# Batch dim must be the same
# Batch dim: (B1, B2, ... Bn)
assert bboxes1.shape[:-2] == bboxes2.shape[:-2]
batch_shape = bboxes1.shape[:-2]
rows = bboxes1.size(-2)
cols = bboxes2.size(-2)
if is_aligned:
assert rows == cols
if rows * cols == 0:
if is_aligned:
return bboxes1.new(batch_shape + (rows,))
else:
return bboxes1.new(batch_shape + (rows, cols))
area1 = (bboxes1[..., 2] - bboxes1[..., 0]) * (
bboxes1[..., 3] - bboxes1[..., 1])
area2 = (bboxes2[..., 2] - bboxes2[..., 0]) * (
bboxes2[..., 3] - bboxes2[..., 1])
if is_aligned:
lt = torch.max(bboxes1[..., :2], bboxes2[..., :2]) # [B, rows, 2]
rb = torch.min(bboxes1[..., 2:], bboxes2[..., 2:]) # [B, rows, 2]
wh = fp16_clamp(rb - lt, min=0)
overlap = wh[..., 0] * wh[..., 1]
if mode in ['iou', 'giou']:
union = area1 + area2 - overlap
else:
union = area1
if mode == 'giou':
enclosed_lt = torch.min(bboxes1[..., :2], bboxes2[..., :2])
enclosed_rb = torch.max(bboxes1[..., 2:], bboxes2[..., 2:])
else:
lt = torch.max(bboxes1[..., :, None, :2],
bboxes2[..., None, :, :2]) # [B, rows, cols, 2]
rb = torch.min(bboxes1[..., :, None, 2:],
bboxes2[..., None, :, 2:]) # [B, rows, cols, 2]
wh = fp16_clamp(rb - lt, min=0)
overlap = wh[..., 0] * wh[..., 1]
if mode in ['iou', 'giou']:
union = area1[..., None] + area2[..., None, :] - overlap
else:
union = area1[..., None]
if mode == 'giou':
enclosed_lt = torch.min(bboxes1[..., :, None, :2],
bboxes2[..., None, :, :2])
enclosed_rb = torch.max(bboxes1[..., :, None, 2:],
bboxes2[..., None, :, 2:])
eps = union.new_tensor([eps])
union = torch.max(union, eps)
ious = overlap / union
if mode in ['iou', 'iof']:
return ious
# calculate gious
enclose_wh = fp16_clamp(enclosed_rb - enclosed_lt, min=0)
enclose_area = enclose_wh[..., 0] * enclose_wh[..., 1]
enclose_area = torch.max(enclose_area, eps)
gious = ious - (enclose_area - union) / enclose_area
return gious
@builder.IOU_CALCULATORS.register_module()
class BoxOverlaps2D:
def __init__(self, scale=1., dtype=None):
self.scale = scale
self.dtype = dtype
def __call__(self, bboxes1, bboxes2, mode='iou', is_aligned=False):
assert bboxes1.size(-1) in [0, 4, 5]
assert bboxes2.size(-1) in [0, 4, 5]
if bboxes2.size(-1) == 5:
bboxes2 = bboxes2[..., :4]
if bboxes1.size(-1) == 5:
bboxes1 = bboxes1[..., :4]
if self.dtype == 'fp16':
# change tensor type to save cpu and cuda memory and keep speed
bboxes1 = cast_tensor_type(bboxes1, self.scale, self.dtype)
bboxes2 = cast_tensor_type(bboxes2, self.scale, self.dtype)
overlaps = bbox_overlaps(bboxes1, bboxes2, mode, is_aligned)
if not overlaps.is_cuda and overlaps.dtype == torch.float16:
# resume cpu float32
overlaps = overlaps.float()
return overlaps
return bbox_overlaps(bboxes1, bboxes2, mode, is_aligned)
def __repr__(self):
"""str: a string describing the module"""
repr_str = self.__class__.__name__ + f'(' \
f'scale={self.scale}, dtype={self.dtype})'
return repr_str
class SamplingResult(util.NiceRepr):
def __init__(self, pos_inds, neg_inds, bboxes, gt_bboxes, assign_result,
gt_flags):
self.pos_inds = pos_inds
self.neg_inds = neg_inds
self.pos_bboxes = bboxes[pos_inds]
self.neg_bboxes = bboxes[neg_inds]
self.pos_is_gt = gt_flags[pos_inds]
self.num_gts = gt_bboxes.shape[0]
self.pos_assigned_gt_inds = assign_result.gt_inds[pos_inds] - 1
if gt_bboxes.numel() == 0:
# hack for index error case
assert self.pos_assigned_gt_inds.numel() == 0
self.pos_gt_bboxes = torch.empty_like(gt_bboxes).view(-1, 4)
else:
if len(gt_bboxes.shape) < 2:
gt_bboxes = gt_bboxes.view(-1, 4)
self.pos_gt_bboxes = gt_bboxes[self.pos_assigned_gt_inds, :]
if assign_result.labels is not None:
self.pos_gt_labels = assign_result.labels[pos_inds]
else:
self.pos_gt_labels = None
@property
def bboxes(self):
"""torch.Tensor: concatenated positive and negative boxes"""
return torch.cat([self.pos_bboxes, self.neg_bboxes])
def to(self, device):
_dict = self.__dict__
for key, value in _dict.items():
if isinstance(value, torch.Tensor):
_dict[key] = value.to(device)
return self
def __nice__(self):
data = self.info.copy()
data['pos_bboxes'] = data.pop('pos_bboxes').shape
data['neg_bboxes'] = data.pop('neg_bboxes').shape
parts = [f"'{k}': {v!r}" for k, v in sorted(data.items())]
body = ' ' + ',\n '.join(parts)
return '{\n' + body + '\n}'
@property
def info(self):
"""Returns a dictionary of info about the object."""
return {
'pos_inds': self.pos_inds,
'neg_inds': self.neg_inds,
'pos_bboxes': self.pos_bboxes,
'neg_bboxes': self.neg_bboxes,
'pos_is_gt': self.pos_is_gt,
'num_gts': self.num_gts,
'pos_assigned_gt_inds': self.pos_assigned_gt_inds,
}
@classmethod
def random(cls, rng=None, **kwargs):
from mmdet.core.util import ensure_rng
rng = ensure_rng(rng)
# make probabalistic?
num = 32
pos_fraction = 0.5
neg_pos_ub = -1
assign_result = AssignResult.random(rng=rng, **kwargs)
# Note we could just compute an assignment
bboxes = util.random_boxes(assign_result.num_preds, rng=rng)
gt_bboxes = util.random_boxes(assign_result.num_gts, rng=rng)
if rng.rand() > 0.2:
# sometimes algorithms squeeze their data, be robust to that
gt_bboxes = gt_bboxes.squeeze()
bboxes = bboxes.squeeze()
if assign_result.labels is None:
gt_labels = None
else:
gt_labels = None # todo
if gt_labels is None:
add_gt_as_proposals = False
else:
add_gt_as_proposals = True # make probabalistic?
sampler = RandomSampler(
num,
pos_fraction,
neg_pos_ub=neg_pos_ub,
add_gt_as_proposals=add_gt_as_proposals,
rng=rng)
self = sampler.sample(assign_result, bboxes, gt_bboxes, gt_labels)
return self
@builder.BBOX_SAMPLERS.register_module()
class RandomSampler:
def __init__(self,
num,
pos_fraction,
neg_pos_ub=-1,
add_gt_as_proposals=True,
**kwargs):
self.num = num
self.pos_fraction = pos_fraction
self.neg_pos_ub = neg_pos_ub
self.add_gt_as_proposals = add_gt_as_proposals
self.pos_sampler = self
self.neg_sampler = self
from mmdet.core.util import ensure_rng
super().__init__()
self.rng = ensure_rng(kwargs.get('rng', None))
def sample(self,
assign_result,
bboxes,
gt_bboxes,
gt_labels=None,
**kwargs):
if len(bboxes.shape) < 2:
bboxes = bboxes[None, :]
bboxes = bboxes[:, :4]
gt_flags = bboxes.new_zeros((bboxes.shape[0],), dtype=torch.uint8)
if self.add_gt_as_proposals and len(gt_bboxes) > 0:
if gt_labels is None:
raise ValueError('gt_labels must be given when add_gt_as_proposals is True')
bboxes = torch.cat([gt_bboxes, bboxes], dim=0)
assign_result.add_gt_(gt_labels)
gt_ones = bboxes.new_ones(gt_bboxes.shape[0], dtype=torch.uint8)
gt_flags = torch.cat([gt_ones, gt_flags])
num_expected_pos = int(self.num * self.pos_fraction)
pos_inds = self.pos_sampler._sample_pos(assign_result, num_expected_pos, bboxes=bboxes, **kwargs)
# We found that sampled indices have duplicated items occasionally.
# (may be a bug of PyTorch)
pos_inds = pos_inds.unique()
num_sampled_pos = pos_inds.numel()
num_expected_neg = self.num - num_sampled_pos
if self.neg_pos_ub >= 0:
_pos = max(1, num_sampled_pos)
neg_upper_bound = int(self.neg_pos_ub * _pos)
if num_expected_neg > neg_upper_bound:
num_expected_neg = neg_upper_bound
neg_inds = self.neg_sampler._sample_neg(
assign_result, num_expected_neg, bboxes=bboxes, **kwargs)
neg_inds = neg_inds.unique()
sampling_result = SamplingResult(pos_inds, neg_inds, bboxes, gt_bboxes,
assign_result, gt_flags)
return sampling_result
def random_choice(self, gallery, num):
assert len(gallery) >= num
is_tensor = isinstance(gallery, torch.Tensor)
if not is_tensor:
if torch.cuda.is_available():
device = torch.cuda.current_device()
else:
device = 'cpu'
gallery = torch.tensor(gallery, dtype=torch.long, device=device)
perm = torch.randperm(gallery.numel())[:num].to(device=gallery.device)
rand_inds = gallery[perm]
if not is_tensor:
rand_inds = rand_inds.cpu().numpy()
return rand_inds
def _sample_pos(self, assign_result, num_expected, **kwargs):
pos_inds = torch.nonzero(assign_result.gt_inds > 0, as_tuple=False)
if pos_inds.numel() != 0:
pos_inds = pos_inds.squeeze(1)
if pos_inds.numel() <= num_expected:
return pos_inds
else:
return self.random_choice(pos_inds, num_expected)
def _sample_neg(self, assign_result, num_expected, **kwargs):
neg_inds = torch.nonzero(assign_result.gt_inds == 0, as_tuple=False)
if neg_inds.numel() != 0:
neg_inds = neg_inds.squeeze(1)
if len(neg_inds) <= num_expected:
return neg_inds
else:
return self.random_choice(neg_inds, num_expected)
| en | 0.806037 | # Interface for possible user-defined properties int: the number of predictions in this assignment Set user-defined new property. Get user-defined property. dict: a dictionary of info about the object str: a "nice" summary string describing this assign result # Create an overlap for each predicted box # Construct gt_inds for each predicted box # maximum number of assignments constraints # remind that we set FG labels to [0, num_class-1] # since mmdet v2.0 # BG cat_id: num_class Add ground truth as assigned results. Args: gt_labels (torch.Tensor): Labels of gt boxes # compute overlap and assign gt on CPU when number of GT is large # 1. assign -1 by default # No ground truth or boxes, return empty assignment # No truth, assign everything to background # for each anchor, which gt best overlaps with it # for each anchor, the max iou of all gts # for each gt, which anchor best overlaps with it # for each gt, the max iou of all proposals # 2. assign negative: below # the negative inds are set to be 0 # 3. assign positive: above positive IoU threshold # Compute center of each roi # Compute width/height of each roi # Use exp(network energy) to enlarge/shrink each roi # Use network energy to shift the center of each roi # Convert center-xy/width/height to top-left, bottom-right Get box regression transformation deltas that can be used to transform the ``bboxes`` into the ``gt_bboxes``. Args: bboxes (torch.Tensor): Source boxes, e.g., object proposals. gt_bboxes (torch.Tensor): Target of the transformation, e.g., ground-truth boxes. Returns: torch.Tensor: Box transformation deltas Apply transformation `pred_bboxes` to `boxes`. Args: bboxes (torch.Tensor): Basic boxes. Shape (B, N, 4) or (N, 4) pred_bboxes (Tensor): Encoded offsets with respect to each roi. Has shape (B, N, num_classes * 4) or (B, N, 4) or (N, num_classes * 4) or (N, 4). Note N = num_anchors * W * H when rois is a grid of anchors.Offset encoding follows [1]_. max_shape (Sequence[int] or torch.Tensor or Sequence[ Sequence[int]],optional): Maximum bounds for boxes, specifies (H, W, C) or (H, W). If bboxes shape is (B, N, 4), then the max_shape should be a Sequence[Sequence[int]] and the length of max_shape should also be B. wh_ratio_clip (float, optional): The allowed ratio between width and height. Returns: torch.Tensor: Decoded boxes. # scale is for preventing overflows # clamp for cpu float16, tensor fp16 has no clamp implementation # Either the boxes are empty or the length of boxes' last dimension is 4 # Batch dim must be the same # Batch dim: (B1, B2, ... Bn) # [B, rows, 2] # [B, rows, 2] # [B, rows, cols, 2] # [B, rows, cols, 2] # calculate gious # change tensor type to save cpu and cuda memory and keep speed # resume cpu float32 str: a string describing the module # hack for index error case torch.Tensor: concatenated positive and negative boxes Returns a dictionary of info about the object. # make probabalistic? # Note we could just compute an assignment # sometimes algorithms squeeze their data, be robust to that # todo # make probabalistic? # We found that sampled indices have duplicated items occasionally. # (may be a bug of PyTorch) | 2.209552 | 2 |
django_settings_yaml/__init__.py | kylegibson/django_settings_yaml | 3 | 6618893 | <reponame>kylegibson/django_settings_yaml
__version__ = "unknown"
try:
from version import __version__
except ImportError:
pass
import sys
import yaml
import string
import os
DEFAULT_ENV_PREFIX = "DJANGO_SETTINGS_ENV_"
SECRET_KEY_FILE = "SECRET_KEY_FILE"
def load_yaml_settings(context, files):
settings = {}
for p in files:
with open(p) as fd:
t = string.Template(fd.read())
y = yaml.load(t.safe_substitute(context))
settings.update(y)
return settings
def read_write_secret_key_file(settings):
try:
with open(settings[SECRET_KEY_FILE]) as rfd:
settings["SECRET_KEY"] = rfd.read().strip()
return settings["SECRET_KEY"]
except IOError:
try:
from random import choice
settings["SECRET_KEY"] = ''.join([choice(string.letters + string.digits + string.punctuation) for i in range(50)])
with open(settings[SECRET_KEY_FILE], "w") as wfd:
wfd.write(settings["SECRET_KEY"])
except IOError:
pass
def get_settings_from_env(prefix=None, env=None):
if not env:
env = os.environ
if not prefix:
prefix = DEFAULT_ENV_PREFIX
settings = {}
for key,val in filter(lambda k: k[0].startswith(prefix), env.items()):
settings[key.replace(prefix, "")] = yaml.load(val)
return settings
def load(context, files, load_env = True, add_python_path = True):
for key, val in os.environ.items():
context["ENV_%s" % key] = val
settings = load_yaml_settings(context, files)
if add_python_path and "PYTHONPATH" in settings:
sys.path.extend([pp for pp in settings["PYTHONPATH"]])
if load_env:
settings.update(get_settings_from_env())
if "SECRET_KEY" not in settings and SECRET_KEY_FILE in settings:
read_write_secret_key_file(settings)
return settings
| __version__ = "unknown"
try:
from version import __version__
except ImportError:
pass
import sys
import yaml
import string
import os
DEFAULT_ENV_PREFIX = "DJANGO_SETTINGS_ENV_"
SECRET_KEY_FILE = "SECRET_KEY_FILE"
def load_yaml_settings(context, files):
settings = {}
for p in files:
with open(p) as fd:
t = string.Template(fd.read())
y = yaml.load(t.safe_substitute(context))
settings.update(y)
return settings
def read_write_secret_key_file(settings):
try:
with open(settings[SECRET_KEY_FILE]) as rfd:
settings["SECRET_KEY"] = rfd.read().strip()
return settings["SECRET_KEY"]
except IOError:
try:
from random import choice
settings["SECRET_KEY"] = ''.join([choice(string.letters + string.digits + string.punctuation) for i in range(50)])
with open(settings[SECRET_KEY_FILE], "w") as wfd:
wfd.write(settings["SECRET_KEY"])
except IOError:
pass
def get_settings_from_env(prefix=None, env=None):
if not env:
env = os.environ
if not prefix:
prefix = DEFAULT_ENV_PREFIX
settings = {}
for key,val in filter(lambda k: k[0].startswith(prefix), env.items()):
settings[key.replace(prefix, "")] = yaml.load(val)
return settings
def load(context, files, load_env = True, add_python_path = True):
for key, val in os.environ.items():
context["ENV_%s" % key] = val
settings = load_yaml_settings(context, files)
if add_python_path and "PYTHONPATH" in settings:
sys.path.extend([pp for pp in settings["PYTHONPATH"]])
if load_env:
settings.update(get_settings_from_env())
if "SECRET_KEY" not in settings and SECRET_KEY_FILE in settings:
read_write_secret_key_file(settings)
return settings | none | 1 | 2.168888 | 2 | |
NAS/AngleNAS/DARTS/training/train_from_scratch.py | naviocean/SimpleCVReproduction | 923 | 6618894 | import os
import sys
import numpy as np
import time
import torch
import glob
import random
import logging
import argparse
import torch.nn as nn
import genotypes
import torch.backends.cudnn as cudnn
from torch.autograd import Variable
from model import NetworkImageNet as Network
from tensorboardX import SummaryWriter
import apex
sys.path.append("../..")
from utils import *
from thop import profile
IMAGENET_TRAINING_SET_SIZE = 1281167
IMAGENET_TEST_SET_SIZE = 50000
parser = argparse.ArgumentParser("training imagenet")
parser.add_argument('--local_rank', type=int, default=None, help='local rank for distributed training')
parser.add_argument('--workers', type=int, default=32, help='number of workers to load dataset')
parser.add_argument('--batch_size', type=int, default=512, help='batch size')
parser.add_argument('--learning_rate', type=float, default=0.25, help='init learning rate')
parser.add_argument('--momentum', type=float, default=0.9, help='momentum')
parser.add_argument('--weight_decay', type=float, default=3e-5, help='weight decay')
parser.add_argument('--report_freq', type=float, default=100, help='report frequency')
parser.add_argument('--epochs', type=int, default=250, help='num of training epochs')
parser.add_argument('--init_channels', type=int, default=48, help='num of init channels')
parser.add_argument('--layers', type=int, default=14, help='total number of layers')
parser.add_argument('--auxiliary', action='store_true', default=True, help='use auxiliary tower')
parser.add_argument('--auxiliary_weight', type=float, default=0.4, help='weight for auxiliary loss')
parser.add_argument('--drop_path_prob', type=float, default=0, help='drop path probability')
parser.add_argument('--save', type=str, default='PDARTS_ABS', help='experiment name')
parser.add_argument('--seed', type=int, default=0, help='random seed')
parser.add_argument('--arch', type=str, default='PDARTS_ABS', help='which architecture to use')
parser.add_argument('--grad_clip', type=float, default=5., help='gradient clipping')
parser.add_argument('--label_smooth', type=float, default=0.1, help='label smoothing')
parser.add_argument('--lr_scheduler', type=str, default='linear', help='lr scheduler, linear or cosine')
parser.add_argument('--train_dir', type=str, default='../../data/train', help='path to training dataset')
parser.add_argument('--test_dir', type=str, default='../../data/test', help='path to test dataset')
parser.add_argument('--eval', default=False, action='store_true')
parser.add_argument('--eval-resume', type=str, default='./checkpoint.pth.tar', help='path for eval model')
args, unparsed = parser.parse_known_args()
args.save = 'eval-{}'.format(args.save)
if args.local_rank == 0 and not os.path.exists(args.save):
create_exp_dir(args.save, scripts_to_save=glob.glob('*.py'))
time.sleep(1)
log_format = '%(asctime)s %(message)s'
logging.basicConfig(stream=sys.stdout, level=logging.INFO,
format=log_format, datefmt='%m/%d %I:%M:%S %p')
fh = logging.FileHandler(os.path.join(args.save, 'log.txt'))
fh.setFormatter(logging.Formatter(log_format))
logging.getLogger().addHandler(fh)
writer = SummaryWriter(logdir=args.save)
CLASSES = 1000
per_epoch_iters = IMAGENET_TRAINING_SET_SIZE // args.batch_size
val_iters = IMAGENET_TEST_SET_SIZE // 200
# Average loss across processes for logging.
def reduce_tensor(tensor, device=0, world_size=1):
tensor = tensor.clone()
dist.reduce(tensor, device)
tensor.div_(world_size)
return tensor
class CrossEntropyLabelSmooth(nn.Module):
def __init__(self, num_classes, epsilon):
super(CrossEntropyLabelSmooth, self).__init__()
self.num_classes = num_classes
self.epsilon = epsilon
self.logsoftmax = nn.LogSoftmax(dim=1)
def forward(self, inputs, targets):
log_probs = self.logsoftmax(inputs)
targets = torch.zeros_like(log_probs).scatter_(1, targets.unsqueeze(1), 1)
targets = (1 - self.epsilon) * targets + self.epsilon / self.num_classes
loss = (-targets * log_probs).mean(0).sum()
return loss
def main():
if not torch.cuda.is_available():
logging.info('No GPU device available')
sys.exit(1)
num_gpus = torch.cuda.device_count()
args.gpu = args.local_rank % num_gpus
torch.cuda.set_device(args.gpu)
np.random.seed(args.seed)
cudnn.benchmark = True
cudnn.deterministic = True
torch.manual_seed(args.seed)
cudnn.enabled=True
torch.cuda.manual_seed(args.seed)
logging.info("args = %s", args)
logging.info("unparsed_args = %s", unparsed)
torch.distributed.init_process_group(backend='nccl', init_method='env://')
args.world_size = torch.distributed.get_world_size()
args.batch_size = args.batch_size // args.world_size
genotype = eval("genotypes.%s" % args.arch)
logging.info('---------Genotype---------')
logging.info(genotype)
logging.info('--------------------------')
model = Network(args.init_channels, CLASSES, args.layers, args.auxiliary, genotype)
model = model.cuda(args.gpu)
model = apex.parallel.DistributedDataParallel(model, delay_allreduce=True)
model_profile = Network(args.init_channels, CLASSES, args.layers, args.auxiliary, genotype)
model_profile = model_profile.cuda(args.gpu)
model_input_size_imagenet = (1, 3, 224, 224)
model_profile.drop_path_prob = 0
flops, _ = profile(model_profile, model_input_size_imagenet)
logging.info("flops = %fMB, param size = %fMB", flops, count_parameters_in_MB(model))
criterion_smooth = CrossEntropyLabelSmooth(CLASSES, args.label_smooth)
criterion_smooth = criterion_smooth.cuda()
optimizer = torch.optim.SGD(
model.parameters(),
args.learning_rate,
momentum=args.momentum,
weight_decay=args.weight_decay
)
# Prepare data
total_iters = per_epoch_iters * args.epochs
train_loader = get_train_dataloader(args.train_dir, args.batch_size, args.local_rank, total_iters)
train_dataprovider = DataIterator(train_loader)
val_loader = get_val_dataloader(args.test_dir)
val_dataprovider = DataIterator(val_loader)
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, float(args.epochs))
start_epoch = 0
best_acc_top1 = 0
best_acc_top5 = 0
checkpoint_tar = os.path.join(args.save, 'checkpoint.pth.tar')
if os.path.exists(checkpoint_tar):
logging.info('loading checkpoint {} ..........'.format(checkpoint_tar))
checkpoint = torch.load(checkpoint_tar, map_location={'cuda:0':'cuda:{}'.format(args.local_rank)})
start_epoch = checkpoint['epoch'] + 1
model.load_state_dict(checkpoint['state_dict'])
logging.info("loaded checkpoint {} epoch = {}" .format(checkpoint_tar, checkpoint['epoch']))
# evaluation mode
if args.eval:
if args.eval_resume is not None:
checkpoint = torch.load(args.eval_resume)
model.module.drop_path_prob = 0
model.load_state_dict(checkpoint['state_dict'])
valid_acc_top1, valid_acc_top5 = infer(val_dataprovider, model.module, val_iters)
print('valid_acc_top1: {}'.format(valid_acc_top1))
exit(0)
for epoch in range(start_epoch, args.epochs):
if args.lr_scheduler == 'cosine':
scheduler.step()
current_lr = scheduler.get_lr()[0]
elif args.lr_scheduler == 'linear':
current_lr = adjust_lr(optimizer, epoch)
else:
logging.info('Wrong lr type, exit')
sys.exit(1)
logging.info('Epoch: %d lr %e', epoch, current_lr)
if epoch < 5 and args.batch_size > 256:
for param_group in optimizer.param_groups:
param_group['lr'] = current_lr * (epoch + 1) / 5.0
logging.info('Warming-up Epoch: %d, LR: %e', epoch, current_lr * (epoch + 1) / 5.0)
model.module.drop_path_prob = args.drop_path_prob * epoch / args.epochs
epoch_start = time.time()
train_acc, train_obj = train(train_dataprovider, model, criterion_smooth, optimizer, per_epoch_iters)
writer.add_scalar('Train/Loss', train_obj, epoch)
writer.add_scalar('Train/LR', current_lr, epoch)
if args.local_rank == 0 and (epoch % 5 == 0 or args.epochs - epoch < 10) :
valid_acc_top1, valid_acc_top5 = infer(val_dataprovider, model.module, val_iters)
is_best = False
if valid_acc_top5 > best_acc_top5:
best_acc_top5 = valid_acc_top5
if valid_acc_top1 > best_acc_top1:
best_acc_top1 = valid_acc_top1
is_best = True
logging.info('Valid_acc_top1: %f', valid_acc_top1)
logging.info('Valid_acc_top5: %f', valid_acc_top5)
logging.info('best_acc_top1: %f', best_acc_top1)
epoch_duration = time.time() - epoch_start
logging.info('Epoch time: %ds.', epoch_duration)
save_checkpoint_({
'epoch': epoch,
'state_dict': model.state_dict(),
'best_acc_top1': best_acc_top1,
'optimizer' : optimizer.state_dict(),
}, args.save)
def adjust_lr(optimizer, epoch):
# Smaller slope for the last 5 epochs because lr * 1/250 is relatively large
if args.epochs - epoch > 5:
lr = args.learning_rate * (args.epochs - 5 - epoch) / (args.epochs - 5)
else:
lr = args.learning_rate * (args.epochs - epoch) / ((args.epochs - 5) * 5)
for param_group in optimizer.param_groups:
param_group['lr'] = lr
return lr
def train(train_dataprovider, model, criterion, optimizer, train_iters):
objs = AvgrageMeter()
top1 = AvgrageMeter()
top5 = AvgrageMeter()
batch_time = AvgrageMeter()
model.train()
for i in range(train_iters):
t0 = time.time()
input, target = train_dataprovider.next()
datatime = time.time() - t0
target = target.cuda(non_blocking=True)
input = input.cuda(non_blocking=True)
b_start = time.time()
optimizer.zero_grad()
logits, logits_aux = model(input)
loss = criterion(logits, target)
if args.auxiliary:
loss_aux = criterion(logits_aux, target)
loss += args.auxiliary_weight*loss_aux
loss_reduce = reduce_tensor(loss, 0, args.world_size)
loss.backward()
nn.utils.clip_grad_norm_(model.parameters(), args.grad_clip)
optimizer.step()
batch_time.update(time.time() - b_start)
prec1, prec5 = accuracy(logits, target, topk=(1, 5))
n = input.size(0)
objs.update(loss_reduce.data.item(), n)
top1.update(prec1.data.item(), n)
top5.update(prec5.data.item(), n)
if i % args.report_freq == 0 and args.local_rank == 0:
logging.info('TRAIN Step: %03d/%03d Objs: %e R1: %f R5: %f BTime: %.3fs Datatime: %.3f',
i, train_iters, objs.avg, top1.avg, top5.avg, batch_time.avg, float(datatime))
return top1.avg, objs.avg
def infer(val_dataprovider, model, val_iters):
top1 = AvgrageMeter()
top5 = AvgrageMeter()
model.eval()
for i in range(val_iters):
t0 = time.time()
input, target = val_dataprovider.next()
datatime = time.time() - t0
input = input.cuda()
target = target.cuda(non_blocking=True)
with torch.no_grad():
logits, _ = model(input)
prec1, prec5 = accuracy(logits, target, topk=(1, 5))
n = input.size(0)
top1.update(prec1.data.item(), n)
top5.update(prec5.data.item(), n)
if i % args.report_freq == 0:
logging.info('VALID Step: %03d/%03d R1: %f R5: %f Datatime: %.3f', i, val_iters, top1.avg, top5.avg, float(datatime))
return top1.avg, top5.avg
if __name__ == '__main__':
main()
| import os
import sys
import numpy as np
import time
import torch
import glob
import random
import logging
import argparse
import torch.nn as nn
import genotypes
import torch.backends.cudnn as cudnn
from torch.autograd import Variable
from model import NetworkImageNet as Network
from tensorboardX import SummaryWriter
import apex
sys.path.append("../..")
from utils import *
from thop import profile
IMAGENET_TRAINING_SET_SIZE = 1281167
IMAGENET_TEST_SET_SIZE = 50000
parser = argparse.ArgumentParser("training imagenet")
parser.add_argument('--local_rank', type=int, default=None, help='local rank for distributed training')
parser.add_argument('--workers', type=int, default=32, help='number of workers to load dataset')
parser.add_argument('--batch_size', type=int, default=512, help='batch size')
parser.add_argument('--learning_rate', type=float, default=0.25, help='init learning rate')
parser.add_argument('--momentum', type=float, default=0.9, help='momentum')
parser.add_argument('--weight_decay', type=float, default=3e-5, help='weight decay')
parser.add_argument('--report_freq', type=float, default=100, help='report frequency')
parser.add_argument('--epochs', type=int, default=250, help='num of training epochs')
parser.add_argument('--init_channels', type=int, default=48, help='num of init channels')
parser.add_argument('--layers', type=int, default=14, help='total number of layers')
parser.add_argument('--auxiliary', action='store_true', default=True, help='use auxiliary tower')
parser.add_argument('--auxiliary_weight', type=float, default=0.4, help='weight for auxiliary loss')
parser.add_argument('--drop_path_prob', type=float, default=0, help='drop path probability')
parser.add_argument('--save', type=str, default='PDARTS_ABS', help='experiment name')
parser.add_argument('--seed', type=int, default=0, help='random seed')
parser.add_argument('--arch', type=str, default='PDARTS_ABS', help='which architecture to use')
parser.add_argument('--grad_clip', type=float, default=5., help='gradient clipping')
parser.add_argument('--label_smooth', type=float, default=0.1, help='label smoothing')
parser.add_argument('--lr_scheduler', type=str, default='linear', help='lr scheduler, linear or cosine')
parser.add_argument('--train_dir', type=str, default='../../data/train', help='path to training dataset')
parser.add_argument('--test_dir', type=str, default='../../data/test', help='path to test dataset')
parser.add_argument('--eval', default=False, action='store_true')
parser.add_argument('--eval-resume', type=str, default='./checkpoint.pth.tar', help='path for eval model')
args, unparsed = parser.parse_known_args()
args.save = 'eval-{}'.format(args.save)
if args.local_rank == 0 and not os.path.exists(args.save):
create_exp_dir(args.save, scripts_to_save=glob.glob('*.py'))
time.sleep(1)
log_format = '%(asctime)s %(message)s'
logging.basicConfig(stream=sys.stdout, level=logging.INFO,
format=log_format, datefmt='%m/%d %I:%M:%S %p')
fh = logging.FileHandler(os.path.join(args.save, 'log.txt'))
fh.setFormatter(logging.Formatter(log_format))
logging.getLogger().addHandler(fh)
writer = SummaryWriter(logdir=args.save)
CLASSES = 1000
per_epoch_iters = IMAGENET_TRAINING_SET_SIZE // args.batch_size
val_iters = IMAGENET_TEST_SET_SIZE // 200
# Average loss across processes for logging.
def reduce_tensor(tensor, device=0, world_size=1):
tensor = tensor.clone()
dist.reduce(tensor, device)
tensor.div_(world_size)
return tensor
class CrossEntropyLabelSmooth(nn.Module):
def __init__(self, num_classes, epsilon):
super(CrossEntropyLabelSmooth, self).__init__()
self.num_classes = num_classes
self.epsilon = epsilon
self.logsoftmax = nn.LogSoftmax(dim=1)
def forward(self, inputs, targets):
log_probs = self.logsoftmax(inputs)
targets = torch.zeros_like(log_probs).scatter_(1, targets.unsqueeze(1), 1)
targets = (1 - self.epsilon) * targets + self.epsilon / self.num_classes
loss = (-targets * log_probs).mean(0).sum()
return loss
def main():
if not torch.cuda.is_available():
logging.info('No GPU device available')
sys.exit(1)
num_gpus = torch.cuda.device_count()
args.gpu = args.local_rank % num_gpus
torch.cuda.set_device(args.gpu)
np.random.seed(args.seed)
cudnn.benchmark = True
cudnn.deterministic = True
torch.manual_seed(args.seed)
cudnn.enabled=True
torch.cuda.manual_seed(args.seed)
logging.info("args = %s", args)
logging.info("unparsed_args = %s", unparsed)
torch.distributed.init_process_group(backend='nccl', init_method='env://')
args.world_size = torch.distributed.get_world_size()
args.batch_size = args.batch_size // args.world_size
genotype = eval("genotypes.%s" % args.arch)
logging.info('---------Genotype---------')
logging.info(genotype)
logging.info('--------------------------')
model = Network(args.init_channels, CLASSES, args.layers, args.auxiliary, genotype)
model = model.cuda(args.gpu)
model = apex.parallel.DistributedDataParallel(model, delay_allreduce=True)
model_profile = Network(args.init_channels, CLASSES, args.layers, args.auxiliary, genotype)
model_profile = model_profile.cuda(args.gpu)
model_input_size_imagenet = (1, 3, 224, 224)
model_profile.drop_path_prob = 0
flops, _ = profile(model_profile, model_input_size_imagenet)
logging.info("flops = %fMB, param size = %fMB", flops, count_parameters_in_MB(model))
criterion_smooth = CrossEntropyLabelSmooth(CLASSES, args.label_smooth)
criterion_smooth = criterion_smooth.cuda()
optimizer = torch.optim.SGD(
model.parameters(),
args.learning_rate,
momentum=args.momentum,
weight_decay=args.weight_decay
)
# Prepare data
total_iters = per_epoch_iters * args.epochs
train_loader = get_train_dataloader(args.train_dir, args.batch_size, args.local_rank, total_iters)
train_dataprovider = DataIterator(train_loader)
val_loader = get_val_dataloader(args.test_dir)
val_dataprovider = DataIterator(val_loader)
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, float(args.epochs))
start_epoch = 0
best_acc_top1 = 0
best_acc_top5 = 0
checkpoint_tar = os.path.join(args.save, 'checkpoint.pth.tar')
if os.path.exists(checkpoint_tar):
logging.info('loading checkpoint {} ..........'.format(checkpoint_tar))
checkpoint = torch.load(checkpoint_tar, map_location={'cuda:0':'cuda:{}'.format(args.local_rank)})
start_epoch = checkpoint['epoch'] + 1
model.load_state_dict(checkpoint['state_dict'])
logging.info("loaded checkpoint {} epoch = {}" .format(checkpoint_tar, checkpoint['epoch']))
# evaluation mode
if args.eval:
if args.eval_resume is not None:
checkpoint = torch.load(args.eval_resume)
model.module.drop_path_prob = 0
model.load_state_dict(checkpoint['state_dict'])
valid_acc_top1, valid_acc_top5 = infer(val_dataprovider, model.module, val_iters)
print('valid_acc_top1: {}'.format(valid_acc_top1))
exit(0)
for epoch in range(start_epoch, args.epochs):
if args.lr_scheduler == 'cosine':
scheduler.step()
current_lr = scheduler.get_lr()[0]
elif args.lr_scheduler == 'linear':
current_lr = adjust_lr(optimizer, epoch)
else:
logging.info('Wrong lr type, exit')
sys.exit(1)
logging.info('Epoch: %d lr %e', epoch, current_lr)
if epoch < 5 and args.batch_size > 256:
for param_group in optimizer.param_groups:
param_group['lr'] = current_lr * (epoch + 1) / 5.0
logging.info('Warming-up Epoch: %d, LR: %e', epoch, current_lr * (epoch + 1) / 5.0)
model.module.drop_path_prob = args.drop_path_prob * epoch / args.epochs
epoch_start = time.time()
train_acc, train_obj = train(train_dataprovider, model, criterion_smooth, optimizer, per_epoch_iters)
writer.add_scalar('Train/Loss', train_obj, epoch)
writer.add_scalar('Train/LR', current_lr, epoch)
if args.local_rank == 0 and (epoch % 5 == 0 or args.epochs - epoch < 10) :
valid_acc_top1, valid_acc_top5 = infer(val_dataprovider, model.module, val_iters)
is_best = False
if valid_acc_top5 > best_acc_top5:
best_acc_top5 = valid_acc_top5
if valid_acc_top1 > best_acc_top1:
best_acc_top1 = valid_acc_top1
is_best = True
logging.info('Valid_acc_top1: %f', valid_acc_top1)
logging.info('Valid_acc_top5: %f', valid_acc_top5)
logging.info('best_acc_top1: %f', best_acc_top1)
epoch_duration = time.time() - epoch_start
logging.info('Epoch time: %ds.', epoch_duration)
save_checkpoint_({
'epoch': epoch,
'state_dict': model.state_dict(),
'best_acc_top1': best_acc_top1,
'optimizer' : optimizer.state_dict(),
}, args.save)
def adjust_lr(optimizer, epoch):
# Smaller slope for the last 5 epochs because lr * 1/250 is relatively large
if args.epochs - epoch > 5:
lr = args.learning_rate * (args.epochs - 5 - epoch) / (args.epochs - 5)
else:
lr = args.learning_rate * (args.epochs - epoch) / ((args.epochs - 5) * 5)
for param_group in optimizer.param_groups:
param_group['lr'] = lr
return lr
def train(train_dataprovider, model, criterion, optimizer, train_iters):
objs = AvgrageMeter()
top1 = AvgrageMeter()
top5 = AvgrageMeter()
batch_time = AvgrageMeter()
model.train()
for i in range(train_iters):
t0 = time.time()
input, target = train_dataprovider.next()
datatime = time.time() - t0
target = target.cuda(non_blocking=True)
input = input.cuda(non_blocking=True)
b_start = time.time()
optimizer.zero_grad()
logits, logits_aux = model(input)
loss = criterion(logits, target)
if args.auxiliary:
loss_aux = criterion(logits_aux, target)
loss += args.auxiliary_weight*loss_aux
loss_reduce = reduce_tensor(loss, 0, args.world_size)
loss.backward()
nn.utils.clip_grad_norm_(model.parameters(), args.grad_clip)
optimizer.step()
batch_time.update(time.time() - b_start)
prec1, prec5 = accuracy(logits, target, topk=(1, 5))
n = input.size(0)
objs.update(loss_reduce.data.item(), n)
top1.update(prec1.data.item(), n)
top5.update(prec5.data.item(), n)
if i % args.report_freq == 0 and args.local_rank == 0:
logging.info('TRAIN Step: %03d/%03d Objs: %e R1: %f R5: %f BTime: %.3fs Datatime: %.3f',
i, train_iters, objs.avg, top1.avg, top5.avg, batch_time.avg, float(datatime))
return top1.avg, objs.avg
def infer(val_dataprovider, model, val_iters):
top1 = AvgrageMeter()
top5 = AvgrageMeter()
model.eval()
for i in range(val_iters):
t0 = time.time()
input, target = val_dataprovider.next()
datatime = time.time() - t0
input = input.cuda()
target = target.cuda(non_blocking=True)
with torch.no_grad():
logits, _ = model(input)
prec1, prec5 = accuracy(logits, target, topk=(1, 5))
n = input.size(0)
top1.update(prec1.data.item(), n)
top5.update(prec5.data.item(), n)
if i % args.report_freq == 0:
logging.info('VALID Step: %03d/%03d R1: %f R5: %f Datatime: %.3f', i, val_iters, top1.avg, top5.avg, float(datatime))
return top1.avg, top5.avg
if __name__ == '__main__':
main()
| en | 0.887294 | # Average loss across processes for logging. # Prepare data # evaluation mode # Smaller slope for the last 5 epochs because lr * 1/250 is relatively large | 1.878282 | 2 |
freezerstate/statusupdate.py | jgkelly/FreezerState | 0 | 6618895 | <filename>freezerstate/statusupdate.py
# Global status notification times
import freezerstate.config
import time
import datetime
class StatusUpdate:
def __init__(self, test_enabled=None, test_times=None):
self.module = '[StatusUpdate]'
self.notification_times = []
notify_times = freezerstate.CONFIG.STATUS_CHECK_TIMES if test_enabled is None else test_times
self.load_times(notify_times)
def should_notify(self, time_value):
test_time = time_value
if (type(time_value) == datetime.datetime):
# time(hour = time_value.hour, minute = time_value.minute)
test_time = time_value.time()
test_text = test_time.strftime('%H:%M')
for x in self.notification_times:
if x.tm_hour == time_value.hour and x.tm_min == time_value.minute:
return True
return False
def load_times(self, times):
if times is None:
return
time_list = times.split(',')
if len(time_list) == 0:
return
for x in time_list:
try:
note_time = time.strptime(x, '%H:%M')
self.notification_times.append(note_time)
except ValueError as ve:
print(f'Time value: {x} is not a valid time - Ignoring')
| <filename>freezerstate/statusupdate.py
# Global status notification times
import freezerstate.config
import time
import datetime
class StatusUpdate:
def __init__(self, test_enabled=None, test_times=None):
self.module = '[StatusUpdate]'
self.notification_times = []
notify_times = freezerstate.CONFIG.STATUS_CHECK_TIMES if test_enabled is None else test_times
self.load_times(notify_times)
def should_notify(self, time_value):
test_time = time_value
if (type(time_value) == datetime.datetime):
# time(hour = time_value.hour, minute = time_value.minute)
test_time = time_value.time()
test_text = test_time.strftime('%H:%M')
for x in self.notification_times:
if x.tm_hour == time_value.hour and x.tm_min == time_value.minute:
return True
return False
def load_times(self, times):
if times is None:
return
time_list = times.split(',')
if len(time_list) == 0:
return
for x in time_list:
try:
note_time = time.strptime(x, '%H:%M')
self.notification_times.append(note_time)
except ValueError as ve:
print(f'Time value: {x} is not a valid time - Ignoring')
| en | 0.388088 | # Global status notification times # time(hour = time_value.hour, minute = time_value.minute) | 2.732967 | 3 |
tests/settings.py | amikrop/django-paste | 3 | 6618896 | SECRET_KEY = ' '
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'rest_framework',
'paste.apps.PasteConfig',
]
ROOT_URLCONF = 'tests.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
},
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
| SECRET_KEY = ' '
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'rest_framework',
'paste.apps.PasteConfig',
]
ROOT_URLCONF = 'tests.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
},
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
| none | 1 | 1.309277 | 1 | |
question_generation/framework/samples/sample_framework_usage.py | hucvl/craft | 9 | 6618897 | import json
import os
from pathlib import Path
from framework.simulation import SimulationInstance, SimulationRunner
def run_simulation_instance(scene_id: int, id: int):
output_json_path = Path(f"samples/outputs/{id:06d}.json").absolute().as_posix()
output_video_path = Path(f"samples/outputs/{id:06d}.mpg").absolute().as_posix()
controller_file_path = Path(f"samples/outputs/controller_{scene_id}_{id:06d}.json").absolute().as_posix()
variations_file_path = Path(f"samples/outputs/variations_{scene_id}_{id:06d}.json").absolute().as_posix()
questions_file_path = Path(f"samples/outputs/questions_{scene_id}_{id:06d}.json").absolute().as_posix()
debug_file_path = Path(f"samples/outputs/debug_{scene_id}_{id:06d}.txt").absolute().as_posix()
with open(controller_file_path, 'w') as controller_file:
json.dump(
json.loads(
f"""{{
"simulationID": {scene_id},
"offline": false,
"outputVideoPath": "{output_video_path}",
"outputJSONPath": "{output_json_path}",
"width": 256,
"height": 256,
"inputScenePath": "",
"stepCount": 600
}}"""),
controller_file,
indent=2
)
exec_path = Path("../../simulation/2d/SVQA-Box2D/Build/bin/x86_64/Release/Testbed").absolute().as_posix()
working_dir = Path("../../simulation/2d/SVQA-Box2D/Testbed").absolute().as_posix()
runner = SimulationRunner(exec_path, working_directory=working_dir)
instance = SimulationInstance(id, controller_file_path, variations_file_path, questions_file_path, runner)
instance.run_simulation(debug_output_path=debug_file_path)
instance.run_variations()
instance.generate_questions(simulation_config=None)
if __name__ == '__main__':
# CAUTION: Current working directory must be one level from the root directory, preferably "framework".
os.makedirs("samples/outputs", exist_ok=True)
run_simulation_instance(6, 1)
| import json
import os
from pathlib import Path
from framework.simulation import SimulationInstance, SimulationRunner
def run_simulation_instance(scene_id: int, id: int):
output_json_path = Path(f"samples/outputs/{id:06d}.json").absolute().as_posix()
output_video_path = Path(f"samples/outputs/{id:06d}.mpg").absolute().as_posix()
controller_file_path = Path(f"samples/outputs/controller_{scene_id}_{id:06d}.json").absolute().as_posix()
variations_file_path = Path(f"samples/outputs/variations_{scene_id}_{id:06d}.json").absolute().as_posix()
questions_file_path = Path(f"samples/outputs/questions_{scene_id}_{id:06d}.json").absolute().as_posix()
debug_file_path = Path(f"samples/outputs/debug_{scene_id}_{id:06d}.txt").absolute().as_posix()
with open(controller_file_path, 'w') as controller_file:
json.dump(
json.loads(
f"""{{
"simulationID": {scene_id},
"offline": false,
"outputVideoPath": "{output_video_path}",
"outputJSONPath": "{output_json_path}",
"width": 256,
"height": 256,
"inputScenePath": "",
"stepCount": 600
}}"""),
controller_file,
indent=2
)
exec_path = Path("../../simulation/2d/SVQA-Box2D/Build/bin/x86_64/Release/Testbed").absolute().as_posix()
working_dir = Path("../../simulation/2d/SVQA-Box2D/Testbed").absolute().as_posix()
runner = SimulationRunner(exec_path, working_directory=working_dir)
instance = SimulationInstance(id, controller_file_path, variations_file_path, questions_file_path, runner)
instance.run_simulation(debug_output_path=debug_file_path)
instance.run_variations()
instance.generate_questions(simulation_config=None)
if __name__ == '__main__':
# CAUTION: Current working directory must be one level from the root directory, preferably "framework".
os.makedirs("samples/outputs", exist_ok=True)
run_simulation_instance(6, 1)
| en | 0.513448 | {{ "simulationID": {scene_id}, "offline": false, "outputVideoPath": "{output_video_path}", "outputJSONPath": "{output_json_path}", "width": 256, "height": 256, "inputScenePath": "", "stepCount": 600 }} # CAUTION: Current working directory must be one level from the root directory, preferably "framework". | 2.34197 | 2 |
config/__init__.py | huangy10/WH-LightIM | 0 | 6618898 | from config import GlobalConfig
| from config import GlobalConfig
| none | 1 | 1.144548 | 1 | |
torchmoon/__version__.py | afeldman/TorchMoon | 0 | 6618899 | major=1
minor=0
patch=4
__version__ = (major, minor, patch)
VERSION = ".".join([str(x) for x in __version__])
| major=1
minor=0
patch=4
__version__ = (major, minor, patch)
VERSION = ".".join([str(x) for x in __version__])
| none | 1 | 2.037413 | 2 | |
03-data_structures/geopoint.py | palmieric/Tecnologie_Web-Introduzione_a_Python | 3 | 6618900 | <reponame>palmieric/Tecnologie_Web-Introduzione_a_Python
class GeoPoint:
def __init__(self, lat, lon):
self.__lat=lat
self.__lon=lon
def getLat(self):
return self.__lat
def getLon(self):
return self.__lon
pos1 = GeoPoint(40.85, 14.28)
print(pos1.getLat(), pos1.getLon())
| class GeoPoint:
def __init__(self, lat, lon):
self.__lat=lat
self.__lon=lon
def getLat(self):
return self.__lat
def getLon(self):
return self.__lon
pos1 = GeoPoint(40.85, 14.28)
print(pos1.getLat(), pos1.getLon()) | none | 1 | 3.23596 | 3 | |
papers/Entailment-Issues/code/debias/clf_distill_loss_functions.py | ArleneYuZhiwei/KC | 29 | 6618901 | <gh_stars>10-100
'''
The code is adapted from https://github.com/UKPLab/emnlp2020-debiasing-unknown/blob/main/src/clf_distill_loss_functions.py
License: Apache License 2.0
'''
import torch
from torch import nn
from torch.nn import functional as F
from torch.nn import CrossEntropyLoss
import numpy as np
import math
class ClfDistillLossFunction(nn.Module):
"""Torch classification debiasing loss function"""
def forward(self, hidden, logits, bias, labels):
"""
:param hidden: [batch, n_features] hidden features from the model
:param logits: [batch, n_classes] logit score for each class
:param bias: [batch, n_classes] log-probabilties from the bias for each class
:param labels: [batch] integer class labels
:return: scalar loss
"""
raise NotImplementedError()
class Plain(ClfDistillLossFunction):
def forward(self, hidden, logits, bias, labels):
return F.cross_entropy(logits, labels)
class LabelSmoothing(ClfDistillLossFunction):
def __init__(self, num_class):
super(LabelSmoothing, self).__init__()
self.num_class = num_class
def forward(self, hidden, logits, bias, labels):
softmaxf = torch.nn.Softmax(dim=1)
probs = softmaxf(logits)
one_hot_labels = torch.eye(logits.size(1)).cuda()[labels]
alphas = (one_hot_labels * torch.exp(bias)).sum(1).unsqueeze(1).expand_as(one_hot_labels)
target_probs = (1 - alphas) * one_hot_labels + alphas / self.num_class
example_loss = -(target_probs * probs.log()).sum(1)
batch_loss = example_loss.mean()
return batch_loss
class ReweightBaseline(ClfDistillLossFunction):
def forward(self, hidden, logits, bias, labels):
logits = logits.float() # In case we were in fp16 mode
loss = F.cross_entropy(logits, labels, reduction='none')
# default we use cuda ....
one_hot_labels = torch.eye(logits.size(1)).cuda()[labels]
weights = 1 - (one_hot_labels * torch.exp(bias)).sum(1)
return (weights * loss).sum() / weights.sum()
class BiasProductBaseline(ClfDistillLossFunction):
def forward(self, hidden, logits, bias, labels):
logits = logits.float() # In case we were in fp16 mode
logits = F.log_softmax(logits, 1)
return F.cross_entropy(logits + bias.float(), labels)
| '''
The code is adapted from https://github.com/UKPLab/emnlp2020-debiasing-unknown/blob/main/src/clf_distill_loss_functions.py
License: Apache License 2.0
'''
import torch
from torch import nn
from torch.nn import functional as F
from torch.nn import CrossEntropyLoss
import numpy as np
import math
class ClfDistillLossFunction(nn.Module):
"""Torch classification debiasing loss function"""
def forward(self, hidden, logits, bias, labels):
"""
:param hidden: [batch, n_features] hidden features from the model
:param logits: [batch, n_classes] logit score for each class
:param bias: [batch, n_classes] log-probabilties from the bias for each class
:param labels: [batch] integer class labels
:return: scalar loss
"""
raise NotImplementedError()
class Plain(ClfDistillLossFunction):
def forward(self, hidden, logits, bias, labels):
return F.cross_entropy(logits, labels)
class LabelSmoothing(ClfDistillLossFunction):
def __init__(self, num_class):
super(LabelSmoothing, self).__init__()
self.num_class = num_class
def forward(self, hidden, logits, bias, labels):
softmaxf = torch.nn.Softmax(dim=1)
probs = softmaxf(logits)
one_hot_labels = torch.eye(logits.size(1)).cuda()[labels]
alphas = (one_hot_labels * torch.exp(bias)).sum(1).unsqueeze(1).expand_as(one_hot_labels)
target_probs = (1 - alphas) * one_hot_labels + alphas / self.num_class
example_loss = -(target_probs * probs.log()).sum(1)
batch_loss = example_loss.mean()
return batch_loss
class ReweightBaseline(ClfDistillLossFunction):
def forward(self, hidden, logits, bias, labels):
logits = logits.float() # In case we were in fp16 mode
loss = F.cross_entropy(logits, labels, reduction='none')
# default we use cuda ....
one_hot_labels = torch.eye(logits.size(1)).cuda()[labels]
weights = 1 - (one_hot_labels * torch.exp(bias)).sum(1)
return (weights * loss).sum() / weights.sum()
class BiasProductBaseline(ClfDistillLossFunction):
def forward(self, hidden, logits, bias, labels):
logits = logits.float() # In case we were in fp16 mode
logits = F.log_softmax(logits, 1)
return F.cross_entropy(logits + bias.float(), labels) | en | 0.78735 | The code is adapted from https://github.com/UKPLab/emnlp2020-debiasing-unknown/blob/main/src/clf_distill_loss_functions.py License: Apache License 2.0 Torch classification debiasing loss function :param hidden: [batch, n_features] hidden features from the model :param logits: [batch, n_classes] logit score for each class :param bias: [batch, n_classes] log-probabilties from the bias for each class :param labels: [batch] integer class labels :return: scalar loss # In case we were in fp16 mode # default we use cuda .... # In case we were in fp16 mode | 2.685327 | 3 |
house_code/main_programs/PSUPozyx/1D_ranging.py | mukobi/Pozyx-Gabe | 1 | 6618902 | <gh_stars>1-10
#!/usr/bin/env python
"""
The Pozyx ready to range tutorial (c) Pozyx Labs
Please read the tutorial: https://www.pozyx.io/Documentation/Tutorials/ready_to_range/Python
This demo requires two Pozyx devices. It demonstrates the ranging capabilities and the functionality to
to remotely control a Pozyx device. Move around with the other Pozyx device.
This demo measures the range between the two devices.
"""
import sys
from pypozyx import *
from pypozyx.definitions.bitmasks import POZYX_INT_MASK_IMU
import time
from modules.file_writing import RangingFileWriting as FileIO
from modules.file_writing import FileOpener
from modules.console_logging_functions import CondensedConsoleLogging as Console
from modules.configuration import Configuration as Configuration
from modules.pozyx_osc import PozyxUDP
sys.path.append(sys.path[0] + "/..")
from constants import definitions
class RangeOutputContainer:
"""Holds the range data, motion data, and more for a single device"""
def __init__(self, tag, device_range, smoothed_range, sensor_data, loop_status):
self.tag = tag
self.device_range = device_range
self.sensor_data = sensor_data
self.loop_status = loop_status
self.smoothed_range = smoothed_range
self.velocity = ""
class ReadyToRange(object):
"""Continuously performs ranging between the Pozyx and a destination"""
def __init__(self, i_pozyx, i_tags, i_destination_id, i_to_get_sensor_data,
i_protocol=POZYX_RANGE_PROTOCOL_FAST):
self.pozyx = i_pozyx
self.tags = i_tags
self.destination_id = i_destination_id
self.to_get_sensor_data = i_to_get_sensor_data
self.protocol = i_protocol
def loop(self, range_data_array):
"""Performs ranging and collects motion data as needed"""
for idx, tag in enumerate(self.tags):
# get 1D position in this section
device_range = DeviceRange()
loop_status = self.pozyx.doRanging(tag, device_range, self.destination_id)
if int(device_range.distance) > 2147483647:
loop_status = POZYX_FAILURE
# get motion data in this section-
sensor_data = SensorData()
calibration_status = SingleRegister()
if self.to_get_sensor_data:
sensor_data.data_format = 'IhhhhhhhhhhhhhhhhhhhhhhB'
if tag is not None or self.pozyx.checkForFlag(POZYX_INT_MASK_IMU, 0.01) == POZYX_SUCCESS:
loop_status = self.pozyx.getAllSensorData(sensor_data, tag)
loop_status &= self.pozyx.getCalibrationStatus(calibration_status, tag)
single = range_data_array[idx]
single.tag = tag
single.device_range = device_range
single.sensor_data = sensor_data
single.loop_status = loop_status
class ContinueI(Exception):
pass
continue_i = ContinueI()
if __name__ == "__main__":
serial_port = Configuration.get_correct_serial_port()
pozyx = PozyxSerial(serial_port)
use_velocity = True
# import properties from saved properties file
config = Configuration.get_properties()
tags = config.tags
anchors = config.anchors
attributes_to_log = config.attributes_to_log
to_use_file = config.use_file
filename = config.data_file
range_anchor_id = config.range_anchor_id
alpha_pos = config.position_smooth
alpha_vel = config.velocity_smooth
smooth_velocity = alpha_vel < 1.00
to_get_sensor_data = not attributes_to_log == []
ranging_protocol = POZYX_RANGE_PROTOCOL_PRECISION # the ranging protocol
# IMPORTANT: set destination_id to None if it is meant to be ranging from the device
# connected to the computer. Do this by setting the destination_id to an empty
# string "" in the GUI
r = ReadyToRange(
pozyx, tags, range_anchor_id, to_get_sensor_data, ranging_protocol)
range_data_array = []
previous_distance_array = []
for tag in tags:
range_data_array.append(RangeOutputContainer(None, None, 0, None, None))
previous_distance_array.append(0)
if not tags:
sys.exit("Please add at least one remote device for 1D ranging.")
logfile = None
if to_use_file:
logfile = FileOpener.create_csv(filename)
FileIO.write_range_headers_to_file(logfile, tags, attributes_to_log)
# wait for motion data to work before running main loop
if to_get_sensor_data:
not_started = True
while not_started:
r.loop(range_data_array)
try:
not_started = int(range_data_array[0].sensor_data.pressure) == 0
except TypeError:
not_started = True
pozyxUDP = None
try:
# Initialize EMA filter so it doesn't start at 0
r.loop(range_data_array)
for single_data in range_data_array:
if type(single_data.device_range.distance) is int:
single_data.smoothed_range = single_data.device_range.distance
# update message client after data working - don't send initial 0 range over osc
pozyxUDP = PozyxUDP()
index = 0
start = time.time()
new_time = 0.0
time.sleep(0.0001)
while True:
try:
elapsed = time.time() - start
old_time = new_time
new_time = elapsed
time_difference = new_time - old_time
for idx, dataset in enumerate(range_data_array):
previous_distance_array[idx] = dataset.device_range.distance
r.loop(range_data_array)
for idx, dataset in enumerate(range_data_array):
if dataset.device_range.distance == 0 and previous_distance_array[idx] != 0:
raise continue_i
for single_data in range_data_array:
single_data.elapsed_time = elapsed # update time for OSC message
# EMA filter calculations
if type(single_data.device_range.distance) is int:
old_smoothed_range = single_data.smoothed_range
single_data.smoothed_range = (
(1 - alpha_pos) * single_data.smoothed_range
+ alpha_pos * single_data.device_range.distance)
new_smoothed_range = single_data.smoothed_range
if not (time_difference == 0) and not (elapsed <= 0.001):
if single_data.velocity == "":
single_data.velocity = 0.0
measured_velocity = (new_smoothed_range - old_smoothed_range) / time_difference
single_data.velocity = (
(1 - alpha_vel) * single_data.velocity
+ alpha_vel * measured_velocity)
if not smooth_velocity:
single_data.velocity = measured_velocity
Console.print_1d_ranging_output(
index, elapsed, range_data_array, attributes_to_log)
if to_use_file:
FileIO.write_range_data_to_file(
logfile, index, elapsed, time_difference, range_data_array, attributes_to_log)
if range_data_array[0].loop_status == POZYX_SUCCESS:
data_type = ([definitions.DATA_TYPE_RANGING, definitions.DATA_TYPE_MOTION_DATA] if attributes_to_log
else [definitions.DATA_TYPE_RANGING])
pozyxUDP.send_message(elapsed, tags, range_data_array, data_type)
index = index + 1
except ContinueI:
continue
finally:
if to_use_file:
pozyxUDP.producer.close_socket()
logfile.close()
print("closing file")
# time.sleep(1)
| #!/usr/bin/env python
"""
The Pozyx ready to range tutorial (c) Pozyx Labs
Please read the tutorial: https://www.pozyx.io/Documentation/Tutorials/ready_to_range/Python
This demo requires two Pozyx devices. It demonstrates the ranging capabilities and the functionality to
to remotely control a Pozyx device. Move around with the other Pozyx device.
This demo measures the range between the two devices.
"""
import sys
from pypozyx import *
from pypozyx.definitions.bitmasks import POZYX_INT_MASK_IMU
import time
from modules.file_writing import RangingFileWriting as FileIO
from modules.file_writing import FileOpener
from modules.console_logging_functions import CondensedConsoleLogging as Console
from modules.configuration import Configuration as Configuration
from modules.pozyx_osc import PozyxUDP
sys.path.append(sys.path[0] + "/..")
from constants import definitions
class RangeOutputContainer:
"""Holds the range data, motion data, and more for a single device"""
def __init__(self, tag, device_range, smoothed_range, sensor_data, loop_status):
self.tag = tag
self.device_range = device_range
self.sensor_data = sensor_data
self.loop_status = loop_status
self.smoothed_range = smoothed_range
self.velocity = ""
class ReadyToRange(object):
"""Continuously performs ranging between the Pozyx and a destination"""
def __init__(self, i_pozyx, i_tags, i_destination_id, i_to_get_sensor_data,
i_protocol=POZYX_RANGE_PROTOCOL_FAST):
self.pozyx = i_pozyx
self.tags = i_tags
self.destination_id = i_destination_id
self.to_get_sensor_data = i_to_get_sensor_data
self.protocol = i_protocol
def loop(self, range_data_array):
"""Performs ranging and collects motion data as needed"""
for idx, tag in enumerate(self.tags):
# get 1D position in this section
device_range = DeviceRange()
loop_status = self.pozyx.doRanging(tag, device_range, self.destination_id)
if int(device_range.distance) > 2147483647:
loop_status = POZYX_FAILURE
# get motion data in this section-
sensor_data = SensorData()
calibration_status = SingleRegister()
if self.to_get_sensor_data:
sensor_data.data_format = 'IhhhhhhhhhhhhhhhhhhhhhhB'
if tag is not None or self.pozyx.checkForFlag(POZYX_INT_MASK_IMU, 0.01) == POZYX_SUCCESS:
loop_status = self.pozyx.getAllSensorData(sensor_data, tag)
loop_status &= self.pozyx.getCalibrationStatus(calibration_status, tag)
single = range_data_array[idx]
single.tag = tag
single.device_range = device_range
single.sensor_data = sensor_data
single.loop_status = loop_status
class ContinueI(Exception):
pass
continue_i = ContinueI()
if __name__ == "__main__":
serial_port = Configuration.get_correct_serial_port()
pozyx = PozyxSerial(serial_port)
use_velocity = True
# import properties from saved properties file
config = Configuration.get_properties()
tags = config.tags
anchors = config.anchors
attributes_to_log = config.attributes_to_log
to_use_file = config.use_file
filename = config.data_file
range_anchor_id = config.range_anchor_id
alpha_pos = config.position_smooth
alpha_vel = config.velocity_smooth
smooth_velocity = alpha_vel < 1.00
to_get_sensor_data = not attributes_to_log == []
ranging_protocol = POZYX_RANGE_PROTOCOL_PRECISION # the ranging protocol
# IMPORTANT: set destination_id to None if it is meant to be ranging from the device
# connected to the computer. Do this by setting the destination_id to an empty
# string "" in the GUI
r = ReadyToRange(
pozyx, tags, range_anchor_id, to_get_sensor_data, ranging_protocol)
range_data_array = []
previous_distance_array = []
for tag in tags:
range_data_array.append(RangeOutputContainer(None, None, 0, None, None))
previous_distance_array.append(0)
if not tags:
sys.exit("Please add at least one remote device for 1D ranging.")
logfile = None
if to_use_file:
logfile = FileOpener.create_csv(filename)
FileIO.write_range_headers_to_file(logfile, tags, attributes_to_log)
# wait for motion data to work before running main loop
if to_get_sensor_data:
not_started = True
while not_started:
r.loop(range_data_array)
try:
not_started = int(range_data_array[0].sensor_data.pressure) == 0
except TypeError:
not_started = True
pozyxUDP = None
try:
# Initialize EMA filter so it doesn't start at 0
r.loop(range_data_array)
for single_data in range_data_array:
if type(single_data.device_range.distance) is int:
single_data.smoothed_range = single_data.device_range.distance
# update message client after data working - don't send initial 0 range over osc
pozyxUDP = PozyxUDP()
index = 0
start = time.time()
new_time = 0.0
time.sleep(0.0001)
while True:
try:
elapsed = time.time() - start
old_time = new_time
new_time = elapsed
time_difference = new_time - old_time
for idx, dataset in enumerate(range_data_array):
previous_distance_array[idx] = dataset.device_range.distance
r.loop(range_data_array)
for idx, dataset in enumerate(range_data_array):
if dataset.device_range.distance == 0 and previous_distance_array[idx] != 0:
raise continue_i
for single_data in range_data_array:
single_data.elapsed_time = elapsed # update time for OSC message
# EMA filter calculations
if type(single_data.device_range.distance) is int:
old_smoothed_range = single_data.smoothed_range
single_data.smoothed_range = (
(1 - alpha_pos) * single_data.smoothed_range
+ alpha_pos * single_data.device_range.distance)
new_smoothed_range = single_data.smoothed_range
if not (time_difference == 0) and not (elapsed <= 0.001):
if single_data.velocity == "":
single_data.velocity = 0.0
measured_velocity = (new_smoothed_range - old_smoothed_range) / time_difference
single_data.velocity = (
(1 - alpha_vel) * single_data.velocity
+ alpha_vel * measured_velocity)
if not smooth_velocity:
single_data.velocity = measured_velocity
Console.print_1d_ranging_output(
index, elapsed, range_data_array, attributes_to_log)
if to_use_file:
FileIO.write_range_data_to_file(
logfile, index, elapsed, time_difference, range_data_array, attributes_to_log)
if range_data_array[0].loop_status == POZYX_SUCCESS:
data_type = ([definitions.DATA_TYPE_RANGING, definitions.DATA_TYPE_MOTION_DATA] if attributes_to_log
else [definitions.DATA_TYPE_RANGING])
pozyxUDP.send_message(elapsed, tags, range_data_array, data_type)
index = index + 1
except ContinueI:
continue
finally:
if to_use_file:
pozyxUDP.producer.close_socket()
logfile.close()
print("closing file")
# time.sleep(1) | en | 0.851027 | #!/usr/bin/env python The Pozyx ready to range tutorial (c) Pozyx Labs Please read the tutorial: https://www.pozyx.io/Documentation/Tutorials/ready_to_range/Python This demo requires two Pozyx devices. It demonstrates the ranging capabilities and the functionality to to remotely control a Pozyx device. Move around with the other Pozyx device. This demo measures the range between the two devices. Holds the range data, motion data, and more for a single device Continuously performs ranging between the Pozyx and a destination Performs ranging and collects motion data as needed # get 1D position in this section # get motion data in this section- # import properties from saved properties file # the ranging protocol # IMPORTANT: set destination_id to None if it is meant to be ranging from the device # connected to the computer. Do this by setting the destination_id to an empty # string "" in the GUI # wait for motion data to work before running main loop # Initialize EMA filter so it doesn't start at 0 # update message client after data working - don't send initial 0 range over osc # update time for OSC message # EMA filter calculations # time.sleep(1) | 2.748199 | 3 |
main/word-break/word-break-fast.py | EliahKagan/old-practice-snapshot | 0 | 6618903 | END_MARK = None
class Solution:
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: bool
"""
# build the trie
trie = {}
for word in wordDict:
cur = trie
for ch in word:
try:
cur = cur[ch]
except KeyError:
nxt = {}
cur[ch] = nxt
cur = nxt
cur[END_MARK] = END_MARK
# create the initial table
slen = len(s)
table = [False] * slen
table.append(True)
# attempt to build a chain of words
for i in range(slen - 1, -1, -1):
try:
node = trie
for j in range(i, slen):
node = node[s[j]]
if table[j + 1] and END_MARK in node:
table[i] = True
break
except KeyError:
pass
return table[0]
| END_MARK = None
class Solution:
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: bool
"""
# build the trie
trie = {}
for word in wordDict:
cur = trie
for ch in word:
try:
cur = cur[ch]
except KeyError:
nxt = {}
cur[ch] = nxt
cur = nxt
cur[END_MARK] = END_MARK
# create the initial table
slen = len(s)
table = [False] * slen
table.append(True)
# attempt to build a chain of words
for i in range(slen - 1, -1, -1):
try:
node = trie
for j in range(i, slen):
node = node[s[j]]
if table[j + 1] and END_MARK in node:
table[i] = True
break
except KeyError:
pass
return table[0]
| en | 0.583967 | :type s: str :type wordDict: List[str] :rtype: bool # build the trie # create the initial table # attempt to build a chain of words | 3.276267 | 3 |
src/tests/integration/forms/binary_forms_test.py | tale-lang/tale | 17 | 6618904 | <filename>src/tests/integration/forms/binary_forms_test.py
from tale.core import execute
def test_first_argument():
# Arrange.
program = """
(x) + (y) = x
a + b
"""
# Act.
out = execute(program)
# Assert.
assert out == 'a'
def test_second_argument():
# Arrange.
program = """
(x) + (y) = y
a + b
"""
# Act.
out = execute(program)
# Assert.
assert out == 'b'
def test_calling_keyword_form_in_body():
# Arrange.
program = """
(x) and: (y) = x
(x) + (y) = x and: y
a + b
"""
# Act.
out = execute(program)
# Assert.
assert out == 'a'
def test_compound_binary_expression():
# Arrange.
program = """
(x) + (y) = y
a + b + c + d
"""
# Act.
out = execute(program)
# Assert.
assert out == 'd'
| <filename>src/tests/integration/forms/binary_forms_test.py
from tale.core import execute
def test_first_argument():
# Arrange.
program = """
(x) + (y) = x
a + b
"""
# Act.
out = execute(program)
# Assert.
assert out == 'a'
def test_second_argument():
# Arrange.
program = """
(x) + (y) = y
a + b
"""
# Act.
out = execute(program)
# Assert.
assert out == 'b'
def test_calling_keyword_form_in_body():
# Arrange.
program = """
(x) and: (y) = x
(x) + (y) = x and: y
a + b
"""
# Act.
out = execute(program)
# Assert.
assert out == 'a'
def test_compound_binary_expression():
# Arrange.
program = """
(x) + (y) = y
a + b + c + d
"""
# Act.
out = execute(program)
# Assert.
assert out == 'd'
| en | 0.573432 | # Arrange. (x) + (y) = x a + b # Act. # Assert. # Arrange. (x) + (y) = y a + b # Act. # Assert. # Arrange. (x) and: (y) = x (x) + (y) = x and: y a + b # Act. # Assert. # Arrange. (x) + (y) = y a + b + c + d # Act. # Assert. | 2.59767 | 3 |
src/components/per_buffer_tderror.py | am-rutherford/pymarl | 1 | 6618905 | import pathlib
from copy import deepcopy
from math import floor
from typing import DefaultDict
from sympy import EX
import torch as th
import numpy as np
from types import SimpleNamespace as SN
from .episode_buffer import EpisodeBatch
from .epsilon_schedules import RiseThenFlatSchedule
class TD_PERBuffer(EpisodeBatch):
"""Implements non-uniform sampling from the episode buffer. Weighted proportionally based on episode return.
"""
def __init__(self, args, scheme, groups, buffer_size, max_seq_length, preprocess=None, device="cpu"):
"""
Args:
per_alpha: Exponent applied to the sum of the reward score and per_epsilon. Must lie in the range [0, 1].
per_epsilon: Constant added to reward score.
per_beta: importance sampling exponent, controls how much prioritization to apply. Must lie in the range [0, 1].
"""
super(TD_PERBuffer, self).__init__(scheme, groups, buffer_size, max_seq_length, preprocess=preprocess, device=device)
self.buffer_size = buffer_size # same as self.batch_size but more explicit
self.buffer_index = 0
self.episodes_in_buffer = 0
self.device = device
assert (args.per_alpha >= 0) and (args.per_alpha <= 1), "per_alpha is out of bounds, must lie in the range [0, 1]"
assert args.per_epsilon >= 0, "per_epsilon must be positive"
assert (args.per_beta >= 0) and (args.per_beta <= 1), "per_beta is out of bounds, must lie in the range [0, 1]"
assert (args.per_beta_anneal >= 0) and (args.per_beta_anneal <= 1), "per_beta_anneal is out of bounds, must lie in the range [0, 1]"
self.per_alpha = args.per_alpha
self.per_epsilon = args.per_epsilon
self.per_beta_schedule = RiseThenFlatSchedule(args.per_beta, 1, floor(args.t_max * args.per_beta_anneal), decay="linear")
self.per_beta = self.per_beta_schedule.eval(0)
self.max_td_error = args.per_epsilon
print(f'Initialising TD ERROR PER buffer, annealing beta from {args.per_beta} to 1 over {floor(args.t_max * args.per_beta_anneal)} timesteps.')
self.td_errors = th.zeros((buffer_size, 1, 1), device=self.device)
self.reward_sum = th.zeros((buffer_size, 1, 1), device=self.device)
self.e_sampled = th.zeros((buffer_size, 1, 1), device=self.device)
# for logging values
self.buffer_counter = 0
self.reward_sum_record = {}
self.sample_count = {}
self.buffer_sample_count = th.zeros((buffer_size, 1, 1), device=self.device)
def insert_episode_batch(self, ep_batch):
"""Insert episode into replay buffer.
Args:
ep_batch (EpiosdeBatch): Episode to be inserted
"""
#print(f'inserting episode batch, buffer idx {self.buffer_index}, ep batch size {ep_batch.batch_size}')
if self.buffer_index + ep_batch.batch_size <= self.buffer_size:
## PER values
assert ep_batch.batch_size == 1
self.td_errors[self.buffer_index] = (self.max_td_error)**self.per_alpha
self.e_sampled[self.buffer_index] = 0
self.update(ep_batch.data.transition_data,
slice(self.buffer_index, self.buffer_index + ep_batch.batch_size),
slice(0, ep_batch.max_seq_length),
mark_filled=False)
self.update(ep_batch.data.episode_data,
slice(self.buffer_index, self.buffer_index + ep_batch.batch_size))
self.reward_sum_record[self.buffer_counter] = th.sum(ep_batch["reward"]) # just for debugging
#print(f'buffer idx {self.buffer_index}, ep in buffer {self.episodes_in_buffer}, buffer counter {self.buffer_counter}')
if self.buffer_counter >= self.buffer_size:
self.sample_count[self.buffer_counter-self.buffer_size] = self.buffer_sample_count[self.buffer_index]
self.buffer_sample_count[self.buffer_index] = 0
self.buffer_counter += ep_batch.batch_size
# increment buffer index
self.buffer_index = (self.buffer_index + ep_batch.batch_size)
self.episodes_in_buffer = max(self.episodes_in_buffer, self.buffer_index)
self.buffer_index = self.buffer_index % self.buffer_size # resets buffer index once it is greater than buffer size, allows it to then remove oldest epsiodes
assert self.buffer_index < self.buffer_size
else:
buffer_left = self.buffer_size - self.buffer_index # i guess this is for when buffer_size % batch_size > 0
print(f' -- Uneaven entry to buffer -- ')
self.insert_episode_batch(ep_batch[0:buffer_left, :])
self.insert_episode_batch(ep_batch[buffer_left:, :])
def can_sample(self, batch_size):
return self.episodes_in_buffer > batch_size
def sample(self, batch_size, t):
"""Returns a sample of episodes from the replay buffer
Args:
batch_size (int): Number of episodes to return
t (int): training timestep at which sampling is occuring, used to anneal per_beta
"""
assert self.can_sample(batch_size)
if self.episodes_in_buffer == batch_size:
self._sample_idxs = np.arange(batch_size)
return self[:batch_size]
else:
probs = self.td_errors[:self.episodes_in_buffer]/th.sum(self.td_errors[:self.episodes_in_buffer], dim=0)
ep_ids = np.random.choice(self.episodes_in_buffer, batch_size, replace=False, p=th.flatten(probs).cpu().detach().numpy())
# Calculate importance sampling weights -- correct for bias introduced
self.per_beta = self.per_beta_schedule.eval(t)
is_weights = th.ones((batch_size, 1, 1), device=self.device) * 1/probs[ep_ids] * 1/self.episodes_in_buffer
is_weights = th.pow(is_weights, self.per_beta)
is_weights = is_weights/th.max(is_weights) # normalise
self.data.transition_data["weights"][ep_ids]= is_weights
# Update PER values for episodes sampled for first time # NOTE could be made more torchy
'''for i in ep_ids:
if not self.e_sampled[i]:
self.pvalues[i] = self.reward_sum[i] ** self.reward_power
self.e_sampled[i] = 1
self.buffer_sample_count[i] += 1'''
self._sample_idxs = ep_ids
return self[ep_ids]
def update_batch_td_errors(self, td_error):
"""
Args:
td_error: masked td errors
"""
error_sum = th.abs(th.sum(td_error, dim=1))
self.td_errors[self._sample_idxs] = error_sum.view(len(self._sample_idxs), 1, 1)
self.e_sampled[self._sample_idxs] = 1
self.buffer_sample_count[self._sample_idxs] = self.buffer_sample_count[self._sample_idxs] + 1
self.max_td_error = th.max(self.td_errors)
self.td_errors[(self.e_sampled == 0).nonzero()] = self.max_td_error
def __repr__(self):
return "PER ReplayBuffer. {}/{} episodes. Keys:{} Groups:{}".format(self.episodes_in_buffer,
self.buffer_size,
self.scheme.keys(),
self.groups.keys())
def save_td_per_distributions(per_buffer, path):
""" Saves PER distributions within the directory specified by `path`.
Path should not specify the file name.
"""
print(f'saving PER objects to {path}')
td_errors = th.flatten(per_buffer.td_errors).cpu().detach().numpy()
reward_sum_record = deepcopy(per_buffer.reward_sum_record)
e_sampled = th.flatten(per_buffer.e_sampled).cpu().detach().numpy()
b_sampled = th.flatten(per_buffer.buffer_sample_count).cpu().detach().numpy()
sample_count = deepcopy(per_buffer.sample_count)
per_beta = deepcopy(per_buffer.per_beta)
th.save({"td_errors": td_errors,
"reward_sum_record": reward_sum_record,
"e_sampled": e_sampled,
"buffer_sample_count": b_sampled,
"sample_count": sample_count,
"per_beta": per_beta},
"{}/per_objs.th".format(path)) | import pathlib
from copy import deepcopy
from math import floor
from typing import DefaultDict
from sympy import EX
import torch as th
import numpy as np
from types import SimpleNamespace as SN
from .episode_buffer import EpisodeBatch
from .epsilon_schedules import RiseThenFlatSchedule
class TD_PERBuffer(EpisodeBatch):
"""Implements non-uniform sampling from the episode buffer. Weighted proportionally based on episode return.
"""
def __init__(self, args, scheme, groups, buffer_size, max_seq_length, preprocess=None, device="cpu"):
"""
Args:
per_alpha: Exponent applied to the sum of the reward score and per_epsilon. Must lie in the range [0, 1].
per_epsilon: Constant added to reward score.
per_beta: importance sampling exponent, controls how much prioritization to apply. Must lie in the range [0, 1].
"""
super(TD_PERBuffer, self).__init__(scheme, groups, buffer_size, max_seq_length, preprocess=preprocess, device=device)
self.buffer_size = buffer_size # same as self.batch_size but more explicit
self.buffer_index = 0
self.episodes_in_buffer = 0
self.device = device
assert (args.per_alpha >= 0) and (args.per_alpha <= 1), "per_alpha is out of bounds, must lie in the range [0, 1]"
assert args.per_epsilon >= 0, "per_epsilon must be positive"
assert (args.per_beta >= 0) and (args.per_beta <= 1), "per_beta is out of bounds, must lie in the range [0, 1]"
assert (args.per_beta_anneal >= 0) and (args.per_beta_anneal <= 1), "per_beta_anneal is out of bounds, must lie in the range [0, 1]"
self.per_alpha = args.per_alpha
self.per_epsilon = args.per_epsilon
self.per_beta_schedule = RiseThenFlatSchedule(args.per_beta, 1, floor(args.t_max * args.per_beta_anneal), decay="linear")
self.per_beta = self.per_beta_schedule.eval(0)
self.max_td_error = args.per_epsilon
print(f'Initialising TD ERROR PER buffer, annealing beta from {args.per_beta} to 1 over {floor(args.t_max * args.per_beta_anneal)} timesteps.')
self.td_errors = th.zeros((buffer_size, 1, 1), device=self.device)
self.reward_sum = th.zeros((buffer_size, 1, 1), device=self.device)
self.e_sampled = th.zeros((buffer_size, 1, 1), device=self.device)
# for logging values
self.buffer_counter = 0
self.reward_sum_record = {}
self.sample_count = {}
self.buffer_sample_count = th.zeros((buffer_size, 1, 1), device=self.device)
def insert_episode_batch(self, ep_batch):
"""Insert episode into replay buffer.
Args:
ep_batch (EpiosdeBatch): Episode to be inserted
"""
#print(f'inserting episode batch, buffer idx {self.buffer_index}, ep batch size {ep_batch.batch_size}')
if self.buffer_index + ep_batch.batch_size <= self.buffer_size:
## PER values
assert ep_batch.batch_size == 1
self.td_errors[self.buffer_index] = (self.max_td_error)**self.per_alpha
self.e_sampled[self.buffer_index] = 0
self.update(ep_batch.data.transition_data,
slice(self.buffer_index, self.buffer_index + ep_batch.batch_size),
slice(0, ep_batch.max_seq_length),
mark_filled=False)
self.update(ep_batch.data.episode_data,
slice(self.buffer_index, self.buffer_index + ep_batch.batch_size))
self.reward_sum_record[self.buffer_counter] = th.sum(ep_batch["reward"]) # just for debugging
#print(f'buffer idx {self.buffer_index}, ep in buffer {self.episodes_in_buffer}, buffer counter {self.buffer_counter}')
if self.buffer_counter >= self.buffer_size:
self.sample_count[self.buffer_counter-self.buffer_size] = self.buffer_sample_count[self.buffer_index]
self.buffer_sample_count[self.buffer_index] = 0
self.buffer_counter += ep_batch.batch_size
# increment buffer index
self.buffer_index = (self.buffer_index + ep_batch.batch_size)
self.episodes_in_buffer = max(self.episodes_in_buffer, self.buffer_index)
self.buffer_index = self.buffer_index % self.buffer_size # resets buffer index once it is greater than buffer size, allows it to then remove oldest epsiodes
assert self.buffer_index < self.buffer_size
else:
buffer_left = self.buffer_size - self.buffer_index # i guess this is for when buffer_size % batch_size > 0
print(f' -- Uneaven entry to buffer -- ')
self.insert_episode_batch(ep_batch[0:buffer_left, :])
self.insert_episode_batch(ep_batch[buffer_left:, :])
def can_sample(self, batch_size):
return self.episodes_in_buffer > batch_size
def sample(self, batch_size, t):
"""Returns a sample of episodes from the replay buffer
Args:
batch_size (int): Number of episodes to return
t (int): training timestep at which sampling is occuring, used to anneal per_beta
"""
assert self.can_sample(batch_size)
if self.episodes_in_buffer == batch_size:
self._sample_idxs = np.arange(batch_size)
return self[:batch_size]
else:
probs = self.td_errors[:self.episodes_in_buffer]/th.sum(self.td_errors[:self.episodes_in_buffer], dim=0)
ep_ids = np.random.choice(self.episodes_in_buffer, batch_size, replace=False, p=th.flatten(probs).cpu().detach().numpy())
# Calculate importance sampling weights -- correct for bias introduced
self.per_beta = self.per_beta_schedule.eval(t)
is_weights = th.ones((batch_size, 1, 1), device=self.device) * 1/probs[ep_ids] * 1/self.episodes_in_buffer
is_weights = th.pow(is_weights, self.per_beta)
is_weights = is_weights/th.max(is_weights) # normalise
self.data.transition_data["weights"][ep_ids]= is_weights
# Update PER values for episodes sampled for first time # NOTE could be made more torchy
'''for i in ep_ids:
if not self.e_sampled[i]:
self.pvalues[i] = self.reward_sum[i] ** self.reward_power
self.e_sampled[i] = 1
self.buffer_sample_count[i] += 1'''
self._sample_idxs = ep_ids
return self[ep_ids]
def update_batch_td_errors(self, td_error):
"""
Args:
td_error: masked td errors
"""
error_sum = th.abs(th.sum(td_error, dim=1))
self.td_errors[self._sample_idxs] = error_sum.view(len(self._sample_idxs), 1, 1)
self.e_sampled[self._sample_idxs] = 1
self.buffer_sample_count[self._sample_idxs] = self.buffer_sample_count[self._sample_idxs] + 1
self.max_td_error = th.max(self.td_errors)
self.td_errors[(self.e_sampled == 0).nonzero()] = self.max_td_error
def __repr__(self):
return "PER ReplayBuffer. {}/{} episodes. Keys:{} Groups:{}".format(self.episodes_in_buffer,
self.buffer_size,
self.scheme.keys(),
self.groups.keys())
def save_td_per_distributions(per_buffer, path):
""" Saves PER distributions within the directory specified by `path`.
Path should not specify the file name.
"""
print(f'saving PER objects to {path}')
td_errors = th.flatten(per_buffer.td_errors).cpu().detach().numpy()
reward_sum_record = deepcopy(per_buffer.reward_sum_record)
e_sampled = th.flatten(per_buffer.e_sampled).cpu().detach().numpy()
b_sampled = th.flatten(per_buffer.buffer_sample_count).cpu().detach().numpy()
sample_count = deepcopy(per_buffer.sample_count)
per_beta = deepcopy(per_buffer.per_beta)
th.save({"td_errors": td_errors,
"reward_sum_record": reward_sum_record,
"e_sampled": e_sampled,
"buffer_sample_count": b_sampled,
"sample_count": sample_count,
"per_beta": per_beta},
"{}/per_objs.th".format(path)) | en | 0.741149 | Implements non-uniform sampling from the episode buffer. Weighted proportionally based on episode return. Args: per_alpha: Exponent applied to the sum of the reward score and per_epsilon. Must lie in the range [0, 1]. per_epsilon: Constant added to reward score. per_beta: importance sampling exponent, controls how much prioritization to apply. Must lie in the range [0, 1]. # same as self.batch_size but more explicit # for logging values Insert episode into replay buffer. Args: ep_batch (EpiosdeBatch): Episode to be inserted #print(f'inserting episode batch, buffer idx {self.buffer_index}, ep batch size {ep_batch.batch_size}') ## PER values # just for debugging #print(f'buffer idx {self.buffer_index}, ep in buffer {self.episodes_in_buffer}, buffer counter {self.buffer_counter}') # increment buffer index # resets buffer index once it is greater than buffer size, allows it to then remove oldest epsiodes # i guess this is for when buffer_size % batch_size > 0 Returns a sample of episodes from the replay buffer Args: batch_size (int): Number of episodes to return t (int): training timestep at which sampling is occuring, used to anneal per_beta # Calculate importance sampling weights -- correct for bias introduced # normalise # Update PER values for episodes sampled for first time # NOTE could be made more torchy for i in ep_ids: if not self.e_sampled[i]: self.pvalues[i] = self.reward_sum[i] ** self.reward_power self.e_sampled[i] = 1 self.buffer_sample_count[i] += 1 Args: td_error: masked td errors Saves PER distributions within the directory specified by `path`. Path should not specify the file name. | 2.248897 | 2 |
tests/test_ga.py | R3bs/darwin | 0 | 6618906 | <filename>tests/test_ga.py<gh_stars>0
import pytest
import darwin
import numpy as np
# define the mapping parameters used
x = (-200,+200)
y = (-1000,+1000)
# discrete used
map1 = (0,1,2,3)
map2 = ('a', 'b', 'c', 'd')
def test_htcondor_ga_continuous(supplyFitnessFunction):
ga = darwin.Algorithm(darwin.opt.GeneticAlgorithm)
ga.mutationProbability = np.random.uniform(0.05, 0.25)
ga.particles = np.random.randint(5, 15)
ga.iterations = np.random.randint(5, 15)
ga.executionEngine = darwin.drm.HTCondor
ga.addVariable('x', x)
ga.addVariable('y', y)
ga.function = supplyFitnessFunction
ga.submitFile = 'sanity.submit'
ga.start()
def test_htcondor_ga_discrete(supplyDiscreteFitnessFunction):
ga = darwin.Algorithm(darwin.opt.GeneticAlgorithm)
ga.mutationProbability = np.random.uniform(0.05, 0.25)
ga.particles = np.random.randint(5, 15)
ga.iterations = np.random.randint(5, 15)
ga.executionEngine = darwin.drm.HTCondor
ga.addVariable('map1', map1, discrete=True)
ga.addVariable('map2', map2, discrete=True)
ga.function = supplyDiscreteFitnessFunction
ga.submitFile = 'sanity_discrete.submit'
ga.start()
def test_local_ga_continuous(supplyFitnessFunction):
ga = darwin.Algorithm(darwin.opt.GeneticAlgorithm)
ga.mutationProbability = np.random.uniform(0.05, 0.25)
ga.particles = np.random.randint(5, 15)
ga.iterations = np.random.randint(5, 15)
ga.executionEngine = darwin.drm.TaskSpooler
ga.addVariable('x', x)
ga.addVariable('y', y)
ga.function = supplyFitnessFunction
ga.submitFile = 'sanity.submit'
ga.start()
def test_local_ga_discrete(supplyDiscreteFitnessFunction):
ga = darwin.Algorithm(darwin.opt.GeneticAlgorithm)
ga.mutationProbability = np.random.uniform(0.05, 0.25)
ga.particles = np.random.randint(5, 15)
ga.iterations = np.random.randint(5, 15)
ga.executionEngine = darwin.drm.TaskSpooler
ga.addVariable('map1', map1, discrete=True)
ga.addVariable('map2', map2, discrete=True)
ga.function = supplyDiscreteFitnessFunction
ga.submitFile = 'sanity_discrete.submit'
ga.start()
| <filename>tests/test_ga.py<gh_stars>0
import pytest
import darwin
import numpy as np
# define the mapping parameters used
x = (-200,+200)
y = (-1000,+1000)
# discrete used
map1 = (0,1,2,3)
map2 = ('a', 'b', 'c', 'd')
def test_htcondor_ga_continuous(supplyFitnessFunction):
ga = darwin.Algorithm(darwin.opt.GeneticAlgorithm)
ga.mutationProbability = np.random.uniform(0.05, 0.25)
ga.particles = np.random.randint(5, 15)
ga.iterations = np.random.randint(5, 15)
ga.executionEngine = darwin.drm.HTCondor
ga.addVariable('x', x)
ga.addVariable('y', y)
ga.function = supplyFitnessFunction
ga.submitFile = 'sanity.submit'
ga.start()
def test_htcondor_ga_discrete(supplyDiscreteFitnessFunction):
ga = darwin.Algorithm(darwin.opt.GeneticAlgorithm)
ga.mutationProbability = np.random.uniform(0.05, 0.25)
ga.particles = np.random.randint(5, 15)
ga.iterations = np.random.randint(5, 15)
ga.executionEngine = darwin.drm.HTCondor
ga.addVariable('map1', map1, discrete=True)
ga.addVariable('map2', map2, discrete=True)
ga.function = supplyDiscreteFitnessFunction
ga.submitFile = 'sanity_discrete.submit'
ga.start()
def test_local_ga_continuous(supplyFitnessFunction):
ga = darwin.Algorithm(darwin.opt.GeneticAlgorithm)
ga.mutationProbability = np.random.uniform(0.05, 0.25)
ga.particles = np.random.randint(5, 15)
ga.iterations = np.random.randint(5, 15)
ga.executionEngine = darwin.drm.TaskSpooler
ga.addVariable('x', x)
ga.addVariable('y', y)
ga.function = supplyFitnessFunction
ga.submitFile = 'sanity.submit'
ga.start()
def test_local_ga_discrete(supplyDiscreteFitnessFunction):
ga = darwin.Algorithm(darwin.opt.GeneticAlgorithm)
ga.mutationProbability = np.random.uniform(0.05, 0.25)
ga.particles = np.random.randint(5, 15)
ga.iterations = np.random.randint(5, 15)
ga.executionEngine = darwin.drm.TaskSpooler
ga.addVariable('map1', map1, discrete=True)
ga.addVariable('map2', map2, discrete=True)
ga.function = supplyDiscreteFitnessFunction
ga.submitFile = 'sanity_discrete.submit'
ga.start()
| en | 0.103653 | # define the mapping parameters used # discrete used | 2.15593 | 2 |
atoms_and_modules/stats_tools.py | bcdarwin/pydpiper | 0 | 6618907 | from pydpiper.pipeline import Pipeline, CmdStage, InputFile, OutputFile, LogFile
from atoms_and_modules.registration_functions import isFileHandler
from atoms_and_modules.minc_atoms import xfmConcat, xfmInvert
import pydpiper.file_handling as fh
from optparse import OptionGroup
import sys
def addStatsOptions(parser):
group = OptionGroup(parser, "Statistics options",
"Options for calculating statistics.")
group.add_option("--calc-stats", dest="calc_stats",
action="store_true",
help="Calculate statistics at the end of the registration. [Default]")
group.add_option("--no-calc-stats", dest="calc_stats",
action="store_false",
help="If specified, statistics are not calculated. Opposite of --calc-stats.")
group.add_option("--stats-kernels", dest="stats_kernels",
type="string", default="1.0,0.5,0.2,0.1",
help="comma separated list of blurring kernels for analysis. Default is: 1.0,0.5,0.2,0.1")
parser.set_defaults(calc_stats=True)
parser.add_option_group(group)
def createOutputFileName(iFH, xfm, outputDir, nameExt):
outDir = iFH.setOutputDirectory(outputDir)
outBase = fh.removeBaseAndExtension(xfm) + nameExt
outputFile = fh.createBaseName(outDir, outBase)
return outputFile
class StatsGroup(object):
"""This group saves the key output from each instance for CalcStats,
so it can easily be retrieved later."""
def __init__(self):
self.relativeJacobians = {}
self.absoluteJacobians = {}
class CalcStats(object):
"""Statistics calculation between an input and target.
This class calculates multiple displacement fields, relative and absolute jacobians.
General functionality as follows:
1. Class instantiated with input, target and statsKernels. Note that here, the statsKernels
specified are blurs used to smooth the displacement fields prior to additional calculations.
They may be a string of comma separated values or an array of doubles.
2. An additional transform may also be included to calculate absolute
jacobians to a different space, as is described in the __init__ function,
documentation and elsewhere in the code.
3. If needed, invert transform between input and target in setupXfms(). This is necessary
as this class assumes that the target is the reference space, from which all stats
are calculated.
4. Call fullStatsCalc. This calculates linear and
pure nonlinear displacement before calculating jacobians.
5. Ability to recenter displacements using an average may be re-added in the future.
"""
def __init__(self, inputFH, targetFH, statsKernels, additionalXfm=None):
self.p = Pipeline()
self.inputFH = inputFH
self.targetFH = targetFH
self.blurs = []
self.setupBlurs(statsKernels)
self.statsGroup = StatsGroup()
self.setupXfms()
""" additionalXfm is an optional transform that may be specified. If it is,
it is concatenated with the lastXfm from input to target. This additional
transform must also be in the same direction as the lastXfm (e.g. input to target)
Example usage: if the lastXfm from input to target goes from lsq12 to nlin space
and you would like to calculate the absolute jacobians to lsq6 space, the additional
transform specified may be the lsq6 to lsq12 transform from input to target.
"""
self.additionalXfm = additionalXfm
self.fullStatsCalc()
def setupBlurs(self, statsKernels):
if isinstance(statsKernels, list):
self.blurs = statsKernels
elif isinstance(statsKernels, str):
for i in statsKernels.split(","):
self.blurs.append(float(i))
else:
print "Improper type of blurring kernels specified for stats calculation: " + str(statsKernels)
sys.exit()
def setupXfms(self):
self.xfm = self.inputFH.getLastXfm(self.targetFH)
if not self.xfm:
print "Cannot calculate statistics. No transform between input and target specified."
print "Input: " + self.inputFH.getLastBasevol()
print "Target: " + self.targetFH.getLastBasevol()
sys.exit()
else:
self.invXfm = self.targetFH.getLastXfm(self.inputFH)
if not self.invXfm:
xi = xfmInvert(self.xfm, FH=self.inputFH)
self.p.addStage(xi)
self.invXfm = xi.outputFiles[0]
def fullStatsCalc(self):
self.linAndNlinDisplacement()
self.calcDetAndLogDet(useFullDisp=False) # Calculate relative jacobians
self.calcDetAndLogDet(useFullDisp=True) # Calculate absolute jacobians
def calcFullDisplacement(self):
"""Calculate full displacement from target to input. If an
additionaXfm is specified, it is concatenated to self.xfm here """
if self.additionalXfm:
outXfm = createOutputFileName(self.inputFH, self.xfm, "transforms", "_with_additional.xfm")
xc = xfmConcat([self.additionalXfm, self.xfm], outXfm, fh.logFromFile(self.inputFH.logDir, outXfm))
self.p.addStage(xc)
xi = xfmInvert(xc.outputFiles[0], FH=self.inputFH)
self.p.addStage(xi)
fullDisp = mincDisplacement(self.targetFH, self.inputFH, transform=xi.outputFiles[0])
else:
fullDisp = mincDisplacement(self.targetFH, self.inputFH, transform=self.invXfm)
self.p.addStage(fullDisp)
self.fullDisp = fullDisp.outputFiles[0]
def calcNlinDisplacement(self):
"""Calculate pure non-linear displacement from target to input
1. Concatenate self.invXfm (target to input xfm) and self.linearPartOfNlinXfm
2. Compute mincDisplacement on this transform.
"""
pureNlinXfm = createOutputFileName(self.inputFH, self.invXfm, "transforms", "_pure_nlin.xfm")
xc = xfmConcat([self.invXfm, self.linearPartOfNlinXfm],
pureNlinXfm, fh.logFromFile(self.inputFH.logDir, pureNlinXfm))
self.p.addStage(xc)
nlinDisp = mincDisplacement(self.targetFH, self.inputFH, transform=pureNlinXfm)
self.p.addStage(nlinDisp)
self.nlinDisp = nlinDisp.outputFiles[0]
def linAndNlinDisplacement(self):
"""
Calculation of full and pure non-linear displacements.
The former is used to calculate absolute jacobians,
the latter to calculate relative. The direction of the
transforms and displacements is defined in each subclass.
"""
#1. Calculate linear part of non-linear xfm from input to target.
# This is necessary prior to calculating the pure nonlinear displacement
lpnl = linearPartofNlin(self.inputFH, self.targetFH)
self.p.addStage(lpnl)
self.linearPartOfNlinXfm = lpnl.outputFiles[0]
# 2. Calculate the pure non-linear displacement
self.calcNlinDisplacement()
# 3. Calculate the full displacement
self.calcFullDisplacement()
def calcDetAndLogDet(self, useFullDisp=False):
if useFullDisp:
dispToUse = self.fullDisp #absolute jacobians
else:
dispToUse = self.nlinDisp #relative jacobians
"""Insert -1 at beginning of blurs array to include the calculation of unblurred jacobians."""
self.blurs.insert(0,-1)
for b in self.blurs:
"""Create base name for determinant calculation."""
outputBase = fh.removeBaseAndExtension(dispToUse).split("_displacement")[0]
"""Calculate smoothed deformation field for all blurs other than -1"""
if b != -1:
fwhm = "--fwhm=" + str(b)
outSmooth = fh.createBaseName(self.inputFH.tmpDir,
outputBase + "_smooth_displacement_fwhm" + str(b) + ".mnc")
cmd = ["smooth_vector", "--clobber", "--filter", fwhm,
InputFile(dispToUse), OutputFile(outSmooth)]
smoothVec = CmdStage(cmd)
smoothVec.setLogFile(LogFile(fh.logFromFile(self.inputFH.logDir, outSmooth)))
self.p.addStage(smoothVec)
"""Set input for determinant calculation."""
inputDet = outSmooth
nameAddendum = "_fwhm" + str(b)
else:
inputDet = dispToUse
nameAddendum = ""
outputDet = fh.createBaseName(self.inputFH.tmpDir,
outputBase + "_determinant" + nameAddendum + ".mnc")
outDetShift = fh.createBaseName(self.inputFH.tmpDir,
outputBase + "_det_plus1" + nameAddendum + ".mnc")
if useFullDisp:
#absolute jacobians
outLogDet = fh.createBaseName(self.inputFH.statsDir,
outputBase + "_absolute_log_determinant" + nameAddendum + ".mnc")
else:
#relative jacobians
outLogDet = fh.createBaseName(self.inputFH.statsDir,
outputBase + "_relative_log_determinant" + nameAddendum + ".mnc")
"""Calculate the determinant, then add 1 (per mincblob weirdness)"""
cmd = ["mincblob", "-clobber", "-determinant", InputFile(inputDet), OutputFile(outputDet)]
det = CmdStage(cmd)
det.setLogFile(LogFile(fh.logFromFile(self.inputFH.logDir, outputDet)))
self.p.addStage(det)
cmd = ["mincmath", "-clobber", "-2", "-const", str(1), "-add",
InputFile(outputDet), OutputFile(outDetShift)]
det = CmdStage(cmd)
det.setLogFile(LogFile(fh.logFromFile(self.inputFH.logDir, outDetShift)))
self.p.addStage(det)
"""Calculate log determinant (jacobian) and add to statsGroup."""
cmd = ["mincmath", "-clobber", "-2", "-log", InputFile(outDetShift), OutputFile(outLogDet)]
det = CmdStage(cmd)
det.setLogFile(LogFile(fh.logFromFile(self.inputFH.logDir, outLogDet)))
self.p.addStage(det)
if useFullDisp:
self.statsGroup.absoluteJacobians[b] = outLogDet
else:
self.statsGroup.relativeJacobians[b] = outLogDet
class CalcChainStats(CalcStats):
"""This class calculates multiple displacement fields, absolute and relative
jacobians. IT DOES NOT allow for adding an additional transform, as in the
base class (CalcStats). This child class is designed specifically for the
registration chain application (or similar) and has less complexity than CalcStats()"""
def __init__(self, inputFH, targetFH, statsKernels):
CalcStats.__init__(self, inputFH, targetFH, statsKernels)
def setupXfms(self):
self.xfm = self.inputFH.getLastXfm(self.targetFH)
if not self.xfm:
print "Cannot calculate statistics. No transform between input and target specified."
sys.exit()
def calcFullDisplacement(self):
"""Calculates the full displacement from input to target without removing
the linear part. Note that inputFH is deliberately specified twice in the
mincDisplacement call: Once as the input space, and once for the location
of the log files. """
fullDisp = mincDisplacement(self.inputFH, self.inputFH, transform=self.xfm)
self.p.addStage(fullDisp)
self.fullDisp = fullDisp.outputFiles[0]
def calcNlinDisplacement(self):
"""Calculate pure non-linear displacement from input to target
1. Invert the linear transform, so we get the linear xfm from target to input.
2. Concatenate the full non-linear (input to target) transform with the
linear target to input transform.
3. Calculate the displacement on this transform. """
xi = xfmInvert(self.linearPartOfNlinXfm, FH=self.inputFH)
self.p.addStage(xi)
pureNlinXfm = createOutputFileName(self.inputFH, self.xfm, "transforms", "_pure_nlin.xfm")
xc = xfmConcat([self.xfm, xi.outputFiles[0]],
pureNlinXfm, fh.logFromFile(self.inputFH.logDir, pureNlinXfm))
self.p.addStage(xc)
nlinDisp = mincDisplacement(self.inputFH, self.inputFH, transform=pureNlinXfm)
self.p.addStage(nlinDisp)
self.nlinDisp = nlinDisp.outputFiles[0]
class linearPartofNlin(CmdStage):
def __init__(self, inputFH, targetFH, defaultDir="transforms"):
CmdStage.__init__(self, None)
try:
if isFileHandler(inputFH, targetFH):
self.inFile = inputFH.getLastBasevol()
self.mask = inputFH.getMask()
self.xfm = inputFH.getLastXfm(targetFH)
self.outfile = self.setOutputFile(inputFH, defaultDir)
self.logFile = fh.logFromFile(inputFH.logDir, self.outfile)
else:
print ("linear part of nlin currently only works using file handlers. "
"Exception being raised.")
raise
except:
print "Failed in putting together linearPartofNlin command"
print "Unexpected error: ", sys.exc_info()
self.addDefaults()
self.finalizeCommand()
self.setName()
def addDefaults(self):
self.inputFiles += [self.inFile, self.xfm]
self.outputFiles += [self.outfile]
self.cmd += ["lin_from_nlin",
"-clobber", "-lsq12"]
if self.mask:
self.inputFiles += [self.mask]
self.cmd += ["-mask", self.mask]
def finalizeCommand(self):
self.cmd += [self.inFile, self.xfm, self.outfile]
def setName(self):
self.name = "lin_from_nlin "
def setOutputFile(self, inFile, defaultDir):
outDir = inFile.setOutputDirectory(defaultDir)
outBase = (fh.removeBaseAndExtension(self.xfm) + "_linear_part.xfm")
outputFile = fh.createBaseName(outDir, outBase)
return(outputFile)
class mincDisplacement(CmdStage):
"""This class calculates the displacement from an input
volume, using a specified transform from this input to
another volume. Must specify input volume, transform from
that volume to a target, and an outputFH, which is where
the output and log files should be stored. The outputFH
and inputFH may be the same volume. A default directory
for the output may optionally be specified, but is tmp if
unspecified.
"""
def __init__(self, inputFH, outputFH, transform, defaultDir="tmp"):
CmdStage.__init__(self, None)
try:
if isFileHandler(inputFH, outputFH):
self.inFile = inputFH.getLastBasevol()
self.xfm = transform
self.outfile = createOutputFileName(outputFH, self.xfm, defaultDir, "_displacement.mnc")
self.logFile = fh.logFromFile(outputFH.logDir, self.outfile)
else:
print ("minc_displacement only works using file handlers. "
"Exception being raised.")
raise
except:
print "Failed in putting together minc_displacement command"
print "Unexpected error: ", sys.exc_info()
self.addDefaults()
self.finalizeCommand()
self.setName()
def addDefaults(self):
self.inputFiles += [self.inFile, self.xfm]
self.outputFiles += [self.outfile]
self.cmd += ["minc_displacement", "-clobber"]
def finalizeCommand(self):
self.cmd += [self.inFile, self.xfm, self.outfile]
def setName(self):
self.name = "minc_displacement "
| from pydpiper.pipeline import Pipeline, CmdStage, InputFile, OutputFile, LogFile
from atoms_and_modules.registration_functions import isFileHandler
from atoms_and_modules.minc_atoms import xfmConcat, xfmInvert
import pydpiper.file_handling as fh
from optparse import OptionGroup
import sys
def addStatsOptions(parser):
group = OptionGroup(parser, "Statistics options",
"Options for calculating statistics.")
group.add_option("--calc-stats", dest="calc_stats",
action="store_true",
help="Calculate statistics at the end of the registration. [Default]")
group.add_option("--no-calc-stats", dest="calc_stats",
action="store_false",
help="If specified, statistics are not calculated. Opposite of --calc-stats.")
group.add_option("--stats-kernels", dest="stats_kernels",
type="string", default="1.0,0.5,0.2,0.1",
help="comma separated list of blurring kernels for analysis. Default is: 1.0,0.5,0.2,0.1")
parser.set_defaults(calc_stats=True)
parser.add_option_group(group)
def createOutputFileName(iFH, xfm, outputDir, nameExt):
outDir = iFH.setOutputDirectory(outputDir)
outBase = fh.removeBaseAndExtension(xfm) + nameExt
outputFile = fh.createBaseName(outDir, outBase)
return outputFile
class StatsGroup(object):
"""This group saves the key output from each instance for CalcStats,
so it can easily be retrieved later."""
def __init__(self):
self.relativeJacobians = {}
self.absoluteJacobians = {}
class CalcStats(object):
"""Statistics calculation between an input and target.
This class calculates multiple displacement fields, relative and absolute jacobians.
General functionality as follows:
1. Class instantiated with input, target and statsKernels. Note that here, the statsKernels
specified are blurs used to smooth the displacement fields prior to additional calculations.
They may be a string of comma separated values or an array of doubles.
2. An additional transform may also be included to calculate absolute
jacobians to a different space, as is described in the __init__ function,
documentation and elsewhere in the code.
3. If needed, invert transform between input and target in setupXfms(). This is necessary
as this class assumes that the target is the reference space, from which all stats
are calculated.
4. Call fullStatsCalc. This calculates linear and
pure nonlinear displacement before calculating jacobians.
5. Ability to recenter displacements using an average may be re-added in the future.
"""
def __init__(self, inputFH, targetFH, statsKernels, additionalXfm=None):
self.p = Pipeline()
self.inputFH = inputFH
self.targetFH = targetFH
self.blurs = []
self.setupBlurs(statsKernels)
self.statsGroup = StatsGroup()
self.setupXfms()
""" additionalXfm is an optional transform that may be specified. If it is,
it is concatenated with the lastXfm from input to target. This additional
transform must also be in the same direction as the lastXfm (e.g. input to target)
Example usage: if the lastXfm from input to target goes from lsq12 to nlin space
and you would like to calculate the absolute jacobians to lsq6 space, the additional
transform specified may be the lsq6 to lsq12 transform from input to target.
"""
self.additionalXfm = additionalXfm
self.fullStatsCalc()
def setupBlurs(self, statsKernels):
if isinstance(statsKernels, list):
self.blurs = statsKernels
elif isinstance(statsKernels, str):
for i in statsKernels.split(","):
self.blurs.append(float(i))
else:
print "Improper type of blurring kernels specified for stats calculation: " + str(statsKernels)
sys.exit()
def setupXfms(self):
self.xfm = self.inputFH.getLastXfm(self.targetFH)
if not self.xfm:
print "Cannot calculate statistics. No transform between input and target specified."
print "Input: " + self.inputFH.getLastBasevol()
print "Target: " + self.targetFH.getLastBasevol()
sys.exit()
else:
self.invXfm = self.targetFH.getLastXfm(self.inputFH)
if not self.invXfm:
xi = xfmInvert(self.xfm, FH=self.inputFH)
self.p.addStage(xi)
self.invXfm = xi.outputFiles[0]
def fullStatsCalc(self):
self.linAndNlinDisplacement()
self.calcDetAndLogDet(useFullDisp=False) # Calculate relative jacobians
self.calcDetAndLogDet(useFullDisp=True) # Calculate absolute jacobians
def calcFullDisplacement(self):
"""Calculate full displacement from target to input. If an
additionaXfm is specified, it is concatenated to self.xfm here """
if self.additionalXfm:
outXfm = createOutputFileName(self.inputFH, self.xfm, "transforms", "_with_additional.xfm")
xc = xfmConcat([self.additionalXfm, self.xfm], outXfm, fh.logFromFile(self.inputFH.logDir, outXfm))
self.p.addStage(xc)
xi = xfmInvert(xc.outputFiles[0], FH=self.inputFH)
self.p.addStage(xi)
fullDisp = mincDisplacement(self.targetFH, self.inputFH, transform=xi.outputFiles[0])
else:
fullDisp = mincDisplacement(self.targetFH, self.inputFH, transform=self.invXfm)
self.p.addStage(fullDisp)
self.fullDisp = fullDisp.outputFiles[0]
def calcNlinDisplacement(self):
"""Calculate pure non-linear displacement from target to input
1. Concatenate self.invXfm (target to input xfm) and self.linearPartOfNlinXfm
2. Compute mincDisplacement on this transform.
"""
pureNlinXfm = createOutputFileName(self.inputFH, self.invXfm, "transforms", "_pure_nlin.xfm")
xc = xfmConcat([self.invXfm, self.linearPartOfNlinXfm],
pureNlinXfm, fh.logFromFile(self.inputFH.logDir, pureNlinXfm))
self.p.addStage(xc)
nlinDisp = mincDisplacement(self.targetFH, self.inputFH, transform=pureNlinXfm)
self.p.addStage(nlinDisp)
self.nlinDisp = nlinDisp.outputFiles[0]
def linAndNlinDisplacement(self):
"""
Calculation of full and pure non-linear displacements.
The former is used to calculate absolute jacobians,
the latter to calculate relative. The direction of the
transforms and displacements is defined in each subclass.
"""
#1. Calculate linear part of non-linear xfm from input to target.
# This is necessary prior to calculating the pure nonlinear displacement
lpnl = linearPartofNlin(self.inputFH, self.targetFH)
self.p.addStage(lpnl)
self.linearPartOfNlinXfm = lpnl.outputFiles[0]
# 2. Calculate the pure non-linear displacement
self.calcNlinDisplacement()
# 3. Calculate the full displacement
self.calcFullDisplacement()
def calcDetAndLogDet(self, useFullDisp=False):
if useFullDisp:
dispToUse = self.fullDisp #absolute jacobians
else:
dispToUse = self.nlinDisp #relative jacobians
"""Insert -1 at beginning of blurs array to include the calculation of unblurred jacobians."""
self.blurs.insert(0,-1)
for b in self.blurs:
"""Create base name for determinant calculation."""
outputBase = fh.removeBaseAndExtension(dispToUse).split("_displacement")[0]
"""Calculate smoothed deformation field for all blurs other than -1"""
if b != -1:
fwhm = "--fwhm=" + str(b)
outSmooth = fh.createBaseName(self.inputFH.tmpDir,
outputBase + "_smooth_displacement_fwhm" + str(b) + ".mnc")
cmd = ["smooth_vector", "--clobber", "--filter", fwhm,
InputFile(dispToUse), OutputFile(outSmooth)]
smoothVec = CmdStage(cmd)
smoothVec.setLogFile(LogFile(fh.logFromFile(self.inputFH.logDir, outSmooth)))
self.p.addStage(smoothVec)
"""Set input for determinant calculation."""
inputDet = outSmooth
nameAddendum = "_fwhm" + str(b)
else:
inputDet = dispToUse
nameAddendum = ""
outputDet = fh.createBaseName(self.inputFH.tmpDir,
outputBase + "_determinant" + nameAddendum + ".mnc")
outDetShift = fh.createBaseName(self.inputFH.tmpDir,
outputBase + "_det_plus1" + nameAddendum + ".mnc")
if useFullDisp:
#absolute jacobians
outLogDet = fh.createBaseName(self.inputFH.statsDir,
outputBase + "_absolute_log_determinant" + nameAddendum + ".mnc")
else:
#relative jacobians
outLogDet = fh.createBaseName(self.inputFH.statsDir,
outputBase + "_relative_log_determinant" + nameAddendum + ".mnc")
"""Calculate the determinant, then add 1 (per mincblob weirdness)"""
cmd = ["mincblob", "-clobber", "-determinant", InputFile(inputDet), OutputFile(outputDet)]
det = CmdStage(cmd)
det.setLogFile(LogFile(fh.logFromFile(self.inputFH.logDir, outputDet)))
self.p.addStage(det)
cmd = ["mincmath", "-clobber", "-2", "-const", str(1), "-add",
InputFile(outputDet), OutputFile(outDetShift)]
det = CmdStage(cmd)
det.setLogFile(LogFile(fh.logFromFile(self.inputFH.logDir, outDetShift)))
self.p.addStage(det)
"""Calculate log determinant (jacobian) and add to statsGroup."""
cmd = ["mincmath", "-clobber", "-2", "-log", InputFile(outDetShift), OutputFile(outLogDet)]
det = CmdStage(cmd)
det.setLogFile(LogFile(fh.logFromFile(self.inputFH.logDir, outLogDet)))
self.p.addStage(det)
if useFullDisp:
self.statsGroup.absoluteJacobians[b] = outLogDet
else:
self.statsGroup.relativeJacobians[b] = outLogDet
class CalcChainStats(CalcStats):
"""This class calculates multiple displacement fields, absolute and relative
jacobians. IT DOES NOT allow for adding an additional transform, as in the
base class (CalcStats). This child class is designed specifically for the
registration chain application (or similar) and has less complexity than CalcStats()"""
def __init__(self, inputFH, targetFH, statsKernels):
CalcStats.__init__(self, inputFH, targetFH, statsKernels)
def setupXfms(self):
self.xfm = self.inputFH.getLastXfm(self.targetFH)
if not self.xfm:
print "Cannot calculate statistics. No transform between input and target specified."
sys.exit()
def calcFullDisplacement(self):
"""Calculates the full displacement from input to target without removing
the linear part. Note that inputFH is deliberately specified twice in the
mincDisplacement call: Once as the input space, and once for the location
of the log files. """
fullDisp = mincDisplacement(self.inputFH, self.inputFH, transform=self.xfm)
self.p.addStage(fullDisp)
self.fullDisp = fullDisp.outputFiles[0]
def calcNlinDisplacement(self):
"""Calculate pure non-linear displacement from input to target
1. Invert the linear transform, so we get the linear xfm from target to input.
2. Concatenate the full non-linear (input to target) transform with the
linear target to input transform.
3. Calculate the displacement on this transform. """
xi = xfmInvert(self.linearPartOfNlinXfm, FH=self.inputFH)
self.p.addStage(xi)
pureNlinXfm = createOutputFileName(self.inputFH, self.xfm, "transforms", "_pure_nlin.xfm")
xc = xfmConcat([self.xfm, xi.outputFiles[0]],
pureNlinXfm, fh.logFromFile(self.inputFH.logDir, pureNlinXfm))
self.p.addStage(xc)
nlinDisp = mincDisplacement(self.inputFH, self.inputFH, transform=pureNlinXfm)
self.p.addStage(nlinDisp)
self.nlinDisp = nlinDisp.outputFiles[0]
class linearPartofNlin(CmdStage):
def __init__(self, inputFH, targetFH, defaultDir="transforms"):
CmdStage.__init__(self, None)
try:
if isFileHandler(inputFH, targetFH):
self.inFile = inputFH.getLastBasevol()
self.mask = inputFH.getMask()
self.xfm = inputFH.getLastXfm(targetFH)
self.outfile = self.setOutputFile(inputFH, defaultDir)
self.logFile = fh.logFromFile(inputFH.logDir, self.outfile)
else:
print ("linear part of nlin currently only works using file handlers. "
"Exception being raised.")
raise
except:
print "Failed in putting together linearPartofNlin command"
print "Unexpected error: ", sys.exc_info()
self.addDefaults()
self.finalizeCommand()
self.setName()
def addDefaults(self):
self.inputFiles += [self.inFile, self.xfm]
self.outputFiles += [self.outfile]
self.cmd += ["lin_from_nlin",
"-clobber", "-lsq12"]
if self.mask:
self.inputFiles += [self.mask]
self.cmd += ["-mask", self.mask]
def finalizeCommand(self):
self.cmd += [self.inFile, self.xfm, self.outfile]
def setName(self):
self.name = "lin_from_nlin "
def setOutputFile(self, inFile, defaultDir):
outDir = inFile.setOutputDirectory(defaultDir)
outBase = (fh.removeBaseAndExtension(self.xfm) + "_linear_part.xfm")
outputFile = fh.createBaseName(outDir, outBase)
return(outputFile)
class mincDisplacement(CmdStage):
"""This class calculates the displacement from an input
volume, using a specified transform from this input to
another volume. Must specify input volume, transform from
that volume to a target, and an outputFH, which is where
the output and log files should be stored. The outputFH
and inputFH may be the same volume. A default directory
for the output may optionally be specified, but is tmp if
unspecified.
"""
def __init__(self, inputFH, outputFH, transform, defaultDir="tmp"):
CmdStage.__init__(self, None)
try:
if isFileHandler(inputFH, outputFH):
self.inFile = inputFH.getLastBasevol()
self.xfm = transform
self.outfile = createOutputFileName(outputFH, self.xfm, defaultDir, "_displacement.mnc")
self.logFile = fh.logFromFile(outputFH.logDir, self.outfile)
else:
print ("minc_displacement only works using file handlers. "
"Exception being raised.")
raise
except:
print "Failed in putting together minc_displacement command"
print "Unexpected error: ", sys.exc_info()
self.addDefaults()
self.finalizeCommand()
self.setName()
def addDefaults(self):
self.inputFiles += [self.inFile, self.xfm]
self.outputFiles += [self.outfile]
self.cmd += ["minc_displacement", "-clobber"]
def finalizeCommand(self):
self.cmd += [self.inFile, self.xfm, self.outfile]
def setName(self):
self.name = "minc_displacement "
| en | 0.804044 | This group saves the key output from each instance for CalcStats, so it can easily be retrieved later. Statistics calculation between an input and target. This class calculates multiple displacement fields, relative and absolute jacobians. General functionality as follows: 1. Class instantiated with input, target and statsKernels. Note that here, the statsKernels specified are blurs used to smooth the displacement fields prior to additional calculations. They may be a string of comma separated values or an array of doubles. 2. An additional transform may also be included to calculate absolute jacobians to a different space, as is described in the __init__ function, documentation and elsewhere in the code. 3. If needed, invert transform between input and target in setupXfms(). This is necessary as this class assumes that the target is the reference space, from which all stats are calculated. 4. Call fullStatsCalc. This calculates linear and pure nonlinear displacement before calculating jacobians. 5. Ability to recenter displacements using an average may be re-added in the future. additionalXfm is an optional transform that may be specified. If it is, it is concatenated with the lastXfm from input to target. This additional transform must also be in the same direction as the lastXfm (e.g. input to target) Example usage: if the lastXfm from input to target goes from lsq12 to nlin space and you would like to calculate the absolute jacobians to lsq6 space, the additional transform specified may be the lsq6 to lsq12 transform from input to target. # Calculate relative jacobians # Calculate absolute jacobians Calculate full displacement from target to input. If an additionaXfm is specified, it is concatenated to self.xfm here Calculate pure non-linear displacement from target to input 1. Concatenate self.invXfm (target to input xfm) and self.linearPartOfNlinXfm 2. Compute mincDisplacement on this transform. Calculation of full and pure non-linear displacements. The former is used to calculate absolute jacobians, the latter to calculate relative. The direction of the transforms and displacements is defined in each subclass. #1. Calculate linear part of non-linear xfm from input to target. # This is necessary prior to calculating the pure nonlinear displacement # 2. Calculate the pure non-linear displacement # 3. Calculate the full displacement #absolute jacobians #relative jacobians Insert -1 at beginning of blurs array to include the calculation of unblurred jacobians. Create base name for determinant calculation. Calculate smoothed deformation field for all blurs other than -1 Set input for determinant calculation. #absolute jacobians #relative jacobians Calculate the determinant, then add 1 (per mincblob weirdness) Calculate log determinant (jacobian) and add to statsGroup. This class calculates multiple displacement fields, absolute and relative jacobians. IT DOES NOT allow for adding an additional transform, as in the base class (CalcStats). This child class is designed specifically for the registration chain application (or similar) and has less complexity than CalcStats() Calculates the full displacement from input to target without removing the linear part. Note that inputFH is deliberately specified twice in the mincDisplacement call: Once as the input space, and once for the location of the log files. Calculate pure non-linear displacement from input to target 1. Invert the linear transform, so we get the linear xfm from target to input. 2. Concatenate the full non-linear (input to target) transform with the linear target to input transform. 3. Calculate the displacement on this transform. This class calculates the displacement from an input volume, using a specified transform from this input to another volume. Must specify input volume, transform from that volume to a target, and an outputFH, which is where the output and log files should be stored. The outputFH and inputFH may be the same volume. A default directory for the output may optionally be specified, but is tmp if unspecified. | 2.211188 | 2 |
scratchnetwork/losses/softmax_crossentropy.py | adriaciurana/scrath-network | 2 | 6618908 | <reponame>adriaciurana/scrath-network
from .loss import Loss
import numpy as np
class SoftmaxCrossEntropy(Loss):
def __init__(self, node, params=None):
if params is None:
params = {}
super(SoftmaxCrossEntropy, self).__init__(node, params=params)
def computeSize(self):
super(SoftmaxCrossEntropy, self).computeSize()
return tuple([1])
def forward(self, inputs):
super(SoftmaxCrossEntropy, self).forward(inputs)
pred, true = inputs
probs = np.exp(pred - np.max(pred, axis=-1, keepdims=True))
probs /= np.sum(probs, axis=-1, keepdims=True)
self.values.probs = probs
self.values.true = np.int64(true.flatten()) #np.argmax(true, axis=-1)
return -np.mean(np.log(probs[np.arange(self.values.true.shape[0]), self.values.true] + 1e-100))
def derivatives(self, doutput):
dx = self.values.probs.copy()
dx[np.arange(self.values.true.shape[0]), self.values.true] -= 1
return dx
| from .loss import Loss
import numpy as np
class SoftmaxCrossEntropy(Loss):
def __init__(self, node, params=None):
if params is None:
params = {}
super(SoftmaxCrossEntropy, self).__init__(node, params=params)
def computeSize(self):
super(SoftmaxCrossEntropy, self).computeSize()
return tuple([1])
def forward(self, inputs):
super(SoftmaxCrossEntropy, self).forward(inputs)
pred, true = inputs
probs = np.exp(pred - np.max(pred, axis=-1, keepdims=True))
probs /= np.sum(probs, axis=-1, keepdims=True)
self.values.probs = probs
self.values.true = np.int64(true.flatten()) #np.argmax(true, axis=-1)
return -np.mean(np.log(probs[np.arange(self.values.true.shape[0]), self.values.true] + 1e-100))
def derivatives(self, doutput):
dx = self.values.probs.copy()
dx[np.arange(self.values.true.shape[0]), self.values.true] -= 1
return dx | ja | 0.137348 | #np.argmax(true, axis=-1) | 2.672699 | 3 |
hyrodactil/tests/customisable_emails/test_utils.py | hizardapp/Hizard | 1 | 6618909 | <reponame>hizardapp/Hizard
from django.test import TestCase
from django.core import mail
from ..factories._companies import CompanyFactory
from ..factories._customisable_emails import EmailTemplateFactory
from customisable_emails.utils import get_email_template, send_customised_email
class UtilsTest(TestCase):
def test_get_template(self):
company = CompanyFactory()
EmailTemplateFactory(code="confirmation", company=company)
subject_template, body_template = get_email_template(
company=company,
code="confirmation"
)
self.assertTrue(subject_template)
self.assertTrue(body_template)
def test_get_template_failure(self):
company = CompanyFactory()
subject_template, body_template = get_email_template(
company=company,
code="confirmation"
)
self.assertIsNone(subject_template)
self.assertIsNone(body_template)
def test_send_template(self):
company = CompanyFactory()
EmailTemplateFactory(company=company,
subject="Hi {{applicant}}",
body="Dear {{applicant}} XXX",
code="confirmation")
send_customised_email("confirmation",
company=company,
to="<EMAIL>",
context=dict(applicant="Henry")
)
self.assertEqual(len(mail.outbox), 1)
email, = mail.outbox
self.assertTrue("<EMAIL>" in email.to)
self.assertEqual(email.subject, "Hi Henry")
self.assertTrue(email.body, "Dear Henry XXX")
| from django.test import TestCase
from django.core import mail
from ..factories._companies import CompanyFactory
from ..factories._customisable_emails import EmailTemplateFactory
from customisable_emails.utils import get_email_template, send_customised_email
class UtilsTest(TestCase):
def test_get_template(self):
company = CompanyFactory()
EmailTemplateFactory(code="confirmation", company=company)
subject_template, body_template = get_email_template(
company=company,
code="confirmation"
)
self.assertTrue(subject_template)
self.assertTrue(body_template)
def test_get_template_failure(self):
company = CompanyFactory()
subject_template, body_template = get_email_template(
company=company,
code="confirmation"
)
self.assertIsNone(subject_template)
self.assertIsNone(body_template)
def test_send_template(self):
company = CompanyFactory()
EmailTemplateFactory(company=company,
subject="Hi {{applicant}}",
body="Dear {{applicant}} XXX",
code="confirmation")
send_customised_email("confirmation",
company=company,
to="<EMAIL>",
context=dict(applicant="Henry")
)
self.assertEqual(len(mail.outbox), 1)
email, = mail.outbox
self.assertTrue("<EMAIL>" in email.to)
self.assertEqual(email.subject, "Hi Henry")
self.assertTrue(email.body, "Dear Henry XXX") | none | 1 | 2.37178 | 2 | |
creel_portal/views.py | AdamCottrill/CreelPortal | 0 | 6618910 | from django.shortcuts import render, redirect
from django.http import JsonResponse
from django.views.generic import ListView, DetailView
from django.template import RequestContext
from django.shortcuts import get_object_or_404
from django.db.models import Q, F
import json
from django.core.serializers.json import DjangoJSONEncoder
from creel_portal.models import FN011, FN026, FR713, FR714
from creel_portal.forms import FN026Form
from .utils import (
get_aggregate_catch_estimates,
get_aggregate_effort_estimates,
get_catch_totals,
)
class CreelListView(ListView):
model = FN011
template_name = "creel_portal/creel_list.html"
def get_queryset(self, **kwargs):
queryset = FN011.objects.order_by("lake", "-prj_date0").select_related("lake")
self.lake = self.kwargs.get("lake")
self.q = self.request.GET.get("q")
if self.lake:
queryset = queryset.filter(lake__lake_name=self.lake)
if self.q:
queryset = queryset.filter(
Q(prj_cd__icontains=self.q) | Q(prj_nm__icontains=self.q)
)
return queryset
def get_context_data(self, **kwargs):
context = super(CreelListView, self).get_context_data(**kwargs)
context["lake"] = self.lake
context["q"] = self.q
return context
class CreelDetailView(DetailView):
"""A class based view to provide all of the details assocaited with a
creel. In addition to the basic FN011 information, it also
includes effort and catch estiamtes from the last creel run (if
one is available.)
"""
model = FN011
template_name = "creel_portal/creel_detail.html"
context_object_name = "creel"
def get_queryset(self):
queryset = super(CreelDetailView, self).get_queryset()
queryset = queryset.select_related("prj_ldr").prefetch_related(
"seasons",
"seasons__daytypes",
"seasons__daytypes__periods",
"seasons__exception_dates",
"modes",
"spatial_strata",
"creel_run",
)
return queryset
def get_context_data(self, **kwargs):
"""The creel detail page requires a number additional pieces of
information that are used to populate the map, the tables, and the
charts."""
context = super(CreelDetailView, self).get_context_data(**kwargs)
creel = kwargs.get("object")
spots = creel.spatial_strata.values("label", "ddlon", "ddlat")
context["spaces"] = json.dumps(list(spots), cls=DjangoJSONEncoder)
catch_estimates = get_aggregate_catch_estimates(creel)
context["catch_estimates"] = catch_estimates
effort_estimates = get_aggregate_effort_estimates(creel)
context["effort_estimates"] = effort_estimates
# these are used by the chart - we might want to move them to
# the api and load this data via ajax when the page loads.
catch_totals = get_catch_totals(creel)
context["catch_totals"] = catch_totals
return context
def edit_creel_space(request, slug, space):
"""
Arguments:
- `request`:
- `slug`:
- `space`:
"""
space = get_object_or_404(FN026, creel__slug=slug, space=space)
if request.method == "POST":
form = FN026Form(request.POST, instance=space)
if form.is_valid():
form.save()
return redirect("creel_detail", slug=space.creel.slug)
else:
form = FN026Form(instance=space)
return render(
request, "creel_portal/edit_creel_space.html", {"form": form, "space": space}
)
def effort_estimates(request, slug):
"""
Arguments:
- `request`:
"""
creel = get_object_or_404(FN011, slug=slug)
spots = creel.spatial_strata.values("label", "ddlon", "ddlat")
spots_json = json.dumps(list(spots), cls=DjangoJSONEncoder)
return render(
request,
"creel_portal/creel_effort_plots.html",
{"creel": creel, "spaces": spots_json},
)
def catch_estimates(request, slug):
"""
Arguments:
- `request`:
"""
creel = get_object_or_404(FN011, slug=slug)
spots = creel.spatial_strata.values("label", "ddlon", "ddlat")
spots_json = json.dumps(list(spots), cls=DjangoJSONEncoder)
return render(
request,
"creel_portal/creel_catch_plots.html",
{"creel": creel, "spaces": spots_json},
)
def effort_estimates_json(request, slug):
"""This is just a temporary function to get the effort estimates for a
single creel and dump them as json for cross filter to consume. This
should be reaplaced by a real api endpoint.
Arguments:
- `request`:
"""
creel = FN011.objects.get(slug=slug)
final_run = creel.final_run.run
qs = (
FR713.objects.filter(
date__isnull=True,
fr712__rec_tp=2,
fr712__stratum__creel_run__creel=creel,
fr712__stratum__creel_run__run=final_run,
)
.select_related(
"fr712__stratum__season",
"fr712__stratum__season__datetype",
"fr712__stratum__season__datetype__period",
"fr712__stratum__mode",
"fr712__stratum__spatial_strata",
)
.annotate(
season=F("fr712__stratum__season__ssn_des"),
dtp=F("fr712__stratum__daytype__dtp_nm"),
period=F("fr712__stratum__period__prd"),
mode=F("fr712__stratum__mode__mode_des"),
area=F("fr712__stratum__area__space_des"),
ddlat=F("fr712__stratum__area__ddlat"),
ddlon=F("fr712__stratum__area__ddlon"),
)
.values(
"id",
"effre",
"effae",
"effao_s",
"effro_s",
"mode",
"season",
"dtp",
"period",
"area",
"ddlat",
"ddlon",
)
)
return JsonResponse(list(qs), safe=False)
def catch_estimates_json(request, slug):
"""This is just a temporary function to get the catch estimates for a
single creel and dump them as json for cross filter to consume. This
should be reaplaced by a real api endpoint.
Arguments:
- `request`:
"""
creel = FN011.objects.get(slug=slug)
final_run = creel.final_run.run
qs = (
FR714.objects.filter(
date__isnull=True,
fr712__rec_tp=2,
fr712__stratum__creel_run__creel=creel,
fr712__stratum__creel_run__run=final_run,
)
.select_related(
"species",
"fr712__stratum__season",
"fr712__stratum__season__datetype",
"fr712__stratum__season__datetype__period",
"fr712__stratum__mode",
"fr712__stratum__spatial_strata",
)
.annotate(
species_name=F("species__spc_nmco"),
season=F("fr712__stratum__season__ssn_des"),
dtp=F("fr712__stratum__daytype__dtp_nm"),
period=F("fr712__stratum__period__prd"),
mode=F("fr712__stratum__mode__mode_des"),
area=F("fr712__stratum__area__space_des"),
ddlat=F("fr712__stratum__area__ddlat"),
ddlon=F("fr712__stratum__area__ddlon"),
)
.values(
"id",
"species_name",
"sek",
"catne",
"mode",
"season",
"dtp",
"period",
"area",
"ddlat",
"ddlon",
)
)
return JsonResponse(list(qs), safe=False)
| from django.shortcuts import render, redirect
from django.http import JsonResponse
from django.views.generic import ListView, DetailView
from django.template import RequestContext
from django.shortcuts import get_object_or_404
from django.db.models import Q, F
import json
from django.core.serializers.json import DjangoJSONEncoder
from creel_portal.models import FN011, FN026, FR713, FR714
from creel_portal.forms import FN026Form
from .utils import (
get_aggregate_catch_estimates,
get_aggregate_effort_estimates,
get_catch_totals,
)
class CreelListView(ListView):
model = FN011
template_name = "creel_portal/creel_list.html"
def get_queryset(self, **kwargs):
queryset = FN011.objects.order_by("lake", "-prj_date0").select_related("lake")
self.lake = self.kwargs.get("lake")
self.q = self.request.GET.get("q")
if self.lake:
queryset = queryset.filter(lake__lake_name=self.lake)
if self.q:
queryset = queryset.filter(
Q(prj_cd__icontains=self.q) | Q(prj_nm__icontains=self.q)
)
return queryset
def get_context_data(self, **kwargs):
context = super(CreelListView, self).get_context_data(**kwargs)
context["lake"] = self.lake
context["q"] = self.q
return context
class CreelDetailView(DetailView):
"""A class based view to provide all of the details assocaited with a
creel. In addition to the basic FN011 information, it also
includes effort and catch estiamtes from the last creel run (if
one is available.)
"""
model = FN011
template_name = "creel_portal/creel_detail.html"
context_object_name = "creel"
def get_queryset(self):
queryset = super(CreelDetailView, self).get_queryset()
queryset = queryset.select_related("prj_ldr").prefetch_related(
"seasons",
"seasons__daytypes",
"seasons__daytypes__periods",
"seasons__exception_dates",
"modes",
"spatial_strata",
"creel_run",
)
return queryset
def get_context_data(self, **kwargs):
"""The creel detail page requires a number additional pieces of
information that are used to populate the map, the tables, and the
charts."""
context = super(CreelDetailView, self).get_context_data(**kwargs)
creel = kwargs.get("object")
spots = creel.spatial_strata.values("label", "ddlon", "ddlat")
context["spaces"] = json.dumps(list(spots), cls=DjangoJSONEncoder)
catch_estimates = get_aggregate_catch_estimates(creel)
context["catch_estimates"] = catch_estimates
effort_estimates = get_aggregate_effort_estimates(creel)
context["effort_estimates"] = effort_estimates
# these are used by the chart - we might want to move them to
# the api and load this data via ajax when the page loads.
catch_totals = get_catch_totals(creel)
context["catch_totals"] = catch_totals
return context
def edit_creel_space(request, slug, space):
"""
Arguments:
- `request`:
- `slug`:
- `space`:
"""
space = get_object_or_404(FN026, creel__slug=slug, space=space)
if request.method == "POST":
form = FN026Form(request.POST, instance=space)
if form.is_valid():
form.save()
return redirect("creel_detail", slug=space.creel.slug)
else:
form = FN026Form(instance=space)
return render(
request, "creel_portal/edit_creel_space.html", {"form": form, "space": space}
)
def effort_estimates(request, slug):
"""
Arguments:
- `request`:
"""
creel = get_object_or_404(FN011, slug=slug)
spots = creel.spatial_strata.values("label", "ddlon", "ddlat")
spots_json = json.dumps(list(spots), cls=DjangoJSONEncoder)
return render(
request,
"creel_portal/creel_effort_plots.html",
{"creel": creel, "spaces": spots_json},
)
def catch_estimates(request, slug):
"""
Arguments:
- `request`:
"""
creel = get_object_or_404(FN011, slug=slug)
spots = creel.spatial_strata.values("label", "ddlon", "ddlat")
spots_json = json.dumps(list(spots), cls=DjangoJSONEncoder)
return render(
request,
"creel_portal/creel_catch_plots.html",
{"creel": creel, "spaces": spots_json},
)
def effort_estimates_json(request, slug):
"""This is just a temporary function to get the effort estimates for a
single creel and dump them as json for cross filter to consume. This
should be reaplaced by a real api endpoint.
Arguments:
- `request`:
"""
creel = FN011.objects.get(slug=slug)
final_run = creel.final_run.run
qs = (
FR713.objects.filter(
date__isnull=True,
fr712__rec_tp=2,
fr712__stratum__creel_run__creel=creel,
fr712__stratum__creel_run__run=final_run,
)
.select_related(
"fr712__stratum__season",
"fr712__stratum__season__datetype",
"fr712__stratum__season__datetype__period",
"fr712__stratum__mode",
"fr712__stratum__spatial_strata",
)
.annotate(
season=F("fr712__stratum__season__ssn_des"),
dtp=F("fr712__stratum__daytype__dtp_nm"),
period=F("fr712__stratum__period__prd"),
mode=F("fr712__stratum__mode__mode_des"),
area=F("fr712__stratum__area__space_des"),
ddlat=F("fr712__stratum__area__ddlat"),
ddlon=F("fr712__stratum__area__ddlon"),
)
.values(
"id",
"effre",
"effae",
"effao_s",
"effro_s",
"mode",
"season",
"dtp",
"period",
"area",
"ddlat",
"ddlon",
)
)
return JsonResponse(list(qs), safe=False)
def catch_estimates_json(request, slug):
"""This is just a temporary function to get the catch estimates for a
single creel and dump them as json for cross filter to consume. This
should be reaplaced by a real api endpoint.
Arguments:
- `request`:
"""
creel = FN011.objects.get(slug=slug)
final_run = creel.final_run.run
qs = (
FR714.objects.filter(
date__isnull=True,
fr712__rec_tp=2,
fr712__stratum__creel_run__creel=creel,
fr712__stratum__creel_run__run=final_run,
)
.select_related(
"species",
"fr712__stratum__season",
"fr712__stratum__season__datetype",
"fr712__stratum__season__datetype__period",
"fr712__stratum__mode",
"fr712__stratum__spatial_strata",
)
.annotate(
species_name=F("species__spc_nmco"),
season=F("fr712__stratum__season__ssn_des"),
dtp=F("fr712__stratum__daytype__dtp_nm"),
period=F("fr712__stratum__period__prd"),
mode=F("fr712__stratum__mode__mode_des"),
area=F("fr712__stratum__area__space_des"),
ddlat=F("fr712__stratum__area__ddlat"),
ddlon=F("fr712__stratum__area__ddlon"),
)
.values(
"id",
"species_name",
"sek",
"catne",
"mode",
"season",
"dtp",
"period",
"area",
"ddlat",
"ddlon",
)
)
return JsonResponse(list(qs), safe=False)
| en | 0.89006 | A class based view to provide all of the details assocaited with a creel. In addition to the basic FN011 information, it also includes effort and catch estiamtes from the last creel run (if one is available.) The creel detail page requires a number additional pieces of information that are used to populate the map, the tables, and the charts. # these are used by the chart - we might want to move them to # the api and load this data via ajax when the page loads. Arguments: - `request`: - `slug`: - `space`: Arguments: - `request`: Arguments: - `request`: This is just a temporary function to get the effort estimates for a single creel and dump them as json for cross filter to consume. This should be reaplaced by a real api endpoint. Arguments: - `request`: This is just a temporary function to get the catch estimates for a single creel and dump them as json for cross filter to consume. This should be reaplaced by a real api endpoint. Arguments: - `request`: | 2.052935 | 2 |
pys/libs/function_tools.py | Xithrius/Examples | 0 | 6618911 | import functools
def main(something, another='item') -> bool:
if another == 'item':
return True
func0 = functools.partial(main, 'test', 'another test')
func1 = functools.partial(main, 'test')
print(func0(), func1())
| import functools
def main(something, another='item') -> bool:
if another == 'item':
return True
func0 = functools.partial(main, 'test', 'another test')
func1 = functools.partial(main, 'test')
print(func0(), func1())
| none | 1 | 3.323184 | 3 | |
tests/coffeeclient.py | VictorOliveiraPy/desingn-de-api | 0 | 6618912 | import argparse
import json
import re
import requests
BASE_URL = 'http://localhost:8000'
# def place_order(coffee, size, milk, location):
# url = f'{BASE_URL}/order/create?coffe{coffee}?size={size}?milk{milk}&location={location}'
#
# r = requests.get(url)
#
# return ''.join(re.findall(r'Order=(\d+)', r.text))
def post(coffee, size, milk, location):
url = f'{BASE_URL}/order'
data = dict(coffee=coffee, size=size, milk=milk, location=location)
headers = {'content-type': 'application/json'}
response = requests.post(url, data=json.dumps(data), headers=headers)
return response.json()
def get(id):
url = f'{BASE_URL}/order/{id}'
headers = {'content-type': 'application/json'}
response = requests.get(url, headers=headers)
d = response.json()
return d
def build_parser():
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(dest='command')
subparsers.required = True
sp_order = subparsers.add_parser('order')
sp_order.add_argument('coffee')
sp_order.add_argument('size')
sp_order.add_argument('milk')
sp_order.add_argument('location')
return parser
if __name__ == '__main__':
parser = build_parser()
args = parser.parse_args()
order = post(args.coffee, args.size, args.milk, args.location)
print(order)
print(get(id=order['id']))
| import argparse
import json
import re
import requests
BASE_URL = 'http://localhost:8000'
# def place_order(coffee, size, milk, location):
# url = f'{BASE_URL}/order/create?coffe{coffee}?size={size}?milk{milk}&location={location}'
#
# r = requests.get(url)
#
# return ''.join(re.findall(r'Order=(\d+)', r.text))
def post(coffee, size, milk, location):
url = f'{BASE_URL}/order'
data = dict(coffee=coffee, size=size, milk=milk, location=location)
headers = {'content-type': 'application/json'}
response = requests.post(url, data=json.dumps(data), headers=headers)
return response.json()
def get(id):
url = f'{BASE_URL}/order/{id}'
headers = {'content-type': 'application/json'}
response = requests.get(url, headers=headers)
d = response.json()
return d
def build_parser():
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(dest='command')
subparsers.required = True
sp_order = subparsers.add_parser('order')
sp_order.add_argument('coffee')
sp_order.add_argument('size')
sp_order.add_argument('milk')
sp_order.add_argument('location')
return parser
if __name__ == '__main__':
parser = build_parser()
args = parser.parse_args()
order = post(args.coffee, args.size, args.milk, args.location)
print(order)
print(get(id=order['id']))
| en | 0.529842 | # def place_order(coffee, size, milk, location): # url = f'{BASE_URL}/order/create?coffe{coffee}?size={size}?milk{milk}&location={location}' # # r = requests.get(url) # # return ''.join(re.findall(r'Order=(\d+)', r.text)) | 2.790227 | 3 |
competition/models.py | psifertex/collabCTF | 2 | 6618913 | <reponame>psifertex/collabCTF
import os
from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
from django.core.urlresolvers import reverse
from django.db import models
class Competition(models.Model):
name = models.CharField('Name', max_length=255, unique=True)
slug = models.SlugField(unique=True)
url = models.URLField('Competition URL', blank=True)
start_time = models.DateTimeField(blank=True, null=True)
end_time = models.DateTimeField(blank=True, null=True)
def __unicode__(self):
return self.name
__str__ = __unicode__
def get_absolute_url(self):
return reverse('view_ctf', kwargs={'ctf_slug': self.slug})
class Challenge(models.Model):
NOT_STARTED = 0
IN_PROGRESS = 1
SOLVED = 2
PROGRESS_CHOICES = (
(NOT_STARTED, 'Not Started'),
(IN_PROGRESS, 'In Progress'),
(SOLVED, 'Solved')
)
name = models.CharField('Name', max_length=255)
slug = models.SlugField()
progress = models.PositiveSmallIntegerField(choices=PROGRESS_CHOICES)
num_progress = models.FloatField('Progress %', default=0)
point_value = models.FloatField(default=0)
competition = models.ForeignKey(Competition, related_name='challenges')
last_viewed = models.DateTimeField(auto_created=True)
def __unicode__(self):
return self.name
__str__ = __unicode__
def get_absolute_url(self):
return reverse('view_challenge', kwargs={'ctf_slug': self.competition.slug, 'chall_slug': self.slug})
def last_viewed_display(self):
if self.last_viewed == 0:
return 'Never'
else:
return self.last_viewed
class Meta:
unique_together = ('name', 'competition')
ordering = ('progress',)
class ChallengeFile(models.Model):
file = models.FileField(upload_to='files/')
ctime = models.DateTimeField(auto_created=True)
mtime = models.DateTimeField(auto_now=True)
challenge = models.ForeignKey(Challenge, related_name='files')
def __unicode__(self):
return self.file.name
__str__ = __unicode__
def filename(self):
return os.path.basename(self.file.name)
class Tag(models.Model):
tag = models.SlugField()
is_category = models.BooleanField(default=False)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
def __unicode__(self):
return self.tag
__str__ = __unicode__ | import os
from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
from django.core.urlresolvers import reverse
from django.db import models
class Competition(models.Model):
name = models.CharField('Name', max_length=255, unique=True)
slug = models.SlugField(unique=True)
url = models.URLField('Competition URL', blank=True)
start_time = models.DateTimeField(blank=True, null=True)
end_time = models.DateTimeField(blank=True, null=True)
def __unicode__(self):
return self.name
__str__ = __unicode__
def get_absolute_url(self):
return reverse('view_ctf', kwargs={'ctf_slug': self.slug})
class Challenge(models.Model):
NOT_STARTED = 0
IN_PROGRESS = 1
SOLVED = 2
PROGRESS_CHOICES = (
(NOT_STARTED, 'Not Started'),
(IN_PROGRESS, 'In Progress'),
(SOLVED, 'Solved')
)
name = models.CharField('Name', max_length=255)
slug = models.SlugField()
progress = models.PositiveSmallIntegerField(choices=PROGRESS_CHOICES)
num_progress = models.FloatField('Progress %', default=0)
point_value = models.FloatField(default=0)
competition = models.ForeignKey(Competition, related_name='challenges')
last_viewed = models.DateTimeField(auto_created=True)
def __unicode__(self):
return self.name
__str__ = __unicode__
def get_absolute_url(self):
return reverse('view_challenge', kwargs={'ctf_slug': self.competition.slug, 'chall_slug': self.slug})
def last_viewed_display(self):
if self.last_viewed == 0:
return 'Never'
else:
return self.last_viewed
class Meta:
unique_together = ('name', 'competition')
ordering = ('progress',)
class ChallengeFile(models.Model):
file = models.FileField(upload_to='files/')
ctime = models.DateTimeField(auto_created=True)
mtime = models.DateTimeField(auto_now=True)
challenge = models.ForeignKey(Challenge, related_name='files')
def __unicode__(self):
return self.file.name
__str__ = __unicode__
def filename(self):
return os.path.basename(self.file.name)
class Tag(models.Model):
tag = models.SlugField()
is_category = models.BooleanField(default=False)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
def __unicode__(self):
return self.tag
__str__ = __unicode__ | none | 1 | 2.096268 | 2 | |
src/app.py | GRazafy/shadow_corona | 0 | 6618914 | <filename>src/app.py
import datetime
import os
import yaml
import numpy as np
import pandas as pd
import dash
import dash_core_components as dcc
import dash_bootstrap_components as dbc
import dash_html_components as html
from dash.dependencies import Input, Output
# Lecture du fichier d'environnement
ENV_FILE = '../env.yaml'
with open(ENV_FILE) as f:
params = yaml.load(f, Loader=yaml.FullLoader)
# Initialisation des chemins vers les fichiers
ROOT_DIR = os.path.dirname(os.path.abspath(ENV_FILE))
DATA_FILE = os.path.join(ROOT_DIR,
params['directories']['processed'],
params['files']['all_data'])
# Lecture du fichier de données
epidemie_df = (pd.read_csv(DATA_FILE, parse_dates=['Last Update'])
.assign(day=lambda _df: _df['Last Update'].dt.date)
.drop_duplicates(subset=['Country/Region', 'Province/State', 'day'])
[lambda df: df['day'] <= datetime.date(2020, 3, 24)]
)
countries = [{'label': c, 'value': c} for c in sorted(epidemie_df['Country/Region'].unique())]
app = dash.Dash('Corona Virus Explorer',external_stylesheets=[dbc.themes.BOOTSTRAP])
app.layout = html.Div([
dcc.Interval(id='refresh', interval=200),
html.H2(['Corona Virus Explorer'], style={'textAlign': 'center'}),
html.Div([
html.Div([
html.Div([
html.H4(
"Today Total: ",
),
html.P(
id="Counter",
),
],
className="count_container"
),
html.Div([
html.P(
"Filter by construction date (or select range in histogram):",
className="control_label",
),
dcc.DatePickerRange(
id = 'datepicker-input',
display_format='DD/MM/YYYY',
),
dbc.RadioItems(
id='radioitems-input',
options=[
{'label': 'Confirmed', 'value': 'Confirmed'},
{'label': 'Deaths', 'value': 'Deaths'},
{'label': 'Recovered', 'value': 'Recovered'},
{'label': 'Active', 'value': 'Active'}
],
value='Confirmed',
),
html.P("Filter by countries :"),
dcc.Dropdown(
id="countries",
options=countries,
multi=True,
className="dcc_control",
),
],
className="option_container"
),
],
className="side_container four columns",
),
html.Div([
dcc.Tabs([
dcc.Tab(label='Time', children=[
html.Div([
dcc.Graph(id='graph1')
]),
]),
dcc.Tab(label='Map', children=[
dcc.Graph(id='map1'),
dcc.Slider(
id='map_day',
min=0,
max=(epidemie_df['day'].max() - epidemie_df['day'].min()).days,
value=0,
updatemode='drag',
tooltip = {
'always_visible': True
}
),
]),
#TODO change Dropdown to current countries
dcc.Tab(label='Model',children=[
html.H6(['The model']),
dcc.Graph(id='graph2'),
dcc.Dropdown(id='country3',options=countries)
]),
]),
],
className="main_container eight columns",
),
],
className="MainLayout",
),
])
@app.callback(Output("Counter", "children"),
[
Input('radioitems-input', 'value'),
]
)
def update_statusBar(variable):
return epidemie_df.groupby('day').agg({variable: 'sum'}).max()
@app.callback(
Output('graph1', 'figure'),
[
Input('countries','value'),
Input('radioitems-input', 'value'),
]
)
def update_graph(countries, variable):
graphs_df = []
if countries != [] and type(countries) is list:
for e_country in countries:
graphs_df.append(epidemie_df[epidemie_df['Country/Region'] == e_country]
.groupby(['Country/Region', 'day'])
.agg({variable: 'sum'})
.reset_index()
)
print(graphs_df)
graph_df = epidemie_df.groupby('day').agg({variable: 'sum'}).reset_index()
traces = []
count = 0
if countries != [] and type(countries) is list:
for graph in graphs_df:
traces.append(dict(
x=graph['day'],
y=graph[variable],
type='line',
name=countries[count]
))
count = count+1
else:
traces.append(dict(
x=graph_df['day'],
y=graph_df[variable],
type='line',
name='Total'
))
return {
'data':traces
}
@app.callback(
Output('map1', 'figure'),
[
Input('map_day', 'value'),
Input('radioitems-input', 'value'),
]
)
def update_map(map_day,variable):
day = epidemie_df['day'].unique()[map_day]
map_df = (epidemie_df[epidemie_df['day'] == day]
.groupby(['Combined_Key'])
.agg({variable: 'sum', 'Latitude': 'mean', 'Longitude': 'mean'})
.reset_index()
)
print(epidemie_df['Combined_Key'])
return {
'data': [
dict(
type='scattergeo',
lon=map_df['Longitude'],
lat=map_df['Latitude'],
text=map_df.apply(lambda r: r['Combined_Key'] + ' (' + str(r[variable]) + ')', axis=1),
mode='markers',
marker=dict(
size=np.maximum(2*np.log(map_df[variable]), 5)
)
)
],
'layout': dict(
title=str(day),
autosize=True,
automargin=True,
margin=dict(l=30, r=30, b=20, t=40),
hovermode="closest",
plot_bgcolor="#F9F9F9",
paper_bgcolor="#F9F9F9",
geo=dict(
showland = True,
landcolor = "rgb(212, 212, 212)",
subunitcolor = "rgb(255, 255, 255)",
countrycolor = "rgb(255, 255, 255)",
showlakes = True,
lakecolor = "rgb(255, 255, 255)",
showsubunits = True,
showcountries = True,
resolution = 50,
# lonaxis = dict(
# showgrid = False,
# gridwidth = 0.5,
# range= [ -140.0, -55.0 ],
# dtick = 5
# ),
# lataxis = dict (
# showgrid = False,
# gridwidth = 0.5,
# range= [ 20.0, 60.0 ],
# dtick = 5
# )
)
)
}
if __name__ == '__main__':
app.run_server(debug=True) | <filename>src/app.py
import datetime
import os
import yaml
import numpy as np
import pandas as pd
import dash
import dash_core_components as dcc
import dash_bootstrap_components as dbc
import dash_html_components as html
from dash.dependencies import Input, Output
# Lecture du fichier d'environnement
ENV_FILE = '../env.yaml'
with open(ENV_FILE) as f:
params = yaml.load(f, Loader=yaml.FullLoader)
# Initialisation des chemins vers les fichiers
ROOT_DIR = os.path.dirname(os.path.abspath(ENV_FILE))
DATA_FILE = os.path.join(ROOT_DIR,
params['directories']['processed'],
params['files']['all_data'])
# Lecture du fichier de données
epidemie_df = (pd.read_csv(DATA_FILE, parse_dates=['Last Update'])
.assign(day=lambda _df: _df['Last Update'].dt.date)
.drop_duplicates(subset=['Country/Region', 'Province/State', 'day'])
[lambda df: df['day'] <= datetime.date(2020, 3, 24)]
)
countries = [{'label': c, 'value': c} for c in sorted(epidemie_df['Country/Region'].unique())]
app = dash.Dash('Corona Virus Explorer',external_stylesheets=[dbc.themes.BOOTSTRAP])
app.layout = html.Div([
dcc.Interval(id='refresh', interval=200),
html.H2(['Corona Virus Explorer'], style={'textAlign': 'center'}),
html.Div([
html.Div([
html.Div([
html.H4(
"Today Total: ",
),
html.P(
id="Counter",
),
],
className="count_container"
),
html.Div([
html.P(
"Filter by construction date (or select range in histogram):",
className="control_label",
),
dcc.DatePickerRange(
id = 'datepicker-input',
display_format='DD/MM/YYYY',
),
dbc.RadioItems(
id='radioitems-input',
options=[
{'label': 'Confirmed', 'value': 'Confirmed'},
{'label': 'Deaths', 'value': 'Deaths'},
{'label': 'Recovered', 'value': 'Recovered'},
{'label': 'Active', 'value': 'Active'}
],
value='Confirmed',
),
html.P("Filter by countries :"),
dcc.Dropdown(
id="countries",
options=countries,
multi=True,
className="dcc_control",
),
],
className="option_container"
),
],
className="side_container four columns",
),
html.Div([
dcc.Tabs([
dcc.Tab(label='Time', children=[
html.Div([
dcc.Graph(id='graph1')
]),
]),
dcc.Tab(label='Map', children=[
dcc.Graph(id='map1'),
dcc.Slider(
id='map_day',
min=0,
max=(epidemie_df['day'].max() - epidemie_df['day'].min()).days,
value=0,
updatemode='drag',
tooltip = {
'always_visible': True
}
),
]),
#TODO change Dropdown to current countries
dcc.Tab(label='Model',children=[
html.H6(['The model']),
dcc.Graph(id='graph2'),
dcc.Dropdown(id='country3',options=countries)
]),
]),
],
className="main_container eight columns",
),
],
className="MainLayout",
),
])
@app.callback(Output("Counter", "children"),
[
Input('radioitems-input', 'value'),
]
)
def update_statusBar(variable):
return epidemie_df.groupby('day').agg({variable: 'sum'}).max()
@app.callback(
Output('graph1', 'figure'),
[
Input('countries','value'),
Input('radioitems-input', 'value'),
]
)
def update_graph(countries, variable):
graphs_df = []
if countries != [] and type(countries) is list:
for e_country in countries:
graphs_df.append(epidemie_df[epidemie_df['Country/Region'] == e_country]
.groupby(['Country/Region', 'day'])
.agg({variable: 'sum'})
.reset_index()
)
print(graphs_df)
graph_df = epidemie_df.groupby('day').agg({variable: 'sum'}).reset_index()
traces = []
count = 0
if countries != [] and type(countries) is list:
for graph in graphs_df:
traces.append(dict(
x=graph['day'],
y=graph[variable],
type='line',
name=countries[count]
))
count = count+1
else:
traces.append(dict(
x=graph_df['day'],
y=graph_df[variable],
type='line',
name='Total'
))
return {
'data':traces
}
@app.callback(
Output('map1', 'figure'),
[
Input('map_day', 'value'),
Input('radioitems-input', 'value'),
]
)
def update_map(map_day,variable):
day = epidemie_df['day'].unique()[map_day]
map_df = (epidemie_df[epidemie_df['day'] == day]
.groupby(['Combined_Key'])
.agg({variable: 'sum', 'Latitude': 'mean', 'Longitude': 'mean'})
.reset_index()
)
print(epidemie_df['Combined_Key'])
return {
'data': [
dict(
type='scattergeo',
lon=map_df['Longitude'],
lat=map_df['Latitude'],
text=map_df.apply(lambda r: r['Combined_Key'] + ' (' + str(r[variable]) + ')', axis=1),
mode='markers',
marker=dict(
size=np.maximum(2*np.log(map_df[variable]), 5)
)
)
],
'layout': dict(
title=str(day),
autosize=True,
automargin=True,
margin=dict(l=30, r=30, b=20, t=40),
hovermode="closest",
plot_bgcolor="#F9F9F9",
paper_bgcolor="#F9F9F9",
geo=dict(
showland = True,
landcolor = "rgb(212, 212, 212)",
subunitcolor = "rgb(255, 255, 255)",
countrycolor = "rgb(255, 255, 255)",
showlakes = True,
lakecolor = "rgb(255, 255, 255)",
showsubunits = True,
showcountries = True,
resolution = 50,
# lonaxis = dict(
# showgrid = False,
# gridwidth = 0.5,
# range= [ -140.0, -55.0 ],
# dtick = 5
# ),
# lataxis = dict (
# showgrid = False,
# gridwidth = 0.5,
# range= [ 20.0, 60.0 ],
# dtick = 5
# )
)
)
}
if __name__ == '__main__':
app.run_server(debug=True) | fr | 0.468647 | # Lecture du fichier d'environnement # Initialisation des chemins vers les fichiers # Lecture du fichier de données #TODO change Dropdown to current countries # lonaxis = dict( # showgrid = False, # gridwidth = 0.5, # range= [ -140.0, -55.0 ], # dtick = 5 # ), # lataxis = dict ( # showgrid = False, # gridwidth = 0.5, # range= [ 20.0, 60.0 ], # dtick = 5 # ) | 2.499557 | 2 |
nodedge/editor_widget.py | Nodedge/nodedge | 7 | 6618915 | <filename>nodedge/editor_widget.py<gh_stars>1-10
# -*- coding: utf-8 -*-
"""
Editor widget module containing :class:`~nodedge.editor_widget.EditorWidget` class.
"""
import logging
import os
from typing import List, Optional
from PySide2.QtCore import Qt
from PySide2.QtGui import QBrush, QMouseEvent, QPen
from PySide2.QtWidgets import (
QApplication,
QGraphicsItem,
QLabel,
QMessageBox,
QVBoxLayout,
QWidget,
)
from nodedge.blocks.block import Block
from nodedge.edge import Edge, EdgeType
from nodedge.graphics_view import GraphicsView
from nodedge.node import Node
from nodedge.scene import InvalidFile, Scene
from nodedge.socket_type import SocketType
from nodedge.utils import dumpException
class EditorWidget(QWidget):
""":class:`~nodedge.editor_widget.EditorWidget` class"""
SceneClass = Scene
GraphicsViewClass = GraphicsView
"""
:class:`~nodedge.editor_widget.EditorWidget` class
The editor widget is the main widget of the ``QMainWindow``.
"""
def __init__(self, parent=None):
"""
Default constructor.
:param parent: parent widget
:type parent: ``QWidget``
:Instance Attributes:
- **filename** - currently graph's filename or ``None``
"""
super().__init__(parent)
self.__logger = logging.getLogger(__file__)
self.__logger.setLevel(logging.INFO)
self.filename: str = ""
self.initUI()
# noinspection PyAttributeOutsideInit
def initUI(self):
"""
Set up this :class:`~nodedge.editor_widget.EditorWidget` with its layout,
:class:`~nodedge.scene.Scene` and :class:`~nodedge.graphics_view.GraphicsView`.
"""
self.layout: QVBoxLayout = QVBoxLayout()
self.layout.setContentsMargins(0, 0, 0, 0)
self.setLayout(self.layout)
self.scene: Scene = self.__class__.SceneClass()
self.graphicsView: GraphicsView = self.__class__.GraphicsViewClass(
self.scene.graphicsScene, self
)
self.layout.addWidget(self.graphicsView)
@property
def hasName(self) -> bool:
"""
:getter: Return if a file has been loaded in this
:class:`~nodedge.editor_widget.EditorWidget` or not.
:rtype: ``bool``
"""
return self.filename != ""
@property
def shortName(self) -> str:
"""
:getter: Return the short name of this
:class:`~nodedge.editor_widget.EditorWidget`.
:rtype: ``str``
"""
return os.path.basename(self.filename)
@property
def userFriendlyFilename(self) -> str:
"""
:getter: Return the user friendly filename.
.. note::
This name is displayed as window title.
:rtype: ``str``
"""
name = os.path.basename(self.filename) if self.hasName else "New graph"
return name + ("*" if self.isModified else "")
@property
def isModified(self) -> bool:
"""
:getter: Has current :class:`~nodedge.scene.Scene` been modified?
:rtype: ``bool``
"""
return self.scene.isModified
@property
def canUndo(self) -> bool:
"""
:getter: Return whether previously executed operations are saved in history
or not.
:rtype: ``bool``
"""
return self.scene.history.canUndo is True
@property
def canRedo(self) -> bool:
"""
:getter: Return whether the history contains cancelled operations or not.
:rtype: ``bool``
"""
return self.scene.history.canRedo is True
@property
def selectedItems(self) -> List[QGraphicsItem]:
"""
:getter: Return :class:`~nodedge.scene.Scene`'s currently selected items.
:rtype: ``list[QGraphicsItem]``
"""
return self.scene.selectedItems
@property
def hasSelectedItems(self) -> bool:
"""
:getter: Return ``True`` if there is selected items in the
:class:`nodedge.node_scene.Scene`.
:rtype: ``bool``
"""
return self.selectedItems != []
def updateTitle(self) -> None:
"""
Update the ``QMainWindow``'s title with the user friendly filename.
"""
self.setWindowTitle(self.userFriendlyFilename)
def newFile(self) -> None:
"""
Create a new file.
Clear the scene and history, and reset filename.
"""
self.scene.clear()
self.filename = ""
self.scene.history.clear()
def loadFile(self, filename: str) -> bool:
"""
Load serialized graph from JSON file.
:param filename: file to load
:type filename: ``str``
:return: Operation success
:rtype: ``bool``
"""
QApplication.setOverrideCursor(Qt.WaitCursor)
try:
self.scene.loadFromFile(filename)
self.filename = filename
# Don't store initial stamp because the file has still not been changed.
self.scene.history.clear()
QApplication.restoreOverrideCursor()
self.evalNodes()
return True
except FileNotFoundError as e:
self.__logger.warning(f"File {filename} not found: {e}")
dumpException(e)
QMessageBox.warning(
self,
"Error loading %s" % os.path.basename(filename),
str(e).replace("[Errno 2]", ""),
)
return False
except InvalidFile as e:
self.__logger.warning(f"Error loading {filename}: {e}")
QApplication.restoreOverrideCursor()
QMessageBox.warning(
self, f"Error loading {os.path.basename(filename)}", str(e)
)
dumpException(e)
return False
def saveFile(self, filename: Optional[str] = None) -> bool:
"""
Save serialized graph to JSON file.
When called with empty parameter, the filename is unchanged.
:param filename: file to store the graph
:type filename: ``str`` | ``None``
:return: Operation success
:rtype: ``bool``
"""
if filename is not None:
self.filename = filename
QApplication.setOverrideCursor(Qt.WaitCursor)
self.scene.saveToFile(self.filename)
QApplication.restoreOverrideCursor()
return True
def evalNodes(self) -> None:
"""
Evaluate all the nodes present in the scene.
"""
for node in self.scene.nodes:
if isinstance(node, Block):
node.eval()
def mouseReleaseEvent(self, ev: QMouseEvent) -> None:
"""
Handle Qt's mouse's button release event.
:param ev: Mouse release event
:type ev: ``QMouseEvent``
"""
self.graphicsView.mouseReleaseEvent(ev)
super().mouseReleaseEvent(ev)
def mousePressEvent(self, ev: QMouseEvent) -> None:
"""
Handle Qt's mouse's button press event.
:param ev: Mouse press event
:type ev: ``QMouseEvent``
"""
self.graphicsView.mousePressEvent(ev)
super().mousePressEvent(ev)
def addDebugContent(self) -> None:
"""
Testing method to put random QGraphicsItems and elements into QGraphicsScene
"""
greenBrush = QBrush(Qt.green)
outlinePen = QPen(Qt.black)
outlinePen.setWidth(2)
rect = self.scene.graphicsScene.addRect(
-100, -100, 80, 100, outlinePen, greenBrush
)
rect.setFlag(QGraphicsItem.ItemIsMovable)
def addNodes(self) -> None:
"""
Testing method to create 3 :class:`~nodedge.node.Node` connected by 2
:class:`~nodedge.edge.Edge`.
"""
node1 = Node(
self.scene,
"Node 1",
inputSocketTypes=[SocketType.Any, SocketType.Number, SocketType.String],
outputSocketTypes=[SocketType.Any],
)
node2 = Node(
self.scene,
"Node 2",
inputSocketTypes=[SocketType.Any, SocketType.Number, SocketType.String],
outputSocketTypes=[SocketType.Any],
)
node3 = Node(
self.scene,
"Node 3",
inputSocketTypes=[SocketType.Any, SocketType.Number, SocketType.String],
outputSocketTypes=[SocketType.Any],
)
node1.pos = (-350, -250)
node2.pos = (-75, 100)
node3.pos = (200, -75)
Edge( # noqa: F841
self.scene,
node1.outputSockets[0],
node2.inputSockets[1],
edgeType=EdgeType.BEZIER,
)
Edge( # noqa: F841
self.scene,
node2.outputSockets[0],
node3.inputSockets[2],
edgeType=EdgeType.BEZIER,
)
self.scene.history.storeInitialStamp()
def addCustomNode(self):
"""Testing method to create a custom Node with custom content"""
class NNodeContent(QLabel):
def __init__(self, parentNode, parent=None):
super().__init__("FooBar")
self.node = parentNode
self.setParent(parent)
class NNode(Node):
NodeContentClass = NNodeContent
self.scene.setNodeClassSelector(lambda data: NNode)
node = NNode(self.scene, "A Custom Node 1", inputSocketTypes=[0, 1, 2])
self.__logger.debug("Node content:", node.content)
| <filename>nodedge/editor_widget.py<gh_stars>1-10
# -*- coding: utf-8 -*-
"""
Editor widget module containing :class:`~nodedge.editor_widget.EditorWidget` class.
"""
import logging
import os
from typing import List, Optional
from PySide2.QtCore import Qt
from PySide2.QtGui import QBrush, QMouseEvent, QPen
from PySide2.QtWidgets import (
QApplication,
QGraphicsItem,
QLabel,
QMessageBox,
QVBoxLayout,
QWidget,
)
from nodedge.blocks.block import Block
from nodedge.edge import Edge, EdgeType
from nodedge.graphics_view import GraphicsView
from nodedge.node import Node
from nodedge.scene import InvalidFile, Scene
from nodedge.socket_type import SocketType
from nodedge.utils import dumpException
class EditorWidget(QWidget):
""":class:`~nodedge.editor_widget.EditorWidget` class"""
SceneClass = Scene
GraphicsViewClass = GraphicsView
"""
:class:`~nodedge.editor_widget.EditorWidget` class
The editor widget is the main widget of the ``QMainWindow``.
"""
def __init__(self, parent=None):
"""
Default constructor.
:param parent: parent widget
:type parent: ``QWidget``
:Instance Attributes:
- **filename** - currently graph's filename or ``None``
"""
super().__init__(parent)
self.__logger = logging.getLogger(__file__)
self.__logger.setLevel(logging.INFO)
self.filename: str = ""
self.initUI()
# noinspection PyAttributeOutsideInit
def initUI(self):
"""
Set up this :class:`~nodedge.editor_widget.EditorWidget` with its layout,
:class:`~nodedge.scene.Scene` and :class:`~nodedge.graphics_view.GraphicsView`.
"""
self.layout: QVBoxLayout = QVBoxLayout()
self.layout.setContentsMargins(0, 0, 0, 0)
self.setLayout(self.layout)
self.scene: Scene = self.__class__.SceneClass()
self.graphicsView: GraphicsView = self.__class__.GraphicsViewClass(
self.scene.graphicsScene, self
)
self.layout.addWidget(self.graphicsView)
@property
def hasName(self) -> bool:
"""
:getter: Return if a file has been loaded in this
:class:`~nodedge.editor_widget.EditorWidget` or not.
:rtype: ``bool``
"""
return self.filename != ""
@property
def shortName(self) -> str:
"""
:getter: Return the short name of this
:class:`~nodedge.editor_widget.EditorWidget`.
:rtype: ``str``
"""
return os.path.basename(self.filename)
@property
def userFriendlyFilename(self) -> str:
"""
:getter: Return the user friendly filename.
.. note::
This name is displayed as window title.
:rtype: ``str``
"""
name = os.path.basename(self.filename) if self.hasName else "New graph"
return name + ("*" if self.isModified else "")
@property
def isModified(self) -> bool:
"""
:getter: Has current :class:`~nodedge.scene.Scene` been modified?
:rtype: ``bool``
"""
return self.scene.isModified
@property
def canUndo(self) -> bool:
"""
:getter: Return whether previously executed operations are saved in history
or not.
:rtype: ``bool``
"""
return self.scene.history.canUndo is True
@property
def canRedo(self) -> bool:
"""
:getter: Return whether the history contains cancelled operations or not.
:rtype: ``bool``
"""
return self.scene.history.canRedo is True
@property
def selectedItems(self) -> List[QGraphicsItem]:
"""
:getter: Return :class:`~nodedge.scene.Scene`'s currently selected items.
:rtype: ``list[QGraphicsItem]``
"""
return self.scene.selectedItems
@property
def hasSelectedItems(self) -> bool:
"""
:getter: Return ``True`` if there is selected items in the
:class:`nodedge.node_scene.Scene`.
:rtype: ``bool``
"""
return self.selectedItems != []
def updateTitle(self) -> None:
"""
Update the ``QMainWindow``'s title with the user friendly filename.
"""
self.setWindowTitle(self.userFriendlyFilename)
def newFile(self) -> None:
"""
Create a new file.
Clear the scene and history, and reset filename.
"""
self.scene.clear()
self.filename = ""
self.scene.history.clear()
def loadFile(self, filename: str) -> bool:
"""
Load serialized graph from JSON file.
:param filename: file to load
:type filename: ``str``
:return: Operation success
:rtype: ``bool``
"""
QApplication.setOverrideCursor(Qt.WaitCursor)
try:
self.scene.loadFromFile(filename)
self.filename = filename
# Don't store initial stamp because the file has still not been changed.
self.scene.history.clear()
QApplication.restoreOverrideCursor()
self.evalNodes()
return True
except FileNotFoundError as e:
self.__logger.warning(f"File {filename} not found: {e}")
dumpException(e)
QMessageBox.warning(
self,
"Error loading %s" % os.path.basename(filename),
str(e).replace("[Errno 2]", ""),
)
return False
except InvalidFile as e:
self.__logger.warning(f"Error loading {filename}: {e}")
QApplication.restoreOverrideCursor()
QMessageBox.warning(
self, f"Error loading {os.path.basename(filename)}", str(e)
)
dumpException(e)
return False
def saveFile(self, filename: Optional[str] = None) -> bool:
"""
Save serialized graph to JSON file.
When called with empty parameter, the filename is unchanged.
:param filename: file to store the graph
:type filename: ``str`` | ``None``
:return: Operation success
:rtype: ``bool``
"""
if filename is not None:
self.filename = filename
QApplication.setOverrideCursor(Qt.WaitCursor)
self.scene.saveToFile(self.filename)
QApplication.restoreOverrideCursor()
return True
def evalNodes(self) -> None:
"""
Evaluate all the nodes present in the scene.
"""
for node in self.scene.nodes:
if isinstance(node, Block):
node.eval()
def mouseReleaseEvent(self, ev: QMouseEvent) -> None:
"""
Handle Qt's mouse's button release event.
:param ev: Mouse release event
:type ev: ``QMouseEvent``
"""
self.graphicsView.mouseReleaseEvent(ev)
super().mouseReleaseEvent(ev)
def mousePressEvent(self, ev: QMouseEvent) -> None:
"""
Handle Qt's mouse's button press event.
:param ev: Mouse press event
:type ev: ``QMouseEvent``
"""
self.graphicsView.mousePressEvent(ev)
super().mousePressEvent(ev)
def addDebugContent(self) -> None:
"""
Testing method to put random QGraphicsItems and elements into QGraphicsScene
"""
greenBrush = QBrush(Qt.green)
outlinePen = QPen(Qt.black)
outlinePen.setWidth(2)
rect = self.scene.graphicsScene.addRect(
-100, -100, 80, 100, outlinePen, greenBrush
)
rect.setFlag(QGraphicsItem.ItemIsMovable)
def addNodes(self) -> None:
"""
Testing method to create 3 :class:`~nodedge.node.Node` connected by 2
:class:`~nodedge.edge.Edge`.
"""
node1 = Node(
self.scene,
"Node 1",
inputSocketTypes=[SocketType.Any, SocketType.Number, SocketType.String],
outputSocketTypes=[SocketType.Any],
)
node2 = Node(
self.scene,
"Node 2",
inputSocketTypes=[SocketType.Any, SocketType.Number, SocketType.String],
outputSocketTypes=[SocketType.Any],
)
node3 = Node(
self.scene,
"Node 3",
inputSocketTypes=[SocketType.Any, SocketType.Number, SocketType.String],
outputSocketTypes=[SocketType.Any],
)
node1.pos = (-350, -250)
node2.pos = (-75, 100)
node3.pos = (200, -75)
Edge( # noqa: F841
self.scene,
node1.outputSockets[0],
node2.inputSockets[1],
edgeType=EdgeType.BEZIER,
)
Edge( # noqa: F841
self.scene,
node2.outputSockets[0],
node3.inputSockets[2],
edgeType=EdgeType.BEZIER,
)
self.scene.history.storeInitialStamp()
def addCustomNode(self):
"""Testing method to create a custom Node with custom content"""
class NNodeContent(QLabel):
def __init__(self, parentNode, parent=None):
super().__init__("FooBar")
self.node = parentNode
self.setParent(parent)
class NNode(Node):
NodeContentClass = NNodeContent
self.scene.setNodeClassSelector(lambda data: NNode)
node = NNode(self.scene, "A Custom Node 1", inputSocketTypes=[0, 1, 2])
self.__logger.debug("Node content:", node.content)
| en | 0.679498 | # -*- coding: utf-8 -*- Editor widget module containing :class:`~nodedge.editor_widget.EditorWidget` class. :class:`~nodedge.editor_widget.EditorWidget` class :class:`~nodedge.editor_widget.EditorWidget` class The editor widget is the main widget of the ``QMainWindow``. Default constructor. :param parent: parent widget :type parent: ``QWidget`` :Instance Attributes: - **filename** - currently graph's filename or ``None`` # noinspection PyAttributeOutsideInit Set up this :class:`~nodedge.editor_widget.EditorWidget` with its layout, :class:`~nodedge.scene.Scene` and :class:`~nodedge.graphics_view.GraphicsView`. :getter: Return if a file has been loaded in this :class:`~nodedge.editor_widget.EditorWidget` or not. :rtype: ``bool`` :getter: Return the short name of this :class:`~nodedge.editor_widget.EditorWidget`. :rtype: ``str`` :getter: Return the user friendly filename. .. note:: This name is displayed as window title. :rtype: ``str`` :getter: Has current :class:`~nodedge.scene.Scene` been modified? :rtype: ``bool`` :getter: Return whether previously executed operations are saved in history or not. :rtype: ``bool`` :getter: Return whether the history contains cancelled operations or not. :rtype: ``bool`` :getter: Return :class:`~nodedge.scene.Scene`'s currently selected items. :rtype: ``list[QGraphicsItem]`` :getter: Return ``True`` if there is selected items in the :class:`nodedge.node_scene.Scene`. :rtype: ``bool`` Update the ``QMainWindow``'s title with the user friendly filename. Create a new file. Clear the scene and history, and reset filename. Load serialized graph from JSON file. :param filename: file to load :type filename: ``str`` :return: Operation success :rtype: ``bool`` # Don't store initial stamp because the file has still not been changed. Save serialized graph to JSON file. When called with empty parameter, the filename is unchanged. :param filename: file to store the graph :type filename: ``str`` | ``None`` :return: Operation success :rtype: ``bool`` Evaluate all the nodes present in the scene. Handle Qt's mouse's button release event. :param ev: Mouse release event :type ev: ``QMouseEvent`` Handle Qt's mouse's button press event. :param ev: Mouse press event :type ev: ``QMouseEvent`` Testing method to put random QGraphicsItems and elements into QGraphicsScene Testing method to create 3 :class:`~nodedge.node.Node` connected by 2 :class:`~nodedge.edge.Edge`. # noqa: F841 # noqa: F841 Testing method to create a custom Node with custom content | 2.338093 | 2 |
workflows/subgroup_discovery/SubgroupDiscovery/Beam_SD.py | xflows/clowdflows | 38 | 6618916 | import orange
import sys
from SDRule import *
true = 1
false = 0
class Beam_SD:
def __init__(self, minSupport = 0.2, beamWidth = 5, g = 1, **kwds):
self.minSupport = minSupport
self.beamWidth = beamWidth
self.g = g
def __call__(self, data, targetClass, num_of_rules ):
if self.dataOK(data): # Checks weather targetClass is discrete
data_discretized = False
# If any of the attributes are continuous, discretize them
if data.domain.hasContinuousAttributes():
original_data = data
data_discretized = True
new_domain = []
discretize = orange.EntropyDiscretization(forceAttribute=True)
for attribute in data.domain.attributes:
if attribute.varType == orange.VarTypes.Continuous:
d_attribute = discretize(attribute, data)
# An attribute is irrelevant, if it is discretized into a single interval
# if len(d_attribute.getValueFrom.transformer.points) > 0:
new_domain.append(d_attribute)
else:
new_domain.append(attribute)
data = original_data.select(new_domain + [original_data.domain.classVar])
# initialization of beams
beam = [SDRule(data=data, targetClass=targetClass, g=self.g)] * self.beamWidth
newBeam = [SDRule(data=data, targetClass=targetClass, g=self.g)] * self.beamWidth
worstRuleIndex = 0
improvements = true
while improvements:
improvements = false
for rule in beam:
for attr in data.domain.attributes:
value = attr.firstvalue()
while(value):
newRule = rule.cloneAndAddCondition(attr,value)
if newRule.support > self.minSupport and self.betterThanWorstRule(newRule, newBeam, worstRuleIndex) and self.isRelevant(newRule, newBeam):
worstRuleIndex = self.replaceWorstRule(newRule, newBeam, worstRuleIndex)
improvements = true
value = attr.nextvalue(value)
beam = newBeam
# perform rule subset selection
if num_of_rules != 0:
beam = self.ruleSubsetSelection(beam, num_of_rules, data)
if data_discretized:
targetClassRule = SDRule(original_data, targetClass, conditions=[], g=1)
# change beam so the rules apply to original data
beam = [rule.getUndiscretized(original_data) for rule in beam]
else:
targetClassRule = SDRule(data, targetClass, conditions=[], g =1)
return SDRules(beam, targetClassRule, "SD")
def isRelevant(self, newRule, beam):
for rule in beam:
if newRule.isIrrelevant(rule):
return false
return true
def betterThanWorstRule(self, newRule, beam, worstRuleIndex):
if newRule.quality > beam[worstRuleIndex].quality: # better quality
return true
elif newRule.quality == beam[worstRuleIndex].quality and newRule.complexity < beam[worstRuleIndex].complexity: # same quality and smaller complexity
return true
else:
return false
def replaceWorstRule(self, rule, beam, worstRuleIndex):
beam[worstRuleIndex] = rule
wri = 0
for i in range(len(beam)):
if beam[i].quality < beam[wri].quality:
wri = i
return wri
def dataOK(self, data):
# if data.domain.hasContinuousAttributes():
# print "All attributes must be discrete."
# return false
if data.domain.classVar.varType != orange.VarTypes.Discrete:
print "Target Variable must be discrete"%(attr.name)
return false
return true
def ruleSubsetSelection(self, beam, num_of_rules, data):
SS = []
c = orange.newmetaid()
data.addMetaAttribute(c) #initialize to 1
if num_of_rules <= len(beam):
for i in range(num_of_rules):
best_score = 0
best_rule_index = 0
for i in range(len(beam)):
score = 0
for d in data: # calculate sum of weights of examples
if beam[i].filter(d):
score += 1.0/d.getweight(c)
if score>best_score:
best_score = score
best_rule_index = i
for d in data: # increase exampe counter
if beam[best_rule_index].filter(d):
d.setweight(c, d.getweight(c)+1)
SS.append(beam[best_rule_index])
del beam[best_rule_index]
data.removeMetaAttribute(c)
return SS
#___________________________________________________________________________________
if __name__=="__main__":
filename = "..\\..\\doc\\datasets\\lenses.tab"
if 'linux' in sys.platform:
filename= "/usr/doc/orange/datasets/lenses.tab"
data = orange.ExampleTable(filename)
learner = Beam_SD( minSupport = 0.2, beamWidth = 5, g = 6)
targetClass= orange.Value(data.domain.classVar, "soft")
rules = learner (data , targetClass=targetClass, num_of_rules=3)
rules.printRules()
| import orange
import sys
from SDRule import *
true = 1
false = 0
class Beam_SD:
def __init__(self, minSupport = 0.2, beamWidth = 5, g = 1, **kwds):
self.minSupport = minSupport
self.beamWidth = beamWidth
self.g = g
def __call__(self, data, targetClass, num_of_rules ):
if self.dataOK(data): # Checks weather targetClass is discrete
data_discretized = False
# If any of the attributes are continuous, discretize them
if data.domain.hasContinuousAttributes():
original_data = data
data_discretized = True
new_domain = []
discretize = orange.EntropyDiscretization(forceAttribute=True)
for attribute in data.domain.attributes:
if attribute.varType == orange.VarTypes.Continuous:
d_attribute = discretize(attribute, data)
# An attribute is irrelevant, if it is discretized into a single interval
# if len(d_attribute.getValueFrom.transformer.points) > 0:
new_domain.append(d_attribute)
else:
new_domain.append(attribute)
data = original_data.select(new_domain + [original_data.domain.classVar])
# initialization of beams
beam = [SDRule(data=data, targetClass=targetClass, g=self.g)] * self.beamWidth
newBeam = [SDRule(data=data, targetClass=targetClass, g=self.g)] * self.beamWidth
worstRuleIndex = 0
improvements = true
while improvements:
improvements = false
for rule in beam:
for attr in data.domain.attributes:
value = attr.firstvalue()
while(value):
newRule = rule.cloneAndAddCondition(attr,value)
if newRule.support > self.minSupport and self.betterThanWorstRule(newRule, newBeam, worstRuleIndex) and self.isRelevant(newRule, newBeam):
worstRuleIndex = self.replaceWorstRule(newRule, newBeam, worstRuleIndex)
improvements = true
value = attr.nextvalue(value)
beam = newBeam
# perform rule subset selection
if num_of_rules != 0:
beam = self.ruleSubsetSelection(beam, num_of_rules, data)
if data_discretized:
targetClassRule = SDRule(original_data, targetClass, conditions=[], g=1)
# change beam so the rules apply to original data
beam = [rule.getUndiscretized(original_data) for rule in beam]
else:
targetClassRule = SDRule(data, targetClass, conditions=[], g =1)
return SDRules(beam, targetClassRule, "SD")
def isRelevant(self, newRule, beam):
for rule in beam:
if newRule.isIrrelevant(rule):
return false
return true
def betterThanWorstRule(self, newRule, beam, worstRuleIndex):
if newRule.quality > beam[worstRuleIndex].quality: # better quality
return true
elif newRule.quality == beam[worstRuleIndex].quality and newRule.complexity < beam[worstRuleIndex].complexity: # same quality and smaller complexity
return true
else:
return false
def replaceWorstRule(self, rule, beam, worstRuleIndex):
beam[worstRuleIndex] = rule
wri = 0
for i in range(len(beam)):
if beam[i].quality < beam[wri].quality:
wri = i
return wri
def dataOK(self, data):
# if data.domain.hasContinuousAttributes():
# print "All attributes must be discrete."
# return false
if data.domain.classVar.varType != orange.VarTypes.Discrete:
print "Target Variable must be discrete"%(attr.name)
return false
return true
def ruleSubsetSelection(self, beam, num_of_rules, data):
SS = []
c = orange.newmetaid()
data.addMetaAttribute(c) #initialize to 1
if num_of_rules <= len(beam):
for i in range(num_of_rules):
best_score = 0
best_rule_index = 0
for i in range(len(beam)):
score = 0
for d in data: # calculate sum of weights of examples
if beam[i].filter(d):
score += 1.0/d.getweight(c)
if score>best_score:
best_score = score
best_rule_index = i
for d in data: # increase exampe counter
if beam[best_rule_index].filter(d):
d.setweight(c, d.getweight(c)+1)
SS.append(beam[best_rule_index])
del beam[best_rule_index]
data.removeMetaAttribute(c)
return SS
#___________________________________________________________________________________
if __name__=="__main__":
filename = "..\\..\\doc\\datasets\\lenses.tab"
if 'linux' in sys.platform:
filename= "/usr/doc/orange/datasets/lenses.tab"
data = orange.ExampleTable(filename)
learner = Beam_SD( minSupport = 0.2, beamWidth = 5, g = 6)
targetClass= orange.Value(data.domain.classVar, "soft")
rules = learner (data , targetClass=targetClass, num_of_rules=3)
rules.printRules()
| en | 0.695945 | # Checks weather targetClass is discrete # If any of the attributes are continuous, discretize them # An attribute is irrelevant, if it is discretized into a single interval # if len(d_attribute.getValueFrom.transformer.points) > 0: # initialization of beams # perform rule subset selection # change beam so the rules apply to original data # better quality # same quality and smaller complexity # if data.domain.hasContinuousAttributes(): # print "All attributes must be discrete." # return false #initialize to 1 # calculate sum of weights of examples # increase exampe counter #___________________________________________________________________________________ | 2.431529 | 2 |
netbox/tenancy/migrations/0004_package_model.py | paxio/netbox | 1 | 6618917 | <filename>netbox/tenancy/migrations/0004_package_model.py
# -*- coding: utf-8 -*-
# Generated by Django 1.11.10 on 2018-02-23 13:22
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import extras.models
class Migration(migrations.Migration):
dependencies = [
('ipam', '0023_package_model'),
('tenancy', '0003_unicode_literals'),
]
operations = [
migrations.CreateModel(
name='Package',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created', models.DateField(auto_now_add=True)),
('last_updated', models.DateTimeField(auto_now=True)),
('name', models.CharField(max_length=30, unique=True)),
('slug', models.SlugField(unique=True)),
('ipv4_enabled', models.BooleanField(default=True, help_text='Customers recieve an IPv4 address', verbose_name='IPv4 is enabled')),
('ipv6_enabled', models.BooleanField(default=True, help_text='Customers recieve an IPv6 address', verbose_name='IPv6 is enabled')),
('multicast_enabled', models.BooleanField(default=True, help_text='Customers can use multicast', verbose_name='Multicast is enabled')),
('service_type', models.PositiveSmallIntegerField(choices=[(0, 'Static configuration'), (1, 'Dynamic configuration')], default=1, help_text='Static or dynamic configuration', verbose_name='Service type')),
('speed_upload', models.PositiveIntegerField(verbose_name='Upload speed rate (Kbps)')),
('speed_download', models.PositiveIntegerField(verbose_name='Download speed rate (Kbps)')),
('qos_profile', models.CharField(max_length=30)),
('tag_type', models.PositiveSmallIntegerField(choices=[(0, 'Untagged port'), (1, 'Single tagged port'), (2, 'Double tagged port')], default=2, help_text='Customers provide any VLAN tags', verbose_name='Tag type')),
('dhcp_pool', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='prefixes', to='ipam.Prefix')),
('group', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='packages', to='tenancy.TenantGroup')),
],
options={
'ordering': ['group', 'name'],
},
),
]
| <filename>netbox/tenancy/migrations/0004_package_model.py
# -*- coding: utf-8 -*-
# Generated by Django 1.11.10 on 2018-02-23 13:22
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import extras.models
class Migration(migrations.Migration):
dependencies = [
('ipam', '0023_package_model'),
('tenancy', '0003_unicode_literals'),
]
operations = [
migrations.CreateModel(
name='Package',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created', models.DateField(auto_now_add=True)),
('last_updated', models.DateTimeField(auto_now=True)),
('name', models.CharField(max_length=30, unique=True)),
('slug', models.SlugField(unique=True)),
('ipv4_enabled', models.BooleanField(default=True, help_text='Customers recieve an IPv4 address', verbose_name='IPv4 is enabled')),
('ipv6_enabled', models.BooleanField(default=True, help_text='Customers recieve an IPv6 address', verbose_name='IPv6 is enabled')),
('multicast_enabled', models.BooleanField(default=True, help_text='Customers can use multicast', verbose_name='Multicast is enabled')),
('service_type', models.PositiveSmallIntegerField(choices=[(0, 'Static configuration'), (1, 'Dynamic configuration')], default=1, help_text='Static or dynamic configuration', verbose_name='Service type')),
('speed_upload', models.PositiveIntegerField(verbose_name='Upload speed rate (Kbps)')),
('speed_download', models.PositiveIntegerField(verbose_name='Download speed rate (Kbps)')),
('qos_profile', models.CharField(max_length=30)),
('tag_type', models.PositiveSmallIntegerField(choices=[(0, 'Untagged port'), (1, 'Single tagged port'), (2, 'Double tagged port')], default=2, help_text='Customers provide any VLAN tags', verbose_name='Tag type')),
('dhcp_pool', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='prefixes', to='ipam.Prefix')),
('group', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='packages', to='tenancy.TenantGroup')),
],
options={
'ordering': ['group', 'name'],
},
),
]
| en | 0.706986 | # -*- coding: utf-8 -*- # Generated by Django 1.11.10 on 2018-02-23 13:22 | 1.687636 | 2 |
server.py | ozancaglayan/mmt-ui | 4 | 6618918 | <filename>server.py
#!/usr/bin/env python
import bz2
import pickle
import argparse
from collections import defaultdict
from pathlib import Path
from flask import render_template, Flask, url_for
from flask_caching import Cache
from src.lib import parse_multeval_results_table, parse_ranksys
from src.utils import natural_sort
CONFIG = {
"CACHE_TYPE": "simple", # Flask-Caching related configs
"CACHE_DEFAULT_TIMEOUT": 36000,
}
app = Flask('mmt-ui')
app.config.from_mapping(CONFIG)
cache = Cache(app)
def get_tree_dict(folder):
"""Parses a folder hierarchy where each subfolder is a multeval
output folder that contains experiment results into a dict."""
def read_sources(fname):
"""Reads srcs.pkl.bz2 files to get source sentences used in MT
training for visualization purposes."""
try:
with bz2.BZ2File(fname, 'rb') as f:
d = pickle.load(f)
except Exception:
return None
return {k: d[v] if isinstance(v, str) else v for k, v in d.items()}
# Final dictionary has tasks as keys, test_sets as inner keys
# and a tuple of (path_to_folder, URL for results page, source sentences)
# as value
d = defaultdict(lambda: defaultdict(dict))
# The folder with experiment results
tasks = [exp.name for exp in Path(folder).iterdir() if exp.is_dir()]
tasks = natural_sort(tasks)
for task in tasks:
# Each subfolder is an experiment's multeval results
# srclang-trglang_<task description>
slang, tlang = task.split('_', 1)[0].split('-')
for test_set in Path(f'{folder}/{task}').iterdir():
source_dict = read_sources(test_set / 'srcs.pkl.bz2')
d[task][test_set.name] = (
Path(f'{folder}/{task}/{test_set.name}'),
url_for('results', task=task, testset=test_set.name),
source_dict)
return d
@app.route("/")
def index():
return render_template('index.html', tasks=get_tree_dict(app.config['results']))
@app.route("/<task>/<testset>")
@app.route("/<task>/<testset>/<system>")
@cache.memoize(timeout=36000)
def results(task, testset, system=None):
result_db = get_tree_dict(app.config['results'])
folder, _, source_dict = result_db[task][testset]
# Parse multeval table
results_table, baseline = parse_multeval_results_table(
folder / 'results.txt', task, testset)
kwargs = {'task': task, 'testset': testset, 'results_table': results_table}
if system is not None:
srcs = source_dict[system] if source_dict else None
kwargs['system'] = system
kwargs['baseline'] = baseline
kwargs['systems_table'] = parse_ranksys(
folder / 'ranksys', system, testset, srcs)
return render_template('view.html', **kwargs)
def main():
parser = argparse.ArgumentParser(prog='mmt-ui')
parser.add_argument('-r', '--results', help='Results folder',
required=True, type=str)
parser.add_argument('-p', '--port', help='Server port', default=8086)
parser.add_argument('-n', '--host', help='Host server IP', default='0.0.0.0')
parser.add_argument('-d', '--debug', help='Debug mode for Flask',
action='store_true')
parser.add_argument('-D', '--deploy', help='Enable deployment server',
action='store_true')
args = parser.parse_args()
app.config['results'] = args.results
app.config['DEBUG'] = args.debug
if args.deploy:
from waitress import serve
serve(app, host=args.host, port=args.port)
else:
app.run(host=args.host, port=args.port, threaded=True)
if __name__ == '__main__':
main()
| <filename>server.py
#!/usr/bin/env python
import bz2
import pickle
import argparse
from collections import defaultdict
from pathlib import Path
from flask import render_template, Flask, url_for
from flask_caching import Cache
from src.lib import parse_multeval_results_table, parse_ranksys
from src.utils import natural_sort
CONFIG = {
"CACHE_TYPE": "simple", # Flask-Caching related configs
"CACHE_DEFAULT_TIMEOUT": 36000,
}
app = Flask('mmt-ui')
app.config.from_mapping(CONFIG)
cache = Cache(app)
def get_tree_dict(folder):
"""Parses a folder hierarchy where each subfolder is a multeval
output folder that contains experiment results into a dict."""
def read_sources(fname):
"""Reads srcs.pkl.bz2 files to get source sentences used in MT
training for visualization purposes."""
try:
with bz2.BZ2File(fname, 'rb') as f:
d = pickle.load(f)
except Exception:
return None
return {k: d[v] if isinstance(v, str) else v for k, v in d.items()}
# Final dictionary has tasks as keys, test_sets as inner keys
# and a tuple of (path_to_folder, URL for results page, source sentences)
# as value
d = defaultdict(lambda: defaultdict(dict))
# The folder with experiment results
tasks = [exp.name for exp in Path(folder).iterdir() if exp.is_dir()]
tasks = natural_sort(tasks)
for task in tasks:
# Each subfolder is an experiment's multeval results
# srclang-trglang_<task description>
slang, tlang = task.split('_', 1)[0].split('-')
for test_set in Path(f'{folder}/{task}').iterdir():
source_dict = read_sources(test_set / 'srcs.pkl.bz2')
d[task][test_set.name] = (
Path(f'{folder}/{task}/{test_set.name}'),
url_for('results', task=task, testset=test_set.name),
source_dict)
return d
@app.route("/")
def index():
return render_template('index.html', tasks=get_tree_dict(app.config['results']))
@app.route("/<task>/<testset>")
@app.route("/<task>/<testset>/<system>")
@cache.memoize(timeout=36000)
def results(task, testset, system=None):
result_db = get_tree_dict(app.config['results'])
folder, _, source_dict = result_db[task][testset]
# Parse multeval table
results_table, baseline = parse_multeval_results_table(
folder / 'results.txt', task, testset)
kwargs = {'task': task, 'testset': testset, 'results_table': results_table}
if system is not None:
srcs = source_dict[system] if source_dict else None
kwargs['system'] = system
kwargs['baseline'] = baseline
kwargs['systems_table'] = parse_ranksys(
folder / 'ranksys', system, testset, srcs)
return render_template('view.html', **kwargs)
def main():
parser = argparse.ArgumentParser(prog='mmt-ui')
parser.add_argument('-r', '--results', help='Results folder',
required=True, type=str)
parser.add_argument('-p', '--port', help='Server port', default=8086)
parser.add_argument('-n', '--host', help='Host server IP', default='0.0.0.0')
parser.add_argument('-d', '--debug', help='Debug mode for Flask',
action='store_true')
parser.add_argument('-D', '--deploy', help='Enable deployment server',
action='store_true')
args = parser.parse_args()
app.config['results'] = args.results
app.config['DEBUG'] = args.debug
if args.deploy:
from waitress import serve
serve(app, host=args.host, port=args.port)
else:
app.run(host=args.host, port=args.port, threaded=True)
if __name__ == '__main__':
main()
| en | 0.819795 | #!/usr/bin/env python # Flask-Caching related configs Parses a folder hierarchy where each subfolder is a multeval output folder that contains experiment results into a dict. Reads srcs.pkl.bz2 files to get source sentences used in MT training for visualization purposes. # Final dictionary has tasks as keys, test_sets as inner keys # and a tuple of (path_to_folder, URL for results page, source sentences) # as value # The folder with experiment results # Each subfolder is an experiment's multeval results # srclang-trglang_<task description> # Parse multeval table | 2.368438 | 2 |
package/solution.py | pchtsp/fmp-instances | 0 | 6618919 | <filename>package/solution.py<gh_stars>0
# /usr/bin/python3
import pytups.superdict as sd
import pytups.tuplist as tl
import numpy as np
class Solution(object):
"""
These objects represent the solution to the assignment problem
It does not include the initial examples.
The methods are made to make it easy to get information.
They also draw graphs.
examples format:
>>> {'task': {'RESOURCE_1': {'PERIOD_1': 'TASK_1'}}, 'state_m': {'RESOURCE_1': {'PERIOD_2': {'MAINT_1': 1}}}}
"""
def __init__(self, solution_data):
data_default = {'state_m': {}, 'task': {}, 'aux': {'ret': {}, 'rut': {}, 'start': {}}}
self.data = sd.SuperDict.from_dict(data_default)
self.data.update(sd.SuperDict.from_dict(solution_data))
self.migrate_to_multimaint()
def migrate_to_multimaint(self):
states = self.data.get('state')
if not states:
return
# here, we have an old solution format
# we just convert the maint into a dict of maints
self.data['state_m'] = \
states.to_dictup().\
vapply(lambda v: sd.SuperDict({v: 1})).\
to_dictdict()
self.data.pop('state')
return
def get_category(self, category, param):
if param is None:
return self.data[category]
if param in list(self.data[category].values())[0]:
return sd.SuperDict.from_dict(self.data[category]).get_property(param)
raise IndexError("param {} is not present in the category {}".format(param, category))
def get_periods(self):
resource_period = self.get_tasks().keys_tl().to_dict(result_col=0).keys_l()
return sorted(resource_period)
def get_tasks(self):
return self.data['task'].to_dictup()
def get_state_tuplist(self, resource=None):
states = self.get_state(resource)
return tl.TupList(states.keys())
def get_state(self, resource=None):
data = self.data['state_m']
if resource is not None:
data = data.filter(resource, check=False)
return data.to_dictup()
def get_task_resources(self, periods=None):
tasks = self.get_tasks()
if periods:
periods = set(periods)
tasks = tasks.kfilter(lambda k: k[1] in periods)
return tasks.to_tuplist().to_dict(result_col=0, indices=[2, 1], is_list=True)
def get_task_num_resources(self, periods=None, resources=None):
tasks = self.get_tasks()
if periods:
periods = set(periods)
tasks = tasks.kfilter(lambda k: k[1] in periods)
if resources:
resources = set(resources)
tasks = tasks.kfilter(lambda k: k[0] in resources)
if not len(tasks):
return sd.SuperDict()
resource, period = zip(*tasks.keys())
task = tasks.values_l()
keys, values = np.unique(np.array(list(zip(task, period))), axis=0, return_counts=True)
result = sd.SuperDict({tuple(k): v for k, v in zip(keys, values)})
return result
def get_task_num_resources_old(self, periods=None):
result2 = self.get_task_resources(periods).vapply(len)
return result2
def get_state_tasks(self):
statesMissions = self.get_state_tuplist() + self.get_tasks().to_tuplist()
return tl.TupList(statesMissions)
def get_schedule(self, compare_tups):
"""
returns periods of time where a resources has a specific state
In a way, collapses single period assignments into a start-finish
:return: a (resource, start, finish, task) tuple
"""
statesMissions = self.get_state_tasks()
result = statesMissions.to_start_finish(compare_tups=compare_tups)
return result
def get_unavailable(self):
num_tasks = self.get_in_task()
in_maint = self.get_in_some_maintenance()
return {k: in_maint[k] + num_tasks[k] for k in in_maint} # in_maint has all periods already
def get_in_task(self):
tasks = [(t, r) for (r, t) in self.get_tasks()]
return tl.TupList(tasks).\
to_dict(1, is_list=True).\
to_lendict().\
fill_with_default(self.get_periods())
def get_in_some_maintenance(self):
raise ValueError("This is no longer supported")
def get_period_state(self, resource, period, cat):
try:
return self.data[cat][resource][period]
except KeyError:
return None
def get_period_state_category(self, resource, period):
task = self.get_period_state(resource, period, 'task')
if task is not None:
return task, 'task'
states = self.get_period_state(resource, period, 'state_m')
if states is not None:
return states, 'state_m'
return None, None
def is_resource_free(self, resource, period):
if self.get_period_state(resource, period, 'task') is not None:
return False
states = self.get_period_state(resource, period, 'state_m')
if states is not None and 'M' in states:
return False
return True
if __name__ == "__main__":
pass | <filename>package/solution.py<gh_stars>0
# /usr/bin/python3
import pytups.superdict as sd
import pytups.tuplist as tl
import numpy as np
class Solution(object):
"""
These objects represent the solution to the assignment problem
It does not include the initial examples.
The methods are made to make it easy to get information.
They also draw graphs.
examples format:
>>> {'task': {'RESOURCE_1': {'PERIOD_1': 'TASK_1'}}, 'state_m': {'RESOURCE_1': {'PERIOD_2': {'MAINT_1': 1}}}}
"""
def __init__(self, solution_data):
data_default = {'state_m': {}, 'task': {}, 'aux': {'ret': {}, 'rut': {}, 'start': {}}}
self.data = sd.SuperDict.from_dict(data_default)
self.data.update(sd.SuperDict.from_dict(solution_data))
self.migrate_to_multimaint()
def migrate_to_multimaint(self):
states = self.data.get('state')
if not states:
return
# here, we have an old solution format
# we just convert the maint into a dict of maints
self.data['state_m'] = \
states.to_dictup().\
vapply(lambda v: sd.SuperDict({v: 1})).\
to_dictdict()
self.data.pop('state')
return
def get_category(self, category, param):
if param is None:
return self.data[category]
if param in list(self.data[category].values())[0]:
return sd.SuperDict.from_dict(self.data[category]).get_property(param)
raise IndexError("param {} is not present in the category {}".format(param, category))
def get_periods(self):
resource_period = self.get_tasks().keys_tl().to_dict(result_col=0).keys_l()
return sorted(resource_period)
def get_tasks(self):
return self.data['task'].to_dictup()
def get_state_tuplist(self, resource=None):
states = self.get_state(resource)
return tl.TupList(states.keys())
def get_state(self, resource=None):
data = self.data['state_m']
if resource is not None:
data = data.filter(resource, check=False)
return data.to_dictup()
def get_task_resources(self, periods=None):
tasks = self.get_tasks()
if periods:
periods = set(periods)
tasks = tasks.kfilter(lambda k: k[1] in periods)
return tasks.to_tuplist().to_dict(result_col=0, indices=[2, 1], is_list=True)
def get_task_num_resources(self, periods=None, resources=None):
tasks = self.get_tasks()
if periods:
periods = set(periods)
tasks = tasks.kfilter(lambda k: k[1] in periods)
if resources:
resources = set(resources)
tasks = tasks.kfilter(lambda k: k[0] in resources)
if not len(tasks):
return sd.SuperDict()
resource, period = zip(*tasks.keys())
task = tasks.values_l()
keys, values = np.unique(np.array(list(zip(task, period))), axis=0, return_counts=True)
result = sd.SuperDict({tuple(k): v for k, v in zip(keys, values)})
return result
def get_task_num_resources_old(self, periods=None):
result2 = self.get_task_resources(periods).vapply(len)
return result2
def get_state_tasks(self):
statesMissions = self.get_state_tuplist() + self.get_tasks().to_tuplist()
return tl.TupList(statesMissions)
def get_schedule(self, compare_tups):
"""
returns periods of time where a resources has a specific state
In a way, collapses single period assignments into a start-finish
:return: a (resource, start, finish, task) tuple
"""
statesMissions = self.get_state_tasks()
result = statesMissions.to_start_finish(compare_tups=compare_tups)
return result
def get_unavailable(self):
num_tasks = self.get_in_task()
in_maint = self.get_in_some_maintenance()
return {k: in_maint[k] + num_tasks[k] for k in in_maint} # in_maint has all periods already
def get_in_task(self):
tasks = [(t, r) for (r, t) in self.get_tasks()]
return tl.TupList(tasks).\
to_dict(1, is_list=True).\
to_lendict().\
fill_with_default(self.get_periods())
def get_in_some_maintenance(self):
raise ValueError("This is no longer supported")
def get_period_state(self, resource, period, cat):
try:
return self.data[cat][resource][period]
except KeyError:
return None
def get_period_state_category(self, resource, period):
task = self.get_period_state(resource, period, 'task')
if task is not None:
return task, 'task'
states = self.get_period_state(resource, period, 'state_m')
if states is not None:
return states, 'state_m'
return None, None
def is_resource_free(self, resource, period):
if self.get_period_state(resource, period, 'task') is not None:
return False
states = self.get_period_state(resource, period, 'state_m')
if states is not None and 'M' in states:
return False
return True
if __name__ == "__main__":
pass | en | 0.848931 | # /usr/bin/python3 These objects represent the solution to the assignment problem It does not include the initial examples. The methods are made to make it easy to get information. They also draw graphs. examples format: >>> {'task': {'RESOURCE_1': {'PERIOD_1': 'TASK_1'}}, 'state_m': {'RESOURCE_1': {'PERIOD_2': {'MAINT_1': 1}}}} # here, we have an old solution format # we just convert the maint into a dict of maints returns periods of time where a resources has a specific state In a way, collapses single period assignments into a start-finish :return: a (resource, start, finish, task) tuple # in_maint has all periods already | 3.31043 | 3 |
Lab05_Format_String_Vulnerability/code/exp_rewrite_0xff99000.py | L1B0/- | 0 | 6618920 | from pwn import *
io = remote("127.0.0.1",9090,typ='udp')
# 0x3344 -> 0x0000
payload = "%26$hnaa" + p32(0x0804a040)
# 0x22 -> 0x99
payload += p32(0x0804a040+2)
payload += p32(0x0804a040+3)
payload += "%{}c".format(0x99-len(payload)+6)
payload += "%27$hhn"
#0x11 -> 0xff
payload += "%{}c".format(0xff-0x99)
payload += "%28$hhn"
print payload
io.sendline(payload)
io.interactive()
| from pwn import *
io = remote("127.0.0.1",9090,typ='udp')
# 0x3344 -> 0x0000
payload = "%26$hnaa" + p32(0x0804a040)
# 0x22 -> 0x99
payload += p32(0x0804a040+2)
payload += p32(0x0804a040+3)
payload += "%{}c".format(0x99-len(payload)+6)
payload += "%27$hhn"
#0x11 -> 0xff
payload += "%{}c".format(0xff-0x99)
payload += "%28$hhn"
print payload
io.sendline(payload)
io.interactive()
| en | 0.317623 | # 0x3344 -> 0x0000 # 0x22 -> 0x99 #0x11 -> 0xff | 2.212729 | 2 |
tests/pipeline/ios/test_gdrive_io.py | jorgetagle/dagger | 5 | 6618921 | import unittest
from dagger.pipeline.io_factory import gdrive_io
import yaml
class GDriveIOTest(unittest.TestCase):
def setUp(self) -> None:
with open('tests/fixtures/pipeline/ios/gdrive_io.yaml', "r") as stream:
config = yaml.safe_load(stream)
self.db_io = gdrive_io.GDriveIO(config, "/")
def test_properties(self):
self.assertEqual(self.db_io.alias(), "gdrive://test_folder/test_file_name")
self.assertEqual(self.db_io.rendered_name, "test_folder/test_file_name")
self.assertEqual(self.db_io.airflow_name, "gdrive-test_folder-test_file_name")
| import unittest
from dagger.pipeline.io_factory import gdrive_io
import yaml
class GDriveIOTest(unittest.TestCase):
def setUp(self) -> None:
with open('tests/fixtures/pipeline/ios/gdrive_io.yaml', "r") as stream:
config = yaml.safe_load(stream)
self.db_io = gdrive_io.GDriveIO(config, "/")
def test_properties(self):
self.assertEqual(self.db_io.alias(), "gdrive://test_folder/test_file_name")
self.assertEqual(self.db_io.rendered_name, "test_folder/test_file_name")
self.assertEqual(self.db_io.airflow_name, "gdrive-test_folder-test_file_name")
| none | 1 | 2.249117 | 2 | |
api/src/event/previousPage.py | SamuelJansen/CourseEditor | 0 | 6618922 | <filename>api/src/event/previousPage.py
import eventFunction
def previousPage(event) :
event.status = eventFunction.Status.NOT_RESOLVED
print(f' EventFunction called: previousPage({event.object.application.name})')
| <filename>api/src/event/previousPage.py
import eventFunction
def previousPage(event) :
event.status = eventFunction.Status.NOT_RESOLVED
print(f' EventFunction called: previousPage({event.object.application.name})')
| none | 1 | 2.371797 | 2 | |
web/core/serializers.py | MTES-MCT/biocarburants | 0 | 6618923 | <gh_stars>0
from rest_framework import serializers
from core.models import CarbureLot, CarbureLotEvent, CarbureLotComment, CarbureNotification, CarbureStock, CarbureStockTransformation, Depot, Entity, EntityCertificate, EntityDepot, GenericCertificate, GenericError, SustainabilityDeclaration
from doublecount.serializers import BiofuelSerializer, CountrySerializer, EntitySerializer, FeedStockSerializer
from producers.models import ProductionSite
class DepotSerializer(serializers.ModelSerializer):
country = CountrySerializer(read_only=True)
class Meta:
model = Depot
fields = ['id', 'name', 'city', 'depot_id', 'country', 'depot_type', 'address', 'postal_code', 'gps_coordinates', 'accise']
class EntityDepotSerializer(serializers.ModelSerializer):
depot = DepotSerializer(read_only=True)
entity = EntitySerializer(read_only=True)
blender = EntitySerializer(read_only=True)
class Meta:
model = EntityDepot
fields = ['entity', 'depot', 'ownership_type', 'blending_is_outsourced', 'blender']
class ProductionSiteSerializer(serializers.ModelSerializer):
country = CountrySerializer(read_only=True)
producer = EntitySerializer(read_only=True)
class Meta:
model = ProductionSite
fields = ['id', 'producer', 'name', 'country', 'date_mise_en_service', 'ges_option', 'eligible_dc', 'dc_reference',
'site_id', 'address', 'city', 'postal_code', 'gps_coordinates', 'manager_name', 'manager_phone', 'manager_email']
class GenericErrorSerializer(serializers.ModelSerializer):
class Meta:
model = GenericError
fields = ['error', 'is_blocking', 'field', 'value', 'extra', 'fields', 'acked_by_creator', 'acked_by_recipient']
class GenericErrorAdminSerializer(serializers.ModelSerializer):
class Meta:
model = GenericError
fields = ['error', 'is_blocking', 'field', 'value', 'extra', 'fields', 'acked_by_admin', 'acked_by_auditor']
class CarbureLotEventSerializer(serializers.ModelSerializer):
user = serializers.SlugRelatedField(read_only=True, slug_field='email')
class Meta:
model = CarbureLotEvent
fields = ['user', 'event_type', 'event_dt', 'metadata']
class CarbureStockEventSerializer(serializers.ModelSerializer):
class Meta:
model = CarbureLotEvent
fields = ['user', 'event_type', 'event_dt', 'metadata']
class CarbureLotCommentSerializer(serializers.ModelSerializer):
entity=EntitySerializer(read_only=True)
class Meta:
model = CarbureLotComment
fields = ['entity', 'user', 'comment_type', 'comment_dt', 'comment']
class CarbureLotCSVSerializer(serializers.ModelSerializer):
producer = serializers.SerializerMethodField()
production_site = serializers.SerializerMethodField()
production_country = serializers.SerializerMethodField()
supplier = serializers.SerializerMethodField()
client = serializers.SerializerMethodField()
delivery_date = serializers.SerializerMethodField()
delivery_site = serializers.SerializerMethodField()
delivery_site_country = serializers.SerializerMethodField()
country_of_origin = serializers.SerializerMethodField()
biofuel = serializers.SerializerMethodField()
feedstock = serializers.SerializerMethodField()
feedstock_category = serializers.SerializerMethodField()
production_site_double_counting_certificate = serializers.SerializerMethodField()
class Meta:
model = CarbureLot
fields = ['year', 'period', 'carbure_id', 'producer', 'production_site',
'production_country', 'production_site_commissioning_date', 'production_site_certificate', 'production_site_double_counting_certificate',
'supplier', 'supplier_certificate',
'transport_document_reference', 'client', 'delivery_date', 'delivery_site', 'delivery_site_country', 'delivery_type',
'volume', 'weight', 'lhv_amount', 'feedstock', 'feedstock_category', 'biofuel', 'country_of_origin',
'eec', 'el', 'ep', 'etd', 'eu', 'esca', 'eccs', 'eccr', 'eee', 'ghg_total', 'ghg_reference', 'ghg_reduction', 'ghg_reference_red_ii', 'ghg_reduction_red_ii',
'free_field'
]
def get_production_site_double_counting_certificate(self, obj):
return obj.production_site_double_counting_certificate if obj.feedstock and obj.feedstock.is_double_compte else ''
def get_producer(self, obj):
return obj.carbure_producer.name if obj.carbure_producer else obj.unknown_producer
def get_production_site(self, obj):
return obj.carbure_production_site.name if obj.carbure_production_site else obj.unknown_production_site
def get_production_country(self, obj):
return obj.production_country.code_pays if obj.production_country else ''
def get_supplier(self, obj):
return obj.carbure_supplier.name if obj.carbure_supplier else obj.unknown_supplier
def get_client(self, obj):
return obj.carbure_client.name if obj.carbure_client else obj.unknown_client
def get_delivery_date(self, obj):
return obj.delivery_date.strftime('%d/%m/%Y') if obj.delivery_date else ''
def get_delivery_site(self, obj):
return obj.carbure_delivery_site.depot_id if obj.carbure_delivery_site else obj.unknown_delivery_site
def get_delivery_site_country(self, obj):
return obj.delivery_site_country.code_pays if obj.delivery_site_country else ''
def get_feedstock(self, obj):
return obj.feedstock.code if obj.feedstock else ''
def get_feedstock_category(self, obj):
return obj.feedstock.category if obj.feedstock else ''
def get_biofuel(self, obj):
return obj.biofuel.code if obj.biofuel else ''
def get_country_of_origin(self, obj):
return obj.country_of_origin.code_pays if obj.country_of_origin else ''
class CarbureStockCSVSerializer(serializers.ModelSerializer):
production_site = serializers.SerializerMethodField()
production_country = serializers.SerializerMethodField()
supplier = serializers.SerializerMethodField()
delivery_date = serializers.SerializerMethodField()
depot = serializers.SerializerMethodField()
depot_name = serializers.SerializerMethodField()
feedstock = serializers.SerializerMethodField()
biofuel = serializers.SerializerMethodField()
country_of_origin = serializers.SerializerMethodField()
class Meta:
model = CarbureStock
fields = ['carbure_id',
'production_site', 'production_country',
'supplier', 'delivery_date', 'depot', 'depot_name',
'remaining_volume', 'remaining_weight',
'feedstock', 'biofuel', 'country_of_origin',
'ghg_reduction_red_ii',
]
def get_production_site(self, obj):
return obj.carbure_production_site.name if obj.carbure_production_site else obj.unknown_production_site
def get_production_country(self, obj):
return obj.production_country.code_pays if obj.production_country else ''
def get_supplier(self, obj):
return obj.carbure_supplier.name if obj.carbure_supplier else obj.unknown_supplier
def get_delivery_date(self, obj):
date = obj.get_delivery_date()
return date.strftime('%d/%m/%Y') if date else ''
def get_depot(self, obj):
return obj.depot.depot_id if obj.depot else ''
def get_depot_name(self, obj):
return obj.depot.name if obj.depot else ''
def get_feedstock(self, obj):
return obj.feedstock.code if obj.feedstock else ''
def get_biofuel(self, obj):
return obj.biofuel.code if obj.biofuel else ''
def get_country_of_origin(self, obj):
return obj.country_of_origin.code_pays if obj.country_of_origin else ''
class CarbureStockPublicSerializer(serializers.ModelSerializer):
depot = DepotSerializer(read_only=True)
carbure_client = EntitySerializer(read_only=True)
feedstock = FeedStockSerializer(read_only=True)
biofuel = BiofuelSerializer(read_only=True)
country_of_origin = CountrySerializer(read_only=True)
carbure_production_site = ProductionSiteSerializer(read_only=True)
production_country = CountrySerializer(read_only=True)
carbure_supplier = EntitySerializer(read_only=True)
initial_volume = serializers.SerializerMethodField()
delivery_date = serializers.SerializerMethodField()
period = serializers.SerializerMethodField()
class Meta:
model = CarbureStock
fields = ['id', 'carbure_id', 'depot', 'carbure_client',
'remaining_volume', 'remaining_weight', 'remaining_lhv_amount', 'feedstock', 'biofuel', 'country_of_origin',
'carbure_production_site', 'unknown_production_site', 'production_country', 'carbure_supplier', 'unknown_supplier',
'ghg_reduction', 'ghg_reduction_red_ii', 'initial_volume', 'delivery_date', 'period']
def get_initial_volume(self, obj):
if obj.parent_lot:
return obj.parent_lot.volume
elif obj.parent_transformation:
return obj.parent_transformation.volume_destination
else:
return 0
# return obj.parent_lot.volume if obj.parent_lot else obj.parent_transformation.volume_destination
def get_delivery_date(self, obj):
return obj.get_delivery_date().strftime('%Y-%m-%d')
def get_period(self, obj):
date = obj.get_delivery_date()
return date.year * 100 + date.month
class CarbureStockTransformationPublicSerializer(serializers.ModelSerializer):
source_stock = CarbureStockPublicSerializer(read_only=True)
dest_stock = CarbureStockPublicSerializer(read_only=True)
class Meta:
model = CarbureStockTransformation
fields = [
'transformation_type',
'source_stock',
'dest_stock',
'volume_deducted_from_source',
'volume_destination',
'metadata',
'transformed_by',
'entity',
'transformation_dt',
]
class CarbureLotPublicSerializer(serializers.ModelSerializer):
carbure_producer = EntitySerializer(read_only=True)
carbure_production_site = ProductionSiteSerializer(read_only=True)
production_country = CountrySerializer(read_only=True)
carbure_supplier = EntitySerializer(read_only=True)
carbure_client = EntitySerializer(read_only=True)
carbure_dispatch_site = DepotSerializer(read_only=True)
dispatch_site_country = CountrySerializer(read_only=True)
carbure_delivery_site = DepotSerializer(read_only=True)
delivery_site_country = CountrySerializer(read_only=True)
feedstock = FeedStockSerializer(read_only=True)
biofuel = BiofuelSerializer(read_only=True)
country_of_origin = CountrySerializer(read_only=True)
added_by = EntitySerializer(read_only=True)
carbure_vendor = EntitySerializer(read_only=True)
class Meta:
model = CarbureLot
fields = ['id', 'year', 'period', 'carbure_id',
'carbure_producer', 'unknown_producer', 'carbure_production_site', 'unknown_production_site',
'production_country', 'production_site_commissioning_date', 'production_site_certificate', 'production_site_double_counting_certificate',
'carbure_supplier', 'unknown_supplier', 'supplier_certificate', 'supplier_certificate_type',
'transport_document_type', 'transport_document_reference', 'carbure_client', 'unknown_client',
'dispatch_date', 'carbure_dispatch_site', 'unknown_dispatch_site', 'dispatch_site_country',
'delivery_date', 'carbure_delivery_site', 'unknown_delivery_site', 'delivery_site_country', 'delivery_type',
'lot_status', 'correction_status',
'volume', 'weight', 'lhv_amount', 'feedstock', 'biofuel', 'country_of_origin',
'eec', 'el', 'ep', 'etd', 'eu', 'esca', 'eccs', 'eccr', 'eee', 'ghg_total', 'ghg_reference', 'ghg_reduction', 'ghg_reference_red_ii', 'ghg_reduction_red_ii',
'free_field', 'added_by', 'created_at', 'carbure_vendor', 'vendor_certificate', 'vendor_certificate_type',
]
class CarbureLotAdminSerializer(CarbureLotPublicSerializer):
class Meta:
model = CarbureLot
fields = ['id', 'year', 'period', 'carbure_id',
'carbure_producer', 'unknown_producer', 'carbure_production_site', 'unknown_production_site',
'production_country', 'production_site_commissioning_date', 'production_site_certificate', 'production_site_double_counting_certificate',
'carbure_supplier', 'unknown_supplier', 'supplier_certificate', 'supplier_certificate_type',
'transport_document_type', 'transport_document_reference', 'carbure_client', 'unknown_client',
'dispatch_date', 'carbure_dispatch_site', 'unknown_dispatch_site', 'dispatch_site_country',
'delivery_date', 'carbure_delivery_site', 'unknown_delivery_site', 'delivery_site_country', 'delivery_type',
'lot_status', 'correction_status',
'volume', 'weight', 'lhv_amount', 'feedstock', 'biofuel', 'country_of_origin',
'eec', 'el', 'ep', 'etd', 'eu', 'esca', 'eccs', 'eccr', 'eee', 'ghg_total', 'ghg_reference', 'ghg_reduction', 'ghg_reference_red_ii', 'ghg_reduction_red_ii',
'free_field', 'added_by', 'created_at', 'highlighted_by_auditor', 'highlighted_by_admin', 'carbure_vendor', 'vendor_certificate', 'vendor_certificate_type',
]
class GenericCertificateSerializer(serializers.ModelSerializer):
class Meta:
model = GenericCertificate
fields = ['certificate_id', 'certificate_type', 'certificate_holder', 'certificate_issuer', 'address', 'valid_from', 'valid_until', 'download_link', 'scope', 'input', 'output']
class EntityCertificateSerializer(serializers.ModelSerializer):
entity = EntitySerializer()
certificate = GenericCertificateSerializer()
class Meta:
model = EntityCertificate
fields = ['id', 'entity', 'certificate', 'has_been_updated', 'checked_by_admin', 'rejected_by_admin', 'added_dt']
class SustainabilityDeclarationSerializer(serializers.ModelSerializer):
entity = EntitySerializer()
period = serializers.SerializerMethodField()
def get_period(self, obj):
return obj.period.year * 100 + obj.period.month
class Meta:
model = SustainabilityDeclaration
fields = ['entity', 'declared', 'checked', 'deadline', 'period', 'reminder_count']
class CarbureNotificationSerializer(serializers.ModelSerializer):
dest = EntitySerializer()
class Meta:
model = CarbureNotification
fields = ['id', 'dest', 'datetime', 'type', 'acked', 'send_by_email', 'email_sent', 'meta']
| from rest_framework import serializers
from core.models import CarbureLot, CarbureLotEvent, CarbureLotComment, CarbureNotification, CarbureStock, CarbureStockTransformation, Depot, Entity, EntityCertificate, EntityDepot, GenericCertificate, GenericError, SustainabilityDeclaration
from doublecount.serializers import BiofuelSerializer, CountrySerializer, EntitySerializer, FeedStockSerializer
from producers.models import ProductionSite
class DepotSerializer(serializers.ModelSerializer):
country = CountrySerializer(read_only=True)
class Meta:
model = Depot
fields = ['id', 'name', 'city', 'depot_id', 'country', 'depot_type', 'address', 'postal_code', 'gps_coordinates', 'accise']
class EntityDepotSerializer(serializers.ModelSerializer):
depot = DepotSerializer(read_only=True)
entity = EntitySerializer(read_only=True)
blender = EntitySerializer(read_only=True)
class Meta:
model = EntityDepot
fields = ['entity', 'depot', 'ownership_type', 'blending_is_outsourced', 'blender']
class ProductionSiteSerializer(serializers.ModelSerializer):
country = CountrySerializer(read_only=True)
producer = EntitySerializer(read_only=True)
class Meta:
model = ProductionSite
fields = ['id', 'producer', 'name', 'country', 'date_mise_en_service', 'ges_option', 'eligible_dc', 'dc_reference',
'site_id', 'address', 'city', 'postal_code', 'gps_coordinates', 'manager_name', 'manager_phone', 'manager_email']
class GenericErrorSerializer(serializers.ModelSerializer):
class Meta:
model = GenericError
fields = ['error', 'is_blocking', 'field', 'value', 'extra', 'fields', 'acked_by_creator', 'acked_by_recipient']
class GenericErrorAdminSerializer(serializers.ModelSerializer):
class Meta:
model = GenericError
fields = ['error', 'is_blocking', 'field', 'value', 'extra', 'fields', 'acked_by_admin', 'acked_by_auditor']
class CarbureLotEventSerializer(serializers.ModelSerializer):
user = serializers.SlugRelatedField(read_only=True, slug_field='email')
class Meta:
model = CarbureLotEvent
fields = ['user', 'event_type', 'event_dt', 'metadata']
class CarbureStockEventSerializer(serializers.ModelSerializer):
class Meta:
model = CarbureLotEvent
fields = ['user', 'event_type', 'event_dt', 'metadata']
class CarbureLotCommentSerializer(serializers.ModelSerializer):
entity=EntitySerializer(read_only=True)
class Meta:
model = CarbureLotComment
fields = ['entity', 'user', 'comment_type', 'comment_dt', 'comment']
class CarbureLotCSVSerializer(serializers.ModelSerializer):
producer = serializers.SerializerMethodField()
production_site = serializers.SerializerMethodField()
production_country = serializers.SerializerMethodField()
supplier = serializers.SerializerMethodField()
client = serializers.SerializerMethodField()
delivery_date = serializers.SerializerMethodField()
delivery_site = serializers.SerializerMethodField()
delivery_site_country = serializers.SerializerMethodField()
country_of_origin = serializers.SerializerMethodField()
biofuel = serializers.SerializerMethodField()
feedstock = serializers.SerializerMethodField()
feedstock_category = serializers.SerializerMethodField()
production_site_double_counting_certificate = serializers.SerializerMethodField()
class Meta:
model = CarbureLot
fields = ['year', 'period', 'carbure_id', 'producer', 'production_site',
'production_country', 'production_site_commissioning_date', 'production_site_certificate', 'production_site_double_counting_certificate',
'supplier', 'supplier_certificate',
'transport_document_reference', 'client', 'delivery_date', 'delivery_site', 'delivery_site_country', 'delivery_type',
'volume', 'weight', 'lhv_amount', 'feedstock', 'feedstock_category', 'biofuel', 'country_of_origin',
'eec', 'el', 'ep', 'etd', 'eu', 'esca', 'eccs', 'eccr', 'eee', 'ghg_total', 'ghg_reference', 'ghg_reduction', 'ghg_reference_red_ii', 'ghg_reduction_red_ii',
'free_field'
]
def get_production_site_double_counting_certificate(self, obj):
return obj.production_site_double_counting_certificate if obj.feedstock and obj.feedstock.is_double_compte else ''
def get_producer(self, obj):
return obj.carbure_producer.name if obj.carbure_producer else obj.unknown_producer
def get_production_site(self, obj):
return obj.carbure_production_site.name if obj.carbure_production_site else obj.unknown_production_site
def get_production_country(self, obj):
return obj.production_country.code_pays if obj.production_country else ''
def get_supplier(self, obj):
return obj.carbure_supplier.name if obj.carbure_supplier else obj.unknown_supplier
def get_client(self, obj):
return obj.carbure_client.name if obj.carbure_client else obj.unknown_client
def get_delivery_date(self, obj):
return obj.delivery_date.strftime('%d/%m/%Y') if obj.delivery_date else ''
def get_delivery_site(self, obj):
return obj.carbure_delivery_site.depot_id if obj.carbure_delivery_site else obj.unknown_delivery_site
def get_delivery_site_country(self, obj):
return obj.delivery_site_country.code_pays if obj.delivery_site_country else ''
def get_feedstock(self, obj):
return obj.feedstock.code if obj.feedstock else ''
def get_feedstock_category(self, obj):
return obj.feedstock.category if obj.feedstock else ''
def get_biofuel(self, obj):
return obj.biofuel.code if obj.biofuel else ''
def get_country_of_origin(self, obj):
return obj.country_of_origin.code_pays if obj.country_of_origin else ''
class CarbureStockCSVSerializer(serializers.ModelSerializer):
production_site = serializers.SerializerMethodField()
production_country = serializers.SerializerMethodField()
supplier = serializers.SerializerMethodField()
delivery_date = serializers.SerializerMethodField()
depot = serializers.SerializerMethodField()
depot_name = serializers.SerializerMethodField()
feedstock = serializers.SerializerMethodField()
biofuel = serializers.SerializerMethodField()
country_of_origin = serializers.SerializerMethodField()
class Meta:
model = CarbureStock
fields = ['carbure_id',
'production_site', 'production_country',
'supplier', 'delivery_date', 'depot', 'depot_name',
'remaining_volume', 'remaining_weight',
'feedstock', 'biofuel', 'country_of_origin',
'ghg_reduction_red_ii',
]
def get_production_site(self, obj):
return obj.carbure_production_site.name if obj.carbure_production_site else obj.unknown_production_site
def get_production_country(self, obj):
return obj.production_country.code_pays if obj.production_country else ''
def get_supplier(self, obj):
return obj.carbure_supplier.name if obj.carbure_supplier else obj.unknown_supplier
def get_delivery_date(self, obj):
date = obj.get_delivery_date()
return date.strftime('%d/%m/%Y') if date else ''
def get_depot(self, obj):
return obj.depot.depot_id if obj.depot else ''
def get_depot_name(self, obj):
return obj.depot.name if obj.depot else ''
def get_feedstock(self, obj):
return obj.feedstock.code if obj.feedstock else ''
def get_biofuel(self, obj):
return obj.biofuel.code if obj.biofuel else ''
def get_country_of_origin(self, obj):
return obj.country_of_origin.code_pays if obj.country_of_origin else ''
class CarbureStockPublicSerializer(serializers.ModelSerializer):
depot = DepotSerializer(read_only=True)
carbure_client = EntitySerializer(read_only=True)
feedstock = FeedStockSerializer(read_only=True)
biofuel = BiofuelSerializer(read_only=True)
country_of_origin = CountrySerializer(read_only=True)
carbure_production_site = ProductionSiteSerializer(read_only=True)
production_country = CountrySerializer(read_only=True)
carbure_supplier = EntitySerializer(read_only=True)
initial_volume = serializers.SerializerMethodField()
delivery_date = serializers.SerializerMethodField()
period = serializers.SerializerMethodField()
class Meta:
model = CarbureStock
fields = ['id', 'carbure_id', 'depot', 'carbure_client',
'remaining_volume', 'remaining_weight', 'remaining_lhv_amount', 'feedstock', 'biofuel', 'country_of_origin',
'carbure_production_site', 'unknown_production_site', 'production_country', 'carbure_supplier', 'unknown_supplier',
'ghg_reduction', 'ghg_reduction_red_ii', 'initial_volume', 'delivery_date', 'period']
def get_initial_volume(self, obj):
if obj.parent_lot:
return obj.parent_lot.volume
elif obj.parent_transformation:
return obj.parent_transformation.volume_destination
else:
return 0
# return obj.parent_lot.volume if obj.parent_lot else obj.parent_transformation.volume_destination
def get_delivery_date(self, obj):
return obj.get_delivery_date().strftime('%Y-%m-%d')
def get_period(self, obj):
date = obj.get_delivery_date()
return date.year * 100 + date.month
class CarbureStockTransformationPublicSerializer(serializers.ModelSerializer):
source_stock = CarbureStockPublicSerializer(read_only=True)
dest_stock = CarbureStockPublicSerializer(read_only=True)
class Meta:
model = CarbureStockTransformation
fields = [
'transformation_type',
'source_stock',
'dest_stock',
'volume_deducted_from_source',
'volume_destination',
'metadata',
'transformed_by',
'entity',
'transformation_dt',
]
class CarbureLotPublicSerializer(serializers.ModelSerializer):
carbure_producer = EntitySerializer(read_only=True)
carbure_production_site = ProductionSiteSerializer(read_only=True)
production_country = CountrySerializer(read_only=True)
carbure_supplier = EntitySerializer(read_only=True)
carbure_client = EntitySerializer(read_only=True)
carbure_dispatch_site = DepotSerializer(read_only=True)
dispatch_site_country = CountrySerializer(read_only=True)
carbure_delivery_site = DepotSerializer(read_only=True)
delivery_site_country = CountrySerializer(read_only=True)
feedstock = FeedStockSerializer(read_only=True)
biofuel = BiofuelSerializer(read_only=True)
country_of_origin = CountrySerializer(read_only=True)
added_by = EntitySerializer(read_only=True)
carbure_vendor = EntitySerializer(read_only=True)
class Meta:
model = CarbureLot
fields = ['id', 'year', 'period', 'carbure_id',
'carbure_producer', 'unknown_producer', 'carbure_production_site', 'unknown_production_site',
'production_country', 'production_site_commissioning_date', 'production_site_certificate', 'production_site_double_counting_certificate',
'carbure_supplier', 'unknown_supplier', 'supplier_certificate', 'supplier_certificate_type',
'transport_document_type', 'transport_document_reference', 'carbure_client', 'unknown_client',
'dispatch_date', 'carbure_dispatch_site', 'unknown_dispatch_site', 'dispatch_site_country',
'delivery_date', 'carbure_delivery_site', 'unknown_delivery_site', 'delivery_site_country', 'delivery_type',
'lot_status', 'correction_status',
'volume', 'weight', 'lhv_amount', 'feedstock', 'biofuel', 'country_of_origin',
'eec', 'el', 'ep', 'etd', 'eu', 'esca', 'eccs', 'eccr', 'eee', 'ghg_total', 'ghg_reference', 'ghg_reduction', 'ghg_reference_red_ii', 'ghg_reduction_red_ii',
'free_field', 'added_by', 'created_at', 'carbure_vendor', 'vendor_certificate', 'vendor_certificate_type',
]
class CarbureLotAdminSerializer(CarbureLotPublicSerializer):
class Meta:
model = CarbureLot
fields = ['id', 'year', 'period', 'carbure_id',
'carbure_producer', 'unknown_producer', 'carbure_production_site', 'unknown_production_site',
'production_country', 'production_site_commissioning_date', 'production_site_certificate', 'production_site_double_counting_certificate',
'carbure_supplier', 'unknown_supplier', 'supplier_certificate', 'supplier_certificate_type',
'transport_document_type', 'transport_document_reference', 'carbure_client', 'unknown_client',
'dispatch_date', 'carbure_dispatch_site', 'unknown_dispatch_site', 'dispatch_site_country',
'delivery_date', 'carbure_delivery_site', 'unknown_delivery_site', 'delivery_site_country', 'delivery_type',
'lot_status', 'correction_status',
'volume', 'weight', 'lhv_amount', 'feedstock', 'biofuel', 'country_of_origin',
'eec', 'el', 'ep', 'etd', 'eu', 'esca', 'eccs', 'eccr', 'eee', 'ghg_total', 'ghg_reference', 'ghg_reduction', 'ghg_reference_red_ii', 'ghg_reduction_red_ii',
'free_field', 'added_by', 'created_at', 'highlighted_by_auditor', 'highlighted_by_admin', 'carbure_vendor', 'vendor_certificate', 'vendor_certificate_type',
]
class GenericCertificateSerializer(serializers.ModelSerializer):
class Meta:
model = GenericCertificate
fields = ['certificate_id', 'certificate_type', 'certificate_holder', 'certificate_issuer', 'address', 'valid_from', 'valid_until', 'download_link', 'scope', 'input', 'output']
class EntityCertificateSerializer(serializers.ModelSerializer):
entity = EntitySerializer()
certificate = GenericCertificateSerializer()
class Meta:
model = EntityCertificate
fields = ['id', 'entity', 'certificate', 'has_been_updated', 'checked_by_admin', 'rejected_by_admin', 'added_dt']
class SustainabilityDeclarationSerializer(serializers.ModelSerializer):
entity = EntitySerializer()
period = serializers.SerializerMethodField()
def get_period(self, obj):
return obj.period.year * 100 + obj.period.month
class Meta:
model = SustainabilityDeclaration
fields = ['entity', 'declared', 'checked', 'deadline', 'period', 'reminder_count']
class CarbureNotificationSerializer(serializers.ModelSerializer):
dest = EntitySerializer()
class Meta:
model = CarbureNotification
fields = ['id', 'dest', 'datetime', 'type', 'acked', 'send_by_email', 'email_sent', 'meta'] | en | 0.119596 | # return obj.parent_lot.volume if obj.parent_lot else obj.parent_transformation.volume_destination | 1.909802 | 2 |
Yank/commands/cleanup.py | lilyminium/yank | 136 | 6618924 | <reponame>lilyminium/yank<filename>Yank/commands/cleanup.py
#!/usr/local/bin/env python
# =============================================================================================
# MODULE DOCSTRING
# =============================================================================================
"""
Clean up files produced by a YANK calculation.
"""
# =============================================================================================
# MODULE IMPORTS
# =============================================================================================
import os
import os.path
import glob
# =============================================================================================
# COMMAND-LINE INTERFACE
# =============================================================================================
usage = """
YANK cleanup
Usage:
yank cleanup (-s=STORE | --store=STORE) [-v | --verbose]
Description:
Clean up (delete) the run files.
Required Arguments:
-s=STORE, --store=STORE Storage directory for NetCDF data files.
General Options:
-v, --verbose Print verbose output
"""
# =============================================================================================
# COMMAND DISPATCH
# =============================================================================================
def dispatch(args):
verbose = args['--verbose']
# Remove NetCDF files in the destination directory.
for filename in glob.glob(os.path.join(args['--store'], '*.nc')):
if verbose: print("Removing file {}".format(filename))
os.remove(filename)
return True
| #!/usr/local/bin/env python
# =============================================================================================
# MODULE DOCSTRING
# =============================================================================================
"""
Clean up files produced by a YANK calculation.
"""
# =============================================================================================
# MODULE IMPORTS
# =============================================================================================
import os
import os.path
import glob
# =============================================================================================
# COMMAND-LINE INTERFACE
# =============================================================================================
usage = """
YANK cleanup
Usage:
yank cleanup (-s=STORE | --store=STORE) [-v | --verbose]
Description:
Clean up (delete) the run files.
Required Arguments:
-s=STORE, --store=STORE Storage directory for NetCDF data files.
General Options:
-v, --verbose Print verbose output
"""
# =============================================================================================
# COMMAND DISPATCH
# =============================================================================================
def dispatch(args):
verbose = args['--verbose']
# Remove NetCDF files in the destination directory.
for filename in glob.glob(os.path.join(args['--store'], '*.nc')):
if verbose: print("Removing file {}".format(filename))
os.remove(filename)
return True | en | 0.379768 | #!/usr/local/bin/env python # ============================================================================================= # MODULE DOCSTRING # ============================================================================================= Clean up files produced by a YANK calculation. # ============================================================================================= # MODULE IMPORTS # ============================================================================================= # ============================================================================================= # COMMAND-LINE INTERFACE # ============================================================================================= YANK cleanup Usage: yank cleanup (-s=STORE | --store=STORE) [-v | --verbose] Description: Clean up (delete) the run files. Required Arguments: -s=STORE, --store=STORE Storage directory for NetCDF data files. General Options: -v, --verbose Print verbose output # ============================================================================================= # COMMAND DISPATCH # ============================================================================================= # Remove NetCDF files in the destination directory. | 2.314767 | 2 |
lib/py/distances/distance_calc_multi.py | DeepK/distance-embed | 3 | 6618925 | import warnings
warnings.filterwarnings("ignore")
# key in data name
import sys
name = sys.argv[1]
# load data
from py.utils.load_data import read_dataset
X_train, _, X_test, _ = read_dataset(name)
data = []
data.extend(X_train)
data.extend(X_test)
print ("Loaded {} sentences".format(len(data)))
# get distance measures
from py.distances.distances import PairedDistance
# calculate distances in parallel
from multiprocessing import Pool
import numpy
from time import time as ts
n_processes = 3
n = len(data)
k_max = n * (n - 1) // 2
k_step = n ** 2 // 100000
hausdorffdist = numpy.zeros(k_max)
energydist = numpy.zeros(k_max)
def proc(start):
hausdorffdist = []
energydist = []
k1 = start
k2 = min(start + k_step, k_max)
for k in range(k1, k2):
i = int(n - 2 - int(numpy.sqrt(-8 * k + 4 * n * (n - 1) - 7) / 2.0 - 0.5))
j = int(k + i + 1 - n * (n - 1) / 2 + (n - i) * ((n - i) - 1) / 2)
a = data[i]
b = data[j]
paired_dist = PairedDistance(a, b)
# get various distances
energydist.append(paired_dist.energy_dist())
hausdorffdist.append(paired_dist.hausdorff())
return k1, k2, hausdorffdist, energydist
ts_start = ts()
with Pool(n_processes) as pool:
for k1, k2, res1, res2 in pool.imap_unordered(proc, range(0, k_max, k_step)):
hausdorffdist[k1:k2] = res1
energydist[k1:k2] = res2
print("{:.0f} minutes, {:,}..{:,} out of {:,}".format(
(ts() - ts_start)/60, k1, k2, k_max))
print("Elapsed %.0f minutes" % ((ts() - ts_start) / 60))
print("Saving...")
numpy.savez("../../../produced/hausdorffdist_{}.numpyz".format(name), dist=hausdorffdist)
numpy.savez("../../../produced/energydist_{}.numpyz".format(name), dist=energydist)
print("DONE")
| import warnings
warnings.filterwarnings("ignore")
# key in data name
import sys
name = sys.argv[1]
# load data
from py.utils.load_data import read_dataset
X_train, _, X_test, _ = read_dataset(name)
data = []
data.extend(X_train)
data.extend(X_test)
print ("Loaded {} sentences".format(len(data)))
# get distance measures
from py.distances.distances import PairedDistance
# calculate distances in parallel
from multiprocessing import Pool
import numpy
from time import time as ts
n_processes = 3
n = len(data)
k_max = n * (n - 1) // 2
k_step = n ** 2 // 100000
hausdorffdist = numpy.zeros(k_max)
energydist = numpy.zeros(k_max)
def proc(start):
hausdorffdist = []
energydist = []
k1 = start
k2 = min(start + k_step, k_max)
for k in range(k1, k2):
i = int(n - 2 - int(numpy.sqrt(-8 * k + 4 * n * (n - 1) - 7) / 2.0 - 0.5))
j = int(k + i + 1 - n * (n - 1) / 2 + (n - i) * ((n - i) - 1) / 2)
a = data[i]
b = data[j]
paired_dist = PairedDistance(a, b)
# get various distances
energydist.append(paired_dist.energy_dist())
hausdorffdist.append(paired_dist.hausdorff())
return k1, k2, hausdorffdist, energydist
ts_start = ts()
with Pool(n_processes) as pool:
for k1, k2, res1, res2 in pool.imap_unordered(proc, range(0, k_max, k_step)):
hausdorffdist[k1:k2] = res1
energydist[k1:k2] = res2
print("{:.0f} minutes, {:,}..{:,} out of {:,}".format(
(ts() - ts_start)/60, k1, k2, k_max))
print("Elapsed %.0f minutes" % ((ts() - ts_start) / 60))
print("Saving...")
numpy.savez("../../../produced/hausdorffdist_{}.numpyz".format(name), dist=hausdorffdist)
numpy.savez("../../../produced/energydist_{}.numpyz".format(name), dist=energydist)
print("DONE")
| en | 0.827256 | # key in data name # load data # get distance measures # calculate distances in parallel # get various distances | 2.435141 | 2 |
train/config.py | AppliedDeepLearning/train | 1 | 6618926 | <reponame>AppliedDeepLearning/train
import tensorflow as tf
_is_training_eager = False
_COLLECTION = 'training'
def training(*arguments, **keywords):
fn = _training_eager if tf.executing_eagerly() else _training
return fn(*arguments, **keywords)
def init_training(*arguments, **keywords):
fn = _init_training_eager if tf.executing_eagerly() else _init_training
return fn(*arguments, **keywords)
def _training_eager(value=None):
global _is_training_eager
if value is None:
return _is_training_eager
_is_training_eager = bool(value)
def _init_training_eager():
pass
def _training(value=None, session=None):
_init_training()
if value is None:
return tf.get_collection(_COLLECTION)[0]
if session is None:
session = tf.get_default_session()
value = int(value) + 1
tf.get_collection(_COLLECTION)[value].eval(session=session)
def _init_training():
if len(tf.get_collection(_COLLECTION)) == 0:
v = tf.Variable(False, trainable=False, name='is_training')
tf.add_to_collection(_COLLECTION, v)
tf.add_to_collection(_COLLECTION, tf.assign(v, False, name='set_training_false'))
tf.add_to_collection(_COLLECTION, tf.assign(v, True, name='set_training_true'))
| import tensorflow as tf
_is_training_eager = False
_COLLECTION = 'training'
def training(*arguments, **keywords):
fn = _training_eager if tf.executing_eagerly() else _training
return fn(*arguments, **keywords)
def init_training(*arguments, **keywords):
fn = _init_training_eager if tf.executing_eagerly() else _init_training
return fn(*arguments, **keywords)
def _training_eager(value=None):
global _is_training_eager
if value is None:
return _is_training_eager
_is_training_eager = bool(value)
def _init_training_eager():
pass
def _training(value=None, session=None):
_init_training()
if value is None:
return tf.get_collection(_COLLECTION)[0]
if session is None:
session = tf.get_default_session()
value = int(value) + 1
tf.get_collection(_COLLECTION)[value].eval(session=session)
def _init_training():
if len(tf.get_collection(_COLLECTION)) == 0:
v = tf.Variable(False, trainable=False, name='is_training')
tf.add_to_collection(_COLLECTION, v)
tf.add_to_collection(_COLLECTION, tf.assign(v, False, name='set_training_false'))
tf.add_to_collection(_COLLECTION, tf.assign(v, True, name='set_training_true')) | none | 1 | 2.686609 | 3 | |
graphs/graph_list.py | Maiven/Python | 21 | 6618927 | #!/usr/bin/python
# Author: <NAME>
# We can use Python's dictionary for constructing the graph.
class AdjacencyList:
def __init__(self):
self.adj_list = {}
def add_edge(self, from_vertex: int, to_vertex: int) -> None:
# check if vertex is already present
if from_vertex in self.adj_list:
self.adj_list[from_vertex].append(to_vertex)
else:
self.adj_list[from_vertex] = [to_vertex]
def print_list(self) -> None:
for i in self.adj_list:
print((i, "->", " -> ".join([str(j) for j in self.adj_list[i]])))
if __name__ == "__main__":
al = AdjacencyList()
al.add_edge(0, 1)
al.add_edge(0, 4)
al.add_edge(4, 1)
al.add_edge(4, 3)
al.add_edge(1, 0)
al.add_edge(1, 4)
al.add_edge(1, 3)
al.add_edge(1, 2)
al.add_edge(2, 3)
al.add_edge(3, 4)
al.print_list()
# OUTPUT:
# 0 -> 1 -> 4
# 1 -> 0 -> 4 -> 3 -> 2
# 2 -> 3
# 3 -> 4
# 4 -> 1 -> 3
| #!/usr/bin/python
# Author: <NAME>
# We can use Python's dictionary for constructing the graph.
class AdjacencyList:
def __init__(self):
self.adj_list = {}
def add_edge(self, from_vertex: int, to_vertex: int) -> None:
# check if vertex is already present
if from_vertex in self.adj_list:
self.adj_list[from_vertex].append(to_vertex)
else:
self.adj_list[from_vertex] = [to_vertex]
def print_list(self) -> None:
for i in self.adj_list:
print((i, "->", " -> ".join([str(j) for j in self.adj_list[i]])))
if __name__ == "__main__":
al = AdjacencyList()
al.add_edge(0, 1)
al.add_edge(0, 4)
al.add_edge(4, 1)
al.add_edge(4, 3)
al.add_edge(1, 0)
al.add_edge(1, 4)
al.add_edge(1, 3)
al.add_edge(1, 2)
al.add_edge(2, 3)
al.add_edge(3, 4)
al.print_list()
# OUTPUT:
# 0 -> 1 -> 4
# 1 -> 0 -> 4 -> 3 -> 2
# 2 -> 3
# 3 -> 4
# 4 -> 1 -> 3
| en | 0.191183 | #!/usr/bin/python # Author: <NAME> # We can use Python's dictionary for constructing the graph. # check if vertex is already present # OUTPUT: # 0 -> 1 -> 4 # 1 -> 0 -> 4 -> 3 -> 2 # 2 -> 3 # 3 -> 4 # 4 -> 1 -> 3 | 4.015217 | 4 |
applications/mupiopolitico/views.py | PEM-Humboldt/visor-geografico-I2d-backend | 0 | 6618928 | <filename>applications/mupiopolitico/views.py
from django.shortcuts import render
from rest_framework.generics import ListAPIView
from django.db.models import Q
from .models import MpioPolitico
from .serializers import mpioPoliticoSerializer
# Create your views here.
class mupioSearch(ListAPIView):
serializer_class=mpioPoliticoSerializer
def get_queryset(self):
kword = self.kwargs['kword']
queryParams = kword.split(",")
numberParams = len(queryParams)
q1 = queryParams[0]
qmupios= MpioPolitico.objects.filter(nombre__istartswith=q1)[:5]
if qmupios:
if numberParams == 1:
context = qmupios
else:
q2 = queryParams[1]
context = MpioPolitico.objects.filter(Q(nombre__istartswith=q1) & Q(dpto_nombre__istartswith=q2))[:5]
else:
if numberParams == 1:
context = MpioPolitico.objects.filter(dpto_nombre__istartswith=q1)[:5]
else:
q2 = queryParams[1]
context = MpioPolitico.objects.filter(Q(dpto_nombre__istartswith=q1) & Q(nombre__istartswith=q2))[:5]
return context
| <filename>applications/mupiopolitico/views.py
from django.shortcuts import render
from rest_framework.generics import ListAPIView
from django.db.models import Q
from .models import MpioPolitico
from .serializers import mpioPoliticoSerializer
# Create your views here.
class mupioSearch(ListAPIView):
serializer_class=mpioPoliticoSerializer
def get_queryset(self):
kword = self.kwargs['kword']
queryParams = kword.split(",")
numberParams = len(queryParams)
q1 = queryParams[0]
qmupios= MpioPolitico.objects.filter(nombre__istartswith=q1)[:5]
if qmupios:
if numberParams == 1:
context = qmupios
else:
q2 = queryParams[1]
context = MpioPolitico.objects.filter(Q(nombre__istartswith=q1) & Q(dpto_nombre__istartswith=q2))[:5]
else:
if numberParams == 1:
context = MpioPolitico.objects.filter(dpto_nombre__istartswith=q1)[:5]
else:
q2 = queryParams[1]
context = MpioPolitico.objects.filter(Q(dpto_nombre__istartswith=q1) & Q(nombre__istartswith=q2))[:5]
return context
| en | 0.968116 | # Create your views here. | 1.922756 | 2 |
tools/DbInit.py | StrickerLee/SYSU-Software-2017 | 40 | 6618929 | <filename>tools/DbInit.py
# -*- coding: utf-8 -*-
import pymysql
import json
def initDb(USER, PASSWORD):
try:
print("Connecting to database...")
db_con = pymysql.connect(
host="localhost",
user=USER,
passwd=PASSWORD
)
except:
print("Connection is failed, check your root account in config.json")
print("Successful connect to database")
cursor = db_con.cursor()
# drop previous database
try:
print("Drop previous database...")
sql = 'DROP DATABASE IF EXISTS django'
cursor.execute(sql)
except Exception as Error:
print(Error)
# drop user
try:
print("Drop previous user for sdin...")
sql = "DROP USER 'django'@'localhost'"
cursor.execute(sql)
except Exception as Error:
print(Error)
#create database for sdin
try:
print("Creating database for sdin...")
sql = "CREATE DATABASE IF NOT EXISTS django"
cursor.execute(sql)
except Exception as Error:
print(Error)
#create user for sdin's database
try:
print("Creating user for sdin's database...")
sql = "CREATE USER 'django'@'localhost' IDENTIFIED BY '<PASSWORD>!'"
cursor.execute(sql)
except Exception as Error:
print(Error)
#grant privileges to user
try:
print("Granting privileges to the user on sdin's database...")
sql = "grant all privileges on django.* to django@localhost"
cursor.execute(sql)
cursor.execute("flush privileges")
except Exception as Error:
print(Error)
print("Database has initialized!")
return 1
if __name__ == "__main__":
with open("config.json", "r", encoding='utf-8') as load_f:
cnf = json.load(load_f)
flag = initDb(cnf["mysql_root_account"], cnf["mysql_root_password"])
| <filename>tools/DbInit.py
# -*- coding: utf-8 -*-
import pymysql
import json
def initDb(USER, PASSWORD):
try:
print("Connecting to database...")
db_con = pymysql.connect(
host="localhost",
user=USER,
passwd=PASSWORD
)
except:
print("Connection is failed, check your root account in config.json")
print("Successful connect to database")
cursor = db_con.cursor()
# drop previous database
try:
print("Drop previous database...")
sql = 'DROP DATABASE IF EXISTS django'
cursor.execute(sql)
except Exception as Error:
print(Error)
# drop user
try:
print("Drop previous user for sdin...")
sql = "DROP USER 'django'@'localhost'"
cursor.execute(sql)
except Exception as Error:
print(Error)
#create database for sdin
try:
print("Creating database for sdin...")
sql = "CREATE DATABASE IF NOT EXISTS django"
cursor.execute(sql)
except Exception as Error:
print(Error)
#create user for sdin's database
try:
print("Creating user for sdin's database...")
sql = "CREATE USER 'django'@'localhost' IDENTIFIED BY '<PASSWORD>!'"
cursor.execute(sql)
except Exception as Error:
print(Error)
#grant privileges to user
try:
print("Granting privileges to the user on sdin's database...")
sql = "grant all privileges on django.* to django@localhost"
cursor.execute(sql)
cursor.execute("flush privileges")
except Exception as Error:
print(Error)
print("Database has initialized!")
return 1
if __name__ == "__main__":
with open("config.json", "r", encoding='utf-8') as load_f:
cnf = json.load(load_f)
flag = initDb(cnf["mysql_root_account"], cnf["mysql_root_password"])
| en | 0.776545 | # -*- coding: utf-8 -*- # drop previous database # drop user #create database for sdin #create user for sdin's database #grant privileges to user | 3.05259 | 3 |
adminultimateguide/createFakeData.py | csurbier/djangoadminultimateguide | 0 | 6618930 | <filename>adminultimateguide/createFakeData.py<gh_stars>0
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "adminultimateguide.settings")
import django
django.setup()
from faker import factory,Faker
from backoffice.models import *
from model_bakery.recipe import Recipe,foreign_key
fake = Faker()
########### First 100 random Authors,Questions and choices
for _ in range(100):
author = Recipe(
Author,
name = fake.name(),
createdDate = fake.future_datetime(end_date="+30d", tzinfo=None),
updatedDate = fake.future_datetime(end_date="+30d", tzinfo=None),
)
# create question
question = Recipe(Question,
question_text = fake.sentence(nb_words=6, variable_nb_words=True, ext_word_list=None),
pub_date =fake.future_datetime(end_date="+30d", tzinfo=None),
refAuthor=foreign_key(author),
createdDate=fake.future_datetime(end_date="+30d", tzinfo=None),
updatedDate=fake.future_datetime(end_date="+30d", tzinfo=None),
)
# create Choices
choice = Recipe(Choice,
question=foreign_key(question),
choice_text = fake.sentence(nb_words=1, variable_nb_words=True, ext_word_list=None),
createdDate=fake.future_datetime(end_date="+30d", tzinfo=None),
updatedDate=fake.future_datetime(end_date="+30d", tzinfo=None),
)
choice.make() | <filename>adminultimateguide/createFakeData.py<gh_stars>0
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "adminultimateguide.settings")
import django
django.setup()
from faker import factory,Faker
from backoffice.models import *
from model_bakery.recipe import Recipe,foreign_key
fake = Faker()
########### First 100 random Authors,Questions and choices
for _ in range(100):
author = Recipe(
Author,
name = fake.name(),
createdDate = fake.future_datetime(end_date="+30d", tzinfo=None),
updatedDate = fake.future_datetime(end_date="+30d", tzinfo=None),
)
# create question
question = Recipe(Question,
question_text = fake.sentence(nb_words=6, variable_nb_words=True, ext_word_list=None),
pub_date =fake.future_datetime(end_date="+30d", tzinfo=None),
refAuthor=foreign_key(author),
createdDate=fake.future_datetime(end_date="+30d", tzinfo=None),
updatedDate=fake.future_datetime(end_date="+30d", tzinfo=None),
)
# create Choices
choice = Recipe(Choice,
question=foreign_key(question),
choice_text = fake.sentence(nb_words=1, variable_nb_words=True, ext_word_list=None),
createdDate=fake.future_datetime(end_date="+30d", tzinfo=None),
updatedDate=fake.future_datetime(end_date="+30d", tzinfo=None),
)
choice.make() | en | 0.488174 | ########### First 100 random Authors,Questions and choices # create question # create Choices | 2.01668 | 2 |
LeetCode/Powerful Integers.py | UtkarshPathrabe/Competitive-Coding | 13 | 6618931 | <reponame>UtkarshPathrabe/Competitive-Coding<filename>LeetCode/Powerful Integers.py
class Solution:
def powerfulIntegers(self, x: int, y: int, bound: int) -> List[int]:
result = set()
for i in range(20):
for j in range(20):
val = x ** i + y ** j
if val <= bound:
result.add(val)
return list(result) | Integers.py
class Solution:
def powerfulIntegers(self, x: int, y: int, bound: int) -> List[int]:
result = set()
for i in range(20):
for j in range(20):
val = x ** i + y ** j
if val <= bound:
result.add(val)
return list(result) | none | 1 | 3.215672 | 3 | |
frontend/website_view.py | t1goe/FYP-bss-rebalancing | 0 | 6618932 | <gh_stars>0
from datetime import datetime
import math
import pickle
from os import listdir
from os.path import isfile, join
import csv
from flask import Flask, render_template, request
import tensorflow as tf
from tensorflow import keras
import copy
import numpy as np
from sklearn.preprocessing import MinMaxScaler
from numpy import concatenate
from generate_jobs import generate_jobs
app = Flask(__name__)
@app.route('/', methods=['POST', 'GET'])
def display():
stations = get_station_names()
sorted(stations.keys(), key=lambda x: x.lower())
if request.args.get('datetime') is not None:
dt = request.args.get('datetime')
if request.args.get('station_id') is None:
return render_template('site.html', station_info=stations, result=None)
else:
if request.args.get('simple') is None:
answer = full_predict(
request.args.get('station_id'),
convert_time(dt),
convert_date(dt),
convert_day(dt),
request.args.get('rain'),
request.args.get('temp'),
request.args.get('rhum')
)
elif request.args.get('simple') == 'on':
answer = simple_predict(
request.args.get('station_id'),
convert_time(dt),
convert_date(dt),
convert_day(dt)
)
else:
answer = 0
answer = round(answer)
return render_template('site.html',
station_info=stations,
current_station_name=stations[request.args.get('station_id')],
current_time_info=request.args.get('datetime'),
result=answer)
@app.route('/list', methods=['POST', 'GET'])
def list():
stations = get_station_names()
sorted(stations.keys(), key=lambda x: x.lower())
if request.args.get('date') is not None:
dt = request.args.get('date')
if request.args.get('date') is None:
return render_template('list.html',
station_info=stations,
result=None)
else:
answers = {}
for x in range(24):
answers[str(x) + ":00"] = (
round(
simple_predict(
request.args.get('station_id'),
(x * 12),
convert_date(dt + 'T00:00'),
convert_day(dt + 'T00:00')
)
)
)
return render_template('list.html',
station_info=stations,
current_station_name=stations[request.args.get('station_id')],
current_date_info=request.args.get('date'),
result=answers
)
@app.route('/jobs', methods=['POST', 'GET'])
def jobs():
if request.args.get('datetime') is None:
return render_template('jobs.html',
current_date_info=None,
result=None
)
else:
input_date = datetime.strptime(request.args.get('datetime'), "%Y-%m-%dT%H:%M")
results = generate_jobs(date=input_date)
return render_template('jobs.html',
current_date_info=request.args.get('datetime'),
result=convert_results_to_english(results)
)
def convert_results_to_english(results):
station_names = get_station_names()
pos = 0
for job in results:
new_job = (
str(job[0]) + " | " + station_names[str(job[0])],
str(job[1]) + " | " + station_names[str(job[1])],
job[2]
)
results[pos] = new_job
pos += 1
return results
def convert_time(x):
"""
Converts TIME field in the CSV to an integer representing
what time of day it is (in number of 5min increments) from 0 to 287
eg
- 00:00 -> 0
- 00:10 -> 2
- 02:20 -> 28
etc
"""
a = x.split('T')
a = a[1].split(':')
ans = math.floor((int(a[0]) * 12) + (int(a[1]) / 5))
return ans
def convert_date(x):
"""
Converts TIME field to an integer representing the day of the year
eg
- 2019-02-10 -> 41
"""
current_date = datetime.strptime(x, "%Y-%m-%dT%H:%M")
return current_date.strftime('%j')
def convert_day(x):
"""
Converts TIME field to an integer representing the day of the week
eg
- 2019-02-10 -> 0 (Sunday)
"""
current_date = datetime.strptime(x, "%Y-%m-%dT%H:%M")
return current_date.strftime('%w')
def get_station_names():
mypath = '../datasets/bss/dublin/ml_models/'
files = [f for f in listdir(mypath) if isfile(join(mypath, f))]
station_ids = [x.split('.')[0].split('_')[1] for x in files]
output = {}
for sid in station_ids:
csv_file = csv.reader(open('../datasets/bss/dublin/original/dublin.csv', "r"), delimiter=",")
for row in csv_file:
if sid == row[0]:
output[sid] = row[1]
return output
def simple_predict(station_id, int_time, int_date, int_day):
destination_directory = '../datasets/bss/dublin/simple_ml_models/'
scaler_destination_directory = copy.deepcopy(destination_directory) + 'scalers/'
model = tf.keras.models.load_model(destination_directory + 'station_' + str(station_id) + '.h5')
file = open(scaler_destination_directory + 'station_' + str(station_id) + '.pkl', "rb")
scaler = pickle.load(file)
file.close()
params = np.array([0, int_time, int_date, int_day])
params = params.reshape(1, -1)
params = scaler.transform(params)
params = np.array([params])
params = params.tolist()
params[0][0].pop(0)
params = np.array(params)
answer = model.predict(params)
full_row = concatenate((answer, params[0]), axis=1)
inv_row = scaler.inverse_transform(full_row)
return inv_row[0][0]
def full_predict(station_id, int_time, int_date, int_day, rain, temp, rhum):
destination_directory = '../datasets/bss/dublin/ml_models/'
scaler_destination_directory = copy.deepcopy(destination_directory) + 'scalers/'
model = tf.keras.models.load_model(destination_directory + 'station_' + str(station_id) + '.h5')
file = open(scaler_destination_directory + 'station_' + str(station_id) + '.pkl', "rb")
scaler = pickle.load(file)
file.close()
params = np.array([0, int_time, int_date, int_day, rain, temp, rhum])
params = params.reshape(1, -1)
params = scaler.transform(params)
params = np.array([params])
params = params.tolist()
params[0][0].pop(0)
params = np.array(params)
answer = model.predict(params)
full_row = concatenate((answer, params[0]), axis=1)
inv_row = scaler.inverse_transform(full_row)
return inv_row[0][0]
if __name__ == '__main__':
# full_predict(2, 24, 213, 4, 0, 14, 87)
# station_id, int_time, int_date, int_day, rain, temp, rhum
app.run(debug=True)
| from datetime import datetime
import math
import pickle
from os import listdir
from os.path import isfile, join
import csv
from flask import Flask, render_template, request
import tensorflow as tf
from tensorflow import keras
import copy
import numpy as np
from sklearn.preprocessing import MinMaxScaler
from numpy import concatenate
from generate_jobs import generate_jobs
app = Flask(__name__)
@app.route('/', methods=['POST', 'GET'])
def display():
stations = get_station_names()
sorted(stations.keys(), key=lambda x: x.lower())
if request.args.get('datetime') is not None:
dt = request.args.get('datetime')
if request.args.get('station_id') is None:
return render_template('site.html', station_info=stations, result=None)
else:
if request.args.get('simple') is None:
answer = full_predict(
request.args.get('station_id'),
convert_time(dt),
convert_date(dt),
convert_day(dt),
request.args.get('rain'),
request.args.get('temp'),
request.args.get('rhum')
)
elif request.args.get('simple') == 'on':
answer = simple_predict(
request.args.get('station_id'),
convert_time(dt),
convert_date(dt),
convert_day(dt)
)
else:
answer = 0
answer = round(answer)
return render_template('site.html',
station_info=stations,
current_station_name=stations[request.args.get('station_id')],
current_time_info=request.args.get('datetime'),
result=answer)
@app.route('/list', methods=['POST', 'GET'])
def list():
stations = get_station_names()
sorted(stations.keys(), key=lambda x: x.lower())
if request.args.get('date') is not None:
dt = request.args.get('date')
if request.args.get('date') is None:
return render_template('list.html',
station_info=stations,
result=None)
else:
answers = {}
for x in range(24):
answers[str(x) + ":00"] = (
round(
simple_predict(
request.args.get('station_id'),
(x * 12),
convert_date(dt + 'T00:00'),
convert_day(dt + 'T00:00')
)
)
)
return render_template('list.html',
station_info=stations,
current_station_name=stations[request.args.get('station_id')],
current_date_info=request.args.get('date'),
result=answers
)
@app.route('/jobs', methods=['POST', 'GET'])
def jobs():
if request.args.get('datetime') is None:
return render_template('jobs.html',
current_date_info=None,
result=None
)
else:
input_date = datetime.strptime(request.args.get('datetime'), "%Y-%m-%dT%H:%M")
results = generate_jobs(date=input_date)
return render_template('jobs.html',
current_date_info=request.args.get('datetime'),
result=convert_results_to_english(results)
)
def convert_results_to_english(results):
station_names = get_station_names()
pos = 0
for job in results:
new_job = (
str(job[0]) + " | " + station_names[str(job[0])],
str(job[1]) + " | " + station_names[str(job[1])],
job[2]
)
results[pos] = new_job
pos += 1
return results
def convert_time(x):
"""
Converts TIME field in the CSV to an integer representing
what time of day it is (in number of 5min increments) from 0 to 287
eg
- 00:00 -> 0
- 00:10 -> 2
- 02:20 -> 28
etc
"""
a = x.split('T')
a = a[1].split(':')
ans = math.floor((int(a[0]) * 12) + (int(a[1]) / 5))
return ans
def convert_date(x):
"""
Converts TIME field to an integer representing the day of the year
eg
- 2019-02-10 -> 41
"""
current_date = datetime.strptime(x, "%Y-%m-%dT%H:%M")
return current_date.strftime('%j')
def convert_day(x):
"""
Converts TIME field to an integer representing the day of the week
eg
- 2019-02-10 -> 0 (Sunday)
"""
current_date = datetime.strptime(x, "%Y-%m-%dT%H:%M")
return current_date.strftime('%w')
def get_station_names():
mypath = '../datasets/bss/dublin/ml_models/'
files = [f for f in listdir(mypath) if isfile(join(mypath, f))]
station_ids = [x.split('.')[0].split('_')[1] for x in files]
output = {}
for sid in station_ids:
csv_file = csv.reader(open('../datasets/bss/dublin/original/dublin.csv', "r"), delimiter=",")
for row in csv_file:
if sid == row[0]:
output[sid] = row[1]
return output
def simple_predict(station_id, int_time, int_date, int_day):
destination_directory = '../datasets/bss/dublin/simple_ml_models/'
scaler_destination_directory = copy.deepcopy(destination_directory) + 'scalers/'
model = tf.keras.models.load_model(destination_directory + 'station_' + str(station_id) + '.h5')
file = open(scaler_destination_directory + 'station_' + str(station_id) + '.pkl', "rb")
scaler = pickle.load(file)
file.close()
params = np.array([0, int_time, int_date, int_day])
params = params.reshape(1, -1)
params = scaler.transform(params)
params = np.array([params])
params = params.tolist()
params[0][0].pop(0)
params = np.array(params)
answer = model.predict(params)
full_row = concatenate((answer, params[0]), axis=1)
inv_row = scaler.inverse_transform(full_row)
return inv_row[0][0]
def full_predict(station_id, int_time, int_date, int_day, rain, temp, rhum):
destination_directory = '../datasets/bss/dublin/ml_models/'
scaler_destination_directory = copy.deepcopy(destination_directory) + 'scalers/'
model = tf.keras.models.load_model(destination_directory + 'station_' + str(station_id) + '.h5')
file = open(scaler_destination_directory + 'station_' + str(station_id) + '.pkl', "rb")
scaler = pickle.load(file)
file.close()
params = np.array([0, int_time, int_date, int_day, rain, temp, rhum])
params = params.reshape(1, -1)
params = scaler.transform(params)
params = np.array([params])
params = params.tolist()
params[0][0].pop(0)
params = np.array(params)
answer = model.predict(params)
full_row = concatenate((answer, params[0]), axis=1)
inv_row = scaler.inverse_transform(full_row)
return inv_row[0][0]
if __name__ == '__main__':
# full_predict(2, 24, 213, 4, 0, 14, 87)
# station_id, int_time, int_date, int_day, rain, temp, rhum
app.run(debug=True) | en | 0.768817 | Converts TIME field in the CSV to an integer representing what time of day it is (in number of 5min increments) from 0 to 287 eg - 00:00 -> 0 - 00:10 -> 2 - 02:20 -> 28 etc Converts TIME field to an integer representing the day of the year eg - 2019-02-10 -> 41 Converts TIME field to an integer representing the day of the week eg - 2019-02-10 -> 0 (Sunday) # full_predict(2, 24, 213, 4, 0, 14, 87) # station_id, int_time, int_date, int_day, rain, temp, rhum | 2.286674 | 2 |
selfdrive/car/volkswagen/carcontroller.py | juliandoyle/openpilot | 0 | 6618933 | <gh_stars>0
from cereal import car
from common.numpy_fast import clip, interp
from selfdrive.car import apply_std_steer_torque_limits
from selfdrive.car.volkswagen import volkswagencan
from selfdrive.car.volkswagen.values import PQ_CARS, DBC_FILES, CANBUS, NetworkLocation, MQB_LDW_MESSAGES, BUTTON_STATES, CarControllerParams as P
from opendbc.can.packer import CANPacker
VisualAlert = car.CarControl.HUDControl.VisualAlert
class CarController():
def __init__(self, dbc_name, CP, VM):
self.apply_steer_last = 0
# self.mobPreEnable = False
# self.mobEnabled = False
# self.haltenCounter = 0
self.hcaSameTorqueCount = 0
self.hcaEnabledFrameCount = 0
self.graButtonStatesToSend = None
self.graMsgSentCount = 0
self.graMsgStartFramePrev = 0
self.graMsgBusCounterPrev = 0
if CP.carFingerprint in PQ_CARS:
self.packer_pt = CANPacker(DBC_FILES.pq)
self.create_steering_control = volkswagencan.create_pq_steering_control
self.create_acc_buttons_control = volkswagencan.create_pq_acc_buttons_control
self.create_hud_control = volkswagencan.create_pq_hud_control
# self.create_gas_control = volkswagencan.create_pq_pedal_control
# self.create_braking_control = volkswagencan.create_pq_braking_control
# self.create_awv_control = volkswagencan.create_pq_awv_control
# self.create_bremse8_control = volkswagencan.create_pq_bremse8_control
self.ldw_step = P.PQ_LDW_STEP
else:
self.packer_pt = CANPacker(DBC_FILES.mqb)
self.create_steering_control = volkswagencan.create_mqb_steering_control
self.create_acc_buttons_control = volkswagencan.create_mqb_acc_buttons_control
self.create_hud_control = volkswagencan.create_mqb_hud_control
self.ldw_step = P.MQB_LDW_STEP
if CP.networkLocation == NetworkLocation.fwdCamera:
self.ext_can = CANBUS.pt
else:
self.ext_can = CANBUS.cam
self.steer_rate_limited = False
def update(self, enabled, CS, frame, ext_bus, actuators, visual_alert, left_lane_visible, right_lane_visible, left_lane_depart, right_lane_depart):
""" Controls thread """
can_sends = []
# **** Steering Controls ************************************************ #
if frame % P.HCA_STEP == 0:
# Logic to avoid HCA state 4 "refused":
# * Don't steer unless HCA is in state 3 "ready" or 5 "active"
# * Don't steer at standstill
# * Don't send > 3.00 Newton-meters torque
# * Don't send the same torque for > 6 seconds
# * Don't send uninterrupted steering for > 360 seconds
# One frame of HCA disabled is enough to reset the timer, without zeroing the
# torque value. Do that anytime we happen to have 0 torque, or failing that,
# when exceeding ~1/3 the 360 second timer.
if enabled and CS.out.vEgo > CS.CP.minSteerSpeed and not (CS.out.standstill or CS.out.steerError or CS.out.steerWarning):
new_steer = int(round(actuators.steer * P.STEER_MAX))
apply_steer = apply_std_steer_torque_limits(new_steer, self.apply_steer_last, CS.out.steeringTorque, P)
self.steer_rate_limited = new_steer != apply_steer
if apply_steer == 0:
hcaEnabled = False
self.hcaEnabledFrameCount = 0
else:
self.hcaEnabledFrameCount += 1
if self.hcaEnabledFrameCount >= 118 * (100 / P.HCA_STEP): # 118s
hcaEnabled = False
self.hcaEnabledFrameCount = 0
else:
hcaEnabled = True
if self.apply_steer_last == apply_steer:
self.hcaSameTorqueCount += 1
if self.hcaSameTorqueCount > 1.9 * (100 / P.HCA_STEP): # 1.9s
apply_steer -= (1, -1)[apply_steer < 0]
self.hcaSameTorqueCount = 0
else:
self.hcaSameTorqueCount = 0
else:
hcaEnabled = False
apply_steer = 0
self.apply_steer_last = apply_steer
idx = (frame / P.HCA_STEP) % 16
can_sends.append(self.create_steering_control(self.packer_pt, CANBUS.pt, apply_steer,
idx, hcaEnabled))
# can_sends.append(self.create_bremse8_control(self.packer_pt, CANBUS.cam, idx, CS.bremse8))
# **** Braking Controls ************************************************ #
# if(frame % P.MOB_STEP == 0) and CS.CP.enableGasInterceptor:
# mobEnabled = self.mobEnabled
# mobPreEnable = self.mobPreEnable
# # TODO make sure we use the full 8190 when calculating braking.
# apply_brake = int(round(interp(actuators.accel, P.BRAKE_LOOKUP_BP, P.BRAKE_LOOKUP_V)))
# stopping_wish = False
# if enabled:
# if apply_brake > 0:
# if not mobEnabled:
# mobEnabled = True
# apply_brake = 0
# elif not mobPreEnable:
# mobPreEnable = True
# apply_brake = 0
# elif apply_brake > 1199:
# apply_brake = 1200
# CS.brake_warning = True
# if CS.currentSpeed < 5.6:
# stopping_wish = True
# else:
# mobPreEnable = False
# mobEnabled = False
# if CS.Stillstand:
# self.haltenCounter = self.haltenCounter + 1
# if self.haltenCounter > 10:
# apply_brake = 0
# mobPreEnable = False
# mobEnabled = False
# else:
# self.haltenCounter = 0
# else:
# apply_brake = 0
# mobPreEnable = False
# mobEnabled = False
# idx = (frame / P.MOB_STEP) % 16
# self.mobPreEnable = mobPreEnable
# self.mobEnabled = mobEnabled
# can_sends.append(
# self.create_braking_control(self.packer_pt, CANBUS.br, apply_brake, idx, mobEnabled, mobPreEnable, stopping_wish))
# **** GAS Controls ***************************************************** #
# if (frame % P.GAS_STEP == 0) and CS.CP.enableGasInterceptor:
# apply_gas = 0
# if enabled:
# apply_gas = int(round(interp(actuators.accel, P.GAS_LOOKUP_BP, P.GAS_LOOKUP_V)))
# apply_gas = apply_gas + 3 * CS.out.aEgo
# can_sends.append(self.create_gas_control(self.packer_pt, CANBUS.cam, apply_gas, frame // 2))
# **** HUD Controls ***************************************************** #
if frame % self.ldw_step == 0:
hca_enabled = True if enabled and not CS.out.standstill else False
# FIXME: drive this down to the MQB/PQ specific create_hud_control functions
if visual_alert in [VisualAlert.steerRequired, VisualAlert.ldw]:
hud_alert = MQB_LDW_MESSAGES["laneAssistTakeOverSilent"]
else:
hud_alert = MQB_LDW_MESSAGES["none"]
can_sends.append(self.create_hud_control(self.packer_pt, CANBUS.pt, hca_enabled,
CS.out.steeringPressed, hud_alert, left_lane_visible,
right_lane_visible, CS.ldw_lane_warning_left,
CS.ldw_lane_warning_right, CS.ldw_side_dlc_tlc,
CS.ldw_dlc, CS.ldw_tlc, CS.out.standstill,
left_lane_depart, right_lane_depart))
# **** AWV Controls ***************************************************** #
# if (frame % P.AWV_STEP == 0) and CS.CP.enableGasInterceptor:
# green_led = 1 if enabled else 0
# orange_led = 1 if self.mobPreEnable and self.mobEnabled else 0
# halten = False
# if enabled:
# if CS.Stillstand:
# halten = True
# idx = (frame / P.MOB_STEP) % 16
# can_sends.append(self.create_awv_control(self.packer_pt, CANBUS.pt, idx, orange_led, green_led, halten, CS.mAWV))
# **** ACC Button Controls ********************************************** #
# FIXME: this entire section is in desperate need of refactoring
if frame > self.graMsgStartFramePrev + P.GRA_VBP_STEP:
if not enabled and CS.out.cruiseState.enabled:
# Cancel ACC if it's engaged with OP disengaged.
self.graButtonStatesToSend = BUTTON_STATES.copy()
self.graButtonStatesToSend["cancel"] = True
elif enabled and CS.out.standstill:
# Blip the Resume button if we're engaged at standstill.
# FIXME: This is a naive implementation, improve with visiond or radar input.
# A subset of MQBs like to "creep" too aggressively with this implementation.
self.graButtonStatesToSend = BUTTON_STATES.copy()
self.graButtonStatesToSend["resumeCruise"] = True
if CS.graMsgBusCounter != self.graMsgBusCounterPrev:
self.graMsgBusCounterPrev = CS.graMsgBusCounter
if self.graButtonStatesToSend is not None:
if self.graMsgSentCount == 0:
self.graMsgStartFramePrev = frame
idx = (CS.graMsgBusCounter + 1) % 16
# can_sends.append(self.create_acc_buttons_control(self.packer_pt, self.ext_can, self.graButtonStatesToSend, CS, idx))
self.graMsgSentCount += 1
if self.graMsgSentCount >= P.GRA_VBP_COUNT:
self.graButtonStatesToSend = None
self.graMsgSentCount = 0
return can_sends
| from cereal import car
from common.numpy_fast import clip, interp
from selfdrive.car import apply_std_steer_torque_limits
from selfdrive.car.volkswagen import volkswagencan
from selfdrive.car.volkswagen.values import PQ_CARS, DBC_FILES, CANBUS, NetworkLocation, MQB_LDW_MESSAGES, BUTTON_STATES, CarControllerParams as P
from opendbc.can.packer import CANPacker
VisualAlert = car.CarControl.HUDControl.VisualAlert
class CarController():
def __init__(self, dbc_name, CP, VM):
self.apply_steer_last = 0
# self.mobPreEnable = False
# self.mobEnabled = False
# self.haltenCounter = 0
self.hcaSameTorqueCount = 0
self.hcaEnabledFrameCount = 0
self.graButtonStatesToSend = None
self.graMsgSentCount = 0
self.graMsgStartFramePrev = 0
self.graMsgBusCounterPrev = 0
if CP.carFingerprint in PQ_CARS:
self.packer_pt = CANPacker(DBC_FILES.pq)
self.create_steering_control = volkswagencan.create_pq_steering_control
self.create_acc_buttons_control = volkswagencan.create_pq_acc_buttons_control
self.create_hud_control = volkswagencan.create_pq_hud_control
# self.create_gas_control = volkswagencan.create_pq_pedal_control
# self.create_braking_control = volkswagencan.create_pq_braking_control
# self.create_awv_control = volkswagencan.create_pq_awv_control
# self.create_bremse8_control = volkswagencan.create_pq_bremse8_control
self.ldw_step = P.PQ_LDW_STEP
else:
self.packer_pt = CANPacker(DBC_FILES.mqb)
self.create_steering_control = volkswagencan.create_mqb_steering_control
self.create_acc_buttons_control = volkswagencan.create_mqb_acc_buttons_control
self.create_hud_control = volkswagencan.create_mqb_hud_control
self.ldw_step = P.MQB_LDW_STEP
if CP.networkLocation == NetworkLocation.fwdCamera:
self.ext_can = CANBUS.pt
else:
self.ext_can = CANBUS.cam
self.steer_rate_limited = False
def update(self, enabled, CS, frame, ext_bus, actuators, visual_alert, left_lane_visible, right_lane_visible, left_lane_depart, right_lane_depart):
""" Controls thread """
can_sends = []
# **** Steering Controls ************************************************ #
if frame % P.HCA_STEP == 0:
# Logic to avoid HCA state 4 "refused":
# * Don't steer unless HCA is in state 3 "ready" or 5 "active"
# * Don't steer at standstill
# * Don't send > 3.00 Newton-meters torque
# * Don't send the same torque for > 6 seconds
# * Don't send uninterrupted steering for > 360 seconds
# One frame of HCA disabled is enough to reset the timer, without zeroing the
# torque value. Do that anytime we happen to have 0 torque, or failing that,
# when exceeding ~1/3 the 360 second timer.
if enabled and CS.out.vEgo > CS.CP.minSteerSpeed and not (CS.out.standstill or CS.out.steerError or CS.out.steerWarning):
new_steer = int(round(actuators.steer * P.STEER_MAX))
apply_steer = apply_std_steer_torque_limits(new_steer, self.apply_steer_last, CS.out.steeringTorque, P)
self.steer_rate_limited = new_steer != apply_steer
if apply_steer == 0:
hcaEnabled = False
self.hcaEnabledFrameCount = 0
else:
self.hcaEnabledFrameCount += 1
if self.hcaEnabledFrameCount >= 118 * (100 / P.HCA_STEP): # 118s
hcaEnabled = False
self.hcaEnabledFrameCount = 0
else:
hcaEnabled = True
if self.apply_steer_last == apply_steer:
self.hcaSameTorqueCount += 1
if self.hcaSameTorqueCount > 1.9 * (100 / P.HCA_STEP): # 1.9s
apply_steer -= (1, -1)[apply_steer < 0]
self.hcaSameTorqueCount = 0
else:
self.hcaSameTorqueCount = 0
else:
hcaEnabled = False
apply_steer = 0
self.apply_steer_last = apply_steer
idx = (frame / P.HCA_STEP) % 16
can_sends.append(self.create_steering_control(self.packer_pt, CANBUS.pt, apply_steer,
idx, hcaEnabled))
# can_sends.append(self.create_bremse8_control(self.packer_pt, CANBUS.cam, idx, CS.bremse8))
# **** Braking Controls ************************************************ #
# if(frame % P.MOB_STEP == 0) and CS.CP.enableGasInterceptor:
# mobEnabled = self.mobEnabled
# mobPreEnable = self.mobPreEnable
# # TODO make sure we use the full 8190 when calculating braking.
# apply_brake = int(round(interp(actuators.accel, P.BRAKE_LOOKUP_BP, P.BRAKE_LOOKUP_V)))
# stopping_wish = False
# if enabled:
# if apply_brake > 0:
# if not mobEnabled:
# mobEnabled = True
# apply_brake = 0
# elif not mobPreEnable:
# mobPreEnable = True
# apply_brake = 0
# elif apply_brake > 1199:
# apply_brake = 1200
# CS.brake_warning = True
# if CS.currentSpeed < 5.6:
# stopping_wish = True
# else:
# mobPreEnable = False
# mobEnabled = False
# if CS.Stillstand:
# self.haltenCounter = self.haltenCounter + 1
# if self.haltenCounter > 10:
# apply_brake = 0
# mobPreEnable = False
# mobEnabled = False
# else:
# self.haltenCounter = 0
# else:
# apply_brake = 0
# mobPreEnable = False
# mobEnabled = False
# idx = (frame / P.MOB_STEP) % 16
# self.mobPreEnable = mobPreEnable
# self.mobEnabled = mobEnabled
# can_sends.append(
# self.create_braking_control(self.packer_pt, CANBUS.br, apply_brake, idx, mobEnabled, mobPreEnable, stopping_wish))
# **** GAS Controls ***************************************************** #
# if (frame % P.GAS_STEP == 0) and CS.CP.enableGasInterceptor:
# apply_gas = 0
# if enabled:
# apply_gas = int(round(interp(actuators.accel, P.GAS_LOOKUP_BP, P.GAS_LOOKUP_V)))
# apply_gas = apply_gas + 3 * CS.out.aEgo
# can_sends.append(self.create_gas_control(self.packer_pt, CANBUS.cam, apply_gas, frame // 2))
# **** HUD Controls ***************************************************** #
if frame % self.ldw_step == 0:
hca_enabled = True if enabled and not CS.out.standstill else False
# FIXME: drive this down to the MQB/PQ specific create_hud_control functions
if visual_alert in [VisualAlert.steerRequired, VisualAlert.ldw]:
hud_alert = MQB_LDW_MESSAGES["laneAssistTakeOverSilent"]
else:
hud_alert = MQB_LDW_MESSAGES["none"]
can_sends.append(self.create_hud_control(self.packer_pt, CANBUS.pt, hca_enabled,
CS.out.steeringPressed, hud_alert, left_lane_visible,
right_lane_visible, CS.ldw_lane_warning_left,
CS.ldw_lane_warning_right, CS.ldw_side_dlc_tlc,
CS.ldw_dlc, CS.ldw_tlc, CS.out.standstill,
left_lane_depart, right_lane_depart))
# **** AWV Controls ***************************************************** #
# if (frame % P.AWV_STEP == 0) and CS.CP.enableGasInterceptor:
# green_led = 1 if enabled else 0
# orange_led = 1 if self.mobPreEnable and self.mobEnabled else 0
# halten = False
# if enabled:
# if CS.Stillstand:
# halten = True
# idx = (frame / P.MOB_STEP) % 16
# can_sends.append(self.create_awv_control(self.packer_pt, CANBUS.pt, idx, orange_led, green_led, halten, CS.mAWV))
# **** ACC Button Controls ********************************************** #
# FIXME: this entire section is in desperate need of refactoring
if frame > self.graMsgStartFramePrev + P.GRA_VBP_STEP:
if not enabled and CS.out.cruiseState.enabled:
# Cancel ACC if it's engaged with OP disengaged.
self.graButtonStatesToSend = BUTTON_STATES.copy()
self.graButtonStatesToSend["cancel"] = True
elif enabled and CS.out.standstill:
# Blip the Resume button if we're engaged at standstill.
# FIXME: This is a naive implementation, improve with visiond or radar input.
# A subset of MQBs like to "creep" too aggressively with this implementation.
self.graButtonStatesToSend = BUTTON_STATES.copy()
self.graButtonStatesToSend["resumeCruise"] = True
if CS.graMsgBusCounter != self.graMsgBusCounterPrev:
self.graMsgBusCounterPrev = CS.graMsgBusCounter
if self.graButtonStatesToSend is not None:
if self.graMsgSentCount == 0:
self.graMsgStartFramePrev = frame
idx = (CS.graMsgBusCounter + 1) % 16
# can_sends.append(self.create_acc_buttons_control(self.packer_pt, self.ext_can, self.graButtonStatesToSend, CS, idx))
self.graMsgSentCount += 1
if self.graMsgSentCount >= P.GRA_VBP_COUNT:
self.graButtonStatesToSend = None
self.graMsgSentCount = 0
return can_sends | en | 0.526696 | # self.mobPreEnable = False # self.mobEnabled = False # self.haltenCounter = 0 # self.create_gas_control = volkswagencan.create_pq_pedal_control # self.create_braking_control = volkswagencan.create_pq_braking_control # self.create_awv_control = volkswagencan.create_pq_awv_control # self.create_bremse8_control = volkswagencan.create_pq_bremse8_control Controls thread # **** Steering Controls ************************************************ # # Logic to avoid HCA state 4 "refused": # * Don't steer unless HCA is in state 3 "ready" or 5 "active" # * Don't steer at standstill # * Don't send > 3.00 Newton-meters torque # * Don't send the same torque for > 6 seconds # * Don't send uninterrupted steering for > 360 seconds # One frame of HCA disabled is enough to reset the timer, without zeroing the # torque value. Do that anytime we happen to have 0 torque, or failing that, # when exceeding ~1/3 the 360 second timer. # 118s # 1.9s # can_sends.append(self.create_bremse8_control(self.packer_pt, CANBUS.cam, idx, CS.bremse8)) # **** Braking Controls ************************************************ # # if(frame % P.MOB_STEP == 0) and CS.CP.enableGasInterceptor: # mobEnabled = self.mobEnabled # mobPreEnable = self.mobPreEnable # # TODO make sure we use the full 8190 when calculating braking. # apply_brake = int(round(interp(actuators.accel, P.BRAKE_LOOKUP_BP, P.BRAKE_LOOKUP_V))) # stopping_wish = False # if enabled: # if apply_brake > 0: # if not mobEnabled: # mobEnabled = True # apply_brake = 0 # elif not mobPreEnable: # mobPreEnable = True # apply_brake = 0 # elif apply_brake > 1199: # apply_brake = 1200 # CS.brake_warning = True # if CS.currentSpeed < 5.6: # stopping_wish = True # else: # mobPreEnable = False # mobEnabled = False # if CS.Stillstand: # self.haltenCounter = self.haltenCounter + 1 # if self.haltenCounter > 10: # apply_brake = 0 # mobPreEnable = False # mobEnabled = False # else: # self.haltenCounter = 0 # else: # apply_brake = 0 # mobPreEnable = False # mobEnabled = False # idx = (frame / P.MOB_STEP) % 16 # self.mobPreEnable = mobPreEnable # self.mobEnabled = mobEnabled # can_sends.append( # self.create_braking_control(self.packer_pt, CANBUS.br, apply_brake, idx, mobEnabled, mobPreEnable, stopping_wish)) # **** GAS Controls ***************************************************** # # if (frame % P.GAS_STEP == 0) and CS.CP.enableGasInterceptor: # apply_gas = 0 # if enabled: # apply_gas = int(round(interp(actuators.accel, P.GAS_LOOKUP_BP, P.GAS_LOOKUP_V))) # apply_gas = apply_gas + 3 * CS.out.aEgo # can_sends.append(self.create_gas_control(self.packer_pt, CANBUS.cam, apply_gas, frame // 2)) # **** HUD Controls ***************************************************** # # FIXME: drive this down to the MQB/PQ specific create_hud_control functions # **** AWV Controls ***************************************************** # # if (frame % P.AWV_STEP == 0) and CS.CP.enableGasInterceptor: # green_led = 1 if enabled else 0 # orange_led = 1 if self.mobPreEnable and self.mobEnabled else 0 # halten = False # if enabled: # if CS.Stillstand: # halten = True # idx = (frame / P.MOB_STEP) % 16 # can_sends.append(self.create_awv_control(self.packer_pt, CANBUS.pt, idx, orange_led, green_led, halten, CS.mAWV)) # **** ACC Button Controls ********************************************** # # FIXME: this entire section is in desperate need of refactoring # Cancel ACC if it's engaged with OP disengaged. # Blip the Resume button if we're engaged at standstill. # FIXME: This is a naive implementation, improve with visiond or radar input. # A subset of MQBs like to "creep" too aggressively with this implementation. # can_sends.append(self.create_acc_buttons_control(self.packer_pt, self.ext_can, self.graButtonStatesToSend, CS, idx)) | 2.112312 | 2 |
AppServer/lib/django-1.2/tests/regressiontests/inspectdb/tests.py | loftwah/appscale | 790 | 6618934 | <reponame>loftwah/appscale<filename>AppServer/lib/django-1.2/tests/regressiontests/inspectdb/tests.py<gh_stars>100-1000
from StringIO import StringIO
from django.core.management import call_command
from django.test import TestCase
class InspectDBTestCase(TestCase):
def test_attribute_name_not_python_keyword(self):
out = StringIO()
call_command('inspectdb', stdout=out)
error_message = "inspectdb generated an attribute name which is a python keyword"
self.assertFalse("from = models.ForeignKey(InspectdbPeople)" in out.getvalue(), msg=error_message)
self.assertTrue("from_field = models.ForeignKey(InspectdbPeople)" in out.getvalue())
out.close()
| from StringIO import StringIO
from django.core.management import call_command
from django.test import TestCase
class InspectDBTestCase(TestCase):
def test_attribute_name_not_python_keyword(self):
out = StringIO()
call_command('inspectdb', stdout=out)
error_message = "inspectdb generated an attribute name which is a python keyword"
self.assertFalse("from = models.ForeignKey(InspectdbPeople)" in out.getvalue(), msg=error_message)
self.assertTrue("from_field = models.ForeignKey(InspectdbPeople)" in out.getvalue())
out.close() | none | 1 | 2.346243 | 2 | |
authentication/module/service/authenticationService.py | williamducfer/eras | 1 | 6618935 | from calendar import timegm
from datetime import datetime
from jose import jwt, JWTError
from module import config
from module import db
from module.service.serviceException import ServiceException
from module.util.mongoUtil import mongo_result_wrapper
def check_user(email, keep_password=False, keep_temporary_token=False):
if not email:
raise ServiceException('INVALID USER EMAIL')
user = get_user(email, keep_password, keep_temporary_token)
if not user:
raise ServiceException('INVALID USER EMAIL')
return user
def insert_user(email, first_name, last_name, role):
if not email:
raise ServiceException('Email is required')
user = get_user(email)
if user:
raise ServiceException('User already exists')
now = timegm(datetime.utcnow().utctimetuple())
payload = {
'iat': now,
'exp': now + config['JWT_DELTA_LONG_EXPIRATION'],
'sub': email,
'sub_role': role,
'sub_firstName': first_name,
'sub_lastName': last_name
}
token = jwt.encode(payload, config['JWT_SECRET_KEY'], algorithm=config['JWT_ALGORITHM'])
db.users.insert_one({
'email': email,
'firstName': first_name,
'lastName': last_name,
'role': role,
'temporaryToken': token
})
return token
def update_user_password(email, key, new_password, key_is_token=False):
user = check_user(email, True, True)
if key_is_token:
try:
if 'temporaryToken' in user and user['temporaryToken'] == key:
verify_token(email, key)
else:
raise ServiceException('Invalid token')
except ServiceException:
raise ServiceException('Invalid token')
elif config['CIPHER'].decrypt(user['password']) != key:
raise ServiceException('Invalid old password')
db.users.update_one({
'email': email
}, {
'$set': {
'password': config['CIPHER'].encrypt(new_password),
'lastPasswordUpdate': datetime.utcnow()
},
'$unset': {
'temporaryToken': 1
}
})
def get_temporary_token(email):
user = check_user(email)
now = timegm(datetime.utcnow().utctimetuple())
payload = {
'iat': now,
'exp': now + config['JWT_DELTA_LONG_EXPIRATION'],
'sub': email,
'sub_role': user['role'],
'sub_firstName': user['firstName'],
'sub_lastName': user['lastName']
}
token = jwt.encode(payload, config['JWT_SECRET_KEY'], algorithm=config['JWT_ALGORITHM'])
db.users.update_one({
'email': email
}, {
'$set': {
'temporaryToken': token
}
})
return token, user
def update_user(email, first_name, last_name, role):
check_user(email)
db.users.update_one({
'email': email
}, {
'$set': {
'firstName': first_name,
'lastName': last_name,
'role': role
}
})
def remove_user(email):
check_user(email)
db.users.delete_one({
'email': email
})
@mongo_result_wrapper()
def get_users():
return db.users.aggregate([
{'$match': {}},
{'$project': {
'_id': 0,
'email': 1,
'firstName': 1,
'lastName': 1,
'role': 1
}}
])
@mongo_result_wrapper(is_single_result=True)
def get_user(email, keep_password=False, keep_temporary_token=False):
project = {
'_id': 0,
'email': 1,
'firstName': 1,
'lastName': 1,
'role': 1
}
if keep_password:
project['password'] = <PASSWORD>'
if keep_temporary_token:
project['temporaryToken'] = '$temporaryToken'
return db.users.aggregate([
{'$match': {'email': email}},
{'$project': project}
])
def authenticate(email, password):
user = check_user(email, True)
if config['CIPHER'].decrypt(user['password']) == password:
now = timegm(datetime.utcnow().utctimetuple())
payload = {
'iat': now,
'exp': now + config['JWT_DELTA_EXPIRATION'],
'sub': user['email'],
'sub_role': user['role'],
'sub_firstName': user['firstName'],
'sub_lastName': user['lastName']
}
token = jwt.encode(payload, config['JWT_SECRET_KEY'], algorithm=config['JWT_ALGORITHM'])
db.users.update_one({
'email': email
}, {
'$set': {
'lastAuthentication': datetime.utcnow()
}
})
return {
'email': user['email'],
'role': user['role'],
'firstName': user['firstName'],
'lastName': user['lastName'],
'token': token
}
else:
raise ServiceException('Invalid password')
def verify_token(email, token):
check_user(email)
try:
user = jwt.decode(token, config['JWT_SECRET_KEY'], algorithms=config['JWT_ALGORITHM'], subject=email)
return {
'email': user['sub'],
'role': user['sub_role'],
'firstName': user['sub_firstName'],
'lastName': user['sub_lastName'],
'token': token
}
except JWTError:
raise ServiceException('Invalid token')
def refresh_token(email, token):
user = check_user(email)
try:
verify_token(email, token)
except ServiceException:
raise ServiceException('Invalid token')
now = timegm(datetime.utcnow().utctimetuple()) # now in seconds
payload = {
'iat': now,
'exp': now + config['JWT_DELTA_EXPIRATION'],
'sub': user['email'],
'sub_role': user['role'],
'sub_firstName': user['firstName'],
'sub_lastName': user['lastName']
}
token = jwt.encode(payload, config['JWT_SECRET_KEY'], algorithm=config['JWT_ALGORITHM'])
return {
'email': user['email'],
'role': user['role'],
'firstName': user['firstName'],
'lastName': user['lastName'],
'token': token
}
| from calendar import timegm
from datetime import datetime
from jose import jwt, JWTError
from module import config
from module import db
from module.service.serviceException import ServiceException
from module.util.mongoUtil import mongo_result_wrapper
def check_user(email, keep_password=False, keep_temporary_token=False):
if not email:
raise ServiceException('INVALID USER EMAIL')
user = get_user(email, keep_password, keep_temporary_token)
if not user:
raise ServiceException('INVALID USER EMAIL')
return user
def insert_user(email, first_name, last_name, role):
if not email:
raise ServiceException('Email is required')
user = get_user(email)
if user:
raise ServiceException('User already exists')
now = timegm(datetime.utcnow().utctimetuple())
payload = {
'iat': now,
'exp': now + config['JWT_DELTA_LONG_EXPIRATION'],
'sub': email,
'sub_role': role,
'sub_firstName': first_name,
'sub_lastName': last_name
}
token = jwt.encode(payload, config['JWT_SECRET_KEY'], algorithm=config['JWT_ALGORITHM'])
db.users.insert_one({
'email': email,
'firstName': first_name,
'lastName': last_name,
'role': role,
'temporaryToken': token
})
return token
def update_user_password(email, key, new_password, key_is_token=False):
user = check_user(email, True, True)
if key_is_token:
try:
if 'temporaryToken' in user and user['temporaryToken'] == key:
verify_token(email, key)
else:
raise ServiceException('Invalid token')
except ServiceException:
raise ServiceException('Invalid token')
elif config['CIPHER'].decrypt(user['password']) != key:
raise ServiceException('Invalid old password')
db.users.update_one({
'email': email
}, {
'$set': {
'password': config['CIPHER'].encrypt(new_password),
'lastPasswordUpdate': datetime.utcnow()
},
'$unset': {
'temporaryToken': 1
}
})
def get_temporary_token(email):
user = check_user(email)
now = timegm(datetime.utcnow().utctimetuple())
payload = {
'iat': now,
'exp': now + config['JWT_DELTA_LONG_EXPIRATION'],
'sub': email,
'sub_role': user['role'],
'sub_firstName': user['firstName'],
'sub_lastName': user['lastName']
}
token = jwt.encode(payload, config['JWT_SECRET_KEY'], algorithm=config['JWT_ALGORITHM'])
db.users.update_one({
'email': email
}, {
'$set': {
'temporaryToken': token
}
})
return token, user
def update_user(email, first_name, last_name, role):
check_user(email)
db.users.update_one({
'email': email
}, {
'$set': {
'firstName': first_name,
'lastName': last_name,
'role': role
}
})
def remove_user(email):
check_user(email)
db.users.delete_one({
'email': email
})
@mongo_result_wrapper()
def get_users():
return db.users.aggregate([
{'$match': {}},
{'$project': {
'_id': 0,
'email': 1,
'firstName': 1,
'lastName': 1,
'role': 1
}}
])
@mongo_result_wrapper(is_single_result=True)
def get_user(email, keep_password=False, keep_temporary_token=False):
project = {
'_id': 0,
'email': 1,
'firstName': 1,
'lastName': 1,
'role': 1
}
if keep_password:
project['password'] = <PASSWORD>'
if keep_temporary_token:
project['temporaryToken'] = '$temporaryToken'
return db.users.aggregate([
{'$match': {'email': email}},
{'$project': project}
])
def authenticate(email, password):
user = check_user(email, True)
if config['CIPHER'].decrypt(user['password']) == password:
now = timegm(datetime.utcnow().utctimetuple())
payload = {
'iat': now,
'exp': now + config['JWT_DELTA_EXPIRATION'],
'sub': user['email'],
'sub_role': user['role'],
'sub_firstName': user['firstName'],
'sub_lastName': user['lastName']
}
token = jwt.encode(payload, config['JWT_SECRET_KEY'], algorithm=config['JWT_ALGORITHM'])
db.users.update_one({
'email': email
}, {
'$set': {
'lastAuthentication': datetime.utcnow()
}
})
return {
'email': user['email'],
'role': user['role'],
'firstName': user['firstName'],
'lastName': user['lastName'],
'token': token
}
else:
raise ServiceException('Invalid password')
def verify_token(email, token):
check_user(email)
try:
user = jwt.decode(token, config['JWT_SECRET_KEY'], algorithms=config['JWT_ALGORITHM'], subject=email)
return {
'email': user['sub'],
'role': user['sub_role'],
'firstName': user['sub_firstName'],
'lastName': user['sub_lastName'],
'token': token
}
except JWTError:
raise ServiceException('Invalid token')
def refresh_token(email, token):
user = check_user(email)
try:
verify_token(email, token)
except ServiceException:
raise ServiceException('Invalid token')
now = timegm(datetime.utcnow().utctimetuple()) # now in seconds
payload = {
'iat': now,
'exp': now + config['JWT_DELTA_EXPIRATION'],
'sub': user['email'],
'sub_role': user['role'],
'sub_firstName': user['firstName'],
'sub_lastName': user['lastName']
}
token = jwt.encode(payload, config['JWT_SECRET_KEY'], algorithm=config['JWT_ALGORITHM'])
return {
'email': user['email'],
'role': user['role'],
'firstName': user['firstName'],
'lastName': user['lastName'],
'token': token
}
| en | 0.886991 | # now in seconds | 2.248111 | 2 |
backend/app/paste/schemas/__init__.py | d4sein/Pastebin | 3 | 6618936 | from app.paste.schemas.paste_schema import PasteSchema
| from app.paste.schemas.paste_schema import PasteSchema
| none | 1 | 1.112633 | 1 | |
python/collection/stack.py | tachyonsoftware/algorithms | 17 | 6618937 | class Stack(object):
def __init__(self):
self.stack = []
def push(self, val):
self.stack.append(val)
def pop(self):
if len(self) <= 0:
raise IndexError("Pop from empty stack")
return self.stack.pop()
def __len__(self):
return len(self.stack)
def is_empty(self):
return not self.stack
def peek(self):
if len(self) <= 0:
raise IndexError("Peek from empty stack")
return self.stack[-1]
| class Stack(object):
def __init__(self):
self.stack = []
def push(self, val):
self.stack.append(val)
def pop(self):
if len(self) <= 0:
raise IndexError("Pop from empty stack")
return self.stack.pop()
def __len__(self):
return len(self.stack)
def is_empty(self):
return not self.stack
def peek(self):
if len(self) <= 0:
raise IndexError("Peek from empty stack")
return self.stack[-1]
| none | 1 | 3.960711 | 4 | |
apps/home/models.py | Prakshal-Jain/CodeAura | 0 | 6618938 | <filename>apps/home/models.py<gh_stars>0
from django.db import models
from datetime import date
from django import forms
from django.conf import settings
from django.contrib.auth.models import (
AbstractBaseUser,
BaseUserManager,
)
from django.utils import timezone
from django.core.exceptions import ValidationError
# TODO: add image deletion after an update or delete of a model
# Create your models here.
class Team(models.Model):
first_name = models.CharField("First name", max_length=30)
last_name = models.CharField("Last name", max_length=30)
profile_image = models.ImageField(null=False, blank=True, upload_to="Team_profile_media")
comments = models.TextField("What do you think about CodeAura?", max_length=200)
contribution = models.CharField("Please enter your contributions.", max_length=100, default="Contributor")
email = models.EmailField("Email", default="<EMAIL>")
join_date = models.DateTimeField("Date joined", default=timezone.now)
class User(AbstractBaseUser):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
email = models.EmailField("Email Address", unique=True)
username = models.CharField(max_length=100)
is_staff = models.BooleanField(
"is staff",
default=False,
help_text="Admin site access",
)
is_active = models.BooleanField(
"User active",
default=True,
null=True,
help_text="if a user is active."
)
date_joined = models.DateTimeField("Date joined", default=timezone.now)
REQUIRED_FIELDS = ("first_name", "last_name", "username")
class Meta:
swappable = "AUTH_USER_MODEL"
def __str__(self):
return self.username
def clean(self):
for required_field in self.REQUIRED_FIELDS:
if getattr(self, required_field) is None:
raise ValidationError(f"Field '{required_field}' is missing.")
class UserProfile(models.Model):
user = models.OneToOneField(
settings.AUTH_USER_MODEL, models.CASCADE, related_name="profile"
)
display_picture = models.ImageField()
date_of_birth = models.DateField()
REQUIRED_FIELDS = ("date_of_birth",)
def clean(self):
for required_field in self.REQUIRED_FIELDS:
if getattr(self, required_field) is None:
raise ValidationError(f"Field '{required_field}' is missing.")
| <filename>apps/home/models.py<gh_stars>0
from django.db import models
from datetime import date
from django import forms
from django.conf import settings
from django.contrib.auth.models import (
AbstractBaseUser,
BaseUserManager,
)
from django.utils import timezone
from django.core.exceptions import ValidationError
# TODO: add image deletion after an update or delete of a model
# Create your models here.
class Team(models.Model):
first_name = models.CharField("First name", max_length=30)
last_name = models.CharField("Last name", max_length=30)
profile_image = models.ImageField(null=False, blank=True, upload_to="Team_profile_media")
comments = models.TextField("What do you think about CodeAura?", max_length=200)
contribution = models.CharField("Please enter your contributions.", max_length=100, default="Contributor")
email = models.EmailField("Email", default="<EMAIL>")
join_date = models.DateTimeField("Date joined", default=timezone.now)
class User(AbstractBaseUser):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
email = models.EmailField("Email Address", unique=True)
username = models.CharField(max_length=100)
is_staff = models.BooleanField(
"is staff",
default=False,
help_text="Admin site access",
)
is_active = models.BooleanField(
"User active",
default=True,
null=True,
help_text="if a user is active."
)
date_joined = models.DateTimeField("Date joined", default=timezone.now)
REQUIRED_FIELDS = ("first_name", "last_name", "username")
class Meta:
swappable = "AUTH_USER_MODEL"
def __str__(self):
return self.username
def clean(self):
for required_field in self.REQUIRED_FIELDS:
if getattr(self, required_field) is None:
raise ValidationError(f"Field '{required_field}' is missing.")
class UserProfile(models.Model):
user = models.OneToOneField(
settings.AUTH_USER_MODEL, models.CASCADE, related_name="profile"
)
display_picture = models.ImageField()
date_of_birth = models.DateField()
REQUIRED_FIELDS = ("date_of_birth",)
def clean(self):
for required_field in self.REQUIRED_FIELDS:
if getattr(self, required_field) is None:
raise ValidationError(f"Field '{required_field}' is missing.")
| en | 0.933816 | # TODO: add image deletion after an update or delete of a model # Create your models here. | 2.189582 | 2 |
submissions/abc001/c.py | m-star18/atcoder | 1 | 6618939 | import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)
deg, dis = map(int, readline().split())
h = ['NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW', 'N']
f_l = [0, 3, 16, 34, 55, 80, 108, 139, 172, 208, 245, 285, 327]
f_h = [x - 1 for x in f_l[1:]] + [10 ** 18]
deg /= 10
dis = (dis + 3) // 6
deg -= 11.25
deg //= 22.5
if deg < 0 or deg >= 15:
h_ans = h[-1]
else:
h_ans = h[int(deg)]
f_ans = 0
for i, (l, r) in enumerate(zip(f_l, f_h)):
if l <= dis <= r:
f_ans = i
if f_ans == 0:
h_ans = 'C'
print(h_ans, f_ans)
| import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)
deg, dis = map(int, readline().split())
h = ['NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW', 'N']
f_l = [0, 3, 16, 34, 55, 80, 108, 139, 172, 208, 245, 285, 327]
f_h = [x - 1 for x in f_l[1:]] + [10 ** 18]
deg /= 10
dis = (dis + 3) // 6
deg -= 11.25
deg //= 22.5
if deg < 0 or deg >= 15:
h_ans = h[-1]
else:
h_ans = h[int(deg)]
f_ans = 0
for i, (l, r) in enumerate(zip(f_l, f_h)):
if l <= dis <= r:
f_ans = i
if f_ans == 0:
h_ans = 'C'
print(h_ans, f_ans)
| none | 1 | 2.568397 | 3 | |
util_scripts/clusterize_frontend.py | ishine/pase | 428 | 6618940 | <reponame>ishine/pase<filename>util_scripts/clusterize_frontend.py
from sklearn.cluster import KMeans
from pase.models.frontend import wf_builder
from pase.dataset import PairWavDataset, DictCollater
from torchvision.transforms import Compose
from pase.transforms import *
from torch.utils.data import DataLoader
import numpy as np
import argparse
import timeit
import pickle
import os
import json
def cluster(opts):
CUDA = True if torch.cuda.is_available() else False
device = 'cuda' if CUDA else 'cpu'
num_devices = 1
np.random.seed(opts.seed)
random.seed(opts.seed)
torch.manual_seed(opts.seed)
if CUDA:
torch.cuda.manual_seed_all(opts.seed)
num_devices = torch.cuda.device_count()
print('[*] Using CUDA {} devices'.format(num_devices))
else:
print('[!] Using CPU')
fe = wf_builder(opts.fe_cfg)
if opts.fe_ckpt is not None:
fe.load_pretrained(opts.fe_ckpt, load_last=True, verbose=True)
else:
print('WARNING: No pretrained ckpt loaded for FE! Random clustering?')
fe.to(device)
fe.eval()
trans = Compose([ToTensor(),
SingleChunkWav(opts.chunk_size, random_scale=False)])
# Build Dataset(s) and DataLoader(s)
dset = PairWavDataset(opts.data_root, opts.data_cfg, 'train',
transform=trans)
dloader = DataLoader(dset, batch_size=opts.batch_size,
shuffle=True, collate_fn=DictCollater(),
num_workers=opts.num_workers)
# acumulate train chunks and do clustering on them,
# with each chunk containing several frames
X = []
timings = []
N = opts.num_samples // opts.batch_size
beg_t = timeit.default_timer()
for bidx in range(1, N + 1, 1):
batch = next(dloader.__iter__())
chunk = batch['chunk']
y = fe(chunk.to(device)).mean(dim=2)
X.append(y.view(-1, y.size(-1)).cpu().data.numpy())
end_t = timeit.default_timer()
timings.append(end_t - beg_t)
beg_t = timeit.default_timer()
if bidx % opts.log_freq == 0 or bidx >= N:
print('Forwarded batch {:4d}/{:4d}, btime: {:.2f} s, '
'mbtime: {:.2f} s'.format(bidx, N, timings[-1],
np.mean(timings)),
end='\r')
print()
X = np.concatenate(X, axis=0)
print('Total X shape: ', X.shape)
print('Running KMeans...')
beg_t = timeit.default_timer()
kmeans = KMeans(n_clusters=opts.k_clusters, n_jobs=opts.n_jobs,
verbose=0).fit(X)
end_t = timeit.default_timer()
print('Clusterized in {:.2f} s'.format(end_t - beg_t))
print('Saving KMeans...')
with open(os.path.join(opts.save_path, 'kmeans.pkl'), 'wb') as f:
pickle.dump(kmeans, f)
print('Finished program')
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--data_cfg', type=str,
default='data/librispeech_data.cfg')
parser.add_argument('--data_root', type=str,
default='data/LibriSpeech/Librispeech_spkid_sel')
parser.add_argument('--fe_cfg', type=str, default=None)
parser.add_argument('--fe_ckpt', type=str, default=None)
parser.add_argument('--chunk_size', type=int, default=16000)
parser.add_argument('--num_samples', type=int, default=100000)
parser.add_argument('--num_workers', type=int, default=1)
parser.add_argument('--n_jobs', type=int, default=-1)
parser.add_argument('--seed', type=int, default=1)
parser.add_argument('--batch_size', type=int, default=200)
parser.add_argument('--log_freq', type=int, default=15)
parser.add_argument('--k_clusters', type=int, default=128,
help='Number of clusters (Def: 128).')
parser.add_argument('--save_path', type=str, default='kmeans_FE')
opts = parser.parse_args()
if not os.path.exists(opts.save_path):
os.makedirs(opts.save_path)
with open(os.path.join(opts.save_path, 'cluster.opts'), 'w') as opts_f:
opts_f.write(json.dumps(vars(opts), indent=2))
cluster(opts)
| from sklearn.cluster import KMeans
from pase.models.frontend import wf_builder
from pase.dataset import PairWavDataset, DictCollater
from torchvision.transforms import Compose
from pase.transforms import *
from torch.utils.data import DataLoader
import numpy as np
import argparse
import timeit
import pickle
import os
import json
def cluster(opts):
CUDA = True if torch.cuda.is_available() else False
device = 'cuda' if CUDA else 'cpu'
num_devices = 1
np.random.seed(opts.seed)
random.seed(opts.seed)
torch.manual_seed(opts.seed)
if CUDA:
torch.cuda.manual_seed_all(opts.seed)
num_devices = torch.cuda.device_count()
print('[*] Using CUDA {} devices'.format(num_devices))
else:
print('[!] Using CPU')
fe = wf_builder(opts.fe_cfg)
if opts.fe_ckpt is not None:
fe.load_pretrained(opts.fe_ckpt, load_last=True, verbose=True)
else:
print('WARNING: No pretrained ckpt loaded for FE! Random clustering?')
fe.to(device)
fe.eval()
trans = Compose([ToTensor(),
SingleChunkWav(opts.chunk_size, random_scale=False)])
# Build Dataset(s) and DataLoader(s)
dset = PairWavDataset(opts.data_root, opts.data_cfg, 'train',
transform=trans)
dloader = DataLoader(dset, batch_size=opts.batch_size,
shuffle=True, collate_fn=DictCollater(),
num_workers=opts.num_workers)
# acumulate train chunks and do clustering on them,
# with each chunk containing several frames
X = []
timings = []
N = opts.num_samples // opts.batch_size
beg_t = timeit.default_timer()
for bidx in range(1, N + 1, 1):
batch = next(dloader.__iter__())
chunk = batch['chunk']
y = fe(chunk.to(device)).mean(dim=2)
X.append(y.view(-1, y.size(-1)).cpu().data.numpy())
end_t = timeit.default_timer()
timings.append(end_t - beg_t)
beg_t = timeit.default_timer()
if bidx % opts.log_freq == 0 or bidx >= N:
print('Forwarded batch {:4d}/{:4d}, btime: {:.2f} s, '
'mbtime: {:.2f} s'.format(bidx, N, timings[-1],
np.mean(timings)),
end='\r')
print()
X = np.concatenate(X, axis=0)
print('Total X shape: ', X.shape)
print('Running KMeans...')
beg_t = timeit.default_timer()
kmeans = KMeans(n_clusters=opts.k_clusters, n_jobs=opts.n_jobs,
verbose=0).fit(X)
end_t = timeit.default_timer()
print('Clusterized in {:.2f} s'.format(end_t - beg_t))
print('Saving KMeans...')
with open(os.path.join(opts.save_path, 'kmeans.pkl'), 'wb') as f:
pickle.dump(kmeans, f)
print('Finished program')
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--data_cfg', type=str,
default='data/librispeech_data.cfg')
parser.add_argument('--data_root', type=str,
default='data/LibriSpeech/Librispeech_spkid_sel')
parser.add_argument('--fe_cfg', type=str, default=None)
parser.add_argument('--fe_ckpt', type=str, default=None)
parser.add_argument('--chunk_size', type=int, default=16000)
parser.add_argument('--num_samples', type=int, default=100000)
parser.add_argument('--num_workers', type=int, default=1)
parser.add_argument('--n_jobs', type=int, default=-1)
parser.add_argument('--seed', type=int, default=1)
parser.add_argument('--batch_size', type=int, default=200)
parser.add_argument('--log_freq', type=int, default=15)
parser.add_argument('--k_clusters', type=int, default=128,
help='Number of clusters (Def: 128).')
parser.add_argument('--save_path', type=str, default='kmeans_FE')
opts = parser.parse_args()
if not os.path.exists(opts.save_path):
os.makedirs(opts.save_path)
with open(os.path.join(opts.save_path, 'cluster.opts'), 'w') as opts_f:
opts_f.write(json.dumps(vars(opts), indent=2))
cluster(opts) | en | 0.807231 | # Build Dataset(s) and DataLoader(s) # acumulate train chunks and do clustering on them, # with each chunk containing several frames | 2.046058 | 2 |
cadnano/views/propertyview/propertyeditorwidget.py | sherwoodyao/cadnano2.5 | 69 | 6618941 | # -*- coding: utf-8 -*-
"""
Attributes:
COLOR_PATTERN (regex): Description
"""
import re
from typing import (
List,
Set
)
from PyQt5.QtCore import (
Qt,
QRect,
QModelIndex
)
from PyQt5.QtGui import (
QFont,
QPalette,
QPainter
)
from PyQt5.QtWidgets import (
QTreeWidget,
QHeaderView,
QStyledItemDelegate,
QStyleOptionButton,
QStyleOptionViewItem,
QStyle,
QCommonStyle,
QWidget,
QUndoStack
)
from cadnano.objectinstance import ObjectInstance
from cadnano.proxies.cnenum import (
ItemEnum,
ViewReceiveEnum
)
from cadnano.gui.palette import getBrushObj
from cadnano.controllers import ViewRootController
from cadnano.views.pathview import pathstyles as styles
from cadnano.views.outlinerview.cnoutlineritem import CNOutlinerItem
from .oligoitem import OligoSetItem
from .nucleicacidpartitem import NucleicAcidPartSetItem
from .virtualhelixitem import VirtualHelixSetItem
from .cnpropertyitem import CNPropertyItem
from cadnano.cntypes import (
PartT,
DocT,
WindowT
)
COLOR_PATTERN = re.compile("#[0-9a-f].....")
_FONT = QFont(styles.THE_FONT, 12)
_QCOMMONSTYLE = QCommonStyle()
class PropertyEditorWidget(QTreeWidget):
"""
PropertyEditorWidget enables direct editing attributes of an
item that is selected in the Outliner.
"""
view_type = ViewReceiveEnum.PROPERTY
def __init__(self, parent: QWidget = None):
"""Summary
Args:
parent (None, optional): Description
"""
super(PropertyEditorWidget, self).__init__(parent)
self._outline_view_obj_set = set()
self._outline_view_obj_list = []
self.are_signals_on = True
self.setAttribute(Qt.WA_MacShowFocusRect, 0) # no mac focus halo
# end def
def undoStack(self) -> QUndoStack:
return self._document.undoStack()
# end def
def configure(self, window: WindowT, document: DocT):
"""
Args:
window: Description
document: Description
"""
self._window = window
self._document = document
self._controller = ViewRootController(self, document)
self._root = self.invisibleRootItem()
# Appearance
self.setFont(_FONT)
# Columns
self.setColumnCount(2)
self.setIndentation(14)
# Header
self.setHeaderLabels(["Property", "Value"])
h = self.header()
h.resizeSection(0, 200)
h.resizeSection(1, 100)
h.setSectionResizeMode(QHeaderView.Interactive)
# h.setStretchLastSection(False)
custom_delegate = CustomStyleItemDelegate(self)
self.setItemDelegate(custom_delegate)
self.model().dataChanged.connect(self.dataChangedSlot)
self.hide()
# Add some dummy items
# p1 = self.addDummyRow("sequence", "ATCGACTGATCG")
# p2 = self.addDummyRow("circular", True)
# end def
# def addDummyRow(self, property_name, value, parent_QTreeWidgetItem=None):
# if parent_QTreeWidgetItem is None:
# parent_QTreeWidgetItem = self.invisibleRootItem()
# tw_item = QTreeWidgetItem(parent_QTreeWidgetItem)
# tw_item.setData(0, Qt.EditRole, property_name)
# tw_item.setData(1, Qt.EditRole, value)
# tw_item.setFlags(tw_item.flags() | Qt.ItemIsEditable)
# return tw_item
# end def
### SIGNALS ###
### SLOTS ###
def outlinerItemSelectionChanged(self):
"""
Raises:
NotImplementedError: Description
"""
o = self._window.outliner_widget
for child in self.children():
if isinstance(child, (CNPropertyItem)):
child.disconnectSignals()
selected_items = o.selectedItems()
self.clear() # remove pre-existing items
self._outline_view_obj_set.clear()
self._outline_view_obj_list = []
# print("prop multiple selected:", len(selected_items))
# if len(selected_items):
# print(selected_items[0])
# get the selected item
item_types = set([item.itemType() for item in selected_items])
num_types = len(item_types)
if num_types != 1: # assume no mixed types for now
return
item_type = item_types.pop()
outline_view_obj_list = [item.outlineViewObj() for item in selected_items if item.isSelected()]
'''Workaround as items in QTreeWidget.selectedItems() may be not
actually selected
'''
if len(outline_view_obj_list) == 0:
# print("outlinerItemSelectionChanged returning2")
return
self._outline_view_obj_set = set(outline_view_obj_list)
self._outline_view_obj_list = outline_view_obj_list
# special case for parts since there is currently no part filter
if item_type is ItemEnum.NUCLEICACID:
pe_item = NucleicAcidPartSetItem(parent=self)
self.show()
return
item = selected_items[0]
if item.FILTER_NAME not in self._document.filter_set:
print(item.FILTER_NAME, "not in self._document.filter_set")
return
if item_type is ItemEnum.OLIGO:
pe_item = OligoSetItem(parent=self)
self.show()
elif item_type is ItemEnum.VIRTUALHELIX:
pe_item = VirtualHelixSetItem(parent=self)
self.show()
else:
raise NotImplementedError
# end def
def partAddedSlot(self, sender: PartT, model_part_instance: ObjectInstance):
"""
Args:
sender: Model object that emitted the signal.
model_part_instance (ObjectInstance): The model part
"""
# end def
def documentChangeViewSignalingSlot(self, view_types: int):
self.are_signals_on = True if view_types & self.view_type else False
# end def
def clearSelectionsSlot(self, document: DocT):
"""
Args:
doc: Description
"""
# end def
def dataChangedSlot(self, top_left: QModelIndex, bot_right: QModelIndex):
"""docstring for propertyChangedSlot
Args:
top_left: Description
bot_right: Description
"""
c_i = self.currentItem()
if c_i is None:
return
if c_i == self.itemFromIndex(top_left):
c_i.updateCNModel()
# call this to prevent UNDO calls propagating through the Widget first
self.outlinerItemSelectionChanged()
# end def
def selectedChangedSlot(self, item_dict: dict):
"""
Args:
item_dict: Description
"""
# end def
def selectionFilterChangedSlot(self, filter_name_set: Set[str]):
"""
Args:
filter_name_set: Description
"""
pass
# end def
def preXoverFilterChangedSlot(self, filter_name: str):
"""
Args:
filter_name: Description
"""
pass
# end def
def resetRootItemSlot(self, document: DocT):
"""
Args:
document: Description
"""
self.clear()
# end def
### ACCESSORS ###
def window(self) -> WindowT:
"""
Returns:
model :class:`CNMainWindow`
"""
return self._window
# end def
def outlineViewObjSet(self) -> Set[CNOutlinerItem]:
return self._outline_view_obj_set
# end def
def outlineViewObjList(self) -> List[CNOutlinerItem]:
return self._outline_view_obj_list
# end def
### METHODS ###
def resetDocumentAndController(self, document: DocT):
"""
Args:
document: model :class:`Document`
"""
self._document = document
self._controller = ViewRootController(self, document)
# end def
# end class PropertyEditorWidget
class CustomStyleItemDelegate(QStyledItemDelegate):
"""Summary
"""
def createEditor(self, parent_qw: QWidget,
option: QStyleOptionViewItem,
model_index: QModelIndex) -> QWidget:
"""
Args:
parent_qw: Description
option: Description
model_index: Description
Returns:
the widget used to edit the item specified by index for editing
"""
column = model_index.column()
treewidgetitem = self.parent().itemFromIndex(model_index)
if column == 0: # Property Name
return None
elif column == 1:
editor = treewidgetitem.configureEditor(parent_qw, option, model_index)
return editor
else:
return QStyledItemDelegate.createEditor(self,
parent_qw,
option, model_index)
# end def
def updateEditorGeometry(self, editor: QWidget,
option: QStyleOptionViewItem,
model_index: QModelIndex):
"""
Args:
editor: Description
option: Description
model_index: Description
"""
column = model_index.column()
if column == 0:
editor.setGeometry(option.rect)
elif column == 1:
value = model_index.model().data(model_index, Qt.EditRole)
data_type = type(value)
if data_type is bool:
rect = QRect(option.rect)
delta = option.rect.width() / 2 - 9
rect.setX(option.rect.x() + delta) # Hack to center the checkbox
editor.setGeometry(rect)
else:
editor.setGeometry(option.rect)
else:
QStyledItemDelegate.updateEditorGeometry(self, editor, option, model_index)
# end def
def paint(self, painter: QPainter,
option: QStyleOptionViewItem,
model_index: QModelIndex):
"""
Args:
painter: Description
option: Description
model_index: Description
"""
# row = model_index.row()
column = model_index.column()
if column == 0: # Part Name
option.displayAlignment = Qt.AlignVCenter
QStyledItemDelegate.paint(self, painter, option, model_index)
if column == 1: # Visibility
value = model_index.model().data(model_index, Qt.EditRole)
data_type = type(value)
if data_type is str:
# print("val", value)
if COLOR_PATTERN.search(value):
# print("found color")
element = _QCOMMONSTYLE.PE_IndicatorCheckBox
styleoption = QStyleOptionViewItem()
styleoption.palette.setBrush(QPalette.Button, getBrushObj(value))
styleoption.rect = QRect(option.rect)
_QCOMMONSTYLE.drawPrimitive(element, styleoption, painter)
option.displayAlignment = Qt.AlignVCenter
QStyledItemDelegate.paint(self, painter, option, model_index)
elif data_type is int:
option.displayAlignment = Qt.AlignVCenter
QStyledItemDelegate.paint(self, painter, option, model_index)
elif data_type is float:
option.displayAlignment = Qt.AlignVCenter
QStyledItemDelegate.paint(self, painter, option, model_index)
elif data_type is bool:
element = _QCOMMONSTYLE.PE_IndicatorCheckBox
styleoption = QStyleOptionButton()
styleoption.rect = QRect(option.rect)
checked = value
styleoption.state |= QStyle.State_On if checked else QStyle.State_Off
styleoption.palette.setBrush(QPalette.Button, Qt.white)
styleoption.palette.setBrush(QPalette.HighlightedText, Qt.black)
_QCOMMONSTYLE.drawPrimitive(element, styleoption, painter)
if checked:
element = _QCOMMONSTYLE.PE_IndicatorMenuCheckMark
_QCOMMONSTYLE.drawPrimitive(element, styleoption, painter)
else:
QStyledItemDelegate.paint(self, painter, option, model_index)
# end def
# end class CustomStyleItemDelegate
| # -*- coding: utf-8 -*-
"""
Attributes:
COLOR_PATTERN (regex): Description
"""
import re
from typing import (
List,
Set
)
from PyQt5.QtCore import (
Qt,
QRect,
QModelIndex
)
from PyQt5.QtGui import (
QFont,
QPalette,
QPainter
)
from PyQt5.QtWidgets import (
QTreeWidget,
QHeaderView,
QStyledItemDelegate,
QStyleOptionButton,
QStyleOptionViewItem,
QStyle,
QCommonStyle,
QWidget,
QUndoStack
)
from cadnano.objectinstance import ObjectInstance
from cadnano.proxies.cnenum import (
ItemEnum,
ViewReceiveEnum
)
from cadnano.gui.palette import getBrushObj
from cadnano.controllers import ViewRootController
from cadnano.views.pathview import pathstyles as styles
from cadnano.views.outlinerview.cnoutlineritem import CNOutlinerItem
from .oligoitem import OligoSetItem
from .nucleicacidpartitem import NucleicAcidPartSetItem
from .virtualhelixitem import VirtualHelixSetItem
from .cnpropertyitem import CNPropertyItem
from cadnano.cntypes import (
PartT,
DocT,
WindowT
)
COLOR_PATTERN = re.compile("#[0-9a-f].....")
_FONT = QFont(styles.THE_FONT, 12)
_QCOMMONSTYLE = QCommonStyle()
class PropertyEditorWidget(QTreeWidget):
"""
PropertyEditorWidget enables direct editing attributes of an
item that is selected in the Outliner.
"""
view_type = ViewReceiveEnum.PROPERTY
def __init__(self, parent: QWidget = None):
"""Summary
Args:
parent (None, optional): Description
"""
super(PropertyEditorWidget, self).__init__(parent)
self._outline_view_obj_set = set()
self._outline_view_obj_list = []
self.are_signals_on = True
self.setAttribute(Qt.WA_MacShowFocusRect, 0) # no mac focus halo
# end def
def undoStack(self) -> QUndoStack:
return self._document.undoStack()
# end def
def configure(self, window: WindowT, document: DocT):
"""
Args:
window: Description
document: Description
"""
self._window = window
self._document = document
self._controller = ViewRootController(self, document)
self._root = self.invisibleRootItem()
# Appearance
self.setFont(_FONT)
# Columns
self.setColumnCount(2)
self.setIndentation(14)
# Header
self.setHeaderLabels(["Property", "Value"])
h = self.header()
h.resizeSection(0, 200)
h.resizeSection(1, 100)
h.setSectionResizeMode(QHeaderView.Interactive)
# h.setStretchLastSection(False)
custom_delegate = CustomStyleItemDelegate(self)
self.setItemDelegate(custom_delegate)
self.model().dataChanged.connect(self.dataChangedSlot)
self.hide()
# Add some dummy items
# p1 = self.addDummyRow("sequence", "ATCGACTGATCG")
# p2 = self.addDummyRow("circular", True)
# end def
# def addDummyRow(self, property_name, value, parent_QTreeWidgetItem=None):
# if parent_QTreeWidgetItem is None:
# parent_QTreeWidgetItem = self.invisibleRootItem()
# tw_item = QTreeWidgetItem(parent_QTreeWidgetItem)
# tw_item.setData(0, Qt.EditRole, property_name)
# tw_item.setData(1, Qt.EditRole, value)
# tw_item.setFlags(tw_item.flags() | Qt.ItemIsEditable)
# return tw_item
# end def
### SIGNALS ###
### SLOTS ###
def outlinerItemSelectionChanged(self):
"""
Raises:
NotImplementedError: Description
"""
o = self._window.outliner_widget
for child in self.children():
if isinstance(child, (CNPropertyItem)):
child.disconnectSignals()
selected_items = o.selectedItems()
self.clear() # remove pre-existing items
self._outline_view_obj_set.clear()
self._outline_view_obj_list = []
# print("prop multiple selected:", len(selected_items))
# if len(selected_items):
# print(selected_items[0])
# get the selected item
item_types = set([item.itemType() for item in selected_items])
num_types = len(item_types)
if num_types != 1: # assume no mixed types for now
return
item_type = item_types.pop()
outline_view_obj_list = [item.outlineViewObj() for item in selected_items if item.isSelected()]
'''Workaround as items in QTreeWidget.selectedItems() may be not
actually selected
'''
if len(outline_view_obj_list) == 0:
# print("outlinerItemSelectionChanged returning2")
return
self._outline_view_obj_set = set(outline_view_obj_list)
self._outline_view_obj_list = outline_view_obj_list
# special case for parts since there is currently no part filter
if item_type is ItemEnum.NUCLEICACID:
pe_item = NucleicAcidPartSetItem(parent=self)
self.show()
return
item = selected_items[0]
if item.FILTER_NAME not in self._document.filter_set:
print(item.FILTER_NAME, "not in self._document.filter_set")
return
if item_type is ItemEnum.OLIGO:
pe_item = OligoSetItem(parent=self)
self.show()
elif item_type is ItemEnum.VIRTUALHELIX:
pe_item = VirtualHelixSetItem(parent=self)
self.show()
else:
raise NotImplementedError
# end def
def partAddedSlot(self, sender: PartT, model_part_instance: ObjectInstance):
"""
Args:
sender: Model object that emitted the signal.
model_part_instance (ObjectInstance): The model part
"""
# end def
def documentChangeViewSignalingSlot(self, view_types: int):
self.are_signals_on = True if view_types & self.view_type else False
# end def
def clearSelectionsSlot(self, document: DocT):
"""
Args:
doc: Description
"""
# end def
def dataChangedSlot(self, top_left: QModelIndex, bot_right: QModelIndex):
"""docstring for propertyChangedSlot
Args:
top_left: Description
bot_right: Description
"""
c_i = self.currentItem()
if c_i is None:
return
if c_i == self.itemFromIndex(top_left):
c_i.updateCNModel()
# call this to prevent UNDO calls propagating through the Widget first
self.outlinerItemSelectionChanged()
# end def
def selectedChangedSlot(self, item_dict: dict):
"""
Args:
item_dict: Description
"""
# end def
def selectionFilterChangedSlot(self, filter_name_set: Set[str]):
"""
Args:
filter_name_set: Description
"""
pass
# end def
def preXoverFilterChangedSlot(self, filter_name: str):
"""
Args:
filter_name: Description
"""
pass
# end def
def resetRootItemSlot(self, document: DocT):
"""
Args:
document: Description
"""
self.clear()
# end def
### ACCESSORS ###
def window(self) -> WindowT:
"""
Returns:
model :class:`CNMainWindow`
"""
return self._window
# end def
def outlineViewObjSet(self) -> Set[CNOutlinerItem]:
return self._outline_view_obj_set
# end def
def outlineViewObjList(self) -> List[CNOutlinerItem]:
return self._outline_view_obj_list
# end def
### METHODS ###
def resetDocumentAndController(self, document: DocT):
"""
Args:
document: model :class:`Document`
"""
self._document = document
self._controller = ViewRootController(self, document)
# end def
# end class PropertyEditorWidget
class CustomStyleItemDelegate(QStyledItemDelegate):
"""Summary
"""
def createEditor(self, parent_qw: QWidget,
option: QStyleOptionViewItem,
model_index: QModelIndex) -> QWidget:
"""
Args:
parent_qw: Description
option: Description
model_index: Description
Returns:
the widget used to edit the item specified by index for editing
"""
column = model_index.column()
treewidgetitem = self.parent().itemFromIndex(model_index)
if column == 0: # Property Name
return None
elif column == 1:
editor = treewidgetitem.configureEditor(parent_qw, option, model_index)
return editor
else:
return QStyledItemDelegate.createEditor(self,
parent_qw,
option, model_index)
# end def
def updateEditorGeometry(self, editor: QWidget,
option: QStyleOptionViewItem,
model_index: QModelIndex):
"""
Args:
editor: Description
option: Description
model_index: Description
"""
column = model_index.column()
if column == 0:
editor.setGeometry(option.rect)
elif column == 1:
value = model_index.model().data(model_index, Qt.EditRole)
data_type = type(value)
if data_type is bool:
rect = QRect(option.rect)
delta = option.rect.width() / 2 - 9
rect.setX(option.rect.x() + delta) # Hack to center the checkbox
editor.setGeometry(rect)
else:
editor.setGeometry(option.rect)
else:
QStyledItemDelegate.updateEditorGeometry(self, editor, option, model_index)
# end def
def paint(self, painter: QPainter,
option: QStyleOptionViewItem,
model_index: QModelIndex):
"""
Args:
painter: Description
option: Description
model_index: Description
"""
# row = model_index.row()
column = model_index.column()
if column == 0: # Part Name
option.displayAlignment = Qt.AlignVCenter
QStyledItemDelegate.paint(self, painter, option, model_index)
if column == 1: # Visibility
value = model_index.model().data(model_index, Qt.EditRole)
data_type = type(value)
if data_type is str:
# print("val", value)
if COLOR_PATTERN.search(value):
# print("found color")
element = _QCOMMONSTYLE.PE_IndicatorCheckBox
styleoption = QStyleOptionViewItem()
styleoption.palette.setBrush(QPalette.Button, getBrushObj(value))
styleoption.rect = QRect(option.rect)
_QCOMMONSTYLE.drawPrimitive(element, styleoption, painter)
option.displayAlignment = Qt.AlignVCenter
QStyledItemDelegate.paint(self, painter, option, model_index)
elif data_type is int:
option.displayAlignment = Qt.AlignVCenter
QStyledItemDelegate.paint(self, painter, option, model_index)
elif data_type is float:
option.displayAlignment = Qt.AlignVCenter
QStyledItemDelegate.paint(self, painter, option, model_index)
elif data_type is bool:
element = _QCOMMONSTYLE.PE_IndicatorCheckBox
styleoption = QStyleOptionButton()
styleoption.rect = QRect(option.rect)
checked = value
styleoption.state |= QStyle.State_On if checked else QStyle.State_Off
styleoption.palette.setBrush(QPalette.Button, Qt.white)
styleoption.palette.setBrush(QPalette.HighlightedText, Qt.black)
_QCOMMONSTYLE.drawPrimitive(element, styleoption, painter)
if checked:
element = _QCOMMONSTYLE.PE_IndicatorMenuCheckMark
_QCOMMONSTYLE.drawPrimitive(element, styleoption, painter)
else:
QStyledItemDelegate.paint(self, painter, option, model_index)
# end def
# end class CustomStyleItemDelegate
| en | 0.48399 | # -*- coding: utf-8 -*- Attributes: COLOR_PATTERN (regex): Description PropertyEditorWidget enables direct editing attributes of an item that is selected in the Outliner. Summary Args: parent (None, optional): Description # no mac focus halo # end def # end def Args: window: Description document: Description # Appearance # Columns # Header # h.setStretchLastSection(False) # Add some dummy items # p1 = self.addDummyRow("sequence", "ATCGACTGATCG") # p2 = self.addDummyRow("circular", True) # end def # def addDummyRow(self, property_name, value, parent_QTreeWidgetItem=None): # if parent_QTreeWidgetItem is None: # parent_QTreeWidgetItem = self.invisibleRootItem() # tw_item = QTreeWidgetItem(parent_QTreeWidgetItem) # tw_item.setData(0, Qt.EditRole, property_name) # tw_item.setData(1, Qt.EditRole, value) # tw_item.setFlags(tw_item.flags() | Qt.ItemIsEditable) # return tw_item # end def ### SIGNALS ### ### SLOTS ### Raises: NotImplementedError: Description # remove pre-existing items # print("prop multiple selected:", len(selected_items)) # if len(selected_items): # print(selected_items[0]) # get the selected item # assume no mixed types for now Workaround as items in QTreeWidget.selectedItems() may be not actually selected # print("outlinerItemSelectionChanged returning2") # special case for parts since there is currently no part filter # end def Args: sender: Model object that emitted the signal. model_part_instance (ObjectInstance): The model part # end def # end def Args: doc: Description # end def docstring for propertyChangedSlot Args: top_left: Description bot_right: Description # call this to prevent UNDO calls propagating through the Widget first # end def Args: item_dict: Description # end def Args: filter_name_set: Description # end def Args: filter_name: Description # end def Args: document: Description # end def ### ACCESSORS ### Returns: model :class:`CNMainWindow` # end def # end def # end def ### METHODS ### Args: document: model :class:`Document` # end def # end class PropertyEditorWidget Summary Args: parent_qw: Description option: Description model_index: Description Returns: the widget used to edit the item specified by index for editing # Property Name # end def Args: editor: Description option: Description model_index: Description # Hack to center the checkbox # end def Args: painter: Description option: Description model_index: Description # row = model_index.row() # Part Name # Visibility # print("val", value) # print("found color") # end def # end class CustomStyleItemDelegate | 1.94872 | 2 |
tests/test_steps/test_varmetric.py | ajstewart/tkp | 9 | 6618942 | <reponame>ajstewart/tkp<filename>tests/test_steps/test_varmetric.py<gh_stars>1-10
import unittest
import logging
import tkp.db.model
from tkp.testutil.alchemy import gen_band, gen_dataset, gen_skyregion,\
gen_lightcurve
from tkp.testutil.decorators import database_disabled
import tkp.db
from tkp.steps.varmetric import execute_store_varmetric
logging.basicConfig(level=logging.INFO)
logging.getLogger('sqlalchemy.engine').setLevel(logging.WARNING)
class TestApi(unittest.TestCase):
@classmethod
def setUpClass(cls):
# Can't use a regular skip here, due to a Nose bug:
# https://github.com/nose-devs/nose/issues/946
if database_disabled():
raise unittest.SkipTest("Database functionality disabled "
"in configuration.")
cls.db = tkp.db.Database()
cls.db.connect()
def setUp(self):
self.session = self.db.Session()
self.dataset = gen_dataset('test varmetric step')
band = gen_band(dataset=self.dataset, central=150**6)
skyregion = gen_skyregion(self.dataset)
lightcurve = gen_lightcurve(band, self.dataset, skyregion)
self.session.add_all(lightcurve)
self.session.flush()
self.session.commit()
def test_execute_store_varmetric(self):
session = self.db.Session()
execute_store_varmetric(session=session, dataset_id=self.dataset.id)
self.session.flush()
def test_execute_store_varmetric_twice(self):
session = self.db.Session()
execute_store_varmetric(session=session, dataset_id=self.dataset.id)
self.session.flush()
execute_store_varmetric(session=session, dataset_id=self.dataset.id)
self.session.flush()
| import unittest
import logging
import tkp.db.model
from tkp.testutil.alchemy import gen_band, gen_dataset, gen_skyregion,\
gen_lightcurve
from tkp.testutil.decorators import database_disabled
import tkp.db
from tkp.steps.varmetric import execute_store_varmetric
logging.basicConfig(level=logging.INFO)
logging.getLogger('sqlalchemy.engine').setLevel(logging.WARNING)
class TestApi(unittest.TestCase):
@classmethod
def setUpClass(cls):
# Can't use a regular skip here, due to a Nose bug:
# https://github.com/nose-devs/nose/issues/946
if database_disabled():
raise unittest.SkipTest("Database functionality disabled "
"in configuration.")
cls.db = tkp.db.Database()
cls.db.connect()
def setUp(self):
self.session = self.db.Session()
self.dataset = gen_dataset('test varmetric step')
band = gen_band(dataset=self.dataset, central=150**6)
skyregion = gen_skyregion(self.dataset)
lightcurve = gen_lightcurve(band, self.dataset, skyregion)
self.session.add_all(lightcurve)
self.session.flush()
self.session.commit()
def test_execute_store_varmetric(self):
session = self.db.Session()
execute_store_varmetric(session=session, dataset_id=self.dataset.id)
self.session.flush()
def test_execute_store_varmetric_twice(self):
session = self.db.Session()
execute_store_varmetric(session=session, dataset_id=self.dataset.id)
self.session.flush()
execute_store_varmetric(session=session, dataset_id=self.dataset.id)
self.session.flush() | en | 0.776199 | # Can't use a regular skip here, due to a Nose bug: # https://github.com/nose-devs/nose/issues/946 | 2.051927 | 2 |
Trakttv.bundle/Contents/Libraries/Shared/plugin/sync/modes/fast_pull/movies.py | disrupted/Trakttv.bundle | 1,346 | 6618943 | <gh_stars>1000+
from plugin.sync.core.enums import SyncData, SyncMedia, SyncMode
from plugin.sync.core.guid import GuidParser
from plugin.sync.modes.core.base import log_unsupported, mark_unsupported
from plugin.sync.modes.fast_pull.base import Base
from plex_database.models import MetadataItem
import elapsed
import logging
log = logging.getLogger(__name__)
class Movies(Base):
data = [
SyncData.Collection,
SyncData.Playback,
SyncData.Ratings,
SyncData.Watched
]
def __init__(self, task):
super(Movies, self).__init__(task)
# Sections
self.p_sections = None
self.p_sections_map = None
# Items
self.p_count = None
self.p_movies = None
self.p_unsupported = None
@elapsed.clock
def construct(self):
# Retrieve movie sections
self.p_sections, self.p_sections_map = self.sections('movie')
# Determine number of movies that will be processed
self.p_count = self.plex.library.movies.count(
self.p_sections,
account=self.current.account.plex.key
)
# Increment progress steps total
self.current.progress.group(Movies).add(self.p_count)
@elapsed.clock
def start(self):
# Fetch movies with account settings
self.p_movies = self.plex.library.movies.mapped(
self.p_sections, [
MetadataItem.library_section,
MetadataItem.added_at
],
account=self.current.account.plex.key,
parse_guid=True
)
# Reset state
self.p_unsupported = {}
@elapsed.clock
def run(self):
# Process movies
for mo_id, guid, p_movie in self.p_movies:
# Increment one step
self.current.progress.group(Movies).step()
# Parse guid
match = GuidParser.parse(guid)
if not match.supported:
mark_unsupported(self.p_unsupported, mo_id, guid)
continue
if not match.found:
log.info('Unable to find identifier for: %s/%s (rating_key: %r)', guid.service, guid.id, mo_id)
continue
key = (match.guid.service, match.guid.id)
# Try retrieve `pk` for `key`
pk = self.trakt.table('movies').get(key)
# Store in item map
self.current.map.add(p_movie.get('library_section'), mo_id, [key, pk])
if pk is None:
# No `pk` found
continue
# Run pull handlers if the item has been added recently
if self.should_pull(mo_id, p_movie.get('added_at')):
log.info('Movie %r has been added recently, running pull sync instead', mo_id)
# Execute handlers
for data in self.get_data(SyncMedia.Movies):
t_movie = self.trakt[(SyncMedia.Movies, data)].get(pk)
self.execute_handlers(
SyncMode.Pull, SyncMedia.Movies, data,
key=mo_id,
p_item=p_movie,
t_item=t_movie
)
else:
# Execute handlers for changed data
for data, action, t_movie in self.iter_changes(SyncMedia.Movies, pk):
self.execute_handlers(
self.mode, SyncMedia.Movies, data,
action=action,
key=mo_id,
p_item=p_movie,
t_item=t_movie
)
# Task checkpoint
self.checkpoint()
# Stop progress group
self.current.progress.group(Movies).stop()
# Log details
log_unsupported(log, 'Found %d unsupported movie(s)', self.p_unsupported)
| from plugin.sync.core.enums import SyncData, SyncMedia, SyncMode
from plugin.sync.core.guid import GuidParser
from plugin.sync.modes.core.base import log_unsupported, mark_unsupported
from plugin.sync.modes.fast_pull.base import Base
from plex_database.models import MetadataItem
import elapsed
import logging
log = logging.getLogger(__name__)
class Movies(Base):
data = [
SyncData.Collection,
SyncData.Playback,
SyncData.Ratings,
SyncData.Watched
]
def __init__(self, task):
super(Movies, self).__init__(task)
# Sections
self.p_sections = None
self.p_sections_map = None
# Items
self.p_count = None
self.p_movies = None
self.p_unsupported = None
@elapsed.clock
def construct(self):
# Retrieve movie sections
self.p_sections, self.p_sections_map = self.sections('movie')
# Determine number of movies that will be processed
self.p_count = self.plex.library.movies.count(
self.p_sections,
account=self.current.account.plex.key
)
# Increment progress steps total
self.current.progress.group(Movies).add(self.p_count)
@elapsed.clock
def start(self):
# Fetch movies with account settings
self.p_movies = self.plex.library.movies.mapped(
self.p_sections, [
MetadataItem.library_section,
MetadataItem.added_at
],
account=self.current.account.plex.key,
parse_guid=True
)
# Reset state
self.p_unsupported = {}
@elapsed.clock
def run(self):
# Process movies
for mo_id, guid, p_movie in self.p_movies:
# Increment one step
self.current.progress.group(Movies).step()
# Parse guid
match = GuidParser.parse(guid)
if not match.supported:
mark_unsupported(self.p_unsupported, mo_id, guid)
continue
if not match.found:
log.info('Unable to find identifier for: %s/%s (rating_key: %r)', guid.service, guid.id, mo_id)
continue
key = (match.guid.service, match.guid.id)
# Try retrieve `pk` for `key`
pk = self.trakt.table('movies').get(key)
# Store in item map
self.current.map.add(p_movie.get('library_section'), mo_id, [key, pk])
if pk is None:
# No `pk` found
continue
# Run pull handlers if the item has been added recently
if self.should_pull(mo_id, p_movie.get('added_at')):
log.info('Movie %r has been added recently, running pull sync instead', mo_id)
# Execute handlers
for data in self.get_data(SyncMedia.Movies):
t_movie = self.trakt[(SyncMedia.Movies, data)].get(pk)
self.execute_handlers(
SyncMode.Pull, SyncMedia.Movies, data,
key=mo_id,
p_item=p_movie,
t_item=t_movie
)
else:
# Execute handlers for changed data
for data, action, t_movie in self.iter_changes(SyncMedia.Movies, pk):
self.execute_handlers(
self.mode, SyncMedia.Movies, data,
action=action,
key=mo_id,
p_item=p_movie,
t_item=t_movie
)
# Task checkpoint
self.checkpoint()
# Stop progress group
self.current.progress.group(Movies).stop()
# Log details
log_unsupported(log, 'Found %d unsupported movie(s)', self.p_unsupported) | en | 0.78745 | # Sections # Items # Retrieve movie sections # Determine number of movies that will be processed # Increment progress steps total # Fetch movies with account settings # Reset state # Process movies # Increment one step # Parse guid # Try retrieve `pk` for `key` # Store in item map # No `pk` found # Run pull handlers if the item has been added recently # Execute handlers # Execute handlers for changed data # Task checkpoint # Stop progress group # Log details | 2.059319 | 2 |
china_server.py | PaleNeutron/WarshipGrilsRobot | 4 | 6618944 | #!/usr/bin/env python3
import zemulator
import zrobot
# class Mission_6_1_A_China(zrobot.Mission_6_1_A):
# def __init__():
# self.boss_ships = '射水鱼'
class Mission_5_2_C(zrobot.Mission):
def __init__(self, ze: zemulator.ZjsnEmulator):
super(Mission_5_2_C, self).__init__('5-2C', 502, ze)
def set_first_nodes(self):
self.node_c = zrobot.Node('C', enemy_target='轻母')
self.node_f = zrobot.Node('F')
self.node_h = zrobot.Node('H')
self.node_i = zrobot.Node('I')
self.node_j = zrobot.Node(
'J', formation=4, night_flag=1, big_broken_protect=False)
self.node_c.add_next(self.node_f)
self.node_f.add_next([self.node_i, self.node_h])
self.node_i.add_next(self.node_j)
self.node_h.add_next(self.node_j)
return self.node_c
def prepare(self):
# 所有水下船只
if 10018811 in self.ze.unlockShip:
self.available = False
zrobot._logger.info('有北京风了,2-5已经毕业')
return
ss_ships = []
for ship in sorted(self.ze.userShip, key=lambda x: x["level"], reverse=True):
conditions = [ship["level"] > 1,
ship.type in ['潜艇', '炮潜'],
]
if all(conditions):
ss_ships.append(ship.id)
zrobot._logger.debug("ss_ships:{}".format(
[(self.ze.userShip[ship_id].name, self.ze.userShip[ship_id].level) for ship_id in ss_ships]))
for i in range(0, 6):
self.ze.ship_groups[i] = (ss_ships, 1, False)
self.ze.ship_groups[0][0].insert(
0, self.ze.userShip.name("U47").id) # 尽可能狼群U47旗舰
return self.ze.change_ships()
class Mission_2_5_mid(zrobot.Mission):
def __init__(self, ze: zemulator.ZjsnEmulator):
super(Mission_2_5_mid, self).__init__('2-5mid', 205, ze)
def set_first_nodes(self):
self.node_a = zrobot.Node('A')
self.node_b = zrobot.Node('B')
self.node_d = zrobot.Node('D', node_type='skip')
self.node_h = zrobot.Node('H', node_type='skip')
self.node_k = zrobot.Node('K', node_type='skip')
self.node_o = zrobot.Node('O', night_flag=1)
self.node_a.add_next(self.node_b)
self.node_b.add_next(self.node_d)
self.node_d.add_next(self.node_h)
self.node_h.add_next(self.node_k)
self.node_k.add_next(self.node_o)
return self.node_a
def prepare(self):
# 所有高级潜艇
if 10026711 in self.ze.unlockShip:
self.available = False
zrobot._logger.info('有岛风了,2-5中路已经毕业')
return
ss_ships = []
for ship in sorted(self.ze.userShip, key=lambda x: x["level"], reverse=True):
conditions = [ship["level"] > 60,
ship.type in ['潜艇'],
]
if all(conditions):
ss_ships.append(ship.id)
zrobot._logger.debug("ss_ships:{}".format(
[(self.ze.userShip[ship_id].name, self.ze.userShip[ship_id].level) for ship_id in ss_ships]))
taitai = [566, 115]
cv_ships = []
# 所有高速,高级航母
for ship in sorted(self.ze.userShip, key=lambda x: x["level"], reverse=True):
conditions = [ship["level"] > 75,
ship.type in ['航母', '装母'],
ship.speed > 30,
ship.id not in taitai,
]
if all(conditions):
cv_ships.append(ship.id)
cv_ships.extend(taitai)
zrobot._logger.debug("cv_ships:{}".format(
[(self.ze.userShip[ship_id].name, self.ze.userShip[ship_id].level) for ship_id in cv_ships]))
self.ze.ship_groups[0] = ([16523], 0.7, True) # 飙车胡德
self.ze.ship_groups[1] = self.ze.ship_groups[2] = (ss_ships, 0, False)
self.ze.ship_groups[3] = self.ze.ship_groups[5] = (
cv_ships, 0.7, False)
self.ze.ship_groups[4] = (taitai, 0.7, True)
# self.ze.ship_groups[3][0].insert(0,13664) # 大凤优先4号位置
self.ze.ship_groups[3] = ([13664], 0.7, True) # 大凤
self.ze.ship_groups[4] = ([115], 0.7, True) # 太太
self.ze.ship_groups[5] = ([43707], 0.7, True) # 加加
return self.ze.change_ships()
class Mission_5_5_C(zrobot.Mission):
def __init__(self, ze: zemulator.ZjsnEmulator):
super(Mission_5_5_C, self).__init__('5-5C', 505, ze)
def set_first_nodes(self):
self.node_c = zrobot.Node('C', formation=4, enemy_avoid=zemulator.ZjsnShip.type_id("轻巡"))
self.node_f = zrobot.Node('F')
self.node_i = zrobot.Node('I', formation=4, night_flag=1)
self.node_c.add_next(self.node_f)
self.node_f.add_next(self.node_i)
return self.node_c
def prepare(self):
# 所有90级以上水下船只
ss_ships = []
for ship in sorted(self.ze.userShip, key=lambda x: x["level"], reverse=True):
conditions = [ship["level"] >= 70,
ship.type in ['潜艇', '炮潜'],
]
if all(conditions):
ss_ships.append(ship.id)
ships = [self.ze.userShip[ship_id] for ship_id in ss_ships]
zrobot._logger.debug("ss_ships:{}".format(
[(s.name, s.level) for s in ships]))
for i in range(0, 6):
self.ze.ship_groups[i] = (ss_ships, 1, False)
self.ze.ship_groups[0][0].insert(
0, self.ze.userShip.name("U47").id) # 尽可能狼群U47旗舰
return self.ze.change_ships()
class Mission_5_5_B(zrobot.Mission):
def __init__(self, ze: zemulator.ZjsnEmulator):
super(Mission_5_5_B, self).__init__('5-5B', 505, ze)
def set_first_nodes(self):
self.node_b = zrobot.Node(
'B', additional_spy_filter=lambda sr: '战巡' in str(sr) or '雷巡' in str(sr))
return self.node_b
def prepare(self):
boss_ships = [9210, 5324] # 牛仔级
cv_ship = [43707]
# 所有改造后的ca, 等级从低到高
ca_ships = []
for ship in sorted(self.ze.userShip, key=lambda x: x["level"], reverse=False):
conditions = [ship["level"] < 100,
ship.type in ['重巡'],
ship.evolved,
]
if all(conditions):
ca_ships.append(ship.id)
ships = [self.ze.userShip[ship_id] for ship_id in ca_ships]
zrobot._logger.debug("ca_ships:{}".format(
[(s.name, s.level) for s in ships]))
for i in range(1, 5):
self.ze.ship_groups[i] = (ca_ships, 1, False)
self.ze.ship_groups[0] = (boss_ships, 1, True)
self.ze.ship_groups[5] = (cv_ship, 1, True)
return self.ze.change_ships()
class Mission_2_5_up(zrobot.Mission):
def __init__(self, ze: zemulator.ZjsnEmulator):
super(Mission_2_5_up, self).__init__('2-5-up', 205, ze)
def set_first_nodes(self):
self.node_a = self.node_chain([zrobot.Node('A', enemy_avoid='20502003'),
zrobot.Node('B'),
zrobot.Node('c', node_type='resource').add_next(
zrobot.Node('g').add_next(
zrobot.Node('j', night_flag=1, formation=4))),
zrobot.Node('f'),
zrobot.Node(
'j', night_flag=1, formation=4),
])
return self.node_a
def prepare(self):
if 10010213 in self.ze.unlockShip:
zrobot._logger.debug('有陆奥了')
return False
# 所有高级潜艇
ss_ships = []
for ship in sorted(self.ze.userShip, key=lambda x: x["level"], reverse=True):
conditions = [ship["level"] > 60,
ship.type in ['潜艇'],
]
if all(conditions):
ss_ships.append(ship.id)
zrobot._logger.debug("ss_ships:{}".format(
[(self.ze.userShip[ship_id].name, self.ze.userShip[ship_id].level) for ship_id in ss_ships]))
for i in range(1, 4):
self.ze.ship_groups[i] = (ss_ships, 0, False)
self.ze.ship_groups[0] = ([43014], 0.8, True)
self.ze.ship_groups[4] = ([115], 0.8, True)
self.ze.ship_groups[5] = ([43707], 0.8, True)
return self.ze.change_ships()
class Mission_2_5_down(zrobot.Mission):
def __init__(self, ze: zemulator.ZjsnEmulator):
super(Mission_2_5_down, self).__init__('2-5down', 205, ze)
def set_first_nodes(self):
self.node_a = zrobot.Node('A', additional_spy_filter=lambda sr: len(
sr['enemyVO']['enemyShips']) == 5)
# self.node_a = Node('A', node_type='skip')
self.node_b = zrobot.Node('B')
self.node_e = zrobot.Node('E', node_type='resource')
self.node_i = zrobot.Node('I')
self.node_l = zrobot.Node('L', night_flag=1, formation=4)
self.node_m = zrobot.Node('M', night_flag=1, formation=4)
self.node_n = zrobot.Node('N', night_flag=1, formation=4)
self.node_a.add_next(self.node_b)
self.node_b.add_next(self.node_e)
self.node_e.add_next(self.node_i)
# self.node_i.add_next(self.node_l) # 不用去了,苍龙有了
# self.node_i.add_next(self.node_m) # 不用去了,比睿有了
self.node_i.add_next(self.node_n)
return self.node_a
def prepare(self):
# 所有能开幕的水下船只
ss_ships = []
for ship in sorted(self.ze.userShip, key=lambda x: x["level"], reverse=True):
conditions = [ship["level"] > 11,
ship.type in ['潜艇', '炮潜'],
]
if all(conditions):
ss_ships.append(ship.id)
ships = [self.ze.userShip[ship_id] for ship_id in ss_ships]
zrobot._logger.debug("ss_ships:{}".format(
[(s.name, s.level) for s in ships]))
for i in range(0, 6):
self.ze.ship_groups[i] = (ss_ships, 0, False)
self.ze.ship_groups[0][0].insert(0, 6744) # 尽可能狼群U47旗舰
return self.ze.change_ships()
class Mission_6_3(zrobot.Mission):
def __init__(self, ze: zemulator.ZjsnEmulator):
super(Mission_6_3, self).__init__('6-3', 603, ze)
def set_first_nodes(self):
self.node_b = zrobot.Node(
'B', enemy_target=zemulator.ZjsnShip.type_id('重巡'), formation=4)
# self.node_a = Node('A', node_type='skip')
self.node_e = zrobot.Node('E', formation=4)
self.node_h = zrobot.Node('H', formation=4)
self.node_j = zrobot.Node('J', formation=4, night_flag=1)
self.node_b.add_next(self.node_e)
self.node_e.add_next(self.node_h)
self.node_h.add_next(self.node_j)
return self.node_b
def prepare(self):
if 10030812 in self.ze.unlockShip and 10021811 in self.ze.unlockShip:
zrobot._logger.info('有哥特兰和古斯塔夫了')
return False
# 所有能开幕的水下船只
ss_ships = []
for ship in sorted(self.ze.userShip, key=lambda x: x["level"], reverse=True):
conditions = [ship["level"] > 75,
ship.type in ['潜艇', '炮潜'],
]
if all(conditions):
ss_ships.append(ship.id)
ships = [self.ze.userShip[ship_id] for ship_id in ss_ships]
zrobot._logger.debug("ss_ships:{}".format(
[(s.name, s.level) for s in ships]))
for i in range(0, 6):
self.ze.ship_groups[i] = (ss_ships, 0, False)
self.ze.ship_groups[0][0].insert(0, 6744) # 尽可能狼群U47旗舰
return self.ze.change_ships()
class MissionPants(zrobot.Mission):
""""""
def __init__(self, ze: zemulator.ZjsnEmulator):
super(MissionPants, self).__init__('pants', 201, ze)
self.pants_num = 0
self.pants_yesterday = 20
self.enable = True
self.last_pants_time = self.ze.now
def set_first_nodes(self):
self.node_b = zrobot.Node('B', node_type='resource')
self.node_d = zrobot.Node('D', node_type='resource')
self.node_f = zrobot.Node(
'F', night_flag=1, enemy_target=zemulator.ZjsnShip.type_id('补给'))
self.node_b.add_next(self.node_d)
self.node_d.add_next(self.node_f)
return self.node_b
@property
def pants_available(self):
now = self.ze.now
if self.last_pants_time < self.ze.now.replace(hour=0, minute=0, second=0) < now:
self.pants_yesterday = self.ze.spoils
return self.ze.spoils_event and self.ze.todaySpoilsNum < 50
def prepare(self):
if not self.pants_available:
self.available = False
return
if self.count > 100:
zrobot._logger.warning('pants {}, SL {}'.format(
self.ze.todaySpoilsNum, self.count))
# 所有高级改造DD
dd_ships = []
for ship in sorted(self.ze.userShip, key=lambda x: x["level"], reverse=False):
conditions = [ship["level"] > 80,
ship.type in ['驱逐'],
ship.evolved == 1,
]
if all(conditions):
dd_ships.append(ship.id)
ships = [self.ze.userShip[ship_id] for ship_id in dd_ships]
zrobot._logger.debug("dd_ships:{}".format(
[(s.name, s.level) for s in ships]))
# 所有高级改造cv
cv_ships = []
for ship in sorted(self.ze.userShip, key=lambda x: x["level"], reverse=False):
conditions = [ship.type in ['航母'],
ship.level > 1,
ship.evolved == 1 or not ship.can_evo,
]
if all(conditions):
cv_ships.append(ship.id)
ships = [self.ze.userShip[ship_id] for ship_id in cv_ships]
zrobot._logger.debug("cv_ships:{}".format(
[(s.name, s.level) for s in ships]))
self.ze.ship_groups = [()]*6
for i in range(0, 4):
self.ze.ship_groups[i] = (dd_ships, 1, False)
for i in range(2, 4):
self.ze.ship_groups[i] = (cv_ships, 1, False)
# self.ze.ship_groups[2] = ([self.ze.userShip.name("约克城").id], 1, True)
self.ze.ship_groups[4] = self.ze.ship_groups[5] = (None, 1, False)
return self.ze.change_ships()
def summery(self):
if self.success:
zrobot._logger.info("{} SL {} 次, 共捞{}胖次, result:{}".format(
self.mission_name, self.count,
self.ze.todaySpoilsNum + 1,
[(i.name, i.level) for i in self.ze.working_ships]))
self.count = 0
self.last_pants_time = self.ze.now
class Mission_4_3(zrobot.Mission):
"""一次45铝,一小时2700铝,再见了,远征铝"""
def __init__(self, ze: zemulator.ZjsnEmulator):
super().__init__('偷铝', 403, ze)
def set_first_nodes(self):
self.node_b = zrobot.Node('B')
self.node_d = zrobot.Node('D', node_type='resource')
self.node_b.add_next(self.node_d)
self.aluminum = 0
return self.node_b
def prepare(self):
# 所有高级改造DD
dd_ships = []
for ship in sorted(self.ze.userShip, key=lambda x: x["level"], reverse=False):
conditions = [ship["level"] > 80,
ship.type in ['驱逐'],
ship.evolved == 1,
]
if all(conditions):
dd_ships.append(ship.id)
ships = [self.ze.userShip[ship_id] for ship_id in dd_ships]
zrobot._logger.debug("dd_ships:{}".format(
[(s.name, s.level) for s in ships]))
self.ze.ship_groups[0] = (dd_ships, 0, False) # 旗舰必须是完好的防止大破
for i in range(1, 4):
self.ze.ship_groups[i] = (dd_ships, 1, False)
self.ze.ship_groups[4] = self.ze.ship_groups[5] = (None, 1, False)
return self.ze.change_ships()
def summery(self):
super().summery()
if self.success:
if 'userResVo' in self.node_d.battle_result:
zrobot._logger.info("资源: 油:{0[oil]:<7} 弹:{0[ammo]:<7} 钢:{0[steel]:<7} 铝:{0[aluminium]:<7}".format(
self.node_d.battle_result['userResVo']))
class Mission_5_3(zrobot.Mission):
"""一次45铝,一小时2700铝,再见了,远征铝"""
def __init__(self, ze: zemulator.ZjsnEmulator):
super().__init__('偷钢', 503, ze)
def set_first_nodes(self):
self.node_b = zrobot.Node('B')
self.node_d = zrobot.Node('D', node_type='resource')
self.node_b.add_next(self.node_d)
self.aluminum = 0
return self.node_b
def prepare(self):
# 所有高级DD
dd_ships = []
for ship in sorted(self.ze.userShip, key=lambda x: x["level"], reverse=False):
conditions = [ship["level"] > 80,
ship.type in ['驱逐'],
# ship.evolved == 1,
]
if all(conditions):
dd_ships.append(ship.id)
ships = [self.ze.userShip[ship_id] for ship_id in dd_ships]
zrobot._logger.debug("dd_ships:{}".format(
[(s.name, s.level) for s in ships]))
self.ze.ship_groups[0] = (dd_ships, 0, False) # 旗舰必须是完好的防止大破
for i in range(1, 4):
self.ze.ship_groups[i] = (dd_ships, 1, False)
self.ze.ship_groups[4] = self.ze.ship_groups[5] = (None, 1, False)
return self.ze.change_ships()
def summery(self):
super().summery()
if self.success:
if 'userResVo' in self.node_d.battle_result:
zrobot._logger.info("资源: 油:{0[oil]:<7} 弹:{0[ammo]:<7} 钢:{0[steel]:<7} 铝:{0[aluminium]:<7}".format(
self.node_d.battle_result['userResVo']))
class Mission_2_2(zrobot.Mission):
"""一次17油,一小时1000油,效率高于远征,大有可为"""
def __init__(self, ze: zemulator.ZjsnEmulator):
super().__init__('偷油', 202, ze)
def set_first_nodes(self):
self.node_a = zrobot.Node('A')
self.node_c = zrobot.Node('C', node_type='resource')
self.node_a.add_next(self.node_c)
return self.node_a
def prepare(self):
# 单DD偷油,擦伤就修,防止大破劝退
dd_ships = []
for ship in sorted(self.ze.userShip, key=lambda x: x["level"], reverse=False):
conditions = [ship["level"] > 80,
ship.type in ['驱逐'],
ship.evolved == 1,
]
if all(conditions):
dd_ships.append(ship.id)
ships = [self.ze.userShip[ship_id] for ship_id in dd_ships]
zrobot._logger.debug("dd_ships:{}".format(
[(s.name, s.level) for s in ships]))
for i in range(1, 6):
self.ze.ship_groups[i] = (None, 1, False)
self.ze.ship_groups[0] = (dd_ships, 0, False)
return self.ze.change_ships()
# class Mission_1_1(zrobot.Mission):
# def __init__(self, ze: zemulator.ZjsnEmulator):
# super(Mission_1_1, self).__init__('1-1A', 101, ze)
# def set_first_nodes(self):
# self.node_a = zrobot.Node('A')
# return self.node_a
# def prepare(self):
# # 所有高级改造DD
# dd_ships = []
# for ship in sorted(self.ze.userShip, key=lambda x: x["level"], reverse=True):
# conditions = [100 > ship["level"] > 20,
# ship.type in ['驱逐'],
# ship.evolved == 1,
# ]
# if all(conditions):
# dd_ships.append(ship.id)
# ships = [self.ze.userShip[ship_id] for ship_id in dd_ships]
# zrobot._logger.debug("dd_ships:{}".format(
# [(s.name, s.level) for s in ships]))
# for i in range(1, 6):
# self.ze.ship_groups[i] = (None, 1, False)
# self.ze.ship_groups[0] = (dd_ships, 1, False)
# try:
# self.ze.change_ships()
# except zemulator.ZjsnError:
# return False
# return True
class Mission_6_4(zrobot.Mission):
def __init__(self, ze: zemulator.ZjsnEmulator):
super(Mission_6_4, self).__init__('6-4', 604, ze)
self.pants_num = 0
def set_first_nodes(self):
self.node_a = self.node_chain([zrobot.Node('A', enemy_avoid=zemulator.ZjsnShip.type_id('战巡')),
zrobot.Node('B'),
zrobot.Node('e', enemy_avoid=zemulator.ZjsnShip.type_id('潜艇'), night_flag=1)])
return self.node_a
def prepare(self):
if 10023712 in self.ze.unlockShip:
zrobot._logger.debug('有昆特了')
return False
boss_ships = [s.id for s in self.ze.userShip if s.name ==
'赤城' and s.level > 80] # 赤城带队洗地
cv_ships = []
for ship in sorted(self.ze.userShip, key=lambda x: x["level"], reverse=True):
conditions = [20 < ship["level"] < 100,
ship.type in ['航母'],
ship.name not in ['突击者', '赤城'],
]
if all(conditions):
cv_ships.append(ship.id)
ships = [self.ze.userShip[ship_id] for ship_id in cv_ships]
zrobot._logger.debug("cv_ships:{}".format(
[(s.name, s.level) for s in ships]))
# 所有改造后的ca, 等级从低到高
ca_ships = []
for ship in sorted(self.ze.userShip, key=lambda x: x["level"], reverse=False):
conditions = [ship["level"] < 100,
ship.type in ['重巡'],
ship.evolved,
]
if all(conditions):
ca_ships.append(ship.id)
ships = [self.ze.userShip[ship_id] for ship_id in ca_ships]
zrobot._logger.debug("ca_ships:{}".format(
[(s.name, s.level) for s in ships]))
for i in range(0, 6):
self.ze.ship_groups[i] = (cv_ships, 1, True)
# boss_ships = cv_ships
self.ze.ship_groups[0] = (boss_ships, 1, True)
self.ze.ship_groups[1] = ([229], 1, True)
self.ze.ship_groups[2] = (ca_ships, 1, True)
return self.ze.change_ships()
class Mission_6_4_fish(zrobot.Mission):
def __init__(self, ze: zemulator.ZjsnEmulator):
super(Mission_6_4_fish, self).__init__('6-4 fish', 604, ze)
def set_first_nodes(self):
# self.node_a = Node('A', additional_spy_filter=lambda sr: '战巡' in str(sr) or '航母'in str(sr))
self.node_c = self.node_chain(
[zrobot.Node('c', formation=4, night_flag=1),
zrobot.Node('f', formation=4),
zrobot.Node('h'),
zrobot.Node('j', node_type="resource"),
zrobot.Node('l', enemy_target='20100003', formation=4),
]
)
self.node_b = self.node_chain([zrobot.Node('b', formation=4, night_flag=1),
zrobot.Node(
'd', formation=4, night_flag=1),
])
self.node_a = zrobot.Node('a', enemy_avoid=zemulator.ZjsnShip.type_id('驱逐'))
self.node_a.add_next(self.node_b)
self.node_a.add_next(self.node_c)
return self.node_a
def prepare(self):
target = 10023712
if target in self.ze.unlockShip:
zrobot._logger.info('有{}了'.format(
zemulator._INIT_DATA_.ship_card[target]["title"]))
return False
# 所有能开幕的水下船只
ss_ships = []
for ship in sorted(self.ze.userShip, key=lambda x: x["level"], reverse=True):
conditions = [ship["level"] > 75,
ship.type in ['潜艇', '炮潜'],
]
if all(conditions):
ss_ships.append(ship.id)
ships = [self.ze.userShip[ship_id] for ship_id in ss_ships]
zrobot._logger.debug("ss_ships:{}".format(
[(s.name, s.level) for s in ships]))
for i in range(0, 6):
self.ze.ship_groups[i] = (ss_ships, 0, False)
self.ze.ship_groups[0][0].insert(0, 6744) # 尽可能狼群U47旗舰
return self.ze.change_ships()
class MissionEvent2(zrobot.Mission):
def __init__(self, ze: zemulator.ZjsnEmulator):
super().__init__('E9', 9940, ze)
# self.battle_fleet = [229, 370, 16523, 1410, 115, 43707]
self.battle_fleet = []
self.enable = True
def set_first_nodes(self):
self.node_a = self.node_chain([zrobot.Node('b', enemy_target=994003001),
zrobot.Node('f', node_type="skip"),
zrobot.Node('j', node_type="resource"),
zrobot.Node('p'),
zrobot.Node(
'q', formation=4, night_flag=1),
])
return self.node_a
def prepare(self):
if self.boss_hp == 0:
return False
# fleet = [self.ze.userShip.name(name).id for name in self.battle_fleet]
if not self.battle_fleet:
self.battle_fleet = self.ze.working_ships_id
fleet = self.battle_fleet
fleet_group = [([i], 0.9, True) for i in fleet]
self.ze.ship_groups = fleet_group
return self.ze.change_ships()
def summery(self):
super().summery()
zrobot._logger.debug("boss hp={}".format(self.boss_hp))
class MissionEvent_ex(zrobot.Mission):
def __init__(self, ze: zemulator.ZjsnEmulator):
super().__init__('event_ex', 9951, ze)
self.battle_fleet = []
def set_first_nodes(self):
self.node_a = self.node_chain([zrobot.Node('b'),
zrobot.Node('g', node_type="resource"),
zrobot.Node('l', formation=5),
])
return self.node_a
def prepare(self):
# if 10029011 in self.ze.unlockShip:
# zrobot._logger.debug("有96了,告别ex")
# return False
# fleet = [self.ze.userShip.name(name).id for name in self.battle_fleet]
if not self.battle_fleet:
self.battle_fleet = self.ze.working_ships_id
fleet = self.battle_fleet
fleet_group = [([i], 0.85, True) for i in fleet]
self.ze.ship_groups = fleet_group
return self.ze.change_ships()
class MissionEvent_E7(zrobot.Mission):
def __init__(self, ze: zemulator.ZjsnEmulator):
super().__init__('e7', 9948, ze)
self.battle_fleet = [13598, 13664, 1519, 11872, 115, 43707]
# self.battle_fleet = []
def set_first_nodes(self):
self.node_a = self.node_chain([zrobot.Node('a', node_type='skip'),
zrobot.Node('d'),
zrobot.Node('i', node_type='resource'),
zrobot.Node('o', node_type='resource'),
zrobot.Node('r'),
])
self.node_a.add_next(zrobot.Node('c', formation=5))
self.node_a.skip_rate_limit = 0.8
return self.node_a
def prepare(self):
if 10015413 in self.ze.unlockShip:
zrobot._logger.debug("有勇敢了,告别E7")
return False
# fleet = [self.ze.userShip.name(name).id for name in self.battle_fleet]
if not self.battle_fleet:
self.battle_fleet = self.ze.working_ships_id
fleet = self.battle_fleet
fleet_group = [([i], 0.85, True) for i in fleet]
self.ze.ship_groups = fleet_group
return self.ze.change_ships()
class MissionEvent(zrobot.Mission):
event_base = 9959
event_num = 7
def __init__(self, ze: zemulator.ZjsnEmulator):
super().__init__('event', self.event_base + self.event_num, ze)
# [16523,229,1519,11872,115,43707]
self.battle_fleet = []
self.battle_fleet_name = ['吹雪', '信赖', '白雪', '绫波', '晓', '雷']
def set_first_nodes(self):
# temp = zrobot.Node.DEFAULT_SLEEP_TIME
# zrobot.Node.DEFAULT_SLEEP_TIME = 20
# self.ze.working_fleet = 3
self.node_q = zrobot.Node('q', night_flag=1)
self.node_n = zrobot.Node('n', night_flag=1, formation=4).add_next(self.node_q)
self.node_o = zrobot.Node('o', night_flag=1, formation=4).add_next(self.node_q)
self.node_a = self.node_chain([zrobot.Node('b'),
zrobot.Node('d', node_type='skip'),
zrobot.Node('h'),
# zrobot.Node('o', node_type=zrobot.NODE_SKIP),
zrobot.Node('k', node_type='skip'),
zrobot.Node('p', night_flag=1, formation=4),
[self.node_n, self.node_o],
])
# self.node_a.skip_rate_limit = 0.8
# zrobot.Node.DEFAULT_SLEEP_TIME = temp
return self.node_a
def prepare(self):
if self.boss_hp == 0:
return False
# fleet = [self.ze.userShip.name(name).id for name in self.battle_fleet]
if self.battle_fleet_name:
self.battle_fleet = [self.ze.userShip.name(name).id for name in self.battle_fleet_name]
if not self.battle_fleet:
self.battle_fleet = self.ze.working_ships_id
zrobot._logger.debug("current battle ships are : {}".format([s.name for s in self.ze.working_ships]))
fleet = self.battle_fleet
fleet_group = [([i], 0.85, True) for i in fleet]
self.ze.ship_groups = fleet_group
return self.ze.change_ships()
def summery(self):
super().summery()
zrobot._logger.debug("boss hp={}".format(self.boss_hp))
class ChinaRobot(zrobot.Robot):
def __init__(self):
super().__init__('junhongbill', 'ouzhoutiduzjsn')
self.ze.equipment_formula = [10, 90, 90, 30]
self.ze.boat_formula = [200, 30, 200, 30]
self.explore.explore_table = (
([11063, 329, 58584, 44607, 44538, 63100], '20002'),
([7367, 13972, 11497, 8452, 3822, 53932], '10004'),
([128, 14094, 113, 101, 52334, 7373], '40001'),
([123, 13973, 10800, 53659, 10706, 104], '20001')
)
self.build_mission.plan = {
'乔治': [400, 80, 650, 101],
'莫斯科': [350, 130, 350, 130],
'斯维尔德洛夫': [200, 30, 200, 30],
'1405': [30, 30, 60, 30],
}
# self.campaign.mission_code = 102
# self.ze.unlocked_report()
# for ship in self.ze.userShip:
# n = ship.name.replace("日", "曰")
# if ship.nick_name != n:
# print("{} renamed to {}".format(ship.nick_name, ship.name))
# self.ze.rename_ship(ship.id, n)
def set_missions(self):
challenge = zrobot.Challenge(self.ze)
challenge.ninghai = 1215
challenge.friends = [2593850, 74851, 2827412]
self.add_mission(challenge)
self.add_mission(zrobot.TacticTrain_Campaign(self.ze))
self.add_mission(zrobot.TacticTrain(self.ze))
self.add_mission(Mission_6_3(self.ze))
self.add_mission(MissionEvent_ex(self.ze))
# self.add_mission(Mission_6_4_fish(self.ze))
# self.add_mission(Mission_5_2_C(self.ze))
# self.add_mission(Mission_2_5_mid(self.ze))
# self.add_mission(Mission_2_5_down(self.ze))
# self.add_mission(Mission_2_5_up(self.ze))
self.add_mission(Mission_5_5_C(self.ze))
self.add_mission(zrobot.Mission_1_1(self.ze))
# self.add_mission(Mission_4_3(self.ze))
# self.add_mission(Mission_2_2(self.ze))
# self.add_mission(Mission_5_5_B(self.ze))
self.add_mission(Mission_6_4(self.ze))
self.add_mission(MissionEvent(self.ze))
self.pants = MissionPants(self.ze)
self.add_mission(self.pants)
if __name__ == '__main__':
r = ChinaRobot()
# r.missions['event'].switch()
# r.missions['6-4'].switch()
# r.missions['pants'].switch()
# r.missions['5-5C'].enable = True
# r.missions['kill_fish'].switch()
# r.kill_fish.boss_ships = '无比'
# r.missions['TacticTrain'].switch()
# r.missions['TacticTrain_Campaign'].switch()
t = r.start()
| #!/usr/bin/env python3
import zemulator
import zrobot
# class Mission_6_1_A_China(zrobot.Mission_6_1_A):
# def __init__():
# self.boss_ships = '射水鱼'
class Mission_5_2_C(zrobot.Mission):
def __init__(self, ze: zemulator.ZjsnEmulator):
super(Mission_5_2_C, self).__init__('5-2C', 502, ze)
def set_first_nodes(self):
self.node_c = zrobot.Node('C', enemy_target='轻母')
self.node_f = zrobot.Node('F')
self.node_h = zrobot.Node('H')
self.node_i = zrobot.Node('I')
self.node_j = zrobot.Node(
'J', formation=4, night_flag=1, big_broken_protect=False)
self.node_c.add_next(self.node_f)
self.node_f.add_next([self.node_i, self.node_h])
self.node_i.add_next(self.node_j)
self.node_h.add_next(self.node_j)
return self.node_c
def prepare(self):
# 所有水下船只
if 10018811 in self.ze.unlockShip:
self.available = False
zrobot._logger.info('有北京风了,2-5已经毕业')
return
ss_ships = []
for ship in sorted(self.ze.userShip, key=lambda x: x["level"], reverse=True):
conditions = [ship["level"] > 1,
ship.type in ['潜艇', '炮潜'],
]
if all(conditions):
ss_ships.append(ship.id)
zrobot._logger.debug("ss_ships:{}".format(
[(self.ze.userShip[ship_id].name, self.ze.userShip[ship_id].level) for ship_id in ss_ships]))
for i in range(0, 6):
self.ze.ship_groups[i] = (ss_ships, 1, False)
self.ze.ship_groups[0][0].insert(
0, self.ze.userShip.name("U47").id) # 尽可能狼群U47旗舰
return self.ze.change_ships()
class Mission_2_5_mid(zrobot.Mission):
def __init__(self, ze: zemulator.ZjsnEmulator):
super(Mission_2_5_mid, self).__init__('2-5mid', 205, ze)
def set_first_nodes(self):
self.node_a = zrobot.Node('A')
self.node_b = zrobot.Node('B')
self.node_d = zrobot.Node('D', node_type='skip')
self.node_h = zrobot.Node('H', node_type='skip')
self.node_k = zrobot.Node('K', node_type='skip')
self.node_o = zrobot.Node('O', night_flag=1)
self.node_a.add_next(self.node_b)
self.node_b.add_next(self.node_d)
self.node_d.add_next(self.node_h)
self.node_h.add_next(self.node_k)
self.node_k.add_next(self.node_o)
return self.node_a
def prepare(self):
# 所有高级潜艇
if 10026711 in self.ze.unlockShip:
self.available = False
zrobot._logger.info('有岛风了,2-5中路已经毕业')
return
ss_ships = []
for ship in sorted(self.ze.userShip, key=lambda x: x["level"], reverse=True):
conditions = [ship["level"] > 60,
ship.type in ['潜艇'],
]
if all(conditions):
ss_ships.append(ship.id)
zrobot._logger.debug("ss_ships:{}".format(
[(self.ze.userShip[ship_id].name, self.ze.userShip[ship_id].level) for ship_id in ss_ships]))
taitai = [566, 115]
cv_ships = []
# 所有高速,高级航母
for ship in sorted(self.ze.userShip, key=lambda x: x["level"], reverse=True):
conditions = [ship["level"] > 75,
ship.type in ['航母', '装母'],
ship.speed > 30,
ship.id not in taitai,
]
if all(conditions):
cv_ships.append(ship.id)
cv_ships.extend(taitai)
zrobot._logger.debug("cv_ships:{}".format(
[(self.ze.userShip[ship_id].name, self.ze.userShip[ship_id].level) for ship_id in cv_ships]))
self.ze.ship_groups[0] = ([16523], 0.7, True) # 飙车胡德
self.ze.ship_groups[1] = self.ze.ship_groups[2] = (ss_ships, 0, False)
self.ze.ship_groups[3] = self.ze.ship_groups[5] = (
cv_ships, 0.7, False)
self.ze.ship_groups[4] = (taitai, 0.7, True)
# self.ze.ship_groups[3][0].insert(0,13664) # 大凤优先4号位置
self.ze.ship_groups[3] = ([13664], 0.7, True) # 大凤
self.ze.ship_groups[4] = ([115], 0.7, True) # 太太
self.ze.ship_groups[5] = ([43707], 0.7, True) # 加加
return self.ze.change_ships()
class Mission_5_5_C(zrobot.Mission):
def __init__(self, ze: zemulator.ZjsnEmulator):
super(Mission_5_5_C, self).__init__('5-5C', 505, ze)
def set_first_nodes(self):
self.node_c = zrobot.Node('C', formation=4, enemy_avoid=zemulator.ZjsnShip.type_id("轻巡"))
self.node_f = zrobot.Node('F')
self.node_i = zrobot.Node('I', formation=4, night_flag=1)
self.node_c.add_next(self.node_f)
self.node_f.add_next(self.node_i)
return self.node_c
def prepare(self):
# 所有90级以上水下船只
ss_ships = []
for ship in sorted(self.ze.userShip, key=lambda x: x["level"], reverse=True):
conditions = [ship["level"] >= 70,
ship.type in ['潜艇', '炮潜'],
]
if all(conditions):
ss_ships.append(ship.id)
ships = [self.ze.userShip[ship_id] for ship_id in ss_ships]
zrobot._logger.debug("ss_ships:{}".format(
[(s.name, s.level) for s in ships]))
for i in range(0, 6):
self.ze.ship_groups[i] = (ss_ships, 1, False)
self.ze.ship_groups[0][0].insert(
0, self.ze.userShip.name("U47").id) # 尽可能狼群U47旗舰
return self.ze.change_ships()
class Mission_5_5_B(zrobot.Mission):
def __init__(self, ze: zemulator.ZjsnEmulator):
super(Mission_5_5_B, self).__init__('5-5B', 505, ze)
def set_first_nodes(self):
self.node_b = zrobot.Node(
'B', additional_spy_filter=lambda sr: '战巡' in str(sr) or '雷巡' in str(sr))
return self.node_b
def prepare(self):
boss_ships = [9210, 5324] # 牛仔级
cv_ship = [43707]
# 所有改造后的ca, 等级从低到高
ca_ships = []
for ship in sorted(self.ze.userShip, key=lambda x: x["level"], reverse=False):
conditions = [ship["level"] < 100,
ship.type in ['重巡'],
ship.evolved,
]
if all(conditions):
ca_ships.append(ship.id)
ships = [self.ze.userShip[ship_id] for ship_id in ca_ships]
zrobot._logger.debug("ca_ships:{}".format(
[(s.name, s.level) for s in ships]))
for i in range(1, 5):
self.ze.ship_groups[i] = (ca_ships, 1, False)
self.ze.ship_groups[0] = (boss_ships, 1, True)
self.ze.ship_groups[5] = (cv_ship, 1, True)
return self.ze.change_ships()
class Mission_2_5_up(zrobot.Mission):
def __init__(self, ze: zemulator.ZjsnEmulator):
super(Mission_2_5_up, self).__init__('2-5-up', 205, ze)
def set_first_nodes(self):
self.node_a = self.node_chain([zrobot.Node('A', enemy_avoid='20502003'),
zrobot.Node('B'),
zrobot.Node('c', node_type='resource').add_next(
zrobot.Node('g').add_next(
zrobot.Node('j', night_flag=1, formation=4))),
zrobot.Node('f'),
zrobot.Node(
'j', night_flag=1, formation=4),
])
return self.node_a
def prepare(self):
if 10010213 in self.ze.unlockShip:
zrobot._logger.debug('有陆奥了')
return False
# 所有高级潜艇
ss_ships = []
for ship in sorted(self.ze.userShip, key=lambda x: x["level"], reverse=True):
conditions = [ship["level"] > 60,
ship.type in ['潜艇'],
]
if all(conditions):
ss_ships.append(ship.id)
zrobot._logger.debug("ss_ships:{}".format(
[(self.ze.userShip[ship_id].name, self.ze.userShip[ship_id].level) for ship_id in ss_ships]))
for i in range(1, 4):
self.ze.ship_groups[i] = (ss_ships, 0, False)
self.ze.ship_groups[0] = ([43014], 0.8, True)
self.ze.ship_groups[4] = ([115], 0.8, True)
self.ze.ship_groups[5] = ([43707], 0.8, True)
return self.ze.change_ships()
class Mission_2_5_down(zrobot.Mission):
def __init__(self, ze: zemulator.ZjsnEmulator):
super(Mission_2_5_down, self).__init__('2-5down', 205, ze)
def set_first_nodes(self):
self.node_a = zrobot.Node('A', additional_spy_filter=lambda sr: len(
sr['enemyVO']['enemyShips']) == 5)
# self.node_a = Node('A', node_type='skip')
self.node_b = zrobot.Node('B')
self.node_e = zrobot.Node('E', node_type='resource')
self.node_i = zrobot.Node('I')
self.node_l = zrobot.Node('L', night_flag=1, formation=4)
self.node_m = zrobot.Node('M', night_flag=1, formation=4)
self.node_n = zrobot.Node('N', night_flag=1, formation=4)
self.node_a.add_next(self.node_b)
self.node_b.add_next(self.node_e)
self.node_e.add_next(self.node_i)
# self.node_i.add_next(self.node_l) # 不用去了,苍龙有了
# self.node_i.add_next(self.node_m) # 不用去了,比睿有了
self.node_i.add_next(self.node_n)
return self.node_a
def prepare(self):
# 所有能开幕的水下船只
ss_ships = []
for ship in sorted(self.ze.userShip, key=lambda x: x["level"], reverse=True):
conditions = [ship["level"] > 11,
ship.type in ['潜艇', '炮潜'],
]
if all(conditions):
ss_ships.append(ship.id)
ships = [self.ze.userShip[ship_id] for ship_id in ss_ships]
zrobot._logger.debug("ss_ships:{}".format(
[(s.name, s.level) for s in ships]))
for i in range(0, 6):
self.ze.ship_groups[i] = (ss_ships, 0, False)
self.ze.ship_groups[0][0].insert(0, 6744) # 尽可能狼群U47旗舰
return self.ze.change_ships()
class Mission_6_3(zrobot.Mission):
def __init__(self, ze: zemulator.ZjsnEmulator):
super(Mission_6_3, self).__init__('6-3', 603, ze)
def set_first_nodes(self):
self.node_b = zrobot.Node(
'B', enemy_target=zemulator.ZjsnShip.type_id('重巡'), formation=4)
# self.node_a = Node('A', node_type='skip')
self.node_e = zrobot.Node('E', formation=4)
self.node_h = zrobot.Node('H', formation=4)
self.node_j = zrobot.Node('J', formation=4, night_flag=1)
self.node_b.add_next(self.node_e)
self.node_e.add_next(self.node_h)
self.node_h.add_next(self.node_j)
return self.node_b
def prepare(self):
if 10030812 in self.ze.unlockShip and 10021811 in self.ze.unlockShip:
zrobot._logger.info('有哥特兰和古斯塔夫了')
return False
# 所有能开幕的水下船只
ss_ships = []
for ship in sorted(self.ze.userShip, key=lambda x: x["level"], reverse=True):
conditions = [ship["level"] > 75,
ship.type in ['潜艇', '炮潜'],
]
if all(conditions):
ss_ships.append(ship.id)
ships = [self.ze.userShip[ship_id] for ship_id in ss_ships]
zrobot._logger.debug("ss_ships:{}".format(
[(s.name, s.level) for s in ships]))
for i in range(0, 6):
self.ze.ship_groups[i] = (ss_ships, 0, False)
self.ze.ship_groups[0][0].insert(0, 6744) # 尽可能狼群U47旗舰
return self.ze.change_ships()
class MissionPants(zrobot.Mission):
""""""
def __init__(self, ze: zemulator.ZjsnEmulator):
super(MissionPants, self).__init__('pants', 201, ze)
self.pants_num = 0
self.pants_yesterday = 20
self.enable = True
self.last_pants_time = self.ze.now
def set_first_nodes(self):
self.node_b = zrobot.Node('B', node_type='resource')
self.node_d = zrobot.Node('D', node_type='resource')
self.node_f = zrobot.Node(
'F', night_flag=1, enemy_target=zemulator.ZjsnShip.type_id('补给'))
self.node_b.add_next(self.node_d)
self.node_d.add_next(self.node_f)
return self.node_b
@property
def pants_available(self):
now = self.ze.now
if self.last_pants_time < self.ze.now.replace(hour=0, minute=0, second=0) < now:
self.pants_yesterday = self.ze.spoils
return self.ze.spoils_event and self.ze.todaySpoilsNum < 50
def prepare(self):
if not self.pants_available:
self.available = False
return
if self.count > 100:
zrobot._logger.warning('pants {}, SL {}'.format(
self.ze.todaySpoilsNum, self.count))
# 所有高级改造DD
dd_ships = []
for ship in sorted(self.ze.userShip, key=lambda x: x["level"], reverse=False):
conditions = [ship["level"] > 80,
ship.type in ['驱逐'],
ship.evolved == 1,
]
if all(conditions):
dd_ships.append(ship.id)
ships = [self.ze.userShip[ship_id] for ship_id in dd_ships]
zrobot._logger.debug("dd_ships:{}".format(
[(s.name, s.level) for s in ships]))
# 所有高级改造cv
cv_ships = []
for ship in sorted(self.ze.userShip, key=lambda x: x["level"], reverse=False):
conditions = [ship.type in ['航母'],
ship.level > 1,
ship.evolved == 1 or not ship.can_evo,
]
if all(conditions):
cv_ships.append(ship.id)
ships = [self.ze.userShip[ship_id] for ship_id in cv_ships]
zrobot._logger.debug("cv_ships:{}".format(
[(s.name, s.level) for s in ships]))
self.ze.ship_groups = [()]*6
for i in range(0, 4):
self.ze.ship_groups[i] = (dd_ships, 1, False)
for i in range(2, 4):
self.ze.ship_groups[i] = (cv_ships, 1, False)
# self.ze.ship_groups[2] = ([self.ze.userShip.name("约克城").id], 1, True)
self.ze.ship_groups[4] = self.ze.ship_groups[5] = (None, 1, False)
return self.ze.change_ships()
def summery(self):
if self.success:
zrobot._logger.info("{} SL {} 次, 共捞{}胖次, result:{}".format(
self.mission_name, self.count,
self.ze.todaySpoilsNum + 1,
[(i.name, i.level) for i in self.ze.working_ships]))
self.count = 0
self.last_pants_time = self.ze.now
class Mission_4_3(zrobot.Mission):
"""一次45铝,一小时2700铝,再见了,远征铝"""
def __init__(self, ze: zemulator.ZjsnEmulator):
super().__init__('偷铝', 403, ze)
def set_first_nodes(self):
self.node_b = zrobot.Node('B')
self.node_d = zrobot.Node('D', node_type='resource')
self.node_b.add_next(self.node_d)
self.aluminum = 0
return self.node_b
def prepare(self):
# 所有高级改造DD
dd_ships = []
for ship in sorted(self.ze.userShip, key=lambda x: x["level"], reverse=False):
conditions = [ship["level"] > 80,
ship.type in ['驱逐'],
ship.evolved == 1,
]
if all(conditions):
dd_ships.append(ship.id)
ships = [self.ze.userShip[ship_id] for ship_id in dd_ships]
zrobot._logger.debug("dd_ships:{}".format(
[(s.name, s.level) for s in ships]))
self.ze.ship_groups[0] = (dd_ships, 0, False) # 旗舰必须是完好的防止大破
for i in range(1, 4):
self.ze.ship_groups[i] = (dd_ships, 1, False)
self.ze.ship_groups[4] = self.ze.ship_groups[5] = (None, 1, False)
return self.ze.change_ships()
def summery(self):
super().summery()
if self.success:
if 'userResVo' in self.node_d.battle_result:
zrobot._logger.info("资源: 油:{0[oil]:<7} 弹:{0[ammo]:<7} 钢:{0[steel]:<7} 铝:{0[aluminium]:<7}".format(
self.node_d.battle_result['userResVo']))
class Mission_5_3(zrobot.Mission):
"""一次45铝,一小时2700铝,再见了,远征铝"""
def __init__(self, ze: zemulator.ZjsnEmulator):
super().__init__('偷钢', 503, ze)
def set_first_nodes(self):
self.node_b = zrobot.Node('B')
self.node_d = zrobot.Node('D', node_type='resource')
self.node_b.add_next(self.node_d)
self.aluminum = 0
return self.node_b
def prepare(self):
# 所有高级DD
dd_ships = []
for ship in sorted(self.ze.userShip, key=lambda x: x["level"], reverse=False):
conditions = [ship["level"] > 80,
ship.type in ['驱逐'],
# ship.evolved == 1,
]
if all(conditions):
dd_ships.append(ship.id)
ships = [self.ze.userShip[ship_id] for ship_id in dd_ships]
zrobot._logger.debug("dd_ships:{}".format(
[(s.name, s.level) for s in ships]))
self.ze.ship_groups[0] = (dd_ships, 0, False) # 旗舰必须是完好的防止大破
for i in range(1, 4):
self.ze.ship_groups[i] = (dd_ships, 1, False)
self.ze.ship_groups[4] = self.ze.ship_groups[5] = (None, 1, False)
return self.ze.change_ships()
def summery(self):
super().summery()
if self.success:
if 'userResVo' in self.node_d.battle_result:
zrobot._logger.info("资源: 油:{0[oil]:<7} 弹:{0[ammo]:<7} 钢:{0[steel]:<7} 铝:{0[aluminium]:<7}".format(
self.node_d.battle_result['userResVo']))
class Mission_2_2(zrobot.Mission):
"""一次17油,一小时1000油,效率高于远征,大有可为"""
def __init__(self, ze: zemulator.ZjsnEmulator):
super().__init__('偷油', 202, ze)
def set_first_nodes(self):
self.node_a = zrobot.Node('A')
self.node_c = zrobot.Node('C', node_type='resource')
self.node_a.add_next(self.node_c)
return self.node_a
def prepare(self):
# 单DD偷油,擦伤就修,防止大破劝退
dd_ships = []
for ship in sorted(self.ze.userShip, key=lambda x: x["level"], reverse=False):
conditions = [ship["level"] > 80,
ship.type in ['驱逐'],
ship.evolved == 1,
]
if all(conditions):
dd_ships.append(ship.id)
ships = [self.ze.userShip[ship_id] for ship_id in dd_ships]
zrobot._logger.debug("dd_ships:{}".format(
[(s.name, s.level) for s in ships]))
for i in range(1, 6):
self.ze.ship_groups[i] = (None, 1, False)
self.ze.ship_groups[0] = (dd_ships, 0, False)
return self.ze.change_ships()
# class Mission_1_1(zrobot.Mission):
# def __init__(self, ze: zemulator.ZjsnEmulator):
# super(Mission_1_1, self).__init__('1-1A', 101, ze)
# def set_first_nodes(self):
# self.node_a = zrobot.Node('A')
# return self.node_a
# def prepare(self):
# # 所有高级改造DD
# dd_ships = []
# for ship in sorted(self.ze.userShip, key=lambda x: x["level"], reverse=True):
# conditions = [100 > ship["level"] > 20,
# ship.type in ['驱逐'],
# ship.evolved == 1,
# ]
# if all(conditions):
# dd_ships.append(ship.id)
# ships = [self.ze.userShip[ship_id] for ship_id in dd_ships]
# zrobot._logger.debug("dd_ships:{}".format(
# [(s.name, s.level) for s in ships]))
# for i in range(1, 6):
# self.ze.ship_groups[i] = (None, 1, False)
# self.ze.ship_groups[0] = (dd_ships, 1, False)
# try:
# self.ze.change_ships()
# except zemulator.ZjsnError:
# return False
# return True
class Mission_6_4(zrobot.Mission):
def __init__(self, ze: zemulator.ZjsnEmulator):
super(Mission_6_4, self).__init__('6-4', 604, ze)
self.pants_num = 0
def set_first_nodes(self):
self.node_a = self.node_chain([zrobot.Node('A', enemy_avoid=zemulator.ZjsnShip.type_id('战巡')),
zrobot.Node('B'),
zrobot.Node('e', enemy_avoid=zemulator.ZjsnShip.type_id('潜艇'), night_flag=1)])
return self.node_a
def prepare(self):
if 10023712 in self.ze.unlockShip:
zrobot._logger.debug('有昆特了')
return False
boss_ships = [s.id for s in self.ze.userShip if s.name ==
'赤城' and s.level > 80] # 赤城带队洗地
cv_ships = []
for ship in sorted(self.ze.userShip, key=lambda x: x["level"], reverse=True):
conditions = [20 < ship["level"] < 100,
ship.type in ['航母'],
ship.name not in ['突击者', '赤城'],
]
if all(conditions):
cv_ships.append(ship.id)
ships = [self.ze.userShip[ship_id] for ship_id in cv_ships]
zrobot._logger.debug("cv_ships:{}".format(
[(s.name, s.level) for s in ships]))
# 所有改造后的ca, 等级从低到高
ca_ships = []
for ship in sorted(self.ze.userShip, key=lambda x: x["level"], reverse=False):
conditions = [ship["level"] < 100,
ship.type in ['重巡'],
ship.evolved,
]
if all(conditions):
ca_ships.append(ship.id)
ships = [self.ze.userShip[ship_id] for ship_id in ca_ships]
zrobot._logger.debug("ca_ships:{}".format(
[(s.name, s.level) for s in ships]))
for i in range(0, 6):
self.ze.ship_groups[i] = (cv_ships, 1, True)
# boss_ships = cv_ships
self.ze.ship_groups[0] = (boss_ships, 1, True)
self.ze.ship_groups[1] = ([229], 1, True)
self.ze.ship_groups[2] = (ca_ships, 1, True)
return self.ze.change_ships()
class Mission_6_4_fish(zrobot.Mission):
def __init__(self, ze: zemulator.ZjsnEmulator):
super(Mission_6_4_fish, self).__init__('6-4 fish', 604, ze)
def set_first_nodes(self):
# self.node_a = Node('A', additional_spy_filter=lambda sr: '战巡' in str(sr) or '航母'in str(sr))
self.node_c = self.node_chain(
[zrobot.Node('c', formation=4, night_flag=1),
zrobot.Node('f', formation=4),
zrobot.Node('h'),
zrobot.Node('j', node_type="resource"),
zrobot.Node('l', enemy_target='20100003', formation=4),
]
)
self.node_b = self.node_chain([zrobot.Node('b', formation=4, night_flag=1),
zrobot.Node(
'd', formation=4, night_flag=1),
])
self.node_a = zrobot.Node('a', enemy_avoid=zemulator.ZjsnShip.type_id('驱逐'))
self.node_a.add_next(self.node_b)
self.node_a.add_next(self.node_c)
return self.node_a
def prepare(self):
target = 10023712
if target in self.ze.unlockShip:
zrobot._logger.info('有{}了'.format(
zemulator._INIT_DATA_.ship_card[target]["title"]))
return False
# 所有能开幕的水下船只
ss_ships = []
for ship in sorted(self.ze.userShip, key=lambda x: x["level"], reverse=True):
conditions = [ship["level"] > 75,
ship.type in ['潜艇', '炮潜'],
]
if all(conditions):
ss_ships.append(ship.id)
ships = [self.ze.userShip[ship_id] for ship_id in ss_ships]
zrobot._logger.debug("ss_ships:{}".format(
[(s.name, s.level) for s in ships]))
for i in range(0, 6):
self.ze.ship_groups[i] = (ss_ships, 0, False)
self.ze.ship_groups[0][0].insert(0, 6744) # 尽可能狼群U47旗舰
return self.ze.change_ships()
class MissionEvent2(zrobot.Mission):
def __init__(self, ze: zemulator.ZjsnEmulator):
super().__init__('E9', 9940, ze)
# self.battle_fleet = [229, 370, 16523, 1410, 115, 43707]
self.battle_fleet = []
self.enable = True
def set_first_nodes(self):
self.node_a = self.node_chain([zrobot.Node('b', enemy_target=994003001),
zrobot.Node('f', node_type="skip"),
zrobot.Node('j', node_type="resource"),
zrobot.Node('p'),
zrobot.Node(
'q', formation=4, night_flag=1),
])
return self.node_a
def prepare(self):
if self.boss_hp == 0:
return False
# fleet = [self.ze.userShip.name(name).id for name in self.battle_fleet]
if not self.battle_fleet:
self.battle_fleet = self.ze.working_ships_id
fleet = self.battle_fleet
fleet_group = [([i], 0.9, True) for i in fleet]
self.ze.ship_groups = fleet_group
return self.ze.change_ships()
def summery(self):
super().summery()
zrobot._logger.debug("boss hp={}".format(self.boss_hp))
class MissionEvent_ex(zrobot.Mission):
def __init__(self, ze: zemulator.ZjsnEmulator):
super().__init__('event_ex', 9951, ze)
self.battle_fleet = []
def set_first_nodes(self):
self.node_a = self.node_chain([zrobot.Node('b'),
zrobot.Node('g', node_type="resource"),
zrobot.Node('l', formation=5),
])
return self.node_a
def prepare(self):
# if 10029011 in self.ze.unlockShip:
# zrobot._logger.debug("有96了,告别ex")
# return False
# fleet = [self.ze.userShip.name(name).id for name in self.battle_fleet]
if not self.battle_fleet:
self.battle_fleet = self.ze.working_ships_id
fleet = self.battle_fleet
fleet_group = [([i], 0.85, True) for i in fleet]
self.ze.ship_groups = fleet_group
return self.ze.change_ships()
class MissionEvent_E7(zrobot.Mission):
def __init__(self, ze: zemulator.ZjsnEmulator):
super().__init__('e7', 9948, ze)
self.battle_fleet = [13598, 13664, 1519, 11872, 115, 43707]
# self.battle_fleet = []
def set_first_nodes(self):
self.node_a = self.node_chain([zrobot.Node('a', node_type='skip'),
zrobot.Node('d'),
zrobot.Node('i', node_type='resource'),
zrobot.Node('o', node_type='resource'),
zrobot.Node('r'),
])
self.node_a.add_next(zrobot.Node('c', formation=5))
self.node_a.skip_rate_limit = 0.8
return self.node_a
def prepare(self):
if 10015413 in self.ze.unlockShip:
zrobot._logger.debug("有勇敢了,告别E7")
return False
# fleet = [self.ze.userShip.name(name).id for name in self.battle_fleet]
if not self.battle_fleet:
self.battle_fleet = self.ze.working_ships_id
fleet = self.battle_fleet
fleet_group = [([i], 0.85, True) for i in fleet]
self.ze.ship_groups = fleet_group
return self.ze.change_ships()
class MissionEvent(zrobot.Mission):
event_base = 9959
event_num = 7
def __init__(self, ze: zemulator.ZjsnEmulator):
super().__init__('event', self.event_base + self.event_num, ze)
# [16523,229,1519,11872,115,43707]
self.battle_fleet = []
self.battle_fleet_name = ['吹雪', '信赖', '白雪', '绫波', '晓', '雷']
def set_first_nodes(self):
# temp = zrobot.Node.DEFAULT_SLEEP_TIME
# zrobot.Node.DEFAULT_SLEEP_TIME = 20
# self.ze.working_fleet = 3
self.node_q = zrobot.Node('q', night_flag=1)
self.node_n = zrobot.Node('n', night_flag=1, formation=4).add_next(self.node_q)
self.node_o = zrobot.Node('o', night_flag=1, formation=4).add_next(self.node_q)
self.node_a = self.node_chain([zrobot.Node('b'),
zrobot.Node('d', node_type='skip'),
zrobot.Node('h'),
# zrobot.Node('o', node_type=zrobot.NODE_SKIP),
zrobot.Node('k', node_type='skip'),
zrobot.Node('p', night_flag=1, formation=4),
[self.node_n, self.node_o],
])
# self.node_a.skip_rate_limit = 0.8
# zrobot.Node.DEFAULT_SLEEP_TIME = temp
return self.node_a
def prepare(self):
if self.boss_hp == 0:
return False
# fleet = [self.ze.userShip.name(name).id for name in self.battle_fleet]
if self.battle_fleet_name:
self.battle_fleet = [self.ze.userShip.name(name).id for name in self.battle_fleet_name]
if not self.battle_fleet:
self.battle_fleet = self.ze.working_ships_id
zrobot._logger.debug("current battle ships are : {}".format([s.name for s in self.ze.working_ships]))
fleet = self.battle_fleet
fleet_group = [([i], 0.85, True) for i in fleet]
self.ze.ship_groups = fleet_group
return self.ze.change_ships()
def summery(self):
super().summery()
zrobot._logger.debug("boss hp={}".format(self.boss_hp))
class ChinaRobot(zrobot.Robot):
def __init__(self):
super().__init__('junhongbill', 'ouzhoutiduzjsn')
self.ze.equipment_formula = [10, 90, 90, 30]
self.ze.boat_formula = [200, 30, 200, 30]
self.explore.explore_table = (
([11063, 329, 58584, 44607, 44538, 63100], '20002'),
([7367, 13972, 11497, 8452, 3822, 53932], '10004'),
([128, 14094, 113, 101, 52334, 7373], '40001'),
([123, 13973, 10800, 53659, 10706, 104], '20001')
)
self.build_mission.plan = {
'乔治': [400, 80, 650, 101],
'莫斯科': [350, 130, 350, 130],
'斯维尔德洛夫': [200, 30, 200, 30],
'1405': [30, 30, 60, 30],
}
# self.campaign.mission_code = 102
# self.ze.unlocked_report()
# for ship in self.ze.userShip:
# n = ship.name.replace("日", "曰")
# if ship.nick_name != n:
# print("{} renamed to {}".format(ship.nick_name, ship.name))
# self.ze.rename_ship(ship.id, n)
def set_missions(self):
challenge = zrobot.Challenge(self.ze)
challenge.ninghai = 1215
challenge.friends = [2593850, 74851, 2827412]
self.add_mission(challenge)
self.add_mission(zrobot.TacticTrain_Campaign(self.ze))
self.add_mission(zrobot.TacticTrain(self.ze))
self.add_mission(Mission_6_3(self.ze))
self.add_mission(MissionEvent_ex(self.ze))
# self.add_mission(Mission_6_4_fish(self.ze))
# self.add_mission(Mission_5_2_C(self.ze))
# self.add_mission(Mission_2_5_mid(self.ze))
# self.add_mission(Mission_2_5_down(self.ze))
# self.add_mission(Mission_2_5_up(self.ze))
self.add_mission(Mission_5_5_C(self.ze))
self.add_mission(zrobot.Mission_1_1(self.ze))
# self.add_mission(Mission_4_3(self.ze))
# self.add_mission(Mission_2_2(self.ze))
# self.add_mission(Mission_5_5_B(self.ze))
self.add_mission(Mission_6_4(self.ze))
self.add_mission(MissionEvent(self.ze))
self.pants = MissionPants(self.ze)
self.add_mission(self.pants)
if __name__ == '__main__':
r = ChinaRobot()
# r.missions['event'].switch()
# r.missions['6-4'].switch()
# r.missions['pants'].switch()
# r.missions['5-5C'].enable = True
# r.missions['kill_fish'].switch()
# r.kill_fish.boss_ships = '无比'
# r.missions['TacticTrain'].switch()
# r.missions['TacticTrain_Campaign'].switch()
t = r.start()
| en | 0.285746 | #!/usr/bin/env python3 # class Mission_6_1_A_China(zrobot.Mission_6_1_A): # def __init__(): # self.boss_ships = '射水鱼' # 所有水下船只 # 尽可能狼群U47旗舰 # 所有高级潜艇 # 所有高速,高级航母 # 飙车胡德 # self.ze.ship_groups[3][0].insert(0,13664) # 大凤优先4号位置 # 大凤 # 太太 # 加加 # 所有90级以上水下船只 # 尽可能狼群U47旗舰 # 牛仔级 # 所有改造后的ca, 等级从低到高 # 所有高级潜艇 # self.node_a = Node('A', node_type='skip') # self.node_i.add_next(self.node_l) # 不用去了,苍龙有了 # self.node_i.add_next(self.node_m) # 不用去了,比睿有了 # 所有能开幕的水下船只 # 尽可能狼群U47旗舰 # self.node_a = Node('A', node_type='skip') # 所有能开幕的水下船只 # 尽可能狼群U47旗舰 # 所有高级改造DD # 所有高级改造cv # self.ze.ship_groups[2] = ([self.ze.userShip.name("约克城").id], 1, True) 一次45铝,一小时2700铝,再见了,远征铝 # 所有高级改造DD # 旗舰必须是完好的防止大破 一次45铝,一小时2700铝,再见了,远征铝 # 所有高级DD # ship.evolved == 1, # 旗舰必须是完好的防止大破 一次17油,一小时1000油,效率高于远征,大有可为 # 单DD偷油,擦伤就修,防止大破劝退 # class Mission_1_1(zrobot.Mission): # def __init__(self, ze: zemulator.ZjsnEmulator): # super(Mission_1_1, self).__init__('1-1A', 101, ze) # def set_first_nodes(self): # self.node_a = zrobot.Node('A') # return self.node_a # def prepare(self): # # 所有高级改造DD # dd_ships = [] # for ship in sorted(self.ze.userShip, key=lambda x: x["level"], reverse=True): # conditions = [100 > ship["level"] > 20, # ship.type in ['驱逐'], # ship.evolved == 1, # ] # if all(conditions): # dd_ships.append(ship.id) # ships = [self.ze.userShip[ship_id] for ship_id in dd_ships] # zrobot._logger.debug("dd_ships:{}".format( # [(s.name, s.level) for s in ships])) # for i in range(1, 6): # self.ze.ship_groups[i] = (None, 1, False) # self.ze.ship_groups[0] = (dd_ships, 1, False) # try: # self.ze.change_ships() # except zemulator.ZjsnError: # return False # return True # 赤城带队洗地 # 所有改造后的ca, 等级从低到高 # boss_ships = cv_ships # self.node_a = Node('A', additional_spy_filter=lambda sr: '战巡' in str(sr) or '航母'in str(sr)) # 所有能开幕的水下船只 # 尽可能狼群U47旗舰 # self.battle_fleet = [229, 370, 16523, 1410, 115, 43707] # fleet = [self.ze.userShip.name(name).id for name in self.battle_fleet] # if 10029011 in self.ze.unlockShip: # zrobot._logger.debug("有96了,告别ex") # return False # fleet = [self.ze.userShip.name(name).id for name in self.battle_fleet] # self.battle_fleet = [] # fleet = [self.ze.userShip.name(name).id for name in self.battle_fleet] # [16523,229,1519,11872,115,43707] # temp = zrobot.Node.DEFAULT_SLEEP_TIME # zrobot.Node.DEFAULT_SLEEP_TIME = 20 # self.ze.working_fleet = 3 # zrobot.Node('o', node_type=zrobot.NODE_SKIP), # self.node_a.skip_rate_limit = 0.8 # zrobot.Node.DEFAULT_SLEEP_TIME = temp # fleet = [self.ze.userShip.name(name).id for name in self.battle_fleet] # self.campaign.mission_code = 102 # self.ze.unlocked_report() # for ship in self.ze.userShip: # n = ship.name.replace("日", "曰") # if ship.nick_name != n: # print("{} renamed to {}".format(ship.nick_name, ship.name)) # self.ze.rename_ship(ship.id, n) # self.add_mission(Mission_6_4_fish(self.ze)) # self.add_mission(Mission_5_2_C(self.ze)) # self.add_mission(Mission_2_5_mid(self.ze)) # self.add_mission(Mission_2_5_down(self.ze)) # self.add_mission(Mission_2_5_up(self.ze)) # self.add_mission(Mission_4_3(self.ze)) # self.add_mission(Mission_2_2(self.ze)) # self.add_mission(Mission_5_5_B(self.ze)) # r.missions['event'].switch() # r.missions['6-4'].switch() # r.missions['pants'].switch() # r.missions['5-5C'].enable = True # r.missions['kill_fish'].switch() # r.kill_fish.boss_ships = '无比' # r.missions['TacticTrain'].switch() # r.missions['TacticTrain_Campaign'].switch() | 2.527457 | 3 |
pelicanconf.py | schryer/schryer_pelican_blog | 0 | 6618945 | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = u'<NAME>'
SITENAME = u'<NAME>'
SITEURL = 'schryer_pelican_blog'
CUSTOM_ARTICLE_SHARING = 'sharing.html'
CUSTOM_ARTICLE_SCRIPTS = 'sharing_scripts.html'
TIMEZONE = 'Europe/Tallinn'
DEFAULT_LANG = u'en'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = None
CATEGORY_FEED_ATOM = None
TRANSLATION_FEED_ATOM = None
# Blogroll
#LINKS = (('Pelican', 'http://getpelican.com/'),
# ('Python.org', 'http://python.org/'),
# ('Jinja2', 'http://jinja.pocoo.org/'),
# ('You can modify those links in your config file', '#'),)
# Social widget
#SOCIAL = (('You can add links in your config file', '#'),
# ('Another social link', '#'),)
DEFAULT_PAGINATION = 10
# Uncomment following line if you want document-relative URLs when developing
#RELATIVE_URLS = True
THEME = 'pelican-themes/subtle'
MARKUP = ['md', 'ipynb']
DISPLAY_CATEGORIES_ON_MENU = True
PLUGIN_PATHS = ['pelican-plugins',]
PLUGINS = ['render_math', 'ipynb']
| #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = u'<NAME>'
SITENAME = u'<NAME>'
SITEURL = 'schryer_pelican_blog'
CUSTOM_ARTICLE_SHARING = 'sharing.html'
CUSTOM_ARTICLE_SCRIPTS = 'sharing_scripts.html'
TIMEZONE = 'Europe/Tallinn'
DEFAULT_LANG = u'en'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = None
CATEGORY_FEED_ATOM = None
TRANSLATION_FEED_ATOM = None
# Blogroll
#LINKS = (('Pelican', 'http://getpelican.com/'),
# ('Python.org', 'http://python.org/'),
# ('Jinja2', 'http://jinja.pocoo.org/'),
# ('You can modify those links in your config file', '#'),)
# Social widget
#SOCIAL = (('You can add links in your config file', '#'),
# ('Another social link', '#'),)
DEFAULT_PAGINATION = 10
# Uncomment following line if you want document-relative URLs when developing
#RELATIVE_URLS = True
THEME = 'pelican-themes/subtle'
MARKUP = ['md', 'ipynb']
DISPLAY_CATEGORIES_ON_MENU = True
PLUGIN_PATHS = ['pelican-plugins',]
PLUGINS = ['render_math', 'ipynb']
| en | 0.536802 | #!/usr/bin/env python # -*- coding: utf-8 -*- # # Feed generation is usually not desired when developing # Blogroll #LINKS = (('Pelican', 'http://getpelican.com/'), # ('Python.org', 'http://python.org/'), # ('Jinja2', 'http://jinja.pocoo.org/'), # ('You can modify those links in your config file', '#'),) # Social widget #SOCIAL = (('You can add links in your config file', '#'), # ('Another social link', '#'),) # Uncomment following line if you want document-relative URLs when developing #RELATIVE_URLS = True | 1.711347 | 2 |
setup.py | RheingoldRiver/lol_esports_parser | 1 | 6618946 | import setuptools
from os import path
this_directory = path.abspath(path.dirname(__file__))
with open(path.join(this_directory, "README.md"), encoding="utf-8") as f:
long_description = f.read()
setuptools.setup(
name="lol_esports_parser",
version="0.1a4",
packages=setuptools.find_packages(),
install_requires=[
"requests",
"dateparser",
"lol-id-tools>=1.4.0",
"riot-transmute>=0.1a6",
"lol-dto>=0.1a3",
"riotwatcher",
],
url="https://github.com/mrtolkien/lol_esports_parser",
license="MIT",
author='<NAME>',
author_email="<EMAIL>",
description="A utility to query and transform LoL games from QQ and ACS into the LolGame DTO format.",
long_description=long_description,
long_description_content_type="text/markdown",
)
| import setuptools
from os import path
this_directory = path.abspath(path.dirname(__file__))
with open(path.join(this_directory, "README.md"), encoding="utf-8") as f:
long_description = f.read()
setuptools.setup(
name="lol_esports_parser",
version="0.1a4",
packages=setuptools.find_packages(),
install_requires=[
"requests",
"dateparser",
"lol-id-tools>=1.4.0",
"riot-transmute>=0.1a6",
"lol-dto>=0.1a3",
"riotwatcher",
],
url="https://github.com/mrtolkien/lol_esports_parser",
license="MIT",
author='<NAME>',
author_email="<EMAIL>",
description="A utility to query and transform LoL games from QQ and ACS into the LolGame DTO format.",
long_description=long_description,
long_description_content_type="text/markdown",
)
| none | 1 | 1.758454 | 2 | |
scripts/britfonedict_to_json.py | md84419/English-to-IPA | 0 | 6618947 | <filename>scripts/britfonedict_to_json.py<gh_stars>0
#!/usr/bin/python
# USAGE:
# PYTHONPATH=".." python opendict_to_json.py ../eng_to_ipa/resources/Opendict_source_files/en_UK.txt > ../eng_to_ipa/resources/Open_dict.json
import csv, getopt, json, io, os, re, sys, subprocess
from signal import signal, SIGPIPE, SIG_DFL
signal(SIGPIPE, SIG_DFL)
def main(argv):
input_file = None
output_file = None
try:
opts, args = getopt.getopt(argv, "o:")
except getopt.GetoptError:
print( "{0}: syntax: [-o output.json] input.csv".format( sys.argv[0]) )
sys.exit(2)
for opt, arg in opts:
if opt == '-o':
output_file = arg
try:
input_file = args[0]
except:
print( "{0}: syntax: [-o output.json] input.csv".format( sys.argv[0]) )
sys.exit(2)
britfone_dict = {}
with open('../eng_to_ipa/resources/Britfone_source_files/britfone.main.3.0.1.csv', newline='') as csvfile:
reader = csv.reader(csvfile, delimiter=',', quotechar='|')
for rows in reader:
k = rows[0]
v = rows[1].strip()
# fix 3.0.1 source
if k == 'AYE(1)': k = 'AYE'
if k == 'YOB(1)': k = 'YOB'
if k == 'PROJECTS(2)': k = 'PROJECTS(1)'
if k == 'PROJECTS(3)': k = 'PROJECTS(2)'
k = k.lower()
v = v.lower().replace(' ', 'ˑ')
britfone_dict.update( {k: [v]} )
britfone_dict = fix_britfone( britfone_dict )
britfone_dict = fix_britfone_words( britfone_dict )
if( output_file != None ):
try:
with open(os.path.join(os.path.abspath(os.path.dirname(__file__)),
'..','eng_to_ipa','resources',output_file), 'wb') as o_fp:
json.dump( britfone_dict, o_fp, check_circular=True, indent=None, sort_keys=True, separators=[',\n', ':'], ensure_ascii=False )
sys.exit(0)
except TypeError:
pass
j = json.dumps( britfone_dict, check_circular=True, indent=None, separators=[',', ': '], sort_keys=True, ensure_ascii=False )
j = re.sub("{", "{\n", j)
j = re.sub("],", "],\n", j)
j = re.sub("]}", "]\n}", j)
print( j )
sys.exit(0)
def fix_britfone(source):
"""Add the IPA nobreak characters to the diphthongs, as these aren't present in the source file"""
destination = source
for key1 in destination:
for key2 in range( len( destination[key1] )):
# Map phonetic to phonemic
destination[key1][key2] = destination[key1][key2].replace("ˈɐ", "ˈʌ")
destination[key1][key2] = destination[key1][key2].replace("ˌɐ", "ˌʌ")
destination[key1][key2] = destination[key1][key2].replace("ɐ", "ʌ")
destination[key1][key2] = destination[key1][key2].replace("ɹ", "r")
destination[key1][key2] = destination[key1][key2].replace("ɹ", "r")
# Undo Upton's scheme (Oxford dictionary)
# See section 7 of https://www.phon.ucl.ac.uk/home/wells/ipa-english-uni.htm
# See also https://teflpedia.com/IPA_phoneme_/e%C9%99/ and related pages for the other symbols
destination[key1][key2] = destination[key1][key2].replace("ˈɛ", "ˈe")
destination[key1][key2] = destination[key1][key2].replace("ˌɛ", "ˌe")
destination[key1][key2] = destination[key1][key2].replace("ɛr", "eə")
destination[key1][key2] = destination[key1][key2].replace("ɛː", "eə")
destination[key1][key2] = destination[key1][key2].replace("ɛ", "e")
#mark the diphthongs with the non-breaking space character
destination[key1][key2] = destination[key1][key2].replace("aɪ", "aɪ")
destination[key1][key2] = destination[key1][key2].replace("aʊ", "aʊ")
destination[key1][key2] = destination[key1][key2].replace("dʒ", "dʒ")
destination[key1][key2] = destination[key1][key2].replace("eə", "eə")
destination[key1][key2] = destination[key1][key2].replace("eɪ", "eɪ")
destination[key1][key2] = destination[key1][key2].replace("iə", "iə")
destination[key1][key2] = destination[key1][key2].replace("tʃ", "tʃ")
destination[key1][key2] = destination[key1][key2].replace("ɔɪ", "ɔɪ")
destination[key1][key2] = destination[key1][key2].replace("əl", "əl")
destination[key1][key2] = destination[key1][key2].replace("əʊ", "əʊ")
destination[key1][key2] = destination[key1][key2].replace("ɛə", "ɛə")
destination[key1][key2] = destination[key1][key2].replace("ɪə", "ɪə")
destination[key1][key2] = destination[key1][key2].replace("ʊə", "ʊə")
# Use the standard (quantitative-qualitative) IPA notation scheme for vowels
# See section 5 of https://www.phon.ucl.ac.uk/home/wells/ipa-english-uni.htm
destination[key1][key2] = re.sub("ɑ(?!)", "ɑː", destination[key1][key2])
destination[key1][key2] = destination[key1][key2].replace("ɒː", "ɒ")
destination[key1][key2] = re.sub("i(?!)", "iː", destination[key1][key2])
destination[key1][key2] = re.sub("ɔ(?!)", "ɔː", destination[key1][key2])
destination[key1][key2] = re.sub("u(?!)", "uː", destination[key1][key2])
destination[key1][key2] = destination[key1][key2].replace("ːː", "ː")
# Change quadphthongs into 2x UK diphthongs
#destination[key1][key2] = destination[key1][key2].replace("eɪəʊ", "eɪ əʊ")
#destination[key1][key2] = destination[key1][key2].replace("ɔɪəʊ", "ɔɪ əʊ")
return destination
# fix whole words
def fix_britfone_words( dct ):
# change
dct.update({"loch": ["lˑˈɒˑx"]})
dct.update({"sewer": ["sˑˈʊə"]})
# remove
dct.pop('croissant', None)
dct.pop('with(2)', None)
dct.pop('with(4)', None)
dct.pop('years(2)', None)
# add
dct.update({"and(0)": ["nˑd"]})
dct.update({"uk": ["jˑuːˑkˑeɪ"]})
dct.update({"gb": ["dʒˑiːˑbˑiː"]})
dct.update({"years'": ["jˑˈɪəˑz"]})
dct.update({"years-old": ["jˑˈɪəˑzˑɔːˑlˑd"]})
dct.update({'light-years': ["ˈlˑaɪˑˌtˑjˑˈɪəˑz"]})
dct.update({'new-years': ["nˑjˑˈuːˑjˑˈɪəˑz"]})
dct.update({'thousand-years-long': ["ˈθˑaʊˑzˑəˑnˑˌdˑjˑˈɪəˑzˑˈlˑɔːˑŋ"]})
dct.update({'robotica': ["rˑˈəʊˑbˑˈɒˑtˑɪˑkˑʌ"]})
return dct
if( __name__ == "__main__"):
main(sys.argv[1:])
| <filename>scripts/britfonedict_to_json.py<gh_stars>0
#!/usr/bin/python
# USAGE:
# PYTHONPATH=".." python opendict_to_json.py ../eng_to_ipa/resources/Opendict_source_files/en_UK.txt > ../eng_to_ipa/resources/Open_dict.json
import csv, getopt, json, io, os, re, sys, subprocess
from signal import signal, SIGPIPE, SIG_DFL
signal(SIGPIPE, SIG_DFL)
def main(argv):
input_file = None
output_file = None
try:
opts, args = getopt.getopt(argv, "o:")
except getopt.GetoptError:
print( "{0}: syntax: [-o output.json] input.csv".format( sys.argv[0]) )
sys.exit(2)
for opt, arg in opts:
if opt == '-o':
output_file = arg
try:
input_file = args[0]
except:
print( "{0}: syntax: [-o output.json] input.csv".format( sys.argv[0]) )
sys.exit(2)
britfone_dict = {}
with open('../eng_to_ipa/resources/Britfone_source_files/britfone.main.3.0.1.csv', newline='') as csvfile:
reader = csv.reader(csvfile, delimiter=',', quotechar='|')
for rows in reader:
k = rows[0]
v = rows[1].strip()
# fix 3.0.1 source
if k == 'AYE(1)': k = 'AYE'
if k == 'YOB(1)': k = 'YOB'
if k == 'PROJECTS(2)': k = 'PROJECTS(1)'
if k == 'PROJECTS(3)': k = 'PROJECTS(2)'
k = k.lower()
v = v.lower().replace(' ', 'ˑ')
britfone_dict.update( {k: [v]} )
britfone_dict = fix_britfone( britfone_dict )
britfone_dict = fix_britfone_words( britfone_dict )
if( output_file != None ):
try:
with open(os.path.join(os.path.abspath(os.path.dirname(__file__)),
'..','eng_to_ipa','resources',output_file), 'wb') as o_fp:
json.dump( britfone_dict, o_fp, check_circular=True, indent=None, sort_keys=True, separators=[',\n', ':'], ensure_ascii=False )
sys.exit(0)
except TypeError:
pass
j = json.dumps( britfone_dict, check_circular=True, indent=None, separators=[',', ': '], sort_keys=True, ensure_ascii=False )
j = re.sub("{", "{\n", j)
j = re.sub("],", "],\n", j)
j = re.sub("]}", "]\n}", j)
print( j )
sys.exit(0)
def fix_britfone(source):
"""Add the IPA nobreak characters to the diphthongs, as these aren't present in the source file"""
destination = source
for key1 in destination:
for key2 in range( len( destination[key1] )):
# Map phonetic to phonemic
destination[key1][key2] = destination[key1][key2].replace("ˈɐ", "ˈʌ")
destination[key1][key2] = destination[key1][key2].replace("ˌɐ", "ˌʌ")
destination[key1][key2] = destination[key1][key2].replace("ɐ", "ʌ")
destination[key1][key2] = destination[key1][key2].replace("ɹ", "r")
destination[key1][key2] = destination[key1][key2].replace("ɹ", "r")
# Undo Upton's scheme (Oxford dictionary)
# See section 7 of https://www.phon.ucl.ac.uk/home/wells/ipa-english-uni.htm
# See also https://teflpedia.com/IPA_phoneme_/e%C9%99/ and related pages for the other symbols
destination[key1][key2] = destination[key1][key2].replace("ˈɛ", "ˈe")
destination[key1][key2] = destination[key1][key2].replace("ˌɛ", "ˌe")
destination[key1][key2] = destination[key1][key2].replace("ɛr", "eə")
destination[key1][key2] = destination[key1][key2].replace("ɛː", "eə")
destination[key1][key2] = destination[key1][key2].replace("ɛ", "e")
#mark the diphthongs with the non-breaking space character
destination[key1][key2] = destination[key1][key2].replace("aɪ", "aɪ")
destination[key1][key2] = destination[key1][key2].replace("aʊ", "aʊ")
destination[key1][key2] = destination[key1][key2].replace("dʒ", "dʒ")
destination[key1][key2] = destination[key1][key2].replace("eə", "eə")
destination[key1][key2] = destination[key1][key2].replace("eɪ", "eɪ")
destination[key1][key2] = destination[key1][key2].replace("iə", "iə")
destination[key1][key2] = destination[key1][key2].replace("tʃ", "tʃ")
destination[key1][key2] = destination[key1][key2].replace("ɔɪ", "ɔɪ")
destination[key1][key2] = destination[key1][key2].replace("əl", "əl")
destination[key1][key2] = destination[key1][key2].replace("əʊ", "əʊ")
destination[key1][key2] = destination[key1][key2].replace("ɛə", "ɛə")
destination[key1][key2] = destination[key1][key2].replace("ɪə", "ɪə")
destination[key1][key2] = destination[key1][key2].replace("ʊə", "ʊə")
# Use the standard (quantitative-qualitative) IPA notation scheme for vowels
# See section 5 of https://www.phon.ucl.ac.uk/home/wells/ipa-english-uni.htm
destination[key1][key2] = re.sub("ɑ(?!)", "ɑː", destination[key1][key2])
destination[key1][key2] = destination[key1][key2].replace("ɒː", "ɒ")
destination[key1][key2] = re.sub("i(?!)", "iː", destination[key1][key2])
destination[key1][key2] = re.sub("ɔ(?!)", "ɔː", destination[key1][key2])
destination[key1][key2] = re.sub("u(?!)", "uː", destination[key1][key2])
destination[key1][key2] = destination[key1][key2].replace("ːː", "ː")
# Change quadphthongs into 2x UK diphthongs
#destination[key1][key2] = destination[key1][key2].replace("eɪəʊ", "eɪ əʊ")
#destination[key1][key2] = destination[key1][key2].replace("ɔɪəʊ", "ɔɪ əʊ")
return destination
# fix whole words
def fix_britfone_words( dct ):
# change
dct.update({"loch": ["lˑˈɒˑx"]})
dct.update({"sewer": ["sˑˈʊə"]})
# remove
dct.pop('croissant', None)
dct.pop('with(2)', None)
dct.pop('with(4)', None)
dct.pop('years(2)', None)
# add
dct.update({"and(0)": ["nˑd"]})
dct.update({"uk": ["jˑuːˑkˑeɪ"]})
dct.update({"gb": ["dʒˑiːˑbˑiː"]})
dct.update({"years'": ["jˑˈɪəˑz"]})
dct.update({"years-old": ["jˑˈɪəˑzˑɔːˑlˑd"]})
dct.update({'light-years': ["ˈlˑaɪˑˌtˑjˑˈɪəˑz"]})
dct.update({'new-years': ["nˑjˑˈuːˑjˑˈɪəˑz"]})
dct.update({'thousand-years-long': ["ˈθˑaʊˑzˑəˑnˑˌdˑjˑˈɪəˑzˑˈlˑɔːˑŋ"]})
dct.update({'robotica': ["rˑˈəʊˑbˑˈɒˑtˑɪˑkˑʌ"]})
return dct
if( __name__ == "__main__"):
main(sys.argv[1:])
| en | 0.689982 | #!/usr/bin/python # USAGE: # PYTHONPATH=".." python opendict_to_json.py ../eng_to_ipa/resources/Opendict_source_files/en_UK.txt > ../eng_to_ipa/resources/Open_dict.json # fix 3.0.1 source Add the IPA nobreak characters to the diphthongs, as these aren't present in the source file # Map phonetic to phonemic # Undo Upton's scheme (Oxford dictionary) # See section 7 of https://www.phon.ucl.ac.uk/home/wells/ipa-english-uni.htm # See also https://teflpedia.com/IPA_phoneme_/e%C9%99/ and related pages for the other symbols #mark the diphthongs with the non-breaking space character # Use the standard (quantitative-qualitative) IPA notation scheme for vowels # See section 5 of https://www.phon.ucl.ac.uk/home/wells/ipa-english-uni.htm # Change quadphthongs into 2x UK diphthongs #destination[key1][key2] = destination[key1][key2].replace("eɪəʊ", "eɪ əʊ") #destination[key1][key2] = destination[key1][key2].replace("ɔɪəʊ", "ɔɪ əʊ") # fix whole words # change # remove # add | 2.639138 | 3 |
src/coalescenceml/artifacts/base_artifact.py | CornellDataScience/CoalescenceML | 1 | 6618948 | <filename>src/coalescenceml/artifacts/base_artifact.py
from typing import Any, Dict
from ml_metadata.proto import metadata_store_pb2
from tfx.types.artifact import Artifact, Property, PropertyType
from coalescenceml.artifacts.constants import (
DATATYPE_PROPERTY_KEY,
PRODUCER_PROPERTY_KEY,
)
DATATYPE_PROPERTY = Property(type=PropertyType.STRING)
PRODUCER_PROPERTY = Property(type=PropertyType.STRING)
class BaseArtifact(Artifact):
""" """
TYPE_NAME: str = "BaseArtifact"
PROPERTIES: Dict[str, Property] = {
DATATYPE_PROPERTY_KEY: DATATYPE_PROPERTY,
PRODUCER_PROPERTY_KEY: PRODUCER_PROPERTY,
}
MLMD_TYPE: Any = None
def __init__(self, *args: Any, **kwargs: Any) -> None:
""""""
self.validate_and_set_type()
super(BaseArtifact, self).__init__(*args, **kwargs)
@classmethod
def validate_and_set_type(cls) -> None:
"""Validate artifact and set type"""
type_name = cls.TYPE_NAME
if not isinstance(type_name, str):
raise ValueError(
f"The subclass {cls} must overrise TYPE_NAME attribute with a string type name (got {type_name} instead)"
)
# Create ml metadata artifact type
mlmd_artifact_type = metadata_store_pb2.ArtifactType()
mlmd_artifact_type.name = type_name # store the name
# Perform validation on properties
if cls.PROPERTIES:
if not isinstance(cls.PROPERTIES, dict):
raise ValueError(f"The subclass {cls}.PROPERTIES is not a dict")
for key, value in cls.PROPERTIES.items():
if not (isinstance(key, str) and isinstance(value, Property)):
raise ValueError(
f"The subclass {cls}.PROPERTIES dictionary must have keys of type string and values of type tfx.types.artifact.Property"
)
# Finally populate ML metadata properties
for key, value in cls.PROPERTIES.items():
mlmd_artifact_type.properties[key] = value.mlmd_type()
else:
raise ValueError("Empty properties dictionary!")
cls.MLMD_ARTIFACT_TYPE = mlmd_artifact_type
| <filename>src/coalescenceml/artifacts/base_artifact.py
from typing import Any, Dict
from ml_metadata.proto import metadata_store_pb2
from tfx.types.artifact import Artifact, Property, PropertyType
from coalescenceml.artifacts.constants import (
DATATYPE_PROPERTY_KEY,
PRODUCER_PROPERTY_KEY,
)
DATATYPE_PROPERTY = Property(type=PropertyType.STRING)
PRODUCER_PROPERTY = Property(type=PropertyType.STRING)
class BaseArtifact(Artifact):
""" """
TYPE_NAME: str = "BaseArtifact"
PROPERTIES: Dict[str, Property] = {
DATATYPE_PROPERTY_KEY: DATATYPE_PROPERTY,
PRODUCER_PROPERTY_KEY: PRODUCER_PROPERTY,
}
MLMD_TYPE: Any = None
def __init__(self, *args: Any, **kwargs: Any) -> None:
""""""
self.validate_and_set_type()
super(BaseArtifact, self).__init__(*args, **kwargs)
@classmethod
def validate_and_set_type(cls) -> None:
"""Validate artifact and set type"""
type_name = cls.TYPE_NAME
if not isinstance(type_name, str):
raise ValueError(
f"The subclass {cls} must overrise TYPE_NAME attribute with a string type name (got {type_name} instead)"
)
# Create ml metadata artifact type
mlmd_artifact_type = metadata_store_pb2.ArtifactType()
mlmd_artifact_type.name = type_name # store the name
# Perform validation on properties
if cls.PROPERTIES:
if not isinstance(cls.PROPERTIES, dict):
raise ValueError(f"The subclass {cls}.PROPERTIES is not a dict")
for key, value in cls.PROPERTIES.items():
if not (isinstance(key, str) and isinstance(value, Property)):
raise ValueError(
f"The subclass {cls}.PROPERTIES dictionary must have keys of type string and values of type tfx.types.artifact.Property"
)
# Finally populate ML metadata properties
for key, value in cls.PROPERTIES.items():
mlmd_artifact_type.properties[key] = value.mlmd_type()
else:
raise ValueError("Empty properties dictionary!")
cls.MLMD_ARTIFACT_TYPE = mlmd_artifact_type
| en | 0.627682 | Validate artifact and set type # Create ml metadata artifact type # store the name # Perform validation on properties # Finally populate ML metadata properties | 2.189423 | 2 |
pyads/adsdevice.py | turnerpeterk/pyads | 38 | 6618949 | <reponame>turnerpeterk/pyads<filename>pyads/adsdevice.py<gh_stars>10-100
import copy
import struct
from .adsclient import AdsClient
from .adsdatatype import AdsDatatype
from .adsconnection import AdsConnection
from .binaryparser import BinaryParser
class AdsDevice(AdsClient):
def __init__(self, adsConnection = None, amsTarget = None, amsSource = None, targetIP = None):
AdsClient.__init__(self, adsConnection, amsTarget, amsSource, targetIP)
def GetSymbolHandle(self, variableName):
symbolData = self.ReadWrite(0xF003, 0x0000, 4, variableName.encode('ascii') + b'\x00').Data
symbolHandle = struct.unpack("I", symbolData)[0]
return symbolHandle
def ReadByName(self, variableName, adsDatatype, length = None):
symbolHandle = self.GetSymbolHandle(variableName)
return self.ReadByHandle(symbolHandle, adsDatatype, length)
def ReadByHandle(self, symbolHandle, adsDatatype, length = None):
if length is None:
length = AdsDatatype.GetSize(adsDatatype)
data = self.Read(0xF005, symbolHandle, length).Data
return AdsDatatype.Unpack(data, adsDatatype)
def WriteByName(self, variableName, adsDatatype, value):
symbolHandle = self.GetSymbolHandle(variableName)
self.WriteByHandle(symbolHandle, adsDatatype, value)
def WriteByHandle(self, symbolHandle, adsDatatype, value):
valueRaw = AdsDatatype.Pack(value, adsDatatype)
self.Write(0xF005, symbolHandle, valueRaw)
| import copy
import struct
from .adsclient import AdsClient
from .adsdatatype import AdsDatatype
from .adsconnection import AdsConnection
from .binaryparser import BinaryParser
class AdsDevice(AdsClient):
def __init__(self, adsConnection = None, amsTarget = None, amsSource = None, targetIP = None):
AdsClient.__init__(self, adsConnection, amsTarget, amsSource, targetIP)
def GetSymbolHandle(self, variableName):
symbolData = self.ReadWrite(0xF003, 0x0000, 4, variableName.encode('ascii') + b'\x00').Data
symbolHandle = struct.unpack("I", symbolData)[0]
return symbolHandle
def ReadByName(self, variableName, adsDatatype, length = None):
symbolHandle = self.GetSymbolHandle(variableName)
return self.ReadByHandle(symbolHandle, adsDatatype, length)
def ReadByHandle(self, symbolHandle, adsDatatype, length = None):
if length is None:
length = AdsDatatype.GetSize(adsDatatype)
data = self.Read(0xF005, symbolHandle, length).Data
return AdsDatatype.Unpack(data, adsDatatype)
def WriteByName(self, variableName, adsDatatype, value):
symbolHandle = self.GetSymbolHandle(variableName)
self.WriteByHandle(symbolHandle, adsDatatype, value)
def WriteByHandle(self, symbolHandle, adsDatatype, value):
valueRaw = AdsDatatype.Pack(value, adsDatatype)
self.Write(0xF005, symbolHandle, valueRaw) | none | 1 | 2.65662 | 3 | |
common/src/stack/switch/command/list/switch/partition/__init__.py | knutsonchris/stacki | 0 | 6618950 | # @copyright@
# Copyright (c) 2006 - 2019 Teradata
# All rights reserved. Stacki(r) v5.x stacki.com
# https://github.com/Teradata/stacki/blob/master/LICENSE.txt
# @copyright@
import stack.commands
from stack.commands.sync.switch.ib import enforce_subnet_manager
from stack.exception import ArgRequired, ParamValue, CommandError
class Command(
stack.commands.Command,
stack.commands.SwitchArgumentProcessor,
):
"""
Lists the infiniband partitions in the Stacki database for one or more
switches.
<arg type='string' name='switch'>
The name of the switches to list partitions for.
</arg>
<param type='string' name='name' optional='1'>
The name of the partition to list on the switch(es).
</param>
<param type='boolean' name='enforce_sm' optional='1'>
If a switch is not an infiniband subnet manager an error will be raised.
</param>
"""
def run(self, params, args):
if not len(args):
raise ArgRequired(self, 'switch')
name, enforce_sm = self.fillParams([
('name', None),
('enforce_sm', False),
])
if name:
name = name.lower()
if name == 'default':
name = 'Default'
elif name != None:
try:
name = '0x{0:04x}'.format(int(name, 16))
except ValueError:
raise ParamValue(self, 'name', 'a hex value between 0x0001 and 0x7ffe, or "default"')
switches = self.getSwitchNames(args)
switch_attrs = self.getHostAttrDict(switches)
for switch in switches:
if switch_attrs[switch].get('switch_type') != 'infiniband':
raise CommandError(self, f'{switch} does not have a switch_type of "infiniband"')
if self.str2bool(enforce_sm):
enforce_subnet_manager(self, switches)
format_str = ','.join(['%s'] * len(switches))
sw_select = '''
nodes.name, ib.part_name, ib.part_key, ib.options
FROM nodes, ib_partitions ib
WHERE nodes.name IN (%s)
AND nodes.id=ib.switch''' % format_str
vals = list(switches)
if name:
sw_select += ' AND ib.part_name=%s'
vals.append(name)
sw_select += ' ORDER BY nodes.name'
self.beginOutput()
for line in self.db.select(sw_select, vals):
self.addOutput(line[0], (line[1], '0x{0:04x}'.format(line[2]), line[3]))
self.endOutput(header=['switch', 'partition', 'partition key', 'options'])
| # @copyright@
# Copyright (c) 2006 - 2019 Teradata
# All rights reserved. Stacki(r) v5.x stacki.com
# https://github.com/Teradata/stacki/blob/master/LICENSE.txt
# @copyright@
import stack.commands
from stack.commands.sync.switch.ib import enforce_subnet_manager
from stack.exception import ArgRequired, ParamValue, CommandError
class Command(
stack.commands.Command,
stack.commands.SwitchArgumentProcessor,
):
"""
Lists the infiniband partitions in the Stacki database for one or more
switches.
<arg type='string' name='switch'>
The name of the switches to list partitions for.
</arg>
<param type='string' name='name' optional='1'>
The name of the partition to list on the switch(es).
</param>
<param type='boolean' name='enforce_sm' optional='1'>
If a switch is not an infiniband subnet manager an error will be raised.
</param>
"""
def run(self, params, args):
if not len(args):
raise ArgRequired(self, 'switch')
name, enforce_sm = self.fillParams([
('name', None),
('enforce_sm', False),
])
if name:
name = name.lower()
if name == 'default':
name = 'Default'
elif name != None:
try:
name = '0x{0:04x}'.format(int(name, 16))
except ValueError:
raise ParamValue(self, 'name', 'a hex value between 0x0001 and 0x7ffe, or "default"')
switches = self.getSwitchNames(args)
switch_attrs = self.getHostAttrDict(switches)
for switch in switches:
if switch_attrs[switch].get('switch_type') != 'infiniband':
raise CommandError(self, f'{switch} does not have a switch_type of "infiniband"')
if self.str2bool(enforce_sm):
enforce_subnet_manager(self, switches)
format_str = ','.join(['%s'] * len(switches))
sw_select = '''
nodes.name, ib.part_name, ib.part_key, ib.options
FROM nodes, ib_partitions ib
WHERE nodes.name IN (%s)
AND nodes.id=ib.switch''' % format_str
vals = list(switches)
if name:
sw_select += ' AND ib.part_name=%s'
vals.append(name)
sw_select += ' ORDER BY nodes.name'
self.beginOutput()
for line in self.db.select(sw_select, vals):
self.addOutput(line[0], (line[1], '0x{0:04x}'.format(line[2]), line[3]))
self.endOutput(header=['switch', 'partition', 'partition key', 'options'])
| en | 0.463774 | # @copyright@ # Copyright (c) 2006 - 2019 Teradata # All rights reserved. Stacki(r) v5.x stacki.com # https://github.com/Teradata/stacki/blob/master/LICENSE.txt # @copyright@ Lists the infiniband partitions in the Stacki database for one or more switches. <arg type='string' name='switch'> The name of the switches to list partitions for. </arg> <param type='string' name='name' optional='1'> The name of the partition to list on the switch(es). </param> <param type='boolean' name='enforce_sm' optional='1'> If a switch is not an infiniband subnet manager an error will be raised. </param> nodes.name, ib.part_name, ib.part_key, ib.options FROM nodes, ib_partitions ib WHERE nodes.name IN (%s) AND nodes.id=ib.switch | 1.981786 | 2 |