<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Callback script executed on the tester machine
"""
from __future__ import with_statement

import os
import socket
import paramiko
import sys
import ConfigParser

from . import vmlogging

_DEFAULT_SSH_PORT = 22
_logger = vmlogging.create_module_logger('callback')

def _setup_logging():
    """Instruct paramiko to log stuff.
    Should be disabled in production?
    """
    paramiko.util.log_to_file('callback_sftp.log')

def get_default_remote_host_keys():
    """Search for host keys in default paths
    """
    # search two default paths (Linux & Windows)
    search_paths = ['~/.ssh/known_hosts', '~/ssh/known_hosts']
    paths = map(lambda x : os.path.expanduser(x), search_paths)
    for path in paths:
        try:
            host_keys = paramiko.util.load_host_keys(path)
            return host_keys
        except:
            _logger.info('Cannot open known_hosts file [%s]' % path)
    else:
        # on failure return an empty key dictionary
        return {}

def is_remote_server_key_known(key, hostname):
    """Return True if the remote hostname server key is found in
    default known_hosts files.
    """
    keys = get_default_remote_host_keys()
    if not keys.has_key(hostname):
        _logger.error('Remote server returned no host key!')
    elif not keys[hostname].has_key(key.get_name()):
        _logger.error('Remote server host key unknown!')
    elif keys[hostname][key.get_name()] != key:
        _logger.error('Remote server host key changed!')
    else:
        _logger.info('Remote server host key is valid.')
        return True
    return False

def open_socket(hostname, port):
    """Open a connection to the destination machine"""
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.connect((hostname, port))
        return sock
    except Exception:
        _logger.exception('Cannot open connection to %s:%d' % (
                hostname, port))
        raise

def get_default_private_RSA():
    """Returns the private RSA key if it exists and can
    be used without a password.
    """
    path = os.path.join(os.environ['HOME'], '.ssh', 'id_rsa')
    try:
        key = paramiko.RSAKey.from_private_key_file(path)
        return key
    except paramiko.PasswordRequiredException:
        _logger.info('could not auth passwordless with RSA key %s' % path)

def get_default_private_DSA():
    """Returns the private DSA key if it exists and can
    be used without a password.
    """
    path = os.path.join(os.environ['HOME'], '.ssh', 'id_dsa')
    try:
        key = paramiko.DSAKey.from_private_key_file(path)
        return key
    except paramiko.PasswordRequiredException:
        _logger.info('could not auth passwordless with DSA key %s' % path)

def get_default_private_key():
    """Returns a private key if one exists and can
    be used without a password.
    """
    key = get_default_private_RSA()
    if None == key:
        key = get_default_private_DSA()
    return key

def connect_to_host(conf_vars):
    """Open a transport connection and authentificate.

    Return a reference to the open connection.
    """
    port = _DEFAULT_SSH_PORT
    host = conf_vars['remotehostname']
    username = conf_vars['remoteusername']

    sock = open_socket(host, port)
    t = paramiko.Transport(sock)
    try:
        try:
            t.start_client()
        except paramiko.SSHException:
            _logger.error(
                    'Cannot negociate SSH protocol with %s:%d.', host, port)
            raise
        remotekey = t.get_remote_server_key()
        if not is_remote_server_key_known(remotekey, host):
            raise RuntimeError('Cannot validate remote host key')
        key = get_default_private_key()
        t.auth_publickey(username, key)
        return t
    except:
        _logger.exception('Connection to %s:%d failed.', host, port)
        t.close()
        raise

def sftp_mkdir_if_not_exits(sftp, dir):
    """If path does not exist mkdir it.
    """
    try:
        sftp.chdir(dir)
    except IOError:
        sftp.mkdir(dir)
        sftp.chdir(dir)

def sftp_transfer_files(sftp, files, conf_vars):
    """Transfers all existing files from the 'files' list
    through sftp.
    """
    for fpath in files:
        # extract the name of the file from the path
        fname = os.path.basename(fpath)
        # append the name to the destination
        fdest = os.path.join(conf_vars['resultsdest'], fname)
        if not os.path.isfile(fpath):
            _logger.info('Could not find file [%s] to transfer' % fpath)
            sftp.open(fdest, 'w').write('-- (could not locate this file on the test vm) --')
        else:
            # actually transfer the files
            _logger.debug('PUTTING: local:[%s] remote:[%s]' % (fpath, fdest))
            sftp.put(fpath, fdest)

def _get_unzipped_local_path(filename):
    """The callback script and filename are sent in a .zip to the
    tester machine. When unzipped they should be in the same directory.
    """
    d = os.path.dirname(sys.argv[0])
    return os.path.normpath(os.path.join(d, filename))

def get_unzipped_local_storer_config():
    """Get the path of the local storer config file."""
    return _get_unzipped_local_path('storer')

def _config_variables(config_file, section_name):
    """Return a dictionary with values from the config_path file.

    NB:  the keys will be all lowercase!
    """
    _config = ConfigParser.RawConfigParser()
    with open(config_file) as handle:
        _config.readfp(handle)
    return dict(_config.items(section_name))

def get_deadline(conf_vars):
    """Return the deadline for the current homework"""
    assignment = conf_vars['assignment']
    storer_config = get_unzipped_local_storer_config()
    # XXX the 'assignment ' + on the next line is a HACK!
    # in the storer config the assignments are stored as 'assignment 1-minishell-linux'
    # but our assignment variable is just '1-minishell-linux'.
    # we shouldn't hardcode 'assignment ' here!
    storer_assignment_vars = _config_variables(storer_config, 'assignment ' + assignment)
    return storer_assignment_vars['deadline']

def send_results_and_notify(files, conf_vars):
    """Opens a connection, transfers files, and
    TODO: calls a script on the storer.
    """
    try:
        t = connect_to_host(conf_vars)
    except:
        _logger.exception('could not connect to remote host')
        return
    try:
        if len(files) > 0:
            sftp = paramiko.SFTPClient.from_transport(t)
            sftp_mkdir_if_not_exits(sftp, conf_vars['resultsdest'])
            sftp_transfer_files(sftp, files, conf_vars)
    except:
        _logger.exception('error while transferring files with paramiko')
    finally:
        t.close()

def print_usage():
    print 'Usage: %s config_file [files to send to storer]' % sys.argv[0]

def run_callback(config_file, files):
    _setup_logging()
    conf_vars = _config_variables(config_file, 'Assignment')
    send_results_and_notify(list(files), conf_vars)

def main():
    if len(sys.argv) < 2:
        print 'No config file given'
        print_usage()
        exit(1)

    config_file = sys.argv[1]
    # skip first two: the script name and the config file :)
    files = sys.argv[2:]
    run_callback(config_file, files)

if __name__ == "__main__":
    main()
<commit_msg>Removed validation of remote host key in order to allow tester on localhost<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Callback script executed on the tester machine
"""
from __future__ import with_statement

import os
import socket
import paramiko
import sys
import ConfigParser

from . import vmlogging

_DEFAULT_SSH_PORT = 22
_logger = vmlogging.create_module_logger('callback')

def _setup_logging():
    """Instruct paramiko to log stuff.
    Should be disabled in production?
    """
    paramiko.util.log_to_file('callback_sftp.log')

def get_default_remote_host_keys():
    """Search for host keys in default paths
    """
    # search two default paths (Linux & Windows)
    search_paths = ['~/.ssh/known_hosts', '~/ssh/known_hosts']
    paths = map(lambda x : os.path.expanduser(x), search_paths)
    for path in paths:
        try:
            host_keys = paramiko.util.load_host_keys(path)
            return host_keys
        except:
            _logger.info('Cannot open known_hosts file [%s]' % path)
    else:
        # on failure return an empty key dictionary
        return {}

def is_remote_server_key_known(key, hostname):
    """Return True if the remote hostname server key is found in
    default known_hosts files.
    """
    keys = get_default_remote_host_keys()
    if not keys.has_key(hostname):
        _logger.error('Remote server returned no host key!')
    elif not keys[hostname].has_key(key.get_name()):
        _logger.error('Remote server host key unknown!')
    elif keys[hostname][key.get_name()] != key:
        _logger.error('Remote server host key changed!')
    else:
        _logger.info('Remote server host key is valid.')
        return True
    return False

def open_socket(hostname, port):
    """Open a connection to the destination machine"""
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.connect((hostname, port))
        return sock
    except Exception:
        _logger.exception('Cannot open connection to %s:%d' % (
                hostname, port))
        raise

def get_default_private_RSA():
    """Returns the private RSA key if it exists and can
    be used without a password.
    """
    path = os.path.join(os.environ['HOME'], '.ssh', 'id_rsa')
    try:
        key = paramiko.RSAKey.from_private_key_file(path)
        return key
    except paramiko.PasswordRequiredException:
        _logger.info('could not auth passwordless with RSA key %s' % path)

def get_default_private_DSA():
    """Returns the private DSA key if it exists and can
    be used without a password.
    """
    path = os.path.join(os.environ['HOME'], '.ssh', 'id_dsa')
    try:
        key = paramiko.DSAKey.from_private_key_file(path)
        return key
    except paramiko.PasswordRequiredException:
        _logger.info('could not auth passwordless with DSA key %s' % path)

def get_default_private_key():
    """Returns a private key if one exists and can
    be used without a password.
    """
    key = get_default_private_RSA()
    if None == key:
        key = get_default_private_DSA()
    return key

def connect_to_host(conf_vars):
    """Open a transport connection and authentificate.

    Return a reference to the open connection.
    """
    port = _DEFAULT_SSH_PORT
    host = conf_vars['remotehostname']
    username = conf_vars['remoteusername']

    sock = open_socket(host, port)
    t = paramiko.Transport(sock)
    try:
        try:
            t.start_client()
        except paramiko.SSHException:
            _logger.error(
                    'Cannot negociate SSH protocol with %s:%d.', host, port)
            raise
        remotekey = t.get_remote_server_key()
        #if not is_remote_server_key_known(remotekey, host):
        #    raise RuntimeError('Cannot validate remote host key')
        key = get_default_private_key()
        t.auth_publickey(username, key)
        return t
    except:
        _logger.exception('Connection to %s:%d failed.', host, port)
        t.close()
        raise

def sftp_mkdir_if_not_exits(sftp, dir):
    """If path does not exist mkdir it.
    """
    try:
        sftp.chdir(dir)
    except IOError:
        sftp.mkdir(dir)
        sftp.chdir(dir)

def sftp_transfer_files(sftp, files, conf_vars):
    """Transfers all existing files from the 'files' list
    through sftp.
    """
    for fpath in files:
        # extract the name of the file from the path
        fname = os.path.basename(fpath)
        # append the name to the destination
        fdest = os.path.join(conf_vars['resultsdest'], fname)
        if not os.path.isfile(fpath):
            _logger.info('Could not find file [%s] to transfer' % fpath)
            sftp.open(fdest, 'w').write('-- (could not locate this file on the test vm) --')
        else:
            # actually transfer the files
            _logger.debug('PUTTING: local:[%s] remote:[%s]' % (fpath, fdest))
            sftp.put(fpath, fdest)

