text
stringlengths 29
850k
|
---|
# Copyright (c) Mochi Media, Inc.
# Copyright (c) Ralph Meijer.
# See LICENSE for details.
"""
Asynchronous Scribe client support.
This provides a Twisted based Scribe client with an asynchronous interface for
sending logs and a consumer for L{udplog.twisted.DispatcherFromUDPLogProtocol}.
"""
from __future__ import division, absolute_import
import copy
import logging
import simplejson
from twisted.internet import defer
from twisted.internet import protocol
from twisted.python import log
from scribe import scribe
from thrift.Thrift import TApplicationException, TMessageType
from thrift.protocol import TBinaryProtocol
from thrift.transport import TTwisted
class AsyncScribeClient(scribe.Client):
"""
Asynchronous Scribe client.
This derives from L{scribe.Client} to work with the Twisted Thrift
transport and provide an asynchronous interface for L{Log}.
@ivar _reqs: List of pending requests. When a result comes in, the
associated deferred will be fired. If the connection is closed,
the deferreds of the pending requests will be fired with an exception.
"""
def __init__(self, transport, factory):
"""
Set up a scribe client.
@param transport: The transport of the connection to the Scribe
server.
@param factory: The protocol factory of the Thrift transport
protocol.
"""
scribe.Client.__init__(self, factory.getProtocol(transport))
self._reqs = {}
def Log(self, messages):
"""
Log messages.
@param messages: The messages to be sent.
@type messages: C{list} of L{scribe.LogEntry}.
@return: L{Deferred<twisted.internet.defer.Deferred>}.
"""
d = defer.Deferred()
self._reqs[self._seqid] = d
self.send_Log(messages)
return d
def send_Log(self, messages):
"""
Called to send log messages.
"""
scribe.Client.send_Log(self, messages)
self._seqid += 1
def recv_Log(self, iprot, mtype, rseqid):
"""
Called when the result of the log request was received.
"""
if mtype == TMessageType.EXCEPTION:
result = TApplicationException()
else:
result = scribe.Log_result()
result.read(iprot)
iprot.readMessageEnd()
try:
d = self._reqs.pop(rseqid)
except KeyError:
log.err(result, "Unexpected log result")
if isinstance(result, Exception):
d.errback(result)
elif result.success is not None:
d.callback(result.success)
else:
d.errback(TApplicationException(
TApplicationException.MISSING_RESULT,
'Log failed: unknown result'))
class ScribeProtocol(TTwisted.ThriftClientProtocol):
"""
Scribe protocol.
This connects an asynchronous Scribe client to a server and sends
out log events from C{dispatcher}.
"""
def __init__(self, dispatcher, minLogLevel=logging.INFO):
self.dispatcher = dispatcher
self.minLogLevel = minLogLevel
factory = TBinaryProtocol.TBinaryProtocolFactory(strictRead=False,
strictWrite=False)
TTwisted.ThriftClientProtocol.__init__(self, AsyncScribeClient,
factory)
def connectionMade(self):
"""
Add this protocol as a consumer of log events.
"""
TTwisted.ThriftClientProtocol.connectionMade(self)
self.dispatcher.register(self.sendEvent)
def connectionLost(self, reason=protocol.connectionDone):
"""
Remove this protocol as a consumer of log events.
"""
self.dispatcher.unregister(self.sendEvent)
TTwisted.ThriftClientProtocol.connectionLost(self, reason)
def sendEvent(self, event):
"""
Write an event to Scribe.
"""
event = copy.copy(event)
# Drop events with a log level lower than the configured minimum.
logLevel = logging.getLevelName(event.get('logLevel', 'INFO'))
if logLevel < self.minLogLevel:
return
category = event['category']
del event['category']
try:
message = simplejson.dumps(event)
except ValueError, e:
log.err(e, "Could not encode event to JSON")
return
entry = scribe.LogEntry(category=category, message=message)
d = self.client.Log(messages=[entry])
d.addErrback(log.err)
|
Watch The Jitterbug (Original London Cast) in the style of Wizard Of Oz - Musical video for a preview of this backing track. The audio file used in this video is an MP3 render of the Hit Trax MIDI File backing track. Some tracks may include sampled instruments from high quality sample libraries. Most times we record the audio direct from the outputs of a MIDI File player like a MERISH, Okyweb, Roland or Yamaha device.
TECHNICAL NOTES for The Jitterbug (Original London Cast) in the style of Wizard Of Oz - Musical. Sonic results may vary in different MIDI File players and devices, including sound libraries. Hit Trax assumes buyers know the capabilities and limitations of their MIDI playback devices, sound library, related devices and apps. Click the 'Show all Wizard Of Oz - Musical MIDI File Backing Tracks box’. to view all Hit Trax titles by Wizard Of Oz - Musical.
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Easy & simple yet flexible backup script """
import sys
import os
import argparse
import time
import socket
import traceback
import json
import plugins
import targets
from utils.stdio import CRESET, CBOLD, LGREEN, CDIM, LWARN
__author__ = 'Quentin Stoeckel'
__copyright__ = 'Copyright 2016, Quentin Stoeckel and contributors'
__credits__ = ['Contributors at https://github.com/chteuchteu/Simple-Backup-Script/graphs/contributors']
__license__ = 'gpl-v2'
__version__ = '1.0.0'
__maintainer__ = "qstoeckel"
__email__ = '[email protected]'
__status__ = 'Production'
config = {
'days_to_keep': 15,
'backups': [],
'targets': []
}
config_filename = 'config.json'
config_filename_old = 'config.py'
config_filepath = os.path.join(os.path.dirname(__file__), config_filename)
config_filepath_old = os.path.join(os.path.dirname(__file__), config_filename_old)
# Functions
def load_config():
# Load config
if not os.path.isfile(config_filepath):
if os.path.isfile(config_filepath_old):
print(CBOLD + LWARN, '\n{} is deprecated. Please use --migrate to generate {}'.format(
config_filename_old, config_filename), CRESET)
else:
print(CBOLD + LWARN, '\nCould not find configuration file {}'.format(config_filename), CRESET)
sys.exit(1)
with open(config_filepath, 'r') as config_file:
json_config = json.load(config_file)
config['days_to_keep'] = json_config.get('days_to_keep', config['days_to_keep'])
config['alert_emails'] = json_config.get('alert_emails')
config['sentry_dsn'] = json_config.get('sentry_dsn')
config['backups'] = json_config.get('backups', [])
config['targets'] = json_config.get('targets', [])
# Now that we know if Sentry should be enabled, load its sdk:
init_sentry()
def send_file(backup, backup_filepath, target_profile):
# Build destination filename
filename, file_extension = os.path.splitext(backup_filepath)
# ...explicitly handle ".tar.gz" extensions
if backup_filepath.endswith('.tar.gz'):
file_extension = '.tar.gz'
dest_file_name = 'backup-{hostname}-{timestamp}-{backup_name}({backup_profile}){file_extension}'.format(
hostname=socket.gethostname(),
timestamp=time.strftime("%Y%m%d-%H%M"),
backup_profile=backup.get('profile'),
backup_name=backup.get('name'),
file_extension=file_extension
)
_targets = targets.get_supported_targets()
type = target_profile.get('type', 'remote')
if type not in _targets:
print("Unknown target type \"{}\".".format(type))
sys.exit(1)
target = _targets[type]()
error = target.copy_to_target(config, target_profile, backup_filepath, dest_file_name)
if error is not None:
e, traceback = error
handle_error(backup, e, traceback)
print('')
def get_backup(backup_name):
candidates = [b for b in config['backups'] if b.get('name') == backup_name]
return candidates[0] if len(candidates) == 1 else None
def do_backup(backup):
backup_profile = backup.get('profile')
# Check backup profile
profiles = plugins.get_supported_backup_profiles()
if backup_profile not in profiles:
print("Unknown project type \"{}\".".format(backup_profile))
sys.exit(1)
# JUST DO IT
print(CBOLD+LGREEN, "Creating backup file", CRESET)
plugin = profiles[backup_profile]()
backup_filepath = plugin.create_backup_file(backup)
if backup_filepath is None:
print("Could not create backup file for \"{}\".".format(backup_profile))
return
# Send it to the moon (to each target)
backup_targets = config['targets'] if args.target == 'all' else [config['targets'][int(args.target)]]
for target_profile in backup_targets:
try:
send_file(backup, backup_filepath, target_profile)
except Exception as e:
# Print exception (for output in logs)
print(traceback.format_exc())
handle_error(backup, e, traceback)
# Delete the file
if plugin.remove_artifact:
print(CDIM, "Deleting {}".format(backup_filepath), CRESET)
os.remove(backup_filepath)
plugin.clean()
return
def init_sentry():
sentry_dsn = config.get('sentry_dsn', None)
if sentry_dsn is not None:
try:
import sentry_sdk
sentry_sdk.init(sentry_dsn)
return sentry_sdk
except Exception as error:
print(error)
return None
def handle_error(backup, exception, traceback):
# sentry
sentry = init_sentry()
if sentry is not None:
sentry.set_level('error')
sentry.set_tag('backup', backup.get('name'))
sentry.capture_exception(exception)
# mails
email_addresses = config.get('alert_emails', None)
if email_addresses is not None:
message = 'Simple-Backup-Script: backup "{}" failed'.format(backup.get('name'))
formatted_traceback = traceback.format_exc()
for address in [a for a in email_addresses if a]:
if address:
send_mail(address, message, formatted_traceback)
# Inspired by http://stackoverflow.com/a/27874213/1474079
def send_mail(recipient, subject, body):
import subprocess
try:
process = subprocess.Popen(['mail', '-s', subject, recipient], stdin=subprocess.PIPE)
process.communicate(input=bytes(body, 'UTF-8'))
return True
except Exception as error:
print(error)
return False
try:
# Check python version
if sys.version_info.major < 3:
print('Warning: Python 2.x isn\'t officially supported. Use at your own risk.')
# Check command line arguments
parser = argparse.ArgumentParser(description='Easily backup projects')
parser.add_argument('--self-update', action='store_true', dest='self_update')
parser.add_argument('--backup', default='ask_for_it')
parser.add_argument('--target', default='all')
parser.add_argument('-a', '--all', action='store_true')
parser.add_argument('--migrate', action='store_true')
parser.add_argument('--test-mails', action='store_true', dest='test_mails')
parser.add_argument('--test-config', action='store_true', dest='test_config')
args = parser.parse_args()
if args.migrate:
from utils.migrator import migrate
migrate()
elif args.self_update:
# cd to own directory
self_dir = os.path.dirname(os.path.realpath(__file__))
if not os.path.isdir(os.path.join(self_dir, '.git')):
print(CDIM+LWARN, "Cannot self-update: missing .git directory", CRESET)
sys.exit(1)
os.chdir(self_dir)
os.system("git pull")
print()
print(LGREEN, "Updated to the latest version", CRESET)
elif args.test_mails:
load_config()
email_addresses = config['alert_emails']
mail_sent = False
if email_addresses:
for address in [a for a in email_addresses if a]:
if address:
if send_mail(address, 'Simple-Backup-Script: test e-mail', ''):
mail_sent = True
print('Test mail sent to {}'.format(address))
else:
print('Could not send mail to {}'.format(address))
if not mail_sent:
print('No mail could be sent.')
else:
print('"alert_emails" is null or empty.')
sys.exit(1)
elif args.test_config:
print('Opening {}'.format(config_filename))
try:
load_config()
if len(config['backups']) == 0:
print(LWARN, 'Error: there a no configured backup profile', CRESET)
sys.exit(1)
if len(config['targets']) == 0:
print(LWARN, 'Error: there are no configured targets', CRESET)
sys.exit(1)
print(CBOLD + LGREEN, '{} successfully parsed:'.format(config_filename), CRESET)
print(' - Default days_to_keep: {}'.format(config['days_to_keep']))
print(' - Alert emails: {}'.format(config['alert_emails']))
print(' - {} backup profile(s)'.format(len(config['backups'])))
print(' - {} backup target(s)'.format(len(config['targets'])))
for i, target in enumerate(config['targets']):
if target.get('host') is None:
print(CBOLD + LWARN, 'Warning: Missing "host" attribute in target {}'.format(i), CRESET)
host = target.get('host', '#{}'.format(i+1))
if target.get('user') is None:
print(CBOLD + LWARN, 'Warning: Missing "user" attribute in target {}'.format(host), CRESET)
if target.get('dir') is None:
print(CBOLD + LWARN, 'Warning: Missing "dir" attribute in target {}'.format(host), CRESET)
except Exception:
print('Could not parse configuration:')
print(traceback.format_exc())
else:
load_config()
# Ask for backup to run
if len(config['backups']) == 0:
print(CBOLD + LGREEN, "Please configure backup projects in backup.py", CRESET)
sys.exit(1)
if args.all:
# Backup all profiles
for i, project in enumerate(config['backups']):
print(CBOLD+LGREEN, "\n{} - Backing up {} ({})".format(i, project.get('name'), project.get('profile')), CRESET)
backup = config['backups'][i]
do_backup(backup)
elif args.backup == 'ask_for_it':
print("Please select a backup profile to execute")
for i, project in enumerate(config['backups']):
print("\t[{}] {} ({})".format(str(i), project.get('name'), project.get('profile')))
backup_index = -1
is_valid = 0
while not is_valid:
try:
backup_index = int(input("? "))
is_valid = 1
except ValueError:
print("Not a valid integer.")
if 0 <= backup_index < len(config['backups']):
# Here goes the thing
backup = config['backups'][backup_index]
do_backup(backup)
else:
print("I won't take that as an answer")
else: # Backup project passed as argument
backup = get_backup(args.backup)
if backup is None:
print("This backup does not exist, or there may be several backups with this name")
sys.exit(1)
else:
do_backup(backup)
except KeyboardInterrupt:
print('\n^C signal caught, exiting')
sys.exit(1)
|
Greetings, You Who Brave the Night!
This report is preliminary, but noteworthy. As of 3:30 this morning, it appears that yet another change is beginning to occur to the anomalous lunar patterns that first surfaced early last winter. These patterns, in one form or other, have been extant now for almost exactly one year. However, the most widely known and easily noticed of these forms, the apparent radical clockwise rotation of the post zenith lunar features, (As seen from Earth) did not, in fact, begin occurring until the full moon of July 3, 2004.
A quick review for those just joining us. Beginning with that full moon, back in July 3, 2004, the moon would each rise with its features in the historically correct positions. (as it always had) The features would remain stationary as the moon climbed up into the sky, but then upon reaching zenith, the features would appear to suddenly rotate in the space of several hours, approx. 90 degrees! We all remember the fuss that routine caused, I am sure. For an example of what I am describing, picture in your mind that the right eye of the man in the moon, (Mare Crisium) normally found near the 2 O'clock position, would suddenly begin to rotate at zenith and in the space of several hours would have appeared to have moved from it's normal 2 o'clock position to nearly the 5:30 position. The next night the pattern would repeat. Anyway, this went on for six months, occurring exactly the same way each cycle.
Now once again, (curiously enough, yet again, on a full moon) it looks as though a change is in the works. Tonight the moon rose with the right eye straight up at 12 O'clock. However, this time, by the time it reached zenith it had already rotated to the 2 O'clock Position. To the best of my knowledge, this is the first time it has ever noticeably rotated prior to reaching zenith! It is now three and a half hours past zenith and the right eye has only moved to the 3 O'clock position. This is highly unusual and out of character with the past aberrations that have been exhibited over the last year.
We shall shortly see what happens, and if this new pattern is fated to continue. If I were to take a wild guess at this point, it would be that the moon feature rotation is "precessing" in it's current orbit as seen from Earth. The appearance of new changes are occurring in shorter and shorter intervals as well. It will be interesting to see how long this new pattern sticks around. I suspect that something is knocking the living daylights out of our solar system.
|
#!/usr/bin/env python
# -*- coding:UTF-8 -*-
# Copyright (c) 2019 Nicolas Iooss
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Parse a KeyStore in PKCS#12 format
Using openssl, it is possible to dump the certificates and private keys from
a PKCS#12 keystore:
openssl pkcs12 -info -passin pass:changeit -nodes -in store.p12
Nevertheless this command does not show the bags with type "secretBag", that
contain secret keys for symmetric encryption algorithms.
Documentation:
* https://tools.ietf.org/html/rfc7292
RFC 7292, PKCS #12: Personal Information Exchange Syntax v1.1
* https://tools.ietf.org/html/rfc2315
RFC 2315, PKCS #7: Cryptographic Message Syntax Version 1.5
* https://tools.ietf.org/html/rfc5208
RFC 5208, Public-Key Cryptography Standards (PKCS) #8:
Private-Key Information Syntax Specification Version 1.2
* https://www.openssl.org/docs/man1.0.2/man1/pkcs12.html
openssl-pkcs12 man page
NB. PKCS#12 pbeWithSHA1And40BitRC2-CBC key-derivation and encryption algorithm
is used to encrypt WebLogic passwords. The code uses JSAFE with algorithm
"PBE/SHA1/RC2/CBC/PKCS12PBE-5-128", which is pbeWithSHA1And40BitRC2-CBC with
five rounds. More information is available on:
* https://bitbucket.org/vladimir_dyuzhev/recover-weblogic-password/src/b48ef4a82db57f12e52788fe08b80e54e847d42c/src/weblogic/security/internal/encryption/JSafeSecretKeyEncryptor.java
* https://www.cryptsoft.com/pkcs11doc/v220/group__SEC__12__27__PKCS____12__PASSWORD__BASED__ENCRYPTION__AUTHENTICATION__MECHANISMS.html
* https://github.com/maaaaz/weblogicpassworddecryptor
* https://blog.netspi.com/decrypting-weblogic-passwords/
* https://github.com/NetSPI/WebLogicPasswordDecryptor/blob/master/Invoke-WebLogicPasswordDecryptor.psm1
"""
import argparse
import binascii
import datetime
import hashlib
import hmac
import logging
import os.path
import re
import struct
import sys
import tempfile
import Cryptodome.Cipher.ARC2
import Cryptodome.Cipher.DES3
import rc2
import util_asn1
from util_bin import run_openssl_show_cert, run_process_with_input, xx
from util_crypto import report_if_missing_cryptography, describe_der_certificate
logger = logging.getLogger(__name__)
def generate_p12_keystore(password):
"""Generate a PKCS#12 keystore with some content"""
temporary_dir = tempfile.mkdtemp(suffix='_java_keystore-test')
ks_path = os.path.join(temporary_dir, 'store.jks')
try:
# By default it generates a DSA keypair
run_process_with_input(
[
'keytool', '-genkeypair', '-noprompt',
'-keyalg', 'dsa',
'-storetype', 'pkcs12',
'-keystore', ks_path,
'-storepass', password,
'-alias', 'mykeypair',
'-dname', 'CN=example',
],
None, fatal=True)
run_process_with_input(
[
'keytool', '-genkeypair', '-noprompt',
'-keyalg', 'rsa', '-sigalg', 'SHA256withRSA',
'-storetype', 'pkcs12',
'-keystore', ks_path,
'-storepass', password,
'-alias', 'mykeypair_rsa_sha256sig',
'-dname', 'CN=example',
],
None, fatal=True)
# Add a secret key
run_process_with_input(
[
'keytool', '-genseckey',
'-keyalg', 'aes', '-keysize', '192',
'-storetype', 'pkcs12',
'-keystore', ks_path,
'-storepass', password,
'-alias', 'mysecret_aes192key',
],
None, fatal=True)
with open(ks_path, 'rb') as fks:
ks_content = fks.read()
if not ks_content:
raise ValueError("keytool did not produce any output")
return ks_content
finally:
try:
os.remove(ks_path)
except OSError as exc:
# If removing the files failed, the error will appear in rmdir
logger.debug("Error while removing files: %r", exc)
os.rmdir(temporary_dir)
def pkcs12_derivation(alg, id_byte, password, salt, iterations, result_size=None):
"""Compute a key and iv from a password and salt according to PKCS#12
id_byte is, according to https://tools.ietf.org/html/rfc7292#appendix-B.3 :
* 1 to generate a key
* 2 to generate an initial value (IV)
* 3 to generate an integrity key
OpenSSL implementation:
https://github.com/openssl/openssl/blob/OpenSSL_1_1_1/crypto/pkcs12/p12_key.c
"""
if alg == 'SHA1':
hash_func = hashlib.sha1
u = 160 # SHA1 digest size, in bits
v = 512 # SHA1 block size, in bits
else:
raise NotImplementedError("Unimplemented algorithm {} for PKCS#12 key derivation".format(alg))
assert (u % 8) == (v % 8) == 0
u_bytes = u // 8
v_bytes = v // 8
if result_size is None:
result_size = u_bytes
diversifier = struct.pack('B', id_byte) * v_bytes
expanded_salt_size = v_bytes * ((len(salt) + v_bytes - 1) // v_bytes)
expanded_salt = (salt * ((expanded_salt_size // len(salt)) + 1))[:expanded_salt_size]
assert len(expanded_salt) == expanded_salt_size
pass_bytes = password.encode('utf-16be') + b'\0\0'
expanded_pass_size = v_bytes * ((len(pass_bytes) + v_bytes - 1) // v_bytes)
expanded_pass = (pass_bytes * ((expanded_pass_size // len(pass_bytes)) + 1))[:expanded_pass_size]
assert len(expanded_pass) == expanded_pass_size
i_size = expanded_salt_size + expanded_pass_size
i_value = expanded_salt + expanded_pass
result = b''
while len(result) < result_size:
ctx = hash_func(diversifier)
ctx.update(i_value)
a_value = ctx.digest()
for _ in range(1, iterations):
a_value = hash_func(a_value).digest()
assert len(a_value) == u_bytes
result += a_value
b_value = struct.unpack(v_bytes * 'B', (a_value * ((v_bytes + u_bytes - 1) // u_bytes))[:v_bytes])
new_i_value = []
for j in range(0, i_size, v_bytes):
# Ij = Ij + B + 1
ij = list(struct.unpack(v_bytes * 'B', i_value[j:j + v_bytes]))
c = 1
for k in range(v_bytes - 1, -1, -1):
c += ij[k] + b_value[k]
ij[k] = c & 0xff
c = c >> 8
new_i_value.append(struct.pack(v_bytes * 'B', *ij))
i_value = b''.join(new_i_value)
return result[:result_size]
# Check the implementation with values from "openssl pkcs12" with OPENSSL_DEBUG_KEYGEN
assert pkcs12_derivation(
'SHA1', 3, 'changeit',
binascii.unhexlify('c6b068958d7d6085ba52c9cc3212a8fc2e50b3da'), 100000
) == binascii.unhexlify('ef3c7f41e19e7bc7bf06650164aff556d15206d7')
assert pkcs12_derivation(
'SHA1', 1, 'changeit',
binascii.unhexlify('a9fb3e857865d5e2aeff3983389c980d5de4bf39'), 50000, 24
) == binascii.unhexlify('12fe77bc0be3ae0d063c4858e948ff4e85c39daa08b833c9')
assert pkcs12_derivation(
'SHA1', 2, 'changeit',
binascii.unhexlify('a9fb3e857865d5e2aeff3983389c980d5de4bf39'), 50000, 8
) == binascii.unhexlify('13515c2efce50ef9')
def try_pkcs12_decrypt(encrypted, enc_alg, password, indent=''):
"""Try to decrypt some data with the given password and PKCS#12 password-based encryption algorithms"""
if not isinstance(enc_alg, util_asn1.PKCS12PbeAlg):
raise NotImplementedError("Unimplemented encryption algorithm {}".format(enc_alg))
if enc_alg.oid_name == 'pbeWithSHA1And3-KeyTripleDES-CBC':
# 192-bits 3DES key and 64-bit IV from SHA1
key = pkcs12_derivation(alg='SHA1', id_byte=1, password=password, salt=enc_alg.salt,
iterations=enc_alg.iterations, result_size=24)
iv = pkcs12_derivation(alg='SHA1', id_byte=2, password=password, salt=enc_alg.salt,
iterations=enc_alg.iterations, result_size=8)
crypto_3des = Cryptodome.Cipher.DES3.new(key, Cryptodome.Cipher.DES3.MODE_CBC, iv)
decrypted = crypto_3des.decrypt(encrypted)
elif enc_alg.oid_name == 'pbeWithSHA1And40BitRC2-CBC':
# 40-bits RC2 key and 64-bit IV from SHA1
key = pkcs12_derivation(alg='SHA1', id_byte=1, password=password, salt=enc_alg.salt,
iterations=enc_alg.iterations, result_size=5)
iv = pkcs12_derivation(alg='SHA1', id_byte=2, password=password, salt=enc_alg.salt,
iterations=enc_alg.iterations, result_size=8)
try:
crypto_rc2 = Cryptodome.Cipher.ARC2.new(key, Cryptodome.Cipher.ARC2.MODE_CBC, iv, effective_keylen=40)
decrypted = crypto_rc2.decrypt(encrypted)
except ValueError:
# Use custom RC2 implementation because "effective_keylen=40" is not always supported
# https://github.com/Legrandin/pycryptodome/issues/267
crypto_rc2 = rc2.RC2(key)
decrypted = crypto_rc2.decrypt(encrypted, rc2.MODE_CBC, iv)
else:
raise NotImplementedError("Unimplemented encryption algorithm {}".format(enc_alg))
# Check PKCS#5 padding
padlen, = struct.unpack('B', decrypted[-1:])
if not (1 <= padlen <= 0x10) or any(x != decrypted[-1] for x in decrypted[-padlen:]):
print("{}* wrong password (bad PKCS#5 padding)".format(indent))
return None
print("{}(password: {})".format(indent, repr(password)))
return decrypted[:-padlen]
def print_p12_keybag(keybag_der, password, show_pem=False, list_only=False, indent=''):
"""Parse PKCS#12 keyBag ASN.1 data"""
# KeyBag ::= PrivateKeyInfo -- from PKCS #8
# EncryptedPrivateKeyInfo ::= SEQUENCE {
# encryptionAlgorithm EncryptionAlgorithmIdentifier,
# encryptedData EncryptedData
# }
# EncryptionAlgorithmIdentifier ::= AlgorithmIdentifier
# EncryptedData ::= OCTET STRING
enc_alg_der, enc_data_der = util_asn1.decode_sequence(keybag_der, 2)
enc_alg = util_asn1.decode_x509_algid(enc_alg_der)
enc_data = util_asn1.decode_octet_string(enc_data_der)
print("{}* encryption algorithm: {}".format(indent, enc_alg))
if not isinstance(enc_alg, util_asn1.PKCS12PbeAlg):
raise NotImplementedError("Unimplemented encryption algorithm {}".format(enc_alg))
decrypted = try_pkcs12_decrypt(enc_data, enc_alg, password, indent=indent)
if decrypted is not None:
# Show the private key
util_asn1.show_pkcs8_private_key_info(decrypted, list_only=list_only, show_pem=show_pem, indent=indent)
def print_p12_certBag(certbag_der, show_pem=False, list_only=False, indent=''):
"""Parse PKCS#12 certBag ASN.1 data"""
# CertBag ::= SEQUENCE {
# certId BAG-TYPE.&id ({CertTypes}),
# certValue [0] EXPLICIT BAG-TYPE.&Type ({CertTypes}{@certId})
# }
cert_id_der, cert_value_der = util_asn1.decode_sequence(certbag_der, 2)
cert_id = util_asn1.decode_oid(cert_id_der)
cert_value_der = util_asn1.decode_object(cert_value_der)
if cert_id != 'x509Certificate':
raise NotImplementedError("Unknown certificate format {}".format(repr(cert_id)))
cert = util_asn1.decode_octet_string(cert_value_der)
description = describe_der_certificate(cert)
if description:
print("{}* Certificate: {}".format(indent, description))
else:
print("{}* Certificate: (no description available)".format(indent))
run_openssl_show_cert(cert, list_only=list_only, show_pem=show_pem, indent=indent)
def print_p12_secretBag(secretbag_der, password, show_pem=False, list_only=False, indent=''):
"""Parse PKCS#12 secretBag ASN.1 data"""
# SecretBag ::= SEQUENCE {
# secretTypeId BAG-TYPE.&id ({SecretTypes}),
# secretValue [0] EXPLICIT BAG-TYPE.&Type ({SecretTypes} {@secretTypeId})
# }
secret_type_id_der, secret_value_der = util_asn1.decode_sequence(secretbag_der, 2)
secret_type_id = util_asn1.decode_oid(secret_type_id_der)
secret_value_der = util_asn1.decode_object(secret_value_der)
print("{}* secret type: {}".format(indent, secret_type_id))
secret_value = util_asn1.decode_octet_string(secret_value_der)
if secret_type_id == 'keyBag':
print_p12_keybag(secret_value, password, show_pem=show_pem, list_only=list_only, indent=indent)
else:
raise NotImplementedError("Unimplemented secretBag type {}".format(secret_type_id))
def print_p12_safe_contents(safe_contents_der, password, show_pem=False, list_only=False, indent=''):
"""Parse PKCS#12 SafeContents ASN.1 data
https://tools.ietf.org/html/rfc7292#section-4.2
The SafeContents type is made up of SafeBags. Each SafeBag holds one
piece of information -- a key, a certificate, etc. -- which is
identified by an object identifier.
"""
# SafeContents ::= SEQUENCE OF SafeBag
# SafeBag ::= SEQUENCE {
# bagId BAG-TYPE.&id ({PKCS12BagSet})
# bagValue [0] EXPLICIT BAG-TYPE.&Type({PKCS12BagSet}{@bagId}),
# bagAttributes SET OF PKCS12Attribute OPTIONAL
# }
# PKCS12Attribute ::= SEQUENCE {
# attrId ATTRIBUTE.&id ({PKCS12AttrSet}),
# attrValues SET OF ATTRIBUTE.&Type ({PKCS12AttrSet}{@attrId})
# } -- This type is compatible with the X.500 type 'Attribute'
# PKCS12AttrSet ATTRIBUTE ::= {
# friendlyName | -- from PKCS #9
# localKeyId, -- from PKCS #9
# ... -- Other attributes are allowed
# }
safe_bags = util_asn1.decode_sequence(safe_contents_der)
print("{}* {} {}:".format(indent, len(safe_bags), "safe bags" if len(safe_bags) >= 2 else "safe bag"))
for idx_safe_bag, safe_bag_der in enumerate(safe_bags):
safe_bag = util_asn1.decode_sequence(safe_bag_der, counts=(2, 3))
bag_id = util_asn1.decode_oid(safe_bag[0])
bag_value = util_asn1.decode_object(safe_bag[1])
try:
bag_attributes = util_asn1.decode_set(safe_bag[2]) if len(safe_bag) >= 3 else []
except NotImplementedError as exc:
# Recover from error caused by old PyCrypto
logger.warning("Unable to decode bag attributes: %s", exc)
attr_descs = ['?']
else:
attr_descs = []
for bag_attribute_der in bag_attributes:
attr_id_der, attr_values_der = util_asn1.decode_sequence(bag_attribute_der, 2)
attr_id = util_asn1.decode_oid(attr_id_der)
attr_values_der = util_asn1.decode_set(attr_values_der)
attr_values = [util_asn1.decode_any_string(v) for v in attr_values_der]
attr_descs.append("{}={}".format(attr_id, ','.join(repr(v) for v in attr_values)))
if attr_id == 'localKeyID' and len(attr_values) == 1:
m = re.match(r'^Time ([0-9]+)$', attr_values[0])
if m:
# Parse the timestamp from the local key ID
timestamp = int(m.group(1))
attr_descs.append("date='{}'".format(datetime.datetime.fromtimestamp(timestamp / 1000.)))
print("{} [{}] {} ({})".format(indent, idx_safe_bag + 1, bag_id, ', '.join(attr_descs)))
if bag_id == 'keyBag':
print_p12_keybag(bag_value, password, show_pem=show_pem, list_only=list_only, indent=indent + " ")
elif bag_id == 'certBag':
print_p12_certBag(bag_value, show_pem=show_pem, list_only=list_only, indent=indent + " ")
elif bag_id == 'secretBag':
print_p12_secretBag(bag_value, password, show_pem=show_pem, list_only=list_only, indent=indent + " ")
else:
print("{} * bag value: {}".format(indent, repr(bag_value)))
raise NotImplementedError("Unimplemented bag id {}".format(bag_id))
def print_p12_keystore(ks_content, password, show_pem=False, list_only=False):
"""Parse a PKCS#12 KeyStore file and print it"""
# run_process_with_input(['openssl', 'asn1parse', '-i', '-inform', 'DER'], ks_content, fatal=True)
# PFX (Personal Information Exchange) is defined as:
# PFX ::= SEQUENCE {
# version INTEGER {v3(3)}(v3,...),
# authSafe ContentInfo,
# macData MacData OPTIONAL
# }
version, authsafe_der, macdata_der = util_asn1.decode_sequence(ks_content, 3)
if version != 3:
raise NotImplementedError("Unimplemented PFX version {}".format(version))
# ContentInfo ::= SEQUENCE {
# contentType ContentType,
# content [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL
# }
# ContentType ::= OBJECT IDENTIFIER
authsafe_content_type_der, authsafe_content_der = util_asn1.decode_sequence(authsafe_der, 2)
authsafe_content_type = util_asn1.decode_oid(authsafe_content_type_der)
if authsafe_content_type != 'pkcs7-data':
raise NotImplementedError("Unimplemented PFX content type {}".format(authsafe_content_type))
authsafe_content_der = util_asn1.decode_object(authsafe_content_der)
authsafe_content = util_asn1.decode_octet_string(authsafe_content_der)
# MacData ::= SEQUENCE {
# mac DigestInfo,
# macSalt OCTET STRING,
# iterations INTEGER DEFAULT 1
# }
macdata_asn1 = util_asn1.decode_sequence(macdata_der)
if len(macdata_asn1) == 2:
mac_der, mac_salt_der = macdata_asn1
mac_iterations = 1
elif len(macdata_asn1) == 3:
mac_der, mac_salt_der, mac_iterations = macdata_asn1
else:
raise ValueError("Unexpected number of items in ASN.1 MacData sequence")
mac_salt = util_asn1.decode_octet_string(mac_salt_der)
# DigestInfo ::= SEQUENCE {
# digestAlgorithm DigestAlgorithmIdentifier,
# digest Digest
# }
# DigestAlgorithmIdentifier ::= AlgorithmIdentifier
# Digest ::= OCTET STRING
mac_digest_algorithm_der, mac_digest_der = util_asn1.decode_sequence(mac_der, 2)
mac_digest_algorithm = util_asn1.decode_x509_algid(mac_digest_algorithm_der)
mac_digest = util_asn1.decode_octet_string(mac_digest_der)
print("* PKCS#12 Keystore MAC:")
print(" * algorithm: {}".format(mac_digest_algorithm))
print(" * salt: {}".format(xx(mac_salt)))
print(" * iterations: {}".format(mac_iterations))
print(" * HMAC digest: {}".format(xx(mac_digest)))
mac_key = pkcs12_derivation(
alg=mac_digest_algorithm,
id_byte=3,
password=password,
salt=mac_salt,
iterations=mac_iterations)
mac_hmac = hmac.new(key=mac_key, msg=authsafe_content, digestmod=hashlib.sha1).digest()
if mac_hmac == mac_digest:
print(" (password: {})".format(repr(password)))
print(" (HMAC key: {})".format(xx(mac_key)))
else:
print(" (computed HMAC: {})".format(xx(mac_hmac)))
print(" * wrong password (pad HMAC digest)")
# AuthenticatedSafe ::= SEQUENCE OF ContentInfo
# -- Data if unencrypted
# -- EncryptedData if password-encrypted
# -- EnvelopedData if public key-encrypted
authsafe_seq = util_asn1.decode_sequence(authsafe_content)
print("* {} data blocks:".format(len(authsafe_seq)))
for blk_index, blk_der in enumerate(authsafe_seq):
blk_content_type_der, blk_content_der = util_asn1.decode_sequence(blk_der, 2)
blk_content_type = util_asn1.decode_oid(blk_content_type_der)
blk_content_der = util_asn1.decode_object(blk_content_der) # tag "cont[0]"
if blk_content_type == 'pkcs7-data':
safe_contents = util_asn1.decode_octet_string(blk_content_der)
print(" [{}] unencrypted safe contents:".format(blk_index + 1))
print_p12_safe_contents(safe_contents, password, show_pem=show_pem, list_only=list_only, indent=" ")
elif blk_content_type == 'pkcs7-encryptedData':
print(" [{}] encrypted safe contents:".format(blk_index + 1))
# EncryptedData ::= SEQUENCE {
# version Version,
# encryptedContentInfo EncryptedContentInfo
# }
encblk_version, encrypted_ci_der = util_asn1.decode_sequence(blk_content_der, 2)
if encblk_version != 0:
raise NotImplementedError("Unimplemented PKCS#7 EncryptedData version {}".format(encblk_version))
# EncryptedContentInfo ::= SEQUENCE {
# contentType ContentType,
# contentEncryptionAlgorithm ContentEncryptionAlgorithmIdentifier,
# encryptedContent [0] IMPLICIT EncryptedContent OPTIONAL
# }
# ContentEncryptionAlgorithmIdentifier ::= AlgorithmIdentifier
# EncryptedContent ::= OCTET STRING
enc_ctype_der, enc_alg_der, enc_content_der = util_asn1.decode_sequence(encrypted_ci_der, 3)
enc_ctype = util_asn1.decode_oid(enc_ctype_der)
enc_alg = util_asn1.decode_x509_algid(enc_alg_der)
enc_content = util_asn1.decode_object(enc_content_der) # tag "cont[0]"
if enc_ctype != 'pkcs7-data':
raise NotImplementedError("Unimplemented PKCS#7 EncryptedData content type {}".format(enc_ctype))
print(" * encryption algorithm: {}".format(enc_alg))
safe_contents = try_pkcs12_decrypt(enc_content, enc_alg, password, indent=" ")
if safe_contents is not None:
print_p12_safe_contents(safe_contents, password, show_pem=show_pem, list_only=list_only, indent=" ")
else:
raise NotImplementedError("Unimplemented bag content type {}".format(blk_content_type))
def main(argv=None):
"""Program entry point"""
parser = argparse.ArgumentParser(
description="Parse a PKCS#12 keystore file",
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('input', metavar='KEYSTORE', nargs='?', type=str,
help="load a keystore instead of generating one")
parser.add_argument('-d', '--debug', action='store_true',
help="show debug messages")
parser.add_argument('-p', '--password', type=str, default='changeit',
help="keystore password")
parser.add_argument('-l', '--list', action='store_true',
help="list only, without printing the data")
parser.add_argument('-P', '--pem', action='store_true',
help="show certificates and private keys in PEM format")
args = parser.parse_args(argv)
logging.basicConfig(format='[%(levelname)-5s] %(message)s',
level=logging.DEBUG if args.debug else logging.INFO)
report_if_missing_cryptography()
if args.input:
with open(args.input, 'rb') as fin:
ks_content = fin.read()
logger.debug("Parsing file %r (%d bytes)", args.input, len(ks_content))
else:
try:
ks_content = generate_p12_keystore(args.password)
except ValueError as exc:
logger.fatal("Generating a keystore failed: %s", exc)
return 1
logger.debug("Parsing keystore (%d bytes)", len(ks_content))
try:
print_p12_keystore(ks_content, args.password, show_pem=args.pem, list_only=args.list)
except ValueError as exc:
logger.fatal("Parsing the keystore failed: %s", exc)
raise # Show the stack trace
return 0
if __name__ == '__main__':
sys.exit(main())
|
’Tis the season for family and friends to create their own new holiday memories and traditions this year at The Resort at Pelican Hill in Newport Beach. Now a favorite Southern California getaway, the Resort is located just 45 minutes from Los Angeles and 15 minutes from John Wayne Airport.
The package starts at $695 per night, excluding tax and based on availability.
The package starts at $995 for a two-bedroom Villa, $1,450 for a three-bedroom Villa or $1,950 for a four-bedroom Villa per night, excluding tax and based on availability.
The package starts at $795 for a bungalow per night, $1,150 for a two-bedroom Villa, $1,550 for a three-bedroom Villa or $2,050 for a four-bedroom Villa per night, excluding tax and based on availability.
Leave the decorations up to us this holiday season and arrive to discover your very own bungalow or Villa furnished with a wreath, garlands, a decorated tree, and a holiday CD with traditional favorites. We also offer the traditional Jewish menorah display if requested.
Available November 27 through December 24, 2009, the package starts at $895 for bungalows and $1,095 for a two-bedroom Villa, $1,500 for a three-bedroom Villa or $2,000 for a four-bedroom Villa per night, excluding tax and based on availability.
Available December 31, the package starts at $895 for two in a bungalow, excluding tax and based on availability. Additional guests can be added with specific costs for adults and children.
Available December 31, the package starts at $1295 for two in a two-bedroom Villa, $1595 for two in a three-bedroom Villa and $1895 for two in a four-bedroom Villa, excluding tax and based on availability. Additional guests can be added with specific costs for adults and children.
Reservations for all of these packages can be made by calling 800-820-6800.
Holiday shopping is easy this year at The Resort at Pelican Hill, where personalized gift cards can be designed for each friend and family member in one convenient location that will showcase their favorite indulgences. Sure to be remembered as their favorite present this year, the gift cards are available in denominations of $100, $200, $300, $500, $1,000 and $2,500. Guests who purchase gift cards for $1,000 or more will receive a 10% discount.
Favorite uses for the gift cards are an overnight stay in a bungalow or Villa; a therapeutic 60 or 90-minute spa treatment; a scenic dinner overlooking the ocean in Andrea, Pelican Grill or Coliseum Pool & Grill; a round of golf on the Fazio-designed ocean courses; and personal training sessions.
Gift cards can be purchased at the Gift Certificate Desk in the Resort lobby, Concierge Desk, Newsstand Shop and Allegra, 24 hours a day at the Front Desk, by calling toll free at 800- 820-6800, or for more information online on our Web site at www.pelicanhill.com.
To capture the essence of traditional tea with an Italian accent, this holiday season children and adults can experience the new Tea Time Renaissance daily from November 27 through December 31, 2009 from 2:30 to 5 p.m. in the gracious Great Room at The Resort at Pelican Hill.
Each Friday, Saturday and Sunday in December, Santa Claus will also greet children personally during the Tea Time Renaissance event. A live harpist will perform classical music throughout the afternoon.
The tea starts at $32 per person for adults and $16 for children. Reservations are requested and can be made by calling 800-820-6800. For larger parties of 9-20 people, the private dining room can also be reserved at an additional cost.
For guests who want to relax in the Great Room throughout the holidays, from November 16, 2009 to January 3, 2010, a champagne cart and tapas menu are offered from 5:30 p.m. to midnight, with a live piano duo for entertainment.
From November 16, 2009 through January 3, 2010, including Thanksgiving, Christmas Eve and Christmas Day, Executive Pastry Chef Frederic Monnet has created festive holiday gelatos, pastries and desserts in the Laboratorio del Gelato and Pastry Kitchen that can be purchased in the Caffe including from 6 a.m. to 10 p.m. To-go options are also available.
As a special draw for children and hot chocolate aficionados, a special Holiday Hot Chocolate Menu is available in the Caffe from November 28, 2009 through January 3, 2010 with a choice of whipped creams and toppings.
The therapist scoops a beautiful dollop of creamy sugar scrub infused with the seasonal pomegranate ingredient filled with anti-oxidants. After gently sloughing the skin, the gelato is washed away, and the guest is then cocooned in fresh muslin, as aloe and cucumber gel. The therapist concludes the treatment by applying whipped body butter with essential oil for ultra moisturizing.
• Smoothing Thyme Body Buff Treatment (45-minutes, $150 excluding gratuity) A fine salt body polish with fresh thyme and other organic herbs is applied with circular, feather-like strokes to gently yet thoroughly exfoliate the feet and entire body, cleansing the pores and adding nourishing minerals and herbs to the skin. After showering, guests receive an enriching skin re-hydration with Rosemary Olive Body Butter, leaving the skin to feel fresh and glowing.
While relaxing in the Men and Women’s Relaxation Rooms during the holidays, guests can enjoy signature hot spiced holiday tea created by TeaSpa, a pomegranate and wine beverage and dark chocolate pomegranate truffles as our complimentary holiday gift during their spa visit. Spa reservations can be made by calling (800) 820-6800.
-A grand Thanksgiving celebration with traditional brunch featuring seasonal and classic offerings created by Executive Chef Jean-Pierre Dubray and his culinary team available from 10:30 a.m. to 4 p.m. The feast is $85 for adults, $40 for children under 12 and $20 for children under five, excluding tax and gratuity. An acoustic guitarist performs throughout the day and a professional photographer is available to take family portraits and frame them from 10:30 a.m. to 2 p.m. with price varying based on photo size and frame style.
-A three-course Thanksgiving Dinner menu with a variety of options is available from 4 to 10 p.m. for $90 per adult and $45 per child under 12, excluding tax and gratuity. The regular Tuscan menu is also available and Andrea Bar also offers a Happy Bar Crudo a la carte menu from 11 a.m. to midnight.
-A three-course menu created by Chef Tripp Mauldin with a variety of options is available from 11:30 am to 10 p.m. for $85 for adults, $40 for children under 12 and $20 for children under five with a special kids menu, excluding tax and gratuity. The regular menu also available and a pianist, bass player and singer perform live from 11:30 a.m. to 10 p.m.
-A three-course multi-generational menu is available through Room Service from 11:30 a.m. to 10 p.m. A regular in-room dining menu also available.
-On Thanksgiving, a breakfast buffet is available from 7 to 11:30 a.m. for $32 for adults and $16 for children under 12. From noon to 10 p.m., a three-course menu with a variety of options created by Chef Chang Silivay is $80 for adults and $40 for children.
-A grand holiday celebration with seasonal and classic offerings created by Executive Chef Jean-Pierre Dubray and his culinary team available from 10:30 a.m. to 4 p.m. The feast is $85 for adults, $40 for children under 12 and $20 for children under five, excluding tax and gratuity. Acoustic guitarist entertainment.
-On Christmas Eve, a three-course dinner with a variety of options is available from 3 to 10 p.m. for $90 per adult and $45 for children under 12, excluding tax and gratuity. A live acoustic guitarist will perform and a select menu featuring traditional holiday menu and regular items also available in Andrea Bar.
-On Christmas Day, a special three-course Christmas Day menu is available with a variety of special holiday offerings from 11:30 a.m. to 10 p.m. for $90 for adults and $45 for children under 12, excluding tax and gratuity. A special menu available for children under five years of age and a limited regular Andrea menu.
-A three-course Christmas Eve Dinner with a variety of course options is available from 5 to 10 p.m. for $85 for adults, $40 for children under 12, excluding tax and gratuity. A special menu for children under five also available and a jazz trio will perform in the lounge from 6:30 to 10 pm.
-On Christmas Day, a three-course holiday menu features a variety of options for each course is available from 11:30 a.m. to 10 p.m. for $85 per adult and $40 for children under 12, excluding tax and gratuity. Children under five are complimentary and a limited regular menu and special lounge menu are also available. A piano jazz duo will perform from noon to 8 p.m.
-A three-course dinner with a variety of course options is available from 5 to 10 p.m. for $80 per adult, $40 for children under 12, excluding tax and gratuity.
-On Christmas Day, a three-course holiday menu with a variety of course options is available from 11:30 a.m. to 10 p.m. for $80 per adult and $40 for children under 12.
-Traditional Christmas fare from a special holiday is available a la carte menu through In-Room Dining in the comfort of a spacious bungalow from 5 to 10 p.m. The regular in-room dining menu is also available.
-On December 25, a special Christmas a la carte menu through In-Room Dining available from 11:30 a.m. to 10 p.m.
-A Togethering Christmas Feast is available a la carte served family-style in the guest’s personal Villa dining room. Available from 11:30 a.m. to 10 p.m., champagne and wine pairings are also available, as well as the standard in-room dining menu.
-A New Year’s Eve Gala will be offered in Andrea featuring a four-course menu with multiple course choices with two seatings from 5 to 8 p.m. for $100 per person for 5 p.m. seating, or $140 per person for 8:30 p.m. to 1 a.m., both excluding beverages, tax and gratuity.
-On New Year’s Eve from 11:30 a.m. to 10 p.m. we offer a regular lunch menu, a special Italian Happy Bar Crudo menu and a champagne menu for pairings. A four-piece dancing band and singer will perform from 9 p.m. to 1 a.m. A balloon will drop at midnight to celebrate the New Year with a complimentary glass of Prosecco sparkling wine to toast.
-On New Year’s Day, a regular dinner menu is available from 5 to 8 p.m. and the Andrea Bar is also open.
-A three-course prix-fixe menu if offered from 5 to 10 p.m. for $80 per adult, $40 for children under 12, excluding tax and gratuity, and complimentary for kids under five. A standard dinner menu and a festive limited bar menu are available from 10 p.m. to midnight. Live entertainment with a DJ is provided from 7 p.m. to 12:30 a.m. and a complimentary glass of Prosecco sparkling wine to toast at midnight.
-On New Year’s Day, a traditional breakfast buffet is available from 7 to 11:30 a.m. for $32 per adult and $16 for children under 12. A special brunch menu with a variety of dish options is available from noon to 5 p.m. for $55 per adult, $30 per children under 12 and $20 for kids under five, excluding tax and gratuity. The regular dinner menu is available from 5 to 10 p.m. At the pool, the regular menu is available from 10 a.m. to 6 p.m.
-Chef Tripp Maudlin’s special four-course prix fixe menu with a choice of dishes is available from 5 to 10 p.m. for $120 per adult and $65 per child under age 12. Dancing and entertainment by a three-piece band and singer is offered from 7:30 p.m. to 12:30 a.m. A balloon drop will take place at midnight in the lounge with a complimentary glass of Prosecco sparkling wine.
-On New Year’s Day, a traditional brunch menu is available from 10 a.m. to 3 p.m. for $55 for adults and $27 for children under 12. A special New Year’s Day Football Bowl Games Menu offered in the Pelican Lounge from 10 a.m. to 11 p.m.
-For overnight guests, a holiday a la carte menu is available in their spacious bungalow or Villa from 11:30 a.m. to 10 p.m.
-On New Year’s Day, a Champagne Breakfast-in-Bed is available in a bungalow or Villa, including a split bottle of Veuve Clicquot and a la carte menu options. The order must be placed the day prior.
For all dining reservations, please call (800) 820-6800.
The Resort at Pelican Hill is one of the world’s finest resorts blending the principles of Italy’s most renowned Renaissance architect with chic California casual elegance. Special features include 128 villas with an unparalleled array of appointments, immersing guests in the absolute finest of everything; 204 luxuriously appointed bungalow suites; a rejuvenating spa with a menu of the world’s most celebrated therapies; world-class restaurants including authentic Northern Italian cuisine in Andrea; an iconic Coliseum Pool, the largest circular pool anywhere with tiered decks and luxurious cabanas; and Pelican Hill Golf Club boasting two 18-hole courses by Tom Fazio with stunning ocean panoramas from nearly every hole. Set on a 504-acre site in Newport Beach that is one of the most serene and beautiful coastal settings in Southern California, The Resort at Pelican Hill captures the essence of an Italian seaside village, terraced on a verdant hillside in harmony with the natural environment.
|
from lost_visions import forms
from lost_visions.utils.flickr import getImageTags
from lost_visions.views import get_random_image_data
from dajaxice.utils import deserialize_form
__author__ = 'ubuntu'
from dajax.core import Dajax
from dajaxice.decorators import dajaxice_register
def get_an_image():
# assume a problem !!!
problem = True
# loop to prefer failing than looping forever
loop = 0
while problem and loop < 20:
loop+=1
image_data = get_random_image_data()
if image_data is not None:
if 'flickr_id' in image_data:
# this is all we care about for now
problem = False
# return flickr_tags['image_location']
return image_data['flickr_large_source']
def read_category_form(form):
CategoryForm = forms.category_form_factory()
form = CategoryForm(deserialize_form(form))
if form.is_valid():
print 'valid form'
else:
print 'invalid form'
categories = ["cycling",
"cover",
"castle",
"decorative papers",
"ship",
"technology",
"sciencefiction",
"children's book illustration",
"letter",
"decoration",
"map",
"fashion",
"portrait",
"christmas"]
for cat in categories:
if cat in form.cleaned_data:
print cat
def read_tags_form(form):
TagsForm = forms.tag_form_factory({})
tags_form = TagsForm(form)
@dajaxice_register
def load_image(request):
dajax = Dajax()
img_url = get_an_image()
# print img_url
dajax.script('change_image("' + img_url + '");')
# dajax.assign('#result', 'value', 'hi' + image_id)
# dajax.alert('You sent "%s"' % name)
return dajax.json()
@dajaxice_register
def submit_tags(request, form, image_id):
read_tags_form(form)
print request.POST
dajax = Dajax()
# img_url = get_an_image()
# print img_url
# dajax.script('change_image("' + img_url + '");')
dajax.script('add_new_tags();')
# dajax.assign('#result', 'value', 'hi' + image_id)
# dajax.alert('You sent "%s"' % name)
return dajax.json()
@dajaxice_register
def submit_creation_techniques(request, form, image_id):
read_category_form(form)
print request.POST
dajax = Dajax()
dajax.script('add_description();')
return dajax.json()
@dajaxice_register
def submit_free_text(request, form, image_id):
read_category_form(form)
print request.POST
dajax = Dajax()
# TODO start here
dajax.script('add_thank_you();')
return dajax.json()
@dajaxice_register
def submit_new_tags(request, form, image_id):
print request.POST
dajax = Dajax()
# TODO start here
dajax.script('add_categories();')
return dajax.json()
@dajaxice_register
def submit_categories(request, form, image_id):
read_category_form(form)
print request.POST
dajax = Dajax()
dajax.script('add_creation_techniques();')
return dajax.json()
|
Description : Institute of Banking Personal Selection IBPS Officer Scale II And Officer Scale III Interview Call Letter Has Been Declared. Those Candidates Who Are Pass Their Officer Scale Mains Exam And Waiting For Interview Call Letter. Now Can Download Their Interview Call Letter.
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# --- Import Area
from enums.TaskStatus import TaskStatus
class TaskDAG:
"""Class to represent a DAG [Direct Acyclic Graph] for a Task"""
# --- Attributes
# Private
_tasks = None # All the tasks
# Constants
# --- Constructor
def __init__(self, tasks):
""""
TaskDAG Constructor
:param: tasks: Task Array
"""
self._tasks = tasks
# --- Methods
def get_root_tasks(self):
"""
Method to get the root tasks
:return: Task Array
"""
root_task = []
for i in range(0, len(self._tasks)):
if self._tasks[i].is_root():
root_task.append(self._tasks[i])
return root_task
def get_leaf_tasks(self):
"""
Method to get the leaf tasks
:return Task Array
"""
leaf_tasks = []
for i in range(0, len(self._tasks)):
if self._tasks[i].is_ready():
leaf_tasks.append(self._tasks[i])
return leaf_tasks
def get_ready_tasks(self):
"""
Method to get all the ready tasks
:return Task Array
"""
ready_tasks = []
for i in range(0, len(self._tasks)):
if self._tasks[i].is_ready():
ready_tasks.append(self._tasks[i])
return ready_tasks
def get_current_tasks(self):
"""
Method to get the current tasks
:return Task Array
"""
current_tasks = []
for i in range(0, len(self._tasks)):
if self._tasks[i].is_current_root():
current_tasks.append(self._tasks[i])
return current_tasks
def are_all_tasks_finished(self):
"""
Method to check if all tasks are finished
:return Bool
"""
for i in range(0, len(self._tasks)):
if self._tasks[i].is_finished() is False:
return False
return True
def init(self):
"""
Method to init all tasks
"""
for i in range(0, len(self._tasks)):
self._tasks[i].status = TaskStatus.PENDING
root_tasks = self.get_root_tasks()
for i in range(0, len(root_tasks)):
self._tasks[i].status = TaskStatus.READY
def update_tasks(self, simulation_date):
"""
Method to update tasks
:param simulation_date: Integer
"""
for i in range(0, len(self._tasks)):
self._tasks[i].update(simulation_date)
def update(self, simulation_date):
"""
Method to update all tasks
:param simulation_date: Integer
"""
#Reset all start date
for i in range(0, len(self._tasks)):
self._tasks[i].reset_start_dates()
# Top-Down Update Min Start Dates
curr_tasks = self.get_current_tasks()
for i in range(0, len(curr_tasks)):
if curr_tasks[i].is_running() is False:
curr_tasks[i].set_min_start_date(simulation_date)
# Compute overall max end Date
max_end_date = 0
leaf_tasks = self.get_leaf_tasks()
for i in range(0, len(leaf_tasks)):
leaf_task = leaf_tasks[i]
max_end_date = max(leaf_task.min_start_date + leaf_task.duration, max_end_date)
# Bottom-Up Update max start date
for i in range(0, len(leaf_tasks)):
leaf_task = leaf_tasks[i]
leaf_task.set_max_start_date(max_end_date - leaf_task.duration)
# Update the criticality of tasks
for i in range(0, len(self._tasks)):
self._tasks[i].computer_criticality()
# --- Getters/Setters
|
Our extensive 2009 retrospective confirmed the beauty of the vintage. Few fruity-styled wines were as refined as this stunning Auslese by the Merkelbach brothers.
Our extensive 2009 retrospective with over 150 wines re-tasted will be released in the coming days. It showed that these wines are remarkably accessible: They are easy to understand, not overly acidic, and packed with succulent fruit.
The stunning 2009er Ürziger Würzgarten Auslese (Auction) by the Merkelbach brothers underpins this like few others.
Ask any grower in the Mosel who still does things like in the old days and chances are high that the name Merkelbach will fall.
This is no surprise. These two over 80 year-young growers have stubbornly continued to produce wine like they always have done, right since they joined the family business ... over 60 years ago!
The vines are old and trained on single pole. The yields are high. The Merkelbach brothers are quite open about it: 100 hl/ha is not exceptional. The wines are harvested not overly late, parcel by parcel, and are fermented spontaneously in traditional oak casks before each cask is being bottled separately.
understanding the AP numbers a few years ago).
Mosel Fine Wines Issue No 33 (Jan 2017).
2009 was a warm vintage with quite some rain just before the harvest. This type of growing conditions suited perfectly the vineyard approach of the Merkelbach. High yields limited the sugar level concentration on the vines and single pole training reduced the exposure of the grapes to the direct sunlight.
Overall, the Ürziger Würzgarten sector, one of the last full walls still planted with grapes on single pole in the Mosel, did quite well in 2009.
The 2009er Ürziger Würzgarten Auslese AP 14 was a special cask which the Merkelbach brothers decided to sell via the annual Trier Auction of the Bernkasteler Ring (an association in which the family has been a member since decades).
The wine was fermented down to 9% of alcohol, i.e. a little bit higher than what has become the norm lately for fruity-styled wines. Also this proved perfect as it buffered off some of the sweetness and perfected the balance in the wine.
Overall, the wine is already quite enjoyable but still gains from extensive airing. The result is magnificent. There is fruit. There is zest. There is ripeness. There is freshness. But above all, there is balance and elegance.
This wine proves a great success and is also a tribute to the high quality of the wines crafted by the Merkelbach brothers since over half a century.
Our full retrospective of the 2009 vintage was published in the Mosel Fine Wines Issue No 45 (Apr 2019). You are a subscriber and miss this Issue? Simply send us a request by email and we will be happy to send you a copy. You are not yet a subscriber and wish to get this Issue? Subscribe free of charge by registering yourself here below and ask us for a copy by email.
|
from __future__ import division
import numpy as np
from pySDC.Transfer import transfer
from pySDC.datatype_classes.mesh import mesh, rhs_imex_mesh
# FIXME: extend this to ndarrays
class mesh_to_mesh_1d(transfer):
"""
Custon transfer class, implements Transfer.py
This implementation can restrict and prolong between 1d meshes, using weigthed restriction and 7th-order prologation
via matrix-vector multiplication.
Attributes:
fine: reference to the fine level
coarse: reference to the coarse level
init_f: number of variables on the fine level (whatever init represents there)
init_c: number of variables on the coarse level (whatever init represents there)
Rspace: spatial restriction matrix, dim. Nf x Nc
Pspace: spatial prolongation matrix, dim. Nc x Nf
"""
def __init__(self,fine_level,coarse_level):
"""
Initialization routine
Args:
fine_level: fine level connected with the transfer operations (passed to parent)
coarse_level: coarse level connected with the transfer operations (passed to parent)
"""
# invoke super initialization
super(mesh_to_mesh_1d,self).__init__(fine_level,coarse_level)
# if number of variables is the same on both levels, Rspace and Pspace are identity
if self.init_c == self.init_f:
self.Rspace = np.eye(self.init_c)
# assemble weighted restriction by hand
else:
self.Rspace = np.zeros((self.init_f,self.init_c))
np.fill_diagonal(self.Rspace[1::2,:],1)
np.fill_diagonal(self.Rspace[0::2,:],1/2)
np.fill_diagonal(self.Rspace[2::2,:],1/2)
self.Rspace = 1/2*self.Rspace.T
# if number of variables is the same on both levels, Rspace and Pspace are identity
if self.init_f == self.init_c:
self.Pspace = np.eye(self.init_f)
# assemble 7th-order prolongation by hand
else:
self.Pspace = np.zeros((self.init_f,self.init_c))
np.fill_diagonal(self.Pspace[1::2,:],1)
# np.fill_diagonal(self.Pspace[0::2,:],1/2)
# np.fill_diagonal(self.Pspace[2::2,:],1/2)
# this would be 3rd-order accurate
# c1 = -0.0625
# c2 = 0.5625
# c3 = c2
# c4 = c1
# np.fill_diagonal(self.Pspace[0::2,:],c3)
# np.fill_diagonal(self.Pspace[2::2,:],c2)
# np.fill_diagonal(self.Pspace[0::2,1:],c4)
# np.fill_diagonal(self.Pspace[4::2,:],c1)
# self.Pspace[0,0:3] = [0.9375, -0.3125, 0.0625]
# self.Pspace[-1,-3:self.init_c] = [0.0625, -0.3125, 0.9375]
np.fill_diagonal(self.Pspace[0::2,:],0.5859375)
np.fill_diagonal(self.Pspace[2::2,:],0.5859375)
np.fill_diagonal(self.Pspace[0::2,1:],-0.09765625)
np.fill_diagonal(self.Pspace[4::2,:],-0.09765625)
np.fill_diagonal(self.Pspace[0::2,2:],0.01171875)
np.fill_diagonal(self.Pspace[6::2,:],0.01171875)
self.Pspace[0,0:5] = [1.23046875, -0.8203125, 0.4921875, -0.17578125, 0.02734375]
self.Pspace[2,0:5] = [0.41015625, 0.8203125, -0.2734375, 0.08203125, -0.01171875]
self.Pspace[-1,-5:self.init_c] = [0.02734375, -0.17578125, 0.4921875, -0.8203125, 1.23046875]
self.Pspace[-3,-5:self.init_c] = [-0.01171875, 0.08203125, -0.2734375, 0.8203125, 0.41015625]
pass
def restrict_space(self,F):
"""
Restriction implementation
Args:
F: the fine level data (easier to access than via the fine attribute)
"""
if isinstance(F,mesh):
u_coarse = mesh(self.init_c,val=0)
u_coarse.values = np.dot(self.Rspace,F.values)
elif isinstance(F,rhs_imex_mesh):
u_coarse = rhs_imex_mesh(self.init_c)
u_coarse.impl.values = np.dot(self.Rspace,F.impl.values)
u_coarse.expl.values = np.dot(self.Rspace,F.expl.values)
return u_coarse
def prolong_space(self,G):
"""
Prolongation implementation
Args:
G: the coarse level data (easier to access than via the coarse attribute)
"""
if isinstance(G,mesh):
u_fine = mesh(self.init_f,val=0)
u_fine.values = np.dot(self.Pspace,G.values)
elif isinstance(G,rhs_imex_mesh):
u_fine = rhs_imex_mesh(self.init_f)
u_fine.impl.values = np.dot(self.Pspace,G.impl.values)
u_fine.expl.values = np.dot(self.Pspace,G.expl.values)
return u_fine
|
Wages can be submitted via TNPAWS using one of two formats.
Once the Wage File has been created and saved on your PC as a text file (FileName.txt), it can be uploaded into the TNPAWS Wage System.
To upload the file on your PC click the Browse button and navigate to the file to be uploaded. Select the file and click the open button.
After the file format (.txt) has been verified, the system will begin to verify the submitted data. If the file format is incorrect, you will recieve an error message 'Your file was not uploaded because it does not have a .txt extension'. Once the file is saved in the correct format (.txt), you can upload the file again.
The system will validate the individual data fields. If data errors are found, a list of the errors with the line number will be displayed on the screen.
Clear Button: Clicking the Clear button will reset the screen back to its original state.
|
# -*- coding: utf-8 -*-
"""
Copyright 2016 Walter José and Alex de Sá
This file is part of the RECIPE Algorithm.
The RECIPE is free software: you can redistribute it and/or
modify it under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your option)
any later version.
RECIPE is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. See http://www.gnu.org/licenses/.
"""
from sklearn.naive_bayes import BernoulliNB
def bernoulliNB(args):
"""Uses scikit-learn's BernoulliNB, a naive bayes classifier for multinomial models
Parameters
----------
alpha : float
Additive (Laplace/Lidstone) smoothing parameter (0 for no smoothing).
binarize : float or None
Threshold for binarizing (mapping to booleans) of sample features. If None, input is presumed to already consist of binary vectors.
fit_prior : boolean
Whether to learn class prior probabilities or not. If false, a uniform prior will be used.
"""
alp = 1.0
if(args[2].find("None")==-1):
alp = float(args[2])
fit = False
if(args[3].find("True")!=-1):
fit = True
bina = 0.0
if(args[1].find("None")==-1):
bina=float(args[1])
return BernoulliNB(alpha=alp, binarize=bina, fit_prior=fit, class_prior=None)
|
This Cognac cask-finished whiskey has light, airy aromas of vanilla cream, heather honey, golden syrup, flaked coconut, and whole orange. Baked pastries and tangy orange precede a mid-palate spice rush, with grapefruit flavors building through a lengthy, spicy finish. Several sourced Irish whiskeys use local water to cut down to bottling strength; Lambay uses water drawn from the island’s Trinity Well.
|
# -*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import re
from common import public
class qyxg_wscpws():
"""开庭公告"""
need_check_ziduan = ['caseout_come',
'court_litigant',
# 'court_acceptance_fee',
# 'historycase'
]
def check_caseout_come(self, indexstr, ustr):
"""案件结果"""
"""可为空,若非空至少包含两个中文汉字或两个英文字母"""
ret = None
if ustr and len(ustr):
if not public.has_count_hz(ustr, 2) \
and not public.has_count_en(ustr, 2):
ret = u'没有2个以上汉字页没有2个英文字母'
return ret
def check_court_litigant(self, indexstr, ustr):
"""法院当事人"""
"""可为空,若非空至少包含两个中文汉字或两个英文字母"""
ret = None
if ustr and len(ustr):
if not public.has_count_hz(ustr, 2) \
and not public.has_count_en(ustr, 2):
ret = u'没有2个以上汉字页没有2个英文字母'
return ret
def check_court_acceptance_fee(self, indexstr, ustr):
"""受理费"""
"""可为空,若非空为数字+单位的格式"""
ret = None
if ustr and len(ustr):
if not re.compile(u'^\d{1,}(元|\$)$').match(ustr):
ret = u'不符合格式数字+单位'
return ret
def check_historycase(self, indexstr, ustr):
"""历审案例"""
"""可为空,必须全为汉字,且包含“法院”两字"""
ret = None
if ustr and len(ustr):
if public.is_allchinese(ustr):
if u'法院' not in ustr:
ret = u'不包含法院二字'
else:
ret = u'不全为汉字'
return ret
|
Normally, when you want a wedding photographer, you shop around, looking at the various portfolios, etc. But, the MAIN problem with this is that the photographer might have only ONE good photo at any wedding, and they could put this into the portfolio. In my mind, the photographs are right up their with the Bride in importance for a wedding, so I was nervous about just using any wedding photographer.
We found Adam via a friend, after looking at their own Wedding Album. We were AMAZED at the fact that ALL their wedding photos were INCREDIBLE. This is probably the BEST way to find a wedding photographer, when you see a selection of over 100 photographs, and every one of them is excellent.
|
import mathutils
import math
#
# General remarks regarding all functions presented here:
#
# Each motion is an array of transforms presented in form of tuples
# (loc:Vector, rot:Quaternion)
#
# =============================================================================
#
# Calculates a relative movement of 'childMotion' with respect to 'rootMotion'.
#
# The method works only if both motions have the exact same number of keyframes.
#
#
# @return new motion if the operation was successful, or an empty motion otherwise
#
def calcRelativeMotion( rootMotion, childMotion ):
resultingMotion = []
framesCount = len( rootMotion )
if framesCount != len( childMotion ):
op.report( {'ERROR'}, "transform_utils.calcRelativeMotion: The method works only with motions with the same number of keyframes" )
return resultingMotion
for frameIdx in range( framesCount ):
rootLoc, rootRot = rootMotion[frameIdx]
childLoc, childRot = childMotion[frameIdx]
invRootRot = rootRot.conjugated().normalized()
# translation
translation = childLoc - rootLoc
translation.rotate( invRootRot )
# rotation
rotation = invRootRot * childRot
resultingMotion.append( ( translation, rotation ) )
return resultingMotion
#
# Calculates the rotation around the Z axis ( the yaw ) of the specified transform
#
def calcYaw( transform ):
worldFwdDir = mathutils.Vector( ( 1.0, 0.0, 0.0 ) )
rotatedVec = worldFwdDir.copy()
rotatedVec.rotate( transform[1] )
rotatedVec.z = 0.0
rotatedVec.normalize()
worldFwdDir2D = worldFwdDir.to_2d()
rotatedVec2D = rotatedVec.to_2d()
yawAngle = -worldFwdDir2D.angle_signed( rotatedVec2D, 0.0 )
return yawAngle
#
# Prints the motion definition
#
def printMotion( motion, header ):
print( header )
frameIdx = 1
for keyframe in motion:
loc, rot = keyframe[0:2]
print( "Frame ", frameIdx, ". loc", loc, "; rot", rot )
frameIdx += 1
|
We listened to you and as a result we’re expanding the range of choice available under the second stretch goal.
to get a 2nd soft neoprene carrycase.
Note: What does “add £5 ($8) to your current pledge amount” mean?
This has to do with the fact that the carrycase has a higher value than the Y cable & external inline control.
So for backers of the pair who want a soft neoprene carrycase for both of their FS-Xs we’re offering the possibility to add an extra £5 ($8) to their current pledge to get a 2nd carrycase (this means they get 50% off their second carrycase).
And because we’re offering this option for pair backers we’re doing the same for the single FS-X backers as this only fair. If they add an extra £5 ($8) to their current pledge they also can get a carrycase (with 50% off).
Hope you agree that this is the fair thing to do!
Thanks again for your fantastic support and comments.
They were very helpful in helping us make up our minds.
iwieiwiw, Marsha Tyszler, and 6 more people like this update.
@ Marsha Tyszler: Thanks for the kind words! No problem!
@ Step666: Yes, that’s right!
@ Laurence Freedman, Lee Gibson & bsl100: Glad you liked this Update!
Extra case for a fiver. Good enough deal. I've added on the extra £5 to my pledge.
These are all such great options! It is very kind of you to allow us flexibility in choosing our extras. It speaks volumes (no pun intended!) to the fact that you're listening (no pun intended again!) to your customers and truly aim to please us! Of course, you've been trying to adjust the FS-X's design and features based on our suggestions, which is most important, but adjusting these small details shows just how much you care! It's very much appreciated!
So, just to check, as a backer who pledged for a pair of FS-Xs, if I add £15 I can get a pair of cases, a Y-cable and an in-line control?
@Ulises same way every KS project manager does... with the survey at the end of the campaign.
Out of curiosity, how are you going to track people's choices?
You've listened, you've responded, and you can be damn sure you've made a ton of people happy. I should know, I'm one of them!
|
#
# Copyright 2008, 2013 Red Hat, Inc.
# Cole Robinson <[email protected]>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301 USA.
"""
Classes for building and installing libvirt storage xml
General workflow for the different storage objects:
1. Storage Pool:
Pool type options can be exposed to a user via the static function
L{StoragePool.get_pool_types}. Any selection can be fed back into
L{StoragePool.get_pool_class} to get the particular volume class to
instantiate. From here, values can be set at init time or via
properties post init.
Different pool types have different options and
requirements, so using getattr() is probably the best way to check
for parameter availability.
2) Storage Volume:
There are a few options for determining what pool volume class to use:
- Pass the pools type for L{StoragePool.get_volume_for_pool}
- Pass the pool object or name to L{StorageVolume.get_volume_for_pool}
These will give back the appropriate class to instantiate. For most cases,
all that's needed is a name and capacity, the rest will be filled in.
@see: U{http://libvirt.org/storage.html}
"""
import os
import threading
import time
import logging
import libvirt
import urlgrabber
from virtinst.util import xml_escape as escape
from virtinst import util
from virtinst import support
DEFAULT_DEV_TARGET = "/dev"
DEFAULT_LVM_TARGET_BASE = "/dev/"
DEFAULT_DIR_TARGET_BASE = "/var/lib/libvirt/images/"
DEFAULT_SCSI_TARGET = "/dev/disk/by-path"
DEFAULT_MPATH_TARGET = "/dev/mapper"
# Pulled from libvirt, used for building on older versions
VIR_STORAGE_VOL_FILE = 0
VIR_STORAGE_VOL_BLOCK = 1
def is_create_vol_from_supported(conn):
return support.check_pool_support(conn,
support.SUPPORT_STORAGE_CREATEVOLFROM)
def _parse_pool_source_list(source_xml):
def source_parser(node):
ret_list = []
child = node.children
while child:
if child.name == "source":
val_dict = {}
source = child.children
while source:
if source.name == "name":
val_dict["source_name"] = source.content
elif source.name == "host":
val_dict["host"] = source.prop("name")
elif source.name == "format":
val_dict["format"] = source.prop("type")
elif source.name in ["device", "dir"]:
val_dict["source_path"] = source.prop("path")
source = source.next
ret_list.append(val_dict)
child = child.next
for val_dict in ret_list:
if (val_dict.get("format") == "lvm2" and
val_dict.get("source_name") and
not val_dict.get("target_path")):
val_dict["target_path"] = (DEFAULT_LVM_TARGET_BASE +
val_dict["source_name"])
return ret_list
return util.parse_node_helper(source_xml, "sources", source_parser)
class StorageObject(object):
"""
Base class for building any libvirt storage object.
Mostly meaningless to directly instantiate.
"""
TYPE_POOL = "pool"
TYPE_VOLUME = "volume"
def __init__(self, object_type, name, conn=None):
"""
Initialize storage object parameters
"""
if object_type not in [self.TYPE_POOL, self.TYPE_VOLUME]:
raise ValueError(_("Unknown storage object type: %s") % type)
self._object_type = object_type
self._conn = None
self._name = None
if conn is not None:
self.conn = conn
self.name = name
# Initialize all optional properties
self._perms = None
## Properties
def get_object_type(self):
# 'pool' or 'volume'
return self._object_type
object_type = property(get_object_type)
def get_conn(self):
return self._conn
def set_conn(self, val):
if not isinstance(val, libvirt.virConnect):
raise ValueError(_("'conn' must be a libvirt connection object."))
if not util.is_storage_capable(val):
raise ValueError(_("Passed connection is not libvirt storage "
"capable"))
self._conn = val
conn = property(get_conn, set_conn, doc="""
Libvirt connection to check object against/install on
""")
def get_name(self):
return self._name
def set_name(self, val):
util.validate_name(_("Storage object"), val)
# Check that name doesn't collide with other storage objects
self._check_name_collision(val)
self._name = val
name = property(get_name, set_name, doc=_("Name for the storage object."))
# Get/Set methods for use by some objects. Will register where applicable
def get_perms(self):
return self._perms
def set_perms(self, val):
if type(val) is not dict:
raise ValueError(_("Permissions must be passed as a dict object"))
for key in ["mode", "owner", "group"]:
if not key in val:
raise ValueError(_("Permissions must contain 'mode', 'owner' and 'group' keys."))
self._perms = val
# Validation helper functions
def _validate_path(self, path):
if not isinstance(path, str) or not path.startswith("/"):
raise ValueError(_("'%s' is not an absolute path." % path))
def _check_name_collision(self, name):
ignore = name
raise NotImplementedError()
# XML Building
def _get_storage_xml(self):
"""
Returns the pool/volume specific xml blob
"""
raise NotImplementedError()
def _get_perms_xml(self):
perms = self.get_perms()
if not perms:
return ""
xml = " <permissions>\n" + \
" <mode>0%o</mode>\n" % perms["mode"] + \
" <owner>%d</owner>\n" % perms["owner"] + \
" <group>%d</group>\n" % perms["group"]
if "label" in perms:
xml += " <label>%s</label>\n" % perms["label"]
xml += " </permissions>\n"
return xml
def get_xml_config(self):
"""
Construct the xml description of the storage object
@returns: xml description
@rtype: C{str}
"""
if not hasattr(self, "type"):
root_xml = "<%s>\n" % self.object_type
else:
_type = getattr(self, "type")
root_xml = "<%s type='%s'>\n" % (self.object_type, _type)
xml = "%s" % (root_xml) + \
""" <name>%s</name>\n""" % (self.name) + \
"""%(stor_xml)s""" % {"stor_xml" : self._get_storage_xml()} + \
"""</%s>\n""" % (self.object_type)
return xml
class StoragePool(StorageObject):
"""
Base class for building and installing libvirt storage pool xml
"""
# @group Types: TYPE_*
TYPE_DIR = "dir"
TYPE_FS = "fs"
TYPE_NETFS = "netfs"
TYPE_LOGICAL = "logical"
TYPE_DISK = "disk"
TYPE_ISCSI = "iscsi"
TYPE_SCSI = "scsi"
TYPE_MPATH = "mpath"
# Pool type descriptions for use in higher level programs
_types = {}
_types[TYPE_DIR] = _("Filesystem Directory")
_types[TYPE_FS] = _("Pre-Formatted Block Device")
_types[TYPE_NETFS] = _("Network Exported Directory")
_types[TYPE_LOGICAL] = _("LVM Volume Group")
_types[TYPE_DISK] = _("Physical Disk Device")
_types[TYPE_ISCSI] = _("iSCSI Target")
_types[TYPE_SCSI] = _("SCSI Host Adapter")
_types[TYPE_MPATH] = _("Multipath Device Enumerator")
def get_pool_class(ptype):
"""
Return class associated with passed pool type.
@param ptype: Pool type
@type ptype: member of I{Types}
"""
if ptype not in StoragePool._types:
raise ValueError(_("Unknown storage pool type: %s" % ptype))
if ptype == StoragePool.TYPE_DIR:
return DirectoryPool
if ptype == StoragePool.TYPE_FS:
return FilesystemPool
if ptype == StoragePool.TYPE_NETFS:
return NetworkFilesystemPool
if ptype == StoragePool.TYPE_LOGICAL:
return LogicalPool
if ptype == StoragePool.TYPE_DISK:
return DiskPool
if ptype == StoragePool.TYPE_ISCSI:
return iSCSIPool
if ptype == StoragePool.TYPE_SCSI:
return SCSIPool
if ptype == StoragePool.TYPE_MPATH:
return MultipathPool
get_pool_class = staticmethod(get_pool_class)
def get_volume_for_pool(pool_type):
"""Convenience method, returns volume class associated with pool_type"""
pool_class = StoragePool.get_pool_class(pool_type)
return pool_class.get_volume_class()
get_volume_for_pool = staticmethod(get_volume_for_pool)
def get_pool_types():
"""Return list of appropriate pool types"""
return StoragePool._types.keys()
get_pool_types = staticmethod(get_pool_types)
def get_pool_type_desc(pool_type):
"""Return human readable description for passed pool type"""
if pool_type in StoragePool._types:
return StoragePool._types[pool_type]
else:
return "%s pool" % pool_type
get_pool_type_desc = staticmethod(get_pool_type_desc)
def pool_list_from_sources(conn, name, pool_type, host=None):
"""
Return a list of StoragePool instances built from libvirt's pool
source enumeration (if supported).
@param conn: Libvirt connection
@param name: Name for the new pool
@param pool_type: Pool type string from I{Types}
@param host: Option host string to poll for sources
"""
if not support.check_conn_support(conn,
support.SUPPORT_CONN_FINDPOOLSOURCES):
return []
pool_class = StoragePool.get_pool_class(pool_type)
pool_inst = pool_class(conn=conn, name=name)
if host:
source_xml = "<source><host name='%s'/></source>" % host
else:
source_xml = "<source/>"
try:
xml = conn.findStoragePoolSources(pool_type, source_xml, 0)
except libvirt.libvirtError, e:
if support.is_error_nosupport(e):
return []
raise
retlist = []
source_list = _parse_pool_source_list(xml)
for source in source_list:
pool_inst = pool_class(conn=conn, name=name)
for key, val in source.items():
if not hasattr(pool_inst, key):
continue
setattr(pool_inst, key, val)
retlist.append(pool_inst)
return retlist
pool_list_from_sources = staticmethod(pool_list_from_sources)
def __init__(self, conn, name, type, target_path=None, uuid=None):
# pylint: disable=W0622
# Redefining built-in 'type', but it matches the XML so keep it
StorageObject.__init__(self, object_type=StorageObject.TYPE_POOL,
name=name, conn=conn)
if type not in self.get_pool_types():
raise ValueError(_("Unknown storage pool type: %s" % type))
self._type = type
self._target_path = None
self._host = None
self._format = None
self._source_path = None
self._uuid = None
if target_path is None:
target_path = self._get_default_target_path()
self.target_path = target_path
if uuid:
self.uuid = uuid
# Initialize all optional properties
self._host = None
self._source_path = None
self._random_uuid = util.generate_uuid(self.conn)
# Properties used by all pools
def get_type(self):
return self._type
type = property(get_type,
doc=_("Storage device type the pool will represent."))
def get_target_path(self):
return self._target_path
def set_target_path(self, val):
self._validate_path(val)
self._target_path = os.path.abspath(val)
# Get/Set methods for use by some pools. Will be registered when applicable
def get_source_path(self):
return self._source_path
def set_source_path(self, val):
self._validate_path(val)
self._source_path = os.path.abspath(val)
def get_host(self):
return self._host
def set_host(self, val):
if not isinstance(val, str):
raise ValueError(_("Host name must be a string"))
self._host = val
# uuid: uuid of the storage object. optional: generated if not set
def get_uuid(self):
return self._uuid
def set_uuid(self, val):
val = util.validate_uuid(val)
self._uuid = val
uuid = property(get_uuid, set_uuid)
# Validation functions
def _check_name_collision(self, name):
pool = None
try:
pool = self.conn.storagePoolLookupByName(name)
except libvirt.libvirtError:
pass
if pool:
raise ValueError(_("Name '%s' already in use by another pool." %
name))
def _get_default_target_path(self):
raise NotImplementedError()
# XML Building
def _get_target_xml(self):
raise NotImplementedError()
def _get_source_xml(self):
raise NotImplementedError()
def _get_storage_xml(self):
src_xml = ""
if self._get_source_xml() != "":
src_xml = " <source>\n" + \
"%s" % (self._get_source_xml()) + \
" </source>\n"
tar_xml = " <target>\n" + \
"%s" % (self._get_target_xml()) + \
" </target>\n"
return " <uuid>%s</uuid>\n" % (self.uuid or self._random_uuid) + \
"%s" % src_xml + \
"%s" % tar_xml
def install(self, meter=None, create=False, build=False, autostart=False):
"""
Install storage pool xml.
"""
xml = self.get_xml_config()
logging.debug("Creating storage pool '%s' with xml:\n%s",
self.name, xml)
if not meter:
meter = urlgrabber.progress.BaseMeter()
try:
pool = self.conn.storagePoolDefineXML(xml, 0)
except Exception, e:
raise RuntimeError(_("Could not define storage pool: %s" % str(e)))
errmsg = None
if build:
try:
pool.build(libvirt.VIR_STORAGE_POOL_BUILD_NEW)
except Exception, e:
errmsg = _("Could not build storage pool: %s" % str(e))
if create and not errmsg:
try:
pool.create(0)
except Exception, e:
errmsg = _("Could not start storage pool: %s" % str(e))
if autostart and not errmsg:
try:
pool.setAutostart(True)
except Exception, e:
errmsg = _("Could not set pool autostart flag: %s" % str(e))
if errmsg:
# Try and clean up the leftover pool
try:
pool.undefine()
except Exception, e:
logging.debug("Error cleaning up pool after failure: " +
"%s" % str(e))
raise RuntimeError(errmsg)
return pool
class DirectoryPool(StoragePool):
"""
Create a directory based storage pool
"""
def get_volume_class():
return FileVolume
get_volume_class = staticmethod(get_volume_class)
# Register applicable property methods from parent class
perms = property(StorageObject.get_perms, StorageObject.set_perms)
target_path = property(StoragePool.get_target_path,
StoragePool.set_target_path,
doc=_("Directory to use for the storage pool."))
def __init__(self, conn, name, target_path=None, uuid=None, perms=None):
StoragePool.__init__(self, name=name, type=StoragePool.TYPE_DIR,
target_path=target_path, uuid=uuid, conn=conn)
if perms:
self.perms = perms
def _get_default_target_path(self):
path = (DEFAULT_DIR_TARGET_BASE + self.name)
return path
def _get_target_xml(self):
xml = " <path>%s</path>\n" % escape(self.target_path) + \
"%s" % self._get_perms_xml()
return xml
def _get_source_xml(self):
return ""
class FilesystemPool(StoragePool):
"""
Create a formatted partition based storage pool
"""
def get_volume_class():
return FileVolume
get_volume_class = staticmethod(get_volume_class)
formats = ["auto", "ext2", "ext3", "ext4", "ufs", "iso9660", "udf",
"gfs", "gfs2", "vfat", "hfs+", "xfs"]
# Register applicable property methods from parent class
perms = property(StorageObject.get_perms, StorageObject.set_perms)
source_path = property(StoragePool.get_source_path,
StoragePool.set_source_path,
doc=_("The existing device to mount for the pool."))
target_path = property(StoragePool.get_target_path,
StoragePool.set_target_path,
doc=_("Location to mount the source device."))
def __init__(self, conn, name, source_path=None, target_path=None,
format="auto", uuid=None, perms=None):
# pylint: disable=W0622
# Redefining built-in 'format', but it matches the XML so keep it
StoragePool.__init__(self, name=name, type=StoragePool.TYPE_FS,
target_path=target_path, uuid=uuid, conn=conn)
self.format = format
if source_path:
self.source_path = source_path
if perms:
self.perms = perms
def get_format(self):
return self._format
def set_format(self, val):
if not val in self.formats:
raise ValueError(_("Unknown Filesystem format: %s" % val))
self._format = val
format = property(get_format, set_format,
doc=_("Filesystem type of the source device."))
def _get_default_target_path(self):
path = (DEFAULT_DIR_TARGET_BASE + self.name)
return path
def _get_target_xml(self):
xml = " <path>%s</path>\n" % escape(self.target_path) + \
"%s" % self._get_perms_xml()
return xml
def _get_source_xml(self):
if not self.source_path:
raise RuntimeError(_("Device path is required"))
xml = " <format type='%s'/>\n" % self.format + \
" <device path='%s'/>\n" % escape(self.source_path)
return xml
class NetworkFilesystemPool(StoragePool):
"""
Create a network mounted filesystem storage pool
"""
def get_volume_class():
return FileVolume
get_volume_class = staticmethod(get_volume_class)
formats = ["auto", "nfs", "glusterfs"]
# Register applicable property methods from parent class
source_path = property(StoragePool.get_source_path,
StoragePool.set_source_path,
doc=_("Path on the host that is being shared."))
host = property(StoragePool.get_host, StoragePool.set_host,
doc=_("Name of the host sharing the storage."))
target_path = property(StoragePool.get_target_path,
StoragePool.set_target_path,
doc=_("Location to mount the source device."))
def __init__(self, conn, name, source_path=None, host=None,
target_path=None, format="auto", uuid=None):
# pylint: disable=W0622
# Redefining built-in 'format', but it matches the XML so keep it
StoragePool.__init__(self, name=name, type=StoragePool.TYPE_NETFS,
uuid=uuid, target_path=target_path, conn=conn)
self.format = format
if source_path:
self.source_path = source_path
if host:
self.host = host
def get_format(self):
return self._format
def set_format(self, val):
if not val in self.formats:
raise ValueError(_("Unknown Network Filesystem format: %s" % val))
self._format = val
format = property(get_format, set_format,
doc=_("Type of network filesystem."))
def _get_default_target_path(self):
path = (DEFAULT_DIR_TARGET_BASE + self.name)
return path
def _get_target_xml(self):
xml = " <path>%s</path>\n" % escape(self.target_path)
return xml
def _get_source_xml(self):
if not self.host:
raise RuntimeError(_("Hostname is required"))
if not self.source_path:
raise RuntimeError(_("Host path is required"))
xml = """ <format type="%s"/>\n""" % self.format + \
""" <host name="%s"/>\n""" % self.host + \
""" <dir path="%s"/>\n""" % escape(self.source_path)
return xml
class LogicalPool(StoragePool):
"""
Create a logical (lvm volume group) storage pool
"""
def get_volume_class():
return LogicalVolume
get_volume_class = staticmethod(get_volume_class)
# Register applicable property methods from parent class
perms = property(StorageObject.get_perms, StorageObject.set_perms)
target_path = property(StoragePool.get_target_path,
StoragePool.set_target_path,
doc=_("Location of the existing LVM volume group."))
def __init__(self, conn, name, target_path=None, uuid=None, perms=None,
source_path=None, source_name=None):
StoragePool.__init__(self, name=name, type=StoragePool.TYPE_LOGICAL,
target_path=target_path, uuid=uuid, conn=conn)
self._source_name = None
if perms:
self.perms = perms
if source_path:
self.source_path = source_path
if source_name:
self.source_name = source_name
# Need to overwrite storage path checks, since this optionally be a list
# of devices
def get_source_path(self):
return self._source_path
def set_source_path(self, val):
if not val:
self._source_path = None
return
if type(val) != list:
StoragePool.set_source_path(self, val)
else:
self._source_path = val
source_path = property(get_source_path, set_source_path,
doc=_("Optional device(s) to build new LVM volume "
"on."))
def get_source_name(self):
if self._source_name:
return self._source_name
# If a source name isn't explictly set, try to determine it from
# existing parameters
srcname = self.name
if (self.target_path and
self.target_path.startswith(DEFAULT_LVM_TARGET_BASE)):
# If there is a target path, parse it for an expected VG
# location, and pull the name from there
vg = self.target_path[len(DEFAULT_LVM_TARGET_BASE):]
srcname = vg.split("/", 1)[0]
return srcname
def set_source_name(self, val):
self._source_name = val
source_name = property(get_source_name, set_source_name,
doc=_("Name of the Volume Group"))
def _make_source_name(self):
srcname = self.name
if self.source_path:
# Building a pool, so just use pool name
return srcname
def _get_default_target_path(self):
return DEFAULT_LVM_TARGET_BASE + self.name
def _get_target_xml(self):
xml = " <path>%s</path>\n" % escape(self.target_path) + \
"%s" % self._get_perms_xml()
return xml
def _get_source_xml(self):
sources = self.source_path
if type(sources) != list:
sources = sources and [sources] or []
xml = ""
for s in sources:
xml += " <device path='%s'/>\n" % s
if self.source_name:
xml += " <name>%s</name>\n" % self.source_name
return xml
def install(self, meter=None, create=False, build=False, autostart=False):
if build and not self.source_path:
raise ValueError(_("Must explicitly specify source path if "
"building pool"))
return StoragePool.install(self, meter=meter, create=create,
build=build, autostart=autostart)
class DiskPool(StoragePool):
"""
Create a storage pool from a physical disk
"""
def get_volume_class():
return DiskVolume
get_volume_class = staticmethod(get_volume_class)
# Register applicable property methods from parent class
source_path = property(StoragePool.get_source_path,
StoragePool.set_source_path,
doc=_("Path to the existing disk device."))
target_path = property(StoragePool.get_target_path,
StoragePool.set_target_path,
doc=_("Root location for identifying new storage"
" volumes."))
formats = ["auto", "bsd", "dos", "dvh", "gpt", "mac", "pc98", "sun"]
def __init__(self, conn, name, source_path=None, target_path=None,
format="auto", uuid=None):
# pylint: disable=W0622
# Redefining built-in 'format', but it matches the XML so keep it
StoragePool.__init__(self, name=name, type=StoragePool.TYPE_DISK,
uuid=uuid, target_path=target_path, conn=conn)
self.format = format
if source_path:
self.source_path = source_path
def get_format(self):
return self._format
def set_format(self, val):
if not val in self.formats:
raise ValueError(_("Unknown Disk format: %s" % val))
self._format = val
format = property(get_format, set_format,
doc=_("Format of the source device's partition table."))
def _get_default_target_path(self):
return DEFAULT_DEV_TARGET
def _get_target_xml(self):
xml = " <path>%s</path>\n" % escape(self.target_path)
return xml
def _get_source_xml(self):
if not self.source_path:
raise RuntimeError(_("Host path is required"))
xml = ""
# There is no explicit "auto" type for disk pools, but leaving out
# the format type seems to do the job for existing formatted disks
if self.format != "auto":
xml = """ <format type="%s"/>\n""" % self.format
xml += """ <device path="%s"/>\n""" % escape(self.source_path)
return xml
def install(self, meter=None, create=False, build=False, autostart=False):
if self.format == "auto" and build:
raise ValueError(_("Must explicitly specify disk format if "
"formatting disk device."))
return StoragePool.install(self, meter=meter, create=create,
build=build, autostart=autostart)
class iSCSIPool(StoragePool):
"""
Create an iSCSI based storage pool
"""
host = property(StoragePool.get_host, StoragePool.set_host,
doc=_("Name of the host sharing the storage."))
target_path = property(StoragePool.get_target_path,
StoragePool.set_target_path,
doc=_("Root location for identifying new storage"
" volumes."))
def get_volume_class():
raise NotImplementedError(_("iSCSI volume creation is not supported."))
get_volume_class = staticmethod(get_volume_class)
def __init__(self, conn, name, source_path=None, host=None,
target_path=None, uuid=None):
StoragePool.__init__(self, name=name, type=StoragePool.TYPE_ISCSI,
uuid=uuid, target_path=target_path, conn=conn)
if source_path:
self.source_path = source_path
if host:
self.host = host
self._iqn = None
# Need to overwrite pool *_source_path since iscsi device isn't
# a fully qualified path
def get_source_path(self):
return self._source_path
def set_source_path(self, val):
self._source_path = val
source_path = property(get_source_path, set_source_path,
doc=_("Path on the host that is being shared."))
def _get_iqn(self):
return self._iqn
def _set_iqn(self, val):
self._iqn = val
iqn = property(_get_iqn, _set_iqn,
doc=_("iSCSI initiator qualified name"))
def _get_default_target_path(self):
return DEFAULT_SCSI_TARGET
def _get_target_xml(self):
xml = " <path>%s</path>\n" % escape(self.target_path)
return xml
def _get_source_xml(self):
if not self.host:
raise RuntimeError(_("Hostname is required"))
if not self.source_path:
raise RuntimeError(_("Host path is required"))
iqn_xml = ""
if self.iqn:
iqn_xml += """ <initiator>\n"""
iqn_xml += """ <iqn name="%s"/>\n""" % escape(self.iqn)
iqn_xml += """ </initiator>\n"""
xml = """ <host name="%s"/>\n""" % self.host
xml += """ <device path="%s"/>\n""" % escape(self.source_path)
xml += iqn_xml
return xml
class SCSIPool(StoragePool):
"""
Create a SCSI based storage pool
"""
target_path = property(StoragePool.get_target_path,
StoragePool.set_target_path,
doc=_("Root location for identifying new storage"
" volumes."))
def get_volume_class():
raise NotImplementedError(_("SCSI volume creation is not supported."))
get_volume_class = staticmethod(get_volume_class)
def __init__(self, conn, name, source_path=None,
target_path=None, uuid=None):
StoragePool.__init__(self, name=name, type=StoragePool.TYPE_SCSI,
uuid=uuid, target_path=target_path, conn=conn)
if source_path:
self.source_path = source_path
# Need to overwrite pool *_source_path since iscsi device isn't
# a fully qualified path
def get_source_path(self):
return self._source_path
def set_source_path(self, val):
self._source_path = val
source_path = property(get_source_path, set_source_path,
doc=_("Name of the scsi adapter (ex. host2)"))
def _get_default_target_path(self):
return DEFAULT_SCSI_TARGET
def _get_target_xml(self):
xml = " <path>%s</path>\n" % escape(self.target_path)
return xml
def _get_source_xml(self):
if not self.source_path:
raise RuntimeError(_("Adapter name is required"))
xml = """ <adapter name="%s"/>\n""" % escape(self.source_path)
return xml
class MultipathPool(StoragePool):
"""
Create a Multipath based storage pool
"""
target_path = property(StoragePool.get_target_path,
StoragePool.set_target_path,
doc=_("Root location for identifying new storage"
" volumes."))
def get_volume_class():
raise NotImplementedError(_("Multipath volume creation is not "
"supported."))
get_volume_class = staticmethod(get_volume_class)
def __init__(self, conn, name, target_path=None, uuid=None):
StoragePool.__init__(self, name=name, type=StoragePool.TYPE_MPATH,
uuid=uuid, target_path=target_path, conn=conn)
def _get_default_target_path(self):
return DEFAULT_MPATH_TARGET
def _get_target_xml(self):
xml = " <path>%s</path>\n" % escape(self.target_path)
return xml
def _get_source_xml(self):
return ""
##########################
# Storage Volume classes #
##########################
class StorageVolume(StorageObject):
"""
Base class for building and installing libvirt storage volume xml
"""
formats = []
# File vs. Block for the Volume class
_file_type = None
def __init__(self, name, capacity, conn=None, pool_name=None, pool=None,
allocation=0):
"""
@param name: Name for the new storage volume
@param capacity: Total size of the new volume (in bytes)
@param conn: optional virConnect instance to lookup pool_name on
@param pool_name: optional pool_name to install on
@param pool: virStoragePool object to install on
@param allocation: amount of storage to actually allocate (default 0)
"""
if pool is None:
if pool_name is None:
raise ValueError(_("One of pool or pool_name must be "
"specified."))
if conn is None:
raise ValueError(_("'conn' must be specified with 'pool_name'"))
pool = StorageVolume.lookup_pool_by_name(pool_name=pool_name,
conn=conn)
self._pool = None
self.pool = pool
poolconn = self.pool._conn # pylint: disable=W0212
StorageObject.__init__(self, object_type=StorageObject.TYPE_VOLUME,
name=name, conn=poolconn)
self._allocation = None
self._capacity = None
self._format = None
self._input_vol = None
self.allocation = allocation
self.capacity = capacity
# Indicate that the volume installation has finished. Used to
# definitively tell the storage progress thread to stop polling.
self._install_finished = True
def get_volume_for_pool(pool_object=None, pool_name=None, conn=None):
"""
Returns volume class associated with passed pool_object/name
"""
pool_object = StorageVolume.lookup_pool_by_name(pool_object=pool_object,
pool_name=pool_name,
conn=conn)
return StoragePool.get_volume_for_pool(util.get_xml_path(pool_object.XMLDesc(0), "/pool/@type"))
get_volume_for_pool = staticmethod(get_volume_for_pool)
def find_free_name(name, pool_object=None, pool_name=None, conn=None,
suffix="", collidelist=None, start_num=0):
"""
Finds a name similar (or equal) to passed 'name' that is not in use
by another pool
This function scans the list of existing Volumes on the passed or
looked up pool object for a collision with the passed name. If the
name is in use, it append "-1" to the name and tries again, then "-2",
continuing to 100000 (which will hopefully never be reached.") If
suffix is specified, attach it to the (potentially incremented) name
before checking for collision.
Ex name="test", suffix=".img" -> name-3.img
@param collidelist: An extra list of names to check for collision
@type collidelist: C{list}
@returns: A free name
@rtype: C{str}
"""
collidelist = collidelist or []
pool_object = StorageVolume.lookup_pool_by_name(
pool_object=pool_object,
pool_name=pool_name,
conn=conn)
pool_object.refresh(0)
return util.generate_name(name, pool_object.storageVolLookupByName,
suffix, collidelist=collidelist,
start_num=start_num)
find_free_name = staticmethod(find_free_name)
def lookup_pool_by_name(pool_object=None, pool_name=None, conn=None):
"""
Returns pool object determined from passed parameters.
Largely a convenience function for the other static functions.
"""
if pool_object is None and pool_name is None:
raise ValueError(_("Must specify pool_object or pool_name"))
if pool_name is not None and pool_object is None:
if conn is None:
raise ValueError(_("'conn' must be specified with 'pool_name'"))
if not util.is_storage_capable(conn):
raise ValueError(_("Connection does not support storage "
"management."))
try:
pool_object = conn.storagePoolLookupByName(pool_name)
except Exception, e:
raise ValueError(_("Couldn't find storage pool '%s': %s" %
(pool_name, str(e))))
if not isinstance(pool_object, libvirt.virStoragePool):
raise ValueError(_("pool_object must be a virStoragePool"))
return pool_object
lookup_pool_by_name = staticmethod(lookup_pool_by_name)
# Properties used by all volumes
def get_file_type(self):
return self._file_type
file_type = property(get_file_type)
def get_capacity(self):
return self._capacity
def set_capacity(self, val):
if type(val) not in (int, float, long) or val <= 0:
raise ValueError(_("Capacity must be a positive number"))
newcap = int(val)
origcap = self.capacity
origall = self.allocation
self._capacity = newcap
if self.allocation is not None and (newcap < self.allocation):
self._allocation = newcap
ret = self.is_size_conflict()
if ret[0]:
self._capacity = origcap
self._allocation = origall
raise ValueError(ret[1])
elif ret[1]:
logging.warn(ret[1])
capacity = property(get_capacity, set_capacity)
def get_allocation(self):
return self._allocation
def set_allocation(self, val):
if type(val) not in (int, float, long) or val < 0:
raise ValueError(_("Allocation must be a non-negative number"))
newall = int(val)
if self.capacity is not None and newall > self.capacity:
logging.debug("Capping allocation at capacity.")
newall = self.capacity
origall = self._allocation
self._allocation = newall
ret = self.is_size_conflict()
if ret[0]:
self._allocation = origall
raise ValueError(ret[1])
elif ret[1]:
logging.warn(ret[1])
allocation = property(get_allocation, set_allocation)
def get_pool(self):
return self._pool
def set_pool(self, newpool):
if not isinstance(newpool, libvirt.virStoragePool):
raise ValueError(_("'pool' must be a virStoragePool instance."))
if newpool.info()[0] != libvirt.VIR_STORAGE_POOL_RUNNING:
raise ValueError(_("pool '%s' must be active." % newpool.name()))
self._pool = newpool
pool = property(get_pool, set_pool)
def get_input_vol(self):
return self._input_vol
def set_input_vol(self, vol):
if vol is None:
self._input_vol = None
return
if not isinstance(vol, libvirt.virStorageVol):
raise ValueError(_("input_vol must be a virStorageVol"))
poolconn = self.pool._conn # pylint: disable=W0212
if not is_create_vol_from_supported(poolconn):
raise ValueError(_("Creating storage from an existing volume is"
" not supported by this libvirt version."))
self._input_vol = vol
input_vol = property(get_input_vol, set_input_vol,
doc=_("virStorageVolume pointer to clone/use as "
"input."))
# Property functions used by more than one child class
def get_format(self):
return self._format
def set_format(self, val):
if val not in self.formats:
raise ValueError(_("'%s' is not a valid format.") % val)
self._format = val
def _check_name_collision(self, name):
vol = None
try:
vol = self.pool.storageVolLookupByName(name)
except libvirt.libvirtError:
pass
if vol:
raise ValueError(_("Name '%s' already in use by another volume." %
name))
def _check_target_collision(self, path):
col = None
try:
col = self.conn.storageVolLookupByPath(path)
except libvirt.libvirtError:
pass
if col:
return True
return False
# xml building functions
def _get_target_xml(self):
raise NotImplementedError()
def _get_source_xml(self):
raise NotImplementedError()
def _get_storage_xml(self):
src_xml = ""
if self._get_source_xml() != "":
src_xml = " <source>\n" + \
"%s" % (self._get_source_xml()) + \
" </source>\n"
tar_xml = " <target>\n" + \
"%s" % (self._get_target_xml()) + \
" </target>\n"
return " <capacity>%d</capacity>\n" % self.capacity + \
" <allocation>%d</allocation>\n" % self.allocation + \
"%s" % src_xml + \
"%s" % tar_xml
def install(self, meter=None):
"""
Build and install storage volume from xml
"""
xml = self.get_xml_config()
logging.debug("Creating storage volume '%s' with xml:\n%s",
self.name, xml)
t = threading.Thread(target=self._progress_thread,
name="Checking storage allocation",
args=(meter,))
t.setDaemon(True)
if not meter:
meter = urlgrabber.progress.BaseMeter()
try:
self._install_finished = False
t.start()
meter.start(size=self.capacity,
text=_("Allocating '%s'") % self.name)
if self.input_vol:
vol = self.pool.createXMLFrom(xml, self.input_vol, 0)
else:
vol = self.pool.createXML(xml, 0)
meter.end(self.capacity)
logging.debug("Storage volume '%s' install complete.",
self.name)
return vol
except libvirt.libvirtError, e:
if support.is_error_nosupport(e):
raise RuntimeError("Libvirt version does not support "
"storage cloning.")
raise
except Exception, e:
raise RuntimeError("Couldn't create storage volume "
"'%s': '%s'" % (self.name, str(e)))
finally:
self._install_finished = True
def _progress_thread(self, meter):
lookup_attempts = 10
vol = None
if not meter:
return
while lookup_attempts > 0:
try:
vol = self.pool.storageVolLookupByName(self.name)
break
except:
lookup_attempts -= 1
time.sleep(.2)
if self._install_finished:
break
else:
continue
break
if vol is None:
logging.debug("Couldn't lookup storage volume in prog thread.")
return
while not self._install_finished:
ignore, ignore, alloc = vol.info()
meter.update(alloc)
time.sleep(1)
def is_size_conflict(self):
"""
Report if requested size exceeds its pool's available amount
@returns: 2 element tuple:
1. True if collision is fatal, false otherwise
2. String message if some collision was encountered.
@rtype: 2 element C{tuple}: (C{bool}, C{str})
"""
# pool info is [pool state, capacity, allocation, available]
avail = self.pool.info()[3]
if self.allocation > avail:
return (True, _("There is not enough free space on the storage "
"pool to create the volume. "
"(%d M requested allocation > %d M available)" %
((self.allocation / (1024 * 1024)),
(avail / (1024 * 1024)))))
elif self.capacity > avail:
return (False, _("The requested volume capacity will exceed the "
"available pool space when the volume is fully "
"allocated. "
"(%d M requested capacity > %d M available)" %
((self.capacity / (1024 * 1024)),
(avail / (1024 * 1024)))))
return (False, "")
class FileVolume(StorageVolume):
"""
Build and install xml for use on pools which use file based storage
"""
_file_type = VIR_STORAGE_VOL_FILE
formats = ["raw", "bochs", "cloop", "cow", "dmg", "iso", "qcow",
"qcow2", "qed", "vmdk", "vpc"]
create_formats = ["raw", "cow", "qcow", "qcow2", "qed", "vmdk", "vpc"]
# Register applicable property methods from parent class
perms = property(StorageObject.get_perms, StorageObject.set_perms)
format = property(StorageVolume.get_format, StorageVolume.set_format)
def __init__(self, name, capacity, pool=None, pool_name=None, conn=None,
format="raw", allocation=None, perms=None):
# pylint: disable=W0622
# Redefining built-in 'format', but it matches the XML so keep it
StorageVolume.__init__(self, name=name, pool=pool, pool_name=pool_name,
allocation=allocation, capacity=capacity,
conn=conn)
self.format = format
if perms:
self.perms = perms
def _get_target_xml(self):
return " <format type='%s'/>\n" % self.format + \
"%s" % self._get_perms_xml()
def _get_source_xml(self):
return ""
class DiskVolume(StorageVolume):
"""
Build and install xml volumes for use on physical disk pools
"""
_file_type = VIR_STORAGE_VOL_BLOCK
# Register applicable property methods from parent class
perms = property(StorageObject.get_perms, StorageObject.set_perms)
def __init__(self, name, capacity, pool=None, pool_name=None, conn=None,
allocation=None, perms=None):
StorageVolume.__init__(self, name=name, pool=pool, pool_name=pool_name,
allocation=allocation, capacity=capacity,
conn=conn)
if perms:
self.perms = perms
def _get_target_xml(self):
return "%s" % self._get_perms_xml()
def _get_source_xml(self):
return ""
class LogicalVolume(StorageVolume):
"""
Build and install logical volumes for lvm pools
"""
_file_type = VIR_STORAGE_VOL_BLOCK
# Register applicable property methods from parent class
perms = property(StorageObject.get_perms, StorageObject.set_perms)
def __init__(self, name, capacity, pool=None, pool_name=None, conn=None,
allocation=None, perms=None):
if allocation and allocation != capacity:
logging.warn(_("Sparse logical volumes are not supported, "
"setting allocation equal to capacity"))
StorageVolume.__init__(self, name=name, pool=pool, pool_name=pool_name,
allocation=capacity, capacity=capacity,
conn=conn)
if perms:
self.perms = perms
def set_capacity(self, capacity):
super(LogicalVolume, self).set_capacity(capacity)
self.allocation = capacity
capacity = property(StorageVolume.get_capacity, set_capacity)
def set_allocation(self, allocation):
if allocation != self.capacity:
logging.warn(_("Sparse logical volumes are not supported, "
"setting allocation equal to capacity"))
super(LogicalVolume, self).set_allocation(self.capacity)
capacity = property(StorageVolume.get_allocation, set_allocation)
def _get_target_xml(self):
return "%s" % self._get_perms_xml()
def _get_source_xml(self):
return ""
class CloneVolume(StorageVolume):
"""
Build and install a volume that is a clone of an existing volume
"""
format = property(StorageVolume.get_format, StorageVolume.set_format)
def __init__(self, name, input_vol):
if not isinstance(input_vol, libvirt.virStorageVol):
raise ValueError(_("input_vol must be a virStorageVol"))
pool = input_vol.storagePoolLookupByVolume()
# Populate some basic info
xml = input_vol.XMLDesc(0)
typ = input_vol.info()[0]
cap = int(util.get_xml_path(xml, "/volume/capacity"))
alc = int(util.get_xml_path(xml, "/volume/allocation"))
fmt = util.get_xml_path(xml, "/volume/target/format/@type")
StorageVolume.__init__(self, name=name, pool=pool,
pool_name=pool.name(),
allocation=alc, capacity=cap)
self.input_vol = input_vol
self._file_type = typ
self._format = fmt
def _get_target_xml(self):
return ""
def _get_source_xml(self):
return ""
def get_xml_config(self):
xml = self.input_vol.XMLDesc(0)
newxml = util.set_xml_path(xml, "/volume/name", self.name)
return newxml
# class iSCSIVolume(StorageVolume):
# """
# Build and install xml for use on iSCSI device pools
# """
# _file_type = VIR_STORAGE_VOL_BLOCK
#
# def __init__(self, *args, **kwargs):
# raise NotImplementedError
|
Quick access to the heavy equipment information you need!
Customer Portal for Heavy Equipment, Parts & Service | Kirby Smith Machinery, Inc.
Whether you are in the field, at the shop or out to dinner, you can log into your MyDealer customer portal account at your convenience.
Kirby-Smith Machinery has been serving the equipment needs of our customers for over 30 years with quality products and services. As a full-service dealer, we strive to provide our customers with the most efficient and effective ways to work with our company. With MyDealer, we can extend our customer service further by offering around-the-clock access to your account and equipment information online.
Quickly find specific details about your current equipment!
The My Equipment detail screen gives you everything you need to know about your equipment – make, model, description, service history and more. You can even create new service appointments.
Easily review past or current invoices to stay up-to-date!
My Invoices gives you access to outstanding invoices, with the ability to see your history and aging and view a copy of the actual invoice details. Easily download and print outstanding and/or paid invoices, statements and quotes.
Fast access to important rental information!
The My Rentals screen allows you to view details for the equipment you’ve rented. You can seamlessly request service online or call Kirby-Smith directly.
Get real-time updates on trending information from your dealership!
Stay informed about what’s going on at your assigned Kirby-Smith Machinery dealership and be the first to know about our latest news and promotions.
Ready to buy or rent your next piece of equipment? Find it here!
Browse our available inventory and see what we have ready to sell. With only a few taps of a finger you can see what is available for sale and for rent at various Kirby-Smith Machinery branch locations.
Review our extensive parts inventory to find exactly what you need!
Quickly search for parts, including substitution information if required, and easily view custom shopping lists and prior orders. Not done shopping? No problem! The shopping cart can be saved for processing at a later time. Checkout process includes Google mapping directly to the pick-up location.
|
# Copyright 2016 - Nokia.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from django.urls import reverse
from django.urls import reverse_lazy
from django.utils.translation import ugettext_lazy as _
from django.views import generic
from horizon import forms
from horizon import tables
from mistraldashboard.action_executions import forms as action_execution_forms
from mistraldashboard.action_executions import tables as mistral_tables
from mistraldashboard import api
from mistraldashboard.default import utils
from mistraldashboard import forms as mistral_forms
def get_single_action_execution_data(request, **kwargs):
action_execution_id = kwargs['action_execution_id']
action_execution = api.action_execution_get(
request,
action_execution_id
)
return action_execution
class OverviewView(generic.TemplateView):
template_name = 'mistral/action_executions/detail.html'
page_title = _("Action Execution Details")
workflow_url = 'horizon:mistral:workflows:detail'
task_execution_url = 'horizon:mistral:tasks:detail'
def get_context_data(self, **kwargs):
context = super(OverviewView, self).get_context_data(**kwargs)
action_execution = get_single_action_execution_data(
self.request,
**kwargs
)
if action_execution.workflow_name:
action_execution.workflow_url = reverse(
self.workflow_url,
args=[action_execution.workflow_name])
if action_execution.task_execution_id:
action_execution.task_execution_url = reverse(
self.task_execution_url,
args=[action_execution.task_execution_id]
)
if action_execution.input:
action_execution.input = utils.prettyprint(action_execution.input)
if action_execution.output:
action_execution.output = utils.prettyprint(
action_execution.output
)
if action_execution.state:
action_execution.state = utils.label(action_execution.state)
action_execution.accepted = utils.booleanfield(
action_execution.accepted
)
breadcrumb = [(action_execution.id, reverse(
'horizon:mistral:action_executions:detail',
args=[action_execution.id]
))]
context["custom_breadcrumb"] = breadcrumb
context['action_execution'] = action_execution
return context
class CodeView(forms.ModalFormView):
template_name = 'mistral/default/code.html'
modal_header = _("Code view")
form_id = "code_view"
form_class = mistral_forms.EmptyForm
cancel_label = "OK"
cancel_url = reverse_lazy("horizon:mistral:action_executions:index")
page_title = _("Code view")
def get_context_data(self, **kwargs):
context = super(CodeView, self).get_context_data(**kwargs)
column = self.kwargs['column']
action_execution = get_single_action_execution_data(
self.request,
**self.kwargs
)
io = {}
if column == 'input':
io['name'] = _('Input')
io['value'] = utils.prettyprint(action_execution.input)
elif column == 'output':
io['name'] = _('Output')
io['value'] = (
utils.prettyprint(action_execution.output)
if action_execution.output
else _("No available output yet")
)
context['io'] = io
return context
class IndexView(tables.DataTableView):
table_class = mistral_tables.ActionExecutionsTable
template_name = 'mistral/action_executions/index.html'
def get_data(self):
return api.action_executions_list(self.request)
class UpdateView(forms.ModalFormView):
template_name = 'mistral/action_executions/update.html'
modal_header = _("Update Action Execution")
form_id = "update_action_execution"
form_class = action_execution_forms.UpdateForm
submit_label = _("Update")
success_url = reverse_lazy("horizon:mistral:action_executions:index")
submit_url = "horizon:mistral:action_executions:update"
cancel_url = "horizon:mistral:action_executions:index"
page_title = _("Update Action Execution")
def get_initial(self):
return {"action_execution_id": self.kwargs["action_execution_id"]}
def get_context_data(self, **kwargs):
context = super(UpdateView, self).get_context_data(**kwargs)
context['submit_url'] = reverse(
self.submit_url,
args=[self.kwargs["action_execution_id"]]
)
return context
class FilteredByTaskView(tables.DataTableView):
table_class = mistral_tables.ActionExecutionsTable
template_name = 'mistral/action_executions/filtered.html'
data = {}
def get_data(self, **kwargs):
task_id = self.kwargs['task_id']
data = api.action_executions_list(self.request, task_id)
return data
|
Wikipedia on Quantization, Wikipedia on Sampling, Wikipedia on Sampling Rate, and Wikipedia on Nyquists's Theorem (everything past the first two paragraphs on Nyquist's Theorem is too advanced for this class's subject matter).
Note that Lab 2 is due April 18!
Read about Decimal, Binary, Octal, and Hexadecimal in the TCP guide.
Read about Boolean and Logical Functions in the TCP guide.
Note that Lab 1 is due April 9!
Familiarize yourself with the TCP guide and how to navigate it.
Be ready to google things like "MAC address tutorial" or "Wikipedia LAN"
Your grade will come from the weekly quizzes (30%), the class exercises--exercises having to do with networking(20%), and your final exam (40%) and a fudge factor forclass participation via sections and the forum (10%). Your weekly quizzes will cover the material listed in the assignments section of this website and will be heavily hinted on during Tuesday lecture. Your quiz grade will be derived from your best 7 quizzes, but there will be no makeup quizzes. If this is a quarter in which you can't make it to class for at least 7/10 Thursdays, this is not a good class for you to take this quarter.
|
# -*- coding: utf-8 -*-
"""Copyright (c) 2009-2012 Sergio Gabriel Teves
All rights reserved.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import os
import os.path
import string
from django.utils.translation import ugettext as _
from django.utils.encoding import smart_text
import versioncontrol.lib.browser as browser
from versioncontrol.lib.support import svnclient
import logging
logger = logging.getLogger('vertaal.vcs')
def need_repo(fn):
def repo_fn(self, *args, **kw):
try:
info = self.client.info()
if self.client.parseurl(info['url']) <> self.client.parseurl(self.url):
self._switch_url()
except svnclient.ClientError:
self.init_repo()
return fn(self, *args, **kw)
return repo_fn
def need_update(fn):
def repo_fn(self, *args, **kw):
self.update()
return fn(self, *args, **kw)
return repo_fn
def encode_text(text, encoding='utf-8'):
xv = filter(lambda x: x in string.printable, text)
return smart_text(xv, encoding=encoding)
# try:
# return smart_text(text, encoding=encoding)
# except UnicodeDecodeError:
# xv = filter(lambda x: x in string.printable, text)
# return smart_text(xv, encoding=encoding)
class SubversionBrowser(browser.RepositoryBrowser):
update_completed = 'update'
relocate_error_msg = 'is already a working copy for a different URL'
def __init__(self, location, url, folder, branch='trunk', auth=None):
super(SubversionBrowser, self).__init__(location, url, folder, branch, auth)
self.client = svnclient.Client(location=self._normalizePath(location))
self.client.set_trust_server_cert(True)
if auth:
self.set_login(auth)
self.relocated = False
def set_login(self, auth):
self.client.set_username(auth.get_user())
self.client.set_password(auth.get_password())
def _notify(self, arg_dict):
msg = None
try:
logger.debug(arg_dict)
if arg_dict['action'] == self.update_completed:
msg = _('At revision %s.') % arg_dict['revision']
elif arg_dict.has_key('path'):
if arg_dict['action'] == svnclient.notify_action.added:
self._send_callback(self.callback_on_file_add,arg_dict['path'])
elif arg_dict['action'] == svnclient.notify_action.deleted:
self._send_callback(self.callback_on_file_delete,arg_dict['path'])
elif arg_dict['action'] == svnclient.notify_action.updated:
self._send_callback(self.callback_on_file_update,arg_dict['path'])
elif arg_dict['action'] == svnclient.notify_action.replaced:
self._send_callback(self.callback_on_file_update,arg_dict['path'])
msg = '%s %s' % (arg_dict['action'], os.path.basename(arg_dict['path']))
except KeyError:
logger.error(arg_dict)
if msg:
self._send_callback(self.callback_on_action_notify, msg)
def _parse_event_list(self, eventList):
for event in eventList:
self._notify(event)
@property
def _remote_path(self):
if self.branch == u'trunk':
repo_path = self.branch
else:
repo_path = "branches/%s" % self.branch
return "%s/%s" % (repo_path, self.folder)
def _switch_url(self):
current_url = self.client.parseurl(self.client.get_remote_url())
new_url = self.client.parseurl(self.url)
self._send_callback(self.callback_on_action_notify,
_('URL has changed. Relocate from %(prior)s to %(actual)s')
% {'prior': current_url,
'actual': new_url})
self.client.relocate(current_url, new_url)
def _normalizePath(self, path):
return os.path.normpath(os.path.normcase(path));
def init_repo(self):
logger.debug("init")
self._send_callback(self.callback_on_action_notify,_('Initializing repository %s') % self._remote_path)
try:
logger.debug("check path %s" % self.location)
info = self.client.info()
if self.client.parseurl(info['url']) <> self.client.parseurl(self.url):
self._switch_url()
except svnclient.ClientError, e:
logger.debug(e)
logger.debug("Checkout %s on %s" % (self.url + self._remote_path, self.location))
rev = 0
try:
rev, eventList = self.client.checkout(url = self.url + self._remote_path)
self._parse_event_list(eventList)
except svnclient.ClientError, e:
# TODO handle relocate error more effectivly
if e.message.find(self.relocate_error_msg):
logger.debug("Must relocate")
self._switch_url()
rev = self.update()
else:
raise
logger.debug("end")
self._notify({'action': self.update_completed, 'revision': rev})
return rev
@need_repo
def cleanup(self):
self.client.cleanup()
@need_repo
def update(self):
self.cleanup()
self._send_callback(self.callback_on_action_notify,_('Updating repository %s') % self._remote_path)
rev = 0
try:
rev, eventList = self.client.update(force=True)
self._parse_event_list(eventList)
except svnclient.ClientError, e:
#if self._checkerror(e, 155000): # relocate
logger.debug("Must relocate")
self._switch_url()
rev, eventList = self.client.update(force=True)
self._parse_event_list(eventList)
self._notify({'action': self.update_completed, 'revision': rev})
return rev
@need_repo
def revert(self, path=None):
try:
if path is not None:
self.client.revert([path])
else:
filelist = self.client.status()
if filelist is not None:
files = []
for event in filelist:
files.append(event['path'])
self.client.revert(files)
except Exception, e:
logger.error("Revert %s failed: %s" % (self.location, str(e)))
pass
def _checkin(self, msg):
filelist = self.client.status()
files = []
if filelist is not None:
for event in filelist:
if event['action'] == svnclient.notify_action.noadded:
files.append(event['path'])
if len(files) > 0:
self.client.add(files)
rev = self.client.commit(message=encode_text(msg))
return rev
def submit(self, auth, files, msg):
if auth:
self.set_login(auth)
logger.debug("Perform submit %s (%s) [%s]" % (self.location, files, msg))
self._send_callback(self.callback_on_action_notify,_('Checking in'))
rev = 0
try:
rev = self._checkin(msg)
except svnclient.ClientError, e:
logger.debug(str(e))
logger.warn(str(e))
self.cleanup()
try:
rev = self._checkin(msg)
except:
raise
except:
raise
self._notify({'action': self.update_completed, 'revision': rev})
return rev
|
Take a look at these wide-ranging variety of metal wall art meant for wall artwork, photography, and more to obtain the ideal decor to your room. We realize that metal wall art differs in size, frame type, shape, price, and design, so you're able to choose plasma cut metal wall art that complete your interior and your personal sense of style. You will discover everything from contemporary wall art to vintage wall artwork, in order to be assured that there surely is something you'll enjoy and correct for your room.
We always have many options regarding metal wall art for your home, as well as plasma cut metal wall art. Make sure anytime you are searching for where to purchase metal wall art over the internet, you find the right options, how the simplest way must you select an ideal metal wall art for your house? Below are a few photos that could help: get as many ideas as you possibly can before you buy, go with a scheme that will not express mismatch along your wall and make certain that you adore it to pieces.
Do not be excessively reckless when choosing metal wall art and explore several stores as you can. Probably you'll find better and more appealing creations than that selection you checked at that first store you went to. Moreover, really don't limit yourself. Whenever there are actually just a small number of stores or galleries around the town where you reside, you could start to take to browsing online. You will find loads of online artwork galleries having numerous plasma cut metal wall art you may select from.
Concerning the most used artwork items which can be apt for your interior are plasma cut metal wall art, picture prints, or art paints. Additionally, there are wall sculptures and bas-relief, which may look similar to 3D artworks compared to sculptures. Also, if you have most popular artist, possibly he or she has a webpage and you are able to always check and shop their products via online. There are also designers that offer electronic copies of the works and you available to only have printed out.
One more point you have to keep in mind in selecting metal wall art is that it should never inharmonious together with your wall or in general interior decoration. Understand that you are getting these art parts for you to boost the aesthetic appeal of your home, perhaps not create chaos on it. You possibly can pick something that may involve some comparison but do not pick one that is extremely at chances with the decoration.
It's not necessary to purchase metal wall art just because a some artist or friend said it truly is good. One thing that we often hear is that beauty will be subjective. Whatever may possibly look amazing to other people may not necessarily be the type of thing that you like. The best qualification you should use in purchasing plasma cut metal wall art is whether thinking about it makes you're feeling comfortable or excited, or not. When it does not impress your feelings, then it may be better you find at other metal wall art. After all, it will be for your home, perhaps not theirs, therefore it's great you move and select something which appeals to you.
Nothing changes a interior such as for instance a lovely little bit of plasma cut metal wall art. A watchfully opted for poster or print may elevate your environments and change the sensation of a space. But how will you discover the good item? The metal wall art will be as unique as individuals design. This means there are hassle-free and rapidly principles to choosing metal wall art for the house, it really must be something you prefer.
Once you discover the parts of metal wall art you love designed to compatible splendidly with your decoration, whether that is coming from a famous artwork gallery or others, do not let your enthusiasm get the higher of you and hang the piece the moment it arrives. That you do not desire to get a wall filled with holes. Plan first where it'd place.
Whatever room or living area that you're remodelling, the plasma cut metal wall art has figures that'll fit what you want. Have a look at a large number of images to develop into prints or posters, featuring common themes for example panoramas, landscapes, culinary, animals, city skylines, and abstract compositions. With the addition of groupings of metal wall art in different shapes and dimensions, along with different wall art, we included interest and identity to the room.
Have you been trying to find approaches to beautify your space? Art stands out as an excellent solution for tiny or huge places likewise, offering any interior a completed and polished visual appearance in minutes. If you need ideas for designing your space with plasma cut metal wall art before you get your goods, you can look for our useful ideas and guide on metal wall art here.
There's lots of alternate options of plasma cut metal wall art you will see here. Every single metal wall art has a unique style and characteristics in which pull art fans in to the variety. Interior decor including wall art, interior accents, and wall mirrors - can easily enhance and carry personal preference to a room. These produce for great family room, workspace, or bedroom artwork pieces!
When you are prepared create your plasma cut metal wall art also know just what you are looking, you can actually browse through our different selection of metal wall art to find the perfect piece for your home. No matter if you need bedroom artwork, dining room artwork, or any interior in between, we've acquired what you would like to go your home in to a wonderfully designed space. The current artwork, classic art, or reproductions of the classics you like are just a click away.
|
#
# Copyright (C) 2016 UAVCAN Development Team <uavcan.org>
#
# This software is distributed under the terms of the MIT License.
#
# Author: Pavel Kirienko <[email protected]>
#
import time
import uavcan
import logging
import queue
from PyQt5.QtWidgets import QWidget, QDialog, QPlainTextEdit, QSpinBox, QHBoxLayout, QVBoxLayout, QComboBox, \
QCompleter, QLabel
from PyQt5.QtCore import Qt, QTimer
from . import CommitableComboBoxWithHistory, make_icon_button, get_monospace_font, show_error, FilterBar
logger = logging.getLogger(__name__)
class QuantityDisplay(QWidget):
def __init__(self, parent, quantity_name, units_of_measurement):
super(QuantityDisplay, self).__init__(parent)
self._label = QLabel('?', self)
layout = QHBoxLayout(self)
layout.addStretch(1)
layout.addWidget(QLabel(quantity_name, self))
layout.addWidget(self._label)
layout.addWidget(QLabel(units_of_measurement, self))
layout.addStretch(1)
layout.setContentsMargins(0, 0, 0, 0)
self.setLayout(layout)
def set(self, value):
self._label.setText(str(value))
class RateEstimator:
def __init__(self, update_interval=0.5, averaging_period=4):
self._update_interval = update_interval
self._estimate_lifetime = update_interval * averaging_period
self._averaging_period = averaging_period
self._hist = []
self._checkpoint_ts = 0
self._events_since_checkpoint = 0
self._estimate_expires_at = time.monotonic()
def register_event(self, timestamp):
self._events_since_checkpoint += 1
dt = timestamp - self._checkpoint_ts
if dt >= self._update_interval:
# Resetting the stat if expired
mono_ts = time.monotonic()
expired = mono_ts > self._estimate_expires_at
self._estimate_expires_at = mono_ts + self._estimate_lifetime
if expired:
self._hist = []
elif len(self._hist) >= self._averaging_period:
self._hist.pop()
# Updating the history
self._hist.insert(0, self._events_since_checkpoint / dt)
self._checkpoint_ts = timestamp
self._events_since_checkpoint = 0
def get_rate_with_timestamp(self):
if time.monotonic() <= self._estimate_expires_at:
return (sum(self._hist) / len(self._hist)), self._checkpoint_ts
class SubscriberWindow(QDialog):
WINDOW_NAME_PREFIX = 'Subscriber'
def __init__(self, parent, node, active_data_type_detector):
super(SubscriberWindow, self).__init__(parent)
self.setWindowTitle(self.WINDOW_NAME_PREFIX)
self.setAttribute(Qt.WA_DeleteOnClose) # This is required to stop background timers!
self._node = node
self._active_data_type_detector = active_data_type_detector
self._active_data_type_detector.message_types_updated.connect(self._update_data_type_list)
self._message_queue = queue.Queue()
self._subscriber_handle = None
self._update_timer = QTimer(self)
self._update_timer.setSingleShot(False)
self._update_timer.timeout.connect(self._do_redraw)
self._update_timer.start(100)
self._log_viewer = QPlainTextEdit(self)
self._log_viewer.setReadOnly(True)
self._log_viewer.setLineWrapMode(QPlainTextEdit.NoWrap)
self._log_viewer.setFont(get_monospace_font())
self._log_viewer.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
try:
self._log_viewer.setPlaceholderText('Received messages will be printed here in YAML format')
except AttributeError: # Old PyQt
pass
self._num_rows_spinbox = QSpinBox(self)
self._num_rows_spinbox.setToolTip('Number of rows to display; large number will impair performance')
self._num_rows_spinbox.valueChanged.connect(
lambda: self._log_viewer.setMaximumBlockCount(self._num_rows_spinbox.value()))
self._num_rows_spinbox.setMinimum(1)
self._num_rows_spinbox.setMaximum(1000000)
self._num_rows_spinbox.setValue(100)
self._num_errors = 0
self._num_messages_total = 0
self._num_messages_past_filter = 0
self._msgs_per_sec_estimator = RateEstimator()
self._num_messages_total_label = QuantityDisplay(self, 'Total', 'msgs')
self._num_messages_past_filter_label = QuantityDisplay(self, 'Accepted', 'msgs')
self._msgs_per_sec_label = QuantityDisplay(self, 'Accepting', 'msg/sec')
self._type_selector = CommitableComboBoxWithHistory(self)
self._type_selector.setToolTip('Name of the message type to subscribe to')
self._type_selector.setInsertPolicy(QComboBox.NoInsert)
completer = QCompleter(self._type_selector)
completer.setCaseSensitivity(Qt.CaseSensitive)
completer.setModel(self._type_selector.model())
self._type_selector.setCompleter(completer)
self._type_selector.on_commit = self._do_start
self._type_selector.setFont(get_monospace_font())
self._type_selector.setSizeAdjustPolicy(QComboBox.AdjustToContents)
self._type_selector.setFocus(Qt.OtherFocusReason)
self._active_filter = None
self._filter_bar = FilterBar(self)
self._filter_bar.on_filter = self._install_filter
self._start_stop_button = make_icon_button('video-camera', 'Begin subscription', self, checkable=True,
on_clicked=self._toggle_start_stop)
self._pause_button = make_icon_button('pause', 'Pause updates, non-displayed messages will be queued in memory',
self, checkable=True)
self._clear_button = make_icon_button('trash-o', 'Clear output and reset stat counters', self,
on_clicked=self._do_clear)
self._show_all_message_types = make_icon_button('puzzle-piece',
'Show all known message types, not only those that are '
'currently being exchanged over the bus',
self, checkable=True, on_clicked=self._update_data_type_list)
layout = QVBoxLayout(self)
controls_layout = QHBoxLayout(self)
controls_layout.addWidget(self._start_stop_button)
controls_layout.addWidget(self._pause_button)
controls_layout.addWidget(self._clear_button)
controls_layout.addWidget(self._filter_bar.add_filter_button)
controls_layout.addWidget(self._show_all_message_types)
controls_layout.addWidget(self._type_selector, 1)
controls_layout.addWidget(self._num_rows_spinbox)
layout.addLayout(controls_layout)
layout.addWidget(self._filter_bar)
layout.addWidget(self._log_viewer, 1)
stats_layout = QHBoxLayout(self)
stats_layout.addWidget(self._num_messages_total_label)
stats_layout.addWidget(self._num_messages_past_filter_label)
stats_layout.addWidget(self._msgs_per_sec_label)
layout.addLayout(stats_layout)
self.setLayout(layout)
# Initial updates
self._update_data_type_list()
def _install_filter(self, f):
self._active_filter = f
def _apply_filter(self, yaml_message):
"""This function will throw if the filter expression is malformed!"""
if self._active_filter is None:
return True
return self._active_filter.match(yaml_message)
def _on_message(self, e):
# Global statistics
self._num_messages_total += 1
# Rendering and filtering
try:
text = uavcan.to_yaml(e)
if not self._apply_filter(text):
return
except Exception as ex:
self._num_errors += 1
text = '!!! [%d] MESSAGE PROCESSING FAILED: %s' % (self._num_errors, ex)
else:
self._num_messages_past_filter += 1
self._msgs_per_sec_estimator.register_event(e.transfer.ts_monotonic)
# Sending the text for later rendering
try:
self._message_queue.put_nowait(text)
except queue.Full:
pass
def _toggle_start_stop(self):
try:
if self._subscriber_handle is None:
self._do_start()
else:
self._do_stop()
finally:
self._start_stop_button.setChecked(self._subscriber_handle is not None)
def _do_stop(self):
if self._subscriber_handle is not None:
self._subscriber_handle.remove()
self._subscriber_handle = None
self._pause_button.setChecked(False)
self.setWindowTitle(self.WINDOW_NAME_PREFIX)
def _do_start(self):
self._do_stop()
self._do_clear()
try:
selected_type = self._type_selector.currentText().strip()
if not selected_type:
return
data_type = uavcan.TYPENAMES[selected_type]
except Exception as ex:
show_error('Subscription error', 'Could not load requested data type', ex, self)
return
try:
self._subscriber_handle = self._node.add_handler(data_type, self._on_message)
except Exception as ex:
show_error('Subscription error', 'Could not create requested subscription', ex, self)
return
self.setWindowTitle('%s [%s]' % (self.WINDOW_NAME_PREFIX, selected_type))
self._start_stop_button.setChecked(True)
def _do_redraw(self):
self._num_messages_total_label.set(self._num_messages_total)
self._num_messages_past_filter_label.set(self._num_messages_past_filter)
estimated_rate = self._msgs_per_sec_estimator.get_rate_with_timestamp()
self._msgs_per_sec_label.set('N/A' if estimated_rate is None else ('%.0f' % estimated_rate[0]))
if self._pause_button.isChecked():
return
self._log_viewer.setUpdatesEnabled(False)
while True:
try:
text = self._message_queue.get_nowait()
except queue.Empty:
break
else:
self._log_viewer.appendPlainText(text + '\n')
self._log_viewer.setUpdatesEnabled(True)
def _update_data_type_list(self):
logger.info('Updating data type list')
if self._show_all_message_types.isChecked():
items = self._active_data_type_detector.get_names_of_all_message_types_with_data_type_id()
else:
items = self._active_data_type_detector.get_names_of_active_messages()
self._type_selector.clear()
self._type_selector.addItems(items)
def _do_clear(self):
self._num_messages_total = 0
self._num_messages_past_filter = 0
self._do_redraw()
self._log_viewer.clear()
def closeEvent(self, qcloseevent):
try:
self._subscriber_handle.close()
except Exception:
pass
super(SubscriberWindow, self).closeEvent(qcloseevent)
@staticmethod
def spawn(parent, node, active_data_type_detector):
SubscriberWindow(parent, node, active_data_type_detector).show()
|
Stunning crystal topaz rosary bracelet with a cross and a miraculous medal. The miraculous centerpiece depicting Our Lady of Grace. On the reverse, 12 stars surround a large "M," from which a cross arises.
|
#!/usr/bin/env python
#
# Electrum - lightweight Bitcoin client
# Copyright (C) 2012 thomasv@gitorious
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import sys, time, datetime, re, threading
from electrum_frc.i18n import _, set_language
from electrum_frc.util import print_error, print_msg
import os.path, json, ast, traceback
import webbrowser
import shutil
import StringIO
import PyQt4
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import PyQt4.QtCore as QtCore
from electrum_frc.bitcoin import MIN_RELAY_TX_FEE, is_valid
from electrum_frc.plugins import run_hook
import icons_rc
from electrum_frc.util import format_satoshis, NotEnoughFunds
from electrum_frc import Transaction
from electrum_frc import mnemonic
from electrum_frc import util, bitcoin, commands, Interface, Wallet
from electrum_frc import SimpleConfig, Wallet, WalletStorage
from electrum_frc import Imported_Wallet
from amountedit import AmountEdit, BTCAmountEdit, MyLineEdit
from network_dialog import NetworkDialog
from qrcodewidget import QRCodeWidget, QRDialog
from qrtextedit import ScanQRTextEdit, ShowQRTextEdit
from decimal import Decimal
import httplib
import socket
import webbrowser
import csv
from electrum_frc import ELECTRUM_VERSION
import re
from util import MyTreeWidget, HelpButton, EnterButton, line_dialog, text_dialog, ok_cancel_buttons, close_button, WaitingDialog
from util import filename_field, ok_cancel_buttons2, address_field
from util import MONOSPACE_FONT
class StatusBarButton(QPushButton):
def __init__(self, icon, tooltip, func):
QPushButton.__init__(self, icon, '')
self.setToolTip(tooltip)
self.setFlat(True)
self.setMaximumWidth(25)
self.clicked.connect(func)
self.func = func
self.setIconSize(QSize(25,25))
def keyPressEvent(self, e):
if e.key() == QtCore.Qt.Key_Return:
apply(self.func,())
default_column_widths = {
"history":[40,140,350,140],
"contacts":[350,330],
"receive": [370,200,130]
}
# status of payment requests
PR_UNPAID = 0
PR_EXPIRED = 1
PR_SENT = 2 # sent but not propagated
PR_PAID = 3 # send and propagated
PR_ERROR = 4 # could not parse
pr_icons = {
PR_UNPAID:":icons/unpaid.png",
PR_PAID:":icons/confirmed.png",
PR_EXPIRED:":icons/expired.png"
}
pr_tooltips = {
PR_UNPAID:_('Unpaid'),
PR_PAID:_('Paid'),
PR_EXPIRED:_('Expired')
}
class ElectrumWindow(QMainWindow):
labelsChanged = pyqtSignal()
def __init__(self, config, network, gui_object):
QMainWindow.__init__(self)
self.config = config
self.network = network
self.gui_object = gui_object
self.tray = gui_object.tray
self.go_lite = gui_object.go_lite
self.lite = None
self.create_status_bar()
self.need_update = threading.Event()
self.decimal_point = config.get('decimal_point', 8)
self.num_zeros = int(config.get('num_zeros',0))
self.invoices = {}
self.completions = QStringListModel()
self.tabs = tabs = QTabWidget(self)
self.column_widths = self.config.get("column_widths_2", default_column_widths )
tabs.addTab(self.create_history_tab(), _('History') )
tabs.addTab(self.create_send_tab(), _('Send') )
tabs.addTab(self.create_receive_tab(), _('Receive') )
tabs.addTab(self.create_addresses_tab(), _('Addresses') )
tabs.addTab(self.create_contacts_tab(), _('Contacts') )
tabs.addTab(self.create_invoices_tab(), _('Invoices') )
tabs.addTab(self.create_console_tab(), _('Console') )
tabs.setMinimumSize(600, 400)
tabs.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
self.setCentralWidget(tabs)
try:
self.setGeometry(*self.config.get("winpos-qt"))
except:
self.setGeometry(100, 100, 840, 400)
if self.config.get("is_maximized"):
self.showMaximized()
self.setWindowIcon(QIcon(":icons/electrum.png"))
self.init_menubar()
QShortcut(QKeySequence("Ctrl+W"), self, self.close)
QShortcut(QKeySequence("Ctrl+Q"), self, self.close)
QShortcut(QKeySequence("Ctrl+R"), self, self.update_wallet)
QShortcut(QKeySequence("Ctrl+PgUp"), self, lambda: tabs.setCurrentIndex( (tabs.currentIndex() - 1 )%tabs.count() ))
QShortcut(QKeySequence("Ctrl+PgDown"), self, lambda: tabs.setCurrentIndex( (tabs.currentIndex() + 1 )%tabs.count() ))
for i in range(tabs.count()):
QShortcut(QKeySequence("Alt+" + str(i + 1)), self, lambda i=i: tabs.setCurrentIndex(i))
self.connect(self, QtCore.SIGNAL('update_status'), self.update_status)
self.connect(self, QtCore.SIGNAL('banner_signal'), lambda: self.console.showMessage(self.network.banner) )
self.connect(self, QtCore.SIGNAL('transaction_signal'), lambda: self.notify_transactions() )
self.connect(self, QtCore.SIGNAL('payment_request_ok'), self.payment_request_ok)
self.connect(self, QtCore.SIGNAL('payment_request_error'), self.payment_request_error)
self.labelsChanged.connect(self.update_tabs)
self.history_list.setFocus(True)
# network callbacks
if self.network:
self.network.register_callback('updated', lambda: self.need_update.set())
self.network.register_callback('banner', lambda: self.emit(QtCore.SIGNAL('banner_signal')))
self.network.register_callback('status', lambda: self.emit(QtCore.SIGNAL('update_status')))
self.network.register_callback('new_transaction', lambda: self.emit(QtCore.SIGNAL('transaction_signal')))
self.network.register_callback('stop', self.close)
# set initial message
self.console.showMessage(self.network.banner)
self.wallet = None
self.payment_request = None
self.qr_window = None
self.not_enough_funds = False
self.pluginsdialog = None
def update_account_selector(self):
# account selector
accounts = self.wallet.get_account_names()
self.account_selector.clear()
if len(accounts) > 1:
self.account_selector.addItems([_("All accounts")] + accounts.values())
self.account_selector.setCurrentIndex(0)
self.account_selector.show()
else:
self.account_selector.hide()
def close_wallet(self):
self.wallet.stop_threads()
self.hide()
run_hook('close_wallet')
def load_wallet(self, wallet):
import electrum_frc
self.wallet = wallet
self.update_wallet_format()
# address used to create a dummy transaction and estimate transaction fee
a = self.wallet.addresses(False)
self.dummy_address = a[0] if a else None
self.invoices = self.wallet.storage.get('invoices', {})
self.accounts_expanded = self.wallet.storage.get('accounts_expanded',{})
self.current_account = self.wallet.storage.get("current_account", None)
title = 'Electrum-FRC ' + self.wallet.electrum_version + ' - ' + os.path.basename(self.wallet.storage.path)
if self.wallet.is_watching_only(): title += ' [%s]' % (_('watching only'))
self.setWindowTitle( title )
self.update_history_tab()
self.show()
self.update_wallet()
# Once GUI has been initialized check if we want to announce something since the callback has been called before the GUI was initialized
self.notify_transactions()
self.update_account_selector()
# update menus
self.new_account_menu.setEnabled(self.wallet.can_create_accounts())
self.private_keys_menu.setEnabled(not self.wallet.is_watching_only())
self.password_menu.setEnabled(self.wallet.can_change_password())
self.seed_menu.setEnabled(self.wallet.has_seed())
self.mpk_menu.setEnabled(self.wallet.is_deterministic())
self.import_menu.setEnabled(self.wallet.can_import())
self.export_menu.setEnabled(self.wallet.can_export())
self.update_lock_icon()
self.update_buttons_on_seed()
self.update_console()
self.clear_receive_tab()
self.update_receive_tab()
run_hook('load_wallet', wallet)
def update_wallet_format(self):
# convert old-format imported keys
if self.wallet.imported_keys:
password = self.password_dialog(_("Please enter your password in order to update imported keys"))
try:
self.wallet.convert_imported_keys(password)
except:
self.show_message("error")
def open_wallet(self):
wallet_folder = self.wallet.storage.path
filename = unicode( QFileDialog.getOpenFileName(self, "Select your wallet file", wallet_folder) )
if not filename:
return
try:
storage = WalletStorage({'wallet_path': filename})
except Exception as e:
self.show_message(str(e))
return
if not storage.file_exists:
self.show_message(_("File not found") + ' ' + filename)
return
# read wizard action
try:
wallet = Wallet(storage)
except BaseException as e:
QMessageBox.warning(None, _('Warning'), str(e), _('OK'))
return
action = wallet.get_action()
# ask for confirmation
if action is not None:
if not self.question(_("This file contains an incompletely created wallet.\nDo you want to complete its creation now?")):
return
# close current wallet
self.close_wallet()
# run wizard
if action is not None:
import installwizard
wizard = installwizard.InstallWizard(self.config, self.network, storage)
try:
wallet = wizard.run(action)
except BaseException as e:
traceback.print_exc(file=sys.stdout)
QMessageBox.information(None, _('Error'), str(e), _('OK'))
return
if not wallet:
return
else:
wallet.start_threads(self.network)
# load new wallet in gui
self.load_wallet(wallet)
def backup_wallet(self):
import shutil
path = self.wallet.storage.path
wallet_folder = os.path.dirname(path)
filename = unicode( QFileDialog.getSaveFileName(self, _('Enter a filename for the copy of your wallet'), wallet_folder) )
if not filename:
return
new_path = os.path.join(wallet_folder, filename)
if new_path != path:
try:
shutil.copy2(path, new_path)
QMessageBox.information(None,"Wallet backup created", _("A copy of your wallet file was created in")+" '%s'" % str(new_path))
except (IOError, os.error), reason:
QMessageBox.critical(None,"Unable to create backup", _("Electrum-FRC was unable to copy your wallet file to the specified location.")+"\n" + str(reason))
def new_wallet(self):
import installwizard
wallet_folder = os.path.dirname(os.path.abspath(self.wallet.storage.path))
i = 1
while True:
filename = "wallet_%d"%i
if filename in os.listdir(wallet_folder):
i += 1
else:
break
filename = line_dialog(self, _('New Wallet'), _('Enter file name') + ':', _('OK'), filename)
if not filename:
return
full_path = os.path.join(wallet_folder, filename)
storage = WalletStorage({'wallet_path': full_path})
if storage.file_exists:
QMessageBox.critical(None, "Error", _("File exists"))
return
if self.wallet:
self.close_wallet()
wizard = installwizard.InstallWizard(self.config, self.network, storage)
wallet = wizard.run('new')
if wallet:
self.load_wallet(wallet)
def init_menubar(self):
menubar = QMenuBar()
file_menu = menubar.addMenu(_("&File"))
file_menu.addAction(_("&Open"), self.open_wallet).setShortcut(QKeySequence.Open)
file_menu.addAction(_("&New/Restore"), self.new_wallet).setShortcut(QKeySequence.New)
file_menu.addAction(_("&Save Copy"), self.backup_wallet).setShortcut(QKeySequence.SaveAs)
file_menu.addAction(_("&Quit"), self.close)
wallet_menu = menubar.addMenu(_("&Wallet"))
wallet_menu.addAction(_("&New contact"), self.new_contact_dialog)
self.new_account_menu = wallet_menu.addAction(_("&New account"), self.new_account_dialog)
wallet_menu.addSeparator()
self.password_menu = wallet_menu.addAction(_("&Password"), self.change_password_dialog)
self.seed_menu = wallet_menu.addAction(_("&Seed"), self.show_seed_dialog)
self.mpk_menu = wallet_menu.addAction(_("&Master Public Keys"), self.show_master_public_keys)
wallet_menu.addSeparator()
labels_menu = wallet_menu.addMenu(_("&Labels"))
labels_menu.addAction(_("&Import"), self.do_import_labels)
labels_menu.addAction(_("&Export"), self.do_export_labels)
self.private_keys_menu = wallet_menu.addMenu(_("&Private keys"))
self.private_keys_menu.addAction(_("&Sweep"), self.sweep_key_dialog)
self.import_menu = self.private_keys_menu.addAction(_("&Import"), self.do_import_privkey)
self.export_menu = self.private_keys_menu.addAction(_("&Export"), self.export_privkeys_dialog)
wallet_menu.addAction(_("&Export History"), self.export_history_dialog)
tools_menu = menubar.addMenu(_("&Tools"))
# Settings / Preferences are all reserved keywords in OSX using this as work around
tools_menu.addAction(_("Electrum-FRC preferences") if sys.platform == 'darwin' else _("Preferences"), self.settings_dialog)
tools_menu.addAction(_("&Network"), self.run_network_dialog)
tools_menu.addAction(_("&Plugins"), self.plugins_dialog)
tools_menu.addSeparator()
tools_menu.addAction(_("&Sign/verify message"), self.sign_verify_message)
tools_menu.addAction(_("&Encrypt/decrypt message"), self.encrypt_message)
tools_menu.addSeparator()
csv_transaction_menu = tools_menu.addMenu(_("&Create transaction"))
csv_transaction_menu.addAction(_("&From CSV file"), self.do_process_from_csv_file)
csv_transaction_menu.addAction(_("&From CSV text"), self.do_process_from_csv_text)
raw_transaction_menu = tools_menu.addMenu(_("&Load transaction"))
raw_transaction_menu.addAction(_("&From file"), self.do_process_from_file)
raw_transaction_menu.addAction(_("&From text"), self.do_process_from_text)
raw_transaction_menu.addAction(_("&From the blockchain"), self.do_process_from_txid)
raw_transaction_menu.addAction(_("&From QR code"), self.read_tx_from_qrcode)
self.raw_transaction_menu = raw_transaction_menu
help_menu = menubar.addMenu(_("&Help"))
help_menu.addAction(_("&About"), self.show_about)
help_menu.addAction(_("&Official website"), lambda: webbrowser.open("http://electrum.org"))
help_menu.addSeparator()
help_menu.addAction(_("&Documentation"), lambda: webbrowser.open("http://electrum.orain.org/")).setShortcut(QKeySequence.HelpContents)
help_menu.addAction(_("&Report Bug"), self.show_report_bug)
self.setMenuBar(menubar)
def show_about(self):
QMessageBox.about(self, "Electrum-FRC",
_("Version")+" %s" % (self.wallet.electrum_version) + "\n\n" + _("Electrum-FRC's focus is speed, with low resource usage and simplifying Freicoin. You do not need to perform regular backups, because your wallet can be recovered from a secret phrase that you can memorize or write on paper. Startup times are instant because it operates in conjunction with high-performance servers that handle the most complicated parts of the Freicoin system."))
def show_report_bug(self):
QMessageBox.information(self, "Electrum-FRC - " + _("Reporting Bugs"),
_("Please report any bugs as issues on github:")+" <a href=\"https://github.com/spesmilo/electrum/issues\">https://github.com/spesmilo/electrum/issues</a>")
def notify_transactions(self):
if not self.network or not self.network.is_connected():
return
print_error("Notifying GUI")
if len(self.network.pending_transactions_for_notifications) > 0:
# Combine the transactions if there are more then three
tx_amount = len(self.network.pending_transactions_for_notifications)
if(tx_amount >= 3):
total_amount = 0
for tx in self.network.pending_transactions_for_notifications:
is_relevant, is_mine, v, fee = self.wallet.get_tx_value(tx)
if(v > 0):
total_amount += v
self.notify(_("%(txs)s new transactions received. Total amount received in the new transactions %(amount)s %(unit)s") \
% { 'txs' : tx_amount, 'amount' : self.format_amount(total_amount), 'unit' : self.base_unit()})
self.network.pending_transactions_for_notifications = []
else:
for tx in self.network.pending_transactions_for_notifications:
if tx:
self.network.pending_transactions_for_notifications.remove(tx)
is_relevant, is_mine, v, fee = self.wallet.get_tx_value(tx)
if(v > 0):
self.notify(_("New transaction received. %(amount)s %(unit)s") % { 'amount' : self.format_amount(v), 'unit' : self.base_unit()})
def notify(self, message):
if self.tray:
self.tray.showMessage("Electrum-FRC", message, QSystemTrayIcon.Information, 20000)
# custom wrappers for getOpenFileName and getSaveFileName, that remember the path selected by the user
def getOpenFileName(self, title, filter = ""):
directory = self.config.get('io_dir', unicode(os.path.expanduser('~')))
fileName = unicode( QFileDialog.getOpenFileName(self, title, directory, filter) )
if fileName and directory != os.path.dirname(fileName):
self.config.set_key('io_dir', os.path.dirname(fileName), True)
return fileName
def getSaveFileName(self, title, filename, filter = ""):
directory = self.config.get('io_dir', unicode(os.path.expanduser('~')))
path = os.path.join( directory, filename )
fileName = unicode( QFileDialog.getSaveFileName(self, title, path, filter) )
if fileName and directory != os.path.dirname(fileName):
self.config.set_key('io_dir', os.path.dirname(fileName), True)
return fileName
def close(self):
if self.qr_window:
self.qr_window.close()
QMainWindow.close(self)
run_hook('close_main_window')
def connect_slots(self, sender):
self.connect(sender, QtCore.SIGNAL('timersignal'), self.timer_actions)
self.previous_payto_e=''
def timer_actions(self):
if self.need_update.is_set():
self.update_wallet()
self.need_update.clear()
run_hook('timer_actions')
def format_amount(self, x, is_diff=False, whitespaces=False):
return format_satoshis(x, is_diff, self.num_zeros, self.decimal_point, whitespaces)
def get_decimal_point(self):
return self.decimal_point
def base_unit(self):
assert self.decimal_point in [2, 5, 8]
if self.decimal_point == 2:
return 'uFRC'
if self.decimal_point == 5:
return 'mFRC'
if self.decimal_point == 8:
return 'FRC'
raise Exception('Unknown base unit')
def update_status(self):
if not self.wallet:
return
if self.network is None or not self.network.is_running():
text = _("Offline")
icon = QIcon(":icons/status_disconnected.png")
elif self.network.is_connected():
server_lag = self.network.get_local_height() - self.network.get_server_height()
if not self.wallet.up_to_date:
text = _("Synchronizing...")
icon = QIcon(":icons/status_waiting.png")
elif server_lag > 1:
text = _("Server is lagging (%d blocks)"%server_lag)
icon = QIcon(":icons/status_lagging.png")
else:
use_height = self.network.get_local_height()
c, u = self.wallet.get_account_balance(self.current_account, use_height)
text = _( "Balance" ) + ": %s "%( self.format_amount(c) ) + self.base_unit()
if u: text += " [%s unconfirmed]"%( self.format_amount(u,True).strip() )
# append fiat balance and price from exchange rate plugin
r = {}
run_hook('get_fiat_status_text', c+u, r)
quote = r.get(0)
if quote:
text += "%s"%quote
if self.tray:
self.tray.setToolTip(text)
icon = QIcon(":icons/status_connected.png")
else:
text = _("Not connected")
icon = QIcon(":icons/status_disconnected.png")
self.balance_label.setText(text)
self.status_button.setIcon( icon )
def update_wallet(self):
self.update_status()
if self.wallet.up_to_date or not self.network or not self.network.is_connected():
self.update_tabs()
def update_tabs(self):
self.update_history_tab()
self.update_receive_tab()
self.update_address_tab()
self.update_contacts_tab()
self.update_completions()
self.update_invoices_tab()
def create_history_tab(self):
self.history_list = l = MyTreeWidget(self)
l.setColumnCount(5)
for i,width in enumerate(self.column_widths['history']):
l.setColumnWidth(i, width)
l.setHeaderLabels( [ '', _('Date'), _('Description') , _('Amount'), _('Balance')] )
l.itemDoubleClicked.connect(self.tx_label_clicked)
l.itemChanged.connect(self.tx_label_changed)
l.customContextMenuRequested.connect(self.create_history_menu)
return l
def create_history_menu(self, position):
self.history_list.selectedIndexes()
item = self.history_list.currentItem()
be = self.config.get('block_explorer', 'Coinplorer')
if be == 'Coinplorer':
block_explorer = 'https://coinplorer.com/FRC/Transactions/'
#elif be == 'Blockr.io':
# block_explorer = 'https://blockr.io/tx/info/'
#elif be == 'Insight.is':
# block_explorer = 'http://live.insight.is/tx/'
#elif be == "Blocktrail.com":
# block_explorer = 'https://www.blocktrail.com/BTC/tx/'
if not item: return
tx_hash = str(item.data(0, Qt.UserRole).toString())
if not tx_hash: return
menu = QMenu()
menu.addAction(_("Copy ID to Clipboard"), lambda: self.app.clipboard().setText(tx_hash))
menu.addAction(_("Details"), lambda: self.show_transaction(self.wallet.transactions.get(tx_hash)))
menu.addAction(_("Edit description"), lambda: self.tx_label_clicked(item,2))
menu.addAction(_("View on block explorer"), lambda: webbrowser.open(block_explorer + tx_hash))
menu.exec_(self.contacts_list.viewport().mapToGlobal(position))
def show_transaction(self, tx):
import transaction_dialog
d = transaction_dialog.TxDialog(tx, self)
d.exec_()
def tx_label_clicked(self, item, column):
if column==2 and item.isSelected():
self.is_edit=True
item.setFlags(Qt.ItemIsEditable|Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled | Qt.ItemIsDragEnabled)
self.history_list.editItem( item, column )
item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled | Qt.ItemIsDragEnabled)
self.is_edit=False
def tx_label_changed(self, item, column):
if self.is_edit:
return
self.is_edit=True
tx_hash = str(item.data(0, Qt.UserRole).toString())
tx = self.wallet.transactions.get(tx_hash)
text = unicode( item.text(2) )
self.wallet.set_label(tx_hash, text)
if text:
item.setForeground(2, QBrush(QColor('black')))
else:
text = self.wallet.get_default_label(tx_hash)
item.setText(2, text)
item.setForeground(2, QBrush(QColor('gray')))
self.is_edit=False
def edit_label(self, is_recv):
l = self.address_list if is_recv else self.contacts_list
item = l.currentItem()
item.setFlags(Qt.ItemIsEditable|Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled | Qt.ItemIsDragEnabled)
l.editItem( item, 1 )
item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled | Qt.ItemIsDragEnabled)
def address_label_clicked(self, item, column, l, column_addr, column_label):
if column == column_label and item.isSelected():
is_editable = item.data(0, 32).toBool()
if not is_editable:
return
addr = unicode( item.text(column_addr) )
label = unicode( item.text(column_label) )
item.setFlags(Qt.ItemIsEditable|Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled | Qt.ItemIsDragEnabled)
l.editItem( item, column )
item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled | Qt.ItemIsDragEnabled)
def address_label_changed(self, item, column, l, column_addr, column_label):
if column == column_label:
addr = unicode( item.text(column_addr) )
text = unicode( item.text(column_label) )
is_editable = item.data(0, 32).toBool()
if not is_editable:
return
changed = self.wallet.set_label(addr, text)
if changed:
self.update_history_tab()
self.update_completions()
self.current_item_changed(item)
run_hook('item_changed', item, column)
def current_item_changed(self, a):
run_hook('current_item_changed', a)
def format_time(self, timestamp):
try:
time_str = datetime.datetime.fromtimestamp( timestamp).isoformat(' ')[:-3]
except Exception:
time_str = _("error")
return time_str
def update_history_tab(self):
self.history_list.clear()
for item in self.wallet.get_tx_history(self.current_account):
tx_hash, conf, is_mine, value, fee, balance, timestamp = item
time_str = _("unknown")
if conf > 0:
time_str = self.format_time(timestamp)
if conf == -1:
time_str = 'unverified'
icon = QIcon(":icons/unconfirmed.png")
elif conf == 0:
time_str = 'pending'
icon = QIcon(":icons/unconfirmed.png")
elif conf < 6:
icon = QIcon(":icons/clock%d.png"%conf)
else:
icon = QIcon(":icons/confirmed.png")
if value is not None:
v_str = self.format_amount(value, True, whitespaces=True)
else:
v_str = '--'
balance_str = self.format_amount(balance, whitespaces=True)
if tx_hash:
label, is_default_label = self.wallet.get_label(tx_hash)
else:
label = _('Pruned transaction outputs')
is_default_label = False
item = QTreeWidgetItem( [ '', time_str, label, v_str, balance_str] )
item.setFont(2, QFont(MONOSPACE_FONT))
item.setFont(3, QFont(MONOSPACE_FONT))
item.setFont(4, QFont(MONOSPACE_FONT))
if value < 0:
item.setForeground(3, QBrush(QColor("#BC1E1E")))
if tx_hash:
item.setData(0, Qt.UserRole, tx_hash)
item.setToolTip(0, "%d %s\nTxId:%s" % (conf, _('Confirmations'), tx_hash) )
if is_default_label:
item.setForeground(2, QBrush(QColor('grey')))
item.setIcon(0, icon)
self.history_list.insertTopLevelItem(0,item)
self.history_list.setCurrentItem(self.history_list.topLevelItem(0))
run_hook('history_tab_update')
def create_receive_tab(self):
w = QWidget()
grid = QGridLayout(w)
grid.setColumnMinimumWidth(3, 300)
grid.setColumnStretch(5, 1)
self.receive_address_e = QLineEdit()
self.receive_address_e.setReadOnly(True)
grid.addWidget(QLabel(_('Receiving address')), 0, 0)
grid.addWidget(self.receive_address_e, 0, 1, 1, 3)
self.receive_address_e.textChanged.connect(self.update_receive_qr)
self.copy_button = QPushButton()
self.copy_button.setIcon(QIcon(":icons/copy.png"))
self.copy_button.clicked.connect(lambda: self.app.clipboard().setText(self.receive_address_e.text()))
grid.addWidget(self.copy_button, 0, 4)
self.receive_message_e = QLineEdit()
grid.addWidget(QLabel(_('Message')), 1, 0)
grid.addWidget(self.receive_message_e, 1, 1, 1, 3)
self.receive_message_e.textChanged.connect(self.update_receive_qr)
self.receive_amount_e = BTCAmountEdit(self.get_decimal_point)
grid.addWidget(QLabel(_('Requested amount')), 2, 0)
grid.addWidget(self.receive_amount_e, 2, 1, 1, 2)
self.receive_amount_e.textChanged.connect(self.update_receive_qr)
self.save_request_button = QPushButton(_('Save'))
self.save_request_button.clicked.connect(self.save_payment_request)
grid.addWidget(self.save_request_button, 3, 1)
clear_button = QPushButton(_('New'))
clear_button.clicked.connect(self.new_receive_address)
grid.addWidget(clear_button, 3, 2)
grid.setRowStretch(4, 1)
self.receive_qr = QRCodeWidget(fixedSize=200)
grid.addWidget(self.receive_qr, 0, 5, 5, 2)
self.receive_qr.mousePressEvent = lambda x: self.toggle_qr_window()
grid.setRowStretch(5, 1)
self.receive_requests_label = QLabel(_('Saved Requests'))
self.receive_list = MyTreeWidget(self)
self.receive_list.customContextMenuRequested.connect(self.receive_list_menu)
self.receive_list.currentItemChanged.connect(self.receive_item_changed)
self.receive_list.itemClicked.connect(self.receive_item_changed)
self.receive_list.setHeaderLabels( [_('Date'), _('Account'), _('Address'), _('Message'), _('Amount')] )
self.receive_list.setSortingEnabled(True)
self.receive_list.setColumnWidth(0, 180)
self.receive_list.hideColumn(1) # the update will show it if necessary
self.receive_list.setColumnWidth(2, 340)
h = self.receive_list.header()
h.setStretchLastSection(False)
h.setResizeMode(3, QHeaderView.Stretch)
grid.addWidget(self.receive_requests_label, 6, 0)
grid.addWidget(self.receive_list, 7, 0, 1, 6)
return w
def receive_item_changed(self, item):
if item is None:
return
addr = str(item.text(2))
req = self.receive_requests[addr]
time, amount, message = req['time'], req['amount'], req['msg']
self.receive_address_e.setText(addr)
self.receive_message_e.setText(message)
self.receive_amount_e.setAmount(amount)
def receive_list_delete(self, item):
addr = str(item.text(2))
self.receive_requests.pop(addr)
self.wallet.storage.put('receive_requests2', self.receive_requests)
self.update_receive_tab()
self.clear_receive_tab()
def receive_list_menu(self, position):
item = self.receive_list.itemAt(position)
menu = QMenu()
menu.addAction(_("Copy to clipboard"), lambda: self.app.clipboard().setText(str(item.text(2))))
menu.addAction(_("Delete"), lambda: self.receive_list_delete(item))
menu.exec_(self.receive_list.viewport().mapToGlobal(position))
def save_payment_request(self):
timestamp = int(time.time())
addr = str(self.receive_address_e.text())
amount = self.receive_amount_e.get_amount()
message = unicode(self.receive_message_e.text())
if not message and not amount:
QMessageBox.warning(self, _('Error'), _('No message or amount'), _('OK'))
return
self.receive_requests = self.wallet.storage.get('receive_requests2',{})
self.receive_requests[addr] = {'time':timestamp, 'amount':amount, 'msg':message}
self.wallet.storage.put('receive_requests2', self.receive_requests)
self.update_receive_tab()
def get_receive_address(self):
domain = self.wallet.get_account_addresses(self.current_account, include_change=False)
for addr in domain:
if not self.wallet.history.get(addr) and addr not in self.receive_requests.keys():
return addr
def new_receive_address(self):
addr = self.get_receive_address()
if addr is None:
if isinstance(self.wallet, Imported_Wallet):
self.show_message(_('No more addresses in your wallet.'))
return
if not self.question(_("Warning: The next address will not be recovered automatically if you restore your wallet from seed; you may need to add it manually.\n\nThis occurs because you have too many unused addresses in your wallet. To avoid this situation, use the existing addresses first.\n\nCreate anyway?")):
return
addr = self.wallet.create_new_address(self.current_account, False)
self.set_receive_address(addr)
def set_receive_address(self, addr):
self.receive_address_e.setText(addr)
self.receive_message_e.setText('')
self.receive_amount_e.setAmount(None)
def clear_receive_tab(self):
self.receive_requests = self.wallet.storage.get('receive_requests2',{})
domain = self.wallet.get_account_addresses(self.current_account, include_change=False)
for addr in domain:
if not self.wallet.history.get(addr) and addr not in self.receive_requests.keys():
break
else:
addr = ''
self.receive_address_e.setText(addr)
self.receive_message_e.setText('')
self.receive_amount_e.setAmount(None)
def toggle_qr_window(self):
import qrwindow
if not self.qr_window:
self.qr_window = qrwindow.QR_Window(self)
self.qr_window.setVisible(True)
self.qr_window_geometry = self.qr_window.geometry()
else:
if not self.qr_window.isVisible():
self.qr_window.setVisible(True)
self.qr_window.setGeometry(self.qr_window_geometry)
else:
self.qr_window_geometry = self.qr_window.geometry()
self.qr_window.setVisible(False)
self.update_receive_qr()
def receive_at(self, addr):
if not bitcoin.is_address(addr):
return
self.tabs.setCurrentIndex(2)
self.receive_address_e.setText(addr)
def update_receive_tab(self):
self.receive_requests = self.wallet.storage.get('receive_requests2',{})
# hide receive tab if no receive requests available
b = len(self.receive_requests) > 0
self.receive_list.setVisible(b)
self.receive_requests_label.setVisible(b)
# check if it is necessary to show the account
self.receive_list.setColumnHidden(1, len(self.wallet.get_accounts()) == 1)
# update the receive address if necessary
current_address = self.receive_address_e.text()
domain = self.wallet.get_account_addresses(self.current_account, include_change=False)
if not current_address in domain:
addr = self.get_receive_address()
if addr:
self.set_receive_address(addr)
# clear the list and fill it again
self.receive_list.clear()
for address, req in self.receive_requests.viewitems():
timestamp, amount, message = req['time'], req['amount'], req['msg']
# only show requests for the current account
if address not in domain:
continue
date = self.format_time(timestamp)
account = self.wallet.get_account_name(self.wallet.get_account_from_address(address))
item = QTreeWidgetItem( [ date, account, address, message, self.format_amount(amount) if amount else ""])
item.setFont(2, QFont(MONOSPACE_FONT))
self.receive_list.addTopLevelItem(item)
def update_receive_qr(self):
import urlparse, urllib
addr = str(self.receive_address_e.text())
amount = self.receive_amount_e.get_amount()
message = unicode(self.receive_message_e.text()).encode('utf8')
self.save_request_button.setEnabled((amount is not None) or (message != ""))
if addr:
query = []
if amount:
query.append('amount=%s'%format_satoshis(amount))
if message:
query.append('message=%s'%urllib.quote(message))
p = urlparse.ParseResult(scheme='freicoin', netloc='', path=addr, params='', query='&'.join(query), fragment='')
url = urlparse.urlunparse(p)
else:
url = ""
self.receive_qr.setData(url)
if self.qr_window:
self.qr_window.set_content(addr, amount, message, url)
def create_send_tab(self):
w = QWidget()
self.send_grid = grid = QGridLayout(w)
grid.setSpacing(8)
grid.setColumnMinimumWidth(3,300)
grid.setColumnStretch(5,1)
grid.setRowStretch(8, 1)
from paytoedit import PayToEdit
self.amount_e = BTCAmountEdit(self.get_decimal_point)
self.payto_e = PayToEdit(self)
self.payto_help = HelpButton(_('Recipient of the funds.') + '\n\n' + _('You may enter a Freicoin address, a label from your list of contacts (a list of completions will be proposed), or an alias (email-like address that forwards to a Freicoin address)'))
grid.addWidget(QLabel(_('Pay to')), 1, 0)
grid.addWidget(self.payto_e, 1, 1, 1, 3)
grid.addWidget(self.payto_help, 1, 4)
completer = QCompleter()
completer.setCaseSensitivity(False)
self.payto_e.setCompleter(completer)
completer.setModel(self.completions)
self.message_e = MyLineEdit()
self.message_help = HelpButton(_('Description of the transaction (not mandatory).') + '\n\n' + _('The description is not sent to the recipient of the funds. It is stored in your wallet file, and displayed in the \'History\' tab.'))
grid.addWidget(QLabel(_('Description')), 2, 0)
grid.addWidget(self.message_e, 2, 1, 1, 3)
grid.addWidget(self.message_help, 2, 4)
self.from_label = QLabel(_('From'))
grid.addWidget(self.from_label, 3, 0)
self.from_list = MyTreeWidget(self)
self.from_list.setColumnCount(2)
self.from_list.setColumnWidth(0, 350)
self.from_list.setColumnWidth(1, 50)
self.from_list.setHeaderHidden(True)
self.from_list.setMaximumHeight(80)
self.from_list.setContextMenuPolicy(Qt.CustomContextMenu)
self.from_list.customContextMenuRequested.connect(self.from_list_menu)
grid.addWidget(self.from_list, 3, 1, 1, 3)
self.set_pay_from([])
self.amount_help = HelpButton(_('Amount to be sent.') + '\n\n' \
+ _('The amount will be displayed in red if you do not have enough funds in your wallet. Note that if you have frozen some of your addresses, the available funds will be lower than your total balance.') \
+ '\n\n' + _('Keyboard shortcut: type "!" to send all your coins.'))
grid.addWidget(QLabel(_('Amount')), 4, 0)
grid.addWidget(self.amount_e, 4, 1, 1, 2)
grid.addWidget(self.amount_help, 4, 3)
self.fee_e_label = QLabel(_('Fee'))
self.fee_e = BTCAmountEdit(self.get_decimal_point)
grid.addWidget(self.fee_e_label, 5, 0)
grid.addWidget(self.fee_e, 5, 1, 1, 2)
msg = _('Freicoin transactions are in general not free. A transaction fee is paid by the sender of the funds.') + '\n\n'\
+ _('The amount of fee can be decided freely by the sender. However, transactions with low fees take more time to be processed.') + '\n\n'\
+ _('A suggested fee is automatically added to this field. You may override it. The suggested fee increases with the size of the transaction.')
self.fee_e_help = HelpButton(msg)
grid.addWidget(self.fee_e_help, 5, 3)
self.update_fee_edit()
self.send_button = EnterButton(_("Send"), self.do_send)
grid.addWidget(self.send_button, 6, 1)
b = EnterButton(_("Clear"), self.do_clear)
grid.addWidget(b, 6, 2)
self.payto_sig = QLabel('')
grid.addWidget(self.payto_sig, 7, 0, 1, 4)
w.setLayout(grid)
def on_shortcut():
sendable = self.get_sendable_balance()
inputs = self.get_coins()
for i in inputs: self.wallet.add_input_info(i)
addr = self.payto_e.payto_address if self.payto_e.payto_address else self.dummy_address
output = ('address', addr, sendable)
dummy_tx = Transaction(inputs, [output])
fee = self.wallet.estimated_fee(dummy_tx)
self.amount_e.setAmount(max(0,sendable-fee))
self.amount_e.textEdited.emit("")
self.fee_e.setAmount(fee)
self.amount_e.shortcut.connect(on_shortcut)
def text_edited(is_fee):
outputs = self.payto_e.get_outputs()
amount = self.amount_e.get_amount()
fee = self.fee_e.get_amount() if is_fee else None
if amount is None:
self.fee_e.setAmount(None)
self.not_enough_funds = False
else:
if not outputs:
addr = self.payto_e.payto_address if self.payto_e.payto_address else self.dummy_address
outputs = [('address', addr, amount)]
try:
tx = self.wallet.make_unsigned_transaction(outputs, fee, coins = self.get_coins())
self.not_enough_funds = False
except NotEnoughFunds:
self.not_enough_funds = True
if not is_fee:
fee = None if self.not_enough_funds else self.wallet.get_tx_fee(tx)
self.fee_e.setAmount(fee)
self.payto_e.textChanged.connect(lambda:text_edited(False))
self.amount_e.textEdited.connect(lambda:text_edited(False))
self.fee_e.textEdited.connect(lambda:text_edited(True))
def entry_changed():
if not self.not_enough_funds:
palette = QPalette()
palette.setColor(self.amount_e.foregroundRole(), QColor('black'))
text = ""
else:
palette = QPalette()
palette.setColor(self.amount_e.foregroundRole(), QColor('red'))
text = _( "Not enough funds" )
c, u = self.wallet.get_frozen_balance()
if c+u: text += ' (' + self.format_amount(c+u).strip() + ' ' + self.base_unit() + ' ' +_("are frozen") + ')'
self.statusBar().showMessage(text)
self.amount_e.setPalette(palette)
self.fee_e.setPalette(palette)
self.amount_e.textChanged.connect(entry_changed)
self.fee_e.textChanged.connect(entry_changed)
run_hook('create_send_tab', grid)
return w
def update_fee_edit(self):
b = self.config.get('can_edit_fees', False)
self.fee_e.setVisible(b)
self.fee_e_label.setVisible(b)
self.fee_e_help.setVisible(b)
def from_list_delete(self, item):
i = self.from_list.indexOfTopLevelItem(item)
self.pay_from.pop(i)
self.redraw_from_list()
def from_list_menu(self, position):
item = self.from_list.itemAt(position)
menu = QMenu()
menu.addAction(_("Remove"), lambda: self.from_list_delete(item))
menu.exec_(self.from_list.viewport().mapToGlobal(position))
def set_pay_from(self, domain = None):
self.pay_from = [] if domain == [] else self.wallet.get_unspent_coins(domain, height=self.network.get_local_height())
self.redraw_from_list()
def redraw_from_list(self):
self.from_list.clear()
self.from_label.setHidden(len(self.pay_from) == 0)
self.from_list.setHidden(len(self.pay_from) == 0)
def format(x):
h = x.get('prevout_hash')
return h[0:8] + '...' + h[-8:] + ":%d"%x.get('prevout_n') + u'\t' + "%s"%x.get('address')
for item in self.pay_from:
self.from_list.addTopLevelItem(QTreeWidgetItem( [format(item), self.format_amount(item['value']) ]))
def update_completions(self):
l = []
for addr,label in self.wallet.labels.items():
if addr in self.wallet.addressbook:
l.append( label + ' <' + addr + '>')
run_hook('update_completions', l)
self.completions.setStringList(l)
def protected(func):
return lambda s, *args: s.do_protect(func, args)
def read_send_tab(self):
if self.payment_request and self.payment_request.has_expired():
QMessageBox.warning(self, _('Error'), _('Payment request has expired'), _('OK'))
return
label = unicode( self.message_e.text() )
if self.payment_request:
outputs = self.payment_request.get_outputs()
else:
errors = self.payto_e.get_errors()
if errors:
self.show_warning(_("Invalid Lines found:") + "\n\n" + '\n'.join([ _("Line #") + str(x[0]+1) + ": " + x[1] for x in errors]))
return
outputs = self.payto_e.get_outputs()
if not outputs:
QMessageBox.warning(self, _('Error'), _('No outputs'), _('OK'))
return
for _type, addr, amount in outputs:
if addr is None:
QMessageBox.warning(self, _('Error'), _('Freicoin Address is None'), _('OK'))
return
if _type == 'address' and not bitcoin.is_address(addr):
QMessageBox.warning(self, _('Error'), _('Invalid Freicoin Address'), _('OK'))
return
if amount is None:
QMessageBox.warning(self, _('Error'), _('Invalid Amount'), _('OK'))
return
fee = self.fee_e.get_amount()
if fee is None:
QMessageBox.warning(self, _('Error'), _('Invalid Fee'), _('OK'))
return
amount = sum(map(lambda x:x[2], outputs))
confirm_amount = self.config.get('confirm_amount', 100000000)
if amount >= confirm_amount:
o = '\n'.join(map(lambda x:x[1], outputs))
if not self.question(_("send %(amount)s to %(address)s?")%{ 'amount' : self.format_amount(amount) + ' '+ self.base_unit(), 'address' : o}):
return
coins = self.get_coins()
return outputs, fee, label, coins
def do_send(self):
if run_hook('before_send'):
return
r = self.read_send_tab()
if not r:
return
outputs, fee, label, coins = r
try:
tx = self.wallet.make_unsigned_transaction(outputs, fee, None, coins = coins)
if not tx:
raise BaseException(_("Insufficient funds"))
except Exception as e:
traceback.print_exc(file=sys.stdout)
self.show_message(str(e))
return
if tx.get_fee() < MIN_RELAY_TX_FEE and tx.requires_fee(self.wallet.verifier):
QMessageBox.warning(self, _('Error'), _("This transaction requires a higher fee, or it will not be propagated by the network."), _('OK'))
return
if not self.config.get('can_edit_fees', False):
if not self.question(_("A fee of %(fee)s will be added to this transaction.\nProceed?")%{ 'fee' : self.format_amount(fee) + ' '+ self.base_unit()}):
return
else:
confirm_fee = self.config.get('confirm_fee', 100000)
if fee >= confirm_fee:
if not self.question(_("The fee for this transaction seems unusually high.\nAre you really sure you want to pay %(fee)s in fees?")%{ 'fee' : self.format_amount(fee) + ' '+ self.base_unit()}):
return
self.send_tx(tx, label)
@protected
def send_tx(self, tx, label, password):
self.send_button.setDisabled(True)
# call hook to see if plugin needs gui interaction
run_hook('send_tx', tx)
# sign the tx
def sign_thread():
if self.wallet.is_watching_only():
return tx
self.wallet.sign_transaction(tx, password)
return tx
def sign_done(tx):
if not tx.is_complete() or self.config.get('show_before_broadcast'):
self.show_transaction(tx)
self.do_clear()
return
if label:
self.wallet.set_label(tx.hash(), label)
self.broadcast_transaction(tx)
# keep a reference to WaitingDialog or the gui might crash
self.waiting_dialog = WaitingDialog(self, 'Signing..', sign_thread, sign_done, lambda: self.send_button.setDisabled(False))
self.waiting_dialog.start()
def broadcast_transaction(self, tx):
def broadcast_thread():
# non-GUI thread
pr = self.payment_request
if pr is None:
return self.wallet.sendtx(tx)
if pr.has_expired():
self.payment_request = None
return False, _("Payment request has expired")
status, msg = self.wallet.sendtx(tx)
if not status:
return False, msg
self.invoices[pr.get_id()] = (pr.get_domain(), pr.get_memo(), pr.get_amount(), pr.get_expiration_date(), PR_PAID, tx.hash())
self.wallet.storage.put('invoices', self.invoices)
self.payment_request = None
refund_address = self.wallet.addresses()[0]
ack_status, ack_msg = pr.send_ack(str(tx), refund_address)
if ack_status:
msg = ack_msg
return status, msg
def broadcast_done(status, msg):
# GUI thread
if status:
QMessageBox.information(self, '', _('Payment sent.') + '\n' + msg, _('OK'))
self.update_invoices_tab()
self.do_clear()
else:
QMessageBox.warning(self, _('Error'), msg, _('OK'))
self.send_button.setDisabled(False)
self.waiting_dialog = WaitingDialog(self, 'Broadcasting..', broadcast_thread, broadcast_done)
self.waiting_dialog.start()
def prepare_for_payment_request(self):
self.tabs.setCurrentIndex(1)
self.payto_e.is_pr = True
for e in [self.payto_e, self.amount_e, self.message_e]:
e.setFrozen(True)
for h in [self.payto_help, self.amount_help, self.message_help]:
h.hide()
self.payto_e.setText(_("please wait..."))
return True
def payment_request_ok(self):
pr = self.payment_request
pr_id = pr.get_id()
if pr_id not in self.invoices:
self.invoices[pr_id] = (pr.get_domain(), pr.get_memo(), pr.get_amount(), pr.get_expiration_date(), PR_UNPAID, None)
self.wallet.storage.put('invoices', self.invoices)
self.update_invoices_tab()
else:
print_error('invoice already in list')
status = self.invoices[pr_id][4]
if status == PR_PAID:
self.do_clear()
self.show_message("invoice already paid")
self.payment_request = None
return
self.payto_help.show()
self.payto_help.set_alt(lambda: self.show_pr_details(pr))
if not pr.has_expired():
self.payto_e.setGreen()
else:
self.payto_e.setExpired()
self.payto_e.setText(pr.domain)
self.amount_e.setText(self.format_amount(pr.get_amount()))
self.message_e.setText(pr.get_memo())
# signal to set fee
self.amount_e.textEdited.emit("")
def payment_request_error(self):
self.do_clear()
self.show_message(self.payment_request.error)
self.payment_request = None
def pay_from_URI(self,URI):
if not URI:
return
address, amount, label, message, request_url = util.parse_URI(URI)
try:
address, amount, label, message, request_url = util.parse_URI(URI)
except Exception as e:
QMessageBox.warning(self, _('Error'), _('Invalid freicoin URI:') + '\n' + str(e), _('OK'))
return
self.tabs.setCurrentIndex(1)
if not request_url:
if label:
if self.wallet.labels.get(address) != label:
if self.question(_('Save label "%(label)s" for address %(address)s ?'%{'label':label,'address':address})):
if address not in self.wallet.addressbook and not self.wallet.is_mine(address):
self.wallet.addressbook.append(address)
self.wallet.set_label(address, label)
else:
label = self.wallet.labels.get(address)
if address:
self.payto_e.setText(label + ' <'+ address +'>' if label else address)
if message:
self.message_e.setText(message)
if amount:
self.amount_e.setAmount(amount)
self.amount_e.textEdited.emit("")
return
from electrum_frc import paymentrequest
def payment_request():
self.payment_request = paymentrequest.PaymentRequest(self.config)
self.payment_request.read(request_url)
if self.payment_request.verify():
self.emit(SIGNAL('payment_request_ok'))
else:
self.emit(SIGNAL('payment_request_error'))
self.pr_thread = threading.Thread(target=payment_request).start()
self.prepare_for_payment_request()
def do_clear(self):
self.not_enough_funds = False
self.payto_e.is_pr = False
self.payto_sig.setVisible(False)
for e in [self.payto_e, self.message_e, self.amount_e, self.fee_e]:
e.setText('')
e.setFrozen(False)
for h in [self.payto_help, self.amount_help, self.message_help]:
h.show()
self.payto_help.set_alt(None)
self.set_pay_from([])
self.update_status()
run_hook('do_clear')
def set_addrs_frozen(self,addrs,freeze):
for addr in addrs:
if not addr: continue
if addr in self.wallet.frozen_addresses and not freeze:
self.wallet.unfreeze(addr)
elif addr not in self.wallet.frozen_addresses and freeze:
self.wallet.freeze(addr)
self.update_address_tab()
def create_list_tab(self, headers):
"generic tab creation method"
l = MyTreeWidget(self)
l.setColumnCount( len(headers) )
l.setHeaderLabels( headers )
w = QWidget()
vbox = QVBoxLayout()
w.setLayout(vbox)
vbox.setMargin(0)
vbox.setSpacing(0)
vbox.addWidget(l)
buttons = QWidget()
vbox.addWidget(buttons)
return l, w
def create_addresses_tab(self):
l, w = self.create_list_tab([ _('Address'), _('Label'), _('Balance'), _('Tx')])
for i,width in enumerate(self.column_widths['receive']):
l.setColumnWidth(i, width)
l.setContextMenuPolicy(Qt.CustomContextMenu)
l.customContextMenuRequested.connect(self.create_receive_menu)
l.setSelectionMode(QAbstractItemView.ExtendedSelection)
l.itemDoubleClicked.connect(lambda a, b: self.address_label_clicked(a,b,l,0,1))
l.itemChanged.connect(lambda a,b: self.address_label_changed(a,b,l,0,1))
l.currentItemChanged.connect(lambda a,b: self.current_item_changed(a))
self.address_list = l
return w
def save_column_widths(self):
self.column_widths["receive"] = []
for i in range(self.address_list.columnCount() -1):
self.column_widths["receive"].append(self.address_list.columnWidth(i))
self.column_widths["history"] = []
for i in range(self.history_list.columnCount() - 1):
self.column_widths["history"].append(self.history_list.columnWidth(i))
self.column_widths["contacts"] = []
for i in range(self.contacts_list.columnCount() - 1):
self.column_widths["contacts"].append(self.contacts_list.columnWidth(i))
self.config.set_key("column_widths_2", self.column_widths, True)
def create_contacts_tab(self):
l, w = self.create_list_tab([_('Address'), _('Label'), _('Tx')])
l.setContextMenuPolicy(Qt.CustomContextMenu)
l.customContextMenuRequested.connect(self.create_contact_menu)
for i,width in enumerate(self.column_widths['contacts']):
l.setColumnWidth(i, width)
l.itemDoubleClicked.connect(lambda a, b: self.address_label_clicked(a,b,l,0,1))
l.itemChanged.connect(lambda a,b: self.address_label_changed(a,b,l,0,1))
self.contacts_list = l
return w
def create_invoices_tab(self):
l, w = self.create_list_tab([_('Date'), _('Requestor'), _('Memo'), _('Amount'), _('Status')])
l.setColumnWidth(0, 150)
l.setColumnWidth(1, 150)
l.setColumnWidth(3, 150)
l.setColumnWidth(4, 40)
h = l.header()
h.setStretchLastSection(False)
h.setResizeMode(2, QHeaderView.Stretch)
l.setContextMenuPolicy(Qt.CustomContextMenu)
l.customContextMenuRequested.connect(self.create_invoice_menu)
self.invoices_list = l
return w
def update_invoices_tab(self):
invoices = self.wallet.storage.get('invoices', {})
l = self.invoices_list
l.clear()
for key, value in sorted(invoices.items(), key=lambda x: -x[1][3]):
domain, memo, amount, expiration_date, status, tx_hash = value
if status == PR_UNPAID and expiration_date and expiration_date < time.time():
status = PR_EXPIRED
date_str = datetime.datetime.fromtimestamp(expiration_date).isoformat(' ')[:-3]
item = QTreeWidgetItem( [ date_str, domain, memo, self.format_amount(amount, whitespaces=True), ''] )
icon = QIcon(pr_icons.get(status))
item.setIcon(4, icon)
item.setToolTip(4, pr_tooltips.get(status,''))
item.setData(0, 32, key)
item.setFont(1, QFont(MONOSPACE_FONT))
item.setFont(3, QFont(MONOSPACE_FONT))
l.addTopLevelItem(item)
l.setCurrentItem(l.topLevelItem(0))
def delete_imported_key(self, addr):
if self.question(_("Do you want to remove")+" %s "%addr +_("from your wallet?")):
self.wallet.delete_imported_key(addr)
self.update_address_tab()
self.update_history_tab()
def edit_account_label(self, k):
text, ok = QInputDialog.getText(self, _('Rename account'), _('Name') + ':', text = self.wallet.labels.get(k,''))
if ok:
label = unicode(text)
self.wallet.set_label(k,label)
self.update_address_tab()
def account_set_expanded(self, item, k, b):
item.setExpanded(b)
self.accounts_expanded[k] = b
def create_account_menu(self, position, k, item):
menu = QMenu()
exp = item.isExpanded()
menu.addAction(_("Minimize") if exp else _("Maximize"), lambda: self.account_set_expanded(item, k, not exp))
menu.addAction(_("Rename"), lambda: self.edit_account_label(k))
if self.wallet.seed_version > 4:
menu.addAction(_("View details"), lambda: self.show_account_details(k))
if self.wallet.account_is_pending(k):
menu.addAction(_("Delete"), lambda: self.delete_pending_account(k))
menu.exec_(self.address_list.viewport().mapToGlobal(position))
def delete_pending_account(self, k):
self.wallet.delete_pending_account(k)
self.update_address_tab()
self.update_account_selector()
def create_receive_menu(self, position):
# fixme: this function apparently has a side effect.
# if it is not called the menu pops up several times
#self.address_list.selectedIndexes()
selected = self.address_list.selectedItems()
multi_select = len(selected) > 1
addrs = [unicode(item.text(0)) for item in selected]
if not multi_select:
item = self.address_list.itemAt(position)
if not item: return
addr = addrs[0]
if not is_valid(addr):
k = str(item.data(0,32).toString())
if k:
self.create_account_menu(position, k, item)
else:
item.setExpanded(not item.isExpanded())
return
menu = QMenu()
if not multi_select:
menu.addAction(_("Copy to clipboard"), lambda: self.app.clipboard().setText(addr))
menu.addAction(_("Request payment"), lambda: self.receive_at(addr))
menu.addAction(_("Edit label"), lambda: self.edit_label(True))
menu.addAction(_("Public keys"), lambda: self.show_public_keys(addr))
if self.wallet.can_export():
menu.addAction(_("Private key"), lambda: self.show_private_key(addr))
if not self.wallet.is_watching_only():
menu.addAction(_("Sign/verify message"), lambda: self.sign_verify_message(addr))
menu.addAction(_("Encrypt/decrypt message"), lambda: self.encrypt_message(addr))
if self.wallet.is_imported(addr):
menu.addAction(_("Remove from wallet"), lambda: self.delete_imported_key(addr))
if any(addr not in self.wallet.frozen_addresses for addr in addrs):
menu.addAction(_("Freeze"), lambda: self.set_addrs_frozen(addrs, True))
if any(addr in self.wallet.frozen_addresses for addr in addrs):
menu.addAction(_("Unfreeze"), lambda: self.set_addrs_frozen(addrs, False))
def can_send(addr):
return addr not in self.wallet.frozen_addresses and self.wallet.get_addr_balance(addr) != (0, 0)
if any(can_send(addr) for addr in addrs):
menu.addAction(_("Send From"), lambda: self.send_from_addresses(addrs))
run_hook('receive_menu', menu, addrs)
menu.exec_(self.address_list.viewport().mapToGlobal(position))
def get_sendable_balance(self):
return sum(map(lambda x:x['value'], self.get_coins()))
def get_coins(self):
if self.pay_from:
return self.pay_from
else:
domain = self.wallet.get_account_addresses(self.current_account)
for i in self.wallet.frozen_addresses:
if i in domain: domain.remove(i)
return self.wallet.get_unspent_coins(domain, height=self.network.get_local_height())
def send_from_addresses(self, addrs):
self.set_pay_from( addrs )
self.tabs.setCurrentIndex(1)
def payto(self, addr):
if not addr: return
label = self.wallet.labels.get(addr)
m_addr = label + ' <' + addr + '>' if label else addr
self.tabs.setCurrentIndex(1)
self.payto_e.setText(m_addr)
self.amount_e.setFocus()
def delete_contact(self, x):
if self.question(_("Do you want to remove")+" %s "%x +_("from your list of contacts?")):
self.wallet.delete_contact(x)
self.wallet.set_label(x, None)
self.update_history_tab()
self.update_contacts_tab()
self.update_completions()
def create_contact_menu(self, position):
item = self.contacts_list.itemAt(position)
menu = QMenu()
if not item:
menu.addAction(_("New contact"), lambda: self.new_contact_dialog())
else:
addr = unicode(item.text(0))
label = unicode(item.text(1))
is_editable = item.data(0,32).toBool()
payto_addr = item.data(0,33).toString()
menu.addAction(_("Copy to Clipboard"), lambda: self.app.clipboard().setText(addr))
menu.addAction(_("Pay to"), lambda: self.payto(payto_addr))
menu.addAction(_("QR code"), lambda: self.show_qrcode("freicoin:" + addr, _("Address")))
if is_editable:
menu.addAction(_("Edit label"), lambda: self.edit_label(False))
menu.addAction(_("Delete"), lambda: self.delete_contact(addr))
run_hook('create_contact_menu', menu, item)
menu.exec_(self.contacts_list.viewport().mapToGlobal(position))
def delete_invoice(self, key):
self.invoices.pop(key)
self.wallet.storage.put('invoices', self.invoices)
self.update_invoices_tab()
def show_invoice(self, key):
from electrum_frc.paymentrequest import PaymentRequest
domain, memo, value, expiration, status, tx_hash = self.invoices[key]
pr = PaymentRequest(self.config)
pr.read_file(key)
pr.domain = domain
pr.verify()
self.show_pr_details(pr, tx_hash)
def show_pr_details(self, pr, tx_hash=None):
msg = 'Domain: ' + pr.domain
msg += '\nStatus: ' + pr.get_status()
msg += '\nMemo: ' + pr.get_memo()
msg += '\nPayment URL: ' + pr.payment_url
msg += '\n\nOutputs:\n' + '\n'.join(map(lambda x: x[1] + ' ' + self.format_amount(x[2])+ self.base_unit(), pr.get_outputs()))
if tx_hash:
msg += '\n\nTransaction ID: ' + tx_hash
QMessageBox.information(self, 'Invoice', msg , 'OK')
def do_pay_invoice(self, key):
from electrum_frc.paymentrequest import PaymentRequest
domain, memo, value, expiration, status, tx_hash = self.invoices[key]
pr = PaymentRequest(self.config)
pr.read_file(key)
pr.domain = domain
self.payment_request = pr
self.prepare_for_payment_request()
if pr.verify():
self.payment_request_ok()
else:
self.payment_request_error()
def create_invoice_menu(self, position):
item = self.invoices_list.itemAt(position)
if not item:
return
key = str(item.data(0, 32).toString())
domain, memo, value, expiration, status, tx_hash = self.invoices[key]
menu = QMenu()
menu.addAction(_("Details"), lambda: self.show_invoice(key))
if status == PR_UNPAID:
menu.addAction(_("Pay Now"), lambda: self.do_pay_invoice(key))
menu.addAction(_("Delete"), lambda: self.delete_invoice(key))
menu.exec_(self.invoices_list.viewport().mapToGlobal(position))
def update_address_tab(self):
l = self.address_list
# extend the syntax for consistency
l.addChild = l.addTopLevelItem
l.insertChild = l.insertTopLevelItem
l.clear()
accounts = self.wallet.get_accounts()
if self.current_account is None:
account_items = sorted(accounts.items())
else:
account_items = [(self.current_account, accounts.get(self.current_account))]
for k, account in account_items:
if len(accounts) > 1:
name = self.wallet.get_account_name(k)
c,u = self.wallet.get_account_balance(k)
account_item = QTreeWidgetItem( [ name, '', self.format_amount(c+u), ''] )
l.addTopLevelItem(account_item)
account_item.setExpanded(self.accounts_expanded.get(k, True))
account_item.setData(0, 32, k)
else:
account_item = l
sequences = [0,1] if account.has_change() else [0]
for is_change in sequences:
if len(sequences) > 1:
name = _("Receiving") if not is_change else _("Change")
seq_item = QTreeWidgetItem( [ name, '', '', '', ''] )
account_item.addChild(seq_item)
if not is_change:
seq_item.setExpanded(True)
else:
seq_item = account_item
used_item = QTreeWidgetItem( [ _("Used"), '', '', '', ''] )
used_flag = False
addr_list = account.get_addresses(is_change)
for address in addr_list:
num, is_used = self.wallet.is_used(address)
label = self.wallet.labels.get(address,'')
c, u = self.wallet.get_addr_balance(address)
balance = self.format_amount(c + u)
item = QTreeWidgetItem( [ address, label, balance, "%d"%num] )
item.setFont(0, QFont(MONOSPACE_FONT))
item.setData(0, 32, True) # label can be edited
if address in self.wallet.frozen_addresses:
item.setBackgroundColor(0, QColor('lightblue'))
if self.wallet.is_beyond_limit(address, account, is_change):
item.setBackgroundColor(0, QColor('red'))
if is_used:
if not used_flag:
seq_item.insertChild(0, used_item)
used_flag = True
used_item.addChild(item)
else:
seq_item.addChild(item)
# we use column 1 because column 0 may be hidden
l.setCurrentItem(l.topLevelItem(0),1)
def update_contacts_tab(self):
l = self.contacts_list
l.clear()
for address in self.wallet.addressbook:
label = self.wallet.labels.get(address,'')
n = self.wallet.get_num_tx(address)
item = QTreeWidgetItem( [ address, label, "%d"%n] )
item.setFont(0, QFont(MONOSPACE_FONT))
# 32 = label can be edited (bool)
item.setData(0,32, True)
# 33 = payto string
item.setData(0,33, address)
l.addTopLevelItem(item)
run_hook('update_contacts_tab', l)
l.setCurrentItem(l.topLevelItem(0))
def create_console_tab(self):
from console import Console
self.console = console = Console()
return console
def update_console(self):
console = self.console
console.history = self.config.get("console-history",[])
console.history_index = len(console.history)
console.updateNamespace({'wallet' : self.wallet, 'network' : self.network, 'gui':self})
console.updateNamespace({'util' : util, 'bitcoin':bitcoin})
c = commands.Commands(self.wallet, self.network, lambda: self.console.set_json(True))
methods = {}
def mkfunc(f, method):
return lambda *args: apply( f, (method, args, self.password_dialog ))
for m in dir(c):
if m[0]=='_' or m in ['network','wallet']: continue
methods[m] = mkfunc(c._run, m)
console.updateNamespace(methods)
def change_account(self,s):
if s == _("All accounts"):
self.current_account = None
else:
accounts = self.wallet.get_account_names()
for k, v in accounts.items():
if v == s:
self.current_account = k
self.update_history_tab()
self.update_status()
self.update_address_tab()
self.update_receive_tab()
def create_status_bar(self):
sb = QStatusBar()
sb.setFixedHeight(35)
qtVersion = qVersion()
self.balance_label = QLabel("")
sb.addWidget(self.balance_label)
from version_getter import UpdateLabel
self.updatelabel = UpdateLabel(self.config, sb)
self.account_selector = QComboBox()
self.account_selector.setSizeAdjustPolicy(QComboBox.AdjustToContents)
self.connect(self.account_selector,SIGNAL("activated(QString)"),self.change_account)
sb.addPermanentWidget(self.account_selector)
if (int(qtVersion[0]) >= 4 and int(qtVersion[2]) >= 7):
sb.addPermanentWidget( StatusBarButton( QIcon(":icons/switchgui.png"), _("Switch to Lite Mode"), self.go_lite ) )
self.lock_icon = QIcon()
self.password_button = StatusBarButton( self.lock_icon, _("Password"), self.change_password_dialog )
sb.addPermanentWidget( self.password_button )
sb.addPermanentWidget( StatusBarButton( QIcon(":icons/preferences.png"), _("Preferences"), self.settings_dialog ) )
self.seed_button = StatusBarButton( QIcon(":icons/seed.png"), _("Seed"), self.show_seed_dialog )
sb.addPermanentWidget( self.seed_button )
self.status_button = StatusBarButton( QIcon(":icons/status_disconnected.png"), _("Network"), self.run_network_dialog )
sb.addPermanentWidget( self.status_button )
run_hook('create_status_bar', sb)
self.setStatusBar(sb)
def update_lock_icon(self):
icon = QIcon(":icons/lock.png") if self.wallet.use_encryption else QIcon(":icons/unlock.png")
self.password_button.setIcon( icon )
def update_buttons_on_seed(self):
self.seed_button.setVisible(self.wallet.has_seed())
self.password_button.setVisible(self.wallet.can_change_password())
self.send_button.setText(_("Create unsigned transaction") if self.wallet.is_watching_only() else _("Send"))
def change_password_dialog(self):
from password_dialog import PasswordDialog
d = PasswordDialog(self.wallet, self)
d.run()
self.update_lock_icon()
def new_contact_dialog(self):
d = QDialog(self)
d.setWindowTitle(_("New Contact"))
vbox = QVBoxLayout(d)
vbox.addWidget(QLabel(_('New Contact')+':'))
grid = QGridLayout()
line1 = QLineEdit()
line2 = QLineEdit()
grid.addWidget(QLabel(_("Address")), 1, 0)
grid.addWidget(line1, 1, 1)
grid.addWidget(QLabel(_("Name")), 2, 0)
grid.addWidget(line2, 2, 1)
vbox.addLayout(grid)
vbox.addLayout(ok_cancel_buttons(d))
if not d.exec_():
return
address = str(line1.text())
label = unicode(line2.text())
if not is_valid(address):
QMessageBox.warning(self, _('Error'), _('Invalid Address'), _('OK'))
return
self.wallet.add_contact(address)
if label:
self.wallet.set_label(address, label)
self.update_contacts_tab()
self.update_history_tab()
self.update_completions()
self.tabs.setCurrentIndex(3)
@protected
def new_account_dialog(self, password):
dialog = QDialog(self)
dialog.setModal(1)
dialog.setWindowTitle(_("New Account"))
vbox = QVBoxLayout()
vbox.addWidget(QLabel(_('Account name')+':'))
e = QLineEdit()
vbox.addWidget(e)
msg = _("Note: Newly created accounts are 'pending' until they receive freicoins.") + " " \
+ _("You will need to wait for 2 confirmations until the correct balance is displayed and more addresses are created for that account.")
l = QLabel(msg)
l.setWordWrap(True)
vbox.addWidget(l)
vbox.addLayout(ok_cancel_buttons(dialog))
dialog.setLayout(vbox)
r = dialog.exec_()
if not r: return
name = str(e.text())
self.wallet.create_pending_account(name, password)
self.update_address_tab()
self.update_account_selector()
self.tabs.setCurrentIndex(3)
def show_master_public_keys(self):
dialog = QDialog(self)
dialog.setModal(1)
dialog.setWindowTitle(_("Master Public Keys"))
mpk_dict = self.wallet.get_master_public_keys()
vbox = QVBoxLayout()
# only show the combobox in case multiple accounts are available
if len(mpk_dict) > 1:
gb = QGroupBox(_("Master Public Keys"))
vbox.addWidget(gb)
group = QButtonGroup()
first_button = None
for name in sorted(mpk_dict.keys()):
b = QRadioButton(gb)
b.setText(name)
group.addButton(b)
vbox.addWidget(b)
if not first_button:
first_button = b
mpk_text = ShowQRTextEdit()
mpk_text.setMaximumHeight(170)
vbox.addWidget(mpk_text)
def show_mpk(b):
name = str(b.text())
mpk = mpk_dict.get(name, "")
mpk_text.setText(mpk)
mpk_text.selectAll() # for easy copying
group.buttonReleased.connect(show_mpk)
first_button.setChecked(True)
show_mpk(first_button)
#combobox.currentIndexChanged[str].connect(lambda acc: show_mpk(acc))
elif len(mpk_dict) == 1:
mpk = mpk_dict.values()[0]
mpk_text = ShowQRTextEdit(text=mpk)
mpk_text.setMaximumHeight(170)
mpk_text.selectAll() # for easy copying
vbox.addWidget(mpk_text)
vbox.addLayout(close_button(dialog))
dialog.setLayout(vbox)
dialog.exec_()
@protected
def show_seed_dialog(self, password):
if not self.wallet.has_seed():
QMessageBox.information(self, _('Message'), _('This wallet has no seed'), _('OK'))
return
try:
mnemonic = self.wallet.get_mnemonic(password)
except BaseException as e:
QMessageBox.warning(self, _('Error'), str(e), _('OK'))
return
from seed_dialog import SeedDialog
d = SeedDialog(self, mnemonic, self.wallet.has_imported_keys())
d.exec_()
def show_qrcode(self, data, title = _("QR code")):
if not data:
return
d = QRDialog(data, self, title)
d.exec_()
def do_protect(self, func, args):
if self.wallet.use_encryption:
password = self.password_dialog()
if not password:
return
else:
password = None
if args != (False,):
args = (self,) + args + (password,)
else:
args = (self,password)
apply( func, args)
def show_public_keys(self, address):
if not address: return
try:
pubkey_list = self.wallet.get_public_keys(address)
except Exception as e:
traceback.print_exc(file=sys.stdout)
self.show_message(str(e))
return
d = QDialog(self)
d.setMinimumSize(600, 200)
d.setModal(1)
d.setWindowTitle(_("Public key"))
vbox = QVBoxLayout()
vbox.addWidget( QLabel(_("Address") + ': ' + address))
vbox.addWidget( QLabel(_("Public key") + ':'))
keys = ShowQRTextEdit(text='\n'.join(pubkey_list))
vbox.addWidget(keys)
vbox.addLayout(close_button(d))
d.setLayout(vbox)
d.exec_()
@protected
def show_private_key(self, address, password):
if not address: return
try:
pk_list = self.wallet.get_private_key(address, password)
except Exception as e:
traceback.print_exc(file=sys.stdout)
self.show_message(str(e))
return
d = QDialog(self)
d.setMinimumSize(600, 200)
d.setModal(1)
d.setWindowTitle(_("Private key"))
vbox = QVBoxLayout()
vbox.addWidget( QLabel(_("Address") + ': ' + address))
vbox.addWidget( QLabel(_("Private key") + ':'))
keys = ShowQRTextEdit(text='\n'.join(pk_list))
vbox.addWidget(keys)
vbox.addLayout(close_button(d))
d.setLayout(vbox)
d.exec_()
@protected
def do_sign(self, address, message, signature, password):
message = unicode(message.toPlainText())
message = message.encode('utf-8')
try:
sig = self.wallet.sign_message(str(address.text()), message, password)
signature.setText(sig)
except Exception as e:
self.show_message(str(e))
def do_verify(self, address, message, signature):
message = unicode(message.toPlainText())
message = message.encode('utf-8')
if bitcoin.verify_message(address.text(), str(signature.toPlainText()), message):
self.show_message(_("Signature verified"))
else:
self.show_message(_("Error: wrong signature"))
def sign_verify_message(self, address=''):
d = QDialog(self)
d.setModal(1)
d.setWindowTitle(_('Sign/verify Message'))
d.setMinimumSize(410, 290)
layout = QGridLayout(d)
message_e = QTextEdit()
layout.addWidget(QLabel(_('Message')), 1, 0)
layout.addWidget(message_e, 1, 1)
layout.setRowStretch(2,3)
address_e = QLineEdit()
address_e.setText(address)
layout.addWidget(QLabel(_('Address')), 2, 0)
layout.addWidget(address_e, 2, 1)
signature_e = QTextEdit()
layout.addWidget(QLabel(_('Signature')), 3, 0)
layout.addWidget(signature_e, 3, 1)
layout.setRowStretch(3,1)
hbox = QHBoxLayout()
b = QPushButton(_("Sign"))
b.clicked.connect(lambda: self.do_sign(address_e, message_e, signature_e))
hbox.addWidget(b)
b = QPushButton(_("Verify"))
b.clicked.connect(lambda: self.do_verify(address_e, message_e, signature_e))
hbox.addWidget(b)
b = QPushButton(_("Close"))
b.clicked.connect(d.accept)
hbox.addWidget(b)
layout.addLayout(hbox, 4, 1)
d.exec_()
@protected
def do_decrypt(self, message_e, pubkey_e, encrypted_e, password):
try:
decrypted = self.wallet.decrypt_message(str(pubkey_e.text()), str(encrypted_e.toPlainText()), password)
message_e.setText(decrypted)
except BaseException as e:
traceback.print_exc(file=sys.stdout)
self.show_warning(str(e))
def do_encrypt(self, message_e, pubkey_e, encrypted_e):
message = unicode(message_e.toPlainText())
message = message.encode('utf-8')
try:
encrypted = bitcoin.encrypt_message(message, str(pubkey_e.text()))
encrypted_e.setText(encrypted)
except BaseException as e:
traceback.print_exc(file=sys.stdout)
self.show_warning(str(e))
def encrypt_message(self, address = ''):
d = QDialog(self)
d.setModal(1)
d.setWindowTitle(_('Encrypt/decrypt Message'))
d.setMinimumSize(610, 490)
layout = QGridLayout(d)
message_e = QTextEdit()
layout.addWidget(QLabel(_('Message')), 1, 0)
layout.addWidget(message_e, 1, 1)
layout.setRowStretch(2,3)
pubkey_e = QLineEdit()
if address:
pubkey = self.wallet.get_public_keys(address)[0]
pubkey_e.setText(pubkey)
layout.addWidget(QLabel(_('Public key')), 2, 0)
layout.addWidget(pubkey_e, 2, 1)
encrypted_e = QTextEdit()
layout.addWidget(QLabel(_('Encrypted')), 3, 0)
layout.addWidget(encrypted_e, 3, 1)
layout.setRowStretch(3,1)
hbox = QHBoxLayout()
b = QPushButton(_("Encrypt"))
b.clicked.connect(lambda: self.do_encrypt(message_e, pubkey_e, encrypted_e))
hbox.addWidget(b)
b = QPushButton(_("Decrypt"))
b.clicked.connect(lambda: self.do_decrypt(message_e, pubkey_e, encrypted_e))
hbox.addWidget(b)
b = QPushButton(_("Close"))
b.clicked.connect(d.accept)
hbox.addWidget(b)
layout.addLayout(hbox, 4, 1)
d.exec_()
def question(self, msg):
return QMessageBox.question(self, _('Message'), msg, QMessageBox.Yes | QMessageBox.No, QMessageBox.No) == QMessageBox.Yes
def show_message(self, msg):
QMessageBox.information(self, _('Message'), msg, _('OK'))
def show_warning(self, msg):
QMessageBox.warning(self, _('Warning'), msg, _('OK'))
def password_dialog(self, msg=None):
d = QDialog(self)
d.setModal(1)
d.setWindowTitle(_("Enter Password"))
pw = QLineEdit()
pw.setEchoMode(2)
vbox = QVBoxLayout()
if not msg:
msg = _('Please enter your password')
vbox.addWidget(QLabel(msg))
grid = QGridLayout()
grid.setSpacing(8)
grid.addWidget(QLabel(_('Password')), 1, 0)
grid.addWidget(pw, 1, 1)
vbox.addLayout(grid)
vbox.addLayout(ok_cancel_buttons(d))
d.setLayout(vbox)
run_hook('password_dialog', pw, grid, 1)
if not d.exec_(): return
return unicode(pw.text())
def tx_from_text(self, txt):
"json or raw hexadecimal"
try:
txt.decode('hex')
is_hex = True
except:
is_hex = False
if is_hex:
try:
return Transaction.deserialize(txt)
except:
traceback.print_exc(file=sys.stdout)
QMessageBox.critical(None, _("Unable to parse transaction"), _("Electrum-FRC was unable to parse your transaction"))
return
try:
tx_dict = json.loads(str(txt))
assert "hex" in tx_dict.keys()
tx = Transaction.deserialize(tx_dict["hex"])
#if tx_dict.has_key("input_info"):
# input_info = json.loads(tx_dict['input_info'])
# tx.add_input_info(input_info)
return tx
except Exception:
traceback.print_exc(file=sys.stdout)
QMessageBox.critical(None, _("Unable to parse transaction"), _("Electrum-FRC was unable to parse your transaction"))
def read_tx_from_qrcode(self):
from electrum_frc import qrscanner
try:
data = qrscanner.scan_qr(self.config)
except BaseException, e:
QMessageBox.warning(self, _('Error'), _(e), _('OK'))
return
if not data:
return
# if the user scanned a bitcoin URI
if data.startswith("freicoin:"):
self.pay_from_URI(data)
return
# else if the user scanned an offline signed tx
# transactions are binary, but qrcode seems to return utf8...
z = data.decode('utf8')
data = ''.join(chr(ord(b)) for b in z).encode('hex')
tx = self.tx_from_text(data)
if not tx:
return
self.show_transaction(tx)
def read_tx_from_file(self):
fileName = self.getOpenFileName(_("Select your transaction file"), "*.txn")
if not fileName:
return
try:
with open(fileName, "r") as f:
file_content = f.read()
except (ValueError, IOError, os.error), reason:
QMessageBox.critical(None, _("Unable to read file or no transaction found"), _("Electrum-FRC was unable to open your transaction file") + "\n" + str(reason))
return self.tx_from_text(file_content)
@protected
def sign_raw_transaction(self, tx, password):
try:
self.wallet.sign_transaction(tx, password)
except Exception as e:
traceback.print_exc(file=sys.stdout)
QMessageBox.warning(self, _("Error"), str(e))
def do_process_from_text(self):
text = text_dialog(self, _('Input raw transaction'), _("Transaction:"), _("Load transaction"))
if not text:
return
tx = self.tx_from_text(text)
if tx:
self.show_transaction(tx)
def do_process_from_file(self):
tx = self.read_tx_from_file()
if tx:
self.show_transaction(tx)
def do_process_from_txid(self):
from electrum_frc import transaction
txid, ok = QInputDialog.getText(self, _('Lookup transaction'), _('Transaction ID') + ':')
if ok and txid:
r = self.network.synchronous_get([ ('blockchain.transaction.get',[str(txid)]) ])[0]
if r:
tx = transaction.Transaction.deserialize(r)
if tx:
self.show_transaction(tx)
else:
self.show_message("unknown transaction")
def do_process_from_csvReader(self, csvReader):
outputs = []
errors = []
errtext = ""
try:
for position, row in enumerate(csvReader):
address = row[0]
if not bitcoin.is_address(address):
errors.append((position, address))
continue
amount = Decimal(row[1])
amount = int(100000000*amount)
outputs.append(('address', address, amount))
except (ValueError, IOError, os.error), reason:
QMessageBox.critical(None, _("Unable to read file or no transaction found"), _("Electrum-FRC was unable to open your transaction file") + "\n" + str(reason))
return
if errors != []:
for x in errors:
errtext += "CSV Row " + str(x[0]+1) + ": " + x[1] + "\n"
QMessageBox.critical(None, _("Invalid Addresses"), _("ABORTING! Invalid Addresses found:") + "\n\n" + errtext)
return
try:
tx = self.wallet.make_unsigned_transaction(outputs, None, None)
except Exception as e:
self.show_message(str(e))
return
self.show_transaction(tx)
def do_process_from_csv_file(self):
fileName = self.getOpenFileName(_("Select your transaction CSV"), "*.csv")
if not fileName:
return
try:
with open(fileName, "r") as f:
csvReader = csv.reader(f)
self.do_process_from_csvReader(csvReader)
except (ValueError, IOError, os.error), reason:
QMessageBox.critical(None, _("Unable to read file or no transaction found"), _("Electrum-FRC was unable to open your transaction file") + "\n" + str(reason))
return
def do_process_from_csv_text(self):
text = text_dialog(self, _('Input CSV'), _("Please enter a list of outputs.") + '\n' \
+ _("Format: address, amount. One output per line"), _("Load CSV"))
if not text:
return
f = StringIO.StringIO(text)
csvReader = csv.reader(f)
self.do_process_from_csvReader(csvReader)
@protected
def export_privkeys_dialog(self, password):
if self.wallet.is_watching_only():
self.show_message(_("This is a watching-only wallet"))
return
try:
self.wallet.check_password(password)
except Exception as e:
QMessageBox.warning(self, _('Error'), str(e), _('OK'))
return
d = QDialog(self)
d.setWindowTitle(_('Private keys'))
d.setMinimumSize(850, 300)
vbox = QVBoxLayout(d)
msg = "%s\n%s\n%s" % (_("WARNING: ALL your private keys are secret."),
_("Exposing a single private key can compromise your entire wallet!"),
_("In particular, DO NOT use 'redeem private key' services proposed by third parties."))
vbox.addWidget(QLabel(msg))
e = QTextEdit()
e.setReadOnly(True)
vbox.addWidget(e)
defaultname = 'electrum-private-keys.csv'
select_msg = _('Select file to export your private keys to')
hbox, filename_e, csv_button = filename_field(self, self.config, defaultname, select_msg)
vbox.addLayout(hbox)
h, b = ok_cancel_buttons2(d, _('Export'))
b.setEnabled(False)
vbox.addLayout(h)
private_keys = {}
addresses = self.wallet.addresses(True)
done = False
def privkeys_thread():
for addr in addresses:
time.sleep(0.1)
if done:
break
private_keys[addr] = "\n".join(self.wallet.get_private_key(addr, password))
d.emit(SIGNAL('computing_privkeys'))
d.emit(SIGNAL('show_privkeys'))
def show_privkeys():
s = "\n".join( map( lambda x: x[0] + "\t"+ x[1], private_keys.items()))
e.setText(s)
b.setEnabled(True)
d.connect(d, QtCore.SIGNAL('computing_privkeys'), lambda: e.setText("Please wait... %d/%d"%(len(private_keys),len(addresses))))
d.connect(d, QtCore.SIGNAL('show_privkeys'), show_privkeys)
threading.Thread(target=privkeys_thread).start()
if not d.exec_():
done = True
return
filename = filename_e.text()
if not filename:
return
try:
self.do_export_privkeys(filename, private_keys, csv_button.isChecked())
except (IOError, os.error), reason:
export_error_label = _("Electrum-FRC was unable to produce a private key-export.")
QMessageBox.critical(None, _("Unable to create csv"), export_error_label + "\n" + str(reason))
except Exception as e:
self.show_message(str(e))
return
self.show_message(_("Private keys exported."))
def do_export_privkeys(self, fileName, pklist, is_csv):
with open(fileName, "w+") as f:
if is_csv:
transaction = csv.writer(f)
transaction.writerow(["address", "private_key"])
for addr, pk in pklist.items():
transaction.writerow(["%34s"%addr,pk])
else:
import json
f.write(json.dumps(pklist, indent = 4))
def do_import_labels(self):
labelsFile = self.getOpenFileName(_("Open labels file"), "*.dat")
if not labelsFile: return
try:
f = open(labelsFile, 'r')
data = f.read()
f.close()
for key, value in json.loads(data).items():
self.wallet.set_label(key, value)
QMessageBox.information(None, _("Labels imported"), _("Your labels were imported from")+" '%s'" % str(labelsFile))
except (IOError, os.error), reason:
QMessageBox.critical(None, _("Unable to import labels"), _("Electrum-FRC was unable to import your labels.")+"\n" + str(reason))
def do_export_labels(self):
labels = self.wallet.labels
try:
fileName = self.getSaveFileName(_("Select file to save your labels"), 'electrum_labels.dat', "*.dat")
if fileName:
with open(fileName, 'w+') as f:
json.dump(labels, f)
QMessageBox.information(None, _("Labels exported"), _("Your labels where exported to")+" '%s'" % str(fileName))
except (IOError, os.error), reason:
QMessageBox.critical(None, _("Unable to export labels"), _("Electrum-FRC was unable to export your labels.")+"\n" + str(reason))
def export_history_dialog(self):
d = QDialog(self)
d.setWindowTitle(_('Export History'))
d.setMinimumSize(400, 200)
vbox = QVBoxLayout(d)
defaultname = os.path.expanduser('~/electrum-history.csv')
select_msg = _('Select file to export your wallet transactions to')
hbox, filename_e, csv_button = filename_field(self, self.config, defaultname, select_msg)
vbox.addLayout(hbox)
vbox.addStretch(1)
h, b = ok_cancel_buttons2(d, _('Export'))
vbox.addLayout(h)
run_hook('export_history_dialog', self,hbox)
self.update()
if not d.exec_():
return
filename = filename_e.text()
if not filename:
return
try:
self.do_export_history(self.wallet, filename, csv_button.isChecked())
except (IOError, os.error), reason:
export_error_label = _("Electrum-FRC was unable to produce a transaction export.")
QMessageBox.critical(self, _("Unable to export history"), export_error_label + "\n" + str(reason))
return
QMessageBox.information(self,_("History exported"), _("Your wallet history has been successfully exported."))
def do_export_history(self, wallet, fileName, is_csv):
history = wallet.get_tx_history()
lines = []
for item in history:
tx_hash, confirmations, is_mine, value, fee, balance, timestamp = item
if confirmations:
if timestamp is not None:
try:
time_string = datetime.datetime.fromtimestamp(timestamp).isoformat(' ')[:-3]
except [RuntimeError, TypeError, NameError] as reason:
time_string = "unknown"
pass
else:
time_string = "unknown"
else:
time_string = "pending"
if value is not None:
value_string = format_satoshis(value, True)
else:
value_string = '--'
if fee is not None:
fee_string = format_satoshis(fee, True)
else:
fee_string = '0'
if tx_hash:
label, is_default_label = wallet.get_label(tx_hash)
label = label.encode('utf-8')
else:
label = ""
balance_string = format_satoshis(balance, False)
if is_csv:
lines.append([tx_hash, label, confirmations, value_string, fee_string, balance_string, time_string])
else:
lines.append({'txid':tx_hash, 'date':"%16s"%time_string, 'label':label, 'value':value_string})
with open(fileName, "w+") as f:
if is_csv:
transaction = csv.writer(f, lineterminator='\n')
transaction.writerow(["transaction_hash","label", "confirmations", "value", "fee", "balance", "timestamp"])
for line in lines:
transaction.writerow(line)
else:
import json
f.write(json.dumps(lines, indent = 4))
def sweep_key_dialog(self):
d = QDialog(self)
d.setWindowTitle(_('Sweep private keys'))
d.setMinimumSize(600, 300)
vbox = QVBoxLayout(d)
vbox.addWidget(QLabel(_("Enter private keys")))
keys_e = QTextEdit()
keys_e.setTabChangesFocus(True)
vbox.addWidget(keys_e)
h, address_e = address_field(self.wallet.addresses(False))
vbox.addLayout(h)
vbox.addStretch(1)
hbox, button = ok_cancel_buttons2(d, _('Sweep'))
vbox.addLayout(hbox)
button.setEnabled(False)
def get_address():
addr = str(address_e.text())
if bitcoin.is_address(addr):
return addr
def get_pk():
pk = str(keys_e.toPlainText()).strip()
if Wallet.is_private_key(pk):
return pk.split()
f = lambda: button.setEnabled(get_address() is not None and get_pk() is not None)
keys_e.textChanged.connect(f)
address_e.textChanged.connect(f)
if not d.exec_():
return
fee = self.wallet.fee_per_kb
tx = Transaction.sweep(get_pk(), self.network, get_address(), fee)
self.show_transaction(tx)
@protected
def do_import_privkey(self, password):
if not self.wallet.has_imported_keys():
r = QMessageBox.question(None, _('Warning'), '<b>'+_('Warning') +':\n</b><br/>'+ _('Imported keys are not recoverable from seed.') + ' ' \
+ _('If you ever need to restore your wallet from its seed, these keys will be lost.') + '<p>' \
+ _('Are you sure you understand what you are doing?'), 3, 4)
if r == 4: return
text = text_dialog(self, _('Import private keys'), _("Enter private keys")+':', _("Import"))
if not text: return
text = str(text).split()
badkeys = []
addrlist = []
for key in text:
try:
addr = self.wallet.import_key(key, password)
except Exception as e:
badkeys.append(key)
continue
if not addr:
badkeys.append(key)
else:
addrlist.append(addr)
if addrlist:
QMessageBox.information(self, _('Information'), _("The following addresses were added") + ':\n' + '\n'.join(addrlist))
if badkeys:
QMessageBox.critical(self, _('Error'), _("The following inputs could not be imported") + ':\n'+ '\n'.join(badkeys))
self.update_address_tab()
self.update_history_tab()
def settings_dialog(self):
self.need_restart = False
d = QDialog(self)
d.setWindowTitle(_('Electrum-FRC Settings'))
d.setModal(1)
vbox = QVBoxLayout()
grid = QGridLayout()
grid.setColumnStretch(0,1)
widgets = []
lang_label = QLabel(_('Language') + ':')
lang_help = HelpButton(_('Select which language is used in the GUI (after restart).'))
lang_combo = QComboBox()
from electrum_frc.i18n import languages
lang_combo.addItems(languages.values())
try:
index = languages.keys().index(self.config.get("language",''))
except Exception:
index = 0
lang_combo.setCurrentIndex(index)
if not self.config.is_modifiable('language'):
for w in [lang_combo, lang_label]: w.setEnabled(False)
def on_lang(x):
lang_request = languages.keys()[lang_combo.currentIndex()]
if lang_request != self.config.get('language'):
self.config.set_key("language", lang_request, True)
self.need_restart = True
lang_combo.currentIndexChanged.connect(on_lang)
widgets.append((lang_label, lang_combo, lang_help))
nz_label = QLabel(_('Zeros after decimal point') + ':')
nz_help = HelpButton(_('Number of zeros displayed after the decimal point. For example, if this is set to 2, "1." will be displayed as "1.00"'))
nz = QSpinBox()
nz.setMinimum(0)
nz.setMaximum(self.decimal_point)
nz.setValue(self.num_zeros)
if not self.config.is_modifiable('num_zeros'):
for w in [nz, nz_label]: w.setEnabled(False)
def on_nz():
value = nz.value()
if self.num_zeros != value:
self.num_zeros = value
self.config.set_key('num_zeros', value, True)
self.update_history_tab()
self.update_address_tab()
nz.valueChanged.connect(on_nz)
widgets.append((nz_label, nz, nz_help))
fee_label = QLabel(_('Transaction fee per kb') + ':')
fee_help = HelpButton(_('Fee per kilobyte of transaction.') + '\n' \
+ _('Recommended value') + ': ' + self.format_amount(bitcoin.RECOMMENDED_FEE) + ' ' + self.base_unit())
fee_e = BTCAmountEdit(self.get_decimal_point)
fee_e.setAmount(self.wallet.fee_per_kb)
if not self.config.is_modifiable('fee_per_kb'):
for w in [fee_e, fee_label]: w.setEnabled(False)
def on_fee():
fee = fee_e.get_amount()
self.wallet.set_fee(fee)
fee_e.editingFinished.connect(on_fee)
widgets.append((fee_label, fee_e, fee_help))
units = ['FRC', 'mFRC', 'uFRC']
unit_label = QLabel(_('Base unit') + ':')
unit_combo = QComboBox()
unit_combo.addItems(units)
unit_combo.setCurrentIndex(units.index(self.base_unit()))
msg = _('Base unit of your wallet.')\
+ '\n1FRC=1000mFRC.\n' \
+ _(' These settings affects the fields in the Send tab')+' '
unit_help = HelpButton(msg)
def on_unit(x):
unit_result = units[unit_combo.currentIndex()]
if self.base_unit() == unit_result:
return
if unit_result == 'FRC':
self.decimal_point = 8
elif unit_result == 'mFRC':
self.decimal_point = 5
elif unit_result == 'uFRC':
self.decimal_point = 2
else:
raise Exception('Unknown base unit')
self.config.set_key('decimal_point', self.decimal_point, True)
self.update_history_tab()
self.update_receive_tab()
self.update_address_tab()
self.update_invoices_tab()
fee_e.setAmount(self.wallet.fee_per_kb)
self.update_status()
unit_combo.currentIndexChanged.connect(on_unit)
widgets.append((unit_label, unit_combo, unit_help))
block_explorers = ['Coinplorer']
block_ex_label = QLabel(_('Online Block Explorer') + ':')
block_ex_combo = QComboBox()
block_ex_combo.addItems(block_explorers)
block_ex_combo.setCurrentIndex(block_explorers.index(self.config.get('block_explorer', 'Coinplorer')))
block_ex_help = HelpButton(_('Choose which online block explorer to use for functions that open a web browser'))
def on_be(x):
be_result = block_explorers[block_ex_combo.currentIndex()]
self.config.set_key('block_explorer', be_result, True)
block_ex_combo.currentIndexChanged.connect(on_be)
widgets.append((block_ex_label, block_ex_combo, block_ex_help))
from electrum_frc import qrscanner
system_cameras = qrscanner._find_system_cameras()
qr_combo = QComboBox()
qr_combo.addItem("Default","default")
for camera, device in system_cameras.items():
qr_combo.addItem(camera, device)
#combo.addItem("Manually specify a device", config.get("video_device"))
index = qr_combo.findData(self.config.get("video_device"))
qr_combo.setCurrentIndex(index)
qr_label = QLabel(_('Video Device') + ':')
qr_combo.setEnabled(qrscanner.zbar is not None)
qr_help = HelpButton(_("Install the zbar package to enable this.\nOn linux, type: 'apt-get install python-zbar'"))
on_video_device = lambda x: self.config.set_key("video_device", str(qr_combo.itemData(x).toString()), True)
qr_combo.currentIndexChanged.connect(on_video_device)
widgets.append((qr_label, qr_combo, qr_help))
usechange_cb = QCheckBox(_('Use change addresses'))
usechange_cb.setChecked(self.wallet.use_change)
usechange_help = HelpButton(_('Using change addresses makes it more difficult for other people to track your transactions.'))
if not self.config.is_modifiable('use_change'): usechange_cb.setEnabled(False)
def on_usechange(x):
usechange_result = x == Qt.Checked
if self.wallet.use_change != usechange_result:
self.wallet.use_change = usechange_result
self.wallet.storage.put('use_change', self.wallet.use_change)
usechange_cb.stateChanged.connect(on_usechange)
widgets.append((usechange_cb, None, usechange_help))
showtx_cb = QCheckBox(_('Show transaction before broadcast'))
showtx_cb.setChecked(self.config.get('show_before_broadcast', False))
showtx_cb.stateChanged.connect(lambda x: self.config.set_key('show_before_broadcast', showtx_cb.isChecked()))
showtx_help = HelpButton(_('Display the details of your transactions before broadcasting it.'))
widgets.append((showtx_cb, None, showtx_help))
can_edit_fees_cb = QCheckBox(_('Set transaction fees manually'))
can_edit_fees_cb.setChecked(self.config.get('can_edit_fees', False))
def on_editfees(x):
self.config.set_key('can_edit_fees', x == Qt.Checked)
self.update_fee_edit()
can_edit_fees_cb.stateChanged.connect(on_editfees)
can_edit_fees_help = HelpButton(_('This option lets you edit fees in the send tab.'))
widgets.append((can_edit_fees_cb, None, can_edit_fees_help))
for a,b,c in widgets:
i = grid.rowCount()
if b:
grid.addWidget(a, i, 0)
grid.addWidget(b, i, 1)
else:
grid.addWidget(a, i, 0, 1, 2)
grid.addWidget(c, i, 2)
vbox.addLayout(grid)
vbox.addStretch(1)
vbox.addLayout(close_button(d))
d.setLayout(vbox)
# run the dialog
d.exec_()
run_hook('close_settings_dialog')
if self.need_restart:
QMessageBox.warning(self, _('Success'), _('Please restart Electrum-FRC to activate the new GUI settings'), _('OK'))
def run_network_dialog(self):
if not self.network:
QMessageBox.warning(self, _('Offline'), _('You are using Electrum-FRC in offline mode.\nRestart Electrum-FRC if you want to get connected.'), _('OK'))
return
NetworkDialog(self.wallet.network, self.config, self).do_exec()
def closeEvent(self, event):
self.config.set_key("is_maximized", self.isMaximized())
if not self.isMaximized():
g = self.geometry()
self.config.set_key("winpos-qt", [g.left(),g.top(),g.width(),g.height()])
self.save_column_widths()
self.config.set_key("console-history", self.console.history[-50:], True)
self.wallet.storage.put('accounts_expanded', self.accounts_expanded)
event.accept()
def plugins_dialog(self):
from electrum_frc.plugins import plugins
self.pluginsdialog = d = QDialog(self)
d.setWindowTitle(_('Electrum-FRC Plugins'))
d.setModal(1)
vbox = QVBoxLayout(d)
# plugins
scroll = QScrollArea()
scroll.setEnabled(True)
scroll.setWidgetResizable(True)
scroll.setMinimumSize(400,250)
vbox.addWidget(scroll)
w = QWidget()
scroll.setWidget(w)
w.setMinimumHeight(len(plugins)*35)
grid = QGridLayout()
grid.setColumnStretch(0,1)
w.setLayout(grid)
def do_toggle(cb, p, w):
if p.is_enabled():
if p.disable():
p.close()
else:
if p.enable():
p.load_wallet(self.wallet)
p.init_qt(self.gui_object)
r = p.is_enabled()
cb.setChecked(r)
if w: w.setEnabled(r)
def mk_toggle(cb, p, w):
return lambda: do_toggle(cb,p,w)
for i, p in enumerate(plugins):
try:
cb = QCheckBox(p.fullname())
cb.setDisabled(not p.is_available())
cb.setChecked(p.is_enabled())
grid.addWidget(cb, i, 0)
if p.requires_settings():
w = p.settings_widget(self)
w.setEnabled( p.is_enabled() )
grid.addWidget(w, i, 1)
else:
w = None
cb.clicked.connect(mk_toggle(cb,p,w))
grid.addWidget(HelpButton(p.description()), i, 2)
except Exception:
print_msg("Error: cannot display plugin", p)
traceback.print_exc(file=sys.stdout)
grid.setRowStretch(i+1,1)
vbox.addLayout(close_button(d))
d.exec_()
def show_account_details(self, k):
account = self.wallet.accounts[k]
d = QDialog(self)
d.setWindowTitle(_('Account Details'))
d.setModal(1)
vbox = QVBoxLayout(d)
name = self.wallet.get_account_name(k)
label = QLabel('Name: ' + name)
vbox.addWidget(label)
vbox.addWidget(QLabel(_('Address type') + ': ' + account.get_type()))
vbox.addWidget(QLabel(_('Derivation') + ': ' + k))
vbox.addWidget(QLabel(_('Master Public Key:')))
text = QTextEdit()
text.setReadOnly(True)
text.setMaximumHeight(170)
vbox.addWidget(text)
mpk_text = '\n'.join( account.get_master_pubkeys() )
text.setText(mpk_text)
vbox.addLayout(close_button(d))
d.exec_()
|
Safety in a swimming pool doesn’t just mean strapping wings on the little ones — check those diapers!
Parents often worry about the potential for drowning in pools, but a pool not maintained and treated properly with chemicals and swimmers who do not use proper hygiene and good sense create a risk for all, especially the very young, those with immune disorders and the elderly. In addition, people can become seriously ill if directions are not followed when treating pools with chemicals.
Seventy people have been reported in Illinois with pool related illnesses, though none in Tazewell County so far, said Dr. Michael Wahl, medical director for the Illinois Poison Control Center.
Most diarrhea germs are killed by the chemicals in a pool, but there is a parasite called Cryptosporidium that can survive for up to 10 days in treated water. It causes diarrhea that lasts from one to two weeks, said Wahl. There were 32 Cryptosporidium outbreaks linked to swimming pools or water playgrounds in Illinois in 2016, double the number reported in 2014.
“Crystosporidium is really hard to kill with chlorine,” said Wahl. “Those are the cases the Center for Disease Control has highlighted as having outbreaks with a lot of people being made ill.
There are other water illnesses caused by germs in the water — other gastrointestinal illnesses, and skin, ear, respiratory, eye, neurologic and wound infections, said Dahl.
Dahl said people can be safer if they follow simple rules — avoid swimming if they have diarrhea, shower with soap before swimming to help remove germs that could contaminate the water, don’t swallow water, don’t sit on water jets, and take children and infants on bathroom breaks and check for dirty diapers every hour.
Pool chemicals can be dangerous to pool operators and swimmers if directions are not followed. If pool cleaner is ingested, touches the skin or is inhaled, it can cause medical problems such as organ failure, loss of vision, severe abdominal pain, low blood pressure or throat swelling. Nearly a dozen children at a waterpark in Northwest Indiana reported chemical burns after swimming at a waterpark possibly linked to too much chlorine in the water, according to an IPC press release.
Always use the correct amount of pool cleaner and other substances, handle and store pool cleaners as indicated on their packaging, and never mix chemicals because it can create toxic substances like chlorine gas. Small backyard pools and wading pools should be emptied daily because most people do not treat the water in them.
DragonLand Water Park in Pekin is packing in the swimmers this week with the 90-plus degree heat.
All health department rules are followed. There are signs on the doors and in the restrooms that tell people not to get into the pool with open wounds or if they have had diarrhea in the past 24 hours.
The Tazewell County Health Department inspects public pools several times during the swim season to check records and measure the chemicals in the water, said Powers. A trained technician keeps track of water treatment. If the levels are too high or too low, the DragonLand Water Park is closed until the numbers are back to safe levels. Powers said there have been no closures this year.
Powers said Tazewell County residents are lucky — the TCHD tests the pools. The Peoria Park District pools are tested only one time to get a certificate to open.
“I’m impressed,” said Powers of the work the TCHD does.
If people suspect that they or someone they know has been exposed to a potentially harmful substance, call the IPC at 800-222-1222. The line is open 24 hours every day of the year. The call is free and confidential. For more information, visit the IPC’s website: illinoispoisoncenter.org.
|
import numpy as np
import math
import random
def generate_random_Ugoal_HARD(N, **kwargs):
# N is the length of random matrix multiplication yielding Ugoal
# N ~ 100 should be enough
# This method is hard because it creates Ugoal over the whole space
# Ugoal 2x2 unitary matrix
# create identity matrix
Ugoal = np.eye(2)
# create all N random angles in 2*pi*[0,1)
seq_angle = 2.0 * math.pi * np.random.rand(1, N)
# determine random operator
help2 = np.random.randint(3, size=(1, N))
for k in range(N):
hlp = seq_angle[0][k];
if help2[0][k] == 0:
Ugoal = X_Mat(hlp) * Ugoal
elif help2[0][k] == 1:
Ugoal = Y_Mat(hlp) * Ugoal
else:
Ugoal = Z_Mat(hlp) * Ugoal
return Ugoal
def generate_random_Ugoal_EASY(N, alpha):
# N is the length of random matrix multiplication yielding Ugoal
# N ~ 100 should be enough
# alpha is the used angle between rotation axes
# This method is easy because it creates Ugoal over the whole space
# Ugoal 2x2 unitary matrix
# create identity matrix
Ugoal = np.eye(2)
# create all N random angles in 2*pi*[0,1)
seq_angle = 2.0 * math.pi * np.random.rand(1, N)
# determine random operator
help2 = np.random.randint(2, size=(1, N))
for k in range(N):
hlp = seq_angle[0][k];
if help2[0][k] == 0:
Ugoal = Z_Mat(hlp) * Ugoal
else:
Ugoal = W_Mat(hlp, alpha) * Ugoal
return Ugoal
def generate_random_Ugoal_RANDOM(**kwargs):
# Random guess with the following parametrization for U
# U = @(q1, q2, q3) [
# [ cos(q1)*exp( i*q2 ), sin(q1)*exp( i*q3 )];
# [-sin(q1)*exp(-i*q3 ), cos(q1)*exp(-i*q2 )]
# ];
# create random angles
q1 = random.uniform(0.0, 0.5 * math.pi)
q2 = random.uniform(0.0, 2.0 * math.pi)
q3 = random.uniform(0.0, 2.0 * math.pi)
return np.matrix([
[math.cos(q1) * my_cexp(q2), math.sin(q1) * my_cexp(q3)],
[-math.sin(q1) * my_cexp(-q3), math.cos(q1) * my_cexp(-q2)]])
def my_cexp(x):
return math.cos(x) + 1j * math.sin(x)
def X_Mat(a):
return np.matrix([[math.cos(a / 2.0), -1j * math.sin(a / 2.0)],
[-1j * math.sin(a / 2.0), math.cos(a / 2.0)]])
def Y_Mat(a):
return np.matrix([[math.cos(a / 2.0), -math.sin(a / 2.0)],
[math.sin(a / 2.0), math.cos(a / 2.0)]])
def Z_Mat(a):
return np.matrix([[math.cos(-a / 2.0) + 1j * math.sin(-a / 2.0), 0],
[0, math.cos(a / 2.0) + 1j * math.sin(a / 2.0)]])
def W_Mat(a, alpha):
return np.matrix([[math.cos(a / 2) - 1j * math.cos(alpha) * math.sin(a / 2.0),
-math.sin(a / 2.0) * math.sin(alpha)],
[math.sin(a / 2.0) * math.sin(alpha),
math.cos(a / 2.0) + 1j * math.cos(alpha) * math.sin(
a / 2.0)]])
|
Q: How do I renew a canceled membership? A: First login according to these instructions. Scroll down to “My Subscriptions” and click the “Renew” button next to a subscription with a status of “Cancel”. Then proceed with the checkout as normal.
Q: How do I cancel a membership? A: First login according to these instructions. Scroll down to “My Subscriptions” and click the “Cancel” button next to a subscription with a status of “Active”.
Q: How do I change my password? A: First login according to these instructions. Then click on the link “change your password”. You will then be able to change your password.
Q: How do I recover my lost password? A: From any screen go to the menu at the top and click “Login”. On the “Login” screen click the link “Lost Password” and follow the instructions. An email will be sent to you to assist in recovering or changing your password.
|
import re
def fileNameTextToFloat(valStr, unitStr):
# if there's a 'p' character, then we have to deal with decimal vals
if 'p' in valStr:
regex = re.compile(r"([0-9]+)p([0-9]+)")
wholeVal = regex.findall(valStr)[0][0]
decimalVal = regex.findall(valStr)[0][1]
baseVal = 1.0*int(wholeVal) + 1.0*int(decimalVal)/10**len(decimalVal)
else:
baseVal = 1.0*int(valStr)
if unitStr == "G":
multiplier = 1e9
elif unitStr == "M":
multiplier = 1e6
elif unitStr == "k":
multiplier = 1e3
else:
multiplier = 1.0
return baseVal * multiplier
class iqFileObject():
def __init__(self, prefix = None, centerFreq = None,
sampRate = None, fileName = None):
# if no file name is specified, store the parameters
if fileName is None:
self.prefix = prefix
self.centerFreq = centerFreq
self.sampRate = sampRate
# if the file name is specified, we must derive the parameters
# from the file name
else:
# first check if we have a simple file name or a name+path
regex = re.compile(r"\/")
if regex.match(fileName):
# separate the filename from the rest of the path
regex = re.compile(r"\/([a-zA-Z0-9_.]+)$")
justName = regex.findall(fileName)[0]
else:
justName = fileName
# get the substrings representing the values
regex = re.compile(r"_c([0-9p]+)([GMK])_s([0-9p]+)([GMk])\.iq$")
paramList = regex.findall(justName)
try:
centerValStr = paramList[0][0]
centerUnitStr = paramList[0][1]
sampValStr = paramList[0][2]
sampUnitStr = paramList[0][3]
self.centerFreq = fileNameTextToFloat(centerValStr, centerUnitStr)
self.sampRate = fileNameTextToFloat(sampValStr, sampUnitStr)
except:
return
def fileName(self):
tempStr = self.prefix
# add center frequency
# first determine if we should use k, M, G or nothing
# then divide by the appropriate unit
if self.centerFreq > 1e9:
unitMag = 'G'
wholeVal = int(1.0*self.centerFreq/1e9)
decimalVal = (1.0*self.centerFreq - 1e9*wholeVal)
decimalVal = int(decimalVal/1e7)
elif self.centerFreq > 1e6:
unitMag = 'M'
wholeVal = int(1.0*self.centerFreq/1e6)
decimalVal = (1.0*self.centerFreq - 1e6*wholeVal)
decimalVal = int(decimalVal/1e4)
elif self.centerFreq > 1e3:
unitMag = 'k'
wholeVal = int(1.0*self.centerFreq/1e3)
decimalVal = (1.0*self.centerFreq - 1e3*wholeVal)
decimalVal = int(decimalVal/1e1)
else:
unitMag = ''
value = int(self.centerFreq)
if decimalVal == 0:
tempStr += "_c{}{}".format(wholeVal, unitMag)
else:
tempStr += "_c{}p{}{}".format(wholeVal, decimalVal, unitMag)
# do the same thing for the sample rate
if self.sampRate > 1e6:
unitMag = 'M'
wholeVal = int(1.0*self.sampRate/1e6)
decimalVal = (1.0*self.sampRate - 1e6*wholeVal)
decimalVal = int(decimalVal/1e4)
elif self.sampRate > 1e3:
unitMag = 'k'
wholeVal = int(1.0*self.sampRate/1e3)
decimalVal = (1.0*self.sampRate - 1e3*wholeVal)
value = self.sampRate/1e1
else:
unitMag = ''
value = int(self.sampRate)
if decimalVal == 0:
tempStr += "_s{}{}".format(wholeVal, unitMag)
else:
tempStr += "_s{}p{}{}".format(wholeVal, decimalVal, unitMag)
tempStr += ".iq"
return tempStr
|
For me, Marrakesh always conjured up visions of market stalls, marijuana and maudlin hippies. Fez was a fuzzy and nebulous notion of an exotic fabled city. Morocco was never on my bucket list. In fact, I knew very little about it.
I am wiser now. A three week trip throughout Morocco with two sons temporarily overseas and desperate after a harsh Northern hemisphere winter for sunshine, good surf and Safricans and a septuagenarian mom always ready for adventure, has made me so. Yip, marijuana there was… but not only in Marrakesh; the few hippies seemed happy and the exquisite carpets of Fez were not of the magical mystical kind. How often our preconceptions are misconceptions!
Morocco is not a desert country inhabited mainly by turbaned Black Africans. It is peopled with black African Africans, Arab Africans, Berber Africans, French neo-Africans and a variety of non-Africans. Much of the countryside is green and fertile. Its cities are vibrant, divided into the old modenas hidden behind ancient walls, and the new and modern. We explored mainly the old, where life continues as it has for centuries – tradesmen and artisans creating or selling their wares from tiny stalls packed along narrow alley ways. The goods sold may not have changed much either- spices, leatherware, kaftans, jellabas, live poultry, rabbits, tripe, fruit, pancakes, carpets, pottery and other finely crafted, finely patterned articles made from clay, wood and metals. In the souqs (markets places) of Marrakesh modernity intrudes as one dodges scooters carrying goods and passengers while in the souqs of Fez, heavily laden donkeys and mules assume right of way.
In the alleys, behind studded doors within doors surrounded by splendid mosaic tiles and intricately carved stucco archways, renovated riads testify to the brilliant craftsmanship of the Moroccan people. One marvels at the time that must have been spent in beautifying the ceilings, walls and internal courtyards of these mansions inhabited by the upper and ruling classes, many of which are now well-run and popular B&Bs.
Contrasting completely are the huge kasbahs with their great crenellated walls which once protected the ruling families, their servants and guards and their provisions stored in case of siege. Most famous of these, and most restored, is Ait Benhaddou near Ouarzazate in the desert, used as a backdrop in the film “Gladiators” as well as several other box office hits. Its setting is as enchanting as the buildings themselves.
The river valleys are richly cultivated by subsistence farmers – fields of onions, wheat and broad beans, herbs and other vegetables, while the rocky hillsides are dotted with tethered goats and sheep, patiently watched over by their owners who might occasionally have a chance of a chat with a neighbour plodding by sidesaddled on his donkey. How different their lives are from ours. I wondered whether I could exchange mine for theirs…I couldn’t! I have become too dependent on the accoutrements of my modern, urban South African life and the feminist in me would rebel viciously against washing carpets and clothes in a stream, cooking on primitive stoves, toiling in the fields and raising the family while my spouse drank endless cups of coffee at the pavement cafe with his buddies, morning to nightfall. But, I think I do the men a disfavour- many work long, long hours in their stalls and restaurants vying for the trade of the locals and tourists. Life is not easy in Morocco.
The southern areas are drying up, rivers are not receiving as much water from snow-melt, pastures are overgrazed, forests have been chopped down and it is said that one out of seven beaches have disappeared as a result of gross tourism developments. Morocco is also drowning in pollution – plastic bags, plastic cartons and other garbage litter empty spaces – the scourge of modern civilisation. One has to look beyond this to the beauty of the country and towns. Gorgeous architecture, radiant colours, warm friendly people….I wished I could have had indepth conversations with our travelling companions in the buses and trains, in the souqs and hotels but English is hardly spoken and my French, Berber and Arabic are non-existent.
Other impressions? The gobstopping weaving of taxis and other vehicles through intersections and in traffic circles in the towns and cities was nightmarish- and yet we always arrived unscathed with our luggage still intact in the boots that did not always close. We did not witness a single accident scene or wreckage. The younger people are dressing like their Western counterparts and using the internet and cellphones as relentlessly as our own youth. Lemon blossoms imbued the air with their fragrance while the oranges were the sweetest we had ever tasted….
It was a wonderful, balmy three weeks (barmy too at times!) and we have all left Morocco with pleasant and precious memories, a good deal richer for the experience. Worth adding to the bucket list!
Previous postOceangybe surfers raise awareness about plastic pollution Next postLynn and Jennifer Moss- not the average drama queens!
A brilliant trip & a marvelous article ,thank you for sharing Viv.
Great article, Viv. You’ve captured it well! I’m glad you had such a good trip.
|
import requests
from requests.auth import HTTPDigestAuth
import json
from cloudapp.exceptions import CloudAppHttpError
class CloudAppAPI:
def __init__(self, username, password):
self.username = username
self.password = password
def upload(self, path):
data = self.__get('http://my.cl.ly/items/new')
# TODO: Do something with data['uploads_remaining']
url = data['url']
params = data['params']
headers = {'accept': 'application/json'}
response = requests.post(url, files={'file': open(path, 'rb')}, data=params, allow_redirects=False)
uri = response.headers['location']
data = self.__get(uri)
return data['download_url']
def __get(self, uri):
headers = {'accept': 'application/json'}
r = requests.get(uri, auth=HTTPDigestAuth(self.username, self.password),
headers=headers)
if r.status_code != 200:
raise CloudAppHttpError(response=r)
return json.loads(r.text)
|
Indeed, (877) 863-9721 Pop-up is a troublesome virus that may create a whole lot of vulnerabilities onto your Windows System. It may degrade your Windows System performance and introduce so many other threats to your System. Generally speaking, (877) 863-9721 Pop-up is a type of malicious software program that is programmed to work in the favor of its developers and bring so many troubles to you. It is possible that the virus may take over on your Firefox and displays a wide range of commercial ads while your online session to generate online marketing revenue on the basis of your per click or per purchase.
Even, in some cases, we've seen malware performing other type of malicious activities such as stealing confidential data and online banking credentials from the affected Windows 10. Further, malware connects affected Windows System various remote locations and downloads potentially malicious files and updated on the scheduled time. What is worse, (877) 863-9721 Pop-up may allow remote hackers to access your Windows 10 and monitor your private activities using your Webcam or stealing your private images or videos. In so many case, we've seen that remote hackers steals private files and blackmail the victims to extort money. Notably, such type of virus can also encode your files and ask you to pay off ransom. Hence, Deletion of the (877) 863-9721 Pop-up is a must.
Your homepage and search engine may be replaced with (877) 863-9721 Pop-up.
Know How To prevent (877) 863-9721 Pop-up attacks?
Apparently, (877) 863-9721 Pop-up invades your Windows 10 mostly through bundled software and spam emails attachments. But it could also arrive on your Windows System via unsafe sites and when you install trojanized updates from certainly redirected URLs. Therefore, to prevent (877) 863-9721 Pop-up attacks, we suggest you to pay your close attention while using your Windows System. Never double click spam emails attachments or suspicious updates pop ups. Even, you should always go through Custom/Advanced option when you install free programs to block installation of (877) 863-9721 Pop-up or other similar programs.
Finally, we advise you to make use of following guideline and Clean (877) 863-9721 Pop-up from your Windows 10 instantly.
This entry was posted in Latest PC Threats and tagged Delete (877) 863-9721 Pop-up from Mozilla, Delete (877) 863-9721 Pop-up from Windows 10, Get Rid Of (877) 863-9721 Pop-up, Remove (877) 863-9721 Pop-up from Chrome, Uninstall (877) 863-9721 Pop-up from Chrome, Uninstall (877) 863-9721 Pop-up from Internet Explorer, Uninstall (877) 863-9721 Pop-up from Safari. Bookmark the permalink.
|
# Generated by Django 1.9.11 on 2016-12-19 19:51
from django.db import migrations
PAID_SEAT_TYPES = ('credit', 'professional', 'verified',)
PROGRAM_TYPE = 'Professional Certificate'
def add_program_type(apps, schema_editor):
SeatType = apps.get_model('course_metadata', 'SeatType')
ProgramType = apps.get_model('course_metadata', 'ProgramType')
seat_types = SeatType.objects.filter(slug__in=PAID_SEAT_TYPES)
program_type, __ = ProgramType.objects.update_or_create(name=PROGRAM_TYPE)
program_type.applicable_seat_types.clear()
program_type.applicable_seat_types.add(*seat_types)
program_type.save()
def drop_program_type(apps, schema_editor):
ProgramType = apps.get_model('course_metadata', 'ProgramType')
ProgramType.objects.filter(name=PROGRAM_TYPE).delete()
class Migration(migrations.Migration):
dependencies = [
('edx_catalog_extensions', '0001_squashed_0003_create_publish_to_marketing_site_flag'),
]
operations = [
migrations.RunPython(add_program_type, drop_program_type)
]
run_before = [
('course_metadata', '0247_auto_20200428_1910')
]
|
Released in the three-year gap between 1991’s all-conquering Nevermind and 1994’s In Utero, Incesticide is not a studio album proper, but instead a compilation of material recorded between 1988 and 1991 comprising a mixture of unreleased tracks, b-sides and rarities.
The album features their 1990 single ‘Sliver’, previously not included on any of their albums, as well as its b-side, ‘Dive’, which opens the proceedings. Five of the tracks are taken from two BBC sessions, the first of which features songs recorded for John Peel’s show in 1990. The Peel session consists entirely of cover versions, including a gnarly, pounding rendition of Devo’s ‘Turnaround’ and two songs by Glaswegian punk duo The Vaselines, namely ‘Molly’s Lips’ and ‘Son of a Gun’. The second session was recorded at the BBC’s Maida Vale studios for Mark Goodier a year later and includes the uptempo ‘new wave’ version of Nevermind’s ‘Polly’, as well as Cobain’s anti-sexism themed ‘Been a Son’.
In addition to two other previously unreleased tracks ‘Stain’, ‘Big Long Now’ and the closing salvo ‘Aneurysm’, the remainder of the album is a collection of tracks taken from the band’s first recorded demos from 1988, including ‘Beeswax’, ‘Downer’, ‘Big Long Now’, ‘Mexican Seafood’ and ‘Aero Zeppelin’, all of which were recorded by Sub Pop stalwart Jack Endino.
Despite the fact it’s not a proper studio album, as a collection of songs it’s a pretty great record in itself. When Geffen released it in 1992 it wasn’t marketed with much gusto as the label felt it would be overkill following the five singles released from Nevermind over the previous 12 months. However, demand for new music from the band at the time was still huge and the In Utero sessions were taking time to yield results, so Incesticide was only ever really intended as a stop-gap to appease fans hungry for more material.
What’s great about Incesticide though is that even though it was technically released as a kind of follow-up to Nevermind, because it wasn’t recorded that way there was none of the pressure of following up such a huge commercial success. The result is that all the way through this record there are points when you can really tell that the band are enjoying themselves, especially on tracks like ‘Sliver’ with its “Grandma take me home” hook and on the BBC session tracks. Given some of the dark subject matter on In Utero, not to mention everything else that followed, Incesticide sounds like a moment of relative happiness for both Cobain and the band in general, which is a reminder that despite everything there was always a sense of fun about Nirvana and much of their music.
Any Nirvana fans who don’t already know it should probably be ashamed of themselves, but some younger listeners who weren’t there the first time around may not have heard some of the tracks on Incesticide and they are well worth adding to your collection. If you’re a fan of the Seattle grunge scene in general or you’re into some of the current crop of bands that cite them as an influence then we’d highly recommend giving it a listen.
|
################ Copyright 2005-2016 Team GoldenEye: Source #################
#
# This file is part of GoldenEye: Source's Python Library.
#
# GoldenEye: Source's Python Library is free software: you can redistribute
# it and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 3 of the License,
# or(at your option) any later version.
#
# GoldenEye: Source's Python Library is distributed in the hope that it will
# be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GoldenEye: Source's Python Library.
# If not, see <http://www.gnu.org/licenses/>.
#############################################################################
from . import GEScenario, GEScenarioHelp
from .Utils import OppositeTeam, _
from .Utils.GEOvertime import GEOvertime
from .Utils.GETimer import EndRoundCallback, TimerTracker, Timer
from .Utils.GEWarmUp import GEWarmUp
import GEEntity, GEPlayer, GEUtil, GEWeapon, GEMPGameRules as GERules, GEGlobal as Glb
USING_API = Glb.API_VERSION_1_2_0
FL_DEBUG = False
class Token:
def __init__( self ):
self._ent = GEEntity.EntityHandle( None )
self.next_drop_time = 0 #Drop-spam prevention
self.bothered = False #If we've been dropped by a member of the enemy team and are waiting to be rescued.
def SetTokenEnt( self, token ):
self._ent = GEEntity.EntityHandle( token )
def GetTokenEnt( self ):
return self._ent.Get()
def GetOwner( self ):
ent = self.GetTokenEnt()
if ent is not None:
return ent.GetPlayerOwner()
else:
return None
# -----------------------
# BEGIN CAPTURE THE KEY
# CLASS DEFINITION
# -----------------------
class CaptureTheFlag( GEScenario ):
# Static Defines
( PROBAR_MI6, PROBAR_JANUS, PROBAR_OVERRIDE ) = range( 1, 4 )
( MSG_JANUS_CHANNEL, MSG_MI6_CHANNEL, MSG_MISC_CHANNEL ) = range( 3 )
MSG_JANUS_YPOS = 0.71
MSG_MI6_YPOS = 0.75
MSG_MISC_YPOS = 0.67
OVERTIME_DELAY = 3.0
CVAR_CAPOVERRIDE = "ctf_capture_override_time"
CVAR_CAPPOINTS = "ctf_player_capture_points"
CVAR_SPEEDMULT = "ctf_player_speed_mult"
CVAR_WARMUP = "ctf_warmup_time"
CVAR_ALLOWTOSS = "ctf_allow_flag_toss"
CVAR_FLAGMI6 = "ctf_flag_skin_mi6"
CVAR_FLAGJANUS = "ctf_flag_skin_janus"
TOKEN_MI6 = 'token_mi6'
TOKEN_JANUS = 'token_janus'
COLOR_NEUTRAL = GEUtil.Color( 220, 220, 220, 255 )
COLOR_JANUS_GLOW = GEUtil.Color( 14, 139, 237, 200 )
COLOR_JANUS_RADAR = GEUtil.Color( 94, 171, 231, 255 )
COLOR_JANUS_OBJ_COLD = GEUtil.Color( 94, 171, 231, 150 )
COLOR_JANUS_OBJ_HOT = GEUtil.Color( 94, 171, 231, 235 )
COLOR_MI6_GLOW = GEUtil.Color( 224, 18, 18, 200 )
COLOR_MI6_RADAR = GEUtil.Color( 206, 43, 43, 255 )
COLOR_MI6_OBJ_COLD = GEUtil.Color( 206, 43, 43, 150 )
COLOR_MI6_OBJ_HOT = GEUtil.Color( 206, 43, 43, 235 )
( COLOR_RADAR, COLOR_OBJ_COLD, COLOR_OBJ_HOT ) = range( 3 )
TAG = "[CTF]"
def __init__( self ):
super( CaptureTheFlag, self ).__init__()
# Create trackers and utilities
self.warmupTimer = GEWarmUp( self )
self.timerTracker = TimerTracker( self )
self.overtime = GEOvertime()
# Initialize base elements
self.game_tokens = { Glb.TEAM_MI6 : Token(), Glb.TEAM_JANUS : Token() }
self.game_timers = {}
def GetPrintName( self ):
return "#GES_GP_CAPTUREKEY_NAME"
def GetScenarioHelp( self, help_obj ):
assert isinstance( help_obj, GEScenarioHelp )
help_obj.SetInfo( "#GES_GPH_CTK_TAGLINE", "http://wiki.geshl2.com/Capture_The_Key" )
help_obj.SetDescription( "#GES_GP_CAPTUREKEY_HELP" )
pane = help_obj.AddPane( "ctk" )
help_obj.AddHelp( pane, "ctk_objectives", "#GES_GPH_CTK_OBJECTIVES" )
help_obj.AddHelp( pane, "ctk_radar", "#GES_GPH_CTK_RADAR" )
def GetGameDescription( self ):
return "Capture The Flag"
def GetTeamPlay( self ):
return Glb.TEAMPLAY_ALWAYS
def OnLoadGamePlay( self ):
# Precache our models
GEUtil.PrecacheModel( "models/gameplay/capturepoint.mdl" )
# Ensure our sounds are precached
GEUtil.PrecacheSound( "GEGamePlay.Overtime" )
GEUtil.PrecacheSound( "GEGamePlay.Token_Grab" )
GEUtil.PrecacheSound( "GEGamePlay.Token_Grab_Enemy" )
GEUtil.PrecacheSound( "GEGamePlay.Token_Capture_Friend" )
GEUtil.PrecacheSound( "GEGamePlay.Token_Capture_Enemy" )
GEUtil.PrecacheSound( "GEGamePlay.Token_Drop_Friend" )
GEUtil.PrecacheSound( "GEGamePlay.Token_Drop_Enemy" )
# Setup our tokens
tokenmgr = GERules.GetTokenMgr()
# MI6 Team Token Definition
tokenmgr.SetupToken( self.TOKEN_MI6, limit=1, team=Glb.TEAM_MI6,
location=Glb.SPAWN_TOKEN | Glb.SPAWN_OTHERTEAM,
glow_color=self.COLOR_MI6_GLOW, glow_dist=450.0,
allow_switch=False, respawn_delay=20,
view_model="models/weapons/tokens/v_flagtoken.mdl",
world_model="models/weapons/tokens/w_flagtoken.mdl",
print_name="#GES_GP_CTK_BRIEFCASE" )
# Janus Team Token Definition
tokenmgr.SetupToken( self.TOKEN_JANUS, limit=1, team=Glb.TEAM_JANUS,
location=Glb.SPAWN_TOKEN | Glb.SPAWN_OTHERTEAM,
glow_color=self.COLOR_JANUS_GLOW, glow_dist=450.0,
allow_switch=False, respawn_delay=20,
view_model="models/weapons/tokens/v_flagtoken.mdl",
world_model="models/weapons/tokens/w_flagtoken.mdl",
print_name="#GES_GP_CTK_KEY" )
# Setup the capture areas
tokenmgr.SetupCaptureArea( "capture_mi6", model="models/gameplay/capturepoint.mdl", skin=1,
limit=1, location=Glb.SPAWN_CAPAREA | Glb.SPAWN_MYTEAM,
rqd_token=self.TOKEN_MI6, rqd_team=Glb.TEAM_MI6 )
tokenmgr.SetupCaptureArea( "capture_janus", model="models/gameplay/capturepoint.mdl", skin=2,
limit=1, location=Glb.SPAWN_CAPAREA | Glb.SPAWN_MYTEAM,
rqd_token=self.TOKEN_JANUS, rqd_team=Glb.TEAM_JANUS )
# Reset variables
self.game_inWaitTime = True
self.game_inWarmup = True
self.game_inOvertime = False
self.game_inOvertimeDelay = False
self.game_canFinishRound = True
# Clear the timer list
self.timerTracker.RemoveTimer()
# Create the MI6 delay timer
self.game_timers[Glb.TEAM_MI6] = self.timerTracker.CreateTimer( "ctk_mi6" )
self.game_timers[Glb.TEAM_MI6].SetAgeRate( 1.2, 1.5 )
self.game_timers[Glb.TEAM_MI6].SetUpdateCallback( self.ctk_OnTokenTimerUpdate, 0.1 )
# Create the Janus delay timer
self.game_timers[Glb.TEAM_JANUS] = self.timerTracker.CreateTimer( "ctk_janus" )
self.game_timers[Glb.TEAM_JANUS].SetAgeRate( 1.2, 1.5 )
self.game_timers[Glb.TEAM_JANUS].SetUpdateCallback( self.ctk_OnTokenTimerUpdate, 0.1 )
self.rules_flagmi6 = 1
self.rules_flagjanus = 2
# CVars
self.CreateCVar( self.CVAR_CAPOVERRIDE, "0", "Sets the amount of seconds that a player has to stay on a capture point to capture if both tokens are held" )
self.CreateCVar( self.CVAR_CAPPOINTS, "5", "Sets the amount of points a player recieves on token capture" )
self.CreateCVar( self.CVAR_SPEEDMULT, "0.95", "Speed multiplier for a player holding a token [0.5 - 1.5]" )
self.CreateCVar( self.CVAR_WARMUP, "15", "Seconds of warmup time before the match begins (set to 0 to disable)" )
self.CreateCVar( self.CVAR_ALLOWTOSS, "0", "Allow players to toss the flag with !voodoo. WILL ALLOW GRIEFING ON SOME MAPS." )
self.CreateCVar( self.CVAR_FLAGMI6, "1", "Skin of the MI6 flag." )
self.CreateCVar( self.CVAR_FLAGJANUS, "2", "Skin of the Janus flag." )
self.rules_overrideTime = 0
self.rules_playerCapPoints = 5
self.rules_speedMultiplier = 0.95
self.rules_warmupTime = 15
self.rules_allowToss = False
# Make sure we don't start out in wait time or have a warmup if we changed gameplay mid-match
if GERules.GetNumActivePlayers() >= 2:
self.game_inWaitTime = False
self.warmupTimer.StartWarmup(0)
GERules.GetRadar().SetForceRadar( True )
GERules.SetSpawnInvulnTime( 5, False )
GERules.EnableSuperfluousAreas()
GERules.SetAllowTeamSpawns( True )
def OnUnloadGamePlay(self):
super( CaptureTheFlag, self ).OnUnloadGamePlay()
self.game_timers = None
self.warmupTimer = None
self.timerTracker = None
self.overtime = None
def OnCVarChanged( self, name, oldvalue, newvalue ):
if name == self.CVAR_CAPOVERRIDE:
overridetime = float( newvalue )
self.rules_overrideTime = 0 if overridetime < 0 else overridetime
elif name == self.CVAR_CAPPOINTS:
points = int( newvalue )
self.rules_playerCapPoints = 0 if points < 0 else points
elif name == self.CVAR_SPEEDMULT:
self.rules_speedMultiplier = float( newvalue )
elif name == self.CVAR_ALLOWTOSS:
self.rules_allowToss = True if int( newvalue ) > 0 else False
elif name == self.CVAR_FLAGMI6 and int( newvalue ) != self.rules_flagmi6:
self.rules_flagmi6 = int( newvalue )
GEWeapon.ToGEWeapon(self.game_tokens[Glb.TEAM_JANUS].GetTokenEnt()).SetSkin( self.rules_flagmi6 )
elif name == self.CVAR_FLAGJANUS and int( newvalue ) != self.rules_flagjanus:
self.rules_flagjanus = int( newvalue )
GEWeapon.ToGEWeapon( self.game_tokens[Glb.TEAM_MI6].GetTokenEnt() ).SetSkin( self.rules_flagjanus )
elif name == self.CVAR_WARMUP:
self.rules_warmupTime = int( newvalue )
if self.warmupTimer.IsInWarmup():
self.warmupTimer.StartWarmup( self.rules_warmupTime )
if self.rules_warmupTime <= 0:
GERules.EndRound( False )
def OnRoundBegin( self ):
GERules.ResetAllPlayersScores()
# This makes sure players get a new set of bars on spawn
self.game_inOvertime = False
self.game_canFinishRound = True
if not self.game_inWaitTime and not self.warmupTimer.HadWarmup():
self.warmupTimer.StartWarmup( self.rules_warmupTime )
def CanRoundEnd( self ):
if self.warmupTimer.IsInWarmup():
return False
# No overtime with only 1 player.
if GERules.GetNumActivePlayers() < 2:
self.game_canFinishRound = True
return True
# See if any tokens are picked, if so we postpone the ending
# We can only break overtime if a token is dropped or captured
if not self.game_inOvertime and not GERules.IsIntermission():
mi6Score = GERules.GetTeam( Glb.TEAM_MI6 ).GetRoundScore()
janusScore = GERules.GetTeam( Glb.TEAM_JANUS ).GetRoundScore()
# Only go into overtime if our match scores are close and we have a token in hand
if abs( mi6Score - janusScore ) <= 0 and ( self.ctk_IsTokenHeld( Glb.TEAM_MI6 ) or self.ctk_IsTokenHeld( Glb.TEAM_JANUS ) ):
GEUtil.HudMessage( None, "#GES_GPH_OVERTIME_TITLE", -1, self.MSG_MISC_YPOS, self.COLOR_NEUTRAL, 4.0, self.MSG_MISC_CHANNEL )
GEUtil.PopupMessage( None, "#GES_GPH_OVERTIME_TITLE", "#GES_GPH_OVERTIME" )
GEUtil.EmitGameplayEvent( "ctf_overtime" )
GEUtil.PlaySoundTo( None, "GEGamePlay.Overtime", True )
self.game_inOvertime = True
self.game_inOvertimeDelay = False
self.game_canFinishRound = False
# Ensure overtime never lasts longer than 5 minutes
self.overtime.StartOvertime( 300.0 )
elif not self.game_inOvertimeDelay and not GERules.IsIntermission():
# Exit overtime if a team is eliminated, awarding the other team a point
if GERules.GetNumInRoundTeamPlayers( Glb.TEAM_MI6 ) == 0:
GERules.GetTeam( Glb.TEAM_JANUS ).AddRoundScore( 1 )
GEUtil.HudMessage( None, _( "#GES_GP_CTK_OVERTIME_SCORE", "Janus" ), -1, -1, self.COLOR_NEUTRAL, 5.0 )
self.timerTracker.OneShotTimer( self.OVERTIME_DELAY, EndRoundCallback )
self.game_inOvertimeDelay = True
elif GERules.GetNumInRoundTeamPlayers( Glb.TEAM_JANUS ) == 0:
GERules.GetTeam( Glb.TEAM_MI6 ).AddRoundScore( 1 )
GEUtil.HudMessage( None, _( "#GES_GP_CTK_OVERTIME_SCORE", "MI6" ), -1, -1, self.COLOR_NEUTRAL, 5.0 )
self.timerTracker.OneShotTimer( self.OVERTIME_DELAY, EndRoundCallback )
self.game_inOvertimeDelay = True
elif not self.overtime.CheckOvertime():
# Overtime failsafe tripped, end the round now
return True
return self.game_canFinishRound
def OnPlayerSpawn( self, player ):
player.SetSpeedMultiplier( 1.0 )
player.SetScoreBoardColor( Glb.SB_COLOR_NORMAL )
def OnThink( self ):
# Enter "wait time" if we only have 1 player
if GERules.GetNumActivePlayers() < 2 and self.warmupTimer.HadWarmup():
# Check overtime fail safe
if self.game_inOvertime:
self.game_canFinishRound = True
# Restart the round and count the scores if we were previously not in wait time
if not self.game_inWaitTime:
GERules.EndRound()
self.game_inWaitTime = True
return
# Restart the round (not counting scores) if we were in wait time
if self.game_inWaitTime:
GEUtil.HudMessage( None, "#GES_GP_GETREADY", -1, -1, GEUtil.CColor( 255, 255, 255, 255 ), 2.5 )
GERules.EndRound( False )
self.game_inWaitTime = False
def OnPlayerKilled( self, victim, killer, weapon ):
assert isinstance( victim, GEPlayer.CGEMPPlayer )
assert isinstance( killer, GEPlayer.CGEMPPlayer )
# In warmup? No victim?
if self.warmupTimer.IsInWarmup() or not victim:
return
victimTeam = victim.GetTeamNumber()
killerTeam = killer.GetTeamNumber() if killer else -1 # Only need to do this for killer since not having a victim aborts early.
# death by world
if not killer:
victim.AddRoundScore( -1 )
elif victim == killer or victimTeam == killerTeam:
# Suicide or team kill
killer.AddRoundScore( -1 )
else:
# Check to see if this was a kill against a token bearer (defense). We know we have a killer and a victim but there might not be a weapon.
if victim == self.game_tokens[victimTeam].GetOwner():
clr_hint = '^i' if killerTeam == Glb.TEAM_MI6 else '^r'
GEUtil.EmitGameplayEvent( "ctf_tokendefended", str( killer.GetUserID() ), str( victim.GetUserID() ), str( victimTeam ), weapon.GetClassname().lower() if weapon else "weapon_none", True )
GEUtil.PostDeathMessage( _( "#GES_GP_CTK_DEFENDED", clr_hint, killer.GetCleanPlayerName(), self.ctk_TokenName( victimTeam ) ) )
killer.AddRoundScore( 2 )
else:
killer.AddRoundScore( 1 )
def CanPlayerRespawn( self, player ):
if self.game_inOvertime:
GEUtil.PopupMessage( player, "#GES_GPH_ELIMINATED_TITLE", "#GES_GPH_ELIMINATED" )
player.SetScoreBoardColor( Glb.SB_COLOR_ELIMINATED )
return False
return True
def OnCaptureAreaSpawned( self, area ):
team = area.GetTeamNumber()
tknName = self.TOKEN_MI6 if team == Glb.TEAM_MI6 else self.TOKEN_JANUS
GERules.GetRadar().AddRadarContact( area, Glb.RADAR_TYPE_OBJECTIVE, True, "sprites/hud/radar/capture_point", self.ctk_GetColor( OppositeTeam(team) ) )
GERules.GetRadar().SetupObjective( area, team, tknName, "#GES_GP_CTK_OBJ_CAPTURE", self.ctk_GetColor( OppositeTeam(team), self.COLOR_OBJ_HOT ), 0, True )
def OnCaptureAreaRemoved( self, area ):
GERules.GetRadar().DropRadarContact( area )
def OnCaptureAreaEntered( self, area, player, token ):
assert isinstance( area, GEEntity.CBaseEntity )
assert isinstance( player, GEPlayer.CGEMPPlayer )
assert isinstance( token, GEWeapon.CGEWeapon )
if token is None:
return
# If the other team has our token, we have to wait a set period
tokenteam = token.GetTeamNumber()
otherteam = OppositeTeam( player.GetTeamNumber() )
if self.ctk_IsTokenHeld( otherteam ) and self.rules_overrideTime >= 0:
if self.rules_overrideTime > 0 and not self.game_inOvertime: # Can't capture if other team has your token in overtime.
timer = self.game_timers[tokenteam]
if timer.state is Timer.STATE_STOP:
GEUtil.InitHudProgressBar( player, self.PROBAR_OVERRIDE, "#GES_GP_CTK_CAPTURE_OVR", Glb.HUDPB_SHOWBAR, self.rules_overrideTime, -1, 0.6, 120, 16, GEUtil.CColor( 220, 220, 220, 240 ) )
timer.Start( self.rules_overrideTime )
else:
GEUtil.HudMessage( player, "#GES_GP_CTK_CAPTURE_DENY", -1, 0.6, GEUtil.CColor( 220, 220, 220, 240 ), 2.0, self.MSG_MISC_CHANNEL )
else:
self.ctk_CaptureToken( token, player )
def OnCaptureAreaExited( self, area, player ):
assert isinstance( area, GEEntity.CBaseEntity )
assert isinstance( player, GEPlayer.CGEMPPlayer )
tokenteam = player.GetTeamNumber()
self.game_timers[tokenteam].Pause()
def OnTokenSpawned( self, token ):
tokenTeam = token.GetTeamNumber()
GERules.GetRadar().AddRadarContact( token, Glb.RADAR_TYPE_TOKEN, True, "", self.ctk_GetColor( tokenTeam ) )
GERules.GetRadar().SetupObjective( token, Glb.TEAM_NONE, "", self.ctk_TokenName( tokenTeam ), self.ctk_GetColor( tokenTeam, self.COLOR_OBJ_COLD ) )
self.game_tokens[tokenTeam].SetTokenEnt( token )
self.game_tokens[tokenTeam].bothered = False
if token.GetTeamNumber() == Glb.TEAM_MI6:
token.SetSkin( self.rules_flagjanus )
else:
token.SetSkin( self.rules_flagmi6 )
def OnTokenPicked( self, token, player ):
tokenTeam = token.GetTeamNumber()
otherTeam = OppositeTeam( tokenTeam )
if self.game_tokens[tokenTeam].bothered:
self.game_tokens[tokenTeam].next_drop_time = GEUtil.GetTime() + 8.0
else:
self.game_tokens[tokenTeam].next_drop_time = GEUtil.GetTime()
self.game_tokens[tokenTeam].bothered = True
GERules.GetRadar().DropRadarContact( token )
GERules.GetRadar().AddRadarContact( player, Glb.RADAR_TYPE_PLAYER, True, "sprites/hud/radar/run", self.ctk_GetColor( OppositeTeam(player.GetTeamNumber()) ) )
GERules.GetRadar().SetupObjective( player, Glb.TEAM_NONE, "", self.ctk_TokenName( tokenTeam ), self.ctk_GetColor( tokenTeam, self.COLOR_OBJ_HOT ) )
GEUtil.EmitGameplayEvent( "ctf_tokenpicked", str( player.GetUserID() ), str( tokenTeam ) )
# Token bearers move faster
player.SetSpeedMultiplier( self.rules_speedMultiplier )
player.SetScoreBoardColor( Glb.SB_COLOR_WHITE )
msgFriend = _( "#GES_GP_CTK_PICKED_FRIEND", player.GetCleanPlayerName(), self.ctk_TokenName( tokenTeam ) )
msgEnemy = _( "#GES_GP_CTK_PICKED_FOE", player.GetCleanPlayerName(), self.ctk_TokenName( tokenTeam ) )
self.ctk_PostMessage( msgFriend, tokenTeam, otherTeam )
self.ctk_PostMessage( msgEnemy, otherTeam, otherTeam )
GEUtil.PlaySoundTo( tokenTeam, "GEGamePlay.Token_Grab", False )
GEUtil.PlaySoundTo( otherTeam, "GEGamePlay.Token_Grab_Enemy", False )
def OnTokenDropped( self, token, player ):
tokenTeam = token.GetTeamNumber()
otherTeam = OppositeTeam( tokenTeam )
# Stop the override timer and force remove just in case
GEUtil.RemoveHudProgressBar( player, self.PROBAR_OVERRIDE )
self.game_timers[tokenTeam].Stop()
# Remove the victim's objective status.
GERules.GetRadar().DropRadarContact( player )
GERules.GetRadar().ClearObjective( player )
GEUtil.EmitGameplayEvent( "ctf_tokendropped", str( player.GetUserID() ), str( tokenTeam ) )
GERules.GetRadar().AddRadarContact( token, Glb.RADAR_TYPE_TOKEN, True, "", self.ctk_GetColor( tokenTeam ) )
GERules.GetRadar().SetupObjective( token, Glb.TEAM_NONE, "", self.ctk_TokenName( tokenTeam ), self.ctk_GetColor( tokenTeam, self.COLOR_OBJ_COLD ) )
player.SetSpeedMultiplier( 1.0 )
player.SetScoreBoardColor( Glb.SB_COLOR_NORMAL )
msg = _( "#GES_GP_CTK_DROPPED", player.GetCleanPlayerName(), self.ctk_TokenName( tokenTeam ) )
self.ctk_PostMessage( msg, tokenTeam, otherTeam )
self.ctk_PostMessage( msg, otherTeam, otherTeam )
GEUtil.PlaySoundTo( tokenTeam, "GEGamePlay.Token_Drop_Friend", True )
GEUtil.PlaySoundTo( otherTeam, "GEGamePlay.Token_Drop_Enemy", True )
def OnEnemyTokenTouched( self, token, player ):
tokenTeam = token.GetTeamNumber()
otherTeam = OppositeTeam( tokenTeam )
if self.game_tokens[tokenTeam].bothered:
GERules.GetTokenMgr().RemoveTokenEnt( token, False )
player.AddRoundScore( 2 )
msgFriend = _( "#GES_GP_CTK_RETURNED_FRIEND", player.GetCleanPlayerName(), self.ctk_TokenName( tokenTeam ) )
msgEnemy = _( "#GES_GP_CTK_RETURNED_FOE", player.GetCleanPlayerName(), self.ctk_TokenName( tokenTeam ) )
self.ctk_PostMessage( msgFriend, otherTeam, tokenTeam )
self.ctk_PostMessage( msgEnemy, tokenTeam, tokenTeam )
GEUtil.PlaySoundTo( tokenTeam, "GEGamePlay.Token_Drop_Enemy", False )
GEUtil.PlaySoundTo( otherTeam, "GEGamePlay.Token_Drop_Friend", False )
def OnTokenRemoved( self, token ):
tokenTeam = token.GetTeamNumber()
GERules.GetRadar().DropRadarContact( token )
self.game_tokens[tokenTeam].SetTokenEnt( None )
def OnPlayerSay( self, player, text ):
team = player.GetTeamNumber()
# If the player issues !voodoo they will drop their token
if text.lower() == Glb.SAY_COMMAND1 and team != Glb.TEAM_SPECTATOR:
if self.rules_allowToss:
tokendef = self.game_tokens[team]
if player == tokendef.GetOwner():
if GEUtil.GetTime() >= tokendef.next_drop_time:
GERules.GetTokenMgr().TransferToken( tokendef.GetTokenEnt(), None )
else:
timeleft = max( 1, int( tokendef.next_drop_time - GEUtil.GetTime() ) )
GEUtil.HudMessage( player, _( "#GES_GP_CTK_TOKEN_DROP", timeleft ), -1, self.MSG_MISC_YPOS, self.COLOR_NEUTRAL, 2.0, self.MSG_MISC_CHANNEL )
else:
GEUtil.HudMessage( player, "#GES_GP_CTK_TOKEN_DROP_NOFLAG", -1, self.MSG_MISC_YPOS, self.COLOR_NEUTRAL, 2.0, self.MSG_MISC_CHANNEL )
else:
GEUtil.HudMessage( player, "#GES_GP_CTK_TOKEN_DROP_DISABLED", -1, self.MSG_MISC_YPOS, self.COLOR_NEUTRAL, 2.0, self.MSG_MISC_CHANNEL )
return True
return False
#-------------------#
# Utility Functions #
#-------------------#
def ctk_GetColor( self, team, color_type=0 ):
if team == Glb.TEAM_JANUS:
if color_type == CaptureTheFlag.COLOR_RADAR:
return self.COLOR_JANUS_RADAR
elif color_type == CaptureTheFlag.COLOR_OBJ_COLD:
return self.COLOR_JANUS_OBJ_COLD
else:
return self.COLOR_JANUS_OBJ_HOT
elif team == Glb.TEAM_MI6:
if color_type == CaptureTheFlag.COLOR_RADAR:
return self.COLOR_MI6_RADAR
elif color_type == CaptureTheFlag.COLOR_OBJ_COLD:
return self.COLOR_MI6_OBJ_COLD
else:
return self.COLOR_MI6_OBJ_HOT
else:
return self.COLOR_NEUTRAL
def ctk_CaptureToken( self, token, holder ):
assert isinstance( token, GEWeapon.CGEWeapon )
assert isinstance( holder, GEPlayer.CGEMPPlayer )
tokenTeam = token.GetTeamNumber()
otherTeam = OppositeTeam( tokenTeam )
GERules.GetRadar().DropRadarContact( token )
GERules.GetRadar().DropRadarContact( holder )
holder.SetSpeedMultiplier( 1.0 )
holder.SetScoreBoardColor( Glb.SB_COLOR_NORMAL )
# Check overtime requirements
if self.game_inOvertime:
if not self.game_inOvertimeDelay:
self.game_inOvertimeDelay = True
self.timerTracker.OneShotTimer( self.OVERTIME_DELAY, EndRoundCallback )
else:
# We already scored in overtime, ignore this
return
# Capture the token and give the capturing team points
GERules.GetTokenMgr().CaptureToken( token )
# Make sure our timer goes away
self.game_timers[tokenTeam].Stop()
GEUtil.RemoveHudProgressBar( holder, self.PROBAR_OVERRIDE )
# Give points if not in warmup
if not self.warmupTimer.IsInWarmup():
GERules.GetTeam( tokenTeam ).AddRoundScore( 1 )
holder.AddRoundScore( self.rules_playerCapPoints )
GEUtil.EmitGameplayEvent( "ctf_tokencapture", str( holder.GetUserID() ), str( tokenTeam ), "", "", True )
GEUtil.PlaySoundTo( tokenTeam, "GEGamePlay.Token_Capture_Friend", True )
GEUtil.PlaySoundTo( otherTeam, "GEGamePlay.Token_Capture_Enemy", True )
msg = _( "#GES_GP_CTK_CAPTURE", holder.GetCleanPlayerName(), self.ctk_TokenName( tokenTeam ) )
self.ctk_PostMessage( msg )
GEUtil.PostDeathMessage( msg )
def ctk_OnTokenTimerUpdate( self, timer, update_type ):
assert isinstance( timer, Timer )
tokenTeam = Glb.TEAM_MI6 if ( timer.GetName() == "ctk_mi6" ) else Glb.TEAM_JANUS
otherTeam = OppositeTeam( tokenTeam )
time = timer.GetCurrentTime()
holder = self.game_tokens[tokenTeam].GetOwner()
if holder is not None:
if update_type == Timer.UPDATE_FINISH:
token = self.game_tokens[tokenTeam].GetTokenEnt()
if token is not None:
self.ctk_CaptureToken( token, holder )
elif update_type == Timer.UPDATE_STOP:
GEUtil.RemoveHudProgressBar( holder, self.PROBAR_OVERRIDE )
elif update_type == Timer.UPDATE_RUN:
GEUtil.UpdateHudProgressBar( holder, self.PROBAR_OVERRIDE, time )
# Check to see if the other team dropped their token mid-capture and we are still on the capture point.
if not self.ctk_IsTokenHeld( otherTeam ):
if timer.state == Timer.STATE_PAUSE:
timer.Stop()
else:
timer.Finish()
def ctk_IsTokenHeld( self, team ):
return self.game_tokens[team].GetOwner() != None
def ctk_PostMessage( self, msg, to_team=Glb.TEAM_NONE, from_team=Glb.TEAM_NONE ):
if from_team == Glb.TEAM_MI6:
channel = self.MSG_JANUS_CHANNEL
ypos = self.MSG_JANUS_YPOS
elif from_team == Glb.TEAM_JANUS:
channel = self.MSG_MI6_CHANNEL
ypos = self.MSG_MI6_YPOS
else:
channel = self.MSG_MISC_CHANNEL
ypos = self.MSG_MISC_YPOS
if to_team == Glb.TEAM_NONE:
GEUtil.HudMessage( None, msg, -1, ypos, self.ctk_GetColor( from_team ), 5.0, channel )
else:
GEUtil.HudMessage( to_team, msg, -1, ypos, self.ctk_GetColor( from_team ), 5.0, channel )
def ctk_TokenName( self, team ):
return "#GES_GP_CTK_OBJ_JANUS" if team == Glb.TEAM_MI6 else "#GES_GP_CTK_OBJ_MI6"
|
krisbow grinding krisbow – Grinding Mill China. The zenith product line, consisting of more than 30 machines, sets the standard for our industry.
macam grinding stone krisbow seo test makita grinding machine pa6 gf30 specification cme is quite experienced in construction,milling and mining industry.
Grinding Machine Krisbow - greenrevolution . Grinding Machine Krisbow Malta – Rock & Ore Crusher. machine shops in Illinois (IL), CNC machining.
vertical grinder krisbow Vertical Feed Grinders ,tons/hour Smart design,grinding stone krisbow kw machine for grinding grapes Crusher, krisbow grindingmarigoldjaipur.
krisbow kgs surface grinding machine terratek in bench grinder electric power wet powered waterstone stone bench grinder sharpener tool machine. Read More.
macam grinding stone krisbow grinding machine, coal crusher, wet grinder, vertical grinding, rock 0 5 mn tonne grinding capacity is how much cement capacity .
|
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import time
from openerp.addons.at_base import extreport
class Parser(extreport.basic_parser):
def __init__(self, cr, uid, name, context=None):
super(Parser, self).__init__(cr, uid, name, context=context)
self.localcontext.update({
"time": time,
"sale_order_lines": self.sale_order_lines,
"currency" : self.currency,
"payment_note" : self.payment_note,
"payment_term" : self.payment_term,
"taxes" : self.taxes
})
def payment_note(self, sale_order):
return sale_order.payment_term and sale_order.payment_term.note or ""
def currency(self, sale_order):
return (sale_order.pricelist_id and sale_order.pricelist_id.currency_id and sale_order.pricelist_id.currency_id.symbol) or ''
def payment_term(self,sale_order):
return self.payment_note(sale_order)
def taxes(self,sale_order):
t_res = {}
t_tax_obj = self.pool.get("account.tax")
t_sale_obj = self.pool.get("sale.order")
for t_tax_id, t_tax_amount in t_sale_obj._tax_amount(self.cr,self.uid,sale_order.id,self.localcontext).items():
t_tax = t_tax_obj.browse(self.cr,self.uid,t_tax_id,self.localcontext)
t_amount = t_res.get(t_tax.name,0.0)
t_amount += t_tax_amount
t_res[t_tax.name] = t_amount
return t_res
def prepare(self, sale_order):
prepared_lines = []
order_lines = []
obj_order_line = self.pool.get('sale.order.line')
ids = obj_order_line.search(self.cr, self.uid, [('order_id', '=', sale_order.id)])
for sid in range(0, len(ids)):
order = obj_order_line.browse(self.cr, self.uid, ids[sid], self.localcontext)
order_lines.append(order)
pos = 1
for line in order_lines:
# line name
notes = []
lines = line.name.split("\n")
line_name = lines and lines[0] or ""
if len(lines) > 1:
notes.extend(lines[1:])
# line notes
#if line.note:
# notes.extend(line.note.split("\n"))
line_note = "\n".join(notes)
res = {}
res['tax_id'] = ', '.join(map(lambda x: x.name, line.tax_id)) or ''
res['name'] = line_name
res["note"] = line_note
res['product_uom_qty'] = line.product_uos and line.product_uos_qty or line.product_uom_qty or 0.00
res['product_uom'] = line.product_uos and line.product_uos.name or line.product_uom.name
res['price_unit'] = line.price_unit_untaxed or 0.00
res['discount'] = line.discount or 0.00
res['price_subtotal'] = line.price_subtotal or 0.00
res['price_subtotal_taxed'] = line.price_subtotal_taxed or 0.00
res['currency'] = sale_order.pricelist_id.currency_id.symbol
res['pos'] = str(pos)
res['id'] = line.id
res['price_subtotal_nodisc'] = line.price_subtotal_nodisc or 0.00
pos += 1
prepared_lines.append(res)
res = [{
"lines" : prepared_lines,
}]
return res
def sale_order_lines(self, sale_order):
return self.prepare(sale_order)[0]["lines"]
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
Unilodge @ Metro Adelaide is a boutique student accommodation located on Victoria Street in Adelaide. You will be very centrally placed near Rundle Mall, the entertainment precinct and have the university campuses in Adelaide nearby as well. With amazing attention to detail, quality finishes, advanced technology and environmental excellence, there is everything you would need here for a perfect stay. There are plenty of Indoor and Outdoor Social Spaces such as Games Room, Student Lounge with TV and Foxtel, Dining Area and Outdoor Courtyard for you to enjoy. Choose from a whole range of 2 Bedroom Apartments and if you like you can book the one with balcony as well! There are choices of 1 Bedroom Apartments available as well.
The contemporary and modern design of Unilodge Metro Adelaide accommodation offers you a brilliant student experience in the city. Depending on what exactly you are looking for, you can choose from one of the many 2 bedroom apartments at the property. Few of them come with balconies and some of them are also split into two floors, offering your more space. You will in your room have a very comfortable bed, a workstation, ample storage for all your belongings and a common living area with a fully fitted kitchen. However the bathroom is shared amongst the flatmates. Living in a two-bedroom apartment is the perfect way to enjoy your university life in the city. A two bedroom flat offers you enough privacy when looking to focus on your studies without any distraction and you have the perfect flatmate when you need to unwind and relax after a long study day. Come home to the company of your flatmate, watch your favourite shows together or you can prepare your meals in the kitchen. It is never dull when you have your friend around. If you are looking to have a party, then why not throw one in your own apartment. The living area is perfect to host your friends. There is plenty more at the property for you to enjoy outside of your apartment. The 1 bedroom apartment will be completely self-contained with your personal bed, private bathroom, kitchen, living area, workstation and ample space for storage. To encourage student residents to socialise the property has great social spaces. Work through your stress after a long day in the games room. Play a game of pool or you can challenge your friends to a game of table tennis too! The lounge is perfect for you and your friends to sit together and enjoy a movie or you could simply binge watch on the latest season of Flash! There is an outdoor courtyard as well at the property, perfect for enjoying the brilliant weather and even if you are looking to get a tan!
International students in Adelaide will have plenty to explore, as this city is fast becoming the lifestyle capital of Australia. Catch a match at the Adelaide Oval, it is said to be one of the prettiest cricket ground, you will surely enjoy the experience. The Art Gallery of South Australia is worth a visit too! Enjoy going around and witnessing art from few of the big names in the Australian art circuit. Take one of the free guided tours and afterwards sit down to enjoy some savoury snacks in the Café out back!
You will love the nightlife that the city has to offer. There are plenty of bars and clubs right at your doorstep to enjoy. Head to Red Square Bar with your friends for a great night out, this busy nightclub hosts local and global DJs. So put on your dancing shoes and get ready for a night of fun with your friends. The best part about this place is that it is just 2mins walk away, so you can be home and tucked in bed in no time. There are great restaurants around the property as well. If you are not in the mood to cook then you can head to Happy Belly Chinese Restaurant with your friends or you can simply get yourself a take-away sub from Subway from across the street. Both these places are within easy walking distance from the property.
Room in a Two Bedroom Apartment - 1 Bedroom Standard Share is nicely built having good storage and living space. It includes private bedroom having a single bed, wardrobe, study desk chair, shared bathroom and an open plan shared kitchen. The apartment is well equipped with all modern amenities required for an easy and comfortable living.
Two Bedroom is nicely built having good storage and living space. It includes private bedroom having single bed, wardrobe, study desk chair, shared bathroom and an open plan shared kitchen. The apartment is well equipped with all modern amenities required for an easy and comfortable living.
Two Bedroom Deluxe with Balcony is nicely built having good storage and living space. It includes private bedroom having single bed, wardrobe. study desk chair, shared bathroom and an open plan shared kitchen and a balcony. The apartment is well equipped with all modern amenities required for an easy and comfortable living.
Two Bedroom Deluxe is nicely built having good storage and living space. It includes private bedroom having single bed, wardrobe. study desk chair, private bathroom and an open plan shared kitchen and a balcony. The apartment is well equipped with all modern amenities required for an easy and comfortable living.
Two Bedroom Penthouse Loft is nicely built in 68sqm area having good storage and living space. It includes private bedroom having single bed, wardrobe. study desk chair, shared bathroom and an open plan shared kitchen. The penthouse is well equipped with all modern amenities required for an easy and comfortable living.
Two Bedroom Penthouse Loft Deluxe is nicely built in 74sqm area having good storage and living space. It includes private bedroom having single bed, wardrobe. study desk chair, shared bathroom and an open plan shared kitchen. The penthouse is well equipped with all modern amenities required for an easy and comfortable living.
One Bedroom Apartment is nicely built having good storage and living space. It includes private bedroom having single bed, wardrobe, study desk chair, private bathroom and an open plan private kitchen. The apartment is well equipped with all modern amenities required for an easy and comfortable living.
One Bedroom with Balcony is nicely built having good storage and living space. It includes private bedroom having single bed, wardrobe, study desk chair, private bathroom, an open plan private kitchen and a balcony. The apartment is well equipped with all modern amenities required for an easy and comfortable living.
One Bedroom Deluxe with Balcony is nicely built having good storage and living space. It includes private bedroom having single bed, wardrobe, study desk chair, private bathroom, an open plan private kitchen and a balcony. The apartment is well equipped with all modern amenities required for an easy and comfortable living.
One Bedroom Queen is nicely built having good storage and living space. It includes private bedroom having single bed, wardrobe, study desk chair, private bathroom, an open plan private kitchen. The apartment is well equipped with all modern amenities required for an easy and comfortable living.
Electricity connection, internet connection and water is included in your rent.
|
#!/usr/bin/python
# Copyright 2017 SuperDARN Canada
#
# brian.py
# 2018-01-30
# Communicate with all processes to administrate the borealis software
import sys
import os
import time
from datetime import datetime
import threading
import argparse
import zmq
sys.path.append(os.environ["BOREALISPATH"])
if __debug__:
sys.path.append(os.environ["BOREALISPATH"] + '/build/debug/utils/protobuf') # TODO need to get this from scons environment, 'release' may be 'debug'
else:
sys.path.append(os.environ["BOREALISPATH"] + '/build/release/utils/protobuf')
import driverpacket_pb2
import sigprocpacket_pb2
import rxsamplesmetadata_pb2
import processeddata_pb2
sys.path.append(os.environ["BOREALISPATH"] + '/utils/experiment_options')
import experimentoptions as options
sys.path.append(os.environ["BOREALISPATH"] + '/utils/zmq_borealis_helpers')
import socket_operations as so
TIME_PROFILE = True
def router(opts):
"""The router is responsible for moving traffic between modules by routing traffic using
named sockets.
Args:
opts (ExperimentOptions): Options parsed from config.
"""
context = zmq.Context().instance()
router = context.socket(zmq.ROUTER)
router.setsockopt(zmq.ROUTER_MANDATORY, 1)
router.bind(opts.router_address)
sys.stdout.write("Starting router!\n")
frames_to_send = []
while True:
events = router.poll(timeout=1)
if events:
dd = router.recv_multipart()
sender, receiver, empty, data = dd
if __debug__:
output = "Router input/// Sender -> {}: Receiver -> {}\n"
output = output.format(sender, receiver)
sys.stdout.write(output)
frames_received = [receiver,sender,empty,data]
frames_to_send.append(frames_received)
if __debug__:
output = "Router output/// Receiver -> {}: Sender -> {}\n"
output = output.format(receiver, sender)
sys.stdout.write(output)
non_sent = []
for frames in frames_to_send:
try:
router.send_multipart(frames)
except zmq.ZMQError as e:
if __debug__:
output = "Unable to send frame Receiver -> {}: Sender -> {}\n"
output = output.format(frames[0], frames[1])
sys.stdout.write(output)
non_sent.append(frames)
frames_to_send = non_sent
def sequence_timing(opts):
"""Thread function for sequence timing
This function simulates the flow of data between brian's sequence timing and other parts of the
radar system. This function serves to check whether the sequence timing is working as expected
and to rate control the system to make sure the processing can handle data rates.
:param context: zmq context, if None, then this method will get one
:type context: zmq context, optional
"""
ids = [opts.brian_to_radctrl_identity,
opts.brian_to_driver_identity,
opts.brian_to_dspbegin_identity,
opts.brian_to_dspend_identity]
sockets_list = so.create_sockets(ids, opts.router_address)
brian_to_radar_control = sockets_list[0]
brian_to_driver = sockets_list[1]
brian_to_dsp_begin = sockets_list[2]
brian_to_dsp_end = sockets_list[3]
sequence_poller = zmq.Poller()
sequence_poller.register(brian_to_radar_control, zmq.POLLIN)
sequence_poller.register(brian_to_dsp_begin, zmq.POLLIN)
sequence_poller.register(brian_to_dsp_end, zmq.POLLIN)
sequence_poller.register(brian_to_driver, zmq.POLLIN)
def printing(msg):
SEQUENCE_TIMING = "\033[31m" + "SEQUENCE TIMING: " + "\033[0m"
sys.stdout.write(SEQUENCE_TIMING + msg + "\n")
context = zmq.Context().instance()
start_new_sock = context.socket(zmq.PAIR)
start_new_sock.bind("inproc://start_new")
def start_new():
""" This function serves to rate control the system. If processing is faster than the
sequence time than the speed of the driver is the limiting factor. If processing takes
longer than sequence time, than the dsp unit limits the speed of the system.
"""
start_new = context.socket(zmq.PAIR)
start_new.connect("inproc://start_new")
want_to_start = False
good_to_start = True
dsp_finish_counter = 2
# starting a new sequence and keeping the system correctly pipelined is dependent on 3
# conditions. We trigger a 'want_to_start' when the samples have been collected from the
# driver and dsp is ready to do its job. This signals that the driver is capable of
# collecting new data. 'good_to_start' is triggered once the samples have been copied to
# the GPU and the filtering begins. 'extra_good_to_start' is needed to make sure the
# system can keep up with the demand if the gpu is working hard. Without this flag its
# possible to overload the gpu and crash the system with overallocation of memory. This
# is set once the filtering is complete.
#
# The last flag is actually a counter because on the first run it is 2 sequences
# behind the current sequence and then after that its only 1 sequence behind. The dsp
# is always processing the work while a new sequence is being collected.
if TIME_PROFILE:
time_now = datetime.utcnow()
while True:
if want_to_start and good_to_start and dsp_finish_counter:
#Acknowledge new sequence can begin to Radar Control by requesting new sequence
#metadata
if __debug__:
printing("Requesting metadata from Radar control")
so.send_request(brian_to_radar_control, opts.radctrl_to_brian_identity,
"Requesting metadata")
want_to_start = good_to_start = False
dsp_finish_counter -= 1
message = start_new.recv_string()
if message == "want_to_start":
if TIME_PROFILE:
print('Driver ready: {}'.format(datetime.utcnow() - time_now))
time_now = datetime.utcnow()
want_to_start = True
if message == "good_to_start":
if TIME_PROFILE:
print('Copied to GPU: {}'.format(datetime.utcnow() - time_now))
time_now = datetime.utcnow()
good_to_start = True
if message == "extra_good_to_start":
if TIME_PROFILE:
print('DSP finished w/ data: {}'.format(datetime.utcnow() - time_now))
time_now = datetime.utcnow()
dsp_finish_counter = 1;
thread = threading.Thread(target=start_new)
thread.daemon = True
thread.start()
time.sleep(1)
last_processing_time = 0
first_time = True
late_counter = 0
while True:
if first_time:
#Request new sequence metadata
if __debug__:
printing("Requesting metadata from Radar control")
so.send_request(brian_to_radar_control, opts.radctrl_to_brian_identity,
"Requesting metadata")
first_time = False
socks = dict(sequence_poller.poll())
if brian_to_driver in socks and socks[brian_to_driver] == zmq.POLLIN:
#Receive metadata of completed sequence from driver such as timing
reply = so.recv_obj(brian_to_driver, opts.driver_to_brian_identity, printing)
meta = rxsamplesmetadata_pb2.RxSamplesMetadata()
meta.ParseFromString(reply)
if __debug__:
reply_output = "Driver sent -> time {} ms, sqnum {}"
reply_output = reply_output.format(meta.sequence_time*1e3, meta.sequence_num)
printing(reply_output)
#Requesting acknowledgement of work begins from DSP
if __debug__:
printing("Requesting work begins from DSP")
iden = opts.dspbegin_to_brian_identity + str(meta.sequence_num)
so.send_request(brian_to_dsp_begin, iden, "Requesting work begins")
start_new_sock.send_string("want_to_start")
if brian_to_radar_control in socks and socks[brian_to_radar_control] == zmq.POLLIN:
#Get new sequence metadata from radar control
reply = so.recv_obj(brian_to_radar_control, opts.radctrl_to_brian_identity, printing)
sigp = sigprocpacket_pb2.SigProcPacket()
sigp.ParseFromString(reply)
if __debug__:
reply_output = "Radar control sent -> sequence {} time {} ms"
reply_output = reply_output.format(sigp.sequence_num, sigp.sequence_time)
printing(reply_output)
#Request acknowledgement of sequence from driver
if __debug__:
printing("Requesting ack from driver")
so.send_request(brian_to_driver, opts.driver_to_brian_identity, "Requesting ack")
if brian_to_dsp_begin in socks and socks[brian_to_dsp_begin] == zmq.POLLIN:
#Get acknowledgement that work began in processing.
reply = so.recv_bytes_from_any_iden(brian_to_dsp_begin)
sig_p = sigprocpacket_pb2.SigProcPacket()
sig_p.ParseFromString(reply)
if __debug__:
reply_output = "Dsp began -> sqnum {}".format(sig_p.sequence_num)
printing(reply_output)
#Requesting acknowledgement of work ends from DSP
if __debug__:
printing("Requesting work end from DSP")
iden = opts.dspend_to_brian_identity + str(sig_p.sequence_num)
so.send_request(brian_to_dsp_end, iden, "Requesting work ends")
#acknowledge we want to start something new.
start_new_sock.send_string("good_to_start")
if brian_to_dsp_end in socks and socks[brian_to_dsp_end] == zmq.POLLIN:
#Receive ack that work finished on previous sequence.
reply = so.recv_bytes_from_any_iden(brian_to_dsp_end)
sig_p = sigprocpacket_pb2.SigProcPacket()
sig_p.ParseFromString(reply)
if __debug__:
reply_output = "Dsp sent -> time {}, sqnum {}"
reply_output = reply_output.format(sig_p.kerneltime, sig_p.sequence_num)
printing(reply_output)
if sig_p.sequence_num != 0:
if sig_p.kerneltime > last_processing_time:
late_counter += 1
else:
late_counter = 0
last_processing_time = sig_p.kerneltime
if __debug__:
printing("Late counter {}".format(late_counter))
#acknowledge that we are good and able to start something new.
start_new_sock.send_string("extra_good_to_start")
def main():
parser = argparse.ArgumentParser()
help_msg = 'Run only the router. Do not run any of the other threads or functions.'
parser.add_argument('--router-only', action='store_true', help=help_msg)
args = parser.parse_args()
opts = options.ExperimentOptions()
threads = []
threads.append(threading.Thread(target=router, args=(opts,)))
if not args.router_only:
threads.append(threading.Thread(target=sequence_timing, args=(opts,)))
for thread in threads:
thread.daemon = True
thread.start()
while True:
time.sleep(1)
if __name__ == "__main__":
main()
|
After his tweet yesterday announcing the 51% attack on Bitcoin Gold, Litecoin’s Charlie Lee proved the dominance of Litecoin in all altcoins that used Scrypt for Proof of Work.
Scrypt is a password-key based derivation function. The function was created by Colin Percival and was specifically designed to make it costly to perform large-scale hardware attacks.
|
"""
"""
import json
import logging
import decimal
from mitxmako.shortcuts import render_to_response
from django.conf import settings
from django.core.urlresolvers import reverse
from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseRedirect
from django.shortcuts import redirect
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from django.views.generic.base import View
from django.utils.decorators import method_decorator
from django.utils.translation import ugettext as _
from django.utils.http import urlencode
from django.contrib.auth.decorators import login_required
from course_modes.models import CourseMode
from student.models import CourseEnrollment
from student.views import course_from_id
from shoppingcart.models import Order, CertificateItem
from shoppingcart.processors.CyberSource import (
get_signed_purchase_params, get_purchase_endpoint
)
from verify_student.models import SoftwareSecurePhotoVerification
import ssencrypt
log = logging.getLogger(__name__)
class VerifyView(View):
@method_decorator(login_required)
def get(self, request, course_id):
"""
"""
# If the user has already been verified within the given time period,
# redirect straight to the payment -- no need to verify again.
if SoftwareSecurePhotoVerification.user_has_valid_or_pending(request.user):
return redirect(
reverse('verify_student_verified',
kwargs={'course_id': course_id}))
elif CourseEnrollment.enrollment_mode_for_user(request.user, course_id) == 'verified':
return redirect(reverse('dashboard'))
else:
# If they haven't completed a verification attempt, we have to
# restart with a new one. We can't reuse an older one because we
# won't be able to show them their encrypted photo_id -- it's easier
# bookkeeping-wise just to start over.
progress_state = "start"
verify_mode = CourseMode.mode_for_course(course_id, "verified")
# if the course doesn't have a verified mode, we want to kick them
# from the flow
if not verify_mode:
return redirect(reverse('dashboard'))
if course_id in request.session.get("donation_for_course", {}):
chosen_price = request.session["donation_for_course"][course_id]
else:
chosen_price = verify_mode.min_price
course = course_from_id(course_id)
context = {
"progress_state": progress_state,
"user_full_name": request.user.profile.name,
"course_id": course_id,
"course_name": course.display_name_with_default,
"course_org" : course.display_org_with_default,
"course_num" : course.display_number_with_default,
"purchase_endpoint": get_purchase_endpoint(),
"suggested_prices": [
decimal.Decimal(price)
for price in verify_mode.suggested_prices.split(",")
],
"currency": verify_mode.currency.upper(),
"chosen_price": chosen_price,
"min_price": verify_mode.min_price,
}
return render_to_response('verify_student/photo_verification.html', context)
class VerifiedView(View):
"""
View that gets shown once the user has already gone through the
verification flow
"""
@method_decorator(login_required)
def get(self, request, course_id):
"""
Handle the case where we have a get request
"""
if CourseEnrollment.enrollment_mode_for_user(request.user, course_id) == 'verified':
return redirect(reverse('dashboard'))
verify_mode = CourseMode.mode_for_course(course_id, "verified")
if course_id in request.session.get("donation_for_course", {}):
chosen_price = request.session["donation_for_course"][course_id]
else:
chosen_price = verify_mode.min_price.format("{:g}")
course = course_from_id(course_id)
context = {
"course_id": course_id,
"course_name": course.display_name_with_default,
"course_org" : course.display_org_with_default,
"course_num" : course.display_number_with_default,
"purchase_endpoint": get_purchase_endpoint(),
"currency": verify_mode.currency.upper(),
"chosen_price": chosen_price,
}
return render_to_response('verify_student/verified.html', context)
@login_required
def create_order(request):
"""
Submit PhotoVerification and create a new Order for this verified cert
"""
if not SoftwareSecurePhotoVerification.user_has_valid_or_pending(request.user):
attempt = SoftwareSecurePhotoVerification(user=request.user)
b64_face_image = request.POST['face_image'].split(",")[1]
b64_photo_id_image = request.POST['photo_id_image'].split(",")[1]
attempt.upload_face_image(b64_face_image.decode('base64'))
attempt.upload_photo_id_image(b64_photo_id_image.decode('base64'))
attempt.mark_ready()
attempt.save()
course_id = request.POST['course_id']
donation_for_course = request.session.get('donation_for_course', {})
current_donation = donation_for_course.get(course_id, decimal.Decimal(0))
contribution = request.POST.get("contribution", donation_for_course.get(course_id, 0))
try:
amount = decimal.Decimal(contribution).quantize(decimal.Decimal('.01'), rounding=decimal.ROUND_DOWN)
except decimal.InvalidOperation:
return HttpResponseBadRequest(_("Selected price is not valid number."))
if amount != current_donation:
donation_for_course[course_id] = amount
request.session['donation_for_course'] = donation_for_course
verified_mode = CourseMode.modes_for_course_dict(course_id).get('verified', None)
# make sure this course has a verified mode
if not verified_mode:
return HttpResponseBadRequest(_("This course doesn't support verified certificates"))
if amount < verified_mode.min_price:
return HttpResponseBadRequest(_("No selected price or selected price is below minimum."))
# I know, we should check this is valid. All kinds of stuff missing here
cart = Order.get_cart_for_user(request.user)
cart.clear()
CertificateItem.add_to_order(cart, course_id, amount, 'verified')
params = get_signed_purchase_params(cart)
return HttpResponse(json.dumps(params), content_type="text/json")
@require_POST
@csrf_exempt # SS does its own message signing, and their API won't have a cookie value
def results_callback(request):
"""
Software Secure will call this callback to tell us whether a user is
verified to be who they said they are.
"""
body = request.body
try:
body_dict = json.loads(body)
except ValueError:
log.exception("Invalid JSON received from Software Secure:\n\n{}\n".format(body))
return HttpResponseBadRequest("Invalid JSON. Received:\n\n{}".format(body))
if not isinstance(body_dict, dict):
log.error("Reply from Software Secure is not a dict:\n\n{}\n".format(body))
return HttpResponseBadRequest("JSON should be dict. Received:\n\n{}".format(body))
headers = {
"Authorization": request.META.get("HTTP_AUTHORIZATION", ""),
"Date": request.META.get("HTTP_DATE", "")
}
sig_valid = ssencrypt.has_valid_signature(
"POST",
headers,
body_dict,
settings.VERIFY_STUDENT["SOFTWARE_SECURE"]["API_ACCESS_KEY"],
settings.VERIFY_STUDENT["SOFTWARE_SECURE"]["API_SECRET_KEY"]
)
_, access_key_and_sig = headers["Authorization"].split(" ")
access_key = access_key_and_sig.split(":")[0]
# This is what we should be doing...
#if not sig_valid:
# return HttpResponseBadRequest("Signature is invalid")
# This is what we're doing until we can figure out why we disagree on sigs
if access_key != settings.VERIFY_STUDENT["SOFTWARE_SECURE"]["API_ACCESS_KEY"]:
return HttpResponseBadRequest("Access key invalid")
receipt_id = body_dict.get("EdX-ID")
result = body_dict.get("Result")
reason = body_dict.get("Reason", "")
error_code = body_dict.get("MessageType", "")
try:
attempt = SoftwareSecurePhotoVerification.objects.get(receipt_id=receipt_id)
except SoftwareSecurePhotoVerification.DoesNotExist:
log.error("Software Secure posted back for receipt_id {}, but not found".format(receipt_id))
return HttpResponseBadRequest("edX ID {} not found".format(receipt_id))
if result == "PASS":
log.debug("Approving verification for {}".format(receipt_id))
attempt.approve()
elif result == "FAIL":
log.debug("Denying verification for {}".format(receipt_id))
attempt.deny(json.dumps(reason), error_code=error_code)
elif result == "SYSTEM FAIL":
log.debug("System failure for {} -- resetting to must_retry".format(receipt_id))
attempt.system_error(json.dumps(reason), error_code=error_code)
log.error("Software Secure callback attempt for %s failed: %s", receipt_id, reason)
else:
log.error("Software Secure returned unknown result {}".format(result))
return HttpResponseBadRequest(
"Result {} not understood. Known results: PASS, FAIL, SYSTEM FAIL".format(result)
)
return HttpResponse("OK!")
@login_required
def show_requirements(request, course_id):
"""
Show the requirements necessary for
"""
if CourseEnrollment.enrollment_mode_for_user(request.user, course_id) == 'verified':
return redirect(reverse('dashboard'))
course = course_from_id(course_id)
context = {
"course_id": course_id,
"course_name": course.display_name_with_default,
"course_org" : course.display_org_with_default,
"course_num" : course.display_number_with_default,
"is_not_active": not request.user.is_active,
}
return render_to_response("verify_student/show_requirements.html", context)
def show_verification_page(request):
pass
def enroll(user, course_id, mode_slug):
"""
Enroll the user in a course for a certain mode.
This is the view you send folks to when they click on the enroll button.
This does NOT cover changing enrollment modes -- it's intended for new
enrollments only, and will just redirect to the dashboard if it detects
that an enrollment already exists.
"""
# If the user is already enrolled, jump to the dashboard. Yeah, we could
# do upgrades here, but this method is complicated enough.
if CourseEnrollment.is_enrolled(user, course_id):
return HttpResponseRedirect(reverse('dashboard'))
available_modes = CourseModes.modes_for_course(course_id)
# If they haven't chosen a mode...
if not mode_slug:
# Does this course support multiple modes of Enrollment? If so, redirect
# to a page that lets them choose which mode they want.
if len(available_modes) > 1:
return HttpResponseRedirect(
reverse('choose_enroll_mode', kwargs={'course_id': course_id})
)
# Otherwise, we use the only mode that's supported...
else:
mode_slug = available_modes[0].slug
# If the mode is one of the simple, non-payment ones, do the enrollment and
# send them to their dashboard.
if mode_slug in ("honor", "audit"):
CourseEnrollment.enroll(user, course_id, mode=mode_slug)
return HttpResponseRedirect(reverse('dashboard'))
if mode_slug == "verify":
if SoftwareSecurePhotoVerification.has_submitted_recent_request(user):
# Capture payment info
# Create an order
# Create a VerifiedCertificate order item
return HttpResponse.Redirect(reverse('verified'))
# There's always at least one mode available (default is "honor"). If they
# haven't specified a mode, we just assume it's
if not mode:
mode = available_modes[0]
elif len(available_modes) == 1:
if mode != available_modes[0]:
raise Exception()
mode = available_modes[0]
if mode == "honor":
CourseEnrollment.enroll(user, course_id)
return HttpResponseRedirect(reverse('dashboard'))
|
By doing that the IP address of Host-Server and Stream URL has been changed but out stream stopped working.
We are looking forward to host and test it on public IP to demonstrate it to customer. Please guide us, we are doing something wrong or is there any other way to achieve it?
when i go YOUR_IPADDRESS in browser, im getting a login screen for something. you might could get issues with that when using port 80 in your wowza setup.
how do you access the enginemanager on localhost? are you running a windows server?
you dont have to change the ipadress. If its * its also usable for the given ip.
what do you mean by out stream stopped?
2. Is your public ipaddress working on the network adapter?
Firewall: Did you setup your firewall correct or did you open the correct ports to it?
|
# Copyright 2011 OpenStack Foundation
# All Rights Reserved.
# Copyright 2013 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Tests For miscellaneous util methods used with compute."""
import copy
import string
import uuid
import mock
from oslo_serialization import jsonutils
import six
from nova.compute import flavors
from nova.compute import manager
from nova.compute import power_state
from nova.compute import task_states
from nova.compute import utils as compute_utils
import nova.conf
from nova import context
from nova import exception
from nova.image import glance
from nova.network import model
from nova import objects
from nova.objects import base
from nova.objects import block_device as block_device_obj
from nova.objects import fields
from nova import rpc
from nova import test
from nova.tests.unit import fake_block_device
from nova.tests.unit import fake_instance
from nova.tests.unit import fake_network
from nova.tests.unit import fake_notifier
from nova.tests.unit import fake_server_actions
import nova.tests.unit.image.fake
from nova.tests.unit.objects import test_flavor
from nova.tests import uuidsentinel as uuids
CONF = nova.conf.CONF
FAKE_IMAGE_REF = uuids.image_ref
def create_instance(context, user_id='fake', project_id='fake', params=None):
"""Create a test instance."""
flavor = flavors.get_flavor_by_name('m1.tiny')
net_info = model.NetworkInfo([])
info_cache = objects.InstanceInfoCache(network_info=net_info)
inst = objects.Instance(context=context,
image_ref=uuids.fake_image_ref,
reservation_id='r-fakeres',
user_id=user_id,
project_id=project_id,
instance_type_id=flavor.id,
flavor=flavor,
old_flavor=None,
new_flavor=None,
system_metadata={},
ami_launch_index=0,
root_gb=0,
ephemeral_gb=0,
info_cache=info_cache)
if params:
inst.update(params)
inst.create()
return inst
class ComputeValidateDeviceTestCase(test.NoDBTestCase):
def setUp(self):
super(ComputeValidateDeviceTestCase, self).setUp()
self.context = context.RequestContext('fake', 'fake')
# check if test name includes "xen"
if 'xen' in self.id():
self.flags(compute_driver='xenapi.XenAPIDriver')
self.instance = objects.Instance(uuid=uuid.uuid4().hex,
root_device_name=None,
default_ephemeral_device=None)
else:
self.instance = objects.Instance(uuid=uuid.uuid4().hex,
root_device_name='/dev/vda',
default_ephemeral_device='/dev/vdb')
flavor = objects.Flavor(**test_flavor.fake_flavor)
self.instance.system_metadata = {}
self.instance.flavor = flavor
self.instance.default_swap_device = None
self.data = []
def _validate_device(self, device=None):
bdms = base.obj_make_list(self.context,
objects.BlockDeviceMappingList(), objects.BlockDeviceMapping,
self.data)
return compute_utils.get_device_name_for_instance(
self.instance, bdms, device)
@staticmethod
def _fake_bdm(device):
return fake_block_device.FakeDbBlockDeviceDict({
'source_type': 'volume',
'destination_type': 'volume',
'device_name': device,
'no_device': None,
'volume_id': 'fake',
'snapshot_id': None,
'guest_format': None
})
def test_wrap(self):
self.data = []
for letter in string.ascii_lowercase[2:]:
self.data.append(self._fake_bdm('/dev/vd' + letter))
device = self._validate_device()
self.assertEqual(device, '/dev/vdaa')
def test_wrap_plus_one(self):
self.data = []
for letter in string.ascii_lowercase[2:]:
self.data.append(self._fake_bdm('/dev/vd' + letter))
self.data.append(self._fake_bdm('/dev/vdaa'))
device = self._validate_device()
self.assertEqual(device, '/dev/vdab')
def test_later(self):
self.data = [
self._fake_bdm('/dev/vdc'),
self._fake_bdm('/dev/vdd'),
self._fake_bdm('/dev/vde'),
]
device = self._validate_device()
self.assertEqual(device, '/dev/vdf')
def test_gap(self):
self.data = [
self._fake_bdm('/dev/vdc'),
self._fake_bdm('/dev/vde'),
]
device = self._validate_device()
self.assertEqual(device, '/dev/vdd')
def test_no_bdms(self):
self.data = []
device = self._validate_device()
self.assertEqual(device, '/dev/vdc')
def test_lxc_names_work(self):
self.instance['root_device_name'] = '/dev/a'
self.instance['ephemeral_device_name'] = '/dev/b'
self.data = []
device = self._validate_device()
self.assertEqual(device, '/dev/c')
def test_name_conversion(self):
self.data = []
device = self._validate_device('/dev/c')
self.assertEqual(device, '/dev/vdc')
device = self._validate_device('/dev/sdc')
self.assertEqual(device, '/dev/vdc')
device = self._validate_device('/dev/xvdc')
self.assertEqual(device, '/dev/vdc')
def test_invalid_device_prefix(self):
self.assertRaises(exception.InvalidDevicePath,
self._validate_device, '/baddata/vdc')
def test_device_in_use(self):
exc = self.assertRaises(exception.DevicePathInUse,
self._validate_device, '/dev/vda')
self.assertIn('/dev/vda', six.text_type(exc))
def test_swap(self):
self.instance['default_swap_device'] = "/dev/vdc"
device = self._validate_device()
self.assertEqual(device, '/dev/vdd')
def test_swap_no_ephemeral(self):
self.instance.default_ephemeral_device = None
self.instance.default_swap_device = "/dev/vdb"
device = self._validate_device()
self.assertEqual(device, '/dev/vdc')
def test_ephemeral_xenapi(self):
self.instance.flavor.ephemeral_gb = 10
self.instance.flavor.swap = 0
device = self._validate_device()
self.assertEqual(device, '/dev/xvdc')
def test_swap_xenapi(self):
self.instance.flavor.ephemeral_gb = 0
self.instance.flavor.swap = 10
device = self._validate_device()
self.assertEqual(device, '/dev/xvdb')
def test_swap_and_ephemeral_xenapi(self):
self.instance.flavor.ephemeral_gb = 10
self.instance.flavor.swap = 10
device = self._validate_device()
self.assertEqual(device, '/dev/xvdd')
def test_swap_and_one_attachment_xenapi(self):
self.instance.flavor.ephemeral_gb = 0
self.instance.flavor.swap = 10
device = self._validate_device()
self.assertEqual(device, '/dev/xvdb')
self.data.append(self._fake_bdm(device))
device = self._validate_device()
self.assertEqual(device, '/dev/xvdd')
def test_no_dev_root_device_name_get_next_name(self):
self.instance['root_device_name'] = 'vda'
device = self._validate_device()
self.assertEqual('/dev/vdc', device)
class DefaultDeviceNamesForInstanceTestCase(test.NoDBTestCase):
def setUp(self):
super(DefaultDeviceNamesForInstanceTestCase, self).setUp()
self.context = context.RequestContext('fake', 'fake')
self.ephemerals = block_device_obj.block_device_make_list(
self.context,
[fake_block_device.FakeDbBlockDeviceDict(
{'id': 1,
'instance_uuid': uuids.block_device_instance,
'device_name': '/dev/vdb',
'source_type': 'blank',
'destination_type': 'local',
'delete_on_termination': True,
'guest_format': None,
'boot_index': -1})])
self.swap = block_device_obj.block_device_make_list(
self.context,
[fake_block_device.FakeDbBlockDeviceDict(
{'id': 2,
'instance_uuid': uuids.block_device_instance,
'device_name': '/dev/vdc',
'source_type': 'blank',
'destination_type': 'local',
'delete_on_termination': True,
'guest_format': 'swap',
'boot_index': -1})])
self.block_device_mapping = block_device_obj.block_device_make_list(
self.context,
[fake_block_device.FakeDbBlockDeviceDict(
{'id': 3,
'instance_uuid': uuids.block_device_instance,
'device_name': '/dev/vda',
'source_type': 'volume',
'destination_type': 'volume',
'volume_id': 'fake-volume-id-1',
'boot_index': 0}),
fake_block_device.FakeDbBlockDeviceDict(
{'id': 4,
'instance_uuid': uuids.block_device_instance,
'device_name': '/dev/vdd',
'source_type': 'snapshot',
'destination_type': 'volume',
'snapshot_id': 'fake-snapshot-id-1',
'boot_index': -1}),
fake_block_device.FakeDbBlockDeviceDict(
{'id': 5,
'instance_uuid': uuids.block_device_instance,
'device_name': '/dev/vde',
'source_type': 'blank',
'destination_type': 'volume',
'boot_index': -1})])
self.instance = {'uuid': uuids.instance,
'ephemeral_gb': 2}
self.is_libvirt = False
self.root_device_name = '/dev/vda'
self.update_called = False
self.patchers = []
self.patchers.append(
mock.patch.object(objects.BlockDeviceMapping, 'save'))
for patcher in self.patchers:
patcher.start()
def tearDown(self):
super(DefaultDeviceNamesForInstanceTestCase, self).tearDown()
for patcher in self.patchers:
patcher.stop()
def _test_default_device_names(self, *block_device_lists):
compute_utils.default_device_names_for_instance(self.instance,
self.root_device_name,
*block_device_lists)
def test_only_block_device_mapping(self):
# Test no-op
original_bdm = copy.deepcopy(self.block_device_mapping)
self._test_default_device_names([], [], self.block_device_mapping)
for original, new in zip(original_bdm, self.block_device_mapping):
self.assertEqual(original.device_name, new.device_name)
# Assert it defaults the missing one as expected
self.block_device_mapping[1]['device_name'] = None
self.block_device_mapping[2]['device_name'] = None
self._test_default_device_names([], [], self.block_device_mapping)
self.assertEqual('/dev/vdb',
self.block_device_mapping[1]['device_name'])
self.assertEqual('/dev/vdc',
self.block_device_mapping[2]['device_name'])
def test_with_ephemerals(self):
# Test ephemeral gets assigned
self.ephemerals[0]['device_name'] = None
self._test_default_device_names(self.ephemerals, [],
self.block_device_mapping)
self.assertEqual(self.ephemerals[0]['device_name'], '/dev/vdb')
self.block_device_mapping[1]['device_name'] = None
self.block_device_mapping[2]['device_name'] = None
self._test_default_device_names(self.ephemerals, [],
self.block_device_mapping)
self.assertEqual('/dev/vdc',
self.block_device_mapping[1]['device_name'])
self.assertEqual('/dev/vdd',
self.block_device_mapping[2]['device_name'])
def test_with_swap(self):
# Test swap only
self.swap[0]['device_name'] = None
self._test_default_device_names([], self.swap, [])
self.assertEqual(self.swap[0]['device_name'], '/dev/vdb')
# Test swap and block_device_mapping
self.swap[0]['device_name'] = None
self.block_device_mapping[1]['device_name'] = None
self.block_device_mapping[2]['device_name'] = None
self._test_default_device_names([], self.swap,
self.block_device_mapping)
self.assertEqual(self.swap[0]['device_name'], '/dev/vdb')
self.assertEqual('/dev/vdc',
self.block_device_mapping[1]['device_name'])
self.assertEqual('/dev/vdd',
self.block_device_mapping[2]['device_name'])
def test_all_together(self):
# Test swap missing
self.swap[0]['device_name'] = None
self._test_default_device_names(self.ephemerals,
self.swap, self.block_device_mapping)
self.assertEqual(self.swap[0]['device_name'], '/dev/vdc')
# Test swap and eph missing
self.swap[0]['device_name'] = None
self.ephemerals[0]['device_name'] = None
self._test_default_device_names(self.ephemerals,
self.swap, self.block_device_mapping)
self.assertEqual(self.ephemerals[0]['device_name'], '/dev/vdb')
self.assertEqual(self.swap[0]['device_name'], '/dev/vdc')
# Test all missing
self.swap[0]['device_name'] = None
self.ephemerals[0]['device_name'] = None
self.block_device_mapping[1]['device_name'] = None
self.block_device_mapping[2]['device_name'] = None
self._test_default_device_names(self.ephemerals,
self.swap, self.block_device_mapping)
self.assertEqual(self.ephemerals[0]['device_name'], '/dev/vdb')
self.assertEqual(self.swap[0]['device_name'], '/dev/vdc')
self.assertEqual('/dev/vdd',
self.block_device_mapping[1]['device_name'])
self.assertEqual('/dev/vde',
self.block_device_mapping[2]['device_name'])
class UsageInfoTestCase(test.TestCase):
def setUp(self):
def fake_get_nw_info(cls, ctxt, instance):
self.assertTrue(ctxt.is_admin)
return fake_network.fake_get_instance_nw_info(self, 1, 1)
super(UsageInfoTestCase, self).setUp()
self.stub_out('nova.network.api.get_instance_nw_info',
fake_get_nw_info)
fake_notifier.stub_notifier(self)
self.addCleanup(fake_notifier.reset)
self.flags(compute_driver='fake.FakeDriver',
network_manager='nova.network.manager.FlatManager')
self.compute = manager.ComputeManager()
self.user_id = 'fake'
self.project_id = 'fake'
self.context = context.RequestContext(self.user_id, self.project_id)
def fake_show(meh, context, id, **kwargs):
return {'id': 1, 'properties': {'kernel_id': 1, 'ramdisk_id': 1}}
self.flags(group='glance', api_servers=['http://localhost:9292'])
self.stub_out('nova.tests.unit.image.fake._FakeImageService.show',
fake_show)
fake_network.set_stub_network_methods(self)
fake_server_actions.stub_out_action_events(self)
def test_notify_usage_exists(self):
# Ensure 'exists' notification generates appropriate usage data.
instance = create_instance(self.context)
# Set some system metadata
sys_metadata = {'image_md_key1': 'val1',
'image_md_key2': 'val2',
'other_data': 'meow'}
instance.system_metadata.update(sys_metadata)
instance.save()
compute_utils.notify_usage_exists(
rpc.get_notifier('compute'), self.context, instance)
self.assertEqual(len(fake_notifier.NOTIFICATIONS), 1)
msg = fake_notifier.NOTIFICATIONS[0]
self.assertEqual(msg.priority, 'INFO')
self.assertEqual(msg.event_type, 'compute.instance.exists')
payload = msg.payload
self.assertEqual(payload['tenant_id'], self.project_id)
self.assertEqual(payload['user_id'], self.user_id)
self.assertEqual(payload['instance_id'], instance['uuid'])
self.assertEqual(payload['instance_type'], 'm1.tiny')
type_id = flavors.get_flavor_by_name('m1.tiny')['id']
self.assertEqual(str(payload['instance_type_id']), str(type_id))
flavor_id = flavors.get_flavor_by_name('m1.tiny')['flavorid']
self.assertEqual(str(payload['instance_flavor_id']), str(flavor_id))
for attr in ('display_name', 'created_at', 'launched_at',
'state', 'state_description',
'bandwidth', 'audit_period_beginning',
'audit_period_ending', 'image_meta'):
self.assertIn(attr, payload,
"Key %s not in payload" % attr)
self.assertEqual(payload['image_meta'],
{'md_key1': 'val1', 'md_key2': 'val2'})
image_ref_url = "%s/images/%s" % (glance.generate_glance_url(),
uuids.fake_image_ref)
self.assertEqual(payload['image_ref_url'], image_ref_url)
self.compute.terminate_instance(self.context, instance, [], [])
def test_notify_usage_exists_deleted_instance(self):
# Ensure 'exists' notification generates appropriate usage data.
instance = create_instance(self.context)
# Set some system metadata
sys_metadata = {'image_md_key1': 'val1',
'image_md_key2': 'val2',
'other_data': 'meow'}
instance.system_metadata.update(sys_metadata)
instance.save()
self.compute.terminate_instance(self.context, instance, [], [])
compute_utils.notify_usage_exists(
rpc.get_notifier('compute'), self.context, instance)
msg = fake_notifier.NOTIFICATIONS[-1]
self.assertEqual(msg.priority, 'INFO')
self.assertEqual(msg.event_type, 'compute.instance.exists')
payload = msg.payload
self.assertEqual(payload['tenant_id'], self.project_id)
self.assertEqual(payload['user_id'], self.user_id)
self.assertEqual(payload['instance_id'], instance['uuid'])
self.assertEqual(payload['instance_type'], 'm1.tiny')
type_id = flavors.get_flavor_by_name('m1.tiny')['id']
self.assertEqual(str(payload['instance_type_id']), str(type_id))
flavor_id = flavors.get_flavor_by_name('m1.tiny')['flavorid']
self.assertEqual(str(payload['instance_flavor_id']), str(flavor_id))
for attr in ('display_name', 'created_at', 'launched_at',
'state', 'state_description',
'bandwidth', 'audit_period_beginning',
'audit_period_ending', 'image_meta'):
self.assertIn(attr, payload, "Key %s not in payload" % attr)
self.assertEqual(payload['image_meta'],
{'md_key1': 'val1', 'md_key2': 'val2'})
image_ref_url = "%s/images/%s" % (glance.generate_glance_url(),
uuids.fake_image_ref)
self.assertEqual(payload['image_ref_url'], image_ref_url)
def test_notify_about_instance_action(self):
instance = create_instance(self.context)
compute_utils.notify_about_instance_action(
self.context,
instance,
host='fake-compute',
action='delete',
phase='start')
self.assertEqual(len(fake_notifier.VERSIONED_NOTIFICATIONS), 1)
notification = fake_notifier.VERSIONED_NOTIFICATIONS[0]
self.assertEqual(notification['priority'], 'INFO')
self.assertEqual(notification['event_type'], 'instance.delete.start')
self.assertEqual(notification['publisher_id'],
'nova-compute:fake-compute')
payload = notification['payload']['nova_object.data']
self.assertEqual(payload['tenant_id'], self.project_id)
self.assertEqual(payload['user_id'], self.user_id)
self.assertEqual(payload['uuid'], instance['uuid'])
flavorid = flavors.get_flavor_by_name('m1.tiny')['flavorid']
flavor = payload['flavor']['nova_object.data']
self.assertEqual(str(flavor['flavorid']), flavorid)
for attr in ('display_name', 'created_at', 'launched_at',
'state', 'task_state', 'display_description', 'locked',
'auto_disk_config'):
self.assertIn(attr, payload, "Key %s not in payload" % attr)
self.assertEqual(payload['image_uuid'], uuids.fake_image_ref)
def test_notify_about_volume_swap(self):
instance = create_instance(self.context)
compute_utils.notify_about_volume_swap(
self.context, instance, 'fake-compute',
fields.NotificationAction.VOLUME_SWAP,
fields.NotificationPhase.START,
uuids.old_volume_id, uuids.new_volume_id)
self.assertEqual(len(fake_notifier.VERSIONED_NOTIFICATIONS), 1)
notification = fake_notifier.VERSIONED_NOTIFICATIONS[0]
self.assertEqual('INFO', notification['priority'])
self.assertEqual('instance.%s.%s' %
(fields.NotificationAction.VOLUME_SWAP,
fields.NotificationPhase.START),
notification['event_type'])
self.assertEqual('nova-compute:fake-compute',
notification['publisher_id'])
payload = notification['payload']['nova_object.data']
self.assertEqual(self.project_id, payload['tenant_id'])
self.assertEqual(self.user_id, payload['user_id'])
self.assertEqual(instance['uuid'], payload['uuid'])
flavorid = flavors.get_flavor_by_name('m1.tiny')['flavorid']
flavor = payload['flavor']['nova_object.data']
self.assertEqual(flavorid, str(flavor['flavorid']))
for attr in ('display_name', 'created_at', 'launched_at',
'state', 'task_state'):
self.assertIn(attr, payload)
self.assertEqual(uuids.fake_image_ref, payload['image_uuid'])
self.assertEqual(uuids.old_volume_id, payload['old_volume_id'])
self.assertEqual(uuids.new_volume_id, payload['new_volume_id'])
def test_notify_about_volume_swap_with_error(self):
instance = create_instance(self.context)
try:
# To get exception trace, raise and catch an exception
raise test.TestingException('Volume swap error.')
except Exception as ex:
compute_utils.notify_about_volume_swap(
self.context, instance, 'fake-compute',
fields.NotificationAction.VOLUME_SWAP,
fields.NotificationPhase.ERROR,
uuids.old_volume_id, uuids.new_volume_id, ex)
self.assertEqual(len(fake_notifier.VERSIONED_NOTIFICATIONS), 1)
notification = fake_notifier.VERSIONED_NOTIFICATIONS[0]
self.assertEqual('ERROR', notification['priority'])
self.assertEqual('instance.%s.%s' %
(fields.NotificationAction.VOLUME_SWAP,
fields.NotificationPhase.ERROR),
notification['event_type'])
self.assertEqual('nova-compute:fake-compute',
notification['publisher_id'])
payload = notification['payload']['nova_object.data']
self.assertEqual(self.project_id, payload['tenant_id'])
self.assertEqual(self.user_id, payload['user_id'])
self.assertEqual(instance['uuid'], payload['uuid'])
flavorid = flavors.get_flavor_by_name('m1.tiny')['flavorid']
flavor = payload['flavor']['nova_object.data']
self.assertEqual(flavorid, str(flavor['flavorid']))
for attr in ('display_name', 'created_at', 'launched_at',
'state', 'task_state'):
self.assertIn(attr, payload)
self.assertEqual(uuids.fake_image_ref, payload['image_uuid'])
self.assertEqual(uuids.old_volume_id, payload['old_volume_id'])
self.assertEqual(uuids.new_volume_id, payload['new_volume_id'])
# Check ExceptionPayload
exception_payload = payload['fault']['nova_object.data']
self.assertEqual('TestingException', exception_payload['exception'])
self.assertEqual('Volume swap error.',
exception_payload['exception_message'])
self.assertEqual('test_notify_about_volume_swap_with_error',
exception_payload['function_name'])
self.assertEqual('nova.tests.unit.compute.test_compute_utils',
exception_payload['module_name'])
def test_notify_usage_exists_instance_not_found(self):
# Ensure 'exists' notification generates appropriate usage data.
instance = create_instance(self.context)
self.compute.terminate_instance(self.context, instance, [], [])
compute_utils.notify_usage_exists(
rpc.get_notifier('compute'), self.context, instance)
msg = fake_notifier.NOTIFICATIONS[-1]
self.assertEqual(msg.priority, 'INFO')
self.assertEqual(msg.event_type, 'compute.instance.exists')
payload = msg.payload
self.assertEqual(payload['tenant_id'], self.project_id)
self.assertEqual(payload['user_id'], self.user_id)
self.assertEqual(payload['instance_id'], instance['uuid'])
self.assertEqual(payload['instance_type'], 'm1.tiny')
type_id = flavors.get_flavor_by_name('m1.tiny')['id']
self.assertEqual(str(payload['instance_type_id']), str(type_id))
flavor_id = flavors.get_flavor_by_name('m1.tiny')['flavorid']
self.assertEqual(str(payload['instance_flavor_id']), str(flavor_id))
for attr in ('display_name', 'created_at', 'launched_at',
'state', 'state_description',
'bandwidth', 'audit_period_beginning',
'audit_period_ending', 'image_meta'):
self.assertIn(attr, payload, "Key %s not in payload" % attr)
self.assertEqual(payload['image_meta'], {})
image_ref_url = "%s/images/%s" % (glance.generate_glance_url(),
uuids.fake_image_ref)
self.assertEqual(payload['image_ref_url'], image_ref_url)
def test_notify_about_instance_usage(self):
instance = create_instance(self.context)
# Set some system metadata
sys_metadata = {'image_md_key1': 'val1',
'image_md_key2': 'val2',
'other_data': 'meow'}
instance.system_metadata.update(sys_metadata)
instance.save()
extra_usage_info = {'image_name': 'fake_name'}
compute_utils.notify_about_instance_usage(
rpc.get_notifier('compute'),
self.context, instance, 'create.start',
extra_usage_info=extra_usage_info)
self.assertEqual(len(fake_notifier.NOTIFICATIONS), 1)
msg = fake_notifier.NOTIFICATIONS[0]
self.assertEqual(msg.priority, 'INFO')
self.assertEqual(msg.event_type, 'compute.instance.create.start')
payload = msg.payload
self.assertEqual(payload['tenant_id'], self.project_id)
self.assertEqual(payload['user_id'], self.user_id)
self.assertEqual(payload['instance_id'], instance['uuid'])
self.assertEqual(payload['instance_type'], 'm1.tiny')
type_id = flavors.get_flavor_by_name('m1.tiny')['id']
self.assertEqual(str(payload['instance_type_id']), str(type_id))
flavor_id = flavors.get_flavor_by_name('m1.tiny')['flavorid']
self.assertEqual(str(payload['instance_flavor_id']), str(flavor_id))
for attr in ('display_name', 'created_at', 'launched_at',
'state', 'state_description', 'image_meta'):
self.assertIn(attr, payload, "Key %s not in payload" % attr)
self.assertEqual(payload['image_meta'],
{'md_key1': 'val1', 'md_key2': 'val2'})
self.assertEqual(payload['image_name'], 'fake_name')
image_ref_url = "%s/images/%s" % (glance.generate_glance_url(),
uuids.fake_image_ref)
self.assertEqual(payload['image_ref_url'], image_ref_url)
self.compute.terminate_instance(self.context, instance, [], [])
def test_notify_about_aggregate_update_with_id(self):
# Set aggregate payload
aggregate_payload = {'aggregate_id': 1}
compute_utils.notify_about_aggregate_update(self.context,
"create.end",
aggregate_payload)
self.assertEqual(len(fake_notifier.NOTIFICATIONS), 1)
msg = fake_notifier.NOTIFICATIONS[0]
self.assertEqual(msg.priority, 'INFO')
self.assertEqual(msg.event_type, 'aggregate.create.end')
payload = msg.payload
self.assertEqual(payload['aggregate_id'], 1)
def test_notify_about_aggregate_update_with_name(self):
# Set aggregate payload
aggregate_payload = {'name': 'fakegroup'}
compute_utils.notify_about_aggregate_update(self.context,
"create.start",
aggregate_payload)
self.assertEqual(len(fake_notifier.NOTIFICATIONS), 1)
msg = fake_notifier.NOTIFICATIONS[0]
self.assertEqual(msg.priority, 'INFO')
self.assertEqual(msg.event_type, 'aggregate.create.start')
payload = msg.payload
self.assertEqual(payload['name'], 'fakegroup')
def test_notify_about_aggregate_update_without_name_id(self):
# Set empty aggregate payload
aggregate_payload = {}
compute_utils.notify_about_aggregate_update(self.context,
"create.start",
aggregate_payload)
self.assertEqual(len(fake_notifier.NOTIFICATIONS), 0)
class ComputeUtilsGetValFromSysMetadata(test.NoDBTestCase):
def test_get_value_from_system_metadata(self):
instance = fake_instance.fake_instance_obj('fake-context')
system_meta = {'int_val': 1,
'int_string': '2',
'not_int': 'Nope'}
instance.system_metadata = system_meta
result = compute_utils.get_value_from_system_metadata(
instance, 'int_val', int, 0)
self.assertEqual(1, result)
result = compute_utils.get_value_from_system_metadata(
instance, 'int_string', int, 0)
self.assertEqual(2, result)
result = compute_utils.get_value_from_system_metadata(
instance, 'not_int', int, 0)
self.assertEqual(0, result)
class ComputeUtilsGetNWInfo(test.NoDBTestCase):
def test_instance_object_none_info_cache(self):
inst = fake_instance.fake_instance_obj('fake-context',
expected_attrs=['info_cache'])
self.assertIsNone(inst.info_cache)
result = compute_utils.get_nw_info_for_instance(inst)
self.assertEqual(jsonutils.dumps([]), result.json())
class ComputeUtilsGetRebootTypes(test.NoDBTestCase):
def setUp(self):
super(ComputeUtilsGetRebootTypes, self).setUp()
self.context = context.RequestContext('fake', 'fake')
def test_get_reboot_type_started_soft(self):
reboot_type = compute_utils.get_reboot_type(task_states.REBOOT_STARTED,
power_state.RUNNING)
self.assertEqual(reboot_type, 'SOFT')
def test_get_reboot_type_pending_soft(self):
reboot_type = compute_utils.get_reboot_type(task_states.REBOOT_PENDING,
power_state.RUNNING)
self.assertEqual(reboot_type, 'SOFT')
def test_get_reboot_type_hard(self):
reboot_type = compute_utils.get_reboot_type('foo', power_state.RUNNING)
self.assertEqual(reboot_type, 'HARD')
def test_get_reboot_not_running_hard(self):
reboot_type = compute_utils.get_reboot_type('foo', 'bar')
self.assertEqual(reboot_type, 'HARD')
class ComputeUtilsTestCase(test.NoDBTestCase):
def setUp(self):
super(ComputeUtilsTestCase, self).setUp()
self.compute = 'compute'
self.user_id = 'fake'
self.project_id = 'fake'
self.context = context.RequestContext(self.user_id,
self.project_id)
@mock.patch.object(objects.InstanceActionEvent, 'event_start')
@mock.patch.object(objects.InstanceActionEvent,
'event_finish_with_failure')
def test_wrap_instance_event(self, mock_finish, mock_start):
inst = {"uuid": uuids.instance}
@compute_utils.wrap_instance_event(prefix='compute')
def fake_event(self, context, instance):
pass
fake_event(self.compute, self.context, instance=inst)
self.assertTrue(mock_start.called)
self.assertTrue(mock_finish.called)
@mock.patch.object(objects.InstanceActionEvent, 'event_start')
@mock.patch.object(objects.InstanceActionEvent,
'event_finish_with_failure')
def test_wrap_instance_event_return(self, mock_finish, mock_start):
inst = {"uuid": uuids.instance}
@compute_utils.wrap_instance_event(prefix='compute')
def fake_event(self, context, instance):
return True
retval = fake_event(self.compute, self.context, instance=inst)
self.assertTrue(retval)
self.assertTrue(mock_start.called)
self.assertTrue(mock_finish.called)
@mock.patch.object(objects.InstanceActionEvent, 'event_start')
@mock.patch.object(objects.InstanceActionEvent,
'event_finish_with_failure')
def test_wrap_instance_event_log_exception(self, mock_finish, mock_start):
inst = {"uuid": uuids.instance}
@compute_utils.wrap_instance_event(prefix='compute')
def fake_event(self2, context, instance):
raise exception.NovaException()
self.assertRaises(exception.NovaException, fake_event,
self.compute, self.context, instance=inst)
self.assertTrue(mock_start.called)
self.assertTrue(mock_finish.called)
args, kwargs = mock_finish.call_args
self.assertIsInstance(kwargs['exc_val'], exception.NovaException)
@mock.patch('netifaces.interfaces')
def test_get_machine_ips_value_error(self, mock_interfaces):
# Tests that the utility method does not explode if netifaces raises
# a ValueError.
iface = mock.sentinel
mock_interfaces.return_value = [iface]
with mock.patch('netifaces.ifaddresses',
side_effect=ValueError) as mock_ifaddresses:
addresses = compute_utils.get_machine_ips()
self.assertEqual([], addresses)
mock_ifaddresses.assert_called_once_with(iface)
@mock.patch('nova.compute.utils.notify_about_instance_usage')
@mock.patch('nova.objects.Instance.destroy')
def test_notify_about_instance_delete(self, mock_instance_destroy,
mock_notify_usage):
instance = fake_instance.fake_instance_obj(
self.context, expected_attrs=('system_metadata',))
with compute_utils.notify_about_instance_delete(
mock.sentinel.notifier, self.context, instance):
instance.destroy()
expected_notify_calls = [
mock.call(mock.sentinel.notifier, self.context, instance,
'delete.start'),
mock.call(mock.sentinel.notifier, self.context, instance,
'delete.end', system_metadata=instance.system_metadata)
]
mock_notify_usage.assert_has_calls(expected_notify_calls)
class ComputeUtilsQuotaDeltaTestCase(test.TestCase):
def setUp(self):
super(ComputeUtilsQuotaDeltaTestCase, self).setUp()
self.context = context.RequestContext('fake', 'fake')
def test_upsize_quota_delta(self):
old_flavor = flavors.get_flavor_by_name('m1.tiny')
new_flavor = flavors.get_flavor_by_name('m1.medium')
expected_deltas = {
'cores': new_flavor['vcpus'] - old_flavor['vcpus'],
'ram': new_flavor['memory_mb'] - old_flavor['memory_mb']
}
deltas = compute_utils.upsize_quota_delta(self.context, new_flavor,
old_flavor)
self.assertEqual(expected_deltas, deltas)
def test_downsize_quota_delta(self):
inst = create_instance(self.context, params=None)
inst.old_flavor = flavors.get_flavor_by_name('m1.medium')
inst.new_flavor = flavors.get_flavor_by_name('m1.tiny')
expected_deltas = {
'cores': (inst.new_flavor['vcpus'] -
inst.old_flavor['vcpus']),
'ram': (inst.new_flavor['memory_mb'] -
inst.old_flavor['memory_mb'])
}
deltas = compute_utils.downsize_quota_delta(self.context, inst)
self.assertEqual(expected_deltas, deltas)
def test_reverse_quota_delta(self):
inst = create_instance(self.context, params=None)
inst.old_flavor = flavors.get_flavor_by_name('m1.tiny')
inst.new_flavor = flavors.get_flavor_by_name('m1.medium')
expected_deltas = {
'cores': -1 * (inst.new_flavor['vcpus'] -
inst.old_flavor['vcpus']),
'ram': -1 * (inst.new_flavor['memory_mb'] -
inst.old_flavor['memory_mb'])
}
deltas = compute_utils.reverse_upsize_quota_delta(self.context, inst)
self.assertEqual(expected_deltas, deltas)
@mock.patch.object(objects.Quotas, 'reserve')
@mock.patch.object(objects.quotas, 'ids_from_instance')
def test_reserve_quota_delta(self, mock_ids_from_instance,
mock_reserve):
quotas = objects.Quotas(context=context)
inst = create_instance(self.context, params=None)
inst.old_flavor = flavors.get_flavor_by_name('m1.tiny')
inst.new_flavor = flavors.get_flavor_by_name('m1.medium')
mock_ids_from_instance.return_value = (inst.project_id, inst.user_id)
mock_reserve.return_value = quotas
deltas = compute_utils.upsize_quota_delta(self.context,
inst.new_flavor,
inst.old_flavor)
compute_utils.reserve_quota_delta(self.context, deltas, inst)
mock_reserve.assert_called_once_with(project_id=inst.project_id,
user_id=inst.user_id, **deltas)
class IsVolumeBackedInstanceTestCase(test.TestCase):
def setUp(self):
super(IsVolumeBackedInstanceTestCase, self).setUp()
self.user_id = 'fake'
self.project_id = 'fake'
self.context = context.RequestContext(self.user_id,
self.project_id)
def test_is_volume_backed_instance_no_bdm_no_image(self):
ctxt = self.context
instance = create_instance(ctxt, params={'image_ref': ''})
self.assertTrue(
compute_utils.is_volume_backed_instance(ctxt, instance, None))
def test_is_volume_backed_instance_empty_bdm_with_image(self):
ctxt = self.context
instance = create_instance(ctxt, params={
'root_device_name': 'vda',
'image_ref': FAKE_IMAGE_REF
})
self.assertFalse(
compute_utils.is_volume_backed_instance(
ctxt, instance,
block_device_obj.block_device_make_list(ctxt, [])))
def test_is_volume_backed_instance_bdm_volume_no_image(self):
ctxt = self.context
instance = create_instance(ctxt, params={
'root_device_name': 'vda',
'image_ref': ''
})
bdms = block_device_obj.block_device_make_list(ctxt,
[fake_block_device.FakeDbBlockDeviceDict(
{'source_type': 'volume',
'device_name': '/dev/vda',
'volume_id': uuids.volume_id,
'instance_uuid':
'f8000000-0000-0000-0000-000000000000',
'boot_index': 0,
'destination_type': 'volume'})])
self.assertTrue(
compute_utils.is_volume_backed_instance(ctxt, instance, bdms))
def test_is_volume_backed_instance_bdm_local_no_image(self):
# if the root device is local the instance is not volume backed, even
# if no image_ref is set.
ctxt = self.context
instance = create_instance(ctxt, params={
'root_device_name': 'vda',
'image_ref': ''
})
bdms = block_device_obj.block_device_make_list(ctxt,
[fake_block_device.FakeDbBlockDeviceDict(
{'source_type': 'volume',
'device_name': '/dev/vda',
'volume_id': uuids.volume_id,
'destination_type': 'local',
'instance_uuid': 'f8000000-0000-0000-0000-000000000000',
'boot_index': 0,
'snapshot_id': None}),
fake_block_device.FakeDbBlockDeviceDict(
{'source_type': 'volume',
'device_name': '/dev/vdb',
'instance_uuid': 'f8000000-0000-0000-0000-000000000000',
'boot_index': 1,
'destination_type': 'volume',
'volume_id': 'c2ec2156-d75e-11e2-985b-5254009297d6',
'snapshot_id': None})])
self.assertFalse(
compute_utils.is_volume_backed_instance(ctxt, instance, bdms))
def test_is_volume_backed_instance_bdm_volume_with_image(self):
ctxt = self.context
instance = create_instance(ctxt, params={
'root_device_name': 'vda',
'image_ref': FAKE_IMAGE_REF
})
bdms = block_device_obj.block_device_make_list(ctxt,
[fake_block_device.FakeDbBlockDeviceDict(
{'source_type': 'volume',
'device_name': '/dev/vda',
'volume_id': uuids.volume_id,
'boot_index': 0,
'destination_type': 'volume'})])
self.assertTrue(
compute_utils.is_volume_backed_instance(ctxt, instance, bdms))
def test_is_volume_backed_instance_bdm_snapshot(self):
ctxt = self.context
instance = create_instance(ctxt, params={
'root_device_name': 'vda'
})
bdms = block_device_obj.block_device_make_list(ctxt,
[fake_block_device.FakeDbBlockDeviceDict(
{'source_type': 'volume',
'device_name': '/dev/vda',
'snapshot_id': 'de8836ac-d75e-11e2-8271-5254009297d6',
'instance_uuid': 'f8000000-0000-0000-0000-000000000000',
'destination_type': 'volume',
'boot_index': 0,
'volume_id': None})])
self.assertTrue(
compute_utils.is_volume_backed_instance(ctxt, instance, bdms))
@mock.patch.object(objects.BlockDeviceMappingList, 'get_by_instance_uuid')
def test_is_volume_backed_instance_empty_bdm_by_uuid(self, mock_bdms):
ctxt = self.context
instance = create_instance(ctxt)
mock_bdms.return_value = block_device_obj.block_device_make_list(
ctxt, [])
self.assertFalse(
compute_utils.is_volume_backed_instance(ctxt, instance, None))
mock_bdms.assert_called_with(ctxt, instance.uuid)
|
Rules: 1- Attach the pivoting pointer to the board and place the game flat on a table. 2- The youngest player begins and turns the pointer first. If the pointer stops on a coloured place, the player takes a chocolate of that colour [propriété] from the box and places it on the board, on a place of that colour. Then it is the turn of the next player. 3- If the pointer stops on the Waterworks / Electricity company, the player takes that chocolate from the box and puts it in the appropriate place. 4- If the pointer stops on a question mark, the player takes the chocolate of their choice from the box. 5- If the pointer stops on the Free Parking place, the player misses a turn. 6 - Once the last chocolate of a specific colour [propriété ou Compagnie des eaux / Compagnie d'éléctricité] has been placed on the board, the next player whose pointer stops on that colour may eat the chocolate. 7- When all the properties have been distributed, the player winning the most chocolates wins part 1. Please note: Choking hazard - small pieces. Not suitable for children under three years. Players: 2 - 4 Age: from 8 years.
Sugar, cocoa solids, cocoa butter, whole MILK powder, skimmed MILK powder, emulsifier (SOY lecithin), vanilla (natural flavour)., Cocoa: 28.1 % minimum., ALLERGENS: Contains MILK and SOY.
|
from urllib.parse import urljoin
from grab.spider import Spider, Task
from d_parser.helpers.cookies_init import cookies_init
from d_parser.helpers.el_parser import get_max_page
from d_parser.helpers.parser_extender import check_body_errors, process_error, common_init
from d_parser.helpers.re_set import Ree
from helpers.config import Config
from helpers.url_generator import UrlGenerator
# Warn: Don't remove task argument even if not use it (it's break grab and spider crashed)
# Warn: noinspection PyUnusedLocal
class DSpider(Spider):
initial_urls = Config.get_seq('SITE_URL')
def __init__(self, thread_number, try_limit=0):
super().__init__(thread_number=thread_number, network_try_limit=try_limit, priority_mode='const')
DSpider._check_body_errors = check_body_errors
DSpider._process_error = process_error
DSpider._common_init = common_init
self._common_init(try_limit)
Ree.init()
Ree.is_page_number(Config.get('SITE_PAGE_PARAM'))
self.const_price_on_request = Config.get('APP_PRICE_ON_REQUEST')
self.const_stock_zero = Config.get('APP_STOCK_ZERO')
self.const_default_place = 'Полежаевская'
def create_grab_instance(self, **kwargs):
g = super(DSpider, self).create_grab_instance(**kwargs)
return cookies_init(self.cookie_jar, g)
def task_initial(self, grab, task):
self.logger.info('[{}] Initial url: {}'.format(task.name, task.url))
if self._check_body_errors(grab, task):
self.logger.fatal('[{}] Err task with url {}, attempt {}'.format(task.name, task.url, task.task_try_count))
return
try:
cat_list = grab.doc.select('//ul[@class="catalog_nav_1"]//a[contains(@href, "catalog")]')
for index, row in enumerate(cat_list):
raw_link = row.attr('href')
# make absolute urls if needed
if raw_link[:1] == '/':
raw_link = urljoin(self.domain, raw_link)
yield Task('parse_cat', url=raw_link, priority=90, raw=True)
except Exception as e:
self._process_error(grab, task, e)
finally:
self.logger.info('[{}] Finish: {}'.format(task.name, task.url))
def task_parse_cat(self, grab, task):
self.logger.info('[{}] Start: {}'.format(task.name, task.url))
if self._check_body_errors(grab, task):
self.logger.fatal('[{}] Err task with url {}, attempt {}'.format(task.name, task.url, task.task_try_count))
return
try:
cat_list = grab.doc.select('//div[@class="category_list"]//a[contains(@href, "catalog")]')
for index, row in enumerate(cat_list):
raw_link = row.attr('href')
# make absolute urls if needed
if raw_link[:1] == '/':
raw_link = urljoin(self.domain, raw_link)
yield Task('parse_items', url=raw_link, priority=100, raw=True)
except Exception as e:
self._process_error(grab, task, e)
finally:
self.logger.info('[{}] Finish: {}'.format(task.name, task.url))
# def task_parse_page(self, grab, task):
# self.logger.info('[{}] Start: {}'.format(task.name, task.url))
#
# if self._check_body_errors(grab, task):
# self.logger.fatal('[{}] Err task with url {}, attempt {}'.format(task.name, task.url, task.task_try_count))
# return
#
# try:
# items = grab.doc.select('//a[contains(@href, "{}")]'.format(Config.get('SITE_PAGE_PARAM')))
# max_page = get_max_page(items, 1)
# self.logger.info('[{}] Find max page: {}'.format(task.name, max_page))
#
# url_gen = UrlGenerator(task.url, Config.get('SITE_PAGE_PARAM'))
#
# for p in range(1, max_page + 1):
# url = url_gen.get_page(p)
# yield Task('parse_items', url=url, priority=110)
#
# except Exception as e:
# self._process_error(grab, task, e)
#
# finally:
# self.logger.info('[{}] Finish: {}'.format(task.name, task.url))
def task_parse_items(self, grab, task):
self.logger.info('[{}] Start: {}'.format(task.name, task.url))
if self._check_body_errors(grab, task):
if task.task_try_count < self.err_limit:
self.logger.error('[{}] Restart task with url {}, attempt {}'.format(task.name, task.url, task.task_try_count))
yield Task('parse_items', url=task.url, priority=105, task_try_count=task.task_try_count + 1, raw=True)
else:
self.logger.error('[{}] Skip task with url {}, attempt {}'.format(task.name, task.url, task.task_try_count))
return
try:
# parse pagination numbers
if not task.get('d_skip_page_check'):
items = grab.doc.select('//a[contains(@href, "{}")]'.format(Config.get('SITE_PAGE_PARAM')))
max_page = get_max_page(items, 1)
self.logger.info('[{}] Find max page: {}'.format(task.name, max_page))
url_gen = UrlGenerator(task.url, Config.get('SITE_PAGE_PARAM'))
# self-execute from 2 page (if needed)
for p in range(2, max_page + 1):
url = url_gen.get_page(p)
yield Task('parse_items', url=url, priority=100, d_skip_page_check=True, raw=True)
# parse items
items_list = grab.doc.select('//div[@class="cart_table"]/div/div/table/tbody/tr')
for index, row in enumerate(items_list):
try:
# NAME
item_name = row.select('./td[1]//div[@class="description"]/div/a').text().strip()
# UNIT
unit = row.select('./td[2]').text().strip()
if unit == '':
unit = 'ед.'
# PRICE
price_raw = row.select('./td[6]//meta[@itemprop="lowprice"]').attr('content')
match = Ree.float.match(price_raw)
# check & fix
if not match:
self.logger.warning('[{}] Skip item, because price is {} (line: {})'.format(task.name, price_raw, index))
continue
price = match.groupdict()['price'].replace(',', '.')
# COUNT
count = row.select('./td[5]')
count_text = count.text().strip()
# case 1: string line
if count_text == 'распродано':
item_count = self.const_price_on_request
item_place = self.const_default_place
# OUTPUT
self.logger.debug('[{}] Item added, index {} at url {}'.format(task.name, index, task.url))
self.result.append({
'name': item_name,
'count': item_count,
'unit': unit,
'price': price,
'place': item_place
})
# case 2: string line
elif count_text == 'под заказ':
item_count = self.const_stock_zero
item_place = self.const_default_place
# OUTPUT
self.logger.debug('[{}] Item added, index {} at url {}'.format(task.name, index, task.url))
self.result.append({
'name': item_name,
'count': item_count,
'unit': unit,
'price': price,
'place': item_place
})
# case 3
else:
count_rows = count.select('.//div[@class="layer_info"]/table/tbody/tr')
for count_row in count_rows:
item_place = count_row.select('./td[1]').text().strip()
item_count = 0
# add stock
place_count_stock = count_row.select('./td[1]').text().strip()
if Ree.float.match(place_count_stock):
item_count += float(place_count_stock)
# add expo
place_count_expo = count_row.select('./td[2]').text().strip()
if Ree.float.match(place_count_expo):
item_count += float(place_count_expo)
if item_count > 0:
# OUTPUT
self.logger.debug('[{}] Item added, index {} at url {}'.format(task.name, index, task.url))
self.result.append({
'name': item_name,
# 3.140 -> 3.14; 3.0 -> 3
'count': '{0:g}'.format(item_count),
'unit': unit,
'price': price,
'place': item_place
})
except IndexError as e:
self.logger.warning('[{}] Skip item: {}, {}'.format(task.name, type(e).__name__, task.url))
except Exception as e:
self._process_error(grab, task, e)
finally:
self.logger.info('[{}] Finish: {}'.format(task.name, task.url))
|
It would be a whole lot easier to buy a car if you only had a handful of choices to pick from. If someone could give you five cars to choose from, the whole experience would be a lot easier for you. Of course, someone is not going to do that. In addition, having only a few choices to choose from is not exactly what you want in a car buying experience. Whether you are looking for something new, used, or even one of those New Trucks that are out there, you want choices. Of course, with choices comes a need to do a good amount of research on what is out there. When it comes to looking at Cars For Sale in Port Washington, WI, it is important that you take the time to really look at what is out there for you to consider.
When you are looking at Cars For Sale in Port Washington, WI, cast as wide of a net as possible. Look at a variety of different lots, as well as a variety of different cars. Embrace the fact that you are going to have to look by spending your time not just trudging around the lot, but also by doing some research at home. While you are going to look at Cars For Sale in Port Washington, WI, by doing research online you can be sure that you know what you are looking at when you hit the lot.
|
# Copyright (C) weslowskij
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from xml.etree.ElementTree import SubElement,Element
from mylibs.myPersistent import PersistentObject
class MyList(list, PersistentObject):
def __init__(self, *args, **kwargs):
#super(MyList,self).__init__(*args, **kwargs)
list.__init__(self, *args, **kwargs)
self.nid = "None"
self.dog_class = "unchanged"
self.dog_class = None
def toXml2(self, tree, attributename):
if tree is not None:
song = SubElement(tree, attributename)
else:
song = Element(str(self.__class__.__name__))
#song = SubElement(tree, attributename)
song.attrib["nid"]= repr(self.nid)
titles = self.__dict__.iterkeys()
for i, o in enumerate(self):
#pdb.set_trace()
#window = SubElement(song, "pos")
#window.attrib["pos"]=repr(i)
window = song
#o = self.__getattribute__(title)
title = str(i)
# exceptions
"""
if title in self.persistentexception:
print "skipping" , title
continue
"""
"""
if title in self.persistentexceptiondontexpand:
newtitle = ET.SubElement(song, str(title))
newtitle.text = repr(o)
continue
"""
if hasattr(o, "toXml2"):
o.toXml2(window,"pos_"+repr(i))
else:
newtitle = SubElement(window, o.__class__.__name__)
newtitle.text = repr(o)
return song
def fromXml2(self,tree):
for pos in tree:
dog = None
if self.dog_class is None:
dog=PersistentObject()
else:
dog = self.dog_class()
dog.fromXml2(pos)
#print dog.__dict__
self.append(dog)
def append(self, p_object):
list.append(self,p_object)
def items(self):
return list(enumerate(self))
|
Food safety quality is important because when the standards are maintained, consumers will have confidence in the food industry. People in the food industry should be careful about what they serve consumers and they should not serve food that contains salmonella, bacteria, and mad cow disease. When there is proper maintenance of food standards, there will be no harmful effects to consumers when they consume food from businesses and companies in the food industry. If one wants to expand their reach globally with their products, they need to be careful about food safety quality because if they don’t, other countries will reject products that come from a certain brand or region. One may need to hire professionals who are knowledgeable about food safety quality in their company or business.
Companies and businesses which maintain food safety quality will be able to protect their customers from diseases. Through the use of innovation, companies and businesses have come up with ways to ensure that products have a long shelf life and this is good for consumers because they can be protected from harmful bacteria. One of the ways to maintain a good image in the eyes of customers is by maintaining food safety quality. Those companies and businesses which have not kept food safety quality have gone out of business because no one wants to buy their products due to a bad image.
Food safety quality is important because when it is maintained there will be a reduction in foodborne illnesses. Food safety quality should be maintained in service establishments such as restaurants especially during food preparation. The staff should also be knowledgeable about the risks that are associated with their food preparation. When equipment is handled well in a food establishment, there will be good food safety quality in an establishment.
One of the ways to ensure that an establishment is keeping food safety standards is when staff members learn how to carry out food safety quality. One should stay updated about food safety quality and one way to do this is to read more about it since there are new standards that are coming up every now and then. The benefit of keeping these standards is that companies and customers will both be satisfied. Businesses and companies which want to stay in the food industry for a long time need to maintain food safety quality.
|
# ===================================================================
#
# Copyright (c) 2015, Legrandin <[email protected]>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ===================================================================
import unittest
from Cryptodome.SelfTest.st_common import list_test_cases
from Cryptodome.Util.py3compat import tobytes, b, unhexlify
from Cryptodome.Cipher import AES, DES3, DES
from Cryptodome.Hash import SHAKE128
def get_tag_random(tag, length):
return SHAKE128.new(data=tobytes(tag)).read(length)
from Cryptodome.SelfTest.Cipher.test_CBC import BlockChainingTests
class OfbTests(BlockChainingTests):
aes_mode = AES.MODE_OFB
des3_mode = DES3.MODE_OFB
# Redefine test_unaligned_data_128/64
def test_unaligned_data_128(self):
plaintexts = [ b("7777777") ] * 100
cipher = AES.new(self.key_128, AES.MODE_CFB, self.iv_128, segment_size=8)
ciphertexts = [ cipher.encrypt(x) for x in plaintexts ]
cipher = AES.new(self.key_128, AES.MODE_CFB, self.iv_128, segment_size=8)
self.assertEqual(b("").join(ciphertexts), cipher.encrypt(b("").join(plaintexts)))
cipher = AES.new(self.key_128, AES.MODE_CFB, self.iv_128, segment_size=128)
ciphertexts = [ cipher.encrypt(x) for x in plaintexts ]
cipher = AES.new(self.key_128, AES.MODE_CFB, self.iv_128, segment_size=128)
self.assertEqual(b("").join(ciphertexts), cipher.encrypt(b("").join(plaintexts)))
def test_unaligned_data_64(self):
plaintexts = [ b("7777777") ] * 100
cipher = DES3.new(self.key_192, DES3.MODE_CFB, self.iv_64, segment_size=8)
ciphertexts = [ cipher.encrypt(x) for x in plaintexts ]
cipher = DES3.new(self.key_192, DES3.MODE_CFB, self.iv_64, segment_size=8)
self.assertEqual(b("").join(ciphertexts), cipher.encrypt(b("").join(plaintexts)))
cipher = DES3.new(self.key_192, DES3.MODE_CFB, self.iv_64, segment_size=64)
ciphertexts = [ cipher.encrypt(x) for x in plaintexts ]
cipher = DES3.new(self.key_192, DES3.MODE_CFB, self.iv_64, segment_size=64)
self.assertEqual(b("").join(ciphertexts), cipher.encrypt(b("").join(plaintexts)))
from Cryptodome.SelfTest.Cipher.test_CBC import NistBlockChainingVectors
class NistOfbVectors(NistBlockChainingVectors):
aes_mode = AES.MODE_OFB
des_mode = DES.MODE_OFB
des3_mode = DES3.MODE_OFB
# Create one test method per file
nist_aes_kat_mmt_files = (
# KAT
"OFBGFSbox128.rsp",
"OFBGFSbox192.rsp",
"OFBGFSbox256.rsp",
"OFBKeySbox128.rsp",
"OFBKeySbox192.rsp",
"OFBKeySbox256.rsp",
"OFBVarKey128.rsp",
"OFBVarKey192.rsp",
"OFBVarKey256.rsp",
"OFBVarTxt128.rsp",
"OFBVarTxt192.rsp",
"OFBVarTxt256.rsp",
# MMT
"OFBMMT128.rsp",
"OFBMMT192.rsp",
"OFBMMT256.rsp",
)
nist_aes_mct_files = (
"OFBMCT128.rsp",
"OFBMCT192.rsp",
"OFBMCT256.rsp",
)
for file_name in nist_aes_kat_mmt_files:
def new_func(self, file_name=file_name):
self._do_kat_aes_test(file_name)
setattr(NistOfbVectors, "test_AES_" + file_name, new_func)
for file_name in nist_aes_mct_files:
def new_func(self, file_name=file_name):
self._do_mct_aes_test(file_name)
setattr(NistOfbVectors, "test_AES_" + file_name, new_func)
del file_name, new_func
nist_tdes_files = (
"TOFBMMT2.rsp", # 2TDES
"TOFBMMT3.rsp", # 3TDES
"TOFBinvperm.rsp", # Single DES
"TOFBpermop.rsp",
"TOFBsubtab.rsp",
"TOFBvarkey.rsp",
"TOFBvartext.rsp",
)
for file_name in nist_tdes_files:
def new_func(self, file_name=file_name):
self._do_tdes_test(file_name)
setattr(NistOfbVectors, "test_TDES_" + file_name, new_func)
# END OF NIST OFB TEST VECTORS
class SP800TestVectors(unittest.TestCase):
"""Class exercising the OFB test vectors found in Section F.4
of NIST SP 800-3A"""
def test_aes_128(self):
plaintext = '6bc1bee22e409f96e93d7e117393172a' +\
'ae2d8a571e03ac9c9eb76fac45af8e51' +\
'30c81c46a35ce411e5fbc1191a0a52ef' +\
'f69f2445df4f9b17ad2b417be66c3710'
ciphertext = '3b3fd92eb72dad20333449f8e83cfb4a' +\
'7789508d16918f03f53c52dac54ed825' +\
'9740051e9c5fecf64344f7a82260edcc' +\
'304c6528f659c77866a510d9c1d6ae5e'
key = '2b7e151628aed2a6abf7158809cf4f3c'
iv = '000102030405060708090a0b0c0d0e0f'
key = unhexlify(key)
iv = unhexlify(iv)
plaintext = unhexlify(plaintext)
ciphertext = unhexlify(ciphertext)
cipher = AES.new(key, AES.MODE_OFB, iv)
self.assertEqual(cipher.encrypt(plaintext), ciphertext)
cipher = AES.new(key, AES.MODE_OFB, iv)
self.assertEqual(cipher.decrypt(ciphertext), plaintext)
cipher = AES.new(key, AES.MODE_OFB, iv)
self.assertEqual(cipher.encrypt(plaintext[:-8]), ciphertext[:-8])
cipher = AES.new(key, AES.MODE_OFB, iv)
self.assertEqual(cipher.decrypt(ciphertext[:-8]), plaintext[:-8])
def test_aes_192(self):
plaintext = '6bc1bee22e409f96e93d7e117393172a' +\
'ae2d8a571e03ac9c9eb76fac45af8e51' +\
'30c81c46a35ce411e5fbc1191a0a52ef' +\
'f69f2445df4f9b17ad2b417be66c3710'
ciphertext = 'cdc80d6fddf18cab34c25909c99a4174' +\
'fcc28b8d4c63837c09e81700c1100401' +\
'8d9a9aeac0f6596f559c6d4daf59a5f2' +\
'6d9f200857ca6c3e9cac524bd9acc92a'
key = '8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b'
iv = '000102030405060708090a0b0c0d0e0f'
key = unhexlify(key)
iv = unhexlify(iv)
plaintext = unhexlify(plaintext)
ciphertext = unhexlify(ciphertext)
cipher = AES.new(key, AES.MODE_OFB, iv)
self.assertEqual(cipher.encrypt(plaintext), ciphertext)
cipher = AES.new(key, AES.MODE_OFB, iv)
self.assertEqual(cipher.decrypt(ciphertext), plaintext)
cipher = AES.new(key, AES.MODE_OFB, iv)
self.assertEqual(cipher.encrypt(plaintext[:-8]), ciphertext[:-8])
cipher = AES.new(key, AES.MODE_OFB, iv)
self.assertEqual(cipher.decrypt(ciphertext[:-8]), plaintext[:-8])
def test_aes_256(self):
plaintext = '6bc1bee22e409f96e93d7e117393172a' +\
'ae2d8a571e03ac9c9eb76fac45af8e51' +\
'30c81c46a35ce411e5fbc1191a0a52ef' +\
'f69f2445df4f9b17ad2b417be66c3710'
ciphertext = 'dc7e84bfda79164b7ecd8486985d3860' +\
'4febdc6740d20b3ac88f6ad82a4fb08d' +\
'71ab47a086e86eedf39d1c5bba97c408' +\
'0126141d67f37be8538f5a8be740e484'
key = '603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4'
iv = '000102030405060708090a0b0c0d0e0f'
key = unhexlify(key)
iv = unhexlify(iv)
plaintext = unhexlify(plaintext)
ciphertext = unhexlify(ciphertext)
cipher = AES.new(key, AES.MODE_OFB, iv)
self.assertEqual(cipher.encrypt(plaintext), ciphertext)
cipher = AES.new(key, AES.MODE_OFB, iv)
self.assertEqual(cipher.decrypt(ciphertext), plaintext)
cipher = AES.new(key, AES.MODE_OFB, iv)
self.assertEqual(cipher.encrypt(plaintext[:-8]), ciphertext[:-8])
cipher = AES.new(key, AES.MODE_OFB, iv)
self.assertEqual(cipher.decrypt(ciphertext[:-8]), plaintext[:-8])
def get_tests(config={}):
tests = []
tests += list_test_cases(OfbTests)
if config.get('slow_tests'):
tests += list_test_cases(NistOfbVectors)
tests += list_test_cases(SP800TestVectors)
return tests
if __name__ == '__main__':
suite = lambda: unittest.TestSuite(get_tests())
unittest.main(defaultTest='suite')
|
IT organizations are looking to expose their functionality to a variety of clients. Although many protocols exist for communicating data on the Internet, HTTP seems to be dominating due to its ease of use and wide acceptance.
ASP.NET Web API allows developers to expose data and services to the Web directly over HTTP. This approach offers developers the ability to fully harness the richness of HTTP as an application layer protocol to communicate with a broad set of clients, including browsers, mobile devices, desktop applications, or backend services. The architecture is designed to support applications built with REST, but it does not force new applications to use a REST-style architecture.
This new technology first emerged in October 2010 at the Microsoft Professional Developers Conference (PDC) with the release of Preview 1. At the time, it was called "WCF Web API." Since then the product has continued to evolve. Preview 6, released in November 2011, is the latest version. Shortly after the release of Preview 6, Microsoft announced the new name of ASP.NET Web API. The project is a joint effort between the WCF and ASP.NET teams to create an integrated Web API framework.
Download the ASP.NET MVC4 beta.
Unfortunately, Silverlight applications aren't supported at this time. However, HTTP resources can be consumed in Silverlight using HttpWebRequest. The WCF Web API and WCF support for jQuery content on the CodePlex site is ending and will be removed by the end of 2012.
To demonstrate the powerful capabilities of ASP.NET Web API, I'll do a code walk-through. Let's assume I own a used car dealership and want to display my inventory to potential customers with various platforms (mobile, PC) or trading partners (wholesale dealers or distributors) using back-end services. I'm going to create a service that will report all vehicles on-hand, and later allow the results to be queried and filtered.
First, I'll create an ASP.NET MVC 3 solution called WebAPIDemo, as shown in Figure 1.
Figure 1. Selecting ASP.NET MVC 3 Web App.
I want to start with an empty project, so I'll select the Empty template and click OK, as shown in Figure 2.
Figure 2. Selecting an Empty project template.
Next, I'll retrieve the latest NuGet Package, via Package Manager in Visual Studio. I'll right-click on the solution in Solution Explorer, select Manage NuGet Packages and then enter WebApi.All in the search box. This retrieves the latest version of the package as shown in Figure 3.
Figure 3. Selecting WebApi.All v0.6.0.
In this case, I have WebApi.All already installed so a green checkmark appears next to it. If it wasn't installed, an install button would be in place of the green checkmark. Clicking the install button next to WebApi.All in the center pane will start the installation.
Accepting the necessary license agreements (see Figure 4) will continue the installation until completion, as shown in Figure 5.
Figure 4. License Terms for installation.
Figure 5. Additional installation after accepting license agreements.
At this point, the project has all the necessary references in place to start coding. Figure 6 shows a view of Solution Explorer with the default files provided from the selected template.
Figure 6. Default files after selecting template and WebApi.All installation.
Next, I'll create a folder in the project and call it InventoryWebAPIs. I'll add a class to this folder and call it InventoryAPI.vb, as shown in Figure 7.
Figure 7. Selecting class file.
The complete code is shown in Listing 1.
Create a Resources folder in the project with a new InventoryDTO class within it. This Resources folder will hold the Data Transfer Object (DTO) to be passed to and from the ASP.NET Web API.
The next step is to specify the "Start Action" for the project in the project properties. Because this is an ASP.NET MVC project, I'll specify the name of the class previously set up with the <ServiceContract()> attribute, class "Inventory." Please note, this class is in folder InventoryWebAPIs, so it also needs to be specified for "Specific Page," as shown in Figure 8.
Figure 8. Specifying class name of Web API for Start Action.
If the class "InventoryWebAPIs/Inventory" isn't specified and the project is started, an HTTP 404 error will result.
If the settings in my project are correct, I can start debugging my project and it will immediately render an XML form of the data, as shown in Figure 9.
Figure 9. Default result of initial execution.
This configuration variable will then be used in the previously added routes.Add. The modified code is reflected in Listing 2.
After making the necessary coding changes, I will start debugging the application by pressing F5. When the initial page loads, it will look similar to Figure 9. However, if I append "/test" to the URL, it displays the built-in test client, as shown in Figure 10.
Figure 10. Default ASP.NET Web API test client page.
Resources are the available APIs.
History displays a listing of calls submitted to the server in chronological order.
Request shows the verb, URI and the content header request sent to the server. These items will remain blank until a URI is selected from the Resources section.
Response shows the data received from the server.
To use the test client, click the Resources link in the left pane. This will populate the "Request" section with verb, URI and content header. Clicking the Send button will result in the output seen in Figure 11.
Figure 11. Test client with Request and Response.
The advantage of the test client is it expedites sending different content headers and verbs to the server. These are available in lists that appear when editing either the verb or the header, as shown in Figure 12. This allows the data to be sent in XML, JSON, plain text or any other format listed. Once the content header changes, ASP.NET Web API immediately adjusts to send the proper formatted output to the client.
Figure 12. Selecting different header information.
Another advantage of ASP.NET Web API is the ability to provide OData query support. Currently, only a subset of the query URI formats are accepted ($top, $skip, $orderby and $filter). To modify the existing API for OData support, simply change it to return an IQueryable type. This will also require using the System.Linq namespace. A complete listing of the modified code is shown in Listing 3.
After making the necessary changes, the project is now ready to provide OData query support. Once the browser page loads, append the query string "?$top=2&$orderby=Model" to the address, click Send, and the modified query will be returned as shown in Figure 13.
Figure 13. Test client with OData Request and Response.
ASP.NET Web API is not fully released yet, but it still offers many promising features. It allows the ability to write a service once and provide many different output formats with little effort on the developer’s side. This capability is made available in ASP.NET MVC 3, ASP.NET MVC 4 beta and standard ASP.NET applications. In addition, it offers a built-in test client to facilitate testing and viewing the data passed to and from the client.
|
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'arcons_basic_gui.ui'
#
# Created: Tue Dec 11 17:40:34 2012
# by: PyQt4 UI code generator 4.8.3
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
class Ui_arcons(object):
def setupUi(self, arcons):
arcons.setObjectName(_fromUtf8("arcons"))
arcons.setEnabled(True)
arcons.resize(860, 960)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(arcons.sizePolicy().hasHeightForWidth())
arcons.setSizePolicy(sizePolicy)
arcons.setMouseTracking(True)
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(_fromUtf8("lib/Archon.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
arcons.setWindowIcon(icon)
arcons.setWindowFilePath(_fromUtf8(""))
arcons.setAnimated(True)
self.centralwidget = QtGui.QWidget(arcons)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.frame = QtGui.QFrame(self.centralwidget)
self.frame.setGeometry(QtCore.QRect(0, 0, 391, 151))
self.frame.setFrameShape(QtGui.QFrame.Box)
self.frame.setFrameShadow(QtGui.QFrame.Sunken)
self.frame.setObjectName(_fromUtf8("frame"))
self.label = QtGui.QLabel(self.frame)
self.label.setGeometry(QtCore.QRect(110, 10, 251, 21))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Arial"))
font.setPointSize(18)
font.setWeight(75)
font.setBold(True)
self.label.setFont(font)
self.label.setObjectName(_fromUtf8("label"))
self.array_temp_lcd = QtGui.QLCDNumber(self.frame)
self.array_temp_lcd.setGeometry(QtCore.QRect(10, 40, 81, 41))
self.array_temp_lcd.setObjectName(_fromUtf8("array_temp_lcd"))
self.pulse_tube_temp_lcd = QtGui.QLCDNumber(self.frame)
self.pulse_tube_temp_lcd.setGeometry(QtCore.QRect(10, 90, 81, 41))
self.pulse_tube_temp_lcd.setObjectName(_fromUtf8("pulse_tube_temp_lcd"))
self.label_3 = QtGui.QLabel(self.frame)
self.label_3.setGeometry(QtCore.QRect(100, 50, 101, 21))
font = QtGui.QFont()
font.setPointSize(14)
self.label_3.setFont(font)
self.label_3.setObjectName(_fromUtf8("label_3"))
self.label_4 = QtGui.QLabel(self.frame)
self.label_4.setGeometry(QtCore.QRect(100, 90, 121, 41))
font = QtGui.QFont()
font.setPointSize(14)
self.label_4.setFont(font)
self.label_4.setObjectName(_fromUtf8("label_4"))
self.open_shutter_radioButton = QtGui.QRadioButton(self.frame)
self.open_shutter_radioButton.setEnabled(False)
self.open_shutter_radioButton.setGeometry(QtCore.QRect(240, 90, 141, 41))
font = QtGui.QFont()
font.setPointSize(14)
self.open_shutter_radioButton.setFont(font)
self.open_shutter_radioButton.setFocusPolicy(QtCore.Qt.NoFocus)
self.open_shutter_radioButton.setAutoExclusive(False)
self.open_shutter_radioButton.setObjectName(_fromUtf8("open_shutter_radioButton"))
self.cycle_fridge_radioButton = QtGui.QRadioButton(self.frame)
self.cycle_fridge_radioButton.setEnabled(False)
self.cycle_fridge_radioButton.setGeometry(QtCore.QRect(240, 40, 141, 41))
font = QtGui.QFont()
font.setPointSize(14)
self.cycle_fridge_radioButton.setFont(font)
self.cycle_fridge_radioButton.setFocusPolicy(QtCore.Qt.NoFocus)
self.cycle_fridge_radioButton.setAutoExclusive(False)
self.cycle_fridge_radioButton.setObjectName(_fromUtf8("cycle_fridge_radioButton"))
self.lineEdit = QtGui.QLineEdit(self.frame)
self.lineEdit.setGeometry(QtCore.QRect(80, 180, 113, 20))
self.lineEdit.setObjectName(_fromUtf8("lineEdit"))
self.frame_2 = QtGui.QFrame(self.centralwidget)
self.frame_2.setGeometry(QtCore.QRect(390, 0, 471, 181))
self.frame_2.setFrameShape(QtGui.QFrame.Box)
self.frame_2.setFrameShadow(QtGui.QFrame.Sunken)
self.frame_2.setObjectName(_fromUtf8("frame_2"))
self.label_2 = QtGui.QLabel(self.frame_2)
self.label_2.setGeometry(QtCore.QRect(150, 0, 261, 41))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Arial"))
font.setPointSize(18)
font.setWeight(75)
font.setBold(True)
self.label_2.setFont(font)
self.label_2.setObjectName(_fromUtf8("label_2"))
self.compass_graphicsView = QtGui.QGraphicsView(self.frame_2)
self.compass_graphicsView.setGeometry(QtCore.QRect(70, 90, 81, 81))
self.compass_graphicsView.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.compass_graphicsView.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.compass_graphicsView.setInteractive(False)
self.compass_graphicsView.setObjectName(_fromUtf8("compass_graphicsView"))
self.label_5 = QtGui.QLabel(self.frame_2)
self.label_5.setGeometry(QtCore.QRect(10, 40, 31, 21))
font = QtGui.QFont()
font.setPointSize(10)
self.label_5.setFont(font)
self.label_5.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.label_5.setObjectName(_fromUtf8("label_5"))
self.label_6 = QtGui.QLabel(self.frame_2)
self.label_6.setGeometry(QtCore.QRect(10, 60, 31, 21))
font = QtGui.QFont()
font.setPointSize(10)
self.label_6.setFont(font)
self.label_6.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.label_6.setObjectName(_fromUtf8("label_6"))
self.label_7 = QtGui.QLabel(self.frame_2)
self.label_7.setGeometry(QtCore.QRect(170, 120, 111, 21))
font = QtGui.QFont()
font.setPointSize(10)
self.label_7.setFont(font)
self.label_7.setLayoutDirection(QtCore.Qt.RightToLeft)
self.label_7.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.label_7.setObjectName(_fromUtf8("label_7"))
self.label_8 = QtGui.QLabel(self.frame_2)
self.label_8.setGeometry(QtCore.QRect(180, 40, 101, 21))
font = QtGui.QFont()
font.setPointSize(10)
self.label_8.setFont(font)
self.label_8.setLayoutDirection(QtCore.Qt.RightToLeft)
self.label_8.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.label_8.setObjectName(_fromUtf8("label_8"))
self.label_9 = QtGui.QLabel(self.frame_2)
self.label_9.setGeometry(QtCore.QRect(180, 60, 101, 21))
font = QtGui.QFont()
font.setPointSize(10)
self.label_9.setFont(font)
self.label_9.setLayoutDirection(QtCore.Qt.RightToLeft)
self.label_9.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.label_9.setObjectName(_fromUtf8("label_9"))
self.label_10 = QtGui.QLabel(self.frame_2)
self.label_10.setGeometry(QtCore.QRect(150, 140, 131, 21))
font = QtGui.QFont()
font.setPointSize(10)
self.label_10.setFont(font)
self.label_10.setLayoutDirection(QtCore.Qt.RightToLeft)
self.label_10.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.label_10.setObjectName(_fromUtf8("label_10"))
self.label_11 = QtGui.QLabel(self.frame_2)
self.label_11.setGeometry(QtCore.QRect(150, 80, 131, 21))
font = QtGui.QFont()
font.setPointSize(10)
self.label_11.setFont(font)
self.label_11.setLayoutDirection(QtCore.Qt.RightToLeft)
self.label_11.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.label_11.setObjectName(_fromUtf8("label_11"))
self.label_12 = QtGui.QLabel(self.frame_2)
self.label_12.setGeometry(QtCore.QRect(170, 100, 111, 21))
font = QtGui.QFont()
font.setPointSize(10)
self.label_12.setFont(font)
self.label_12.setLayoutDirection(QtCore.Qt.RightToLeft)
self.label_12.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.label_12.setObjectName(_fromUtf8("label_12"))
self.status_label = QtGui.QLabel(self.frame_2)
self.status_label.setGeometry(QtCore.QRect(10, 10, 131, 21))
font = QtGui.QFont()
font.setPointSize(12)
self.status_label.setFont(font)
self.status_label.setFrameShape(QtGui.QFrame.Box)
self.status_label.setObjectName(_fromUtf8("status_label"))
self.local_time_label = QtGui.QLabel(self.frame_2)
self.local_time_label.setGeometry(QtCore.QRect(290, 140, 131, 21))
font = QtGui.QFont()
font.setPointSize(12)
self.local_time_label.setFont(font)
self.local_time_label.setFrameShape(QtGui.QFrame.Box)
self.local_time_label.setText(_fromUtf8(""))
self.local_time_label.setObjectName(_fromUtf8("local_time_label"))
self.utc_label = QtGui.QLabel(self.frame_2)
self.utc_label.setGeometry(QtCore.QRect(290, 120, 131, 21))
font = QtGui.QFont()
font.setPointSize(12)
self.utc_label.setFont(font)
self.utc_label.setFrameShape(QtGui.QFrame.Box)
self.utc_label.setText(_fromUtf8(""))
self.utc_label.setObjectName(_fromUtf8("utc_label"))
self.lst_label = QtGui.QLabel(self.frame_2)
self.lst_label.setGeometry(QtCore.QRect(290, 100, 131, 21))
font = QtGui.QFont()
font.setPointSize(12)
self.lst_label.setFont(font)
self.lst_label.setFrameShape(QtGui.QFrame.Box)
self.lst_label.setText(_fromUtf8(""))
self.lst_label.setObjectName(_fromUtf8("lst_label"))
self.airmass_label = QtGui.QLabel(self.frame_2)
self.airmass_label.setGeometry(QtCore.QRect(290, 80, 131, 21))
font = QtGui.QFont()
font.setPointSize(12)
self.airmass_label.setFont(font)
self.airmass_label.setFrameShape(QtGui.QFrame.Box)
self.airmass_label.setText(_fromUtf8(""))
self.airmass_label.setObjectName(_fromUtf8("airmass_label"))
self.az_label = QtGui.QLabel(self.frame_2)
self.az_label.setGeometry(QtCore.QRect(290, 60, 131, 21))
font = QtGui.QFont()
font.setPointSize(12)
self.az_label.setFont(font)
self.az_label.setFrameShape(QtGui.QFrame.Box)
self.az_label.setText(_fromUtf8(""))
self.az_label.setObjectName(_fromUtf8("az_label"))
self.alt_label = QtGui.QLabel(self.frame_2)
self.alt_label.setGeometry(QtCore.QRect(290, 40, 131, 21))
font = QtGui.QFont()
font.setPointSize(12)
self.alt_label.setFont(font)
self.alt_label.setFrameShape(QtGui.QFrame.Box)
self.alt_label.setText(_fromUtf8(""))
self.alt_label.setObjectName(_fromUtf8("alt_label"))
self.ra_label = QtGui.QLabel(self.frame_2)
self.ra_label.setGeometry(QtCore.QRect(50, 40, 121, 21))
font = QtGui.QFont()
font.setPointSize(12)
self.ra_label.setFont(font)
self.ra_label.setFrameShape(QtGui.QFrame.Box)
self.ra_label.setText(_fromUtf8(""))
self.ra_label.setObjectName(_fromUtf8("ra_label"))
self.dec_label = QtGui.QLabel(self.frame_2)
self.dec_label.setGeometry(QtCore.QRect(50, 60, 121, 21))
font = QtGui.QFont()
font.setPointSize(12)
self.dec_label.setFont(font)
self.dec_label.setFrameShape(QtGui.QFrame.Box)
self.dec_label.setText(_fromUtf8(""))
self.dec_label.setObjectName(_fromUtf8("dec_label"))
self.frame_3 = QtGui.QFrame(self.centralwidget)
self.frame_3.setGeometry(QtCore.QRect(0, 150, 391, 521))
self.frame_3.setFrameShape(QtGui.QFrame.Box)
self.frame_3.setFrameShadow(QtGui.QFrame.Sunken)
self.frame_3.setObjectName(_fromUtf8("frame_3"))
self.save_raw_checkBox = QtGui.QCheckBox(self.frame_3)
self.save_raw_checkBox.setEnabled(False)
self.save_raw_checkBox.setGeometry(QtCore.QRect(300, 70, 91, 21))
font = QtGui.QFont()
font.setPointSize(12)
self.save_raw_checkBox.setFont(font)
self.save_raw_checkBox.setObjectName(_fromUtf8("save_raw_checkBox"))
self.data_directory_lineEdit = QtGui.QLineEdit(self.frame_3)
self.data_directory_lineEdit.setGeometry(QtCore.QRect(110, 40, 201, 21))
self.data_directory_lineEdit.setObjectName(_fromUtf8("data_directory_lineEdit"))
self.label_14 = QtGui.QLabel(self.frame_3)
self.label_14.setGeometry(QtCore.QRect(10, 40, 91, 21))
font = QtGui.QFont()
font.setPointSize(12)
self.label_14.setFont(font)
self.label_14.setObjectName(_fromUtf8("label_14"))
self.label_16 = QtGui.QLabel(self.frame_3)
self.label_16.setGeometry(QtCore.QRect(20, 210, 91, 21))
font = QtGui.QFont()
font.setPointSize(10)
self.label_16.setFont(font)
self.label_16.setObjectName(_fromUtf8("label_16"))
self.label_13 = QtGui.QLabel(self.frame_3)
self.label_13.setGeometry(QtCore.QRect(120, 0, 241, 41))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Arial"))
font.setPointSize(18)
font.setWeight(75)
font.setBold(True)
self.label_13.setFont(font)
self.label_13.setObjectName(_fromUtf8("label_13"))
self.label_15 = QtGui.QLabel(self.frame_3)
self.label_15.setGeometry(QtCore.QRect(20, 170, 111, 31))
font = QtGui.QFont()
font.setPointSize(10)
self.label_15.setFont(font)
self.label_15.setObjectName(_fromUtf8("label_15"))
self.calibrate_data_checkBox = QtGui.QCheckBox(self.frame_3)
self.calibrate_data_checkBox.setEnabled(False)
self.calibrate_data_checkBox.setGeometry(QtCore.QRect(280, 100, 121, 21))
font = QtGui.QFont()
font.setPointSize(12)
self.calibrate_data_checkBox.setFont(font)
self.calibrate_data_checkBox.setObjectName(_fromUtf8("calibrate_data_checkBox"))
self.stop_observation_pushButton = QtGui.QPushButton(self.frame_3)
self.stop_observation_pushButton.setGeometry(QtCore.QRect(200, 200, 181, 41))
font = QtGui.QFont()
font.setPointSize(10)
self.stop_observation_pushButton.setFont(font)
self.stop_observation_pushButton.setObjectName(_fromUtf8("stop_observation_pushButton"))
self.start_observation_pushButton = QtGui.QPushButton(self.frame_3)
self.start_observation_pushButton.setGeometry(QtCore.QRect(200, 140, 181, 51))
font = QtGui.QFont()
font.setPointSize(14)
self.start_observation_pushButton.setFont(font)
self.start_observation_pushButton.setObjectName(_fromUtf8("start_observation_pushButton"))
self.close_pushButton = QtGui.QPushButton(self.frame_3)
self.close_pushButton.setGeometry(QtCore.QRect(50, 460, 121, 41))
self.close_pushButton.setObjectName(_fromUtf8("close_pushButton"))
self.search_pushButton = QtGui.QPushButton(self.frame_3)
self.search_pushButton.setGeometry(QtCore.QRect(320, 40, 61, 21))
self.search_pushButton.setObjectName(_fromUtf8("search_pushButton"))
self.obs_time_spinBox = QtGui.QSpinBox(self.frame_3)
self.obs_time_spinBox.setGeometry(QtCore.QRect(120, 170, 71, 31))
font = QtGui.QFont()
font.setPointSize(12)
self.obs_time_spinBox.setFont(font)
self.obs_time_spinBox.setMaximum(99999)
self.obs_time_spinBox.setProperty(_fromUtf8("value"), 30)
self.obs_time_spinBox.setObjectName(_fromUtf8("obs_time_spinBox"))
self.remaining_time_lcdNumber = QtGui.QLCDNumber(self.frame_3)
self.remaining_time_lcdNumber.setGeometry(QtCore.QRect(120, 210, 61, 21))
self.remaining_time_lcdNumber.setObjectName(_fromUtf8("remaining_time_lcdNumber"))
self.frequency_tuneup_pushButton = QtGui.QPushButton(self.frame_3)
self.frequency_tuneup_pushButton.setEnabled(False)
self.frequency_tuneup_pushButton.setGeometry(QtCore.QRect(50, 400, 121, 51))
self.frequency_tuneup_pushButton.setObjectName(_fromUtf8("frequency_tuneup_pushButton"))
self.file_name_lineEdit = QtGui.QLineEdit(self.frame_3)
self.file_name_lineEdit.setEnabled(False)
self.file_name_lineEdit.setGeometry(QtCore.QRect(82, 70, 211, 22))
self.file_name_lineEdit.setText(_fromUtf8(""))
self.file_name_lineEdit.setObjectName(_fromUtf8("file_name_lineEdit"))
self.target_lineEdit = QtGui.QLineEdit(self.frame_3)
self.target_lineEdit.setGeometry(QtCore.QRect(100, 100, 171, 22))
self.target_lineEdit.setObjectName(_fromUtf8("target_lineEdit"))
self.label_20 = QtGui.QLabel(self.frame_3)
self.label_20.setGeometry(QtCore.QRect(10, 70, 91, 20))
font = QtGui.QFont()
font.setPointSize(12)
self.label_20.setFont(font)
self.label_20.setObjectName(_fromUtf8("label_20"))
self.label_21 = QtGui.QLabel(self.frame_3)
self.label_21.setGeometry(QtCore.QRect(10, 100, 91, 17))
font = QtGui.QFont()
font.setPointSize(12)
self.label_21.setFont(font)
self.label_21.setObjectName(_fromUtf8("label_21"))
self.frame_6 = QtGui.QFrame(self.frame_3)
self.frame_6.setGeometry(QtCore.QRect(210, 390, 141, 111))
self.frame_6.setFrameShape(QtGui.QFrame.StyledPanel)
self.frame_6.setFrameShadow(QtGui.QFrame.Raised)
self.frame_6.setObjectName(_fromUtf8("frame_6"))
self.subtract_sky_radioButton = QtGui.QRadioButton(self.frame_6)
self.subtract_sky_radioButton.setGeometry(QtCore.QRect(20, 0, 111, 31))
font = QtGui.QFont()
font.setPointSize(12)
self.subtract_sky_radioButton.setFont(font)
self.subtract_sky_radioButton.setChecked(False)
self.subtract_sky_radioButton.setAutoExclusive(False)
self.subtract_sky_radioButton.setObjectName(_fromUtf8("subtract_sky_radioButton"))
self.flat_field_radioButton = QtGui.QRadioButton(self.frame_6)
self.flat_field_radioButton.setEnabled(True)
self.flat_field_radioButton.setGeometry(QtCore.QRect(20, 20, 111, 31))
font = QtGui.QFont()
font.setPointSize(12)
self.flat_field_radioButton.setFont(font)
self.flat_field_radioButton.setCheckable(True)
self.flat_field_radioButton.setChecked(False)
self.flat_field_radioButton.setAutoExclusive(False)
self.flat_field_radioButton.setObjectName(_fromUtf8("flat_field_radioButton"))
self.int_time_spinBox = QtGui.QSpinBox(self.frame_6)
self.int_time_spinBox.setGeometry(QtCore.QRect(10, 50, 51, 22))
self.int_time_spinBox.setMaximum(9999)
self.int_time_spinBox.setProperty(_fromUtf8("value"), 1)
self.int_time_spinBox.setObjectName(_fromUtf8("int_time_spinBox"))
self.label_19 = QtGui.QLabel(self.frame_6)
self.label_19.setGeometry(QtCore.QRect(60, 50, 81, 21))
font = QtGui.QFont()
font.setPointSize(10)
self.label_19.setFont(font)
self.label_19.setObjectName(_fromUtf8("label_19"))
self.options_radioButton = QtGui.QRadioButton(self.frame_6)
self.options_radioButton.setGeometry(QtCore.QRect(10, 80, 131, 21))
font = QtGui.QFont()
font.setPointSize(9)
self.options_radioButton.setFont(font)
self.options_radioButton.setObjectName(_fromUtf8("options_radioButton"))
self.textEdit = QtGui.QTextEdit(self.frame_3)
self.textEdit.setGeometry(QtCore.QRect(10, 260, 371, 101))
self.textEdit.setObjectName(_fromUtf8("textEdit"))
self.label_27 = QtGui.QLabel(self.frame_3)
self.label_27.setGeometry(QtCore.QRect(10, 240, 151, 17))
self.label_27.setObjectName(_fromUtf8("label_27"))
self.update_description = QtGui.QPushButton(self.frame_3)
self.update_description.setGeometry(QtCore.QRect(10, 360, 141, 31))
self.update_description.setObjectName(_fromUtf8("update_description"))
self.continuous = QtGui.QCheckBox(self.frame_3)
self.continuous.setGeometry(QtCore.QRect(20, 130, 181, 41))
self.continuous.setObjectName(_fromUtf8("continuous"))
self.frame_4 = QtGui.QFrame(self.centralwidget)
self.frame_4.setGeometry(QtCore.QRect(390, 180, 471, 491))
self.frame_4.setFrameShape(QtGui.QFrame.Box)
self.frame_4.setFrameShadow(QtGui.QFrame.Sunken)
self.frame_4.setObjectName(_fromUtf8("frame_4"))
self.tv_image = QtGui.QGraphicsView(self.frame_4)
self.tv_image.setGeometry(QtCore.QRect(10, 10, 444, 464))
self.tv_image.setMouseTracking(True)
self.tv_image.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.tv_image.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.tv_image.setAlignment(QtCore.Qt.AlignHCenter|QtCore.Qt.AlignTop)
self.tv_image.setObjectName(_fromUtf8("tv_image"))
self.frame_5 = QtGui.QFrame(self.centralwidget)
self.frame_5.setGeometry(QtCore.QRect(0, 670, 861, 231))
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.frame_5.sizePolicy().hasHeightForWidth())
self.frame_5.setSizePolicy(sizePolicy)
self.frame_5.setFrameShape(QtGui.QFrame.Box)
self.frame_5.setFrameShadow(QtGui.QFrame.Sunken)
self.frame_5.setObjectName(_fromUtf8("frame_5"))
self.spectra_plot = MPL_Widget(self.frame_5)
self.spectra_plot.setGeometry(QtCore.QRect(250, 0, 491, 241))
self.spectra_plot.setObjectName(_fromUtf8("spectra_plot"))
self.pixel_number_label = QtGui.QLabel(self.frame_5)
self.pixel_number_label.setGeometry(QtCore.QRect(40, 50, 131, 31))
self.pixel_number_label.setFrameShape(QtGui.QFrame.NoFrame)
self.pixel_number_label.setAlignment(QtCore.Qt.AlignCenter)
self.pixel_number_label.setObjectName(_fromUtf8("pixel_number_label"))
self.pixelpath = QtGui.QLabel(self.frame_5)
self.pixelpath.setGeometry(QtCore.QRect(40, 90, 141, 31))
font = QtGui.QFont()
font.setPointSize(14)
self.pixelpath.setFont(font)
self.pixelpath.setFrameShape(QtGui.QFrame.Box)
self.pixelpath.setText(_fromUtf8(""))
self.pixelpath.setObjectName(_fromUtf8("pixelpath"))
self.row = QtGui.QLabel(self.frame_5)
self.row.setGeometry(QtCore.QRect(40, 150, 61, 31))
self.row.setFrameShape(QtGui.QFrame.Box)
self.row.setText(_fromUtf8(""))
self.row.setObjectName(_fromUtf8("row"))
self.label_32 = QtGui.QLabel(self.frame_5)
self.label_32.setGeometry(QtCore.QRect(40, 130, 61, 16))
self.label_32.setObjectName(_fromUtf8("label_32"))
self.col = QtGui.QLabel(self.frame_5)
self.col.setGeometry(QtCore.QRect(130, 150, 61, 31))
self.col.setFrameShape(QtGui.QFrame.Box)
self.col.setText(_fromUtf8(""))
self.col.setObjectName(_fromUtf8("col"))
self.label_34 = QtGui.QLabel(self.frame_5)
self.label_34.setGeometry(QtCore.QRect(130, 130, 61, 16))
self.label_34.setObjectName(_fromUtf8("label_34"))
self.groupBox = QtGui.QGroupBox(self.centralwidget)
self.groupBox.setGeometry(QtCore.QRect(870, 10, 171, 191))
self.groupBox.setObjectName(_fromUtf8("groupBox"))
self.drag_select_radioButton = QtGui.QRadioButton(self.groupBox)
self.drag_select_radioButton.setGeometry(QtCore.QRect(10, 30, 141, 31))
self.drag_select_radioButton.setAutoExclusive(False)
self.drag_select_radioButton.setObjectName(_fromUtf8("drag_select_radioButton"))
self.mode_buttonGroup = QtGui.QButtonGroup(arcons)
self.mode_buttonGroup.setObjectName(_fromUtf8("mode_buttonGroup"))
self.mode_buttonGroup.addButton(self.drag_select_radioButton)
self.rect_select_radioButton = QtGui.QRadioButton(self.groupBox)
self.rect_select_radioButton.setGeometry(QtCore.QRect(10, 70, 161, 21))
self.rect_select_radioButton.setChecked(True)
self.rect_select_radioButton.setAutoExclusive(False)
self.rect_select_radioButton.setObjectName(_fromUtf8("rect_select_radioButton"))
self.mode_buttonGroup.addButton(self.rect_select_radioButton)
self.rect_x_spinBox = QtGui.QSpinBox(self.groupBox)
self.rect_x_spinBox.setGeometry(QtCore.QRect(30, 90, 57, 31))
self.rect_x_spinBox.setMinimum(1)
self.rect_x_spinBox.setMaximum(32)
self.rect_x_spinBox.setProperty(_fromUtf8("value"), 1)
self.rect_x_spinBox.setObjectName(_fromUtf8("rect_x_spinBox"))
self.rect_y_spinBox = QtGui.QSpinBox(self.groupBox)
self.rect_y_spinBox.setGeometry(QtCore.QRect(110, 90, 57, 31))
self.rect_y_spinBox.setMinimum(1)
self.rect_y_spinBox.setMaximum(32)
self.rect_y_spinBox.setProperty(_fromUtf8("value"), 1)
self.rect_y_spinBox.setObjectName(_fromUtf8("rect_y_spinBox"))
self.label_23 = QtGui.QLabel(self.groupBox)
self.label_23.setGeometry(QtCore.QRect(20, 90, 16, 31))
self.label_23.setObjectName(_fromUtf8("label_23"))
self.label_24 = QtGui.QLabel(self.groupBox)
self.label_24.setGeometry(QtCore.QRect(100, 90, 16, 31))
self.label_24.setObjectName(_fromUtf8("label_24"))
self.circ_select_radioButton = QtGui.QRadioButton(self.groupBox)
self.circ_select_radioButton.setGeometry(QtCore.QRect(10, 130, 151, 21))
self.circ_select_radioButton.setAutoExclusive(False)
self.circ_select_radioButton.setObjectName(_fromUtf8("circ_select_radioButton"))
self.mode_buttonGroup.addButton(self.circ_select_radioButton)
self.circ_r_spinBox = QtGui.QSpinBox(self.groupBox)
self.circ_r_spinBox.setGeometry(QtCore.QRect(40, 150, 57, 31))
self.circ_r_spinBox.setMinimum(0)
self.circ_r_spinBox.setMaximum(16)
self.circ_r_spinBox.setProperty(_fromUtf8("value"), 0)
self.circ_r_spinBox.setObjectName(_fromUtf8("circ_r_spinBox"))
self.label_25 = QtGui.QLabel(self.groupBox)
self.label_25.setGeometry(QtCore.QRect(30, 150, 16, 31))
self.label_25.setObjectName(_fromUtf8("label_25"))
self.choose_beamimage = QtGui.QPushButton(self.centralwidget)
self.choose_beamimage.setGeometry(QtCore.QRect(1050, 770, 171, 41))
self.choose_beamimage.setObjectName(_fromUtf8("choose_beamimage"))
self.choose_bindir = QtGui.QPushButton(self.centralwidget)
self.choose_bindir.setGeometry(QtCore.QRect(1050, 740, 171, 41))
self.choose_bindir.setObjectName(_fromUtf8("choose_bindir"))
self.brightpix = QtGui.QSpinBox(self.centralwidget)
self.brightpix.setGeometry(QtCore.QRect(880, 250, 57, 25))
self.brightpix.setMaximum(2024)
self.brightpix.setProperty(_fromUtf8("value"), 50)
self.brightpix.setObjectName(_fromUtf8("brightpix"))
self.label_22 = QtGui.QLabel(self.centralwidget)
self.label_22.setGeometry(QtCore.QRect(940, 250, 121, 21))
self.label_22.setObjectName(_fromUtf8("label_22"))
self.takesky = QtGui.QPushButton(self.centralwidget)
self.takesky.setGeometry(QtCore.QRect(1050, 700, 171, 51))
self.takesky.setObjectName(_fromUtf8("takesky"))
self.frame_7 = QtGui.QFrame(self.centralwidget)
self.frame_7.setGeometry(QtCore.QRect(860, 390, 181, 511))
self.frame_7.setFrameShape(QtGui.QFrame.Box)
self.frame_7.setFrameShadow(QtGui.QFrame.Sunken)
self.frame_7.setObjectName(_fromUtf8("frame_7"))
self.label_36 = QtGui.QLabel(self.frame_7)
self.label_36.setGeometry(QtCore.QRect(30, 10, 141, 41))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Arial"))
font.setPointSize(18)
font.setWeight(75)
font.setBold(True)
self.label_36.setFont(font)
self.label_36.setObjectName(_fromUtf8("label_36"))
self.cal_time = QtGui.QSpinBox(self.frame_7)
self.cal_time.setGeometry(QtCore.QRect(20, 180, 57, 25))
self.cal_time.setMaximum(10000)
self.cal_time.setObjectName(_fromUtf8("cal_time"))
self.cal_angle = QtGui.QDoubleSpinBox(self.frame_7)
self.cal_angle.setGeometry(QtCore.QRect(90, 180, 62, 25))
self.cal_angle.setMaximum(360.0)
self.cal_angle.setObjectName(_fromUtf8("cal_angle"))
self.goto_angle = QtGui.QDoubleSpinBox(self.frame_7)
self.goto_angle.setGeometry(QtCore.QRect(90, 240, 62, 25))
self.goto_angle.setObjectName(_fromUtf8("goto_angle"))
self.label_37 = QtGui.QLabel(self.frame_7)
self.label_37.setGeometry(QtCore.QRect(90, 220, 62, 17))
self.label_37.setObjectName(_fromUtf8("label_37"))
self.label_38 = QtGui.QLabel(self.frame_7)
self.label_38.setGeometry(QtCore.QRect(20, 160, 51, 21))
font = QtGui.QFont()
font.setPointSize(10)
self.label_38.setFont(font)
self.label_38.setObjectName(_fromUtf8("label_38"))
self.label_39 = QtGui.QLabel(self.frame_7)
self.label_39.setGeometry(QtCore.QRect(90, 160, 61, 21))
font = QtGui.QFont()
font.setPointSize(10)
self.label_39.setFont(font)
self.label_39.setObjectName(_fromUtf8("label_39"))
self.do_cal_button = QtGui.QPushButton(self.frame_7)
self.do_cal_button.setGeometry(QtCore.QRect(10, 120, 151, 41))
self.do_cal_button.setObjectName(_fromUtf8("do_cal_button"))
self.go_home_button = QtGui.QPushButton(self.frame_7)
self.go_home_button.setGeometry(QtCore.QRect(10, 61, 151, 41))
self.go_home_button.setObjectName(_fromUtf8("go_home_button"))
self.goto_button = QtGui.QPushButton(self.frame_7)
self.goto_button.setGeometry(QtCore.QRect(10, 220, 71, 51))
self.goto_button.setObjectName(_fromUtf8("goto_button"))
self.label_40 = QtGui.QLabel(self.frame_7)
self.label_40.setGeometry(QtCore.QRect(20, 310, 151, 41))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Arial"))
font.setPointSize(18)
font.setWeight(75)
font.setBold(True)
self.label_40.setFont(font)
self.label_40.setObjectName(_fromUtf8("label_40"))
self.laser_toggle = QtGui.QCheckBox(self.frame_7)
self.laser_toggle.setGeometry(QtCore.QRect(20, 270, 111, 41))
self.laser_toggle.setObjectName(_fromUtf8("laser_toggle"))
self.laser_label = QtGui.QLabel(self.frame_7)
self.laser_label.setGeometry(QtCore.QRect(120, 270, 51, 41))
self.laser_label.setObjectName(_fromUtf8("laser_label"))
self.filter1 = QtGui.QRadioButton(self.frame_7)
self.filter1.setGeometry(QtCore.QRect(20, 350, 102, 21))
self.filter1.setAutoExclusive(False)
self.filter1.setObjectName(_fromUtf8("filter1"))
self.filter_buttonGroup = QtGui.QButtonGroup(arcons)
self.filter_buttonGroup.setObjectName(_fromUtf8("filter_buttonGroup"))
self.filter_buttonGroup.addButton(self.filter1)
self.filter2 = QtGui.QRadioButton(self.frame_7)
self.filter2.setGeometry(QtCore.QRect(20, 370, 102, 21))
self.filter2.setAutoExclusive(False)
self.filter2.setObjectName(_fromUtf8("filter2"))
self.filter_buttonGroup.addButton(self.filter2)
self.filter3 = QtGui.QRadioButton(self.frame_7)
self.filter3.setGeometry(QtCore.QRect(20, 390, 102, 21))
self.filter3.setAutoExclusive(False)
self.filter3.setObjectName(_fromUtf8("filter3"))
self.filter_buttonGroup.addButton(self.filter3)
self.filter4 = QtGui.QRadioButton(self.frame_7)
self.filter4.setGeometry(QtCore.QRect(20, 410, 102, 21))
self.filter4.setAutoExclusive(False)
self.filter4.setObjectName(_fromUtf8("filter4"))
self.filter_buttonGroup.addButton(self.filter4)
self.filter5 = QtGui.QRadioButton(self.frame_7)
self.filter5.setGeometry(QtCore.QRect(20, 430, 102, 21))
self.filter5.setAutoExclusive(False)
self.filter5.setObjectName(_fromUtf8("filter5"))
self.filter_buttonGroup.addButton(self.filter5)
self.filter6 = QtGui.QRadioButton(self.frame_7)
self.filter6.setGeometry(QtCore.QRect(20, 450, 102, 21))
self.filter6.setChecked(True)
self.filter6.setAutoExclusive(False)
self.filter6.setObjectName(_fromUtf8("filter6"))
self.filter_buttonGroup.addButton(self.filter6)
self.label_26 = QtGui.QLabel(self.centralwidget)
self.label_26.setGeometry(QtCore.QRect(1060, 810, 101, 17))
self.label_26.setObjectName(_fromUtf8("label_26"))
self.label_17 = QtGui.QLabel(self.centralwidget)
self.label_17.setGeometry(QtCore.QRect(1060, 830, 46, 13))
self.label_17.setObjectName(_fromUtf8("label_17"))
self.label_18 = QtGui.QLabel(self.centralwidget)
self.label_18.setGeometry(QtCore.QRect(1060, 863, 46, 20))
self.label_18.setObjectName(_fromUtf8("label_18"))
self.RA_lineEdit = QtGui.QLineEdit(self.centralwidget)
self.RA_lineEdit.setEnabled(False)
self.RA_lineEdit.setGeometry(QtCore.QRect(1060, 840, 113, 20))
self.RA_lineEdit.setObjectName(_fromUtf8("RA_lineEdit"))
self.Dec_lineEdit = QtGui.QLineEdit(self.centralwidget)
self.Dec_lineEdit.setEnabled(False)
self.Dec_lineEdit.setGeometry(QtCore.QRect(1060, 880, 113, 20))
self.Dec_lineEdit.setObjectName(_fromUtf8("Dec_lineEdit"))
self.label_41 = QtGui.QLabel(self.centralwidget)
self.label_41.setGeometry(QtCore.QRect(900, 210, 141, 41))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Arial"))
font.setPointSize(18)
font.setWeight(75)
font.setBold(True)
self.label_41.setFont(font)
self.label_41.setObjectName(_fromUtf8("label_41"))
self.vmin = QtGui.QSpinBox(self.centralwidget)
self.vmin.setGeometry(QtCore.QRect(886, 350, 61, 25))
self.vmin.setMaximum(1000000)
self.vmin.setProperty(_fromUtf8("value"), 100)
self.vmin.setObjectName(_fromUtf8("vmin"))
self.vmax = QtGui.QSpinBox(self.centralwidget)
self.vmax.setGeometry(QtCore.QRect(960, 350, 57, 25))
self.vmax.setMaximum(1000000)
self.vmax.setProperty(_fromUtf8("value"), 1500)
self.vmax.setObjectName(_fromUtf8("vmax"))
self.label_28 = QtGui.QLabel(self.centralwidget)
self.label_28.setGeometry(QtCore.QRect(940, 280, 62, 17))
self.label_28.setObjectName(_fromUtf8("label_28"))
self.contrast_mode = QtGui.QCheckBox(self.centralwidget)
self.contrast_mode.setGeometry(QtCore.QRect(880, 300, 161, 31))
self.contrast_mode.setObjectName(_fromUtf8("contrast_mode"))
self.label_29 = QtGui.QLabel(self.centralwidget)
self.label_29.setGeometry(QtCore.QRect(890, 330, 62, 17))
font = QtGui.QFont()
font.setPointSize(12)
self.label_29.setFont(font)
self.label_29.setObjectName(_fromUtf8("label_29"))
self.label_30 = QtGui.QLabel(self.centralwidget)
self.label_30.setGeometry(QtCore.QRect(960, 330, 62, 17))
font = QtGui.QFont()
font.setPointSize(11)
self.label_30.setFont(font)
self.label_30.setObjectName(_fromUtf8("label_30"))
arcons.setCentralWidget(self.centralwidget)
self.statusbar = QtGui.QStatusBar(arcons)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
arcons.setStatusBar(self.statusbar)
self.menubar = QtGui.QMenuBar(arcons)
self.menubar.setGeometry(QtCore.QRect(0, 0, 860, 22))
self.menubar.setObjectName(_fromUtf8("menubar"))
arcons.setMenuBar(self.menubar)
self.retranslateUi(arcons)
QtCore.QObject.connect(self.close_pushButton, QtCore.SIGNAL(_fromUtf8("clicked()")), arcons.close)
QtCore.QMetaObject.connectSlotsByName(arcons)
def retranslateUi(self, arcons):
arcons.setWindowTitle(QtGui.QApplication.translate("arcons", "ARCONS", None, QtGui.QApplication.UnicodeUTF8))
self.label.setText(QtGui.QApplication.translate("arcons", "ARCONS Status", None, QtGui.QApplication.UnicodeUTF8))
self.label_3.setText(QtGui.QApplication.translate("arcons", "Array Temp", None, QtGui.QApplication.UnicodeUTF8))
self.label_4.setText(QtGui.QApplication.translate("arcons", "Pulse Tube Temp", None, QtGui.QApplication.UnicodeUTF8))
self.open_shutter_radioButton.setText(QtGui.QApplication.translate("arcons", "Open Shutter", None, QtGui.QApplication.UnicodeUTF8))
self.cycle_fridge_radioButton.setText(QtGui.QApplication.translate("arcons", "Cycle Fridge", None, QtGui.QApplication.UnicodeUTF8))
self.label_2.setText(QtGui.QApplication.translate("arcons", "Telescope Status", None, QtGui.QApplication.UnicodeUTF8))
self.label_5.setText(QtGui.QApplication.translate("arcons", "RA", None, QtGui.QApplication.UnicodeUTF8))
self.label_6.setText(QtGui.QApplication.translate("arcons", "Dec", None, QtGui.QApplication.UnicodeUTF8))
self.label_7.setText(QtGui.QApplication.translate("arcons", "UTC", None, QtGui.QApplication.UnicodeUTF8))
self.label_8.setText(QtGui.QApplication.translate("arcons", "Altitude", None, QtGui.QApplication.UnicodeUTF8))
self.label_9.setText(QtGui.QApplication.translate("arcons", "Azimuth", None, QtGui.QApplication.UnicodeUTF8))
self.label_10.setText(QtGui.QApplication.translate("arcons", "Local Time", None, QtGui.QApplication.UnicodeUTF8))
self.label_11.setText(QtGui.QApplication.translate("arcons", "Airmass", None, QtGui.QApplication.UnicodeUTF8))
self.label_12.setText(QtGui.QApplication.translate("arcons", "LST", None, QtGui.QApplication.UnicodeUTF8))
self.status_label.setText(QtGui.QApplication.translate("arcons", "Status", None, QtGui.QApplication.UnicodeUTF8))
self.save_raw_checkBox.setText(QtGui.QApplication.translate("arcons", " Save Raw", None, QtGui.QApplication.UnicodeUTF8))
self.label_14.setText(QtGui.QApplication.translate("arcons", "Data Directory:", None, QtGui.QApplication.UnicodeUTF8))
self.label_16.setText(QtGui.QApplication.translate("arcons", "Remaining time:", None, QtGui.QApplication.UnicodeUTF8))
self.label_13.setText(QtGui.QApplication.translate("arcons", "SDR Control", None, QtGui.QApplication.UnicodeUTF8))
self.label_15.setText(QtGui.QApplication.translate("arcons", "Exposure Time:", None, QtGui.QApplication.UnicodeUTF8))
self.calibrate_data_checkBox.setText(QtGui.QApplication.translate("arcons", "Calibrate Data", None, QtGui.QApplication.UnicodeUTF8))
self.stop_observation_pushButton.setText(QtGui.QApplication.translate("arcons", "Stop Observation", None, QtGui.QApplication.UnicodeUTF8))
self.start_observation_pushButton.setText(QtGui.QApplication.translate("arcons", "Start Observation", None, QtGui.QApplication.UnicodeUTF8))
self.close_pushButton.setText(QtGui.QApplication.translate("arcons", "Close", None, QtGui.QApplication.UnicodeUTF8))
self.search_pushButton.setText(QtGui.QApplication.translate("arcons", "Browse", None, QtGui.QApplication.UnicodeUTF8))
self.frequency_tuneup_pushButton.setText(QtGui.QApplication.translate("arcons", "Frequency \n"
"Tune-up", None, QtGui.QApplication.UnicodeUTF8))
self.target_lineEdit.setText(QtGui.QApplication.translate("arcons", "Target", None, QtGui.QApplication.UnicodeUTF8))
self.label_20.setText(QtGui.QApplication.translate("arcons", "File name:", None, QtGui.QApplication.UnicodeUTF8))
self.label_21.setText(QtGui.QApplication.translate("arcons", "Target name:", None, QtGui.QApplication.UnicodeUTF8))
self.subtract_sky_radioButton.setText(QtGui.QApplication.translate("arcons", "Subtract Sky", None, QtGui.QApplication.UnicodeUTF8))
self.flat_field_radioButton.setText(QtGui.QApplication.translate("arcons", "Flat Field", None, QtGui.QApplication.UnicodeUTF8))
self.label_19.setText(QtGui.QApplication.translate("arcons", " Integration (s)", None, QtGui.QApplication.UnicodeUTF8))
self.options_radioButton.setText(QtGui.QApplication.translate("arcons", "Expand Controls-->", None, QtGui.QApplication.UnicodeUTF8))
self.label_27.setText(QtGui.QApplication.translate("arcons", "Additional Header Info:", None, QtGui.QApplication.UnicodeUTF8))
self.update_description.setText(QtGui.QApplication.translate("arcons", "Update in Header", None, QtGui.QApplication.UnicodeUTF8))
self.continuous.setText(QtGui.QApplication.translate("arcons", " Continuous Observing", None, QtGui.QApplication.UnicodeUTF8))
self.pixel_number_label.setText(QtGui.QApplication.translate("arcons", "Displaying Plot for\n"
" Pixel Number:", None, QtGui.QApplication.UnicodeUTF8))
self.label_32.setText(QtGui.QApplication.translate("arcons", "Row:", None, QtGui.QApplication.UnicodeUTF8))
self.label_34.setText(QtGui.QApplication.translate("arcons", "Col:", None, QtGui.QApplication.UnicodeUTF8))
self.groupBox.setTitle(QtGui.QApplication.translate("arcons", "Pixel Selection Mode", None, QtGui.QApplication.UnicodeUTF8))
self.drag_select_radioButton.setText(QtGui.QApplication.translate("arcons", "Click && Drag", None, QtGui.QApplication.UnicodeUTF8))
self.rect_select_radioButton.setText(QtGui.QApplication.translate("arcons", "Single Click Rectangle", None, QtGui.QApplication.UnicodeUTF8))
self.label_23.setText(QtGui.QApplication.translate("arcons", "x", None, QtGui.QApplication.UnicodeUTF8))
self.label_24.setText(QtGui.QApplication.translate("arcons", "y", None, QtGui.QApplication.UnicodeUTF8))
self.circ_select_radioButton.setText(QtGui.QApplication.translate("arcons", "Single Click Circle", None, QtGui.QApplication.UnicodeUTF8))
self.label_25.setText(QtGui.QApplication.translate("arcons", "r", None, QtGui.QApplication.UnicodeUTF8))
self.choose_beamimage.setText(QtGui.QApplication.translate("arcons", "Choose Beamimage", None, QtGui.QApplication.UnicodeUTF8))
self.choose_bindir.setText(QtGui.QApplication.translate("arcons", "Choose Bin Dir.", None, QtGui.QApplication.UnicodeUTF8))
self.label_22.setText(QtGui.QApplication.translate("arcons", "Saturated Pix", None, QtGui.QApplication.UnicodeUTF8))
self.takesky.setText(QtGui.QApplication.translate("arcons", "Take Sky Exposure", None, QtGui.QApplication.UnicodeUTF8))
self.label_36.setText(QtGui.QApplication.translate("arcons", "Calibration", None, QtGui.QApplication.UnicodeUTF8))
self.label_37.setText(QtGui.QApplication.translate("arcons", "Angle", None, QtGui.QApplication.UnicodeUTF8))
self.label_38.setText(QtGui.QApplication.translate("arcons", "Cal Time:", None, QtGui.QApplication.UnicodeUTF8))
self.label_39.setText(QtGui.QApplication.translate("arcons", "Cal Angle:", None, QtGui.QApplication.UnicodeUTF8))
self.do_cal_button.setText(QtGui.QApplication.translate("arcons", "Do Cal", None, QtGui.QApplication.UnicodeUTF8))
self.go_home_button.setText(QtGui.QApplication.translate("arcons", "Go Home", None, QtGui.QApplication.UnicodeUTF8))
self.goto_button.setText(QtGui.QApplication.translate("arcons", "GoTo", None, QtGui.QApplication.UnicodeUTF8))
self.label_40.setText(QtGui.QApplication.translate("arcons", "Filter Wheel", None, QtGui.QApplication.UnicodeUTF8))
self.laser_toggle.setText(QtGui.QApplication.translate("arcons", "Laser Box", None, QtGui.QApplication.UnicodeUTF8))
self.laser_label.setText(QtGui.QApplication.translate("arcons", "OFF", None, QtGui.QApplication.UnicodeUTF8))
self.filter1.setText(QtGui.QApplication.translate("arcons", "Filter 1", None, QtGui.QApplication.UnicodeUTF8))
self.filter2.setText(QtGui.QApplication.translate("arcons", "Filter 2", None, QtGui.QApplication.UnicodeUTF8))
self.filter3.setText(QtGui.QApplication.translate("arcons", "Filter 3", None, QtGui.QApplication.UnicodeUTF8))
self.filter4.setText(QtGui.QApplication.translate("arcons", "Filter 4", None, QtGui.QApplication.UnicodeUTF8))
self.filter5.setText(QtGui.QApplication.translate("arcons", "Filter 5", None, QtGui.QApplication.UnicodeUTF8))
self.filter6.setText(QtGui.QApplication.translate("arcons", "Filter 6", None, QtGui.QApplication.UnicodeUTF8))
self.label_26.setText(QtGui.QApplication.translate("arcons", "Testing Junk", None, QtGui.QApplication.UnicodeUTF8))
self.label_17.setText(QtGui.QApplication.translate("arcons", "RA", None, QtGui.QApplication.UnicodeUTF8))
self.label_18.setText(QtGui.QApplication.translate("arcons", "Dec", None, QtGui.QApplication.UnicodeUTF8))
self.RA_lineEdit.setText(QtGui.QApplication.translate("arcons", "0.0", None, QtGui.QApplication.UnicodeUTF8))
self.Dec_lineEdit.setText(QtGui.QApplication.translate("arcons", "0.0", None, QtGui.QApplication.UnicodeUTF8))
self.label_41.setText(QtGui.QApplication.translate("arcons", "Contrast", None, QtGui.QApplication.UnicodeUTF8))
self.label_28.setText(QtGui.QApplication.translate("arcons", "or", None, QtGui.QApplication.UnicodeUTF8))
self.contrast_mode.setText(QtGui.QApplication.translate("arcons", "Manually", None, QtGui.QApplication.UnicodeUTF8))
self.label_29.setText(QtGui.QApplication.translate("arcons", "Min", None, QtGui.QApplication.UnicodeUTF8))
self.label_30.setText(QtGui.QApplication.translate("arcons", "Max", None, QtGui.QApplication.UnicodeUTF8))
from mpl_pyqt4_widget import MPL_Widget
|
Availability: Essential Cleansing Solution is no longer available. Try the New Dermalogica Intensive Moisture Cleanser.
I’ve been using Dermalogica for over 20 years!! I love this product..
I've been using the Essential Cleansing Solution for years. It's the best. I wouldn't use anything else.
Love it. Really does a great job cleaning.
I use this product so many years ,it make my face smooth and very clean ,I love it.
This is the very first product I used from dermalogicas line years ago. I was hooked!! I still use this everyday but, at nigh time I do use the age smart cleansing solution. Those two together seem to work best do me and I wouldn't trade either one of them for anything !!
Wouldn't consider using anything else. Dermologica essential cleansing solution is a gentle cleanser for my dry aged skin. Feels wonderful after cleansing!
|
# -*- coding: utf-8 -*-
"""
Created on Thu May 21 14:37:15 2015
@author: Marco Tinacci
"""
import networkx as nx
import matplotlib.pyplot as plt
import numpy as np
import Contagion
def plotGraph(g,alpha,node_scale=1, seed=None, pos=None):
# layout
if pos == None:
pos = nx.circular_layout(g)
# pos = nx.random_layout(g)
# draw nodes
nx.draw_networkx_nodes(g,pos,
nodelist = filter(lambda x:g.node[x]['BANKRUPT'] == 0,g.nodes()), # active -> green
node_size = [node_scale*g.node[k]['ASSET'] for k in g.nodes()],
node_color = 'g')#[node_scale*g.node[k]['ASSET'] for k in g.nodes()],cmap = plt.cm.Blues)
nx.draw_networkx_nodes(g,pos,
nodelist = filter(lambda x:g.node[x]['BANKRUPT'] == 2,g.nodes()), # failure -> yellow
node_size = 10,
node_color = 'y',
node_shape = 's')
nx.draw_networkx_nodes(g,pos,
nodelist = filter(lambda x:g.node[x]['BANKRUPT'] == 1,g.nodes()), # default -> red
node_size = 10,
node_color = 'r',
node_shape = 's')
nx.draw_networkx_nodes(g,pos,
nodelist = filter(lambda x:g.node[x]['BANKRUPT'] == 3,g.nodes()), # init -> blue
node_size = 10,
node_color = 'b',
node_shape = 's')
# draw edges
if g.edges():
edges,weights = zip(*nx.get_edge_attributes(g,'weight').items())
nx.draw_networkx_edges(g, pos,
edge_color = map(lambda x:x+20,weights),
width=1,
edge_cmap = plt.cm.Blues,
arrows=False)
# plot graph
nx.write_gml(g,'output_graphs/n'+str(len(g))+'a'+str(alpha)+'s'+str(seed)+'.gml')
plt.savefig('output_graphs/n'+str(len(g))+'a'+str(alpha)+'s'+str(seed)+'.png')
plt.show()
return pos
def scatterDegreeSize(g):
# fig = plt.figure()
# ax2 = fig.add_subplot(111)
# ax2.scatter(map(lambda x:g.degree(x), g.nodes()),
# map(lambda y:y['ASSET'], g.node.values()))
plt.scatter(map(lambda x:g.degree(x), g.nodes()),
map(lambda y:y['ASSET'], g.node.values()))
plt.xlabel('degree')
plt.ylabel('asset')
plt.show()
|
Analipsi is between two of Crete's prime destinations, Heraklion, 25 km to the west, and Hersonissos, just a few km to the east. Analipsi saw development as a tourist destination a bit later than other places, thus it presents in some respects a more authentic Cretan experience.
The village, set among the fields, fruit and olive groves of rural Crete, hugs a kilometer-long level stretch of land and is a place of white houses with gardens, and tavernas draped with wisteria their entrances, some of which have stylistic calligraphic script-like signage instead of traditional block-style letters.
As you enter the village you come to the tiny, picturesque whitewashed chapel of Agia Marina (patron of pregnant women, childbirth, peasants, and dying people, among others). You may be able to cram a half dozen people into this blue-trimmed little jewel, which is a favorite spot for photographers, especially during those golden summer sunsets which Crete is well-known for. Lyttos Beach is just east of the church. This large, sandy, and well-organized with umbrellas and sun beds is the town's main beach.
Since many of the people in the village work fields outside of the village, you'll encounter the occasional farm implement laying around - plows, discs and the like, as well as lots of older people in traditional long dresses, head scarves, or the familiar black of the older widow. The site of villagers setting chairs in front of their houses, chatting, smoking and playing backgammon makes this place look as normal as life can be in rural Greece.
The pace of life in Analipsi forces you to slow down to match its rhythms. Life revolves around the central square for the locals, with its cafes and restaurants, and the beaches for the tourists.
After some rocky coastline, there are some other beaches west of Analipsi, some of which are good for wind surfing when the conditions are right.
Analipsi is a good base for exploring other destinations in Crete, such as Heraklion, the capital, a 25-minute drive away, and the Palace of Knossos, just south of Heraklion. The Lassithi Plateau, a half-hour's drive south of Analipsi, is a scenic rural area of citrus grove, monasteries, and forgotten villages perched on hill and mountainsides.
Analipsi is a nice place for a quiet holiday and a taste of the real Crete.
|
# ask for int, report runnig total / version 1
num = 0
total = 0
while num != -1:
total = total + num
print("total so far = " + str(total))
num = int(input("next int: "))
# ask for int, report runnig total / version 2
total = 0
while True:
num = int(input("next int: "))
if num == -1:
break
total += num
print("total so far = " + str(total))
# check if number is prime
num = int(input("int: "))
total = 0
for x in range(2, num):
if num % x == 0:
print(str(num) + " is NOT prime")
break # we don't need to continue checking
else:
print(str(num) + " is PRIME")
# check multiple numbers
while True:
num = int(input("int: "))
if num == -1:
break
if num < 3:
print("int must be greater than 2")
continue
is_prime = True
for i in range(2, num):
if num % i == 0:
is_prime = False
break
if is_prime:
print(str(num) + " is PRIME")
else:
print(str(num) + " is NOT prime")
# print out primes up to 100
for i in range(3, 101):
is_prime = True
for j in range(2, i-1):
if i % j == 0:
is_prime = False
break
if is_prime:
print(str(i) + " is PRIME")
else:
print(str(i) + " is NOT prime")
# print multilication table
for i in range(1, 11):
for j in range(1, 11):
print("%3d" % (i * j), end=' ')
print()
print()
|
Pulitzer Prize-winning biographer Stacy Schiff’s erudite, well-researched and often witty reconstruction of the brief life of Cleopatra, now out in paperback, establishes in her opening pages the fact that much of what we know about the famous Egyptian queen was written by wags and detractors decades and even centuries after she died at the age of 39 in 69 B.C.
Using writers contemporary with Cleopatra as her primary sources, Schiff separates fact from fiction in long, sweeping paragraphs so filled with rich descriptions that the reader is often compelled to reread them to get the full impact of the luminous and vivid details.
During her 21-year reign, Cleopatra ruled over a massive swath of countries along the Mediterranean, from Cyrene (in modern Libya) to the west to Tarsus (southern Turkey) and Cyprus in the east — every coastal Mideast country save Palestine. Her armies were no competition for the Romans, whom she held off with her astute negotiations, but her naval fleet was impressive.
Cleopatra was the seventh in a line with that name, and she wasn’t even Egyptian: She was Macedonian, as was the namesake of her capital city. Following the trend of crowned heads in her time, she murdered her two younger brothers, to whom she was married, and her sister, to preserve her throne. (Contemporary King Herod killed his own children and half of his wife’s family.) One of her ancestors, Ptolemy VII, raped his niece when she was an adolescent. Following a quarrel, he killed their 14-year-old son, chopped him into bits and sent the pieces in a trunk to the boy’s mother on the eve of her birthday.
Cleopatra spoke nine languages fluently. The Egyptian language and hieroglyphics were so difficult to speak and read that Greek was the primary language of diplomacy and commerce. Cleopatra was the only member of the Ptolemy dynasty to learn her people’s language.
With the possible exception of Queen Elizabeth I, she was the most successful female ruler who ever lived, and the richest. One list estimates her worth at nearly $96 billion, making her the 22nd wealthiest person in history.
Egypt’s rich wheat fields, watered annually by the flooding of the Nile River, became the breadbasket of the Mideast and major supplier of grain to Rome.
Her famous barges were 300 feet long, powered by purple sails. “Their bows were ivory, elaborate colonnades lined the deck ... eighteen foot gilded statues decorated stern and prow.” Silver and gold-plated serving pieces weighing tons were given to diners as souvenirs, as were the tables and couches they had dined upon. A fleet of 400 supply ships followed the queen’s barge.
Cleopatra seduced often-married Julius Caesar and produced his only son, Caesarion (“little Caesar”). She felt that the son, who closely resembled his father, and his name would guarantee amnesty for them both in the event conditions with Rome ever soured. After Caesar’s assassination in 44 B.C., she likewise seduced Mark Antony, gave him three children and, as far as Rome was concerned, turned him into an Egyptian.
Shiff makes it clear that Cleopatra was no Elizabeth Taylor. The only credible likeness of Cleopatra, on a coin, portrays her with a hooked nose and a strong chin, hardly a beauty.
Was she the harlot her Roman contemporaries and later historians claimed? Shiff found no evidence that she had sexual liaisons with any men other than Julius Caesar and Mark Antony.
In Cleopatra’s suicide, Shiff makes a strong case for poison, not an asp. She had been experimenting (on servants, of course) with various concoctions that would be swift and painless. Hemlock and opium were traditional and good choices, but Shiff concludes, as Plutarch had, that “no one knows.” No record of her burial site remains.
Cleopatra’s legacy continues to fascinate and has not diminished over the millennia. Stacy Shiff’s superb and scholarly study of the “king of queens” is well worth reading and even rereading.
Doug James is an adjunct professor of communication arts at Spring Hill College.
|
from django.contrib import admin
from django.db import models
from django import forms
ARTICLE_BASE_FIELDSET = (
None, {
'fields': ('title', 'slug', 'subtitle', 'summary', 'content', 'update_date', )
}
)
ARTICLE_CONTENT_FIELDSET = (
None, {
'fields': ('title', 'subtitle', 'summary', 'content', )
}
)
ARTCILE_METADATA_FIELDSET = (
'Metadata', {
'fields': ('slug', 'create_date', 'update_date', 'modified_date', ),
'classes': ('collapse', )
}
)
SINGLE_AUTHOR_FIELDSET = (
'Author', {
'fields': ('author', ),
}
)
MULTI_AUTHOR_FIELDSET = (
'Authors', {
'fields': ('authors', ),
}
)
NONSTAFF_AUTHOR_FIELDSET = (
'Author', {
'fields': ('non_staff_author', ),
}
)
KEY_IMAGE_FIELDSET = (
'Key Image', {
'fields': ('key_image', 'key_image_credit', )
}
)
PUBLISHING_FIELDSET = (
'Publishing', {
'fields': ('status', ('pub_date', 'pub_time'), )
}
)
class ArticleBaseAdmin(admin.ModelAdmin):
search_fields = ('title', 'subtitle', )
prepopulated_fields = {'slug': ('title', )}
formfield_overrides = {
models.CharField: {'widget': forms.TextInput(attrs={'size': '117'})},
}
|
Can you make Every Day From Online Roulette? - Yes!
Ok, so you’ve tried all the ‘Paid and Free Roulette Systems’ and now you need something that can actually work.
Let’s turn the situation around and start making money now. Let’s see if we can win at Roulette and beat the casino. If you take 10 minutes to (carefully) read the following pages, you can win money right away. (There are no downloads, sign-ups or anything to pay). This is where you will find your winning and FREE Roulette Systems to make money online. Roulette Secrets Uncovered? These are Roulette Secrets Uncovered!
The steps I show here are so simple, you can quickly and easily learn a Roulette Strategy, even if you have never played Roulette before and are a total beginner! Aim for small but consistent wins. It all adds up.
My name is Ryan, I work as a freelance software consultant for many of the major online casinos (since 2001), especially on gambling systems for Roulette and table-based games. I provide free roulette systems and roulette strategy.
The important rule to making money online is to stick to the rules and make £150 to £300 (or more) profit a day, every day, tax free. (Some friends call this teleworking, telecommuting, working from home – I’m not so sure!). The systems work with all major currencies.
Rule 1 : Do Not change to a different Roulette System half-way through a game.
Rule 2 : Do Not get greedy! Just stick with a Roulette System and you will make a profit.
Rule 3 : Do Not use these Systems in ‘real-life’ casinos, they will show you the door!
To make a good profit, you should ideally have at least £40 (around $60 or €45) as your initial playing deposit. This makes up part of the Roulette Strategy. Tip: The software tends to look at this amount as a base unit for a casual player, and not red-flagged for ‘odd’ behaviour. NOTE: Some of the casinos will only allow a minimum wager of £1 in ‘Fun Play’, but at least it’s not your real money! Please don’t jump to Roulette System 2 or 3 until you have tried Roulette System 1 first.
Click on the Guide 1 button and let’s get started with a Free Roulette System that will become your personal cash-cow!
"Thank you Ryan. With your roulette systems, I can comfortably pay my monthly mortgage, without having to get stressed. Good work mate."
"So easy, so so easy. I only play at the weekends, and have used your systems for 4 years. It pays for the family holiday each year. Thank you!"
"I wish I had found your website earlier. In the past month, I gained over €850 with the systems and I will celebrate tonight with friends! Yes!"
PLEASE NOTE: All systems are tried by myself personally, and trusted friends, on the casinos listed, and all of these systems are completely free to you. I will not condone, sell or advertise any system that requires any payment what-so-ever. The systems I use are yours for life. And they are all here – FREE. Never buy any Roulette system or Roulette strategy or Roulette cheats software. The upkeep of this site is minimal, but a little donation would be appreciated once I get around to organising a link! In the meantime, if you like my site, please share it! Are these really Free Roulette Systems? Yes. Will you learn a Roulette Strategy? Yes. Do you need to provide your details to use these? No. Avoid the scams!
A good Roulette Strategy for winning on Roulette is to take just a little time to understand the Roulette Strategy once – this should take no more than 10 minutes of your time. Once you understand the Roulette Strategy, your Free Roulette System will become a joy to use. After all, a roulette strategy is what is going to help you beat the odds. And make money!
|
"""
AGENT: individual attributes
"""
import random
class FemaleState:
juvenile, cycling, pregnant, nursing0, nursing1 = range(5)
class MaleState:
juvsol, sol, fol, lea = range(4)
class HamadryasRhp:
rhp = {
"1": {6: 30, 6.5: 48, 7: 61, 7.5: 65, 8.0: 68, 8.5: 71, 9.0: 73, 9.5: 75, 10.0: 76,
10.5: 77, 11: 78, 11.5: 79, 12: 79.5, 12.5: 80, 13: 80, 13.5: 80,
14: 79.5, 14.5: 79, 15: 78, 15.5: 77, 16: 76, 16.5: 75, 17: 73,
17.5: 71, 18: 68, 18.5: 65, 19: 61, 19.5: 48, 20: 30, 20.5: 0},
"2": {6: 15, 6.5: 24, 7: 30.5, 7.5: 32.5, 8.0: 34, 8.5: 35.5, 9.0: 36.5, 9.5: 37.5, 10.0: 38,
10.5: 38.5, 11: 39, 11.5: 39.5, 12: 39.75, 12.5: 40, 13: 40, 13.5: 40,
14: 39.75, 14.5: 39.5, 15: 39, 15.5: 38.5, 16: 38, 16.5: 37.5, 17: 36.5,
17.5: 35.5, 18: 34, 18.5: 32.5, 19: 30.5, 19.5: 24, 20: 15, 20.5: 0},
"3": {6: 2, 6.5: 4, 7: 6, 7.5: 9, 8.0: 12, 8.5: 16, 9.0: 20, 9.5: 25, 10.0: 30,
10.5: 40, 11: 50, 11.5: 60, 12: 75, 12.5: 90, 13: 96, 13.5: 100,
14: 96, 14.5: 90, 15: 75, 15.5: 60, 16: 50, 16.5: 40, 17: 30,
17.5: 22, 18: 16, 18.5: 11, 19: 8, 19.5: 4, 20: 2, 20.5: 0},
"4": {6: 1, 6.5: 2, 7: 3, 7.5: 4.5, 8.0: 6, 8.5: 8, 9.0: 10, 9.5: 12.5, 10.0: 15,
10.5: 20, 11: 25, 11.5: 30, 12: 37.5, 12.5: 45, 13: 48, 13.5: 50,
14: 48, 14.5: 45, 15: 37.5, 15.5: 30, 16: 25, 16.5: 20, 17: 15,
17.5: 11, 18: 8, 18.5: 5.5, 19: 4, 19.5: 2, 20: 1, 20.5: 0}
}
class AgentClass(object):
def __init__(self, sex, mother, sire):
# defines an agent.py of any species
self.index = 0
self.age = 0.0
self.sex = sex
self.femaleState = None
self.last_birth = None
self.sire_of_fetus = None
self.parents = [mother, sire]
self.offspring = []
self.dispersed = False
# set to True if born during sim
self.born = False
class HamadryasAgent(AgentClass):
# defines the attributes that a hamadryas baboon must have
def __init__(self, sex, mother, sire, bandID):
self.taxon = "hamadryas"
self.clanID = None
self.bandID = bandID
self.OMUID = None
self.maleState = None
self.females = []
self.malefols = []
self.femaleState = None
self.maleState = None
super(HamadryasAgent, self).__init__(sex, mother, sire)
def get_rhp(self):
score = HamadryasRhp.rhp[self.rhp][self.age]
return score
class MakeAgents:
@staticmethod
def makenewhamadryas(bandID, sex, mother, sire, population, sim, age=0.0):
newagent = HamadryasAgent(sex, mother, sire, bandID)
newagent.age = age
if newagent.sex == 'm':
newagent.rhp = MakeAgents.assignrhpcurve(newagent)
else:
newagent.femaleState = FemaleState.juvenile
newagent.index = MakeAgents.get_unique_index(population)
# parents get credit
if sire and sire in population.dict.keys():
population.dict[sire].offspring.append(newagent.index)
population.dict[sire].last_birth = population.halfyear
if mother and mother in population.dict.keys():
population.dict[mother].offspring.append(newagent.index)
return newagent
@staticmethod
def assignrhpcurve(agent):
score = None
if agent.taxon == "hamadryas":
score = random.choice(["1", "2", "3", "4"])
elif agent.taxon == "savannah":
score = random.choice(["1", "2", "3", "4", "5"])
return score
@staticmethod
def get_unique_index(population):
newindex = population.topeverindex + 1
population.topeverindex = newindex
return newindex
|
Query requests used with CloudWatch Events are HTTP or HTTPS requests that use the HTTP verb GET or POST and a Query parameter named Action or Operation. This documentation uses Action, although Operation is supported for backward compatibility.
An endpoint is a URL that serves as an entry point for a web service. You can select a regional endpoint when you make your requests to reduce latency. For information about the endpoints used with CloudWatch Events, see Regions and Endpoints in the Amazon Web Services General Reference.
|
# Copyright 2019 DeepMind Technologies Ltd. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests the C++ matrix game utility methods exposed to Python."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl.testing import absltest
import pyspiel
class TensorGamesUtilsTest(absltest.TestCase):
def test_extensive_to_tensor_game_type(self):
game = pyspiel.extensive_to_tensor_game(
pyspiel.load_game(
"turn_based_simultaneous_game(game=blotto(players=3,coins=5))"))
game_type = game.get_type()
self.assertEqual(game_type.dynamics, pyspiel.GameType.Dynamics.SIMULTANEOUS)
self.assertEqual(game_type.chance_mode,
pyspiel.GameType.ChanceMode.DETERMINISTIC)
self.assertEqual(game_type.information,
pyspiel.GameType.Information.ONE_SHOT)
self.assertEqual(game_type.utility, pyspiel.GameType.Utility.ZERO_SUM)
def test_extensive_to_tensor_game_payoff_tensor(self):
turn_based_game = pyspiel.load_game_as_turn_based(
"blotto(players=3,coins=5)")
tensor_game1 = pyspiel.extensive_to_tensor_game(turn_based_game)
tensor_game2 = pyspiel.load_tensor_game("blotto(players=3,coins=5)")
self.assertEqual(tensor_game1.shape(), tensor_game2.shape())
s0 = turn_based_game.new_initial_state()
self.assertEqual(tensor_game1.shape()[0], s0.num_distinct_actions())
for a0 in range(s0.num_distinct_actions()):
s1 = s0.child(a0)
self.assertEqual(tensor_game1.shape()[1], s1.num_distinct_actions())
for a1 in range(s1.num_distinct_actions()):
s2 = s1.child(a1)
self.assertEqual(tensor_game1.shape()[2], s2.num_distinct_actions())
for a2 in range(s2.num_distinct_actions()):
s3 = s2.child(a2)
self.assertTrue(s3.is_terminal())
for player in range(3):
self.assertEqual(
s3.returns()[player],
tensor_game1.player_utility(player, (a0, a1, a2)))
self.assertEqual(
s3.returns()[player],
tensor_game2.player_utility(player, (a0, a1, a2)))
if __name__ == "__main__":
absltest.main()
|
Be part of the NEW campaign!!!
THANK YOU...this is not over!
Only 15 spots left to attend one of our historic Loft Parties!
Washed Out: "Calling Out of Context"
José González: "This Is How We Walk On the Moon"
Laurel Halo: "Platform On The Ocean"
|
# SVC library - usefull Python routines and classes
# Copyright (C) 2006-2008 Jan Svec, [email protected]
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
import codecs
from svc.egg import PythonEgg
from svc.utils import issequence
from svc.ui.treedist import OrderedTree, ROOT_CONCEPT
class _ConceptLine(list):
def __init__(self, separator):
super(_ConceptLine, self).__init__()
self._separator = separator
def addSeparator(self):
self.append(self._separator)
def removeSeparator(self):
while self and self[-1] == self._separator:
del self[-1]
def flushLine(self):
self.removeSeparator()
ret = ''.join(self)
del self[:]
return OrderedTree.fromString(ret, label=ROOT_CONCEPT)
class MLF(PythonEgg, dict):
MLF_HEADER = '#!MLF!#'
@classmethod
def mapFromMLF(cls, contents):
return contents
def mapToMLF(self, value):
return value
@classmethod
def readFromFile(cls, fn):
fr = codecs.open(fn, 'r', 'utf-8')
try:
return cls.fromLines(fr)
finally:
fr.close()
@classmethod
def fromLines(cls, lines):
forest = cls()
it = iter(lines)
header = it.next().strip()
if header != cls.MLF_HEADER:
raise ValueError("Not a MLF file, bad header")
filename_line = True
for line in it:
if filename_line:
filename_line = False
filename = line.strip()[1:-1]
filename = os.path.splitext(filename)[0]
content_lines = []
continue
elif line[0] == '.':
filename_line = True
forest[filename] = cls.mapFromMLF(content_lines)
del content_lines
continue
else:
content_lines.append(line)
return forest
def writeToFile(self, fn):
fw = codecs.open(fn, 'w', 'utf-8')
try:
for line in self.toLines():
fw.write(line)
finally:
fw.close()
def toLines(self):
yield self.MLF_HEADER + '\n'
for key in sorted(self):
yield '"%s"\n' % key
value = self[key]
for line in self.mapToMLF(value):
yield line
yield '.\n'
class ConceptMLF(MLF):
@classmethod
def mapFromMLF(cls, contents):
str = ' '.join(s.strip() for s in contents)
return OrderedTree.fromString(str, label=ROOT_CONCEPT)
def mapToMLF(self, value):
return str(value)
|
Still haven't seen Mamma Mia yet? Well what are you waiting for? Now is the best time to see one of Broadway's biggest hits. The show which first premiered in London is not only a huge hit on Broadway but all around the world. In fact it's been estimated that over 30 million people have seen Mamma Mia since it first opened in 1999. Not bad for a show that nobody thought would make it in the first place.
Now I personally have never seen the show. To be honest I probably never will. It just doesn't interest me. Besides I don't think two guys from Sweden are going to lose any sleep because some ticket broker from New York doesn't want to see their little show. It really doesn't matter. Mamma Mia is here to stay. That you can count on.
|
# -*- coding: utf-8 -*-
# Copyright (C) 2009, 2015 Rocky Bernstein <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Our local modules
from trepan.processor.command import base_subcmd as Mbase_subcmd
from trepan.lib import complete as Mcomplete
import columnize
class InfoSignals(Mbase_subcmd.DebuggerSubcommand):
'''**info signals** [*signal-name*]
**info signals** \*
Show information about how debugger treats signals to the program.
Here are the boolean actions we can take:
* Stop: enter the debugger when the signal is sent to the debugged program
* Print: print that the signal was received
* Stack: show a call stack
* Pass: pass the signal onto the program
If *signal-name* is not given, we the above show information for all
signals. If '*' is given we just give a list of signals.
'''
min_abbrev = 3 # info sig
need_stack = False
short_help = 'What debugger does when program gets various signals'
def complete(self, prefix):
completions = sorted(['*'] + self.debugger.sigmgr.siglist)
return Mcomplete.complete_token(completions, prefix)
def run(self, args):
if len(args) > 0 and args[0] == '*' :
self.msg(self.columnize_commands(self.debugger.sigmgr.siglist))
else:
self.debugger.sigmgr.info_signal(['signal'] + args)
return
pass
if __name__ == '__main__':
from trepan.processor.command import mock, info as Minfo
d, cp = mock.dbg_setup()
i = Minfo.InfoCommand(cp)
sub = InfoSignals(i)
# sub.run([])
# sub.run(['*'])
pass
|
Ryan Gosling held hands with Eva Mendes at the Saturday Night Live afterparty in New York City on Saturday, September 30, where Scarlett Johansson was also spotted with cast member Colin Jost.
Mendes, 43, looked gorgeous in a patterned jumpsuit while the La La Land actor, 36, who hosted the season 43 premiere, wore a denim jacket, brown patterned sweater and blue pants.
The show’s musical guest Jay-Z, in a red velvet Berluti jacket, slayed his performances of “Bam” and “4:44,” attended the afterparty with wife Beyoncé. The “Sorry” singer, 36, showed off her fit body in a pair of black high-waisted pants and a white top, just five months after giving birth to the couple’s twins, Rumi and Sir.
Alicia Keys and husband Swiss Beatz made an appearance, while Johansson was seen with her boyfriend, “Weekend Update” host Jost. Emmy-winning SNL producer Lindsay Shookus was also spotted, sans boyfriend Ben Affleck.
Other memorable moments from the episode included the cold opener featuring Alec Baldwin, as Donald Trump, with Kate McKinnon, who played Jeff Sessions.
In one of the night’s best sketches, Gosling tried his best to make up for his first SNL appearance in 2015 — where he couldn’t hold back his laughter during an alien encounter skit — but failed terribly the second time around, thanks to McKinnon’s comedic chops. Maybe next time!
|
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.gridlayout import GridLayout
class HomeButtons(GridLayout):
def __init__(self, **kwargs):
super(HomeButtons, self).__init__(**kwargs)
self.cols = 2
self.rows = 2
btn1 = Button(text='BElGen Live Graph')
btn2 = Button(text='Lights')
btn3 = Button(text='Unused')
btn4 = Button(text='Unused')
self.add_widget(btn1)
btn1.bind(on_press = callbackgraph)
self.add_widget(btn2)
btn2.bind(on_press = callbacklights)
self.add_widget(btn3)
btn3.bind(on_press = callbackunused)
self.add_widget(btn4)
btn4.bind(on_press = callbackunused)
def callbackgraph(instance):
print('The button <%s> is being pressed' %instance.text)
def callbacklights(instance):
print('The button <%s> is being pressed' %instance.text)
def callbackunused(instance):
print('The button is <%s>' %instance.text)
class HomeUtilitiesApp(App):
def build(self):
return HomeButtons()
HomeUtilitiesApp().run()
|
At the ball that was to change her life, Rona Trafford danced with a mysterious Harlequin. She learned that this prospective suitor was being unfaithful to another, and so fled to Paris, taking up a job as a governess. Her employer's brother joined them. Unknown to her, he was concealing a dramatic secret, one that threatened to destroy them both. How they confronted danger, and how Rona learned more about the Harlequin, is told in this exciting romantic novel by BARBARA CARTLAND.
|
#!/usr/bin/env python
#coding:utf-8
"""
パーティクルフィルタでエピソード的タスクを学習させる
全体的な流れ:
while(報酬==0):
センサ値をN回取得して平均を取る
latest_sen = 平均
パーティクルを尤度関数を用いて再配置する(報酬は前回得たものを用いる)
パーティクルの投票で行動を決定する
前回の報酬、観測、行動をepisode_setに追加
while(行動終了の条件を満たさない):
一瞬だけ行動する
N回センサ値を取得して平均を取る
報酬を得る
報酬をlaetst_episodeに追加
"""
import rospy
import os
import random
import math
import sys
from raspimouse_ros.msg import LightSensorValues
from gazebo_msgs.msg import ModelStates
from geometry_msgs.msg import Twist
args = sys.argv
try:
reward_arm = args[1]
except IndexError:
print "実行時に引数として'right'または'left'を指定してください"
sys.exit()
# 変更可能なパラメータ
p = 1000 # パーティクルの数
lmd = 17 #retrospective_resettingの時、いくつのイベントを残すか
N = 10 # 何回分のセンサ値の平均を取って利用するか
fw_threshold = 5000 # 前進をやめるかどうかの判定に使われる閾値(rf+rs+ls+lf)
alpha_threshold = 0.3 # retrospective_resettingを行うかどうかの閾値。0.0だと行わない。1.0だと常に行う。
greedy_particles = 0.8 # パーティクルが尤度関数に基づいてリサンプリングされる確率
not_fit_reduce = 0.4 # つじつまが合わないエピソードの尤度に掛けて削減する。0.0から1.0
sensitivity = 600 # センサ値の差に応じて尤度を減少させるための値.\
# その他のグローバル変数
x = 0.0; y = 0.0 # ロボットの座標
rf = 0; rs = 0; ls = 0; lf = 0 # センサ値
sensors_val = [0,0,0,0] # 平均を取るためにrf,rs,ls,lfの和を入れるための変数
counter = 0 # sensors_callbackを何回実行したか
T = 1 # 最新の時間ステップ(いままで経験したエピソードの数+1)
T0 = 1
action = "" # 行動."f","r","l","s"の3種類(前進、右旋回、左旋回,待機)
moving_flag = False # ロボットが行動中かどうかのフラグ
got_average_flag = False # センサ値が平均値をとっているかどうかのフラグ
end_flag = False # 非ゼロ報酬を得たらこのフラグが立って、すべての処理を終わらせる。
particle = range(p) # パーティクルの位置、重みが入るリスト。パーティクルの重みの合計は1
for i in particle:
particle[i] = [0, 1.0/p]
latest_episode = [0.0 ,0, 0, 0, 0,""] # 最新のエピソード。報酬値、センサ値、行動。
episode_set = [] # 過去のエピソードの集合。報酬値、センサ値、行動
alpha = 0.0
###########################################################
# particle,episode_setについてファイルから読み込む #
###########################################################
if os.path.exists("./particle.txt"):
f = open("particle.txt","r")
particle = f.read()
particle = eval(particle)
f.close()
print "ファイル:particle.txtを読み込みました"
if os.path.exists("./episode_set.txt"):
f = open("episode_set.txt","r")
episode_set = f.read()
episode_set = eval(episode_set)
f.close
T = len(episode_set) + 1
T0 = len(episode_set) + 1
print "ファイル:episode_set.txtを読み込みました"
else:
f = open("result.txt","a")
f.write("---\n")
f.close()
def sensors_ave():
"""センサの平均値を求める"""
global rf;global rs;global ls;global lf
global sensors_val
global got_average_flag
sensors_val[0] += rf
sensors_val[1] += rs
sensors_val[2] += ls
sensors_val[3] += lf
if counter%N == 0:
got_average_flag = True
for i in range(4):
sensors_val[i] /= N
else:
got_average_flag = False
def reward_check(x,y):
"""
ロボットの位置に基づき、正解・不正解・行動の続行等を決定する
"""
global end_flag
global latest_episode
if reward_arm == "right":
if(x - 0.36) ** 2 + (y + 0.15) ** 2 <= 0.005:
print "###_reward_check_:ロボットは正解に到達"
f = open("result.txt","a")
f.write(reward_arm)
f.write(":O\n")
f.close()
latest_episode[0] = 1.0
end_flag = True
elif(x - 0.36) ** 2 + (y - 0.15) ** 2 <= 0.005:
print "###_reward_check_:ロボットは不正解に到達"
f = open("result.txt","a")
f.write(reward_arm)
f.write(":X\n")
f.close()
latest_episode[0] = -1.0
end_flag = True
else:
latest_episode[0] = 0.0
end_flag = False
elif reward_arm == "left":
if(x - 0.36) ** 2 + (y - 0.15) ** 2 <= 0.005:
print "###_reward_check_:ロボットは正解に到達"
f = open("result.txt","a")
f.write(reward_arm)
f.write(":O\n")
f.close()
latest_episode[0] = 1.0
end_flag = True
elif(x - 0.36) ** 2 + (y + 0.15) ** 2 <= 0.005:
print "###_reward_check_:ロボットは不正解に到達"
f = open("result.txt","a")
f.write(reward_arm)
f.write(":X\n")
f.close()
latest_episode[0] = -1.0
end_flag = True
else:
latest_episode[0] = 0.0
end_flag = False
def sensor_update(particle):
"""
パーティクルの尤度を更新し、αも求める
引数:particle
戻り値:particle,alpha
処理:
すべてのパーティクルの位置を一つづつスライドさせる
各パーティクルの重みを求める
αを求める
αを用いてパーティクルの重みを正規化する
"""
alpha = 0.0
if T != 1:
for i in range(p):
if episode_set[ particle[i][0] ][0] == latest_episode[0] and particle[i][1] != "X":
l1 = math.fabs(latest_episode[1] - episode_set[ particle[i][0] ][1])
l2 = math.fabs(latest_episode[2] - episode_set[ particle[i][0] ][2])
l3 = math.fabs(latest_episode[3] - episode_set[ particle[i][0] ][3])
l4 = math.fabs(latest_episode[4] - episode_set[ particle[i][0] ][4])
particle[i][1] = 0.5 ** ((l1+l2+l3+l4) / sensitivity)
else:
l1 = math.fabs(latest_episode[1] - episode_set[ particle[i][0] ][1])
l2 = math.fabs(latest_episode[2] - episode_set[ particle[i][0] ][2])
l3 = math.fabs(latest_episode[3] - episode_set[ particle[i][0] ][3])
l4 = math.fabs(latest_episode[4] - episode_set[ particle[i][0] ][4])
particle[i][1] = (0.5 ** ((l1+l2+l3+l4) / sensitivity)) * not_fit_reduce
elif T == 1:
for i in range(p):
particle[i][1] = 1.0/p
#alphaも求める
for i in range(p):
alpha += particle[i][1]
#alphaで正規化
if math.fabs(alpha) >= 0.0001:
for i in range(p):
particle[i][1] /= alpha
else:
for i in range(p):
particle[i][1] = 1.0/p
alpha /= p
print "alpha:",alpha
return particle,alpha
def retrospective_resetting():
"""
retrospective_resettingを行う
処理:
パーティクルを、直近のlmd個のイベント中に均等に配置する
それぞれ尤度を求め、リサンプリングする
リセッティングの結果尤度が減少した場合には取り消す。
"""
global episode_set
global particle
#print "###_リセッティングをします_###"
#print "###_resetting_###:エピソードの数:",len(episode_set),"より、",len(episode_set)-lmd,"から",len(episode_set)-1,"までの中から選ぶ"
for i in range(p):
particle[i][0] = random.randint(len(episode_set)-lmd,len(episode_set)-1)
if particle[i][0] < 0:
particle[i][0] = random.randint(0,len(episode_set)-1)
particle[i][1] = 1.0/p
def motion_update(particle):
"""
尤度に基づいてパーティクルをリサンプリングする関数
リサンプリング後のパーティクルの分布も表示する
引数:particle
戻り値:particle
"""
if T != 1: #重みに基づいてリサンプリング
likelihood = [0.0 for i in range(len(episode_set))]
for i in range(len(likelihood)):#パーティクルの尤度からエピソードの尤度(likelihood)を求める
for ii in range (p):
if particle[ii][0] == i:
likelihood[i]+= particle[ii][1]
#likelihoodの分布に基づき8割のパーティクルを配置する
for i in range(int(p * greedy_particles)):
seed = random.randint(1,100)
for ii in range(len(likelihood)):
seed -= likelihood[ii] * 100
if seed <= 0:
particle[i][0] = ii
break
#likelihoodとは無関係に残りのパーティクルを配置する
for i in range(int(p * greedy_particles),p):
seed = random.randint(0,len(episode_set)-1)
particle[i][0] = seed
#パーティクルがどこにいくつあるか表示する
particle_numbers = [0 for i in range(len(episode_set))]
for i in range(p):
particle_numbers[particle[i][0]] += 1
"""
print "===パーティクルの分布==="
cnt = 0
for i in range(len(particle_numbers)):
print particle_numbers[i],"\t",
cnt += 1
if cnt % 4 == 0:
print " "
print "T"
"""
elif T == 0:
for i in range(p):
particle[i][0] = 0
return particle
def decision_making(particle,latest_episode):
"""
投票によって行動を決定する
引数:particle,latest_episode
戻り値:action
"""
if T == 1:#まだどんなエピソードも経験していない 前進させる
return "f"
else: #各パーティクルが投票で決める
vote = range(p)#各パーティクルが自分の所属しているエピソードに対して持つ評価
for i in range(p):
vote[i] = 0.0
for i in range (p):
distance = 0 #パーティクルがいるエピソードとその直後の非ゼロ報酬が得られたエピソードとの距離
non_zero_reward = 0.0
for l in range(len(episode_set) - particle[i][0] - 1):
distance += 1
if episode_set[ particle[i][0] + distance ][0] != 0.0:
non_zero_reward = episode_set[particle[i][0] + distance][0]
break
if non_zero_reward != 0:
vote[i] = non_zero_reward / distance
else:
vote[i] = 0.0
print "センサ値:",latest_episode[1:5]
#voteに基づく行動決定。voteの合計がゼロやマイナスになる可能性がある点に注意
got = [0.0 ,0.0 ,0.0 ,0.0] #得票数が入るリスト f,r,l,sの順番
for i in range(p):
if episode_set[particle[i][0]][5] == "f":
got[0] += vote[i]
elif episode_set[particle[i][0]][5] == "r":
got[1] += vote[i]
elif episode_set[particle[i][0]][5] == "l":
got[2] += vote[i]
#print "###_decision_making_###:得票数 =",got
#前に壁がなければ投票にかかわらず前進させる
if sum(latest_episode[1:5]) < fw_threshold:
return "f"
elif got[1] == got[2]:
return random.choice("rl")
elif got[1] > got[2]:
return "r"
elif got[1] < got[2]:
return "l"
else:
print("###_decision_making_###:error")
def stop(action):
"""
閾値によってmoving_flagをオンオフする
"""
global moving_flag
if action == "f":
if sum(sensors_val) >= fw_threshold:
moving_flag = False
else:
moving_flag = True
else:
if sum(sensors_val) < fw_threshold:
moving_flag = False
else:
moving_flag = True
def slide(particle):
"""
すべてのパーティクルの位置を一つ+1する
引数:particle
戻り値:particle
"""
for i in range(p):
particle[i][0] += 1
if episode_set[ particle[i][0] -1 ][5] != latest_episode[5]:
particle[i][1] = "X" #あとで(sensor_updateのとき)ゼロになる
return particle
def sensors_callback(message):
"""
センサ値をsubscribeするコールバック関数
main
"""
vel = Twist()
vel.linear.x = 0.0
vel.angular.z = 0.0
global rf;global rs;global ls;global lf
global sensors_val
global counter
global moving_flag
global T
global action
global latest_episode
global episode_set
global particle
counter += 1
# センサデータを読み込む
rf = message.right_forward
rs = message.right_side
ls = message.left_side
lf = message.left_forward
sensors_ave() # N回分のセンサ値の平均を取る
if got_average_flag == True and moving_flag == False and end_flag == False:
print "=========================###_sensors_callback_###============================"
for i in range(4):
latest_episode[i+1] = sensors_val[i]
sensors_val[i] = 0
reward_check(x,y)
if end_flag == True:
#センサ値、行動(stay)を書き込んで色々保存して終了
print T/4," 回目のトライアルが終了しました"
print "==================================="
if (T - T0) != 3:
print "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
print "### エピソードの時間ステップが範囲外だったので取り消します ###"
print "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
f = open("result.txt","a")
f.write("↑:MISS!!\n")
f.close
sys.exit()
particle,alpha = sensor_update(particle)
if alpha < alpha_threshold and T != 1:
p_alpha = alpha
p_particle = particle
retrospective_resetting()
particle,alpha = sensor_update(particle)
if p_alpha > alpha:
#print "リセットしないほうがマシだった"
particle = p_particle
motion_update(particle)
action = "s"
latest_episode[5] = "s"
#print "###_sensors_callback_###:latest_episode=",latest_episode
episode_set.append(list(latest_episode))
particle = slide(particle)
#episode_set,particle をファイルに書き込んで終了
f = open("episode_set.txt","w")
f.write(str(episode_set))
f.close()
f = open("particle.txt","w")
f.write(str(particle))
f.close()
sys.exit()
if T % 4 != 2: #ここでズルしている
particle,alpha = sensor_update(particle)
if alpha < alpha_threshold and T != 1:
p_alpha = alpha
p_particle = particle
retrospective_resetting()
particle,alpha = sensor_update(particle)
if p_alpha > alpha:
#print "リセットしないほうがましだった"
particle = p_particle
motion_update(particle) #尤度に基づきパーティクルの分布を更新する
else:
print "2*!"
action = decision_making(particle,latest_episode) #パーティクルの投票に基づき行動を決定する
latest_episode[5] = action #最新のepisode_setにactionを追加
#print "###_sensors_callback_###:latest_episode=",latest_episode
episode_set.append(list(latest_episode))#一連のエピソードをエピソード集合に追加
if T > 1:
particle = slide(particle)
T += 1
moving_flag = True
elif got_average_flag == True and moving_flag == True:
if action == "f":
vel.linear.x = 0.2
elif action == "r":
vel.angular.z = -2.0
elif action == "l":
vel.angular.z = 2.0
stop(action)
pub.publish(vel)
def position_callback(message):
"""ロボットの現在位置をsubscribeする関数"""
global x;global y
x = message.pose[-1].position.x
y = message.pose[-1].position.y
rospy.init_node("particle_filter_on_episode")
pub = rospy.Publisher("/raspimouse/diff_drive_controller/cmd_vel",Twist,queue_size = 10)
sub1 = rospy.Subscriber("/raspimouse/lightsensors",LightSensorValues,sensors_callback)
sub2 = rospy.Subscriber("/gazebo/model_states",ModelStates,position_callback)
rospy.spin()
|
So, I have a fear that I need to overcome… Whenever I think about the upcoming Scuba course I am doing, I realise I have to go through the practice of letting water into my mask and demonstrating I can purge the water.
Thing is I knew that this was my irrational reaction to an irrational fear. I knew more than that that I really do want to dive again. So to overcome my fear I am realising, it is like learning to drive a car, ride a bike or get used to creepy crawlies… it is a mental attitude.
The fear resides in our thinking and the solution too resides in our thinking. Who is the boss of our feelings, fears or thoughts? How often do we think or say, “I can’t help feeling this way!”?
If you cannot help it, who can? If you are not in control of your mind, who is? When we think about it this way, is this not the scary bit… that we are not in control of our own minds?
Overcoming a fear could be one of the best ways to regain the reigns on our free wheeling mind and become the master of our destiny. For isn’t it said that to conquer the world you need to overcome that which scares you the most? Slowly I will retrain my mind so that I am in control and I can make it do what I want it to.
So… who is coming diving with me ‘cuz I am going to get there?
|
from rest_framework import generics, permissions, views, response,status
from .models import Account
from .serializers import AccountCreateSerializer, AccountSerializer, AuthenticateSerializer, \
UpdateAccountSerializer, AccountRetrieveSerializer
# Create your views here.
class AccountCreateView(generics.CreateAPIView):
queryset = Account.objects.all()
serializer_class = AccountCreateSerializer
permission_classes = [permissions.AllowAny]
class AccountListView(generics.ListAPIView):
queryset = Account.objects.all()
serializer_class = AccountSerializer
permission_classes = [permissions.IsAuthenticated]
class AccountRetrieveView(generics.RetrieveAPIView):
queryset = Account.objects.all()
serializer_class = AccountRetrieveSerializer
class UpdateAccountView(generics.UpdateAPIView):
queryset = Account.objects.all()
serializer_class = UpdateAccountSerializer
# permission_classes = [permissions.IsAuthenticated]
class AccountAuthenticationView(views.APIView):
queryset = Account.objects.all()
serializer_class = AuthenticateSerializer
def post(self, request):
data = request.data
serializer = AuthenticateSerializer(data=data)
if serializer.is_valid(raise_exception=True):
new_date = serializer.data
return response.Response(new_date,status=status.HTTP_200_OK)
return response.Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
|
“Mystery Shopping Group” (MSG) provides Ukrainian companies with marketing tools for assessment, monitoring and improvement of quality of customer service.
Ordering “Mystery Shopper” you will receive regular assessment of the quality of your service, and will build effective system of motivation of the personnel, and most important – turn your random customers into regular and loyal clients.
We help businesses in solving the main task — achievement of stable financial growth. From monitoring the quality of work of your employees and understanding customer insights, getting the feedback, to study of competitors we ensure sustainable development of your business.
|
from tornado.web import authenticated
from .base_handlers import BaseHandler
from qiita_ware.dispatchable import preprocessor
from qiita_db.data import RawData
from qiita_db.parameters import (PreprocessedIlluminaParams,
Preprocessed454Params)
from qiita_db.metadata_template import PrepTemplate
from qiita_ware.context import submit
class PreprocessHandler(BaseHandler):
@authenticated
def post(self):
study_id = int(self.get_argument('study_id'))
prep_template_id = int(self.get_argument('prep_template_id'))
raw_data = RawData(PrepTemplate(prep_template_id).raw_data)
param_id = int(self.get_argument('preprocessing_parameters_id'))
# Get the preprocessing parameters
if raw_data.filetype == 'FASTQ':
param_constructor = PreprocessedIlluminaParams
elif raw_data.filetype in ('FASTA', 'SFF'):
param_constructor = Preprocessed454Params
else:
raise ValueError('Unknown filetype')
job_id = submit(self.current_user.id, preprocessor, study_id,
prep_template_id, param_id, param_constructor)
self.render('compute_wait.html',
job_id=job_id, title='Preprocessing',
completion_redirect='/study/description/%d?top_tab='
'raw_data_tab&sub_tab=%s&prep_tab=%s'
% (study_id, raw_data.id,
prep_template_id))
|
Adams, MA is an excellent place to live. It’s got all of the charm and quiet of any small town, but it’s also close enough to the larger city of Henry to have some nearby fun and excitement. Unfortunately, though, Adams is neither as developed or as technologically advanced as it could be. In fact, it isn’t even its own “town” really; it’s still unincorporated and is often lumped in as an outlier of Henry. Despite those facts, many people really love living in Adams and couldn’t imagine living anywhere else; their only problem, however, is that they have a hard time finding Internet service. Most Internet providers just haven’t bothered with Adams, and the Internet service providers that have mostly offer slow, outdated, and unreliable Internet options. The one exception to that rule is HughesNet Internet, also known as HughesNet Satellite Internet. Hughesnet is a satellite Internet service provider that offers very high speed, very reliable satellite Internet to people regardless of where they live, and that extends to people in good old Adams!
People are often unsure about using satellite Internet service in Adams, usually because they don’t know as much about it as they do about older forms of Internet access, such as broadband Internet or wireless Internet. The truth is, however, that satellite internet companies, such as HughesNet in Adams, truly do offer the very best option for securing high speed Internet, especially for those living in rural areas like Adams, Massachusetts. Other options, which may or may not be available for rural Internet subscribers, just aren’t as reliable and don’t provide fast Internet the way that a satellite Internet provider can. Dial-up Internet, for example, is so outdated that many modern computers can’t even support it. Plus, dial-up requires you to have a phone line, ties that phone line up when you’re online, and is notorious for slow connections and constant disconnects, Internet options Adams, MA. Some people think that DSL is a much better option, but when you look at DSL vs. satellite Internet, you’ll see that you still need a phone line, and that if you’re not in close proximity to a central switching station, which most people in rural areas aren’t, you’re not likely to fare much better than you would with dial-up in Adams. Comparing cable vs satellite Internet is even worse, since cable connections need a strong connection to a nearby service center in order to give out good Internet signal in Adams, Massachusetts and to keep speeds from being agonizingly slow . When you grow tired of these options or when you can’t get access to them, give yourself a break by securing surprisingly cheap Internet service from the best Internet provider around, Hughesnet! HughesNet will even send satellite Internet installers to your home at your convenience to set up your service and teach you how to use it; talk about customer support in Adams, MA!
HughesNet Internet is truly the only one of the internet providers that absolutely anyone in Adams, MA can qualify for, regardless of which area of it they live in. When a person chooses to sign up for Hughesnet Satellite Internet, he or she will be able to connect to the Internet absolutely anytime, and other users in the Adams home can use the Internet service as well. See, unlike other Internet service providers and other types of Internet, satellite Internet is delivered via a satellite that sits in orbit. Because of this fact, when Hughesnet becomes your satellite Internet service provider Adams, MA, you don’t need to go through some long, complex, and difficult installation process. Instead, a small mini-dish will simply be installed somewhere on your property, and you’ll be given a modem to connect to your computer. After that, you’re good to go; it’s really that simple in Adams, MA! You can expect nothing but the very best when you choose to secure your Internet service through Hughesnet Internet. Hughesnet Satellite Internet offers the very best speeds of all Internet service providers, including download speeds of up to 12 megabits per second, allowing you to download in Adams, MAeven the largest picture, movie, and music files in much less time than you could with DSL or other Internet providers. A wide variety of customized satellite Internet packages are available from Hughesnet in Adams, MA; in fact, it’s one of the few satellite Internet service provider companies that will actually customize a package specifically to meet your needs. By keeping your best interests in mind at all times, offering great customer service and support, and striving to keep you happy, Hughesnet is easily the best Internet service provider in Adams, MA, and you should have an experience that “meets” your expectations!
|
u'''
Created on Sep 13, 2011
@author: Mark V Systems Limited
(c) Copyright 2011 Mark V Systems Limited, All rights reserved.
'''
import os
from arelle import ViewFile
from lxml import etree
from arelle.RenderingResolver import resolveAxesStructure, RENDER_UNITS_PER_CHAR
from arelle.ViewFile import HTML, XML
from arelle.ModelObject import ModelObject
from arelle.ModelFormulaObject import Aspect, aspectModels, aspectRuleAspects, aspectModelAspect, aspectStr
from arelle.FormulaEvaluator import aspectMatches
from arelle.FunctionXs import xsString
from arelle.ModelInstanceObject import ModelDimensionValue
from arelle.ModelValue import QName
from arelle.ModelXbrl import DEFAULT
from arelle.ModelRenderingObject import (ModelClosedDefinitionNode, ModelEuAxisCoord, ModelFilterDefinitionNode,
OPEN_ASPECT_ENTRY_SURROGATE)
from arelle.PrototypeInstanceObject import FactPrototype
# change tableModel for namespace needed for consistency suite
u'''
from arelle.XbrlConst import (tableModelMMDD as tableModelNamespace,
tableModelMMDDQName as tableModelQName)
'''
from arelle import XbrlConst
from arelle.XmlUtil import innerTextList, child, elementFragmentIdentifier, addQnameValue
from collections import defaultdict
emptySet = set()
emptyList = []
def viewRenderedGrid(modelXbrl, outfile, lang=None, viewTblELR=None, sourceView=None, diffToFile=False, cssExtras=u""):
modelXbrl.modelManager.showStatus(_(u"saving rendering"))
view = ViewRenderedGrid(modelXbrl, outfile, lang, cssExtras)
if sourceView is not None:
viewTblELR = sourceView.tblELR
view.ignoreDimValidity.set(sourceView.ignoreDimValidity.get())
view.xAxisChildrenFirst.set(sourceView.xAxisChildrenFirst.get())
view.yAxisChildrenFirst.set(sourceView.yAxisChildrenFirst.get())
view.view(viewTblELR)
if diffToFile:
from arelle.ValidateInfoset import validateRenderingInfoset
validateRenderingInfoset(modelXbrl, outfile, view.xmlDoc)
view.close(noWrite=True)
else:
view.close()
modelXbrl.modelManager.showStatus(_(u"rendering saved to {0}").format(outfile), clearAfter=5000)
class ViewRenderedGrid(ViewFile.View):
def __init__(self, modelXbrl, outfile, lang, cssExtras):
# find table model namespace based on table namespace
self.tableModelNamespace = XbrlConst.tableModel
for xsdNs in modelXbrl.namespaceDocs.keys():
if xsdNs in (XbrlConst.tableMMDD, XbrlConst.table, XbrlConst.table201305, XbrlConst.table201301, XbrlConst.table2011):
self.tableModelNamespace = xsdNs + u"/model"
break
super(ViewRenderedGrid, self).__init__(modelXbrl, outfile,
u'tableModel xmlns="{0}"'.format(self.tableModelNamespace),
lang,
style=u"rendering",
cssExtras=cssExtras)
class nonTkBooleanVar():
def __init__(self, value=True):
self.value = value
def set(self, value):
self.value = value
def get(self):
return self.value
# context menu boolean vars (non-tkinter boolean
self.ignoreDimValidity = nonTkBooleanVar(value=True)
self.xAxisChildrenFirst = nonTkBooleanVar(value=True)
self.yAxisChildrenFirst = nonTkBooleanVar(value=False)
def tableModelQName(self, localName):
return u'{' + self.tableModelNamespace + u'}' + localName
def viewReloadDueToMenuAction(self, *args):
self.view()
def view(self, viewTblELR=None):
if viewTblELR is not None:
tblELRs = (viewTblELR,)
else:
tblELRs = self.modelXbrl.relationshipSet(u"Table-rendering").linkRoleUris
if self.type == XML:
self.tblElt.append(etree.Comment(u"Entry point file: {0}".format(self.modelXbrl.modelDocument.basename)))
for tblELR in tblELRs:
self.zOrdinateChoices = {}
for discriminator in xrange(1, 65535):
# each table z production
tblAxisRelSet, xTopStructuralNode, yTopStructuralNode, zTopStructuralNode = resolveAxesStructure(self, tblELR)
self.hasTableFilters = bool(self.modelTable.filterRelationships)
self.zStrNodesWithChoices = []
if tblAxisRelSet and self.tblElt is not None:
tableLabel = (self.modelTable.genLabel(lang=self.lang, strip=True) or # use table label, if any
self.roledefinition)
if self.type == HTML: # table on each Z
# each Z is a separate table in the outer table
zTableRow = etree.SubElement(self.tblElt, u"{http://www.w3.org/1999/xhtml}tr")
zRowCell = etree.SubElement(zTableRow, u"{http://www.w3.org/1999/xhtml}td")
zCellTable = etree.SubElement(zRowCell, u"{http://www.w3.org/1999/xhtml}table",
attrib={u"border":u"1", u"cellspacing":u"0", u"cellpadding":u"4", u"style":u"font-size:8pt;"})
self.rowElts = [etree.SubElement(zCellTable, u"{http://www.w3.org/1999/xhtml}tr")
for r in xrange(self.dataFirstRow + self.dataRows - 1)]
etree.SubElement(self.rowElts[0], u"{http://www.w3.org/1999/xhtml}th",
attrib={u"class":u"tableHdr",
u"style":u"max-width:100em;",
u"colspan": unicode(self.dataFirstCol - 1),
u"rowspan": unicode(self.dataFirstRow - 1)}
).text = tableLabel
elif self.type == XML:
self.structuralNodeModelElements = []
if discriminator == 1:
# headers structure only build once for table
tableSetElt = etree.SubElement(self.tblElt, self.tableModelQName(u"tableSet"))
tableSetElt.append(etree.Comment(u"TableSet linkbase file: {0}, line {1}".format(self.modelTable.modelDocument.basename, self.modelTable.sourceline)))
tableSetElt.append(etree.Comment(u"TableSet namespace: {0}".format(self.modelTable.namespaceURI)))
tableSetElt.append(etree.Comment(u"TableSet linkrole: {0}".format(tblELR)))
etree.SubElement(tableSetElt, self.tableModelQName(u"label")
).text = tableLabel
zAspectStructuralNodes = defaultdict(set)
tableElt = etree.SubElement(tableSetElt, self.tableModelQName(u"table"))
self.groupElts = {}
self.headerElts = {}
self.headerCells = defaultdict(list) # order #: (breakdownNode, xml element)
for axis in (u"z", u"y", u"x"):
breakdownNodes = self.breakdownNodes.get(axis)
if breakdownNodes:
hdrsElt = etree.SubElement(tableElt, self.tableModelQName(u"headers"),
attrib={u"axis": axis})
for brkdownNode in self.breakdownNodes.get(axis):
groupElt = etree.SubElement(hdrsElt, self.tableModelQName(u"group"))
groupElt.append(etree.Comment(u"Breakdown node file: {0}, line {1}".format(brkdownNode.modelDocument.basename, brkdownNode.sourceline)))
label = brkdownNode.genLabel(lang=self.lang, strip=True)
if label:
etree.SubElement(groupElt, self.tableModelQName(u"label")).text=label
self.groupElts[brkdownNode] = groupElt
# HF TODO omit header if zero cardinality on breakdown
self.headerElts[brkdownNode] = etree.SubElement(groupElt, self.tableModelQName(u"header"))
else:
tableElt.append(etree.Comment(u"No breakdown group for \"{0}\" axis".format(axis)))
self.zAxis(1, zTopStructuralNode, zAspectStructuralNodes, True)
self.cellsParentElt = tableElt
if self.breakdownNodes.get(u"z"):
self.cellsParentElt = etree.SubElement(self.cellsParentElt, self.tableModelQName(u"cells"),
attrib={u"axis": u"z"})
if self.breakdownNodes.get(u"y"):
self.cellsParentElt = etree.SubElement(self.cellsParentElt, self.tableModelQName(u"cells"),
attrib={u"axis": u"y"})
u''' move into body cells, for entry row-by-row
self.cellsParentElt = etree.SubElement(self.cellsParentElt, self.tableModelQName("cells"),
attrib={"axis": "x"})
'''
# rows/cols only on firstTime for infoset XML, but on each time for xhtml
zAspectStructuralNodes = defaultdict(set)
self.zAxis(1, zTopStructuralNode, zAspectStructuralNodes, False)
xStructuralNodes = []
if self.type == HTML or (xTopStructuralNode and xTopStructuralNode.childStructuralNodes):
self.xAxis(self.dataFirstCol, self.colHdrTopRow, self.colHdrTopRow + self.colHdrRows - 1,
xTopStructuralNode, xStructuralNodes, self.xAxisChildrenFirst.get(), True, True)
if self.type == HTML: # table/tr goes by row
self.yAxisByRow(1, self.dataFirstRow,
yTopStructuralNode, self.yAxisChildrenFirst.get(), True, True)
elif self.type == XML: # infoset goes by col of row header
if yTopStructuralNode and yTopStructuralNode.childStructuralNodes: # no row header element if no rows
self.yAxisByCol(1, self.dataFirstRow,
yTopStructuralNode, self.yAxisChildrenFirst.get(), True, True)
# add header cells to header elements
for position, breakdownCellElts in sorted(self.headerCells.items()):
for breakdownNode, headerCell in breakdownCellElts:
self.headerElts[breakdownNode].append(headerCell)
for structuralNode,modelElt in self.structuralNodeModelElements: # must do after elements are all arragned
modelElt.addprevious(etree.Comment(u"{0}: label {1}, file {2}, line {3}"
.format(structuralNode.definitionNode.localName,
structuralNode.definitionNode.xlinkLabel,
structuralNode.definitionNode.modelDocument.basename,
structuralNode.definitionNode.sourceline)))
if structuralNode.definitionNode.get(u'value'):
modelElt.addprevious(etree.Comment(u" @value {0}".format(structuralNode.definitionNode.get(u'value'))))
for aspect in sorted(structuralNode.aspectsCovered(), key=lambda a: aspectStr(a)):
if structuralNode.hasAspect(aspect) and aspect not in (Aspect.DIMENSIONS, Aspect.OMIT_DIMENSIONS):
aspectValue = structuralNode.aspectValue(aspect)
if aspectValue is None: aspectValue = u"(bound dynamically)"
modelElt.addprevious(etree.Comment(u" aspect {0}: {1}".format(aspectStr(aspect), xsString(None,None,aspectValue))))
for varName, varValue in structuralNode.variables.items():
modelElt.addprevious(etree.Comment(u" variable ${0}: {1}".format(varName, varValue)))
for headerElt in self.headerElts.values(): # remove empty header elements
if not any(e is not None for e in headerElt.iterchildren()):
headerElt.getparent().remove(headerElt)
self.bodyCells(self.dataFirstRow, yTopStructuralNode, xStructuralNodes, zAspectStructuralNodes, self.yAxisChildrenFirst.get())
# find next choice structural node
moreDiscriminators = False
for zStrNodeWithChoices in self.zStrNodesWithChoices:
currentIndex = zStrNodeWithChoices.choiceNodeIndex + 1
if currentIndex < len(zStrNodeWithChoices.choiceStructuralNodes):
zStrNodeWithChoices.choiceNodeIndex = currentIndex
self.zOrdinateChoices[zStrNodeWithChoices.definitionNode] = currentIndex
moreDiscriminators = True
break
else:
zStrNodeWithChoices.choiceNodeIndex = 0
self.zOrdinateChoices[zStrNodeWithChoices.definitionNode] = 0
# continue incrementing next outermore z choices index
if not moreDiscriminators:
break
def zAxis(self, row, zStructuralNode, zAspectStructuralNodes, discriminatorsTable):
if zStructuralNode is not None:
label = zStructuralNode.header(lang=self.lang)
choiceLabel = None
effectiveStructuralNode = zStructuralNode
if zStructuralNode.choiceStructuralNodes: # same as combo box selection in GUI mode
if not discriminatorsTable:
self.zStrNodesWithChoices.insert(0, zStructuralNode) # iteration from last is first
try:
effectiveStructuralNode = zStructuralNode.choiceStructuralNodes[zStructuralNode.choiceNodeIndex]
choiceLabel = effectiveStructuralNode.header(lang=self.lang)
if not label and choiceLabel:
label = choiceLabel # no header for choice
choiceLabel = None
except KeyError:
pass
if choiceLabel:
if self.dataCols > 3:
zLabelSpan = 2
else:
zLabelSpan = 1
zChoiceLabelSpan = self.dataCols - zLabelSpan
else:
zLabelSpan = self.dataCols
if self.type == HTML:
etree.SubElement(self.rowElts[row-1], u"{http://www.w3.org/1999/xhtml}th",
attrib={u"class":u"zAxisHdr",
u"style":u"max-width:200pt;text-align:left;border-bottom:.5pt solid windowtext",
u"colspan": unicode(zLabelSpan)} # "2"}
).text = label
if choiceLabel:
etree.SubElement(self.rowElts[row-1], u"{http://www.w3.org/1999/xhtml}th",
attrib={u"class":u"zAxisHdr",
u"style":u"max-width:200pt;text-align:left;border-bottom:.5pt solid windowtext",
u"colspan": unicode(zChoiceLabelSpan)} # "2"}
).text = choiceLabel
elif self.type == XML:
# headers element built for first pass on z axis
if discriminatorsTable:
brkdownNode = zStructuralNode.breakdownNode
if zStructuralNode.choiceStructuralNodes: # same as combo box selection in GUI mode
# hdrElt.set("label", label)
if discriminatorsTable:
def zSpan(zNode, startNode=False):
if startNode:
thisSpan = 0
elif zStructuralNode.choiceStructuralNodes:
thisSpan = len(zStructuralNode.choiceStructuralNodes)
else:
thisSpan = 1
return sum(zSpan(z) for z in zNode.childStructuralNodes) + thisSpan
span = zSpan(zStructuralNode, True)
for i, choiceStructuralNode in enumerate(zStructuralNode.choiceStructuralNodes):
choiceLabel = choiceStructuralNode.header(lang=self.lang)
cellElt = etree.Element(self.tableModelQName(u"cell"),
attrib={u"span": unicode(span)} if span > 1 else None)
self.headerCells[i].append((brkdownNode, cellElt))
# self.structuralNodeModelElements.append((zStructuralNode, cellElt))
elt = etree.SubElement(cellElt, self.tableModelQName(u"label"))
if choiceLabel:
elt.text = choiceLabel
#else: # choiceLabel from above
# etree.SubElement(hdrElt, self.tableModelQName("label")
# ).text = choiceLabel
else: # no combo choices, single label
cellElt = etree.Element(self.tableModelQName(u"cell"))
self.headerCells[0].append((brkdownNode, cellElt))
# self.structuralNodeModelElements.append((zStructuralNode, cellElt))
elt = etree.SubElement(cellElt, self.tableModelQName(u"label"))
if label:
elt.text = label
for aspect in aspectModels[self.aspectModel]:
if effectiveStructuralNode.hasAspect(aspect, inherit=True): #implies inheriting from other z axes
if aspect == Aspect.DIMENSIONS:
for dim in (effectiveStructuralNode.aspectValue(Aspect.DIMENSIONS, inherit=True) or emptyList):
zAspectStructuralNodes[dim].add(effectiveStructuralNode)
else:
zAspectStructuralNodes[aspect].add(effectiveStructuralNode)
for zStructuralNode in zStructuralNode.childStructuralNodes:
self.zAxis(row + 1, zStructuralNode, zAspectStructuralNodes, discriminatorsTable)
def xAxis(self, leftCol, topRow, rowBelow, xParentStructuralNode, xStructuralNodes, childrenFirst, renderNow, atTop):
if xParentStructuralNode is not None:
parentRow = rowBelow
noDescendants = True
rightCol = leftCol
widthToSpanParent = 0
sideBorder = not xStructuralNodes
for xStructuralNode in xParentStructuralNode.childStructuralNodes:
noDescendants = False
rightCol, row, width, leafNode = self.xAxis(leftCol, topRow + 1, rowBelow, xStructuralNode, xStructuralNodes, # nested items before totals
childrenFirst, childrenFirst, False)
if row - 1 < parentRow:
parentRow = row - 1
#if not leafNode:
# rightCol -= 1
nonAbstract = not xStructuralNode.isAbstract
if nonAbstract:
width += 100 # width for this label
widthToSpanParent += width
if childrenFirst:
thisCol = rightCol
else:
thisCol = leftCol
#print ( "thisCol {0} leftCol {1} rightCol {2} topRow{3} renderNow {4} label {5}".format(thisCol, leftCol, rightCol, topRow, renderNow, label))
if renderNow:
label = xStructuralNode.header(lang=self.lang,
returnGenLabel=isinstance(xStructuralNode.definitionNode, (ModelClosedDefinitionNode, ModelEuAxisCoord)))
columnspan = rightCol - leftCol
if columnspan > 0 and nonAbstract: columnspan += 1
elt = None
if self.type == HTML:
if rightCol == self.dataFirstCol + self.dataCols - 1:
edgeBorder = u"border-right:.5pt solid windowtext;"
else:
edgeBorder = u""
attrib = {u"class":u"xAxisHdr",
u"style":u"text-align:center;max-width:{0}pt;{1}".format(width,edgeBorder)}
if columnspan > 1:
attrib[u"colspan"] = unicode(columnspan)
if leafNode and row > topRow:
attrib[u"rowspan"] = unicode(row - topRow + 1)
elt = etree.Element(u"{http://www.w3.org/1999/xhtml}th",
attrib=attrib)
self.rowElts[topRow-1].insert(leftCol,elt)
elif (self.type == XML and # is leaf or no sub-breakdown cardinality
(xStructuralNode.childStructuralNodes is None or columnspan > 0)): # ignore no-breakdown situation
brkdownNode = xStructuralNode.breakdownNode
cellElt = etree.Element(self.tableModelQName(u"cell"),
attrib={u"span": unicode(columnspan)} if columnspan > 1 else None)
self.headerCells[thisCol].append((brkdownNode, cellElt))
# self.structuralNodeModelElements.append((xStructuralNode, cellElt))
elt = etree.SubElement(cellElt, self.tableModelQName(u"label"))
if nonAbstract or (leafNode and row > topRow):
for rollUpCol in xrange(topRow - self.colHdrTopRow + 1, self.colHdrRows - 1):
rollUpElt = etree.Element(self.tableModelQName(u"cell"),
attrib={u"rollup":u"true"})
self.headerCells[thisCol].append((brkdownNode, cellElt))
for i, role in enumerate(self.colHdrNonStdRoles):
roleLabel = xStructuralNode.header(role=role, lang=self.lang, recurseParent=False) # infoset does not move parent label to decscndant
if roleLabel is not None:
cellElt.append(etree.Comment(u"Label role: {0}, lang {1}"
.format(os.path.basename(role), self.lang)))
labelElt = etree.SubElement(cellElt, self.tableModelQName(u"label"),
#attrib={"role": role,
# "lang": self.lang}
)
labelElt.text = roleLabel
for aspect in sorted(xStructuralNode.aspectsCovered(), key=lambda a: aspectStr(a)):
if xStructuralNode.hasAspect(aspect) and aspect not in (Aspect.DIMENSIONS, Aspect.OMIT_DIMENSIONS):
aspectValue = xStructuralNode.aspectValue(aspect)
if aspectValue is None: aspectValue = u"(bound dynamically)"
if isinstance(aspectValue, ModelObject): # typed dimension value
aspectValue = innerTextList(aspectValue)
aspElt = etree.SubElement(cellElt, self.tableModelQName(u"constraint"))
etree.SubElement(aspElt, self.tableModelQName(u"aspect")
).text = aspectStr(aspect)
etree.SubElement(aspElt, self.tableModelQName(u"value")
).text = xsString(None,None,addQnameValue(self.xmlDoc, aspectValue))
if elt is not None:
elt.text = label if bool(label) and label != OPEN_ASPECT_ENTRY_SURROGATE else u"\u00A0" #produces
if nonAbstract:
if columnspan > 1 and rowBelow > topRow: # add spanned left leg portion one row down
if self.type == HTML:
attrib= {u"class":u"xAxisSpanLeg",
u"rowspan": unicode(rowBelow - row)}
if edgeBorder:
attrib[u"style"] = edgeBorder
elt = etree.Element(u"{http://www.w3.org/1999/xhtml}th",
attrib=attrib)
elt.text = u"\u00A0"
if childrenFirst:
self.rowElts[topRow].append(elt)
else:
self.rowElts[topRow].insert(leftCol,elt)
if self.type == HTML:
for i, role in enumerate(self.colHdrNonStdRoles):
elt = etree.Element(u"{http://www.w3.org/1999/xhtml}th",
attrib={u"class":u"xAxisHdr",
u"style":u"text-align:center;max-width:100pt;{0}".format(edgeBorder)})
self.rowElts[self.dataFirstRow - 1 - len(self.colHdrNonStdRoles) + i].insert(thisCol,elt)
elt.text = xStructuralNode.header(role=role, lang=self.lang) or u"\u00A0"
u'''
if self.colHdrDocRow:
doc = xStructuralNode.header(role="http://www.xbrl.org/2008/role/documentation", lang=self.lang)
if self.type == HTML:
elt = etree.Element("{http://www.w3.org/1999/xhtml}th",
attrib={"class":"xAxisHdr",
"style":"text-align:center;max-width:100pt;{0}".format(edgeBorder)})
self.rowElts[self.dataFirstRow - 2 - self.rowHdrCodeCol].insert(thisCol,elt)
elif self.type == XML:
elt = etree.Element(self.tableModelQName("label"))
self.colHdrElts[self.colHdrRows - 1].insert(thisCol,elt)
elt.text = doc or "\u00A0"
if self.colHdrCodeRow:
code = xStructuralNode.header(role="http://www.eurofiling.info/role/2010/coordinate-code")
if self.type == HTML:
elt = etree.Element("{http://www.w3.org/1999/xhtml}th",
attrib={"class":"xAxisHdr",
"style":"text-align:center;max-width:100pt;{0}".format(edgeBorder)})
self.rowElts[self.dataFirstRow - 2].insert(thisCol,elt)
elif self.type == XML:
elt = etree.Element(self.tableModelQName("label"))
self.colHdrElts[self.colHdrRows - 1 + self.colHdrDocRow].insert(thisCol,elt)
elt.text = code or "\u00A0"
'''
xStructuralNodes.append(xStructuralNode)
if nonAbstract:
rightCol += 1
if renderNow and not childrenFirst:
self.xAxis(leftCol + (1 if nonAbstract else 0), topRow + 1, rowBelow, xStructuralNode, xStructuralNodes, childrenFirst, True, False) # render on this pass
leftCol = rightCol
return (rightCol, parentRow, widthToSpanParent, noDescendants)
def yAxisByRow(self, leftCol, row, yParentStructuralNode, childrenFirst, renderNow, atLeft):
if yParentStructuralNode is not None:
nestedBottomRow = row
for yStructuralNode in yParentStructuralNode.childStructuralNodes:
nestRow, nextRow = self.yAxisByRow(leftCol + 1, row, yStructuralNode, # nested items before totals
childrenFirst, childrenFirst, False)
isAbstract = (yStructuralNode.isAbstract or
(yStructuralNode.childStructuralNodes and
not isinstance(yStructuralNode.definitionNode, (ModelClosedDefinitionNode, ModelEuAxisCoord))))
isNonAbstract = not isAbstract
isLabeled = yStructuralNode.isLabeled
topRow = row
#print ( "row {0} topRow {1} nxtRow {2} col {3} renderNow {4} label {5}".format(row, topRow, nextRow, leftCol, renderNow, label))
if renderNow and isLabeled:
label = yStructuralNode.header(lang=self.lang,
returnGenLabel=isinstance(yStructuralNode.definitionNode, ModelClosedDefinitionNode),
recurseParent=not isinstance(yStructuralNode.definitionNode, ModelFilterDefinitionNode))
columnspan = self.rowHdrCols - leftCol + 1 if isNonAbstract or nextRow == row else 1
if childrenFirst and isNonAbstract and nextRow > row:
elt = etree.Element(u"{http://www.w3.org/1999/xhtml}th",
attrib={u"class":u"yAxisSpanArm",
u"style":u"text-align:center;min-width:2em;",
u"rowspan": unicode(nextRow - topRow)}
)
insertPosition = self.rowElts[nextRow-1].__len__()
self.rowElts[row - 1].insert(insertPosition, elt)
elt.text = u"\u00A0"
hdrRow = nextRow # put nested stuff on bottom row
row = nextRow # nested header still goes on this row
else:
hdrRow = row
# provide top or bottom borders
edgeBorder = u""
if childrenFirst:
if hdrRow == self.dataFirstRow:
edgeBorder = u"border-top:.5pt solid windowtext;"
else:
if hdrRow == len(self.rowElts):
edgeBorder = u"border-bottom:.5pt solid windowtext;"
depth = yStructuralNode.depth
attrib = {u"style":u"text-align:{0};max-width:{1}em;{2}".format(
u"left" if isNonAbstract or nestRow == hdrRow else u"center",
# this is a wrap length max width in characters
self.rowHdrColWidth[depth] if isAbstract else
self.rowHdrWrapLength - sum(self.rowHdrColWidth[0:depth]),
edgeBorder),
u"colspan": unicode(columnspan)}
if label == OPEN_ASPECT_ENTRY_SURROGATE: # entry of dimension
attrib[u"style"] += u";background:#fff" # override for white background
if isAbstract:
attrib[u"rowspan"] = unicode(nestRow - hdrRow)
attrib[u"class"] = u"yAxisHdrAbstractChildrenFirst" if childrenFirst else u"yAxisHdrAbstract"
elif nestRow > hdrRow:
attrib[u"class"] = u"yAxisHdrWithLeg"
elif childrenFirst:
attrib[u"class"] = u"yAxisHdrWithChildrenFirst"
else:
attrib[u"class"] = u"yAxisHdr"
elt = etree.Element(u"{http://www.w3.org/1999/xhtml}th",
attrib=attrib
)
elt.text = label if bool(label) and label != OPEN_ASPECT_ENTRY_SURROGATE else u"\u00A0"
if isNonAbstract:
self.rowElts[hdrRow-1].append(elt)
if not childrenFirst and nestRow > hdrRow: # add spanned left leg portion one row down
etree.SubElement(self.rowElts[hdrRow],
u"{http://www.w3.org/1999/xhtml}th",
attrib={u"class":u"yAxisSpanLeg",
u"style":u"text-align:center;max-width:{0}pt;{1}".format(RENDER_UNITS_PER_CHAR, edgeBorder),
u"rowspan": unicode(nestRow - hdrRow)}
).text = u"\u00A0"
hdrClass = u"yAxisHdr" if not childrenFirst else u"yAxisHdrWithChildrenFirst"
for i, role in enumerate(self.rowHdrNonStdRoles):
hdr = yStructuralNode.header(role=role, lang=self.lang)
etree.SubElement(self.rowElts[hdrRow - 1],
u"{http://www.w3.org/1999/xhtml}th",
attrib={u"class":hdrClass,
u"style":u"text-align:left;max-width:100pt;{0}".format(edgeBorder)}
).text = hdr or u"\u00A0"
u'''
if self.rowHdrDocCol:
docCol = self.dataFirstCol - 1 - self.rowHdrCodeCol
doc = yStructuralNode.header(role="http://www.xbrl.org/2008/role/documentation")
etree.SubElement(self.rowElts[hdrRow - 1],
"{http://www.w3.org/1999/xhtml}th",
attrib={"class":hdrClass,
"style":"text-align:left;max-width:100pt;{0}".format(edgeBorder)}
).text = doc or "\u00A0"
if self.rowHdrCodeCol:
codeCol = self.dataFirstCol - 1
code = yStructuralNode.header(role="http://www.eurofiling.info/role/2010/coordinate-code")
etree.SubElement(self.rowElts[hdrRow - 1],
"{http://www.w3.org/1999/xhtml}th",
attrib={"class":hdrClass,
"style":"text-align:center;max-width:40pt;{0}".format(edgeBorder)}
).text = code or "\u00A0"
# gridBorder(self.gridRowHdr, leftCol, self.dataFirstRow - 1, BOTTOMBORDER)
'''
else:
self.rowElts[hdrRow-1].insert(leftCol - 1, elt)
if isNonAbstract:
row += 1
elif childrenFirst:
row = nextRow
if nestRow > nestedBottomRow:
nestedBottomRow = nestRow + (isNonAbstract and not childrenFirst)
if row > nestedBottomRow:
nestedBottomRow = row
#if renderNow and not childrenFirst:
# dummy, row = self.yAxis(leftCol + 1, row, yAxisHdrObj, childrenFirst, True, False) # render on this pass
if not childrenFirst:
dummy, row = self.yAxisByRow(leftCol + 1, row, yStructuralNode, childrenFirst, renderNow, False) # render on this pass
return (nestedBottomRow, row)
def yAxisByCol(self, leftCol, row, yParentStructuralNode, childrenFirst, renderNow, atTop):
if yParentStructuralNode is not None:
nestedBottomRow = row
for yStructuralNode in yParentStructuralNode.childStructuralNodes:
nestRow, nextRow = self.yAxisByCol(leftCol + 1, row, yStructuralNode, # nested items before totals
childrenFirst, childrenFirst, False)
isAbstract = (yStructuralNode.isAbstract or
(yStructuralNode.childStructuralNodes and
not isinstance(yStructuralNode.definitionNode, (ModelClosedDefinitionNode, ModelEuAxisCoord))))
isNonAbstract = not isAbstract
isLabeled = yStructuralNode.isLabeled
topRow = row
if childrenFirst and isNonAbstract:
row = nextRow
#print ( "thisCol {0} leftCol {1} rightCol {2} topRow{3} renderNow {4} label {5}".format(thisCol, leftCol, rightCol, topRow, renderNow, label))
if renderNow and isLabeled:
label = yStructuralNode.header(lang=self.lang,
returnGenLabel=isinstance(yStructuralNode.definitionNode, (ModelClosedDefinitionNode, ModelEuAxisCoord)),
recurseParent=not isinstance(yStructuralNode.definitionNode, ModelFilterDefinitionNode))
brkdownNode = yStructuralNode.breakdownNode
rowspan= nestRow - row + 1
cellElt = etree.Element(self.tableModelQName(u"cell"),
attrib={u"span": unicode(rowspan)} if rowspan > 1 else None)
elt = etree.SubElement(cellElt, self.tableModelQName(u"label"))
elt.text = label if label != OPEN_ASPECT_ENTRY_SURROGATE else u""
self.headerCells[leftCol].append((brkdownNode, cellElt))
# self.structuralNodeModelElements.append((yStructuralNode, cellElt))
for rollUpCol in xrange(leftCol, self.rowHdrCols - 1):
rollUpElt = etree.Element(self.tableModelQName(u"cell"),
attrib={u"rollup":u"true"})
self.headerCells[leftCol].append((brkdownNode, rollUpElt))
#if isNonAbstract:
i = -1 # for case where no enumeration takes place
for i, role in enumerate(self.rowHdrNonStdRoles):
roleLabel = yStructuralNode.header(role=role, lang=self.lang, recurseParent=False)
if roleLabel is not None:
cellElt.append(etree.Comment(u"Label role: {0}, lang {1}"
.format(os.path.basename(role), self.lang)))
labelElt = etree.SubElement(cellElt, self.tableModelQName(u"label"),
#attrib={"role":role,
# "lang":self.lang}
).text = roleLabel
self.headerCells[leftCol].append((brkdownNode, cellElt))
for aspect in sorted(yStructuralNode.aspectsCovered(), key=lambda a: aspectStr(a)):
if yStructuralNode.hasAspect(aspect) and aspect not in (Aspect.DIMENSIONS, Aspect.OMIT_DIMENSIONS):
aspectValue = yStructuralNode.aspectValue(aspect)
if aspectValue is None: aspectValue = u"(bound dynamically)"
if isinstance(aspectValue, ModelObject): # typed dimension value
aspectValue = innerTextList(aspectValue)
if isinstance(aspectValue, unicode) and aspectValue.startswith(OPEN_ASPECT_ENTRY_SURROGATE):
continue # not an aspect, position for a new entry
elt = etree.SubElement(cellElt, self.tableModelQName(u"constraint"))
etree.SubElement(elt, self.tableModelQName(u"aspect")
).text = aspectStr(aspect)
etree.SubElement(elt, self.tableModelQName(u"value")
).text = xsString(None,None,addQnameValue(self.xmlDoc, aspectValue))
u'''
if self.rowHdrDocCol:
labelElt = etree.SubElement(cellElt, self.tableModelQName("label"),
attrib={"span": str(rowspan)} if rowspan > 1 else None)
elt.text = yStructuralNode.header(role="http://www.xbrl.org/2008/role/documentation",
lang=self.lang)
self.rowHdrElts[self.rowHdrCols - 1].append(elt)
if self.rowHdrCodeCol:
elt = etree.Element(self.tableModelQName("label"),
attrib={"span": str(rowspan)} if rowspan > 1 else None)
elt.text = yStructuralNode.header(role="http://www.eurofiling.info/role/2010/coordinate-code",
lang=self.lang)
self.rowHdrElts[self.rowHdrCols - 1 + self.rowHdrDocCol].append(elt)
'''
if isNonAbstract:
row += 1
elif childrenFirst:
row = nextRow
if nestRow > nestedBottomRow:
nestedBottomRow = nestRow + (isNonAbstract and not childrenFirst)
if row > nestedBottomRow:
nestedBottomRow = row
#if renderNow and not childrenFirst:
# dummy, row = self.yAxis(leftCol + 1, row, yStructuralNode, childrenFirst, True, False) # render on this pass
if not childrenFirst:
dummy, row = self.yAxisByCol(leftCol + 1, row, yStructuralNode, childrenFirst, renderNow, False) # render on this pass
return (nestedBottomRow, row)
def bodyCells(self, row, yParentStructuralNode, xStructuralNodes, zAspectStructuralNodes, yChildrenFirst):
if yParentStructuralNode is not None:
dimDefaults = self.modelXbrl.qnameDimensionDefaults
for yStructuralNode in yParentStructuralNode.childStructuralNodes:
if yChildrenFirst:
row = self.bodyCells(row, yStructuralNode, xStructuralNodes, zAspectStructuralNodes, yChildrenFirst)
if not (yStructuralNode.isAbstract or
(yStructuralNode.childStructuralNodes and
not isinstance(yStructuralNode.definitionNode, (ModelClosedDefinitionNode, ModelEuAxisCoord)))) and yStructuralNode.isLabeled:
if self.type == XML:
if self.breakdownNodes.get(u"x"):
cellsParentElt = etree.SubElement(self.cellsParentElt, self.tableModelQName(u"cells"),
attrib={u"axis": u"x"})
else:
cellsParentElt = self.cellsParentElt
isEntryPrototype = yStructuralNode.isEntryPrototype(default=False) # row to enter open aspects
yAspectStructuralNodes = defaultdict(set)
for aspect in aspectModels[self.aspectModel]:
if yStructuralNode.hasAspect(aspect):
if aspect == Aspect.DIMENSIONS:
for dim in (yStructuralNode.aspectValue(Aspect.DIMENSIONS) or emptyList):
yAspectStructuralNodes[dim].add(yStructuralNode)
else:
yAspectStructuralNodes[aspect].add(yStructuralNode)
yTagSelectors = yStructuralNode.tagSelectors
# data for columns of rows
ignoreDimValidity = self.ignoreDimValidity.get()
for i, xStructuralNode in enumerate(xStructuralNodes):
xAspectStructuralNodes = defaultdict(set)
for aspect in aspectModels[self.aspectModel]:
if xStructuralNode.hasAspect(aspect):
if aspect == Aspect.DIMENSIONS:
for dim in (xStructuralNode.aspectValue(Aspect.DIMENSIONS) or emptyList):
xAspectStructuralNodes[dim].add(xStructuralNode)
else:
xAspectStructuralNodes[aspect].add(xStructuralNode)
cellTagSelectors = yTagSelectors | xStructuralNode.tagSelectors
cellAspectValues = {}
matchableAspects = set()
for aspect in _DICT_SET(xAspectStructuralNodes.keys()) | _DICT_SET(yAspectStructuralNodes.keys()) | _DICT_SET(zAspectStructuralNodes.keys()):
aspectValue = xStructuralNode.inheritedAspectValue(yStructuralNode,
self, aspect, cellTagSelectors,
xAspectStructuralNodes, yAspectStructuralNodes, zAspectStructuralNodes)
# value is None for a dimension whose value is to be not reported in this slice
if (isinstance(aspect, _INT) or # not a dimension
dimDefaults.get(aspect) != aspectValue or # explicit dim defaulted will equal the value
aspectValue is not None): # typed dim absent will be none
cellAspectValues[aspect] = aspectValue
matchableAspects.add(aspectModelAspect.get(aspect,aspect)) #filterable aspect from rule aspect
cellDefaultedDims = _DICT_SET(dimDefaults) - _DICT_SET(cellAspectValues.keys())
priItemQname = cellAspectValues.get(Aspect.CONCEPT)
concept = self.modelXbrl.qnameConcepts.get(priItemQname)
conceptNotAbstract = concept is None or not concept.isAbstract
from arelle.ValidateXbrlDimensions import isFactDimensionallyValid
fact = None
value = None
objectId = None
justify = None
fp = FactPrototype(self, cellAspectValues)
if conceptNotAbstract:
# reduce set of matchable facts to those with pri item qname and have dimension aspects
facts = self.modelXbrl.factsByQname[priItemQname] if priItemQname else self.modelXbrl.factsInInstance
if self.hasTableFilters:
facts = self.modelTable.filterFacts(self.rendrCntx, facts)
for aspect in matchableAspects: # trim down facts with explicit dimensions match or just present
if isinstance(aspect, QName):
aspectValue = cellAspectValues.get(aspect, None)
if isinstance(aspectValue, ModelDimensionValue):
if aspectValue.isExplicit:
dimMemQname = aspectValue.memberQname # match facts with this explicit value
else:
dimMemQname = None # match facts that report this dimension
elif isinstance(aspectValue, QName):
dimMemQname = aspectValue # match facts that have this explicit value
elif aspectValue is None: # match typed dims that don't report this value
dimMemQname = DEFAULT
else:
dimMemQname = None # match facts that report this dimension
facts = facts & self.modelXbrl.factsByDimMemQname(aspect, dimMemQname)
for fact in facts:
if (all(aspectMatches(self.rendrCntx, fact, fp, aspect)
for aspect in matchableAspects) and
all(fact.context.dimMemberQname(dim,includeDefaults=True) in (dimDefaults[dim], None)
for dim in cellDefaultedDims)):
if yStructuralNode.hasValueExpression(xStructuralNode):
value = yStructuralNode.evalValueExpression(fact, xStructuralNode)
else:
value = fact.effectiveValue
justify = u"right" if fact.isNumeric else u"left"
break
if justify is None:
justify = u"right" if fp.isNumeric else u"left"
if conceptNotAbstract:
if self.type == XML:
cellsParentElt.append(etree.Comment(u"Cell concept {0}: segDims {1}, scenDims {2}"
.format(fp.qname,
u', '.join(u"({}={})".format(dimVal.dimensionQname, dimVal.memberQname)
for dimVal in sorted(fp.context.segDimVals.values(), key=lambda d: d.dimensionQname)),
u', '.join(u"({}={})".format(dimVal.dimensionQname, dimVal.memberQname)
for dimVal in sorted(fp.context.scenDimVals.values(), key=lambda d: d.dimensionQname)),
)))
if value is not None or ignoreDimValidity or isFactDimensionallyValid(self, fp) or isEntryPrototype:
if self.type == HTML:
etree.SubElement(self.rowElts[row - 1],
u"{http://www.w3.org/1999/xhtml}td",
attrib={u"class":u"cell",
u"style":u"text-align:{0};width:8em".format(justify)}
).text = value or u"\u00A0"
elif self.type == XML:
if value is not None and fact is not None:
cellsParentElt.append(etree.Comment(u"{0}: context {1}, value {2}, file {3}, line {4}"
.format(fact.qname,
fact.contextID,
value[:32], # no more than 32 characters
fact.modelDocument.basename,
fact.sourceline)))
elif fact is not None:
cellsParentElt.append(etree.Comment(u"Fact was not matched {0}: context {1}, value {2}, file {3}, line {4}, aspects not matched: {5}, dimensions expected to have been defaulted: {6}"
.format(fact.qname,
fact.contextID,
fact.effectiveValue[:32],
fact.modelDocument.basename,
fact.sourceline,
u', '.join(unicode(aspect)
for aspect in matchableAspects
if not aspectMatches(self.rendrCntx, fact, fp, aspect)),
u', '.join(unicode(dim)
for dim in cellDefaultedDims
if fact.context.dimMemberQname(dim,includeDefaults=True) not in (dimDefaults[dim], None))
)))
cellElt = etree.SubElement(cellsParentElt, self.tableModelQName(u"cell"))
if value is not None and fact is not None:
etree.SubElement(cellElt, self.tableModelQName(u"fact")
).text = u'{}#{}'.format(fact.modelDocument.basename,
elementFragmentIdentifier(fact))
else:
if self.type == HTML:
etree.SubElement(self.rowElts[row - 1],
u"{http://www.w3.org/1999/xhtml}td",
attrib={u"class":u"blockedCell",
u"style":u"text-align:{0};width:8em".format(justify)}
).text = u"\u00A0\u00A0"
elif self.type == XML:
etree.SubElement(cellsParentElt, self.tableModelQName(u"cell"),
attrib={u"blocked":u"true"})
else: # concept is abstract
if self.type == HTML:
etree.SubElement(self.rowElts[row - 1],
u"{http://www.w3.org/1999/xhtml}td",
attrib={u"class":u"abstractCell",
u"style":u"text-align:{0};width:8em".format(justify)}
).text = u"\u00A0\u00A0"
elif self.type == XML:
etree.SubElement(cellsParentElt, self.tableModelQName(u"cell"),
attrib={u"abstract":u"true"})
fp.clear() # dereference
row += 1
if not yChildrenFirst:
row = self.bodyCells(row, yStructuralNode, xStructuralNodes, zAspectStructuralNodes, yChildrenFirst)
return row
|
"Before you entered my life, I was not fully me."
I walked into your classroom frustrated. I felt as though no good could come from this situation. I was nine years old and had just been diagnosed with a visual-spatial learning disability, one that required me to leave my previous school and enter yours.
I was mad at my parents for taking me away from my friends, at myself for not understanding, and at you for placing me in a class of only five students. Your room was full of beanbags, computers and games, and yet I longed for the normalcy of crowded spaces and rows of desks.
When I came to you, I was in third grade and couldn't read or write. I was unmotivated and in a constant state of distress when it came to schooling. I had come from a private school that could not teach me in a way that worked for me. I was transferred to your public school, one known for its special-education programs.
I hated being different and feeling like I was stupid and less worthy than other students. I was embarrassed when you would take me from my regular classroom and bring me to yours for the day, indicating my "special status." You could tell I was upset and you took me under your wing. You started where I was and provided me the tools to move on.
It took two months to respect you, a year to understand you, two years to learn my own ability, and three years to move past your safe space. You broke those years into moments and got me excited about learning. You not only taught me what I needed to move past my disability, but you supported me in all that I did outside of it. You attended my theater performances, built a relationship with my parents, and helped me advocate for myself.
A girl who once had to be bribed to read, forced to write, and was unsure in her abilities was transformed. You showed me that we each learn differently, and that success would arrive with hard work.
I have not seen you since my youth, but I still think about you. I ponder what my life would have been like if I had never met you. I think of how unhappy and jumbled I was before I entered your classroom. I would love to cross paths with you now and show you all I have accomplished because of you.
Now, I intern in an elementary school filled with children who face the same kinds of uncertainty that I faced all those years ago. I work one-on-one with these children as you worked one-on-one with me. When I see a child who is struggling, I think back to the tools that you gave me. When I see a child in need of support, I advocate for her like you taught me. I hope I am touching the lives of these children the way you touched mine.
Before you entered my life, I was not fully me. So, thank you, thank you for giving me dreams and aspirations, and most of all, thank you for giving me the tools to give back to others what you gave to me.
This story is from Chicken Soup for the Soul: Inspiration for Teachers: 101 Stories about How You Make a Difference © 2017 Chicken Soup for the Soul, LLC. All rights reserved.
The pair had a discussion on Kimmel's show.
"It’s deceivingly simple and quite nuanced: a message about our body conveyed by Dove bottles themselves."
|
#!/usr/bin/env python
import time
import sys
import logging
from socketIO_client import SocketIO
APPKEY = '56a0a88c4407a3cd028ac2fe'
TOPIC = 'test'
ALIAS = 'test'
logger = logging.getLogger('messenger')
class Messenger:
def __init__(self, appkey, alias, customid):
self.__logger = logging.getLogger('messenger.Messenger')
self.__logger.info('init')
self.appkey = appkey
self.customid = customid
self.alias = alias
self.socketIO = SocketIO('182.92.1.46', 3000)
self.socketIO.on('socketconnectack', self.on_socket_connect_ack)
self.socketIO.on('connack', self.on_connack)
self.socketIO.on('puback', self.on_puback)
self.socketIO.on('suback', self.on_suback)
self.socketIO.on('message', self.on_message)
self.socketIO.on('set_alias_ack', self.on_set_alias)
self.socketIO.on('get_topic_list_ack', self.on_get_topic_list_ack)
self.socketIO.on('get_alias_list_ack', self.on_get_alias_list_ack)
# self.socketIO.on('puback', self.on_publish2_ack)
self.socketIO.on('recvack', self.on_publish2_recvack)
self.socketIO.on('get_state_ack', self.on_get_state_ack)
self.socketIO.on('alias', self.on_alias)
def __del__(self):
self.__logger.info('del')
def loop(self):
self.socketIO.wait(seconds=0.002)
def on_socket_connect_ack(self, args):
self.__logger.debug('on_socket_connect_ack: %s', args)
self.socketIO.emit('connect', {'appkey': self.appkey, 'customid': self.customid})
def on_connack(self, args):
self.__logger.debug('on_connack: %s', args)
self.socketIO.emit('set_alias', {'alias': self.alias})
def on_puback(self, args):
self.__logger.debug('on_puback: %s', args)
def on_suback(self, args):
self.__logger.debug('on_suback: %s', args)
def on_message(self, args):
self.__logger.debug('on_message: %s', args)
def on_set_alias(self, args):
self.__logger.debug('on_set_alias: %s', args)
def on_get_alias(self, args):
self.__logger.debug('on_get_alias: %s', args)
def on_alias(self, args):
self.__logger.debug('on_alias: %s', args)
def on_get_topic_list_ack(self, args):
self.__logger.debug('on_get_topic_list_ack: %s', args)
def on_get_alias_list_ack(self, args):
self.__logger.debug('on_get_alias_list_ack: %s', args)
def on_publish2_ack(self, args):
self.__logger.debug('on_publish2_ack: %s', args)
def on_publish2_recvack(self, args):
self.__logger.debug('on_publish2_recvack: %s', args)
def on_get_state_ack(self, args):
self.__logger.debug('on_get_state_ack: %s', args)
def publish(self, msg, topic, qos):
self.__logger.debug('publish: %s', msg)
self.socketIO.emit('publish', {'topic': topic, 'msg': msg, 'qos': qos})
def publish_to_alias(self, alias, msg):
self.__logger.debug('publish_to_alias: %s %s', alias, msg)
self.socketIO.emit('publish_to_alias', {'alias': alias, 'msg': msg})
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
m = Messenger(APPKEY, ALIAS, ALIAS);
while True:
m.loop()
time.sleep(0.02)
|
We heard the Russian soprano Aida Garifullina at Rosenblatt Recitals in 2014 (see my review) and her debut disc on Decca is a similar mix of French and Italian standards, with some Russian rarities and songs. Accompanied by the ORF Radio-Symphonieorchester Wien, conductor Cornelius Meister, Garifullina sings arias from Gounod's Romeo et Juliette, Delibes' Lakme, Rimsky-Korsakov's Song of India, The Snow Maiden and The Golden Cockerel, and Tchaikovsky's Mazeppa, plus songs by Tchaikovsky and Rachmaninov, and traditional songs.
Garifullina has a fine lyric coloratura voice with a surprising strength and vibrancy to it, so that the more coloratura items have a very particular quality to them which makes her performances very appealing. She also has a lovely secure technique and a nice evenness of tone from top to bottom. Simply listening to the opening item of the disc, Juliette's Je veux vivre from Gounod's Romeo et Juliette gives you the idea, with shapely phrases, technical security and great charm. But the timbre is a long way from a traditional French lyric coloratura, and there is little sense of Juliette the young naif.
Moving on to The Bell Song from Delibes' Lakme we can again appreciate the beauty of sound allied to superb technical delivery, yet the voice sounds rather more robust than at teenager with little in the way of vulnerability or fragility. More importantly, the emotional demeanour is similar to the first song, we lack a sense of character.
You feel that there is more connection between singer and material in the first two Rimsky Korsakov items, arias from The Song of India and The Snow Maiden. Here, in her own native language there is a greater sense of colour to the words, though even here I wondered if you could guess the emotional content of the arias by listening cold. The big advantage of hearing Garifullina in this music is that she is able to combine a fine technique, with quite a full voice in just the way the roles require.
She sings Tchaikovsky's Serenada from Six Romances and Rachmaninov's Lilacs from Twelve Romances with great style and engaging charm, though you feel it is the musical line which is most important to her rather than inflecting the words.
The traditional song Alluki is marred by a being given in a big, film-score type arrangement which does the song no favours, but provides Garifullina with a fine vehicle.
There is a lovely lyric melancholy to Maria's lullaby from Tchaikovsky's Mazeppa, and the two items from Rimsky Korsakov's The Golden Cockerel show the Queen of Shemmakha at her most langorously seductive.
We return to rather generic romance for How beautiful it is here from Rachmaninov's Twelve Romances, and there is a yearning melancholy to Rimsky Korsakov's The Rose and the Nightingale (though you should seek out Cathy Berberian's performance if you want to hear it sung with real character). Frankly, the Rachmaninov's Vocalise suits Garifullina admirably, but here the piece is taken at a pace which is almost funereal.
Finally we get a traditional Cossack lullaby in a rather leisurely tempo, and the the familiar Midnight in Moscow by Soloviev-Sedoy, but given the showbiz treatment.
If you like beautiful singing, then this is the disc for you. In all the items on the disc, Garifullina shows herself to be a stylish, elegant performer with a supreme technique. But her main concern is technique, and sense of line. When we get characterisation it is fairly generic and there is little sense of her colouring and inflecting words, and digging deep into character. Perhaps I am being a little hard, but I feel that Garifullina has such a lovely combination of technique and charm, that it is shame that these arias and songs do not count for much, much more.
|
# -*- coding: utf-8 -*-
import os
import sys
import time
import psutil
import pytest
from plumbum import NOHUP, local
try:
from plumbum.cmd import bash, echo
except ImportError:
bash = None
echo = None
from plumbum._testtools import skip_on_windows
from plumbum.path.utils import delete
@skip_on_windows
class TestNohupLocal:
def read_file(self, filename):
assert filename in os.listdir(".")
with open(filename) as f:
return f.read()
@pytest.mark.usefixtures("testdir")
def test_slow(self):
delete("nohup.out")
sp = bash["slow_process.bash"]
sp & NOHUP
time.sleep(0.5)
assert self.read_file("slow_process.out") == "Starting test\n1\n"
assert self.read_file("nohup.out") == "1\n"
time.sleep(1)
assert self.read_file("slow_process.out") == "Starting test\n1\n2\n"
assert self.read_file("nohup.out") == "1\n2\n"
time.sleep(2)
delete("nohup.out", "slow_process.out")
def test_append(self):
delete("nohup.out")
output = echo["This is output"]
output & NOHUP
time.sleep(0.2)
assert self.read_file("nohup.out") == "This is output\n"
output & NOHUP
time.sleep(0.2)
assert self.read_file("nohup.out") == "This is output\n" * 2
delete("nohup.out")
def test_redir(self):
delete("nohup_new.out")
output = echo["This is output"]
output & NOHUP(stdout="nohup_new.out")
time.sleep(0.2)
assert self.read_file("nohup_new.out") == "This is output\n"
delete("nohup_new.out")
(output > "nohup_new.out") & NOHUP
time.sleep(0.2)
assert self.read_file("nohup_new.out") == "This is output\n"
delete("nohup_new.out")
output & NOHUP
time.sleep(0.2)
assert self.read_file("nohup.out") == "This is output\n"
delete("nohup.out")
def test_closed_filehandles(self):
proc = psutil.Process()
file_handles_prior = proc.num_fds()
sleep_proc = local["sleep"]["1"] & NOHUP
sleep_proc.wait()
file_handles_after = proc.num_fds()
assert file_handles_prior >= file_handles_after
|
SATEL has a leading domestic market position in an intruder alarm industry, specializing in designing, production and sale of high-quality electronic alarm system devices, active on polish market since 1990.
Highly qualified engineers, outstanding machine park efficiency and its versatility allow the company to maintain a competitive edge on the entire range of products. Thanks to that SATEL’s offer is still widening up, which effects in a growing number of satisfied clients and a leading position on polish market and well known brand on over 40 foreign markets. SATEL’s activity is not just designing and production of electronic devices but also fully individually elaborated and manufactured plastic element. SATEL’s manufacturing activity is complemented by technical support, sales department and creative marketing team.
In connection with dynamic company development we keep on searching for ambitious, creative and open minded people, who are ready to involve themselves in building together a strong brand. In return we offer a job in a company which has a strong position, gives an opportunity for rising up qualifications and professional development in a young and dynamic team.
Our mission is to obtain our leading market position in an intruder alarm industry, by offering solutions based on the latest technologies. Over 280 employees actively involved in achieving that task together with permanent, dynamic growth of production field create a bright way to attain that target.
|
# Copyright 2017 The EcoDataLearn. All Rights Reserved.
# Author Stephen (Yu) Shao
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Builds the mathtool function
Implements the mathtool
"""
from approximation import *
from regression import *
# Approximation
approx_obj = MathApprox()
approx_obj.handle()
x = approx_obj.get_x()
y = approx_obj.get_y()
# Regression
deg = 1
regress_obj = MathRegress(x, y)
regress_obj.handle(deg)
deg = 7
regress_obj.handle(deg)
|
In Central America, child labor is a major impeding factor to a country's path towards economic progress and education. Nicaragua, the largest country in Central America, has a long history with child labor and its effects on employment opportunities, access to sanitation facilities, medication, and health care. In 2008, the U.S. Department of Labor funded the ENTERATE project to fight child labor in Nicaragua.
The U.S. Department of Labor funded the 2008-2011 ENTERATE project to fight child labor in Nicaragua. The project was led by AIR, in partnership with Nicaraguan partners La Cuculmeca, INPRHU-Somoto, and Club Infantil and aimed to reduce the worst forms of child labor in Nicaragua, with a focus on the coffee growing regions of Jinotega and Madriz.
The project enrolled a total of 12,603 children over the life of the project and managed to withdraw 10,636 children from exploitive labor or prevent those at-risk children from falling into child labor. Even beneficiaries that did not formally fulfill the criteria for withdrawal from child labor still managed to reduce, on average, their weekly working hours by 14.4 hours. The project also worked to strengthen the capacity of public and private organizations dealing with exploitative child labor in Nicaragua. ENTERATE engaged the private sector (especially coffee producers) to increase the level of impact and sustainability of project interventions, and has carried out awareness strategies to mobilize local stakeholders. The success of the project activities can also been seen in the very high rate of 88% of ENTERATE beneficiaries passing to the next grade level due to the comprehensive set of interventions, compared to an average rate of approximately 70% nationally.
ENTERATE’s strategy for success was to combine support for access to basic education (or vocational education) with complementary services (study and interest groups, recreational activities, etc.) as well as awareness raising efforts and continuous community-based monitoring and follow-up. Another particularly effective aspect of ENTERATE was its monitoring system, which reliably measured children’s labor and education status. The effectiveness of the system was partly due to the creation of a user-friendly system that could be easily managed and implemented by project associates as well as community volunteers. The monitoring system also included proactive mechanisms for verifying the validity of data and providing ongoing support to field staff and volunteers. ENTERATE worked with the Nicaraguan Ministry of Education to provide teacher training in primary schools on active learning methodologies and children’s rights in project supported schools. Additionally, ENTERATE empowered children to advocate for their rights and promote youth leadership.
ENTERATE has designed a national awareness campaign that was further developed and delivered by at risk children and former child laborers, giving them a voice at the local and national levels. ENTERATE’s youth leadership efforts should be considered a best practice among USDOL-funded projects. The project effectively promoted the involvement of youth and provided them with increasingly more responsibility in making programmatic decisions. These efforts helped the project achieve a greater impact on W/P as well as prepared targeted youth beneficiaries to become young leaders who can remain as future and sustainable advocates regarding child labor issues.
|
"""
sentry.web.frontend.accounts
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
from django.contrib import messages
from django.contrib.auth import login as login_user, authenticate
from django.core.context_processors import csrf
from django.core.urlresolvers import reverse
from django.db import IntegrityError, transaction
from django.http import HttpResponseRedirect, Http404
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_protect
from django.utils import timezone
from django.utils.translation import ugettext as _
from sudo.decorators import sudo_required
from sentry.models import (
UserEmail, LostPasswordHash, Project, UserOption, Authenticator
)
from sentry.signals import email_verified
from sentry.web.decorators import login_required, signed_auth_required
from sentry.web.forms.accounts import (
AccountSettingsForm, AppearanceSettingsForm,
RecoverPasswordForm, ChangePasswordRecoverForm,
)
from sentry.web.helpers import render_to_response
from sentry.utils.auth import get_auth_providers, get_login_redirect
def send_password_recovery_mail(user):
password_hash, created = LostPasswordHash.objects.get_or_create(
user=user
)
if not password_hash.is_valid():
password_hash.date_added = timezone.now()
password_hash.set_hash()
password_hash.save()
password_hash.send_recover_mail()
return password_hash
@login_required
def login_redirect(request):
login_url = get_login_redirect(request)
return HttpResponseRedirect(login_url)
def expired(request, user):
password_hash = send_password_recovery_mail(user)
return render_to_response('sentry/account/recover/expired.html', {
'email': password_hash.user.email,
}, request)
def recover(request):
form = RecoverPasswordForm(request.POST or None,
captcha=bool(request.session.get('needs_captcha')))
if form.is_valid():
password_hash = send_password_recovery_mail(form.cleaned_data['user'])
request.session.pop('needs_captcha', None)
return render_to_response('sentry/account/recover/sent.html', {
'email': password_hash.user.email,
}, request)
elif request.POST and not request.session.get('needs_captcha'):
request.session['needs_captcha'] = 1
form = RecoverPasswordForm(request.POST or None, captcha=True)
form.errors.pop('captcha', None)
context = {
'form': form,
}
return render_to_response('sentry/account/recover/index.html', context, request)
def recover_confirm(request, user_id, hash):
try:
password_hash = LostPasswordHash.objects.get(user=user_id, hash=hash)
if not password_hash.is_valid():
password_hash.delete()
raise LostPasswordHash.DoesNotExist
user = password_hash.user
except LostPasswordHash.DoesNotExist:
context = {}
tpl = 'sentry/account/recover/failure.html'
else:
tpl = 'sentry/account/recover/confirm.html'
if request.method == 'POST':
form = ChangePasswordRecoverForm(request.POST)
if form.is_valid():
user.set_password(form.cleaned_data['password'])
user.save()
# Ugly way of doing this, but Django requires the backend be set
user = authenticate(
username=user.username,
password=form.cleaned_data['password'],
)
login_user(request, user)
password_hash.delete()
return login_redirect(request)
else:
form = ChangePasswordRecoverForm()
context = {
'form': form,
}
return render_to_response(tpl, context, request)
@login_required
def start_confirm_email(request):
has_unverified_emails = request.user.has_unverified_emails()
if has_unverified_emails:
request.user.send_confirm_emails()
msg = _('A verification email has been sent to %s.') % request.user.email
else:
msg = _('Your email (%s) has already been verified.') % request.user.email
messages.add_message(request, messages.SUCCESS, msg)
return HttpResponseRedirect(reverse('sentry-account-settings'))
def confirm_email(request, user_id, hash):
msg = _('Thanks for confirming your email')
level = messages.SUCCESS
try:
email = UserEmail.objects.get(user=user_id, validation_hash=hash)
if not email.hash_is_valid():
raise UserEmail.DoesNotExist
except UserEmail.DoesNotExist:
if request.user.is_anonymous() or request.user.has_unverified_emails():
msg = _('There was an error confirming your email. Please try again or '
'visit your Account Settings to resend the verification email.')
level = messages.ERROR
else:
email.is_verified = True
email.validation_hash = ''
email.save()
email_verified.send(email=email.email, sender=email)
messages.add_message(request, level, msg)
return HttpResponseRedirect(reverse('sentry-account-settings'))
@csrf_protect
@never_cache
@login_required
@transaction.atomic
def settings(request):
user = request.user
form = AccountSettingsForm(
user, request.POST or None,
initial={
'email': user.email,
'username': user.username,
'name': user.name,
},
)
if form.is_valid():
old_email = user.email
form.save()
# remove previously valid email address
# TODO(dcramer): we should maintain validation here when we support
# multiple email addresses
if request.user.email != old_email:
UserEmail.objects.filter(user=user, email=old_email).delete()
try:
with transaction.atomic():
user_email = UserEmail.objects.create(
user=user,
email=user.email,
)
except IntegrityError:
pass
else:
user_email.set_hash()
user_email.save()
user.send_confirm_emails()
messages.add_message(
request, messages.SUCCESS, 'Your settings were saved.')
return HttpResponseRedirect(request.path)
context = csrf(request)
context.update({
'form': form,
'page': 'settings',
'has_2fa': Authenticator.objects.user_has_2fa(request.user),
'AUTH_PROVIDERS': get_auth_providers(),
})
return render_to_response('sentry/account/settings.html', context, request)
@csrf_protect
@never_cache
@login_required
@sudo_required
@transaction.atomic
def twofactor_settings(request):
interfaces = Authenticator.objects.all_interfaces_for_user(
request.user, return_missing=True)
if request.method == 'POST' and 'back' in request.POST:
return HttpResponseRedirect(reverse('sentry-account-settings'))
context = csrf(request)
context.update({
'page': 'security',
'has_2fa': any(x.is_enrolled and not x.is_backup_interface for x in interfaces),
'interfaces': interfaces,
})
return render_to_response('sentry/account/twofactor.html', context, request)
@csrf_protect
@never_cache
@login_required
@transaction.atomic
def avatar_settings(request):
context = csrf(request)
context.update({
'page': 'avatar',
'AUTH_PROVIDERS': get_auth_providers(),
})
return render_to_response('sentry/account/avatar.html', context, request)
@csrf_protect
@never_cache
@login_required
@transaction.atomic
def appearance_settings(request):
from django.conf import settings
options = UserOption.objects.get_all_values(user=request.user, project=None)
form = AppearanceSettingsForm(request.user, request.POST or None, initial={
'language': options.get('language') or request.LANGUAGE_CODE,
'stacktrace_order': int(options.get('stacktrace_order', -1) or -1),
'timezone': options.get('timezone') or settings.SENTRY_DEFAULT_TIME_ZONE,
'clock_24_hours': options.get('clock_24_hours') or False,
})
if form.is_valid():
form.save()
messages.add_message(request, messages.SUCCESS, 'Your settings were saved.')
return HttpResponseRedirect(request.path)
context = csrf(request)
context.update({
'form': form,
'page': 'appearance',
'AUTH_PROVIDERS': get_auth_providers(),
})
return render_to_response('sentry/account/appearance.html', context, request)
@csrf_protect
@never_cache
@signed_auth_required
@transaction.atomic
def email_unsubscribe_project(request, project_id):
# For now we only support getting here from the signed link.
if not request.user_from_signed_request:
raise Http404()
try:
project = Project.objects.get(pk=project_id)
except Project.DoesNotExist:
raise Http404()
if request.method == 'POST':
if 'cancel' not in request.POST:
UserOption.objects.set_value(
request.user, project, 'mail:alert', 0)
return HttpResponseRedirect(reverse('sentry'))
context = csrf(request)
context['project'] = project
return render_to_response('sentry/account/email_unsubscribe_project.html',
context, request)
@csrf_protect
@never_cache
@login_required
def list_identities(request):
from social_auth.models import UserSocialAuth
identity_list = list(UserSocialAuth.objects.filter(user=request.user))
AUTH_PROVIDERS = get_auth_providers()
context = csrf(request)
context.update({
'identity_list': identity_list,
'page': 'identities',
'AUTH_PROVIDERS': AUTH_PROVIDERS,
})
return render_to_response('sentry/account/identities.html', context, request)
|
First, I have my Thanksgiving Pack to share with you!
I am so excited to do this with my kiddies!!
one morning half turkey and half kid!
I also included five other Thanksgiving-themed activities!
by matching their animal card to the identical one.
Click on the cover below to download!
The writing craftivity looks like so much fun!
I hope that you get to feeling better soon!! I also wanted to thank you for donating something special to the Rockin Teacher Materials giveaway therefore giving me the chance to win!!
Thank you for sharing your pairing cards!!! Love them!!
I am coming over from Rockin Teacher Materials. Thanks for sharing things for the giveaway. I hope that I win!
Love your Turkey Pack!! What a great giveaway Rockin Teachers is having. Thanks for participating!!
Love the freebie – thanks! Checking in from Rockin Teachers!
Checking in from Rockin Teachers!
Rockin' Teacher sent me!! Thanks for participating!!
so adorable! what a great idea!!thanks!
|
""" Collection of helpers for Kolekto.
"""
import os
import gdbm
import json
def get_hash(input_string):
""" Return the hash of the movie depending on the input string.
If the input string looks like a symbolic link to a movie in a Kolekto
tree, return its movies hash, else, return the input directly in lowercase.
"""
# Check if the input looks like a link to a movie:
if os.path.islink(input_string):
directory, movie_hash = os.path.split(os.readlink(input_string))
input_string = movie_hash
return input_string.lower()
class JsonDbm(object):
""" A simple GNU DBM database which store JSON-serialized Python.
"""
def __init__(self, filename, object_class=dict):
self._db = gdbm.open(filename, 'c')
self._object_class = object_class
def __contains__(self, key):
return key in self._db
def get(self, key):
""" Get data associated with provided key.
"""
return self._object_class(json.loads(self._db[key]))
def count(self):
""" Count records in the database.
"""
return len(self._db)
def save(self, key, data):
""" Save data associated with key.
"""
self._db[key] = json.dumps(data)
self._db.sync()
def remove(self, key):
""" Remove the specified key from the database.
"""
del self._db[key]
self._db.sync()
def iteritems(self):
""" Iterate over (key, data) couple stored in database.
"""
for key in self.itermovieshash():
yield key, self.get(key)
|
Our best selling basic flip flop includes an imprint on the outside strap of both sandals or sole imprint and has a sporty racing stripe around the sole. All-fabric straps add a more premium look and feel.
Additional Location/Colors: Setup $45(G) per color, plus $.70(C) run charge per color. Max 2 colors on insoles. Max 1-color on strap.
Imprint Area: 5/8" x 3" on Strap.
|
import socket
from MySocket import MySocket
import datetime
import os.path
LOGFOLDER = 'D:\\log\\'
def tail( f, lines=20 ):
total_lines_wanted = lines
BLOCK_SIZE = 1024
f.seek(0, 2)
block_end_byte = f.tell()
lines_to_go = total_lines_wanted
block_number = -1
blocks = [] # blocks of size BLOCK_SIZE, in reverse order starting
# from the end of the file
while lines_to_go > 0 and block_end_byte > 0:
if (block_end_byte - BLOCK_SIZE > 0):
# read the last block we haven't yet read
f.seek(block_number*BLOCK_SIZE, 2)
blocks.append(f.read(BLOCK_SIZE))
else:
# file too small, start from begining
f.seek(0,0)
# only read what was not read
blocks.append(f.read(block_end_byte))
lines_found = blocks[-1].count('\n'.encode())
lines_to_go -= lines_found
block_end_byte -= BLOCK_SIZE
block_number -= 1
blocks = [ x.decode() for x in blocks]
all_read_text = ''.join(reversed(blocks))
return '\n'.join(all_read_text.splitlines()[-total_lines_wanted:])
def GetTemperature(sock):
now = datetime.datetime.today()
foldername = now.strftime('%y-%m-%d')
foldername = LOGFOLDER + foldername + '\\CH6 T ' + foldername + '.log'
foldername = os.path.normpath(foldername)
try:
myfile = open(foldername,'rb')
except FileNotFoundError: #if file not present, try previous day's file
now = now - datetime.timedelta(days=1)
foldername = now.strftime('%y-%m-%d')
foldername = LOGFOLDER + foldername + '\\CH6 T ' + foldername + '.log'
foldername = os.path.normpath(foldername)
myfile = open(foldername,'rb')
ss = MySocket(sock)
word = tail(myfile,2)
word = word.split(',')[-1]
ss.mysend(word.encode('utf_8'))
now = datetime.datetime.today()
T = float(word)*1000.
print("Temperature sent at %s, T = %f mK" % (now.strftime('%y-%m-%d %H:%M:%S'),T))
ss.sock.close()
print("StLab Temperature server for BluFors. Initializing...")
# create an INET, STREAMing socket
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# bind the socket to a public host, and a well-known port
#serversocket.bind((socket.gethostname(), 8001))
addr = socket.gethostbyname(socket.gethostname())
port = 8472
serversocket.bind(('', port))
# become a server socket
serversocket.listen(5)
print("Ready. Listening on port %d and address %s" % (port,addr))
try:
while True:
# accept connections from outside
(clientsocket, address) = serversocket.accept()
GetTemperature(clientsocket)
except KeyboardInterrupt:
print('Shutting down temperature server')
serversocket.close()
|
Popular contemporary fast-casual Mexican restaurant mentioned as “Best take-out Mexican food” in the LA Times, Orange Coast Magazine and Sunset Magazine. Two convenient locations: downtown Laguna and in the Albertsons center across from Montage. Green-friendly and organic options. Open 11am–9pm daily, (closed Sundays downtown location). Parking available.
|
from co import bootstrap, send
from la import setUpTransformEngine
from metaii import comp
object_vt, vtvt = bootstrap()
symbol_vt, ast_vt = setUpTransformEngine(object_vt, vtvt)
context_vt = send(vtvt, 'delegated')
#########################################################################
## Simple Syntax to AST ##
#########################################################################
# Helper functions.
send(ast_vt, 'addMethod', 'valueOf', lambda ast: ast.data)
def allocate(vt): return send(vt, 'allocate')
def make_kind(kind): return send(allocate(symbol_vt), 'setName', kind)
def make_ast(KIND, value): return send(allocate(ast_vt), 'init', KIND, value)
def name_of_symbol_of(ast): return send(send(ast, 'typeOf'), 'getName')
# Some AST symbol types.
SYMBOL = make_kind('symbol')
LITERAL = make_kind('literal')
LIST = make_kind('list')
# Helper functions to generate AST for the simple compiler below.
def symbol(name): return make_ast(SYMBOL, name)
def literal(value): return make_ast(LITERAL, value)
def list_(*values): return make_ast(LIST, list(values))
send(vtvt, 'addMethod', 'makeKind', lambda context, kind: make_kind(kind))
send(vtvt, 'addMethod', 'makeAst', lambda context, KIND, value: make_ast(KIND, value))
# META-II compiler for a simple s-expression language, it generates AST
# objects using the helper functions above when evaluated.
cola_machine = comp(r'''
.SYNTAX PROGRAM
PROGRAM = .OUT('(') args .OUT(')') '.' ;
args = $ term ;
term = ( list | literal | symbol ) .OUT(', ') ;
list = '(' .OUT('list_(') args ')' .OUT(')') ;
literal = ( .STRING | .NUMBER ) .OUT('literal('*')') ;
symbol = .ID .OUT('symbol("'*'")') ;
.END
''', open('metaii.asm').read())
#########################################################################
#########################################################################
#########################################################################
# Once we have AST we can use this LISP-like machinery to evaluate it.
def evaluate(ast, context):
sname = name_of_symbol_of(ast)
if sname == 'symbol':
try: return send(context, 'lookup', ast.data)
except: return str(ast.data) + '?'
if sname == 'literal':
return ast.data
first, rest = ast.data[0], ast.data[1:]
sname = name_of_symbol_of(first)
if sname == 'symbol':
if first.data == 'define':
define(rest, context)
return
if first.data == 'lambda':
return make_lambda_ast(rest, context)
exp = tuple(evaluate(it, context) for it in ast.data)
if callable(exp[0]):
return exp[0](*exp[1:])
return exp
def define((var, exp), context):
send(context, 'addMethod', var.data, evaluate(exp, context))
return
def make_lambda_ast((variables, exp), context):
variables = tuple(v.data for v in variables.data)
exp = list_(*exp.data)
def inner(*args):
new_context = send(context, 'delegated')
for k, v in zip(variables, args):
send(new_context, 'addMethod', k, v)
return evaluate(exp, new_context)
return inner
def evaluate_list(ast, context):
result = evaluate(ast, context)
if result is not None:
print '<', result, '>'
eval_context = send(context_vt, 'delegated')
send(eval_context, 'addMethod', 'list', evaluate_list)
#########################################################################
#########################################################################
#########################################################################
# We can also use machinery like this to walk the AST and print a
# representation.
def emit_lit(ast, context):
print ' ' * context.indent, repr(ast.data)
def emit_word(ast, context):
print ' ' * context.indent, '< %s >' % (ast.data,)
def eval_seq(ast, context):
context.indent += 3
print ' ' * context.indent, '/----\\'
for item in ast.data:
send(item, 'eval', context)
print ' ' * context.indent, '\\____/'
context.indent -= 3
print_context = send(context_vt, 'delegated')
send(print_context, 'addMethod', 'literal', emit_lit)
send(print_context, 'addMethod', 'symbol', emit_word)
send(print_context, 'addMethod', 'list', eval_seq)
print_context.indent = 0
#########################################################################
#########################################################################
#########################################################################
if __name__ == '__main__':
from pprint import pprint
send(eval_context, 'addMethod', 'multiply', lambda x, y: y * x)
send(eval_context, 'addMethod', 'allocate', allocate)
send(eval_context, 'addMethod', 'make_kind', make_kind)
send(eval_context, 'addMethod', 'make_ast', make_ast)
send(eval_context, 'addMethod', 'name_of_symbol_of', name_of_symbol_of)
send(eval_context, 'addMethod',
'eval_ast', lambda ast: evaluate_list(ast, eval_context)
)
body = comp('''
( define SYMBOL ( make_kind 'symbol' ) )
( define LITERAL ( make_kind 'literal' ) )
( define LIST ( make_kind 'list' ) )
( define symbol ( lambda (name) ( make_ast SYMBOL name ) ) )
( define literal ( lambda (value) ( make_ast LITERAL value ) ) )
( define list_ ( lambda (values) ( make_ast LIST values ) ) )
( define it ( list_ (
( symbol Larry )
( literal 23 )
( symbol Barry )
)))
( eval_ast it )
( eval_ast ( symbol Bob ) )
(define a 1)(define b Larry)
(a b)
(bill 23)
(define area (lambda (r) (multiply 3.141592653 (multiply r r))))
( area 23 nic )
( 12 'neato' )
.
''', cola_machine)
ast = eval(body)
print body
print
pprint(ast)
print
for ast_ in ast:
send(ast_, 'eval', print_context)
print
print
print 'Evaluating...' ; print
for ast_ in ast:
send(ast_, 'eval', eval_context)
|
Nike Schuhe Schweiz Outlet but I had some game experience last year - 哈哈笑話 - 瑞拉澈^_^樂活網 - Powered by Discuz!
"We'll put him on IR when we're certain he's out for the year," Harbaugh said. "We know it's a serious injury. But when it came back that there was no ligament or cartilage damage,Dirk Nowitzki Jersey, that maybe gave us some hope. So we're going to wait and see how that bone heals."
Clark was signed after tight end Dennis Pitta dislocated and fractured his right hip early in training camp and backup Ed Dickson hurt his hamstring. Although it's unlikely Pitta will play this year, the Ravens do not consider putting him on injured reserve to be a formality.
The 6-1, 309-pound Shipley came to the Ravens in May via a trade with Indianapolis, where he started in five games last year.
So, what's more valuable — familiarity with the playbook or starting experience?
OWINGS MILLS, Md. (AP) — Gino Gradkowski and A.Q. Shipley have become the center of attention on the Baltimore Ravens' offensive line.
This is not a heated competition. Both expect to receive playing time and each is focused on doing his part to get the Ravens back into the Super Bowl.
If Gradkowski wins out, that will give the Ravens a quarterback-center combination from the University of Delaware.
Before being traded to Baltimore, however, Shipley found himself hopelessly stuck behind Samson Satele on the Indianapolis depth chart.
"The games are very important," Castillo said. "Probably the third game we'll split them up and then make a decision."
"Those guys are both playing very well, and that's a good thing for the Ravens,China Football Jerseys Cheap," coach John Harbaugh said. "We'll just have to see how it all plays out in the next couple of weeks as far as who earns the starting spot."
In other news, veteran tight end Dallas Clark joined the team after signing a one-year contract. He practiced for the first time Tuesday.
"If I would have stayed in Indy I would have had to wait for an injury to get my chance because they were paying the other guy a lot more money," Shipley said. "Coming here, it gives me an opportunity to start, and that's all I ask for."
Both players are locked in a competition to replace center Matt Birk,Cheap Jerseys Free Shipping, who retired after the Ravens won the Super Bowl in February. Birk never missed a start during his four years with Baltimore, and now it's time for someone else to snap the ball to quarterback Joe Flacco.
Shipley said: "Anytime you go up against (Green Bay nose guard) B.J. Raji, you've got to get something out of it. I went up against him and a lot of good defensive players in this league. But in terms of me coming here, I felt like a rookie. The terminology is completely different. Once I got it down, though, football is football."
Gradkowski was Birk's backup as a rookie last season. A fourth-round selection out of Delaware, the 6-foot-3, 300-pound Gradkowski saw limited action in 2012 but has the advantage of knowing the system.
At this point, neither Gradkowski nor Shipley has established himself as the favorite to start the opener on Sept. 5 in Denver.
Gradkowski started against Tampa Bay in the preseason opener last week has been working with the first team in practice, but that doesn't necessarily mean he's got the edge. Castillo says Shipley will start on Thursday night against Atlanta.
"It's cool for the university," Gradkowski said, "but we didn't play together. It's just a weird coincidence."
"Everybody says, 'Who's the guy?'" run game coordinator Juan Castillo said Tuesday. "We've got to have some separation. Somebody's got to come to the top. The problem is that they're both playing real well right now. They're both good leaders, they're both tough and ready to fight."
"I don't know if anyone has the advantage,Cheap Jerseys NFL China," Gradkowski said. "We're both working pretty hard and both have the system down really well. Obviously game experience helps, but I had some game experience last year, too. I think it's a good battle."
"We both obviously want the job. Otherwise we wouldn't be here," Shipley said. "That's the only reason to do this thing. But at the same time, we're teammates playing the same position. If a certain scenario comes up on the field, we'll pick each other's brains about it."
Shipley, 27,NFL Jerseys China, was a practice squad player during his first two years in the NFL and sat out the 2011 season after being cut by Philadelphia after training camp. But he played in 14 games for the Colts last year and did a fine job negating Raji while Andrew Luck threw for 362 yards and two touchdowns.
The final decision is at least two weeks away,Killian Tillie Jersey.
GMT+8, 2019-4-19 02:53, Processed in 0.019513 second(s), 5 queries.
|
#!/usr/bin/env python
from nose.tools import eq_
import pyipmi.msgs.hpm
from pyipmi.msgs import encode_message
from pyipmi.msgs import decode_message
def test_uploadfirmwareblockreq_encode():
m = pyipmi.msgs.hpm.UploadFirmwareBlockReq()
m.number = 1
m.data = [0, 1, 2, 3]
data = encode_message(m)
eq_(data, b'\x00\x01\x00\x01\x02\x03')
def test_activatefirmwarereq_decode_valid_req():
m = pyipmi.msgs.hpm.ActivateFirmwareReq()
decode_message(m, b'\x00\x01')
eq_(m.picmg_identifier, 0)
eq_(m.rollback_override_policy, 1)
def test_activatefirmwarereq_encode_valid_req():
m = pyipmi.msgs.hpm.ActivateFirmwareReq()
m.picmg_identifier = 0
m.rollback_override_policy = 0x1
data = encode_message(m)
eq_(data, b'\x00\x01')
def test_activatefirmwarereq_decode_valid_req_wo_optional():
m = pyipmi.msgs.hpm.ActivateFirmwareReq()
decode_message(m, b'\x00')
eq_(m.picmg_identifier, 0)
eq_(m.rollback_override_policy, None)
def test_activatefirmwarereq_encode_valid_req_wo_optional():
m = pyipmi.msgs.hpm.ActivateFirmwareReq()
m.picmg_identifier = 0
m.rollback_override_policy = None
data = encode_message(m)
eq_(data, b'\x00')
|
we are able to supply top quality items, aggressive price and greatest buyer assistance. Our destination is "You come here with difficulty and we offer you a smile to take away" for 12 24 Volt Dc Power Supply , 12 Volt Dc Power Supply , 12 Volt Ac Dc Power Supply , Customer satisfaction is our first goal. Our mission is to pursue the superlative quality making continual progress. We sincerely welcome you to make progress hand in hand with us and construct a prosperous future together.
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import sys
from os import path as p
import pkutils
try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup, find_packages
PARENT_DIR = p.abspath(p.dirname(__file__))
sys.dont_write_bytecode = True
py2_requirements = set(pkutils.parse_requirements('py2-requirements.txt'))
py3_requirements = sorted(pkutils.parse_requirements('requirements.txt'))
dev_requirements = sorted(pkutils.parse_requirements('dev-requirements.txt'))
readme = pkutils.read('README.md')
module = pkutils.parse_module(p.join(PARENT_DIR, 'csv2ofx', '__init__.py'))
license = module.__license__
version = module.__version__
project = module.__title__
description = module.__description__
user = 'reubano'
# Conditional sdist dependencies:
py2 = sys.version_info.major == 2
requirements = sorted(py2_requirements) if py2 else py3_requirements
# Conditional bdist_wheel dependencies:
py2_require = sorted(py2_requirements.difference(py3_requirements))
# Setup requirements
setup_require = [r for r in dev_requirements if 'pkutils' in r]
setup(
name=project,
version=version,
description=description,
long_description=readme,
author=module.__author__,
author_email=module.__email__,
url=pkutils.get_url(project, user),
download_url=pkutils.get_dl_url(project, user, version),
packages=find_packages(exclude=['docs', 'tests']),
include_package_data=True,
package_data={
'data': ['data/*'],
'helpers': ['helpers/*'],
'tests': ['tests/*'],
'docs': ['docs/*'],
'examples': ['examples/*']
},
install_requires=requirements,
extras_require={'python_version<3.0': py2_require},
setup_requires=setup_require,
test_suite='nose.collector',
tests_require=dev_requirements,
license=license,
zip_safe=False,
keywords=[project] + description.split(' '),
classifiers=[
pkutils.LICENSES[license],
pkutils.get_status(version),
'Natural Language :: English',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: Implementation :: PyPy',
'Environment :: Console',
'Topic :: Software Development :: Libraries :: Python Modules',
'Intended Audience :: Developers',
'Operating System :: POSIX :: Linux',
'Operating System :: MacOS :: MacOS X',
'Operating System :: Microsoft :: Windows',
],
platforms=['MacOS X', 'Windows', 'Linux'],
scripts=[p.join('bin', 'csv2ofx')],
)
|
The Barrhill Lot is a custom feeding cattle operation located north of Picture Butte Alberta, Canada. The feed yard has a capacity of about 25,000 head of cattle and there is still room for expansion. We are a finishing feedlot that ships to packing plants located locally and in the U.S.
The feedlot is owned and operated by Kenneth Van Raay. Ken has been apart of the Canadian farming and feedlot industy his whole life. He runs the Barrhill Lot with the help of his wife, Lori, his children and the feedlot foreman. The feedlot operates day to day with the help of about 20 feedlot and farm employees.
Since Kennneth's purchase of the feedlot, the business has grown. The feedyard was expanded by adding one more alley in September 2013 and a new feedmill was constructed in 2011. Recently (Febuary 2014), our in-barn chute system was renovated to better insure proper and easier cattle handling and efficient export testing. In August 2014, we not only did an extensive office expansion but also added the final alley to the feed yard.
As well as the feedlot, Ken Van Raay owns and farms land to produce feed for the Barrhill Lot. Both corn and barley are grown to create silage for the cattle in the yard. The feeding program at Barrhill is desgined to ensure maximize cattle gains. Ken Van Raay Inc. also grows wheat and canola as cash crops.
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
cookiecutter.utils
------------------
Helper functions used throughout Cookiecutter.
"""
from __future__ import unicode_literals
import errno
import logging
import os
import sys
import contextlib
PY3 = sys.version > '3'
if PY3:
pass
else:
import codecs
def make_sure_path_exists(path):
"""
Ensures that a directory exists.
:param path: A directory path.
"""
logging.debug("Making sure path exists: {0}".format(path))
try:
os.makedirs(path)
except OSError as exception:
if exception.errno != errno.EEXIST:
return False
return True
def unicode_open(filename, *args, **kwargs):
"""
Opens a file as usual on Python 3, and with UTF-8 encoding on Python 2.
:param filename: Name of file to open.
"""
kwargs['encoding'] = "utf-8"
if PY3:
return open(filename, *args, **kwargs)
return codecs.open(filename, *args, **kwargs)
@contextlib.contextmanager
def work_in(dirname=None):
"""
Context manager version of os.chdir. When exited, returns to the working
directory prior to entering.
"""
curdir = os.getcwd()
try:
if dirname is not None:
os.chdir(dirname)
yield
finally:
os.chdir(curdir)
|
T cell, human peripheral blood unstim.
Dysregulation of CD154 has been noted in a number of autoimmune disorders, including systemic lupus erythematosus (SLE). The author nucleofected resting T cells with expression vectors encoding GFP or luciferase under the control of a CMV, IL-2 or CD154 promoter. Transfection efficiency was found to be in a range of 55-70% and cells could be activated following transfection by PMA and ionmycin.
CD154 (CD40-ligand) has a wide variety of pleiotropic effects throughout the immune system and is critical to both cellular and humoral immunity. Cell surface and soluble CD154 are primarily expressed by activated CD4 T cells. Expression of CD154 is tightly regulated in a time-dependent manner, and, like most T cell-derived cytokines and other members of the tumor necrosis factor (TNF) superfamily, CD154 is largely regulated at the level of gene transcription. Recently, dysregulated expression of CD154 has been noted in a number of autoimmune disorders, including systemic lupus erythematosus (SLE). In addition, abnormal expression of CD154 has been hypothesized to contribute to a wider array of diseases, from atherosclerosis to Alzheimer's disease. Until recently, very little was known about the transcriptional regulation of CD154. We are exploring CD154 regulation in primary human CD4 T cells in hopes of understanding the cis- and trans-regulatory elements that control its expression in the cells that normally express CD154. Ultimately, we hope to be able to correct abnormal expression of CD154 in various disease states and to help design gene therapy vectors for treating CD154-deficient individuals with hyper-IgM syndrome.
|
# Mantid Repository : https://github.com/mantidproject/mantid
#
# Copyright © 2021 ISIS Rutherford Appleton Laboratory UKRI,
# NScD Oak Ridge National Laboratory, European Spallation Source,
# Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS
# SPDX - License - Identifier: GPL - 3.0 +
import unittest
from unittest import mock
from mantid.api import FrameworkManager, FunctionFactory
from Muon.GUI.Common.fitting_widgets.tf_asymmetry_fitting.tf_asymmetry_fitting_model import TFAsymmetryFittingModel
from Muon.GUI.Common.fitting_widgets.tf_asymmetry_fitting.tf_asymmetry_fitting_presenter import \
TFAsymmetryFittingPresenter
from Muon.GUI.Common.fitting_widgets.tf_asymmetry_fitting.tf_asymmetry_fitting_view import TFAsymmetryFittingView
class TFAsymmetryFittingPresenterTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
FrameworkManager.Instance()
def setUp(self):
self.dataset_names = ["Name1", "Name2"]
self.current_dataset_index = 0
self.start_x = 0.0
self.end_x = 15.0
self.fit_status = "success"
self.chi_squared = 1.5
self.function_name = "FlatBackground"
self.minimizer = "Levenberg-Marquardt"
self.evaluation_type = "eval type"
self.fit_to_raw = True
self.plot_guess = True
self.simultaneous_fitting_mode = True
self.simultaneous_fit_by = "Group/Pair"
self.simultaneous_fit_by_specifier = "fwd"
self.global_parameters = ["A0"]
self.fit_function = FunctionFactory.createFunction("FlatBackground")
self.single_fit_functions = [self.fit_function.clone(), self.fit_function.clone()]
self.tf_asymmetry_mode = True
self.normalisation = 3.0
self.normalisation_error = 0.3
self._setup_mock_view()
self._setup_mock_model()
self._setup_presenter()
self.mock_view_minimizer.assert_called_once_with()
self.mock_view_evaluation_type.assert_called_once_with()
self.mock_view_fit_to_raw.assert_called_once_with()
self.mock_view_simultaneous_fit_by.assert_called_once_with()
self.mock_view_simultaneous_fit_by_specifier.assert_called_once_with()
self.mock_view_global_parameters.assert_called_once_with()
self.mock_view_tf_asymmetry_mode.assert_called_once_with()
self.mock_model_minimizer.assert_called_once_with(self.minimizer)
self.mock_model_evaluation_type.assert_called_once_with(self.evaluation_type)
self.mock_model_fit_to_raw.assert_called_once_with(self.fit_to_raw)
self.mock_model_simultaneous_fit_by.assert_called_once_with(self.simultaneous_fit_by)
self.mock_model_simultaneous_fit_by_specifier.assert_called_once_with(self.simultaneous_fit_by_specifier)
self.mock_model_global_parameters.assert_called_once_with(self.global_parameters)
self.mock_model_tf_asymmetry_mode.assert_called_once_with(self.tf_asymmetry_mode)
self.assertEqual(self.view.set_slot_for_fit_generator_clicked.call_count, 1)
self.assertEqual(self.view.set_slot_for_fit_button_clicked.call_count, 1)
self.assertEqual(self.view.set_slot_for_undo_fit_clicked.call_count, 1)
self.assertEqual(self.view.set_slot_for_plot_guess_changed.call_count, 1)
self.assertEqual(self.view.set_slot_for_fit_name_changed.call_count, 1)
self.assertEqual(self.view.set_slot_for_function_structure_changed.call_count, 1)
self.assertEqual(self.view.set_slot_for_function_parameter_changed.call_count, 1)
self.assertEqual(self.view.set_slot_for_start_x_updated.call_count, 1)
self.assertEqual(self.view.set_slot_for_end_x_updated.call_count, 1)
self.assertEqual(self.view.set_slot_for_minimizer_changed.call_count, 1)
self.assertEqual(self.view.set_slot_for_evaluation_type_changed.call_count, 1)
self.assertEqual(self.view.set_slot_for_use_raw_changed.call_count, 1)
self.assertEqual(self.view.set_slot_for_dataset_changed.call_count, 1)
self.assertEqual(self.view.set_slot_for_fitting_mode_changed.call_count, 1)
self.assertEqual(self.view.set_slot_for_simultaneous_fit_by_changed.call_count, 1)
self.assertEqual(self.view.set_slot_for_simultaneous_fit_by_specifier_changed.call_count, 1)
self.assertEqual(self.view.set_slot_for_fitting_type_changed.call_count, 1)
self.assertEqual(self.view.set_slot_for_normalisation_changed.call_count, 1)
def tearDown(self):
self.presenter = None
self.model = None
self.view = None
def test_that_handle_instrument_changed_will_turn_tf_asymmetry_mode_off(self):
self.presenter.handle_instrument_changed()
self.mock_view_tf_asymmetry_mode.assert_called_with(False)
self.mock_model_tf_asymmetry_mode.assert_called_with(False)
self.assertEqual(self.mock_view_tf_asymmetry_mode.call_count, 2)
self.assertEqual(self.mock_model_tf_asymmetry_mode.call_count, 2)
def test_that_handle_pulse_type_changed_will_not_turn_tf_asymmetry_mode_off_if_it_contains_does_not_contain_DoublePulseEnabled(self):
updated_variables = {"FirstVariable": True, "OtherVariable": False}
self.presenter.handle_pulse_type_changed(updated_variables)
# The call count is one because they were initialized in the constructor
self.assertEqual(self.mock_view_tf_asymmetry_mode.call_count, 1)
self.assertEqual(self.mock_model_tf_asymmetry_mode.call_count, 1)
def test_that_handle_ads_clear_or_remove_workspace_event_will_attempt_to_reset_all_the_data_and_enable_gui(self):
self.presenter.update_and_reset_all_data = mock.Mock()
self.presenter.handle_ads_clear_or_remove_workspace_event()
self.presenter.update_and_reset_all_data.assert_called_with()
self.presenter.enable_editing_notifier.notify_subscribers.assert_called_once_with()
self.assertEqual(self.mock_view_tf_asymmetry_mode.call_count, 1)
self.assertEqual(self.mock_model_tf_asymmetry_mode.call_count, 1)
def test_that_handle_ads_clear_or_remove_workspace_event_will_attempt_to_reset_all_the_data_and_enable_gui_with_no_datasets(self):
self.mock_model_number_of_datasets = mock.PropertyMock(return_value=0)
type(self.model).number_of_datasets = self.mock_model_number_of_datasets
self.presenter.update_and_reset_all_data = mock.Mock()
self.presenter.handle_ads_clear_or_remove_workspace_event()
self.presenter.update_and_reset_all_data.assert_called_with()
self.view.disable_view.assert_called_once_with()
self.mock_view_tf_asymmetry_mode.assert_called_with(False)
self.mock_model_tf_asymmetry_mode.assert_called_with(False)
self.assertEqual(self.mock_view_tf_asymmetry_mode.call_count, 2)
self.assertEqual(self.mock_model_tf_asymmetry_mode.call_count, 2)
def test_that_handle_new_data_loaded_will_attempt_to_reset_all_the_data_and_enable_the_gui(self):
self.presenter.clear_undo_data = mock.Mock()
self.presenter.update_and_reset_all_data = mock.Mock()
self.presenter.handle_new_data_loaded()
self.presenter.update_and_reset_all_data.assert_called_with()
self.mock_view_plot_guess.assert_called_once_with(False)
self.mock_model_plot_guess.assert_called_once_with(False)
self.presenter.clear_undo_data.assert_called_with()
self.presenter.enable_editing_notifier.notify_subscribers.assert_called_once_with()
self.assertEqual(self.mock_view_tf_asymmetry_mode.call_count, 1)
self.assertEqual(self.mock_model_tf_asymmetry_mode.call_count, 1)
def test_that_handle_new_data_loaded_will_disable_the_tab_if_no_data_is_loaded(self):
self.mock_model_number_of_datasets = mock.PropertyMock(return_value=0)
type(self.model).number_of_datasets = self.mock_model_number_of_datasets
self.presenter.clear_undo_data = mock.Mock()
self.presenter.update_and_reset_all_data = mock.Mock()
self.presenter.handle_new_data_loaded()
self.presenter.update_and_reset_all_data.assert_called_with()
self.mock_view_plot_guess.assert_called_once_with(False)
self.mock_model_plot_guess.assert_called_once_with(False)
self.presenter.clear_undo_data.assert_called_with()
self.view.disable_view.assert_called_once_with()
self.mock_view_tf_asymmetry_mode.assert_called_with(False)
self.mock_model_tf_asymmetry_mode.assert_called_with(False)
self.assertEqual(self.mock_view_tf_asymmetry_mode.call_count, 2)
self.assertEqual(self.mock_model_tf_asymmetry_mode.call_count, 2)
def test_that_handle_function_structure_changed_will_attempt_to_update_the_tf_asymmetry_functions(self):
self.presenter.update_tf_asymmetry_functions_in_model_and_view = mock.Mock()
self.presenter.handle_function_structure_changed()
self.presenter.update_tf_asymmetry_functions_in_model_and_view.assert_called_once_with()
def test_that_handle_dataset_name_changed_will_attempt_to_update_the_normalisation_displayed_in_the_view(self):
self.presenter.handle_dataset_name_changed()
self.model.current_normalisation.assert_called_with()
self.model.current_normalisation_error.assert_called_with()
self.view.set_normalisation.assert_called_with(self.normalisation, self.normalisation_error)
def test_that_handle_tf_asymmetry_mode_changed_will_not_set_the_tf_asymmetry_mode_if_the_workspaces_do_not_comply(self):
self.presenter._check_tf_asymmetry_compliance = mock.Mock(return_value=False)
self.presenter.handle_tf_asymmetry_mode_changed(self.tf_asymmetry_mode)
# The call count is one because they were initialized in the constructor
self.assertEqual(self.mock_view_tf_asymmetry_mode.call_count, 1)
self.assertEqual(self.mock_model_tf_asymmetry_mode.call_count, 1)
self.presenter._check_tf_asymmetry_compliance.assert_called_once_with(self.tf_asymmetry_mode)
def test_that_handle_tf_asymmetry_mode_changed_will_set_the_tf_asymmetry_mode_if_the_workspaces_do_comply(self):
self.presenter._check_tf_asymmetry_compliance = mock.Mock(return_value=True)
self.presenter.update_tf_asymmetry_functions_in_model_and_view = mock.Mock()
self.presenter.reset_start_xs_and_end_xs = mock.Mock()
self.presenter.reset_fit_status_and_chi_squared_information = mock.Mock()
self.presenter.clear_undo_data = mock.Mock()
self.presenter.automatically_update_function_name = mock.Mock()
self.presenter.handle_tf_asymmetry_mode_changed(self.tf_asymmetry_mode)
# The call count is one because they were initialized in the constructor
self.assertEqual(self.mock_view_tf_asymmetry_mode.call_count, 2)
self.assertEqual(self.mock_model_tf_asymmetry_mode.call_count, 2)
self.presenter._check_tf_asymmetry_compliance.assert_called_once_with(self.tf_asymmetry_mode)
self.presenter.update_tf_asymmetry_functions_in_model_and_view.assert_called_once_with()
self.presenter.reset_fit_status_and_chi_squared_information.assert_called_once_with()
self.presenter.clear_undo_data.assert_called_once_with()
self.presenter.automatically_update_function_name.assert_called_once_with()
self.model.update_plot_guess(self.plot_guess)
def test_that_handle_normalisation_changed_sets_the_normalisation_in_the_model_and_updates_the_guess(self):
self.presenter.handle_normalisation_changed()
self.mock_view_normalisation.assert_called_with()
self.model.set_current_normalisation.assert_called_once_with(self.normalisation)
self.model.update_plot_guess(self.plot_guess)
def test_that_update_and_reset_all_data_will_attempt_to_update_the_tf_asymmetry_functions(self):
self.presenter.update_tf_asymmetry_functions_in_model_and_view = mock.Mock()
self.presenter.update_and_reset_all_data()
self.presenter.update_tf_asymmetry_functions_in_model_and_view.assert_called_once_with()
def test_that_update_tf_asymmetry_functions_in_model_and_view_shows_a_warning_if_it_fails_to_recalculate_the_functions(self):
self.model.recalculate_tf_asymmetry_functions = mock.Mock(return_value=False)
self.presenter.update_tf_asymmetry_functions_in_model_and_view()
self.model.recalculate_tf_asymmetry_functions.assert_called_once_with()
self.view.warning_popup.assert_called_once_with("Failed to convert fit function to a TF Asymmetry function.")
self.model.current_normalisation.assert_called_with()
self.view.set_normalisation.assert_called_with(self.normalisation, self.normalisation_error)
def test_that_update_tf_asymmetry_functions_in_model_and_view_will_set_the_normalisation_in_the_view(self):
self.model.recalculate_tf_asymmetry_functions = mock.Mock(return_value=True)
self.presenter.update_tf_asymmetry_functions_in_model_and_view()
self.model.recalculate_tf_asymmetry_functions.assert_called_once_with()
self.model.current_normalisation.assert_called_with()
self.view.set_normalisation.assert_called_with(self.normalisation, self.normalisation_error)
def test_that_update_fit_function_in_model_will_update_the_simultaneous_fit_functions_when_in_simultaneous_mode(self):
self.model.update_tf_asymmetry_simultaneous_fit_function = mock.Mock()
self.mock_model_simultaneous_fitting_mode = mock.PropertyMock(return_value=True)
type(self.model).simultaneous_fitting_mode = self.mock_model_simultaneous_fitting_mode
self.presenter.update_fit_function_in_model(self.fit_function)
self.model.update_tf_asymmetry_simultaneous_fit_function.assert_called_once_with(self.fit_function)
def test_that_update_fit_function_in_model_will_update_the_current_fit_function_when_in_single_mode(self):
self.model.update_tf_asymmetry_single_fit_function = mock.Mock()
self.mock_model_simultaneous_fitting_mode = mock.PropertyMock(return_value=False)
type(self.model).simultaneous_fitting_mode = self.mock_model_simultaneous_fitting_mode
self.presenter.update_fit_function_in_model(self.fit_function)
self.model.update_tf_asymmetry_single_fit_function.assert_called_once_with(self.model.current_dataset_index,
self.fit_function)
def test_that_handle_sequential_fit_finished_will_update_the_fit_functions_and_statuses_in_the_view_and_model(self):
self.presenter.update_fit_function_in_view_from_model = mock.Mock()
self.presenter.update_fit_statuses_and_chi_squared_in_view_from_model = mock.Mock()
self.presenter.handle_sequential_fit_finished()
self.presenter.update_fit_function_in_view_from_model.assert_called_once_with()
self.presenter.update_fit_statuses_and_chi_squared_in_view_from_model.assert_called_once_with()
def _setup_mock_view(self):
self.view = mock.Mock(spec=TFAsymmetryFittingView)
# Mock the properties of the view
self.mock_view_current_dataset_index = mock.PropertyMock(return_value=self.current_dataset_index)
type(self.view).current_dataset_index = self.mock_view_current_dataset_index
self.mock_view_current_dataset_name = mock.PropertyMock(return_value=
self.dataset_names[self.current_dataset_index])
type(self.view).current_dataset_name = self.mock_view_current_dataset_name
self.mock_view_simultaneous_fit_by = mock.PropertyMock(return_value=self.simultaneous_fit_by)
type(self.view).simultaneous_fit_by = self.mock_view_simultaneous_fit_by
self.mock_view_simultaneous_fit_by_specifier = mock.PropertyMock(return_value=
self.simultaneous_fit_by_specifier)
type(self.view).simultaneous_fit_by_specifier = self.mock_view_simultaneous_fit_by_specifier
self.mock_view_global_parameters = mock.PropertyMock(return_value=self.global_parameters)
type(self.view).global_parameters = self.mock_view_global_parameters
self.mock_view_minimizer = mock.PropertyMock(return_value=self.minimizer)
type(self.view).minimizer = self.mock_view_minimizer
self.mock_view_evaluation_type = mock.PropertyMock(return_value=self.evaluation_type)
type(self.view).evaluation_type = self.mock_view_evaluation_type
self.mock_view_fit_to_raw = mock.PropertyMock(return_value=self.fit_to_raw)
type(self.view).fit_to_raw = self.mock_view_fit_to_raw
self.mock_view_fit_object = mock.PropertyMock(return_value=self.fit_function)
type(self.view).fit_object = self.mock_view_fit_object
self.mock_view_start_x = mock.PropertyMock(return_value=self.start_x)
type(self.view).start_x = self.mock_view_start_x
self.mock_view_end_x = mock.PropertyMock(return_value=self.end_x)
type(self.view).end_x = self.mock_view_end_x
self.mock_view_plot_guess = mock.PropertyMock(return_value=self.plot_guess)
type(self.view).plot_guess = self.mock_view_plot_guess
self.mock_view_function_name = mock.PropertyMock(return_value=self.function_name)
type(self.view).function_name = self.mock_view_function_name
self.mock_view_simultaneous_fitting_mode = mock.PropertyMock(return_value=self.simultaneous_fitting_mode)
type(self.view).simultaneous_fitting_mode = self.mock_view_simultaneous_fitting_mode
self.mock_view_tf_asymmetry_mode = mock.PropertyMock(return_value=self.tf_asymmetry_mode)
type(self.view).tf_asymmetry_mode = self.mock_view_tf_asymmetry_mode
self.mock_view_normalisation = mock.PropertyMock(return_value=self.normalisation)
type(self.view).normalisation = self.mock_view_normalisation
# Mock the methods of the view
self.view.set_slot_for_fit_generator_clicked = mock.Mock()
self.view.set_slot_for_fit_button_clicked = mock.Mock()
self.view.set_slot_for_undo_fit_clicked = mock.Mock()
self.view.set_slot_for_plot_guess_changed = mock.Mock()
self.view.set_slot_for_fit_name_changed = mock.Mock()
self.view.set_slot_for_function_structure_changed = mock.Mock()
self.view.set_slot_for_function_parameter_changed = mock.Mock()
self.view.set_slot_for_start_x_updated = mock.Mock()
self.view.set_slot_for_end_x_updated = mock.Mock()
self.view.set_slot_for_minimizer_changed = mock.Mock()
self.view.set_slot_for_evaluation_type_changed = mock.Mock()
self.view.set_slot_for_use_raw_changed = mock.Mock()
self.view.set_slot_for_dataset_changed = mock.Mock()
self.view.set_slot_for_fitting_mode_changed = mock.Mock()
self.view.set_slot_for_simultaneous_fit_by_changed = mock.Mock()
self.view.set_slot_for_simultaneous_fit_by_specifier_changed = mock.Mock()
self.view.set_slot_for_fitting_type_changed = mock.Mock()
self.view.set_slot_for_normalisation_changed = mock.Mock()
self.view.set_datasets_in_function_browser = mock.Mock()
self.view.set_current_dataset_index = mock.Mock()
self.view.update_local_fit_status_and_chi_squared = mock.Mock()
self.view.update_global_fit_status = mock.Mock()
self.view.update_fit_function = mock.Mock()
self.view.enable_undo_fit = mock.Mock()
self.view.number_of_datasets = mock.Mock(return_value=len(self.dataset_names))
self.view.warning_popup = mock.Mock()
self.view.get_global_parameters = mock.Mock(return_value=[])
self.view.switch_to_simultaneous = mock.Mock()
self.view.switch_to_single = mock.Mock()
self.view.set_normalisation = mock.Mock()
def _setup_mock_model(self):
self.model = mock.Mock(spec=TFAsymmetryFittingModel)
# Mock the properties of the model
self.mock_model_current_dataset_index = mock.PropertyMock(return_value=self.current_dataset_index)
type(self.model).current_dataset_index = self.mock_model_current_dataset_index
self.mock_model_dataset_names = mock.PropertyMock(return_value=self.dataset_names)
type(self.model).dataset_names = self.mock_model_dataset_names
self.mock_model_current_dataset_name = mock.PropertyMock(return_value=
self.dataset_names[self.current_dataset_index])
type(self.model).current_dataset_name = self.mock_model_current_dataset_name
self.mock_model_number_of_datasets = mock.PropertyMock(return_value=len(self.dataset_names))
type(self.model).number_of_datasets = self.mock_model_number_of_datasets
self.mock_model_start_xs = mock.PropertyMock(return_value=[self.start_x] * len(self.dataset_names))
type(self.model).start_xs = self.mock_model_start_xs
self.mock_model_current_start_x = mock.PropertyMock(return_value=self.start_x)
type(self.model).current_start_x = self.mock_model_current_start_x
self.mock_model_end_xs = mock.PropertyMock(return_value=[self.end_x] * len(self.dataset_names))
type(self.model).end_xs = self.mock_model_end_xs
self.mock_model_current_end_x = mock.PropertyMock(return_value=self.end_x)
type(self.model).current_end_x = self.mock_model_current_end_x
self.mock_model_plot_guess = mock.PropertyMock(return_value=self.plot_guess)
type(self.model).plot_guess = self.mock_model_plot_guess
self.mock_model_minimizer = mock.PropertyMock(return_value=self.minimizer)
type(self.model).minimizer = self.mock_model_minimizer
self.mock_model_evaluation_type = mock.PropertyMock(return_value=self.evaluation_type)
type(self.model).evaluation_type = self.mock_model_evaluation_type
self.mock_model_fit_to_raw = mock.PropertyMock(return_value=self.fit_to_raw)
type(self.model).fit_to_raw = self.mock_model_fit_to_raw
self.mock_model_simultaneous_fit_by = mock.PropertyMock(return_value=self.simultaneous_fit_by)
type(self.model).simultaneous_fit_by = self.mock_model_simultaneous_fit_by
self.mock_model_simultaneous_fit_by_specifier = mock.PropertyMock(return_value=
self.simultaneous_fit_by_specifier)
type(self.model).simultaneous_fit_by_specifier = self.mock_model_simultaneous_fit_by_specifier
self.mock_model_global_parameters = mock.PropertyMock(return_value=self.global_parameters)
type(self.model).global_parameters = self.mock_model_global_parameters
self.mock_model_single_fit_functions = mock.PropertyMock(return_value=self.single_fit_functions)
type(self.model).single_fit_functions = self.mock_model_single_fit_functions
self.mock_model_current_single_fit_function = mock.PropertyMock(return_value=self.fit_function)
type(self.model).current_single_fit_function = self.mock_model_current_single_fit_function
self.mock_model_single_fit_functions_cache = mock.PropertyMock(return_value=self.fit_function)
type(self.model).single_fit_functions_cache = self.mock_model_single_fit_functions_cache
self.mock_model_simultaneous_fit_function = mock.PropertyMock(return_value=self.fit_function)
type(self.model).simultaneous_fit_function = self.mock_model_simultaneous_fit_function
self.mock_model_fit_statuses = mock.PropertyMock(return_value=[self.fit_status] * len(self.dataset_names))
type(self.model).fit_statuses = self.mock_model_fit_statuses
self.mock_model_current_fit_status = mock.PropertyMock(return_value=self.fit_status)
type(self.model).current_fit_status = self.mock_model_current_fit_status
self.mock_model_chi_squared = mock.PropertyMock(return_value=[self.chi_squared] * len(self.dataset_names))
type(self.model).chi_squared = self.mock_model_chi_squared
self.mock_model_current_chi_squared = mock.PropertyMock(return_value=self.chi_squared)
type(self.model).current_chi_squared = self.mock_model_current_chi_squared
self.mock_model_function_name = mock.PropertyMock(return_value=self.function_name)
type(self.model).function_name = self.mock_model_function_name
self.mock_model_function_name_auto_update = mock.PropertyMock(return_value=True)
type(self.model).function_name_auto_update = self.mock_model_function_name_auto_update
self.mock_model_simultaneous_fitting_mode = mock.PropertyMock(return_value=self.simultaneous_fitting_mode)
type(self.model).simultaneous_fitting_mode = self.mock_model_simultaneous_fitting_mode
self.mock_model_global_parameters = mock.PropertyMock(return_value=[])
type(self.model).global_parameters = self.mock_model_global_parameters
self.mock_model_do_rebin = mock.PropertyMock(return_value=False)
type(self.model).do_rebin = self.mock_model_do_rebin
self.mock_model_tf_asymmetry_mode = mock.PropertyMock(return_value=self.tf_asymmetry_mode)
type(self.model).tf_asymmetry_mode = self.mock_model_tf_asymmetry_mode
# Mock the context
self.model.context = mock.Mock()
# Mock the methods of the model
self.model.clear_single_fit_functions = mock.Mock()
self.model.get_single_fit_function_for = mock.Mock(return_value=self.fit_function)
self.model.cache_the_current_fit_functions = mock.Mock()
self.model.clear_undo_data = mock.Mock()
self.model.automatically_update_function_name = mock.Mock()
self.model.save_current_fit_function_to_undo_data = mock.Mock()
self.model.update_plot_guess = mock.Mock()
self.model.remove_all_fits_from_context = mock.Mock()
self.model.reset_current_dataset_index = mock.Mock()
self.model.reset_start_xs_and_end_xs = mock.Mock()
self.model.reset_fit_statuses_and_chi_squared = mock.Mock()
self.model.reset_fit_functions = mock.Mock()
self.model.x_limits_of_workspace = mock.Mock(return_value=(self.start_x, self.end_x))
self.model.retrieve_first_good_data_from_run = mock.Mock(return_value=self.start_x)
self.model.get_active_fit_function = mock.Mock(return_value=self.fit_function)
self.model.get_active_workspace_names = mock.Mock(return_value=[self.dataset_names[self.current_dataset_index]])
self.model.get_active_fit_results = mock.Mock(return_value=[])
self.model.get_workspace_names_to_display_from_context = mock.Mock(return_value=self.dataset_names)
self.model.perform_fit = mock.Mock(return_value=(self.fit_function, self.fit_status, self.chi_squared))
self.model.current_normalisation = mock.Mock(return_value=self.normalisation)
self.model.set_current_normalisation = mock.Mock()
self.model.current_normalisation_error = mock.Mock(return_value=self.normalisation_error)
def _setup_presenter(self):
self.presenter = TFAsymmetryFittingPresenter(self.view, self.model)
# Mock unimplemented methods and notifiers
self.presenter.disable_editing_notifier.notify_subscribers = mock.Mock()
self.presenter.enable_editing_notifier.notify_subscribers = mock.Mock()
self.presenter.selected_fit_results_changed.notify_subscribers = mock.Mock()
self.presenter.fit_function_changed_notifier.notify_subscribers = mock.Mock()
self.presenter.fit_parameter_changed_notifier.notify_subscribers = mock.Mock()
self.presenter.fitting_mode_changed_notifier.notify_subscribers = mock.Mock()
if __name__ == '__main__':
unittest.main()
|
Thank you so very much Dina!
OMG this project rocks my world!
You are so sweet! Thank you Beth!
These are the perfect little treat bags for Halloween trick-or-treating ! Thanks for the great tutorial.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.