Upload folder using huggingface_hub (part 106)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- pool/shard009/Python/0080493_devtools.py +166 -0
- pool/shard009/Python/0080496_cube_fit.py +101 -0
- pool/shard009/Python/0080501_influx_data_logger.py +122 -0
- pool/shard009/Python/0080505_generic.py +73 -0
- pool/shard009/Python/0080507_saphana.py +79 -0
- pool/shard009/Python/0080508_CMRToolkitWizardAntrumCutStep.py +102 -0
- pool/shard009/Python/0080509_classify_cascade.py +150 -0
- pool/shard009/Python/0080515_client.py +201 -0
- pool/shard009/Python/0080516_bookmark.py +43 -0
- pool/shard009/Python/0080519_fb_freq.py +124 -0
- pool/shard009/Python/0080520_transcript_orientations.py +171 -0
- pool/shard009/Python/0080521_layout_utils.py +109 -0
- pool/shard009/Python/0080522_demo.py +191 -0
- pool/shard009/Python/0080525_test_data_objects.py +187 -0
- pool/shard009/Python/0080526_base.py +111 -0
- pool/shard009/Python/0080531_daemon.py +92 -0
- pool/shard009/Python/0080535_info_ifaces.py +34 -0
- pool/shard009/Python/0080537_main.py +87 -0
- pool/shard009/Python/0080540_sflen.py +84 -0
- pool/shard009/Python/0080541_filter.py +60 -0
- pool/shard009/Python/0080551_encryption_usage.py +213 -0
- pool/shard009/Python/0080554_ca_trust.py +59 -0
- pool/shard009/Python/0080557_pressure.py +27 -0
- pool/shard009/Python/0080562_icpc.py +124 -0
- pool/shard009/Python/0080563_pack.py +113 -0
- pool/shard009/Python/0080564_test_disco_dynamodb.py +81 -0
- pool/shard009/Python/0080568_letnode.py +265 -0
- pool/shard009/Python/0080573_Problem4c.py +38 -0
- pool/shard009/Python/0080583_RBFN.py +69 -0
- pool/shard009/Python/0080585_LUV_extraction.py +55 -0
- pool/shard009/Python/0080590_FontConfig.py +149 -0
- pool/shard009/Python/0080593_mikrocliche03.py +90 -0
- pool/shard009/Python/0080594_validators.py +94 -0
- pool/shard009/Python/0080604_mbcharsetprober.py +95 -0
- pool/shard009/Python/0080614_importer.py +363 -0
- pool/shard009/Python/0080618_reg.py +94 -0
- pool/shard009/Python/0080620_BAMSequenceParser.py +153 -0
- pool/shard009/Python/0080623_test_collection_ops.py +90 -0
- pool/shard009/Python/0080624_0003_auto_20200224_1836.py +21 -0
- pool/shard009/Python/0080625_templite.py +228 -0
- pool/shard009/Python/0080626_instanceactions.py +264 -0
- pool/shard009/Python/0080633_member_event.py +19 -0
- pool/shard009/Python/0080644_file_loader.py +147 -0
- pool/shard009/Python/0080654_compareResult.py +172 -0
- pool/shard009/Python/0080657_ovirt_users.py +169 -0
- pool/shard009/Python/0080661_efficientnet_variants.py +135 -0
- pool/shard009/Python/0080663_scriptdocumentation.py +137 -0
- pool/shard009/Python/0080666_views.py +25 -0
- pool/shard009/Python/0080667_update.py +235 -0
- pool/shard009/Python/0080669_test_Server.py +74 -0
pool/shard009/Python/0080493_devtools.py
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
import sys
|
| 5 |
+
import re
|
| 6 |
+
import tempfile
|
| 7 |
+
|
| 8 |
+
from cement.core.foundation import CementApp
|
| 9 |
+
from cement.ext.ext_argparse import ArgparseController, expose
|
| 10 |
+
from cement.utils.version import get_version
|
| 11 |
+
from cement.utils import shell
|
| 12 |
+
|
| 13 |
+
VERSION = get_version()
|
| 14 |
+
|
| 15 |
+
class CementDevtoolsController(ArgparseController):
|
| 16 |
+
class Meta:
|
| 17 |
+
label = 'base'
|
| 18 |
+
arguments = [
|
| 19 |
+
(['-y, --noprompt'],
|
| 20 |
+
dict(help='answer yes to prompts.', action='store_true',
|
| 21 |
+
dest='noprompt')),
|
| 22 |
+
(['--ignore-errors'],
|
| 23 |
+
dict(help="don't stop operations because of errors",
|
| 24 |
+
action='store_true', dest='ignore_errors')),
|
| 25 |
+
(['--loud'], dict(help='add more verbose output',
|
| 26 |
+
action='store_true', dest='loud')),
|
| 27 |
+
]
|
| 28 |
+
|
| 29 |
+
def _do_error(self, msg):
|
| 30 |
+
if self.app.pargs.ignore_errors:
|
| 31 |
+
self.app.log.error(msg)
|
| 32 |
+
else:
|
| 33 |
+
raise Exception(msg)
|
| 34 |
+
|
| 35 |
+
@expose(hide=True)
|
| 36 |
+
def default(self):
|
| 37 |
+
raise AssertionError("A sub-command is required. See --help.")
|
| 38 |
+
|
| 39 |
+
def _do_git(self):
|
| 40 |
+
# make sure we don't have any uncommitted changes
|
| 41 |
+
print('Checking for Uncommitted Changes')
|
| 42 |
+
out, err, res = shell.exec_cmd(['git', '--no-pager', 'diff'])
|
| 43 |
+
if len(out) > 0:
|
| 44 |
+
self._do_error('There are uncommitted changes. See `git status`.')
|
| 45 |
+
|
| 46 |
+
# make sure we don't have any un-added files
|
| 47 |
+
print('Checking for Untracked Files')
|
| 48 |
+
out, err, res = shell.exec_cmd(['git', 'status'])
|
| 49 |
+
if re.match('Untracked files', str(out)):
|
| 50 |
+
self._do_error('There are untracked files. See `git status`.')
|
| 51 |
+
|
| 52 |
+
# make sure there isn't an existing tag
|
| 53 |
+
print("Checking for Duplicate Git Tag")
|
| 54 |
+
out, err, res = shell.exec_cmd(['git', 'tag'])
|
| 55 |
+
for ver in str(out).split('\n'):
|
| 56 |
+
if ver == VERSION:
|
| 57 |
+
self._do_error("Tag %s already exists" % VERSION)
|
| 58 |
+
|
| 59 |
+
print("Tagging Git Release")
|
| 60 |
+
out, err, res = shell.exec_cmd(['git', 'tag', '-a', '-m', VERSION,
|
| 61 |
+
VERSION])
|
| 62 |
+
if res > 0:
|
| 63 |
+
self._do_error("Unable to tag release with git.")
|
| 64 |
+
|
| 65 |
+
def _do_tests(self):
|
| 66 |
+
print('Running Nose Tests')
|
| 67 |
+
out, err, res = shell.exec_cmd(['which', 'nosetests'])
|
| 68 |
+
nose = out.decode('utf-8').strip()
|
| 69 |
+
if self.app.pargs.loud:
|
| 70 |
+
cmd_args = ['coverage', 'run', nose, '--verbosity=3']
|
| 71 |
+
res = shell.exec_cmd2(cmd_args)
|
| 72 |
+
else:
|
| 73 |
+
cmd_args = ['coverage', 'run', nose, '--verbosity=0']
|
| 74 |
+
out, err, res = shell.exec_cmd(cmd_args)
|
| 75 |
+
if res > 0:
|
| 76 |
+
self._do_error("\n\nNose tests did not pass.\n\n" +
|
| 77 |
+
"$ %s\n%s" % (' '.join(cmd_args), err))
|
| 78 |
+
|
| 79 |
+
def _do_flake8(self):
|
| 80 |
+
print("Checking Flake8 Compliance (pep8, pycodestyle, mccabe, etc)")
|
| 81 |
+
cmd_args = ['flake8', 'cement/']
|
| 82 |
+
out, err, res = shell.exec_cmd(cmd_args)
|
| 83 |
+
if res > 0:
|
| 84 |
+
self._do_error("\n\nFlake8 checks did not pass.\n\n" +
|
| 85 |
+
"$ %s\n%s" % (' '.join(cmd_args), str(out)))
|
| 86 |
+
|
| 87 |
+
@expose(help='run all unit tests')
|
| 88 |
+
def run_tests(self):
|
| 89 |
+
print('')
|
| 90 |
+
print('Python Version: %s' % sys.version)
|
| 91 |
+
print('')
|
| 92 |
+
print("Running Tests for Cement Version %s" % VERSION)
|
| 93 |
+
print('-' * 77)
|
| 94 |
+
self._do_flake8()
|
| 95 |
+
self._do_tests()
|
| 96 |
+
print('')
|
| 97 |
+
|
| 98 |
+
@expose(help='run flake8 tests')
|
| 99 |
+
def flake8(self):
|
| 100 |
+
self._do_flake8()
|
| 101 |
+
|
| 102 |
+
def _do_sphinx(self, dest_path):
|
| 103 |
+
print("Building Documentation")
|
| 104 |
+
cmd_args = ['rm', '-rf', 'docs/build/*']
|
| 105 |
+
cmd_args = ['sphinx-build', 'doc/source', dest_path]
|
| 106 |
+
out, err, res = shell.exec_cmd(cmd_args)
|
| 107 |
+
if res > 0:
|
| 108 |
+
self._do_error("\n\nFailed to build sphinx documentation\n\n" +
|
| 109 |
+
"$ %s\n%s" % (' '.join(cmd_args), str(out)))
|
| 110 |
+
|
| 111 |
+
@expose(help='create a cement release')
|
| 112 |
+
def make_release(self):
|
| 113 |
+
print('')
|
| 114 |
+
print("Making Release for Version %s" % VERSION)
|
| 115 |
+
print('-' * 77)
|
| 116 |
+
if not self.app.pargs.noprompt:
|
| 117 |
+
res = input("Continue? [yN] ")
|
| 118 |
+
if res not in ['Y', 'y', '1']:
|
| 119 |
+
sys.exit(1)
|
| 120 |
+
|
| 121 |
+
tmp = tempfile.mkdtemp()
|
| 122 |
+
print("Destination: %s" % tmp)
|
| 123 |
+
os.makedirs(os.path.join(tmp, 'source'))
|
| 124 |
+
os.makedirs(os.path.join(tmp, 'doc'))
|
| 125 |
+
|
| 126 |
+
self._do_flake8()
|
| 127 |
+
self._do_tests()
|
| 128 |
+
self._do_git()
|
| 129 |
+
self._do_sphinx(os.path.join(tmp, 'doc'))
|
| 130 |
+
|
| 131 |
+
tar_path = os.path.join(tmp, 'source', 'cement-%s.tar' % VERSION)
|
| 132 |
+
gzip_path = "%s.gz" % tar_path
|
| 133 |
+
|
| 134 |
+
print("Generating Release Files")
|
| 135 |
+
cmd_args = ['git', 'archive', VERSION,
|
| 136 |
+
'--prefix=cement-%s/' % VERSION,
|
| 137 |
+
'--output=%s' % tar_path]
|
| 138 |
+
out, err, res = shell.exec_cmd(cmd_args)
|
| 139 |
+
|
| 140 |
+
cmd_args = ['gzip', tar_path]
|
| 141 |
+
out, err, res = shell.exec_cmd(cmd_args)
|
| 142 |
+
if res > 0:
|
| 143 |
+
self._do_error("\n\nFailed generating git archive.\n\n" +
|
| 144 |
+
"$ %s" % (' '.join(cmd_args), err))
|
| 145 |
+
|
| 146 |
+
print('')
|
| 147 |
+
|
| 148 |
+
@expose(help='get the current version of the sources')
|
| 149 |
+
def get_version(self):
|
| 150 |
+
print(VERSION)
|
| 151 |
+
|
| 152 |
+
class CementDevtoolsApp(CementApp):
|
| 153 |
+
class Meta:
|
| 154 |
+
label = 'cement-devtools'
|
| 155 |
+
base_controller = CementDevtoolsController
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def main():
|
| 159 |
+
with CementDevtoolsApp() as app:
|
| 160 |
+
try:
|
| 161 |
+
app.run()
|
| 162 |
+
except AssertionError as e:
|
| 163 |
+
print("AssertionError => %s" % e.args[0])
|
| 164 |
+
|
| 165 |
+
if __name__ == '__main__':
|
| 166 |
+
main()
|
pool/shard009/Python/0080496_cube_fit.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Cube Fitting
|
| 3 |
+
============
|
| 4 |
+
|
| 5 |
+
Complicated code for fitting of a whole data cube, pixel-by-pixel
|
| 6 |
+
"""
|
| 7 |
+
import pyspeckit
|
| 8 |
+
try:
|
| 9 |
+
import astropy.io.fits as pyfits
|
| 10 |
+
except ImportError:
|
| 11 |
+
import pyfits
|
| 12 |
+
import numpy as np
|
| 13 |
+
import os
|
| 14 |
+
|
| 15 |
+
def cube_fit(cubefilename, outfilename, errfilename=None, scale_keyword=None,
|
| 16 |
+
vheight=False, verbose=False, signal_cut=3, verbose_level=2,
|
| 17 |
+
clobber=True, **kwargs):
|
| 18 |
+
"""
|
| 19 |
+
Light-weight wrapper for cube fitting
|
| 20 |
+
|
| 21 |
+
Takes a cube and error map (error will be computed naively if not given)
|
| 22 |
+
and computes moments then fits for each spectrum in the cube. It then
|
| 23 |
+
saves the fitted parameters to a reasonably descriptive output file whose
|
| 24 |
+
header will look like ::
|
| 25 |
+
|
| 26 |
+
PLANE1 = 'amplitude'
|
| 27 |
+
PLANE2 = 'velocity'
|
| 28 |
+
PLANE3 = 'sigma'
|
| 29 |
+
PLANE4 = 'err_amplitude'
|
| 30 |
+
PLANE5 = 'err_velocity'
|
| 31 |
+
PLANE6 = 'err_sigma'
|
| 32 |
+
PLANE7 = 'integral'
|
| 33 |
+
PLANE8 = 'integral_error'
|
| 34 |
+
CDELT3 = 1
|
| 35 |
+
CTYPE3 = 'FITPAR'
|
| 36 |
+
CRVAL3 = 0
|
| 37 |
+
CRPIX3 = 1
|
| 38 |
+
|
| 39 |
+
Parameters
|
| 40 |
+
----------
|
| 41 |
+
errfilename: [ None | string name of .fits file ]
|
| 42 |
+
A two-dimensional error map to use for computing signal-to-noise cuts
|
| 43 |
+
scale_keyword: [ None | Char ]
|
| 44 |
+
Keyword to pass to the data cube loader - multiplies cube by the number
|
| 45 |
+
indexed by this header kwarg if it exists. e.g., if your cube is in
|
| 46 |
+
T_A units and you want T_A*
|
| 47 |
+
vheight: [ bool ]
|
| 48 |
+
Is there a background to be fit? Used in moment computation
|
| 49 |
+
verbose: [ bool ]
|
| 50 |
+
verbose_level: [ int ]
|
| 51 |
+
How loud will the fitting procedure be? Passed to momenteach and fiteach
|
| 52 |
+
signal_cut: [ float ]
|
| 53 |
+
Signal-to-Noise ratio minimum. Spectra with a peak below this S/N ratio
|
| 54 |
+
will not be fit and will be left blank in the output fit parameter cube
|
| 55 |
+
clobber: [ bool ]
|
| 56 |
+
Overwrite parameter .fits cube if it exists?
|
| 57 |
+
|
| 58 |
+
`kwargs` are passed to :class:`pyspeckit.Spectrum.specfit`
|
| 59 |
+
"""
|
| 60 |
+
|
| 61 |
+
# Load the spectrum
|
| 62 |
+
sp = pyspeckit.Cube(cubefilename,scale_keyword=scale_keyword)
|
| 63 |
+
if os.path.exists(errfilename):
|
| 64 |
+
errmap = pyfits.getdata(errfilename)
|
| 65 |
+
else:
|
| 66 |
+
# very simple error calculation... biased and bad, needs improvement
|
| 67 |
+
# try using something from the cubes package
|
| 68 |
+
errmap = sp.cube.std(axis=0)
|
| 69 |
+
|
| 70 |
+
# Run the fitter
|
| 71 |
+
sp.mapplot()
|
| 72 |
+
|
| 73 |
+
# Compute the moments at each position to come up with reasonable guesses.
|
| 74 |
+
# This speeds up the process enormously, but can easily mess up the fits if
|
| 75 |
+
# there are bad pixels
|
| 76 |
+
sp.momenteach(vheight=vheight, verbose=verbose)
|
| 77 |
+
sp.fiteach(errmap=errmap, multifit=None, verbose_level=verbose_level,
|
| 78 |
+
signal_cut=signal_cut, usemomentcube=True, blank_value=np.nan,
|
| 79 |
+
verbose=verbose, **kwargs)
|
| 80 |
+
|
| 81 |
+
# steal the header from the error map
|
| 82 |
+
f = pyfits.open(cubefilename)
|
| 83 |
+
# start replacing components of the pyfits object
|
| 84 |
+
f[0].data = np.concatenate([sp.parcube,sp.errcube,sp.integralmap])
|
| 85 |
+
f[0].header['PLANE1'] = 'amplitude'
|
| 86 |
+
f[0].header['PLANE2'] = 'velocity'
|
| 87 |
+
f[0].header['PLANE3'] = 'sigma'
|
| 88 |
+
f[0].header['PLANE4'] = 'err_amplitude'
|
| 89 |
+
f[0].header['PLANE5'] = 'err_velocity'
|
| 90 |
+
f[0].header['PLANE6'] = 'err_sigma'
|
| 91 |
+
f[0].header['PLANE7'] = 'integral'
|
| 92 |
+
f[0].header['PLANE8'] = 'integral_error'
|
| 93 |
+
f[0].header['CDELT3'] = 1
|
| 94 |
+
f[0].header['CTYPE3'] = 'FITPAR'
|
| 95 |
+
f[0].header['CRVAL3'] = 0
|
| 96 |
+
f[0].header['CRPIX3'] = 1
|
| 97 |
+
# save your work
|
| 98 |
+
f.writeto(outfilename, clobber=clobber)
|
| 99 |
+
|
| 100 |
+
return sp
|
| 101 |
+
|
pool/shard009/Python/0080501_influx_data_logger.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""
|
| 3 |
+
A module to control the QO Raspberry Pi based H-Bridge hardware.
|
| 4 |
+
|
| 5 |
+
Qudi is free software: you can redistribute it and/or modify
|
| 6 |
+
it under the terms of the GNU General Public License as published by
|
| 7 |
+
the Free Software Foundation, either version 3 of the License, or
|
| 8 |
+
(at your option) any later version.
|
| 9 |
+
|
| 10 |
+
Qudi is distributed in the hope that it will be useful,
|
| 11 |
+
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
| 12 |
+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
| 13 |
+
GNU General Public License for more details.
|
| 14 |
+
|
| 15 |
+
You should have received a copy of the GNU General Public License
|
| 16 |
+
along with Qudi. If not, see <http://www.gnu.org/licenses/>.
|
| 17 |
+
|
| 18 |
+
Copyright (c) the Qudi Developers. See the COPYRIGHT.txt file at the
|
| 19 |
+
top-level directory of this distribution and at <https://github.com/Ulm-IQO/qudi/>
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
from core.base import Base
|
| 23 |
+
from interface.data_logger_interface import DataLoggerInterface
|
| 24 |
+
|
| 25 |
+
from influxdb import InfluxDBClient
|
| 26 |
+
|
| 27 |
+
class InfluxLogger(Base, DataLoggerInterface):
|
| 28 |
+
""" Log instrument values to InfluxDB.
|
| 29 |
+
"""
|
| 30 |
+
_modclass = 'InfluxLogger'
|
| 31 |
+
_modtype = 'hardware'
|
| 32 |
+
|
| 33 |
+
def __init__(self, **kwargs):
|
| 34 |
+
super().__init__(**kwargs)
|
| 35 |
+
self.log_channels = {}
|
| 36 |
+
|
| 37 |
+
def on_activate(self):
|
| 38 |
+
""" Activate module.
|
| 39 |
+
"""
|
| 40 |
+
config = self.getConfiguration()
|
| 41 |
+
|
| 42 |
+
if 'user' in config:
|
| 43 |
+
self.user = config['user']
|
| 44 |
+
|
| 45 |
+
if 'password' in config:
|
| 46 |
+
self.pw = config['password']
|
| 47 |
+
|
| 48 |
+
if 'dbname' in config:
|
| 49 |
+
self.dbname = config['dbname']
|
| 50 |
+
|
| 51 |
+
if 'host' in config:
|
| 52 |
+
self.host = config['host']
|
| 53 |
+
|
| 54 |
+
if 'port' in config:
|
| 55 |
+
self.port = config['port']
|
| 56 |
+
else:
|
| 57 |
+
self.port = 8086
|
| 58 |
+
|
| 59 |
+
if 'dataseries' in config:
|
| 60 |
+
self.series = config['dataseries']
|
| 61 |
+
|
| 62 |
+
if 'field' in config:
|
| 63 |
+
self.field = config['field']
|
| 64 |
+
|
| 65 |
+
if 'criterion' in config:
|
| 66 |
+
self.cr = config['criterion']
|
| 67 |
+
|
| 68 |
+
self.connect_db()
|
| 69 |
+
|
| 70 |
+
def on_deactivate(self):
|
| 71 |
+
""" Deactivate module.
|
| 72 |
+
"""
|
| 73 |
+
del self.conn
|
| 74 |
+
|
| 75 |
+
def connect_db(self):
|
| 76 |
+
""" Connect to Influx database """
|
| 77 |
+
self.conn = InfluxDBClient(self.host, self.port, self.user, self.pw, self.dbname)
|
| 78 |
+
|
| 79 |
+
def get_log_channels(self):
|
| 80 |
+
""" Get number of logging channels
|
| 81 |
+
|
| 82 |
+
@return int: number of channels
|
| 83 |
+
"""
|
| 84 |
+
return self.log_channels
|
| 85 |
+
|
| 86 |
+
def set_log_channels(self, channelspec):
|
| 87 |
+
""" Set number of logging channels.
|
| 88 |
+
|
| 89 |
+
@param channelspec dict: name, spec
|
| 90 |
+
"""
|
| 91 |
+
for name, spec in channelspec.items():
|
| 92 |
+
if spec is None and name in self.log_channels:
|
| 93 |
+
self.log_channels.pop(name)
|
| 94 |
+
elif name in self.log_channels:
|
| 95 |
+
pass
|
| 96 |
+
else:
|
| 97 |
+
pass
|
| 98 |
+
if True:
|
| 99 |
+
pass
|
| 100 |
+
|
| 101 |
+
def log_to_channel(self, channel, values):
|
| 102 |
+
""" Log values to a specific channel.
|
| 103 |
+
|
| 104 |
+
@param channel str: channel name
|
| 105 |
+
@param values list: data to be logged
|
| 106 |
+
"""
|
| 107 |
+
if channel in self.log_channels.keys() and len(values) == len(self.log_channels[channel][values]):
|
| 108 |
+
conn.write_points(format_data(channel, values, channeltags))
|
| 109 |
+
|
| 110 |
+
def format_data(self, channel_name, values, tags):
|
| 111 |
+
""" Format data according to InfluxDB JSON API.
|
| 112 |
+
|
| 113 |
+
@param channel_name str: channel name
|
| 114 |
+
@param values list: data
|
| 115 |
+
@param tags list(str): list of tags
|
| 116 |
+
"""
|
| 117 |
+
return [{
|
| 118 |
+
'measurement': channel_name,
|
| 119 |
+
'fields': values,
|
| 120 |
+
'tags': tags
|
| 121 |
+
}]
|
| 122 |
+
|
pool/shard009/Python/0080505_generic.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
|
| 3 |
+
"""
|
| 4 |
+
abouttag.generic
|
| 5 |
+
|
| 6 |
+
Provides generic abouttag function; object type specified by first
|
| 7 |
+
parameter.
|
| 8 |
+
|
| 9 |
+
Copyright 2010 AUTHORS (see AUTHORS file)
|
| 10 |
+
License: MIT, see LICENSE for more information
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
from abouttag.fluiddb import FluidDB
|
| 14 |
+
from abouttag.uri import URI
|
| 15 |
+
from abouttag.database import Database
|
| 16 |
+
from abouttag.objects import planet, element, twitteruser
|
| 17 |
+
from abouttag.location import GEOnet
|
| 18 |
+
from abouttag.books import book, ubook, author
|
| 19 |
+
from abouttag.music import album, track, artist, isrc_recording
|
| 20 |
+
|
| 21 |
+
class AboutTagError(Exception):
|
| 22 |
+
pass
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def abouttag(*args):
|
| 26 |
+
|
| 27 |
+
items = {
|
| 28 |
+
'fi-user': FluidDB.user,
|
| 29 |
+
'fi-namespace': FluidDB.namespace,
|
| 30 |
+
'fi-ns': FluidDB.namespace,
|
| 31 |
+
'fi-tag': FluidDB.tag,
|
| 32 |
+
'uri': URI,
|
| 33 |
+
'url': URI,
|
| 34 |
+
'URI': URI,
|
| 35 |
+
'URL': URI,
|
| 36 |
+
'db-table': Database.table,
|
| 37 |
+
'db-field': Database.field,
|
| 38 |
+
'planet': planet,
|
| 39 |
+
'element': element,
|
| 40 |
+
'book': ubook,
|
| 41 |
+
'author': author,
|
| 42 |
+
'album': album,
|
| 43 |
+
'track': track,
|
| 44 |
+
'artist': artist,
|
| 45 |
+
'isrc-recording': isrc_recording,
|
| 46 |
+
'twitter-user': twitteruser,
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
if len(args) == 0:
|
| 50 |
+
raise AboutTagError('No object type specified')
|
| 51 |
+
object = args[0]
|
| 52 |
+
if not object in items:
|
| 53 |
+
raise AboutTagError('Object type %s not known.\n'
|
| 54 |
+
' Supported object types are:\n %s\n'
|
| 55 |
+
% (object, '\n '.join(items.keys())))
|
| 56 |
+
|
| 57 |
+
f = items[object]
|
| 58 |
+
if object.startswith('fi'):
|
| 59 |
+
db = FluidDB()
|
| 60 |
+
return f(db, *args[1:])
|
| 61 |
+
elif object.startswith('db'):
|
| 62 |
+
db = Database()
|
| 63 |
+
return f(db, *args[1:])
|
| 64 |
+
elif object == 'author':
|
| 65 |
+
if len(args) > 2:
|
| 66 |
+
return f(args[1], *(int(a) for a in args[2:]))
|
| 67 |
+
else:
|
| 68 |
+
raise AboutTagError('No author specified')
|
| 69 |
+
else:
|
| 70 |
+
return f(*args[1:])
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
|
pool/shard009/Python/0080507_saphana.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This file is part of the sos project: https://github.com/sosreport/sos
|
| 2 |
+
#
|
| 3 |
+
# This copyrighted material is made available to anyone wishing to use,
|
| 4 |
+
# modify, copy, or redistribute it subject to the terms and conditions of
|
| 5 |
+
# version 2 of the GNU General Public License.
|
| 6 |
+
#
|
| 7 |
+
# See the LICENSE file in the source distribution for further information.
|
| 8 |
+
|
| 9 |
+
import os
|
| 10 |
+
from sos.report.plugins import Plugin, RedHatPlugin
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class saphana(Plugin, RedHatPlugin):
|
| 14 |
+
|
| 15 |
+
short_desc = 'SAP HANA'
|
| 16 |
+
|
| 17 |
+
plugin_name = 'saphana'
|
| 18 |
+
profiles = ['sap']
|
| 19 |
+
|
| 20 |
+
files = ['/hana']
|
| 21 |
+
|
| 22 |
+
def setup(self):
|
| 23 |
+
|
| 24 |
+
sids = []
|
| 25 |
+
|
| 26 |
+
if os.path.isdir("/hana/shared"):
|
| 27 |
+
s = os.listdir("/hana/shared")
|
| 28 |
+
for sid in s:
|
| 29 |
+
if len(sid) == 3:
|
| 30 |
+
sid = sid.strip()
|
| 31 |
+
sids.append(sid)
|
| 32 |
+
|
| 33 |
+
for sid in sids:
|
| 34 |
+
sidadm = '%sadm' % sid.lower()
|
| 35 |
+
|
| 36 |
+
prefix = 'su - %s -c' % sidadm
|
| 37 |
+
|
| 38 |
+
self.add_cmd_output('%s "HDB info"' % prefix,
|
| 39 |
+
suggest_filename="%s_HDB_info" % sid)
|
| 40 |
+
|
| 41 |
+
self.add_cmd_output('%s "hdbsrvutil -v"' % prefix,
|
| 42 |
+
suggest_filename="%s_version" % sid)
|
| 43 |
+
|
| 44 |
+
self.add_cmd_output('%s \'hdbcons "mm l -s -S -p"\'' % prefix,
|
| 45 |
+
suggest_filename="%s_memusage" % sid)
|
| 46 |
+
|
| 47 |
+
self.add_cmd_output('%s \'hdbcons -e hdbindexserver \
|
| 48 |
+
"replication info"\'' % prefix,
|
| 49 |
+
suggest_filename="%s_replicainfo" % sid)
|
| 50 |
+
|
| 51 |
+
if os.path.isdir("/hana/shared/%s/" % sid):
|
| 52 |
+
i = os.listdir("/hana/shared/%s/" % sid)
|
| 53 |
+
for inst in i:
|
| 54 |
+
if "HDB" in inst:
|
| 55 |
+
inst = inst.strip()[-2:]
|
| 56 |
+
|
| 57 |
+
# get GREEN/RED status
|
| 58 |
+
self.add_cmd_output(
|
| 59 |
+
'su - %s -c "sapcontrol -nr %s \
|
| 60 |
+
-function GetProcessList"'
|
| 61 |
+
% (sidadm, inst),
|
| 62 |
+
suggest_filename="%s_%s_status"
|
| 63 |
+
% (sid, inst)
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
path = '/usr/sap/%s/HDB%s/exe/python_support'
|
| 67 |
+
path %= (sid, inst)
|
| 68 |
+
|
| 69 |
+
if os.path.isdir("%s" % path):
|
| 70 |
+
# SCALE OUT - slow
|
| 71 |
+
self.add_cmd_output(
|
| 72 |
+
'su - %s -c "python \
|
| 73 |
+
%s/landscapeHostConfiguration.py"'
|
| 74 |
+
% (sidadm, path),
|
| 75 |
+
suggest_filename="%s_%s_landscapeConfig"
|
| 76 |
+
% (sid, inst)
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
# vim: et ts=4 sw=4
|
pool/shard009/Python/0080508_CMRToolkitWizardAntrumCutStep.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Enable the 'Prefer executable CLIs' option in Slicer under Modules before running the wizard
|
| 2 |
+
from __main__ import qt, ctk, slicer
|
| 3 |
+
|
| 4 |
+
from CMRToolkitWizardStep import *
|
| 5 |
+
from Helper import *
|
| 6 |
+
import PythonQt
|
| 7 |
+
|
| 8 |
+
class CMRToolkitWizardAntrumCutStep( CMRToolkitWizardStep ) :
|
| 9 |
+
|
| 10 |
+
def __init__( self, stepid ):
|
| 11 |
+
self.initialize( stepid )
|
| 12 |
+
self.setName( '6. PV Antrum Cut' )
|
| 13 |
+
self.setDescription( 'Remove pulmonary veins from endocardial segmentation label image' )
|
| 14 |
+
|
| 15 |
+
self.__parent = super( CMRToolkitWizardAntrumCutStep, self )
|
| 16 |
+
|
| 17 |
+
def killButton(self):
|
| 18 |
+
# Hide unneccesary button
|
| 19 |
+
bl = slicer.util.findChildren(text='AutomaticLeft*')
|
| 20 |
+
if len(bl):
|
| 21 |
+
bl[0].hide()
|
| 22 |
+
|
| 23 |
+
def createUserInterface( self ):
|
| 24 |
+
'''
|
| 25 |
+
'''
|
| 26 |
+
self.__layout = self.__parent.createUserInterface()
|
| 27 |
+
print "createUserInterface: CMRToolkitWizardAntrumCutStep"
|
| 28 |
+
|
| 29 |
+
##TODO: Allow user to select the wall and endo or should the images be preloaded?
|
| 30 |
+
|
| 31 |
+
#epiVolumeLabel = qt.QLabel( 'Epi Segmentation (Dilated) Label Image:' )
|
| 32 |
+
#self.__epiVolumeSelector = slicer.qMRMLNodeComboBox()
|
| 33 |
+
#self.__epiVolumeSelector.toolTip = "Select the epicardium segmentation image"
|
| 34 |
+
#self.__epiVolumeSelector.nodeTypes = ['vtkMRMLScalarVolumeNode']
|
| 35 |
+
#self.__epiVolumeSelector.setMRMLScene(slicer.mrmlScene)
|
| 36 |
+
#self.__epiVolumeSelector.addEnabled = False
|
| 37 |
+
#self.__epiVolumeSelector.renameEnabled = True
|
| 38 |
+
#self.__layout.addRow( epiVolumeLabel, self.__epiVolumeSelector )
|
| 39 |
+
|
| 40 |
+
#endoVolumeLabel = qt.QLabel( 'Endo Segmentation Label Image:' )
|
| 41 |
+
#self.__endoVolumeSelector = slicer.qMRMLNodeComboBox()
|
| 42 |
+
#self.__endoVolumeSelector.toolTip = "Select the endocardium segmentation image"
|
| 43 |
+
#self.__endoVolumeSelector.nodeTypes = ['vtkMRMLScalarVolumeNode']
|
| 44 |
+
#self.__endoVolumeSelector.setMRMLScene(slicer.mrmlScene)
|
| 45 |
+
#self.__endoVolumeSelector.addEnabled = False
|
| 46 |
+
#self.__endoVolumeSelector.renameEnabled = True
|
| 47 |
+
#self.__layout.addRow( endoVolumeLabel, self.__endoVolumeSelector )
|
| 48 |
+
|
| 49 |
+
antrumCutButton = qt.QPushButton('Load PV Antrum Cut Module')
|
| 50 |
+
self.__layout.addRow(antrumCutButton)
|
| 51 |
+
antrumCutButton.connect('clicked()', self.startAntrumCut)
|
| 52 |
+
|
| 53 |
+
def startAntrumCut(self):
|
| 54 |
+
# Load epi and endo segmentation volumes from previous steps
|
| 55 |
+
endoSegVolumeID = pNode.GetParameter('endoSegVolumeID')
|
| 56 |
+
endoSegVolume = Helper.getNodeByID(endoSegVolumeID)
|
| 57 |
+
|
| 58 |
+
wallCleanupSegVolumeID = pNode.GetParameter('wallCleanupSegID')
|
| 59 |
+
wallCleanupSegVolume = Helper.getNodeByID(wallCleanupSegVolumeID)
|
| 60 |
+
|
| 61 |
+
volumesLogic = slicer.modules.volumes.logic()
|
| 62 |
+
global antrumCutOutputVolume
|
| 63 |
+
antrumCutOutputVolume = volumesLogic.CreateAndAddLabelVolume( slicer.mrmlScene, endoSegVolume, 'Endocardium No Veins Segmentation Output' )
|
| 64 |
+
|
| 65 |
+
if endoSegVolume != None and wallCleanupSegVolume != None and endoSegVolumeID != wallCleanupSegVolumeID:
|
| 66 |
+
param = {}
|
| 67 |
+
param['endoLayer'] = endoSegVolume.GetID()
|
| 68 |
+
param['wallLayer'] = wallCleanupSegVolume.GetID()
|
| 69 |
+
param['endoNoVeins'] = antrumCutOutputVolume.GetID()
|
| 70 |
+
slicer.cli.run( slicer.modules.cmrtoolkitpvantrumcut, None, param, wait_for_completion=True )
|
| 71 |
+
else:
|
| 72 |
+
qt.QMessageBox.critical(slicer.util.mainWindow(),
|
| 73 |
+
'PV Antrum Cut', 'Both endocardial and wall segmentation images are required to run PV Antrum Cut.')
|
| 74 |
+
|
| 75 |
+
def validate( self, desiredBranchId ):
|
| 76 |
+
self.__parent.validate( desiredBranchId )
|
| 77 |
+
|
| 78 |
+
if antrumCutOutputVolume != None:
|
| 79 |
+
antrumCutVolumeID = antrumCutOutputVolume.GetID()
|
| 80 |
+
pNode = self.parameterNode()
|
| 81 |
+
pNode.SetParameter('antrumCutVolumeID', antrumCutVolumeID)
|
| 82 |
+
self.__parent.validationSucceeded(desiredBranchId)
|
| 83 |
+
else:
|
| 84 |
+
self.__parent.validationFailed(desiredBranchId, 'Error','Endocardium No Veins segmentation image not created successfully.')
|
| 85 |
+
|
| 86 |
+
def onEntry(self, comingFrom, transitionType):
|
| 87 |
+
super(CMRToolkitWizardAntrumCutStep, self).onEntry(comingFrom, transitionType)
|
| 88 |
+
# Make global in order to be accessible by 'startAntrumCut'
|
| 89 |
+
global pNode
|
| 90 |
+
pNode = self.parameterNode()
|
| 91 |
+
pNode.SetParameter('currentStep', self.stepid)
|
| 92 |
+
|
| 93 |
+
qt.QTimer.singleShot(0, self.killButton)
|
| 94 |
+
|
| 95 |
+
def onExit(self, goingTo, transitionType):
|
| 96 |
+
pNode = self.parameterNode()
|
| 97 |
+
|
| 98 |
+
#if goingTo.id() != 'EndoNVIsosurface':
|
| 99 |
+
# return
|
| 100 |
+
|
| 101 |
+
super(CMRToolkitWizardAntrumCutStep, self).onExit(goingTo, transitionType)
|
| 102 |
+
|
pool/shard009/Python/0080509_classify_cascade.py
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sklearn.datasets import load_digits
|
| 2 |
+
from multilayer_perceptron import MultilayerPerceptronClassifier, MultilayerPerceptronRegressor
|
| 3 |
+
import numpy as np
|
| 4 |
+
from matplotlib import pyplot as plt
|
| 5 |
+
import glob
|
| 6 |
+
import Image
|
| 7 |
+
import datetime
|
| 8 |
+
from Haar_extractor import *
|
| 9 |
+
import warnings, os, sys
|
| 10 |
+
import matplotlib.pyplot as plt
|
| 11 |
+
warnings.filterwarnings("ignore") #removes the deprecation warnings
|
| 12 |
+
|
| 13 |
+
print "Start:",datetime.datetime.now()
|
| 14 |
+
|
| 15 |
+
def loadImage(imagepath):
|
| 16 |
+
#load the image and convert to an array
|
| 17 |
+
im=Image.open(imagepath)
|
| 18 |
+
pixels = list(im.getdata())
|
| 19 |
+
final_pix = []
|
| 20 |
+
for pix in pixels:
|
| 21 |
+
p = (pix[0]+pix[1]+pix[2])/3
|
| 22 |
+
final_pix.append(p)
|
| 23 |
+
width, height = im.size
|
| 24 |
+
pixels = [final_pix[i * width:(i + 1) * width] for i in xrange(height)]
|
| 25 |
+
return pixels
|
| 26 |
+
|
| 27 |
+
def loadSubImage(im):
|
| 28 |
+
pixels = list(im.getdata())
|
| 29 |
+
final_pix = []
|
| 30 |
+
for pix in pixels:
|
| 31 |
+
p = (pix[0]+pix[1]+pix[2])/3
|
| 32 |
+
final_pix.append(p)
|
| 33 |
+
width, height = im.size
|
| 34 |
+
pixels = [final_pix[i * width:(i + 1) * width] for i in xrange(height)]
|
| 35 |
+
return pixels
|
| 36 |
+
|
| 37 |
+
#load images and get first features
|
| 38 |
+
pat = []
|
| 39 |
+
paty = []
|
| 40 |
+
test = []
|
| 41 |
+
testy = []
|
| 42 |
+
positive_images = glob.glob("/home/jonathan/Baobab/fromGE/train/baobab/poss/pos*.png")
|
| 43 |
+
for im in positive_images:
|
| 44 |
+
image = loadImage(im)
|
| 45 |
+
haars = getFeatures1(image)
|
| 46 |
+
pat.append(haars)
|
| 47 |
+
paty.append(1)
|
| 48 |
+
negative_images = glob.glob("/home/jonathan/Baobab/fromGE/train/wbackground/bg*.png")
|
| 49 |
+
for im in negative_images:
|
| 50 |
+
image = loadImage(im)
|
| 51 |
+
haars = getFeatures1(image)
|
| 52 |
+
pat.append(haars)
|
| 53 |
+
paty.append(0)
|
| 54 |
+
test_images = glob.glob("/home/jonathan/Baobab/fromGE/train/test/*.png")
|
| 55 |
+
for im in test_images:
|
| 56 |
+
image = loadImage(im)
|
| 57 |
+
haars = getFeatures1(image)
|
| 58 |
+
test.append(haars)
|
| 59 |
+
X = np.array(pat)
|
| 60 |
+
y = np.array(paty)
|
| 61 |
+
|
| 62 |
+
print "Finished loading images and computing first feature set:",datetime.datetime.now()
|
| 63 |
+
|
| 64 |
+
pat = []
|
| 65 |
+
paty = []
|
| 66 |
+
positive_images = glob.glob("/home/jonathan/Baobab/fromGE/train/baobab/poss/pos*.png")
|
| 67 |
+
p = 1
|
| 68 |
+
for im in positive_images:
|
| 69 |
+
p += 1
|
| 70 |
+
image = loadImage(im)
|
| 71 |
+
haars = getHaarFeatures(image)
|
| 72 |
+
pat.append(haars)
|
| 73 |
+
paty.append(1)
|
| 74 |
+
negative_images = glob.glob("/home/jonathan/Baobab/fromGE/train/wbackground/bg*.png")
|
| 75 |
+
for im in negative_images:
|
| 76 |
+
image = loadImage(im)
|
| 77 |
+
haars = getHaarFeatures(image)
|
| 78 |
+
pat.append(haars)
|
| 79 |
+
paty.append(0)
|
| 80 |
+
X2 = np.array(pat)
|
| 81 |
+
y2 = np.array(paty)
|
| 82 |
+
|
| 83 |
+
print "Finished loading images and computing second feature set:",datetime.datetime.now()
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
print "Beginning Training of first classifier:",datetime.datetime.now()
|
| 87 |
+
|
| 88 |
+
# MLP training performance
|
| 89 |
+
mlp = MultilayerPerceptronClassifier(n_hidden = 5,max_iter = 500, alpha = 0.02)
|
| 90 |
+
mlp.fit(X, y)
|
| 91 |
+
print "Beginning Training of second classifier:",datetime.datetime.now()
|
| 92 |
+
mlp2 = MultilayerPerceptronClassifier(n_hidden = 5,max_iter = 800, alpha = 0.02)
|
| 93 |
+
mlp2.fit(X2, y2)
|
| 94 |
+
print "Finished Training:",datetime.datetime.now()
|
| 95 |
+
|
| 96 |
+
print "Training Score = ", mlp.score(X, y)
|
| 97 |
+
print "Training Score 2", mlp2.score(X2, y2)
|
| 98 |
+
print mlp.intercept_output_
|
| 99 |
+
#print "Predicted labels = ", mlp.predict(X)
|
| 100 |
+
#print "True labels = ", y
|
| 101 |
+
#print(datetime.datetime.now())
|
| 102 |
+
#print "Pedicted for test:", mlp.predict(test)
|
| 103 |
+
#print "Pedicted for test:", mlp.predict_proba(test)
|
| 104 |
+
#print(datetime.datetime.now())
|
| 105 |
+
|
| 106 |
+
#~ #test on a real image
|
| 107 |
+
print "Beginning Test of image:",datetime.datetime.now()
|
| 108 |
+
test = []
|
| 109 |
+
im_test=Image.open("/home/jonathan/Baobab/fromGE/256.png")
|
| 110 |
+
box_width = 40
|
| 111 |
+
box_height = 40
|
| 112 |
+
|
| 113 |
+
imheight = 700 #GET FROM IMAGE!!!
|
| 114 |
+
imwidth = 1200
|
| 115 |
+
x, y = 0, 0
|
| 116 |
+
baobabs = []
|
| 117 |
+
while y < (imheight-box_height):
|
| 118 |
+
x = 0
|
| 119 |
+
while x < (imwidth - box_width):
|
| 120 |
+
region = im_test.crop((x,y,x+box_width, y+box_width))
|
| 121 |
+
small_image = loadSubImage(region)
|
| 122 |
+
haars = getFeatures1(small_image)
|
| 123 |
+
test.append(haars)
|
| 124 |
+
results = mlp.predict(test)
|
| 125 |
+
test = []
|
| 126 |
+
if results[0] == 1:
|
| 127 |
+
baobabs.append((x,y))
|
| 128 |
+
x += 10
|
| 129 |
+
y += 10
|
| 130 |
+
print "narrowed down from ~8000 to",len(baobabs)
|
| 131 |
+
print "starting second round:",datetime.datetime.now()
|
| 132 |
+
baobabs2 = []
|
| 133 |
+
#Fix This, need to train a new net with getHaarFeatures...
|
| 134 |
+
for b in baobabs:
|
| 135 |
+
x,y = b
|
| 136 |
+
region = im_test.crop((x,y,x+box_width, y+box_width))
|
| 137 |
+
small_image = loadSubImage(region)
|
| 138 |
+
haars = getHaarFeatures(small_image)
|
| 139 |
+
test.append(haars)
|
| 140 |
+
results = mlp2.predict(test)
|
| 141 |
+
test = []
|
| 142 |
+
if results[0] == 1:
|
| 143 |
+
baobabs2.append((x,y))
|
| 144 |
+
print "narrowed down from %i to" % len(baobabs),len(baobabs2)
|
| 145 |
+
print "Finished:",datetime.datetime.now()
|
| 146 |
+
print baobabs2
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
|
pool/shard009/Python/0080515_client.py
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import urllib
|
| 2 |
+
import re
|
| 3 |
+
import sys
|
| 4 |
+
|
| 5 |
+
from connexion import request
|
| 6 |
+
|
| 7 |
+
from flask import abort, make_response, current_app as app
|
| 8 |
+
|
| 9 |
+
from auslib.AUS import AUS
|
| 10 |
+
from auslib.global_state import dbo
|
| 11 |
+
|
| 12 |
+
import logging
|
| 13 |
+
|
| 14 |
+
AUS = AUS()
|
| 15 |
+
LOG = logging.getLogger(__name__)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def unsubstituted_url_variables():
|
| 19 |
+
abort(404)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def getHeaderArchitecture(buildTarget, ua):
|
| 23 |
+
if buildTarget.startswith('Darwin'):
|
| 24 |
+
if ua and 'PPC' in ua:
|
| 25 |
+
return 'PPC'
|
| 26 |
+
else:
|
| 27 |
+
return 'Intel'
|
| 28 |
+
else:
|
| 29 |
+
return 'Intel'
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def getSystemCapabilities(systemCapabilities):
|
| 33 |
+
# Set defaults for the broken-down fields, because not all query versions
|
| 34 |
+
# will have all values.
|
| 35 |
+
caps = {"instructionSet": None, "memory": None}
|
| 36 |
+
# New-style SYSTEM_CAPABILITIES, as implemented in https://bugzilla.mozilla.org/show_bug.cgi?id=1373367
|
| 37 |
+
if systemCapabilities.startswith("ISET:"):
|
| 38 |
+
for part in systemCapabilities.split(","):
|
| 39 |
+
key, value = part.split(":", 1)
|
| 40 |
+
if key == "ISET":
|
| 41 |
+
caps["instructionSet"] = value
|
| 42 |
+
elif key == "MEM":
|
| 43 |
+
caps["memory"] = int(value)
|
| 44 |
+
# Old-style, unprefixed SYSTEM_CAPABILITIES
|
| 45 |
+
else:
|
| 46 |
+
parts = systemCapabilities.split(",")
|
| 47 |
+
# The only known valid formats for this field are either a single part,
|
| 48 |
+
# or two parts separated by a comma. Anything else is unparsable, so we
|
| 49 |
+
# we cannot safely assign any fields.
|
| 50 |
+
if len(parts) == 1:
|
| 51 |
+
caps["instructionSet"] = parts[0]
|
| 52 |
+
elif len(parts) == 2:
|
| 53 |
+
caps["instructionSet"] = parts[0]
|
| 54 |
+
caps["memory"] = int(parts[1])
|
| 55 |
+
|
| 56 |
+
return caps
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def getCleanQueryFromURL(url):
|
| 60 |
+
query = url.copy()
|
| 61 |
+
# Some versions of Avast make requests and blindly append "?avast=1" to
|
| 62 |
+
# them, which breaks query string parsing if ?force=1 is already
|
| 63 |
+
# there. Because we're nice people we'll fix it up.
|
| 64 |
+
if 'force' in query and 'avast' in query['force']:
|
| 65 |
+
force_value = query['force']
|
| 66 |
+
force_split = force_value.split('?', 1)
|
| 67 |
+
|
| 68 |
+
if len(force_split) < 2:
|
| 69 |
+
force_split = force_value.split('%3F', 1)
|
| 70 |
+
|
| 71 |
+
query['force'] = int(force_split[0])
|
| 72 |
+
|
| 73 |
+
avast_parameter = force_split[1]
|
| 74 |
+
avast_split = avast_parameter.split('=')
|
| 75 |
+
query[avast_split[0]] = int(avast_split[1])
|
| 76 |
+
|
| 77 |
+
# Some versions of Avast have a bug in them that prepends "x86 "
|
| 78 |
+
if 'locale' in query:
|
| 79 |
+
query['locale'] = query['locale'].replace('x86 ', '')
|
| 80 |
+
|
| 81 |
+
return query
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def getQueryFromURL(url):
|
| 85 |
+
query = getCleanQueryFromURL(url)
|
| 86 |
+
if "systemCapabilities" in query:
|
| 87 |
+
query.update(getSystemCapabilities(url["systemCapabilities"]))
|
| 88 |
+
del query["systemCapabilities"]
|
| 89 |
+
query['osVersion'] = urllib.unquote(query['osVersion'])
|
| 90 |
+
ua = request.headers.get('User-Agent')
|
| 91 |
+
query['headerArchitecture'] = getHeaderArchitecture(query['buildTarget'], ua)
|
| 92 |
+
query['force'] = (int(query.get('force', 0)) == 1)
|
| 93 |
+
return query
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def get_update_blob(**url):
|
| 97 |
+
query = getQueryFromURL(url)
|
| 98 |
+
LOG.debug("Got query: %s", query)
|
| 99 |
+
release, update_type = AUS.evaluateRules(query)
|
| 100 |
+
|
| 101 |
+
# passing {},None returns empty xml
|
| 102 |
+
if release:
|
| 103 |
+
response_products = release.getResponseProducts()
|
| 104 |
+
response_blobs = []
|
| 105 |
+
response_blob_names = release.getResponseBlobs()
|
| 106 |
+
if response_products:
|
| 107 |
+
# if we have a SuperBlob of gmp, we process the response products and
|
| 108 |
+
# concatenate their inner XMLs
|
| 109 |
+
for product in response_products:
|
| 110 |
+
product_query = query.copy()
|
| 111 |
+
product_query["product"] = product
|
| 112 |
+
response_release, response_update_type = AUS.evaluateRules(product_query)
|
| 113 |
+
if not response_release:
|
| 114 |
+
continue
|
| 115 |
+
|
| 116 |
+
response_blobs.append({'product_query': product_query,
|
| 117 |
+
'response_release': response_release,
|
| 118 |
+
'response_update_type': response_update_type})
|
| 119 |
+
elif response_blob_names:
|
| 120 |
+
for blob_name in response_blob_names:
|
| 121 |
+
# if we have a SuperBlob of systemaddons, we process the response products and
|
| 122 |
+
# concatenate their inner XMLs
|
| 123 |
+
product_query = query.copy()
|
| 124 |
+
product = dbo.releases.getReleases(name=blob_name, limit=1)[0]['product']
|
| 125 |
+
product_query["product"] = product
|
| 126 |
+
response_release = dbo.releases.getReleaseBlob(name=blob_name)
|
| 127 |
+
if not response_release:
|
| 128 |
+
LOG.warning("No release found with name: %s", blob_name)
|
| 129 |
+
continue
|
| 130 |
+
|
| 131 |
+
response_blobs.append({'product_query': product_query,
|
| 132 |
+
'response_release': response_release,
|
| 133 |
+
'response_update_type': update_type})
|
| 134 |
+
else:
|
| 135 |
+
response_blobs.append({'product_query': query,
|
| 136 |
+
'response_release': release,
|
| 137 |
+
'response_update_type': update_type})
|
| 138 |
+
|
| 139 |
+
# getHeaderXML() returns outermost header for an update which
|
| 140 |
+
# is same for all release type
|
| 141 |
+
xml = release.getHeaderXML()
|
| 142 |
+
# we assume that all blobs will have similar ones. We might want to
|
| 143 |
+
# verify that all of them are indeed the same in the future.
|
| 144 |
+
|
| 145 |
+
# Appending Header
|
| 146 |
+
# In case of superblob Extracting Header form parent release
|
| 147 |
+
xml.append(release.getInnerHeaderXML(query,
|
| 148 |
+
update_type,
|
| 149 |
+
app.config["WHITELISTED_DOMAINS"],
|
| 150 |
+
app.config["SPECIAL_FORCE_HOSTS"]))
|
| 151 |
+
for response_blob in response_blobs:
|
| 152 |
+
xml.extend(response_blob['response_release']
|
| 153 |
+
.getInnerXML(response_blob['product_query'],
|
| 154 |
+
response_blob['response_update_type'],
|
| 155 |
+
app.config["WHITELISTED_DOMAINS"],
|
| 156 |
+
app.config["SPECIAL_FORCE_HOSTS"]))
|
| 157 |
+
# Appending Footer
|
| 158 |
+
# In case of superblob Extracting Header form parent release
|
| 159 |
+
xml.append(release.getInnerFooterXML(query,
|
| 160 |
+
update_type,
|
| 161 |
+
app.config["WHITELISTED_DOMAINS"],
|
| 162 |
+
app.config["SPECIAL_FORCE_HOSTS"]))
|
| 163 |
+
xml.append(release.getFooterXML())
|
| 164 |
+
# ensure valid xml by using the right entity for ampersand
|
| 165 |
+
xml = re.sub('&(?!amp;)', '&', '\n'.join(xml))
|
| 166 |
+
else:
|
| 167 |
+
xml = ['<?xml version="1.0"?>']
|
| 168 |
+
xml.append('<updates>')
|
| 169 |
+
xml.append('</updates>')
|
| 170 |
+
xml = "\n".join(xml)
|
| 171 |
+
LOG.debug("Sending XML: %s", xml)
|
| 172 |
+
response = make_response(xml)
|
| 173 |
+
response.headers["Cache-Control"] = app.cacheControl
|
| 174 |
+
response.mimetype = "text/xml"
|
| 175 |
+
return response
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def _set_functions(function_names, function):
|
| 179 |
+
module = sys.modules[__name__]
|
| 180 |
+
for function_name in function_names:
|
| 181 |
+
setattr(module, function_name, function)
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
update_blob_functions = ["get_update_blob_1",
|
| 185 |
+
"get_update_blob_2",
|
| 186 |
+
"get_update_blob_3",
|
| 187 |
+
"get_update_blob_3_esrpre",
|
| 188 |
+
"get_update_blob_4",
|
| 189 |
+
"get_update_blob_5",
|
| 190 |
+
"get_update_blob_6"]
|
| 191 |
+
|
| 192 |
+
unsubstituted_url_var_functions = ["unsubstituted_url_variables_1",
|
| 193 |
+
"unsubstituted_url_variables_2",
|
| 194 |
+
"unsubstituted_url_variables_3",
|
| 195 |
+
"unsubstituted_url_variables_4",
|
| 196 |
+
"unsubstituted_url_variables_5",
|
| 197 |
+
"unsubstituted_url_variables_6"]
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
_set_functions(update_blob_functions, get_update_blob)
|
| 201 |
+
_set_functions(unsubstituted_url_var_functions, unsubstituted_url_variables)
|
pool/shard009/Python/0080516_bookmark.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from canvasapi.canvas_object import CanvasObject
|
| 2 |
+
from canvasapi.util import combine_kwargs
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class Bookmark(CanvasObject):
|
| 6 |
+
def __str__(self):
|
| 7 |
+
return "{} ({})".format(self.name, self.id)
|
| 8 |
+
|
| 9 |
+
def delete(self, **kwargs):
|
| 10 |
+
"""
|
| 11 |
+
Delete this bookmark.
|
| 12 |
+
|
| 13 |
+
:calls: `DELETE /api/v1/users/self/bookmarks/:id \
|
| 14 |
+
<https://canvas.instructure.com/doc/api/bookmarks.html#method.bookmarks/bookmarks.destroy>`_
|
| 15 |
+
|
| 16 |
+
:rtype: :class:`canvasapi.bookmark.Bookmark`
|
| 17 |
+
"""
|
| 18 |
+
response = self._requester.request(
|
| 19 |
+
"DELETE",
|
| 20 |
+
"users/self/bookmarks/{}".format(self.id),
|
| 21 |
+
_kwargs=combine_kwargs(**kwargs),
|
| 22 |
+
)
|
| 23 |
+
return Bookmark(self._requester, response.json())
|
| 24 |
+
|
| 25 |
+
def edit(self, **kwargs):
|
| 26 |
+
"""
|
| 27 |
+
Modify this bookmark.
|
| 28 |
+
|
| 29 |
+
:calls: `PUT /api/v1/users/self/bookmarks/:id \
|
| 30 |
+
<https://canvas.instructure.com/doc/api/bookmarks.html#method.bookmarks/bookmarks.update>`_
|
| 31 |
+
|
| 32 |
+
:rtype: :class:`canvasapi.bookmark.Bookmark`
|
| 33 |
+
"""
|
| 34 |
+
response = self._requester.request(
|
| 35 |
+
"PUT",
|
| 36 |
+
"users/self/bookmarks/{}".format(self.id),
|
| 37 |
+
_kwargs=combine_kwargs(**kwargs),
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
if "name" in response.json() and "url" in response.json():
|
| 41 |
+
super(Bookmark, self).set_attributes(response.json())
|
| 42 |
+
|
| 43 |
+
return Bookmark(self._requester, response.json())
|
pool/shard009/Python/0080519_fb_freq.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
import re
|
| 3 |
+
import numpy
|
| 4 |
+
from matplotlib import pyplot
|
| 5 |
+
|
| 6 |
+
# Choose correct html parser library
|
| 7 |
+
version = sys.version_info.major
|
| 8 |
+
if version == 2:
|
| 9 |
+
from HTMLParser import HTMLParser
|
| 10 |
+
else:
|
| 11 |
+
from html.parser import HTMLParser
|
| 12 |
+
|
| 13 |
+
### Initialize Data Structures ###
|
| 14 |
+
|
| 15 |
+
# Set Month Data Array and Name values.
|
| 16 |
+
month = [0] * 12
|
| 17 |
+
month_names = [
|
| 18 |
+
"Jan",
|
| 19 |
+
"Feb",
|
| 20 |
+
"March",
|
| 21 |
+
"April",
|
| 22 |
+
"May",
|
| 23 |
+
"June",
|
| 24 |
+
"July",
|
| 25 |
+
"Aug",
|
| 26 |
+
"Sep",
|
| 27 |
+
"Oct",
|
| 28 |
+
"Nov",
|
| 29 |
+
"Dec"
|
| 30 |
+
]
|
| 31 |
+
|
| 32 |
+
# Set Day Data Array and Name values.
|
| 33 |
+
day = [0] * 7
|
| 34 |
+
day_names = [
|
| 35 |
+
"Monday",
|
| 36 |
+
"Tuesday",
|
| 37 |
+
"Wednesday",
|
| 38 |
+
"Thursday",
|
| 39 |
+
"Friday",
|
| 40 |
+
"Saturday",
|
| 41 |
+
"Sunday"
|
| 42 |
+
]
|
| 43 |
+
|
| 44 |
+
# Set Time Data Array and Name values.
|
| 45 |
+
time = [0] * 24
|
| 46 |
+
time_names = []
|
| 47 |
+
for name in range(24):
|
| 48 |
+
if name < 10:
|
| 49 |
+
time_names.append("0" + str(name) + ":")
|
| 50 |
+
else:
|
| 51 |
+
time_names.append(str(name) + ":")
|
| 52 |
+
for i in range(len(time_names)):
|
| 53 |
+
time_names[i] = time_names[i][:-1]
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
### Setup and Activate Parser/Data Gatherer ###
|
| 57 |
+
|
| 58 |
+
# Parse Data while adding to data arrays with regex.
|
| 59 |
+
class MessagesParser(HTMLParser):
|
| 60 |
+
def handle_data(self, data):
|
| 61 |
+
match = re.search(
|
| 62 |
+
"(Saturday|Sunday|Monday|Tuesday|Wednesday|Thursday|Friday)(,) " \
|
| 63 |
+
"[0-9]{2} (January|February|March|April|May|June|" \
|
| 64 |
+
"July|August|September|October|November|December) " \
|
| 65 |
+
"[0-9]{4} at [0-9]{2}:[0-9]{2}", data)
|
| 66 |
+
if match:
|
| 67 |
+
for i in range(12):
|
| 68 |
+
if re.search(month_names[i], match.group(0)):
|
| 69 |
+
month[i] = month[i] + 1
|
| 70 |
+
for i in range(7):
|
| 71 |
+
if re.search(day_names[i], match.group(0)):
|
| 72 |
+
day[i] = day[i] + 1
|
| 73 |
+
for i in range(24):
|
| 74 |
+
if re.search(time_names[i], match.group(0)):
|
| 75 |
+
time[i] = time[i] + 1
|
| 76 |
+
|
| 77 |
+
# Activate Parser on the messenger HTML data file.
|
| 78 |
+
file = open("html/messages.htm", 'r')
|
| 79 |
+
messages = file.readlines()
|
| 80 |
+
parser = MessagesParser()
|
| 81 |
+
for i in range(len(messages)):
|
| 82 |
+
parser.feed(messages[i])
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
### Create Graphs ###
|
| 86 |
+
|
| 87 |
+
# Bar Graph creater function.
|
| 88 |
+
def messages(n_groups, bar_width, x_lim, items, names,
|
| 89 |
+
x_label, y_label, title, file_name):
|
| 90 |
+
|
| 91 |
+
# Plot Graph.
|
| 92 |
+
fig, ax = pyplot.subplots()
|
| 93 |
+
index = numpy.arange(n_groups)
|
| 94 |
+
rects1 = pyplot.bar(index, items, bar_width)
|
| 95 |
+
|
| 96 |
+
# Add texts and lables.
|
| 97 |
+
pyplot.xlabel(x_label)
|
| 98 |
+
pyplot.ylabel(y_label)
|
| 99 |
+
pyplot.title(title)
|
| 100 |
+
|
| 101 |
+
# Shape Graph.
|
| 102 |
+
pyplot.xticks(index + bar_width/2, names)
|
| 103 |
+
pyplot.xlim([min(index) - x_lim, max(index) + x_lim])
|
| 104 |
+
pyplot.tight_layout()
|
| 105 |
+
|
| 106 |
+
# Export Graph.
|
| 107 |
+
pyplot.savefig(file_name)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
# Create Bar Graph for messenger month frequency.
|
| 111 |
+
messages(12, 0.3, 1, month, month_names, "Month of Message Sent",
|
| 112 |
+
"Number of Messages Sent", "Amount of Messages Sent on that Month",
|
| 113 |
+
"messages_month.png")
|
| 114 |
+
|
| 115 |
+
# Create Bar Graph for messenger dag frequency.
|
| 116 |
+
messages(7, 0.35, 0.5, day, day_names, "Day of Message Sent",
|
| 117 |
+
"Number of Messages Sent", "Amount of Messages Sent on Days of the Week",
|
| 118 |
+
"messages_days.png")
|
| 119 |
+
|
| 120 |
+
# Create Bar Graph for messenger time frequency.
|
| 121 |
+
messages(24, 0.20, 0.5, time, time_names, "Time of message sent",
|
| 122 |
+
"Number of messages sent", "Amount of Messages Sent on Time of the Day",
|
| 123 |
+
"messages_times.png")
|
| 124 |
+
|
pool/shard009/Python/0080520_transcript_orientations.py
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2012 Jose Blanca, Peio Ziarsolo, COMAV-Univ. Politecnica Valencia
|
| 2 |
+
# This file is part of ngs_crumbs.
|
| 3 |
+
# ngs_crumbs is free software: you can redistribute it and/or modify
|
| 4 |
+
# it under the terms of the GNU General Public License as
|
| 5 |
+
# published by the Free Software Foundation, either version 3 of the
|
| 6 |
+
# License, or (at your option) any later version.
|
| 7 |
+
|
| 8 |
+
# ngs_crumbs is distributed in the hope that it will be useful,
|
| 9 |
+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
| 10 |
+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
| 11 |
+
# GNU General Public License for more details.
|
| 12 |
+
|
| 13 |
+
# You should have received a copy of the GNU General Public License
|
| 14 |
+
# along with ngs_crumbs. If not, see <http://www.gnu.org/licenses/>.
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
from itertools import compress
|
| 18 |
+
import os.path
|
| 19 |
+
|
| 20 |
+
from crumbs.seq.annotation import (PolyaAnnotator, EstscanOrfAnnotator,
|
| 21 |
+
BlastAnnotator)
|
| 22 |
+
from crumbs.seq.utils.seq_utils import append_to_description
|
| 23 |
+
from crumbs.utils.tags import SEQRECORD
|
| 24 |
+
from crumbs.seq.seq import SeqWrapper
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class TranscriptOrientator(object):
|
| 28 |
+
'''This class orientates the transcripts
|
| 29 |
+
|
| 30 |
+
It can take into account: poly-A, ORFs and blast matches'''
|
| 31 |
+
|
| 32 |
+
def __init__(self, polya_params=None, estscan_params=None,
|
| 33 |
+
blast_params=None):
|
| 34 |
+
self._polya_params = polya_params
|
| 35 |
+
self._estscan_params = estscan_params
|
| 36 |
+
self._blast_params = blast_params
|
| 37 |
+
|
| 38 |
+
self._annotators = self._create_pipeline()
|
| 39 |
+
|
| 40 |
+
def _create_pipeline(self):
|
| 41 |
+
'It creates the annotation pipeline'
|
| 42 |
+
# pylint: disable=W0142
|
| 43 |
+
annotators = []
|
| 44 |
+
if self._polya_params:
|
| 45 |
+
annotators.append({'name': 'polyA'})
|
| 46 |
+
if self._estscan_params:
|
| 47 |
+
annotators.append({'name': 'estscan_orf'})
|
| 48 |
+
if self._blast_params:
|
| 49 |
+
for blast_param in self._blast_params:
|
| 50 |
+
annotators.append({'name': 'blast',
|
| 51 |
+
'blastdb': blast_param['blastdb']})
|
| 52 |
+
return annotators
|
| 53 |
+
|
| 54 |
+
@staticmethod
|
| 55 |
+
def _select_features_by_type(features, kind):
|
| 56 |
+
'it selects features by type'
|
| 57 |
+
return [feat for feat in features if feat.type == kind]
|
| 58 |
+
|
| 59 |
+
def _polya_selector(self, features):
|
| 60 |
+
'It selects the polya'
|
| 61 |
+
# pylint: disable=W0613
|
| 62 |
+
feats = self._select_features_by_type(features, 'polyA_sequence')
|
| 63 |
+
if feats:
|
| 64 |
+
return feats[0]
|
| 65 |
+
|
| 66 |
+
def _orf_selector(self, features):
|
| 67 |
+
'it returns the longest feature'
|
| 68 |
+
# pylint: disable=W0613
|
| 69 |
+
features = self._select_features_by_type(features, 'ORF')
|
| 70 |
+
if not features:
|
| 71 |
+
return None
|
| 72 |
+
|
| 73 |
+
lengths = [len(feat) for feat in features]
|
| 74 |
+
return features[lengths.index(max(lengths))]
|
| 75 |
+
|
| 76 |
+
def _match_part_selector(self, features, blastdb):
|
| 77 |
+
'it return the match_part with the best e-value'
|
| 78 |
+
blastdb = os.path.basename(blastdb)
|
| 79 |
+
features = self._select_features_by_type(features, 'match_part')
|
| 80 |
+
features = [f for f in features if f.qualifiers['blastdb'] == blastdb]
|
| 81 |
+
|
| 82 |
+
if not features:
|
| 83 |
+
return None
|
| 84 |
+
scores = [feat.qualifiers['score'] for feat in features]
|
| 85 |
+
return features[scores.index(min(scores))]
|
| 86 |
+
|
| 87 |
+
def _guess_orientations(self, seqs, annotator_name, blastdb):
|
| 88 |
+
'''It returns the orientation of the annotated transcripts.'''
|
| 89 |
+
orientations = []
|
| 90 |
+
for seq in seqs:
|
| 91 |
+
if annotator_name == 'polyA':
|
| 92 |
+
feature = self._polya_selector(seq.object.features)
|
| 93 |
+
elif annotator_name == 'estscan_orf':
|
| 94 |
+
feature = self._orf_selector(seq.object.features)
|
| 95 |
+
elif annotator_name == 'blast':
|
| 96 |
+
feature = self._match_part_selector(seq.object.features,
|
| 97 |
+
blastdb=blastdb)
|
| 98 |
+
else:
|
| 99 |
+
raise NotImplementedError('This annotator type not supported')
|
| 100 |
+
|
| 101 |
+
orientation = None if feature is None else feature.strand
|
| 102 |
+
orientations.append(orientation)
|
| 103 |
+
return orientations
|
| 104 |
+
|
| 105 |
+
def _get_annotator(self, annotator_name, blastdb):
|
| 106 |
+
'It prepares and returns the annotator'
|
| 107 |
+
if annotator_name == 'polyA':
|
| 108 |
+
annotator = PolyaAnnotator(**self._polya_params)
|
| 109 |
+
elif annotator_name == 'estscan_orf':
|
| 110 |
+
annotator = EstscanOrfAnnotator(**self._estscan_params)
|
| 111 |
+
elif annotator_name == 'blast':
|
| 112 |
+
blast_param = None
|
| 113 |
+
for blast_param_ in self._blast_params:
|
| 114 |
+
if blastdb == blast_param_['blastdb']:
|
| 115 |
+
blast_param = blast_param_
|
| 116 |
+
break
|
| 117 |
+
annotator = BlastAnnotator(**blast_param)
|
| 118 |
+
else:
|
| 119 |
+
raise NotImplementedError('This annotator type not supported')
|
| 120 |
+
return annotator
|
| 121 |
+
|
| 122 |
+
def __call__(self, seqs):
|
| 123 |
+
'It orientates seqs, that should have a SeqRecord in it'
|
| 124 |
+
orientations = None
|
| 125 |
+
orientation_log = [None] * len(seqs)
|
| 126 |
+
|
| 127 |
+
for annotator in self._annotators:
|
| 128 |
+
if orientations:
|
| 129 |
+
to_annalyze = [not o for o in orientations]
|
| 130 |
+
seqs_to_analyze = list(compress(seqs, to_annalyze))
|
| 131 |
+
else:
|
| 132 |
+
orientations = [None] * len(seqs)
|
| 133 |
+
seqs_to_analyze = seqs
|
| 134 |
+
|
| 135 |
+
annotator_name = annotator['name']
|
| 136 |
+
blastdb = annotator.get('blastdb', None)
|
| 137 |
+
annotator = self._get_annotator(annotator_name, blastdb)
|
| 138 |
+
|
| 139 |
+
annot_seqrecords = annotator(seqs_to_analyze)
|
| 140 |
+
annot_strands = self._guess_orientations(annot_seqrecords,
|
| 141 |
+
annotator_name,
|
| 142 |
+
blastdb=blastdb)
|
| 143 |
+
|
| 144 |
+
if blastdb:
|
| 145 |
+
annotator_name += ' ' + os.path.basename(blastdb)
|
| 146 |
+
|
| 147 |
+
analyzed_seqs_index = 0
|
| 148 |
+
for index, orientation in enumerate(orientations):
|
| 149 |
+
if orientation is None:
|
| 150 |
+
orientations[index] = annot_strands[analyzed_seqs_index]
|
| 151 |
+
if annot_strands[analyzed_seqs_index] == -1: # reverse
|
| 152 |
+
orientation_log[index] = annotator_name
|
| 153 |
+
analyzed_seqs_index += 1
|
| 154 |
+
# Now we reverse the seqs that we have guess that are reversed
|
| 155 |
+
reorientated_seqrecords = []
|
| 156 |
+
for orientation, seq, reason in zip(orientations, seqs,
|
| 157 |
+
orientation_log):
|
| 158 |
+
if orientation == -1:
|
| 159 |
+
rev_seqrecord = seq.object.reverse_complement(id=True,
|
| 160 |
+
description=True,
|
| 161 |
+
annotations=True,
|
| 162 |
+
features=True,
|
| 163 |
+
dbxrefs=True,
|
| 164 |
+
name=True)
|
| 165 |
+
seq = SeqWrapper(SEQRECORD, rev_seqrecord, None)
|
| 166 |
+
# we mark the reason why it has been reversed
|
| 167 |
+
text = '(reversed because of: {})'.format(reason)
|
| 168 |
+
append_to_description(seq, text)
|
| 169 |
+
|
| 170 |
+
reorientated_seqrecords.append(seq)
|
| 171 |
+
return reorientated_seqrecords
|
pool/shard009/Python/0080521_layout_utils.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# /***************************************************************************
|
| 2 |
+
# * *
|
| 3 |
+
# * This program is free software; you can redistribute it and/or modify *
|
| 4 |
+
# * it under the terms of the GNU General Public License as published by *
|
| 5 |
+
# * the Free Software Foundation; either version 2 of the License, or *
|
| 6 |
+
# * (at your option) any later version. *
|
| 7 |
+
# * *
|
| 8 |
+
# ***************************************************************************/
|
| 9 |
+
|
| 10 |
+
"""
|
| 11 |
+
Contains utility functions for working with layouts
|
| 12 |
+
"""
|
| 13 |
+
from typing import Optional
|
| 14 |
+
|
| 15 |
+
from qgis.PyQt.QtCore import (
|
| 16 |
+
QFile,
|
| 17 |
+
QIODevice
|
| 18 |
+
)
|
| 19 |
+
from qgis.PyQt.QtXml import QDomDocument
|
| 20 |
+
from qgis.core import (
|
| 21 |
+
QgsLayout,
|
| 22 |
+
QgsReadWriteContext,
|
| 23 |
+
QgsLayoutItem
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class LayoutUtils:
|
| 28 |
+
DATA_SOURCE_PROPERTY = 'variable_stdm_data_source'
|
| 29 |
+
DATA_CATEGORY_PROPERTY = 'variable_stdm_data_category'
|
| 30 |
+
REFERENCED_TABLE_PROPERTY = 'variable_stdm_referenced_table'
|
| 31 |
+
|
| 32 |
+
@staticmethod
|
| 33 |
+
def get_stdm_data_source_for_layout(layout: QgsLayout) -> Optional[str]:
|
| 34 |
+
return layout.customProperty(LayoutUtils.DATA_SOURCE_PROPERTY, None)
|
| 35 |
+
|
| 36 |
+
@staticmethod
|
| 37 |
+
def set_stdm_data_source_for_layout(layout: QgsLayout, source: Optional[str]):
|
| 38 |
+
layout.setCustomProperty(LayoutUtils.DATA_SOURCE_PROPERTY, source)
|
| 39 |
+
|
| 40 |
+
@staticmethod
|
| 41 |
+
def get_stdm_data_category_for_layout(layout: QgsLayout) -> Optional[str]:
|
| 42 |
+
return layout.customProperty(LayoutUtils.DATA_CATEGORY_PROPERTY, None)
|
| 43 |
+
|
| 44 |
+
@staticmethod
|
| 45 |
+
def set_stdm_data_category_for_layout(layout: QgsLayout, category: Optional[str]):
|
| 46 |
+
layout.setCustomProperty(LayoutUtils.DATA_CATEGORY_PROPERTY, category)
|
| 47 |
+
|
| 48 |
+
@staticmethod
|
| 49 |
+
def get_stdm_referenced_table_for_layout(layout: QgsLayout) -> Optional[str]:
|
| 50 |
+
return layout.customProperty(LayoutUtils.REFERENCED_TABLE_PROPERTY, None)
|
| 51 |
+
|
| 52 |
+
@staticmethod
|
| 53 |
+
def set_stdm_referenced_table_for_layout(layout: QgsLayout, table: Optional[str]):
|
| 54 |
+
layout.setCustomProperty(LayoutUtils.REFERENCED_TABLE_PROPERTY, table)
|
| 55 |
+
|
| 56 |
+
@staticmethod
|
| 57 |
+
def load_template_into_layout(layout: QgsLayout, file_path: str):
|
| 58 |
+
"""
|
| 59 |
+
Loads a document template into the view and updates the necessary STDM-related composer items.
|
| 60 |
+
"""
|
| 61 |
+
copy_file = file_path.replace('sdt', 'cpy')
|
| 62 |
+
|
| 63 |
+
# remove existing copy file
|
| 64 |
+
if QFile.exists(copy_file):
|
| 65 |
+
copy_template = QFile(copy_file)
|
| 66 |
+
copy_template.remove()
|
| 67 |
+
|
| 68 |
+
orig_template_file = QFile(file_path)
|
| 69 |
+
|
| 70 |
+
layout.setCustomProperty('variable_template_path', file_path)
|
| 71 |
+
|
| 72 |
+
# make a copy of the original
|
| 73 |
+
orig_template_file.copy(copy_file)
|
| 74 |
+
|
| 75 |
+
# work with copy
|
| 76 |
+
template_file = QFile(copy_file)
|
| 77 |
+
|
| 78 |
+
if not template_file.open(QIODevice.ReadOnly):
|
| 79 |
+
raise IOError(template_file.errorString())
|
| 80 |
+
|
| 81 |
+
template_doc = QDomDocument()
|
| 82 |
+
if template_doc.setContent(template_file):
|
| 83 |
+
# First load vector layers for the table definitions in the config
|
| 84 |
+
# collection before loading the composition from file.
|
| 85 |
+
|
| 86 |
+
# table_config_collection = TableConfigurationCollection.create(template_doc)
|
| 87 |
+
|
| 88 |
+
# Load items into the composition and configure STDM data controls
|
| 89 |
+
context = QgsReadWriteContext()
|
| 90 |
+
try:
|
| 91 |
+
layout.loadFromTemplate(template_doc, context)
|
| 92 |
+
except:
|
| 93 |
+
pass
|
| 94 |
+
|
| 95 |
+
LayoutUtils.sync_ids_with_uuids(layout)
|
| 96 |
+
|
| 97 |
+
template_file.close()
|
| 98 |
+
|
| 99 |
+
@staticmethod
|
| 100 |
+
def sync_ids_with_uuids(layout: QgsLayout):
|
| 101 |
+
"""
|
| 102 |
+
Matches IDs of custom STDM items with the corresponding UUIDs. This
|
| 103 |
+
is applied when loading existing templates so that the saved
|
| 104 |
+
document contains a matching pair of ID and UUID for each composer
|
| 105 |
+
item.
|
| 106 |
+
"""
|
| 107 |
+
items = [i for i in layout.items() if isinstance(i, QgsLayoutItem)]
|
| 108 |
+
for i in items:
|
| 109 |
+
i.setId(i.uuid())
|
pool/shard009/Python/0080522_demo.py
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Opus/UrbanSim urban simulation software.
|
| 2 |
+
# Copyright (C) 2005-2009 University of Washington
|
| 3 |
+
# See opus_core/LICENSE
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
import os
|
| 7 |
+
|
| 8 |
+
from numpy.random import seed
|
| 9 |
+
from numpy import ones, array, where
|
| 10 |
+
from random import sample
|
| 11 |
+
|
| 12 |
+
from opus_core.coefficients import Coefficients
|
| 13 |
+
from opus_core.equation_specification import EquationSpecification
|
| 14 |
+
from opus_core.resources import Resources
|
| 15 |
+
from opus_core.storage_factory import StorageFactory
|
| 16 |
+
from opus_core.session_configuration import SessionConfiguration
|
| 17 |
+
|
| 18 |
+
from urbansim.datasets.household_dataset import HouseholdDataset
|
| 19 |
+
from urbansim.datasets.gridcell_dataset import GridcellDataset
|
| 20 |
+
from urbansim.datasets.zone_dataset import ZoneDataset
|
| 21 |
+
from urbansim.datasets.job_dataset import JobDataset
|
| 22 |
+
from urbansim.models.household_location_choice_model_creator import HouseholdLocationChoiceModelCreator
|
| 23 |
+
|
| 24 |
+
from opus_core.database_management.database_server import DatabaseServer
|
| 25 |
+
from opus_core.database_management.configurations.scenario_database_configuration import ScenarioDatabaseConfiguration
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
# Datasets
|
| 29 |
+
##########
|
| 30 |
+
# agents from householdset.tab
|
| 31 |
+
agents = HouseholdDataset(in_storage = StorageFactory().get_storage('tab_storage', storage_location='.'),
|
| 32 |
+
in_table_name = "householdset", id_name="agent_id")
|
| 33 |
+
|
| 34 |
+
agents.summary()
|
| 35 |
+
agents.get_attribute("income")
|
| 36 |
+
agents.plot_histogram("income", bins = 10)
|
| 37 |
+
agents.r_histogram("income")
|
| 38 |
+
agents.r_scatter("income", "persons")
|
| 39 |
+
|
| 40 |
+
# gridcells from PSRC
|
| 41 |
+
locations_psrc = GridcellDataset(in_storage = StorageFactory().get_storage('flt_storage',
|
| 42 |
+
storage_location = "/home/hana/bandera/urbansim/data/GPSRC"),
|
| 43 |
+
in_table_name = "gc")
|
| 44 |
+
locations_psrc.summary()
|
| 45 |
+
locations_psrc.plot_histogram("distance_to_highway", bins = 15)
|
| 46 |
+
locations_psrc.r_image("distance_to_highway")
|
| 47 |
+
locations_psrc.plot_map("distance_to_highway")
|
| 48 |
+
|
| 49 |
+
locations_psrc.compute_variables("urbansim.gridcell.ln_total_land_value")
|
| 50 |
+
locations_psrc.plot_map("ln_total_land_value")
|
| 51 |
+
|
| 52 |
+
# Models
|
| 53 |
+
########
|
| 54 |
+
|
| 55 |
+
#HLCM
|
| 56 |
+
|
| 57 |
+
# locations from gridcellset.tab
|
| 58 |
+
locations= GridcellDataset(in_storage = StorageFactory().get_storage('tab_storage', storage_location = "."),
|
| 59 |
+
in_table_name = "gridcellset", id_name="location")
|
| 60 |
+
locations.summary()
|
| 61 |
+
|
| 62 |
+
seed(1)
|
| 63 |
+
|
| 64 |
+
coefficients = Coefficients(names=("costcoef", ), values=(-0.01,))
|
| 65 |
+
|
| 66 |
+
specification = EquationSpecification(variables=("gridcell.cost", ),
|
| 67 |
+
coefficients=("costcoef", ))
|
| 68 |
+
|
| 69 |
+
hlcm = HouseholdLocationChoiceModelCreator().get_model(
|
| 70 |
+
location_set = locations,
|
| 71 |
+
sampler=None,
|
| 72 |
+
utilities="opus_core.linear_utilities",
|
| 73 |
+
probabilities="opus_core.mnl_probabilities",
|
| 74 |
+
choices="opus_core.random_choices_from_index",
|
| 75 |
+
compute_capacity_flag=False)
|
| 76 |
+
|
| 77 |
+
agents.get_attribute("location")
|
| 78 |
+
results = hlcm.run(specification, coefficients, agents)
|
| 79 |
+
agents.get_attribute("location")
|
| 80 |
+
hlcm.upc_sequence.plot_choice_histograms(
|
| 81 |
+
capacity=locations.get_attribute("vacant_units"))
|
| 82 |
+
hlcm.upc_sequence.show_plots()
|
| 83 |
+
|
| 84 |
+
coef, results = hlcm.estimate(specification, agents)
|
| 85 |
+
|
| 86 |
+
results = hlcm.run(specification, coef, agents)
|
| 87 |
+
hlcm.upc_sequence.plot_choice_histograms(
|
| 88 |
+
capacity=locations.get_attribute("vacant_units"))
|
| 89 |
+
hlcm.upc_sequence.show_plots()
|
| 90 |
+
|
| 91 |
+
hlcm2 = HouseholdLocationChoiceModelCreator().get_model(
|
| 92 |
+
location_set = locations,
|
| 93 |
+
sampler=None,
|
| 94 |
+
utilities="opus_core.linear_utilities",
|
| 95 |
+
probabilities="opus_core.mnl_probabilities",
|
| 96 |
+
choices="urbansim.lottery_choices",
|
| 97 |
+
compute_capacity_flag=True,
|
| 98 |
+
run_config=Resources({"capacity_string":"gridcell.vacant_units"}))
|
| 99 |
+
|
| 100 |
+
agents.set_values_of_one_attribute("location", -1*ones(agents.size()))
|
| 101 |
+
agents.get_attribute("location")
|
| 102 |
+
|
| 103 |
+
results = hlcm2.run(specification, coefficients, agents)
|
| 104 |
+
agents.get_attribute("location")
|
| 105 |
+
hlcm2.upc_sequence.plot_choice_histograms(
|
| 106 |
+
capacity=locations.get_attribute("vacant_units"))
|
| 107 |
+
hlcm2.upc_sequence.show_plots()
|
| 108 |
+
coef, results = hlcm2.estimate(specification, agents)
|
| 109 |
+
|
| 110 |
+
#HLCM on PSRC
|
| 111 |
+
# households from PSRC
|
| 112 |
+
agents_psrc = HouseholdDataset(in_storage = StorageFactory().get_storage('flt_storage',
|
| 113 |
+
storage_location = "/home/hana/bandera/urbansim/data/GPSRC"),
|
| 114 |
+
in_table_name = "hh")
|
| 115 |
+
agents_psrc.summary()
|
| 116 |
+
|
| 117 |
+
dbcon = []
|
| 118 |
+
|
| 119 |
+
config = ScenarioDatabaseConfiguration()
|
| 120 |
+
server = DatabaseServer(config)
|
| 121 |
+
db = server.get_database('PSRC_2000_baseyear')
|
| 122 |
+
|
| 123 |
+
storage = StorageFactory().get_storage(
|
| 124 |
+
'sql_storage',
|
| 125 |
+
storage_location = db)
|
| 126 |
+
|
| 127 |
+
coefficients = Coefficients(in_storage=storage)
|
| 128 |
+
coefficients.load(in_table_name="household_location_choice_model_coefficients")
|
| 129 |
+
specification = EquationSpecification(in_storage=storage)
|
| 130 |
+
specification.load(in_table_name="household_location_choice_model_specification")
|
| 131 |
+
specification.get_variable_names()
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
hlcm_psrc = HouseholdLocationChoiceModelCreator().get_model(
|
| 135 |
+
location_set = locations_psrc,
|
| 136 |
+
sampler = "opus_core.samplers.weighted_sampler",
|
| 137 |
+
sample_size_locations=10,
|
| 138 |
+
choices="urbansim.lottery_choices",
|
| 139 |
+
compute_capacity_flag=True,
|
| 140 |
+
run_config=Resources({"capacity_string":"urbansim.gridcell.vacant_residential_units"}))
|
| 141 |
+
|
| 142 |
+
result = hlcm_psrc.run(specification, coefficients, agents_psrc,
|
| 143 |
+
agents_index=sample(range(agents_psrc.size()), 500),
|
| 144 |
+
debuglevel=4)
|
| 145 |
+
# run it again
|
| 146 |
+
|
| 147 |
+
idx = where(agents_psrc.get_attribute("grid_id")>0)[0]
|
| 148 |
+
idx.size
|
| 149 |
+
coef, result = hlcm_psrc.estimate(specification, agents_psrc,
|
| 150 |
+
agents_index=idx,
|
| 151 |
+
estimate_config=Resources({"estimation_size_agents":0.01}),
|
| 152 |
+
debuglevel=4)
|
| 153 |
+
|
| 154 |
+
result = hlcm_psrc.run(specification, coef, agents_psrc,
|
| 155 |
+
agents_index=sample(range(agents_psrc.size()), 500),
|
| 156 |
+
debuglevel=4)
|
| 157 |
+
|
| 158 |
+
storage = StorageFactory().get_storage(
|
| 159 |
+
'sql_storage',
|
| 160 |
+
storage_location = db)
|
| 161 |
+
|
| 162 |
+
zones_psrc = ZoneDataset(in_storage = storage)
|
| 163 |
+
hlcm_psrc_zones = HouseholdLocationChoiceModelCreator().get_model(
|
| 164 |
+
location_set = zones_psrc,
|
| 165 |
+
sampler = "opus_core.samplers.weighted_sampler",
|
| 166 |
+
sample_size_locations=10,
|
| 167 |
+
choices="opus_core.random_choices_from_index",
|
| 168 |
+
compute_capacity_flag=False,
|
| 169 |
+
estimate_config=Resources({"weights_for_estimation_string":None}))
|
| 170 |
+
|
| 171 |
+
specification = EquationSpecification(variables=(
|
| 172 |
+
"urbansim.zone.number_of_jobs",
|
| 173 |
+
"urbansim.household.income"),
|
| 174 |
+
coefficients=(
|
| 175 |
+
"NOJ", "INC"))
|
| 176 |
+
|
| 177 |
+
agents_psrc.compute_variables(["urbansim.household.zone_id"],
|
| 178 |
+
resources=Resources({"gridcell":locations_psrc}))
|
| 179 |
+
jobs_psrc = JobDataset(in_storage = StorageFactory().get_storage('flt_storage',
|
| 180 |
+
storage_location = "/home/hana/urbansim/data/GPSRC"),
|
| 181 |
+
in_table_name = "jobs")
|
| 182 |
+
coef, result = hlcm_psrc_zones.estimate(specification, agents_psrc,
|
| 183 |
+
agents_index=idx,
|
| 184 |
+
estimate_config=Resources({"estimation_size_agents":0.01}),
|
| 185 |
+
data_objects={"job":jobs_psrc, "gridcell":locations_psrc},
|
| 186 |
+
debuglevel=4)
|
| 187 |
+
|
| 188 |
+
result = hlcm_psrc_zones.run(specification, coef, agents_psrc,
|
| 189 |
+
agents_index=array(sample(range(agents_psrc.size()), 500)),
|
| 190 |
+
data_objects={"job":jobs_psrc, "gridcell":locations_psrc},
|
| 191 |
+
debuglevel=4)
|
pool/shard009/Python/0080525_test_data_objects.py
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import copy
|
| 2 |
+
import uuid
|
| 3 |
+
from rest_framework.serializers import ValidationError
|
| 4 |
+
from django.test import TestCase
|
| 5 |
+
|
| 6 |
+
from . import fixtures, get_mock_context
|
| 7 |
+
from api.serializers.data_objects import DataObjectSerializer, \
|
| 8 |
+
FileResourceSerializer
|
| 9 |
+
from api.models.data_objects import DataObject
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class TestDataObjectSerializer(TestCase):
|
| 13 |
+
|
| 14 |
+
def testCreate_file(self):
|
| 15 |
+
data = fixtures.data_objects.file_data_object
|
| 16 |
+
s = DataObjectSerializer(data=data)
|
| 17 |
+
s.is_valid(raise_exception=True)
|
| 18 |
+
data_object = s.save()
|
| 19 |
+
self.assertEqual(data_object.file_resource.filename,
|
| 20 |
+
data['value']['filename'])
|
| 21 |
+
|
| 22 |
+
def testCreate_countQueries(self):
|
| 23 |
+
data = fixtures.data_objects.file_data_object
|
| 24 |
+
s = DataObjectSerializer(data=data)
|
| 25 |
+
s.is_valid(raise_exception=True)
|
| 26 |
+
self.assertNumQueries(4, lambda: s.save())
|
| 27 |
+
|
| 28 |
+
def testRender_file(self):
|
| 29 |
+
file_data = fixtures.data_objects.file_data_object['value']
|
| 30 |
+
data_object = DataObject.create_and_initialize_file_resource(**file_data)
|
| 31 |
+
s = DataObjectSerializer(data_object,
|
| 32 |
+
context=get_mock_context())
|
| 33 |
+
rendered_data = s.data
|
| 34 |
+
value = rendered_data['value']
|
| 35 |
+
self.assertEqual(value['filename'], file_data['filename'])
|
| 36 |
+
self.assertEqual(value['md5'], file_data['md5'])
|
| 37 |
+
self.assertEqual(value['source_type'], file_data['source_type'])
|
| 38 |
+
self.assertEqual(value['import_comments'], file_data['import_comments'])
|
| 39 |
+
self.assertEqual(value['imported_from_url'], file_data['imported_from_url'])
|
| 40 |
+
|
| 41 |
+
def testRoundTrip_file(self):
|
| 42 |
+
file_data = fixtures.data_objects.file_data_object['value']
|
| 43 |
+
data_object = DataObject.create_and_initialize_file_resource(**file_data)
|
| 44 |
+
s = DataObjectSerializer(data_object,
|
| 45 |
+
context=get_mock_context())
|
| 46 |
+
rendered_1 = s.data
|
| 47 |
+
|
| 48 |
+
# update UUID to avoid collision
|
| 49 |
+
input_2 = copy.deepcopy(rendered_1)
|
| 50 |
+
input_2['uuid'] = str(uuid.uuid4())
|
| 51 |
+
s = DataObjectSerializer(data=input_2)
|
| 52 |
+
s.is_valid(raise_exception=True)
|
| 53 |
+
data_object = s.save()
|
| 54 |
+
s = DataObjectSerializer(data_object,
|
| 55 |
+
context=get_mock_context())
|
| 56 |
+
rendered_2 = s.data
|
| 57 |
+
|
| 58 |
+
self.assertEqual(rendered_1['type'],
|
| 59 |
+
rendered_2['type'])
|
| 60 |
+
self.assertEqual(rendered_1['datetime_created'],
|
| 61 |
+
rendered_2['datetime_created'])
|
| 62 |
+
self.assertNotEqual(rendered_1['uuid'],
|
| 63 |
+
rendered_2['uuid'])
|
| 64 |
+
self.assertNotEqual(rendered_1['url'],
|
| 65 |
+
rendered_2['url'])
|
| 66 |
+
self.assertEqual(rendered_1['value']['filename'],
|
| 67 |
+
rendered_2['value']['filename'])
|
| 68 |
+
self.assertEqual(rendered_1['value']['md5'],
|
| 69 |
+
rendered_2['value']['md5'])
|
| 70 |
+
self.assertEqual(rendered_1['value']['import_comments'],
|
| 71 |
+
rendered_2['value']['import_comments'])
|
| 72 |
+
self.assertEqual(rendered_1['value']['imported_from_url'],
|
| 73 |
+
rendered_2['value']['imported_from_url'])
|
| 74 |
+
self.assertEqual(rendered_1['value']['upload_status'],
|
| 75 |
+
rendered_2['value']['upload_status'])
|
| 76 |
+
self.assertEqual(rendered_1['value']['source_type'],
|
| 77 |
+
rendered_2['value']['source_type'])
|
| 78 |
+
self.assertEqual(rendered_1['value']['file_url'],
|
| 79 |
+
rendered_2['value']['file_url'])
|
| 80 |
+
|
| 81 |
+
def testCreate_AlreadyExists(self):
|
| 82 |
+
file_data = copy.deepcopy(fixtures.data_objects.file_data_object)['value']
|
| 83 |
+
data_object = DataObject.create_and_initialize_file_resource(**file_data)
|
| 84 |
+
s = DataObjectSerializer(data_object,
|
| 85 |
+
context=get_mock_context())
|
| 86 |
+
rendered_1 = s.data
|
| 87 |
+
|
| 88 |
+
data_object_count_before = DataObject.objects.count()
|
| 89 |
+
s = DataObjectSerializer(data=rendered_1)
|
| 90 |
+
s.is_valid(raise_exception=True)
|
| 91 |
+
data_object = s.save()
|
| 92 |
+
|
| 93 |
+
# Verify that no new object was created
|
| 94 |
+
data_object_count_after = DataObject.objects.count()
|
| 95 |
+
self.assertEqual(data_object_count_before, data_object_count_after)
|
| 96 |
+
|
| 97 |
+
def testCreate_ErrorAlreadyExistsWithMismatch(self):
|
| 98 |
+
file_data = copy.deepcopy(fixtures.data_objects.file_data_object)['value']
|
| 99 |
+
data_object = DataObject.create_and_initialize_file_resource(**file_data)
|
| 100 |
+
s = DataObjectSerializer(data_object,
|
| 101 |
+
context=get_mock_context())
|
| 102 |
+
data_object_count_before = DataObject.objects.count()
|
| 103 |
+
|
| 104 |
+
rendered_1 = s.data
|
| 105 |
+
rendered_1['value']['md5'] = '192f08c86f675deca469ea50ffac38e0'
|
| 106 |
+
s = DataObjectSerializer(data=rendered_1)
|
| 107 |
+
with self.assertRaises(ValidationError):
|
| 108 |
+
s.is_valid(raise_exception=True)
|
| 109 |
+
data_object = s.save()
|
| 110 |
+
|
| 111 |
+
# Verify that no new object was created
|
| 112 |
+
data_object_count_after = DataObject.objects.count()
|
| 113 |
+
self.assertEqual(data_object_count_before, data_object_count_after)
|
| 114 |
+
|
| 115 |
+
def testCreate_noDroolOnFail(self):
|
| 116 |
+
file_data = copy.deepcopy(fixtures.data_objects.file_data_object)
|
| 117 |
+
file_data['value']['md5'] = 'invalid_md5'
|
| 118 |
+
|
| 119 |
+
data_object_count_before = DataObject.objects.count()
|
| 120 |
+
s = DataObjectSerializer(data=file_data)
|
| 121 |
+
s.is_valid(raise_exception=True)
|
| 122 |
+
with self.assertRaises(ValidationError):
|
| 123 |
+
m = s.save()
|
| 124 |
+
data_object_count_after = DataObject.objects.count()
|
| 125 |
+
|
| 126 |
+
self.assertEqual(data_object_count_before, data_object_count_after)
|
| 127 |
+
|
| 128 |
+
data_object_fixtures = [
|
| 129 |
+
copy.deepcopy(fixtures.data_objects.string_data_object),
|
| 130 |
+
copy.deepcopy(fixtures.data_objects.boolean_data_object),
|
| 131 |
+
copy.deepcopy(fixtures.data_objects.float_data_object),
|
| 132 |
+
copy.deepcopy(fixtures.data_objects.integer_data_object)
|
| 133 |
+
]
|
| 134 |
+
|
| 135 |
+
def testCreate_nonFileTypes(self):
|
| 136 |
+
for data in self.data_object_fixtures:
|
| 137 |
+
s = DataObjectSerializer(data=data)
|
| 138 |
+
s.is_valid(raise_exception=True)
|
| 139 |
+
data_object = s.save()
|
| 140 |
+
self.assertEqual(data_object.value, data['value'])
|
| 141 |
+
|
| 142 |
+
rendered_data = DataObjectSerializer(
|
| 143 |
+
data_object, context=get_mock_context()).data
|
| 144 |
+
self.assertEqual(data_object.value, rendered_data['value'])
|
| 145 |
+
|
| 146 |
+
def testRoundTrip_nonFileTypes(self):
|
| 147 |
+
for data in self.data_object_fixtures:
|
| 148 |
+
s1 = DataObjectSerializer(data=data)
|
| 149 |
+
s1.is_valid(raise_exception=True)
|
| 150 |
+
data_object_1 = s1.save()
|
| 151 |
+
self.assertEqual(data_object_1.value, data['value'])
|
| 152 |
+
rendered_data = DataObjectSerializer(
|
| 153 |
+
data_object_1, context=get_mock_context()).data
|
| 154 |
+
|
| 155 |
+
# Update UUID to avoid collision
|
| 156 |
+
rendered_data['uuid'] = uuid.uuid4()
|
| 157 |
+
s2 = DataObjectSerializer(data=rendered_data)
|
| 158 |
+
s2.is_valid(raise_exception=True)
|
| 159 |
+
data_object_2 = s2.save()
|
| 160 |
+
self.assertEqual(data_object_1.value, data_object_2.value)
|
| 161 |
+
|
| 162 |
+
def TestDataObjectUpdateSerializer(TestCase):
|
| 163 |
+
|
| 164 |
+
def testUpdateUploadStatus(self):
|
| 165 |
+
file_data = fixtures.data_objects.file_data_object['value']
|
| 166 |
+
data_object = DataObject.create_and_initialize_file_resource(**file_data)
|
| 167 |
+
s = DataObjectSerializer(data_object,
|
| 168 |
+
context=get_mock_context())
|
| 169 |
+
s.save()
|
| 170 |
+
|
| 171 |
+
s2 = DataObjectUpdateSerializer(data_object)
|
| 172 |
+
s2.update(
|
| 173 |
+
data_object, {'value': {'upload_status': 'error'}})
|
| 174 |
+
self.assertEqual(s2.data['value']['upload_status'], 'error')
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def testUpdateProtectedValue(self):
|
| 178 |
+
file_data = fixtures.data_objects.file_data_object['value']
|
| 179 |
+
data_object = DataObject.create_and_initialize_file_resource(**file_data)
|
| 180 |
+
s = DataObjectSerializer(data_object,
|
| 181 |
+
context=get_mock_context())
|
| 182 |
+
s.save()
|
| 183 |
+
|
| 184 |
+
s2 = DataObjectUpdateSerializer(data_object)
|
| 185 |
+
with self.assertRaises(ValidationError):
|
| 186 |
+
s2.update(
|
| 187 |
+
data_object, {'type': 'string'})
|
pool/shard009/Python/0080526_base.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import unicode_literals
|
| 2 |
+
from webfriend.scripting.scope import Scope
|
| 3 |
+
import inspect
|
| 4 |
+
import importlib
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class CommandProxy(object):
|
| 8 |
+
qualifier = None
|
| 9 |
+
doc_name = None
|
| 10 |
+
default_qualifier = 'core'
|
| 11 |
+
default_method_name = 'default'
|
| 12 |
+
|
| 13 |
+
enabled_proxies = [
|
| 14 |
+
'cookies',
|
| 15 |
+
'core',
|
| 16 |
+
'file',
|
| 17 |
+
'fmt',
|
| 18 |
+
'page',
|
| 19 |
+
'utils',
|
| 20 |
+
'vars',
|
| 21 |
+
]
|
| 22 |
+
|
| 23 |
+
def __init__(self, browser, environment=None, scope=None):
|
| 24 |
+
self.browser = browser
|
| 25 |
+
self.environment = environment
|
| 26 |
+
self.scope = (scope or Scope())
|
| 27 |
+
self._tab = None
|
| 28 |
+
|
| 29 |
+
@property
|
| 30 |
+
def tab(self):
|
| 31 |
+
if self._tab is None:
|
| 32 |
+
return self.browser.default
|
| 33 |
+
else:
|
| 34 |
+
try:
|
| 35 |
+
return self.browser.tabs[self._tab]
|
| 36 |
+
except KeyError:
|
| 37 |
+
raise KeyError("Could not retrieve unknown tab '{}'".format(self._tab))
|
| 38 |
+
|
| 39 |
+
def __contains__(self, local_command_name):
|
| 40 |
+
try:
|
| 41 |
+
if local_command_name == self.as_qualifier():
|
| 42 |
+
return callable(getattr(self, self.default_method_name))
|
| 43 |
+
else:
|
| 44 |
+
return callable(getattr(self, local_command_name))
|
| 45 |
+
except AttributeError:
|
| 46 |
+
pass
|
| 47 |
+
|
| 48 |
+
return False
|
| 49 |
+
|
| 50 |
+
def __getitem__(self, local_command_name):
|
| 51 |
+
if local_command_name == self.as_qualifier():
|
| 52 |
+
return getattr(self, self.default_method_name)
|
| 53 |
+
else:
|
| 54 |
+
return getattr(self, local_command_name)
|
| 55 |
+
|
| 56 |
+
def has_default(self):
|
| 57 |
+
return (self.as_qualifier() in self)
|
| 58 |
+
|
| 59 |
+
@classmethod
|
| 60 |
+
def get_all_proxies(cls):
|
| 61 |
+
proxies = []
|
| 62 |
+
for proxy_module in cls.enabled_proxies:
|
| 63 |
+
module = importlib.import_module('webfriend.scripting.commands.{}'.format(
|
| 64 |
+
proxy_module
|
| 65 |
+
))
|
| 66 |
+
|
| 67 |
+
members = inspect.getmembers(module, inspect.isclass)
|
| 68 |
+
|
| 69 |
+
for subcls in members:
|
| 70 |
+
if issubclass(subcls[1], CommandProxy) and subcls[1] is not CommandProxy:
|
| 71 |
+
proxies.append((subcls[1].as_qualifier(), subcls[1]))
|
| 72 |
+
|
| 73 |
+
return proxies
|
| 74 |
+
|
| 75 |
+
@classmethod
|
| 76 |
+
def get_command_names(cls):
|
| 77 |
+
names = set()
|
| 78 |
+
|
| 79 |
+
for name in dir(cls):
|
| 80 |
+
# underscored items are not commands
|
| 81 |
+
if name.startswith('_'):
|
| 82 |
+
continue
|
| 83 |
+
|
| 84 |
+
# methods inherited from CommandProxy are not commands
|
| 85 |
+
if name in dir(CommandProxy):
|
| 86 |
+
continue
|
| 87 |
+
|
| 88 |
+
if callable(getattr(cls, name)):
|
| 89 |
+
if len(cls.as_qualifier()):
|
| 90 |
+
if cls.as_qualifier() == cls.default_qualifier:
|
| 91 |
+
names.add(name)
|
| 92 |
+
elif name == cls.default_method_name:
|
| 93 |
+
names.add(cls.as_qualifier())
|
| 94 |
+
else:
|
| 95 |
+
names.add(cls.qualify(name))
|
| 96 |
+
|
| 97 |
+
return names
|
| 98 |
+
|
| 99 |
+
@classmethod
|
| 100 |
+
def qualify(cls, name):
|
| 101 |
+
if name == cls.as_qualifier():
|
| 102 |
+
return name
|
| 103 |
+
else:
|
| 104 |
+
return '{}::{}'.format(cls.as_qualifier(), name)
|
| 105 |
+
|
| 106 |
+
@classmethod
|
| 107 |
+
def as_qualifier(cls):
|
| 108 |
+
if cls.qualifier is not None:
|
| 109 |
+
return cls.qualifier
|
| 110 |
+
|
| 111 |
+
return cls.__name__.split('.')[-1].replace('Proxy', '').lower()
|
pool/shard009/Python/0080531_daemon.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
#
|
| 3 |
+
# Copyright (C)2006-2009 Edgewall Software
|
| 4 |
+
# All rights reserved.
|
| 5 |
+
#
|
| 6 |
+
# This software is licensed as described in the file COPYING, which
|
| 7 |
+
# you should have received as part of this distribution. The terms
|
| 8 |
+
# are also available at http://trac.edgewall.org/wiki/TracLicense.
|
| 9 |
+
#
|
| 10 |
+
# This software consists of voluntary contributions made by many
|
| 11 |
+
# individuals. For the exact contribution history, see the revision
|
| 12 |
+
# history and logs, available at http://trac.edgewall.org/log/.
|
| 13 |
+
|
| 14 |
+
import atexit
|
| 15 |
+
import errno
|
| 16 |
+
import os
|
| 17 |
+
import signal
|
| 18 |
+
import sys
|
| 19 |
+
|
| 20 |
+
def daemonize(pidfile=None, progname=None, stdin='/dev/null',
|
| 21 |
+
stdout='/dev/null', stderr='/dev/null', umask=022):
|
| 22 |
+
"""Fork a daemon process."""
|
| 23 |
+
|
| 24 |
+
if pidfile:
|
| 25 |
+
# Check whether the pid file already exists and refers to a still
|
| 26 |
+
# process running
|
| 27 |
+
pidfile = os.path.abspath(pidfile)
|
| 28 |
+
if os.path.exists(pidfile):
|
| 29 |
+
fileobj = open(pidfile)
|
| 30 |
+
try:
|
| 31 |
+
try:
|
| 32 |
+
pid = int(fileobj.read())
|
| 33 |
+
except ValueError:
|
| 34 |
+
sys.exit('Invalid PID in file %s' % pidfile)
|
| 35 |
+
finally:
|
| 36 |
+
fileobj.close()
|
| 37 |
+
|
| 38 |
+
try: # signal the process to see if it is still running
|
| 39 |
+
os.kill(pid, 0)
|
| 40 |
+
if not progname:
|
| 41 |
+
progname = os.path.basename(sys.argv[0])
|
| 42 |
+
sys.exit('%s is already running with pid %s' % (progname, pid))
|
| 43 |
+
except OSError, e:
|
| 44 |
+
if e.errno != errno.ESRCH:
|
| 45 |
+
raise
|
| 46 |
+
|
| 47 |
+
# Perform first fork
|
| 48 |
+
pid = os.fork()
|
| 49 |
+
if pid > 0:
|
| 50 |
+
sys.exit(0) # exit first parent
|
| 51 |
+
|
| 52 |
+
# Decouple from parent environment
|
| 53 |
+
os.chdir('/')
|
| 54 |
+
os.umask(umask)
|
| 55 |
+
os.setsid()
|
| 56 |
+
|
| 57 |
+
# Perform second fork
|
| 58 |
+
pid = os.fork()
|
| 59 |
+
if pid > 0:
|
| 60 |
+
sys.exit(0) # exit second parent
|
| 61 |
+
|
| 62 |
+
# The process is now daemonized, redirect standard file descriptors
|
| 63 |
+
for stream in sys.stdout, sys.stderr:
|
| 64 |
+
stream.flush()
|
| 65 |
+
stdin = open(stdin, 'r')
|
| 66 |
+
stdout = open(stdout, 'a+')
|
| 67 |
+
stderr = open(stderr, 'a+', 0)
|
| 68 |
+
os.dup2(stdin.fileno(), sys.stdin.fileno())
|
| 69 |
+
os.dup2(stdout.fileno(), sys.stdout.fileno())
|
| 70 |
+
os.dup2(stderr.fileno(), sys.stderr.fileno())
|
| 71 |
+
|
| 72 |
+
if pidfile:
|
| 73 |
+
# Register signal handlers to ensure atexit hooks are called on exit
|
| 74 |
+
for signum in [signal.SIGTERM, signal.SIGHUP]:
|
| 75 |
+
signal.signal(signum, handle_signal)
|
| 76 |
+
|
| 77 |
+
# Create/update the pid file, and register a hook to remove it when the
|
| 78 |
+
# process exits
|
| 79 |
+
def remove_pidfile():
|
| 80 |
+
if os.path.exists(pidfile):
|
| 81 |
+
os.remove(pidfile)
|
| 82 |
+
atexit.register(remove_pidfile)
|
| 83 |
+
fileobj = open(pidfile, 'w')
|
| 84 |
+
try:
|
| 85 |
+
fileobj.write(str(os.getpid()))
|
| 86 |
+
finally:
|
| 87 |
+
fileobj.close()
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def handle_signal(signum, frame):
|
| 91 |
+
"""Handle signals sent to the daemonized process."""
|
| 92 |
+
sys.exit()
|
pool/shard009/Python/0080535_info_ifaces.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/python
|
| 2 |
+
|
| 3 |
+
# Author: Alfredo Miranda
|
| 4 |
+
# E-mail: alfredocdmiranda@gmail.com
|
| 5 |
+
# Date: 03/01/2015
|
| 6 |
+
#
|
| 7 |
+
# This is a sample code to pyIface, which lists NICs on computer and
|
| 8 |
+
# show information about them.
|
| 9 |
+
|
| 10 |
+
import pynic
|
| 11 |
+
|
| 12 |
+
list_interfaces = pynic.get_list_interfaces()
|
| 13 |
+
|
| 14 |
+
for pos, i in enumerate(list_interfaces):
|
| 15 |
+
print("{0} - {1}".format(pos, i))
|
| 16 |
+
|
| 17 |
+
opt = int(input("Choose the interface: "))
|
| 18 |
+
|
| 19 |
+
print("########## Interface Info ##########")
|
| 20 |
+
iface = pynic.Iface.get_interface(list_interfaces[opt])
|
| 21 |
+
|
| 22 |
+
print("Name: {0}".format(iface.name))
|
| 23 |
+
print("IPv4: {0}".format(iface.inet_addr))
|
| 24 |
+
print("IPv6: {0}".format(iface.inet6_addr))
|
| 25 |
+
print("MAC: {0}".format(iface.hw_addr))
|
| 26 |
+
print("Broadcast: {0}".format(iface.broad_addr))
|
| 27 |
+
print("Netmask: {0}".format(iface.inet_mask))
|
| 28 |
+
print("Netmask v6: {0}".format(iface.inet6_mask))
|
| 29 |
+
print("Running: {0}".format(iface.running))
|
| 30 |
+
print("Up: {0}".format(iface.updown))
|
| 31 |
+
print("TX bytes: {0} bytes".format(iface.tx_bytes))
|
| 32 |
+
print("RX bytes: {0} bytes".format(iface.rx_bytes))
|
| 33 |
+
print("TX packets: {0} packets".format(iface.tx_packets))
|
| 34 |
+
print("RX packets: {0} packets".format(iface.rx_packets))
|
pool/shard009/Python/0080537_main.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
"""
|
| 3 |
+
Ocean is a n1 x n2 grid.
|
| 4 |
+
|
| 5 |
+
Goals:
|
| 6 |
+
Print the grid of the ocean using ^ for empty cells
|
| 7 |
+
Add the ships and print them as X's
|
| 8 |
+
Let the user fire shots at coordinates and mark on map
|
| 9 |
+
Determin if a shot hit a ship
|
| 10 |
+
Determine if entire ship has been shot.
|
| 11 |
+
Determine if all ships have been shot.
|
| 12 |
+
|
| 13 |
+
User enters coordinate and finds out if they hit a ship and sank it.
|
| 14 |
+
"""
|
| 15 |
+
#
|
| 16 |
+
#
|
| 17 |
+
# THIS IS A SOLVED SOLUTION. DON'T EDIT.
|
| 18 |
+
#
|
| 19 |
+
# If this is an interview, don't read this until you've solved your version.
|
| 20 |
+
#
|
| 21 |
+
#
|
| 22 |
+
#
|
| 23 |
+
#
|
| 24 |
+
#
|
| 25 |
+
#
|
| 26 |
+
#
|
| 27 |
+
#
|
| 28 |
+
#
|
| 29 |
+
#
|
| 30 |
+
#
|
| 31 |
+
#
|
| 32 |
+
#
|
| 33 |
+
#
|
| 34 |
+
#
|
| 35 |
+
#
|
| 36 |
+
#
|
| 37 |
+
#
|
| 38 |
+
#
|
| 39 |
+
#
|
| 40 |
+
#
|
| 41 |
+
#
|
| 42 |
+
#
|
| 43 |
+
#
|
| 44 |
+
#
|
| 45 |
+
#
|
| 46 |
+
#
|
| 47 |
+
#
|
| 48 |
+
#
|
| 49 |
+
#
|
| 50 |
+
#
|
| 51 |
+
#
|
| 52 |
+
#
|
| 53 |
+
#
|
| 54 |
+
#
|
| 55 |
+
#
|
| 56 |
+
#
|
| 57 |
+
#
|
| 58 |
+
#
|
| 59 |
+
#
|
| 60 |
+
#
|
| 61 |
+
#
|
| 62 |
+
#
|
| 63 |
+
#
|
| 64 |
+
#
|
| 65 |
+
#
|
| 66 |
+
#
|
| 67 |
+
#
|
| 68 |
+
# level 1
|
| 69 |
+
def run():
|
| 70 |
+
ocean = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
|
| 71 |
+
ships = [[(0, 0), (0, 1)], [(2, 2), (2, 3)]]
|
| 72 |
+
some_ship = []
|
| 73 |
+
for ship in ships:
|
| 74 |
+
for coordinate in ship:
|
| 75 |
+
some_ship.append(coordinate)
|
| 76 |
+
for row_id, row in enumerate(ocean):
|
| 77 |
+
for column_id, column in enumerate(row):
|
| 78 |
+
if (row_id, column_id) in some_ship:
|
| 79 |
+
print("X", end="")
|
| 80 |
+
else:
|
| 81 |
+
print("^", end="")
|
| 82 |
+
print()
|
| 83 |
+
|
| 84 |
+
# level 2
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
run()
|
pool/shard009/Python/0080540_sflen.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
""" Flowpath length scatter """
|
| 3 |
+
import cgi
|
| 4 |
+
import cStringIO
|
| 5 |
+
import sys
|
| 6 |
+
import glob
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def read_slope(fn):
|
| 10 |
+
lines = open(fn).readlines()
|
| 11 |
+
data = []
|
| 12 |
+
for line in lines:
|
| 13 |
+
if len(line.strip()) == 0 or line[0] == "#":
|
| 14 |
+
continue
|
| 15 |
+
data.append(line)
|
| 16 |
+
fplen = data[2].split()[0]
|
| 17 |
+
xs = []
|
| 18 |
+
slp = []
|
| 19 |
+
travel = 0
|
| 20 |
+
for i in range(3, len(data), 2):
|
| 21 |
+
slen = float(data[i].split()[1])
|
| 22 |
+
nums = data[i + 1].replace(",", "").split()
|
| 23 |
+
for pos in nums[0 : len(nums) : 2]:
|
| 24 |
+
xs.append(float(pos) * slen + travel)
|
| 25 |
+
for pos in nums[1 : len(nums) : 2]:
|
| 26 |
+
slp.append(float(pos))
|
| 27 |
+
travel += slen
|
| 28 |
+
h2 = [0]
|
| 29 |
+
x2 = [0]
|
| 30 |
+
for x, s in zip(xs, slp):
|
| 31 |
+
h2.append(h2[-1] + (x - x2[-1]) * (0 - s))
|
| 32 |
+
x2.append(x)
|
| 33 |
+
|
| 34 |
+
return x2, h2, travel
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def make_plot(huc_12):
|
| 38 |
+
"""Generate the plot please"""
|
| 39 |
+
|
| 40 |
+
import matplotlib
|
| 41 |
+
|
| 42 |
+
matplotlib.use("agg")
|
| 43 |
+
import matplotlib.pyplot as plt
|
| 44 |
+
|
| 45 |
+
(fig, ax) = plt.subplots(2, 1)
|
| 46 |
+
|
| 47 |
+
flengths = [[], [], []]
|
| 48 |
+
for fn in glob.glob("/i/1/slp/%s/%s/*.slp" % (huc_12[:8], huc_12[8:])):
|
| 49 |
+
x, y, flen = read_slope(fn)
|
| 50 |
+
flengths[1].append(flen)
|
| 51 |
+
|
| 52 |
+
x, y, flen = read_slope("/i/2" + fn[4:])
|
| 53 |
+
flengths[2].append(flen)
|
| 54 |
+
|
| 55 |
+
ax[0].set_title("Slope Length Comparison for HUC12: %s" % (huc_12,))
|
| 56 |
+
ax[0].scatter(flengths[2], flengths[1])
|
| 57 |
+
ax[0].set_xlim(left=0)
|
| 58 |
+
ax[0].grid(True)
|
| 59 |
+
ax[0].set_ylim(bottom=0)
|
| 60 |
+
ax[0].plot([0, max(flengths[2])], [0, max(flengths[2])])
|
| 61 |
+
ax[0].set_xlabel("dbfsOrgnlTesting slope length [m]")
|
| 62 |
+
ax[0].set_ylabel("G4 slope length [m]")
|
| 63 |
+
|
| 64 |
+
ax[1].boxplot([flengths[1], flengths[2]])
|
| 65 |
+
ax[1].set_xticks([1, 2])
|
| 66 |
+
ax[1].set_xticklabels(["IDEPv2 G4", "IDEPv2 dbfsOrgnlTesting"])
|
| 67 |
+
ax[1].set_ylabel("Slope Length (m)")
|
| 68 |
+
ax[1].grid(True)
|
| 69 |
+
|
| 70 |
+
ram = cStringIO.StringIO()
|
| 71 |
+
plt.savefig(ram, format="png")
|
| 72 |
+
ram.seek(0)
|
| 73 |
+
r = ram.read()
|
| 74 |
+
|
| 75 |
+
sys.stdout.write("Content-type: image/png\n\n")
|
| 76 |
+
sys.stdout.write(r)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
if __name__ == "__main__":
|
| 80 |
+
# Go Main Go
|
| 81 |
+
form = cgi.FieldStorage()
|
| 82 |
+
huc_12 = form.getfirst("huc_12", "070200090401")
|
| 83 |
+
|
| 84 |
+
make_plot(huc_12)
|
pool/shard009/Python/0080541_filter.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
# coding=utf-8
|
| 3 |
+
def f(x): return x % 2 != 0 and x % 3 !=0
|
| 4 |
+
|
| 5 |
+
a = filter(f, range(2,23))
|
| 6 |
+
|
| 7 |
+
print a
|
| 8 |
+
|
| 9 |
+
def cube(x): return x*x*x
|
| 10 |
+
|
| 11 |
+
b = map(cube, range(2,11))
|
| 12 |
+
|
| 13 |
+
print b
|
| 14 |
+
|
| 15 |
+
seq = range(10)
|
| 16 |
+
def addi(x,y):
|
| 17 |
+
#print x,y
|
| 18 |
+
#print '--'*20
|
| 19 |
+
return (x+y)
|
| 20 |
+
|
| 21 |
+
c = map(addi, seq, seq)
|
| 22 |
+
|
| 23 |
+
#print c
|
| 24 |
+
|
| 25 |
+
d = reduce(addi, range(1,11))
|
| 26 |
+
|
| 27 |
+
print d
|
| 28 |
+
|
| 29 |
+
print '--'*40
|
| 30 |
+
m = []
|
| 31 |
+
|
| 32 |
+
def subtration(x,y):
|
| 33 |
+
global m
|
| 34 |
+
print x,y
|
| 35 |
+
if x > y:
|
| 36 |
+
print "dayu"
|
| 37 |
+
return (x-y)
|
| 38 |
+
elif x < y:
|
| 39 |
+
print 'xiaoyu',x,y
|
| 40 |
+
m.append(y-x)
|
| 41 |
+
return (y-x)
|
| 42 |
+
else:
|
| 43 |
+
print 'dengyu'
|
| 44 |
+
return 0
|
| 45 |
+
pass
|
| 46 |
+
|
| 47 |
+
e = reduce(subtration, range(10,20))
|
| 48 |
+
|
| 49 |
+
print e
|
| 50 |
+
print '--'*40
|
| 51 |
+
print m
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def sum(seq):
|
| 55 |
+
def add(x,y): return x+y
|
| 56 |
+
return reduce(add, seq, 0)
|
| 57 |
+
|
| 58 |
+
g = sum(range(1,29))
|
| 59 |
+
|
| 60 |
+
print g
|
pool/shard009/Python/0080551_encryption_usage.py
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -------------------------------------------------------------------------
|
| 2 |
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
| 3 |
+
# Licensed under the MIT License. See License.txt in the project root for
|
| 4 |
+
# license information.
|
| 5 |
+
# --------------------------------------------------------------------------
|
| 6 |
+
import uuid
|
| 7 |
+
from os import urandom
|
| 8 |
+
|
| 9 |
+
from cryptography.hazmat.backends import default_backend
|
| 10 |
+
from cryptography.hazmat.primitives.asymmetric.padding import (
|
| 11 |
+
OAEP,
|
| 12 |
+
MGF1,
|
| 13 |
+
)
|
| 14 |
+
from cryptography.hazmat.primitives.asymmetric.rsa import generate_private_key
|
| 15 |
+
from cryptography.hazmat.primitives.hashes import SHA1
|
| 16 |
+
from cryptography.hazmat.primitives.keywrap import (
|
| 17 |
+
aes_key_wrap,
|
| 18 |
+
aes_key_unwrap,
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
# Sample implementations of the encryption-related interfaces.
|
| 23 |
+
class KeyWrapper:
|
| 24 |
+
def __init__(self, kid):
|
| 25 |
+
self.kek = urandom(32)
|
| 26 |
+
self.backend = default_backend()
|
| 27 |
+
self.kid = 'local:' + kid
|
| 28 |
+
|
| 29 |
+
def wrap_key(self, key, algorithm='A256KW'):
|
| 30 |
+
if algorithm == 'A256KW':
|
| 31 |
+
return aes_key_wrap(self.kek, key, self.backend)
|
| 32 |
+
|
| 33 |
+
raise ValueError(_ERROR_UNKNOWN_KEY_WRAP_ALGORITHM)
|
| 34 |
+
|
| 35 |
+
def unwrap_key(self, key, algorithm):
|
| 36 |
+
if algorithm == 'A256KW':
|
| 37 |
+
return aes_key_unwrap(self.kek, key, self.backend)
|
| 38 |
+
|
| 39 |
+
raise ValueError(_ERROR_UNKNOWN_KEY_WRAP_ALGORITHM)
|
| 40 |
+
|
| 41 |
+
def get_key_wrap_algorithm(self):
|
| 42 |
+
return 'A256KW'
|
| 43 |
+
|
| 44 |
+
def get_kid(self):
|
| 45 |
+
return self.kid
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class KeyResolver:
|
| 49 |
+
def __init__(self):
|
| 50 |
+
self.keys = {}
|
| 51 |
+
|
| 52 |
+
def put_key(self, key):
|
| 53 |
+
self.keys[key.get_kid()] = key
|
| 54 |
+
|
| 55 |
+
def resolve_key(self, kid):
|
| 56 |
+
return self.keys[kid]
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class RSAKeyWrapper:
|
| 60 |
+
def __init__(self, kid):
|
| 61 |
+
self.private_key = generate_private_key(public_exponent=65537,
|
| 62 |
+
key_size=2048,
|
| 63 |
+
backend=default_backend())
|
| 64 |
+
self.public_key = self.private_key.public_key()
|
| 65 |
+
self.kid = 'local:' + kid
|
| 66 |
+
|
| 67 |
+
def wrap_key(self, key, algorithm='RSA'):
|
| 68 |
+
if algorithm == 'RSA':
|
| 69 |
+
return self.public_key.encrypt(key,
|
| 70 |
+
OAEP(
|
| 71 |
+
mgf=MGF1(algorithm=SHA1()),
|
| 72 |
+
algorithm=SHA1(),
|
| 73 |
+
label=None)
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
raise ValueError(_ERROR_UNKNOWN_KEY_WRAP_ALGORITHM)
|
| 77 |
+
|
| 78 |
+
def unwrap_key(self, key, algorithm):
|
| 79 |
+
if algorithm == 'RSA':
|
| 80 |
+
return self.private_key.decrypt(key,
|
| 81 |
+
OAEP(
|
| 82 |
+
mgf=MGF1(algorithm=SHA1()),
|
| 83 |
+
algorithm=SHA1(),
|
| 84 |
+
label=None)
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
raise ValueError(_ERROR_UNKNOWN_KEY_WRAP_ALGORITHM)
|
| 88 |
+
|
| 89 |
+
def get_key_wrap_algorithm(self):
|
| 90 |
+
return 'RSA'
|
| 91 |
+
|
| 92 |
+
def get_kid(self):
|
| 93 |
+
return self.kid
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
class QueueEncryptionSamples():
|
| 97 |
+
def __init__(self, account):
|
| 98 |
+
self.account = account
|
| 99 |
+
|
| 100 |
+
def run_all_samples(self):
|
| 101 |
+
self.service = self.account.create_queue_service()
|
| 102 |
+
|
| 103 |
+
self.put_encrypted_message()
|
| 104 |
+
self.peek_get_update_encrypted()
|
| 105 |
+
self.decrypt_with_key_encryption_key()
|
| 106 |
+
self.require_encryption()
|
| 107 |
+
self.alternate_key_algorithms()
|
| 108 |
+
|
| 109 |
+
def _get_queue_reference(self, prefix='queue'):
|
| 110 |
+
queue_name = '{}{}'.format(prefix, str(uuid.uuid4()).replace('-', ''))
|
| 111 |
+
return queue_name
|
| 112 |
+
|
| 113 |
+
def _create_queue(self, prefix='queue'):
|
| 114 |
+
queue_name = self._get_queue_reference(prefix)
|
| 115 |
+
self.service.create_queue(queue_name)
|
| 116 |
+
return queue_name
|
| 117 |
+
|
| 118 |
+
def put_encrypted_message(self):
|
| 119 |
+
queue_name = self._create_queue()
|
| 120 |
+
|
| 121 |
+
# KeyWrapper implements the key encryption key interface
|
| 122 |
+
# outlined in the get/update message documentation.
|
| 123 |
+
# Setting the key_encryption_key property will tell these
|
| 124 |
+
# APIs to encrypt messages.
|
| 125 |
+
self.service.key_encryption_key = KeyWrapper('key1')
|
| 126 |
+
self.service.put_message(queue_name, 'message1')
|
| 127 |
+
|
| 128 |
+
self.service.delete_queue(queue_name)
|
| 129 |
+
|
| 130 |
+
def peek_get_update_encrypted(self):
|
| 131 |
+
queue_name = self._create_queue()
|
| 132 |
+
|
| 133 |
+
# The KeyWrapper is still needed for encryption
|
| 134 |
+
self.service.key_encryption_key = KeyWrapper('key1')
|
| 135 |
+
self.service.put_message(queue_name, 'message1')
|
| 136 |
+
|
| 137 |
+
# KeyResolver is used to resolve a key from its id.
|
| 138 |
+
# Its interface is defined in the get/peek messages documentation.
|
| 139 |
+
key_resolver = KeyResolver()
|
| 140 |
+
key_resolver.put_key(self.service.key_encryption_key)
|
| 141 |
+
self.service.key_resolver_function = key_resolver.resolve_key
|
| 142 |
+
self.service.peek_messages(queue_name)
|
| 143 |
+
messages = self.service.get_messages(queue_name)
|
| 144 |
+
self.service.update_message(queue_name,
|
| 145 |
+
messages[0].id,
|
| 146 |
+
messages[0].pop_receipt,
|
| 147 |
+
0,
|
| 148 |
+
content='encrypted_message2')
|
| 149 |
+
|
| 150 |
+
self.service.delete_queue(queue_name)
|
| 151 |
+
|
| 152 |
+
def require_encryption(self):
|
| 153 |
+
queue_name = self._create_queue()
|
| 154 |
+
|
| 155 |
+
self.service.put_message(queue_name, 'Not encrypted')
|
| 156 |
+
# Set the require_encryption property on the service to
|
| 157 |
+
# ensure all messages sent/received are encrypted.
|
| 158 |
+
self.service.require_encryption = True
|
| 159 |
+
|
| 160 |
+
# If the property is set, but no kek is specified upon
|
| 161 |
+
# upload, the method will throw.
|
| 162 |
+
try:
|
| 163 |
+
self.service.put_message(queue_name, 'message1')
|
| 164 |
+
except:
|
| 165 |
+
pass
|
| 166 |
+
|
| 167 |
+
self.service.key_encryption_key = KeyWrapper('key1')
|
| 168 |
+
self.service.key_resolver_function = KeyResolver()
|
| 169 |
+
self.service.key_resolver_function.put_key(self.service.key_encryption_key)
|
| 170 |
+
|
| 171 |
+
# If encryption is required, but a retrieved message is not
|
| 172 |
+
# encrypted, the method will throw.
|
| 173 |
+
try:
|
| 174 |
+
self.service.peek_message(queue_name, 'message1')
|
| 175 |
+
except:
|
| 176 |
+
pass
|
| 177 |
+
|
| 178 |
+
self.service.delete_queue(queue_name)
|
| 179 |
+
|
| 180 |
+
def alternate_key_algorithms(self):
|
| 181 |
+
queue_name = self._create_queue()
|
| 182 |
+
|
| 183 |
+
# To use an alternate method of key wrapping, simply set the
|
| 184 |
+
# key_encryption_key property to a wrapper that uses a different algorithm.
|
| 185 |
+
self.service.key_encryption_key = RSAKeyWrapper('key2')
|
| 186 |
+
self.service.key_resolver_function = None
|
| 187 |
+
|
| 188 |
+
self.service.put_message(queue_name, 'message')
|
| 189 |
+
|
| 190 |
+
key_resolver = KeyResolver()
|
| 191 |
+
key_resolver.put_key(self.service.key_encryption_key)
|
| 192 |
+
self.service.key_resolver_function = key_resolver.resolve_key
|
| 193 |
+
message = self.service.peek_messages(queue_name)
|
| 194 |
+
|
| 195 |
+
self.service.delete_queue(queue_name)
|
| 196 |
+
|
| 197 |
+
def decrypt_with_key_encryption_key(self):
|
| 198 |
+
queue_name = self._create_queue()
|
| 199 |
+
|
| 200 |
+
# The KeyWrapper object also defines methods necessary for
|
| 201 |
+
# decryption as defined in the get/peek messages documentation.
|
| 202 |
+
# Since the key_encryption_key property is still set, messages
|
| 203 |
+
# will be decrypted automatically.
|
| 204 |
+
kek = KeyWrapper('key1')
|
| 205 |
+
self.service.key_encryption_key = kek
|
| 206 |
+
self.service.put_message(queue_name, 'message1')
|
| 207 |
+
|
| 208 |
+
# When decrypting, if both a kek and resolver are set,
|
| 209 |
+
# the resolver will take precedence. Remove the resolver to just use the kek.
|
| 210 |
+
self.service.key_resolver_function = None
|
| 211 |
+
messages = self.service.peek_messages(queue_name)
|
| 212 |
+
|
| 213 |
+
self.service.delete_queue(queue_name)
|
pool/shard009/Python/0080554_ca_trust.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
#=======================================================================
|
| 3 |
+
# A custom IPolicyForHTTPS that allows *adding* extra CAs to the OS
|
| 4 |
+
# supplied CA bundle.
|
| 5 |
+
# Use this as the `contextFactory` for `twisted.web.client.Agent`.
|
| 6 |
+
#=======================================================================
|
| 7 |
+
|
| 8 |
+
# External modules
|
| 9 |
+
from OpenSSL import crypto
|
| 10 |
+
import pem
|
| 11 |
+
from twisted.internet import ssl, defer
|
| 12 |
+
from twisted.internet.interfaces import IOpenSSLClientConnectionCreator
|
| 13 |
+
from twisted.python.components import proxyForInterface
|
| 14 |
+
from twisted.web.iweb import IPolicyForHTTPS
|
| 15 |
+
from zope.interface import implementer
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class AddExtraTrustRoots(proxyForInterface(IOpenSSLClientConnectionCreator)):
|
| 19 |
+
def __init__(self, extraTrustRoots, original):
|
| 20 |
+
self._extraTrustRoots = extraTrustRoots
|
| 21 |
+
super(AddExtraTrustRoots, self).__init__(original)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def clientConnectionForTLS(self, tlsProtocol):
|
| 25 |
+
connection = (super(AddExtraTrustRoots, self).clientConnectionForTLS(tlsProtocol))
|
| 26 |
+
cert_store = connection.get_context().get_cert_store()
|
| 27 |
+
for cert in self._extraTrustRoots:
|
| 28 |
+
cert_store.add_cert(cert)
|
| 29 |
+
return connection
|
| 30 |
+
|
| 31 |
+
@implementer(IPolicyForHTTPS)
|
| 32 |
+
class CustomPolicyForHTTPS(object):
|
| 33 |
+
"""
|
| 34 |
+
SSL connection creator for web clients.
|
| 35 |
+
"""
|
| 36 |
+
def __init__(self, extraTrustRoots=None):
|
| 37 |
+
if extraTrustRoots is None:
|
| 38 |
+
extraTrustRoots = []
|
| 39 |
+
self._extraTrustRoots = extraTrustRoots
|
| 40 |
+
|
| 41 |
+
def creatorForNetloc(self, hostname, port):
|
| 42 |
+
return AddExtraTrustRoots(
|
| 43 |
+
self._extraTrustRoots,
|
| 44 |
+
ssl.optionsForClientTLS(hostname.decode("ascii")))
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def pem_cert_to_x509(pem_cert):
|
| 48 |
+
return crypto.load_certificate(crypto.FILETYPE_PEM, str(pem_cert))
|
| 49 |
+
|
| 50 |
+
def createCustomPolicyFactoryFromPEMs(*pem_files):
|
| 51 |
+
authorities = []
|
| 52 |
+
for pem_file in pem_files:
|
| 53 |
+
for cert in pem.parse_file(pem_file):
|
| 54 |
+
authorities.append(pem_cert_to_x509(cert))
|
| 55 |
+
|
| 56 |
+
def _policyFactory():
|
| 57 |
+
return CustomPolicyForHTTPS(authorities)
|
| 58 |
+
|
| 59 |
+
return _policyFactory
|
pool/shard009/Python/0080557_pressure.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
|
| 4 |
+
import requests
|
| 5 |
+
import numpy as np
|
| 6 |
+
import json
|
| 7 |
+
import client.cn_util
|
| 8 |
+
import sys
|
| 9 |
+
reload(sys)
|
| 10 |
+
sys.setdefaultencoding("utf-8")
|
| 11 |
+
|
| 12 |
+
def test():
|
| 13 |
+
url = "http://localhost:11304/sc/chat?q=%s&u=%s"
|
| 14 |
+
|
| 15 |
+
while True:
|
| 16 |
+
qn = [u'吃饭']
|
| 17 |
+
u = np.random.randint(0, 10)
|
| 18 |
+
q = np.random.choice(qn, 1)[0]
|
| 19 |
+
r_url = url % (q, str(u))
|
| 20 |
+
r = requests.get(r_url)
|
| 21 |
+
text = json.dumps(r.json(), ensure_ascii=False)
|
| 22 |
+
client.cn_util.print_cn(text)
|
| 23 |
+
if 'unclear' in text or 'base' in text:
|
| 24 |
+
print('---------')
|
| 25 |
+
|
| 26 |
+
if __name__ == '__main__':
|
| 27 |
+
test()
|
pool/shard009/Python/0080562_icpc.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datetime import timedelta
|
| 2 |
+
|
| 3 |
+
from django.core.exceptions import ValidationError
|
| 4 |
+
from django.db import connection
|
| 5 |
+
from django.template.defaultfilters import floatformat
|
| 6 |
+
from django.urls import reverse
|
| 7 |
+
from django.utils.html import format_html
|
| 8 |
+
from django.utils.safestring import mark_safe
|
| 9 |
+
from django.utils.translation import gettext_lazy
|
| 10 |
+
|
| 11 |
+
from judge.contest_format.default import DefaultContestFormat
|
| 12 |
+
from judge.contest_format.registry import register_contest_format
|
| 13 |
+
from judge.timezone import from_database_time
|
| 14 |
+
from judge.utils.timedelta import nice_repr
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@register_contest_format('icpc')
|
| 18 |
+
class ICPCContestFormat(DefaultContestFormat):
|
| 19 |
+
name = gettext_lazy('ICPC')
|
| 20 |
+
config_defaults = {'penalty': 20}
|
| 21 |
+
config_validators = {'penalty': lambda x: x >= 0}
|
| 22 |
+
'''
|
| 23 |
+
penalty: Number of penalty minutes each incorrect submission adds. Defaults to 20.
|
| 24 |
+
'''
|
| 25 |
+
|
| 26 |
+
@classmethod
|
| 27 |
+
def validate(cls, config):
|
| 28 |
+
if config is None:
|
| 29 |
+
return
|
| 30 |
+
|
| 31 |
+
if not isinstance(config, dict):
|
| 32 |
+
raise ValidationError('ICPC-styled contest expects no config or dict as config')
|
| 33 |
+
|
| 34 |
+
for key, value in config.items():
|
| 35 |
+
if key not in cls.config_defaults:
|
| 36 |
+
raise ValidationError('unknown config key "%s"' % key)
|
| 37 |
+
if not isinstance(value, type(cls.config_defaults[key])):
|
| 38 |
+
raise ValidationError('invalid type for config key "%s"' % key)
|
| 39 |
+
if not cls.config_validators[key](value):
|
| 40 |
+
raise ValidationError('invalid value "%s" for config key "%s"' % (value, key))
|
| 41 |
+
|
| 42 |
+
def __init__(self, contest, config):
|
| 43 |
+
self.config = self.config_defaults.copy()
|
| 44 |
+
self.config.update(config or {})
|
| 45 |
+
self.contest = contest
|
| 46 |
+
|
| 47 |
+
def update_participation(self, participation):
|
| 48 |
+
cumtime = 0
|
| 49 |
+
last = 0
|
| 50 |
+
penalty = 0
|
| 51 |
+
score = 0
|
| 52 |
+
format_data = {}
|
| 53 |
+
|
| 54 |
+
with connection.cursor() as cursor:
|
| 55 |
+
cursor.execute('''
|
| 56 |
+
SELECT MAX(cs.points) as `points`, (
|
| 57 |
+
SELECT MIN(csub.date)
|
| 58 |
+
FROM judge_contestsubmission ccs LEFT OUTER JOIN
|
| 59 |
+
judge_submission csub ON (csub.id = ccs.submission_id)
|
| 60 |
+
WHERE ccs.problem_id = cp.id AND ccs.participation_id = %s AND ccs.points = MAX(cs.points)
|
| 61 |
+
) AS `time`, cp.id AS `prob`
|
| 62 |
+
FROM judge_contestproblem cp INNER JOIN
|
| 63 |
+
judge_contestsubmission cs ON (cs.problem_id = cp.id AND cs.participation_id = %s) LEFT OUTER JOIN
|
| 64 |
+
judge_submission sub ON (sub.id = cs.submission_id)
|
| 65 |
+
GROUP BY cp.id
|
| 66 |
+
''', (participation.id, participation.id))
|
| 67 |
+
|
| 68 |
+
for points, time, prob in cursor.fetchall():
|
| 69 |
+
time = from_database_time(time)
|
| 70 |
+
dt = (time - participation.start).total_seconds()
|
| 71 |
+
|
| 72 |
+
# Compute penalty
|
| 73 |
+
if self.config['penalty']:
|
| 74 |
+
# An IE can have a submission result of `None`
|
| 75 |
+
subs = participation.submissions.exclude(submission__result__isnull=True) \
|
| 76 |
+
.exclude(submission__result__in=['IE', 'CE']) \
|
| 77 |
+
.filter(problem_id=prob)
|
| 78 |
+
if points:
|
| 79 |
+
prev = subs.filter(submission__date__lte=time).count() - 1
|
| 80 |
+
penalty += prev * self.config['penalty'] * 60
|
| 81 |
+
else:
|
| 82 |
+
# We should always display the penalty, even if the user has a score of 0
|
| 83 |
+
prev = subs.count()
|
| 84 |
+
else:
|
| 85 |
+
prev = 0
|
| 86 |
+
|
| 87 |
+
if points:
|
| 88 |
+
cumtime += dt
|
| 89 |
+
last = max(last, dt)
|
| 90 |
+
|
| 91 |
+
format_data[str(prob)] = {'time': dt, 'points': points, 'penalty': prev}
|
| 92 |
+
score += points
|
| 93 |
+
|
| 94 |
+
participation.cumtime = cumtime + penalty
|
| 95 |
+
participation.score = round(score, self.contest.points_precision)
|
| 96 |
+
participation.tiebreaker = last # field is sorted from least to greatest
|
| 97 |
+
participation.format_data = format_data
|
| 98 |
+
participation.save()
|
| 99 |
+
|
| 100 |
+
def display_user_problem(self, participation, contest_problem):
|
| 101 |
+
format_data = (participation.format_data or {}).get(str(contest_problem.id))
|
| 102 |
+
if format_data:
|
| 103 |
+
penalty = format_html('<small style="color:red"> ({penalty})</small>',
|
| 104 |
+
penalty=floatformat(format_data['penalty'])) if format_data['penalty'] else ''
|
| 105 |
+
return format_html(
|
| 106 |
+
'<td class="{state}"><a href="{url}">{points}{penalty}<div class="solving-time">{time}</div></a></td>',
|
| 107 |
+
state=(('pretest-' if self.contest.run_pretests_only and contest_problem.is_pretested else '') +
|
| 108 |
+
self.best_solution_state(format_data['points'], contest_problem.points)),
|
| 109 |
+
url=reverse('contest_user_submissions',
|
| 110 |
+
args=[self.contest.key, participation.user.user.username, contest_problem.problem.code]),
|
| 111 |
+
points=floatformat(format_data['points']),
|
| 112 |
+
penalty=penalty,
|
| 113 |
+
time=nice_repr(timedelta(seconds=format_data['time']), 'noday'),
|
| 114 |
+
)
|
| 115 |
+
else:
|
| 116 |
+
return mark_safe('<td></td>')
|
| 117 |
+
|
| 118 |
+
def get_label_for_problem(self, index):
|
| 119 |
+
index += 1
|
| 120 |
+
ret = ''
|
| 121 |
+
while index > 0:
|
| 122 |
+
ret += chr((index - 1) % 26 + 65)
|
| 123 |
+
index = (index - 1) // 26
|
| 124 |
+
return ret[::-1]
|
pool/shard009/Python/0080563_pack.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
###############################################################################
|
| 3 |
+
#
|
| 4 |
+
# Copyright (C) 2001-2014 Micronaet SRL (<http://www.micronaet.it>).
|
| 5 |
+
#
|
| 6 |
+
# This program is free software: you can redistribute it and/or modify
|
| 7 |
+
# it under the terms of the GNU Affero General Public License as published
|
| 8 |
+
# by the Free Software Foundation, either version 3 of the License, or
|
| 9 |
+
# (at your option) any later version.
|
| 10 |
+
#
|
| 11 |
+
# This program is distributed in the hope that it will be useful,
|
| 12 |
+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
| 13 |
+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
| 14 |
+
# GNU Affero General Public License for more details.
|
| 15 |
+
#
|
| 16 |
+
# You should have received a copy of the GNU Affero General Public License
|
| 17 |
+
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
| 18 |
+
#
|
| 19 |
+
###############################################################################
|
| 20 |
+
import os
|
| 21 |
+
import sys
|
| 22 |
+
import logging
|
| 23 |
+
import openerp
|
| 24 |
+
import openerp.netsvc as netsvc
|
| 25 |
+
import openerp.addons.decimal_precision as dp
|
| 26 |
+
from openerp.osv import fields, osv, expression, orm
|
| 27 |
+
from datetime import datetime, timedelta
|
| 28 |
+
from dateutil.relativedelta import relativedelta
|
| 29 |
+
from openerp import SUPERUSER_ID, api
|
| 30 |
+
from openerp import tools
|
| 31 |
+
from openerp.tools.translate import _
|
| 32 |
+
from openerp.tools.float_utils import float_round as round
|
| 33 |
+
from openerp.tools import (DEFAULT_SERVER_DATE_FORMAT,
|
| 34 |
+
DEFAULT_SERVER_DATETIME_FORMAT,
|
| 35 |
+
DATETIME_FORMATS_MAP,
|
| 36 |
+
float_compare)
|
| 37 |
+
import base64, urllib
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
_logger = logging.getLogger(__name__)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class BaseContainerType(orm.Model):
|
| 44 |
+
'''Type of Container: type of container used for standard total cost
|
| 45 |
+
used for divide for tot article to part cost on unit
|
| 46 |
+
'''
|
| 47 |
+
_name = 'base.container.type'
|
| 48 |
+
_description = 'Container type'
|
| 49 |
+
|
| 50 |
+
_columns = {
|
| 51 |
+
'name': fields.char('Container', size=40, required=True),
|
| 52 |
+
'cost': fields.float('Loan cost (EUR)', digits=(16, 2)),
|
| 53 |
+
'date': fields.date('Date of quotation'),
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
_defaults = {
|
| 57 |
+
'cost': lambda *x: 0.0,
|
| 58 |
+
'date': lambda *a: datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
class ProductPackagingFunction(orm.Model):
|
| 62 |
+
'''Add extra fields for
|
| 63 |
+
'''
|
| 64 |
+
_inherit = 'product.packaging'
|
| 65 |
+
|
| 66 |
+
# fields function
|
| 67 |
+
def _function_get_volume(self, cr, uid, ids, name, args, context=None):
|
| 68 |
+
res = {}
|
| 69 |
+
for pack in self.browse(cr, uid, ids, context=context):
|
| 70 |
+
res[pack.id] = (
|
| 71 |
+
pack.length or 0 * pack.width or 0 * pack.height or 0
|
| 72 |
+
) / 1000000 # TODO approx
|
| 73 |
+
return res
|
| 74 |
+
|
| 75 |
+
def _function_get_transport(self, cr, uid, ids, name, args, context=None):
|
| 76 |
+
res = {}
|
| 77 |
+
for pack in self.browse(cr, uid, ids, context=context):
|
| 78 |
+
try:
|
| 79 |
+
res[pack.id] = round((
|
| 80 |
+
pack.container_id and pack.container_id.cost or 0) / (
|
| 81 |
+
pack.q_x_container or 0),2)
|
| 82 |
+
except: # division by zero!
|
| 83 |
+
res[pack.id] = 0.00
|
| 84 |
+
return res
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
_columns = {
|
| 88 |
+
'container_id': fields.many2one(
|
| 89 |
+
'base.container.type', 'Container type', ondelete="set null"),
|
| 90 |
+
'q_x_container': fields.integer('Q. x container'),
|
| 91 |
+
'transport_cost': fields.function(
|
| 92 |
+
_function_get_transport, method=True, type='float',
|
| 93 |
+
string='Transport cost unit (EUR)', store=False),
|
| 94 |
+
|
| 95 |
+
'dimension_text': fields.text('Dimension (textual)'), # TO DELETE
|
| 96 |
+
'error_dimension_pack': fields.boolean('Error dimens. pack'), # TO DEL.
|
| 97 |
+
|
| 98 |
+
'pack_volume': fields.float('Pack volum (manual)', digits=(16, 3)),
|
| 99 |
+
'pack_volume_manual': fields.boolean('Manual volum'),
|
| 100 |
+
|
| 101 |
+
# TODO moved in product.ul in v.8 (not existant here)
|
| 102 |
+
'length': fields.float('Length', digits=(16, 2)),
|
| 103 |
+
'height': fields.float('Height', digits=(16, 2)),
|
| 104 |
+
'width': fields.float('Width', digits=(16, 2)),
|
| 105 |
+
|
| 106 |
+
'weight_ul': fields.float('Weight UL', digits=(16, 2)),
|
| 107 |
+
}
|
| 108 |
+
|
| 109 |
+
_defaults = {
|
| 110 |
+
'q_x_container': lambda *x: 0,
|
| 111 |
+
}
|
| 112 |
+
|
| 113 |
+
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
pool/shard009/Python/0080564_test_disco_dynamodb.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Integration tests for disco_dynamodb.py
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
from random import randint
|
| 7 |
+
from tests.helpers.integration_helpers import IntegrationTest
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
MOCK_TABLE_NAME = "IntegrationTest"
|
| 11 |
+
CREATE_CMD = "disco_dynamodb.py create --env {0} --config test/test_dynamodb_create.json --wait"
|
| 12 |
+
DELETE_CMD = "disco_dynamodb.py delete --table {0} --env {1} --wait"
|
| 13 |
+
LIST_CMD = "disco_dynamodb.py list"
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class TestDiscoDynamoDB(IntegrationTest):
|
| 17 |
+
""" Test bin/disco_dynamodb.py """
|
| 18 |
+
|
| 19 |
+
def setUp(self):
|
| 20 |
+
"""
|
| 21 |
+
Generate random environment name for integration test env
|
| 22 |
+
"""
|
| 23 |
+
self.env_name = "env_{0}".format(randint(10000, 99999))
|
| 24 |
+
|
| 25 |
+
def test_create_and_delete_table(self):
|
| 26 |
+
""" Ensures we can create and delete DynamoDB table properly """
|
| 27 |
+
table_list_output = u"{0:<20} {1}".format(MOCK_TABLE_NAME, self.env_name)
|
| 28 |
+
|
| 29 |
+
try:
|
| 30 |
+
create_output = self.run_cmd(CREATE_CMD.format(self.env_name).split())
|
| 31 |
+
|
| 32 |
+
table = json.loads(self._remove_lines_from_logs(create_output))
|
| 33 |
+
|
| 34 |
+
self.assertEqual(table["TableStatus"], "ACTIVE")
|
| 35 |
+
self.assertEqual(table["TableName"], "{0}_{1}".format(MOCK_TABLE_NAME, self.env_name))
|
| 36 |
+
self.assertEqual(table["ProvisionedThroughput"]["WriteCapacityUnits"], 10)
|
| 37 |
+
self.assertEqual(table["ProvisionedThroughput"]["ReadCapacityUnits"], 10)
|
| 38 |
+
for key in table["KeySchema"]:
|
| 39 |
+
if key["KeyType"] == "HASH":
|
| 40 |
+
self.assertEqual(key["AttributeName"], "_id")
|
| 41 |
+
else:
|
| 42 |
+
self.assertEqual(key["AttributeName"], "mock_range_key")
|
| 43 |
+
|
| 44 |
+
self.assertEqual(table["GlobalSecondaryIndexes"][0]["IndexName"], "mock_index")
|
| 45 |
+
self.assertEqual(table["GlobalSecondaryIndexes"][0]["KeySchema"][0]["AttributeName"],
|
| 46 |
+
"mock_index_attr")
|
| 47 |
+
self.assertEqual(table["GlobalSecondaryIndexes"][0]["Projection"]["ProjectionType"], "ALL")
|
| 48 |
+
|
| 49 |
+
# Also assert that table can be found when running the list command
|
| 50 |
+
list_output = self.run_cmd(LIST_CMD.format(self.env_name).split())
|
| 51 |
+
lines = list_output.split('\n')
|
| 52 |
+
self.assertIn(table_list_output, lines)
|
| 53 |
+
finally:
|
| 54 |
+
delete_output = self.run_cmd(DELETE_CMD.format(MOCK_TABLE_NAME, self.env_name).split())
|
| 55 |
+
delete_output = json.loads(self._remove_lines_from_logs(delete_output))
|
| 56 |
+
|
| 57 |
+
self.assertEqual(delete_output["TableName"], "{0}_{1}".format(MOCK_TABLE_NAME, self.env_name))
|
| 58 |
+
self.assertEqual(delete_output["TableStatus"], "DELETED")
|
| 59 |
+
|
| 60 |
+
list_output = self.run_cmd(LIST_CMD.format(self.env_name).split())
|
| 61 |
+
lines = list_output.split('\n')
|
| 62 |
+
self.assertNotIn(table_list_output, lines)
|
| 63 |
+
|
| 64 |
+
def _remove_lines_from_logs(self, input_string):
|
| 65 |
+
lines = []
|
| 66 |
+
|
| 67 |
+
for line in input_string.split("\n"):
|
| 68 |
+
words = line.split()
|
| 69 |
+
|
| 70 |
+
try:
|
| 71 |
+
# If it quacks like a logging line...
|
| 72 |
+
if words[3] in ["WARNING", "WARN", "INFO", "DEBUG", "CRITICAL", "NOTSET"]:
|
| 73 |
+
continue
|
| 74 |
+
except IndexError:
|
| 75 |
+
pass
|
| 76 |
+
|
| 77 |
+
lines.append(line)
|
| 78 |
+
|
| 79 |
+
output_string = "\n".join(lines)
|
| 80 |
+
|
| 81 |
+
return output_string
|
pool/shard009/Python/0080568_letnode.py
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
|
| 3 |
+
"""
|
| 4 |
+
Clase C{LetNode} del árbol de sintáxis abstracta.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from pytiger2c.ast.valuedexpressionnode import ValuedExpressionNode
|
| 8 |
+
from pytiger2c.scope import Scope, FakeScope
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class LetNode(ValuedExpressionNode):
|
| 12 |
+
"""
|
| 13 |
+
Clase C{LetNode} del árbol de sintáxis abstracta.
|
| 14 |
+
|
| 15 |
+
Representa la expresión C{let-in-end} del lenguaje Tiger. La expresión
|
| 16 |
+
C{let-in-end} define tipos y funciones especificadas luego de la instrucción
|
| 17 |
+
C{let} y antes de la instrucción C{in} de forma tal que esas declaraciones
|
| 18 |
+
estén disponibles en el ámbito de ejecución de la secuencia de expresiones
|
| 19 |
+
que se encuentran detrás de la instrucción C{in} y antes de la instrucción
|
| 20 |
+
C{end}.
|
| 21 |
+
|
| 22 |
+
La expresión C{let-in-end} retorna valor si la secuencia de expresiones
|
| 23 |
+
retorna valor y su tipo de retorno es el mismo que la secuencia de
|
| 24 |
+
expresiones.
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
def _get_type_declaration_groups(self):
|
| 28 |
+
"""
|
| 29 |
+
Método para obtener el valor de la propiedad C{type_declaration_groups}.
|
| 30 |
+
"""
|
| 31 |
+
return self._type_declaration_groups
|
| 32 |
+
|
| 33 |
+
type_declaration_groups = property(_get_type_declaration_groups)
|
| 34 |
+
|
| 35 |
+
def _get_function_declaration_groups(self):
|
| 36 |
+
"""
|
| 37 |
+
Método para obtener el valor de la propiedad C{function_declaration_groups}.
|
| 38 |
+
"""
|
| 39 |
+
return self._function_declaration_groups
|
| 40 |
+
|
| 41 |
+
function_declaration_groups = property(_get_function_declaration_groups)
|
| 42 |
+
|
| 43 |
+
def _get_variable_declarations(self):
|
| 44 |
+
"""
|
| 45 |
+
Método para obtener el valor de la propiedad C{variable_declarations}.
|
| 46 |
+
"""
|
| 47 |
+
return self._variable_declarations
|
| 48 |
+
|
| 49 |
+
variable_declarations = property(_get_variable_declarations)
|
| 50 |
+
|
| 51 |
+
def _get_expressions(self):
|
| 52 |
+
"""
|
| 53 |
+
Método para obtener el valor de la propiedad C{expressions}.
|
| 54 |
+
"""
|
| 55 |
+
return self._expressions
|
| 56 |
+
|
| 57 |
+
expressions = property(_get_expressions)
|
| 58 |
+
|
| 59 |
+
def __init__(self, type_declaration_groups, function_declaration_groups,
|
| 60 |
+
variable_declarations, expressions):
|
| 61 |
+
"""
|
| 62 |
+
Inicializa la clase C{LetNode}.
|
| 63 |
+
|
| 64 |
+
@type type_declaration_groups: C{list}
|
| 65 |
+
@param type_declaration_groups: Lista de los grupos de las declaraciones
|
| 66 |
+
de tipos, que forman parte de la lista de declaraciones de la
|
| 67 |
+
estructura C{let-in-end} representada por este nodo del árbol
|
| 68 |
+
de sintáxis abstracta.
|
| 69 |
+
|
| 70 |
+
@type function_declaration_groups: C{list}
|
| 71 |
+
@param function_declaration_groups: Lista de los grupos de las declaraciones
|
| 72 |
+
de funciones, que forman parte de la lista de declaraciones de la
|
| 73 |
+
estructura C{let-in-end} representada por este nodo del árbol
|
| 74 |
+
de sintáxis abstracta.
|
| 75 |
+
|
| 76 |
+
@type variable_declarations: C{list}
|
| 77 |
+
@param variable_declarations: Lista de las declaraciones de variables
|
| 78 |
+
que forman parte de la lista de declaraciones de la
|
| 79 |
+
estructura C{let-in-end} representada por este nodo del árbol
|
| 80 |
+
de sintáxis abstracta.
|
| 81 |
+
|
| 82 |
+
@type expressions: C{ExpressionSequenceNode}
|
| 83 |
+
@param expressions: Sequencia de expresiones que forman parte del cuerpo
|
| 84 |
+
de la expresión C{let-in-end} representada por este nodo del árbol
|
| 85 |
+
de sintáxis abstracta.
|
| 86 |
+
"""
|
| 87 |
+
super(LetNode, self).__init__()
|
| 88 |
+
self._type_declaration_groups = type_declaration_groups
|
| 89 |
+
self._function_declaration_groups = function_declaration_groups
|
| 90 |
+
self._variable_declarations = variable_declarations
|
| 91 |
+
self._expressions = expressions
|
| 92 |
+
|
| 93 |
+
def has_return_value(self):
|
| 94 |
+
"""
|
| 95 |
+
Ver documentación del método C{has_return_value} en C{LanguageNode}.
|
| 96 |
+
"""
|
| 97 |
+
return self._return_type != None
|
| 98 |
+
|
| 99 |
+
def check_semantics(self, scope, errors):
|
| 100 |
+
"""
|
| 101 |
+
Para obtener información acerca de los parámetros recibidos por
|
| 102 |
+
el método consulte la documentación del método C{check_semantics}
|
| 103 |
+
en la clase C{LanguageNode}.
|
| 104 |
+
|
| 105 |
+
En la comprobación semántica de este nodo del árbol de sintáxis abstracta
|
| 106 |
+
primeramente se crea el nuevo ámbito que define la estructura y que
|
| 107 |
+
tendrá como padre el ámbito donde se define la estructura C{let-in-end}.
|
| 108 |
+
|
| 109 |
+
Se recorren todos los grupos de declaraciones de tipos, definiendo los
|
| 110 |
+
tipos en el ámbito creado y se obtiene un conjunto de los tipos que se
|
| 111 |
+
declaran en cada grupo a través del método C{collect_definitions} y luego
|
| 112 |
+
se comprueba semánticamente cada una de estas definiciones de tipos.
|
| 113 |
+
|
| 114 |
+
Se recorren todos los grupos de declaraciones de funciones, comprobando
|
| 115 |
+
la cabecera de la declaración de la función, definiendo las funciones en
|
| 116 |
+
el ámbito creado y se obtiene un conjunto de las funciones que se definen
|
| 117 |
+
en cada grupo través del método C{collect_definitions}.
|
| 118 |
+
|
| 119 |
+
Se comprueban semánticamente todas las declaraciones de variables.
|
| 120 |
+
|
| 121 |
+
Se comprueban semánticamente los cuerpos de las funciones declaradas en
|
| 122 |
+
cada grupo de declaración de funciones.
|
| 123 |
+
|
| 124 |
+
Se comprueba semánticamente la secuencia de expresiones de la estructura
|
| 125 |
+
C{let-in-end} y se asigna el valor de retorno del nodo, en caso de que
|
| 126 |
+
lo tenga.
|
| 127 |
+
|
| 128 |
+
En el procedimiento de comprobación semántica descrito anteriormente se
|
| 129 |
+
realizan dos recorridos por ciertas partes del árbol de sintáxis abstracta
|
| 130 |
+
descendiente de este nodo. Se recorren dos veces los nodos correspondientes
|
| 131 |
+
a las declaraciones de tipos: una primera vez para obtener los nomrbes de los
|
| 132 |
+
tipos que se definen en cada grupo y luego para comprobar semánticamente
|
| 133 |
+
estas declaraciones de tipos. De manera semejante, se recorren dos veces los
|
| 134 |
+
nodos del árbol de sintáxis abstracta correspondientes a las declaraciones
|
| 135 |
+
de las funciones: una primera vez para obtener los nombres de las funciones
|
| 136 |
+
que se definen en cada grupo y una segunda vez para comprobar semánticamente
|
| 137 |
+
el cuerpo de las funciones.
|
| 138 |
+
"""
|
| 139 |
+
self._scope = Scope(scope)
|
| 140 |
+
all_types = set()
|
| 141 |
+
groups_types = []
|
| 142 |
+
all_functions = set()
|
| 143 |
+
groups_functions = []
|
| 144 |
+
|
| 145 |
+
erros_before = len(errors)
|
| 146 |
+
|
| 147 |
+
# First pass through the nodes of the type declarations.
|
| 148 |
+
for type_declaration_group in self._type_declaration_groups:
|
| 149 |
+
group_types = type_declaration_group.collect_definitions(self.scope, errors)
|
| 150 |
+
groups_types.append(group_types)
|
| 151 |
+
all_types.update(group_types)
|
| 152 |
+
|
| 153 |
+
if erros_before != len(errors):
|
| 154 |
+
return
|
| 155 |
+
|
| 156 |
+
# Second pass through the nodes of the type declarations. The second pass
|
| 157 |
+
# is divided in two parts: the first through the alias declaration and
|
| 158 |
+
# the second through the rest of the declarations.
|
| 159 |
+
types_fake_scope = FakeScope(self.scope)
|
| 160 |
+
for index, type_declaration_group in enumerate(self._type_declaration_groups):
|
| 161 |
+
types_fake_scope.current_siblings = all_types - groups_types[index]
|
| 162 |
+
type_declaration_group.check_aliases_semantics(types_fake_scope, errors)
|
| 163 |
+
types_fake_scope.current_siblings = None
|
| 164 |
+
|
| 165 |
+
if erros_before != len(errors):
|
| 166 |
+
return
|
| 167 |
+
|
| 168 |
+
for index, type_declaration_group in enumerate(self._type_declaration_groups):
|
| 169 |
+
types_fake_scope.current_siblings = all_types - groups_types[index]
|
| 170 |
+
type_declaration_group.check_semantics(types_fake_scope, errors)
|
| 171 |
+
types_fake_scope.current_siblings = None
|
| 172 |
+
|
| 173 |
+
if erros_before != len(errors):
|
| 174 |
+
return
|
| 175 |
+
|
| 176 |
+
# First pass through the nodes of the function declarations.
|
| 177 |
+
for func_declaration_group in self._function_declaration_groups:
|
| 178 |
+
group_functions = func_declaration_group.collect_definitions(self.scope, errors)
|
| 179 |
+
groups_functions.append(group_functions)
|
| 180 |
+
all_functions.update(group_functions)
|
| 181 |
+
|
| 182 |
+
if erros_before != len(errors):
|
| 183 |
+
return
|
| 184 |
+
|
| 185 |
+
# The only pass through the nodes of the variable declarations.
|
| 186 |
+
for variable_declaration in self._variable_declarations:
|
| 187 |
+
variable_declaration.check_semantics(self.scope, errors)
|
| 188 |
+
|
| 189 |
+
if erros_before != len(errors):
|
| 190 |
+
return
|
| 191 |
+
|
| 192 |
+
# Second pass through the nodes of the function declarations.
|
| 193 |
+
functions_fake_scope = FakeScope(self.scope)
|
| 194 |
+
for index, func_declaration_group in enumerate(self._function_declaration_groups):
|
| 195 |
+
functions_fake_scope.current_siblings = all_functions - groups_functions[index]
|
| 196 |
+
func_declaration_group.check_semantics(functions_fake_scope, errors)
|
| 197 |
+
functions_fake_scope.current_siblings = None
|
| 198 |
+
|
| 199 |
+
if erros_before != len(errors):
|
| 200 |
+
return
|
| 201 |
+
|
| 202 |
+
# The only pass through the expressions.
|
| 203 |
+
self._expressions.check_semantics(self.scope, errors)
|
| 204 |
+
|
| 205 |
+
# Setting the return value of the node.
|
| 206 |
+
if self._expressions.has_return_value():
|
| 207 |
+
self._return_type = self._expressions.return_type
|
| 208 |
+
else:
|
| 209 |
+
self._return_type = None
|
| 210 |
+
|
| 211 |
+
def generate_dot(self, generator):
|
| 212 |
+
"""
|
| 213 |
+
Genera un grafo en formato Graphviz DOT correspondiente al árbol de
|
| 214 |
+
sintáxis abstracta del programa Tiger del cual este nodo es raíz.
|
| 215 |
+
|
| 216 |
+
Para obtener información acerca de los parámetros recibidos por
|
| 217 |
+
este método consulte la documentación del método C{generate_dot}
|
| 218 |
+
de la clase C{LanguageNode}.
|
| 219 |
+
"""
|
| 220 |
+
me = generator.add_node(str(self.__class__.__name__))
|
| 221 |
+
for type_declaration_group in self.type_declaration_groups:
|
| 222 |
+
type_declaration_group = type_declaration_group.generate_dot(generator)
|
| 223 |
+
generator.add_edge(me, type_declaration_group)
|
| 224 |
+
for function_declaration_group in self.function_declaration_groups:
|
| 225 |
+
function_declaration_group = function_declaration_group.generate_dot(generator)
|
| 226 |
+
generator.add_edge(me, function_declaration_group)
|
| 227 |
+
for variable_declaration in self.variable_declarations:
|
| 228 |
+
variable_declaration = variable_declaration.generate_dot(generator)
|
| 229 |
+
generator.add_edge(me, variable_declaration)
|
| 230 |
+
expressions = self.expressions.generate_dot(generator)
|
| 231 |
+
generator.add_edge(me, expressions)
|
| 232 |
+
return me
|
| 233 |
+
|
| 234 |
+
def generate_code(self, generator):
|
| 235 |
+
"""
|
| 236 |
+
Genera el código correspondiente a la estructura del lenguaje Tiger
|
| 237 |
+
representada por el nodo.
|
| 238 |
+
|
| 239 |
+
Para obtener información acerca de los parámetros recibidos por
|
| 240 |
+
este método consulte la documentación del método C{generate_code}
|
| 241 |
+
de la clase C{LanguageNode}.
|
| 242 |
+
"""
|
| 243 |
+
self.scope.generate_code(generator)
|
| 244 |
+
if self.scope.parent:
|
| 245 |
+
statement = '{scope}->parent = {parent};'
|
| 246 |
+
statement = statement.format(scope=self.scope.code_name,
|
| 247 |
+
parent=self.scope.parent.code_name)
|
| 248 |
+
generator.add_statement(statement)
|
| 249 |
+
|
| 250 |
+
for type_declaration_group in self.type_declaration_groups:
|
| 251 |
+
type_declaration_group.generate_code(generator)
|
| 252 |
+
|
| 253 |
+
for variable_declaration in self.variable_declarations:
|
| 254 |
+
variable_declaration.generate_code(generator)
|
| 255 |
+
|
| 256 |
+
for function_declaration_group in self.function_declaration_groups:
|
| 257 |
+
function_declaration_group.generate_code(generator)
|
| 258 |
+
|
| 259 |
+
self.expressions.generate_code(generator)
|
| 260 |
+
|
| 261 |
+
if self.has_return_value():
|
| 262 |
+
self._code_name = self.expressions.code_name
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
|
pool/shard009/Python/0080573_Problem4c.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import matplotlib.pyplot as plt
|
| 2 |
+
def func(x):
|
| 3 |
+
return x**4 - 2
|
| 4 |
+
def false_position(a, b, thresh, max_step, f):
|
| 5 |
+
itr = []
|
| 6 |
+
diffs = []
|
| 7 |
+
x1 = a
|
| 8 |
+
x2 = b
|
| 9 |
+
val1 = f(x1)
|
| 10 |
+
val2 = f(x2)
|
| 11 |
+
# Swap values
|
| 12 |
+
if( val1 > 0 ):
|
| 13 |
+
x1, x2, val1, val2 = x2, x1, val2, val1
|
| 14 |
+
for i in range(max_step):
|
| 15 |
+
x_new = x1 + (x2 - x1)*val1/(val1 - val2)
|
| 16 |
+
val_new = f(x_new)
|
| 17 |
+
itr.append(i)
|
| 18 |
+
diffs.append(abs(val_new))
|
| 19 |
+
if( abs(val_new) < thresh):
|
| 20 |
+
return x_new, itr, diffs
|
| 21 |
+
if( val_new < 0 ):
|
| 22 |
+
x1 = x_new
|
| 23 |
+
val1 = val_new
|
| 24 |
+
else:
|
| 25 |
+
x2 = x_new
|
| 26 |
+
val2 = val_new
|
| 27 |
+
return x_new, itr, diffs
|
| 28 |
+
x, itr, diffs = false_position( 0, 2, 1e-10, 300, func)
|
| 29 |
+
print(x)
|
| 30 |
+
print(len(itr))
|
| 31 |
+
plt.plot(itr, diffs)
|
| 32 |
+
plt.gca().set_yscale('log')
|
| 33 |
+
plt.grid()
|
| 34 |
+
plt.title('False Position Convergence')
|
| 35 |
+
plt.ylabel('log( |f(x_n)| )')
|
| 36 |
+
plt.xlabel('step, n')
|
| 37 |
+
plt.savefig('Problem4c.png')
|
| 38 |
+
plt.show()
|
pool/shard009/Python/0080583_RBFN.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from scipy import *
|
| 2 |
+
from scipy.linalg import norm, pinv
|
| 3 |
+
import numpy as np
|
| 4 |
+
|
| 5 |
+
from matplotlib import pyplot as plt
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class RBF:
|
| 9 |
+
def __init__(self, indim, numCenters, outdim):
|
| 10 |
+
self.indim = indim
|
| 11 |
+
self.outdim = outdim
|
| 12 |
+
self.numCenters = numCenters
|
| 13 |
+
self.centers = [random.uniform(-1, 1, indim) for i in xrange(numCenters)]
|
| 14 |
+
self.beta = 8
|
| 15 |
+
self.W = random.random((self.numCenters, self.outdim))
|
| 16 |
+
|
| 17 |
+
def _basisfunc(self, c, d):
|
| 18 |
+
assert len(d) == self.indim
|
| 19 |
+
return exp(-self.beta * norm(c - d) ** 2)
|
| 20 |
+
|
| 21 |
+
def _calcAct(self, X):
|
| 22 |
+
# calculate activations of RBFs
|
| 23 |
+
G = zeros((X.shape[0], self.numCenters), float)
|
| 24 |
+
for ci, c in enumerate(self.centers):
|
| 25 |
+
for xi, x in enumerate(X):
|
| 26 |
+
G[xi, ci] = self._basisfunc(c, x)
|
| 27 |
+
return G
|
| 28 |
+
|
| 29 |
+
def train(self, X, Y):
|
| 30 |
+
""" X: matrix of dimensions n x indim
|
| 31 |
+
y: column vector of dimension n x 1 """
|
| 32 |
+
|
| 33 |
+
# choose random center vectors from training set
|
| 34 |
+
rnd_idx = random.permutation(X.shape[0])[:self.numCenters]
|
| 35 |
+
self.centers = [X[i, :] for i in rnd_idx]
|
| 36 |
+
|
| 37 |
+
# print "center", self.centers
|
| 38 |
+
# calculate activations of RBFs
|
| 39 |
+
G = self._calcAct(X)
|
| 40 |
+
# print G
|
| 41 |
+
|
| 42 |
+
# calculate output weights (pseudoinverse)
|
| 43 |
+
self.W = dot(pinv(G), Y)
|
| 44 |
+
|
| 45 |
+
def test(self, X):
|
| 46 |
+
""" X: matrix of dimensions n x indim """
|
| 47 |
+
|
| 48 |
+
G = self._calcAct(X)
|
| 49 |
+
Y = dot(G, self.W)
|
| 50 |
+
return Y
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
if __name__ == '__main__':
|
| 54 |
+
n = 100
|
| 55 |
+
x = mgrid[-1:1:complex(0, n)].reshape(n, 1)
|
| 56 |
+
# set y and add random noise
|
| 57 |
+
y = sin(3 * (x + 0.5) ** 3 - 1)
|
| 58 |
+
# y += random.normal(0, 0.1, y.shape)
|
| 59 |
+
|
| 60 |
+
# rbf regression
|
| 61 |
+
rbf = RBF(1, 10, 1)
|
| 62 |
+
rbf.train(x, y)
|
| 63 |
+
z = rbf.test(x)
|
| 64 |
+
|
| 65 |
+
# print (z)
|
| 66 |
+
# print (y)
|
| 67 |
+
|
| 68 |
+
out = z - y
|
| 69 |
+
print (out.var())
|
pool/shard009/Python/0080585_LUV_extraction.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Code to go through the image dataset and save LUV matrix associated
|
| 3 |
+
For the 40 percent sampled data, saves the matrix at ../../data/LUV_40p.npy
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from scipy import misc
|
| 7 |
+
from skimage import color
|
| 8 |
+
from skimage import data
|
| 9 |
+
from PIL import Image
|
| 10 |
+
import numpy as np
|
| 11 |
+
import os
|
| 12 |
+
import PIL
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
path = "/home/avikalp/semester6/BS/twitter_images/img"
|
| 16 |
+
|
| 17 |
+
good_indices = list(np.load('good_indices.npy'))
|
| 18 |
+
bad_indices = []
|
| 19 |
+
IV = []
|
| 20 |
+
IU = []
|
| 21 |
+
IL = []
|
| 22 |
+
LUV = []
|
| 23 |
+
subset_indices = np.load('subset40p_indices.npy')
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
for count in subset_indices:
|
| 28 |
+
print (count)
|
| 29 |
+
current_image = path + str(count)
|
| 30 |
+
img = Image.open(current_image)
|
| 31 |
+
# img = misc.imread(current_image)
|
| 32 |
+
img = img.resize((128, 128), Image.ANTIALIAS)
|
| 33 |
+
# img.show()
|
| 34 |
+
# print (img.shape)
|
| 35 |
+
img = np.array(img)
|
| 36 |
+
# if img.shape[2] != 3:
|
| 37 |
+
# bad_indices.append(count)
|
| 38 |
+
# good_indices.remove(count)
|
| 39 |
+
# continue
|
| 40 |
+
arr = color.rgb2luv(img)
|
| 41 |
+
LUV.append(arr)
|
| 42 |
+
# IV_Current = arr[:,:,2]
|
| 43 |
+
# IV.append(IV_Current)
|
| 44 |
+
# IU_Current = arr[:,:,1]
|
| 45 |
+
# IU.append(IU_Current)
|
| 46 |
+
# IL_Current = arr[:,:,0]
|
| 47 |
+
# IL.append(IL_Current)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
# # np.save('good_indices.npy', good_indices)
|
| 51 |
+
# # np.save('bad_indices.npy', bad_indices)
|
| 52 |
+
# np.save('LUV_V_40p.npy',IV)
|
| 53 |
+
# np.save('LUV_U_40p.npy',IU)
|
| 54 |
+
# np.save('LUV_L_40p.npy',IL)
|
| 55 |
+
np.save('LUV_40p.npy', LUV)
|
pool/shard009/Python/0080590_FontConfig.py
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# FontConfig.py (c) 2006 Canonical, released under the GPL
|
| 2 |
+
#
|
| 3 |
+
# This file implements the fontconfig hack
|
| 4 |
+
#
|
| 5 |
+
# The problem is that different languages have different needs for
|
| 6 |
+
# fontconfig preferences. While it would be really good to have a single
|
| 7 |
+
# config file it seems to be not feasible right now for practial purposes
|
| 8 |
+
# (see https://wiki.ubuntu.com/DapperL10nSprint for more information)
|
| 9 |
+
#
|
| 10 |
+
# so this file implements a hack to add prefered languages based on the
|
| 11 |
+
# configuration we got from the CJK community
|
| 12 |
+
|
| 13 |
+
import glob
|
| 14 |
+
import string
|
| 15 |
+
import os.path
|
| 16 |
+
|
| 17 |
+
from LocaleInfo import LocaleInfo
|
| 18 |
+
import macros
|
| 19 |
+
from utils import language2locale
|
| 20 |
+
|
| 21 |
+
class ExceptionMultipleConfigurations(Exception):
|
| 22 |
+
" error when multiple languages are symlinked "
|
| 23 |
+
pass
|
| 24 |
+
class ExceptionUnconfigured(Exception):
|
| 25 |
+
" error if no configuration is set "
|
| 26 |
+
pass
|
| 27 |
+
class ExceptionNoConfigForLocale(Exception):
|
| 28 |
+
" error if there is no config for the given locale "
|
| 29 |
+
pass
|
| 30 |
+
|
| 31 |
+
class FontConfigHack(object):
|
| 32 |
+
""" abstract the fontconfig hack """
|
| 33 |
+
def __init__(self,
|
| 34 |
+
datadir="/usr/share/language-selector/",
|
| 35 |
+
globalConfDir="/etc/fonts"):
|
| 36 |
+
self.datadir="%s/fontconfig" % datadir
|
| 37 |
+
self._datadir = datadir
|
| 38 |
+
self.globalConfDir=globalConfDir
|
| 39 |
+
self.li = LocaleInfo("languagelist", datadir)
|
| 40 |
+
def _getLocaleCountryFromFileName(self, name):
|
| 41 |
+
"""
|
| 42 |
+
internal helper to extracr from our fontconfig filenames
|
| 43 |
+
of the form 69-language-selector-zh-tw.conf the locale
|
| 44 |
+
and country
|
| 45 |
+
|
| 46 |
+
returns string of the form locale_COUTNRY (e.g. zh_TW)
|
| 47 |
+
"""
|
| 48 |
+
fname = os.path.splitext(os.path.basename(name))[0]
|
| 49 |
+
(head, ll, cc) = string.rsplit(fname, "-", 2)
|
| 50 |
+
return "%s_%s" % (ll, cc.upper())
|
| 51 |
+
def getAvailableConfigs(self):
|
| 52 |
+
""" get the configurations we have as a list of languages
|
| 53 |
+
(returns a list of ['zh_CN','zh_TW'])
|
| 54 |
+
"""
|
| 55 |
+
res = []
|
| 56 |
+
pattern = "%s/conf.avail/69-language-selector-*" % self.globalConfDir
|
| 57 |
+
for name in glob.glob(pattern):
|
| 58 |
+
res.append(self._getLocaleCountryFromFileName(name))
|
| 59 |
+
return res
|
| 60 |
+
def getCurrentConfig(self):
|
| 61 |
+
""" returns the current language configuration as a string (e.g. zh_CN)
|
| 62 |
+
|
| 63 |
+
if the configfile is not a symlink it raises a
|
| 64 |
+
ExceptionNotSymlink exception
|
| 65 |
+
if the file dosn't exists raise a
|
| 66 |
+
ExceptionUnconfigured exception
|
| 67 |
+
"""
|
| 68 |
+
pattern = "%s/conf.d/69-language-selector-*" % self.globalConfDir
|
| 69 |
+
current_config = glob.glob(pattern)
|
| 70 |
+
if len(current_config) == 0:
|
| 71 |
+
raise ExceptionUnconfigured()
|
| 72 |
+
if len(current_config) > 1:
|
| 73 |
+
raise ExceptionMultipleConfigurations()
|
| 74 |
+
return self._getLocaleCountryFromFileName(current_config[0])
|
| 75 |
+
|
| 76 |
+
def removeConfig(self):
|
| 77 |
+
""" removes the current fontconfig-voodoo configuration
|
| 78 |
+
and do some sanity checking
|
| 79 |
+
"""
|
| 80 |
+
pattern = "%s/conf.d/*-language-selector-*" % self.globalConfDir
|
| 81 |
+
for f in glob.glob(pattern):
|
| 82 |
+
if os.path.exists(f):
|
| 83 |
+
os.unlink(f)
|
| 84 |
+
|
| 85 |
+
def setConfig(self, locale):
|
| 86 |
+
""" set the configuration for 'locale'. if locale can't be
|
| 87 |
+
found a NoConfigurationForLocale exception it thrown
|
| 88 |
+
"""
|
| 89 |
+
macr = macros.LangpackMacros(self._datadir, locale)
|
| 90 |
+
locale = macr["LOCALE"]
|
| 91 |
+
# check if we have a config
|
| 92 |
+
if locale not in self.getAvailableConfigs():
|
| 93 |
+
raise ExceptionNoConfigForLocale()
|
| 94 |
+
# remove old symlink
|
| 95 |
+
self.removeConfig()
|
| 96 |
+
# do the symlinks, link from /etc/fonts/conf.avail in /etc/fonts/conf.d
|
| 97 |
+
basedir = "%s/conf.avail/" % self.globalConfDir
|
| 98 |
+
for pattern in ["*-language-selector-%s-%s.conf" % (macr["LCODE"], macr["CCODE"].lower()),
|
| 99 |
+
"*-language-selector-%s.conf" % macr["LCODE"],
|
| 100 |
+
]:
|
| 101 |
+
for f in glob.glob(os.path.join(basedir,pattern)):
|
| 102 |
+
fname = os.path.basename(f)
|
| 103 |
+
from_link = os.path.join(self.globalConfDir,"conf.avail",fname)
|
| 104 |
+
to_link = os.path.join(self.globalConfDir, "conf.d", fname)
|
| 105 |
+
os.symlink(from_link, to_link)
|
| 106 |
+
return True
|
| 107 |
+
|
| 108 |
+
def setConfigBasedOnLocale(self):
|
| 109 |
+
""" set the configuration based on the locale in LocaleInfo. If
|
| 110 |
+
no configuration is found the fontconfig config is set to
|
| 111 |
+
'none'
|
| 112 |
+
Can throw a exception
|
| 113 |
+
"""
|
| 114 |
+
lang = self.li.getUserDefaultLanguage()[1]
|
| 115 |
+
if len(lang) == 0:
|
| 116 |
+
lang = self.li.getSystemDefaultLanguage()[1]
|
| 117 |
+
locale = language2locale(lang)
|
| 118 |
+
self.setConfig(locale)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
if __name__ == "__main__":
|
| 122 |
+
fc = FontConfigHack()
|
| 123 |
+
# available
|
| 124 |
+
print "available: ", fc.getAvailableConfigs()
|
| 125 |
+
|
| 126 |
+
# current
|
| 127 |
+
try:
|
| 128 |
+
config = fc.getCurrentConfig()
|
| 129 |
+
except ExceptionUnconfigured:
|
| 130 |
+
print "unconfigured"
|
| 131 |
+
|
| 132 |
+
# set config
|
| 133 |
+
print "set config: ", fc.setConfig("zh_CN")
|
| 134 |
+
print "current: ", fc.getCurrentConfig()
|
| 135 |
+
|
| 136 |
+
# auto mode
|
| 137 |
+
try:
|
| 138 |
+
print "run auto mode: ", fc.setConfigBasedOnLocale()
|
| 139 |
+
except ExceptionNoConfigForLocale:
|
| 140 |
+
print "no config for this locale"
|
| 141 |
+
|
| 142 |
+
# remove
|
| 143 |
+
print "removeConfig()"
|
| 144 |
+
fc.removeConfig()
|
| 145 |
+
try:
|
| 146 |
+
config = fc.getCurrentConfig()
|
| 147 |
+
print "ERROR: have config after calling removeConfig()"
|
| 148 |
+
except ExceptionUnconfigured:
|
| 149 |
+
print "unconfigured (as expected)"
|
pool/shard009/Python/0080593_mikrocliche03.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
from music21 import *
|
| 4 |
+
import random
|
| 5 |
+
import copy
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
n_compassos=16
|
| 10 |
+
|
| 11 |
+
# Criamos um objeto score (partitura) para usar como fluxo principal
|
| 12 |
+
partitura=stream.Score()
|
| 13 |
+
|
| 14 |
+
# Separamos o fluxo em duas partes: duas pautas
|
| 15 |
+
mao_esquerda=stream.PartStaff()
|
| 16 |
+
mao_direita=stream.PartStaff()
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
#Criamos o primeiro compasso para cada pauta
|
| 20 |
+
compasso1L=stream.Measure(number=1)
|
| 21 |
+
compasso1R=stream.Measure(number=1)
|
| 22 |
+
|
| 23 |
+
# Necessitamos formatar o layout do staff para agrupar as duas pautas
|
| 24 |
+
compasso1L.insert(0,layout.SystemLayout())
|
| 25 |
+
compasso1L.insert(0,layout.StaffLayout(staffNumber=2))
|
| 26 |
+
compasso1R.insert(0,layout.SystemLayout())
|
| 27 |
+
|
| 28 |
+
# Inserindo a clave, a formula de compasso inicial
|
| 29 |
+
compasso1L.insert(0,clef.BassClef())
|
| 30 |
+
compasso1L.insert(0,meter.TimeSignature('4/4'))
|
| 31 |
+
mao_esquerda.insert(0,compasso1L)
|
| 32 |
+
|
| 33 |
+
# Inserindo a clave, a formula de compasso inicial
|
| 34 |
+
compasso1R.insert(0,clef.TrebleClef())
|
| 35 |
+
compasso1R.insert(0,meter.TimeSignature('4/4'))
|
| 36 |
+
mao_direita.insert(0,compasso1R)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
########## escalas
|
| 40 |
+
|
| 41 |
+
pitchList = ["C4","D4","F4","G4","A4","C5"]
|
| 42 |
+
PentaScale = scale.AbstractScale()
|
| 43 |
+
PentaScale.buildNetworkFromPitches([pitch.Pitch(p) for p in pitchList])
|
| 44 |
+
escala_melodia = PentaScale._net.realizePitch('D5')
|
| 45 |
+
|
| 46 |
+
escala2 = scale.DorianScale('D')
|
| 47 |
+
escala_baixo=escala2.getPitches('d2', 'd3')
|
| 48 |
+
TAM_linha_baixo=len(escala_baixo)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
random.shuffle(escala_baixo)
|
| 52 |
+
escala_melodia.reverse()
|
| 53 |
+
###################################
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
for n in xrange(n_compassos):
|
| 57 |
+
compasso_esquerdo=stream.Measure(number=n)
|
| 58 |
+
compasso_direito=stream.Measure(number=n)
|
| 59 |
+
rotacao1=random.randint(0,100)
|
| 60 |
+
rotacao2=random.randint(0,100)
|
| 61 |
+
for t in xrange(8):
|
| 62 |
+
baixo=note.Note(escala_baixo[(rotacao1+t)%TAM_linha_baixo],
|
| 63 |
+
quarterLength=.5)
|
| 64 |
+
compasso_esquerdo.append(baixo)
|
| 65 |
+
|
| 66 |
+
melodia=note.Note(escala_melodia[(rotacao2+t)%6],
|
| 67 |
+
quarterLength=.5)
|
| 68 |
+
compasso_direito.append(melodia)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
mao_esquerda.insert(n,compasso_esquerdo)
|
| 73 |
+
mao_direita.insert(n,compasso_direito)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
# Formatando a entrada das partes na camada de layout da partitura
|
| 77 |
+
partitura.insert(0,mao_direita)
|
| 78 |
+
partitura.insert(0,mao_esquerda)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
##################### processamento
|
| 84 |
+
P='lily.pdf'
|
| 85 |
+
M='midi'
|
| 86 |
+
T='text'
|
| 87 |
+
X='musicxml'
|
| 88 |
+
|
| 89 |
+
partitura.show(X)
|
| 90 |
+
|
pool/shard009/Python/0080594_validators.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""
|
| 3 |
+
:copyright: (c) 2013-2021 by Mike Taylor and Kartik Prabhu
|
| 4 |
+
:license: MIT, see LICENSE for more details.
|
| 5 |
+
|
| 6 |
+
IndieWeb URL Validation
|
| 7 |
+
|
| 8 |
+
Regex and URL validators borrowed from django.core.validators
|
| 9 |
+
https://github.com/django/django/blob/master/django/core/validators.py
|
| 10 |
+
|
| 11 |
+
Copyright (c) Django Software Foundation and individual contributors.
|
| 12 |
+
All rights reserved.
|
| 13 |
+
BSD Licensed
|
| 14 |
+
"""
|
| 15 |
+
import re
|
| 16 |
+
|
| 17 |
+
from urllib.parse import urlsplit, urlunsplit
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class RegexValidator(object): # pylint: disable=R0205
|
| 21 |
+
"""Abstract Class to validate URLs using given regular expressions
|
| 22 |
+
"""
|
| 23 |
+
regex = ''
|
| 24 |
+
message = 'Enter a valid value.'
|
| 25 |
+
|
| 26 |
+
def __init__(self, regex=None, message=None):
|
| 27 |
+
if regex is not None:
|
| 28 |
+
self.regex = regex
|
| 29 |
+
if message is not None:
|
| 30 |
+
self.message = message
|
| 31 |
+
|
| 32 |
+
# Compile the regex if it was not passed pre-compiled.
|
| 33 |
+
if isinstance(self.regex, str):
|
| 34 |
+
self.regex = re.compile(self.regex)
|
| 35 |
+
|
| 36 |
+
def __call__(self, value):
|
| 37 |
+
"""
|
| 38 |
+
Validates that the input matches the regular expression.
|
| 39 |
+
"""
|
| 40 |
+
if not self.regex.search(value):
|
| 41 |
+
raise ValueError(self.message)
|
| 42 |
+
|
| 43 |
+
def __eq__(self, other):
|
| 44 |
+
return isinstance(other, RegexValidator) and (self.regex == other.regex) and (self.message == other.message)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class URLValidator(RegexValidator): # pylint: disable=R0903
|
| 48 |
+
"""URL Validation using a regular expression
|
| 49 |
+
"""
|
| 50 |
+
regex = re.compile(
|
| 51 |
+
r'^(?:[a-z0-9\.\-]*)://' # scheme is validated separately
|
| 52 |
+
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain...
|
| 53 |
+
r'localhost|' # localhost...
|
| 54 |
+
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|' # ...or ipv4
|
| 55 |
+
r'\[?[A-F0-9]*:[A-F0-9:]+\]?)' # ...or ipv6
|
| 56 |
+
r'(?::\d+)?' # optional port
|
| 57 |
+
r'(?:/?|[/?]\S+)$', re.IGNORECASE)
|
| 58 |
+
message = 'Enter a valid URL.'
|
| 59 |
+
# check only http and https
|
| 60 |
+
schemes = ['http', 'https']
|
| 61 |
+
|
| 62 |
+
def __init__(self, schemes=None, **kwargs):
|
| 63 |
+
super(URLValidator, self).__init__(**kwargs)
|
| 64 |
+
if schemes is not None:
|
| 65 |
+
self.schemes = schemes
|
| 66 |
+
|
| 67 |
+
def __call__(self, value):
|
| 68 |
+
e = ValueError(self.message)
|
| 69 |
+
# Check for None, and empty string
|
| 70 |
+
if value in (None, ''):
|
| 71 |
+
raise e
|
| 72 |
+
value = str(value)
|
| 73 |
+
# Check first if the scheme is valid
|
| 74 |
+
scheme = value.split('://')[0].lower()
|
| 75 |
+
if scheme not in self.schemes:
|
| 76 |
+
raise e
|
| 77 |
+
|
| 78 |
+
# Then check full URL
|
| 79 |
+
try:
|
| 80 |
+
super(URLValidator, self).__call__(value)
|
| 81 |
+
except ValueError:
|
| 82 |
+
# Trivial case failed. Try for possible IDN domain
|
| 83 |
+
if value:
|
| 84 |
+
scheme, netloc, path, query, fragment = urlsplit(value)
|
| 85 |
+
try:
|
| 86 |
+
netloc = netloc.encode('idna').decode('ascii') # IDN -> ACE
|
| 87 |
+
except UnicodeError: # invalid domain part
|
| 88 |
+
raise e
|
| 89 |
+
url = urlunsplit((scheme, netloc, path, query, fragment))
|
| 90 |
+
super(URLValidator, self).__call__(url)
|
| 91 |
+
else:
|
| 92 |
+
raise e
|
| 93 |
+
else:
|
| 94 |
+
url = value
|
pool/shard009/Python/0080604_mbcharsetprober.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
######################## BEGIN LICENSE BLOCK ########################
|
| 2 |
+
# The Original Code is Mozilla Universal charset detector code.
|
| 3 |
+
#
|
| 4 |
+
# The Initial Developer of the Original Code is
|
| 5 |
+
# Netscape Communications Corporation.
|
| 6 |
+
# Portions created by the Initial Developer are Copyright (C) 2001
|
| 7 |
+
# the Initial Developer. All Rights Reserved.
|
| 8 |
+
#
|
| 9 |
+
# Contributor(s):
|
| 10 |
+
# Mark Pilgrim - port to Python
|
| 11 |
+
# Shy Shalom - original C code
|
| 12 |
+
# Proofpoint, Inc.
|
| 13 |
+
#
|
| 14 |
+
# This library is free software; you can redistribute it and/or
|
| 15 |
+
# modify it under the terms of the GNU Lesser General Public
|
| 16 |
+
# License as published by the Free Software Foundation; either
|
| 17 |
+
# version 2.1 of the License, or (at your option) any later version.
|
| 18 |
+
#
|
| 19 |
+
# This library is distributed in the hope that it will be useful,
|
| 20 |
+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
| 21 |
+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
| 22 |
+
# Lesser General Public License for more details.
|
| 23 |
+
#
|
| 24 |
+
# You should have received a copy of the GNU Lesser General Public
|
| 25 |
+
# License along with this library; if not, write to the Free Software
|
| 26 |
+
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
|
| 27 |
+
# 02110-1301 USA
|
| 28 |
+
######################### END LICENSE BLOCK #########################
|
| 29 |
+
|
| 30 |
+
from .charsetprober import CharSetProber
|
| 31 |
+
from .enums import MachineState, ProbingState
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class MultiByteCharSetProber(CharSetProber):
|
| 35 |
+
"""
|
| 36 |
+
MultiByteCharSetProber
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
def __init__(self, lang_filter=None):
|
| 40 |
+
super().__init__(lang_filter=lang_filter)
|
| 41 |
+
self.distribution_analyzer = None
|
| 42 |
+
self.coding_sm = None
|
| 43 |
+
self._last_char = [0, 0]
|
| 44 |
+
|
| 45 |
+
def reset(self):
|
| 46 |
+
super().reset()
|
| 47 |
+
if self.coding_sm:
|
| 48 |
+
self.coding_sm.reset()
|
| 49 |
+
if self.distribution_analyzer:
|
| 50 |
+
self.distribution_analyzer.reset()
|
| 51 |
+
self._last_char = [0, 0]
|
| 52 |
+
|
| 53 |
+
@property
|
| 54 |
+
def charset_name(self):
|
| 55 |
+
raise NotImplementedError
|
| 56 |
+
|
| 57 |
+
@property
|
| 58 |
+
def language(self):
|
| 59 |
+
raise NotImplementedError
|
| 60 |
+
|
| 61 |
+
def feed(self, byte_str):
|
| 62 |
+
for i in range(len(byte_str)):
|
| 63 |
+
coding_state = self.coding_sm.next_state(byte_str[i])
|
| 64 |
+
if coding_state == MachineState.ERROR:
|
| 65 |
+
self.logger.debug(
|
| 66 |
+
"%s %s prober hit error at byte %s",
|
| 67 |
+
self.charset_name,
|
| 68 |
+
self.language,
|
| 69 |
+
i,
|
| 70 |
+
)
|
| 71 |
+
self._state = ProbingState.NOT_ME
|
| 72 |
+
break
|
| 73 |
+
elif coding_state == MachineState.ITS_ME:
|
| 74 |
+
self._state = ProbingState.FOUND_IT
|
| 75 |
+
break
|
| 76 |
+
elif coding_state == MachineState.START:
|
| 77 |
+
char_len = self.coding_sm.get_current_charlen()
|
| 78 |
+
if i == 0:
|
| 79 |
+
self._last_char[1] = byte_str[0]
|
| 80 |
+
self.distribution_analyzer.feed(self._last_char, char_len)
|
| 81 |
+
else:
|
| 82 |
+
self.distribution_analyzer.feed(byte_str[i - 1 : i + 1], char_len)
|
| 83 |
+
|
| 84 |
+
self._last_char[0] = byte_str[-1]
|
| 85 |
+
|
| 86 |
+
if self.state == ProbingState.DETECTING:
|
| 87 |
+
if self.distribution_analyzer.got_enough_data() and (
|
| 88 |
+
self.get_confidence() > self.SHORTCUT_THRESHOLD
|
| 89 |
+
):
|
| 90 |
+
self._state = ProbingState.FOUND_IT
|
| 91 |
+
|
| 92 |
+
return self.state
|
| 93 |
+
|
| 94 |
+
def get_confidence(self):
|
| 95 |
+
return self.distribution_analyzer.get_confidence()
|
pool/shard009/Python/0080614_importer.py
ADDED
|
@@ -0,0 +1,363 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
# -*- coding: utf8 -*-
|
| 3 |
+
# *****************************************************************
|
| 4 |
+
# ** PTS -- Python Toolkit for working with SKIRT **
|
| 5 |
+
# ** © Astronomical Observatory, Ghent University **
|
| 6 |
+
# *****************************************************************
|
| 7 |
+
|
| 8 |
+
## \package pts.magic.catalog.importer Contains the CatalogImporter class.
|
| 9 |
+
|
| 10 |
+
# -----------------------------------------------------------------
|
| 11 |
+
|
| 12 |
+
# Ensure Python 3 functionality
|
| 13 |
+
from __future__ import absolute_import, division, print_function
|
| 14 |
+
|
| 15 |
+
# Import standard modules
|
| 16 |
+
import os
|
| 17 |
+
from config import Sequence
|
| 18 |
+
|
| 19 |
+
# Import the relevant PTS classes and modules
|
| 20 |
+
from ..basics.catalogcoverage import CatalogCoverage
|
| 21 |
+
from ..tools import catalogs
|
| 22 |
+
from ...core.basics.configurable import OldConfigurable
|
| 23 |
+
from ...core.tools import introspection, tables
|
| 24 |
+
from ...core.tools import filesystem as fs
|
| 25 |
+
from ...core.tools.logging import log
|
| 26 |
+
|
| 27 |
+
# -----------------------------------------------------------------
|
| 28 |
+
|
| 29 |
+
class CatalogImporter(OldConfigurable):
|
| 30 |
+
|
| 31 |
+
"""
|
| 32 |
+
This class ...
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
def __init__(self, config=None):
|
| 36 |
+
|
| 37 |
+
"""
|
| 38 |
+
The constructor ...
|
| 39 |
+
:param config:
|
| 40 |
+
:return:
|
| 41 |
+
"""
|
| 42 |
+
|
| 43 |
+
# Call the constructor of the base class
|
| 44 |
+
super(CatalogImporter, self).__init__(config, "magic")
|
| 45 |
+
|
| 46 |
+
# The image frame
|
| 47 |
+
self.frame = None
|
| 48 |
+
|
| 49 |
+
# The name of the galaxy
|
| 50 |
+
self._has_dustpedia_catalog = None
|
| 51 |
+
self.galaxy_name = None
|
| 52 |
+
|
| 53 |
+
# The galactic and stellar catalogs
|
| 54 |
+
self.galactic_catalog = None
|
| 55 |
+
self.stellar_catalog = None
|
| 56 |
+
|
| 57 |
+
# Determine the path to the catalogs user directory (where the DustPedia catalogs are now stored)
|
| 58 |
+
self.catalogs_user_path = os.path.join(introspection.pts_user_dir, "magic", "catalogs")
|
| 59 |
+
|
| 60 |
+
# -----------------------------------------------------------------
|
| 61 |
+
|
| 62 |
+
def run(self, frame):
|
| 63 |
+
|
| 64 |
+
"""
|
| 65 |
+
This function ...
|
| 66 |
+
:param frame:
|
| 67 |
+
:return:
|
| 68 |
+
"""
|
| 69 |
+
|
| 70 |
+
# 1. Call the setup function
|
| 71 |
+
self.setup(frame)
|
| 72 |
+
|
| 73 |
+
# 2. Import the galactic catalog
|
| 74 |
+
self.import_galactic_catalog()
|
| 75 |
+
|
| 76 |
+
# 3. Import the stellar catalog
|
| 77 |
+
self.import_stellar_catalog()
|
| 78 |
+
|
| 79 |
+
# -----------------------------------------------------------------
|
| 80 |
+
|
| 81 |
+
def clear(self):
|
| 82 |
+
|
| 83 |
+
"""
|
| 84 |
+
This function ...
|
| 85 |
+
:return:
|
| 86 |
+
"""
|
| 87 |
+
|
| 88 |
+
# Set attributes to None
|
| 89 |
+
self.frame = None
|
| 90 |
+
self.galaxy_name = None
|
| 91 |
+
self.galactic_catalog = None
|
| 92 |
+
self.stellar_catalog = None
|
| 93 |
+
|
| 94 |
+
# -----------------------------------------------------------------
|
| 95 |
+
|
| 96 |
+
def setup(self, frame):
|
| 97 |
+
|
| 98 |
+
"""
|
| 99 |
+
This function ...
|
| 100 |
+
:param frame:
|
| 101 |
+
:return:
|
| 102 |
+
"""
|
| 103 |
+
|
| 104 |
+
# Call the setup function of the base class
|
| 105 |
+
super(CatalogImporter, self).setup()
|
| 106 |
+
|
| 107 |
+
# Set the frame
|
| 108 |
+
self.frame = frame
|
| 109 |
+
|
| 110 |
+
# -----------------------------------------------------------------
|
| 111 |
+
|
| 112 |
+
def import_galactic_catalog(self):
|
| 113 |
+
|
| 114 |
+
"""
|
| 115 |
+
This function ...
|
| 116 |
+
:return:
|
| 117 |
+
"""
|
| 118 |
+
|
| 119 |
+
# Inform the user
|
| 120 |
+
log.info("Importing galactic catalog ...")
|
| 121 |
+
|
| 122 |
+
# Use catalog file if specified
|
| 123 |
+
if self.config.galaxies.use_catalog_file: self.import_galactic_catalog_from_file()
|
| 124 |
+
elif self.has_dustpedia_catalog: self.import_galactic_dustpedia_catalog()
|
| 125 |
+
else: self.fetch_galactic_catalog()
|
| 126 |
+
|
| 127 |
+
# -----------------------------------------------------------------
|
| 128 |
+
|
| 129 |
+
def import_stellar_catalog(self):
|
| 130 |
+
|
| 131 |
+
"""
|
| 132 |
+
This function ...
|
| 133 |
+
:return:
|
| 134 |
+
"""
|
| 135 |
+
|
| 136 |
+
# Inform the user
|
| 137 |
+
log.info("Importing stellar catalog ...")
|
| 138 |
+
|
| 139 |
+
# Use catalog file if specified
|
| 140 |
+
if self.config.stars.use_catalog_file: self.import_stellar_catalog_from_file()
|
| 141 |
+
elif self.has_dustpedia_catalog: self.import_stellar_dustpedia_catalog()
|
| 142 |
+
else: self.fetch_stellar_catalog()
|
| 143 |
+
|
| 144 |
+
# -----------------------------------------------------------------
|
| 145 |
+
|
| 146 |
+
@property
|
| 147 |
+
def has_dustpedia_catalog(self):
|
| 148 |
+
|
| 149 |
+
"""
|
| 150 |
+
This function ...
|
| 151 |
+
:return:
|
| 152 |
+
"""
|
| 153 |
+
|
| 154 |
+
# Avoid overhead when calling this function twice
|
| 155 |
+
if self._has_dustpedia_catalog is not None: return self._has_dustpedia_catalog
|
| 156 |
+
|
| 157 |
+
# Get bounding box of the frame
|
| 158 |
+
bounding_box = self.frame.bounding_box()
|
| 159 |
+
|
| 160 |
+
# Loop over all directories within the catalogs directory (different galaxies)
|
| 161 |
+
for galaxy_path in fs.directories_in_path(self.catalogs_user_path):
|
| 162 |
+
|
| 163 |
+
# Get the galaxy name
|
| 164 |
+
galaxy_name = os.path.basename(galaxy_path)
|
| 165 |
+
|
| 166 |
+
# Get the catalog coverage for this galaxy
|
| 167 |
+
coverage = CatalogCoverage(galaxy_name)
|
| 168 |
+
|
| 169 |
+
# Check whether this galaxy matches the current frame
|
| 170 |
+
if coverage.matches(bounding_box):
|
| 171 |
+
|
| 172 |
+
# Debug info
|
| 173 |
+
log.debug("Found a match with DustPedia catalog for galaxy " + galaxy_name)
|
| 174 |
+
|
| 175 |
+
self._has_dustpedia_catalog = True
|
| 176 |
+
self.galaxy_name = galaxy_name
|
| 177 |
+
|
| 178 |
+
break
|
| 179 |
+
|
| 180 |
+
# If a break is not encountered
|
| 181 |
+
else: self._has_dustpedia_catalog = False
|
| 182 |
+
|
| 183 |
+
# Return the answer
|
| 184 |
+
return self._has_dustpedia_catalog
|
| 185 |
+
|
| 186 |
+
# -----------------------------------------------------------------
|
| 187 |
+
|
| 188 |
+
def import_galactic_catalog_from_file(self):
|
| 189 |
+
|
| 190 |
+
"""
|
| 191 |
+
This function ...
|
| 192 |
+
:return:
|
| 193 |
+
"""
|
| 194 |
+
|
| 195 |
+
# Determine the full path to the catalog file
|
| 196 |
+
path = self.full_input_path(self.config.galaxies.catalog_path)
|
| 197 |
+
|
| 198 |
+
# Inform the user
|
| 199 |
+
log.info("Importing galactic catalog from file " + path + " ...")
|
| 200 |
+
|
| 201 |
+
# Load the catalog
|
| 202 |
+
self.galactic_catalog = tables.from_file(path, format="ascii.commented_header")
|
| 203 |
+
|
| 204 |
+
# -----------------------------------------------------------------
|
| 205 |
+
|
| 206 |
+
def import_stellar_catalog_from_file(self):
|
| 207 |
+
|
| 208 |
+
"""
|
| 209 |
+
This function ...
|
| 210 |
+
:return:
|
| 211 |
+
"""
|
| 212 |
+
|
| 213 |
+
# Determine the full path to the catalog file
|
| 214 |
+
path = self.full_input_path(self.config.stars.catalog_path)
|
| 215 |
+
|
| 216 |
+
# Inform the user
|
| 217 |
+
log.info("Importing stellar catalog from file " + path + " ...")
|
| 218 |
+
|
| 219 |
+
# Load the catalog
|
| 220 |
+
self.stellar_catalog = tables.from_file(path, format="ascii.commented_header")
|
| 221 |
+
|
| 222 |
+
# -----------------------------------------------------------------
|
| 223 |
+
|
| 224 |
+
def import_galactic_dustpedia_catalog(self):
|
| 225 |
+
|
| 226 |
+
"""
|
| 227 |
+
This function ...
|
| 228 |
+
:return:
|
| 229 |
+
"""
|
| 230 |
+
|
| 231 |
+
# Inform the user
|
| 232 |
+
log.info("Importing galactic DustPedia catalog for " + self.galaxy_name)
|
| 233 |
+
|
| 234 |
+
# Determine the path to the DustPedia galactic catalog for this galaxy
|
| 235 |
+
galaxy_path = os.path.join(self.catalogs_user_path, self.galaxy_name)
|
| 236 |
+
galactic_catalog_path = os.path.join(galaxy_path, "galaxies.cat")
|
| 237 |
+
|
| 238 |
+
# Load the galactic catalog
|
| 239 |
+
self.galactic_catalog = tables.from_file(galactic_catalog_path)
|
| 240 |
+
|
| 241 |
+
# -----------------------------------------------------------------
|
| 242 |
+
|
| 243 |
+
def import_stellar_dustpedia_catalog(self):
|
| 244 |
+
|
| 245 |
+
"""
|
| 246 |
+
This function ...
|
| 247 |
+
:return:
|
| 248 |
+
"""
|
| 249 |
+
|
| 250 |
+
# Inform the user
|
| 251 |
+
log.info("Importing stellar DustPedia catalog for " + self.galaxy_name)
|
| 252 |
+
|
| 253 |
+
# Determine the path to the DustPedia stellar catalog for this galaxy
|
| 254 |
+
galaxy_path = os.path.join(self.catalogs_user_path, self.galaxy_name)
|
| 255 |
+
stellar_catalog_path = os.path.join(galaxy_path, "stars.cat")
|
| 256 |
+
|
| 257 |
+
# Load the stellar catalog
|
| 258 |
+
self.stellar_catalog = tables.from_file(stellar_catalog_path)
|
| 259 |
+
|
| 260 |
+
# -----------------------------------------------------------------
|
| 261 |
+
|
| 262 |
+
def fetch_galactic_catalog(self):
|
| 263 |
+
|
| 264 |
+
"""
|
| 265 |
+
This function ...
|
| 266 |
+
:return:
|
| 267 |
+
"""
|
| 268 |
+
|
| 269 |
+
# Inform the user
|
| 270 |
+
log.info("Fetching galaxy positions from an online catalog ...")
|
| 271 |
+
|
| 272 |
+
# Create the galaxy catalog
|
| 273 |
+
self.galactic_catalog = catalogs.create_galaxy_catalog(self.frame)
|
| 274 |
+
|
| 275 |
+
# Inform the user
|
| 276 |
+
log.debug("Number of galaxies: " + str(len(self.galactic_catalog)))
|
| 277 |
+
|
| 278 |
+
# -----------------------------------------------------------------
|
| 279 |
+
|
| 280 |
+
def fetch_stellar_catalog(self):
|
| 281 |
+
|
| 282 |
+
"""
|
| 283 |
+
This function ...
|
| 284 |
+
:return:
|
| 285 |
+
"""
|
| 286 |
+
|
| 287 |
+
# Inform the user
|
| 288 |
+
log.info("Fetching star positions from online catalogs ...")
|
| 289 |
+
|
| 290 |
+
# Check whether the 'catalogs' setting defines a single catalog name or a list of such names
|
| 291 |
+
if isinstance(self.config.stars.fetching.catalogs, basestring): catalog_list = [self.config.stars.fetching.catalogs]
|
| 292 |
+
elif isinstance(self.config.stars.fetching.catalogs, Sequence): catalog_list = self.config.stars.fetching.catalogs
|
| 293 |
+
else: raise ValueError("Invalid option for 'catalogs', should be a string or a list of strings")
|
| 294 |
+
|
| 295 |
+
# Create the star catalog
|
| 296 |
+
self.stellar_catalog = catalogs.create_star_catalog(self.frame, catalog_list)
|
| 297 |
+
|
| 298 |
+
# Inform the user
|
| 299 |
+
log.debug("Number of stars: " + str(len(self.stellar_catalog)))
|
| 300 |
+
|
| 301 |
+
# -----------------------------------------------------------------
|
| 302 |
+
|
| 303 |
+
def write_galactic_catalog_to(self, path):
|
| 304 |
+
|
| 305 |
+
"""
|
| 306 |
+
This function ...
|
| 307 |
+
:param path:
|
| 308 |
+
:return:
|
| 309 |
+
"""
|
| 310 |
+
|
| 311 |
+
# Inform the user
|
| 312 |
+
log.info("Writing galactic catalog to " + path + " ...")
|
| 313 |
+
|
| 314 |
+
# Write the catalog to file
|
| 315 |
+
tables.write(self.galactic_catalog, path, format="ascii.commented_header")
|
| 316 |
+
|
| 317 |
+
# -----------------------------------------------------------------
|
| 318 |
+
|
| 319 |
+
def write_stellar_catalog_to(self, path):
|
| 320 |
+
|
| 321 |
+
"""
|
| 322 |
+
This function ...
|
| 323 |
+
:param path:
|
| 324 |
+
:return:
|
| 325 |
+
"""
|
| 326 |
+
|
| 327 |
+
# Inform the user
|
| 328 |
+
log.info("Writing stellar catalog to " + path + " ...")
|
| 329 |
+
|
| 330 |
+
# Write the catalog to file
|
| 331 |
+
tables.write(self.stellar_catalog, path, format="ascii.commented_header")
|
| 332 |
+
|
| 333 |
+
# -----------------------------------------------------------------
|
| 334 |
+
|
| 335 |
+
def write_galactic_catalog(self):
|
| 336 |
+
|
| 337 |
+
"""
|
| 338 |
+
This function ...
|
| 339 |
+
:return:
|
| 340 |
+
"""
|
| 341 |
+
|
| 342 |
+
# Determine the full path to the catalog file
|
| 343 |
+
path = self.full_output_path(self.config.writing.galactic_catalog_path)
|
| 344 |
+
|
| 345 |
+
# Write
|
| 346 |
+
self.write_galactic_catalog_to(path)
|
| 347 |
+
|
| 348 |
+
# -----------------------------------------------------------------
|
| 349 |
+
|
| 350 |
+
def write_stellar_catalog(self):
|
| 351 |
+
|
| 352 |
+
"""
|
| 353 |
+
This function ...
|
| 354 |
+
:return:
|
| 355 |
+
"""
|
| 356 |
+
|
| 357 |
+
# Determine the full path to the catalog file
|
| 358 |
+
path = self.full_output_path(self.config.writing.stellar_catalog_path)
|
| 359 |
+
|
| 360 |
+
# Write
|
| 361 |
+
self.write_stellar_catalog_to(path)
|
| 362 |
+
|
| 363 |
+
# -----------------------------------------------------------------
|
pool/shard009/Python/0080618_reg.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2017 CodiLime
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class BaseRegister:
|
| 17 |
+
"""
|
| 18 |
+
Represents an ISA register. Fields:
|
| 19 |
+
|
| 20 |
+
- name: a name displayed for this register, should be unique.
|
| 21 |
+
- width: width in bits.
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
def __init__(self, name, width):
|
| 25 |
+
self.name = name
|
| 26 |
+
self.width = width
|
| 27 |
+
|
| 28 |
+
def __str__(self):
|
| 29 |
+
return "${}".format(self.name)
|
| 30 |
+
|
| 31 |
+
__repr__ = __str__
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class Register(BaseRegister):
|
| 35 |
+
"""
|
| 36 |
+
Represents a general-purpose, top-level ISA register. Writes to this
|
| 37 |
+
register will not be considered interesting on their own, and will be
|
| 38 |
+
converted wholly to SSA.
|
| 39 |
+
"""
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class RegisterPC(BaseRegister):
|
| 43 |
+
"""
|
| 44 |
+
Represents a program counter register, ie. one that always points to
|
| 45 |
+
some place in the current bundle, and thus will return a known value
|
| 46 |
+
when read.
|
| 47 |
+
"""
|
| 48 |
+
|
| 49 |
+
def __init__(self, name, width, anchor='start', offset=0):
|
| 50 |
+
super().__init__(name, width)
|
| 51 |
+
self.anchor = anchor
|
| 52 |
+
self.offset = offset
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class RegisterSP(BaseRegister):
|
| 56 |
+
"""
|
| 57 |
+
Represents a hardware stack pointer register.
|
| 58 |
+
"""
|
| 59 |
+
|
| 60 |
+
# XXX: does this warrant a special class? Might be better to handle it
|
| 61 |
+
# elsewhere.
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
# "You know what "special" means, right?" -- mupuf
|
| 65 |
+
class RegisterSpecial(BaseRegister):
|
| 66 |
+
"""
|
| 67 |
+
Represents a special register. Reads and writes of this register will be
|
| 68 |
+
considered to be interesting events, and will not be converted to SSA.
|
| 69 |
+
"""
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
class RegisterSplit(BaseRegister):
|
| 73 |
+
"""
|
| 74 |
+
Represents a split register, ie. one that is really multiple other
|
| 75 |
+
registers accessed together as a single entity. ``parts`` is a list
|
| 76 |
+
of (start bit, register) tuples. When accessed, the access is converted
|
| 77 |
+
to multiple smaller accesses to the parts.
|
| 78 |
+
"""
|
| 79 |
+
|
| 80 |
+
def __init__(self, name, width, parts):
|
| 81 |
+
super().__init__(name, width)
|
| 82 |
+
self.parts = parts
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class SubRegister(BaseRegister):
|
| 86 |
+
"""
|
| 87 |
+
Represents a subregister of another register. Defined by starting bit
|
| 88 |
+
position in the parent and width.
|
| 89 |
+
"""
|
| 90 |
+
|
| 91 |
+
def __init__(self, name, parent, start, width):
|
| 92 |
+
super().__init__(name, width)
|
| 93 |
+
self.parent = parent
|
| 94 |
+
self.start = start
|
pool/shard009/Python/0080620_BAMSequenceParser.py
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python2.7
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
|
| 4 |
+
"""
|
| 5 |
+
@package FastqSweeper
|
| 6 |
+
@brief Helper class parsing bam aligned sequence line in pysam compatible objects
|
| 7 |
+
@copyright [GNU General Public License v2](http://www.gnu.org/licenses/gpl-2.0.html)
|
| 8 |
+
@author Adrien Leger - 2015
|
| 9 |
+
* <adrien.leger@gmail.com>
|
| 10 |
+
* <adrien.leger@inserm.fr>
|
| 11 |
+
* <adrien.leger@univ-nantes.fr>
|
| 12 |
+
* [Github](https://github.com/a-slide)
|
| 13 |
+
* [Atlantic Gene Therapies - INSERM 1089] (http://www.atlantic-gene-therapies.fr/)
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
|
| 17 |
+
|
| 18 |
+
# Standard library packages
|
| 19 |
+
from collections import OrderedDict
|
| 20 |
+
from re import compile as recompile
|
| 21 |
+
|
| 22 |
+
# Third party package
|
| 23 |
+
import pysam
|
| 24 |
+
|
| 25 |
+
# Local packages
|
| 26 |
+
|
| 27 |
+
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
|
| 28 |
+
class BAMSequenceParser (object):
|
| 29 |
+
"""Create a pysam compatible AlignedSegment from a raw bam line
|
| 30 |
+
"""
|
| 31 |
+
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
|
| 32 |
+
|
| 33 |
+
#~~~~~~~FONDAMENTAL METHODS~~~~~~~#
|
| 34 |
+
|
| 35 |
+
def __init__ (self, header, skip_secondary=True):
|
| 36 |
+
|
| 37 |
+
print("\nParsing sam sequences")
|
| 38 |
+
|
| 39 |
+
# Store defined variables
|
| 40 |
+
self.header = header
|
| 41 |
+
self.skip_secondary = skip_secondary
|
| 42 |
+
|
| 43 |
+
# counters
|
| 44 |
+
self.count = {"total":0, "invalid":0, "primary":0, "secondary":0}
|
| 45 |
+
|
| 46 |
+
# For cigar to tuple code conversion
|
| 47 |
+
self.cigar_to_code = {'M':0, 'I':1, 'D':2, 'N':3, 'S':4, 'H':5, 'P':6, '=':7, 'X':8}
|
| 48 |
+
self.cigar_regex = recompile("(\d+)([MIDNSHP=X])")
|
| 49 |
+
|
| 50 |
+
def __str__ (self):
|
| 51 |
+
return "".join(["{}\t{}\n".format(i,j) for i, j in self.count.items()])
|
| 52 |
+
|
| 53 |
+
#~~~~~~~PUBLIC METHODS~~~~~~~#
|
| 54 |
+
|
| 55 |
+
def parse_line (self, line):
|
| 56 |
+
|
| 57 |
+
self.count["total"] += 1
|
| 58 |
+
# Try bloc to skip to the next line in case a non standard line is found
|
| 59 |
+
try:
|
| 60 |
+
# Split the line and verify the number of fields
|
| 61 |
+
split_line = line.strip().split("\t")
|
| 62 |
+
assert len (split_line) >= 11, "Invalid number of field in bam aligned sequence"
|
| 63 |
+
|
| 64 |
+
# Init an AlignedSegment
|
| 65 |
+
read = Read(
|
| 66 |
+
qname = split_line[0],
|
| 67 |
+
flag = int(split_line[1]),
|
| 68 |
+
rname = self.header.rname_to_refid(split_line[2]),
|
| 69 |
+
pos = int(split_line[3])-1,
|
| 70 |
+
mapq = int(split_line[4]),
|
| 71 |
+
cigar = self._cigarstring_to_tuple(split_line[5]),
|
| 72 |
+
rnext = self.header.rname_to_refid(split_line[6]),
|
| 73 |
+
pnext = int(split_line[7])-1,
|
| 74 |
+
seq = split_line[9],
|
| 75 |
+
qual = pysam.fromQualityString(split_line[10]),
|
| 76 |
+
tags = self._parse_tags(split_line [11:]) if len (split_line) >= 12 else tuple())
|
| 77 |
+
|
| 78 |
+
# skip the read if secondary and required
|
| 79 |
+
if read.is_secondary:
|
| 80 |
+
self.count["secondary"] += 1
|
| 81 |
+
if self.skip_secondary:
|
| 82 |
+
return None
|
| 83 |
+
|
| 84 |
+
# finally return the read
|
| 85 |
+
self.count["primary"] += 1
|
| 86 |
+
return read
|
| 87 |
+
|
| 88 |
+
except Exception as E:
|
| 89 |
+
print E
|
| 90 |
+
print "Invalid sequence line in bam: {}".format(line)
|
| 91 |
+
self.count["invalid"] += 1
|
| 92 |
+
return None
|
| 93 |
+
|
| 94 |
+
def _cigarstring_to_tuple (self, cigarstring):
|
| 95 |
+
"""Transform the cigar string in a pysam compatible tuple"""
|
| 96 |
+
if cigarstring == "*":
|
| 97 |
+
return None
|
| 98 |
+
else:
|
| 99 |
+
return tuple([(self.cigar_to_code[y], int(x)) for x, y in self.cigar_regex.findall(cigarstring)])
|
| 100 |
+
|
| 101 |
+
def _parse_tags (self, tags_split):
|
| 102 |
+
"""Parse the optional tag fields"""
|
| 103 |
+
tags = []
|
| 104 |
+
|
| 105 |
+
for tag in tags_split:
|
| 106 |
+
tag_split = tag.split(":")
|
| 107 |
+
key = tag_split[0]
|
| 108 |
+
value = int(tag_split[2]) if tag_split[1] == 'i' else tag_split[2]
|
| 109 |
+
tags.append((key, value,))
|
| 110 |
+
|
| 111 |
+
return tuple(tags)
|
| 112 |
+
|
| 113 |
+
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
|
| 114 |
+
class Read (object):
|
| 115 |
+
"""Wrapping class over a pysam AlignedSegment to surdefine, transform the init and
|
| 116 |
+
add dedicated methods"""
|
| 117 |
+
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
|
| 118 |
+
|
| 119 |
+
#~~~~~~~FONDAMENTAL METHODS~~~~~~~#
|
| 120 |
+
|
| 121 |
+
def __init__ (self, qname, flag, rname, pos, mapq, cigar, rnext, pnext, seq, qual, tags):
|
| 122 |
+
"""Create a pysam.AlignedSegment object and define fields"""
|
| 123 |
+
|
| 124 |
+
self.read = pysam.AlignedSegment()
|
| 125 |
+
self.read.query_name = qname
|
| 126 |
+
self.read.flag = flag
|
| 127 |
+
self.read.reference_id = rname
|
| 128 |
+
self.read.reference_start = pos
|
| 129 |
+
self.read.mapping_quality = mapq
|
| 130 |
+
self.read.cigar = cigar
|
| 131 |
+
self.read.next_reference_id = rnext
|
| 132 |
+
self.read.next_reference_start = pnext
|
| 133 |
+
self.read.template_length = self.read.infer_query_length() if self.read.cigar else 0
|
| 134 |
+
self.read.query_sequence = seq
|
| 135 |
+
self.read.query_qualities = qual
|
| 136 |
+
self.read.tags = tags
|
| 137 |
+
self.is_secondary = self.read.is_secondary
|
| 138 |
+
|
| 139 |
+
def __str__ (self):
|
| 140 |
+
return str(self.read)
|
| 141 |
+
|
| 142 |
+
#~~~~~~~PUBLIC METHODS~~~~~~~#
|
| 143 |
+
|
| 144 |
+
def is_properly_mapped(self, min_mapq, min_match_size):
|
| 145 |
+
"""Is properly mapped if mapped on e sequence with a mapq score higher the min_mapq
|
| 146 |
+
and a template lenght higher than min_match_size"""
|
| 147 |
+
return (self.read.tid != -1 and self.read.mapq >= min_mapq and self.read.template_length >= min_match_size)
|
| 148 |
+
|
| 149 |
+
def to_bam (self):
|
| 150 |
+
return self.read
|
| 151 |
+
|
| 152 |
+
def to_fastq (self):
|
| 153 |
+
return "@{}\n{}\n+\n{}\n".format(self.read.qname, self.read.seq, self.read.qual)
|
pool/shard009/Python/0080623_test_collection_ops.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import testutils
|
| 2 |
+
import json
|
| 3 |
+
import psycopg2
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class TestBasics(testutils.BedquiltTestCase):
|
| 7 |
+
|
| 8 |
+
def test_extension_presence(self):
|
| 9 |
+
result = self._query("""
|
| 10 |
+
select * from pg_catalog.pg_extension
|
| 11 |
+
where extname = 'bedquilt';
|
| 12 |
+
""")
|
| 13 |
+
|
| 14 |
+
self.assertIsNotNone(result)
|
| 15 |
+
self.assertEqual(len(result), 1)
|
| 16 |
+
|
| 17 |
+
row = result[0]
|
| 18 |
+
self.assertTrue(len(row) > 0)
|
| 19 |
+
self.assertEqual(row[0], 'bedquilt')
|
| 20 |
+
|
| 21 |
+
def test_assert_version(self):
|
| 22 |
+
result = self._query("""
|
| 23 |
+
select bq_util_assert_minimum_version('1.0.0');
|
| 24 |
+
""")
|
| 25 |
+
self.assertEqual(result, [(True,)])
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class TestCreateCollection(testutils.BedquiltTestCase):
|
| 29 |
+
|
| 30 |
+
def test_creating_a_new_collection(self):
|
| 31 |
+
# create a collection 'testone'
|
| 32 |
+
self.cur.execute("select bq_create_collection('testone')")
|
| 33 |
+
result = self.cur.fetchone()
|
| 34 |
+
|
| 35 |
+
self.assertEqual(len(result), 1)
|
| 36 |
+
self.assertEqual(result[0], True)
|
| 37 |
+
|
| 38 |
+
# create it again
|
| 39 |
+
self.cur.execute("select bq_create_collection('testone')")
|
| 40 |
+
result = self.cur.fetchone()
|
| 41 |
+
|
| 42 |
+
self.assertEqual(len(result), 1)
|
| 43 |
+
self.assertEqual(result[0], False)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class TestListCollections(testutils.BedquiltTestCase):
|
| 47 |
+
|
| 48 |
+
def test_list_collections_empty_instance(self):
|
| 49 |
+
|
| 50 |
+
self.cur.execute("select bq_list_collections();")
|
| 51 |
+
result = self.cur.fetchone()
|
| 52 |
+
|
| 53 |
+
self.assertIsNone(result)
|
| 54 |
+
|
| 55 |
+
def test_list_four_collections(self):
|
| 56 |
+
self.cur.execute("""
|
| 57 |
+
select bq_create_collection('c_one');
|
| 58 |
+
select bq_create_collection('c_two');
|
| 59 |
+
select bq_create_collection('c_three');
|
| 60 |
+
select bq_create_collection('c_four');
|
| 61 |
+
""", )
|
| 62 |
+
|
| 63 |
+
self.cur.execute("select bq_list_collections();")
|
| 64 |
+
result = self.cur.fetchall()
|
| 65 |
+
|
| 66 |
+
self.assertIsNotNone(result)
|
| 67 |
+
|
| 68 |
+
self.assertEqual(map(lambda e: e[0], result),
|
| 69 |
+
['c_one', 'c_two', 'c_three', 'c_four'])
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
class TestDeleteCollection(testutils.BedquiltTestCase):
|
| 73 |
+
|
| 74 |
+
def test_delete_non_existant_collection(self):
|
| 75 |
+
|
| 76 |
+
self.cur.execute("select bq_delete_collection('one');")
|
| 77 |
+
result = self.cur.fetchone()
|
| 78 |
+
|
| 79 |
+
self.assertEqual(len(result), 1)
|
| 80 |
+
self.assertEqual(result[0], False)
|
| 81 |
+
|
| 82 |
+
def test_delete_collection(self):
|
| 83 |
+
|
| 84 |
+
self.cur.execute("select bq_create_collection('one')")
|
| 85 |
+
|
| 86 |
+
self.cur.execute("select bq_delete_collection('one');")
|
| 87 |
+
result = self.cur.fetchone()
|
| 88 |
+
|
| 89 |
+
self.assertEqual(len(result), 1)
|
| 90 |
+
self.assertEqual(result[0], True)
|
pool/shard009/Python/0080624_0003_auto_20200224_1836.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Generated by Django 1.11.28 on 2020-02-24 18:36
|
| 3 |
+
from __future__ import unicode_literals
|
| 4 |
+
|
| 5 |
+
from django.conf import settings
|
| 6 |
+
from django.db import migrations
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class Migration(migrations.Migration):
|
| 10 |
+
|
| 11 |
+
dependencies = [
|
| 12 |
+
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
| 13 |
+
('external_user_ids', '0002_mb_coaching_20200210_1754'),
|
| 14 |
+
]
|
| 15 |
+
|
| 16 |
+
operations = [
|
| 17 |
+
migrations.AlterUniqueTogether(
|
| 18 |
+
name='externalid',
|
| 19 |
+
unique_together=set([('user', 'external_id_type')]),
|
| 20 |
+
),
|
| 21 |
+
]
|
pool/shard009/Python/0080625_templite.py
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
#
|
| 3 |
+
# Templite+
|
| 4 |
+
# A light-weight, fully functional, general purpose templating engine
|
| 5 |
+
#
|
| 6 |
+
# Copyright (c) 2009 joonis new media
|
| 7 |
+
# Author: Thimo Kraemer <thimo.kraemer@joonis.de>
|
| 8 |
+
#
|
| 9 |
+
# Based on Templite - Tomer Filiba
|
| 10 |
+
# http://code.activestate.com/recipes/496702/
|
| 11 |
+
#
|
| 12 |
+
# This program is free software; you can redistribute it and/or modify
|
| 13 |
+
# it under the terms of the GNU General Public License as published by
|
| 14 |
+
# the Free Software Foundation; either version 2 of the License, or
|
| 15 |
+
# (at your option) any later version.
|
| 16 |
+
#
|
| 17 |
+
# This program is distributed in the hope that it will be useful,
|
| 18 |
+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
| 19 |
+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
| 20 |
+
# GNU General Public License for more details.
|
| 21 |
+
#
|
| 22 |
+
# You should have received a copy of the GNU General Public License
|
| 23 |
+
# along with this program; if not, write to the Free Software
|
| 24 |
+
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
| 25 |
+
# MA 02110-1301, USA.
|
| 26 |
+
#
|
| 27 |
+
|
| 28 |
+
import sys, re
|
| 29 |
+
|
| 30 |
+
class Templite(object):
|
| 31 |
+
auto_emit = re.compile('(^[\'\"])|(^[a-zA-Z0-9_\[\]\'\"]+$)')
|
| 32 |
+
|
| 33 |
+
def __init__(self, template, start='${', end='}$'):
|
| 34 |
+
if len(start) != 2 or len(end) != 2:
|
| 35 |
+
raise ValueError('each delimiter must be two characters long')
|
| 36 |
+
delimiter = re.compile('%s(.*?)%s' % (re.escape(start), re.escape(end)), re.DOTALL)
|
| 37 |
+
offset = 0
|
| 38 |
+
tokens = []
|
| 39 |
+
for i, part in enumerate(delimiter.split(template)):
|
| 40 |
+
part = part.replace('\\'.join(list(start)), start)
|
| 41 |
+
part = part.replace('\\'.join(list(end)), end)
|
| 42 |
+
if i % 2 == 0:
|
| 43 |
+
if not part: continue
|
| 44 |
+
part = part.replace('\\', '\\\\').replace('"', '\\"')
|
| 45 |
+
part = '\t' * offset + 'emit("""%s""")' % part
|
| 46 |
+
else:
|
| 47 |
+
part = part.rstrip()
|
| 48 |
+
if not part: continue
|
| 49 |
+
if part.lstrip().startswith(':'):
|
| 50 |
+
if not offset:
|
| 51 |
+
raise SyntaxError('no block statement to terminate: ${%s}$' % part)
|
| 52 |
+
offset -= 1
|
| 53 |
+
part = part.lstrip()[1:]
|
| 54 |
+
if not part.endswith(':'): continue
|
| 55 |
+
elif self.auto_emit.match(part.lstrip()):
|
| 56 |
+
part = 'emit(%s)' % part.lstrip()
|
| 57 |
+
lines = part.splitlines()
|
| 58 |
+
margin = min(len(l) - len(l.lstrip()) for l in lines if l.strip())
|
| 59 |
+
part = '\n'.join('\t' * offset + l[margin:] for l in lines)
|
| 60 |
+
if part.endswith(':'):
|
| 61 |
+
offset += 1
|
| 62 |
+
tokens.append(part)
|
| 63 |
+
if offset:
|
| 64 |
+
raise SyntaxError('%i block statement(s) not terminated' % offset)
|
| 65 |
+
self.__code = compile('\n'.join(tokens), '<templite %r>' % template[:20], 'exec')
|
| 66 |
+
|
| 67 |
+
def render(self, __namespace=None, **kw):
|
| 68 |
+
"""
|
| 69 |
+
renders the template according to the given namespace.
|
| 70 |
+
__namespace - a dictionary serving as a namespace for evaluation
|
| 71 |
+
**kw - keyword arguments which are added to the namespace
|
| 72 |
+
"""
|
| 73 |
+
namespace = {}
|
| 74 |
+
if __namespace: namespace.update(__namespace)
|
| 75 |
+
if kw: namespace.update(kw)
|
| 76 |
+
namespace['emit'] = self.write
|
| 77 |
+
|
| 78 |
+
__stdout = sys.stdout
|
| 79 |
+
sys.stdout = self
|
| 80 |
+
self.__output = []
|
| 81 |
+
eval(self.__code, namespace)
|
| 82 |
+
sys.stdout = __stdout
|
| 83 |
+
return ''.join(self.__output)
|
| 84 |
+
|
| 85 |
+
def write(self, *args):
|
| 86 |
+
for a in args:
|
| 87 |
+
self.__output.append(str(a))
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
if __name__ == '__main__':
|
| 91 |
+
|
| 92 |
+
template = r"""
|
| 93 |
+
This we already know:
|
| 94 |
+
<html>
|
| 95 |
+
<body>
|
| 96 |
+
${
|
| 97 |
+
def say_hello(arg):
|
| 98 |
+
emit("hello ", arg, "<br>")
|
| 99 |
+
}$
|
| 100 |
+
|
| 101 |
+
<table>
|
| 102 |
+
${
|
| 103 |
+
for i in range(10):
|
| 104 |
+
emit("<tr><td> ")
|
| 105 |
+
say_hello(i)
|
| 106 |
+
emit(" </tr></td>\n")
|
| 107 |
+
}$
|
| 108 |
+
</table>
|
| 109 |
+
|
| 110 |
+
${emit("hi")}$
|
| 111 |
+
|
| 112 |
+
tralala ${if x > 7:
|
| 113 |
+
say_hello("big x")}$ lala
|
| 114 |
+
|
| 115 |
+
$\{this is escaped starting delimiter
|
| 116 |
+
|
| 117 |
+
${emit("this }\$ is an escaped ending delimiter")}$
|
| 118 |
+
|
| 119 |
+
${# this is a python comment }$
|
| 120 |
+
|
| 121 |
+
</body>
|
| 122 |
+
</html>
|
| 123 |
+
|
| 124 |
+
But this is completely new:
|
| 125 |
+
${if x > 7:}$
|
| 126 |
+
x is ${emit('greater')}$ than ${print x-1}$ Well, the print statement produces a newline.
|
| 127 |
+
${:else:}$
|
| 128 |
+
This terminates the previous code block and starts an else code block
|
| 129 |
+
Also this would work: $\{:end}\$$\{else:}\$, but not this: $\{:end}\$ $\{else:}\$
|
| 130 |
+
${:this terminates the else-block
|
| 131 |
+
only the starting colon is essential}$
|
| 132 |
+
|
| 133 |
+
So far you had to write:
|
| 134 |
+
${
|
| 135 |
+
if x > 3:
|
| 136 |
+
emit('''
|
| 137 |
+
After a condition you could not continue your template.
|
| 138 |
+
You had to write pure python code.
|
| 139 |
+
The only way was to use %%-based substitutions %s
|
| 140 |
+
''' % x)
|
| 141 |
+
}$
|
| 142 |
+
|
| 143 |
+
${if x > 6:}$
|
| 144 |
+
Now you do not need to break your template ${print x}$
|
| 145 |
+
${:elif x > 3:}$
|
| 146 |
+
This is great
|
| 147 |
+
${:endif}$
|
| 148 |
+
|
| 149 |
+
${for i in range(x-1):}$ Of course you can use any type of block statement ${i}$ ${"fmt: %s" % (i*2)}$
|
| 150 |
+
${:else:}$
|
| 151 |
+
Single variables and expressions starting with quotes are substituted automatically.
|
| 152 |
+
Instead $\{emit(x)}\$ you can write $\{x}\$ or $\{'%s' % x}\$ or $\{"", x}\$
|
| 153 |
+
Therefore standalone statements like break, continue or pass
|
| 154 |
+
must be enlosed by a semicolon: $\{continue;}\$
|
| 155 |
+
The end
|
| 156 |
+
${:end-for}$
|
| 157 |
+
"""
|
| 158 |
+
|
| 159 |
+
t = Templite(template)
|
| 160 |
+
print((t.render(x=8)))
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
# Output is:
|
| 164 |
+
"""
|
| 165 |
+
This we already know:
|
| 166 |
+
<html>
|
| 167 |
+
<body>
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
<table>
|
| 171 |
+
<tr><td> hello 0<br> </tr></td>
|
| 172 |
+
<tr><td> hello 1<br> </tr></td>
|
| 173 |
+
<tr><td> hello 2<br> </tr></td>
|
| 174 |
+
<tr><td> hello 3<br> </tr></td>
|
| 175 |
+
<tr><td> hello 4<br> </tr></td>
|
| 176 |
+
<tr><td> hello 5<br> </tr></td>
|
| 177 |
+
<tr><td> hello 6<br> </tr></td>
|
| 178 |
+
<tr><td> hello 7<br> </tr></td>
|
| 179 |
+
<tr><td> hello 8<br> </tr></td>
|
| 180 |
+
<tr><td> hello 9<br> </tr></td>
|
| 181 |
+
|
| 182 |
+
</table>
|
| 183 |
+
|
| 184 |
+
hi
|
| 185 |
+
|
| 186 |
+
tralala hello big x<br> lala
|
| 187 |
+
|
| 188 |
+
${this is escaped starting delimiter
|
| 189 |
+
|
| 190 |
+
this }$ is an escaped ending delimiter
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
</body>
|
| 195 |
+
</html>
|
| 196 |
+
|
| 197 |
+
But this is completely new:
|
| 198 |
+
|
| 199 |
+
x is greater than 7
|
| 200 |
+
Well, the print statement produces a newline.
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
So far you had to write:
|
| 204 |
+
|
| 205 |
+
After a condition you could not continue your template.
|
| 206 |
+
You had to write pure python code.
|
| 207 |
+
The only way was to use %-based substitutions 8
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
Now you do not need to break your template 8
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
Of course you can use any type of block statement 0 fmt: 0
|
| 216 |
+
Of course you can use any type of block statement 1 fmt: 2
|
| 217 |
+
Of course you can use any type of block statement 2 fmt: 4
|
| 218 |
+
Of course you can use any type of block statement 3 fmt: 6
|
| 219 |
+
Of course you can use any type of block statement 4 fmt: 8
|
| 220 |
+
Of course you can use any type of block statement 5 fmt: 10
|
| 221 |
+
Of course you can use any type of block statement 6 fmt: 12
|
| 222 |
+
|
| 223 |
+
Single variables and expressions starting with quotes are substituted automatically.
|
| 224 |
+
Instead ${emit(x)}$ you can write ${x}$ or ${'%s' % x}$ or ${"", x}$
|
| 225 |
+
Therefore standalone statements like break, continue or pass
|
| 226 |
+
must be enlosed by a semicolon: ${continue;}$
|
| 227 |
+
The end
|
| 228 |
+
"""
|
pool/shard009/Python/0080626_instanceactions.py
ADDED
|
@@ -0,0 +1,264 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Prototype
|
| 3 |
+
---------
|
| 4 |
+
|
| 5 |
+
args
|
| 6 |
+
the raw list of arguments
|
| 7 |
+
traverser
|
| 8 |
+
the traverser
|
| 9 |
+
node
|
| 10 |
+
the current node being evaluated
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
import types
|
| 14 |
+
|
| 15 |
+
import actions
|
| 16 |
+
from validator.compat import FX10_DEFINITION, FX14_DEFINITION
|
| 17 |
+
from validator.constants import BUGZILLA_BUG
|
| 18 |
+
from jstypes import *
|
| 19 |
+
from instanceproperties import _set_HTML_property
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def addEventListener(args, traverser, node, wrapper):
|
| 23 |
+
"""
|
| 24 |
+
Handle calls to addEventListener and make sure that the fourth argument is
|
| 25 |
+
falsey.
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
if not args or len(args) < 4:
|
| 29 |
+
return
|
| 30 |
+
|
| 31 |
+
fourth_arg = traverser._traverse_node(args[3])
|
| 32 |
+
if fourth_arg.get_literal_value():
|
| 33 |
+
traverser.err.notice(
|
| 34 |
+
err_id=("js", "instanceactions", "addEventListener_fourth"),
|
| 35 |
+
notice="`addEventListener` called with truthy fourth argument.",
|
| 36 |
+
description="A falsey fourth argument indicates code that "
|
| 37 |
+
"accesses untrusted code. This code should be "
|
| 38 |
+
"further investigated.",
|
| 39 |
+
filename=traverser.filename,
|
| 40 |
+
line=traverser.line,
|
| 41 |
+
column=traverser.position,
|
| 42 |
+
context=traverser.context)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def createElement(args, traverser, node, wrapper):
|
| 46 |
+
"""Handles createElement calls"""
|
| 47 |
+
|
| 48 |
+
if not args:
|
| 49 |
+
return
|
| 50 |
+
|
| 51 |
+
simple_args = map(traverser._traverse_node, args)
|
| 52 |
+
|
| 53 |
+
first_as_str = actions._get_as_str(simple_args[0].get_literal_value())
|
| 54 |
+
if first_as_str.lower() == u"script":
|
| 55 |
+
_create_script_tag(traverser)
|
| 56 |
+
elif not simple_args[0].is_literal():
|
| 57 |
+
_create_variable_element(traverser)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def createElementNS(args, traverser, node, wrapper):
|
| 61 |
+
"""Handles createElementNS calls"""
|
| 62 |
+
|
| 63 |
+
if not args or len(args) < 2:
|
| 64 |
+
return
|
| 65 |
+
|
| 66 |
+
simple_args = map(traverser._traverse_node, args)
|
| 67 |
+
|
| 68 |
+
second_as_str = actions._get_as_str(simple_args[1].get_literal_value())
|
| 69 |
+
if "script" in second_as_str.lower():
|
| 70 |
+
_create_script_tag(traverser)
|
| 71 |
+
elif not simple_args[1].is_literal():
|
| 72 |
+
_create_variable_element(traverser)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def QueryInterface(args, traverser, node, wrapper):
|
| 76 |
+
"""Handles QueryInterface calls"""
|
| 77 |
+
|
| 78 |
+
if not args:
|
| 79 |
+
return
|
| 80 |
+
|
| 81 |
+
from call_definitions import xpcom_constructor
|
| 82 |
+
return xpcom_constructor("QueryInterface", True, True)(
|
| 83 |
+
wrapper=node,
|
| 84 |
+
arguments=args,
|
| 85 |
+
traverser=traverser)
|
| 86 |
+
|
| 87 |
+
def getInterface(args, traverser, node, wrapper):
|
| 88 |
+
"""Handles getInterface calls"""
|
| 89 |
+
|
| 90 |
+
# This really only needs to be handled for nsIInterfaceRequestor
|
| 91 |
+
# intarfaces, but as it's fair for code to assume that that
|
| 92 |
+
# interface has already been queried and methods with this name
|
| 93 |
+
# are unlikely to behave differently, we just process it for all
|
| 94 |
+
# objects.
|
| 95 |
+
|
| 96 |
+
if not args:
|
| 97 |
+
return
|
| 98 |
+
|
| 99 |
+
from call_definitions import xpcom_constructor
|
| 100 |
+
return xpcom_constructor("getInterface")(
|
| 101 |
+
wrapper=node,
|
| 102 |
+
arguments=args,
|
| 103 |
+
traverser=traverser)
|
| 104 |
+
|
| 105 |
+
def _create_script_tag(traverser):
|
| 106 |
+
"""Raises a warning that the dev is creating a script tag"""
|
| 107 |
+
traverser.err.warning(
|
| 108 |
+
err_id=("testcases_javascript_instanceactions", "_call_expression",
|
| 109 |
+
"called_createelement"),
|
| 110 |
+
warning="createElement() used to create script tag",
|
| 111 |
+
description="The createElement() function was used to create a script "
|
| 112 |
+
"tag in a JavaScript file. Add-ons are not allowed to "
|
| 113 |
+
"create script tags or load code dynamically from the "
|
| 114 |
+
"web.",
|
| 115 |
+
filename=traverser.filename,
|
| 116 |
+
line=traverser.line,
|
| 117 |
+
column=traverser.position,
|
| 118 |
+
context=traverser.context)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def _create_variable_element(traverser):
|
| 122 |
+
"""Raises a warning that the dev is creating an arbitrary element"""
|
| 123 |
+
traverser.err.warning(
|
| 124 |
+
err_id=("testcases_javascript_instanceactions", "_call_expression",
|
| 125 |
+
"createelement_variable"),
|
| 126 |
+
warning="Variable element type being created",
|
| 127 |
+
description=["createElement or createElementNS were used with a "
|
| 128 |
+
"variable rather than a raw string. Literal values should "
|
| 129 |
+
"be used when taking advantage of the element creation "
|
| 130 |
+
"functions.",
|
| 131 |
+
"E.g.: createElement('foo') rather than "
|
| 132 |
+
"createElement(el_type)"],
|
| 133 |
+
filename=traverser.filename,
|
| 134 |
+
line=traverser.line,
|
| 135 |
+
column=traverser.position,
|
| 136 |
+
context=traverser.context)
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def setAttribute(args, traverser, node, wrapper):
|
| 140 |
+
"""This ensures that setAttribute calls don't set on* attributes"""
|
| 141 |
+
|
| 142 |
+
if not args:
|
| 143 |
+
return
|
| 144 |
+
|
| 145 |
+
simple_args = [traverser._traverse_node(a) for a in args]
|
| 146 |
+
|
| 147 |
+
first_as_str = actions._get_as_str(simple_args[0].get_literal_value())
|
| 148 |
+
if first_as_str.lower().startswith("on"):
|
| 149 |
+
traverser.err.notice(
|
| 150 |
+
err_id=("testcases_javascript_instanceactions", "setAttribute",
|
| 151 |
+
"setting_on*"),
|
| 152 |
+
notice="on* attribute being set using setAttribute",
|
| 153 |
+
description="To prevent vulnerabilities, event handlers (like "
|
| 154 |
+
"'onclick' and 'onhover') should always be defined "
|
| 155 |
+
"using addEventListener.",
|
| 156 |
+
filename=traverser.filename,
|
| 157 |
+
line=traverser.line,
|
| 158 |
+
column=traverser.position,
|
| 159 |
+
context=traverser.context)
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def nsIDOMFile_deprec(args, traverser, node, wrapper):
|
| 163 |
+
"""A wrapper for call_definitions.nsIDOMFile_deprec."""
|
| 164 |
+
from call_definitions import nsIDOMFile_deprec as cd_nsIDOMFile_deprec
|
| 165 |
+
cd_nsIDOMFile_deprec(None, [], traverser)
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def insertAdjacentHTML(args, traverser, node, wrapper):
|
| 169 |
+
"""
|
| 170 |
+
Perfrom the same tests on content inserted into the DOM via
|
| 171 |
+
insertAdjacentHTML as we otherwise would for content inserted via the
|
| 172 |
+
various innerHTML/outerHTML properties.
|
| 173 |
+
"""
|
| 174 |
+
if not args or len(args) < 2:
|
| 175 |
+
return
|
| 176 |
+
|
| 177 |
+
content = traverser._traverse_node(args[1])
|
| 178 |
+
_set_HTML_property("insertAdjacentHTML", content, traverser)
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def isSameNode(args, traverser, node, wrapper):
|
| 182 |
+
"""Raise an error when an add-on uses node.isSameNode(foo)."""
|
| 183 |
+
traverser.err.error(
|
| 184 |
+
err_id=("testcases_javascript_instanceactions", "isSameNode"),
|
| 185 |
+
error="isSameNode function has been removed in Gecko 10.",
|
| 186 |
+
description='The "isSameNode" function has been removed. You can use '
|
| 187 |
+
'the === operator as an alternative. See %s for more '
|
| 188 |
+
'information.' % BUGZILLA_BUG % 687400,
|
| 189 |
+
filename=traverser.filename,
|
| 190 |
+
line=traverser.line,
|
| 191 |
+
column=traverser.position,
|
| 192 |
+
context=traverser.context,
|
| 193 |
+
for_appversions=FX10_DEFINITION,
|
| 194 |
+
compatibility_type="error",
|
| 195 |
+
tier=5)
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def openDialog(args, traverser, node, wrapper):
|
| 199 |
+
"""Raise an error if the first argument is a remote URL."""
|
| 200 |
+
if not args:
|
| 201 |
+
return
|
| 202 |
+
uri = traverser._traverse_node(args[0])
|
| 203 |
+
from call_definitions import open_in_chrome_context
|
| 204 |
+
open_in_chrome_context(uri, "openDialog", traverser)
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def replaceWholeText(args, traverser, node, wrapper):
|
| 208 |
+
"""Raise an error when an add-on uses node.replaceWholeText(foo)."""
|
| 209 |
+
traverser.err.error(
|
| 210 |
+
err_id=("testcases_javascript_instanceactions", "replaceWholeText"),
|
| 211 |
+
error="replaceWholeText function has been removed in Gecko 10.",
|
| 212 |
+
description='The "replaceWholeText" function has been removed. See '
|
| 213 |
+
'%s for more information.' % BUGZILLA_BUG % 683482,
|
| 214 |
+
filename=traverser.filename,
|
| 215 |
+
line=traverser.line,
|
| 216 |
+
column=traverser.position,
|
| 217 |
+
context=traverser.context,
|
| 218 |
+
for_appversions=FX10_DEFINITION,
|
| 219 |
+
compatibility_type="error",
|
| 220 |
+
tier=5)
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def PageMod(args, traverser, node, wrapper):
|
| 224 |
+
"""
|
| 225 |
+
This is the function that is called in Jetpack to modify the contents of a
|
| 226 |
+
page with a "content script". This function needs to analyze he first
|
| 227 |
+
parameter. If it is an object and if that object contains a "contentScript"
|
| 228 |
+
string, that string needs to be passed to the validator.testcases.scripting
|
| 229 |
+
library for testing as its own JS script file.
|
| 230 |
+
"""
|
| 231 |
+
|
| 232 |
+
if not args:
|
| 233 |
+
return
|
| 234 |
+
|
| 235 |
+
pm_properties = traverser._traverse_node(args[0])
|
| 236 |
+
if not pm_properties.has_property("contentScript"):
|
| 237 |
+
return
|
| 238 |
+
|
| 239 |
+
content_script = pm_properties.get(traverser, "contentScript")
|
| 240 |
+
if not content_script.is_literal():
|
| 241 |
+
return
|
| 242 |
+
content_script = actions._get_as_str(content_script.get_literal_value())
|
| 243 |
+
if not content_script.strip():
|
| 244 |
+
return
|
| 245 |
+
|
| 246 |
+
import validator.testcases.scripting as sub_scripting
|
| 247 |
+
sub_scripting.test_js_file(
|
| 248 |
+
traverser.err, traverser.filename, content_script,
|
| 249 |
+
line=traverser.line, context=traverser.context)
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
INSTANCE_DEFINITIONS = {"addEventListener": addEventListener,
|
| 253 |
+
"createElement": createElement,
|
| 254 |
+
"createElementNS": createElementNS,
|
| 255 |
+
"getAsBinary": nsIDOMFile_deprec,
|
| 256 |
+
"getAsDataURL": nsIDOMFile_deprec,
|
| 257 |
+
"getInterface": getInterface,
|
| 258 |
+
"insertAdjacentHTML": insertAdjacentHTML,
|
| 259 |
+
"isSameNode": isSameNode,
|
| 260 |
+
"openDialog": openDialog,
|
| 261 |
+
"PageMod": PageMod,
|
| 262 |
+
"QueryInterface": QueryInterface,
|
| 263 |
+
"replaceWholeText": replaceWholeText,
|
| 264 |
+
"setAttribute": setAttribute}
|
pool/shard009/Python/0080633_member_event.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
from five import grok
|
| 3 |
+
from zope import schema
|
| 4 |
+
from plone.directives import dexterity, form
|
| 5 |
+
from plone.dexterity.content import Container
|
| 6 |
+
|
| 7 |
+
from vfu.events import MessageFactory as _
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class IVFUMemberEvent(form.Schema):
|
| 11 |
+
"""
|
| 12 |
+
Event info
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
available = schema.Bool(title=_(u'Available'), required=False, default=True)
|
| 16 |
+
|
| 17 |
+
class VFUMemberEvent(Container):
|
| 18 |
+
grok.implements(IVFUMemberEvent)
|
| 19 |
+
|
pool/shard009/Python/0080644_file_loader.py
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
'''
|
| 3 |
+
Load resource records from a text file.
|
| 4 |
+
'''
|
| 5 |
+
|
| 6 |
+
import os
|
| 7 |
+
import sys
|
| 8 |
+
import ipaddress
|
| 9 |
+
|
| 10 |
+
import dnsmgr_util as util
|
| 11 |
+
|
| 12 |
+
allowed_chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-."
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class Loader:
|
| 16 |
+
"""
|
| 17 |
+
Load records from a file
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
def __init__(self):
|
| 21 |
+
self.reverse4 = True
|
| 22 |
+
self.reverse6 = True
|
| 23 |
+
|
| 24 |
+
def _get_boolean(self, value):
|
| 25 |
+
value = value.lower()
|
| 26 |
+
if value.lower() not in ['on', 'off', 'true', 'false', '1', '0', 't', 'f', 'yes', 'no']:
|
| 27 |
+
raise ValueError('Invalid value %s, should be ON or OFF' % tmp[1])
|
| 28 |
+
return value in ['on', 'true', '1', 't', 'yes']
|
| 29 |
+
|
| 30 |
+
def load(self, filename=None, records=None):
|
| 31 |
+
"""
|
| 32 |
+
Read all records from the records file
|
| 33 |
+
|
| 34 |
+
filename: file to read
|
| 35 |
+
records: where to store loaded records
|
| 36 |
+
|
| 37 |
+
Empty lines and comments starting with # or ; is ignored
|
| 38 |
+
|
| 39 |
+
recursive function, to handle $INCLUDE to other files
|
| 40 |
+
"""
|
| 41 |
+
self.domain = os.path.basename(filename)
|
| 42 |
+
for line in open(filename, "r"):
|
| 43 |
+
line = line.rstrip()
|
| 44 |
+
if line == "" or line[0] == "#" or line[0] == ";":
|
| 45 |
+
continue
|
| 46 |
+
if line[0] == "$":
|
| 47 |
+
tmp = line.split(None, 2)
|
| 48 |
+
if len(tmp) < 2:
|
| 49 |
+
raise ValueError("Invalid $ syntax: %s" % line)
|
| 50 |
+
|
| 51 |
+
elif tmp[0] == "$DOMAIN":
|
| 52 |
+
self.domain = tmp[1]
|
| 53 |
+
|
| 54 |
+
elif tmp[0] == "$INCLUDE":
|
| 55 |
+
self.load(filename=tmp[1])
|
| 56 |
+
|
| 57 |
+
elif tmp[0] == "$REVERSE":
|
| 58 |
+
self.reverse4 = self._get_boolean(tmp[1])
|
| 59 |
+
self.reverse6 = self.reverse4
|
| 60 |
+
|
| 61 |
+
elif tmp[0] == "$REVERSE4":
|
| 62 |
+
self.reverse4 = self._get_boolean(tmp[1])
|
| 63 |
+
|
| 64 |
+
elif tmp[0] == "$REVERSE6":
|
| 65 |
+
self.reverse6 = self._get_boolean(tmp[1])
|
| 66 |
+
|
| 67 |
+
else:
|
| 68 |
+
raise ValueError("Invalid command %s" % tmp[0])
|
| 69 |
+
continue
|
| 70 |
+
|
| 71 |
+
mac_address = None
|
| 72 |
+
reverse = None
|
| 73 |
+
|
| 74 |
+
# Try to find options, end of line, starting with a ;
|
| 75 |
+
p = line.rfind(';')
|
| 76 |
+
if p >= 0:
|
| 77 |
+
line, tmp, options = line.rpartition(';')
|
| 78 |
+
for opt in options.split(' '):
|
| 79 |
+
key,tmp,val=opt.partition("=")
|
| 80 |
+
if key == 'mac':
|
| 81 |
+
mac_address = val
|
| 82 |
+
elif key == 'reverse':
|
| 83 |
+
reverse = self._get_boolean(val)
|
| 84 |
+
|
| 85 |
+
tmp = line.split(None, 3)
|
| 86 |
+
if len(tmp) < 2:
|
| 87 |
+
raise ValueError("Invalid syntax: %s" % line)
|
| 88 |
+
|
| 89 |
+
name = tmp.pop(0)
|
| 90 |
+
if name != "@" and not util.verify_dnsname(name):
|
| 91 |
+
raise ValueError("Invalid name: %s in %s" % (name, line))
|
| 92 |
+
|
| 93 |
+
if tmp[0].isdigit():
|
| 94 |
+
ttl = tmp.pop(0)
|
| 95 |
+
else:
|
| 96 |
+
ttl = ""
|
| 97 |
+
typ = tmp.pop(0).upper()
|
| 98 |
+
value = tmp.pop(0)
|
| 99 |
+
if typ == "A":
|
| 100 |
+
value = ipaddress.IPv4Address(value)
|
| 101 |
+
elif typ == "AAAA":
|
| 102 |
+
value = ipaddress.IPv6Address(value)
|
| 103 |
+
elif typ not in ["CNAME", "MX", "NS", "PTR", "SRV", "SSHFP", "TLSA", "TSIG", "TXT"]:
|
| 104 |
+
raise ValueError("Invalid type: %s in %s" % (typ, line))
|
| 105 |
+
|
| 106 |
+
if reverse is None:
|
| 107 |
+
if typ == 'A':
|
| 108 |
+
reverse = self.reverse4
|
| 109 |
+
elif typ == 'AAAA':
|
| 110 |
+
reverse = self.reverse6
|
| 111 |
+
|
| 112 |
+
record = util.Record(domain=self.domain,
|
| 113 |
+
ttl=ttl,
|
| 114 |
+
name=name,
|
| 115 |
+
typ=typ,
|
| 116 |
+
value=value,
|
| 117 |
+
mac_address=mac_address,
|
| 118 |
+
reverse=reverse,
|
| 119 |
+
)
|
| 120 |
+
records.add(record)
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def main():
|
| 124 |
+
"""
|
| 125 |
+
Function test
|
| 126 |
+
"""
|
| 127 |
+
import argparse
|
| 128 |
+
|
| 129 |
+
parser = argparse.ArgumentParser()
|
| 130 |
+
parser.add_argument('--file',
|
| 131 |
+
default='/etc/dnsmgr/records',
|
| 132 |
+
)
|
| 133 |
+
args = parser.parse_args()
|
| 134 |
+
|
| 135 |
+
if not os.path.isfile(args.file):
|
| 136 |
+
util.die("Cannot find file %s" % args.file)
|
| 137 |
+
|
| 138 |
+
loader = Loader()
|
| 139 |
+
records = util.Records()
|
| 140 |
+
loader.load(filename=args.file, records=records)
|
| 141 |
+
|
| 142 |
+
for record in records:
|
| 143 |
+
print(record)
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
if __name__ == "__main__":
|
| 147 |
+
main()
|
pool/shard009/Python/0080654_compareResult.py
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
accuracy = 1e-8
|
| 2 |
+
|
| 3 |
+
class Cell:
|
| 4 |
+
def __init__(self, vtkCell, bounds, q):
|
| 5 |
+
self.vtkCell = vtkCell
|
| 6 |
+
self.bounds = bounds
|
| 7 |
+
self.q = q
|
| 8 |
+
|
| 9 |
+
def __eq__(self, other):
|
| 10 |
+
global accuracy
|
| 11 |
+
if abs(self.q - other.q) > accuracy:
|
| 12 |
+
return false
|
| 13 |
+
|
| 14 |
+
if len(sel.bounds) != len(other.bounds):
|
| 15 |
+
return false
|
| 16 |
+
|
| 17 |
+
for i in xrange(len(self.bounds)):
|
| 18 |
+
if abs(self.bounds[i] - other.bounds[i]) > accuracy:
|
| 19 |
+
return false
|
| 20 |
+
|
| 21 |
+
return true
|
| 22 |
+
|
| 23 |
+
def __cmp__(self, other):
|
| 24 |
+
global accuracy
|
| 25 |
+
if self.q - other.q > accuracy:
|
| 26 |
+
return 1
|
| 27 |
+
elif other.q - self.q > accuracy:
|
| 28 |
+
return -1
|
| 29 |
+
|
| 30 |
+
if len(self.bounds) != len(other.bounds):
|
| 31 |
+
return false
|
| 32 |
+
|
| 33 |
+
for i in xrange(len(self.bounds)):
|
| 34 |
+
if self.bounds[i] - other.bounds[i] > accuracy:
|
| 35 |
+
return 1
|
| 36 |
+
elif other.bounds[i] - self.bounds[i] > accuracy:
|
| 37 |
+
return -1
|
| 38 |
+
|
| 39 |
+
return 0
|
| 40 |
+
|
| 41 |
+
def __str__(self):
|
| 42 |
+
return "q: " + str(self.q) + " bounds: " + str(self.bounds)
|
| 43 |
+
|
| 44 |
+
def parseRange(argument):
|
| 45 |
+
if ':' in argument:
|
| 46 |
+
return range(*map(int, argument.split(':')))
|
| 47 |
+
return range(int(argument), int(argument)+1)
|
| 48 |
+
|
| 49 |
+
def readCellsFromFile(cells, path, iteration, rank):
|
| 50 |
+
import vtk
|
| 51 |
+
import os.path
|
| 52 |
+
filename = path.replace('__ITERATION__', str(iteration)).replace('__RANK__', str(rank))
|
| 53 |
+
|
| 54 |
+
if os.path.exists(filename):
|
| 55 |
+
reader = vtk.vtkDataSetReader()
|
| 56 |
+
reader.SetFileName(filename)
|
| 57 |
+
reader.SetReadAllScalars(True)
|
| 58 |
+
reader.Update()
|
| 59 |
+
|
| 60 |
+
grid = reader.GetOutput()
|
| 61 |
+
|
| 62 |
+
numberOfCells = grid.GetNumberOfCells()
|
| 63 |
+
cellData = grid.GetCellData()
|
| 64 |
+
qs = cellData.GetScalars("q0")
|
| 65 |
+
|
| 66 |
+
for cellId in xrange(numberOfCells):
|
| 67 |
+
vtkCell = grid.GetCell(cellId)
|
| 68 |
+
|
| 69 |
+
q = qs.GetTuple(cellId)[0]
|
| 70 |
+
cells.append(Cell(vtkCell, vtkCell.GetBounds()[:], q))
|
| 71 |
+
|
| 72 |
+
return numberOfCells
|
| 73 |
+
else:
|
| 74 |
+
return 0
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def findClosestMatch(cell, cells):
|
| 78 |
+
bestIndex = -1
|
| 79 |
+
minDistance = 1000000
|
| 80 |
+
import math
|
| 81 |
+
for index in xrange(len(cells)):
|
| 82 |
+
c = cells[index]
|
| 83 |
+
distance = 0
|
| 84 |
+
for i in xrange(len(cell.bounds)):
|
| 85 |
+
distance += (cell.bounds[i] - c.bounds[i])**2
|
| 86 |
+
distance = math.sqrt((c.q - cell.q)**2 * 10 + distance)
|
| 87 |
+
|
| 88 |
+
if distance < minDistance:
|
| 89 |
+
minDistance = distance
|
| 90 |
+
bestIndex = index
|
| 91 |
+
return bestIndex
|
| 92 |
+
|
| 93 |
+
def findCellInList(cell, cells):
|
| 94 |
+
lower = 0
|
| 95 |
+
upper = len(cells)
|
| 96 |
+
|
| 97 |
+
while(upper > lower):
|
| 98 |
+
middle = (upper + lower) / 2
|
| 99 |
+
middleCell = cells[middle]
|
| 100 |
+
if middleCell < cell:
|
| 101 |
+
lower = middle + 1
|
| 102 |
+
elif middleCell > cell:
|
| 103 |
+
upper = middle
|
| 104 |
+
else:
|
| 105 |
+
return middle
|
| 106 |
+
|
| 107 |
+
return -1
|
| 108 |
+
|
| 109 |
+
def main():
|
| 110 |
+
from argparse import ArgumentParser
|
| 111 |
+
parser = ArgumentParser(description='Tool for comparing vtk output of parallel runs.')
|
| 112 |
+
parser.add_argument('path1', help='The path to the first set of vtk files. Use __ITERATION__ for iteration number and __RANK__ for rank number.')
|
| 113 |
+
parser.add_argument('path2', help='The path to the second set of vtk files. Use __ITERATION__ for iteration number and __RANK__ for rank number.')
|
| 114 |
+
parser.add_argument('iteration1', type=int, help='The iteration number of the first set of vtk files.')
|
| 115 |
+
parser.add_argument('ranks1', help='The range of ranks for the first set of vtk files. Define single number or min:max.')
|
| 116 |
+
parser.add_argument('iteration2', type=int, help='The iteration number of the second set of vtk files.')
|
| 117 |
+
parser.add_argument('ranks2', help='The range of ranks for the second set of vtk files. Define single number or min:max.')
|
| 118 |
+
parser.add_argument('accuracy', help='The accuracy for numerical equality.', type=float, nargs='?', const='1e-5')
|
| 119 |
+
arguments = parser.parse_args()
|
| 120 |
+
|
| 121 |
+
global accuracy
|
| 122 |
+
accuracy = arguments.accuracy
|
| 123 |
+
if arguments.path2 == 'SameAsPath1':
|
| 124 |
+
path2 = arguments.path1
|
| 125 |
+
else:
|
| 126 |
+
path2 = arguments.path2
|
| 127 |
+
|
| 128 |
+
#Loop through ranks1
|
| 129 |
+
cells1 = [] #set()
|
| 130 |
+
ranks1 = parseRange(arguments.ranks1)
|
| 131 |
+
for rank in ranks1:
|
| 132 |
+
print "1: Parsing rank...", rank
|
| 133 |
+
numberOfCells = readCellsFromFile(cells1, arguments.path1, arguments.iteration1, rank)
|
| 134 |
+
print "Read", numberOfCells, "cells."
|
| 135 |
+
print "1: Total number of cells:", len(cells1)
|
| 136 |
+
|
| 137 |
+
#Loop through ranks2
|
| 138 |
+
cells2 = [] #set()
|
| 139 |
+
ranks2 = parseRange(arguments.ranks2)
|
| 140 |
+
|
| 141 |
+
print ranks2
|
| 142 |
+
|
| 143 |
+
for rank in ranks2:
|
| 144 |
+
print "2: Parsing rank", rank
|
| 145 |
+
numberOfCells = readCellsFromFile(cells2, path2, arguments.iteration2, rank)
|
| 146 |
+
print "Read", numberOfCells, "cells."
|
| 147 |
+
print "2: Total number of cells:", len(cells2)
|
| 148 |
+
|
| 149 |
+
#Compare lists
|
| 150 |
+
if len(cells1) != len(cells2):
|
| 151 |
+
raise Exception("Number of cells do not match!")
|
| 152 |
+
|
| 153 |
+
cells1.sort()
|
| 154 |
+
cells2.sort()
|
| 155 |
+
|
| 156 |
+
for cell in cells1:
|
| 157 |
+
index = findCellInList(cell, cells2)
|
| 158 |
+
|
| 159 |
+
if index == -1:
|
| 160 |
+
bestMatch = findClosestMatch(cell, cells2)
|
| 161 |
+
if bestMatch == -1:
|
| 162 |
+
bestMatchString = ""
|
| 163 |
+
else:
|
| 164 |
+
bestMatchString = "Best match is " + str(cells2[bestMatch])
|
| 165 |
+
raise Exception("No matching cell for " + str(cell) + ". " + bestMatchString)
|
| 166 |
+
else:
|
| 167 |
+
del cells2[index]
|
| 168 |
+
|
| 169 |
+
print "All cells match"
|
| 170 |
+
|
| 171 |
+
if __name__=="__main__":
|
| 172 |
+
main()
|
pool/shard009/Python/0080657_ovirt_users.py
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/python
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
#
|
| 4 |
+
# Copyright (c) 2016 Red Hat, Inc.
|
| 5 |
+
#
|
| 6 |
+
# This file is part of Ansible
|
| 7 |
+
#
|
| 8 |
+
# Ansible is free software: you can redistribute it and/or modify
|
| 9 |
+
# it under the terms of the GNU General Public License as published by
|
| 10 |
+
# the Free Software Foundation, either version 3 of the License, or
|
| 11 |
+
# (at your option) any later version.
|
| 12 |
+
#
|
| 13 |
+
# Ansible is distributed in the hope that it will be useful,
|
| 14 |
+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
| 15 |
+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
| 16 |
+
# GNU General Public License for more details.
|
| 17 |
+
#
|
| 18 |
+
# You should have received a copy of the GNU General Public License
|
| 19 |
+
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
|
| 20 |
+
#
|
| 21 |
+
|
| 22 |
+
ANSIBLE_METADATA = {'status': ['preview'],
|
| 23 |
+
'supported_by': 'community',
|
| 24 |
+
'version': '1.0'}
|
| 25 |
+
|
| 26 |
+
DOCUMENTATION = '''
|
| 27 |
+
---
|
| 28 |
+
module: ovirt_users
|
| 29 |
+
short_description: Module to manage users in oVirt
|
| 30 |
+
version_added: "2.3"
|
| 31 |
+
author: "Ondra Machacek (@machacekondra)"
|
| 32 |
+
description:
|
| 33 |
+
- "Module to manage users in oVirt."
|
| 34 |
+
options:
|
| 35 |
+
name:
|
| 36 |
+
description:
|
| 37 |
+
- "Name of the the user to manage. In most LDAPs it's I(uid) of the user, but in Active Directory you must specify I(UPN) of the user."
|
| 38 |
+
required: true
|
| 39 |
+
state:
|
| 40 |
+
description:
|
| 41 |
+
- "Should the user be present/absent."
|
| 42 |
+
choices: ['present', 'absent']
|
| 43 |
+
default: present
|
| 44 |
+
authz_name:
|
| 45 |
+
description:
|
| 46 |
+
- "Authorization provider of the user. In previous versions of oVirt known as domain."
|
| 47 |
+
required: true
|
| 48 |
+
aliases: ['domain']
|
| 49 |
+
extends_documentation_fragment: ovirt
|
| 50 |
+
'''
|
| 51 |
+
|
| 52 |
+
EXAMPLES = '''
|
| 53 |
+
# Examples don't contain auth parameter for simplicity,
|
| 54 |
+
# look at ovirt_auth module to see how to reuse authentication:
|
| 55 |
+
|
| 56 |
+
# Add user user1 from authorization provider example.com-authz
|
| 57 |
+
ovirt_users:
|
| 58 |
+
name: user1
|
| 59 |
+
domain: example.com-authz
|
| 60 |
+
|
| 61 |
+
# Add user user1 from authorization provider example.com-authz
|
| 62 |
+
# In case of Active Directory specify UPN:
|
| 63 |
+
ovirt_users:
|
| 64 |
+
name: user1@ad2.example.com
|
| 65 |
+
domain: example.com-authz
|
| 66 |
+
|
| 67 |
+
# Remove user user1 with authorization provider example.com-authz
|
| 68 |
+
ovirt_users:
|
| 69 |
+
state: absent
|
| 70 |
+
name: user1
|
| 71 |
+
authz_name: example.com-authz
|
| 72 |
+
'''
|
| 73 |
+
|
| 74 |
+
RETURN = '''
|
| 75 |
+
id:
|
| 76 |
+
description: ID of the user which is managed
|
| 77 |
+
returned: On success if user is found.
|
| 78 |
+
type: str
|
| 79 |
+
sample: 7de90f31-222c-436c-a1ca-7e655bd5b60c
|
| 80 |
+
user:
|
| 81 |
+
description: "Dictionary of all the user attributes. User attributes can be found on your oVirt instance
|
| 82 |
+
at following url: https://ovirt.example.com/ovirt-engine/api/model#types/user."
|
| 83 |
+
returned: On success if user is found.
|
| 84 |
+
'''
|
| 85 |
+
|
| 86 |
+
import traceback
|
| 87 |
+
|
| 88 |
+
try:
|
| 89 |
+
import ovirtsdk4.types as otypes
|
| 90 |
+
except ImportError:
|
| 91 |
+
pass
|
| 92 |
+
|
| 93 |
+
from ansible.module_utils.basic import AnsibleModule
|
| 94 |
+
from ansible.module_utils.ovirt import (
|
| 95 |
+
BaseModule,
|
| 96 |
+
check_sdk,
|
| 97 |
+
check_params,
|
| 98 |
+
create_connection,
|
| 99 |
+
ovirt_full_argument_spec,
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def username(module):
|
| 104 |
+
return '{}@{}'.format(module.params['name'], module.params['authz_name'])
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
class UsersModule(BaseModule):
|
| 108 |
+
|
| 109 |
+
def build_entity(self):
|
| 110 |
+
return otypes.User(
|
| 111 |
+
domain=otypes.Domain(
|
| 112 |
+
name=self._module.params['authz_name']
|
| 113 |
+
),
|
| 114 |
+
user_name=username(self._module),
|
| 115 |
+
principal=self._module.params['name'],
|
| 116 |
+
namespace=self._module.params['namespace'],
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def main():
|
| 121 |
+
argument_spec = ovirt_full_argument_spec(
|
| 122 |
+
state=dict(
|
| 123 |
+
choices=['present', 'absent'],
|
| 124 |
+
default='present',
|
| 125 |
+
),
|
| 126 |
+
name=dict(required=True),
|
| 127 |
+
authz_name=dict(required=True, aliases=['domain']),
|
| 128 |
+
namespace=dict(default=None),
|
| 129 |
+
)
|
| 130 |
+
module = AnsibleModule(
|
| 131 |
+
argument_spec=argument_spec,
|
| 132 |
+
supports_check_mode=True,
|
| 133 |
+
)
|
| 134 |
+
check_sdk(module)
|
| 135 |
+
check_params(module)
|
| 136 |
+
|
| 137 |
+
try:
|
| 138 |
+
auth = module.params.pop('auth')
|
| 139 |
+
connection = create_connection(auth)
|
| 140 |
+
users_service = connection.system_service().users_service()
|
| 141 |
+
users_module = UsersModule(
|
| 142 |
+
connection=connection,
|
| 143 |
+
module=module,
|
| 144 |
+
service=users_service,
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
state = module.params['state']
|
| 148 |
+
if state == 'present':
|
| 149 |
+
ret = users_module.create(
|
| 150 |
+
search_params={
|
| 151 |
+
'usrname': username(module),
|
| 152 |
+
}
|
| 153 |
+
)
|
| 154 |
+
elif state == 'absent':
|
| 155 |
+
ret = users_module.remove(
|
| 156 |
+
search_params={
|
| 157 |
+
'usrname': username(module),
|
| 158 |
+
}
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
module.exit_json(**ret)
|
| 162 |
+
except Exception as e:
|
| 163 |
+
module.fail_json(msg=str(e), exception=traceback.format_exc())
|
| 164 |
+
finally:
|
| 165 |
+
connection.close(logout=auth.get('token') is None)
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
if __name__ == "__main__":
|
| 169 |
+
main()
|
pool/shard009/Python/0080661_efficientnet_variants.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The Robustness Metrics Authors.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
# Lint as: python3
|
| 17 |
+
"""EfficientNet models pre-trained with different training protocols.
|
| 18 |
+
|
| 19 |
+
EfficientNet: https://arxiv.org/abs/1905.11946
|
| 20 |
+
AutoAugment: https://arxiv.org/abs/1805.09501
|
| 21 |
+
Adv-Prop: https://arxiv.org/abs/1911.09665
|
| 22 |
+
Noisy Student: https://arxiv.org/abs/1911.04252
|
| 23 |
+
|
| 24 |
+
This code uses TF-Hub modules derived from the checkpoints at
|
| 25 |
+
|
| 26 |
+
https://github.com/tensorflow/tpu/tree/4572efe4a9f709d01dbee85f948218af8b05a36c/models/official/efficientnet
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
from robustness_metrics.common import pipeline_builder
|
| 30 |
+
import tensorflow as tf
|
| 31 |
+
import tensorflow.compat.v1 as tf1
|
| 32 |
+
import tensorflow_hub as hub
|
| 33 |
+
|
| 34 |
+
CROP_PADDING = 32
|
| 35 |
+
EFFICIENTNET_RESOLUTIONS = {
|
| 36 |
+
"b0": 224,
|
| 37 |
+
"b1": 240,
|
| 38 |
+
"b2": 260,
|
| 39 |
+
"b3": 300,
|
| 40 |
+
"b4": 380,
|
| 41 |
+
"b5": 456,
|
| 42 |
+
"b6": 528,
|
| 43 |
+
"b7": 600,
|
| 44 |
+
"l2": 800,
|
| 45 |
+
"l2_475": 475,
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
GS_ROOT = "gs://cloud-tpu-checkpoints/efficientnet/tfhub"
|
| 49 |
+
MODEL_PATHS = {
|
| 50 |
+
# EfficientNet trained on ImageNet.
|
| 51 |
+
"std": GS_ROOT + "/base/efficientnet-b{}",
|
| 52 |
+
# EfficientNet trained on ImageNet with AutoAugment.
|
| 53 |
+
"aa": GS_ROOT + "/aa/efficientnet-b{}",
|
| 54 |
+
# EfficientNet trained on ImageNet with Adv-Prop.
|
| 55 |
+
"adv-prop": GS_ROOT + "/adv/efficientnet-b{}",
|
| 56 |
+
# EfficientNet trained on ImageNet/JFT with the Noisy Student protocol.
|
| 57 |
+
"noisy-student": GS_ROOT + "/ns/efficientnet-b{}",
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def create(model_size="b0", variant="std", resolution=None):
|
| 63 |
+
"""Create EfficientNet models with corresponding preprocessing operations."""
|
| 64 |
+
|
| 65 |
+
if variant not in ("std", "aa", "adv-prop", "noisy-student"):
|
| 66 |
+
raise ValueError(f"EfficientNet variant not supported: {variant}")
|
| 67 |
+
|
| 68 |
+
# Note that for the standard EfficientNet variant only B0-B5 architectures are
|
| 69 |
+
# supported, B0-B7 for all other variants. Noisy-Student also supports L2
|
| 70 |
+
# and L2_475 (with a resolution of 475).
|
| 71 |
+
valid = (variant == "std" and model_size in {f"b{i}" for i in range(6)}) or \
|
| 72 |
+
(variant != "std" and model_size in {f"b{i}" for i in range(8)}) or \
|
| 73 |
+
(variant == "noisy-student" and model_size in ("l2", "l2_475"))
|
| 74 |
+
if not valid:
|
| 75 |
+
raise ValueError(
|
| 76 |
+
f"Invalid `model_size` {model_size!r} for EfficientNet `variant` "
|
| 77 |
+
f"{variant!r}!")
|
| 78 |
+
|
| 79 |
+
if model_size.startswith("l2"):
|
| 80 |
+
noisy_student = hub.KerasLayer(MODEL_PATHS[variant + "-l2"].format(
|
| 81 |
+
model_size))
|
| 82 |
+
else:
|
| 83 |
+
noisy_student = hub.KerasLayer(MODEL_PATHS[variant].format(model_size))
|
| 84 |
+
|
| 85 |
+
@tf.function
|
| 86 |
+
def model(features):
|
| 87 |
+
images = features["image"]
|
| 88 |
+
return tf.nn.softmax(noisy_student(images), axis=-1)
|
| 89 |
+
|
| 90 |
+
def preprocess_fn(features):
|
| 91 |
+
# EfficientNet preprocessing with model-dependent input resolution.
|
| 92 |
+
# Preprocessing mimicks that of the public EfficientNet code from
|
| 93 |
+
# https://github.com/tensorflow/tpu/blob/master/models/official/efficientnet/preprocessing.py
|
| 94 |
+
# (both `_resize_image` and `_decode_and_center_crop` taken from that code)
|
| 95 |
+
|
| 96 |
+
def _resize_image(image, image_size, method=None):
|
| 97 |
+
if method is not None:
|
| 98 |
+
return tf1.image.resize([image], [image_size, image_size], method)[0]
|
| 99 |
+
return tf1.image.resize_bicubic([image], [image_size, image_size])[0]
|
| 100 |
+
|
| 101 |
+
def _decode_and_center_crop(image, image_size, resize_method=None):
|
| 102 |
+
"""Crops to center of image with padding then scales image_size."""
|
| 103 |
+
shape = tf1.shape(image)
|
| 104 |
+
image_height = shape[0]
|
| 105 |
+
image_width = shape[1]
|
| 106 |
+
|
| 107 |
+
padded_center_crop_size = tf1.cast(
|
| 108 |
+
((image_size / (image_size + CROP_PADDING)) *
|
| 109 |
+
tf.cast(tf.minimum(image_height, image_width), tf.float32)),
|
| 110 |
+
tf.int32)
|
| 111 |
+
|
| 112 |
+
offset_height = ((image_height - padded_center_crop_size) + 1) // 2
|
| 113 |
+
offset_width = ((image_width - padded_center_crop_size) + 1) // 2
|
| 114 |
+
image = tf1.image.crop_to_bounding_box(image, offset_height, offset_width,
|
| 115 |
+
padded_center_crop_size,
|
| 116 |
+
padded_center_crop_size)
|
| 117 |
+
image = _resize_image(image, image_size, resize_method)
|
| 118 |
+
return image
|
| 119 |
+
|
| 120 |
+
features["image"] = _decode_and_center_crop(
|
| 121 |
+
features["image"], EFFICIENTNET_RESOLUTIONS[model_size])
|
| 122 |
+
features["image"] = tf1.cast(features["image"], tf1.float32)
|
| 123 |
+
# We assume the modules expect pixels in [-1, 1].
|
| 124 |
+
features["image"] = features["image"] / 127.5 - 1.0
|
| 125 |
+
|
| 126 |
+
return features
|
| 127 |
+
|
| 128 |
+
if resolution is not None:
|
| 129 |
+
preprocess_config_fmt = "resize_small({})|central_crop({})|value_range(-1,1)"
|
| 130 |
+
preprocess_config = preprocess_config_fmt.format(
|
| 131 |
+
int(1.15 * resolution), resolution)
|
| 132 |
+
preprocess_fn = pipeline_builder.get_preprocess_fn(
|
| 133 |
+
preprocess_config, remove_tpu_dtypes=False)
|
| 134 |
+
|
| 135 |
+
return model, preprocess_fn
|
pool/shard009/Python/0080663_scriptdocumentation.py
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
#
|
| 3 |
+
# Picard, the next-generation MusicBrainz tagger
|
| 4 |
+
#
|
| 5 |
+
# Copyright (C) 2021 Bob Swift
|
| 6 |
+
#
|
| 7 |
+
# This program is free software; you can redistribute it and/or
|
| 8 |
+
# modify it under the terms of the GNU General Public License
|
| 9 |
+
# as published by the Free Software Foundation; either version 2
|
| 10 |
+
# of the License, or (at your option) any later version.
|
| 11 |
+
#
|
| 12 |
+
# This program is distributed in the hope that it will be useful,
|
| 13 |
+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
| 14 |
+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
| 15 |
+
# GNU General Public License for more details.
|
| 16 |
+
#
|
| 17 |
+
# You should have received a copy of the GNU General Public License
|
| 18 |
+
# along with this program; if not, write to the Free Software
|
| 19 |
+
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
from PyQt5 import (
|
| 23 |
+
QtCore,
|
| 24 |
+
QtWidgets,
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
from picard.const import PICARD_URLS
|
| 28 |
+
from picard.script import script_function_documentation_all
|
| 29 |
+
|
| 30 |
+
from picard.ui import FONT_FAMILY_MONOSPACE
|
| 31 |
+
from picard.ui.theme import theme
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
DOCUMENTATION_HTML_TEMPLATE = '''
|
| 35 |
+
<!DOCTYPE html>
|
| 36 |
+
<html>
|
| 37 |
+
<head>
|
| 38 |
+
<style>
|
| 39 |
+
dt {
|
| 40 |
+
color: %(script_function_fg)s
|
| 41 |
+
}
|
| 42 |
+
dd {
|
| 43 |
+
/* Qt does not support margin-inline-start, use margin-left/margin-right instead */
|
| 44 |
+
margin-%(inline_start)s: 50px;
|
| 45 |
+
margin-bottom: 50px;
|
| 46 |
+
}
|
| 47 |
+
code {
|
| 48 |
+
font-family: %(monospace_font)s;
|
| 49 |
+
}
|
| 50 |
+
</style>
|
| 51 |
+
</head>
|
| 52 |
+
<body dir="%(dir)s">
|
| 53 |
+
%(html)s
|
| 54 |
+
</body>
|
| 55 |
+
</html>
|
| 56 |
+
'''
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class ScriptingDocumentationWidget(QtWidgets.QWidget):
|
| 60 |
+
"""Custom widget to display the scripting documentation.
|
| 61 |
+
"""
|
| 62 |
+
def __init__(self, parent, include_link=True, *args, **kwargs):
|
| 63 |
+
"""Custom widget to display the scripting documentation.
|
| 64 |
+
|
| 65 |
+
Args:
|
| 66 |
+
parent (QWidget): Parent screen to check layoutDirection()
|
| 67 |
+
include_link (bool): Indicates whether the web link should be included
|
| 68 |
+
"""
|
| 69 |
+
super().__init__(*args, **kwargs)
|
| 70 |
+
|
| 71 |
+
def process_html(html, function):
|
| 72 |
+
if not html:
|
| 73 |
+
html = ''
|
| 74 |
+
template = '<dt>%s%s</dt><dd>%s</dd>'
|
| 75 |
+
if function.module is not None and function.module != 'picard.script.functions':
|
| 76 |
+
module = ' [' + function.module + ']'
|
| 77 |
+
else:
|
| 78 |
+
module = ''
|
| 79 |
+
try:
|
| 80 |
+
firstline, remaining = html.split("\n", 1)
|
| 81 |
+
return template % (firstline, module, remaining)
|
| 82 |
+
except ValueError:
|
| 83 |
+
return template % ("<code>$%s()</code>" % function.name, module, html)
|
| 84 |
+
|
| 85 |
+
funcdoc = script_function_documentation_all(
|
| 86 |
+
fmt='html',
|
| 87 |
+
postprocessor=process_html,
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
if parent.layoutDirection() == QtCore.Qt.RightToLeft:
|
| 91 |
+
text_direction = 'rtl'
|
| 92 |
+
else:
|
| 93 |
+
text_direction = 'ltr'
|
| 94 |
+
|
| 95 |
+
html = DOCUMENTATION_HTML_TEMPLATE % {
|
| 96 |
+
'html': "<dl>%s</dl>" % funcdoc,
|
| 97 |
+
'script_function_fg': theme.syntax_theme.func.name(),
|
| 98 |
+
'monospace_font': FONT_FAMILY_MONOSPACE,
|
| 99 |
+
'dir': text_direction,
|
| 100 |
+
'inline_start': 'right' if text_direction == 'rtl' else 'left'
|
| 101 |
+
}
|
| 102 |
+
# Scripting code is always left-to-right. Qt does not support the dir
|
| 103 |
+
# attribute on inline tags, insert explicit left-right-marks instead.
|
| 104 |
+
if text_direction == 'rtl':
|
| 105 |
+
html = html.replace('<code>', '<code>‎')
|
| 106 |
+
|
| 107 |
+
link = '<a href="' + PICARD_URLS['doc_scripting'] + '">' + _('Open Scripting Documentation in your browser') + '</a>'
|
| 108 |
+
|
| 109 |
+
self.verticalLayout = QtWidgets.QVBoxLayout(self)
|
| 110 |
+
self.verticalLayout.setContentsMargins(0, 0, 0, 0)
|
| 111 |
+
self.verticalLayout.setObjectName("docs_verticalLayout")
|
| 112 |
+
self.textBrowser = QtWidgets.QTextBrowser(self)
|
| 113 |
+
self.textBrowser.setEnabled(True)
|
| 114 |
+
self.textBrowser.setMinimumSize(QtCore.QSize(0, 0))
|
| 115 |
+
self.textBrowser.setObjectName("docs_textBrowser")
|
| 116 |
+
self.textBrowser.setHtml(html)
|
| 117 |
+
self.textBrowser.show()
|
| 118 |
+
self.verticalLayout.addWidget(self.textBrowser)
|
| 119 |
+
self.horizontalLayout = QtWidgets.QHBoxLayout()
|
| 120 |
+
self.horizontalLayout.setContentsMargins(-1, 0, -1, -1)
|
| 121 |
+
self.horizontalLayout.setObjectName("docs_horizontalLayout")
|
| 122 |
+
self.scripting_doc_link = QtWidgets.QLabel(self)
|
| 123 |
+
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Preferred)
|
| 124 |
+
sizePolicy.setHorizontalStretch(0)
|
| 125 |
+
sizePolicy.setVerticalStretch(0)
|
| 126 |
+
sizePolicy.setHeightForWidth(self.scripting_doc_link.sizePolicy().hasHeightForWidth())
|
| 127 |
+
if include_link:
|
| 128 |
+
self.scripting_doc_link.setSizePolicy(sizePolicy)
|
| 129 |
+
self.scripting_doc_link.setMinimumSize(QtCore.QSize(0, 20))
|
| 130 |
+
self.scripting_doc_link.setAlignment(QtCore.Qt.AlignCenter)
|
| 131 |
+
self.scripting_doc_link.setWordWrap(True)
|
| 132 |
+
self.scripting_doc_link.setOpenExternalLinks(True)
|
| 133 |
+
self.scripting_doc_link.setObjectName("docs_scripting_doc_link")
|
| 134 |
+
self.scripting_doc_link.setText(link)
|
| 135 |
+
self.scripting_doc_link.show()
|
| 136 |
+
self.horizontalLayout.addWidget(self.scripting_doc_link)
|
| 137 |
+
self.verticalLayout.addLayout(self.horizontalLayout)
|
pool/shard009/Python/0080666_views.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
|
| 3 |
+
from django.shortcuts import render_to_response
|
| 4 |
+
from django.http import HttpResponseRedirect
|
| 5 |
+
|
| 6 |
+
COOKIE_NAME = 'openid_wg_auth'
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def mainpage(request):
|
| 10 |
+
return render_to_response(
|
| 11 |
+
'main.html',
|
| 12 |
+
{'openid': request.COOKIES.get(COOKIE_NAME, None)}
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def logout(request):
|
| 17 |
+
response = HttpResponseRedirect('/')
|
| 18 |
+
response.delete_cookie(COOKIE_NAME)
|
| 19 |
+
return response
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def success_handler(request, response, openid_url):
|
| 23 |
+
# do not do it in a real application!!! it's just a simple example
|
| 24 |
+
response.set_cookie(COOKIE_NAME, openid_url)
|
| 25 |
+
logging.warning("success_handler openid_url: %s" % openid_url)
|
pool/shard009/Python/0080667_update.py
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Deployment for Mozillians in production.
|
| 3 |
+
|
| 4 |
+
Requires commander (https://github.com/oremj/commander) which is installed on
|
| 5 |
+
the systems that need it.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import os
|
| 9 |
+
import random
|
| 10 |
+
import re
|
| 11 |
+
import sys
|
| 12 |
+
import urllib
|
| 13 |
+
import urllib2
|
| 14 |
+
import commander_settings as settings
|
| 15 |
+
from commander.deploy import task, hostgroups
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
# Setup virtualenv path.
|
| 22 |
+
venv_bin_path = os.path.join(settings.SRC_DIR, '..', 'venv', 'bin')
|
| 23 |
+
os.environ['PATH'] = venv_bin_path + os.pathsep + os.environ['PATH']
|
| 24 |
+
|
| 25 |
+
NEW_RELIC_URL = 'https://rpm.newrelic.com/deployments.xml'
|
| 26 |
+
GITHUB_URL = 'https://github.com/mozilla/mozillians/compare/{oldrev}...{newrev}'
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@task
|
| 30 |
+
def update_code(ctx, tag):
|
| 31 |
+
with ctx.lcd(settings.SRC_DIR):
|
| 32 |
+
ctx.local("git fetch")
|
| 33 |
+
ctx.local("git checkout -f %s" % tag)
|
| 34 |
+
ctx.local("git submodule sync")
|
| 35 |
+
ctx.local("git submodule update --init --recursive")
|
| 36 |
+
ctx.local("find . -type f -name '.gitignore' -or -name '*.pyc' -delete")
|
| 37 |
+
ctx.local('git clean -xdff "vendor-local/"')
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
@task
|
| 41 |
+
def update_locales(ctx):
|
| 42 |
+
with ctx.lcd(os.path.join(settings.SRC_DIR, 'locale')):
|
| 43 |
+
ctx.local('find . -name "*.mo" -delete')
|
| 44 |
+
ctx.local("svn up")
|
| 45 |
+
ctx.local("./compile.sh .")
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
@task
|
| 49 |
+
def update_assets(ctx):
|
| 50 |
+
with ctx.lcd(settings.SRC_DIR):
|
| 51 |
+
ctx.local("LANG=en_US.UTF-8 python manage.py collectstatic --noinput --no-default-ignore -i .git")
|
| 52 |
+
ctx.local("LANG=en_US.UTF-8 python manage.py compress --engine jinja2")
|
| 53 |
+
ctx.local("LANG=en_US.UTF-8 python manage.py update_product_details")
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
@task
|
| 57 |
+
def database(ctx):
|
| 58 |
+
with ctx.lcd(settings.SRC_DIR):
|
| 59 |
+
ctx.local("python manage.py migrate --noinput")
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
@task
|
| 63 |
+
def update_revision_files(ctx):
|
| 64 |
+
with ctx.lcd(settings.SRC_DIR):
|
| 65 |
+
global OLDREV, NEWREV
|
| 66 |
+
NEWREV = ctx.local("git rev-parse HEAD").out.strip()
|
| 67 |
+
OLDREV = ctx.local("cat media/revision.txt").out.strip()
|
| 68 |
+
ctx.local("mv media/revision.txt media/prev-revision.txt")
|
| 69 |
+
ctx.local("echo '%s' > media/revision.txt" % NEWREV)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
@task
|
| 73 |
+
def ping_newrelic(ctx):
|
| 74 |
+
if settings.NEW_RELIC_API_KEY and settings.NEW_RELIC_APP_ID:
|
| 75 |
+
with ctx.lcd(settings.SRC_DIR):
|
| 76 |
+
log_cmd = 'git log --oneline {0}..{1}'.format(OLDREV, NEWREV)
|
| 77 |
+
changelog = ctx.local(log_cmd).out.strip()
|
| 78 |
+
|
| 79 |
+
print 'Post deployment to New Relic'
|
| 80 |
+
desc = generate_desc(OLDREV, NEWREV, changelog)
|
| 81 |
+
if changelog:
|
| 82 |
+
github_url = GITHUB_URL.format(oldrev=OLDREV, newrev=NEWREV)
|
| 83 |
+
changelog = '{0}\n\n{1}'.format(changelog, github_url)
|
| 84 |
+
data = urllib.urlencode({
|
| 85 |
+
'deployment[description]': desc,
|
| 86 |
+
'deployment[revision]': NEWREV,
|
| 87 |
+
'deployment[app_id]': settings.NEW_RELIC_APP_ID,
|
| 88 |
+
'deployment[changelog]': changelog,
|
| 89 |
+
})
|
| 90 |
+
headers = {'x-api-key': settings.NEW_RELIC_API_KEY}
|
| 91 |
+
try:
|
| 92 |
+
request = urllib2.Request(NEW_RELIC_URL, data, headers)
|
| 93 |
+
urllib2.urlopen(request)
|
| 94 |
+
except urllib.URLError as exp:
|
| 95 |
+
print 'Error notifying New Relic: {0}'.format(exp)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
@task
|
| 99 |
+
def update_es_indexes(ctx):
|
| 100 |
+
with ctx.lcd(settings.SRC_DIR):
|
| 101 |
+
ctx.local("python manage.py cron index_all_profiles &")
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
@task
|
| 105 |
+
def validate_fun_facts(ctx):
|
| 106 |
+
with ctx.lcd(settings.SRC_DIR):
|
| 107 |
+
ctx.local("python manage.py cron validate_fun_facts")
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
@task
|
| 111 |
+
def generate_humanstxt(ctx):
|
| 112 |
+
with ctx.lcd(settings.SRC_DIR):
|
| 113 |
+
ctx.local("python manage.py cron generate_humanstxt &")
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
# @task
|
| 117 |
+
# def install_cron(ctx):
|
| 118 |
+
# with ctx.lcd(settings.SRC_DIR):
|
| 119 |
+
# ctx.local("python ./scripts/crontab/gen-crons.py -k %s -u apache > /etc/cron.d/.%s" %
|
| 120 |
+
# (settings.WWW_DIR, settings.CRON_NAME))
|
| 121 |
+
# ctx.local("mv /etc/cron.d/.%s /etc/cron.d/%s" % (settings.CRON_NAME, settings.CRON_NAME))
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
@task
|
| 125 |
+
def checkin_changes(ctx):
|
| 126 |
+
ctx.local(settings.DEPLOY_SCRIPT)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
@hostgroups(settings.WEB_HOSTGROUP, remote_kwargs={'ssh_key': settings.SSH_KEY})
|
| 130 |
+
def deploy_app(ctx):
|
| 131 |
+
ctx.remote(settings.REMOTE_UPDATE_SCRIPT)
|
| 132 |
+
ctx.remote("/bin/touch %s" % settings.REMOTE_WSGI)
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
@hostgroups(settings.WEB_HOSTGROUP, remote_kwargs={'ssh_key': settings.SSH_KEY})
|
| 136 |
+
def prime_app(ctx):
|
| 137 |
+
for http_port in range(80, 82):
|
| 138 |
+
ctx.remote("for i in {1..10}; do curl -so /dev/null -H 'Host: %s' -I http://localhost:%s/ & sleep 1; done" % (settings.REMOTE_HOSTNAME, http_port))
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
@hostgroups(settings.CELERY_HOSTGROUP, remote_kwargs={'ssh_key': settings.SSH_KEY})
|
| 142 |
+
def update_celery(ctx):
|
| 143 |
+
ctx.remote(settings.REMOTE_UPDATE_SCRIPT)
|
| 144 |
+
ctx.remote('/sbin/service %s restart' % settings.CELERY_SERVICE)
|
| 145 |
+
ctx.remote('/sbin/service %s restart' % settings.CELERYBEAT_SERVICE)
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
@task
|
| 149 |
+
def update_info(ctx, tag):
|
| 150 |
+
with ctx.lcd(settings.SRC_DIR):
|
| 151 |
+
ctx.local("date")
|
| 152 |
+
ctx.local("git branch")
|
| 153 |
+
ctx.local("git log -3")
|
| 154 |
+
ctx.local("git status")
|
| 155 |
+
ctx.local("git submodule status")
|
| 156 |
+
ctx.local("python ./manage.py migrate --list")
|
| 157 |
+
with ctx.lcd("locale"):
|
| 158 |
+
ctx.local("svn info")
|
| 159 |
+
ctx.local("svn status")
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
@task
|
| 163 |
+
def pre_update(ctx, ref=settings.UPDATE_REF):
|
| 164 |
+
update_code(ref)
|
| 165 |
+
update_info(ref)
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
@task
|
| 169 |
+
def update(ctx):
|
| 170 |
+
update_assets()
|
| 171 |
+
update_locales()
|
| 172 |
+
database()
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
@task
|
| 176 |
+
def deploy(ctx):
|
| 177 |
+
# install_cron()
|
| 178 |
+
update_revision_files()
|
| 179 |
+
checkin_changes()
|
| 180 |
+
deploy_app()
|
| 181 |
+
prime_app()
|
| 182 |
+
update_celery()
|
| 183 |
+
# Things run below here should not break the deployment if they fail.
|
| 184 |
+
if OLDREV != NEWREV:
|
| 185 |
+
# On dev, this script runs every 15 minutes. If we're pushing the same
|
| 186 |
+
# revision we don't need to churn the index, ping new relic, or any of this.
|
| 187 |
+
ping_newrelic()
|
| 188 |
+
update_es_indexes()
|
| 189 |
+
validate_fun_facts()
|
| 190 |
+
generate_humanstxt()
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
@task
|
| 194 |
+
def update_mozillians(ctx, tag):
|
| 195 |
+
"""Do typical mozillians update"""
|
| 196 |
+
pre_update(tag)
|
| 197 |
+
update()
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
## utility functions ##
|
| 201 |
+
# shamelessly stolen from https://github.com/mythmon/chief-james/
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def get_random_desc():
|
| 205 |
+
return random.choice([
|
| 206 |
+
'No bugfixes--must be adding infinite loops.',
|
| 207 |
+
'No bugfixes--must be rot13ing function names for code security.',
|
| 208 |
+
'No bugfixes--must be demonstrating our elite push technology.',
|
| 209 |
+
'No bugfixes--must be testing james.',
|
| 210 |
+
])
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def extract_bugs(changelog):
|
| 214 |
+
"""Takes output from git log --oneline and extracts bug numbers."""
|
| 215 |
+
bug_regexp = re.compile(r'\bbug (\d+)\b', re.I)
|
| 216 |
+
bugs = set()
|
| 217 |
+
for line in changelog:
|
| 218 |
+
for bug in bug_regexp.findall(line):
|
| 219 |
+
bugs.add(bug)
|
| 220 |
+
|
| 221 |
+
return sorted(list(bugs))
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def generate_desc(from_commit, to_commit, changelog):
|
| 225 |
+
"""Figures out a good description based on what we're pushing out."""
|
| 226 |
+
if from_commit.startswith(to_commit):
|
| 227 |
+
desc = 'Pushing {0} again'.format(to_commit)
|
| 228 |
+
else:
|
| 229 |
+
bugs = extract_bugs(changelog.split('\n'))
|
| 230 |
+
if bugs:
|
| 231 |
+
bugs = ['bug #{0}'.format(bug) for bug in bugs]
|
| 232 |
+
desc = 'Fixing: {0}'.format(', '.join(bugs))
|
| 233 |
+
else:
|
| 234 |
+
desc = get_random_desc()
|
| 235 |
+
return desc
|
pool/shard009/Python/0080669_test_Server.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
import Server
|
| 3 |
+
import Pyro4.naming
|
| 4 |
+
import Pyro4
|
| 5 |
+
import threading
|
| 6 |
+
import Client
|
| 7 |
+
import logging
|
| 8 |
+
import Constants
|
| 9 |
+
|
| 10 |
+
logging.basicConfig(level=logging.INFO)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class TestServer(unittest.TestCase):
|
| 14 |
+
|
| 15 |
+
def setUp(self):
|
| 16 |
+
self.server = Server.Server()
|
| 17 |
+
|
| 18 |
+
def tearDown(self):
|
| 19 |
+
pass
|
| 20 |
+
|
| 21 |
+
def test_server_starts_with_no_clients(self):
|
| 22 |
+
self.assertTrue(len(self.server._clients) == 0)
|
| 23 |
+
|
| 24 |
+
def test_get_all_data_returns_all_data(self):
|
| 25 |
+
self.server.notify({"test": 1})
|
| 26 |
+
self.server.notify({"test2": 2})
|
| 27 |
+
res = self.server.get_all_data()
|
| 28 |
+
self.assertEqual(res, [{"test": 1}, {"test2": 2}])
|
| 29 |
+
|
| 30 |
+
def test_server_returns_nothing_on_no_data(self):
|
| 31 |
+
res = self.server.get_all_data()
|
| 32 |
+
self.assertListEqual(res, [])
|
| 33 |
+
|
| 34 |
+
def test_notify_returns_true(self):
|
| 35 |
+
res = self.server.notify("whatever")
|
| 36 |
+
self.assertTrue(res)
|
| 37 |
+
|
| 38 |
+
def test_send_message_adds_to_queue(self):
|
| 39 |
+
self.server.send_message({"Data": "somevalue"})
|
| 40 |
+
self.server.send_message({"Data": "somevalue2"})
|
| 41 |
+
mes_list = self .server.get_all_messages()
|
| 42 |
+
self.assertTrue(len(mes_list) == 2)
|
| 43 |
+
|
| 44 |
+
def test_get_all_messages(self):
|
| 45 |
+
msg = "test2"
|
| 46 |
+
self.server.send_message(msg)
|
| 47 |
+
msg_list = self.server.get_all_messages()
|
| 48 |
+
self.assertIn(msg, msg_list)
|
| 49 |
+
|
| 50 |
+
def test_get_all_data(self):
|
| 51 |
+
data = "asdadasd"
|
| 52 |
+
self.server.notify(data)
|
| 53 |
+
data_list = self.server.get_all_data()
|
| 54 |
+
self.assertIn(data, data_list)
|
| 55 |
+
|
| 56 |
+
def test_execute_command_sends_to_client_on_fail(self):
|
| 57 |
+
import Constants
|
| 58 |
+
client = Client.Client()
|
| 59 |
+
self.server._clients["test"] = ["garbage_uri", client]#mocking a client
|
| 60 |
+
self.server.execute_command("test", Constants.NETWORK_INFO_TAG)
|
| 61 |
+
|
| 62 |
+
def test_execute_command_sends_to_client_on_success(self):
|
| 63 |
+
import Constants
|
| 64 |
+
import CommandInterface
|
| 65 |
+
client = Client.Client()
|
| 66 |
+
ci = CommandInterface.CommandInterface()
|
| 67 |
+
client.set_command_executor(ci)
|
| 68 |
+
self.server._clients["test"] = ["garbage_uri", client]#mocking a client
|
| 69 |
+
res = self.server.execute_command("test", Constants.NETWORK_INFO_TAG)
|
| 70 |
+
self.assertRegexpMatches(res, "Ethernet")
|
| 71 |
+
|
| 72 |
+
if __name__ == "__main__":
|
| 73 |
+
unittest.main()
|
| 74 |
+
|