def _get_unzipped_local_path(filename):
    """The callback script and filename are sent in a .zip to the
    tester machine. When unzipped they should be in the same directory.
    """
    d = os.path.dirname(sys.argv[0])
    return os.path.normpath(os.path.join(d, filename))

def get_unzipped_local_storer_config():
    """Get the path of the local storer config file."""
    return _get_unzipped_local_path('storer')

def _config_variables(config_file, section_name):
    """Return a dictionary with values from the config_path file.

    NB:  the keys will be all lowercase!
    """
    _config = ConfigParser.RawConfigParser()
    with open(config_file) as handle:
        _config.readfp(handle)
    return dict(_config.items(section_name))

def get_deadline(conf_vars):
    """Return the deadline for the current homework"""
    assignment = conf_vars['assignment']
    storer_config = get_unzipped_local_storer_config()
    # XXX the 'assignment ' + on the next line is a HACK!
    # in the storer config the assignments are stored as 'assignment 1-minishell-linux'
    # but our assignment variable is just '1-minishell-linux'.
    # we shouldn't hardcode 'assignment ' here!
    storer_assignment_vars = _config_variables(storer_config, 'assignment ' + assignment)
    return storer_assignment_vars['deadline']

def send_results_and_notify(files, conf_vars):
    """Opens a connection, transfers files, and
    TODO: calls a script on the storer.
    """
    try:
        t = connect_to_host(conf_vars)
    except:
        _logger.exception('could not connect to remote host')
        return
    try:
        if len(files) > 0:
            sftp = paramiko.SFTPClient.from_transport(t)
            sftp_mkdir_if_not_exits(sftp, conf_vars['resultsdest'])
            sftp_transfer_files(sftp, files, conf_vars)
    except:
        _logger.exception('error while transferring files with paramiko')
    finally:
        t.close()

def print_usage():
    print 'Usage: %s config_file [files to send to storer]' % sys.argv[0]

def run_callback(config_file, files):
    _setup_logging()
    conf_vars = _config_variables(config_file, 'Assignment')
    send_results_and_notify(list(files), conf_vars)

def main():
    if len(sys.argv) < 2:
        print 'No config file given'
        print_usage()
        exit(1)

    config_file = sys.argv[1]
    # skip first two: the script name and the config file :)
    files = sys.argv[2:]
    run_callback(config_file, files)

if __name__ == "__main__":
    main()
<|endoftext|>


<commit_before>#!/usr/bin/env python
################################################################
#
#        Copyright 2013, Big Switch Networks, Inc.
#
# Licensed under the Eclipse Public License, Version 1.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.eclipse.org/legal/epl-v10.html
#
# 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.
#
################################################################
#
#
# Build the ucli_module_t structure based on functions
# define in the given source files.
#
################################################################
import os
import sys
import re
import pprint
import infra
import wod

#
# Find all ucli command handlers in the given source file.
#
# They all have the format ucli_status_t (name)(ucli_context_t* [var])
#
source = None
with open(sys.argv[1], "r") as f:
    source = f.read()

matches = re.findall("(?P<condition>#if.*?\n)?(?:\s*static\s*)?ucli_status_t\s+(?P<function>[_a-zA-Z]\w*)\(\s*ucli_context_t\s*\*\s*[_a-zA-Z]\w*\s*\)", source);

modules = {}
for m in matches:
    # Handler naming format is:
    #
    # [prefix]_ucli_[moduleName]_[command]
    fields = m[1].split("_");
    prefix = fields[0]
    if fields[1] != "ucli":
        raise Exception("Bad format for handler name: %s" % (m))
    module = fields[2];

    if not (prefix, module) in modules:
        modules[(prefix, module)] = []

    d = {}
    d['name'] = m[1]
    d['condition'] = None
    if m[0]:
        d['condition'] = m[0].replace("/*","").replace("*/","").replace("condition:","").strip()

    modules[(prefix,module)].append(d)

# Regenerate the handler tables
start = "/* <auto.ucli.handlers.start> */"
end   = "/* <auto.ucli.handlers.end> */"

s = start
s += """
/******************************************************************************
 *
 * These handler table(s) were autogenerated from the symbols in this
 * source file.
 *
 *****************************************************************************/
"""

for ((p,m), lst) in modules.iteritems():
    s += "static ucli_command_handler_f %s_ucli_%s_handlers__[] = \n" % (p,m)
    s += "{\n"
    for h in lst:
        if h['condition']:
            s += "%s\n" % h['condition']
        s+= "    %s, \n" % (h['name'])
        if h['condition']:
            s += "#endif\n"

    s += "    NULL\n"
    s += "};\n"
s += "/******************************************************************************/\n"
s += end

# Replace old handler tables
rstart = re.sub("\*", "\\\*", start)
rend = re.sub("\*", "\\\*", end)
expr = rstart + ".*" + rend
source = re.sub(expr, s, source, flags=re.DOTALL)
wod.write_on_diff(sys.argv[1], source)

<commit_msg>Remove trailing space.<commit_after>#!/usr/bin/env python
################################################################
#
#        Copyright 2013, Big Switch Networks, Inc.
#
# Licensed under the Eclipse Public License, Version 1.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.eclipse.org/legal/epl-v10.html
#
# 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.
#
################################################################
#
#
# Build the ucli_module_t structure based on functions
# define in the given source files.
#
################################################################
import os
import sys
import re
import pprint
import infra
import wod

#
# Find all ucli command handlers in the given source file.
#
# They all have the format ucli_status_t (name)(ucli_context_t* [var])
#
source = None
with open(sys.argv[1], "r") as f:
    source = f.read()

matches = re.findall("(?P<condition>#if.*?\n)?(?:\s*static\s*)?ucli_status_t\s+(?P<function>[_a-zA-Z]\w*)\(\s*ucli_context_t\s*\*\s*[_a-zA-Z]\w*\s*\)", source);

modules = {}
for m in matches:
    # Handler naming format is:
    #
    # [prefix]_ucli_[moduleName]_[command]
    fields = m[1].split("_");
    prefix = fields[0]
    if fields[1] != "ucli":
        raise Exception("Bad format for handler name: %s" % (m))
    module = fields[2];

    if not (prefix, module) in modules:
        modules[(prefix, module)] = []

    d = {}
    d['name'] = m[1]
    d['condition'] = None
    if m[0]:
        d['condition'] = m[0].replace("/*","").replace("*/","").replace("condition:","").strip()

    modules[(prefix,module)].append(d)

# Regenerate the handler tables
start = "/* <auto.ucli.handlers.start> */"
end   = "/* <auto.ucli.handlers.end> */"

s = start
s += """
/******************************************************************************
 *
 * These handler table(s) were autogenerated from the symbols in this
 * source file.
 *
 *****************************************************************************/
"""

for ((p,m), lst) in modules.iteritems():
    s += "static ucli_command_handler_f %s_ucli_%s_handlers__[] = \n" % (p,m)
    s += "{\n"
    for h in lst:
        if h['condition']:
            s += "%s\n" % h['condition']
        s+= "    %s,\n" % (h['name'])
        if h['condition']:
            s += "#endif\n"

    s += "    NULL\n"
    s += "};\n"
s += "/******************************************************************************/\n"
s += end

# Replace old handler tables
rstart = re.sub("\*", "\\\*", start)
rend = re.sub("\*", "\\\*", end)
expr = rstart + ".*" + rend
source = re.sub(expr, s, source, flags=re.DOTALL)
wod.write_on_diff(sys.argv[1], source)

<|endoftext|>


<commit_before>import numpy as np

from .base import ClassifierMixin
from .svm.base import BaseLibLinear
from .svm import _liblinear

class LogisticRegression(BaseLibLinear, ClassifierMixin):
    """
    Logistic Regression.

    Implements L1 and L2 regularized logistic regression.

    Parameters
    ----------
    X : array-like, shape = [n_samples, n_features]
        Training vector, where n_samples in the number of samples and
        n_features is the number of features.
    Y : array, shape = [n_samples]
        Target vector relative to X

    penalty : string, 'l1' or 'l2'
        Used to specify the norm used in the penalization

    C : float
        Specifies the strength of the regularization. The smaller it is
        the bigger in the regularization.

    fit_intercept : bool, default: True
        Specifies if a constant (a.k.a. bias or intercept) should be
        added the decision function

    Attributes
    ----------

    `coef_` : array, shape = [n_classes-1, n_features]
        Coefficient of the features in the decision function.

    `intercept_` : array, shape = [n_classes-1]
        intercept (a.k.a. bias) added to the decision function.
        It is available only when parameter intercept is set to True

    Methods
    -------
    fit(X, Y) : self
        Fit the model

    predict(X) : array
        Predict using the model.

    See also
    --------
    LinearSVC

    References
    ----------
    LIBLINEAR -- A Library for Large Linear Classification
    http://www.csie.ntu.edu.tw/~cjlin/liblinear/
    """

    def __init__(self, penalty='l2', eps=1e-4, C=1.0, fit_intercept=True):
        super(LogisticRegression, self).__init__ (penalty=penalty, loss='lr',
            dual=False, eps=eps, C=C, fit_intercept=fit_intercept)

    def predict_proba(self, T):
        T = np.asanyarray(T, dtype=np.float64, order='C')
        return _liblinear.predict_prob_wrap(T, self.raw_coef_, self._get_solver_type(),
                                      self.eps, self.C,
                                      self._weight_label,
                                      self._weight, self.label_,
                                      self._get_bias())
<commit_msg>FIX: quick fix in predict_proba in LogisticRegression<commit_after>import numpy as np

from .base import ClassifierMixin
from .svm.base import BaseLibLinear
from .svm import _liblinear

class LogisticRegression(BaseLibLinear, ClassifierMixin):
    """
    Logistic Regression.

    Implements L1 and L2 regularized logistic regression.

    Parameters
    ----------
    X : array-like, shape = [n_samples, n_features]
        Training vector, where n_samples in the number of samples and
        n_features is the number of features.
    Y : array, shape = [n_samples]
        Target vector relative to X

    penalty : string, 'l1' or 'l2'
        Used to specify the norm used in the penalization

    C : float
        Specifies the strength of the regularization. The smaller it is
        the bigger in the regularization.

    fit_intercept : bool, default: True
        Specifies if a constant (a.k.a. bias or intercept) should be
        added the decision function

    Attributes
    ----------

    `coef_` : array, shape = [n_classes-1, n_features]
        Coefficient of the features in the decision function.

    `intercept_` : array, shape = [n_classes-1]
        intercept (a.k.a. bias) added to the decision function.
        It is available only when parameter intercept is set to True

    Methods
    -------
    fit(X, Y) : self
        Fit the model

    predict(X) : array
        Predict using the model.

    See also
    --------
    LinearSVC

    References
    ----------
    LIBLINEAR -- A Library for Large Linear Classification
    http://www.csie.ntu.edu.tw/~cjlin/liblinear/
    """

    def __init__(self, penalty='l2', eps=1e-4, C=1.0, fit_intercept=True):
        super(LogisticRegression, self).__init__ (penalty=penalty, loss='lr',
            dual=False, eps=eps, C=C, fit_intercept=fit_intercept)

    def predict_proba(self, T):
        T = np.asanyarray(T, dtype=np.float64, order='C')
        probas = _liblinear.predict_prob_wrap(T, self.raw_coef_,
                                      self._get_solver_type(),
                                      self.eps, self.C,
                                      self._weight_label,
                                      self._weight, self.label_,
                                      self._get_bias())
        return probas[:,np.argsort(self.label_)]
<|endoftext|>


<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2012 Toomore Chiang, http://toomore.net/
#
# 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.

from datetime import datetime
from .tw_time import TWTime
import csv
import os

class twseopen(object):
    ''' 判斷當日是否開市 '''
    def __init__(self):
        ''' 載入相關檔案 '''
        self.__ocdate = self.__loaddate()

    def Dday(self, time):
        ''' 指定日期 '''
        if type(time) == type(TWTime().now):
            self.twtime = TWTime().now
        elif type(time) == type(TWTime().date):
            self.twtime = TWTime().date
        else:
            pass
        return self.__caldata(time)

    def __loaddate(self):
        ''' 載入檔案
            檔案依據 http://www.twse.com.tw/ch/trading/trading_days.php
        '''
        ld = csv.reader(
                open(os.path.join(os.path.dirname(__file__), 'opendate.csv')))
        re = {}
        re['close'] = []
        re['open'] = []
        for i in ld:
            if i[1] == '0':  # 0 = 休市
                re['close'] += [datetime.strptime(i[0], '%Y/%m/%d').date()]
            elif i[1] == '1':  # 1 = 開市
                re['open'] += [datetime.strptime(i[0], '%Y/%m/%d').date()]
            else:
                pass
        return re

    def __caldata(self, time):
        ''' Market open or not.
            回傳 True：開市，False：休市。
        '''
        if time.date() in self.__ocdate['close']:  # 判對是否為法定休市
            return False
        elif time.date() in self.__ocdate['open']:  # 判對是否為法定開市
            return True
        else:
            if time.weekday() <= 4:  # 判斷是否為平常日開市
                return True
            else:
                return False
<commit_msg>Fixed #5 #6 in twseopen.<commit_after># -*- coding: utf-8 -*-
''' TWSE open date '''
# Copyright (c) 2012 Toomore Chiang, http://toomore.net/
#
# 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.

from .tw_time import TWTime
from datetime import datetime
import csv
import os

class TWSEOpen(object):
    ''' 判斷當日是否開市 '''
    def __init__(self):
        ''' 載入相關檔案 '''
        self.__ocdate = self.__loaddate()
        self.twtime = ''

    def d_day(self, time):
        ''' 指定日期 '''
        if type(time) == type(TWTime().now):
            self.twtime = TWTime().now
        elif type(time) == type(TWTime().date):
            self.twtime = TWTime().date
        else:
            pass
        return self.__caldata(time)

    @staticmethod
    def __loaddate():
        ''' 載入檔案
            檔案依據 http://www.twse.com.tw/ch/trading/trading_days.php
        '''
        csv_path = os.path.join(os.path.dirname(__file__), 'opendate.csv')
        with open(csv_path) as csv_file:
            csv_data = csv.reader(csv_file)
            result = {}
            result['close'] = []
            result['open'] = []
            for i in csv_data:
                if i[1] == '0':  # 0 = 休市
                    result['close'] += [datetime.strptime(i[0], '%Y/%m/%d').date()]
                elif i[1] == '1':  # 1 = 開市
                    result['open'] += [datetime.strptime(i[0], '%Y/%m/%d').date()]
                else:
                    pass
            return result

    def __caldata(self, time):
        ''' Market open or not.
            回傳 True：開市，False：休市。
        '''
        if time.date() in self.__ocdate['close']:  # 判對是否為法定休市
            return False
        elif time.date() in self.__ocdate['open']:  # 判對是否為法定開市
            return True
        else:
            if time.weekday() <= 4:  # 判斷是否為平常日開市
                return True
            else:
                return False
<|endoftext|>


<commit_before>"""
Filename:     run_plot_zonal_mean.py
Author:       Damien Irving, irving.damien@gmail.com
Description:  Create the command line entry to run plot_zonal_mean.py

"""

# Import general Python modules

import sys, os, pdb
import argparse
import pandas
import glob

# Define functions

def find_files(df, run, alt_experiment, experiment, var, model, tscale, match=0, fx_physics=None, fixed=False):
    """Define the file names."""

    if var == 'tas':
        file_start = 'tas-global-mean'
        file_end = 'all.nc'
    else:
        file_start = var
        file_end = '.nc'

    dir_end = 'latest/fixed' if fixed else 'latest'

    df_selection = df.loc[(df['model'] == model) & (df['alt_experiment'] == alt_experiment)]
    df_selection = df_selection[df_selection.run.str.contains(run+'i')]

    assert df_selection.shape[0] in [0, 1, 2]
    if df_selection.shape[0] == 2:
        row_index = match
    else:
        row_index = 0

    if df_selection.shape[0] == 0:
        files = ' '
    else:
        data_dir = df_selection[var].values[row_index]
        if data_dir in ['ua6', 'r87/dbi599']:
            run = df_selection['run'].values[row_index]
            if file_start == 'tas-global-mean':
                data_dir = 'r87/dbi599'
                realm = 'atmos'
            else:
                realm = 'ocean'
            if fx_physics:
                run = 'r0i0'+fx_physics
            file_list = glob.glob('/g/data/%s/DRSv2/CMIP5/%s/%s/%s/%s/%s/%s/%s/%s_*%s' %(data_dir, model, experiment, tscale, realm, run, var, dir_end, file_start, file_end))
            files = " ".join(file_list)
        else:
            files = ' '

    return files

def main(inargs, basin, run):
    """Run the program."""

    command_list = ['python ../visualisation/plot_zonal_mean.py']
    aggregator = 'zi' if inargs.area else 'zm'
    command_list.append('/g/data/r87/dbi599/figures/%s-%s/%s-%s_Oyr_%s_piControl-historical-GHG-AA_%s_%s_clim-198601-200512_trend-all.png'  %(inargs.variable, aggregator, inargs.variable, aggregator, inargs.model, run, basin))
    command_list.append(inargs.standard_name)
    command_list.append(inargs.model)
    command_list.append(run)
    command_list.append(basin)

    df = pandas.read_csv(inargs.data_locs)

    for alt_experiment in ['historical', 'historicalGHG', 'historicalAA', 'historicalnoAA', 'piControl']:
        if alt_experiment in ['historicalAA', 'historicalnoAA']:
            experiment = 'historicalMisc'
        else:
            experiment = alt_experiment

        if experiment == 'piControl':
            exp_run = 'r1'
        elif (experiment == 'historicalMisc') and (inargs.model == 'FGOALS-g2'):
            exp_run = 'r2'
        else:
            exp_run = run

        # Variable data files
        command_list.append('--' + alt_experiment.lower() + '_files')
        if inargs.variable == 'pe':
            if alt_experiment == 'historicalAA':
                physics = inargs.aa_physics
            elif alt_experiment == 'historicalnoAA':
                physics = inargs.noaa_physics
            else:
                physics = 1
            file_list = glob.glob('/g/data/r87/dbi599/DRSv2/CMIP5/%s/%s/mon/ocean/%si1p%s/pe/latest/pe_*.nc' %(inargs.model, experiment, exp_run, str(physics)))
            files = " ".join(file_list)
        else:
            files = find_files(df, exp_run, alt_experiment, experiment, inargs.variable, inargs.model, 'mon', match=inargs.match, fixed=inargs.fixed)
        command_list.append(files)

        # Global mean temperature data files
        if alt_experiment != 'piControl':
            command_list.append('--' + alt_experiment.lower() + '_tas_file')
            tas_file = find_files(df, exp_run, alt_experiment, experiment, 'tas', inargs.model, 'yr', match=inargs.match)
            command_list.append(tas_file)

        # Cell area and basin data files
        if alt_experiment == 'historicalAA' and inargs.model == 'CSIRO-Mk3-6-0':
            assert inargs.aa_physics, "Need to provie --aa_physics"
            fx_physics = 'p' + str(inargs.aa_physics)
        elif alt_experiment == 'historicalnoAA' and inargs.model == 'CSIRO-Mk3-6-0':
            assert inargs.noaa_physics, "Need to provie --noaa_physics"
            fx_physics = 'p' + str(inargs.noaa_physics)
        else:
            fx_physics = 'p0'

        if inargs.historical_fx:
            fx_alt_experiment = 'historical'
            fx_experiment = 'historical'
        else:
            fx_alt_experiment = alt_experiment
            fx_experiment = experiment

        area_file = find_files(df, exp_run, fx_alt_experiment, fx_experiment, 'areacello', inargs.model, 'fx', fx_physics=fx_physics)
        command_list.append('--' + alt_experiment.lower() + '_area_file')
        command_list.append(area_file)

        if not inargs.exclude_basin:
            basin_file = find_files(df, exp_run, fx_alt_experiment, fx_experiment, 'basin', inargs.model, 'fx', fx_physics=fx_physics)
            command_list.append('--' + alt_experiment.lower() + '_basin_file')
            command_list.append(basin_file)

    if inargs.legloc:
        legloc = inargs.legloc
    elif inargs.variable == 'hfds':
        legloc = 8
    elif inargs.variable == 'pe':
        legloc = 3
    elif inargs.variable == 'tauuo':
        legloc = 9
    else:
        legloc = 2
    command_list.append('--legloc ' + str(legloc))

    if inargs.area:
        command_list.append('--area_adjust ')

    final_command = " ".join(command_list)
    print(final_command)
    if inargs.execute:
        os.system(final_command)

if __name__ == '__main__':

    extra_info ="""
author:
  Damien Irving, irving.damien@gmail.com

"""

    description='Create the command line entry to run plot_zonal_mean.py'
    parser = argparse.ArgumentParser(description=description,
                                     epilog=extra_info,
                                     argument_default=argparse.SUPPRESS,
                                     formatter_class=argparse.RawDescriptionHelpFormatter)

    parser.add_argument("data_locs", type=str, help="File detailing where the data is located at NCI")
    parser.add_argument("variable", type=str, help="Variable (e.g. hfds, tauuo)")
    parser.add_argument("standard_name", type=str, help="e.g. surface_downward_x_stress")
    parser.add_argument("model", type=str, help="Model to process")
    parser.add_argument("runs", type=str, nargs='*', help="Runs to process (e.g. r1 r2)")

    parser.add_argument("--execute", action="store_true", default=False,
                        help="Switch to have this script execute the make command rather than printing to screen")

    parser.add_argument("--exclude_basin", action="store_true", default=False,
                        help="Leave out basin files [default=False]")
    parser.add_argument("--historical_fx", action="store_true", default=False,
                        help="Use the historical areacello and basin files for GHG is AA too [default=False]")

    parser.add_argument("--legloc", type=int, default=None,
                        help="Legend location")
    parser.add_argument("--aa_physics", type=int, default=None,
                        help="Need to supply this for the P-E plot and CSIRO other plots")
    parser.add_argument("--noaa_physics", type=int, default=None,
                        help="Need to supply this for the P-E plot and CSIRO other plots")
    parser.add_argument("--match", type=int, default=0,
                        help="Pick the first (index 0) or second (index 1) match - useful for GISS models with two p runs")
    parser.add_argument("--area", action="store_true", default=False,
                        help="Add the area adjustment flag")

    parser.add_argument("--fixed", action="store_true", default=False,
                        help="Look for files in a directory labelled fixed")

    args = parser.parse_args()

    for basin in ('globe', 'atlantic', 'indian', 'pacific'):
        for run in args.runs:
            main(args, basin, run)
<commit_msg>Added handling of GISS GHG physics<commit_after>"""
Filename:     run_plot_zonal_mean.py
Author:       Damien Irving, irving.damien@gmail.com
Description:  Create the command line entry to run plot_zonal_mean.py

"""

# Import general Python modules

import sys, os, pdb
import argparse
import pandas
import glob

# Define functions

def find_files(df, run, alt_experiment, experiment, var, model, tscale, match=0, fx_physics=None, fixed=False):
    """Define the file names."""

    if var == 'tas':
        file_start = 'tas-global-mean'
        file_end = 'all.nc'
    else:
        file_start = var
        file_end = '.nc'

    dir_end = 'latest/fixed' if fixed else 'latest'

    df_selection = df.loc[(df['model'] == model) & (df['alt_experiment'] == alt_experiment)]
    df_selection = df_selection[df_selection.run.str.contains(run+'i')]

    assert df_selection.shape[0] in [0, 1, 2]
    if df_selection.shape[0] == 2:
        row_index = match
    else:
        row_index = 0

    if df_selection.shape[0] == 0:
        files = ' '
    else:
        data_dir = df_selection[var].values[row_index]
        if data_dir in ['ua6', 'r87/dbi599']:
            run = df_selection['run'].values[row_index]
            if file_start == 'tas-global-mean':
                data_dir = 'r87/dbi599'
                realm = 'atmos'
            else:
                realm = 'ocean'
            if fx_physics:
                run = 'r0i0'+fx_physics
            file_list = glob.glob('/g/data/%s/DRSv2/CMIP5/%s/%s/%s/%s/%s/%s/%s/%s_*%s' %(data_dir, model, experiment, tscale, realm, run, var, dir_end, file_start, file_end))
            files = " ".join(file_list)
        else:
            files = ' '

    return files

def main(inargs, basin, run):
    """Run the program."""

    command_list = ['/g/data/r87/dbi599/miniconda3/envs/ocean/bin/python ../visualisation/plot_zonal_mean.py']
    aggregator = 'zi' if inargs.area else 'zm'
    command_list.append('/g/data/r87/dbi599/figures/%s-%s/%s-%s_Oyr_%s_piControl-historical-GHG-AA_%si1p%s_%s_clim-198601-200512_trend-all.png'  %(inargs.variable, aggregator, inargs.variable, aggregator, inargs.model, run, inargs.physics, basin))
    command_list.append(inargs.standard_name)
    command_list.append(inargs.model)
    command_list.append(run)
    command_list.append(basin)

    df = pandas.read_csv(inargs.data_locs)

    for alt_experiment in ['historical', 'historicalGHG', 'historicalAA', 'historicalnoAA', 'piControl']:
        if alt_experiment in ['historicalAA', 'historicalnoAA']:
            experiment = 'historicalMisc'
        else:
            experiment = alt_experiment

        if experiment == 'piControl':
            exp_run = 'r1'
        elif (experiment == 'historicalMisc') and (inargs.model == 'FGOALS-g2'):
            exp_run = 'r2'
        else:
            exp_run = run

        # Variable data files
        command_list.append('--' + alt_experiment.lower() + '_files')
        if inargs.variable == 'pe':
            if alt_experiment == 'historicalAA':
                physics = inargs.aa_physics
            elif alt_experiment == 'historicalnoAA':
                physics = inargs.noaa_physics
            elif (experiment == 'historicalGHG') and inargs.ghg_physics:
                physics = inargs.ghg_physics
            else:
                physics = inargs.physics
            file_list = glob.glob('/g/data/r87/dbi599/DRSv2/CMIP5/%s/%s/mon/ocean/%si1p%s/pe/latest/pe_*.nc' %(inargs.model, experiment, exp_run, str(physics)))
            files = " ".join(file_list)
        else:
            files = find_files(df, exp_run, alt_experiment, experiment, inargs.variable, inargs.model, 'mon', match=inargs.match, fixed=inargs.fixed)
        command_list.append(files)

        # Global mean temperature data files
        if alt_experiment != 'piControl':
            command_list.append('--' + alt_experiment.lower() + '_tas_file')
            tas_file = find_files(df, exp_run, alt_experiment, experiment, 'tas', inargs.model, 'yr', match=inargs.match)
            command_list.append(tas_file)

        # Cell area and basin data files
        if alt_experiment == 'historicalAA' and inargs.model == 'CSIRO-Mk3-6-0':
            assert inargs.aa_physics, "Need to provie --aa_physics"
            fx_physics = 'p' + str(inargs.aa_physics)
        elif alt_experiment == 'historicalnoAA' and inargs.model == 'CSIRO-Mk3-6-0':
            assert inargs.noaa_physics, "Need to provie --noaa_physics"
            fx_physics = 'p' + str(inargs.noaa_physics)
        else:
            fx_physics = 'p0'

        if inargs.historical_fx:
            fx_alt_experiment = 'historical'
            fx_experiment = 'historical'
        else:
            fx_alt_experiment = alt_experiment
            fx_experiment = experiment

        area_file = find_files(df, exp_run, fx_alt_experiment, fx_experiment, 'areacello', inargs.model, 'fx', fx_physics=fx_physics)
        command_list.append('--' + alt_experiment.lower() + '_area_file')
        command_list.append(area_file)

        if not inargs.exclude_basin:
            basin_file = find_files(df, exp_run, fx_alt_experiment, fx_experiment, 'basin', inargs.model, 'fx', fx_physics=fx_physics)
            command_list.append('--' + alt_experiment.lower() + '_basin_file')
            command_list.append(basin_file)

    if inargs.legloc:
        legloc = inargs.legloc
    elif inargs.variable == 'hfds':
        legloc = 8
    elif inargs.variable == 'pe':
        legloc = 3
    elif inargs.variable == 'tauuo':
        legloc = 9
    else:
        legloc = 2
    command_list.append('--legloc ' + str(legloc))

    if inargs.area:
        command_list.append('--area_adjust ')

    final_command = " ".join(command_list)
    print(final_command)
    if inargs.execute:
        os.system(final_command)

if __name__ == '__main__':

    extra_info ="""
author:
  Damien Irving, irving.damien@gmail.com

"""

    description='Create the command line entry to run plot_zonal_mean.py'
    parser = argparse.ArgumentParser(description=description,
                                     epilog=extra_info,
                                     argument_default=argparse.SUPPRESS,
                                     formatter_class=argparse.RawDescriptionHelpFormatter)

    parser.add_argument("data_locs", type=str, help="File detailing where the data is located at NCI")
    parser.add_argument("variable", type=str, help="Variable (e.g. hfds, tauuo)")
    parser.add_argument("standard_name", type=str, help="e.g. surface_downward_x_stress")
    parser.add_argument("model", type=str, help="Model to process")
    parser.add_argument("runs", type=str, nargs='*', help="Runs to process (e.g. r1 r2)")

    parser.add_argument("--execute", action="store_true", default=False,
                        help="Switch to have this script execute the make command rather than printing to screen")

    parser.add_argument("--exclude_basin", action="store_true", default=False,
                        help="Leave out basin files [default=False]")
    parser.add_argument("--historical_fx", action="store_true", default=False,
                        help="Use the historical areacello and basin files for GHG is AA too [default=False]")

    parser.add_argument("--legloc", type=int, default=None,
                        help="Legend location")
    parser.add_argument("--aa_physics", type=int, default=None,
                        help="Need to supply this for the P-E plot and CSIRO other plots")
    parser.add_argument("--noaa_physics", type=int, default=None,
                        help="Need to supply this for the P-E plot and CSIRO other plots")
    parser.add_argument("--ghg_physics", type=int, default=None,
                        help="Override the --physics option for historicalGHG (used for GISS-E2 models)")
    parser.add_argument("--physics", type=int, default=1,
                        help="physics")
    parser.add_argument("--match", type=int, default=0,
                        help="Pick the first (index 0) or second (index 1) match - useful for GISS models with two p runs")
    parser.add_argument("--area", action="store_true", default=False,
                        help="Add the area adjustment flag")

    parser.add_argument("--fixed", action="store_true", default=False,
                        help="Look for files in a directory labelled fixed")

    args = parser.parse_args()

    for basin in ('globe', 'atlantic', 'indian', 'pacific'):
        for run in args.runs:
            main(args, basin, run)
<|endoftext|>


<commit_before>"""
cryptography.py
Author: Payton
Credit: Avery, Daniel

Assignment:

Write and submit a program that encrypts and decrypts user data.

See the detailed requirements at https://github.com/HHS-IntroProgramming/Cryptography/blob/master/README.md
"""
associations = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 .,:;'\"/\\<>(){}[]-=_+?!"
let=[]
kelt=[]
comb = zip(list(let, kelt))
quit = False

while quit == False:
    i = input("Enter e to encrypt, d to decrypt, or q to quit: ")
    if i not in('e','d','q'):
        print("Did not understand command, try again.")
        i = input("Enter e to encrypt, d to decrypt, or q to quit: ")
    if i=="e":
        message=input("Message: ")
        key=input("Key: ")
        m=len(message)
        k=len(key)
        if m>k:
            count = key * int((m-(m%k))/k)
            trun = key[0:(m%k)]
            newkey = count + trun
            print(newkey, message)
        elif k>m:
            newkey = key[0:m]
            print(newkey, message)
        for x in (0,m-1):
            let.append(associations.find(message[x]))
        for y in range (0,m-1):
            kelt.append(associations.find(newkey[y]))
        for c in (0,len(let)):
            r = let[c] + kelt[c]
            comb.append(r)
    if i=="d":

        print(let)
    if i=="q":
        print("Goodbye!")
        quit = True

<commit_msg>Updated from Brython Server: 3/4/2016 2:30:50 PM<commit_after>"""
cryptography.py
Author: Payton
Credit: Avery, Daniel

Assignment:

Write and submit a program that encrypts and decrypts user data.

See the detailed requirements at https://github.com/HHS-IntroProgramming/Cryptography/blob/master/README.md
"""
associations = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 .,:;'\"/\\<>(){}[]-=_+?!"
let=[]
kelt=[]
comb =[]
quit = False

while quit == False:
    i = input("Enter e to encrypt, d to decrypt, or q to quit: ")
    if i not in('e','d','q'):
        print("Did not understand command, try again.")
        i = input("Enter e to encrypt, d to decrypt, or q to quit: ")
    if i=="e":
        message=input("Message: ")
        key=input("Key: ")
        m=len(message)
        k=len(key)
        if m>k:
            count = key * int((m-(m%k))/k)
            trun = key[0:(m%k)]
            newkey = count + trun
            print(newkey, message)
        elif k>m:
            newkey = key[0:m]
            print(newkey, message)
        for x in (0,m-1):
            let.append(associations.find(message[x]))
        for y in range (0,m-1):
            kelt.append(associations.find(newkey[y]))
        for c in (0,len(let)):
            r = let[c] + kelt[c]
            comb.append(associations[r])
            print(comb)
    if i=="d":

        print(let)
    if i=="q":
        print("Goodbye!")
        quit = True

<|endoftext|>


<commit_before>"""
sources: http://stackoverflow.com/questions/306400/how-do-i-randomly-select-an-item-from-a-list-using-python, https://inventwithpython.com/chapter9.html, http://stackoverflow.com/questions/14667578/check-if-a-number-already-exist-in-a-list-in-python, mary feyrer, Glen Passow (game tester), http://stackoverflow.com/questions/7522533/how-can-i-turn-a-string-into-a-list-in-python, http://www.tutorialspoint.com/python/list_remove.htm, https://github.com/first20hours/google-10000-english, adam glueck, http://www.katrinerk.com/courses/python-worksheets/worksheet-reading-and-writing-files
"""
import random
import string
a=string.ascii_lowercase

choose=input("Type '1' if you want to guess the word. Type '2' if you want the computer to guess your word. ")

if choose=='2':
    newword=input("What is your word? ")
    newword=newword.lower()
    l=len(newword) #count the number of letters

    a2=list(a)
    letter=[]
    word=[] #creating a list of letters in newword
    guess=[]
    turns=0
    num=0

    for x in range(0,l):
        abc=newword[x]
        word.append(abc)

    if l>1:
        letter1="e"
        letter.append(letter1)
    if l==1:
        letter1="a"
        letter.append(letter1)
        if letter1==word[x]:
                guess.append(letter1)
        if letter1 not in word:
            turns=turns+1
            nextguess="i"
            print("Computer's guess = "+letter1+"   "+' '.join(guess) )
            letter1=nextguess
        if letter1 in word:
            print("Computer's guess = "+letter1+"   "+' '.join(guess) )
            print("The computer guessed your word.")
            num=2
            turns=8

    while num<1:
        for x in range(0,l):
            if letter1==word[x]:
                guess.append(letter1)
            else:
               guess.append('_')
        if letter1 not in word:
            turns=turns+1
        num=num+2
        print("Computer's guess = "+letter1+"   "+' '.join(guess) )

    while turns<7 and num>0:
        for x in a2:
            if x in letter:
                a2.remove(x)

        letter1=random.choice(a2)

        for x in range(0,l):
            if letter1==word[x]:
               guess[x]=letter1
            elif guess[x] not in a:
                guess[x]='_'

        if letter1 not in word:
            turns=turns+1
        print("Computer's guess = "+letter1+"   "+' '.join(guess) )

        if turns==7:
            print("You stumped the computer!")

        if word==guess:
            print("The computer guessed your word.")
            turns=100

elif choose=='1':
    words=[]
    w=open("google-10000-english-usa.txt")
    for x in w:
        words.append(x)

    newword=random.choice(words) #randomly select word
    print(newword)
    l=len(newword) #count the number of letters

    word=[] #creating a list of letters in newword
    for x in range(0,l-1):
        abc=newword[x]
        word.append(abc)

    letter1=input("number of spaces = "+str(l-1)+". After seven wrong guesses, you lose. First guess? ") #first letter guess

    while letter1 not in a:
        letter1=input("Invalid input. Please guess a lowercase letter.")

    guess=[]
    turns=0
    num=0

    while num<1:
        for x in range(0,l-1):
            if letter1==word[x]:
                guess.append(letter1)
            else:
               guess.append('_')
        if letter1 not in word:
            turns=turns+1
        num=num+2

    while turns<7 and num>0:

        while letter1 not in a:
            print("Invalid input. Please guess a lowercase letter.")

        letter1=input(' '.join(guess)+" Number of wrong guesses = "+str(turns)+". Next guess?")

        for x in range(0,l-1):
            if letter1==word[x]:
               guess[x]=letter1
            elif guess[x] not in a:
                guess[x]='_'

        if letter1 not in word:
            turns=turns+1

        if turns==7:
            print("The word was "+newword+". Game over.")

        if word==guess:
            print("The word is "+newword+". You won!")
            turns=100

else:
    print("Invalid input. Start over.")

<commit_msg>Updated from Brython Server: 5/3/2016 2:20:03 PM<commit_after>"""
sources: http://stackoverflow.com/questions/306400/how-do-i-randomly-select-an-item-from-a-list-using-python, https://inventwithpython.com/chapter9.html, http://stackoverflow.com/questions/14667578/check-if-a-number-already-exist-in-a-list-in-python, mary feyrer, Glen Passow (game tester), http://stackoverflow.com/questions/7522533/how-can-i-turn-a-string-into-a-list-in-python, http://www.tutorialspoint.com/python/list_remove.htm, https://github.com/first20hours/google-10000-english, adam glueck, http://www.katrinerk.com/courses/python-worksheets/worksheet-reading-and-writing-files
"""
import random
import string
a=string.ascii_lowercase

choose=input("Type '1' if you want to guess the word. Type '2' if you want the computer to guess your word. ")

if choose=='2':
    newword=input("What is your word? ")
    newword=newword.lower()
    l=len(newword) #count the number of letters

    a2=list(a)
    letter=[]
    word=[] #creating a list of letters in newword
    guess=[]
    turns=0
    num=0

    for x in range(0,l):
        abc=newword[x]
        word.append(abc)

    if l>1:
        letter1="e"
        letter.append(letter1)
    if l==1:
        letter1="a"
        letter.append(letter1)
        if letter1==word[x]:
                guess.append(letter1)
        if letter1 not in word:
            turns=turns+1
            nextguess="i"
            print("Computer's guess = "+letter1+"   "+' '.join(guess) )
            letter1=nextguess
        if letter1 in word:
            print("Computer's guess = "+letter1+"   "+' '.join(guess) )
            print("The computer guessed your word.")
            num=2
            turns=8

    while num<1:
        for x in range(0,l):
            if letter1==word[x]:
                guess.append(letter1)
            else:
               guess.append('_')
        if letter1 not in word:
            turns=turns+1
        num=num+2
        print("Computer's guess = "+letter1+"   "+' '.join(guess) )

    while turns<7 and num>0:
        for x in a2:
            if x in letter:
                a2.remove(x)

        letter1=random.choice(a2)

        for x in range(0,l):
            if letter1==word[x]:
               guess[x]=letter1
            elif guess[x] not in a:
                guess[x]='_'

        if letter1 not in word:
            turns=turns+1
        print("Computer's guess = "+letter1+"   "+' '.join(guess) )

        if turns==7:
            print("You stumped the computer!")

        if word==guess:
            print("The computer guessed your word.")
            turns=100

elif choose=='1':
    words=[]
    w=open("google-10000-english-usa.txt")
    for x in w:
        words.append(x)

    newword=random.choice(words) #randomly select word
    l=len(newword) #count the number of letters

    word=[] #creating a list of letters in newword
    for x in range(0,l-1):
        abc=newword[x]
        word.append(abc)

    letter1=input("number of spaces = "+str(l-1)+". After seven wrong guesses, you lose. First guess? ") #first letter guess

    while letter1 not in a:
        letter1=input("Invalid input. Please guess a lowercase letter.")

    guess=[]
    turns=0
    num=0

    while num<1:
        for x in range(0,l-1):
            if letter1==word[x]:
                guess.append(letter1)
            else:
               guess.append('_')
        if letter1 not in word:
            turns=turns+1
        num=num+2

    while turns<7 and num>0:

        while letter1 not in a:
            print("Invalid input. Please guess a lowercase letter.")

        letter1=input(' '.join(guess)+" Number of wrong guesses = "+str(turns)+". Next guess?")

        for x in range(0,l-1):
            if letter1==word[x]:
               guess[x]=letter1
            elif guess[x] not in a:
                guess[x]='_'

        if letter1 not in word:
            turns=turns+1

        if turns==7:
            print("The word was "+''.join(word)+". Game over.")

        if word==guess:
            print("The word is "+''.join(word)+". You won!")
            turns=100

else:
    print("Invalid input. Start over.")

<|endoftext|>


<commit_before>import logging

from constants import deep_cases
from machine import Machine
from monoid import Monoid
from control import ElviraPluginControl

class Lexicon:
    """THE machine repository."""
    def __init__(self):
        self.deep_cases = set(deep_cases)  # Set of deep cases

        # static will store only one machine per printname (key),
        # while active can store more
        self.static = {}
        # TODO: map: {active_machine : is it expanded?}
        self.active = {}
        self.create_elvira_machine()

    def create_elvira_machine(self):
        return
        logging.warning("""Elvira machine is created right
                        now at init of Lexicon, HACKHACKHACK""")
        # HACK
        elvira_control = ElviraPluginControl()
        elvira_machine = Machine(elvira_control)
        elvira_machine.append_if_not_there("before_AT")
        elvira_machine.append_if_not_there("after_AT")
        elvira_machine.append_if_not_there("vonat")
        elvira_machine.append_if_not_there("menetrend")
        self.static["elvira"].add(elvira_machine)

    def __add_active_machine(self, m, expanded=False):
        """Helper method for add_active()"""
        printname = str(m)
        if printname in self.active:
            self.active[printname][m] = expanded
        else:
            self.active[printname] = {m: expanded}

    def add_active(self, what):
        """
        adds machines to active collection
        typically called to add a sentence being worked with
        """
        if isinstance(what, list):
            for m in what:
                self.__add_active_machine(m)
        elif isinstance(what, Machine):
            self.__add_active_machine(what)
        else:
            logging.error("""Calling Lexicon.add_active() with an incompatible
                          type""")

    def add_static(self, machines):
        """
        adds machines to static collection
        typically called once to add whole background knowledge
        which is the input of the definition parser
        """
        for m in machines:
            printname = str(m)
            self.static[printname] = m

    def expand(self, machine):
        """
        expanding a machine
        if machine is not active, we raise an exception
        if machine is active but not in knowledge base, we warn the user,
        and do nothing
        if everything is okay, everything from every partition of the
        static machine is copied to the active one
        """
        printname = str(machine)
        if (printname not in self.active or
                machine not in self.active[printname]):
            raise Exception("""only active machines can be expanded
                            right now""")
        if printname not in self.static:
            logging.warning("""expanding a machine that is not in knowledge
                            base ie. Lexicon.static""")
            return

        for i, partition in self.static[printname].base.partitions[1:]:
            # we skipped 0th partition so index has to be corrected
            part_index = i + 1

            # FIXME: copy to active
            for anything in partition:
                machine.append_if_not_there(anything, part_index)

        # change expand status in active store
        self.active[printname][machine] = True

    def activate(self):
        """Finds and returns the machines that should be activated by the
        machines already active. These machines are automatically added
        to self.active as well

        When exactly a machine should be activated is still up for
        consideration; however, currently this method returns a machine if
        all non-primitive machines on its partitions are active."""
        activated = []

        for printname, static_machine in self.static.iteritems():
            to_activate = True
            for partition in static_machine.base.partitions[1:]:
                for machine in partition:
                    if str(machine) not in self.active:
                        to_activate = False
                        break
                if not to_activate:
                    break
            if to_activate:
                m = Machine(Monoid(printname))
                self.add_active(m)
                self.expand(m)
                activated.append(m)
        return activated

    def expanded(self, m):
        """Returns the list of expanded machines."""
        printname = str(m)
        try:
            return self.active[printname][m]
        except KeyError:
            logging.error("""asking whether a machine is expanded about a
                          non-active machine""")
            logging.debug("This machine is: " + str(m))
            return None

    def unexpanded(self, m):
        """Returns the list of unexpanded machines."""
        printname = str(m)
        try:
            return not self.active[printname][m]
        except KeyError:
            logging.error("""asking whether a machine is unexpanded about a
                          non-active machine""")
            logging.debug("This machine is: " + str(m))
            return None

<commit_msg>lots of bugfixes, FIXME/TODO implementations in Lexicon<commit_after>import logging
from itertools import chain
import copy

from constants import deep_cases
from machine import Machine
from monoid import Monoid
from control import ElviraPluginControl

class Lexicon:
    """THE machine repository."""
    def __init__(self):
        self.deep_cases = set(deep_cases)  # Set of deep cases

        # static will store only one machine per printname (key),
        # while active can store more
        self.static = {}
        # TODO: map: {active_machine : is it expanded?}
        self.active = {}
        self.create_elvira_machine()

    def create_elvira_machine(self):
        logging.warning("""Elvira machine is created right
                        now at init of Lexicon, HACKHACKHACK""")
        # HACK
        elvira_control = ElviraPluginControl()
        elvira_machine = Machine(Monoid("elvira"), elvira_control)
        elvira_machine.append_if_not_there("BEFORE_AT")
        elvira_machine.append_if_not_there("AFTER_AT")
        elvira_machine.append_if_not_there("vonat")
        elvira_machine.append_if_not_there("menetrend")
        self.static["elvira"] = elvira_machine

    def __add_active_machine(self, m, expanded=False):
        """Helper method for add_active()"""
        printname = str(m)
        if printname in self.active:
            self.active[printname][m] = expanded
        else:
            self.active[printname] = {m: expanded}

    def add_active(self, what):
        """
        adds machines to active collection
        typically called to add a sentence being worked with
        """
        if isinstance(what, list):
            for m in what:
                self.__add_active_machine(m)
        elif isinstance(what, Machine):
            self.__add_active_machine(what)
        else:
            logging.error("""Calling Lexicon.add_active() with an incompatible
                          type""")

    def add_static(self, machines):
        """
        adds machines to static collection
        typically called once to add whole background knowledge
        which is the input of the definition parser
        """
        for m in machines:
            printname = str(m)
            self.static[printname] = m

    def expand(self, machine):
        """
        expanding a machine
        if machine is not active, we raise an exception
        if machine is active but not in knowledge base, we warn the user,
        and do nothing
        if everything is okay, everything from every partition of the
        static machine is copied to the active one
        """
        printname = str(machine)
        if (printname not in self.active or
                machine not in self.active[printname]):
            raise Exception("""only active machines can be expanded
                            right now, but {0} is not active""".format(
                            printname))
        if printname not in self.static:
            logging.warning("""expanding a machine ({0}) that is not in
                            knowledge base ie. Lexicon.static""".format(
                            printname))
            self.active[printname][machine] = True
            return

        logging.debug("Expanding machine: " + str(machine))
        for i, part in enumerate(self.static[printname].base.partitions[1:]):
            logging.debug(part)
            # we skipped 0th partition so index has to be corrected
            part_index = i + 1

            # FIXME: copy to active
            for anything in part:
                #logging.debug(anything)
                #logging.debug(type(anything))
                machine_to_append = None
                if isinstance(anything, Machine):
                    machine_to_append = anything
                    # FIXME: the machine from the active set, copy, etc.
                else:
                    if anything in self.active:
                        # FIXME: [0] is a hack, fix it
                        machine_to_append = self.active[anything].keys()[0]
                    else:
                        machine_to_append = Machine(Monoid(anything))

                machine.append_if_not_there(machine_to_append, part_index)

                pn = str(machine_to_append)
                if pn not in self.active:
                    self.active[pn] = {}
                    self.active[pn][machine_to_append] = False

        logging.debug(repr(self.active[printname].keys()[0].base.partitions))
        # change expand status in active store
        self.active[printname][machine] = True

    def activate(self):
        """Finds and returns the machines that should be activated by the
        machines already active. These machines are automatically added
        to self.active as well

        When exactly a machine should be activated is still up for
        consideration; however, currently this method returns a machine if
        all non-primitive machines on its partitions are active."""
        activated = []

        for printname, static_machine in self.static.iteritems():
            if printname in self.active:
                continue
            has_machine = False
            for machine in chain(*static_machine.base.partitions[1:]):
                has_machine = True
                if str(machine) not in self.active:
                    break
            else:
                if has_machine:
                    m = Machine(Monoid(printname), copy.copy(static_machine.control))
                    self.add_active(m)
                    activated.append(m)
        return activated

    def is_expanded(self, m):
        """Returns whether m is expanded or not"""
        printname = str(m)
        try:
            return self.active[printname][m]
        except KeyError:
            logging.error("""asking whether a machine is expanded about a
                          non-active machine""")
            logging.debug("This machine is: " + str(m))
            return None

    def get_expanded(self, inverse=False):
        """Returns the list of expanded machines."""
        logging.debug('get_expanded(' + str(inverse) + ')')
        result = []
        for pn, machines in self.active.iteritems():
            for machine in machines:
                # if inverse: return unexpandeds
                if inverse ^ machines[machine]:
                    result.append(machine)
        logging.debug("RESULT: " + ','.join(str(m) for m in result))
        return result

    def get_unexpanded(self):
        return self.get_expanded(True)
<|endoftext|>


<commit_before>from django.contrib import admin

from import_export.admin import ExportMixin
from import_export.resources import ModelResource
from import_export import fields

from models import (Activity, Assignment, Attribute, Campaign, Duty, Event,
                    Family, Location, Message, TriggerByDate, Volunteer,
                    Sendable, TriggerByAssignment, TriggerByEvent)

class DutyInline(admin.TabularInline):
    model = Duty
    readonly_fields = ['unassigned_count']
    extra = 0

class AssignmentInline(admin.TabularInline):
    model = Assignment
    readonly_fields = ['duty', 'assigned_location', 'hh_service_location']
    extra = 0

    def has_add_permission(self, request):
        return False

class AssignmentChangeableInline(admin.TabularInline):
    model = Assignment
    readonly_fields = ['hh_service_location']
    extra = 0

    def has_add_permission(self, request):
        return False

TRIGGER_FIELDSETS = (
    (None,
     {'fields': ('message',)}),
    ('Send on a fixed date',
     {'fields': ('fixed_date', 'assignment_state')}),
    )

class TriggerByDateInline(admin.TabularInline):
    model = TriggerByDate
    extra = 0

class TriggerByAssignmentInline(admin.TabularInline):
    model = TriggerByAssignment
    extra = 0

class TriggerByEventInline(admin.TabularInline):
    model = TriggerByEvent
    extra = 0

class VolunteerInline(admin.StackedInline):
    model = Volunteer
    fields = (('title', 'first_name', 'surname', 'dear_name'),
              ('email_address', 'home_phone', 'mobile_phone'),
              'attributes', 'note',
              'slug')
    readonly_fields = ['slug']
    filter_horizontal = ['attributes']
    extra = 0

class FamilyAdmin(admin.ModelAdmin):
    inlines = [VolunteerInline]
    list_display = ['external_id', 'hh_location', 'names']
    fields = (('external_id', 'surnames'),)
    search_fields = ['external_id', 'volunteer__surname']
    list_filter = ['hh_location']
    change_list_template = "admin/change_list_filter_sidebar.html"
    readonly_fields = ['surnames']
admin.site.register(Family, FamilyAdmin)

class AttributeAdmin(admin.ModelAdmin):
    list_display = ['name']
admin.site.register(Attribute, AttributeAdmin)

class CampaignAdmin(admin.ModelAdmin):
    list_display = ['name', 'assignable_recipient_count',
                    'unassigned_recipient_count', 'volunteers_needed',
                    'volunteers_assigned', 'percent_assigned']
    prepopulated_fields = {"slug": ("name",)}
    search_fields = ['name', 'slug']
    filter_horizontal = ['events', 'locations', 'activities']
    fieldsets = ((None, {'fields': ('name', 'slug', 'from_address',
                                    'bcc_address'), }),
                 ('Recipient selection',
                  {'fields': ('events', 'locations', 'activities'), }),
                 ('Trigger By Date Inlines',
                  {'fields': (),
                   'classes': ('placeholder triggerbydate_set-group',)}),
                 ('Trigger By Assignment Inlines',
                  {'fields': (),
                   'classes': ('placeholder triggerbyassignment_set-group',)}),
                 ('Trigger By Event Inlines',
                  {'fields': (),
                   'classes': ('placeholder triggerbyevent_set-group',)}),
                 ('Recipient list',
                  {'fields': ('recipient_names', ),
                   'classes': ('grp-collapse grp-closed',),
                   })
                 )
    readonly_fields = ['recipient_names']
    inlines = [TriggerByDateInline, TriggerByAssignmentInline,
               TriggerByEventInline]
admin.site.register(Campaign, CampaignAdmin)

class VolunteerAdmin(admin.ModelAdmin):
    fields = ('title', 'first_name', 'surname', 'family', 'dear_name',
              'email_address', 'home_phone', 'mobile_phone', 'external_id',
              'last_summary_view', 'temporary_change', 'note', 'attributes')
    list_display = ['first_name', 'surname', 'title', 'family_link',
                    'email_address', 'home_phone', 'mobile_phone',
                    'attributes_list', 'temporary_change', 'last_summary_view']
    readonly_fields = ['attributes_list', 'last_summary_view']
    raw_id_fields = ['family']
    related_lookup_fields = {
        'fk': ['family'],
    }
    search_fields = ['slug', 'first_name', 'surname', 'family__external_id',
                     'external_id']
    list_filter = ['attributes', 'temporary_change', 'last_summary_view',
                   'attributes__activity', 'assignment__duty']
    filter_horizontal = ['attributes']
    inlines = [AssignmentInline]
    date_hierarchy = 'last_summary_view'
admin.site.register(Volunteer, VolunteerAdmin)

class VolunteerAdded(Volunteer):
    class Meta:
        proxy = True
        verbose_name_plural = "Recently added volunteers"

def _set_attribute(attribute_name, volunteer_queryset):
    attribute = Attribute.objects.get(name=attribute_name)
    for volunteer in volunteer_queryset:
        volunteer.attributes.add(attribute)

def add_attribute_adult(modeladmin, request, queryset):
    _set_attribute('adult', queryset)
add_attribute_adult.short_description = "Add 'adult' attribute"

def add_attribute_stewardable(modeladmin, request, queryset):
    _set_attribute('steward able', queryset)
add_attribute_stewardable.short_description = "Add 'steward able' attribute"

def add_attribute_securityable(modeladmin, request, queryset):
    _set_attribute('security able', queryset)
add_attribute_securityable.short_description = "Add 'security able' attribute"

class VolunteerAddedAdmin(VolunteerAdmin):
    list_display = ['created', 'first_name', 'surname', 'title', 'family_link',
                    'email_address', 'home_phone', 'mobile_phone',
                    'attributes_list', 'temporary_change']
    ordering = ('-created',)
    date_hierarchy = 'created'
    actions = [add_attribute_adult, add_attribute_securityable,
               add_attribute_stewardable]
    list_filter = []
admin.site.register(VolunteerAdded, VolunteerAddedAdmin)

class VolunteerNotModified(Volunteer):
    class Meta:
        proxy = True
        verbose_name_plural = "Recently (not) modified volunteers"

class VolunteerNotModifiedAdmin(VolunteerAdmin):
    list_display = ['modified', 'first_name', 'surname', 'title',
                    'family_link', 'email_address', 'home_phone',
                    'mobile_phone', 'attributes_list', 'temporary_change']
    ordering = ('modified',)
    date_hierarchy = 'modified'
    list_filter = []
admin.site.register(VolunteerNotModified, VolunteerNotModifiedAdmin)

class DutyAdmin(admin.ModelAdmin):
    list_display = ['id', 'event_is_visible_to_volunteers', 'activity',
                    'event', 'location', 'start_time', 'end_time', 'multiple',
                    'unassigned_count', 'coordinator_note', 'details']
    list_filter = ['event__is_visible_to_volunteers', 'activity', 'event',
                   'location', 'start_time', 'event__campaign']
    readonly_fields = ['unassigned_count']
    inlines = [AssignmentChangeableInline]
admin.site.register(Duty, DutyAdmin)

class DutyEditable(Duty):
    class Meta:
        proxy = True
        verbose_name_plural = "Duties (editable)"

class DutyEditableAdmin(DutyAdmin):
    list_editable = ['location', 'multiple', 'start_time', 'end_time',
                     'coordinator_note', 'details']
admin.site.register(DutyEditable, DutyEditableAdmin)

class AssignmentResource(ModelResource):
    event = fields.Field(column_name='event',
                         attribute='duty__event__name')
    event_date = fields.Field(column_name='event date',
                              attribute='duty__event__date')
    activity = fields.Field(column_name='activity',
                            attribute='duty__activity__name')
    location = fields.Field(column_name='location',
                            attribute='duty__location__name')
    assigned_location = fields.Field(column_name='assigned location',
                                     attribute='assigned_location__name')
    start_time = fields.Field(column_name='start time',
                              attribute='duty__start_time')
    end_time = fields.Field(column_name='end time',
                            attribute='duty__end_time')
    volunteer = fields.Field(column_name='volunteer')
    mobile_phone = fields.Field(column_name='mobile phone',
                                attribute='volunteer__mobile_phone')
    home_phone = fields.Field(column_name='home phone',
                              attribute='volunteer__home_phone')
    email_address = fields.Field(column_name='email address',
                                 attribute='volunteer__email_address')
    hh_service_location = fields.Field(column_name='hh_service_location')

    class Meta:
        model = Assignment
        fields = []

    def dehydrate_volunteer(self, assignment):
        return str(assignment.volunteer)

    def dehydrate_hh_service_location(self, assignment):
        return assignment.volunteer.family.get_hh_location_display()

class AssignmentEventFilter(admin.SimpleListFilter):
    title = 'event'
    parameter_name = 'event'

    def lookups(self, request, model_admin):
        events = Event.objects.filter(is_archived=False)
        return [(event.id, event.date_and_name()) for event in events]

    def queryset(self, request, queryset):
        if self.value():
            return queryset.filter(duty__event__exact=self.value())
        else:
            return queryset

class AssignmentAdmin(ExportMixin, admin.ModelAdmin):
    list_display = ('id', 'modified', 'volunteer', 'duty_link',
                    'assigned_location')
    list_filter = ['duty__event__is_visible_to_volunteers',
                   AssignmentEventFilter, 'duty__activity', 'duty__event',
                   'duty__location', 'assigned_location', 'duty__start_time', ]
    date_hierarchy = 'modified'
    search_fields = ['volunteer__first_name', 'volunteer__surname']
    resource_class = AssignmentResource
    list_select_related = True
admin.site.register(Assignment, AssignmentAdmin)

class ActivityAdmin(admin.ModelAdmin):
    list_display = ['name', 'attributes_list', 'web_summary_description',
                    'assignment_message_description']
    readonly_fields = ['attributes_list']
    list_filter = ['attributes']
    change_list_template = "admin/change_list_filter_sidebar.html"
    filter_horizontal = ['attributes']
admin.site.register(Activity, ActivityAdmin)

class LocationAdmin(admin.ModelAdmin):
    list_display = ['name', 'web_summary_description',
                    'assignment_message_description']
    pass
admin.site.register(Location, LocationAdmin)

def visible_to_volunteers_events(modeladmin, request, queryset):
    queryset.update(is_visible_to_volunteers=True)
visible_to_volunteers_events.short_description = \
    "Make events visible to volunteers"

def not_visible_to_volunteers_events(modeladmin, request, queryset):
    queryset.update(is_visible_to_volunteers=False)
not_visible_to_volunteers_events.short_description = \
    "Make events not visible to volunteers"

def archive_events(modeladmin, request, queryset):
    queryset.update(is_archived=True)
archive_events.short_description = "Archive events"

def unarchive_events(modeladmin, request, queryset):
    queryset.update(is_archived=False)
unarchive_events.short_description = "Unarchive events"

def copy_events(modeladmin, request, queryset):
    for event in queryset:
        event.create_deep_copy()
copy_events.short_description = "Copy events"

class EventAdmin(admin.ModelAdmin):
    list_display = ('date', 'name', 'is_visible_to_volunteers',
                    'web_summary_description',
                    'assignment_message_description')
    list_display_links = ('name',)
    list_filter = ['is_archived', 'is_visible_to_volunteers']
    date_hierarchy = 'date'
    change_list_template = "admin/change_list_filter_sidebar.html"
    inlines = [DutyInline]
    actions = [copy_events, visible_to_volunteers_events,
               not_visible_to_volunteers_events, archive_events,
               unarchive_events]
admin.site.register(Event, EventAdmin)

class MessageAdmin(admin.ModelAdmin):
    pass
admin.site.register(Message, MessageAdmin)

class SendableAdmin(admin.ModelAdmin):
    list_display = ['send_date', 'sent_date', 'volunteer', 'assignment',
                    'trigger_detail', 'send_failed']
    list_filter = ['send_failed']
    change_list_template = "admin/change_list_filter_sidebar.html"
    date_hierarchy = 'send_date'
    search_fields = ['volunteer__first_name', 'volunteer__surname',
                     'volunteer__family__external_id',
                     'volunteer__external_id']
    actions = ['send_message']

    def send_message(self, request, queryset):
        sent_count = 0
        for sendable in queryset:
            sendable.send_email()
            sent_count += 1
        if sent_count == 1:
            message_bit = "1 message was"
        else:
            message_bit = "%s messages were" % sent_count
        self.message_user(request, "%s sent." % message_bit)
    send_message.short_description = "Send (or resend) the message"

admin.site.register(Sendable, SendableAdmin)
<commit_msg>Limit filter list for events.<commit_after>from django.contrib import admin

from import_export.admin import ExportMixin
from import_export.resources import ModelResource
from import_export import fields

from models import (Activity, Assignment, Attribute, Campaign, Duty, Event,
                    Family, Location, Message, TriggerByDate, Volunteer,
                    Sendable, TriggerByAssignment, TriggerByEvent)

class DutyInline(admin.TabularInline):
    model = Duty
    readonly_fields = ['unassigned_count']
    extra = 0

class AssignmentInline(admin.TabularInline):
    model = Assignment
    readonly_fields = ['duty', 'assigned_location', 'hh_service_location']
    extra = 0

    def has_add_permission(self, request):
        return False

class AssignmentChangeableInline(admin.TabularInline):
    model = Assignment
    readonly_fields = ['hh_service_location']
    extra = 0

    def has_add_permission(self, request):
        return False

TRIGGER_FIELDSETS = (
    (None,
     {'fields': ('message',)}),
    ('Send on a fixed date',
     {'fields': ('fixed_date', 'assignment_state')}),
    )

class TriggerByDateInline(admin.TabularInline):
    model = TriggerByDate
    extra = 0

class TriggerByAssignmentInline(admin.TabularInline):
    model = TriggerByAssignment
    extra = 0

class TriggerByEventInline(admin.TabularInline):
    model = TriggerByEvent
    extra = 0

class VolunteerInline(admin.StackedInline):
    model = Volunteer
    fields = (('title', 'first_name', 'surname', 'dear_name'),
              ('email_address', 'home_phone', 'mobile_phone'),
              'attributes', 'note',
              'slug')
    readonly_fields = ['slug']
    filter_horizontal = ['attributes']
    extra = 0

class FamilyAdmin(admin.ModelAdmin):
    inlines = [VolunteerInline]
    list_display = ['external_id', 'hh_location', 'names']
    fields = (('external_id', 'surnames'),)
    search_fields = ['external_id', 'volunteer__surname']
    list_filter = ['hh_location']
    change_list_template = "admin/change_list_filter_sidebar.html"
    readonly_fields = ['surnames']
admin.site.register(Family, FamilyAdmin)

class AttributeAdmin(admin.ModelAdmin):
    list_display = ['name']
admin.site.register(Attribute, AttributeAdmin)

class CampaignAdmin(admin.ModelAdmin):
    list_display = ['name', 'assignable_recipient_count',
                    'unassigned_recipient_count', 'volunteers_needed',
                    'volunteers_assigned', 'percent_assigned']
    prepopulated_fields = {"slug": ("name",)}
    search_fields = ['name', 'slug']
    filter_horizontal = ['events', 'locations', 'activities']
    fieldsets = ((None, {'fields': ('name', 'slug', 'from_address',
                                    'bcc_address'), }),
                 ('Recipient selection',
                  {'fields': ('events', 'locations', 'activities'), }),
                 ('Trigger By Date Inlines',
                  {'fields': (),
                   'classes': ('placeholder triggerbydate_set-group',)}),
                 ('Trigger By Assignment Inlines',
                  {'fields': (),
                   'classes': ('placeholder triggerbyassignment_set-group',)}),
                 ('Trigger By Event Inlines',
                  {'fields': (),
                   'classes': ('placeholder triggerbyevent_set-group',)}),
                 ('Recipient list',
                  {'fields': ('recipient_names', ),
                   'classes': ('grp-collapse grp-closed',),
                   })
                 )
    readonly_fields = ['recipient_names']
    inlines = [TriggerByDateInline, TriggerByAssignmentInline,
               TriggerByEventInline]
admin.site.register(Campaign, CampaignAdmin)

class VolunteerAdmin(admin.ModelAdmin):
    fields = ('title', 'first_name', 'surname', 'family', 'dear_name',
              'email_address', 'home_phone', 'mobile_phone', 'external_id',
              'last_summary_view', 'temporary_change', 'note', 'attributes')
    list_display = ['first_name', 'surname', 'title', 'family_link',
                    'email_address', 'home_phone', 'mobile_phone',
                    'attributes_list', 'temporary_change', 'last_summary_view']
    readonly_fields = ['attributes_list', 'last_summary_view']
    raw_id_fields = ['family']
    related_lookup_fields = {
        'fk': ['family'],
    }
    search_fields = ['slug', 'first_name', 'surname', 'family__external_id',
                     'external_id']
    list_filter = ['attributes', 'temporary_change', 'last_summary_view',
                   'attributes__activity', 'assignment__duty']
    filter_horizontal = ['attributes']
    inlines = [AssignmentInline]
    date_hierarchy = 'last_summary_view'
admin.site.register(Volunteer, VolunteerAdmin)

class VolunteerAdded(Volunteer):
    class Meta:
        proxy = True
        verbose_name_plural = "Recently added volunteers"

def _set_attribute(attribute_name, volunteer_queryset):
    attribute = Attribute.objects.get(name=attribute_name)
    for volunteer in volunteer_queryset:
        volunteer.attributes.add(attribute)

def add_attribute_adult(modeladmin, request, queryset):
    _set_attribute('adult', queryset)
add_attribute_adult.short_description = "Add 'adult' attribute"

def add_attribute_stewardable(modeladmin, request, queryset):
    _set_attribute('steward able', queryset)
add_attribute_stewardable.short_description = "Add 'steward able' attribute"

def add_attribute_securityable(modeladmin, request, queryset):
    _set_attribute('security able', queryset)
add_attribute_securityable.short_description = "Add 'security able' attribute"

class VolunteerAddedAdmin(VolunteerAdmin):
    list_display = ['created', 'first_name', 'surname', 'title', 'family_link',
                    'email_address', 'home_phone', 'mobile_phone',
                    'attributes_list', 'temporary_change']
    ordering = ('-created',)
    date_hierarchy = 'created'
    actions = [add_attribute_adult, add_attribute_securityable,
               add_attribute_stewardable]
    list_filter = []
admin.site.register(VolunteerAdded, VolunteerAddedAdmin)

class VolunteerNotModified(Volunteer):
    class Meta:
        proxy = True
        verbose_name_plural = "Recently (not) modified volunteers"

class VolunteerNotModifiedAdmin(VolunteerAdmin):
    list_display = ['modified', 'first_name', 'surname', 'title',
                    'family_link', 'email_address', 'home_phone',
                    'mobile_phone', 'attributes_list', 'temporary_change']
    ordering = ('modified',)
    date_hierarchy = 'modified'
    list_filter = []
admin.site.register(VolunteerNotModified, VolunteerNotModifiedAdmin)

class DutyEventFilter(admin.SimpleListFilter):
    title = 'event (not archived)'
    parameter_name = 'event'

    def events(self):
        return Event.objects.filter(is_archived=False)

    def lookups(self, request, model_admin):
        return [(event.id, event.date_and_name()) for event in self.events()]

    def queryset(self, request, queryset):
        if self.value():
            return queryset.filter(event__exact=self.value())
        else:
            return queryset

class DutyVisibleEventFilter(DutyEventFilter):
    title = 'event (visible only)'

    def events(self):
        return Event.objects.filter(is_visible_to_volunteers=True)

class DutyAdmin(admin.ModelAdmin):
    list_display = ['id', 'event_is_visible_to_volunteers', 'activity',
                    'location', 'start_time', 'end_time', 'multiple',
                    'unassigned_count', 'coordinator_note', 'details']
    list_filter = ['event__is_visible_to_volunteers', DutyVisibleEventFilter,
                   DutyEventFilter, 'activity', 'location', 'start_time',
                   'event__campaign']
    readonly_fields = ['unassigned_count']
    inlines = [AssignmentChangeableInline]
admin.site.register(Duty, DutyAdmin)

class DutyEditable(Duty):
    class Meta:
        proxy = True
        verbose_name_plural = "Duties (editable)"

class DutyEditableAdmin(DutyAdmin):
    list_editable = ['location', 'multiple', 'start_time', 'end_time',
                     'coordinator_note', 'details']
admin.site.register(DutyEditable, DutyEditableAdmin)

class AssignmentResource(ModelResource):
    event = fields.Field(column_name='event',
                         attribute='duty__event__name')
    event_date = fields.Field(column_name='event date',
                              attribute='duty__event__date')
    activity = fields.Field(column_name='activity',
                            attribute='duty__activity__name')
    location = fields.Field(column_name='location',
                            attribute='duty__location__name')
    assigned_location = fields.Field(column_name='assigned location',
                                     attribute='assigned_location__name')
    start_time = fields.Field(column_name='start time',
                              attribute='duty__start_time')
    end_time = fields.Field(column_name='end time',
                            attribute='duty__end_time')
    volunteer = fields.Field(column_name='volunteer')
    mobile_phone = fields.Field(column_name='mobile phone',
                                attribute='volunteer__mobile_phone')
    home_phone = fields.Field(column_name='home phone',
                              attribute='volunteer__home_phone')
    email_address = fields.Field(column_name='email address',
                                 attribute='volunteer__email_address')
    hh_service_location = fields.Field(column_name='hh_service_location')

    class Meta:
        model = Assignment
        fields = []

    def dehydrate_volunteer(self, assignment):
        return str(assignment.volunteer)

    def dehydrate_hh_service_location(self, assignment):
        return assignment.volunteer.family.get_hh_location_display()

class AssignmentEventFilter(admin.SimpleListFilter):
    title = 'event (not archived)'
    parameter_name = 'event'

    def events(self):
        return Event.objects.filter(is_archived=False)

    def lookups(self, request, model_admin):
        return [(event.id, event.date_and_name()) for event in self.events()]

    def queryset(self, request, queryset):
        if self.value():
            return queryset.filter(duty__event__exact=self.value())
        else:
            return queryset

class AssignmentVisibleEventFilter(AssignmentEventFilter):
    title = 'event (visible only)'

    def events(self):
        return Event.objects.filter(is_visible_to_volunteers=True)

class AssignmentAdmin(ExportMixin, admin.ModelAdmin):
    list_display = ('id', 'modified', 'volunteer', 'duty_link',
                    'assigned_location')
    list_filter = ['duty__event__is_visible_to_volunteers',
                   AssignmentVisibleEventFilter, AssignmentEventFilter,
                   'duty__activity', 'duty__event', 'duty__location',
                   'assigned_location', 'duty__start_time', ]
    date_hierarchy = 'modified'
    search_fields = ['volunteer__first_name', 'volunteer__surname']
    resource_class = AssignmentResource
    list_select_related = True
admin.site.register(Assignment, AssignmentAdmin)

class ActivityAdmin(admin.ModelAdmin):
    list_display = ['name', 'attributes_list', 'web_summary_description',
                    'assignment_message_description']
    readonly_fields = ['attributes_list']
    list_filter = ['attributes']
    change_list_template = "admin/change_list_filter_sidebar.html"
    filter_horizontal = ['attributes']
admin.site.register(Activity, ActivityAdmin)

class LocationAdmin(admin.ModelAdmin):
    list_display = ['name', 'web_summary_description',
                    'assignment_message_description']
    pass
admin.site.register(Location, LocationAdmin)

def visible_to_volunteers_events(modeladmin, request, queryset):
    queryset.update(is_visible_to_volunteers=True)
visible_to_volunteers_events.short_description = \
    "Make events visible to volunteers"

def not_visible_to_volunteers_events(modeladmin, request, queryset):
    queryset.update(is_visible_to_volunteers=False)
not_visible_to_volunteers_events.short_description = \
    "Make events not visible to volunteers"

def archive_events(modeladmin, request, queryset):
    queryset.update(is_archived=True)
archive_events.short_description = "Archive events"

def unarchive_events(modeladmin, request, queryset):
    queryset.update(is_archived=False)
unarchive_events.short_description = "Unarchive events"

def copy_events(modeladmin, request, queryset):
    for event in queryset:
        event.create_deep_copy()
copy_events.short_description = "Copy events"

class EventAdmin(admin.ModelAdmin):
    list_display = ('date', 'name', 'is_visible_to_volunteers',
                    'web_summary_description',
                    'assignment_message_description')
    list_display_links = ('name',)
    list_filter = ['is_archived', 'is_visible_to_volunteers']
    date_hierarchy = 'date'
    change_list_template = "admin/change_list_filter_sidebar.html"
    inlines = [DutyInline]
    actions = [copy_events, visible_to_volunteers_events,
               not_visible_to_volunteers_events, archive_events,
               unarchive_events]
admin.site.register(Event, EventAdmin)

class MessageAdmin(admin.ModelAdmin):
    pass
admin.site.register(Message, MessageAdmin)

class SendableAdmin(admin.ModelAdmin):
    list_display = ['send_date', 'sent_date', 'volunteer', 'assignment',
                    'trigger_detail', 'send_failed']
    list_filter = ['send_failed']
    change_list_template = "admin/change_list_filter_sidebar.html"
    date_hierarchy = 'send_date'
    search_fields = ['volunteer__first_name', 'volunteer__surname',
                     'volunteer__family__external_id',
                     'volunteer__external_id']
    actions = ['send_message']

    def send_message(self, request, queryset):
        sent_count = 0
        for sendable in queryset:
            sendable.send_email()
            sent_count += 1
        if sent_count == 1:
            message_bit = "1 message was"
        else:
            message_bit = "%s messages were" % sent_count
        self.message_user(request, "%s sent." % message_bit)
    send_message.short_description = "Send (or resend) the message"

admin.site.register(Sendable, SendableAdmin)
<|endoftext|>