text
stringlengths 29
850k
|
|---|
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'CentralMessage'
db.create_table(u'central_message_centralmessage', (
(u'message_ptr', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['messages_extends.Message'], unique=True, primary_key=True)),
('generated', self.gf('django.db.models.fields.BooleanField')(default=False)),
('generated_on', self.gf('django.db.models.fields.DateTimeField')(null=True, blank=True)),
))
db.send_create_signal(u'central_message', ['CentralMessage'])
# Adding model 'CentralUserMessage'
db.create_table(u'central_message_centralusermessage', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('message', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['messages_extends.Message'], unique=True, null=True, on_delete=models.SET_NULL)),
('master', self.gf('django.db.models.fields.related.ForeignKey')(related_name=u'central_message_centralusermessage_related', to=orm['central_message.CentralMessage'])),
))
db.send_create_signal(u'central_message', ['CentralUserMessage'])
def backwards(self, orm):
# Deleting model 'CentralMessage'
db.delete_table(u'central_message_centralmessage')
# Deleting model 'CentralUserMessage'
db.delete_table(u'central_message_centralusermessage')
models = {
u'auth.group': {
'Meta': {'object_name': 'Group'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
u'auth.permission': {
'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
u'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Group']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Permission']"}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
u'central_message.centralmessage': {
'Meta': {'object_name': 'CentralMessage', '_ormbases': [u'messages_extends.Message']},
'generated': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'generated_on': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
u'message_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': u"orm['messages_extends.Message']", 'unique': 'True', 'primary_key': 'True'})
},
u'central_message.centralusermessage': {
'Meta': {'object_name': 'CentralUserMessage'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'master': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'central_message_centralusermessage_related'", 'to': u"orm['central_message.CentralMessage']"}),
'message': ('django.db.models.fields.related.OneToOneField', [], {'to': u"orm['messages_extends.Message']", 'unique': 'True', 'null': 'True', 'on_delete': 'models.SET_NULL'})
},
u'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
u'messages_extends.message': {
'Meta': {'object_name': 'Message'},
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'expires': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'extra_tags': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'level': ('django.db.models.fields.IntegerField', [], {}),
'message': ('django.db.models.fields.TextField', [], {}),
'modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'read': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']", 'null': 'True', 'blank': 'True'})
}
}
complete_apps = ['central_message']
|
All office bearers in the United States are giving their time and effort without receiving any wages from IGC. Those who work full time with IGC are paid appropriately. God forbid that money should ever become our motivation, limiting factor, or advancing factor in missions. May our true motivation always be our love for the Lord Jesus and the lives of countless millions at the crossroads of heaven and hell.
|
import pytz, datetime
from coaster.sqlalchemy import BaseMixin
from sqlalchemy.sql import func
from sqlalchemy.ext.hybrid import hybrid_property
from ..extensions import db
from ..utils import STRING_LEN
import datetime
t_tracknetwork = db.Table(
u'content_tracknetwork',
db.Column(u'track_id', db.ForeignKey('content_track.id')),
db.Column(u'network_id', db.ForeignKey('radio_network.id'))
)
class ContentTrack(BaseMixin, db.Model):
"""A track to which audio content is added"""
__tablename__ = u'content_track'
name = db.Column(db.String(STRING_LEN))
description = db.Column(db.Text)
uri = db.Column(db.String(200))
# add array
type_id = db.Column(db.ForeignKey('content_type.id'))
uploaded_by = db.Column(db.ForeignKey('user_user.id'))
deleted = db.Column(db.Boolean, default=False)
continuous_play = db.Column(db.Boolean)
content_type = db.relationship(u'ContentType', backref=db.backref('track_content'))
networks = db.relationship(u'Network', secondary=u'content_tracknetwork', backref=db.backref('tracks'))
def __unicode__(self):
return self.name
class ContentUploads(BaseMixin, db.Model):
"""An upload to a particular track"""
__tablename__ = u'content_uploads'
name = db.Column(db.String(STRING_LEN))
uri = db.Column(db.String(200))
ok_to_play = db.Column(db.Boolean)
order = db.Column(db.Integer, default=0)
deleted = db.Column(db.Boolean, default=False)
uploaded_by = db.Column(db.ForeignKey('user_user.id'))
track_id = db.Column(db.ForeignKey('content_track.id'))
type_id = db.Column(db.ForeignKey('content_type.id'))
date_created = db.Column(db.DateTime(timezone=True), server_default=func.now())
updated_at = db.Column(db.DateTime(timezone=True), server_default=func.now())
track = db.relationship(u'ContentTrack', backref=db.backref('files'))
def __unicode__(self):
return self.name
@hybrid_property
def is_remote(self):
return self.uri.startswith('http://') or self.uri.startswith('https://')
class CommunityMenu(BaseMixin, db.Model):
"""An IVR menu for communities to record ads, announcements and greetings"""
__tablename__ = u"content_communitymenu"
station_id = db.Column(db.ForeignKey('radio_station.id'))
welcome_message = db.Column(db.String(200))
welcome_message_txt = db.Column(db.Text())
no_input_message = db.Column(db.String(200))
no_input_message_txt = db.Column(db.Text())
days_prompt = db.Column(db.String(200))
days_prompt_txt = db.Column(db.Text())
record_prompt = db.Column(db.String(200))
record_prompt_txt = db.Column(db.Text())
message_type_prompt = db.Column(db.String(200))
message_type_prompt_txt = db.Column(db.Text())
finalization_prompt = db.Column(db.String(200))
finalization_prompt_txt = db.Column(db.Text())
goodbye_message = db.Column(db.String(200))
goodbye_message_txt = db.Column(db.Text())
use_tts = db.Column(db.Boolean(), default=False)
prefetch_tts = db.Column(db.Boolean(), default=True)
date_created = db.Column(db.DateTime(timezone=True), default=datetime.datetime.utcnow)
updated_at = db.Column(db.DateTime(timezone=True), default=datetime.datetime.utcnow)
station = db.relationship(u'Station', backref=db.backref('community_menu'))
deleted = db.Column(db.Boolean, default=False, nullable=False)
class CommunityContent(BaseMixin, db.Model):
"""A message left by a member of the community (ad, greeting, announcement)"""
__tablename__ = u"content_communitycontent"
station_id = db.Column(db.ForeignKey('radio_station.id'))
originator = db.Column(db.String(20))
message = db.Column(db.String(100))
duration = db.Column(db.Integer)
date_created = db.Column(db.DateTime(timezone=True), server_default=func.now())
type_code = db.Column(db.Integer)
valid_until = db.Column(db.DateTime(timezone=True))
approved = db.Column(db.Boolean(), default=False)
deleted = db.Column(db.Boolean, default=False)
station = db.relationship(u'Station', backref=db.backref('community_content'))
class ContentPodcast(BaseMixin, db.Model):
"""Definition of a podcast"""
__tablename__ = u'content_podcast'
name = db.Column(db.String(STRING_LEN))
uri = db.Column(db.String(200))
description = db.Column(db.String(1000))
ok_to_play = db.Column(db.Boolean)
created_by = db.Column(db.ForeignKey('user_user.id'))
date_created = db.Column(db.DateTime(timezone=True), server_default=func.now())
updated_at = db.Column(db.DateTime(timezone=True), server_default=func.now())
deleted = db.Column(db.Boolean)
class ContentPodcastDownload(BaseMixin, db.Model):
"""Download of a podcast file"""
__tablename__ = u'content_podcastdownload'
file_name = db.Column(db.String(255, convert_unicode=True))
duration = db.Column(db.String(10))
title = db.Column(db.String(255, convert_unicode=True))
summary = db.Column(db.Text(None, convert_unicode=True))
podcast_id = db.Column(db.ForeignKey('content_podcast.id'))
date_published = db.Column(db.DateTime(timezone=True))
date_downloaded = db.Column(db.DateTime(timezone=True), server_default=func.now())
date_created = db.Column(db.DateTime(timezone=True), server_default=func.now())
podcast = db.relationship(u'ContentPodcast', backref=db.backref('podcast_downloads'))
class ContentMusic(BaseMixin, db.Model):
"""Music files on the phone of a station"""
__tablename__ = u'content_music'
title = db.Column(db.String(300, convert_unicode=True))
album_id = db.Column(db.ForeignKey('content_musicalbum.id'))
duration = db.Column(db.Integer)
station_id = db.Column(db.ForeignKey('radio_station.id', ondelete='SET NULL'), nullable=True)
artist_id = db.Column(db.ForeignKey('content_musicartist.id', ondelete='SET NULL'), nullable=True)
station = db.relationship(u'Station', backref=db.backref('music'))
artist = db.relationship(u'ContentMusicArtist', backref=db.backref('music'))
date_created = db.Column(db.DateTime(timezone=True), server_default=func.now())
class ContentMusicAlbum(BaseMixin, db.Model):
"""Albums of Music files on the phone of a station"""
__tablename__ = u'content_musicalbum'
title = db.Column(db.String(255, convert_unicode=True))
station_id = db.Column(db.ForeignKey('radio_station.id'))
date_created = db.Column(db.DateTime(timezone=True), server_default=func.now())
station = db.relationship(u'Station', backref=db.backref('albums'))
class ContentMusicArtist(BaseMixin, db.Model):
"""Artists for the media on phones"""
__tablename__ = u'content_musicartist'
title = db.Column(db.String(255, convert_unicode=True))
station_id = db.Column(db.ForeignKey('radio_station.id'))
date_created = db.Column(db.DateTime(timezone=True), server_default=func.now())
station = db.relationship(u'Station', backref=db.backref('artists'))
class ContentMusicPlaylist(BaseMixin, db.Model):
"""Playlist of the music files on a station"""
__tablename__ = u'content_musicplaylist'
title = db.Column(db.String(STRING_LEN))
station_id = db.Column(db.ForeignKey('radio_station.id'))
description = db.Column(db.Text)
date_created = db.Column(db.DateTime(timezone=True), server_default=func.now())
station = db.relationship(u'Station', backref=db.backref('playlists'))
deleted = db.Column(db.Boolean)
class ContentMusicPlayListItemType(BaseMixin, db.Model):
"""Type of Items in a playlist mapping to media - """
__tablename__ = u'content_musicplaylistitemtype'
title = db.Column(db.String(STRING_LEN))
t_musicartist = db.Table(
u'content_music_musicartist',
db.Column(u'music_id', db.ForeignKey('content_music.id')),
db.Column(u'artist_id', db.ForeignKey('content_musicartist.id'))
)
class ContentMusicPlaylistItem(BaseMixin, db.Model):
"""Definition of an item (song, album, artist) on a playlist"""
__tablename__ = 'content_musicplaylistitem'
playlist_id = db.Column(db.ForeignKey('content_musicplaylist.id'))
playlist_item_id = db.Column(db.Integer)
playlist_item_type_id = db.Column(db.ForeignKey('content_musicplaylistitemtype.id'))
updated_at = db.Column(db.DateTime(), server_default=func.now())
created_at = db.Column(db.DateTime(), server_default=func.now())
deleted = db.Column(db.Boolean, default=False)
class ContentStream(BaseMixin, db.Model):
"""Definition of a stream"""
__tablename__ = u'content_stream'
name = db.Column(db.String(STRING_LEN))
uri = db.Column(db.String(200))
description = db.Column(db.String(1000))
ok_to_play = db.Column(db.Boolean)
created_by = db.Column(db.ForeignKey('user_user.id'))
date_created = db.Column(db.DateTime(timezone=True), server_default=func.now())
updated_at = db.Column(db.DateTime(timezone=True), server_default=func.now())
deleted = db.Column(db.Boolean)
|
Download USB Restore Software at www.usbrestore.com to easily find out erased text files and official documents in less time. Pen drive data restore program provide facility for all user to view deleted data before final start of recovery process.
www.simrestore.com offers Mobile Phone Restore application offers complete solution procedure to restore and rescue lost or erased images, pictures, saved text files, unread messages, and crucial contact numbers from corrupted phone storage medium.
Lost memorable photograph from pen drives? Don??�t feel sad! Visit website www.cardrecovery.biz to download Mac Card Recovery software to restore hard disk drive files.
BKF Repair software instantly Repair Damage bkf file without creates any problem for users. While users get corrupt data from windows bkf file then try to bkf repair tool for repair corruption backup files.
Photo Recovery Software offers interactive graphical user interface to easily get back accidentally formatted images in mouse clicks. Technically advance Pics Recovery Software recoup deleted formatted images from external storage USB pen drive.
Flash Media Recovery Software accessible from www.usbrecovery.biz best and easiest way to recuperate pictures, photos, digital snaps, documents from corrupted, formatted USB drive, memory card, hard disk etc.
Are you worried about how to restore formatted contact numbers? Just visit www.usbrecovery.biz website to install SIM Cards Recovery Software revives missing text message and phone numbers saved in your cell phone.
With effective and more feature Company provide Mobile Phone Repair Software on URL www.memorycardrepair.com that is highly capable to retrieve missing, erased, or deleted phone data within short time duration.
Repair Memory Card Downloads tool to get back formatted multimedia files video clips from SDHC plus card in minimal time. Advanced memory card recovery program repairs erased flash files wallpapers from mini CF card in easiest and fastest manner.
|
#!/usr/bin/env python
#
# Copyright 2008 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""Controller (MVC) for the add existing (project) dialog.
A Google App Engine Application is called a 'project' internally to
the launcher to prevent confusion. Class App is for the launcher
application itself, and class Project is for an App Engine
Application (a 'project').
"""
import os
import wx
import dialog_controller_base
import launcher
from wxgladegen import project_dialogs
class AddExistingController(dialog_controller_base.DialogControllerBase):
"""Controller for an Add Existing Project dialog.
The controller is responsible for displaying the dialog, filling it
in, and (if not cancelled) reading data back and creating a new
launcher.Project.
"""
def __init__(self, dialog=None):
"""Initialize a new controller.
Args:
dialog: the dialog to use. If None, a default is chosen.
"""
super(AddExistingController, self).__init__()
self.dialog = (dialog or project_dialogs.AddExistingProjectDialog(None))
self.MakeBindings()
# Make sure we don't create a Project until we've actually OK'd the dialog.
self._dialog_return_value = None
def _BrowseForDirectory(self, evt):
"""Browse for a directory, then set its path in the dialog.
Called directly from UI.
"""
# Default path is the parent directory
default_path = self.GetPath()
if os.path.exists(default_path):
default_path = os.path.join(default_path, '..')
else:
default_path = ''
# On MacOSX, wx.DD_DIR_MUST_EXIST doesn't appear to be honored. :-(
dirname = wx.DirSelector(message='Pick an existing App Engine App',
defaultPath=default_path,
style=wx.DD_DIR_MUST_EXIST)
if dirname:
self.SetPath(dirname)
def MakeBindings(self):
"""Bind events on our dialog."""
self.MakeBindingsOKCancel()
self.dialog.Bind(wx.EVT_BUTTON, self._BrowseForDirectory,
self.dialog.app_browse_button)
def SetPort(self, port):
"""Set the port in the dialog.
Args:
port: the port number to use.
"""
self.dialog.app_port_text_ctrl.SetValue(str(port))
def SetPath(self, path):
"""Set the path in the dialog.
Args:
path: the path to use.
"""
if not path:
path = ''
self.dialog.app_path_text_ctrl.SetValue(path)
def GetPort(self):
"""Return the port in the dialog."""
return self.dialog.app_port_text_ctrl.GetValue()
def GetPath(self):
"""Return the path in the dialog."""
return self.dialog.app_path_text_ctrl.GetValue()
def ShowModal(self):
"""Show our dialog modally.
Returns:
wx.ID_OK if Update was clicked; wx.ID_CANCEL if Cancel was clicked.
"""
self._dialog_return_value = self.dialog.ShowModal()
return self._dialog_return_value
def _SanityCheckPath(self, path, check_contents=True):
"""Sanity check new values before making a Project.
Args:
path: a filesystem path (from the dialog)
check_contents: if True, check if the contents look valid.
If invalid, warn, but allow things to continue.
Returns:
True if we should make a project from this value.
"""
if not (path and os.path.isdir(path)):
self.FailureMessage('Path invalid; cannot make project.',
'Add Application')
return False
if check_contents and not os.path.exists(os.path.join(path, 'app.yaml')):
self.FailureMessage('Specified path doesn\'t look like an application; ' +
'%s/app.yaml not present. (Allowing anyway.)' % path,
'Add Application')
# fall through; looks bad but don't deny just in case.
# We made it!
return True
def _SanityCheckPort(self, port):
"""Sanity check new values before making a Project.
Args:
port: the port for the project (also from the dialog)
Returns:
True if we should make a project from this value.
"""
try:
port = int(port)
except ValueError:
port = None
if not port or port < 1024:
self.FailureMessage('Port invalid (not a number or less than 1024); ' +
'cannot make project.',
'Add Application')
return False
return True
def Project(self):
"""Return a project created from interaction with this dialog.
Returns:
A launcher.Project, or None.
"""
if self._dialog_return_value != wx.ID_OK:
return None
path = self.GetPath()
port = self.GetPort()
if not (self._SanityCheckPath(path) and self._SanityCheckPort(port)):
return None
return launcher.Project(path, port)
|
Life Innovations Web Design has extensive experience in creating web services for small businesses, non-profit organizations, and corporations looking to market products and services online. Our Company is offering Free Web Hosting and Free Domain Registration to our clients for the 1st year! We'll help you register your domain name and setup your server (Red Hat Enterprise Linux, CentOS, Windows 2008 r2 and etc...) to support your basic, advance, or premium development packages.
3. DEVELOP your online service on time and under budget.
Life Innovations Web Design isn't responsible for our client's content (Copyright Infringement and Illegal Content (Products and Services)) they publish on our servers. A invoice will be rendered stating the services we provide and price.
|
import os
from django.core.files.uploadedfile import SimpleUploadedFile
from PIL import Image
from config.settings.test import MEDIA_ROOT
def simple_uploaded_file(image_path):
"""Crea una SimpleUploadedFile para campos de modelo
ImageField, FileField.
Args:
image_path (str): Path de la imagen a "subir".
Returns:
SimpleUploadedFile:
"""
if not os.path.exists(image_path):
raise FileNotFoundError('El "{}" archivo no existe'.format(image_path))
name = os.path.basename(image_path)
with open(image_path, 'rb') as fh:
image = SimpleUploadedFile(
name=name,
content=fh.read(),
content_type='image/jpeg'
)
return image
def create_image(name='test.png', size=(150, 150), ext='png'):
"""Crea una imagen y la guarda en get_image_path.
Args:
name (str): Nombre de la imagen, por defecto test.png.
size (list): width/height de la imagen, por defecto (150, 150).
ext (str): Extension de la imagen sin el (.), por defecto png
Returns:
Imagen creada
"""
color = (255, 0, 0, 0)
image = Image.new('RGB', size=size, color=color)
image.save(get_image_path(name), ext)
return image
def get_image_path(name='test.png'):
"""Obtiene un path con la ruta y nombre de la imagen /MEDIA_ROOT/{name}.
Args:
name (str): Nombre de la imagen.
Returns:
El path con el nombre del archivo en forma de /MEDIA_ROOT/imagen.png
"""
return '{}/{}'.format(MEDIA_ROOT, name)
def delete_image(name='test.png'):
"""Elimina una imagen.
Args:
name (str): Nombre de la imagen.
"""
image_path = get_image_path(name)
if os.path.exists(image_path):
os.remove(image_path)
|
El sobrepeso infantil constituye uno de los principales problemas de salud en escolares, además de originar creencias erróneas en torno a la Imagen Corporal (IC); provocando insatisfacción y baja autoestima. Este estudio de carácter descriptivo y corte transversal analizó los índices de obesidad, la IC y la opinión sobre videojuegos activos de 577 escolares; con el fin de utilizar estos dispositivos para paliar los problemas descritos. Los resultados mostraron que tres de cada diez escolares tenía problemas peso, que un importante número de participantes no se sentía satisfecho con su IC, así como una actitud favorable sobre la aplicabilidad de Exergames en el aula. Además, se encontraron diferencias estadísticas al relacionar la IC con los índices de obesidad. Como conclusión principal, este estudio demuestra el interés de usar videojuegos activos en el aula para mejorar los problemas de salud producidos por el exceso de peso, así como la IC.
Childhood overweight is one of the main health problems in school children. Also, this population can have misconceptions about their Body Image (BI), inducing dissatisfaction and low self-esteem. This descriptive and transversal research analysed the obesity rates, BI and the opinion about active videogames of 577 school children, in order to use these technologies to improve the problems described before. The results indicated that three out of every ten respondents had weight problems. In addition, the research showed that a significant number of participants was not satisfied with their BI and that they thought that Exergames are fun for doing Physical Education (PE) at school. Besides, the study evinced statistical differences in the relationship between BI and obesity rates. In conclusion, this research shows the interest in using these technologies in PE lessons to improve the health problems caused by overweight and the BI of children as well.
|
"""Add Jobs
Revision ID: 5da21d856a57
Revises: edd910853060
Create Date: 2017-07-30 16:43:35.839411
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '5da21d856a57'
down_revision = 'edd910853060'
branch_labels = None
depends_on = None
def upgrade():
op.create_table(
'jobs',
sa.Column('id', sa.Integer, primary_key=True, autoincrement=True),
sa.Column('command_name', sa.String(100), nullable=False),
sa.Column('parameters', sa.Text(), nullable=False),
sa.Column('schedule', sa.Text(), nullable=False),
sa.Column('created_at', sa.DateTime(timezone=True), nullable=False),
sa.Column('last_executed_at', sa.DateTime(timezone=True), nullable=True),
sa.Column('expired_at', sa.DateTime(timezone=True), nullable=True),
)
op.create_table(
'job_history',
sa.Column('id', sa.Integer, primary_key=True, autoincrement=True),
sa.Column('job_id', sa.Integer, nullable=False),
sa.Column('execution_id', sa.String(256), nullable=False),
sa.Column('executed_at', sa.DateTime(timezone=True), nullable=False),
sa.Column('execution_ended', sa.DateTime(timezone=True), nullable=True),
sa.Column('results', sa.Text(), nullable=True),
sa.Column('result_type', sa.String(100), nullable=True),
)
def downgrade():
op.drop_table('jobs')
op.drop_table('job_history')
|
Every parent has been there. The baby won’t stop wailing, the dog needs to be walked, your partner is hungry and asking for dinner. What do you do? Feel your chest tense up with anxiety? Grab a glass of wine?
Leafly's 4 reasons why we should respect the man. We think they make a point.
Our City Mayor quits forced by serious illness due to lung cancer.
How is it possible cannabis can both trigger anxiety and help against anxiety. Read it here friends.
Colomn from our friends from Hightimes about the Marley Turntable. Vinyl-Freaks check it out!
Cannabis is a multi-purpose, natural medication, treating everything from headaches to insomnia, to cancer. While the traditional method of consumption is smoking hand-rolled “joints”, there are several other ways to ingest this beneficial medication, and the best consumption choice generally depends on the condition or symptom the patient is hoping to treat.
Canada is preparing for a fully regulated, adult-legal cannabis market, beginning in July 2018.
Oscar-winning actor Morgan Freeman says cannabis has helped reduce his fibromyalgia pain, and as such, he’s been an outspoken supporter of full legalization of MMJ and recreational weed.
10 High talks with your… Brain!
The autonomous region of Catalonia, Spain, has legalised cannabis.
The saliva test can be used to find out if people have taken opiates, cocaine, THC (the active ingredient in marijuana) and methamphetamines and has been used in Belgium for some time.
Are Pot Smokers just like anyone else?
Not to be that person who says “I told you so,” but a new study has concluded that pot smokers are not a bunch of lazy slackers but indeed well-adjusted human beings who cross a large swath of society’s diverse types of individuals.
Wernard Bruining, “The Potfather”, is a true cannabis legend. He founded the first coffeeshop in Amsterdam (1973) and the first growshop in Europe (1985). In the nineties, he shifted his attention to medical cannabis. Inside the Cannabis University at Cannabis Liberation Day 2017, Wernard gave a masterclass on how to make your own cannabis oil.
Coffeeshops are allowed to hold a maximum of 500 grams of cannabisproducts in store. This policy brings a few problems along.
Come July in Amsterdam, summer is in full swing and the city's beaches and parks host dance music events, while there are more festivals than you can shake a stick at.
|
import unittest
from robot.errors import DataError
from robot.model import Keywords
from robot.running.userkeyword import (EmbeddedArgs, EmbeddedArgsTemplate,
UserKeywordHandler)
from robot.running.arguments import EmbeddedArguments, UserKeywordArgumentParser
from robot.utils.asserts import assert_equal, assert_true, assert_raises
class Fake(object):
value = ''
message = ''
def __iter__(self):
return iter([])
class FakeArgs(object):
def __init__(self, args):
self.value = args
def __nonzero__(self):
return bool(self.value)
def __iter__(self):
return iter(self.value)
class HandlerDataMock:
def __init__(self, name, args=[]):
self.name = name
self.args = FakeArgs(args)
self.metadata = {}
self.keywords = Keywords()
self.defaults = []
self.varargs = None
self.minargs = 0
self.maxargs = 0
self.return_value = None
self.doc = Fake()
self.timeout = Fake()
self.return_ = Fake()
self.tags = ()
self.teardown = None
def EAT(name, args=[]):
handler = HandlerDataMock(name, args)
embedded = EmbeddedArguments(name)
return EmbeddedArgsTemplate(handler, 'resource', embedded)
class TestEmbeddedArgs(unittest.TestCase):
def setUp(self):
self.tmp1 = EAT('User selects ${item} from list')
self.tmp2 = EAT('${x} * ${y} from "${z}"')
def test_no_embedded_args(self):
assert_true(not EmbeddedArguments('No embedded args here'))
assert_true(EmbeddedArguments('${Yes} embedded args here'))
def test_get_embedded_arg_and_regexp(self):
assert_equal(self.tmp1.embedded_args, ['item'])
assert_equal(self.tmp1.embedded_name.pattern,
'^User\\ selects\\ (.*?)\\ from\\ list$')
assert_equal(self.tmp1.name, 'User selects ${item} from list')
def test_get_multiple_embedded_args_and_regexp(self):
assert_equal(self.tmp2.embedded_args, ['x', 'y', 'z'])
assert_equal(self.tmp2.embedded_name.pattern,
'^(.*?)\\ \\*\\ (.*?)\\ from\\ \\"(.*?)\\"$')
def test_create_handler_when_no_match(self):
assert_raises(ValueError, EmbeddedArgs, 'Not matching', self.tmp1)
def test_create_handler_with_one_embedded_arg(self):
handler = EmbeddedArgs('User selects book from list', self.tmp1)
assert_equal(handler.embedded_args, [('item', 'book')])
assert_equal(handler.name, 'User selects book from list')
assert_equal(handler.longname, 'resource.User selects book from list')
handler = EmbeddedArgs('User selects radio from list', self.tmp1)
assert_equal(handler.embedded_args, [('item', 'radio')])
assert_equal(handler.name, 'User selects radio from list')
assert_equal(handler.longname, 'resource.User selects radio from list')
def test_create_handler_with_many_embedded_args(self):
handler = EmbeddedArgs('User * book from "list"', self.tmp2)
assert_equal(handler.embedded_args,
[('x', 'User'), ('y', 'book'), ('z', 'list')])
def test_create_handler_with_empty_embedded_arg(self):
handler = EmbeddedArgs('User selects from list', self.tmp1)
assert_equal(handler.embedded_args, [('item', '')])
def test_create_handler_with_special_characters_in_embedded_args(self):
handler = EmbeddedArgs('Janne & Heikki * "enjoy" from """', self.tmp2)
assert_equal(handler.embedded_args,
[('x', 'Janne & Heikki'), ('y', '"enjoy"'), ('z', '"')])
def test_embedded_args_without_separators(self):
template = EAT('This ${does}${not} work so well')
handler = EmbeddedArgs('This doesnot work so well', template)
assert_equal(handler.embedded_args, [('does', ''), ('not', 'doesnot')])
def test_embedded_args_with_separators_in_values(self):
template = EAT('This ${could} ${work}-${OK}')
handler = EmbeddedArgs("This doesn't really work---", template)
assert_equal(handler.embedded_args,
[('could', "doesn't"), ('work', 'really work'), ('OK', '--')])
def test_creating_handlers_is_case_insensitive(self):
handler = EmbeddedArgs('User SELECts book frOm liST', self.tmp1)
assert_equal(handler.embedded_args, [('item', 'book')])
assert_equal(handler.name, 'User SELECts book frOm liST')
assert_equal(handler.longname, 'resource.User SELECts book frOm liST')
def test_embedded_args_handler_has_all_needed_attributes(self):
normal = UserKeywordHandler(HandlerDataMock('My name'), None)
embedded = EmbeddedArgs('My name', EAT('My ${name}'))
for attr in dir(normal):
assert_true(hasattr(embedded, attr), "'%s' missing" % attr)
class TestGetArgSpec(unittest.TestCase):
def test_no_args(self):
self._verify('')
def test_one_arg(self):
self._verify('${arg1}', ['arg1',])
def test_one_vararg(self):
self._verify('@{varargs}', exp_varargs='varargs')
def test_one_default(self):
self._verify('${arg1} ${arg2}=default @{varargs}',
['arg1', 'arg2'], ['default'], 'varargs')
def test_one_empty_default(self):
self._verify('${arg1} ${arg2}= @{varargs}',
['arg1', 'arg2'], [''], 'varargs')
def test_many_defaults(self):
self._verify('${arg1}=default1 ${arg2}=default2 ${arg3}=default3',
['arg1', 'arg2', 'arg3'],
['default1', 'default2', 'default3'])
def _verify(self, in_args, exp_args=[], exp_defaults=[], exp_varargs=None):
argspec = self._parse(in_args)
assert_equal(argspec.positional, exp_args)
assert_equal(argspec.defaults, exp_defaults)
assert_equal(argspec.varargs, exp_varargs)
def _parse(self, in_args):
return UserKeywordArgumentParser().parse(in_args.split())
def test_many_varargs_raises(self):
assert_raises(DataError, self._parse, '@{varargs} @{varargs2}')
def test_args_after_varargs_raises(self):
assert_raises(DataError, self._parse, '@{varargs} ${arg1}')
def test_get_defaults_before_args_raises(self):
assert_raises(DataError, self._parse, '${args1}=default ${arg2}')
if __name__ == '__main__':
unittest.main()
|
Kate Atkinson arrived upon the literary scene when her debut novel Behind the Scenes at the Museum unexpectedly won the 1995 Whitbread book of the year prize (renamed Costa Award n 2006), beating the favourites, Salman Rushdie's The Moor's Last Sigh and Roy Jenkins' Gladstone.
Smith, Kevin P., M. Carmen Gomez-Galisteo. "Kate Atkinson". The Literary Encyclopedia. First published 20 September 2002; last revised 03 September 2016.
5191 Kate Atkinson 1 Historical context notes are intended to give basic and preliminary information on a topic. In some cases they will be expanded into longer entries as the Literary Encyclopedia evolves.
|
from keras.models import Model
from keras.layers import Input, Masking, Dense, LSTM
from keras.layers import Dropout, TimeDistributed, Bidirectional, merge
from keras.layers.embeddings import Embedding
from keras.utils import np_utils
import numpy as np
import pandas as pd
import sys
import math
import os
from datetime import datetime
# add path
sys.path.append('../')
sys.path.append('../tools')
from tools import conf
from tools import load_data
from tools import prepare
from tools import plot
np.random.seed(0)
# train hyperparameters
step_length = conf.chunk_step_length
pos_length = conf.chunk_pos_length
emb_vocab = conf.senna_vocab
emb_length = conf.senna_length
hash_vocab = conf.chunk_hash_vocab
hash_length = conf.chunk_hash_length
output_length = conf.chunk_NP_length
split_rate = conf.chunk_split_rate
batch_size = conf.batch_size
nb_epoch = conf.nb_epoch
model_name = os.path.basename(__file__)[:-3]
folder_path = 'model/%s'%model_name
if not os.path.isdir(folder_path):
os.makedirs(folder_path)
# the data, shuffled and split between train and test sets
train_data, dev_data = load_data.load_chunk(dataset='train.txt', split_rate=split_rate)
train_samples = len(train_data)
dev_samples = len(dev_data)
print('train shape:', train_samples)
print('dev shape:', dev_samples)
print()
word_embedding = pd.read_csv('../preprocessing/senna/embeddings.txt', delimiter=' ', header=None)
word_embedding = word_embedding.values
word_embedding = np.concatenate([np.zeros((1,emb_length)),word_embedding, np.random.uniform(-1,1,(1,emb_length))])
hash_embedding = pd.read_csv('../preprocessing/chunk-auto-encoder-2/auto-encoder-embeddings.txt', delimiter=' ', header=None)
hash_embedding = hash_embedding.values
hash_embedding = np.concatenate([np.zeros((1,hash_length)),hash_embedding, np.random.rand(1,hash_length)])
embed_index_input = Input(shape=(step_length,))
embedding = Embedding(emb_vocab+2, emb_length, weights=[word_embedding], mask_zero=True, input_length=step_length)(embed_index_input)
hash_index_input = Input(shape=(step_length,))
encoder_embedding = Embedding(hash_vocab+2, hash_length, weights=[hash_embedding], mask_zero=True, input_length=step_length)(hash_index_input)
pos_input = Input(shape=(step_length, pos_length))
senna_hash_pos_merge = merge([embedding, encoder_embedding, pos_input], mode='concat')
input_mask = Masking(mask_value=0)(senna_hash_pos_merge)
dp_1 = Dropout(0.6)(input_mask)
hidden_1 = Bidirectional(LSTM(128, return_sequences=True))(dp_1)
hidden_2 = Bidirectional(LSTM(64, return_sequences=True))(hidden_1)
dp_2 = Dropout(0.6)(hidden_2)
output = TimeDistributed(Dense(output_length, activation='softmax'))(dp_2)
model = Model(input=[embed_index_input,hash_index_input,pos_input], output=output)
model.compile(loss='categorical_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])
print(model.summary())
number_of_train_batches = int(math.ceil(float(train_samples)/batch_size))
number_of_dev_batches = int(math.ceil(float(dev_samples)/batch_size))
print('start train %s ...\n'%model_name)
best_accuracy = 0
best_epoch = 0
all_train_loss = []
all_dev_loss = []
all_dev_accuracy = []
log = open('%s/model_log.txt'%folder_path, 'w')
start_time = datetime.now()
print('train start at %s\n'%str(start_time))
log.write('train start at %s\n\n'%str(start_time))
for epoch in range(nb_epoch):
start = datetime.now()
print('-'*60)
print('epoch %d start at %s'%(epoch, str(start)))
log.write('-'*60+'\n')
log.write('epoch %d start at %s\n'%(epoch, str(start)))
train_loss = 0
dev_loss = 0
np.random.shuffle(train_data)
for i in range(number_of_train_batches):
train_batch = train_data[i*batch_size: (i+1)*batch_size]
embed_index, hash_index, pos, label, length, sentence = prepare.prepare_chunk(batch=train_batch, gram='bi')
pos = np.array([(np.concatenate([np_utils.to_categorical(p, pos_length), np.zeros((step_length-length[l], pos_length))])) for l,p in enumerate(pos)])
y = np.array([np_utils.to_categorical(each, output_length) for each in label])
train_metrics = model.train_on_batch([embed_index, hash_index, pos], y)
train_loss += train_metrics[0]
all_train_loss.append(train_loss)
correct_predict = 0
all_predict = 0
for j in range(number_of_dev_batches):
dev_batch = dev_data[j*batch_size: (j+1)*batch_size]
embed_index, hash_index, pos, label, length, sentence = prepare.prepare_chunk(batch=dev_batch, gram='bi')
pos = np.array([(np.concatenate([np_utils.to_categorical(p, pos_length), np.zeros((step_length-length[l], pos_length))])) for l,p in enumerate(pos)])
y = np.array([np_utils.to_categorical(each, output_length) for each in label])
# for loss
dev_metrics = model.test_on_batch([embed_index, hash_index, pos], y)
dev_loss += dev_metrics[0]
# for accuracy
prob = model.predict_on_batch([embed_index, hash_index, pos])
for i, l in enumerate(length):
predict_label = np_utils.categorical_probas_to_classes(prob[i])
correct_predict += np.sum(predict_label[:l]==label[i][:l])
all_predict += np.sum(length)
epcoh_accuracy = float(correct_predict)/all_predict
all_dev_accuracy.append(epcoh_accuracy)
all_dev_loss.append(dev_loss)
if epcoh_accuracy>=best_accuracy:
best_accuracy = epcoh_accuracy
best_epoch = epoch
end = datetime.now()
model.save('%s/model_epoch_%d.h5'%(folder_path, epoch), overwrite=True)
print('epoch %d end at %s'%(epoch, str(end)))
print('epoch %d train loss: %f'%(epoch, train_loss))
print('epoch %d dev loss: %f'%(epoch, dev_loss))
print('epoch %d dev accuracy: %f'%(epoch, epcoh_accuracy))
print('best epoch now: %d\n'%best_epoch)
log.write('epoch %d end at %s\n'%(epoch, str(end)))
log.write('epoch %d train loss: %f\n'%(epoch, train_loss))
log.write('epoch %d dev loss: %f\n'%(epoch, dev_loss))
log.write('epoch %d dev accuracy: %f\n'%(epoch, epcoh_accuracy))
log.write('best epoch now: %d\n\n'%best_epoch)
end_time = datetime.now()
print('train end at %s\n'%str(end_time))
log.write('train end at %s\n\n'%str(end_time))
timedelta = end_time - start_time
print('train cost time: %s\n'%str(timedelta))
print('best epoch last: %d\n'%best_epoch)
log.write('train cost time: %s\n\n'%str(timedelta))
log.write('best epoch last: %d\n\n'%best_epoch)
plot.plot_loss(all_train_loss, all_dev_loss, folder_path=folder_path, title='%s'%model_name)
plot.plot_accuracy(all_dev_accuracy, folder_path=folder_path, title='%s'%model_name)
|
HASSELL has received the hotly contested Workplace Over 1000sqm award at the 2018 IDEA held in Sydney on Friday 23 November.
The Interior Design Excellence Awards (IDEA) is Australia’s largest independent design awards program, celebrating the best of the country’s interior and product design.
The client swapped a beachside, campus environment for an urban location, in 30 The Bond – a low, lean commercial building nestled between Sydney’s historic The Rocks and the new Barangaroo waterfront business precinct. The HASSELL designed workplace represents a balance between humanity and technology – a place where art meets science and quality craftsmanship complements understated simplicity.
HASSELL Chairman and Head of Interior Design, Rob Backhouse, said the award is recognition of our commitment to creating places people love.
“At HASSELL we always design with the people who will use our spaces at the forefront of our minds. When it comes to workplaces we strive to create spaces that not only meet a client’s brief, but also where people want to spend a majority of their day. This award reinforces the hard work done by the entire design team to achieve this goal,” Rob said.
GSK House, Singapore, by HASSELL also received a judge’s Highly Commended recognition in the International category.
With its historic but run-down waterfront, San Francisco’s Port Authority decided to restore the shoreline that could greatly influence the future of the city both environmentally and economically.
The HASSELL proposal, titled ‘Resilience, Restoration, Access and Activation’, looks to preserve the significant history and culture of the waterfront while protecting against vulnerability to rising sea-levels, increasing public access and increasing the diversity of uses available to the public along the waterfront. Through restoring lost piers as public recreation, tourism, commercial and cultural functions, the proposal looks to fund significant public realm expansions along a new green Embarcadero.
Off the back of the recent Resilient by Design Bay Area Challenge HASSELL Principal Richard Mullane said preparing for the inevitable sea level rise while repairing former piers , could, and should, be the part of any vision adopted by the Port for the waterfront.
“This waterfront used to be a vibrant gateway to the world, but now more than 20 piers have been lost by decaying and falling into the bay. It’s clear that the main focus should be developing a shoreline for San Francisco that’s not only world class and resilient to future stresses, but also has a diversity of vibrant destinations for the residents of the city,” he said.
Utilising benchmarks HASSELL projects from Sydney’s wharfs, the proposal illustrates an array of possible adaptation approaches suitable for a diverse range of urban uses. From creating sports hubs and museums to mixed-use development and retail to open parks and wildlife sanctuaries, the corridor has the potential to offer far more public access to residents and visitors.
“This is a really important project for San Francisco with endless possibilities to give the public a diverse array of activities and attractions for people of all ages, backgrounds, and economic levels, but also rehabilitate and preserve important sites within the historic Embarcadero district,” Richard said.
For more information on our design, visit the San Francisco Port Authority website.
The HASSELL Futurespective exhibition marks the 80th anniversary of the founding of HASSELL. Held in Hong Kong and Shanghai, the exhibition looks at what we’ve learnt over the past 80 years designing places people love – places that have been successful for our clients and the people who use them.
Futurespective opened in Shanghai on Thursday 15 November and moves to Hong Kong on Wednesday 21 November. The exhibition features models of key global projects, Virtual/Augmented Reality, and behind the scenes content.
At the launch event in Shanghai, guests were invited to view displayed works and discuss the broad ranging changes that have influenced design over the past 80 years. HASSELL Managing Director Steve Coster said these exhibitions offer a great opportunity consider how the work we have completed over the past 80 years impacts cities and communities into the future.
“We are proud of having the opportunity to successfully transform cities, precincts and organisations – as well as shape who we are as a practice today.” Steve said.
It’s important for designers to look beyond workplace trends and instead focus on designing spaces that are as emotionally intelligent as they are technologically intuitive, according to HASSELL Principal Matthew Blain.
Matthew joined international film director, Dorris Dorrie and Alexander Rieck, Co-Director of LAVA (Laboratory for Visionary Architecture), , onstage in Stuttgart to explore the topic of senses at work. Matthew was keynote speaker at Remaultwen 2018, a conference drawing together visionary architectural approaches with film, scenography and brand communications.
Citing as an example Melbourne’s Medibank Place, the game-changing health-based workplace completed by HASSELL in 2014, Matthew explored the notion that designers must first understand the real needs of the workforce and, in turn, design spaces that meet employees’ neurological, sensory and physiological needs.
Also at the event, award-winning German film director Dorrie questioned what it is to work and why we do it. She suggested the current style of office working is counter-intuitive to creativity and encouraged the audience to take time to find a style of work that suits them. LAVA’s Reick explored the future of work and the ever-growing impact Artificial Intelligence will have on the spaces we design.
A vigorous debate followed, In discussing how these approaches to work become more nuanced based on culture and geographic influences, the panel agreed on a fundamental need to create places that meet the physical and social needs of people. In creating spaces that are comfortable, welcoming, beautiful and secure – regardless of the work that is taking place there – designers can help people perform at their best.
HASSELL has received international attention for its quality of BIM and collaboration on Perth’s Optus Stadium, designed by HASSELL COX HKS. Three HASSELL Design Technology representatives have been invited to Autodesk University in Las Vegas to showcase the stadium’s model, which has also received recognition at the Trimble BIM awards.
Autodesk University, an international conference that attracted over 10,000 people last year, aims to connect professionals who create, design, and inspire change within the industry.
HASSELL BIM Manager Julia Allen said that Autodesk University is the premier BIM conference in the world and an ideal setting to discuss the changing technology of architecture and design.
“It’s always exciting to be able to showcase HASSELL to a global audience, particularly a project on the scale of Optus Stadium,” Julia said.
“BIM is ingrained in everything we do at HASSELL and I look forward to seeing how our peers are also using it around the world,” Julia said.
HASSELL and the Optus Stadium model will be the focus of a main exhibit, and the model will be on display until at the Autodesk San Francisco Briefing Centre and Gallery until 2021.
Find out more information on Autodesk University here and the Autodesk San Francisco Briefing Centre and Gallery here.
Climate change hazards, such as sea and bay-level rise, the heat island effect and extreme weather events, pose significant and unprecedented challenges for cities the world over, threatening communities, infrastructure, and public safety.
Recognising the power of international collaboration, open conversation and design to discover innovative ways to tackle climate change impacts, HASSELL has teamed up with San Francisco’s Resilient By Design organisation to bring learnings from this year’s Rockefeller-backed design and community challenge to Australia.
Rather than wait for a natural disaster, the San Francisco Bay Area is proactively reimagining a better and more resilient future. Through the recent Resilient by Design (RBD) Bay Area Challenge San Francisco created a model for design and community-led resilience planning around the world.
A series of panel events in Sydney, Brisbane and Melbourne will feature speakers including Gabriel Metcalf (CEO, Committee for Sydney, previously San Francisco Bay Area Planning and Urban Research Association), Amanda Brown-Stevens (Managing Director, Resilient by Design San Francisco), Beck Dawson (Chief Resilience Office, Metropolitan Sydney), and Toby Kent (Chief Resilience Officer, Resilient Melbourne).
HASSELL Principal and Urban Design Sector Leader, David Tickle said resilience is often narrowly interpreted as pertaining simply to climate change and resulting sea level rise.
“Climate change, rising sea levels, and increased temperatures are clearly all major influences on the resilience of city or community, but these naturally have flow on effects,” David said.
“Infrastructure failure, housing crisis, disease outbreak, cyber threats, and terrorism, are some other examples that can severely impact the long term resilience of cities, including Sydney, Melbourne, and Brisbane. This is why it’s so important to have open, ongoing conversations about how we plan and design the most resilient buildings, precincts and cities with a broad understanding of future challenges,” he said.
“Building urban resilience requires looking at a city holistically and through understanding the systems that make up the city. By strengthening the core of a city and better understanding the potential pressures it may face, a city can improve its longevity and the well-being of its citizens.
“The most important thing we have learnt from being involved in projects such as Resilient by Design is the capacity of individuals, communities, institutions, businesses and systems within a city to come together to survive, adapt and grow no matter what kinds of chronic stresses and acute shocks they experience,” David said.
Melbourne and Sydney are part of The Rockefeller Foundation’s 100 Resilient Cities network which focuses on planning for long-term resilience. The network supports the adoption and incorporation of a view of resilience that includes not just the shocks—earthquakes, fires, floods, etc.—but also the stresses that weaken the fabric of a city on a day-to-day or cyclical basis.
Through these actions, 100 Resilient Cities aims not only to help individual cities become more resilient, but will facilitate the building of a global practice of resilience among governments, NGOs, the private sector, and individual citizens.
“Even though Melbourne and Sydney are currently the only two Australian cities that are part of 100 Resilient Cities, we hope to increase awareness through the program of events and panel discussions and empower more people and communities to be engaged in this important initiative,” David said.
A keynote panel at Sydney Town Hall, partnering with Committee for Sydney, including Gabriel Metcalf (CEO, Committee for Sydney, previously San Francisco Bay Area Planning and Urban Research Association), Beck Dawson (Chief Resilience Office, Metropolitan Sydney), Amanda Brown-Stevens (Managing Director, Resilient by Design San Francisco), and Richard Mullane (Principal, HASSELL).
Amanda Brown-Stevens (Managing Director, Resilient by Design San Francisco) and Richard Mullane (Principal, HASSELL) will present a keynote address exploring the outcomes and learnings for the recent Resilient by Design Bay Area Challenge.
Amanda Brown-Stevens (Managing Director, Resilient by Design San Francisco), Toby Lodge (Principal, HASSELL) and Richard Mullane (Principal, HASSELL) will sit on a panel event partnering with Committee for Brisbane discussing the impact urban design can have on resilience of a city.
Amanda Brown-Stevens (Managing Director, Resilient by Design San Francisco) and Richard Mullane (Principal, HASSELL) will sit on a panel event partnering with City of Melbourne discussing the impact urban design can have on resilience of a city.
In 2018 HASSELL embarked on a mission with NASA to design the first human habitation on Mars. Now, the 2030: A Martian Odyssey Symposium for Extreme Habitats is the first step of a new network-based research platform to connect disciplines and industries.
HASSELL Principal and Head of Design Technology and Innovation Xavier De Kestelier said 2030: A Martian Odyssey is an opportunity to progress thinking on human-centric design and explore what it really means to create ‘places people love’.
“We hope this is the start of an evolving discussion that will draw together learnings from extreme habitats to develop visionary, innovative and scientifically grounded approaches to projects both on Earth and extra-planetary environments,” Xavier said.
The symposium, hosted by HASSELL in London, features a number of Europe’s most adventurous innovators ranging from polar explorers to inter-planetary scientists. Through the course of the day, they will discuss everything from strategies to ensure human survival in deep space, to the practical requirements of costs and the logistics of building in extreme environments.
“It’s a really exciting time to be exploring and pushing the boundaries of design and innovation, particularly when it comes to interplanetary exploration,” said Xavier.
Read more about 2030: A Martian Odyssey here.
Optus Stadium – designed by HASSELL COX HKS – and Darling Harbour Transformation – by HASSELL / HASSELL + Populous – have taken out top honours at the 2018 Australian Institute of Architects National Awards.
Winning two shortlisted categories, Optus Stadium was awarded The Colorbond Award for Steel Architecture and the National Public Architecture Award.
The stadium is transforming the way fans experience major sport and entertainment events, and re-shaping Perth and its landscape in the process. Every design decision for the multi-purpose, 60,000-seat stadium was about achieving a singular vision – an unsurpassed visitor experience every time, every event.
On presenting the awards, the jury cited: “Optus Stadium is an immensely complex undertaking that successfully resolved structural, social and commercial challenges to deliver a world class sporting arena.
HASSELL Principal Peter Dean said the awards once again highlight the incredible vision of the client and Perth in delivering such a city shaping project.
“Optus Stadium truly is a landmark project for the public that is changing the way fans experience sporting and entertainment events. It has received excellent recognition globally and to now have this recognition at the highest honor nationally, and by our peers, reinforces the hard work done by everyone involved in the project,” Peter said.
The Darling Harbour Transformation project was awarded the Walter Burley Griffin Award for Urban Design Award and is Sydney’s most significant urban renewal initiative in 20 years.
Working closely with clients Infrastructure NSW and Lendlease, HASSELL developed the urban design framework and designed the public realm for the entire 20-hectare precinct, including reinvigorated parklands, plazas and event spaces. The harbour-side precinct has been recognised for its integration of the public realm with the architecture of three new venues designed by joint venture HASSELL + Populous, now known as the International Convention Centre Sydney (ICC Sydney).
On presenting the award, the jury cited: “The reinvention of Darling Harbour is a significant moment in Sydney’s urban transformation. Long past its 1980s heyday, the precinct had become tired and congested, with limited visual or physical appeal. Although this is one of the city’s most visited public places, the redevelopment sought to enhance the urban experience – not just for tourists, but for residents and workers.
HASSELL Principal and Head of Landscape Architecture Angus Bruce said the national award is further recognition of the important role truly integrated urban design plays in shaping a city.
|
import datetime
import time
import _db
from _db import Collection, Master
from vFense.db.client import r, db_create_close
AgentStatsKey = 'monit_stats'
AgentCollection = 'agents'
class MonitorKey():
Memory = u'memory'
FileSystem = u'file_system'
Cpu = u'cpu'
Timestamp = u'timestamp'
class Monitor():
"""
Main monitoring class to manage data.
"""
@staticmethod
def save_memory_data(agent=None, data=None):
"""Saves memory data.
Args:
agent: The agent id the data belongs to.
data: Basic data type (str, int, list, dict, etc) to save as is.
"""
if not data or not agent:
return None
data = Monitor._totalfy(data)
result = _db._save_data_point(
agent=agent, collection=Collection.Memory, data=data
)
return result
@staticmethod
def save_cpu_data(agent=None, data=None):
"""Saves cpu data.
Args:
agent: The agent id the data belongs to.
data: Basic data type (str, int, list, dict, etc) to save as is.
"""
if not data or not agent:
return None
result = _db._save_data_point(
agent=agent, collection=Collection.Cpu, data=data
)
return result
@staticmethod
def save_file_system_data(agent=None, data=None):
"""Saves file system data.
"""
if not data or not agent:
return None
new_data = []
for fs in data:
new_data.append(Monitor._totalfy(fs))
result = _db._save_data_point(
agent=agent, collection=Collection.FileSystem, data=new_data
)
return result
@staticmethod
def get_memory_data_since(agent=None, date_time=None):
"""Gets all the memory data.
Args:
agent: The agent id the data belongs to.
date_time: A datetime to get all data since.
Returns:
A list of data points. None otherwise.
"""
if (
not agent
or not date_time
or not isinstance(date_time, datetime.datetime)
):
return None
timestamp = date_time.strftime('%s')
return _db._get_data_points_since(
agent=agent, collection=Collection.Memory, timestamp=timestamp
)
@staticmethod
def get_cpu_data_since(agent=None, date_time=None):
"""Gets all the cpu data.
Args:
agent: The agent id the data belongs to.
date_time: A datetime to get all data since.
Returns:
A list of data points. None otherwise.
"""
if (
not agent
or not date_time
or not isinstance(date_time, datetime.datetime)
):
return None
timestamp = date_time.strftime('%s')
return _db._get_data_points_since(
agent=agent, collection=Collection.Cpu, timestamp=timestamp
)
@staticmethod
def get_file_system_data_since(agent=None, date_time=None):
"""Gets all the file system data.
Args:
agent: The agent id the data belongs to.
date_time: A datetime to get all data since.
Returns:
A list of data points. None otherwise.
"""
if (
not agent
or not date_time
or not isinstance(date_time, datetime.datetime)
):
return None
timestamp = date_time.strftime('%s')
return _db._get_data_points_since(
agent=agent, collection=Collection.FileSystem, timestamp=timestamp
)
@staticmethod
def _totalfy(data):
try:
data['total'] = int(data['free']) + int(data['used'])
except Exception as e:
data['total'] = 0
return data
@staticmethod
@db_create_close
def get_agent_memory_stats(agent=None, conn=None):
"""Gets memory stats directly from the agents collection.
Args:
agent: Agent id to retrieve stats from.
"""
if not agent:
return None
try:
stats = (
r
.table(AgentCollection)
.get(agent)
.pluck(AgentStatsKey)
.run(conn)
)
stats = stats[AgentStatsKey]
if stats:
memory = stats[MonitorKey.Memory]
memory[MonitorKey.Timestamp] = stats[MonitorKey.Timestamp]
return memory
except Exception as e:
# TODO: log here
pass
return None
@staticmethod
@db_create_close
def get_agent_cpu_stats(agent=None, conn=None):
"""Gets cpu stats directly from the agents collection.
Args:
agent: Agent id to retrieve stats from.
"""
if not agent:
return None
try:
stats = (
r
.table(AgentCollection)
.get(agent)
.pluck(AgentStatsKey)
.run(conn)
)
stats = stats[AgentStatsKey]
if stats:
cpu = stats[MonitorKey.Cpu]
cpu[MonitorKey.Timestamp] = stats[MonitorKey.Timestamp]
return cpu
except Exception as e:
# TODO: log here!!
pass
return None
@staticmethod
@db_create_close
def get_agent_file_system_stats(agent=None, conn=None):
"""Gets file_system stats directly from the agents collection.
Args:
agent: Agent id to retrieve stats from.
"""
if not agent:
return None
try:
stats = (
r
.table(AgentCollection)
.get(agent)
.pluck(AgentStatsKey)
.run(conn)
)
stats = stats[AgentStatsKey]
if stats:
fs = []
for _fs in stats[MonitorKey.FileSystem]:
_fs[MonitorKey.Timestamp] = stats[MonitorKey.Timestamp]
fs.append(_fs)
return fs
except Exception as e:
# TODO: log here
pass
return None
def save_monitor_data(agent=None, **kwargs):
"""A catch all function to save monitoring data.
Parameters are basic data type (str, int, list, dict, etc) to save as is.
Args:
agent: The agent id the data belongs to.
kwargs: Keys corresponding to monitor.MonitorKey
Returns:
True if data was saved, False otherwise.
"""
if not agent:
return None
memory = kwargs.get(MonitorKey.Memory)
fs = kwargs.get(MonitorKey.FileSystem)
cpu = kwargs.get(MonitorKey.Cpu)
_mem = None
_cpu = None
_fs = None
if (
not memory
and not cpu
and not fs
):
return None
result = {}
if memory:
_mem = Monitor.save_memory_data(agent, memory)
result[MonitorKey.Memory] = _mem
if cpu:
_cpu = Monitor.save_cpu_data(agent, cpu)
result[MonitorKey.Cpu] = _cpu
if fs:
_fs = Monitor.save_file_system_data(agent, fs)
result[MonitorKey.FileSystem] = _fs
return result
def get_monitor_data_since(agent=None, timestamp=None):
"""A catch all function to get all monitoring data.
Gets the monitoring data since the arguments provided. If all are None,
then the default of 5 hours is used.
Args:
agent: The agent id the data belongs to.
timestamp: Unix timestamp to get data since.
Returns:
A dict with monitor.MonitorKey key. It's possible for values to be None.
"""
_mem = Monitor.get_memory_data_since()
_cpu = Monitor.get_cpu_data_since()
_fs = Monitor.get_file_system_data_since()
data = {}
data[MonitorKey.Memory] = _mem
data[MonitorKey.Cpu] = _cpu
data[MonitorKey.FileSystem] = _fs
return data
@db_create_close
def update_agent_monit_stats(agent=None, **kwargs):
memory = kwargs.get(MonitorKey.Memory)
cpu = kwargs.get(MonitorKey.Cpu)
fs = kwargs.get(MonitorKey.FileSystem)
conn = kwargs.get('conn')
agent_stats = {}
stats = {}
stats['memory'] = Monitor._totalfy(memory)
stats['cpu'] = cpu
stats['timestamp'] = int(time.time())
fs_list = []
for _fs in fs:
fs_list.append(Monitor._totalfy(_fs))
stats['file_system'] = fs_list
agent_stats[AgentStatsKey] = stats
(
r
.table(AgentCollection)
.get(agent)
.update(agent_stats)
.run(conn, no_reply=True)
)
|
We have derived a non-linear charged black hole solution, in the AdS spacetime, which behaves asymptotically like the RN-AdS black hole but at the short distances like a dS geometry. Thus, the black hole is regular. The thermodynamic quantities of the black hole are derived. Also, we analyzed in details the phase transitions of the black hole by observing the discontinuity of the heat capacity at constant pressure and the cusp type double points in the Gibbs free energy-temperature graph. Furthermore, the thermodynamic phases and their stability are investigated relying on the off-sell Gibbs free energy. Finally, we calculated the critical exponents characterizing the behavior of the relevant thermodynamic quantities near the critical point.
|
# https://app.codesignal.com/arcade/code-arcade/labyrinth-of-nested-loops/EQSjA5PRfyHueeNkj
def isSumOfConsecutive2(n):
# Find the number of ways to express n as a sum of some (at least two)
# consecutive positive integers.
# e.g. isSumOfConsecutive2(9) == 2, 2+3+4==9, 4+5==9.
# count = 0
# for i in range(0, n):
# for j in range(i, n):
# if sum(range(i, j)) == n:
# count += 1
# return count
combinations = set([])
# Consecutive values that add up to a certain number have the number divided by the
# amount of values at their center.
# e.g. 9/3 ~ 2, [3], 4
# 9/2 ~ 4, [4.5], 5
for i in range(2, n + 1):
# Find the value at the center.
m = n//i
v = []
# Find the values at both sides of the centers.
for j in range(i):
if i % 2 == 0:
value = m - i//2 + 1 + j
else:
value = m - i//2 + j
if value > 0:
v.append(value)
# Check if all values add up to original value.
if sum(v) == n:
combinations.add(",".join(map(str, v)))
# Return possible amount of combinations of consecutive numbers that add up to n.
return len(combinations)
|
Did you ever have a need to be creative on a short notice? Perhaps your client or boss is looking for a new marketing piece or your competitor is in a weak position and you need to get something into the market quickly?
Here are 12 quick ideas to test or implement when you need fast turnaround that generate results.
One of the fastest techniques is to use somebody’s name. People love the sound of their name and pay attention when their name is used. Whether you are going direct mail or email, target specific people and personalize the contact by using their name.
Everybody knows over 200 people so why not tap into your associates, friends and partner’s network. Create a referral program and incentivize people to promote your brand. Treat your referral program as one of your top notch programs and be generous with your rewards to those who are out promoting your business.
Get out in front of your customers and prospects and get in front of decision makers. Too many times people hide behind email. The best way to get immediate results is a face to face meeting. So fly out to see those people in your business that can make a difference.
One of the most inexpensive ways to create a buzz about your company is to use the media to build it. To do so, you need to inform the media of what you are doing. Put out press releases, put together media kits and send them out to everyone in your industry. Research radio programs looking for guest speakers and send them your press release and ask them to be on their show.
People have a natural curiosity to learn. A great way to get your name out there and position you as an expert in your niche is to offer free training on a topic that is hot in your industry. People will sign up and will begin to spread the word. – Don’t forget to tell them to share the news that you are offering free training with everyone they know.
Right now you have a big asset called social capital. Review your network and do 1 random act of kindness for 5 people in your network with no expectations of an outcome for you. Connect others together, recommend service or product or point them to a great website. This builds equity in those relationships. Do this every day for a month and watch your brand grow.
Create a specialty program that does not cost your customers anything, but by simply being part of your community; they get access to free tips, tools, research, newsletters and events. This gives you a way to continually stay in front of your customers and to reward them for doing business with you. It is easier to sell to existing customers than it is to acquire new ones.
Advertising is an effective way to get your name or your brand out into the marketplace. Research what your target market is reading and place an ad in those magazines. Make your ad compelling and create an offer that drives them to your squeeze page so you can capture their email address and calculate the effectiveness of your advertising.
If you want to be an expert in your niche, why not contact local newspapers and magazines and write an article on your niche. Another method is to write an advertorial – a combination ad and article which offers a visual component (graphics) with strong content (writing) to educate your audience on a process, tip or method.
There are many others selling into your target market but are not competitors. For quick results, tap into their client lists and join forces to offer a joint product or offering or simply offer your clients a free product or service from the other marketer in exchange for him doing the same.
People love a sale! Offer special discounts for your existing customers, for first movers to a new product or simply because…. To get immediate results a special discount program will yield tremendous results.
|
import csv, codecs
import math
from django.core.urlresolvers import resolve
from django.db.models import F, ExpressionWrapper, FloatField, IntegerField, CharField, Case, When, Sum, Func, Min, Q
from django.template.defaulttags import register
from .models import Project, Ingredient, Inventory_Item, MEASUREMENTS, Receipe, Meal_Receipe
def validate_positive(value):
if(value < 0):
raise ValidationError('Please enter a positive value', code='negative-value')
def validate_greater_zero(value):
if(value <= 0):
raise ValidationError('Please enter a value greater than zero', code='not-zero')
MEASUREMENTS = (
('ml', 'Milliliter'),
('g', 'Gram'),
('n', 'Piece'),
)
@register.filter(name='get_item')
def get_item(dictionary, key):
return dictionary.get(key)
def conv_measurement(measurement, quantity):
if(measurement == 'n'):
if(quantity == 1):
return 'piece'
return 'pieces'
return measurement
def prepareContext(request):
context = {}
if('activate_project' in request.GET):
try:
request.session['active_project']=int(request.GET.get('activate_project'))
except:
try:
del request.session['active_project']
except:
pass
try:
context['active_project'] = Project.objects.get(id=request.session['active_project'])
except:
pass
context['active_page'] = resolve(request.path_info).url_name
context['pagetitle'] = context['active_page']
return context
## Ugly thing: if we can import the python2-module, define stuff...
try:
import cStringIO
def _smallhelpforunicode(arg):
if(arg == None):
return ''
return unicode(arg)
class UnicodeWriter:
"""
A CSV writer which will write rows to CSV file "f",
which is encoded in the given encoding.
"""
def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
# Redirect output to a queue
self.queue = cStringIO.StringIO()
self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
self.stream = f
self.encoder = codecs.getincrementalencoder(encoding)()
def writerow(self, row):
self.writer.writerow([_smallhelpforunicode(s).encode("utf-8") for s in row])
# Fetch UTF-8 output from the queue ...
data = self.queue.getvalue()
data = data.decode("utf-8")
# ... and reencode it into the target encoding
data = self.encoder.encode(data)
# write to the target stream
self.stream.write(data)
# empty queue
self.queue.truncate(0)
def writerows(self, rows):
for row in rows:
self.writerow(row)
except:
pass
|
Get the store hours and directions for Minute Clinic in Idaho. Research coupons and discounts for Minute Clinic. Please check to make sure your local Minute Clinic is open for business before you start driving there.
19 Dodge St, Beverly, MA 01915-1705.
311 Newbury St, Danvers, MA 01923-1027.
1900 Main St, Tewksbury, MA 01876-2111.
222 Main Street, Wilmington, MA 1887.
85 High St, Medford, MA 02155-3825.
36 White St, Cambridge, MA 02140-1449.
211 Alewife Brook Pkwy , Cambridge, MA 02138-1101.
1515 Commercial St, Weymouth, MA 02189-3060.
174 Littleton Rd, Westford, MA 01886-3191.
626 Southern Artery, Quincy, MA 02169-5648.
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test TimblClient class
"""
import logging
import unittest
from tt.server import TimblServer
from tt.client import TimblClient, TimblClientError
from common import DATA_DIR
SERVER = None
def start_timbl_server():
global SERVER
options = "-f {0}/dimin.train".format(DATA_DIR)
SERVER = TimblServer(timbl_opts=options)
SERVER.start()
class Test_TimblClient(unittest.TestCase):
def setUp(self):
if not SERVER:
start_timbl_server()
self.client = TimblClient(SERVER.port)
self.client.connect()
def test_disconnect(self):
self.client.disconnect()
self.assertRaises(TimblClientError, self.client.query)
self.assertFalse(self.client.socket)
def test_reconnect(self):
self.client.reconnect()
self.client.query()
def test_connection_timeout(self):
# send incomplete command so server does not reply
self.client.socket.settimeout(1)
self.assertRaises(TimblClientError,
self.client.set,
"-k")
self.client.socket.settimeout(10)
def test_query(self):
# repeat multiple times, because recv in multiple parts occurs rarely
for i in range(25):
status = self.client.query()
## print status
self.assertEqual(status["NEIGHBORS"], "1")
def test_set(self):
self.client.set("-k 10 -d IL")
status = self.client.query()
self.assertEqual(status["NEIGHBORS"], "10")
self.assertEqual(status["DECAY"], "IL")
self.client.set("-k 1 -d Z")
def test_set_error(self):
self.assertRaises(TimblClientError,
self.client.set,
"-w 1")
def test_classify(self):
"""
Exhaustively test classification with any combination of the verbose
output options +/-vdb (distribution), +/-vdi (distance) and +/-vn
(neighbours). The +/-vk seems to be unsupported, as it cannot be "set"
through the server
"""
self.client.set("-k10")
for db in "+vdb -vdb".split():
for di in "+vdi -vdi".split():
for vn in "+vn -vn".split():
self.client.set(db + " " + di + " " + vn)
for i, inst in enumerate(open(DATA_DIR + "/dimin.train")):
if i > 10: break
result = self.client.classify(inst)
self.assertTrue(result.has_key("CATEGORY"))
if db == "+vdb":
self.assertTrue(result.has_key("DISTRIBUTION"))
else:
self.assertFalse(result.has_key("DISTRIBUTION"))
if di == "+vdi":
self.assertTrue(result.has_key("DISTANCE"))
else:
self.assertFalse(result.has_key("DISTANCE"))
if vn == "+vn":
self.assertTrue(result.has_key("NEIGHBOURS"))
else:
self.assertFalse(result.has_key("NEIGHBOURS"))
self.client.set("-k1 -vdb -vdi -vn")
def test_classify_error(self):
self.assertRaises(TimblClientError,
self.client.classify,
"x, x, x, x")
def test_log(self):
# quick & global config of logging system so output of loggers
# goes to stdout
logging.basicConfig(level=logging.DEBUG,
format="%(levelname)-8s <%(name)s> :: %(message)s")
self.client = TimblClient(SERVER.port, log_tag="test_log_client")
self.client.connect()
instances = open(DATA_DIR + "/dimin.train").readlines()
for inst in instances[:2]:
self.client.classify(inst)
self.client.query()
self.client.set("+vdb +vdi +vn")
for inst in instances[:2]:
self.client.classify(inst)
try:
self.client.classify("x, x")
except TimblClientError:
pass
try:
self.client.set("-w 1")
except TimblClientError:
pass
self.client.disconnect()
# global reset of logging level
logging.getLogger().setLevel(logging.CRITICAL)
def tearDown(self):
self.client.disconnect()
if __name__ == '__main__':
import sys
sys.argv.append("-v")
unittest.main()
|
I had a great time playing at Rednecks with Paychecks with Jeff Hobbs and the Jacks. It was a fantastic night of music. The Dustin Perkins band did great, and JB and the Moonshine Band definitely did a fantastic job. It was my first time to be at Rednecks with Paychecks, and it hopefully won't be my last!
|
# -*- coding: utf-8 -*-
import re
import urllib2
import time
import json
class bookIf:
def __init__(self, youth_booklist_url, author_booklist_url):
self.youth_booklist_url = youth_booklist_url
self.author_booklist_url = author_booklist_url
def get_group_booklist(self, group_id):
if group_id != "youth" and group_id != "author":
return None
if group_id == "youth":
if not self.youth_booklist_url:
return None
else:
return self.__get_douban_booklist(self.youth_booklist_url)
if group_id == "author":
if not self.author_booklist_url:
return None
else:
return self.__get_douban_booklist(self.author_booklist_url)
def get_member_booklist(self, member_id, list_type = 'wish'):
root_url = "http://book.douban.com/people/" + member_id
if list_type == "wish":
full_url = root_url + "/wish"
return self.__get_douban_people_readlist(full_url, False) # for wish list, book rating is meaningless, False for not get rating.
elif list_type == "reading":
full_url = root_url + "/do"
return self.__get_douban_people_readlist(full_url)
elif list_type == "done":
full_url = root_url + "/collect"
return self.__get_douban_people_readlist(full_url)
else:
return None
def get_book_info(self, book_id):
root_api = 'https://api.douban.com/v2/book/'
api = root_api + book_id
response = urllib2.urlopen(api)
book_info = json.loads(response.read())
#print book_info['isbn10']
#print book_info['isbn13']
return book_info
def __get_douban_booklist(self, url):
item = 0
total_book_list = []
while True:
full_url = url + "?start={0}&sort=time".format(item)
response = urllib2.urlopen(full_url)
#print "=============================================read page " + str(item/25+1) + "==================================================="
#print urlcheck
html_text = response.read()
#print html_text
#print "===============================================================raw and one line============================================================="
#oneline_html_text = raw_html.replace('\n', ' ').replace('\r', '')
#striped_html = raw_html.strip('\n')
#striped_html = striped_html.strip('\r')
#striped_html = striped_html.strip('\n')
html_text_list = html_text.splitlines()
book_list = []
for i in range(0, len(html_text_list)):
if html_text_list[i].find('<div class="title">') >= 0:
#rematch = re.match(r'(http://book.douban.com/subject/)([0-9]+)(/)', html_text_list[i+1])
rematch = re.search('(?<=subject/)\d+', html_text_list[i+1])
if rematch:
book_id = rematch.group(0)
book_name = html_text_list[i+2].strip()
book_info = {"book_id":"", "book_name":""}
book_info['book_id'] = book_id
book_info['book_name'] = book_name
#print book_info
book_list.append(book_info)
if book_list:
#print book_list
total_book_list += book_list
item += 25
time.sleep(1) #sleep 1 second to avoid being blocked by douban.com for frequent access.
else:
break
#print total_book_list
return total_book_list
def __get_douban_people_readlist(self, url, WANT_RATING = True):
item_num = 0
total_book_list = []
while True:
#print "=============================================read page " + str(item_num/15+1) + "==================================================="
full_url = url + "?start={0}&sort=time".format(item_num)
response = urllib2.urlopen(full_url)
html_text = response.read()
html_text_list = html_text.splitlines()
book_list = []
got_book_title = False # used for search book rating. only after a book title is found, book rating is to be searched.
for html_line in html_text_list:
book_info = {"book_id":"", "book_name":"", "rating":0}
if WANT_RATING and got_book_title:
rate_search = re.search('(<span class="rating)(\d)(-t"></span>)', html_line)
if rate_search:
book_rating = rate_search.group(2)
book_list[len(book_list)-1]["rating"] = int(book_rating)
got_book_title = False
continue
search_result = re.search('(http://book.douban.com/subject/)(\d+)(/)(.+)(title=")(.+)(")', html_line)
if search_result:
book_id = search_result.group(2)
book_name = search_result.group(6)
book_info['book_id'] = book_id
book_info['book_name'] = book_name
book_list.append(book_info)
got_book_title = True
if book_list:
total_book_list += book_list
item_num += 15
#print book_list
time.sleep(1) #sleep 1 second to avoid being blocked by douban.com for frequent access.
else:
break
return total_book_list
|
Dunnage Bags are available as Paper or Woven Material. Dunnage bags provide efficient cargo protection inside shipping containers during transit.
Polyester Composite Strap for secure loading of cargo and maintaining the highest standards in terms of safety while in transit, we take nothing to chance.
Polyester lashing has many advantages over other conventional cargo securing systems. Fortris Lashing eliminates incidents and damage to your cargo.
Fortris Lashing is specifically designed to secure cargo in containers, flat rack trailers and on large ships.
Load Securing Equipment for Oil and Gas UK members.
Polyester Woven Straps for secure loading of cargo and maintaining the highest standards in terms of safety while in transit, we take nothing to chance.
Fortris Load Secure Ensures to Provide 5 Star Rated Strapping to Maximise Your Cargo Safety. Fortris use the highest quality raw material to manufacture the strapping to increase defence against all weather types.
Fortris Load Secure UK is based in the Centre of the country - Burntwood, West Midlands. Allowing us to reach out to our customers efficiently. Fortris Load Secure UK has provided loading and securing solutions in many industries such as Transport and Logistics, Scaffolds, freight services, engineering and manufacturing. We can offer support and guidance on choosing the correct load securing solution for any form of transport. Our aim is to meet your demands and provide comprehensive load securing solutions may it be Chemical Barrel Transportation, Goods in Sea Containers, Grid Box, Refrigerated goods, Cargo on Flat Racks or Cargo in wooden cartons.
For a quick no obligation quote for Dunnage Bags, Strapping and Lashing, or for any other load securing products please complete the form below.
Let us transport your cargo from point A to point B fast and securely.
When is Green Strap not "Green"?
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
import re
import subprocess
from datetime import datetime
def system(*args, **kwargs):
kwargs.setdefault('stdout', subprocess.PIPE)
proc = subprocess.Popen(args, **kwargs)
out, err = proc.communicate()
return out
def now():
"""Current date-time"""
#return str(datetime.now())[:16]
return datetime.now().strftime('%Y-%m-%d %H:%M')
if __name__ == '__main__':
modified = re.compile('^[ACM]+\s+(?P<name>.*\.py)', re.MULTILINE)
files = modified.findall( system('git', 'status', '--porcelain') )
for name in files:
# watching ruby | python | lua scripts
if re.search(r"(\.py|\.rb|\.lua)$", name):
# current script text
with open(name, 'r') as fd: script = fd.read()
# change modification date
script = re.sub('(@changed\s*:\s+)\d{4}-\d{2}-\d{2} \d{2}:\d{2}',
lambda m: m.group(1) + now(), script)
# change script revision
script = re.sub('(@revision\s*:\s+)(\d+)',
lambda m: m.group(1) + str(int(m.group(2))+1), script)
# change script version
script = re.sub('(__version__\s*=\s*\d+\.\d+\.)(\d+)',
lambda m: m.group(1) + str(int(m.group(2))+1), script)
# write back to script
with open(name, 'w') as fd: fd.write(script)
# add changes to commit
system('git', 'add', name)
sys.exit(0)
|
Early in his life Khalil Gibran’s path was that of a freedom fighter pitched against the Ottoman Empire. He was the first Arab in exile to alert the people back home to the oppression visited upon them by their corrupt leaders. Later on he took the path of a seer and a truth seeker, pitched against a tainted self and a tainted humanity. That personal and spiritual struggle culminated in the writing of The Prophet.
This is the story of the difficult birth of a book that is still being read and quoted by millions of people across the world.
|
import base64
import os
from os.path import *
aDirectories = ['templates', 'assets']
sCurrentDir = os.path.dirname(os.path.abspath(__file__))
sTempDir = join(sCurrentDir, 'temporary')
def fnEcodeFilesInDir(in_sCurrentPath, in_sTempPath):
for sFileName in os.listdir(in_sCurrentPath):
sAbsolutePath = join(in_sCurrentPath, sFileName)
sAbsoluteTempPath = join(in_sTempPath, sFileName)
print(sAbsolutePath)
if isdir(sAbsolutePath):
if not isdir(sAbsoluteTempPath):
os.makedirs(sAbsoluteTempPath)
fnEcodeFilesInDir(sAbsolutePath, sAbsoluteTempPath)
for sFileName in os.listdir(in_sCurrentPath):
sAbsolutePath = join(in_sCurrentPath, sFileName)
sAbsoluteTempPath = join(in_sTempPath, sFileName)
print(sAbsolutePath)
if isfile(sAbsolutePath):
try:
objReadFileHandler = file(sAbsolutePath, "r")
sBase64Encoded = base64.b64encode(objReadFileHandler.read())
objWriteFileHandler = file(sAbsoluteTempPath + ".base64", "w")
objWriteFileHandler.write(sBase64Encoded)
objWriteFileHandler.close()
objReadFileHandler.close()
except Exception as objException:
print(objException)
for sDirectory in aDirectories:
sAbsolutePath = join(sCurrentDir, sDirectory)
sAbsoluteTempPath = join(sTempDir, sDirectory)
if isdir(sAbsolutePath):
if not isdir(sAbsoluteTempPath):
os.makedirs(sAbsoluteTempPath)
fnEcodeFilesInDir(sAbsolutePath, sAbsoluteTempPath)
|
Get the 48-Hour Sugar Detox FREE for a Limited Time!
Sugar causes the same reaction in your brain and body as drugs.
STOP DRINKING THAT SODA (even if it’s DIET) AND START FITTING YOUR FAVORITE JEANS!
The reality is that YOU have control of your health!
Hi! I’m Sarah, a certified health coach, and I’ve been there too. I was a complete carb addict and didn’t realize what I was doing to my health until it really started to go downhill. Now I focus on my controlling my sugar intake and have never felt better!
Download this FREE gift now!
Say YES to your health and grab your free detox now!
|
from .forms import TaskForm, TaskPrototypeNameForm, TaskPrototypeForm, \
GenerateTaskForm, RestOfTheTaskPrototypeForm
from .models import Task, TaskProgeny, Verb, TaskPrototype, TaskPrototypeProgeny, \
TaskOwnership, TaskResolution, TaskAccessPrototype, TaskAccess, Protocol
from django import forms
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User, Group
from django.contrib.contenttypes.models import ContentType
from django.db.models import Max, Count, Q
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, redirect, get_object_or_404
from django.template import loader, Context, Template, RequestContext
from django.utils import simplejson
from django.utils.datastructures import MultiValueDictKeyError
from django.views.decorators.cache import never_cache
from what_apps.presence.models import SessionInfo
from taggit.models import Tag
from twilio.util import TwilioCapability
from what_apps.utility.forms import AutoCompleteField
from what_apps.mellon.models import Privilege, get_privileges_for_user
from what_apps.people.models import GenericParty
from what_apps.social.forms import DrawAttentionAjaxForm, MessageForm
from what_apps.social.models import TopLevelMessage
from what_apps.social.views import post_top_level_message
import stomp
import json
#from twilio.Utils import token
T = ContentType.objects.get_for_model(Task)
@login_required
def landing(request):
tasks = Task.objects.can_be_seen_by_user(request.user).order_by('-created')
manual_tasks = tasks.filter(ownership__isnull = True).exclude(creator__username = "AutoTaskCreator")[:10]
task_messages = TopLevelMessage.objects.filter(content_type = T).order_by('-created')[:7]
return render(request, 'do/do_landing.html', locals())
def public_list(request):
'''
Displays tasks that are viewable with the privilege "Anybody in <group_name>"
'''
if not request.user.is_authenticated():
try:
group_name = request.GET['group']
except MultiValueDictKeyError:
return HttpResponseRedirect('/presence/login?next=/do/public_list/')
group = Group.objects.get(name=group_name)
privilege = get_object_or_404(Privilege, prototype__name="Anybody", jurisdiction=group)
access_objects = TaskAccess.objects.filter(prototype__privilege = privilege)
verbs = Verb.objects.filter(prototypes__instances__resolutions__isnull = True).annotate(num_tasks=Count('prototypes__instances')).order_by('-num_tasks')
else:
verbs = Verb.objects.filter(prototypes__instances__resolutions__isnull = True).annotate(num_tasks=Count('prototypes__instances')).order_by('-num_tasks')
tags = Tag.objects.filter(taggit_taggeditem_items__content_type = T).distinct() #TODO: Privileges
return render(request,
'do/three_column_task_list.html',
locals()
)
@never_cache
@login_required
def big_feed(request):
'''
Look at the big board! They're gettin' ready to clobber us!
'''
user_privileges = get_privileges_for_user(request.user)
tasks = Task.objects.filter(access_requirements__prototype__privilege__in = user_privileges, resolutions__isnull = True).order_by('-created')[:10]
ownerships = list(TaskOwnership.objects.filter(task__resolutions__isnull=True).order_by('-created')[:10])
task_messages = list(TopLevelMessage.objects.filter(content_type = T))
task_resolutions = list(TaskResolution.objects.order_by('-created')[:10])
sessions = list(SessionInfo.objects.order_by('-created')[:10])
task_activity = task_messages + task_resolutions + ownerships + sessions
sorted_task_activity = sorted(task_activity, key=lambda item: item.created, reverse=True)[:10]
activity_list = []
for item in sorted_task_activity:
activity_list.append((item, str(item._meta).split('.')[1]))
return render(request,
'do/do_news_feed.html',
locals()
)
#def three_column_task_list(request):
#
# verbs = Verb.objects.annotate(tasks = Count('prototypes__instances')).order_by('-tasks')
#
# return render(request,
# 'do/three_column_task_list.html',
# locals()
# )
@login_required
def task_profile(request, task_id):
task = get_object_or_404(Task, id = task_id)
#It wasn't bad enough that the actual create form was wet and silly. Now this too. TODO: FIX THIS FUCKER.
user_can_make_new_prototypes = True #TODO: Turn this into an actual privilege assessment
task_prototype_name_form = TaskPrototypeNameForm()
task_prototype_name_form.fields['name'].widget.attrs['class'] = "topLevel" #So that we can recognize it later via autocomplete.
rest_of_the_task_prototype_form = RestOfTheTaskPrototypeForm()
user_privileges = get_privileges_for_user(request.user)
#Wet and silly. TODO: Fix
class SimpleChildForm(forms.Form):
child = AutoCompleteField(models = (TaskPrototype,), name_visible_field=True)
class SimpleParentForm(forms.Form):
parent = AutoCompleteField(models = (TaskPrototype,), name_visible_field=True)
task_prototype_form = TaskPrototypeForm()
task_prototype_parent_form = SimpleParentForm()
task_prototype_child_form = SimpleChildForm()
draw_attention_ajax_form = DrawAttentionAjaxForm()
if task.prototype.id == 251 or task.prototype.id == 7:
has_outgoing_call = True
disable_incoming_calls = True
account_sid = "AC260e405c96ce1eddffbddeee43a13004"
auth_token = "fd219130e257e25e78613adc6c003d1a"
capability = TwilioCapability(account_sid, auth_token)
capability.allow_client_outgoing("APd13a42e60c91095f3b8683a77ee2dd05")
#The text of the call recipient will be the name of the person in the case of a tech job. It will be the output of the unicode method of the PhoneNumber in the case of a PhoneCall resolution.
if task.prototype.id == 251:
call_to_name = task.related_objects.all()[0].object.get_full_name()
related_user = task.related_objects.all()[0].object
phone_numbers = task.related_objects.all()[0].object.userprofile.contact_info.phone_numbers.all()
if task.prototype.id == 7:
phone_numbers = [task.related_objects.all()[0].object.from_number]
if task.related_objects.all()[0].object.from_number.owner:
call_to_name = task.related_objects.all()[0].object.from_number.owner
else:
call_to_name = "Phone Number #%s" % (str(task.related_objects.all()[0].object.id))
return render(request,
'do/task_profile.html',
locals()
)
@login_required
def task_prototype_profile(request, task_prototype_id):
'''
Profile page for Task Prototypes.
Allows editing, adding of children or parents, merging / evolving, etc.
'''
tp = get_object_or_404(TaskPrototype, id = task_prototype_id)
task_prototype_form = TaskPrototypeForm(instance=tp)
generate_form = GenerateTaskForm()
return render(request, 'do/task_prototype_profile.html', locals())
#TODO: Security
def own_task(request, task_id):
task = Task.objects.get(id=task_id)
ownership, newly_owned = task.ownership.get_or_create(owner=request.user)
t = loader.get_template('do/task_box.html')
c = RequestContext(request, {'task':task})
if not task.access_requirements.exists(): #We only want to push publically viewable tasks.
#Pushy Stuff
conn = stomp.Connection()
conn.start()
conn.connect()
task_box_dict = {
'verb_id': task.prototype.type.id,
'task_id': task.id,
'box': t.render(c),
}
conn.send(simplejson.dumps(task_box_dict), destination="/do/new_tasks")
response_json = { 'success': 1, 'newly_owned':newly_owned, 'task_id': task.id, 'box': t.render(c) }
return HttpResponse( json.dumps(response_json) )
def get_taskbox_toot_court(request, task_id):
task = Task.objects.get(id=task_id)
return render(request, 'do/task_box.html', locals())
#TODO: Ensure permissions
def create_task(request):
'''
This is one of the worst views I have ever written. -Justin
'''
user_can_make_new_prototypes = True #TODO: Turn this into an actual privilege assessment
task_prototype_name_form = TaskPrototypeNameForm()
task_prototype_name_form.fields['name'].widget.attrs['class'] = "topLevel" #So that we can recognize it later via autocomplete. TODO: DO this in the form object.
rest_of_the_task_prototype_form = RestOfTheTaskPrototypeForm() #TODO: Can we please. please. please make this one object.
#Wet and silly. TODO: Fix
class SimpleChildForm(forms.Form):
child = AutoCompleteField(models = (TaskPrototype,), name_visible_field=True)
class SimpleParentForm(forms.Form):
parent = AutoCompleteField(models = (TaskPrototype,), name_visible_field=True)
task_prototype_form = TaskPrototypeForm()
task_prototype_parent_form = SimpleParentForm()
task_prototype_child_form = SimpleChildForm()
user_privileges = get_privileges_for_user(request.user)
try: #WHAT ON GODS GREEN FUCKING SERVER IS HAPPENING HERE
task_prototype_form.fields['name'].initial = request.GET['name']
except:
pass
return render(request, 'do/create_task_prototype.html', locals())
def task_form_handler(request):
'''
Deal with the task form. There's a lot of stuff that needs tweaking in here.
'''
task_prototype_name_form = TaskPrototypeNameForm()
name = request.POST['lookup_name'] #Set the name to the actual lookup field TODO: Yeah... have we checked that this form is valid? Do we care?
#Now let's figure out if they are trying to create a new prototype or just a new task.
try:
this_tp = TaskPrototype.objects.get(name=name)
new = False
except TaskPrototype.DoesNotExist:
verb = Verb.objects.get(id=request.POST['type'])
this_tp = TaskPrototype.objects.create(name=name, type=verb, creator=request.user)
new = True
if not new:
#If this TaskPrototype is not new, all we're going to do is generate its task.
task = this_tp.instantiate(request.user) #Generate the task with the current user as the creator
if new:
#Figure out the relations that were entered. We'll only do that for existing TaskPrototypes.
relations = ['parent', 'child']
for relation in relations:
counter = 1
suffix = relation #For the first iteration, we need it to just say "parent"
while True:
try:
if request.POST['lookup_' + suffix]:
autocompleted_object = task_prototype_name_form.fields['name'].to_python(request.POST[suffix]) #Use the autocopmlete field's to_python method to grab the object
if autocompleted_object:
related_object = autocompleted_object
else: #They didn't successfully autocomplete; looks like we're making an object up unless the name happens to be an exact match.
what_they_typed = request.POST['lookup_' + suffix]
related_object, is_new = TaskPrototype.objects.get_or_create(name = what_they_typed, defaults={'type': this_tp.type, 'creator': request.user})
#At this point in the function, we now know for sure what the related object is. Either they autocompleted, typed a name that matched but didn't autocopmlete, or they're making a new one.
if relation == "child":
parent = this_tp
child = related_object
priority = (counter * 5)
if relation == "parent":
parent = related_object
child = this_tp
current_max_priority_ag = related_object.children.all().aggregate(Max('priority'))
current_max_priority = current_max_priority_ag['priority__max']
try:
priority = int(current_max_priority) + 5 #Try setting the priority to the highest priority plus 5
except TypeError:
priority = 5 #Fuck it, there is no priority at all; we'll start it at 5
TaskPrototypeProgeny.objects.create(parent = parent, child = child, priority = priority )
else:
break
except MultiValueDictKeyError:
break
counter += 1
suffix = relation + str(counter) #Preparing for the second iteration, it says "parent1"
try:
if request.POST['no_generate']: #They clicked 'prototype only,' so they don't want us to run .instantiate()
pass
except: #They didn't click "prototype only," thus they want the Task to be generated.
task = this_tp.instantiate(request.user) #Generate the task with the current user as the creator
#Now we'll deal with the access requirements.
privilege = Privilege.objects.get(id = request.POST['access_requirement'])
task_access_prototype = TaskAccessPrototype.objects.get_or_create(privilege = privilege, type=5)[0] #Hardcoded 5 - this ought to be an option in the form
task_access = TaskAccess.objects.create(prototype=task_access_prototype, task = task)
#I mean, seriously, shouldn't this be a post-save hook?
if task:
messages.success(request, 'You created <a href="%s">%s</a>.' % (task.get_absolute_url(), this_tp.name)) #TODO: Distinguish messages between creation of TaskPrototype and Task objects.
else:
messages.success(request, 'You created %s.' % this_tp.name) #TODO: Distinguish messages between creation of TaskPrototype and Task objects.
#We may have arrived here from the Task Profile form or some other place where at least one parent is certain. Let's find out.
try:
parent_ipso_facto_id = request.POST['parentIdIpsoFacto']
parent_task = Task.objects.get(id=parent_ipso_facto_id) #By jove, it's tru! Our new task already has a parent Task.
current_max_priority_ag = parent_task.children.all().aggregate(Max('priority'))
current_max_priority = current_max_priority_ag['priority__max']
try: #TODO: Boy, it's started to feel like we need a max_priority method, eh?
priority = int(current_max_priority) + 5 #Try setting the priority to the highest priority plus 5
except TypeError:
priority = 5 #Fuck it, there is no priority at all; we'll start it at 5
task_progeny = TaskProgeny.objects.create(parent=parent_task, child=task, priority = priority)
return HttpResponseRedirect(parent_task.get_absolute_url())
except MultiValueDictKeyError:
pass #Nope, guess not.
return HttpResponseRedirect('/do/create_task') #TODO: Dehydrate this using the reverse of the create task view.
@login_required
def new_child_ajax_handler(request):
form = TaskForm(request.POST)
if form.is_valid():
#First create the child task.
new_child_task = form.save()
#Now create the relationship to the parent.
try:
parent_id = request.POST['parent_id']
parent_task = Task.objects.get(id = parent_id)
siblings = parent_task.children.all() #Siblings of the task we just created
highest_order_rank = siblings.aggregate(Max('order_rank'))['order_rank__max']
if highest_order_rank:
new_order_rank = highest_order_rank + 1
else:
new_order_rank = 1
hierarchy = TaskProgeny.objects.create(child = new_child_task, parent = parent_task, order_rank = new_order_rank)
return HttpResponse(1)
except IndexError:
raise RuntimeError('The Parent ID got yanked from the form. Not cool.')
else:
#TODO: This is an exact repeat of the invalid handler in utility.views.submit_generic. DRY it up.
errors = []
for error in form.errors:
errors.append(error)
dumps = simplejson.dumps(errors)
return HttpResponse(dumps)
#TODO: Check that the user has proper authority
def task_family_as_checklist_template(request):
'''
Takes a Task or TaskPrototype and returns the children as a checklist template.
I don't love this function. It can be far more generic and helpful with a little tinkering. -Justin
'''
is_prototype = request.GET['is_prototype'] #Are we looking for a Task or a TaskPrototype?
id = request.GET['id']
try:
number_to_show = request.GET['limit'] #Maybe they specified a number of children to list....
except KeyError:
number_to_show = False #....maybe they didn't.
task_maybe_prototype_model = TaskPrototype if is_prototype else Task
task_maybe_prototype = task_maybe_prototype_model.objects.get(id=id)
model_name = task_maybe_prototype_model.__name__
progeny_objects = task_maybe_prototype.children.all()
if number_to_show:
progeny_objects = progeny_objects.limit(number_to_show)
return render(request, 'do/children_checklist.html', locals())
def task_prototype_list(request):
task_prototypes = TaskPrototype.objects.all()
return render(request, 'do/task_prototype_list.html', locals())
def get_people_for_verb_as_html(request, verb_id):
'''
Shows peoples' names in the public list page.
'''
verb = Verb.objects.get(id=verb_id)
people = verb.users_who_have_completed_tasks()
return render(request, 'do/people_list.html', locals() )
def get_tasks_as_html(request, object_id, by_verb=True, mix_progeny=False):
'''
Ajax specialized method that returns, in HTML, all the tasks to which a user has access within a specific verb or tag.
If verb is true, get by task. Otherwise, by tag.
Typical use case is a refresh signal sent by the push module or a click on the "three columns" page.
'''
if not by_verb:
tag = Tag.objects.get(id=object_id)
tagged_tasks = tag.taggit_taggeditem_items.filter(content_type = T) #TODO: Apply privileges
if not request.user.is_authenticated():
group_name = request.GET['group']
group = Group.objects.get(name=group_name)
privilege = get_object_or_404(Privilege, prototype__name="Anybody", jurisdiction=group)
access_objects = TaskAccess.objects.filter(prototype__privilege = privilege)
access_tasks = Task.objects.filter(access_requirements__in = access_objects, resolutions__isnull=True).distinct()
if by_verb:
verb = Verb.objects.get(id=object_id)
tasks = access_tasks.filter(prototype__type = verb)
else:
tasks_from_tag = tagged_tasks.filter(task__access_requirements__in = access_objects, resolutions__isnull=True).distinct()
tasks = set()
for task_from_tag in tasks_from_tag:
tasks.add(task_from_tag.content_object)
else: #They're logged in.
if by_verb:
verb = Verb.objects.get(id=object_id)
tasks = verb.get_tasks_for_user(request.user)
else:
tasks_from_tag = tagged_tasks #TODO: Again, privileges
tasks = set()
for task_from_tag in tasks_from_tag:
if task_from_tag.content_object.resolutions.count() == 0:
tasks.add(task_from_tag.content_object)
if not mix_progeny:
#Let's make sure that no child task is listed alongside its parent.
tasks_to_remove = set()
for task in tasks:
for progeny in task.parents.all():
if progeny.parent in tasks:
tasks_to_remove.add(task)
task_set = set(tasks) - tasks_to_remove
tasks = task_set
return render(request, 'do/task_list.html', locals())
#TODO: Security
def mark_completed(request, task_id):
task = Task.objects.get(id=task_id)
resolution = TaskResolution.objects.create(task=task, type="C", creator=request.user)
return HttpResponse(1)
def mark_abandoned(request):
return HttpResponse(1)
def update_task(request, task_id):
task = Task.objects.get(id=task_id)
task.update_to_prototype(user=request.user)
return redirect(task.get_absolute_url())
@login_required
def post_task_message(request, task_id):
'''
Take a message about a task. See if the task is complete and mark it so if so.
If the message field is not blank, send it to the social view to handle the text of the message.
'''
task = Task.objects.get(id=task_id)
try:
if request.POST['completed']:
task.set_status(2, request.user)
except MultiValueDictKeyError:
pass #They didn't mark it completed, no need to think about it further.
if request.POST['message']:
post_top_level_message(request, 'do__task__%s' % (task_id))
return HttpResponseRedirect(task.get_absolute_url())
def protocols(request):
'''
SlashRoot's policies, procedures, and protocols listed here.
Perhaps this will be eliminated once we get the organization of tasks under better control since most of these will be tasks.
'''
protocols = Protocol.objects.all()
return render(request,'do/protocols.html',{'protocols':protocols})
def archives(request):
#completed_tasks = TaskResolution.objects.filter(type='C').order_by('-created')
tasks = SERVICE_PROTOTYPE.instances.filter(status__gt=1).all()
return render(request, 'do/archives.html', locals())
|
A eu safety structure after the chilly warfare presents a severe account of the re-projection and redefinition of Western values and defense associations within the post-Coldwar period. this alteration is explored in 3 phases. the 1st level covers the interval 1990-91 and explains the renovation of a `western protection neighborhood' inherited from the chilly warfare, via a strategy of institutional reconstruction mostly conducted on paper. the second one level from 1991 to 1992 sees the incorporation of a `purpose' for those associations as a framework for the implementation of collective safeguard. The 3rd degree explores the rising questions of legitimacy surrounding the hot projects of those associations as they develop into embroiled within the struggle within the former Yugoslavia. The precedents of valid intervention in upholding democracy, loose markets and human rights within the post-coldwar period are tested from the views of foreign legislations and Gramscian derived ideas of legitimacy, targeting the reputation of army energy by way of civil society, and the way intervention in those phrases turns into a 'cultural practice'.
Rural parts are usually considered as remoted and stagnating components and concrete components as their opposites. opposed to any such backdrop, this booklet seeks to unveil a suite of dynamics that view rural components as ‘translocal’ within the feel that they're ‘changing’ and ‘interconnected’. Social variations ensue in rural parts because the results of extreme exchanges among various humans, settings and geographies.
This quantity combines the theoretical and ancient point of view targeting the categorical positive aspects of a eu philosophy of technology. at the celebration of the twentieth anniversary of the Institute Vienna Circle the Viennese roots and affects may be addressed, furthermore. there is not any doubt that modern philosophy of technological know-how originated typically in Europe starting within the nineteenth century and has stimulated decisively the next improvement of globalized philosophy of technological know-how, esp.
This ebook constitutes the completely reviewed post-proceedings of the ninth foreign Workshop, EUMAS 2011, held in Maastricht, The Netherlands, in November 2011. The sixteen revised complete papers incorporated within the ebook have been conscientiously revised and chosen from forty five submissions. This workshop is essentially meant as a eu discussion board at which researchers and people drawn to actions in relation to learn within the sector of self sustaining brokers and multi-agent structures may possibly meet, current (potentially initial) study effects, difficulties, and concerns in an open and casual yet educational setting.
This publication constitutes the refereed lawsuits of the ninth ecu PVM/MPI Users'Group assembly held in Linz, Austria in September/October 2002. The 50 revised complete papers offered including abstracts of eleven invited contributions have been rigorously reviewed and chosen. The papers are geared up in topical sections on Corss Grid, Par Sim, software utilizing MPI and PVM, parallel algorithms utilizing message passing, programming instruments for MPI and PVM, implementations of MPI and PVM, extensions of MPI and PVM, and function research and optimization.
There is no explanation as to what would motivate national governments to share a large sum of small technical activities in the first place, unless the circumstances were such that the production of a much needed commodity was impossible without cooperation between states, involving the pooling of national resources, as well as production techniques. In that case, the functionalist explanation for cooperation between states would be dependent on this condition every time. Unlike federalism, functionalism sees no need for authority or power to be prescribed in advance.
41 On the whole, there is no empirical evidence of a continuous process of spill over in the European region. 42 The ECSC experience was a slice out of history which corresponded to the process of integration in neo-functionalism. But since then, this has not been repeated on a continuous scale as the neofunctionalists had expected. Also in the 1970s, writers started to turn to examine the effects of external dynamics on integration, whereas earlier studies of neo-functionalism had focused on internal dynamics such as elite calculations of loss or gain.
The result is the emergence and growth of an embryonic political community. 31 Unlike functionalism, neo-functionalism recognises the role of central institutions with policy making powers. These play an important role in the integration process because policies made by the central institution will draw in the other key groups such as business and labour, and the central institution will trigger changes in the behaviour of these groups. It is then hoped that this group pressure for common policy will spill over to the federal sphere of high politics.
|
# Copyright (c) 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved
#
# 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, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing 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 MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR 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.
#
import os
import json
import docutils.core
class TopicTagDB(object):
"""This class acts like a database for the tags of all available topics.
A tag is an element in a topic reStructured text file that contains
information about a topic. Information can range from titles to even
related CLI commands. Here are all of the currently supported tags:
Tag Meaning Required?
--- ------- ---------
:title: The title of the topic Yes
:description: Sentence description of topic Yes
:category: Category topic falls under Yes
:related topic: A related topic No
:related command: A related command No
To see examples of how to specify tags, look in the directory
awscli/topics. Note that tags can have multiple values by delimiting
values with commas. All tags must be on their own line in the file.
This class can load a JSON index represeting all topics and their tags,
scan all of the topics and store the values of their tags, retrieve the
tag value for a particular topic, query for all the topics with a specific
tag and/or value, and save the loaded data back out to a JSON index.
The structure of the database can be viewed as a python dictionary:
{'topic-name-1': {
'title': ['My First Topic Title'],
'description': ['This describes my first topic'],
'category': ['General Topics', 'S3'],
'related command': ['aws s3'],
'related topic': ['topic-name-2']
},
'topic-name-2': { .....
}
The keys of the dictionary are the CLI command names of the topics. These
names are based off the name of the reStructed text file that corresponds
to the topic. The value of these keys are dictionaries of tags, where the
tags are keys and their value is a list of values for that tag. Note
that all tag values for a specific tag of a specific topic are unique.
"""
VALID_TAGS = ['category', 'description', 'title', 'related topic',
'related command']
# The default directory to look for topics.
TOPIC_DIR = os.path.join(
os.path.dirname(
os.path.abspath(__file__)), 'topics')
# The default JSON index to load.
JSON_INDEX = os.path.join(TOPIC_DIR, 'topic-tags.json')
def __init__(self, tag_dictionary=None, index_file=JSON_INDEX,
topic_dir=TOPIC_DIR):
"""
:param index_file: The path to a specific JSON index to load.
If nothing is specified it will default to the default JSON
index at ``JSON_INDEX``.
:param topic_dir: The path to the directory where to retrieve
the topic source files. Note that if you store your index
in this directory, you must supply the full path to the json
index to the ``file_index`` argument as it may not be ignored when
listing topic source files. If nothing is specified it will
default to the default directory at ``TOPIC_DIR``.
"""
self._tag_dictionary = tag_dictionary
if self._tag_dictionary is None:
self._tag_dictionary = {}
self._index_file = index_file
self._topic_dir = topic_dir
@property
def index_file(self):
return self._index_file
@index_file.setter
def index_file(self, value):
self._index_file = value
@property
def topic_dir(self):
return self._topic_dir
@topic_dir.setter
def topic_dir(self, value):
self._topic_dir = value
@property
def valid_tags(self):
return self.VALID_TAGS
def load_json_index(self):
"""Loads a JSON file into the tag dictionary."""
with open(self.index_file, 'r') as f:
self._tag_dictionary = json.load(f)
def save_to_json_index(self):
"""Writes the loaded data back out to the JSON index."""
with open(self.index_file, 'w') as f:
f.write(json.dumps(self._tag_dictionary, indent=4, sort_keys=True))
def get_all_topic_names(self):
"""Retrieves all of the topic names of the loaded JSON index"""
return list(self._tag_dictionary)
def get_all_topic_src_files(self):
"""Retrieves the file paths of all the topics in directory"""
topic_full_paths = []
topic_names = os.listdir(self.topic_dir)
for topic_name in topic_names:
# Do not try to load hidden files.
if not topic_name.startswith('.'):
topic_full_path = os.path.join(self.topic_dir, topic_name)
# Ignore the JSON Index as it is stored with topic files.
if topic_full_path != self.index_file:
topic_full_paths.append(topic_full_path)
return topic_full_paths
def scan(self, topic_files):
"""Scan in the tags of a list of topics into memory.
Note that if there are existing values in an entry in the database
of tags, they will not be overwritten. Any new values will be
appended to original values.
:param topic_files: A list of paths to topics to scan into memory.
"""
for topic_file in topic_files:
with open(topic_file, 'r') as f:
# Parse out the name of the topic
topic_name = self._find_topic_name(topic_file)
# Add the topic to the dictionary if it does not exist
self._add_topic_name_to_dict(topic_name)
topic_content = f.read()
# Record the tags and the values
self._add_tag_and_values_from_content(
topic_name, topic_content)
def _find_topic_name(self, topic_src_file):
# Get the name of each of these files
topic_name_with_ext = os.path.basename(topic_src_file)
# Strip of the .rst extension from the files
return topic_name_with_ext[:-4]
def _add_tag_and_values_from_content(self, topic_name, content):
# Retrieves tags and values and adds from content of topic file
# to the dictionary.
doctree = docutils.core.publish_doctree(content).asdom()
fields = doctree.getElementsByTagName('field')
for field in fields:
field_name = field.getElementsByTagName('field_name')[0]
field_body = field.getElementsByTagName('field_body')[0]
# Get the tag.
tag = field_name.firstChild.nodeValue
if tag in self.VALID_TAGS:
# Get the value of the tag.
values = field_body.childNodes[0].firstChild.nodeValue
# Seperate values into a list by splitting at commas
tag_values = values.split(',')
# Strip the white space around each of these values.
for i in range(len(tag_values)):
tag_values[i] = tag_values[i].strip()
self._add_tag_to_dict(topic_name, tag, tag_values)
else:
raise ValueError(
"Tag %s found under topic %s is not supported."
% (tag, topic_name)
)
def _add_topic_name_to_dict(self, topic_name):
# This method adds a topic name to the dictionary if it does not
# already exist
# Check if the topic is in the topic tag dictionary
if self._tag_dictionary.get(topic_name, None) is None:
self._tag_dictionary[topic_name] = {}
def _add_tag_to_dict(self, topic_name, tag, values):
# This method adds a tag to the dictionary given its tag and value
# If there are existing values associated to the tag it will add
# only values that previously did not exist in the list.
# Add topic to the topic tag dictionary if needed.
self._add_topic_name_to_dict(topic_name)
# Get all of a topics tags
topic_tags = self._tag_dictionary[topic_name]
self._add_key_values(topic_tags, tag, values)
def _add_key_values(self, dictionary, key, values):
# This method adds a value to a dictionary given a key.
# If there are existing values associated to the key it will add
# only values that previously did not exist in the list. All values
# in the dictionary should be lists
if dictionary.get(key, None) is None:
dictionary[key] = []
for value in values:
if value not in dictionary[key]:
dictionary[key].append(value)
def query(self, tag, values=None):
"""Groups topics by a specific tag and/or tag value.
:param tag: The name of the tag to query for.
:param values: A list of tag values to only include in query.
If no value is provided, all possible tag values will be returned
:rtype: dictionary
:returns: A dictionary whose keys are all possible tag values and the
keys' values are all of the topic names that had that tag value
in its source file. For example, if ``topic-name-1`` had the tag
``:category: foo, bar`` and ``topic-name-2`` had the tag
``:category: foo`` and we queried based on ``:category:``,
the returned dictionary would be:
{
'foo': ['topic-name-1', 'topic-name-2'],
'bar': ['topic-name-1']
}
"""
query_dict = {}
for topic_name in self._tag_dictionary.keys():
# Get the tag values for a specified tag of the topic
if self._tag_dictionary[topic_name].get(tag, None) is not None:
tag_values = self._tag_dictionary[topic_name][tag]
for tag_value in tag_values:
# Add the values to dictionary to be returned if
# no value constraints are provided or if the tag value
# falls in the allowed tag values.
if values is None or tag_value in values:
self._add_key_values(query_dict,
key=tag_value,
values=[topic_name])
return query_dict
def get_tag_value(self, topic_name, tag, default_value=None):
"""Get a value of a tag for a topic
:param topic_name: The name of the topic
:param tag: The name of the tag to retrieve
:param default_value: The value to return if the topic and/or tag
does not exist.
"""
if topic_name in self._tag_dictionary:
return self._tag_dictionary[topic_name].get(tag, default_value)
return default_value
def get_tag_single_value(self, topic_name, tag):
"""Get the value of a tag for a topic (i.e. not wrapped in a list)
:param topic_name: The name of the topic
:param tag: The name of the tag to retrieve
:raises VauleError: Raised if there is not exactly one value
in the list value.
"""
value = self.get_tag_value(topic_name, tag)
if value is not None:
if len(value) != 1:
raise ValueError(
'Tag %s for topic %s has value %. Expected a single '
'element in list.' % (tag, topic_name, value)
)
value = value[0]
return value
|
The DC Tester is a Voltage and Ampere breakout for measuring DC current from 0-26V at 3.2A Max, when used with the USB Tester. The DC jacks make it easy a wider variety of devices. You can easily put this in inline between your power supply and your project. Just like the USB Tester. Except now you can use this for any project that isn't USB powered. Then you can probe the voltage or current with your DMM (Digital Multi-Meter).
If you have an OLED Backpack, this will allow you to swap it out with the USB Tester, view the output on the display as well as data log it with the Java app (it will be updated for higher voltage). Due to the wide voltage ranges of the DC Tester, the OLED Backpack will need its own power source. It can be your computer, a phone charger or a USB Battery pack.
Depending on how you use it, you may need to do some soldering. The soldering is pretty easy to do. For an additional fee, we’re happy to solder for you, just be sure to select the option when ordering.
|
import sys
import click
from openelex.base.fetch import BaseFetcher
from .utils import default_state_options, load_module
@click.command(help="Scrape data files and store in local file cache "
"under standardized name")
@default_state_options
@click.option('--unprocessed', is_flag=True,
help="Fetch unprocessed data files only")
def fetch(state, datefilter='', unprocessed=False):
"""
Scrape data files and store in local file cache
under standardized name.
State is required. Optionally provide 'datefilter'
to limit files that are fetched.
"""
state_mod = load_module(state, ['datasource', 'fetch'])
datasrc = state_mod.datasource.Datasource()
if hasattr(state_mod, 'fetch'):
fetcher = state_mod.fetch.FetchResults()
else:
fetcher = BaseFetcher(state)
if unprocessed:
try:
filename_url_pairs = datasrc.unprocessed_filename_url_pairs(datefilter)
except NotImplementedError:
sys.exit("No unprocessed data files are available. Try running this "
"task without the --unprocessed option.")
else:
filename_url_pairs = datasrc.filename_url_pairs(datefilter)
for std_filename, url in filename_url_pairs:
fetcher.fetch(url, std_filename)
|
The new iPad mobile poker app from 888 is finally here, offering plenty of brand new multi-table tournament action in addition to the traditional Sit and Go’s and ring games. The new app is available in the iTunes store for players from the United Kingdom, Russian, Sweden, Germany, Ireland, Portugal, Greece, Czech Republic, Romania, Luxembourg, Finland, Slovakia, Slovenia, Malta, Austria, Hungary, Poland, Latvia, Lithuania and Cyprus. Unlike several other apps with multi-table tournament functionality, 888 boasts full access to pre-scheduled events, complete with tournament tickets and freerolls.
Inbal Lavi, Vice President of 888, had the following to say regarding the new app: “the new 888poker Application is another great milestone for our poker offering. We continually strive to give our players the most entertaining, easy poker experience and now they have full access to more games and prizes while they are on the go.” The new release from 888 is accompanied by a special series of freerolls, allowing iPad owners to join the action right now a compete for prize pools totaling more than $400,000 without paying as much as a single penny. Basically, all 888 customers will receive a free ticket for the a £30,000/$50,000 GIANT Freeroll Tournament, which will be offered twice a week for the duration of this promotion.
The new 888 tournament apps can be downloaded here or you can read the complete review.
|
# vim:fileencoding=utf-8:noet
from powerline.renderer import Renderer
from powerline.colorscheme import ATTR_BOLD, ATTR_ITALIC, ATTR_UNDERLINE
def int_to_rgb(num):
r = (num >> 16) & 0xff
g = (num >> 8) & 0xff
b = num & 0xff
return r, g, b
class ShellRenderer(Renderer):
'''Powerline shell segment renderer.'''
escape_hl_start = ''
escape_hl_end = ''
term_truecolor = False
tmux_escape = False
screen_escape = False
def hlstyle(self, fg=None, bg=None, attr=None):
'''Highlight a segment.
If an argument is None, the argument is ignored. If an argument is
False, the argument is reset to the terminal defaults. If an argument
is a valid color or attribute, it's added to the ANSI escape code.
'''
ansi = [0]
if fg is not None:
if fg is False or fg[0] is False:
ansi += [39]
else:
if self.term_truecolor:
ansi += [38, 2] + list(int_to_rgb(fg[1]))
else:
ansi += [38, 5, fg[0]]
if bg is not None:
if bg is False or bg[0] is False:
ansi += [49]
else:
if self.term_truecolor:
ansi += [48, 2] + list(int_to_rgb(bg[1]))
else:
ansi += [48, 5, bg[0]]
if attr is not None:
if attr is False:
ansi += [22]
else:
if attr & ATTR_BOLD:
ansi += [1]
elif attr & ATTR_ITALIC:
# Note: is likely not to work or even be inverse in place of
# italic. Omit using this in colorschemes.
ansi += [3]
elif attr & ATTR_UNDERLINE:
ansi += [4]
r = '\033[{0}m'.format(';'.join(str(attr) for attr in ansi))
if self.tmux_escape:
r = '\033Ptmux;' + r.replace('\033', '\033\033') + '\033\\'
elif self.screen_escape:
r = '\033P' + r.replace('\033', '\033\033') + '\033\\'
return self.escape_hl_start + r + self.escape_hl_end
@staticmethod
def escape(string):
return string.replace('\\', '\\\\')
renderer = ShellRenderer
|
Pledge your birthday, and make a difference. Instead of asking for gifts or giving them, ask or give a donation.
Thank you for your birthday pledge! We will be in touch with you soon. We hope that you, or your loved one, have a fantastic day.
The Khan Ohana Foundation is a 501(c)(3) tax deductible charity.
|
# Python script to copy AIPS VL tables
import Table, Image, OErr, OSystem
# Init Obit
err=OErr.OErr()
ObitSys=OSystem.OSystem ("CopyVLTables", 1, 103, 1, ["None"],
2, ["../FITSdata/","/mnt/cdrom/MAPS/"], 1, 0, err)
OErr.printErrMsg(err, "Error with Obit startup")
outfile = "Catalog.fits"
outdisk = 1
indisk = 2
def AppendVLTable (infile, outfile=outfile, err=err):
""" Copy VL table ver 1 from infile to outfile
infile = name of input FITS image file with VL table
outfile = name of output FITS image file with extant VL table
err = Python Obit Error/message stack
"""
################################################################
# Get images
inImage = Image.newPImage("Input image", infile, indisk, 1, err)
outImage = Image.newPImage("Output image", outfile, outdisk, 1, err)
OErr.printErrMsg(err, "Error creating image objects")
#
# obtain "AIPS VL" tables from each
inTable = Image.PImageNewImageTable(inImage, 1, "AIPS VL", 1, err)
outTable = Image.PImageNewImageTable(outImage, 3, "AIPS VL", 1, err)
OErr.printErrMsg(err, "Error extracting AIPS VL table objects")
# Concatenate
Table.PConcat (inTable, outTable, err)
OErr.printErrMsg(err, "Error concatenatinfg tables")
print "Appended",infile,"to",outfile
# end AppendVLTable
# CD 4 of NVSS
AppendVLTable ("I1808M04.gz")
AppendVLTable ("I1808M08.gz")
AppendVLTable ("I1808M12.gz")
AppendVLTable ("I1808M16.gz")
#no table AppendVLTable ("I1808M20.gz")
AppendVLTable ("I1808M24.gz")
AppendVLTable ("I1808M28.gz")
AppendVLTable ("I1808P00.gz")
AppendVLTable ("I1808P04.gz")
AppendVLTable ("I1808P08.gz")
AppendVLTable ("I1808P12.gz")
AppendVLTable ("I1808P16.gz")
AppendVLTable ("I1808P20.gz")
AppendVLTable ("I1808P24.gz")
AppendVLTable ("I1808P28.gz")
AppendVLTable ("I1818M32.gz")
AppendVLTable ("I1818M36.gz")
AppendVLTable ("I1818P32.gz")
AppendVLTable ("I1818P36.gz")
AppendVLTable ("I1820M40.gz")
AppendVLTable ("I1820P40.gz")
AppendVLTable ("I1820P44.gz")
AppendVLTable ("I1820P48.gz")
AppendVLTable ("I1824M04.gz")
AppendVLTable ("I1824M08.gz")
AppendVLTable ("I1824M12.gz")
AppendVLTable ("I1824M16.gz")
AppendVLTable ("I1824M20.gz")
AppendVLTable ("I1824M24.gz")
AppendVLTable ("I1824M28.gz")
AppendVLTable ("I1824P00.gz")
AppendVLTable ("I1824P04.gz")
AppendVLTable ("I1824P08.gz")
AppendVLTable ("I1824P12.gz")
AppendVLTable ("I1824P16.gz")
AppendVLTable ("I1824P20.gz")
AppendVLTable ("I1824P24.gz")
AppendVLTable ("I1824P28.gz")
AppendVLTable ("I1824P52.gz")
AppendVLTable ("I1824P56.gz")
AppendVLTable ("I1830P60.gz")
AppendVLTable ("I1830P64.gz")
AppendVLTable ("I1836M32.gz")
AppendVLTable ("I1836M36.gz")
AppendVLTable ("I1836P32.gz")
AppendVLTable ("I1836P36.gz")
AppendVLTable ("I1836P68.gz")
AppendVLTable ("I1840M04.gz")
AppendVLTable ("I1840M08.gz")
AppendVLTable ("I1840M12.gz")
AppendVLTable ("I1840M16.gz")
AppendVLTable ("I1840M20.gz")
AppendVLTable ("I1840M24.gz")
AppendVLTable ("I1840M28.gz")
AppendVLTable ("I1840M40.gz")
AppendVLTable ("I1840P00.gz")
AppendVLTable ("I1840P04.gz")
AppendVLTable ("I1840P08.gz")
AppendVLTable ("I1840P12.gz")
AppendVLTable ("I1840P16.gz")
AppendVLTable ("I1840P20.gz")
AppendVLTable ("I1840P24.gz")
AppendVLTable ("I1840P28.gz")
AppendVLTable ("I1840P40.gz")
AppendVLTable ("I1840P44.gz")
AppendVLTable ("I1840P48.gz")
AppendVLTable ("I1845P72.gz")
AppendVLTable ("I1845P76.gz")
AppendVLTable ("I1848P52.gz")
AppendVLTable ("I1848P56.gz")
AppendVLTable ("I1854M32.gz")
AppendVLTable ("I1854M36.gz")
AppendVLTable ("I1854P32.gz")
AppendVLTable ("I1854P36.gz")
AppendVLTable ("I1856M04.gz")
AppendVLTable ("I1856M08.gz")
AppendVLTable ("I1856M12.gz")
AppendVLTable ("I1856M16.gz")
AppendVLTable ("I1856M20.gz")
AppendVLTable ("I1856M24.gz")
AppendVLTable ("I1856M28.gz")
AppendVLTable ("I1856P00.gz")
AppendVLTable ("I1856P04.gz")
AppendVLTable ("I1856P08.gz")
AppendVLTable ("I1856P12.gz")
AppendVLTable ("I1856P16.gz")
AppendVLTable ("I1856P20.gz")
AppendVLTable ("I1856P24.gz")
AppendVLTable ("I1856P28.gz")
AppendVLTable ("I1900M40.gz")
AppendVLTable ("I1900P40.gz")
AppendVLTable ("I1900P44.gz")
AppendVLTable ("I1900P48.gz")
AppendVLTable ("I1900P60.gz")
AppendVLTable ("I1900P64.gz")
AppendVLTable ("I1900P80.gz")
AppendVLTable ("I1912M04.gz")
AppendVLTable ("I1912M08.gz")
AppendVLTable ("I1912M12.gz")
AppendVLTable ("I1912M16.gz")
AppendVLTable ("I1912M20.gz")
AppendVLTable ("I1912M24.gz")
AppendVLTable ("I1912M28.gz")
AppendVLTable ("I1912M32.gz")
AppendVLTable ("I1912M36.gz")
AppendVLTable ("I1912P00.gz")
AppendVLTable ("I1912P04.gz")
AppendVLTable ("I1912P08.gz")
AppendVLTable ("I1912P12.gz")
AppendVLTable ("I1912P16.gz")
AppendVLTable ("I1912P20.gz")
AppendVLTable ("I1912P24.gz")
AppendVLTable ("I1912P28.gz")
AppendVLTable ("I1912P32.gz")
AppendVLTable ("I1912P36.gz")
AppendVLTable ("I1912P52.gz")
AppendVLTable ("I1912P56.gz")
AppendVLTable ("I1912P68.gz")
AppendVLTable ("I1920M40.gz")
AppendVLTable ("I1920P40.gz")
AppendVLTable ("I1920P44.gz")
AppendVLTable ("I1920P48.gz")
AppendVLTable ("I1928M04.gz")
AppendVLTable ("I1928M08.gz")
AppendVLTable ("I1928M12.gz")
AppendVLTable ("I1928M16.gz")
AppendVLTable ("I1928M20.gz")
AppendVLTable ("I1928M24.gz")
AppendVLTable ("I1928M28.gz")
AppendVLTable ("I1928P00.gz")
AppendVLTable ("I1928P04.gz")
AppendVLTable ("I1928P08.gz")
AppendVLTable ("I1928P12.gz")
AppendVLTable ("I1928P16.gz")
AppendVLTable ("I1928P20.gz")
AppendVLTable ("I1928P24.gz")
AppendVLTable ("I1928P28.gz")
AppendVLTable ("I1930M32.gz")
AppendVLTable ("I1930M36.gz")
AppendVLTable ("I1930P32.gz")
AppendVLTable ("I1930P36.gz")
AppendVLTable ("I1930P60.gz")
AppendVLTable ("I1930P64.gz")
AppendVLTable ("I1930P72.gz")
AppendVLTable ("I1930P76.gz")
AppendVLTable ("I1930P84.gz")
AppendVLTable ("I1936P52.gz")
AppendVLTable ("I1936P56.gz")
AppendVLTable ("I1940M40.gz")
AppendVLTable ("I1940P40.gz")
AppendVLTable ("I1940P44.gz")
AppendVLTable ("I1940P48.gz")
AppendVLTable ("I1944M04.gz")
AppendVLTable ("I1944M08.gz")
AppendVLTable ("I1944M12.gz")
AppendVLTable ("I1944M16.gz")
AppendVLTable ("I1944M20.gz")
AppendVLTable ("I1944M24.gz")
AppendVLTable ("I1944M28.gz")
AppendVLTable ("I1944P00.gz")
AppendVLTable ("I1944P04.gz")
AppendVLTable ("I1944P08.gz")
AppendVLTable ("I1944P12.gz")
AppendVLTable ("I1944P16.gz")
AppendVLTable ("I1944P20.gz")
AppendVLTable ("I1944P24.gz")
AppendVLTable ("I1944P28.gz")
AppendVLTable ("I1948M32.gz")
AppendVLTable ("I1948M36.gz")
AppendVLTable ("I1948P32.gz")
AppendVLTable ("I1948P36.gz")
AppendVLTable ("I1948P68.gz")
AppendVLTable ("I2000M04.gz")
AppendVLTable ("I2000M08.gz")
AppendVLTable ("I2000M12.gz")
AppendVLTable ("I2000M16.gz")
AppendVLTable ("I2000M20.gz")
AppendVLTable ("I2000M24.gz")
AppendVLTable ("I2000M28.gz")
AppendVLTable ("I2000M40.gz")
AppendVLTable ("I2000P00.gz")
AppendVLTable ("I2000P04.gz")
AppendVLTable ("I2000P08.gz")
AppendVLTable ("I2000P12.gz")
AppendVLTable ("I2000P16.gz")
AppendVLTable ("I2000P20.gz")
AppendVLTable ("I2000P24.gz")
AppendVLTable ("I2000P28.gz")
AppendVLTable ("I2000P40.gz")
AppendVLTable ("I2000P44.gz")
AppendVLTable ("I2000P48.gz")
AppendVLTable ("I2000P52.gz")
AppendVLTable ("I2000P56.gz")
AppendVLTable ("I2000P60.gz")
AppendVLTable ("I2000P64.gz")
AppendVLTable ("I2000P80.gz")
AppendVLTable ("I2006M32.gz")
AppendVLTable ("I2006M36.gz")
AppendVLTable ("I2006P32.gz")
AppendVLTable ("I2006P36.gz")
AppendVLTable ("I2015P72.gz")
AppendVLTable ("I2015P76.gz")
AppendVLTable ("I2016M04.gz")
AppendVLTable ("I2016M08.gz")
AppendVLTable ("I2016M12.gz")
AppendVLTable ("I2016M16.gz")
AppendVLTable ("I2016M20.gz")
AppendVLTable ("I2016M24.gz")
AppendVLTable ("I2016M28.gz")
AppendVLTable ("I2016P00.gz")
AppendVLTable ("I2016P04.gz")
AppendVLTable ("I2016P08.gz")
AppendVLTable ("I2016P12.gz")
AppendVLTable ("I2016P16.gz")
AppendVLTable ("I2016P20.gz")
AppendVLTable ("I2016P24.gz")
AppendVLTable ("I2016P28.gz")
AppendVLTable ("I2020M40.gz")
AppendVLTable ("I2020P40.gz")
AppendVLTable ("I2020P44.gz")
AppendVLTable ("I2020P48.gz")
AppendVLTable ("I2024M32.gz")
AppendVLTable ("I2024M36.gz")
AppendVLTable ("I2024P32.gz")
AppendVLTable ("I2024P36.gz")
AppendVLTable ("I2024P52.gz")
AppendVLTable ("I2024P56.gz")
AppendVLTable ("I2024P68.gz")
AppendVLTable ("I2030P60.gz")
AppendVLTable ("I2030P64.gz")
AppendVLTable ("I2032M04.gz")
AppendVLTable ("I2032M08.gz")
AppendVLTable ("I2032M12.gz")
AppendVLTable ("I2032M16.gz")
AppendVLTable ("I2032M20.gz")
AppendVLTable ("I2032M24.gz")
AppendVLTable ("I2032M28.gz")
AppendVLTable ("I2032P00.gz")
AppendVLTable ("I2032P04.gz")
AppendVLTable ("I2032P08.gz")
AppendVLTable ("I2032P12.gz")
AppendVLTable ("I2032P16.gz")
AppendVLTable ("I2032P20.gz")
AppendVLTable ("I2032P24.gz")
AppendVLTable ("I2032P28.gz")
AppendVLTable ("I2040M40.gz")
AppendVLTable ("I2040P40.gz")
AppendVLTable ("I2040P44.gz")
AppendVLTable ("I2040P48.gz")
AppendVLTable ("I2042M32.gz")
AppendVLTable ("I2042M36.gz")
AppendVLTable ("I2042P32.gz")
AppendVLTable ("I2042P36.gz")
AppendVLTable ("I2048M04.gz")
AppendVLTable ("I2048M08.gz")
AppendVLTable ("I2048M12.gz")
AppendVLTable ("I2048M16.gz")
AppendVLTable ("I2048M20.gz")
AppendVLTable ("I2048M24.gz")
AppendVLTable ("I2048M28.gz")
AppendVLTable ("I2048P00.gz")
AppendVLTable ("I2048P04.gz")
AppendVLTable ("I2048P08.gz")
AppendVLTable ("I2048P12.gz")
AppendVLTable ("I2048P16.gz")
AppendVLTable ("I2048P20.gz")
AppendVLTable ("I2048P24.gz")
AppendVLTable ("I2048P28.gz")
AppendVLTable ("I2048P52.gz")
AppendVLTable ("I2048P56.gz")
AppendVLTable ("I2100M32.gz")
AppendVLTable ("I2100M36.gz")
AppendVLTable ("I2100M40.gz")
AppendVLTable ("I2100P32.gz")
AppendVLTable ("I2100P36.gz")
AppendVLTable ("I2100P40.gz")
AppendVLTable ("I2100P44.gz")
AppendVLTable ("I2100P48.gz")
AppendVLTable ("I2100P60.gz")
AppendVLTable ("I2100P64.gz")
AppendVLTable ("I2100P68.gz")
AppendVLTable ("I2100P72.gz")
AppendVLTable ("I2100P76.gz")
AppendVLTable ("I2100P80.gz")
AppendVLTable ("I2100P84.gz")
AppendVLTable ("I2100P88.gz")
AppendVLTable ("I2104M04.gz")
AppendVLTable ("I2104M08.gz")
AppendVLTable ("I2104M12.gz")
AppendVLTable ("I2104M16.gz")
AppendVLTable ("I2104M20.gz")
AppendVLTable ("I2104M24.gz")
AppendVLTable ("I2104M28.gz")
AppendVLTable ("I2104P00.gz")
AppendVLTable ("I2104P04.gz")
AppendVLTable ("I2104P08.gz")
AppendVLTable ("I2104P12.gz")
AppendVLTable ("I2104P16.gz")
AppendVLTable ("I2104P20.gz")
AppendVLTable ("I2104P24.gz")
AppendVLTable ("I2104P28.gz")
AppendVLTable ("I2112P52.gz")
AppendVLTable ("I2112P56.gz")
AppendVLTable ("I2118M32.gz")
AppendVLTable ("I2118M36.gz")
AppendVLTable ("I2118P32.gz")
AppendVLTable ("I2118P36.gz")
AppendVLTable ("I2120M04.gz")
AppendVLTable ("I2120M08.gz")
AppendVLTable ("I2120M12.gz")
AppendVLTable ("I2120M16.gz")
AppendVLTable ("I2120M20.gz")
AppendVLTable ("I2120M24.gz")
AppendVLTable ("I2120M28.gz")
AppendVLTable ("I2120M40.gz")
AppendVLTable ("I2120P00.gz")
AppendVLTable ("I2120P04.gz")
AppendVLTable ("I2120P08.gz")
AppendVLTable ("I2120P12.gz")
AppendVLTable ("I2120P16.gz")
AppendVLTable ("I2120P20.gz")
AppendVLTable ("I2120P24.gz")
AppendVLTable ("I2120P28.gz")
AppendVLTable ("I2120P40.gz")
AppendVLTable ("I2120P44.gz")
AppendVLTable ("I2120P48.gz")
AppendVLTable ("I2130P60.gz")
AppendVLTable ("I2130P64.gz")
AppendVLTable ("I2136M04.gz")
AppendVLTable ("I2136M08.gz")
AppendVLTable ("I2136M12.gz")
AppendVLTable ("I2136M16.gz")
AppendVLTable ("I2136M20.gz")
AppendVLTable ("I2136M24.gz")
AppendVLTable ("I2136M28.gz")
AppendVLTable ("I2136M32.gz")
AppendVLTable ("I2136M36.gz")
AppendVLTable ("I2136P00.gz")
AppendVLTable ("I2136P04.gz")
AppendVLTable ("I2136P08.gz")
AppendVLTable ("I2136P12.gz")
AppendVLTable ("I2136P16.gz")
AppendVLTable ("I2136P20.gz")
AppendVLTable ("I2136P24.gz")
AppendVLTable ("I2136P28.gz")
AppendVLTable ("I2136P32.gz")
AppendVLTable ("I2136P36.gz")
AppendVLTable ("I2136P52.gz")
AppendVLTable ("I2136P56.gz")
AppendVLTable ("I2136P68.gz")
AppendVLTable ("I2140M40.gz")
AppendVLTable ("I2140P40.gz")
AppendVLTable ("I2140P44.gz")
AppendVLTable ("I2140P48.gz")
AppendVLTable ("I2145P72.gz")
AppendVLTable ("I2145P76.gz")
AppendVLTable ("I2152M04.gz")
AppendVLTable ("I2152M08.gz")
AppendVLTable ("I2152M12.gz")
AppendVLTable ("I2152M16.gz")
AppendVLTable ("I2152M20.gz")
AppendVLTable ("I2152M24.gz")
AppendVLTable ("I2152M28.gz")
AppendVLTable ("I2152P00.gz")
AppendVLTable ("I2152P04.gz")
AppendVLTable ("I2152P08.gz")
AppendVLTable ("I2152P12.gz")
AppendVLTable ("I2152P16.gz")
AppendVLTable ("I2152P20.gz")
AppendVLTable ("I2152P24.gz")
AppendVLTable ("I2152P28.gz")
AppendVLTable ("I2154M32.gz")
AppendVLTable ("I2154M36.gz")
AppendVLTable ("I2154P32.gz")
AppendVLTable ("I2154P36.gz")
AppendVLTable ("I2200M40.gz")
AppendVLTable ("I2200P40.gz")
AppendVLTable ("I2200P44.gz")
AppendVLTable ("I2200P48.gz")
AppendVLTable ("I2200P52.gz")
AppendVLTable ("I2200P56.gz")
AppendVLTable ("I2200P60.gz")
AppendVLTable ("I2200P64.gz")
AppendVLTable ("I2200P80.gz")
AppendVLTable ("I2208M04.gz")
AppendVLTable ("I2208M08.gz")
AppendVLTable ("I2208M12.gz")
AppendVLTable ("I2208M16.gz")
AppendVLTable ("I2208M20.gz")
AppendVLTable ("I2208M24.gz")
AppendVLTable ("I2208M28.gz")
AppendVLTable ("I2208P00.gz")
AppendVLTable ("I2208P04.gz")
AppendVLTable ("I2208P08.gz")
AppendVLTable ("I2208P12.gz")
AppendVLTable ("I2208P16.gz")
AppendVLTable ("I2208P20.gz")
AppendVLTable ("I2208P24.gz")
AppendVLTable ("I2208P28.gz")
AppendVLTable ("I2212M32.gz")
AppendVLTable ("I2212M36.gz")
AppendVLTable ("I2212P32.gz")
AppendVLTable ("I2212P36.gz")
AppendVLTable ("I2212P68.gz")
AppendVLTable ("I2220M40.gz")
AppendVLTable ("I2220P40.gz")
AppendVLTable ("I2220P44.gz")
AppendVLTable ("I2220P48.gz")
AppendVLTable ("I2224M04.gz")
AppendVLTable ("I2224M08.gz")
AppendVLTable ("I2224M12.gz")
AppendVLTable ("I2224M16.gz")
AppendVLTable ("I2224M20.gz")
AppendVLTable ("I2224M24.gz")
AppendVLTable ("I2224M28.gz")
AppendVLTable ("I2224P00.gz")
AppendVLTable ("I2224P04.gz")
AppendVLTable ("I2224P08.gz")
AppendVLTable ("I2224P12.gz")
AppendVLTable ("I2224P16.gz")
AppendVLTable ("I2224P20.gz")
AppendVLTable ("I2224P24.gz")
AppendVLTable ("I2224P28.gz")
AppendVLTable ("I2224P52.gz")
AppendVLTable ("I2224P56.gz")
AppendVLTable ("I2230M32.gz")
AppendVLTable ("I2230M36.gz")
AppendVLTable ("I2230P32.gz")
AppendVLTable ("I2230P36.gz")
AppendVLTable ("I2230P60.gz")
AppendVLTable ("I2230P64.gz")
AppendVLTable ("I2230P72.gz")
AppendVLTable ("I2230P76.gz")
AppendVLTable ("I2230P84.gz")
AppendVLTable ("I2240M04.gz")
AppendVLTable ("I2240M08.gz")
AppendVLTable ("I2240M12.gz")
AppendVLTable ("I2240M16.gz")
AppendVLTable ("I2240M20.gz")
AppendVLTable ("I2240M24.gz")
AppendVLTable ("I2240M28.gz")
AppendVLTable ("I2240M40.gz")
AppendVLTable ("I2240P00.gz")
AppendVLTable ("I2240P04.gz")
AppendVLTable ("I2240P08.gz")
AppendVLTable ("I2240P12.gz")
AppendVLTable ("I2240P16.gz")
AppendVLTable ("I2240P20.gz")
AppendVLTable ("I2240P24.gz")
AppendVLTable ("I2240P28.gz")
AppendVLTable ("I2240P40.gz")
AppendVLTable ("I2240P44.gz")
AppendVLTable ("I2240P48.gz")
AppendVLTable ("I2248M32.gz")
AppendVLTable ("I2248M36.gz")
AppendVLTable ("I2248P32.gz")
AppendVLTable ("I2248P36.gz")
AppendVLTable ("I2248P52.gz")
AppendVLTable ("I2248P56.gz")
AppendVLTable ("I2248P68.gz")
AppendVLTable ("I2256M04.gz")
AppendVLTable ("I2256M08.gz")
AppendVLTable ("I2256M12.gz")
AppendVLTable ("I2256M16.gz")
AppendVLTable ("I2256M20.gz")
AppendVLTable ("I2256M24.gz")
AppendVLTable ("I2256M28.gz")
AppendVLTable ("I2256P00.gz")
AppendVLTable ("I2256P04.gz")
AppendVLTable ("I2256P08.gz")
AppendVLTable ("I2256P12.gz")
AppendVLTable ("I2256P16.gz")
AppendVLTable ("I2256P20.gz")
AppendVLTable ("I2256P24.gz")
AppendVLTable ("I2256P28.gz")
AppendVLTable ("I2300M40.gz")
AppendVLTable ("I2300P40.gz")
AppendVLTable ("I2300P44.gz")
AppendVLTable ("I2300P48.gz")
AppendVLTable ("I2300P60.gz")
AppendVLTable ("I2300P64.gz")
AppendVLTable ("I2300P80.gz")
AppendVLTable ("I2306M32.gz")
AppendVLTable ("I2306M36.gz")
AppendVLTable ("I2306P32.gz")
AppendVLTable ("I2306P36.gz")
AppendVLTable ("I2312M04.gz")
AppendVLTable ("I2312M08.gz")
AppendVLTable ("I2312M12.gz")
AppendVLTable ("I2312M16.gz")
AppendVLTable ("I2312M20.gz")
AppendVLTable ("I2312M24.gz")
AppendVLTable ("I2312M28.gz")
AppendVLTable ("I2312P00.gz")
AppendVLTable ("I2312P04.gz")
AppendVLTable ("I2312P08.gz")
AppendVLTable ("I2312P12.gz")
AppendVLTable ("I2312P16.gz")
AppendVLTable ("I2312P20.gz")
AppendVLTable ("I2312P24.gz")
AppendVLTable ("I2312P28.gz")
AppendVLTable ("I2312P52.gz")
AppendVLTable ("I2312P56.gz")
AppendVLTable ("I2315P72.gz")
AppendVLTable ("I2315P76.gz")
AppendVLTable ("I2320M40.gz")
AppendVLTable ("I2320P40.gz")
AppendVLTable ("I2320P44.gz")
AppendVLTable ("I2320P48.gz")
AppendVLTable ("I2324M32.gz")
AppendVLTable ("I2324M36.gz")
AppendVLTable ("I2324P32.gz")
AppendVLTable ("I2324P36.gz")
AppendVLTable ("I2324P68.gz")
AppendVLTable ("I2328M04.gz")
AppendVLTable ("I2328M08.gz")
AppendVLTable ("I2328M12.gz")
AppendVLTable ("I2328M16.gz")
AppendVLTable ("I2328M20.gz")
AppendVLTable ("I2328M24.gz")
AppendVLTable ("I2328M28.gz")
AppendVLTable ("I2328P00.gz")
AppendVLTable ("I2328P04.gz")
AppendVLTable ("I2328P08.gz")
AppendVLTable ("I2328P12.gz")
AppendVLTable ("I2328P16.gz")
AppendVLTable ("I2328P20.gz")
AppendVLTable ("I2328P24.gz")
AppendVLTable ("I2328P28.gz")
AppendVLTable ("I2330P60.gz")
AppendVLTable ("I2330P64.gz")
AppendVLTable ("I2336P52.gz")
AppendVLTable ("I2336P56.gz")
AppendVLTable ("I2340M40.gz")
AppendVLTable ("I2340P40.gz")
AppendVLTable ("I2340P44.gz")
AppendVLTable ("I2340P48.gz")
AppendVLTable ("I2342M32.gz")
AppendVLTable ("I2342M36.gz")
AppendVLTable ("I2342P32.gz")
AppendVLTable ("I2342P36.gz")
AppendVLTable ("I2344M04.gz")
AppendVLTable ("I2344M08.gz")
AppendVLTable ("I2344M12.gz")
AppendVLTable ("I2344M16.gz")
AppendVLTable ("I2344M20.gz")
AppendVLTable ("I2344M24.gz")
AppendVLTable ("I2344M28.gz")
AppendVLTable ("I2344P00.gz")
AppendVLTable ("I2344P04.gz")
AppendVLTable ("I2344P08.gz")
AppendVLTable ("I2344P12.gz")
AppendVLTable ("I2344P16.gz")
AppendVLTable ("I2344P20.gz")
AppendVLTable ("I2344P24.gz")
AppendVLTable ("I2344P28.gz")
# Shutdown Obit
OErr.printErr(err)
del ObitSys
|
Cee Vee has been designing and engineering rudder stocks and fittings for over 30 years. Cee Vee manufacturers high quality rudder stocks to suit many dinghy classes including Fireball, Merlin Rocket, 505, 470, GP14, Contender, Lark, Streaker, Wayfarer and many more. Browse the complete range below.
|
# ***************************************************************************
# * Copyright (c) 2009, 2010 Yorik van Havre <yorik@uncreated.net> *
# * Copyright (c) 2009, 2010 Ken Cline <cline@frii.com> *
# * Copyright (c) 2020 Eliud Cabrera Castillo <e.cabrera-castillo@tum.de> *
# * *
# * This program is free software; you can redistribute it and/or modify *
# * it under the terms of the GNU Lesser General Public License (LGPL) *
# * as published by the Free Software Foundation; either version 2 of *
# * the License, or (at your option) any later version. *
# * for detail see the LICENCE text file. *
# * *
# * This program is distributed in the hope that it will be useful, *
# * but WITHOUT ANY WARRANTY; without even the implied warranty of *
# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
# * GNU Library General Public License for more details. *
# * *
# * You should have received a copy of the GNU Library General Public *
# * License along with this program; if not, write to the Free Software *
# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
# * USA *
# * *
# ***************************************************************************
"""Provides the object code for the DrawingView object (OBSOLETE).
This module is obsolete, since the Drawing Workbench stopped
being developed in v0.17.
The TechDraw Workbench replaces Drawing, and it no longer requires
a `DrawingView` object to display objects in a drawing sheet.
This module is still provided in order to be able to open older files
that use this `DrawingView` object. However, a GUI tool to create
this object should no longer be available.
"""
## @package drawingview
# \ingroup draftobjects
# \brief Provides the object code for the DrawingView object (OBSOLETE).
## \addtogroup draftobjects
# @{
from PySide.QtCore import QT_TRANSLATE_NOOP
import draftfunctions.svg as get_svg
import draftfunctions.dxf as get_dxf
import draftutils.utils as utils
import draftutils.groups as groups
from draftobjects.base import DraftObject
class DrawingView(DraftObject):
"""The DrawingView object. This class is OBSOLETE.
This object was used with the Drawing Workbench, but since this workbench
because obsolete in v0.17, the object should no longer be used.
It is retained for compatibility purposes, that is, to open older
files that may contain this object.
To produce 2D drawings, use TechDraw Workbench.
"""
def __init__(self, obj):
super(DrawingView, self).__init__(obj, "DrawingView")
_tip = QT_TRANSLATE_NOOP("App::Property",
"The linked object")
obj.addProperty("App::PropertyLink",
"Source",
"Base",
_tip)
_tip = QT_TRANSLATE_NOOP("App::Property",
"Projection direction")
obj.addProperty("App::PropertyVector",
"Direction",
"Shape View",
_tip)
_tip = QT_TRANSLATE_NOOP("App::Property",
"The width of the lines inside this object")
obj.addProperty("App::PropertyFloat",
"LineWidth",
"View Style",
_tip)
obj.LineWidth = 0.35
_tip = QT_TRANSLATE_NOOP("App::Property",
"The size of the texts inside this object")
obj.addProperty("App::PropertyLength",
"FontSize",
"View Style",
_tip)
obj.FontSize = 12
_tip = QT_TRANSLATE_NOOP("App::Property",
"The spacing between lines of text")
obj.addProperty("App::PropertyLength",
"LineSpacing",
"View Style",
_tip)
_tip = QT_TRANSLATE_NOOP("App::Property",
"The color of the projected objects")
obj.addProperty("App::PropertyColor",
"LineColor",
"View Style",
_tip)
_tip = QT_TRANSLATE_NOOP("App::Property",
"Shape Fill Style")
obj.addProperty("App::PropertyEnumeration",
"FillStyle",
"View Style",
_tip)
obj.FillStyle = ['shape color'] + list(utils.svgpatterns().keys())
_tip = QT_TRANSLATE_NOOP("App::Property",
"Line Style")
obj.addProperty("App::PropertyEnumeration",
"LineStyle",
"View Style",
_tip)
obj.LineStyle = ['Solid', 'Dashed', 'Dotted', 'Dashdot']
_tip = QT_TRANSLATE_NOOP("App::Property",
"If checked, source objects are displayed "
"regardless of being visible in the 3D model")
obj.addProperty("App::PropertyBool",
"AlwaysOn",
"View Style",
_tip)
def execute(self, obj):
"""Execute when the object is created or recomputed."""
result = ""
if hasattr(obj, "Source") and obj.Source:
if hasattr(obj, "LineStyle"):
ls = obj.LineStyle
else:
ls = None
if hasattr(obj, "LineColor"):
lc = obj.LineColor
else:
lc = None
if hasattr(obj, "LineSpacing"):
lp = obj.LineSpacing
else:
lp = None
if obj.Source.isDerivedFrom("App::DocumentObjectGroup"):
svg = ""
objs = groups.get_group_contents([obj.Source])
for o in objs:
v = o.ViewObject.isVisible()
if hasattr(obj, "AlwaysOn") and obj.AlwaysOn:
v = True
if v:
svg += get_svg.get_svg(o,
obj.Scale,
obj.LineWidth,
obj.FontSize.Value,
obj.FillStyle,
obj.Direction, ls, lc, lp)
else:
svg = get_svg.get_svg(obj.Source,
obj.Scale,
obj.LineWidth,
obj.FontSize.Value,
obj.FillStyle,
obj.Direction, ls, lc, lp)
result += '<g id="' + obj.Name + '"'
result += ' transform="'
result += 'rotate(' + str(obj.Rotation) + ','
result += str(obj.X) + ',' + str(obj.Y)
result += ') '
result += 'translate(' + str(obj.X) + ',' + str(obj.Y) + ') '
result += 'scale(' + str(obj.Scale) + ',' + str(-obj.Scale)
result += ')'
result += '">'
result += svg
result += '</g>'
obj.ViewResult = result
def getDXF(self, obj):
"""Return a DXF fragment."""
return get_dxf.get_dxf(obj)
# Alias for compatibility with v0.18 and earlier
_DrawingView = DrawingView
## @}
|
What is the College Level Examination Program?
The College Level Examination Program, better known as the CLEP, is a program launched by the College Board. This program lets students earn college credit through the experience that they gained working in the field or in other ways. When you take one of these tests, the College Board will grade your test, and if you receive a score higher than a certain amount, you can transfer that credit to one of the associated colleges and avoid taking that class for your degree. The College Board offers these courses in five different subjects.
The exams offered by the College Board are available in foreign languages, business, composition and literature, history and social sciences and mathematics and science. Financial accounting, introduction to business law and principles of management are a few of the business programs available, while the composition and literature tests include college composition and American literature. Those proficient in French, Spanish or German can take a class that lets them skip one or more foreign language courses. Students can also gain biology, humanities, algebra, history and psychology credits and credits for other courses.
How Many Credits Can You Earn?
The number of credits that you can earn through ones of these examinations ranges from three credits to 12 credits. According to the College Board, the number of credits granted varies based on your school. Some schools will let you use the three credits you earn from a psychology test to skip the required social sciences credit needed for graduation. If you earn six to 12 credits, the school may only grant you three credit hours towards your degree. Some schools will give you full credit for the test you take towards the requirements of your degree program.
Do the Tests Cost Money?
Taking this test lets you save money on your college tuition. Most tests cost a flat rate of $80, but taking the full class at your school might cost $300 or more. If the test includes an essay component, you need to pay an additional $10 fee. Nearly 3,000 colleges across the country accept credits earned from those tests, and the College Board offers those tests at nearly 2,000 locations across the country. Active duty military personnel can take the examinations for free, and the tests are also free to some qualifying veterans.
Those who take the College Board examinations are those who want to take fewer classes on campus or online. Most colleges now require that students take a certain number of foreign language classes. If you are bilingual, you can use the exam to skip those courses. The experience that you have in the real world can help you pass that test and avoid taking a full course. Others use the program as a way to cut down on the cost of their tuition. This program is open to high school graduates, continuing education students, college students, veterans and currently enlisted men and women and those who were home schooled.
Most tests available through the College Board take 90 minutes or less to complete, and students can earn up to 12 credit hours of college credit from a single test. The CLEP is a program that is open to students of all ages and backgrounds who want make college a little more affordable.
|
from sqlalchemy import *
from migrate import *
from migrate.changeset import schema
pre_meta = MetaData()
post_meta = MetaData()
post = Table('post', post_meta,
Column('id', Integer, primary_key=True, nullable=False),
Column('body', String(length=140)),
Column('timestamp', DateTime),
Column('user_id', Integer),
)
status = Table('status', post_meta,
Column('id', Integer, primary_key=True, nullable=False),
Column('start', Integer),
Column('status', Boolean),
Column('node_id', Integer),
)
user = Table('user', post_meta,
Column('id', Integer, primary_key=True, nullable=False),
Column('nickname', String(length=64)),
Column('email', String(length=120)),
Column('role', SmallInteger, default=ColumnDefault(0)),
)
def upgrade(migrate_engine):
# Upgrade operations go here. Don't create your own engine; bind
# migrate_engine to your metadata
pre_meta.bind = migrate_engine
post_meta.bind = migrate_engine
post_meta.tables['post'].create()
post_meta.tables['status'].create()
post_meta.tables['user'].create()
def downgrade(migrate_engine):
# Operations to reverse the above upgrade go here.
pre_meta.bind = migrate_engine
post_meta.bind = migrate_engine
post_meta.tables['post'].drop()
post_meta.tables['status'].drop()
post_meta.tables['user'].drop()
|
Human species would not survive more than five years if the bees extinct from our ecosystem. (1) Bees are essential parts of our ecosystem.
If you have a hive nearby your home or the places you hang around, you do not need to kill them or destroy the colony.
Plus instead of using the store-bought, chemical bee repellents, you can use some essential oils to avoid the risk of a bee sting.
These essential oils for bee repellent may give you get better results without any possibilities of side effects.
This articles reviews the efficacy and uses of essential oils as bee repellent.
Why Use Essential Oils for Bee Repellent?
Bees love honey, citrus fruits, sweet tea, and all other sweet flavored things.
While bees help to keep our air dust and pollution free, bee-stung can be severe. In some cases, people might die if not treated accordingly.
There are some conventional bee repellents available in the market. These contain a high level of chemicals. Whereas using essential oils for bee repellent is 100% natural and effective.
Using essential oils as a repellent would not harm the bees and beehives, hive growth in any way.
Using essential oils as bee repellent will leave you with a pleasant aroma. Some of the essential oils have other benefits for human bodies as well.
You will need 1 cup of distilled water, 20 drops tea tree oil, 5 drops citronella oil and 8 oz glass spray bottles.
Shake up all the ingredients in a spray bottle. That’s all! Your essential oil bee repellent is ready!
Store the mix in a cold and dry place, away from the reach of bright light, kids, and pets.
You can spray the mix in the air around the bees or sprinkle some all over your house.
Take 5 tbsp of your favorite brand of shower gel or liquid soap in a sparkle jar and add water to it.
Mix 10-12 drops of peppermint essential oil into the solution.
You can also be dab the essential oil on tissues and stashed around the house as a natural indoor repellent.
Mix 5-6 drops of almond oil with 1-2 drops of carrier oil, such as olive or canola oil.
Apply the diluted oil all over your body to repel bees. As a bonus, you are going to have nourished and moisturized skin.
Take 10 drops of eucalyptus essential oil and mix it with 3-4 drops of pine, cedarwood, or lemon essential oil.
Pour 500 ml of distilled water and shake.
Pour the mix into a sprinkle jar and spray all over your kitchen, inside the closet and living room.
There is no way a single bee would pass through the threshold of your house.
You are going to need 10 tbsp of orange oil and 4-5 drops of rubbing alcohol. Mix these 2 and apply to your skin to prevent bees from coming around you.
You might also brush the surface of your home to repel bees.
If you want to use a spray, add some water to the mix and sprinkle it.
Mix up to 10 drops the oil with 2-3 drops of coconut oil and spread it on your body like lotion.
You can also mix 100 ml of water with the mix in a spray bottle and sprinkle on your skin, hair, and clothes.
You can also try applying pure citronella oil to your skin unless you are allergic to it.
Combine the similar amount of the cedarwood oil with lemongrass and peppermint oil.
Rub the mix on your skin, hair and sprinkle some on your clothes and socks.
You do not have to worry about bees all day long.
An essential oils blend will repel bees more effectively.
Mix 1/8 oz each of jojoba oil, tea tree oil and pennyroyal oil with 1/4 oz lavender and 1/2 oz citronella oil, and 16 oz of almond oil. You can apply the mix to your skin.
If you want to make a bee repellent spray, you might use a similar amount of vodka instead of the carrier oils.
Take care not to mist any of the sprays over food.
Do not spray near your face, especially the eyes.
Do not use a raw version of any of these oils on your skin.
Do not spray on the bees or beehives.
You should consult with a doctor before spraying any of these essential oils on your baby’s clothes.
|
import os
import time
import sys
import argparse
#sys.path.append('/reg/neh/home/ohoidn/anaconda/lib/python2.7/site-packages')
#sys.path.append('/reg/neh/home/ohoidn/anaconda/lib/python2.7/site-packages/pathos-0.2a1.dev0-py2.7.egg')
#sys.path.append('/reg/neh/home/ohoidn/anaconda/lib/python2.7/site-packages/dataccess-1.0-py2.7.egg')
from dataccess import data_access
from dataccess import psget
import config
d4 = psget.get_signal_bg_one_run(688, mode = 'script')
def generate_all_batches(search_range = (-float('inf'), float('inf'))):
rangemin, rangemax = search_range
all_runs = data_access.get_all_runs()
commands = []
for run in all_runs:
if run >= rangemin and run <= rangemax:
for detid in config.detID_list:
commands.append(psget.get_signal_bg_one_run(run, detid = detid, mode = 'script'))
return commands
def submit_all_batches(search_range = (-float('inf'), float('inf'))):
commands = generate_all_batches(search_range = search_range)
for command in commands:
os.system(command)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--min', type = int)
parser.add_argument('--max', type = int)
parser.add_argument('--generate', '-g', action = 'store_true')
parser.add_argument('--submit', '-s', action = 'store_true')
args = parser.parse_args()
if args.min:
amin = args.min
else:
amin = -float('inf')
if args.max:
amax = args.max
else:
amax = float('inf')
search_range = (amin, amax)
if args.generate:
generate_all_batches(search_range = search_range)
if args.submit:
submit_all_batches(search_range = search_range)
time.sleep(1000)
|
Film London is the capital's screen industries agency.
We work to sustain, promote and develop London as a global content production hub, support the development of the city's new and emerging filmmaking talent and invest in a diverse and rich film culture.
We aim to ensure the capital is a thriving centre for creative industries sector that enrich the city's businesses and its people.
From encouraging inward investment to training emerging filmmakers, funding film exhibitors to inspiring film-lovers - we support film in London every step of the way.
The production support and business development team promote and support all areas of the screening industries, from film and television to animation, games and VFX.
Their schemes include Production Finance Market, London Screenings, and Familiarisation Trips for overseas executives.
They offer expert advice on London locations and studio spaces, also providing guidance on permissions, legalities, and the filming code of practice. They also provide networking opportunities and career support, and attend major film festivals around the world to promote London's world-class facilities, locations and talent to the international market.
Film Hub London is a network open to all film exhibitors across the city, from community film clubs to inner city multiplexes. Part of the BFI Film Audience Network, it aims to grow audiences and serve London's diverse communities through a variety of funding, training and networking opportunities for film exhibitors.
Film London engages audiences from around the world with London's film culture, promoting our city as a hotspot for film tourism and encouraging engagement with film in all forms. We are a partner on the EuroScreen project, working to improve innovation, competitiveness and growth in screen tourism, and produce the London Movie Map, which allows film-lovers to tour the city and visit the locations of their favourite London movies.
The Film London's Artists' Moving Image Network, FLAMIN, supports the development and promotion of emerging artist filmmakers. Their schemes include financing and training support for moving image artists, commissioning new works, and the annual Jarman Award.
London's Screen Archives work to preserve and share the city's film heritage. The team supports over 100 archives, museums and libraries in the capital, helping to collaborate on projects, make their moving image collections more accessible, and bring screen heritage alive for Londoners.
The British Film Commission maximises and supports the production of international feature film and television in the UK. They strengthen and promote the UK's production infrastructure and policies, and provide guidance, support and knowledge to international productions.
|
#!/usr/bin/env python
# coding:utf-8
"""
Copyright (c) 2017 BugScan (http://www.bugscan.net)
See the file 'LICENCE' for copying permission
"""
import os
import urllib2
import random
from lib.common import writeFile
from lib.data import paths
from lib.data import target
from lib.data import agents
from lib.data import logger
from lib.settings import DEBUG
def randomAgent():
return random.choice(agents)
def request_data(url):
for i in range(3):
data = None
try:
request = urllib2.Request(url, None, {'User-Agent': randomAgent()})
data = urllib2.urlopen(request).read()
if data:
return data
except Exception, e:
if DEBUG:
logger.warning("Request Exception: %s" % str(e))
return None
def wget(filepath):
url = "%s%s" % (target.TARGET_GIT_URL, filepath)
filename = os.path.join(paths.GITHACK_DIST_TARGET_GIT_PATH, filepath)
dirname = os.path.dirname(filename)
if not os.path.exists(dirname):
os.makedirs(dirname)
data = request_data(url)
if data:
writeFile(filename, data)
if DEBUG:
logger.success("Get %s => %s" % (url, filepath))
def isdirlist():
keywords = [
"To Parent Directory",
"Index of /",
"Directory Listing For /",
"[转到父目录]",
"objects/",
]
data = request_data(target.TARGET_GIT_URL)
if data:
for key in keywords:
if key in data:
logger.info("%s is support Directory Listing" % target.TARGET_GIT_URL)
return True
logger.info("%s is not support Directory Listing" % target.TARGET_GIT_URL)
return False
|
Initial one month contract, likely to extend to three.
The Ashdown Group has been engaged by a successful digital agency to find a contract Mac Support Specialist.
The purpose of the role is to provide 1st line and deskside support services to approximately 450 users. Working as part of a small team you will be the first point of contact for IT, providing general IT troubleshooting, resolving queries by email, phone, remote and deskside support and will require great Mac experience, including of The Casper Suite.
Knowledge of Mac is essential, including configuration management and deployment.
Additional elements of the role will include desktop support, printer support, software installations, patch management as well as maintaining the telephone system.
This is a customer-focused role, with this in mind, you will possess strong communication skills both written and verbal. You will be expected to carry out some project work during this busy time.
|
# -*- coding: utf-8; mode: python; indent-tabs-mode: t; tab-width:4 -*-
import os,glob
from ..Qt import QtGui, QtCore,QtWidgets
import numpy as np
from .templates import ui_onlineBrowser as onlineBrowser
import pyqtgraph as pg
class dummyApp:
def processEvents(self):
pass
try:
import requests
except:
print ('requests library missing. online browser will not work.')
class onlineBrowser(QtWidgets.QFrame,onlineBrowser.Ui_Form):
trace_names = ['#%d'%a for a in range(10)]
trace_colors = [(0,255,0),(255,0,0),(255,255,100),(10,255,255)]
textfiles=[]
def __init__(self,*args,**kwargs):
super(onlineBrowser, self).__init__()
self.setupUi(self)
self.thumbList = {}
self.downloadedSubdir = kwargs.get('save_directory','ExpEYES_Online')
self.clickCallback = kwargs.get('clickCallback',self.showClickedFile)
self.app = kwargs.get('app',dummyApp())
def refresh(self):
self.generateItemList()
def itemClicked(self,sel):
fname = self.thumbList[str(sel)][1]
print(fname)
self.clickCallback( fname )
def clearItems(self):
for a in self.thumbList:
self.listWidget.takeItem(self.listWidget.row(self.thumbList[a][0]))
self.thumbList={}
def generateItemList(self,**kwargs):
self.clearItems()
url = self.urlEdit.text()
dlPath = url+'getStaticScripts'
print ('downloading from ',dlPath)
self.app.processEvents()
self.textfiles = []
homedir = os.path.expanduser('~')
thumbdir = os.path.join(homedir,self.downloadedSubdir)
if not os.path.isdir(thumbdir):
print ('Directory missing. Will create')
os.makedirs(thumbdir)
requests.get(dlPath,hooks=dict(response=self.processData))
def processData(self,expts,*args,**kwargs):
if expts.status_code == 200:
dirList = expts.json()['staticdata']
for a in dirList:
print ('directory :',a)
scriptList = dirList[a]['data']
for b in scriptList:
try:
#x = QtGui.QIcon(thumbpath)
fname = b['Filename']
filepath = dirList[a]['path']
item = QtGui.QListWidgetItem(fname)#x,fname)
self.listWidget.addItem(item)
self.thumbList[fname] = [item,filepath]
except Exception as e:
print( 'failed to load ',b,e)
else:
print ('got nothing. error:',expts.status_code)
def loadFromFile(self,plot,curves,filename,histMode=False):
print('what just happened?')
def showClickedFile(self):
print('what just happened?click.')
|
There is talk floating around the US that the South Eastern and North Eastern Australian Football Leagues may be merged to form a new Eastern AFL.
A few more details of the International Cup plans have become available. The AFL's Ed Biggs has announced a march-past of players and the tournament dinner.
Sydney Swans and Ireland International Rules star, Tadhg Kennelly, helped his old club Listowel Emmets win the North Kerry Gaelic football final while home for Xmas.
Like everyone else, World Footy News is deeply saddened by the massive disaster resulting from the earthquake and tsunamis in the Asia region, with well over 100,000 people confirmed dead. We take this moment to urge anyone who has not already made a donation and can afford to, to do so through agencies such as the Red Cross, United Nations or any other agency you think is appropriate.
The seedings for the 2005 International Cup have been released. It is to be held in Melbourne in August. The same 11 countries that competed in 2002 are expected to return, plus Spain making their first appearance.
As 2004 comes to an end, World Footy News reflects on another interesting year in the international growth of Australian Football, having a look at some of the ups and downs and interesting stories.
Ethiopian Goaner Tutlan has made his debut for St Marys in the Northern Territory AFL reserves. Playing against Southern Districts, the 196cm tall footy-convert kicked four goals from full forward, in his team's big win. His exceptional leap is said to be one of his greatest assets, but coaching staff are keen for him put on a lot more muscle. World Footy News will give updates on the African during the season.
It could be argued that many Australian football supporters know little of the true history of the game, and perhaps not many ponder its future. Most focus only on their own club, perhaps occasionally looking into its past, but rarely the bigger picture of the sport. There are lessons from the past, and the remarkable spread of the game overseas in some ways parallel its movement across Australia over many decades. Some would have us believe that the game has only ever been seriously played in the south east corner of Australia - they do a great injustice to many other major leagues, but also to their own sport, which has a rich and colourful tradition that spans well over a century across its native land. Similarly we need to recognise the emerging markets for footy in North America, Europe, Asia, the Pacific and other untapped regions. Opportunities should not be missed and left for later. If we seek lessons from the past, we might ensure the game's future, which some would argue is less than secure. The following article explores the historic beginnings of Australian Rules football through to the emergence of the AFL and the sport's growth around the world.
|
# coding=utf-8
import requests
from urllib.parse import urlparse
class Login(object):
"""docstring for Login"""
def __init__(self, **signin):
self.url = signin['url']
if not signin['verify']:
self.logindata = signin['logindata']
self.loginurl = signin['loginurl']
self.login()
else:
self.cookies = signin['cookies']
def login(self):
response = requests.post(self.loginurl, data=self.logindata)
self.cookies = response.cookies
return response
def cookie(self):
pass
def setCookies(self, dict):
self.cookies = dict
def getheader(self):
pass
def register(self):
self.setheader()
url = "http://bbs.ithome.com/plugin.php?id=dsu_paulsign:sign&operation=qiandao&infloat=1&sign_as=1&inajax=1"
data = {"formhash": "14acb1bd",
"qdxq": "nu",
"qdmode": "2",
"todaysay": "",
"fastreply": "0"}
self.cookies.update({"discuz_2132_sendmail":"1","discuz_2132_nofavfid":"1","discuz_2132_connect_is_bind":"0"})
return requests.post(url, data=data, cookies=self.cookies, headers=self.headers).text
def setheader(self):
url = urlparse(self.url)
Referer = url.scheme + "://" + url.netloc
self.headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 5.1; rv:32.0) Gecko/20100101 Firefox/32.0",
"Referer": Referer,
"Host": url.netloc,
"Connection": "keep-alive",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
}
def get(self):
self.setheader()
return requests.get(self.url, cookies=self.cookies, headers=self.headers).text
def getWithCookies(self):
self.setheader()
return requests.get(self.url, cookies=self.cookies, headers=self.headers)
def postWithCookies(self):
pass
login = Login(
verify=True,
url="http://bbs.3dmgame.com/home.php?mod=task&do=apply&id=9",
loginurl="http://bbs.ithome.com/member.php?mod=logging&action=login&loginsubmit=yes&infloat=yes&lssubmit=yes",
logindata={"username": "", "password": ""},
# url="http://bbs.ithome.com/home.php?mod=spacecp&ac=usergroup",
cookies=dict(
uchome_2132_auth="5b3bx5iQyK2yuyALeoJChdkEnVAbAJZnz%2FPV5yjjdfpV9nW7JWrzPG21s1Sr8zq1eTzxPYTqCNFRm36S3%2FoGduom8AHI",
uchome_2132_cookiereport="a163d4ArUbOfwx5PFQdjebMJMkqzbiRCt5N2M3%2F7yH5gpTMK%2BfCt",
uchome_2132_checkpm="0",
uchome_2132_connect_is_bind="0",
uchome_2132_home_diymode="1",
uchome_2132_lastact="1409282454%09home.php%09task",
uchome_2132_lastvisit="1409278415",
uchome_2132_noticeTitle="1",
uchome_2132_saltkey="NGlCLgkr",
uchome_2132_sid="C99oC1"
))
print(login.getWithCookies().text)
|
Quietly behind a curtain of international indifference, an African tragedy is unfolding in Congo. This beautiful and immensely rich country has been invaded by its neighbors, not for the high-minded purposes pretended in their rhetoric but out of greed and fear.
Forget the idea of, on the one hand, helping President Laurent Kabila restore democracy, or, on the other, removing his regime only in self-defense against the enemies he harbors. In fact, forget Mr. Kabila, who figures in this drama not as a mover or even a player, but as a pretext or target, little more than a figure of speech. The main objective of those for or against him seems to be to loot what they can of the nation's wealth right now and to gain control of Congo to plunder it further.
The story began with a double convulsion in the heart of Africa. In 1994, a genocidal civil war was launched in Rwanda by ethnic Hutu extremists. That triggered a response by their old antagonists, the Tutsis, which drove a million Hutu fleeing across the western border into Zaire. At the same time, the rotten system of Zaire's dictator, Mobutu Sese Seko, was unravelling. For two years, the suffering Hutu refugees in the jungles of eastern Zaire were kept alive by massive international feeding programs while Hutu guerrillas used the camps as military bases against Rwanda. By 1996, repatriating many refugees, Rwanda struck back. Together with Uganda, it armed and helped Kabila, then a nondescript Congolese rebel leader, at last drive Mobuto into exile.
Any hope that this enormous land, renamed Democratic Republic of the Congo, would move to freedom and independence was soon dashed. Kabila had neither the intention, nor a political base, nor an army of his own to assert a new course. People yearning for democracy saw corruption and repression continue under new management. Kabila, welcomed at first for getting rid of Mobutu, was soon reviled as a creature of Rwanda and Uganda.
These two allies, however, then moved to get rid of him, fostering a rebellion now in progress. The goal is not only to clean out Hutu guerrillas still attacking from Congo bases, but also to gain a monopoly on Congo's wealth for themselves. African sources report that truckloads of looted gold, diamonds, and coffee have already made the political and military leaders of Rwanda and Uganda immensely rich. There is much more where that came from.
Rushing to help Kabila and assure themselves a piece of the pie are some southern neighbors. Zimbabwe is the most active, having already sent thousands of troops to Congo, clashing with Rwandan forces there in open war. Angola is engaged, mainly defensively, fearing Rwandan-Ugandan help for the rebels in its own ongoing civil war. Distant Chad is sending troops to help Kabila for no known reason.
Efforts to bring about a cease-fire and a start toward political solution have met no success. President Nelson Mandela of South Africa tried personally and failed, burning his fingers as his term in office draws to an end.
He at first opposed the southern invasion, then endorsed it and then suffered the embarrassment of having South African arms found on captured Rwandan rebels. The Western powers, after centuries in Africa, have no colonialist or cold-war reasons to become involved in what they label an African responsibility. Congo, the center of Africa, has become a political vacuum. There is no telling what the forces trying to fill it will do to the land and its long-abused people.
|
"""
Demonstration application for range search using kd tree.
Left mouse adds point.
Right mouse click begins drag of rectangle.
"""
import tkinter
from adk.kd import KDTree, X, Y, VERTICAL
from adk.region import Region, minValue, maxValue
RectangleSize = 4
class KDTreeApp:
def __init__(self):
"""App for creating KD tree dynamically and executing range queries."""
self.tree = KDTree()
self.static = False
# for range query
self.selectedRegion = None
self.queryRect = None
self.master = tkinter.Tk()
self.master.title('KD Tree Range Query Application')
self.w = tkinter.Frame(self.master, width=410, height=410)
self.canvas = tkinter.Canvas(self.w, width=400, height=400)
self.paint()
self.canvas.bind("<Button-1>", self.click)
self.canvas.bind("<Motion>", self.moved)
self.canvas.bind("<Button-3>", self.range) # when right mouse clicked
self.canvas.bind("<ButtonRelease-3>", self.clear)
self.canvas.bind("<B3-Motion>", self.range) # only when right mouse dragged
self.w.pack()
def toCartesian(self, y):
"""Convert tkinter point into Cartesian."""
return self.w.winfo_height() - y
def toTk(self,y):
"""Convert Cartesian into tkinter point."""
if y == maxValue: return 0
tk_y = self.w.winfo_height()
if y != minValue:
tk_y -= y
return tk_y
def clear(self, event):
"""End of range search."""
self.selectedRegion = None
self.paint()
def range(self, event):
"""Initiate a range search using a selected rectangular region."""
p = (event.x, self.toCartesian(event.y))
if self.selectedRegion is None:
self.selectedStart = Region(p[X],p[Y], p[X],p[Y])
self.selectedRegion = self.selectedStart.unionPoint(p)
self.paint()
# return (node,status) where status is True if draining entire tree rooted at node. Draw these
# as shaded red rectangle to identify whole sub-tree is selected.
for pair in self.tree.range(self.selectedRegion):
p = pair[0].point
if pair[1]:
self.canvas.create_rectangle(pair[0].region.x_min, self.toTk(pair[0].region.y_min),
pair[0].region.x_max, self.toTk(pair[0].region.y_max),
fill='Red', stipple='gray12')
else:
self.canvas.create_rectangle(p[X] - RectangleSize, self.toTk(p[Y]) - RectangleSize,
p[X] + RectangleSize, self.toTk(p[Y]) + RectangleSize, fill='Red')
self.queryRect = self.canvas.create_rectangle(self.selectedRegion.x_min, self.toTk(self.selectedRegion.y_min),
self.selectedRegion.x_max, self.toTk(self.selectedRegion.y_max),
outline='Red', dash=(2, 4))
def moved(self, event):
"""Only here for static option."""
if self.static:
self.paint()
def click(self, event):
"""Add point to KDtree."""
p = (event.x, self.toCartesian(event.y))
self.tree.add(p)
self.paint()
def drawPartition (self, r, p, orient):
"""Draw partitioning line and points itself as a small square."""
if orient == VERTICAL:
self.canvas.create_line(p[X], self.toTk(r.y_min), p[X], self.toTk(r.y_max))
else:
xlow = r.x_min
if r.x_min <= minValue: xlow = 0
xhigh = r.x_max
if r.x_max >= maxValue: xhigh = self.w.winfo_width()
self.canvas.create_line(xlow, self.toTk(p[Y]), xhigh, self.toTk(p[Y]))
self.canvas.create_rectangle(p[X] - RectangleSize, self.toTk(p[Y]) - RectangleSize,
p[X] + RectangleSize, self.toTk(p[Y]) + RectangleSize, fill='Black')
def visit (self, n):
""" Visit node to paint properly."""
if n == None: return
self.drawPartition(n.region, n.point, n.orient)
self.visit (n.below)
self.visit (n.above)
def prepare(self, event):
"""prepare to add points."""
if self.label:
self.label.destroy()
self.label = None
self.canvas.pack()
def paint(self):
"""Paint quad tree by visiting all nodes, or show introductory message."""
if self.tree.root:
self.canvas.delete(tkinter.ALL)
self.visit(self.tree.root)
else:
self.label = tkinter.Label(self.w, width=100, height = 40, text="Click To Add Points")
self.label.bind("<Button-1>", self.prepare)
self.label.pack()
if __name__ == "__main__":
app = KDTreeApp()
app.w.mainloop()
|
Eastern bluebirds are beautiful, well-known, popular song birds that live in eastern North America. These little birds are easily recognized by the male's bright royal blue upper plumage, chest of reddish brown and white abdomen. The females is duller in color than the male, with grayer upperparts; but with an elegant look from the blue tinges to her wings. These bluebirds are the most common of the three bluebird species. Today many of the eastern bluebirds in North America nest in birdhouses intended for them on "bluebird trails." When not nesting, these birds fly in small flocks around the countryside.
Eastern bluebirds are found in eastern North America and Central America, from southern Canada to Nicaragua. There are a number living on Bermuda. They are partial migrants, the more northerly populations tending to move southwards in winter, with those further south generally remaining resident year-round in the breeding areas. These birds live in open woodlands, orchards, farmlands, and suburban areas. They prefer open land where there are scattered trees for nesting, perching and feeding.
The Eastern bluebird is a diurnal and very social bird. They sometimes gather in flocks numbering one hundred or more. They are also territorial and will defend a feeding and nesting territory around their nest site during the breeding season, as well as, in winter, a feeding territory. These birds are partially migratory, leaving their homes in the north when food becomes scarce or temperatures or other environmental conditions are unfavorable. When feeding, they often fly from their perch to the ground in order to catch a prey item such as an insect. Sometimes they use gleaning or fly catching. With good eyesight, they are able to locate small food items from distances of more than 100 feet. They fly quite low to the ground with a fast and irregular wing beat. Territorial males chase each other at fast speeds, sometimes fighting with their feet, plucking at feathers with their bills, and hitting their opponents with their wings.
Eastern bluebirds are carnivores (insectivores), they eat insects and their larvae, including caterpillars, butterflies, moths, and grasshoppers. They also eat berries, earthworms, spiders, snails, and other invertebrates.
These birds are monogamous, and a pair may mate with each other for more than just one season. Breeding usually occurs in April, though the season runs from February to September. A male will display at a potential nest site to attract a female, bringing nest material, going in and out of a suitable hole, then perching above it, waving his wings. He will select several nest sites, and the female may begin to build nests in different sites before choosing one and completing a nest. The cup-shaped nest is often located in an old woodpecker hole, a dead tree, or a nest box. It is made from dry grasses, weed stems and rootlets. 3 to 5 white or sky blue eggs are laid, and incubation is by the female, for around 12 to 14 days. The altricial chicks hatch within one or two days of one another and their mother broods them at this time. Both parents tend to their young, brooding them at night if it is cold. The chicks fledge at around 16 to 22 days, and are dependent on their parents for a further 3 to 4 weeks. Chicks are reproductively mature at the age of one.
Eastern bluebird numbers fell in the early 20th century as European starlings, house sparrows and other aggressive introduced species caused available nest holes to be increasingly difficult for the bluebirds to use. Other potential threats include increased use of pesticides as well as the use of metal fence posts in preference to wooden ones, decreasing the possibility of nesting holes in rotting posts.
According to the What Bird resource, the total population size of the Eastern bluebird is 10 million individuals. According to the All About Birds resource, the total breeding population of this species is 22 million birds, 86% of them spending some time in the U.S., 22% of them in Mexico, and 1% of them breeding in Canada. Overall, currently this species is classified as Least Concern (LC) on the IUCN Red List and its numbers today are increasing.
Being insectivorous, these birds affect insect populations in their range.
This species is the official state bird for Missouri and New York in the USA.
The Eastern bluebird’s song is one of its most distinguishing characteristics. They use different songs for mating and territoriality, as well as other purposes. The most common bluebird call sounds like “chur lee” or “chir wi”. When repeated a number of times, the call sounds like the words “truly” or “purity”.
A male may sing as many as 1,000 songs an hour in his attempt to attract a mate.
The Eastern bluebird lays two clutches per season. The male continues to look after the first clutch, while the female starts the second, and the young from the first clutch may help tend the second.
Eggs laid by the same female have the same color, and so eggs in the same nest of a different color indicate those of a different female.
If faced by a predator, an eastern bluebird will flick its wings and warble, and a male will make song-like warning cries.
|
#!/usr/bin/env python2
# vim:fileencoding=utf-8
from __future__ import (unicode_literals, division, absolute_import,
print_function)
__license__ = 'GPL v3'
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
import time, textwrap, json
from bisect import bisect_right
from base64 import b64encode
from future_builtins import map
from threading import Thread
from Queue import Queue, Empty
from functools import partial
from urlparse import urlparse
from PyQt5.Qt import (
QWidget, QVBoxLayout, QApplication, QSize, QNetworkAccessManager, QMenu, QIcon,
QNetworkReply, QTimer, QNetworkRequest, QUrl, Qt, QNetworkDiskCache, QToolBar,
pyqtSlot, pyqtSignal)
from PyQt5.QtWebKitWidgets import QWebView, QWebInspector, QWebPage
from calibre import prints
from calibre.constants import iswindows
from calibre.ebooks.oeb.polish.parsing import parse
from calibre.ebooks.oeb.base import serialize, OEB_DOCS
from calibre.ptempfile import PersistentTemporaryDirectory
from calibre.gui2 import error_dialog, open_url
from calibre.gui2.tweak_book import current_container, editors, tprefs, actions, TOP
from calibre.gui2.viewer.documentview import apply_settings
from calibre.gui2.viewer.config import config
from calibre.gui2.widgets2 import HistoryLineEdit2
from calibre.utils.ipc.simple_worker import offload_worker
shutdown = object()
def get_data(name):
'Get the data for name. Returns a unicode string if name is a text document/stylesheet'
if name in editors:
return editors[name].get_raw_data()
return current_container().raw_data(name)
# Parsing of html to add linenumbers {{{
def parse_html(raw):
root = parse(raw, decoder=lambda x:x.decode('utf-8'), line_numbers=True, linenumber_attribute='data-lnum')
return serialize(root, 'text/html').encode('utf-8')
class ParseItem(object):
__slots__ = ('name', 'length', 'fingerprint', 'parsing_done', 'parsed_data')
def __init__(self, name):
self.name = name
self.length, self.fingerprint = 0, None
self.parsed_data = None
self.parsing_done = False
def __repr__(self):
return 'ParsedItem(name=%r, length=%r, fingerprint=%r, parsing_done=%r, parsed_data_is_None=%r)' % (
self.name, self.length, self.fingerprint, self.parsing_done, self.parsed_data is None)
class ParseWorker(Thread):
daemon = True
SLEEP_TIME = 1
def __init__(self):
Thread.__init__(self)
self.requests = Queue()
self.request_count = 0
self.parse_items = {}
self.launch_error = None
def run(self):
mod, func = 'calibre.gui2.tweak_book.preview', 'parse_html'
try:
# Connect to the worker and send a dummy job to initialize it
self.worker = offload_worker(priority='low')
self.worker(mod, func, '<p></p>')
except:
import traceback
traceback.print_exc()
self.launch_error = traceback.format_exc()
return
while True:
time.sleep(self.SLEEP_TIME)
x = self.requests.get()
requests = [x]
while True:
try:
requests.append(self.requests.get_nowait())
except Empty:
break
if shutdown in requests:
self.worker.shutdown()
break
request = sorted(requests, reverse=True)[0]
del requests
pi, data = request[1:]
try:
res = self.worker(mod, func, data)
except:
import traceback
traceback.print_exc()
else:
pi.parsing_done = True
parsed_data = res['result']
if res['tb']:
prints("Parser error:")
prints(res['tb'])
else:
pi.parsed_data = parsed_data
def add_request(self, name):
data = get_data(name)
ldata, hdata = len(data), hash(data)
pi = self.parse_items.get(name, None)
if pi is None:
self.parse_items[name] = pi = ParseItem(name)
else:
if pi.parsing_done and pi.length == ldata and pi.fingerprint == hdata:
return
pi.parsed_data = None
pi.parsing_done = False
pi.length, pi.fingerprint = ldata, hdata
self.requests.put((self.request_count, pi, data))
self.request_count += 1
def shutdown(self):
self.requests.put(shutdown)
def get_data(self, name):
return getattr(self.parse_items.get(name, None), 'parsed_data', None)
def clear(self):
self.parse_items.clear()
def is_alive(self):
return Thread.is_alive(self) or (hasattr(self, 'worker') and self.worker.is_alive())
parse_worker = ParseWorker()
# }}}
# Override network access to load data "live" from the editors {{{
class NetworkReply(QNetworkReply):
def __init__(self, parent, request, mime_type, name):
QNetworkReply.__init__(self, parent)
self.setOpenMode(QNetworkReply.ReadOnly | QNetworkReply.Unbuffered)
self.setRequest(request)
self.setUrl(request.url())
self._aborted = False
if mime_type in OEB_DOCS:
self.resource_name = name
QTimer.singleShot(0, self.check_for_parse)
else:
data = get_data(name)
if isinstance(data, type('')):
data = data.encode('utf-8')
mime_type += '; charset=utf-8'
self.__data = data
self.setHeader(QNetworkRequest.ContentTypeHeader, mime_type)
self.setHeader(QNetworkRequest.ContentLengthHeader, len(self.__data))
QTimer.singleShot(0, self.finalize_reply)
def check_for_parse(self):
if self._aborted:
return
data = parse_worker.get_data(self.resource_name)
if data is None:
return QTimer.singleShot(10, self.check_for_parse)
self.__data = data
self.setHeader(QNetworkRequest.ContentTypeHeader, 'application/xhtml+xml; charset=utf-8')
self.setHeader(QNetworkRequest.ContentLengthHeader, len(self.__data))
self.finalize_reply()
def bytesAvailable(self):
try:
return len(self.__data)
except AttributeError:
return 0
def isSequential(self):
return True
def abort(self):
self._aborted = True
def readData(self, maxlen):
ans, self.__data = self.__data[:maxlen], self.__data[maxlen:]
return ans
read = readData
def finalize_reply(self):
if self._aborted:
return
self.setFinished(True)
self.setAttribute(QNetworkRequest.HttpStatusCodeAttribute, 200)
self.setAttribute(QNetworkRequest.HttpReasonPhraseAttribute, "Ok")
self.metaDataChanged.emit()
self.downloadProgress.emit(len(self.__data), len(self.__data))
self.readyRead.emit()
self.finished.emit()
class NetworkAccessManager(QNetworkAccessManager):
OPERATION_NAMES = {getattr(QNetworkAccessManager, '%sOperation'%x) :
x.upper() for x in ('Head', 'Get', 'Put', 'Post', 'Delete',
'Custom')
}
def __init__(self, *args):
QNetworkAccessManager.__init__(self, *args)
self.current_root = None
self.cache = QNetworkDiskCache(self)
self.setCache(self.cache)
self.cache.setCacheDirectory(PersistentTemporaryDirectory(prefix='disk_cache_'))
self.cache.setMaximumCacheSize(0)
def createRequest(self, operation, request, data):
url = unicode(request.url().toString(QUrl.None))
if operation == self.GetOperation and url.startswith('file://'):
path = url[7:]
if iswindows and path.startswith('/'):
path = path[1:]
c = current_container()
try:
name = c.abspath_to_name(path, root=self.current_root)
except ValueError: # Happens on windows with absolute paths on different drives
name = None
if c.has_name(name):
try:
return NetworkReply(self, request, c.mime_map.get(name, 'application/octet-stream'), name)
except Exception:
import traceback
traceback.print_exc()
return QNetworkAccessManager.createRequest(self, operation, request, data)
# }}}
def uniq(vals):
''' Remove all duplicates from vals, while preserving order. '''
vals = vals or ()
seen = set()
seen_add = seen.add
return tuple(x for x in vals if x not in seen and not seen_add(x))
def find_le(a, x):
'Find rightmost value in a less than or equal to x'
try:
return a[bisect_right(a, x)]
except IndexError:
return a[-1]
class WebPage(QWebPage):
sync_requested = pyqtSignal(object, object, object)
split_requested = pyqtSignal(object, object)
def __init__(self, parent):
QWebPage.__init__(self, parent)
settings = self.settings()
apply_settings(settings, config().parse())
settings.setMaximumPagesInCache(0)
settings.setAttribute(settings.JavaEnabled, False)
settings.setAttribute(settings.PluginsEnabled, False)
settings.setAttribute(settings.PrivateBrowsingEnabled, True)
settings.setAttribute(settings.JavascriptCanOpenWindows, False)
settings.setAttribute(settings.JavascriptCanAccessClipboard, False)
settings.setAttribute(settings.LinksIncludedInFocusChain, False)
settings.setAttribute(settings.DeveloperExtrasEnabled, True)
settings.setDefaultTextEncoding('utf-8')
data = 'data:text/css;charset=utf-8;base64,'
css = '[data-in-split-mode="1"] [data-is-block="1"]:hover { cursor: pointer !important; border-top: solid 5px green !important }'
data += b64encode(css.encode('utf-8'))
settings.setUserStyleSheetUrl(QUrl(data))
self.setNetworkAccessManager(NetworkAccessManager(self))
self.setLinkDelegationPolicy(self.DelegateAllLinks)
self.mainFrame().javaScriptWindowObjectCleared.connect(self.init_javascript)
self.init_javascript()
@dynamic_property
def current_root(self):
def fget(self):
return self.networkAccessManager().current_root
def fset(self, val):
self.networkAccessManager().current_root = val
return property(fget=fget, fset=fset)
def javaScriptConsoleMessage(self, msg, lineno, source_id):
prints('preview js:%s:%s:'%(unicode(source_id), lineno), unicode(msg))
def init_javascript(self):
if not hasattr(self, 'js'):
from calibre.utils.resources import compiled_coffeescript
self.js = compiled_coffeescript('ebooks.oeb.display.utils', dynamic=False)
self.js += P('csscolorparser.js', data=True, allow_user_override=False)
self.js += compiled_coffeescript('ebooks.oeb.polish.preview', dynamic=False)
self._line_numbers = None
mf = self.mainFrame()
mf.addToJavaScriptWindowObject("py_bridge", self)
mf.evaluateJavaScript(self.js)
@pyqtSlot(str, str, str)
def request_sync(self, tag_name, href, sourceline_address):
try:
self.sync_requested.emit(unicode(tag_name), unicode(href), json.loads(unicode(sourceline_address)))
except (TypeError, ValueError, OverflowError, AttributeError):
pass
def go_to_anchor(self, anchor, lnum):
self.mainFrame().evaluateJavaScript('window.calibre_preview_integration.go_to_anchor(%s, %s)' % (
json.dumps(anchor), json.dumps(str(lnum))))
@pyqtSlot(str, str)
def request_split(self, loc, totals):
actions['split-in-preview'].setChecked(False)
loc, totals = json.loads(unicode(loc)), json.loads(unicode(totals))
if not loc or not totals:
return error_dialog(self.view(), _('Invalid location'),
_('Cannot split on the body tag'), show=True)
self.split_requested.emit(loc, totals)
@property
def line_numbers(self):
if self._line_numbers is None:
def atoi(x):
try:
ans = int(x)
except (TypeError, ValueError):
ans = None
return ans
val = self.mainFrame().evaluateJavaScript('window.calibre_preview_integration.line_numbers()')
self._line_numbers = sorted(uniq(filter(lambda x:x is not None, map(atoi, val))))
return self._line_numbers
def go_to_line(self, lnum):
try:
lnum = find_le(self.line_numbers, lnum)
except IndexError:
return
self.mainFrame().evaluateJavaScript(
'window.calibre_preview_integration.go_to_line(%d)' % lnum)
def go_to_sourceline_address(self, sourceline_address):
lnum, tags = sourceline_address
if lnum is None:
return
tags = [x.lower() for x in tags]
self.mainFrame().evaluateJavaScript(
'window.calibre_preview_integration.go_to_sourceline_address(%d, %s)' % (lnum, json.dumps(tags)))
def split_mode(self, enabled):
self.mainFrame().evaluateJavaScript(
'window.calibre_preview_integration.split_mode(%s)' % (
'true' if enabled else 'false'))
class WebView(QWebView):
def __init__(self, parent=None):
QWebView.__init__(self, parent)
self.inspector = QWebInspector(self)
w = QApplication.instance().desktop().availableGeometry(self).width()
self._size_hint = QSize(int(w/3), int(w/2))
self._page = WebPage(self)
self.setPage(self._page)
self.inspector.setPage(self._page)
self.clear()
self.setAcceptDrops(False)
def sizeHint(self):
return self._size_hint
def refresh(self):
self.pageAction(self.page().Reload).trigger()
@dynamic_property
def scroll_pos(self):
def fget(self):
mf = self.page().mainFrame()
return (mf.scrollBarValue(Qt.Horizontal), mf.scrollBarValue(Qt.Vertical))
def fset(self, val):
mf = self.page().mainFrame()
mf.setScrollBarValue(Qt.Horizontal, val[0])
mf.setScrollBarValue(Qt.Vertical, val[1])
return property(fget=fget, fset=fset)
def clear(self):
self.setHtml(_(
'''
<h3>Live preview</h3>
<p>Here you will see a live preview of the HTML file you are currently editing.
The preview will update automatically as you make changes.
<p style="font-size:x-small; color: gray">Note that this is a quick preview
only, it is not intended to simulate an actual ebook reader. Some
aspects of your ebook will not work, such as page breaks and page margins.
'''))
self.page().current_root = None
def setUrl(self, qurl):
self.page().current_root = current_container().root
return QWebView.setUrl(self, qurl)
def inspect(self):
self.inspector.parent().show()
self.inspector.parent().raise_()
self.pageAction(self.page().InspectElement).trigger()
def contextMenuEvent(self, ev):
menu = QMenu(self)
p = self.page()
mf = p.mainFrame()
r = mf.hitTestContent(ev.pos())
url = unicode(r.linkUrl().toString(QUrl.None)).strip()
ca = self.pageAction(QWebPage.Copy)
if ca.isEnabled():
menu.addAction(ca)
menu.addAction(actions['reload-preview'])
menu.addAction(QIcon(I('debug.png')), _('Inspect element'), self.inspect)
if url.partition(':')[0].lower() in {'http', 'https'}:
menu.addAction(_('Open link'), partial(open_url, r.linkUrl()))
menu.exec_(ev.globalPos())
class Preview(QWidget):
sync_requested = pyqtSignal(object, object)
split_requested = pyqtSignal(object, object, object)
split_start_requested = pyqtSignal()
link_clicked = pyqtSignal(object, object)
refresh_starting = pyqtSignal()
refreshed = pyqtSignal()
def __init__(self, parent=None):
QWidget.__init__(self, parent)
self.l = l = QVBoxLayout()
self.setLayout(l)
l.setContentsMargins(0, 0, 0, 0)
self.view = WebView(self)
self.view.page().sync_requested.connect(self.request_sync)
self.view.page().split_requested.connect(self.request_split)
self.view.page().loadFinished.connect(self.load_finished)
self.inspector = self.view.inspector
self.inspector.setPage(self.view.page())
l.addWidget(self.view)
self.bar = QToolBar(self)
l.addWidget(self.bar)
ac = actions['auto-reload-preview']
ac.setCheckable(True)
ac.setChecked(True)
ac.toggled.connect(self.auto_reload_toggled)
self.auto_reload_toggled(ac.isChecked())
self.bar.addAction(ac)
ac = actions['sync-preview-to-editor']
ac.setCheckable(True)
ac.setChecked(True)
ac.toggled.connect(self.sync_toggled)
self.sync_toggled(ac.isChecked())
self.bar.addAction(ac)
self.bar.addSeparator()
ac = actions['split-in-preview']
ac.setCheckable(True)
ac.setChecked(False)
ac.toggled.connect(self.split_toggled)
self.split_toggled(ac.isChecked())
self.bar.addAction(ac)
ac = actions['reload-preview']
ac.triggered.connect(self.refresh)
self.bar.addAction(ac)
actions['preview-dock'].toggled.connect(self.visibility_changed)
self.current_name = None
self.last_sync_request = None
self.refresh_timer = QTimer(self)
self.refresh_timer.timeout.connect(self.refresh)
parse_worker.start()
self.current_sync_request = None
self.search = HistoryLineEdit2(self)
self.search.initialize('tweak_book_preview_search')
self.search.setPlaceholderText(_('Search in preview'))
self.search.returnPressed.connect(partial(self.find, 'next'))
self.bar.addSeparator()
self.bar.addWidget(self.search)
for d in ('next', 'prev'):
ac = actions['find-%s-preview' % d]
ac.triggered.connect(partial(self.find, d))
self.bar.addAction(ac)
def find(self, direction):
text = unicode(self.search.text())
self.view.findText(text, QWebPage.FindWrapsAroundDocument | (
QWebPage.FindBackward if direction == 'prev' else QWebPage.FindFlags(0)))
def request_sync(self, tagname, href, lnum):
if self.current_name:
c = current_container()
if tagname == 'a' and href:
if href and href.startswith('#'):
name = self.current_name
else:
name = c.href_to_name(href, self.current_name) if href else None
if name == self.current_name:
return self.view.page().go_to_anchor(urlparse(href).fragment, lnum)
if name and c.exists(name) and c.mime_map[name] in OEB_DOCS:
return self.link_clicked.emit(name, urlparse(href).fragment or TOP)
self.sync_requested.emit(self.current_name, lnum)
def request_split(self, loc, totals):
if self.current_name:
self.split_requested.emit(self.current_name, loc, totals)
def sync_to_editor(self, name, sourceline_address):
self.current_sync_request = (name, sourceline_address)
QTimer.singleShot(100, self._sync_to_editor)
def _sync_to_editor(self):
if not actions['sync-preview-to-editor'].isChecked():
return
try:
if self.refresh_timer.isActive() or self.current_sync_request[0] != self.current_name:
return QTimer.singleShot(100, self._sync_to_editor)
except TypeError:
return # Happens if current_sync_request is None
sourceline_address = self.current_sync_request[1]
self.current_sync_request = None
self.view.page().go_to_sourceline_address(sourceline_address)
def report_worker_launch_error(self):
if parse_worker.launch_error is not None:
tb, parse_worker.launch_error = parse_worker.launch_error, None
error_dialog(self, _('Failed to launch worker'), _(
'Failed to launch the worker process used for rendering the preview'), det_msg=tb, show=True)
def show(self, name):
if name != self.current_name:
self.refresh_timer.stop()
self.current_name = name
self.report_worker_launch_error()
parse_worker.add_request(name)
self.view.setUrl(QUrl.fromLocalFile(current_container().name_to_abspath(name)))
return True
def refresh(self):
if self.current_name:
self.refresh_timer.stop()
# This will check if the current html has changed in its editor,
# and re-parse it if so
self.report_worker_launch_error()
parse_worker.add_request(self.current_name)
# Tell webkit to reload all html and associated resources
current_url = QUrl.fromLocalFile(current_container().name_to_abspath(self.current_name))
self.refresh_starting.emit()
if current_url != self.view.url():
# The container was changed
self.view.setUrl(current_url)
else:
self.view.refresh()
self.refreshed.emit()
def clear(self):
self.view.clear()
self.current_name = None
@property
def current_root(self):
return self.view.page().current_root
@property
def is_visible(self):
return actions['preview-dock'].isChecked()
@property
def live_css_is_visible(self):
try:
return actions['live-css-dock'].isChecked()
except KeyError:
return False
def start_refresh_timer(self):
if self.live_css_is_visible or (self.is_visible and actions['auto-reload-preview'].isChecked()):
self.refresh_timer.start(tprefs['preview_refresh_time'] * 1000)
def stop_refresh_timer(self):
self.refresh_timer.stop()
def auto_reload_toggled(self, checked):
if self.live_css_is_visible and not actions['auto-reload-preview'].isChecked():
actions['auto-reload-preview'].setChecked(True)
error_dialog(self, _('Cannot disable'), _(
'Auto reloading of the preview panel cannot be disabled while the'
' Live CSS panel is open.'), show=True)
actions['auto-reload-preview'].setToolTip(_(
'Auto reload preview when text changes in editor') if not checked else _(
'Disable auto reload of preview'))
def sync_toggled(self, checked):
actions['sync-preview-to-editor'].setToolTip(_(
'Disable syncing of preview position to editor position') if checked else _(
'Enable syncing of preview position to editor position'))
def visibility_changed(self, is_visible):
if is_visible:
self.refresh()
def split_toggled(self, checked):
actions['split-in-preview'].setToolTip(textwrap.fill(_(
'Abort file split') if checked else _(
'Split this file at a specified location.\n\nAfter clicking this button, click'
' inside the preview panel above at the location you want the file to be split.')))
if checked:
self.split_start_requested.emit()
else:
self.view.page().split_mode(False)
def do_start_split(self):
self.view.page().split_mode(True)
def stop_split(self):
actions['split-in-preview'].setChecked(False)
def load_finished(self, ok):
if actions['split-in-preview'].isChecked():
if ok:
self.do_start_split()
else:
self.stop_split()
def apply_settings(self):
s = self.view.page().settings()
s.setFontSize(s.DefaultFontSize, tprefs['preview_base_font_size'])
s.setFontSize(s.DefaultFixedFontSize, tprefs['preview_mono_font_size'])
s.setFontSize(s.MinimumLogicalFontSize, tprefs['preview_minimum_font_size'])
s.setFontSize(s.MinimumFontSize, tprefs['preview_minimum_font_size'])
sf, ssf, mf = tprefs['preview_serif_family'], tprefs['preview_sans_family'], tprefs['preview_mono_family']
s.setFontFamily(s.StandardFont, {'serif':sf, 'sans':ssf, 'mono':mf, None:sf}[tprefs['preview_standard_font_family']])
s.setFontFamily(s.SerifFont, sf)
s.setFontFamily(s.SansSerifFont, ssf)
s.setFontFamily(s.FixedFont, mf)
|
No crab boil for me!
I truly dislike the flavor of crab or shrimp boil, something is just plain ol' off about it. I start with making normal boiled peanuts, salt-water, and add a few chicken bouillon cubes, onion and garlic. As they get close to done, I add heat- cayenne (red) pepper, dried pepper flakes, fresh jalapenos or datil peppers, at least one habanero. Taste. Sometimes I'll toss in Chipotle tabasco - yummy smoked flavor! Not many eat food as hot spicy as I do, so I make a separate batch that kicks it up a notch.
Comments for No crab boil for me!
That packaged spice mix is awful, ruined a good pot of green peanuts using it. Can't figure out why 99% of recipes use it, nasty. I'm trying yours now, wish I had a couple of datil peppers, but I'll come up with something. And yes, love the Chipotle Tabasco too! Thanks so much for sharing!
Join in and write your own page! It's easy to do. How? Simply click here to return to Cajun Boiled Peanuts.
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Licensed to Alpine Data, Inc.
# Copyright 2017 Alpine Data All Rights reserved.
"""Simple Command-Line Sample For Alpine API.
Command-line application to login and logout with Alpine API
Usage:
$ python workfile.py
To get detailed log output run:
$ python workfile.py --logging_level=DEBUG
"""
import logging
import sys
import time
from alpine.exception import *
from alpine import *
from future.datasource import DataSource
def help():
print("Usage: host=[host] port=[port] user=[username] password=[password]")
def setUp(alpine_host, alpine_port, username, password):
global db_data_source_id
global hadoop_data_source_id
global sample_datasource_db_name
global sample_datasource_hadoop_name
sample_datasource_db_name = "Demo_GP"
sample_datasource_hadoop_name = "Demo_Hadoop"
alpine_session = APIClient(alpine_host, alpine_port)
# Login with the admin user credential
alpine_session.login(username, password)
db_data_source_id = alpine_session.datasource.get_id(sample_datasource_db_name, "Database")
hadoop_data_source_id = alpine_session.datasource.get_id(sample_datasource_hadoop_name, "Hadoop")
# # Demo Database Info (Greenplum)
# sample_datasource_db_description = "Test Greenplum"
# sample_datasource_db_host = "10.10.0.151"
# sample_datasource_db_port = 5432
# sample_datasource_db_database_name = "miner_demo"
# sample_datasource_db_database_username = "miner_demo"
# sample_datasource_db_database_password = "miner_demo"
#
# # Demo Hadoop Info (Cloudera CDH5.7)
# sample_datasource_hadoop_version_string = "Cloudera CDH5.4-5.7"
# sample_datasource_hadoop_description = "Test Cloudera"
# sample_datasource_hadoop_namenode_host = "awscdh57singlenode.alpinenow.local"
# sample_datasource_hadoop_namenode_port = 8020
# sample_datasource_hadoop_resource_manager_host = "awscdh57singlenode.alpinenow.local"
# sample_datasource_hadoop_resource_manager_port = 8032
# sample_datasource_hadoop_username = "yarn"
# sample_datasource_hadoop_group_list = "hadoop"
# sample_datasource_hadoop_additional_parameters = [
# {"key": "mapreduce.jobhistory.address", "value": "awscdh57singlenode.alpinenow.local:10020"},
# {"key": "mapreduce.jobhistory.webapp.address", "value": "awscdh57singlenode.alpinenow.local:19888"},
# {"key": "yarn.app.mapreduce.am.staging-dir", "value": "/tmp"},
# {"key": "yarn.resourcemanager.admin.address", "value": "awscdh57singlenode.alpinenow.local:8033"},
# {"key": "yarn.resourcemanager.resource-tracker.address",
# "value": "awscdh57singlenode.alpinenow.local:8031"},
# {"key": "yarn.resourcemanager.scheduler.address", "value": "awscdh57singlenode.alpinenow.local:8030"}
# ]
# ds = DataSource(alpine_session.base_url, alpine_session.session, alpine_session.token)
# ds.delete_db_data_source_if_exists(sample_datasource_db_name)
# datasource_gp = ds.add_greenplum_data_source(sample_datasource_db_name,
# sample_datasource_db_description,
# sample_datasource_db_host,
# sample_datasource_db_port,
# sample_datasource_db_database_name,
# sample_datasource_db_database_username,
# sample_datasource_db_database_password)
#
# # Create a Hadoop datasource
# ds.delete_hadoop_data_source_if_exists(sample_datasource_hadoop_name)
#
# datasource_hadoop = ds.add_hadoop_data_source(sample_datasource_hadoop_version_string,
# sample_datasource_hadoop_name,
# sample_datasource_hadoop_description,
# sample_datasource_hadoop_namenode_host,
# sample_datasource_hadoop_namenode_port,
# sample_datasource_hadoop_resource_manager_host,
# sample_datasource_hadoop_resource_manager_port,
# sample_datasource_hadoop_username,
# sample_datasource_hadoop_group_list,
# sample_datasource_hadoop_additional_parameters
# )
#
# db_data_source_id = datasource_gp['id']
# hadoop_data_source_id = datasource_hadoop['id']
def tearDown(alpine_host, alpine_port, username, password):
sample_username = "test_user"
sample_workspace_name = "API Sample Workspace"
alpine_session = APIClient(alpine_host, alpine_port)
# Login with the admin user credential
alpine_session.login(username, password)
# Delete the Datasource
# alpine_session.datasource.delete_db_data_source(sample_datasource_db_name)
# response = alpine_session.datasource.delete_hadoop_data_source(sample_datasource_hadoop_name)
# Delete the workspace
response = alpine_session.workspace.delete_workspace(sample_workspace_name)
print("Received response code {0} with reason {1}...".format(response.status_code, response.reason))
# Delete the user.
response = alpine_session.user.delete_user(sample_username)
print("Received response code {0} with reason {1}...".format(response.status_code, response.reason))
def main(alpine_host, alpine_port, username, password):
alpine_host = alpine_host
alpine_port = alpine_port
# Use the setup function to create datasource for use
setUp(alpine_host, alpine_port, username, password)
sample_username = "test_user"
sample_password = "password"
sample_firstname = "First"
sample_lastname = "Last"
sample_member_role = "Business Analyst"
sample_email = "test_user@alpinenow.com"
sample_title = "Title"
sample_deparment = "Department"
sample_admin_type = "admin"
sample_user_type = "analytics_developer"
sample_workspace_name = "API Sample Workspace"
sample_workspace_public_state_true = True
# Create a APIClient session
# alpine_session = APIClient(alpine_host, alpine_port)
# alpine_session.login(username, password)
alpine_session = APIClient(alpine_host, alpine_port, username, password)
# Logging Examples
# use default logger
alpine_session.logger.debug("This is a debug message")
alpine_session.logger.info("This is a info message")
alpine_session.logger.error("This is a error message")
# use a custom logger
custom_logger = logging.getLogger("custom")
custom_logger.debug("This is a custom debug message")
custom_logger.info("This is a custom info message")
custom_logger.error("This is a custom error message")
# Workspace Examples
# Delete sample workspaces if exists
try:
workspace_id = alpine_session.workspace.get_id(workspace_name=sample_workspace_name)
alpine_session.workspace.delete(workspace_id)
except WorkspaceNotFoundException:
pass
# Create a new sample workspace
workspace_info = alpine_session.workspace.create(workspace_name=sample_workspace_name, public=sample_workspace_public_state_true,
summary="")
workspace_id = workspace_info['id']
# User Examples
# Create a new sample user with admin roles
try:
user_id = alpine_session.user.get_id(sample_username)
alpine_session.user.delete(user_id)
except UserNotFoundException:
pass
user_info = alpine_session.user.create(sample_username, sample_password, sample_firstname, sample_lastname, sample_email,
sample_title, sample_deparment, admin_role=sample_admin_type, app_role=sample_user_type)
member_list = alpine_session.workspace.member.add(workspace_id, user_info['id'], sample_member_role)
# Workflow Examples
afm_path = "afm/demo_hadoop_row_filter_regression.afm"
try:
workfile_id = alpine_session.workfile.get_id("demo_hadoop_row_filter_regression", workspace_id)
alpine_session.workfile.delete(workfile_id)
except WorkfileNotFoundException:
pass
datasource_info = [{"data_source_type": alpine_session.datasource.dsType.HadoopCluster,
"data_source_id": hadoop_data_source_id
}]
workfile_info = alpine_session.workfile.upload(workspace_info['id'], afm_path, datasource_info)
print("Uploaded Workfile Info: {0}".format(workfile_info))
variables = [{"name": "@min_credit_line", "value": "7"}]
process_id = alpine_session.workfile.process.run(workfile_info['id'], variables)
workfile_status = None
max_waiting_seconds = 100
for i in range(0, max_waiting_seconds):
workfile_status = alpine_session.workfile.process.query_status(process_id)
if workfile_status in ["WORKING"]:
time.sleep(10)
elif workfile_status == "FINISHED":
print("Workfile Finished after waiting for {0} seconds".format(i*10))
break
else:
raise RunFlowFailureException("Workflow run into unexpected stage: {0}".format(workfile_status))
if workfile_status != "FINISHED":
raise RunFlowFailureException("Run Flow not Finished after running for {0} seconds"
.format(max_waiting_seconds*10))
# Use the Tear dowon function to delete the datasource if needed
# tearDown(alpine_host, alpine_port, username, password)
if __name__ == '__main__':
self = sys.modules['__main__']
if len(sys.argv) >= 5:
host = sys.argv[1].split('=')[1]
port = sys.argv[2].split('=')[1]
username = sys.argv[3].split('=')[1]
password = sys.argv[4].split('=')[1]
main(host, port, username,password)
else:
help()
|
"Genetic variability of the stable fly assessed on a global scale usin" by Kathleen M. Kneeland, Steven R. Skoda et al.
The stable fly, Stomoxys calcitrans (L.) (Diptera: Muscidae), is a blood-feeding, economically important pest of animals and humans worldwide. Improved management strategies are essential and their development would benefit from studies on genetic diversity of stable flies. Especially if done on a global scale, such research could generate information necessary for the development and application of more efficient control methods. Herein we report on a genetic study of stable flies using amplified fragment length polymorphism, with samples of 10–40 individuals acquired from a total of 25 locations in the Nearctic, Neotropic, Palearctic, Afrotropic and Australasian biogeographical regions. We hypothesized that genetic differentiation would exist across geographical barriers. Although FST (0.33) was moderately high, the GST (0.05; representing genetic diversity between individuals) was very low; Nm values (representing gene flow) were high (9.36). The mismatch distribution and tests of neutrality suggested population expansion, with no genetic differentiation between locations. The analysis of molecular variance (AMOVA) results showed the majority of genetic diversity was within groups. The mantel test showed no correlation between geographic and genetic distance; this strongly supports theAMOVA results. These results suggest that stable flies did not show genetic differentiation but are panmictic, with no evidence of isolation by distance or across geographical barriers.
|
# -*- coding: utf-8 -*-
# This file is part of Gertrude.
#
# Gertrude is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# Gertrude is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Gertrude; if not, see <http://www.gnu.org/licenses/>.
from __future__ import unicode_literals
from __future__ import print_function
import wx
import wx.lib
import wx.lib.scrolledpanel
import wx.lib.masked
import wx.lib.stattext
import wx.combo
from wx.lib.masked import Field
from helpers import *
from functions import *
from config import config
from history import Change, Insert, Delete
class GPanel(wx.Panel):
def __init__(self, parent, title):
wx.Panel.__init__(self, parent, style=wx.LB_DEFAULT)
self.sizer = wx.BoxSizer(wx.VERTICAL)
sizer = wx.BoxSizer(wx.HORIZONTAL)
if sys.platform == 'win32':
st = wx.StaticText(self, -1, title, size=(-1, 24), style=wx.BORDER_SUNKEN | wx.ST_NO_AUTORESIZE)
font = wx.Font(12, wx.SWISS, wx.NORMAL, wx.BOLD)
else:
st = wx.lib.stattext.GenStaticText(self, -1, ' ' + title, size=(-1, 28),
style=wx.BORDER_SUNKEN | wx.ST_NO_AUTORESIZE)
font = st.GetFont()
font.SetPointSize(14)
st.SetFont(font)
st.SetBackgroundColour(wx.Colour(10, 36, 106))
st.SetBackgroundStyle(wx.BG_STYLE_COLOUR)
st.SetForegroundColour(wx.Colour(255, 255, 255))
sizer.Add(st, 1, wx.EXPAND)
self.sizer.Add(sizer, 0, wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.BOTTOM, 5)
self.SetSizer(self.sizer)
self.SetAutoLayout(1)
def UpdateContents(self):
pass
class NumericCtrl(wx.TextCtrl):
def __init__(self, parent, id=-1, value="", min=None, max=None, precision=3, action_kw={}, *args, **kwargs):
self.__digits = '0123456789.-'
self.__prec = precision
self.format = '%.' + str(self.__prec) + 'f'
self.__val = 0
self.__min, self.__max = None, None
if max is not None:
self.__max = float(max)
if min is not None:
self.__min = float(min)
wx.TextCtrl.__init__(self, parent, id, value=value, *args, **kwargs)
self.Bind(wx.EVT_CHAR, self.onChar)
def SetPrecision(self, p):
self.__prec = p
self.format = '%.' + str(self.__prec) + 'f'
def onChar(self, event):
""" on Character event"""
key = event.KeyCode
entry = wx.TextCtrl.GetValue(self).strip()
# 2. other non-text characters are passed without change
if key < wx.WXK_SPACE or key == wx.WXK_DELETE or key > 255:
event.Skip()
return
# 3. check for multiple '.' and out of place '-' signs and ignore these
# note that chr(key) will now work due to return at #2
pos = wx.TextCtrl.GetSelection(self)[0]
has_minus = '-' in entry
if ((chr(key) == '.' and (self.__prec == 0 or '.' in entry)) or
(chr(key) == '-' and (has_minus or pos != 0 or (self.__min is not None and self.__min >= 0))) or
(chr(key) != '-' and has_minus and pos == 0)):
return
# 4. allow digits, but not other characters
if chr(key) in self.__digits:
event.Skip()
return
def GetValue(self):
if wx.TextCtrl.GetValue(self) == "":
return None
elif self.__prec > 0:
return float(wx.TextCtrl.GetValue(self))
else:
return int(wx.TextCtrl.GetValue(self))
# def __Text_SetValue(self,value):
def SetValue(self, value):
if value != "":
wx.TextCtrl.SetValue(self, self.format % float(value))
else:
wx.TextCtrl.SetValue(self, "")
self.Refresh()
def GetMin(self):
return self.__min
def GetMax(self):
return self.__max
def SetMin(self, min):
try:
self.__min = float(min)
except:
pass
return self.__min
def SetMax(self, max):
try:
self.__max = float(max)
except:
pass
return self.__max
PHONECTRL_WIDTH = 0
class PhoneCtrl(wx.TextCtrl):
def __init__(self, parent, id, value=None, action_kw={}, *args, **kwargs):
global PHONECTRL_WIDTH
self.__digits = '0123456789'
# this_sty = wx.TAB_TRAVERSAL| wx.TE_PROCESS_ENTER
kw = kwargs
wx.TextCtrl.__init__(self, parent.GetWindow(), id, size=(-1, -1), *args, **kw)
self.SetMaxLength(14)
if PHONECTRL_WIDTH == 0:
dc = wx.WindowDC(self)
PHONECTRL_WIDTH = dc.GetMultiLineTextExtent("00 00 00 00 00", self.GetFont())[0]
self.SetMinSize((PHONECTRL_WIDTH + 15, -1))
wx.EVT_CHAR(self, self.onChar)
wx.EVT_TEXT(self, -1, self.checkSyntax)
wx.EVT_LEFT_DOWN(self, self.OnLeftDown)
def onChar(self, event):
""" on Character event"""
ip = self.GetInsertionPoint()
lp = self.GetLastPosition()
key = event.KeyCode
# 2. other non-text characters are passed without change
if key == wx.WXK_BACK:
if ip > 0:
self.RemoveChar(ip - 1)
return
if key < wx.WXK_SPACE or key == wx.WXK_DELETE or key > 255:
event.Skip()
wx.CallAfter(self.Arrange, key)
return
# 4. allow digits, but not other characters
if chr(key) in self.__digits:
event.Skip()
wx.CallAfter(self.Arrange, key)
def checkSyntax(self, event=None):
value = self.GetValue()
if value != "" and len(value) != 14:
self.SetBackgroundColour(wx.RED)
else:
self.SetBackgroundColour(wx.WHITE)
self.Refresh()
event.Skip()
def Arrange(self, key):
ip = self.GetInsertionPoint()
lp = self.GetLastPosition()
sel = self.GetSelection()
value = self.GetValue()
tmp = self.GetValue().replace(" ", "")
arranged = ""
for c in tmp:
if c in self.__digits:
arranged += c
if len(arranged) < 14 and len(arranged) % 3 == 2:
arranged += " "
else:
ip -= 1
if arranged != value:
self.SetValue(arranged)
if sel == (ip, ip) or arranged != value:
if (ip == len(arranged) or arranged[ip] != " "):
self.SetInsertionPoint(ip)
elif key == wx.WXK_LEFT:
self.SetInsertionPoint(ip - 1)
else:
self.SetInsertionPoint(ip + 1)
def RemoveChar(self, index):
value = self.GetValue()
if value[index] == " ":
value = value[:index - 1] + value[index + 1:]
index -= 1
else:
value = value[:index] + value[index + 1:]
self.SetValue(value)
self.SetInsertionPoint(index)
self.Arrange(wx.WXK_BACK)
def OnLeftDown(self, event):
if event.LeftDown():
event.Skip()
wx.CallAfter(self.OnCursorMoved, event)
def OnCursorMoved(self, event):
ip = self.GetInsertionPoint()
if ip < 14 and ip % 3 == 2:
self.SetInsertionPoint(ip + 1)
if 0: # sys.platform == 'win32':
class DateCtrl(wx.GenericDatePickerCtrl):
def SetValue(self, date):
if date is None:
date = wx.DefaultDateTime
if isinstance(date, (datetime.datetime, datetime.date)):
tt = date.timetuple()
dmy = (tt[2], tt[1] - 1, tt[0])
date = wx.DateTimeFromDMY(*dmy)
wx.GenericDatePickerCtrl.SetValue(self, date)
def GetValue(self):
date = wx.GenericDatePickerCtrl.GetValue(self)
if date.IsValid():
ymd = map(int, date.FormatISODate().split('-'))
return datetime.date(*ymd)
else:
return None
else:
DATECTRL_WIDTH = 0
class DateCtrl(wx.TextCtrl):
def __init__(self, parent, id=-1, value=None, mois=False, *args, **kwargs):
global DATECTRL_WIDTH
self.mois = mois
wx.TextCtrl.__init__(self, parent, id=-1, *args, **kwargs)
if DATECTRL_WIDTH == 0:
dc = wx.WindowDC(self)
DATECTRL_WIDTH = dc.GetMultiLineTextExtent("00/00/0000 ", self.GetFont())[0]
self.SetMinSize((DATECTRL_WIDTH + 10, -1))
wx.EVT_TEXT(self, -1, self.checkSyntax)
if value is not None:
self.SetValue(value)
def checkSyntax(self, event=None):
str = wx.TextCtrl.GetValue(self)
if str == "":
self.SetBackgroundColour(wx.WHITE)
elif self.mois and (
str.lower() in [m.lower() for m in months] or (str.isdigit() and int(str) in range(1, 13))):
self.SetBackgroundColour(wx.WHITE)
else:
if self.mois:
r = str2date(str, day=1)
else:
r = str2date(str)
if r:
self.SetBackgroundColour(wx.WHITE)
else:
self.SetBackgroundColour(wx.RED)
self.Refresh()
event.Skip()
def GetValue(self):
if self.mois:
return wx.TextCtrl.GetValue(self)
elif wx.TextCtrl.GetValue(self) == "":
return None
else:
return str2date(wx.TextCtrl.GetValue(self))
def SetValue(self, value):
if value is None:
wx.TextCtrl.SetValue(self, '')
elif self.mois:
wx.TextCtrl.SetValue(self, value)
else:
wx.TextCtrl.SetValue(self, '%.02d/%.02d/%.04d' % (value.day, value.month, value.year))
self.Refresh()
class TimeCtrl(wx.lib.masked.TimeCtrl):
def __init__(self, parent):
self.spin = wx.SpinButton(parent, -1, wx.DefaultPosition, (-1, 10), wx.SP_VERTICAL)
self.spin.SetRange(-100000, +100000)
self.spin.SetValue(0)
wx.lib.masked.TimeCtrl.__init__(self, parent, id=-1, fmt24hr=True, display_seconds=False, spinButton=self.spin)
def SetParameters(self, **kwargs):
"""
Function providing access to the parameters governing TimeCtrl display and bounds.
"""
maskededit_kwargs = {}
reset_format = False
if kwargs.has_key('display_seconds'):
kwargs['displaySeconds'] = kwargs['display_seconds']
del kwargs['display_seconds']
if kwargs.has_key('format') and kwargs.has_key('displaySeconds'):
del kwargs['displaySeconds'] # always apply format if specified
# assign keyword args as appropriate:
for key, param_value in kwargs.items():
if key not in TimeCtrl.valid_ctrl_params.keys():
raise AttributeError('invalid keyword argument "%s"' % key)
if key == 'format':
wxdt = wx.DateTimeFromDMY(1, 0, 1970)
try:
if wxdt.Format('%p') != 'AM':
require24hr = True
else:
require24hr = False
except:
require24hr = True
# handle both local or generic 'maskededit' autoformat codes:
if param_value == 'HHMMSS' or param_value == 'TIMEHHMMSS':
self.__displaySeconds = True
self.__fmt24hr = False
elif param_value == 'HHMM' or param_value == 'TIMEHHMM':
self.__displaySeconds = False
self.__fmt24hr = False
elif param_value == '24HHMMSS' or param_value == '24HRTIMEHHMMSS':
self.__displaySeconds = True
self.__fmt24hr = True
elif param_value == '24HHMM' or param_value == '24HRTIMEHHMM':
self.__displaySeconds = False
self.__fmt24hr = True
else:
raise AttributeError('"%s" is not a valid format' % param_value)
if require24hr and not self.__fmt24hr:
raise AttributeError('"%s" is an unsupported time format for the current locale' % param_value)
reset_format = True
elif key in ("displaySeconds", "display_seconds") and not kwargs.has_key('format'):
self.__displaySeconds = param_value
reset_format = True
elif key == "min":
min = param_value
elif key == "max":
max = param_value
elif key == "limited":
limited = param_value
elif key == "useFixedWidthFont":
maskededit_kwargs[key] = param_value
elif key == "oob_color":
maskededit_kwargs['invalidBackgroundColor'] = param_value
if reset_format:
if self.__fmt24hr:
if self.__displaySeconds:
maskededit_kwargs['autoformat'] = '24HRTIMEHHMMSS'
else:
maskededit_kwargs['autoformat'] = '24HRTIMEHHMM'
# Set hour field to zero-pad, right-insert, require explicit field change,
# select entire field on entry, and require a resultant valid entry
# to allow character entry:
hourfield = Field(formatcodes='0r<SV', validRegex='0\d|1\d|2[0123]', validRequired=True)
else:
if self.__displaySeconds:
maskededit_kwargs['autoformat'] = 'TIMEHHMMSS'
else:
maskededit_kwargs['autoformat'] = 'TIMEHHMM'
# Set hour field to allow spaces (at start), right-insert,
# require explicit field change, select entire field on entry,
# and require a resultant valid entry to allow character entry:
hourfield = Field(formatcodes='_0<rSV', validRegex='0[1-9]| [1-9]|1[012]', validRequired=True)
ampmfield = Field(formatcodes='S', emptyInvalid=True, validRequired=True)
# Field 1 is always a zero-padded right-insert minute field,
# similarly configured as above:
minutefield = Field(formatcodes='0r<SV', validRegex='[0-5][0|5]', validRequired=True)
fields = [hourfield, minutefield]
if self.__displaySeconds:
fields.append(copy.copy(minutefield)) # second field has same constraints as field 1
if not self.__fmt24hr:
fields.append(ampmfield)
# set fields argument:
maskededit_kwargs['fields'] = fields
# This allows range validation if set
maskededit_kwargs['validFunc'] = self.IsInBounds
# This allows range limits to affect insertion into control or not
# dynamically without affecting individual field constraint validation
maskededit_kwargs['retainFieldValidation'] = True
if hasattr(self, 'controlInitialized') and self.controlInitialized:
self.SetCtrlParameters(**maskededit_kwargs) # set appropriate parameters
# self.SetBounds("00:00", "23:55")
# Validate initial value and set if appropriate
try:
self.SetBounds(min, max)
self.SetLimited(limited)
self.SetValue(value)
except:
self.SetValue('00:00:00')
return {} # no arguments to return
else:
return maskededit_kwargs
def __IncrementValue(self, key, pos):
text = self.GetValue()
field = self._FindField(pos)
start, end = field._extent
slice = text[start:end]
if key == wx.WXK_UP:
increment = 1
else:
increment = -1
if slice in ('A', 'P'):
if slice == 'A':
newslice = 'P'
elif slice == 'P':
newslice = 'A'
newvalue = text[:start] + newslice + text[end:]
elif field._index == 0:
# adjusting this field is trickier, as its value can affect the
# am/pm setting. So, we use wxDateTime to generate a new value for us:
# (Use a fixed date not subject to DST variations:)
converter = wx.DateTimeFromDMY(1, 0, 1970)
converter.ParseTime(text.strip())
currenthour = converter.GetHour()
newhour = (currenthour + increment) % 24
converter.SetHour(newhour)
newvalue = converter # take advantage of auto-conversion for am/pm in .SetValue()
else: # minute or second field; handled the same way:
increment *= 5
newslice = "%02d" % ((int(slice) + increment) % 60)
newvalue = text[:start] + newslice + text[end:]
try:
self.SetValue(newvalue)
except ValueError: # must not be in bounds:
if not wx.Validator_IsSilent():
wx.Bell()
class AutoMixin:
default = None
def __init__(self, parent, instance, member, fixed_instance=False, observers=[], mask=None):
self.__ontext = True
self.parent = parent
self.fixed_instance = fixed_instance
self.observers = observers
self.mask = mask
if not fixed_instance:
parent.ctrls.append(self)
self.SetInstance(instance, member)
self.Bind(wx.EVT_TEXT, self.onText)
def __del__(self):
if not self.fixed_instance:
self.parent.ctrls.remove(self)
def SetInstance(self, instance, member=None):
self.instance = instance
if member:
self.member = member
self.UpdateContents()
def GetCurrentValue(self):
if self.mask:
return eval('self.instance.%s & self.mask' % self.member)
else:
return eval('self.instance.%s' % self.member)
def UpdateContents(self):
if not self.instance:
self.Disable()
else:
self.__ontext = False
try:
value = self.GetCurrentValue()
self.SetValue(self.default if value is None else value)
except Exception as e:
print("Erreur lors de l'evaluation de self.instance.%s" % self.member, e)
self.__ontext = True
self.Enable(not config.readonly)
def onText(self, event):
obj = event.GetEventObject()
if self.__ontext:
self.AutoChange(obj.GetValue())
event.Skip()
def AutoChange(self, new_value):
old_value = eval('self.instance.%s' % self.member)
if self.mask is not None:
new_value |= old_value & ~self.mask
if old_value != new_value:
last = history.Last()
if last is not None and len(last) == 1 and isinstance(last[-1], Change):
if last[-1].instance is not self.instance or last[-1].member != self.member:
history.Append(Change(self.instance, self.member, old_value))
else:
history.Append(Change(self.instance, self.member, old_value))
exec ('self.instance.%s = new_value' % self.member)
for o in self.observers:
counters[o] += 1
class AutoTextCtrl(wx.TextCtrl, AutoMixin):
default = ""
def __init__(self, parent, instance, member, fixed_instance=False, observers=[], *args, **kwargs):
wx.TextCtrl.__init__(self, parent.GetWindow(), -1, *args, **kwargs)
AutoMixin.__init__(self, parent, instance, member, fixed_instance, observers)
def __del__(self):
AutoMixin.__del__(self)
class AutoComboBox(wx.ComboBox, AutoMixin):
def __init__(self, parent, instance, member, fixed_instance=False, observers=[], *args, **kwargs):
wx.ComboBox.__init__(self, parent.GetWindow(), -1, *args, **kwargs)
AutoMixin.__init__(self, parent, instance, member, fixed_instance, observers)
def __del__(self):
AutoMixin.__del__(self)
class AutoDateCtrl(DateCtrl, AutoMixin):
default = None
def __init__(self, parent, instance, member, fixed_instance=False, observers=[], *args, **kwargs):
DateCtrl.__init__(self, parent.GetWindow(), id=-1,
style=wx.DP_DEFAULT | wx.DP_DROPDOWN | wx.DP_SHOWCENTURY | wx.DP_ALLOWNONE, *args, **kwargs)
AutoMixin.__init__(self, parent, instance, member, fixed_instance, observers)
# self.Bind(wx.EVT_DATE_CHANGED, self.onText, self)
# DateCtrl.__init__(self, parent, -1, *args, **kwargs)
# AutoMixin.__init__(self, parent, instance, member)
def __del__(self):
AutoMixin.__del__(self)
class AutoTimeCtrl(TimeCtrl, AutoMixin):
def __init__(self, parent, instance, member, fixed_instance=False, observers=[], *args, **kwargs):
TimeCtrl.__init__(self, parent)
AutoMixin.__init__(self, parent, instance, member, fixed_instance, observers)
self.SetMin("05:00")
def __del__(self):
AutoMixin.__del__(self)
def SetValue(self, value):
if isinstance(value, float):
wx.lib.masked.TimeCtrl.SetValue(self, "%02d:%02d" % (int(value), round((value - int(value)) * 60)))
else:
wx.lib.masked.TimeCtrl.SetValue(self, value)
def onText(self, event):
value = self.GetValue()
try:
self.AutoChange(float(value[:2]) + float(value[3:5]) / 60)
except:
pass
event.Skip()
class AutoNumericCtrl(NumericCtrl, AutoMixin):
default = ""
def __init__(self, parent, instance, member, fixed_instance=False, observers=[], *args, **kwargs):
NumericCtrl.__init__(self, parent.GetWindow(), *args, **kwargs)
AutoMixin.__init__(self, parent, instance, member, fixed_instance, observers)
def __del__(self):
AutoMixin.__del__(self)
class AutoPhoneCtrl(PhoneCtrl, AutoMixin):
default = ""
def __init__(self, parent, instance, member, fixed_instance=False, observers=[], *args, **kwargs):
PhoneCtrl.__init__(self, parent, -1, *args, **kwargs)
AutoMixin.__init__(self, parent, instance, member, fixed_instance, observers)
def __del__(self):
AutoMixin.__del__(self)
if sys.platform == "win32":
class ChoiceWithoutScroll(wx.Choice):
def onMouseWheel(self, event):
pass
def __init__(self, *args, **kwargs):
wx.Choice.__init__(self, *args, **kwargs)
self.Bind(wx.EVT_MOUSEWHEEL, self.onMouseWheel)
else:
ChoiceWithoutScroll = wx.Choice
class ChoiceCtrl(ChoiceWithoutScroll):
def __init__(self, parent, items=None):
ChoiceWithoutScroll.__init__(self, parent, -1)
if items:
self.SetItems(items)
def SetItems(self, items):
ChoiceWithoutScroll.Clear(self)
for item in items:
if isinstance(item, tuple):
self.Append(item[0], item[1])
else:
self.Append(item, item)
def GetValue(self):
selected = self.GetSelection()
return self.GetClientData(selected)
class AutoChoiceCtrl(ChoiceWithoutScroll, AutoMixin):
def __init__(self, parent, instance, member, items=None, fixed_instance=False, observers=[], mask=None, *args, **kwargs):
ChoiceWithoutScroll.__init__(self, parent, -1, *args, **kwargs)
self.values = {}
if items:
self.SetItems(items)
AutoMixin.__init__(self, parent, instance, member, fixed_instance, observers, mask)
parent.Bind(wx.EVT_CHOICE, self.onChoice, self)
def __del__(self):
AutoMixin.__del__(self)
def Append(self, item, clientData):
index = ChoiceWithoutScroll.Append(self, item, clientData)
self.values[clientData] = index
def onChoice(self, event):
self.AutoChange(event.GetClientData())
event.Skip()
def SetValue(self, value):
if self.GetCurrentValue() != value:
exec ('self.instance.%s = value' % self.member)
self.UpdateContents()
def UpdateContents(self):
if not self.instance:
self.Disable()
else:
value = self.GetCurrentValue()
if value in self.values:
self.SetSelection(self.values[value])
else:
self.SetSelection(-1)
self.Enable(not config.readonly)
def SetItems(self, items):
ChoiceWithoutScroll.Clear(self)
self.values.clear()
for item in items:
if isinstance(item, tuple):
self.Append(item[0] if item[0] else "", item[1])
else:
self.Append(item if item else "", item)
try:
self.UpdateContents()
except:
pass
class AutoCheckBox(wx.CheckBox, AutoMixin):
def __init__(self, parent, instance, member, label="", value=1, fixed_instance=False, observers=[], *args,
**kwargs):
wx.CheckBox.__init__(self, parent, -1, label, *args, **kwargs)
self.value = value
AutoMixin.__init__(self, parent, instance, member, fixed_instance, observers)
parent.Bind(wx.EVT_CHECKBOX, self.EvtCheckbox, self)
def __del__(self):
AutoMixin.__del__(self)
def EvtCheckbox(self, event):
previous_value = eval('self.instance.%s' % self.member)
if event.Checked():
self.AutoChange(previous_value | self.value)
else:
self.AutoChange(previous_value & ~self.value)
def SetValue(self, value):
wx.CheckBox.SetValue(self, value & self.value)
class AutoBinaryChoiceCtrl(ChoiceWithoutScroll, AutoMixin):
def __init__(self, parent, instance, member, items=None, fixed_instance=False, observers=[], *args, **kwargs):
ChoiceWithoutScroll.__init__(self, parent, -1, *args, **kwargs)
self.values = {}
if items:
self.SetItems(items)
AutoMixin.__init__(self, parent, instance, member, fixed_instance, observers)
parent.Bind(wx.EVT_CHOICE, self.onChoice, self)
def __del__(self):
AutoMixin.__del__(self)
def Append(self, item, clientData):
index = ChoiceWithoutScroll.Append(self, item, clientData)
self.values[clientData] = index
def onChoice(self, event):
previous_value = eval('self.instance.%s' % self.member)
value = event.GetClientData()
if value:
self.AutoChange(previous_value | self.value)
else:
self.AutoChange(previous_value & ~self.value)
event.Skip()
def SetValue(self, value):
self.UpdateContents()
def UpdateContents(self):
if not self.instance:
self.Disable()
else:
value = eval('self.instance.%s & self.value' % self.member)
if value in self.values:
self.SetSelection(self.values[value])
else:
self.SetSelection(-1)
self.Enable(not config.readonly)
def SetItems(self, items):
ChoiceWithoutScroll.Clear(self)
self.values.clear()
for item, clientData in items:
self.Append(item, clientData)
if clientData:
self.value = clientData
class AutoRadioBox(wx.RadioBox, AutoMixin):
def __init__(self, parent, instance, member, label, choices, fixed_instance=False, observers=[], *args, **kwargs):
wx.RadioBox.__init__(self, parent, -1, label=label, choices=choices, *args, **kwargs)
AutoMixin.__init__(self, parent, instance, member, fixed_instance, observers)
parent.Bind(wx.EVT_RADIOBOX, self.EvtRadiobox, self)
def __del__(self):
AutoMixin.__del__(self)
def EvtRadiobox(self, event):
self.AutoChange(event.GetInt())
def SetValue(self, value):
self.SetSelection(value)
class DatePickerCtrl(wx.DatePickerCtrl):
_GetValue = wx.DatePickerCtrl.GetValue
_SetValue = wx.DatePickerCtrl.SetValue
def GetValue(self):
if self._GetValue().IsValid():
return datetime.date(self._GetValue().GetYear(), self._GetValue().GetMonth() + 1, self._GetValue().GetDay())
else:
return None
def SetValue(self, dt):
if dt is None:
self._SetValue(wx.DateTime())
else:
self._SetValue(wx.DateTimeFromDMY(dt.day, dt.month - 1, dt.year))
class TextDialog(wx.Dialog):
def __init__(self, parent, titre, text):
wx.Dialog.__init__(self, parent, -1, titre, wx.DefaultPosition, wx.DefaultSize)
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.textctrl = wx.TextCtrl(self, -1, text, style=wx.TAB_TRAVERSAL | wx.TE_PROCESS_ENTER)
self.Bind(wx.EVT_TEXT_ENTER, self.OnEnter, self.textctrl)
self.sizer.Add(self.textctrl, 0, wx.EXPAND | wx.ALL, 5)
self.btnsizer = wx.StdDialogButtonSizer()
btn = wx.Button(self, wx.ID_OK)
self.btnsizer.AddButton(btn)
btn = wx.Button(self, wx.ID_CANCEL)
self.btnsizer.AddButton(btn)
self.btnsizer.Realize()
self.sizer.Add(self.btnsizer, 0, wx.ALL, 5)
self.SetSizer(self.sizer)
self.sizer.Fit(self)
def GetText(self):
return self.textctrl.GetValue()
def OnEnter(self, _):
self.EndModal(wx.ID_OK)
class PeriodeDialog(wx.Dialog):
def __init__(self, parent, periode):
wx.Dialog.__init__(self, parent, -1, "Modifier une période", wx.DefaultPosition, wx.DefaultSize)
self.periode = periode
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.fields_sizer = wx.FlexGridSizer(0, 2, 5, 10)
self.fields_sizer.AddGrowableCol(1, 1)
self.debut_ctrl = DateCtrl(self)
self.debut_ctrl.SetValue(periode.debut)
self.fields_sizer.AddMany(
[(wx.StaticText(self, -1, "Début :"), 0, wx.ALIGN_CENTRE_VERTICAL | wx.ALL - wx.BOTTOM, 5),
(self.debut_ctrl, 0, wx.EXPAND | wx.ALIGN_CENTRE_VERTICAL | wx.ALL - wx.BOTTOM, 5)])
self.fin_ctrl = DateCtrl(self)
self.fin_ctrl.SetValue(periode.fin)
self.fields_sizer.AddMany([(wx.StaticText(self, -1, "Fin :"), 0, wx.ALIGN_CENTRE_VERTICAL | wx.ALL, 5),
(self.fin_ctrl, 0, wx.EXPAND | wx.ALIGN_CENTRE_VERTICAL | wx.ALL, 5)])
self.sizer.Add(self.fields_sizer, 0, wx.EXPAND | wx.ALL, 5)
self.btnsizer = wx.StdDialogButtonSizer()
btn = wx.Button(self, wx.ID_OK)
self.btnsizer.AddButton(btn)
btn = wx.Button(self, wx.ID_CANCEL)
self.btnsizer.AddButton(btn)
self.btnsizer.Realize()
self.sizer.Add(self.btnsizer, 0, wx.ALL, 5)
self.SetSizer(self.sizer)
self.sizer.Fit(self)
if sys.platform == "darwin":
SIMPLE_BUTTONS_SIZE = (30, 30)
else:
SIMPLE_BUTTONS_SIZE = (-1, -1)
class PeriodeChoice(wx.BoxSizer):
def __init__(self, parent, constructor, default=None, onModify=None):
wx.BoxSizer.__init__(self, wx.HORIZONTAL)
self.parent = parent
self.constructor = constructor
self.onModify = onModify # TODO rather raise events
self.defaultPeriode = default
self.instance = None
self.readonly = False
self.periodechoice = wx.Choice(parent, size=(220, -1))
parent.Bind(wx.EVT_CHOICE, self.EvtPeriodeChoice, self.periodechoice)
delbmp = wx.Bitmap(GetBitmapFile("remove.png"), wx.BITMAP_TYPE_PNG)
plusbmp = wx.Bitmap(GetBitmapFile("plus.png"), wx.BITMAP_TYPE_PNG)
settingsbmp = wx.Bitmap(GetBitmapFile("settings.png"), wx.BITMAP_TYPE_PNG)
self.periodeaddbutton = wx.BitmapButton(parent, -1, plusbmp, size=SIMPLE_BUTTONS_SIZE)
self.periodeaddbutton.SetToolTipString("Ajouter une période")
self.periodedelbutton = wx.BitmapButton(parent, -1, delbmp, size=SIMPLE_BUTTONS_SIZE)
self.periodedelbutton.SetToolTipString("Supprimer la période")
self.periodesettingsbutton = wx.BitmapButton(parent, -1, settingsbmp, size=SIMPLE_BUTTONS_SIZE)
self.periodesettingsbutton.SetToolTipString("Modifier la période")
self.Add(self.periodechoice, 1, wx.EXPAND | wx.LEFT, 5)
self.Add(self.periodeaddbutton, 0, wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT, 5)
self.Add(self.periodedelbutton, 0, wx.ALIGN_CENTER_VERTICAL | wx.RIGHT, 5)
self.Add(self.periodesettingsbutton, 0, wx.ALIGN_CENTER_VERTICAL)
parent.Bind(wx.EVT_BUTTON, self.EvtPeriodeAddButton, self.periodeaddbutton)
parent.Bind(wx.EVT_BUTTON, self.EvtPeriodeDelButton, self.periodedelbutton)
parent.Bind(wx.EVT_BUTTON, self.EvtPeriodeSettingsButton, self.periodesettingsbutton)
parent.periodechoice = self
def SetInstance(self, instance, periode=None):
self.instance = instance
self.periode = periode
if instance is not None:
self.periodechoice.Clear()
for item in instance:
self.periodechoice.Append(GetPeriodeString(item))
self.Enable()
if periode is not None:
self.periodechoice.SetSelection(periode)
else:
self.Disable()
def EvtPeriodeChoice(self, evt):
ctrl = evt.GetEventObject()
self.periode = ctrl.GetSelection()
self.parent.SetPeriode(self.periode)
self.Enable()
def EvtPeriodeAddButton(self, _):
self.periode = len(self.instance)
new_periode = self.constructor(self.parent)
if len(self.instance) > 0:
last_periode = self.instance[-1]
new_periode.debut = last_periode.fin + datetime.timedelta(1)
if last_periode.debut.day == new_periode.debut.day and last_periode.debut.month == new_periode.debut.month:
new_periode.fin = datetime.date(
last_periode.fin.year + new_periode.debut.year - last_periode.debut.year, last_periode.fin.month,
last_periode.fin.day)
elif self.defaultPeriode:
new_periode.debut = datetime.date(self.defaultPeriode, 1, 1)
new_periode.fin = datetime.date(self.defaultPeriode, 12, 31)
self.instance.append(new_periode)
self.periodechoice.Append(GetPeriodeString(new_periode))
self.periodechoice.SetSelection(self.periode)
self.parent.SetPeriode(self.periode)
history.Append(Delete(self.instance, -1))
self.Enable()
def EvtPeriodeDelButton(self, evt):
dlg = wx.MessageDialog(self.parent,
"Cette période va être supprimée, confirmer ?",
"Confirmation",
wx.YES_NO | wx.NO_DEFAULT | wx.ICON_EXCLAMATION)
if dlg.ShowModal() == wx.ID_YES:
index = self.periodechoice.GetSelection()
periode = self.instance[index]
history.Append(Insert(self.instance, index, periode))
del self.instance[index]
self.periodechoice.Delete(index)
self.periode = len(self.instance) - 1
self.periodechoice.SetSelection(self.periode)
self.parent.SetPeriode(self.periode)
self.Enable()
def EvtPeriodeSettingsButton(self, _):
periode = self.instance[self.periode]
dlg = PeriodeDialog(self.parent, periode)
response = dlg.ShowModal()
dlg.Destroy()
if response == wx.ID_OK:
history.Append([Change(periode, "debut", periode.debut), Change(periode, "fin", periode.fin)])
periode.debut, periode.fin = dlg.debut_ctrl.GetValue(), dlg.fin_ctrl.GetValue()
if self.onModify:
self.onModify()
self.periodechoice.SetString(self.periode, GetPeriodeString(periode))
self.periodechoice.SetSelection(self.periode)
self.Enable()
def set_readonly(self, readonly):
self.readonly = readonly
def Enable(self, enable=True):
self.periodechoice.Enable(enable and len(self.instance) > 0)
self.periodesettingsbutton.Enable(enable and len(self.instance) > 0 and not config.readonly and not self.readonly)
self.periodeaddbutton.Enable(enable and self.instance is not None and (len(self.instance) == 0 or self.instance[-1].fin is not None) and not config.readonly and not self.readonly)
self.periodedelbutton.Enable(enable and self.instance is not None and len(self.instance) > 0 and not config.readonly and not self.readonly)
def Disable(self):
self.Enable(False)
class ControlsGroup(object):
def __init__(self, parent):
self.ctrls = []
self.parent = parent
self.window = None
def UpdateContents(self):
for ctrl in self.ctrls:
ctrl.UpdateContents()
def GetWindow(self):
return self.parent
class AutoTab(wx.lib.scrolledpanel.ScrolledPanel, ControlsGroup):
def __init__(self, parent):
ControlsGroup.__init__(self, parent)
wx.lib.scrolledpanel.ScrolledPanel.__init__(self, parent)
self.window = self
self.SetAutoLayout(1)
self.SetupScrolling()
def GetWindow(self):
return self
class PeriodeMixin(object):
def __init__(self, member):
self.instance = None
self.member = member
self.periode = None
self.current_periode = None
self.ctrls = []
self.periodechoice = None
def UpdateContents(self):
for ctrl in self.ctrls:
ctrl.UpdateContents()
def SetInstance(self, instance, periode=None):
self.instance = instance
self.periode = periode
if instance:
periodes = eval("instance.%s" % self.member)
if len(periodes) > 0:
if periode is None:
self.periode = len(periodes) - 1
if self.periodechoice:
self.periodechoice.SetInstance(periodes, self.periode)
self.current_periode = periodes[self.periode]
else:
self.current_periode = None
if self.periodechoice:
self.periodechoice.SetInstance(periodes)
for ctrl in self.ctrls:
ctrl.SetInstance(self.current_periode)
else:
self.current_periode = None
if self.periodechoice:
self.periodechoice.SetInstance(None)
for ctrl in self.ctrls:
ctrl.SetInstance(None)
def SetPeriode(self, periode):
self.SetInstance(self.instance, periode)
class PeriodePanel(wx.Panel, PeriodeMixin):
def __init__(self, parent, member, *args, **kwargs):
wx.Panel.__init__(self, parent, -1, *args, **kwargs)
PeriodeMixin.__init__(self, member)
parent.ctrls.append(self)
def GetWindow(self):
return self
class HashComboBox(wx.combo.OwnerDrawnComboBox):
def __init__(self, parent, id=-1):
wx.combo.OwnerDrawnComboBox.__init__(self, parent, id, style=wx.CB_READONLY, size=(150, -1))
def OnDrawItem(self, dc, rect, item, flags):
if item == wx.NOT_FOUND:
return
rr = wx.Rect(*rect) # make a copy
rr.Deflate(3, 5)
data = self.GetClientData(item)
if isinstance(data, tuple):
r, g, b, t, s = data
else:
r, g, b, t, s = data.couleur
dc = wx.GCDC(dc)
dc.SetPen(wx.Pen(wx.Colour(r, g, b)))
dc.SetBrush(wx.Brush(wx.Colour(r, g, b, t), s))
dc.DrawRoundedRectangleRect(wx.Rect(rr.x, rr.y - 3, rr.width, rr.height + 6), 3)
if flags & wx.combo.ODCB_PAINTING_CONTROL:
rr.y -= 2
dc.DrawText(self.GetString(item), rr.x + 10, rr.y - 1)
def OnMeasureItem(self, item):
return 24
def OnDrawBackground(self, dc, rect, item, flags):
if flags & wx.combo.ODCB_PAINTING_SELECTED:
bgCol = wx.Colour(160, 160, 160)
dc.SetBrush(wx.Brush(bgCol))
dc.SetPen(wx.Pen(bgCol))
dc.DrawRectangleRect(rect);
class ActivityComboBox(HashComboBox):
def __init__(self, parent, id=-1):
HashComboBox.__init__(self, parent, id)
self.Bind(wx.EVT_COMBOBOX, self.onChangeActivity, self)
self.activity = None
def SetSelection(self, item):
wx.combo.OwnerDrawnComboBox.SetSelection(self, item)
self.activity = self.GetClientData(item)
def onChangeActivity(self, evt):
self.activity = self.GetClientData(self.GetSelection())
evt.Skip()
def add_activity(self, activity):
self.Append(activity.label if activity.label else "", activity)
def Update(self):
selected = 0
self.Clear()
self.add_activity(database.creche.states[0])
if database.creche.has_activites_avec_horaires():
self.Show(True)
for activity in database.creche.activites:
if activity.has_horaires():
if self.activity == activity:
selected = self.GetCount()
self.add_activity(activity)
else:
self.Show(False)
self.SetSelection(selected)
def GetPictoBitmap(index, size=64):
if isinstance(index, int):
index = chr(ord('a') + index)
bitmap = wx.Bitmap(GetBitmapFile("pictos/%s.png" % index), wx.BITMAP_TYPE_PNG)
image = wx.ImageFromBitmap(bitmap)
image = image.Scale(size, size, wx.IMAGE_QUALITY_HIGH)
return wx.BitmapFromImage(image)
class CombinaisonDialog(wx.Dialog):
def __init__(self, parent):
wx.Dialog.__init__(self, parent, -1, "Nouvelle combinaison", wx.DefaultPosition, wx.DefaultSize)
self.sizer = wx.BoxSizer(wx.VERTICAL)
gridSizer = wx.FlexGridSizer(5, 4, 5, 5)
self.combinaison = []
for i in range(20):
picto = wx.BitmapButton(self, -1, GetPictoBitmap(i), style=wx.BU_EXACTFIT)
picto.picto = chr(ord('a') + i)
self.Bind(wx.EVT_BUTTON, self.OnPressPicto, picto)
gridSizer.Add(picto)
self.sizer.Add(gridSizer, 0, wx.EXPAND | wx.ALL, 5)
self.combinaisonPanel = wx.Panel(self, style=wx.SUNKEN_BORDER)
self.combinaisonPanel.SetMinSize((-1, 36))
self.combinaisonSizer = wx.BoxSizer(wx.HORIZONTAL)
self.combinaisonPanel.SetSizer(self.combinaisonSizer)
self.sizer.Add(self.combinaisonPanel, 0, wx.EXPAND)
btnsizer = wx.StdDialogButtonSizer()
btn = wx.Button(self, wx.ID_OK)
btnsizer.AddButton(btn)
btn = wx.Button(self, wx.ID_CANCEL)
btnsizer.AddButton(btn)
btnsizer.Realize()
self.sizer.Add(btnsizer, 0, wx.ALL, 5)
self.SetSizer(self.sizer)
self.sizer.Fit(self)
def OnPressPicto(self, event):
sender = event.GetEventObject()
picto = sender.picto
self.combinaison.append(picto)
bmp = GetPictoBitmap(picto, size=32)
button = wx.StaticBitmap(self.combinaisonPanel, -1, bmp)
self.combinaisonSizer.Add(button, 0, wx.LEFT, 5)
self.combinaisonSizer.Layout()
def GetCombinaison(self):
return "".join(self.combinaison)
class TabletteSizer(wx.StaticBoxSizer):
def __init__(self, parent, object):
wx.StaticBoxSizer.__init__(self, wx.StaticBox(parent, -1, u'Tablette'), wx.VERTICAL)
self.parent = parent
self.object = object
internalSizer = wx.BoxSizer(wx.HORIZONTAL)
self.combinaisonSizer = wx.BoxSizer(wx.HORIZONTAL)
internalSizer.Add(self.combinaisonSizer)
settingsbmp = wx.Bitmap(GetBitmapFile("settings.png"), wx.BITMAP_TYPE_PNG)
self.button = wx.BitmapButton(parent, -1, settingsbmp)
self.button.Enable(not config.readonly)
parent.Bind(wx.EVT_BUTTON, self.OnModifyCombinaison, self.button)
internalSizer.Add(self.button, 0, wx.LEFT, 10)
self.Add(internalSizer, 0, wx.TOP | wx.BOTTOM, 10)
def OnModifyCombinaison(self, _):
dlg = CombinaisonDialog(self.parent)
res = dlg.ShowModal()
if res == wx.ID_OK:
self.object.combinaison = dlg.GetCombinaison()
self.UpdateCombinaison()
history.Append(None)
dlg.Destroy()
def UpdateCombinaison(self):
self.combinaisonSizer.DeleteWindows()
if self.object:
self.button.Enable(not config.readonly)
if self.object.combinaison:
for letter in self.object.combinaison:
bitmap = GetPictoBitmap(letter, size=32)
picto = wx.StaticBitmap(self.parent, -1, bitmap)
self.combinaisonSizer.Add(picto, 0, wx.LEFT, 10)
else:
self.button.Disable()
self.combinaisonSizer.Layout()
self.parent.sizer.Layout()
def SetObject(self, object):
self.object = object
if sys.platform == "darwin":
MACOS_MARGIN = 1
else:
MACOS_MARGIN = 0
|
The University of South Dakota football team had a tough task under first-year coach Joe Glenn, opening their season on the road versus the University of Montana. A strong start to the second half made things interesting but the Coyotes couldn’t get the win, as they lost 35-24.
The Coyotes offense got off to a sluggish start, having to punt in the team’s first four possessions, and was held scoreless after the first quarter. First year starting quarterback, sophomore Josh Vander Maten, was often off target on his pass attempts until he rolled to his right and connected on a short touchdown pass late in the second quarter.
Coach Glenn and his team came out amped to start the second half, as they scored 14 unanswered points. Leading 26-14, the Coyotes were looking strong. Unfortunately, the defense was unable to hold the lead, and gave up 19 unanswered points to Montana.
The Coyotes will look to clean up their mistakes for their first home game next Saturday versus Colgate at 2 p.m. in the DakotaDome.
|
# !/bin/bash
"""This script concatenates two (or more) matrices along a specified axis
"""
import argparse
from LmBackend.common.lmobj import LMObject
from lmpy import Matrix
# .............................................................................
def main():
"""Main method of the script
"""
# Set up the argument parser
parser = argparse.ArgumentParser(
description='Concatenate two (or more) matrices along an axis')
parser.add_argument(
'out_fn', type=str,
help='The file location to write the resulting matrix')
parser.add_argument(
'axis', type=int,
help='The (Matrix) axis to concatenate these matrices on')
parser.add_argument(
'mtx_fn', type=str, nargs='*',
help="The file location of the first matrix")
args = parser.parse_args()
mtxs = []
if args.mtx_fn:
for mtx_fn in args.mtx_fn:
mtxs.append(Matrix.load(mtx_fn))
joined_mtx = Matrix.concatenate(mtxs, axis=args.axis)
# Make sure directory exists
LMObject().ready_filename(args.out_fn)
joined_mtx.write(args.out_fn)
# .............................................................................
if __name__ == "__main__":
main()
|
The Municipality of Veendam, Holland, has recently installed a statue by the artist Rob Oost in the center of the new roundabout built at the entrance to the city, after the works aimed at improve and maintain the road network.
The statue – christened Lloydsplein Veendam – set within a large water pool – is lit at night by DTS’ DIVE 6 FC underwater LED projectors.
Fonteintechniek Gruppen from Hoogeveen was entrusted with the installation of water technology and LED lighting. As regular users of DTS products, they asked Full AVL Distribution to issue an advice on how to make the statue stand out since dusk.
The solution was to install a network of DIVE 6, full-color IP68-rated LED fixtures, remotely powered by a DRIVENET 1664 24Vdc LED controller.
10 DIVE units (40° lenses) have been encased round the statue base, and 4 more units (10° lenses) in the center. The DRIVENET was set in a technical room situated in a basement under the waterline.
The result of the lighting installation was even better than anticipated: the eye-catching Lloydsplein Veendam, graced by the color projections of the DIVEs, turned a traffic hub into an unexpected art setting.
The artwork by Rob Oost consists of two columns of corten steel – symbolizing Ooster and Westerdiep (two Dutch water management regions) that embrace a spiral of stainless steel from which water falls.
|
#!/usr/bin/env python3
import aloobj
import argparse
import collections
import json
import pprint
import struct
import sys
def load_format(file):
return {int(k): v for k,v in json.load(file).items()}
def parse_chunked(format, buf):
chunk_data = collections.defaultdict(list)
while buf:
chunk_id, size = unpack('<Ii', buf)
sub_chunks = size < 0
# Clear the sign bit (used to indicate if a chunk contains sub-chunks)
size &= 0x7fffffff
chunk_type = format.get(chunk_id)
if chunk_type:
if sub_chunks:
chunk_data[chunk_type['name']].append(parse_chunked(format, buf[:size]))
else:
chunk_data[chunk_type['name']].append(parse_chunk(
chunk_type, buf[:size], chunk_data))
del buf[:size]
return chunk_data
def unpack(format, buf):
"""Both unpack and delete. Convert single-element tuples to their element"""
result = struct.unpack_from(format, buf)
if len(result) == 1:
result = result[0]
del buf[:struct.calcsize(format)]
return result
def unpack_asciiz(buf):
l = buf.find(b'\x00')
if l < 0:
# should not happen (famous last words), but if it does, interpret the whole
# bytearray as a string and delete all of its contents (by setting the end
# character to past the end
l = len(buf)
result = buf[:l].decode(encoding='ascii')
del buf[:l+1]
return result
def parse_chunk(format, buf, parent):
result = {}
content = format['content']
for c in content:
name = c.get('name')
t = c['type']
if c.get('head'):
del buf[:2]
if name is None:
del buf[:struct.calcsize(t)]
continue
ct = c.get('count')
if isinstance(ct, dict):
# always take the first element of the given chunk type.
ct = parent[ct['chunk_name']][0][ct['property']] * ct.get('scale', 1)
if ct is None:
if t == 'asciiz':
result[name] = unpack_asciiz(buf)
elif t == 'struct':
result[name] = parse_chunk(c, buf, parent)
else:
result[name] = unpack(t, buf)
elif ct == 'max':
result[name] = []
while buf:
if t == 'asciiz':
result[name].append(unpack_asciiz(buf))
elif t == 'struct':
result[name].append(parse_chunk(c, buf, parent))
else:
result[name].append(unpack(t, buf))
else:
result[name] = []
for _ in range(ct):
if t == 'asciiz':
result[name].append(unpack_asciiz(buff))
elif t == 'struct':
result[name].append(parse_chunk(c, buf, parent))
else:
result[name].append(unpack(t, buf))
return result
def main(args):
with args.json_file as json_file, args.chunked_file as chunked_file,\
args.output_file as output_file:
format = load_format(json_file)
buf = bytearray(chunked_file.read())
parse_result = parse_chunked(format, buf)
if args.output_format == 'dict':
print(parse_result, file=args.output_file)
elif args.output_format == 'json':
json.dump(parse_result, output_file)
print(file=args.output_file)
elif args.output_format == 'obj':
aloobj.dump(parse_result, output_file)
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='Load chunked files based on a json descripton')
parser.add_argument(
'json_file', type=argparse.FileType('r'),
help='The json file which describes the chunked format to be used')
parser.add_argument(
'chunked_file', type=argparse.FileType('rb'),
help='The chunked file to be read using the specified format')
parser.add_argument(
'--output-format', '-f', type=str, choices=('dict', 'json', 'obj'),
default='dict', help='The output format of the resulting data')
parser.add_argument(
'--output-file', '-o', type=argparse.FileType('w'), default=sys.stdout,
help='where to store the output of the operation (default: stdout)')
main(parser.parse_args())
|
01-13-2019 , 14:55 Re: Development Roundup, We need you!
what i really miss are a complex voting/mapvoting like deagle's map manager and an afk managing stuff. and banning should be like amxbans.
If that's what you like then use those plugins instead of the default functionality. That is why the ability to make your own custom plugins exist. The core shouldn't have all these features because it will be impossible to design it to satisfy everybody.
3rd party plugins are pretty outdated sadly.
Why would you make that generalization? Many of them still work just fine. If you have a specific issue with a plugin you can request that it get fixed. The community for 20 year old games is much smaller than it used to be so there is naturally going to be a slow down in development of things for the game(s).
Last edited by fysiks; 01-13-2019 at 14:57.
01-24-2019 , 07:52 Re: Development Roundup, We need you!
02-15-2019 , 15:34 Re: Development Roundup, We need you!
Is custom entity data module going to be integrated in main amxx package?
Last edited by CrazY.; 02-15-2019 at 15:36.
02-25-2019 , 12:04 Re: Development Roundup, We need you!
Hey, I was looking around the example codes from the 1.9 API changes page and some of the default plugins, and I noticed some peculiar coding style which made me wonder.
As far as I understand, callbacks from within the plugin now use the short '@' symbol (which actually becomes part of their name), while forwards registered from includes use the full 'public' keyword. I assume that improves code readability, but can you shed some more light on this? Do you encourage it as a new standard coding practice?
Last edited by <VeCo>; 02-25-2019 at 15:20.
02-25-2019 , 23:03 Re: Development Roundup, We need you!
⋄ start the variable name with the “@” symbol.
The only difference being that the '@' become part of the name (as you noticed).
Since they are functionally the same, someone could choose to use the difference to convey certain context as you explained already. Very few plugins (2 of 21) actually use this method so it certainly can't be called a new standard practice for AMX Mod X. IMO, someone noticed that it worked and figured that they wanted to be different.
Last edited by fysiks; 02-25-2019 at 23:07.
03-15-2019 , 21:14 Re: Development Roundup, We need you!
Nice write up. Implementing @ forthwith.
22/09/1998 Functions whose name start with an '@' are always public.
Yesterday , 03:54 Re: Development Roundup, We need you!
The upcoming update looks to be gamedata breaking. The beta clients already support the new "Account" message, suggesting the update could be released soon. How long would it take to update gamedata?
Yesterday , 05:17 Re: Development Roundup, We need you!
I'm following more or less the changes on /ValveSoftware/halflife but it looks like I missed the "Account" thing, could you elaborate/link on it?
Yesterday , 06:03 Re: Development Roundup, We need you!
Under the beta client, your money and your teammates money is displayed in the scoreboard.
ARG 2: LONG (Amount of Money).
|
# Copyright 2012 Knowledge Economy Developments Ltd
#
# Henry Gomersall
# heng@kedevelopments.co.uk
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from distutils.core import setup, Command
from distutils.extension import Extension
from distutils.util import get_platform
from distutils.ccompiler import get_default_compiler
import os
import numpy
import sys
# Get the version string in rather a roundabout way.
# We can't import it directly as the module may not yet be
# built in pyfftw.
import imp
ver_file, ver_pathname, ver_description = imp.find_module(
'_version', ['pyfftw'])
try:
_version = imp.load_module('version', ver_file, ver_pathname,
ver_description)
finally:
ver_file.close()
version = _version.version
try:
from Cython.Distutils import build_ext as build_ext
sources = [os.path.join(os.getcwd(), 'pyfftw', 'pyfftw.pyx')]
except ImportError as e:
sources = [os.path.join(os.getcwd(), 'pyfftw', 'pyfftw.c')]
if not os.path.exists(sources[0]):
raise ImportError(str(e) + '. ' +
'Cython is required to build the initial .c file.')
# We can't cythonize, but that's ok as it's been done already.
from distutils.command.build_ext import build_ext
include_dirs = [os.path.join(os.getcwd(), 'include'),
os.path.join(os.getcwd(), 'pyfftw'),
numpy.get_include()]
library_dirs = []
package_data = {}
if get_platform() in ('win32', 'win-amd64'):
libraries = ['libfftw3-3', 'libfftw3f-3', 'libfftw3l-3']
include_dirs.append(os.path.join(os.getcwd(), 'include', 'win'))
library_dirs.append(os.path.join(os.getcwd(), 'pyfftw'))
package_data['pyfftw'] = [
'libfftw3-3.dll', 'libfftw3l-3.dll', 'libfftw3f-3.dll']
else:
libraries = ['fftw3', 'fftw3f', 'fftw3l', 'fftw3_threads',
'fftw3f_threads', 'fftw3l_threads']
class custom_build_ext(build_ext):
def finalize_options(self):
build_ext.finalize_options(self)
if self.compiler is None:
compiler = get_default_compiler()
else:
compiler = self.compiler
if compiler == 'msvc':
# Add msvc specific hacks
if (sys.version_info.major, sys.version_info.minor) < (3, 3):
# The check above is a nasty hack. We're using the python
# version as a proxy for the MSVC version. 2008 doesn't
# have stdint.h, so is needed. 2010 does.
#
# We need to add the path to msvc includes
include_dirs.append(os.path.join(os.getcwd(),
'include', 'msvc_2008'))
# We need to prepend lib to all the library names
_libraries = []
for each_lib in self.libraries:
_libraries.append('lib' + each_lib)
self.libraries = _libraries
ext_modules = [Extension('pyfftw.pyfftw',
sources=sources,
libraries=libraries,
library_dirs=library_dirs,
include_dirs=include_dirs)]
long_description = '''
pyFFTW is a pythonic wrapper around `FFTW <http://www.fftw.org/>`_, the
speedy FFT library. The ultimate aim is to present a unified interface for all
the possible transforms that FFTW can perform.
Both the complex DFT and the real DFT are supported, as well as arbitrary
axes of abitrary shaped and strided arrays, which makes it almost
feature equivalent to standard and real FFT functions of ``numpy.fft``
(indeed, it supports the ``clongdouble`` dtype which ``numpy.fft`` does not).
Operating FFTW in multithreaded mode is supported.
A comprehensive unittest suite can be found with the source on the github
repository.
To build for windows from source, download the fftw dlls for your system
and the header file from here (they're in a zip file):
http://www.fftw.org/install/windows.html and place them in the pyfftw
directory. The files are libfftw3-3.dll, libfftw3l-3.dll, libfftw3f-3.dll
and libfftw3.h.
Under linux, to build from source, the FFTW library must be installed already.
This should probably work for OSX, though I've not tried it.
Numpy is a dependency for both.
The documentation can be found
`here <http://hgomersall.github.com/pyFFTW/>`_, and the source
is on `github <https://github.com/hgomersall/pyFFTW>`_.
'''
class TestCommand(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
import sys, subprocess
errno = subprocess.call([sys.executable, '-m',
'unittest', 'discover'])
raise SystemExit(errno)
setup_args = {
'name': 'pyFFTW',
'version': version,
'author': 'Henry Gomersall',
'author_email': 'heng@kedevelopments.co.uk',
'description': 'A pythonic wrapper around FFTW, the FFT library, presenting a unified interface for all the supported transforms.',
'url': 'http://hgomersall.github.com/pyFFTW/',
'long_description': long_description,
'classifiers': [
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Development Status :: 4 - Beta',
'License :: OSI Approved :: GNU General Public License (GPL)',
'Operating System :: OS Independent',
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'Topic :: Scientific/Engineering',
'Topic :: Scientific/Engineering :: Mathematics',
'Topic :: Multimedia :: Sound/Audio :: Analysis',
],
'packages':['pyfftw', 'pyfftw.builders', 'pyfftw.interfaces'],
'ext_modules': ext_modules,
'include_dirs': include_dirs,
'package_data': package_data,
'cmdclass': {'test': TestCommand,
'build_ext': custom_build_ext},
}
if __name__ == '__main__':
setup(**setup_args)
|
Know DCHS Class of 2017 graduates that are NOT on this List? Help us Update the 2017 Class List by adding missing names.
More 2017 alumni from Divine Child HS have posted profiles on Classmates.com®. Click here to register for free at Classmates.com® and view other 2017 alumni.
If you are trying to find people that graduated in '17 at Divine Child HS in Dearborn, MI, check the alumni list below that shows the class of 2017.
If you are a Divine Child alumn, we encourage you to register and be sure to sign up for the alumni newsletter.
|
#this document contains the specific parameters for the generative model
#alter this prior to running code [genmod.py]
print "IMPORTING PARAMETERS"
useTerms = True
useSubs = True
name = 'apoptosis'
#this weights the terms more than the subreddits; this does nothing if subs is turned
#off
termMultiplier = 0.4#
#lambda terms are factors for the smoothing terms
#essentially, the higher they are, the greater the shrinkage
lambdaTerm = 2
lambdaSub = 1
#these are pre-defined groups
#replace this with None if unsupervised learning is used
clusterClasses = ['GG','SJW','O']
#these will make sure unlabeled classes are properly defined as so when
#reading in manually labeled data
nullClasses = ['NA','?']
#this is important for unsupervised learning
nclasses = 3
k=nclasses#just for quick reference
#if greater than 1, n-fold cross-validation is used to determine accuracy of algorithm
#with already-sorted data...this will make the algorithm run nfolds times longer
nfolds = 5
#defines number of iterations for convergence
niter = 9
#this defines the initial weight for labeled terms and subreddits
#true_weight = (2 + sample_size*weight*
#exp(-iter*decayRate)/training_size)/(2*sample_size)
#use decay = 0 to keep the terms fixed
#use weight = 0 to not use any weighting for labeled data
weightInitialTerm = 100
weightInitialSub = 100
decayTerm = 3.
decaySub = 3.
#sets lower bound for what the weight can decay to
weightMinTerm = 2.0/1
weightMinSub = 2.0/1
supervised_mode = False
#this can be used to define priors for clusters. If unchecked, then they will be
#calculated each loop
#it can also be adjusted to the initial value from the training set ("train")
clusterPriors = [0.05,0.01,0.94]
#this will smooth the priors slightly based on one's confidence in the training
#higher values are preferred
priorConfidence = 0.8
#use manually defined weights for each node
useManualWeights=False
#used for backwards parameter selection
paramSelection = True
paramIter = 2
paramFactor = 10
#used to pre-ignore certain variables manually; use this when results are counterintuitive for certain variables
ignoreSubs = []
ignoreTerms = []#[275,285,292]
#used for large subreddits that are frequent enough to warrant utilizing
forceSubs = []
forceTerms = []
#used to determine if fold results should be written
writefolds = True
|
Flash Professional CS5 will allow developers to build applications for Apple's iPhone. The forthcoming release of Adobe's multimedia authoring tool was unveiled Monday at the Adobe MAX 2009 conference, underway in Los Angeles this week.
With Flash Professional CS5, Flash developers will be able to build new applications for the iPhone or repurpose applications that had previously been built for the Web using ActionScript 3. The process simply involves exporting the project from Flash Pro to a native iPhone format (.ipa). There is no JIT or runtime interpretation for the finished application.
A preview version of Flash CS5 is expected to be available later this year. As of this writing, the final ship date and final pricing have not been announced.
Further information about Flash CS5 and its iPhone authoring capabilities, including a video demonstration, can be found on at the Adobe Labs site here.
|
# (c) 2013, Jan-Piet Mens <jpmens(at)gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
try:
import json
except ImportError:
import simplejson as json
from ansible.plugins.lookup import LookupBase
from ansible.module_utils.urls import open_url
# this can be made configurable, not should not use ansible.cfg
ANSIBLE_ETCD_URL = 'http://127.0.0.1:4001'
if os.getenv('ANSIBLE_ETCD_URL') is not None:
ANSIBLE_ETCD_URL = os.environ['ANSIBLE_ETCD_URL']
class Etcd:
def __init__(self, url=ANSIBLE_ETCD_URL, validate_certs=True):
self.url = url
self.baseurl = '%s/v1/keys' % (self.url)
self.validate_certs = validate_certs
def get(self, key):
url = "%s/%s" % (self.baseurl, key)
data = None
value = ""
try:
r = open_url(url, validate_certs=self.validate_certs)
data = r.read()
except:
return value
try:
# {"action":"get","key":"/name","value":"Jane Jolie","index":5}
item = json.loads(data)
if 'value' in item:
value = item['value']
if 'errorCode' in item:
value = "ENOENT"
except:
raise
pass
return value
class LookupModule(LookupBase):
def run(self, terms, variables, **kwargs):
if isinstance(terms, basestring):
terms = [ terms ]
validate_certs = kwargs.get('validate_certs', True)
etcd = Etcd(validate_certs=validate_certs)
ret = []
for term in terms:
key = term.split()[0]
value = etcd.get(key)
ret.append(value)
return ret
|
This document describes two methods for producing an integrity check value from a Diffie-Hellman key pair and one method for producing an integrity check value from an Elliptic Curve key pair. This behavior is needed for such operations as creating the signature of a Public-Key Cryptography Standards (PKCS) #10 Certification Request. These algorithms are designed to provide a Proof-of-Possession of the private key and not to be a general purpose signing algorithm.
|
from django.shortcuts import render_to_response, render, get_object_or_404
from django.template import RequestContext, loader
from django.http import HttpResponse, HttpResponseRedirect
from django.http import Http404
from django.core.urlresolvers import reverse
from helping_hands_app.forms import *
from django.contrib.auth.decorators import login_required
from django.contrib.auth import logout
from django.views.decorators.csrf import csrf_protect
from helping_hands_app.models import Event, Choice
register = None
def index(request):
latest_event_list = Event.objects.all().order_by('-pub_date')[:5]
context = {'latest_event_list': latest_event_list}
return render(request, 'helping_hands_app/index.html', context)
def detail(request, event_id):
event = get_object_or_404(Event, pk=event_id)
return render(request, 'helping_hands_app/detail.html', {'event': event})
def results(request, event_id):
event = get_object_or_404(Event, pk=event_id)
return render(request, 'helping_hands_app/results.html', {'event': event})
def vote(request, event_id):
e = get_object_or_404(Event, pk=event_id)
try:
selected_choice = e.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
# Redisplay the event voting form.
return render(request, 'events/detail.html', {
'event': e,
'error_message': "You didn't select a choice.",
})
else:
selected_choice.votes += 1
selected_choice.save()
# Always return an HttpResponseRedirect after successfully dealing
# with POST data. This prevents data from being posted twice if a
# user hits the Back button.
return HttpResponseRedirect(reverse('events:results', args=(e.id,)))
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
user = User.objects.create_user(
username=form.cleaned_data['username'],
password=form.cleaned_data['password1'],
email=form.cleaned_data['email']
)
return HttpResponseRedirect('/register/success/')
else:
form = RegistrationForm()
variables = RequestContext(request, {
'form': form
})
return render_to_response(
'registration/register.html',
variables,
)
def register_success(request):
return render_to_response(
'registration/success.html',
)
def logout_page(request):
logout(request)
return HttpResponseRedirect('/')
@login_required
def home(request):
return render_to_response(
'home.html',
{ 'user': request.user }
)
|
The Y's Poetry Night, organized by Barbara Helfogtt-Hyett, of Poemworks.com, begins with readings by two published poets. Guests are then invited to participate in the open mic portion of the evening and share their own work. Free and open to the public!
|
"""
This file is part of GASATaD.
GASATaD is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
GASATaD is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with GASATaD. If not, see <http://www.gnu.org/licenses/>.
"""
import os
import sys
from sys import platform
import numpy
import wx
import wx.adv
import wx.grid
from pandas import to_numeric
from pandas.io.excel import read_excel
from pandas.io.parsers import read_csv
from AddColumnInterface import AddColumnInterface
from AskFileType import AskFileType
from BasicStatisticsInterface import BasicStatisticsInterface
from Controller import Controller
from GraphsInterface import HistogramInterface, ScatterPlotInterface, \
PieChartInterface, BoxPlotInterface, BarChartInterface
from Model import OptionsInExportInterface
from OpenFileInterface import OpenCSVFile, OpenXLSFile
from SignificanceTestInterface import SignificanceTestInterface
###########################################################################
## Class MainFrame
###########################################################################
class MainFrame(wx.Frame):
tagsAndValues = {}
histogramOptions = {}
scatterPlotOptions = {}
boxPlotOptions = {}
pieChartOptions = {}
barChartOptions = {}
def __init__(self, parent):
bmp = wx.Image(str(os.path.dirname(__file__)) + "/icons/SplashScreen2.0.png").ConvertToBitmap()
splash = wx.adv.SplashScreen(bmp, wx.adv.SPLASH_CENTRE_ON_SCREEN | wx.adv.SPLASH_TIMEOUT, 3000, None,
style=wx.STAY_ON_TOP | wx.FRAME_NO_TASKBAR) # msec. of splash
wx.Yield()
self.configInit()
# print "Invoked from directory:",self.params['options']['dirfrom']
wx.Frame.__init__(self, parent, id=wx.ID_ANY, title="GASATaD")
if platform != "darwin":
# image = wx.Image('GasatadLogo.png', wx.BITMAP_TYPE_PNG).ConvertToBitmap()
# icon = wx.EmptyIcon()
# icon.CopyFromBitmap(image)
# self.SetIcon(icon)
# ib = wx.IconBundle()
# ib.AddIconFromFile("GasatadLogo.ico", wx.BITMAP_TYPE_ANY)
# self.SetIcons(ib)
icon = wx.Icon("GasatadLogo.ico", wx.BITMAP_TYPE_ICO)
self.SetIcon(icon)
self.CheckUpdates()
# self.SetSizeHintsSz( wx.DefaultSize, wx.DefaultSize )
# MENU BAR
self.m_menubar1 = wx.MenuBar(0)
# ------------ File menu
self.m_fileMenu = wx.Menu()
if sys.platform == "linux":
self.m_menuNewFile = wx.MenuItem(self.m_fileMenu, wx.ID_NEW, u"Open new file...", wx.EmptyString,
wx.ITEM_NORMAL)
self.m_menuAddFile = wx.MenuItem(self.m_fileMenu, wx.ID_OPEN, u"Add file...", wx.EmptyString,
wx.ITEM_NORMAL)
else:
self.m_menuNewFile = wx.MenuItem(self.m_fileMenu, wx.ID_NEW, u"Open new file...\tCtrl+N", wx.EmptyString,
wx.ITEM_NORMAL)
self.m_menuAddFile = wx.MenuItem(self.m_fileMenu, wx.ID_OPEN, u"Add file...\tCtrl+O", wx.EmptyString,
wx.ITEM_NORMAL)
self.m_fileMenu.Append(self.m_menuNewFile)
self.m_fileMenu.Append(self.m_menuAddFile)
self.m_menuAddFile.Enable(False)
self.m_fileMenu.AppendSeparator()
if sys.platform == "linux":
self.m_menuExportData = wx.MenuItem(self.m_fileMenu, wx.ID_SAVE, u"Save data...", wx.EmptyString,
wx.ITEM_NORMAL)
else:
self.m_menuExportData = wx.MenuItem(self.m_fileMenu, wx.ID_SAVE, u"Save data...\tCtrl+S", wx.EmptyString,
wx.ITEM_NORMAL)
self.m_fileMenu.Append(self.m_menuExportData)
self.m_menuExportData.Enable(False)
self.m_fileMenu.AppendSeparator()
if sys.platform == "linux":
self.m_menuResetData = wx.MenuItem(self.m_fileMenu, wx.ID_CLOSE, u"Close data", wx.EmptyString,
wx.ITEM_NORMAL)
self.m_menuQuit = wx.MenuItem(self.m_fileMenu, wx.ID_EXIT, u"Quit", wx.EmptyString, wx.ITEM_NORMAL)
else:
self.m_menuResetData = wx.MenuItem(self.m_fileMenu, wx.ID_CLOSE, u"Close data\tCtrl+W", wx.EmptyString,
wx.ITEM_NORMAL)
self.m_menuQuit = wx.MenuItem(self.m_fileMenu, wx.ID_EXIT, u"Quit\tCtrl+Q", wx.EmptyString, wx.ITEM_NORMAL)
self.m_fileMenu.Append(self.m_menuResetData)
self.m_menuResetData.Enable(False)
self.m_fileMenu.Append(self.m_menuQuit)
self.accel_tbl = wx.AcceleratorTable([
(wx.ACCEL_CTRL, ord('N'), self.m_menuNewFile.GetId()),
(wx.ACCEL_CTRL, ord('O'), self.m_menuAddFile.GetId()),
(wx.ACCEL_CTRL, ord('S'), self.m_menuExportData.GetId()),
(wx.ACCEL_CTRL, ord('W'), self.m_menuResetData.GetId()),
(wx.ACCEL_CTRL, ord('Q'), self.m_menuQuit.GetId())
])
# ------------ Edit menu
self.m_editMenu = wx.Menu()
self.m_undo = wx.MenuItem(self.m_fileMenu, wx.ID_UNDO, u"Undo", wx.EmptyString, wx.ITEM_NORMAL)
self.m_editMenu.Append(self.m_undo)
self.m_undo.Enable(False)
self.m_editMenu.AppendSeparator()
self.m_deletedSelectedCR = wx.MenuItem(self.m_fileMenu, wx.ID_ANY, u"Delete selected columns/rows",
wx.EmptyString, wx.ITEM_NORMAL)
self.m_editMenu.Append(self.m_deletedSelectedCR)
self.m_deletedSelectedCR.Enable(False)
self.m_editMenu.AppendSeparator()
self.m_renameSelectedCol = wx.MenuItem(self.m_fileMenu, wx.ID_ANY, u"Rename selected column", wx.EmptyString,
wx.ITEM_NORMAL)
self.m_editMenu.Append(self.m_renameSelectedCol)
self.m_renameSelectedCol.Enable(False)
self.m_moveSelectedCol = wx.MenuItem(self.m_fileMenu, wx.ID_ANY, u"Move selected column", wx.EmptyString,
wx.ITEM_NORMAL)
self.m_editMenu.Append(self.m_moveSelectedCol)
self.m_moveSelectedCol.Enable(False)
self.m_replaceInCol = wx.MenuItem(self.m_fileMenu, wx.ID_ANY, u"Replace in selected column...", wx.EmptyString,
wx.ITEM_NORMAL)
self.m_editMenu.Append(self.m_replaceInCol)
self.m_replaceInCol.Enable(False)
self.m_sortSubMenu = wx.Menu()
self.m_sortAscending = self.m_sortSubMenu.Append(wx.ID_ANY, "ascending")
self.m_sortDescending = self.m_sortSubMenu.Append(wx.ID_ANY, "descending")
self.sortMenuID = wx.NewId()
self.m_editMenu.Append(self.sortMenuID, "Sort using selected column", self.m_sortSubMenu)
self.m_editMenu.Enable(self.sortMenuID, False)
self.m_discretizeSelectedCol = wx.MenuItem(self.m_fileMenu, wx.ID_ANY, u"Convert selected column to text",
wx.EmptyString, wx.ITEM_NORMAL)
self.m_editMenu.Append(self.m_discretizeSelectedCol)
self.m_discretizeSelectedCol.Enable(False)
self.m_numerizeSelectedCol = wx.MenuItem(self.m_fileMenu, wx.ID_ANY, u"Convert selected column to numbers",
wx.EmptyString, wx.ITEM_NORMAL)
self.m_editMenu.Append(self.m_numerizeSelectedCol)
self.m_numerizeSelectedCol.Enable(False)
self.m_editMenu.AppendSeparator()
self.m_addNewColumn = wx.MenuItem(self.m_fileMenu, wx.ID_ANY, u"Add text column...", wx.EmptyString,
wx.ITEM_NORMAL)
self.m_editMenu.Append(self.m_addNewColumn)
self.m_addNewColumn.Enable(False)
self.m_deleteColumns = wx.MenuItem(self.m_fileMenu, wx.ID_ANY, u"Delete columns...", wx.EmptyString,
wx.ITEM_NORMAL)
self.m_editMenu.Append(self.m_deleteColumns)
self.m_deleteColumns.Enable(False)
# ------------ About menu
self.m_aboutMenu = wx.Menu()
if platform != "darwin":
self.m_menuAbout = wx.MenuItem(self.m_aboutMenu, wx.ID_ABOUT, u"About GASATaD", wx.EmptyString,
wx.ITEM_NORMAL)
else:
self.m_menuAbout = wx.MenuItem(self.m_aboutMenu, wx.ID_ANY, u"About GASATaD", wx.EmptyString,
wx.ITEM_NORMAL)
self.m_aboutMenu.Append(self.m_menuAbout)
self.m_menubar1.Append(self.m_fileMenu, u"File")
self.m_menubar1.Append(self.m_editMenu, u"Edit")
# self.m_menubar1.Append( self.m_optionsMenu, u"Options")
self.m_menubar1.Append(self.m_aboutMenu, u"About")
self.SetMenuBar(self.m_menubar1)
# self.m_menubar1.SetFocus()
globalSizer = wx.BoxSizer(wx.HORIZONTAL)
leftSizer = wx.BoxSizer(wx.VERTICAL)
# -------------------- Information part of the interface
informationSizer = wx.StaticBoxSizer(wx.StaticBox(self, wx.ID_ANY, u""), wx.VERTICAL)
self.m_staticText2 = wx.StaticText(informationSizer.GetStaticBox(), wx.ID_ANY, u"Data information",
wx.DefaultPosition, wx.DefaultSize, 0)
self.m_staticText2.Wrap(-1)
self.m_staticText2.SetFont(
wx.Font(wx.NORMAL_FONT.GetPointSize(), wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD,
False, wx.EmptyString))
informationSizer.Add(self.m_staticText2, 0, wx.ALL, 5)
informationBoxSizer = wx.BoxSizer(wx.VERTICAL)
textInfo = u"Rows: 0 Columns: 0 Nulls: 0"
self.m_information = wx.StaticText(informationSizer.GetStaticBox(), wx.ID_ANY, textInfo, wx.DefaultPosition,
wx.DefaultSize, 0)
informationBoxSizer.Add(self.m_information, 0, wx.LEFT, 0)
informationSizer.Add(informationBoxSizer, 1, wx.RIGHT | wx.LEFT | wx.BOTTOM, 10)
leftSizer.Add(informationSizer, flag=wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border=10)
# -------------------- Buttons of the interface
buttonsSizer = wx.BoxSizer(wx.VERTICAL)
buttonsSubSizer1 = wx.GridSizer(rows=2, cols=2, vgap=0, hgap=0)
self.openNewFileBtn = wx.Button(self, wx.ID_ANY, u"Open new file", wx.DefaultPosition, wx.DefaultSize, 0)
buttonsSubSizer1.Add(self.openNewFileBtn, 0, wx.TOP | wx.BOTTOM | wx.LEFT | wx.EXPAND, 5)
self.addFileBtn = wx.Button(self, wx.ID_ANY, u"Add file", wx.DefaultPosition, wx.DefaultSize, 0)
buttonsSubSizer1.Add(self.addFileBtn, 0, wx.ALL | wx.EXPAND, 5)
self.addFileBtn.Enable(False)
self.exportDataBtn = wx.Button(self, wx.ID_ANY, u"Save data", wx.DefaultPosition, wx.DefaultSize, 0)
buttonsSubSizer1.Add(self.exportDataBtn, 0, wx.TOP | wx.BOTTOM | wx.LEFT | wx.EXPAND, 5)
self.exportDataBtn.Enable(False)
self.resetDataBtn = wx.Button(self, wx.ID_ANY, u"Close data", wx.DefaultPosition, wx.DefaultSize, 0)
buttonsSubSizer1.Add(self.resetDataBtn, 0, wx.ALL | wx.EXPAND, 5)
self.resetDataBtn.Enable(False)
buttonsSizer.Add(buttonsSubSizer1, 0, wx.EXPAND, 0)
buttonsSizer.AddSpacer(10)
self.descriptiveStatsBtn = wx.Button(self, wx.ID_ANY, u"Basic statistics", wx.DefaultPosition, wx.DefaultSize,
0)
self.descriptiveStatsBtn.Enable(False)
# self.descriptiveStatsBtn.SetMinSize( wx.Size( -1,25 ) )
buttonsSizer.Add(self.descriptiveStatsBtn, 0, wx.ALL | wx.EXPAND, 5)
self.significanceTestBtn = wx.Button(self, wx.ID_ANY, u"Significance tests", wx.DefaultPosition, wx.DefaultSize,
0)
self.significanceTestBtn.Enable(False)
# self.significanceTestBtn.SetMinSize( wx.Size( -1,25 ) )
buttonsSizer.Add(self.significanceTestBtn, 0, wx.ALL | wx.EXPAND, 5)
buttonsSizer.AddSpacer(10)
leftSizer.Add(buttonsSizer, flag=wx.ALL | wx.EXPAND, border=5)
# -------------------- Buttons for plot
gSizerChart = wx.GridSizer(0, 3, 0, 0)
# Images needed for the buttons
self.histogramBmp = wx.Image(str(os.path.dirname(__file__)) + "/icons/histogram1.png",
wx.BITMAP_TYPE_ANY).ConvertToBitmap()
self.scatterPlotmBmp = wx.Image(str(os.path.dirname(__file__)) + "/icons/scatterPlot1.png",
wx.BITMAP_TYPE_ANY).ConvertToBitmap()
self.pieChartmBmp = wx.Image(str(os.path.dirname(__file__)) + "/icons/pieChart1.png",
wx.BITMAP_TYPE_ANY).ConvertToBitmap()
self.boxPlotBmp = wx.Image(str(os.path.dirname(__file__)) + "/icons/boxPlot1.png",
wx.BITMAP_TYPE_ANY).ConvertToBitmap()
self.barChartBmp = wx.Image(str(os.path.dirname(__file__)) + "/icons/barChart1.png",
wx.BITMAP_TYPE_ANY).ConvertToBitmap()
self.histogramBtn = wx.BitmapButton(self, wx.ID_ANY, self.histogramBmp, wx.DefaultPosition, wx.Size(80, 80),
wx.BU_AUTODRAW)
gSizerChart.Add(self.histogramBtn, 0, wx.ALIGN_CENTER | wx.ALL, 5)
self.histogramBtn.Enable(False)
self.histogramBtn.SetToolTip(wx.ToolTip("Histogram"))
self.scatterPlotBtn = wx.BitmapButton(self, wx.ID_ANY, self.scatterPlotmBmp, wx.DefaultPosition,
wx.Size(80, 80), wx.BU_AUTODRAW)
gSizerChart.Add(self.scatterPlotBtn, 0, wx.ALIGN_CENTER | wx.ALL, 5)
self.scatterPlotBtn.Enable(False)
self.scatterPlotBtn.SetToolTip(wx.ToolTip("Scatter Plot"))
self.pieChartBtn = wx.BitmapButton(self, wx.ID_ANY, self.pieChartmBmp, wx.DefaultPosition, wx.Size(80, 80),
wx.BU_AUTODRAW)
gSizerChart.Add(self.pieChartBtn, 0, wx.ALIGN_CENTER | wx.ALL, 5)
self.pieChartBtn.Enable(False)
self.pieChartBtn.SetToolTip(wx.ToolTip("Pie Chart"))
self.boxPlotBtn = wx.BitmapButton(self, wx.ID_ANY, self.boxPlotBmp, wx.DefaultPosition, wx.Size(80, 80),
wx.BU_AUTODRAW)
gSizerChart.Add(self.boxPlotBtn, 0, wx.ALIGN_CENTER | wx.ALL, 5)
self.boxPlotBtn.Enable(False)
self.boxPlotBtn.SetToolTip(wx.ToolTip("Box Plot"))
self.barChartBtn = wx.BitmapButton(self, wx.ID_ANY, self.barChartBmp, wx.DefaultPosition, wx.Size(80, 80),
wx.BU_AUTODRAW)
gSizerChart.Add(self.barChartBtn, 0, wx.ALIGN_CENTER | wx.ALL, 5)
self.barChartBtn.Enable(False)
self.barChartBtn.SetToolTip(wx.ToolTip("Bar Chart"))
leftSizer.Add(gSizerChart, flag=wx.ALL | wx.EXPAND, border=5)
# ------------------- Info about upgrades
if self.params['upgradable']:
import wx.lib.agw.gradientbutton as GB
leftSizer.AddStretchSpacer(1)
# self.upgradeButton = wx.Button( self, wx.ID_ANY, u"* New version: "+self.params['availableVersionToUpgrade']+" *", wx.DefaultPosition, wx.DefaultSize, 0 )
self.upgradeButton = GB.GradientButton(self, label="New version available: " + (
self.params['availableVersionToUpgrade'].decode('utf-8')))
self.upgradeButton.SetBaseColours(startcolour=wx.TheColourDatabase.Find('PALE GREEN'),
foregroundcolour=wx.BLACK)
self.upgradeButton.SetPressedBottomColour(wx.TheColourDatabase.Find('LIGHT GREY'))
self.upgradeButton.SetPressedTopColour(wx.TheColourDatabase.Find('LIGHT GREY'))
boldFont = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
boldFont.SetWeight(wx.BOLD)
self.upgradeButton.SetFont(boldFont)
self.Bind(wx.EVT_BUTTON, self.openBrowserDownload, id=self.upgradeButton.GetId())
leftSizer.Add(self.upgradeButton, flag=wx.ALL | wx.EXPAND, border=5)
globalSizer.Add(leftSizer, flag=wx.EXPAND | wx.ALL, border=10)
# ------------------- Data table
self.m_dataTable = wx.grid.Grid(self)
# Grid
self.m_dataTable.CreateGrid(45, 45)
self.m_dataTable.EnableEditing(False)
self.m_dataTable.EnableGridLines(True)
self.m_dataTable.EnableDragGridSize(False)
self.m_dataTable.SetMargins(0, 0)
# Columns
self.m_dataTable.EnableDragColMove(False)
self.m_dataTable.EnableDragColSize(False)
self.m_dataTable.SetColLabelSize(30)
self.m_dataTable.SetColLabelAlignment(wx.ALIGN_CENTRE, wx.ALIGN_CENTRE)
# Rows
self.m_dataTable.EnableDragRowSize(False)
self.m_dataTable.SetRowLabelSize(80)
self.m_dataTable.SetRowLabelAlignment(wx.ALIGN_CENTRE, wx.ALIGN_CENTRE)
# Cell Defaults
self.m_dataTable.SetDefaultCellAlignment(wx.ALIGN_CENTRE, wx.ALIGN_CENTER)
# Selection mode
self.m_dataTable.SetSelectionMode(wx.grid.Grid.wxGridSelectRows | wx.grid.Grid.wxGridSelectColumns)
# self.m_dataTable.EnableEditing(True)
fgSizer8 = wx.BoxSizer(wx.VERTICAL)
fgSizer8.Add(self.m_dataTable)
self.m_dataTable.Enable(False)
self.m_dataTable.Show(True)
globalSizer.Add(fgSizer8, flag=wx.ALL | wx.EXPAND, border=10)
# Options to show the GUI
self.SetSizer(globalSizer)
self.Layout()
self.Centre(wx.BOTH)
self.Show(True)
# self.Move((0,0))
widthScreen, heightScreen = wx.GetDisplaySize()
widthWindow = 1440
heightWindow = 900
if ((widthScreen >= widthWindow) and (heightScreen > heightWindow)):
self.SetSize((widthWindow, heightWindow))
else:
self.Maximize()
self.SetMinSize((1024, 768))
# Binding between buttons and functions which will control the events
self.Bind(wx.EVT_CLOSE, self.closeApp) # Close window
self.Bind(wx.EVT_MENU, self.openFile, self.m_menuNewFile)
self.Bind(wx.EVT_BUTTON, self.openFile, self.openNewFileBtn)
self.Bind(wx.EVT_MENU, self.addFile, self.m_menuAddFile)
self.Bind(wx.EVT_BUTTON, self.addFile, self.addFileBtn)
self.Bind(wx.EVT_MENU, self.saveFile, self.m_menuExportData)
self.Bind(wx.EVT_MENU, self.resetData, self.m_menuResetData)
self.Bind(wx.EVT_MENU, self.undo, self.m_undo)
self.Bind(wx.EVT_MENU, self.createNewColumn, self.m_addNewColumn)
self.Bind(wx.EVT_MENU, self.deleteColumnsByLabels, self.m_deleteColumns)
self.Bind(wx.EVT_MENU, self.deleteColumnsRows, self.m_deletedSelectedCR)
self.Bind(wx.EVT_MENU, self.renameCol, self.m_renameSelectedCol)
self.Bind(wx.EVT_MENU, self.moveCol, self.m_moveSelectedCol)
self.Bind(wx.EVT_MENU, self.replaceInCol, self.m_replaceInCol)
self.Bind(wx.EVT_MENU, self.discretizeCol, self.m_discretizeSelectedCol)
self.Bind(wx.EVT_MENU, self.numerizeCol, self.m_numerizeSelectedCol)
self.Bind(wx.EVT_MENU, self.sortAscendingCol, self.m_sortAscending)
self.Bind(wx.EVT_MENU, self.sortDescendingCol, self.m_sortDescending)
self.Bind(wx.EVT_MENU, self.appInformation, self.m_menuAbout)
self.Bind(wx.EVT_MENU, self.closeApp, self.m_menuQuit)
self.Bind(wx.EVT_BUTTON, self.createBasicStatisticsInterface, self.descriptiveStatsBtn)
self.Bind(wx.EVT_BUTTON, self.resetData, self.resetDataBtn)
self.Bind(wx.EVT_BUTTON, self.saveFile, self.exportDataBtn)
self.Bind(wx.EVT_BUTTON, self.createHistogram, self.histogramBtn)
self.Bind(wx.EVT_BUTTON, self.createScatterPlot, self.scatterPlotBtn)
self.Bind(wx.EVT_BUTTON, self.createPieChart, self.pieChartBtn)
self.Bind(wx.EVT_BUTTON, self.createBoxPlot, self.boxPlotBtn)
self.Bind(wx.EVT_BUTTON, self.createBarChart, self.barChartBtn)
self.Bind(wx.EVT_BUTTON, self.doSignificanceTest, self.significanceTestBtn)
self.Bind(wx.grid.EVT_GRID_CELL_RIGHT_CLICK, self.rightClickOnTable, self.m_dataTable)
self.Bind(wx.grid.EVT_GRID_LABEL_RIGHT_CLICK, self.rightClickOnTable, self.m_dataTable)
self.Bind(wx.grid.EVT_GRID_RANGE_SELECT, self.contentSelected, self.m_dataTable)
self.Bind(wx.grid.EVT_GRID_CELL_LEFT_DCLICK, self.cellModification, self.m_dataTable)
# A controller object is created
self.controller = Controller()
HelpString = (
" -help: shows this information\n"
" -loadCSV fileName: loads CSV file (full path is required)\n"
)
if (len(sys.argv) != 1 and (sys.platform == 'linux' or sys.platform == 'darwin')):
arguments = sys.argv[1:]
possibleArguments = ['-help', '-loadCSV']
for argument in arguments:
if argument[0] == '-':
if argument not in possibleArguments:
print("\n** ERROR: command '" + argument + "' not recognized **\n")
print("** GASATaD terminal mode commands:")
print(HelpString)
sys.exit(0)
if "-help" in arguments:
print("\n** GASATaD: terminal mode **\n")
print(HelpString)
sys.exit(0)
else:
if "-loadCSV" in arguments:
CSVFileName = arguments[arguments.index("-loadCSV") + 1]
print("Loading CSV file: " + CSVFileName)
self.OpenCSVFileNoGUI(CSVFileName)
def undo(self, event):
self.controller.recoverData()
if not self.m_dataTable.IsEnabled():
self.m_dataTable.Enable()
self.refreshGUI()
self.m_undo.SetText("Undo")
self.m_undo.Enable(False)
def cellModification(self, event):
dlg = wx.TextEntryDialog(self, "Type new value for cell (empty for 'null'):", 'Change cell', '')
if dlg.ShowModal() == wx.ID_OK:
newValue = dlg.GetValue()
dlg.Destroy()
if newValue == "":
newValue2 = numpy.NaN
else:
try:
newValue2 = numpy.float64(newValue)
except:
newValue2 = newValue
self.controller.storeData()
self.m_undo.SetText("Undo change cell")
self.m_undo.Enable()
self.controller.changeCellValue(event.GetRow(), event.GetCol(), newValue2)
self.controller.detectColumnTypes()
self.refreshGUI()
event.Skip()
else:
dlg.Destroy()
def contentSelected(self, event):
columnsSelected = self.m_dataTable.GetSelectedCols()
rowsSelected = self.m_dataTable.GetSelectedRows()
if len(rowsSelected) == 0 and len(columnsSelected) == 0:
self.m_deletedSelectedCR.Enable(False)
else:
self.m_deletedSelectedCR.Enable()
if len(rowsSelected) == 0 and len(columnsSelected) == 1:
self.m_renameSelectedCol.Enable()
self.m_moveSelectedCol.Enable()
self.m_editMenu.Enable(self.sortMenuID, True)
columnSelectedLabel = self.m_dataTable.GetColLabelValue(self.m_dataTable.GetSelectedCols()[0])
if columnSelectedLabel not in self.controller.characterValues:
self.m_discretizeSelectedCol.Enable()
if columnSelectedLabel in self.controller.characterValues:
self.m_numerizeSelectedCol.Enable()
self.m_replaceInCol.Enable()
else:
self.m_renameSelectedCol.Enable(False)
self.m_moveSelectedCol.Enable(False)
self.m_discretizeSelectedCol.Enable(False)
self.m_numerizeSelectedCol.Enable(False)
self.m_replaceInCol.Enable(False)
self.m_editMenu.Enable(self.sortMenuID, False)
event.Skip()
def deleteColumnsRows(self, event):
rowsSelected = self.m_dataTable.GetSelectedRows()
columnsSelected = self.m_dataTable.GetSelectedCols()
self.controller.storeData()
self.m_undo.SetText("Undo delete columns/rows")
self.m_undo.Enable()
columnsSelectedLabels = []
for columnIndex in columnsSelected:
columnsSelectedLabels.append(self.m_dataTable.GetColLabelValue(columnIndex))
self.controller.deleteColumns(columnsSelectedLabels)
if len(rowsSelected) > 0:
self.controller.deleteRows(rowsSelected)
if self.controller.programState.dataToAnalyse.empty:
self.controller.resetDataToAnalyse()
self.refreshGUI()
def rightClickOnTable(self, event):
columnClicked = event.GetCol()
columnsSelected = self.m_dataTable.GetSelectedCols()
if columnClicked in columnsSelected:
popupMenu = wx.Menu()
textPopupDelete = "Delete column"
if len(columnsSelected) > 1:
textPopupDelete += "s"
self.popupDeleteID = wx.NewId()
popupMenu.Append(self.popupDeleteID, textPopupDelete)
self.Bind(wx.EVT_MENU, self.deleteColumns, id=self.popupDeleteID)
if len(columnsSelected) == 1:
# Renaming menu entry
popupRenameID = wx.NewId()
popupMenu.Append(popupRenameID, "Rename column")
self.Bind(wx.EVT_MENU, self.renameCol, id=popupRenameID)
# Moving menu entry
popupMoveID = wx.NewId()
popupMenu.Append(popupMoveID, "Move column")
self.Bind(wx.EVT_MENU, self.moveCol, id=popupMoveID)
columnSelectedLabel = self.m_dataTable.GetColLabelValue(self.m_dataTable.GetSelectedCols()[0])
if columnSelectedLabel in self.controller.characterValues:
self.popupReplaceInColID = wx.NewId()
popupMenu.Append(self.popupReplaceInColID, "Replace in column")
self.Bind(wx.EVT_MENU, self.replaceInCol, id=self.popupReplaceInColID)
# Sort menu entry
popupSortSubMenuID = wx.NewId()
popupSortAscendingID = wx.NewId()
popupSortDescendingID = wx.NewId()
popupSubMenuSort = wx.Menu()
popupSubMenuSort.Append(popupSortAscendingID, "ascending")
popupSubMenuSort.Append(popupSortDescendingID, "descending")
popupMenu.Append(popupSortSubMenuID, "Sort using column", popupSubMenuSort)
self.Bind(wx.EVT_MENU, self.sortAscendingCol, id=popupSortAscendingID)
self.Bind(wx.EVT_MENU, self.sortDescendingCol, id=popupSortDescendingID)
# self.m_sortDescending = self.m_sortSubMenu.Append(wx.ID_ANY, "Descending")
# self.sortMenuID = wx.NewId()
# self.m_editMenu.AppendMenu(self.sortMenuID, "Sort using selected column",self.m_sortSubMenu )
# self.m_editMenu.Enable(self.sortMenuID,False)
# Discretizing menu entry
if columnSelectedLabel not in self.controller.characterValues:
self.popupDiscretizeID = wx.NewId()
popupMenu.Append(self.popupDiscretizeID, "Convert column to text")
self.Bind(wx.EVT_MENU, self.discretizeCol, id=self.popupDiscretizeID)
if columnSelectedLabel in self.controller.characterValues:
self.popupNumerizeID = wx.NewId()
popupMenu.Append(self.popupNumerizeID, "Convert column to numbers")
self.Bind(wx.EVT_MENU, self.numerizeCol, id=self.popupNumerizeID)
self.PopupMenu(popupMenu)
popupMenu.Destroy()
rowClicked = event.GetRow()
rowsSelected = self.m_dataTable.GetSelectedRows()
if rowClicked in rowsSelected:
textPopupDelete = "Delete row"
if len(rowsSelected) > 1:
textPopupDelete += "s"
popupMenu = wx.Menu()
self.popupDeleteID = wx.NewId()
popupMenu.Append(self.popupDeleteID, textPopupDelete)
self.Bind(wx.EVT_MENU, self.deleteRows, id=self.popupDeleteID)
self.PopupMenu(popupMenu)
popupMenu.Destroy()
event.Skip()
def deleteColumns(self, event): # Used after right-click on selected columns
columnsSelectedIndex = self.m_dataTable.GetSelectedCols()
columnsSelectedLabels = []
for columnIndex in columnsSelectedIndex:
columnsSelectedLabels.append(self.m_dataTable.GetColLabelValue(columnIndex))
self.controller.storeData()
self.m_undo.SetText("Undo delete columns")
self.m_undo.Enable()
self.controller.deleteColumns(columnsSelectedLabels)
if self.controller.programState.dataToAnalyse.empty:
self.controller.resetDataToAnalyse()
self.refreshGUI()
def moveCol(self, event):
columnsSelectedIndex = self.m_dataTable.GetSelectedCols()
oldPos = columnsSelectedIndex[0]
maxPos = self.controller.getNumberOfColumns() - 1
newPosOk = False
while not newPosOk:
dlg = wx.TextEntryDialog(self, "New position for column (between 0 and " + str(maxPos) + "):",
"Move column", "")
if dlg.ShowModal() == wx.ID_OK:
newPos = dlg.GetValue()
dlg.Destroy()
try:
newPos = int(newPos)
newPosOk = True
except:
None
if newPosOk and (newPos < 0 or newPos > maxPos):
newPosOk = False
else:
dlg.Destroy()
break
if newPosOk:
self.controller.storeData()
self.m_undo.SetText("Undo move column")
self.m_undo.Enable()
colIndex = list(self.controller.getDataToAnalyse().columns)
label = colIndex[columnsSelectedIndex[0]]
colIndex.pop(columnsSelectedIndex[0])
colIndex.insert(newPos, label)
self.controller.reorderColumns(colIndex)
self.refreshGUI(updateDataInfo=False)
self.m_dataTable.SetGridCursor(0, newPos)
self.m_dataTable.MakeCellVisible(0, newPos)
self.m_dataTable.SelectCol(newPos)
def renameCol(self, event):
columnsSelectedIndex = self.m_dataTable.GetSelectedCols()
oldLabel = self.m_dataTable.GetColLabelValue(columnsSelectedIndex[0])
dlg = wx.TextEntryDialog(self, "Type new label for column '" + oldLabel + "':", 'Rename column', '')
if dlg.ShowModal() == wx.ID_OK:
newLabel = dlg.GetValue()
dlg.Destroy()
self.controller.storeData()
self.m_undo.SetText("Undo rename column")
self.m_undo.Enable()
self.controller.renameColumn(oldLabel, newLabel)
self.refreshGUI(updateDataInfo=False, markNans=False)
self.m_dataTable.SetGridCursor(0, columnsSelectedIndex[0])
self.m_dataTable.MakeCellVisible(0, columnsSelectedIndex[0])
self.m_dataTable.SelectCol(columnsSelectedIndex[0])
else:
dlg.Destroy()
def replaceInCol(self, event):
columnsSelectedIndex = self.m_dataTable.GetSelectedCols()
colLabel = self.m_dataTable.GetColLabelValue(columnsSelectedIndex[0])
listTags = list(self.controller.programState.dataToAnalyse[str(colLabel)].unique())
if numpy.NaN in listTags:
listTags.remove(numpy.NaN)
listTags.insert(0, 'null')
selectValuesInterface = ReplaceInColInterface(self, listTags)
if selectValuesInterface.ShowModal() == wx.ID_OK:
self.controller.storeData()
self.m_undo.SetText("Undo replace")
self.m_undo.Enable()
oldTag, newTag = selectValuesInterface.getValues()
if oldTag == 'null':
oldTag = numpy.NaN
if newTag == "":
newTag = numpy.NaN
self.controller.replaceInTextCol(colLabel, oldTag, newTag)
self.refreshGUI()
self.m_dataTable.SetGridCursor(0, columnsSelectedIndex[0])
self.m_dataTable.MakeCellVisible(0, columnsSelectedIndex[0])
self.m_dataTable.SelectCol(columnsSelectedIndex[0])
def discretizeCol(self, event):
columnsSelectedIndex = self.m_dataTable.GetSelectedCols()
columnSelectedLabel = self.m_dataTable.GetColLabelValue(columnsSelectedIndex[0])
self.controller.storeData()
self.m_undo.SetText("Undo convert to text")
self.m_undo.Enable()
self.controller.programState.dataToAnalyse[columnSelectedLabel] = self.controller.programState.dataToAnalyse[
columnSelectedLabel].astype(str)
self.controller.characterValues.append(columnSelectedLabel)
if columnSelectedLabel in self.controller.floatValues:
self.controller.floatValues.remove(columnSelectedLabel)
if columnSelectedLabel in self.controller.integerValues:
self.controller.integerValues.remove(columnSelectedLabel)
self.refreshGUI(updateDataInfo=False)
self.m_dataTable.SetGridCursor(0, columnsSelectedIndex[0])
self.m_dataTable.MakeCellVisible(0, columnsSelectedIndex[0])
def numerizeCol(self, event):
columnsSelectedIndex = self.m_dataTable.GetSelectedCols()
columnSelectedLabel = self.m_dataTable.GetColLabelValue(columnsSelectedIndex[0])
self.controller.storeData()
self.m_undo.SetText("Undo convert to numbers")
self.m_undo.Enable()
oldType = self.controller.programState.dataToAnalyse[columnSelectedLabel].dtypes
self.controller.programState.dataToAnalyse[columnSelectedLabel] = to_numeric(
self.controller.programState.dataToAnalyse[columnSelectedLabel], errors='ignore')
newType = self.controller.programState.dataToAnalyse[columnSelectedLabel].dtypes
if oldType == newType:
dlg = wx.MessageDialog(None,
"The column '" + columnSelectedLabel + "' could not be converted to numerical values",
"Invalid conversion", wx.OK | wx.ICON_INFORMATION)
if dlg.ShowModal() == wx.ID_OK:
dlg.Destroy()
else:
self.controller.characterValues.remove(columnSelectedLabel)
if newType == 'float64':
self.controller.floatValues.append(columnSelectedLabel)
else:
self.controller.integerValues.append(columnSelectedLabel)
self.refreshGUI(updateDataInfo=False)
self.m_dataTable.SetGridCursor(0, columnsSelectedIndex[0])
self.m_dataTable.MakeCellVisible(0, columnsSelectedIndex[0])
def sortAscendingCol(self, event):
self.sortCol(True)
def sortDescendingCol(self, event):
self.sortCol(False)
def sortCol(self, ascendingBool):
self.controller.storeData()
self.m_undo.SetText("Undo sort rows")
self.m_undo.Enable()
columnsSelectedIndex = self.m_dataTable.GetSelectedCols()
columnSelectedLabel = self.m_dataTable.GetColLabelValue(columnsSelectedIndex[0])
self.controller.programState.dataToAnalyse.sort_values(columnSelectedLabel, ascending=ascendingBool,
inplace=True)
self.refreshGUI(updateDataInfo=False)
self.m_dataTable.SetGridCursor(0, columnsSelectedIndex[0])
self.m_dataTable.MakeCellVisible(0, columnsSelectedIndex[0])
self.m_dataTable.SelectCol(columnsSelectedIndex[0])
def deleteRows(self, event): # Used after right-click on selected rows
rowsSelectedIndex = self.m_dataTable.GetSelectedRows()
rowsSelectedLabels = []
for rowIndex in rowsSelectedIndex:
rowsSelectedLabels.append(self.m_dataTable.GetRowLabelValue(rowIndex))
self.controller.storeData()
self.m_undo.SetText("Undo delete rows")
self.m_undo.Enable()
self.controller.deleteRows(rowsSelectedIndex)
if self.controller.programState.dataToAnalyse.empty:
self.controller.resetDataToAnalyse()
self.refreshGUI()
def CheckUpdates(self):
from sys import argv
import urllib.request, urllib.error
import os
remoteVersion = ""
remoteVersionFile = ""
if (platform == "linux" or platform == "linux2") and argv[0] == "/usr/share/gasatad/GASATaD_2_0.py":
remoteVersionFile = "https://raw.githubusercontent.com/milegroup/gasatad/master/docs/programVersions/deb.txt"
elif (platform == "darwin") and ("GASATaD.app" in os.path.realpath(__file__)):
remoteVersionFile = "https://raw.githubusercontent.com/milegroup/gasatad/master/docs/programVersions/mac.txt"
elif platform == "win32" and argv[0].endswith(".exe"):
remoteVersionFile = "https://raw.githubusercontent.com/milegroup/gasatad/master/docs/programVersions/win.txt"
elif argv[0].endswith("GASATaD_2_0.py"):
# print "# Running GASATaD from source"
remoteVersionFile = "https://raw.githubusercontent.com/milegroup/gasatad/master/docs/programVersions/src.txt"
if remoteVersionFile:
try:
if platform != "darwin":
remoteFile = urllib.request.urlopen(remoteVersionFile)
remoteVersion = remoteFile.readline().strip()
remoteFile.close()
else:
import ssl
context = ssl._create_unverified_context()
remoteFile = urllib.request.urlopen(remoteVersionFile, context=context)
remoteVersion = remoteFile.readline().strip()
remoteFile.close()
# print "# Version available in GASATaD web page: ", remoteVersion
except urllib.error.URLError:
# print "# I couldn't check for updates"
None
if remoteVersion:
# print "# Version file exists"
if float(remoteVersion) > float(self.params['version']):
self.params['upgradable'] = True
self.params['availableVersionToUpgrade'] = remoteVersion
# self.params['upgradable'] = True
# self.params['availableVersionToUpgrade'] = remoteVersion
def openBrowserDownload(self, event):
import webbrowser
webbrowser.open("https://milegroup.github.io/gasatad/#download")
def updateDataInfo(self):
if self.controller.programState.dataToAnalyse.empty:
textInfo = u"Rows: 0 Columns: 0 Nulls: 0"
self.m_information.SetLabel(textInfo)
else:
numRows = self.controller.getNumberOfRows()
numCols = self.controller.getNumberOfColumns()
textInfo = "Rows: {0:d} Columns: {1:d} Nulls: {2:d}".format(numRows, numCols, self.params['noOfNulls'])
# textInfo += "\nText columns: {0:d}".format(len(self.controller.characterValues))
# textInfo += "\nInteger columns: {0:d}".format(len(self.controller.integerValues))
# textInfo += "\nFloat columns: {0:d}".format(len(self.controller.floatValues))
self.m_information.SetLabel(textInfo)
def OpenCSVFileNoGUI(self, fileName):
self.data = None
try:
self.Datafile = open(fileName, 'rU')
self.data = read_csv(self.Datafile, sep=None, engine='python', encoding='utf-8')
self.data.drop(self.data.columns[[0]], axis=1, inplace=True)
self.data.rename(columns={'Unnamed: 0': 'NoTag'}, inplace=True)
self.controller.OpenFile(self.data)
except UnicodeDecodeError:
print("Error: non ascii files in file")
return
except:
print("Error: ", sys.exc_info()[0])
print("There was some problem with the file")
return
self.refreshGUI()
print("File: " + fileName + " loaded")
def openFile(self, event):
askfile = AskFileType(self, -1, "open")
askfile.CenterOnScreen()
askfile.ShowModal()
askfile.Destroy()
def addFile(self, event):
askfile = AskFileType(self, -1, "add")
askfile.CenterOnScreen()
askfile.ShowModal()
askfile.Destroy()
def selectCSV(self, additionalFile):
openFileInterf = OpenCSVFile(self, -1, additionalFile=additionalFile, dirfrom=self.params['options']['dirfrom'])
def selectXLS(self, additionalFile):
openFileInterf = OpenXLSFile(self, -1, additionalFile=additionalFile, dirfrom=self.params['options']['dirfrom'])
def OpenAddCSV(self, openFileOptions):
# print "Gonna open CSV file"
# print openFileOptions
self.params['options']['dirfrom'] = openFileOptions['dirName']
readCorrect = True
self.data = None
discardCol = openFileOptions['discardFirstCol']
sepChar = ''
if openFileOptions['sepchar'] == "Comma":
sepChar = ','
elif openFileOptions['sepchar'] == "Semicolon":
sepChar = ';'
elif openFileOptions['sepchar'] == "Tab":
sepChar = '\t'
try:
self.data = read_csv(os.path.join(openFileOptions['dirName'], openFileOptions['fileName']), sep=sepChar,
header=0,
engine='python', encoding='utf-8')
except:
# print "Error: ", sys.exc_info()
type, value, traceback = sys.exc_info()
self.dlg = wx.MessageDialog(None, "Error reading file " + openFileOptions['fileName'] + "\n" + str(value),
"File error", wx.OK | wx.ICON_EXCLAMATION)
if self.dlg.ShowModal() == wx.ID_OK:
self.dlg.Destroy()
readCorrect = False
if readCorrect:
if discardCol:
self.data.drop(self.data.columns[[0]], axis=1, inplace=True)
self.data.rename(columns={'Unnamed: 0': 'NoTag'}, inplace=True)
if openFileOptions['additionalFile'] and readCorrect and (
self.m_dataTable.GetNumberRows() != len(self.data.index)):
self.dlg = wx.MessageDialog(None,
"Number of rows does not match: \n Loaded data has " + str(
self.m_dataTable.GetNumberRows()) + " rows \n File " + openFileOptions[
'fileName'] + " has " + str(
len(self.data.index)) + " rows ", "File error",
wx.OK | wx.ICON_EXCLAMATION)
if self.dlg.ShowModal() == wx.ID_OK:
self.dlg.Destroy()
readCorrect = False
if readCorrect:
if openFileOptions['additionalFile']:
self.controller.storeData()
self.m_undo.SetText("Undo add file")
self.m_undo.Enable()
self.controller.OpenAdditionalFile(self.data)
else:
self.controller.OpenFile(self.data)
self.refreshGUI()
if self.controller.nullValuesInFile(self.data):
self.dlg = wx.MessageDialog(None, "File " + self.filename + " has one or more missing values",
"Missing values", wx.OK | wx.ICON_WARNING)
if self.dlg.ShowModal() == wx.ID_OK:
self.dlg.Destroy()
if openFileOptions['additionalFile']:
# Move the view of the table to the last column
self.m_dataTable.SetGridCursor(0, self.controller.getNumberOfColumns() - 1)
self.m_dataTable.MakeCellVisible(0, self.controller.getNumberOfColumns() - 1)
def OpenAddXLS(self, openFileOptions):
# print "File to load: ", openFileOptions['fileName']
self.params['options']['dirfrom'] = openFileOptions['dirName']
readCorrect = True
self.data = None
rowColNames = openFileOptions['rowColNames']
noColsDiscard = openFileOptions['noColsDiscard']
sheetNumber = openFileOptions['sheetNumber']
# print "Reading col names from row: ", rowColNames
try:
self.data = read_excel(os.path.join(openFileOptions['dirName'], openFileOptions['fileName']),
sheet_name=sheetNumber, header=rowColNames,
index_col=None)
if noColsDiscard != 0:
self.data.drop(self.data.columns[range(noColsDiscard)], axis=1, inplace=True)
# self.data = self.preprocessExcel(self.data)
except:
# print "Error: ", sys.exc_info()
type, value, traceback = sys.exc_info()
self.dlg = wx.MessageDialog(None, "Error reading file " + openFileOptions['fileName'] + "\n" + str(value),
"File error", wx.OK | wx.ICON_EXCLAMATION)
if self.dlg.ShowModal() == wx.ID_OK:
self.dlg.Destroy()
readCorrect = False
if readCorrect:
self.data.rename(columns={'Unnamed: 0': 'NoTag'}, inplace=True)
if openFileOptions['additionalFile'] and readCorrect and (
self.m_dataTable.GetNumberRows() != len(self.data.index)):
self.dlg = wx.MessageDialog(None,
"Number of rows does not match: \n Loaded data has " + str(
self.m_dataTable.GetNumberRows()) + " rows \n File " + openFileOptions[
'fileName'] + " has " + str(
len(self.data.index)) + " rows ", "File error",
wx.OK | wx.ICON_EXCLAMATION)
if self.dlg.ShowModal() == wx.ID_OK:
self.dlg.Destroy()
readCorrect = False
if readCorrect:
if openFileOptions['additionalFile']:
self.controller.storeData()
self.m_undo.SetText("Undo add file")
self.m_undo.Enable()
self.controller.OpenAdditionalFile(self.data)
else:
self.controller.OpenFile(self.data)
self.refreshGUI()
if self.controller.nullValuesInFile(self.data):
self.dlg = wx.MessageDialog(None,
"File " + openFileOptions['fileName'] + " has one or more missing values",
"Missing values", wx.OK | wx.ICON_WARNING)
if self.dlg.ShowModal() == wx.ID_OK:
self.dlg.Destroy()
if openFileOptions['additionalFile']:
# Move the view of the table to the last column
self.m_dataTable.SetGridCursor(0, self.controller.getNumberOfColumns() - 1)
self.m_dataTable.MakeCellVisible(0, self.controller.getNumberOfColumns() - 1)
def preprocessExcel(self, data):
for row in range(len(data.index)):
for col in range(len(data.columns)):
if type(data.iloc[row, col]) == unicode or type(data.iloc[row, col]) == str:
if data.iloc[row, col].isspace():
data.iloc[row, col] = numpy.nan
if type(data.iloc[row, col]) == int:
data.iloc[row, col] = float(data.iloc[row, col])
data.dropna(axis=0, how='all', inplace=True)
for col in data.columns:
allNumbers = True;
for row in data.index:
if not isinstance(data.loc[row, col], (int, long, float)):
allNumbers = False;
if allNumbers:
data[col] = data[col].astype(numpy.float64)
return data
def adaptSizeOfGrid(self):
'''
This function calculates the number of rows and columns to adapt the grid
'''
numColsDataframe = self.controller.getNumberOfColumns()
numRowsDataframe = self.controller.getNumberOfRows()
numColsGrid = self.m_dataTable.GetNumberCols()
numRowsGrid = self.m_dataTable.GetNumberRows()
if numColsDataframe < numColsGrid:
self.m_dataTable.DeleteCols(0, (numColsGrid - numColsDataframe))
else:
self.m_dataTable.AppendCols((numColsDataframe - numColsGrid))
if numRowsDataframe < numRowsGrid:
self.m_dataTable.DeleteRows(0, (numRowsGrid - numRowsDataframe))
else:
self.m_dataTable.AppendRows((numRowsDataframe - numRowsGrid))
def fillInGrid(self):
colLabels = self.controller.getLabelsOfColumns()
numRows = self.controller.getNumberOfRows()
numCols = self.controller.getNumberOfColumns()
dataToAnalyse = self.controller.getDataToAnalyse()
self.adaptSizeOfGrid()
for i in range(len(colLabels)):
self.m_dataTable.SetColLabelValue(i, colLabels[i])
for row in range(numRows):
for col in range(numCols):
if dataToAnalyse.iloc[row, col] != dataToAnalyse.iloc[row, col]:
self.m_dataTable.SetCellValue(row, col, "nan")
elif type(dataToAnalyse.iloc[row, col]) == float:
dataToAnalyse.iloc[row, col] = numpy.float64(dataToAnalyse.iloc[row, col])
elif type(dataToAnalyse.iloc[row, col]) in (int, float, complex, numpy.float64, numpy.int64):
self.m_dataTable.SetCellValue(row, col, '{:5g}'.format(dataToAnalyse.iloc[row, col]))
else:
self.m_dataTable.SetCellValue(row, col, dataToAnalyse.iloc[row, col])
self.controller.detectColumnTypes()
def markNans(self):
# print "# Going to mark nans"
numRows = self.controller.getNumberOfRows()
numCols = self.controller.getNumberOfColumns()
self.params['noOfNulls'] = 0
for row in range(numRows):
for col in range(numCols):
content = self.m_dataTable.GetCellValue(row, col)
if content == 'nan' or content == 'null' or content.lower() == "no data": # This checks for nan
# print "# Nan detected in cell:",row," ",col
self.m_dataTable.SetCellValue(row, col, "null")
# self.m_dataTable.SetCellBackgroundColour(row,col,'peachpuff')
self.m_dataTable.SetCellBackgroundColour(row, col, wx.Colour(255, 218, 185))
self.params['noOfNulls'] += 1
else:
if self.m_dataTable.GetColLabelValue(col) in self.controller.characterValues:
self.m_dataTable.SetCellBackgroundColour(row, col, wx.Colour(250, 250, 210))
elif self.m_dataTable.GetColLabelValue(col) in self.controller.integerValues:
self.m_dataTable.SetCellBackgroundColour(row, col, wx.Colour(240, 255, 255))
else:
self.m_dataTable.SetCellBackgroundColour(row, col, 'white')
def saveFile(self, event):
askfile = AskFileType(self, -1, "save")
askfile.CenterOnScreen()
askfile.ShowModal()
askfile.Destroy()
def saveToCSV(self):
self.fileExtensions = "CSV files (*.csv)|*.csv;*.CSV|All files (*.*)|*.*"
saveFile = wx.FileDialog(self, message='Save file', defaultDir=self.params['options']['dirfrom'],
defaultFile='untitled.csv', wildcard=self.fileExtensions,
style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
if saveFile.ShowModal() == wx.ID_OK:
self.filename = saveFile.GetFilename()
self.directory = saveFile.GetDirectory()
fileExtension = self.filename.rpartition(".")[-1]
if fileExtension.lower() != "csv":
self.dlg = wx.MessageDialog(None,
"Error exporting file " + self.filename + "\nFile extension (.csv) is required",
"File error", wx.OK | wx.ICON_EXCLAMATION)
if self.dlg.ShowModal() == wx.ID_OK:
self.dlg.Destroy()
else:
path = os.path.join(self.directory, self.filename)
exportCsv = ExportCsvOptions(self)
if exportCsv.ShowModal() == wx.ID_OK:
try:
self.controller.exportDataCSV(path, exportCsv.getSelectedExportOptions())
except:
self.dlg = wx.MessageDialog(None, "Error saving to file " + self.filename,
"File error", wx.OK | wx.ICON_EXCLAMATION)
if self.dlg.ShowModal() == wx.ID_OK:
self.dlg.Destroy()
return
dlg = wx.MessageDialog(None, "Data saved to file: " + self.filename, "File operation",
wx.OK | wx.ICON_INFORMATION)
self.params['options']['dirfrom'] = self.directory
if dlg.ShowModal() == wx.ID_OK:
dlg.Destroy()
def saveToXLS(self):
self.fileExtensions = "Excel files (*.xls;*.xlsx)|*.xls;*.xlsx;*.XLS;*.XLSX|All files (*.*)|*.*"
saveFile = wx.FileDialog(self, message='Save file', defaultDir=self.params['options']['dirfrom'],
defaultFile='untitled.xlsx',
wildcard=self.fileExtensions, style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
if saveFile.ShowModal() == wx.ID_OK:
self.filename = saveFile.GetFilename()
self.directory = saveFile.GetDirectory()
fileExtension = self.filename.rpartition(".")[-1]
if fileExtension.lower() not in ["xls", "xlsx"]:
self.dlg = wx.MessageDialog(None,
"Error exporting file " + self.filename + "\nFile extension (.xls|.xlsx) is required",
"File error", wx.OK | wx.ICON_EXCLAMATION)
if self.dlg.ShowModal() == wx.ID_OK:
self.dlg.Destroy()
else:
path = os.path.join(self.directory, self.filename)
try:
self.controller.exportDataExcel(path)
except:
self.dlg = wx.MessageDialog(None, "Error saving to file " + self.filename,
"File error", wx.OK | wx.ICON_EXCLAMATION)
if self.dlg.ShowModal() == wx.ID_OK:
self.dlg.Destroy()
return
dlg = wx.MessageDialog(None, "Data saved to file: " + self.filename, "File operation",
wx.OK | wx.ICON_INFORMATION)
self.params['options']['dirfrom'] = self.directory
if dlg.ShowModal() == wx.ID_OK:
dlg.Destroy()
def resetData(self, event):
self.controller.storeData()
self.m_undo.SetText("Undo close data")
self.m_undo.Enable()
self.controller.resetDataToAnalyse()
self.refreshGUI()
def refreshGUI(self, updateDataInfo=True, markNans=True):
# Reset plots options
self.histogramOptions = {}
self.scatterPlotOptions = {}
self.boxPlotOptions = {}
self.pieChartOptions = {}
self.barChartOptions = {}
if not self.controller.programState.dataToAnalyse.empty: # data present
self.fillInGrid() # Fills wxgrid from the data of the pandas dataframe
self.m_dataTable.AutoSize()
lastColumnOrigSize = self.m_dataTable.GetColSize(self.controller.getNumberOfColumns() - 1)
self.m_dataTable.SetColSize(self.controller.getNumberOfColumns() - 1, lastColumnOrigSize + 30)
self.m_dataTable.ClearSelection()
if markNans:
self.markNans()
if updateDataInfo:
self.updateDataInfo()
self.Layout()
self.m_dataTable.Enable(True)
self.m_dataTable.SetFocus()
# Graphs
self.histogramBtn.Enable(True)
self.scatterPlotBtn.Enable(True)
self.pieChartBtn.Enable(True)
self.boxPlotBtn.Enable(True)
self.barChartBtn.Enable(True)
# Buttons
self.openNewFileBtn.Enable(False)
self.addFileBtn.Enable(True)
self.resetDataBtn.Enable(True)
self.exportDataBtn.Enable(True)
self.descriptiveStatsBtn.Enable(True)
self.significanceTestBtn.Enable(True)
# Menus
self.m_menuNewFile.Enable(False)
self.m_menuAddFile.Enable(True)
self.m_menuResetData.Enable(True)
self.m_menuExportData.Enable(True)
self.m_addNewColumn.Enable(True)
self.m_deleteColumns.Enable(True)
else: # no data
self.fillInGrid()
self.m_dataTable.AppendRows(45)
self.m_dataTable.AppendCols(45)
self.m_dataTable.Enable(False)
# Graphs
self.histogramBtn.Enable(False)
self.scatterPlotBtn.Enable(False)
self.pieChartBtn.Enable(False)
self.boxPlotBtn.Enable(False)
self.barChartBtn.Enable(False)
# Buttons
self.openNewFileBtn.Enable(True)
self.addFileBtn.Enable(False)
self.resetDataBtn.Enable(False)
self.exportDataBtn.Enable(False)
self.descriptiveStatsBtn.Enable(False)
self.significanceTestBtn.Enable(False)
# Menus
self.m_menuNewFile.Enable(True)
self.m_menuAddFile.Enable(False)
self.m_menuResetData.Enable(False)
self.m_menuExportData.Enable(False)
self.m_addNewColumn.Enable(False)
self.m_deleteColumns.Enable(False)
self.updateDataInfo()
self.m_dataTable.SetColLabelSize(30)
self.m_dataTable.SetRowLabelSize(80)
self.Layout()
def deleteColumnsByLabels(self, event):
selectedColumnsInterface = DeleteColumnsInterface(self,
list(self.controller.programState.dataToAnalyse.columns))
if selectedColumnsInterface.ShowModal() == wx.ID_OK:
self.controller.storeData()
self.m_undo.SetText("Undo delete columns")
self.m_undo.Enable()
listOfColumns = selectedColumnsInterface.getSelectedColumns()
self.controller.deleteColumns(listOfColumns)
self.refreshGUI()
# if self.controller.programState.dataToAnalyse.empty:
# self.resetData(None)
# else:
# self.refreshGUI()
def createNewColumn(self, event):
if (len(self.controller.integerValues + self.controller.floatValues) != 0):
# Minimun and maximum for using when spinCtrls are created
minimum = int(self.controller.programState.dataToAnalyse.min(numeric_only=True).min().round()) - 1
maximum = int(self.controller.programState.dataToAnalyse.max(numeric_only=True).max().round()) + 1
factorFrame = AddColumnInterface(self, (self.controller.integerValues + self.controller.floatValues),
list(self.controller.programState.dataToAnalyse.columns), minimum, maximum)
factorFrame.Show(True)
if factorFrame.ShowModal() == wx.ID_OK:
self.controller.storeData()
self.m_undo.SetText("Undo add new column")
self.m_undo.Enable()
factorsFromInterface, self.selectedRadioButton, tagRestValues, nameOfFactor = factorFrame.returnFactors()
self.controller.addColumn(factorsFromInterface, self.selectedRadioButton, tagRestValues, nameOfFactor)
self.refreshGUI()
numCols = self.controller.getNumberOfColumns()
self.m_dataTable.SetGridCursor(0, numCols - 1)
self.m_dataTable.MakeCellVisible(0, numCols - 1)
self.m_dataTable.SelectCol(numCols - 1)
else:
wx.MessageBox("There are no numerical values", "ERROR")
def createBasicStatisticsInterface(self, event):
if (len(self.controller.integerValues + self.controller.floatValues) != 0):
self.tagsAndValues.clear()
for value in self.controller.characterValues:
listTags = list(self.controller.programState.dataToAnalyse[value].unique())
# listTags = [x for x in listTags if unicode(x).encode('utf-8') != 'nan']
listTags = [x for x in listTags if str(x) != 'nan']
self.tagsAndValues[value] = numpy.asarray(listTags)
# self.tagsAndValues[value] = self.controller.programState.dataToAnalyse[str(value)].unique()
dataFrame = self.controller.programState.dataToAnalyse
variablesList = self.controller.floatValues + self.controller.integerValues
minimum = int(self.controller.programState.dataToAnalyse.min(numeric_only=True).min().round()) - 1
maximum = int(self.controller.programState.dataToAnalyse.max(numeric_only=True).max().round()) + 1
basicStatsInterface = BasicStatisticsInterface(self, variablesList, self.tagsAndValues,
self.controller.integerValues, dataFrame)
if basicStatsInterface.ShowModal() == wx.ID_CLOSE:
basicStatsInterface.Destroy()
else:
wx.MessageBox("There are no numerical values in the data", "ERROR", wx.OK | wx.ICON_EXCLAMATION)
def doSignificanceTest(self, event):
if (len(self.controller.integerValues + self.controller.floatValues) != 0):
self.tagsAndValues.clear()
for value in self.controller.characterValues:
listTags = list(self.controller.programState.dataToAnalyse[value].unique())
listTags = [x for x in listTags if str(x) != 'nan']
# listTags = [x for x in listTags if unicode(x).encode('utf-8') != 'nan']
self.tagsAndValues[value] = numpy.asarray(listTags)
# self.tagsAndValues[value] = self.controller.programState.dataToAnalyse[str(value)].unique()
dataFrame = self.controller.programState.dataToAnalyse
variablesList = self.controller.floatValues + self.controller.integerValues
significanceTestFrame = SignificanceTestInterface(self, variablesList, self.tagsAndValues,
self.controller.integerValues, dataFrame)
significanceTestFrame.Show()
if significanceTestFrame.ShowModal() == wx.ID_CANCEL:
significanceTestFrame.Destroy()
else:
wx.MessageBox("There are no numerical values", "ERROR")
def createHistogram(self, event):
if (len(self.controller.integerValues + self.controller.floatValues) != 0):
histogramFrame = HistogramInterface(self, self.controller.floatValues + self.controller.integerValues,
self.controller.characterValues, self.histogramOptions)
if histogramFrame.ShowModal() == wx.ID_OK:
self.histogramOptions = histogramFrame.getHistogramOptions()
self.controller.createHistogram(self.histogramOptions)
else:
wx.MessageBox("There are no numerical values", "ERROR")
def createScatterPlot(self, event):
if (len(self.controller.integerValues + self.controller.floatValues) != 0):
scatterFrame = ScatterPlotInterface(self, self.controller.floatValues + self.controller.integerValues,
self.scatterPlotOptions)
if scatterFrame.ShowModal() == wx.ID_OK:
self.scatterPlotOptions = scatterFrame.getScatterPlotOptions()
self.controller.createScatterPlot(self.scatterPlotOptions)
else:
wx.MessageBox("There are no numerical values", "Attention")
def createPieChart(self, event):
if (len(self.controller.characterValues) != 0):
pieChartFrame = PieChartInterface(self, self.controller.characterValues, self.pieChartOptions)
if pieChartFrame.ShowModal() == wx.ID_OK:
self.pieChartOptions = pieChartFrame.getPieChartOptions()
self.controller.createPieChart(self.pieChartOptions)
else:
wx.MessageBox("There are no categorical variables", "ERROR")
def createBoxPlot(self, event):
if (len(self.controller.integerValues + self.controller.floatValues) != 0):
boxPlotFrame = BoxPlotInterface(self, self.controller.floatValues + self.controller.integerValues,
self.controller.characterValues, self.boxPlotOptions)
if boxPlotFrame.ShowModal() == wx.ID_OK:
self.boxPlotOptions = boxPlotFrame.getBoxPlotOptions()
self.controller.createBoxPlot(self.boxPlotOptions)
else:
wx.MessageBox("There are no numerical variables", "ERROR")
def createBarChart(self, event):
if (len(self.controller.integerValues + self.controller.floatValues) != 0):
barChartFrame = BarChartInterface(self, self.controller.floatValues + self.controller.integerValues,
self.controller.characterValues, self.barChartOptions)
if barChartFrame.ShowModal() == wx.ID_OK:
self.barChartOptions = barChartFrame.getBarChartOptions()
self.controller.createBarChart(self.barChartOptions)
else:
wx.MessageBox("There are no numerical variables", "ERROR")
def showWarning(self):
dlg = wx.MessageDialog(None, "Lower limit must be smaller than the upper limit", "Be careful!",
wx.OK | wx.ICON_EXCLAMATION)
if dlg.ShowModal() == wx.ID_OK:
dlg.Destroy()
def informationAboutNullValues(self):
dlg = wx.MessageDialog(None, "There are null values in this File", "Null Values", wx.OK | wx.ICON_INFORMATION)
if dlg.ShowModal() == wx.ID_OK:
dlg.Destroy()
def appInformation(self, event):
description = u'Graphical Application for Statistical Analysis of TAbulated Data\n\nDaniel Pereira Alonso\nLeandro Rodr\u00EDguez Liñares\nMar\u00EDa Jos\u00E9 Lado Touriño'
info = wx.adv.AboutDialogInfo()
info.SetName('GASATaD')
info.SetVersion(str(self.params['version']))
info.SetDescription(description)
info.SetCopyright(u"\u00A9 2019");
info.SetIcon(wx.Icon(os.path.dirname(os.path.abspath(__file__)) + "/GasatadLogo.ico", wx.BITMAP_TYPE_ICO))
info.SetWebSite("https://milegroup.github.io/gasatad/")
wx.adv.AboutBox(info)
def closeApp(self, event):
emptyData = False
try:
emptyData = self.controller.programState.dataToAnalyse.empty
except:
emptyData = True
if not emptyData:
dlg = wx.MessageDialog(self, "Do you really want to close GASATaD?", "Confirm Exit",
wx.OK | wx.CANCEL | wx.ICON_QUESTION | wx.CANCEL_DEFAULT)
result = dlg.ShowModal()
dlg.Destroy()
if result == wx.ID_OK:
self.configSave()
self.Destroy()
else:
self.configSave()
self.Destroy()
def configInit(self):
"""If config dir and file does not exist, it is created
If config file exists, it is loaded"""
# print "Intializing configuration"
if not os.path.exists(self.params['configDir']):
# print "Directory does not exists ... creating"
os.makedirs(self.params['configDir'])
if os.path.exists(self.params['configFile']):
# print "Loading config"
self.configLoad()
else:
# print "Saving config"
self.configSave()
def configSave(self):
""" Saves configuration file"""
try:
# from ConfigParser import SafeConfigParser
# options = SafeConfigParser()
import configparser
options = configparser.ConfigParser()
options.add_section('gasatad')
for param in self.params['options'].keys():
# In windows, if the path contains non-ascii characters, it is not saved in the configuration file
validParam = True
if param == "dirfrom" and sys.platform == "win32":
tmpStr = self.params['options'][param]
if any(ord(char) > 126 for char in tmpStr):
validParam = False
if validParam:
options.set('gasatad', param, self.params['options'][param])
# print " ",param," - ",self.params['options'][param]
tempF = open(self.params['configFile'], 'w')
# print("Trying to write configuration in ", self.params['configFile'])
options.write(tempF)
tempF.close()
if platform == "win32":
import win32api, win32con
win32api.SetFileAttributes(self.params['configDir'], win32con.FILE_ATTRIBUTE_HIDDEN)
except:
return
def configLoad(self):
""" Loads configuration file"""
# print "Loading file",self.params['configFile']
try:
import configparser
options = configparser.ConfigParser()
options.read(self.params['configFile'])
for section in options.sections():
for param, value in options.items(section):
self.params['options'][param] = value
# print "param",param," - value",value
except:
# print "Problem loading configuration file", self.params['configFile']
try:
os.remove(self.params['configFile'])
except:
pass
return
class ReplaceInColInterface(wx.Dialog):
def __init__(self, parent, listOfTags):
wx.Dialog.__init__(self, parent, id=wx.ID_ANY, title="Replace in column", size=wx.DefaultSize,
pos=wx.DefaultPosition)
mainSizer = wx.BoxSizer(wx.VERTICAL)
topSizer = wx.BoxSizer(wx.HORIZONTAL)
leftSizer = wx.BoxSizer(wx.VERTICAL)
leftSizer.Add(wx.StaticText(self, -1, "Old value:"))
self.cb = wx.ComboBox(self, choices=listOfTags, value=listOfTags[0], size=(160, -1))
leftSizer.Add(self.cb, 0, wx.TOP | wx.LEFT, 5)
topSizer.Add(leftSizer, 0, wx.ALL, 10)
rightSizer = wx.BoxSizer(wx.VERTICAL)
rightSizer.Add(wx.StaticText(self, -1, "New value (empty for 'null'):"))
self.tc = wx.TextCtrl(self, size=(160, -1))
rightSizer.Add(self.tc, 0, wx.TOP | wx.LEFT | wx.EXPAND, 5)
topSizer.Add(rightSizer, 0, wx.ALL, 10)
mainSizer.Add(topSizer)
# Ok and Cancel buttons
okay = wx.Button(self, wx.ID_OK)
cancel = wx.Button(self, wx.ID_CANCEL)
btns = wx.StdDialogButtonSizer()
btns.AddButton(okay)
btns.AddButton(cancel)
btns.Realize()
mainSizer.Add(btns, 0, wx.BOTTOM | wx.ALIGN_RIGHT, 10)
mainSizer.Fit(self)
self.SetSizer(mainSizer)
self.Layout()
self.Fit()
self.Centre(wx.BOTH)
self.Show(True)
def getValues(self):
return self.cb.GetValue(), self.tc.GetValue()
class DeleteColumnsInterface(wx.Dialog):
def __init__(self, parent, listOfColumns):
# The dictionary is initialized -> Key = name of column; value = False (because neither checkbox is selected yet)
self.selectedColumns = dict.fromkeys(listOfColumns, False)
wx.Dialog.__init__(self, parent, id=wx.ID_ANY, title="Delete columns", pos=wx.DefaultPosition,
size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL)
gbSizer1 = wx.GridBagSizer(0, 0)
gbSizer1.SetFlexibleDirection(wx.BOTH)
gbSizer1.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_SPECIFIED)
# Sizer where the names of the columns are placed
fgSizerCheckBoxColumns = wx.FlexGridSizer(0, 4, 0, 0)
fgSizerCheckBoxColumns.SetFlexibleDirection(wx.BOTH)
fgSizerCheckBoxColumns.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_SPECIFIED)
fgSizerCheckBoxColumns.AddGrowableCol(1)
for column in listOfColumns:
self.m_checkBox = wx.CheckBox(self, wx.ID_ANY, str(column), wx.DefaultPosition, wx.DefaultSize, 0)
fgSizerCheckBoxColumns.Add(self.m_checkBox, 0, wx.EXPAND | wx.ALL, 5)
self.Bind(wx.EVT_CHECKBOX, self.changeValueCheckBox, self.m_checkBox)
gbSizer1.Add(fgSizerCheckBoxColumns, wx.GBPosition(0, 0), wx.GBSpan(1, 1), wx.ALIGN_RIGHT | wx.EXPAND | wx.ALL,
5)
# Ok and Cancel buttons
okay = wx.Button(self, wx.ID_OK)
cancel = wx.Button(self, wx.ID_CANCEL)
btns = wx.StdDialogButtonSizer()
btns.AddButton(okay)
btns.AddButton(cancel)
btns.Realize()
gbSizer1.Add(btns, wx.GBPosition(1, 0), wx.GBSpan(1, 1), wx.BOTTOM | wx.ALIGN_RIGHT, 10)
self.SetSizer(gbSizer1)
gbSizer1.Fit(self)
self.Layout()
self.Fit()
self.Centre(wx.BOTH)
self.Show(True)
def changeValueCheckBox(self, event):
checkBox = event.GetEventObject()
if checkBox.IsChecked():
self.selectedColumns[checkBox.GetLabel()] = True
else:
self.selectedColumns[checkBox.GetLabel()] = False
def getSelectedColumns(self):
listSelectedColumns = []
for key in self.selectedColumns.keys():
if self.selectedColumns[key]:
listSelectedColumns.append(key)
return listSelectedColumns
class ExportCsvOptions(wx.Dialog):
def __init__(self, parent):
self.exportOptions = OptionsInExportInterface()
wx.Dialog.__init__(self, parent, id=wx.ID_ANY, title="Export csv", pos=wx.DefaultPosition, size=wx.DefaultSize,
style=wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL)
self.SetSizeHints(wx.DefaultSize, wx.DefaultSize)
gbSizer1 = wx.GridBagSizer(0, 0)
gbSizer1.SetFlexibleDirection(wx.BOTH)
gbSizer1.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_SPECIFIED)
# Sizer for the options
fgSizerExportOptions = wx.FlexGridSizer(0, 2, 0, 0)
fgSizerExportOptions.SetFlexibleDirection(wx.BOTH)
fgSizerExportOptions.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_SPECIFIED)
fgSizerExportOptions.AddGrowableCol(1)
self.characterSet = wx.StaticText(self, wx.ID_ANY, u"Character set:", wx.DefaultPosition, wx.DefaultSize, 0)
self.characterSet.Wrap(-1)
fgSizerExportOptions.Add(self.characterSet, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5)
m_comboBox3Choices = ["UTF-8", "ASCII", "Latin_1"]
self.m_comboBox3 = wx.ComboBox(self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize,
m_comboBox3Choices, wx.CB_READONLY)
self.m_comboBox3.SetSelection(0)
self.Bind(wx.EVT_COMBOBOX, self.setCharacterSetValue, self.m_comboBox3)
fgSizerExportOptions.Add(self.m_comboBox3, 0, wx.ALL | wx.EXPAND | wx.ALIGN_CENTER_VERTICAL, 5)
self.xAxisName = wx.StaticText(self, wx.ID_ANY, u"Field delimiter:", wx.DefaultPosition, wx.DefaultSize, 0)
self.xAxisName.Wrap(-1)
fgSizerExportOptions.Add(self.xAxisName, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5)
m_comboBox3Choices = [",", ";", ":", "{Tab}", "{Space}"]
self.m_comboBox3 = wx.ComboBox(self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize,
m_comboBox3Choices, wx.CB_READONLY)
self.m_comboBox3.SetSelection(0)
self.Bind(wx.EVT_COMBOBOX, self.setFieldDelimiterValue, self.m_comboBox3)
fgSizerExportOptions.Add(self.m_comboBox3, 0, wx.ALL | wx.EXPAND | wx.ALIGN_CENTER_VERTICAL, 5)
self.yAxisName = wx.StaticText(self, wx.ID_ANY, u"Decimal separator:", wx.DefaultPosition, wx.DefaultSize, 0)
self.yAxisName.Wrap(-1)
fgSizerExportOptions.Add(self.yAxisName, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5)
m_comboBox3Choices = [".", ","]
self.m_comboBox3 = wx.ComboBox(self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize,
m_comboBox3Choices, wx.CB_READONLY)
self.m_comboBox3.SetSelection(0)
self.Bind(wx.EVT_COMBOBOX, self.setDecimalSeparatorValue, self.m_comboBox3)
fgSizerExportOptions.Add(self.m_comboBox3, 0, wx.ALL | wx.EXPAND | wx.ALIGN_CENTER_VERTICAL, 5)
gbSizer1.Add(fgSizerExportOptions, wx.GBPosition(0, 0), wx.GBSpan(1, 1), wx.EXPAND | wx.ALL, 5)
# Additional options
AdditionalOptSizer = wx.StaticBoxSizer(wx.StaticBox(self, wx.ID_ANY, u"Additional options"), wx.HORIZONTAL)
self.wColumnNames = wx.CheckBox(self, wx.ID_ANY, "Write column names", wx.DefaultPosition, wx.DefaultSize, 0)
AdditionalOptSizer.Add(self.wColumnNames, 0, wx.ALL, 10)
self.wColumnNames.SetValue(True)
self.Bind(wx.EVT_CHECKBOX, self.setWriteColumnNameValue, self.wColumnNames)
self.wRowNames = wx.CheckBox(self, wx.ID_ANY, "Write row names (Index)", wx.DefaultPosition, wx.DefaultSize, 0)
AdditionalOptSizer.Add(self.wRowNames, 0, wx.ALL, 10)
self.wRowNames.SetValue(True)
self.Bind(wx.EVT_CHECKBOX, self.setWriteRowNames, self.wRowNames)
gbSizer1.Add(AdditionalOptSizer, wx.GBPosition(1, 0), wx.GBSpan(1, 1), wx.ALL, 20)
# Ok and Cancel buttons
okay = wx.Button(self, wx.ID_OK)
cancel = wx.Button(self, wx.ID_CANCEL)
btns = wx.StdDialogButtonSizer()
btns.AddButton(okay)
btns.AddButton(cancel)
btns.Realize()
gbSizer1.Add(btns, wx.GBPosition(3, 0), wx.GBSpan(1, 1), wx.EXPAND | wx.ALL, 5)
self.SetSizer(gbSizer1)
gbSizer1.Fit(self)
self.Layout()
self.Fit()
self.Centre(wx.BOTH)
self.Fit()
self.Show(True)
def setCharacterSetValue(self, event):
option = event.GetEventObject().GetValue().lower()
self.exportOptions.setCharacterSet(option)
def setFieldDelimiterValue(self, event):
option = event.GetEventObject().GetValue()
if option == "{Tab}":
self.exportOptions.setFieldDelimiter("\t")
elif option == "{Space}":
self.exportOptions.setFieldDelimiter(" ")
else:
self.exportOptions.setFieldDelimiter(option)
def setDecimalSeparatorValue(self, event):
option = event.GetEventObject().GetValue()
self.exportOptions.setdecimalSeparator(option)
def setWriteColumnNameValue(self, event):
option = event.GetEventObject().GetValue()
self.exportOptions.setWriteColNames(option)
def setWriteRowNames(self, event):
option = event.GetEventObject().GetValue()
self.exportOptions.setWriteRowNames(option)
def getSelectedExportOptions(self):
return self.exportOptions
|
"The key message on the night was - don't wait until it is too late to seek help," Mr Clare said.
"If you are struggling to keep up with your mortgage repayments talk to your bank or a financial counsellor.
"Free and independent advice is available. Good organisations like The Smith Family and Bankstown based NGO Creating Links can help with free financial advice and help you learn to budget.
"If you have received a default notice from the bank you have to act quickly. You only have 30 days before the bank can take you to court and repossess your home. If you get one of these notices please contact Legal Aid or the Consumer Credit Legal Centre straight away," Mr Clare said.
Another issue that was raised on the night was - is it is a good idea to use your superannuation to help pay the mortgage.
The panel of experts agreed that is only a good idea in very limited circumstances. Before doing this you should seek independent financial advice.
The Housing Stress Information Night was organised by Jason Clare MP, the Federal Member for Blaxland.
"A lot of people are doing it really tough here. More homes are repossessed in our local community than any where else in Australia.
"That's why I organised this information night. To help people doing it tough. To provide real practical advice. I hope it helps to save a few homes.
"This is the sort of thing politicians should do," Mr Clare said.
|
# -*- coding: utf-8 -*-
# (c) 2015 Oihane Crucelaegui - AvanzOSC
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
from openerp import api, fields, models
from openerp.addons import decimal_precision as dp
class ProductAttributeConfigurator(models.AbstractModel):
_name = 'product.attribute.configurator'
@api.one
@api.depends('attribute')
def _get_possible_attribute_values(self):
self.possible_values = self.attribute.value_ids.sorted()
@api.one
@api.depends('value')
def _get_price_extra(self):
self.price_extra = sum(self.value.mapped('price_ids.price_extra'))
attribute = fields.Many2one(comodel_name='product.attribute',
string='Attribute')
value = fields.Many2one(comodel_name='product.attribute.value',
domain="[('attribute_id', '=', attribute),"
"('id', 'in', possible_values[0][2])]",
string='Value')
possible_values = fields.Many2many(
comodel_name='product.attribute.value',
compute='_get_possible_attribute_values')
price_extra = fields.Float(
compute='_get_price_extra', string='Attribute Price Extra',
digits=dp.get_precision('Product Price'),
help="Price Extra: Extra price for the variant with this attribute"
" value on sale price. eg. 200 price extra, 1000 + 200 = 1200.")
class ProductProductAttribute(models.Model):
_inherit = 'product.attribute.configurator'
_name = 'product.product.attribute'
@api.one
@api.depends('attribute', 'product.product_tmpl_id',
'product.product_tmpl_id.attribute_line_ids')
def _get_possible_attribute_values(self):
attr_values = self.env['product.attribute.value']
for attr_line in self.product.product_tmpl_id.attribute_line_ids:
if attr_line.attribute_id.id == self.attribute.id:
attr_values |= attr_line.value_ids
self.possible_values = attr_values.sorted()
@api.one
@api.depends('value', 'product.product_tmpl_id')
def _get_price_extra(self):
price_extra = 0.0
for price in self.value.price_ids:
if price.product_tmpl_id.id == self.product.product_tmpl_id.id:
price_extra = price.price_extra
self.price_extra = price_extra
product = fields.Many2one(
comodel_name='product.product', string='Product')
|
Plainly know-how has advanced extra rapidly prior to now decade or so than ever earlier than. Technology corporations normally market and promote products by emphasizing value, special features and technical specs as a result of these criteria are seen as most necessary by the engineers and scientists who typically run excessive tech companies.
In Chandler, AZ. Picture Tag sells a software called Kwik Tag that helps corporations manage document circulation by enabling users to create digital copies that can be retrieved on demand from a “virtual file cupboard.” Just about each company has issues managing the vast amounts of paper that flow into by means of the office.
Montauk, America’s Greatest Unknown Conspiracy involves mind management experiments, weather manipulation, star gate technology, telepathy, UFOs, Aliens, Nazi’s, pyramids, sleeper agents, Aleister Crowley and black magic, time travel and time ‘police’, distant viewing, Deep Underground Navy Bases (D.U.M.B.s) and above all an unimaginable amount of synchronicity that can’t be simply defined as mere coincidence.
The accord pledges to guard towards tampering with and exploitation of know-how services throughout their improvement, design, distribution and use.†This is seen as a pushback by the technology industry after former National Security Agency contractor Edward Snowden revealed that the United States government could also be intercepting pc hardware and injecting software program to collect knowledge.
The viewer is the typical Joe or Jane who consumes the content, typically without spending a dime; the supplier is the content maker, for example the manufacturing home that makes tv collection, and the advertiser is often a advertising agency that has a direct relationship with the tv firm.
|
# Copyright 2013 Gary Baumgartner
# Distributed under the terms of the GNU General Public License.
#
# This file is part of Assignment 1, CSC148, Fall 2013.
#
# This is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This file is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this file. If not, see <http://www.gnu.org/licenses/>.
from DomainStools import DomainStools
from DomainStools import Cheese
import math
def tour_of_four_stools(n: int, stools: DomainStools) -> None:
"""Move an n cheese tower from the first stool in stools to the fourth.
n - number of cheeses on the first stool of stools
stools - a DomainStools with a tower of cheese on the first stool
and three other empty stools
"""
tour_helper(n, stools, 0, 1, 2, 3)
def tour_helper(n: int, stools: DomainStools, input: int, aux1: int, aux2: int, output: int) -> None:
if n == 1:
stools.move(stools.select_top_cheese(input), stools.select_top_cheese(output))
else:
i = math.ceil(n/2)
tour_helper(n-i, stools, input, aux2, output, aux1)
tour_of_three_stools(i, stools, input, aux2, output)
tour_helper(n-i, stools, aux1, input, aux2, output)
def tour_of_three_stools(n: int, stools: DomainStools, input: int, aux: int, output: int) -> None:
if n == 1:
stools.move(stools.select_top_cheese(input), stools.select_top_cheese(output))
else:
tour_of_three_stools(n-1, stools, input, output, aux)
tour_of_three_stools(1, stools, input, aux, output)
tour_of_three_stools(n-1, stools, aux, input, output)
if __name__ == '__main__':
four_stools = DomainStools(4)
for s in range(7, 0, -1):
four_stools.add(0, Cheese(s))
tour_of_four_stools(7, four_stools)
print(four_stools.number_of_moves())
#three_stools = DomainStools(3)
#for s in range(15, 0, -1):
# three_stools.add(0, Cheese(s))
#tour_of_three_stools(15, three_stools, 0, 1, 2)
#print(three_stools.number_of_moves())
|
With the pace of work at an all-time high, leaders often overlook the importance of ensuring that their teams are galvanized and focused around a collective mission. The composition of groups and teams can shift rapidly creating the need to fortify relationships and revisit priorities on a regular basis. To address these realities, we offer a structured teambuilding design that is focused and practical – and an enjoyable change of pace. Because we understand the challenges that teams typically face, we help them diagnose and remedy issues in the following broad areas: goal setting and direction, change management, communication, personality styles, and shared values and norms. Whether you are the leader of a newly formed team or the leader of a mature team that needs a tune-up, a retreat can jumpstart your efforts to ensure that your team is operating at its peak capacity and able to accomplish its goals and objectives with minimal distraction.
A small private school for children with special needs brought Leadership Solutions in to identify key issues impeding the Board's overall effectiveness, and support development of a plan forward. We began by interviewing Board members to better understand their personal experience on the Board, and followed up by facilitating discussions and conducting teambuilding exercises to address the issues that emerged. Additionally, we assisted the Board in revisiting its structure and composition, and identified key actions to ensure the Board remained on target for the current year's goals and objectives. Overall, the retreat was a celebrated success, allowing the Board to regroup and refocus their time and efforts in a direction that would help ensure longer term success for the school they so passionately supported.
|
import os
import sys
class BaseException(Exception):
"""
BaseException class for all the others
exceptions defined for this app.
"""
def __init__(self, message, cause=None, *args, **kwargs):
"""
BaseException gets a message and a cause. These params
will be displayed when the program raises an exception that
is a child of this class.
:param message: obligatory
:param cause: might be None
"""
super(Exception, self).__init__()
self.message = message
self.cause = cause
try:
exc_type, exc_obj, exc_tb = sys.exc_info()
self.filename = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
self.fileline = exc_tb.tb_lineno
except Exception, e:
print args, kwargs
self.filename = ""
self.fileline = ""
def __str__(self):
"""
Override the str method for all the exceptions.
:return: str
"""
# Get the exception class name
exception_class_name = self.__class__.__name__
# This is the str
to_return = "%s: %s"%(exception_class_name, self.message)
if self.cause:
# Get the str of the cause
to_return += "\r\nError at {filename}@{line}. Caused by: {cause}".format(
filename=self.filename,
line=self.fileline,
cause=self.cause
)
return to_return
def __repr__(self):
"""
Override the __repr__ method for all the exceptions.
:return: str
"""
return str(self)
|
Call us at 208-498-1700 today.
Dr. Martinez would like to welcome you to his practice. Dr. Martinez and his team strive to provide the best in ophthalmology services. We invite you to browse our website to learn more about our services and join our patient family by scheduling an appointment at our Nampa office.
Dr. Martinez is a general ophthalmologist providing vision and surgical care. We accept both eye emergencies as well as scheduled appointments. Patients throughout the Treasure Valley come to Dr. Martinez because they know they will receive the personal attention and professional care that is our foundation. Our team is dedicated to keeping our patients comfortable and well-informed at all times. At Dr. Martinez office, we will explain every exam and procedure and answer all of our patients' questions.
Our one-on-one approach to ophthalmology makes Dr. Martinez and his staff the eye and vision care providers of choice in the Treasure Valley. Our ophthalmology practice offers the following services: complete eye exams, contact lenses, glasses, glaucoma testing, and pre- and post-operative care. For a complete list of services, visit our services page or call our office at 208-498-1700.
At our practice, we are dedicated to providing high-quality medical and surgical eye care services in a comfortable environment. Call us at 208-498-1700 and schedule an appointment today.
Jorge A. Martinez, M.D. is an Ophthalmologist specializing in cataract, laser and advanced vision correction surgery. He received his doctor of medicine degree from Tulane University School of Medicine in New Orleans. His postgraduate training was taken at the Naval Medical Center in San Diego, California.
"Staff is always courteous and engaging to the patient. Thanks you all for the pleasant experience, including you Dr. Martinez!"
"We appreciate Dr’s “hands on” approach. Very refreshing!"
"Friendly staff. Excellent experience. Would definitely recommend Dr. Martinez to others."
"Dr. Martinez is very good at making you feel comfortable and relaxed. Everyone has been so helpful and good at their job. Thanks to all of you."
|
from __future__ import (absolute_import, division, print_function)
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import pyqtSignal as Signal
import sys
from Muon.GUI.Common.utilities import table_utils
from Muon.GUI.Common import message_box
group_table_columns = {0: 'group_name', 1: 'detector_ids', 2: 'number_of_detectors'}
class GroupingTableView(QtGui.QWidget):
# For use by parent widget
dataChanged = Signal()
addPairRequested = Signal(str, str)
@staticmethod
def warning_popup(message):
message_box.warning(str(message))
def __init__(self, parent=None):
super(GroupingTableView, self).__init__(parent)
self.grouping_table = QtGui.QTableWidget(self)
self.set_up_table()
self.setup_interface_layout()
self.grouping_table.cellChanged.connect(self.on_cell_changed)
self._validate_group_name_entry = lambda text: True
self._validate_detector_ID_entry = lambda text: True
self._on_table_data_changed = lambda: 0
# whether the table is updating and therefore we shouldn't respond to signals
self._updating = False
# whether the interface should be disabled
self._disabled = False
def setup_interface_layout(self):
self.setObjectName("GroupingTableView")
self.resize(500, 500)
self.add_group_button = QtGui.QToolButton()
self.remove_group_button = QtGui.QToolButton()
self.group_range_label = QtGui.QLabel()
self.group_range_label.setText('Group Asymmetry Range from:')
self.group_range_min = QtGui.QLineEdit()
self.group_range_min.setEnabled(False)
positive_float_validator = QtGui.QDoubleValidator(0.0, sys.float_info.max, 5)
self.group_range_min.setValidator(positive_float_validator)
self.group_range_use_first_good_data = QtGui.QCheckBox()
self.group_range_use_first_good_data.setText(u"\u03BCs (From data file)")
self.group_range_use_first_good_data.setChecked(True)
self.group_range_max = QtGui.QLineEdit()
self.group_range_max.setEnabled(False)
self.group_range_max.setValidator(positive_float_validator)
self.group_range_use_last_data = QtGui.QCheckBox()
self.group_range_use_last_data.setText(u"\u03BCs (From data file)")
self.group_range_use_last_data.setChecked(True)
self.group_range_to_label = QtGui.QLabel()
self.group_range_to_label.setText('to:')
self.group_range_layout = QtGui.QGridLayout()
self.group_range_layout_min = QtGui.QHBoxLayout()
self.group_range_layout.addWidget(self.group_range_label, 0, 0)
self.group_range_layout.addWidget(self.group_range_min, 0, 1)
self.group_range_layout.addWidget(self.group_range_use_first_good_data, 0, 2)
self.group_range_layout_max = QtGui.QHBoxLayout()
self.group_range_layout.addWidget(self.group_range_to_label, 1, 0, QtCore.Qt.AlignRight)
self.group_range_layout.addWidget(self.group_range_max, 1, 1)
self.group_range_layout.addWidget(self.group_range_use_last_data, 1, 2)
size_policy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
size_policy.setHorizontalStretch(0)
size_policy.setVerticalStretch(0)
size_policy.setHeightForWidth(self.add_group_button.sizePolicy().hasHeightForWidth())
size_policy.setHeightForWidth(self.remove_group_button.sizePolicy().hasHeightForWidth())
self.add_group_button.setSizePolicy(size_policy)
self.add_group_button.setObjectName("addGroupButton")
self.add_group_button.setToolTip("Add a group to the end of the table")
self.add_group_button.setText("+")
self.remove_group_button.setSizePolicy(size_policy)
self.remove_group_button.setObjectName("removeGroupButton")
self.remove_group_button.setToolTip("Remove selected/last group(s) from the table")
self.remove_group_button.setText("-")
self.horizontal_layout = QtGui.QHBoxLayout()
self.horizontal_layout.setObjectName("horizontalLayout")
self.horizontal_layout.addWidget(self.add_group_button)
self.horizontal_layout.addWidget(self.remove_group_button)
self.spacer_item = QtGui.QSpacerItem(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Minimum)
self.horizontal_layout.addItem(self.spacer_item)
self.horizontal_layout.setAlignment(QtCore.Qt.AlignLeft)
self.vertical_layout = QtGui.QVBoxLayout(self)
self.vertical_layout.setObjectName("verticalLayout")
self.vertical_layout.addWidget(self.grouping_table)
self.vertical_layout.addLayout(self.horizontal_layout)
self.vertical_layout.addLayout(self.group_range_layout)
self.setLayout(self.vertical_layout)
def set_up_table(self):
self.grouping_table.setColumnCount(3)
self.grouping_table.setHorizontalHeaderLabels(["Group Name", "Detector IDs", "N Detectors"])
header = self.grouping_table.horizontalHeader()
header.setResizeMode(0, QtGui.QHeaderView.Stretch)
header.setResizeMode(1, QtGui.QHeaderView.Stretch)
header.setResizeMode(2, QtGui.QHeaderView.ResizeToContents)
vertical_headers = self.grouping_table.verticalHeader()
vertical_headers.setMovable(False)
vertical_headers.setResizeMode(QtGui.QHeaderView.ResizeToContents)
vertical_headers.setVisible(True)
self.grouping_table.horizontalHeaderItem(0).setToolTip("The name of the group :"
"\n - The name must be unique across all groups/pairs"
"\n - The name can only use digits, characters and _")
self.grouping_table.horizontalHeaderItem(1).setToolTip("The sorted list of detectors :"
"\n - The list can only contain integers."
"\n - , is used to separate detectors or ranges."
"\n - \"-\" denotes a range, i,e \"1-5\" is the same as"
" \"1,2,3,4,5\" ")
self.grouping_table.horizontalHeaderItem(2).setToolTip("The number of detectors in the group.")
def num_rows(self):
return self.grouping_table.rowCount()
def num_cols(self):
return self.grouping_table.columnCount()
def notify_data_changed(self):
if not self._updating:
self.dataChanged.emit()
# ------------------------------------------------------------------------------------------------------------------
# Adding / removing table entries
# ------------------------------------------------------------------------------------------------------------------
def add_entry_to_table(self, row_entries):
assert len(row_entries) == self.grouping_table.columnCount()
row_position = self.grouping_table.rowCount()
self.grouping_table.insertRow(row_position)
for i, entry in enumerate(row_entries):
item = QtGui.QTableWidgetItem(entry)
if group_table_columns[i] == group_table_columns[0]:
# column 0 : group name
group_name_widget = table_utils.ValidatedTableItem(self._validate_group_name_entry)
group_name_widget.setText(entry)
self.grouping_table.setItem(row_position, 0, group_name_widget)
self.grouping_table.item(row_position, 0).setToolTip(entry)
item.setFlags(QtCore.Qt.ItemIsEnabled)
item.setFlags(QtCore.Qt.ItemIsSelectable)
if group_table_columns[i] == group_table_columns[1]:
# column 1 : detector IDs
detector_widget = table_utils.ValidatedTableItem(self._validate_detector_ID_entry)
detector_widget.setText(entry)
self.grouping_table.setItem(row_position, 1, detector_widget)
self.grouping_table.item(row_position, 1).setToolTip(entry)
if group_table_columns[i] == group_table_columns[2]:
# column 2 : number of detectors
item.setFlags(QtCore.Qt.ItemIsEnabled)
item.setFlags(QtCore.Qt.ItemIsSelectable)
self.grouping_table.setItem(row_position, i, item)
def _get_selected_row_indices(self):
return list(set(index.row() for index in self.grouping_table.selectedIndexes()))
def get_selected_group_names(self):
indexes = self._get_selected_row_indices()
return [str(self.grouping_table.item(i, 0).text()) for i in indexes]
def remove_selected_groups(self):
indices = self._get_selected_row_indices()
for index in reversed(sorted(indices)):
self.grouping_table.removeRow(index)
def remove_last_row(self):
last_row = self.grouping_table.rowCount() - 1
if last_row >= 0:
self.grouping_table.removeRow(last_row)
def enter_group_name(self):
new_group_name, ok = QtGui.QInputDialog.getText(self, 'Group Name', 'Enter name of new group:')
if ok:
return new_group_name
# ------------------------------------------------------------------------------------------------------------------
# Context menu on right-click in the table
# ------------------------------------------------------------------------------------------------------------------
def _context_menu_add_group_action(self, slot):
add_group_action = QtGui.QAction('Add Group', self)
if len(self._get_selected_row_indices()) > 0:
add_group_action.setEnabled(False)
add_group_action.triggered.connect(slot)
return add_group_action
def _context_menu_remove_group_action(self, slot):
if len(self._get_selected_row_indices()) > 1:
# use plural if >1 item selected
remove_group_action = QtGui.QAction('Remove Groups', self)
else:
remove_group_action = QtGui.QAction('Remove Group', self)
if self.num_rows() == 0:
remove_group_action.setEnabled(False)
remove_group_action.triggered.connect(slot)
return remove_group_action
def _context_menu_add_pair_action(self, slot):
add_pair_action = QtGui.QAction('Add Pair', self)
if len(self._get_selected_row_indices()) != 2:
add_pair_action.setEnabled(False)
add_pair_action.triggered.connect(slot)
return add_pair_action
def contextMenuEvent(self, _event):
"""Overridden method"""
self.menu = QtGui.QMenu(self)
self.add_group_action = self._context_menu_add_group_action(self.add_group_button.clicked.emit)
self.remove_group_action = self._context_menu_remove_group_action(self.remove_group_button.clicked.emit)
self.add_pair_action = self._context_menu_add_pair_action(self.add_pair_requested)
if self._disabled:
self.add_group_action.setEnabled(False)
self.remove_group_action.setEnabled(False)
self.add_pair_action.setEnabled(False)
self.menu.addAction(self.add_group_action)
self.menu.addAction(self.remove_group_action)
self.menu.addAction(self.add_pair_action)
self.menu.popup(QtGui.QCursor.pos())
# ------------------------------------------------------------------------------------------------------------------
# Slot connections
# ------------------------------------------------------------------------------------------------------------------
def on_user_changes_group_name(self, slot):
self._validate_group_name_entry = slot
def on_user_changes_detector_IDs(self, slot):
self._validate_detector_ID_entry = slot
def on_add_group_button_clicked(self, slot):
self.add_group_button.clicked.connect(slot)
def on_remove_group_button_clicked(self, slot):
self.remove_group_button.clicked.connect(slot)
def on_table_data_changed(self, slot):
self._on_table_data_changed = slot
def add_pair_requested(self):
selected_names = self.get_selected_group_names()
self.addPairRequested.emit(selected_names[0], selected_names[1])
def on_cell_changed(self, _row, _col):
if not self._updating:
self._on_table_data_changed(_row, _col)
def on_user_changes_min_range_source(self, slot):
self.group_range_use_first_good_data.stateChanged.connect(slot)
def on_user_changes_max_range_source(self, slot):
self.group_range_use_last_data.stateChanged.connect(slot)
def on_user_changes_group_range_min_text_edit(self, slot):
self.group_range_min.editingFinished.connect(slot)
def on_user_changes_group_range_max_text_edit(self, slot):
self.group_range_max.editingFinished.connect(slot)
# ------------------------------------------------------------------------------------------------------------------
#
# ------------------------------------------------------------------------------------------------------------------
def get_table_item_text(self, row, col):
return self.grouping_table.item(row, col).text()
def get_table_contents(self):
if self._updating:
return []
ret = []
for row in range(self.num_rows()):
row_list = []
for col in range(self.num_cols()):
row_list.append(str(self.grouping_table.item(row, col).text()))
ret.append(row_list)
return ret
def clear(self):
# Go backwards to preserve indices
for row in reversed(range(self.num_rows())):
self.grouping_table.removeRow(row)
# ------------------------------------------------------------------------------------------------------------------
# Enabling and disabling editing and updating of the widget
# ------------------------------------------------------------------------------------------------------------------
def disable_updates(self):
"""Usage : """
self._updating = True
def enable_updates(self):
"""Usage : """
self._updating = False
def disable_editing(self):
self.disable_updates()
self._disabled = True
self._disable_buttons()
self._disable_all_table_items()
self._disable_group_ranges()
self.enable_updates()
def enable_editing(self):
self.disable_updates()
self._disabled = False
self._enable_buttons()
self._enable_all_table_items()
self._enable_group_ranges()
self.enable_updates()
def _enable_group_ranges(self):
self.group_range_use_first_good_data.setEnabled(True)
self.group_range_use_last_data.setEnabled(True)
if not self.group_range_use_first_good_data.isChecked():
self.group_range_min.setEnabled(True)
if not self.group_range_use_last_data.isChecked():
self.group_range_max.setEnabled(True)
def _disable_group_ranges(self):
self.group_range_use_first_good_data.setEnabled(False)
self.group_range_use_last_data.setEnabled(False)
self.group_range_min.setEnabled(False)
self.group_range_max.setEnabled(False)
def _enable_buttons(self):
self.add_group_button.setEnabled(True)
self.remove_group_button.setEnabled(True)
def _disable_buttons(self):
self.add_group_button.setEnabled(False)
self.remove_group_button.setEnabled(False)
def _disable_all_table_items(self):
for row in range(self.num_rows()):
for col in range(self.num_cols()):
item = self.grouping_table.item(row, col)
item.setFlags(QtCore.Qt.ItemIsSelectable)
def _enable_all_table_items(self):
for row in range(self.num_rows()):
for col in range(self.num_cols()):
item = self.grouping_table.item(row, col)
if group_table_columns[col] == 'detector_ids':
item.setFlags(QtCore.Qt.ItemIsSelectable |
QtCore.Qt.ItemIsEditable |
QtCore.Qt.ItemIsEnabled)
else:
# Group name and number of detectors should remain un-editable
item.setFlags(QtCore.Qt.ItemIsSelectable)
def get_group_range(self):
return str(self.group_range_min.text()), str(self.group_range_max.text())
def set_group_range(self, range):
self.group_range_min.setText(range[0])
self.group_range_max.setText(range[1])
|
I've changed the forum's mobile interface. The new one has a cleaner look and I'm hopeful it might render a better forum-browsing experience for folks. It's titled 'Mobile Mode' on the drop-down selector and it will auto launch anytime the site is loaded on a mobile device. The 'key' icon is the login link, whereas the 'grid' icon loads the navigation and control screen, and the 'magnifying glass' icon loads the search page. Of course, you may instead prefer to use the Full Site or Tapatalk if you like. If there are any questions please let me know.
|
# -*- coding: utf-8 -*-
from django.db import models
from questions.models import Question
from django.core.mail import send_mail
from django.conf import settings
class Candidate(models.Model):
name = models.CharField(max_length=200)
email = models.EmailField()
def __unicode__(self):
return u'{0} - {1}'.format(self.name, self.email)
def send_mail(self):
questions_id = Answer.objects.filter(candidate=self, grade__gte=7).values_list('question_id')
questions = [question.lower().strip() for question in Question.objects.filter(id__in=questions_id).values_list('question_text', flat=True)]
default_mail = True
if 'html' in questions and 'css' in questions and 'javascript' in questions:
default_mail = False
print 'Front-End'
send_mail('Obrigado por se candidatar', '''Obrigado por se candidatar, assim que tivermos uma vaga disponível
para programador Front-End entraremos em contato.''' , 'joelmir.ribacki@gmail.com',[self.email], fail_silently=False)
if 'python' in questions and 'django' in questions:
default_mail = False
print 'Back-End'
send_mail('Obrigado por se candidatar', '''Obrigado por se candidatar, assim que tivermos uma vaga disponível
para programador Back-End entraremos em contato.''' , 'joelmir.ribacki@gmail.com',[self.email], fail_silently=False)
if 'desenvolvedor ios' in questions or 'desenvolvedor android' in questions:
default_mail = False
print 'Mobile'
send_mail('Obrigado por se candidatar', '''Obrigado por se candidatar, assim que tivermos uma vaga disponível
para programador Mobile entraremos em contato.''' , 'joelmir.ribacki@gmail.com',[self.email], fail_silently=False)
if default_mail:
print 'Default: ', self.email
send_mail('Obrigado por se candidatar', '''Obrigado por se candidatar, assim que tivermos uma vaga disponível
para programador entraremos em contato.''' , settings.DEFAULT_FROM ,[self.email], fail_silently=False)
class Answer(models.Model):
candidate = models.ForeignKey(Candidate)
question = models.ForeignKey(Question)
grade = models.IntegerField()
def __unicode__(self):
return u'{0} - {1} - {2}'.format(self.candidate.name, self.question, self.grade)
|
I downloaded the actual Release of the Sneak Preview and after finishing the install, at first start up of the Netweaver Studio, an error occured.
Below you find the content of the .log file from my workspace directory.
If I startup Eclipse directly from its home-directory, it starts up the normal way, only the SAPIde brings up problems.
Thanks for any advice on this topic.
!MESSAGE Problems occurred while restoring the workspace.
!MESSAGE The project description file (.project) for john is missing. This file contains important information about the project. The project will not function properly until this file is restored.
Caused by: java.lang.NumberFormatException: For input string: "//phproxy.fra.hmrag.com"
It seems like eclipse is interpreting your directory "john..." as a project name. Please rename it into something without dots. I hope this helps.
seems that the real problem was because of a corrupted installation of the Java SDK.
I uninstalled it, restarted, reinstalled and the nalso uninstalled and reinstalled the Preview Edition, and surprise...everything works now!
Nevertehless thanks for your help.
|
import numpy as np
import ode
from CollisionAvoidanceMonitor.transform import Transformation
class GeometryBox(object):
def __init__(self, space, position=(0, 0, 0), size=(1, 1, 1), color=(1, 1, 1), oversize=1, name=None):
# Set parameters for drawing the body
self.color = color
self.size = list(size)
self.oversize = oversize
# Create a box geom for collision detection
self.geom = ode.GeomBox(space, lengths=[s + 2 + oversize for s in self.size])
self.geom.setPosition(position)
# A friendly name
self.name = name
# Set the size of the ODE geometry
def set_size(self, x=None, y=None, z=None, oversize=None):
# Only need to set the size of dimensions supplied
if x is not None:
self.size[0] = x
if y is not None:
self.size[1] = y
if z is not None:
self.size[2] = z
if oversize is not None:
self.oversize = oversize
self.geom.setLengths([s + 2 * self.oversize for s in self.size])
# Set the transform for the geometry
def set_transform(self, transform):
# Get the rotation and position elements from the transformation matrix
rot, pos = transform.get_rotation_matrix(), transform.get_position_matrix()
# Reshape the rotation matrix into a ODE friendly format
rot = np.reshape(rot, 9)
# Apply the translation and rotation to the ODE geometry
self.geom.setPosition(pos)
self.geom.setRotation(rot)
def get_transform(self):
t = Transformation()
t.join(self.geom.getRotation(), self.geom.getPosition())
return t
def get_vertices(self):
vertices = np.array([(-0.5, -0.5, 0.5),
(0.5, -0.5, 0.5),
(0.5, 0.5, 0.5),
(-0.5, 0.5, 0.5),
(-0.5, -0.5, -0.5),
(0.5, -0.5, -0.5),
(0.5, 0.5, -0.5),
(-0.5, 0.5, -0.5)])
vertices *= self.geom.getLengths()
t = self.get_transform()
vertices = [t.evaluate(v) for v in vertices]
return vertices
|
March 17, 2014, East Providence, Rhode Island - Plastics specialist igus has announced the release of its dry-tech® box, an ingenious sample kit designed to help engineers find the right material bearing for their application. The box contains a set of state-of-the-art card overlays, which filter the bearing choices by criteria - similar to the igus online configurator.
The dry-tech sample box includes a complete array of iglide® bearings, ranging from iglide H, which is ideal in corrosive environments, to iglide A350, which can withstand temperatures up to 356 º F, and are perfect for the food industry. The box also contains a user-friendly bearing guide that highlights the key properties of each bearing making the search for the perfect bearing simple and precise.
All igus bearings have dry-running properties, making them lubrication-free, maintenance-free, cost-effective, and long-lasting. iglide bearings are all fully lab tested in the areas of durability, friction, and stability, and are at the core of igus' plastics development.
For more information on the dry-tech box or dry-running iglide bearings, visit the dry-tech page at www.igus.com/iglide.
igus® develops industry-leading Energy Chain® cable carriers, Chainflex® continuous-flex cables, DryLin® linear bearings and linear guides, iglide® plastic bushings, and igubal® spherical bearings. These seemingly unrelated products are linked together through a belief in making functionally advanced, yet affordable plastic components and assemblies. With plastic bearing experience since 1964, cable carrier experience since 1971 and continuous-flex cable since 1989, igus provides the right solution from over 80,000 products available from stock. No minimum order required. For more information, contact igus at 1-800-521-2747 or visit www.igus.com.
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
from time import time
import locale
locale.setlocale(locale.LC_ALL, '')
code = locale.getpreferredencoding()
class scrollstring:
def __init__(self, content, START):
self.content = content # the true content of the string
self.display = content # the displayed string
self.START = START//1 # when this instance is created
self.update()
def update(self):
self.display = self.content
curTime = time()//1
offset = max(int((curTime - self.START) % len(self.content)) - 1, 0)
while offset > 0:
if self.display[0] > chr(127):
offset -= 1
self.display = self.display[3:] + self.display[:3]
else:
offset -= 1
self.display = self.display[1:] + self.display[:1]
# self.display = self.content[offset:] + self.content[:offset]
def __repr__(self):
return self.display
# determine the display length of a string
def truelen(string):
"""
It appears one Asian character takes two spots, but __len__
counts it as three, so this function counts the dispalyed
length of the string.
>>> truelen('abc')
3
>>> truelen('你好')
4
>>> truelen('1二3')
4
>>> truelen('')
0
"""
return len(string) - sum(1 for c in string if c > chr(127))/3
|
Paper new year greeting cards. Sold in sets of 7 cards.
Each order is for a set of 7 designs of Chinese new year greeting cards. On the cards are golden lucky Chinese items with Chinese symbols for new year greetings. 4.5" X 8.3" (11.5cm X 21cm), folded paper cards, inserts and envelopes included.
|
#!/usr/bin/env python
"""
Created on 1 Feb 2018
@author: loay
"""
import os
import sys
import time
from subprocess import *
import sigploit
import ss7main
simsi_path = os.path.join(os.getcwd(), 'ss7/attacks/fraud/simsi')
mtsms_path = os.path.join(os.getcwd(), 'ss7/attacks/fraud/mtsms')
cl_path = os.path.join(os.getcwd(), 'ss7/attacks/fraud/cl')
isd_path = os.path.join(os.getcwd(),'ss7/attacks/fraud/isd')
sai_path = os.path.join(os.getcwd(),'ss7/attacks/fraud/sai')
def simsi():
jar_file = 'SendIMSI.jar'
try:
sendIMSI = check_call(['java', '-jar', os.path.join(simsi_path, jar_file)])
if sendIMSI == 0:
fr = raw_input('\nWould you like to go back to Fraud Menu? (y/n): ')
if fr == 'y' or fr == 'yes':
ss7main.ss7fraud()
elif fr == 'n' or fr == 'no':
attack_menu = raw_input('Would you like to choose another attacks category? (y/n): ')
if attack_menu == 'y' or attack_menu == 'yes':
ss7main.attacksMenu()
elif attack_menu == 'n' or attack_menu == 'no':
main_menu = raw_input('Would you like to go back to the main menu? (y/exit): ')
if main_menu == 'y' or main_menu == 'yes':
sigploit.mainMenu()
elif main_menu == 'exit':
print 'TCAP End...'
sys.exit(0)
except CalledProcessError as e:
print "\033[31m[-]Error:\033[0m%s Failed to Launch, %s" %(jar_file, e.message)
time.sleep(2)
ss7main.ss7fraud()
def mtsms():
jar_file = 'MTForwardSMS.jar'
try:
mtForwardSMS = check_call(['java', '-jar', os.path.join(mtsms_path, jar_file)])
if mtForwardSMS == 0:
fr = raw_input('\nWould you like to go back to Fraud Menu? (y/n): ')
if fr == 'y' or fr == 'yes':
ss7main.ss7fraud()
elif fr == 'n' or fr == 'no':
attack_menu = raw_input('Would you like to choose another attacks category? (y/n): ')
if attack_menu == 'y' or attack_menu == 'yes':
ss7main.attacksMenu()
elif attack_menu == 'n' or attack_menu == 'no':
main_menu = raw_input('Would you like to go back to the main menu? (y/exit): ')
if main_menu == 'y' or main_menu == 'yes':
sigploit.mainMenu()
elif main_menu == 'exit':
print 'TCAP End...'
sys.exit(0)
except CalledProcessError as e:
print "\033[31m[-]Error:\033[0mMTForwardSMS Failed to Launch, " + str(e)
time.sleep(2)
ss7main.ss7fraud()
def cl():
jar_file = 'CancelLocation.jar'
try:
cancelLocation = check_call(['java', '-jar', os.path.join(cl_path, jar_file)])
if cancelLocation == 0:
fr = raw_input('\nWould you like to go back to Fraud Menu? (y/n): ')
if fr == 'y' or fr == 'yes':
ss7main.ss7fraud()
elif fr == 'n' or fr == 'no':
attack_menu = raw_input('Would you like to choose another attacks category? (y/n): ')
if attack_menu == 'y' or attack_menu == 'yes':
ss7main.attacksMenu()
elif attack_menu == 'n' or attack_menu == 'no':
main_menu = raw_input('Would you like to go back to the main menu? (y/exit): ')
if main_menu == 'y' or main_menu == 'yes':
sigploit.mainMenu()
elif main_menu == 'exit':
print 'TCAP End...'
sys.exit(0)
except CalledProcessError as e:
print "\033[31m[-]Error:\033[0mCancelLocation Failed to Launch, " + str(e)
time.sleep(2)
ss7main.ss7fraud()
def isd():
jar_file = 'InsertSubscriberData.jar'
try:
insertSD = check_call(['java','-jar', os.path.join(isd_path,jar_file)])
if insertSD == 0:
fr = raw_input('\nWould you like to go back to Fraud Menu? (y/n): ')
if fr == 'y' or fr == 'yes':
ss7main.Fraud()
elif fr == 'n' or fr == 'no':
attack_menu = raw_input('Would you like to choose another attacks category? (y/n): ')
if attack_menu == 'y'or attack_menu =='yes':
ss7main.attacksMenu()
elif attack_menu == 'n' or attack_menu =='no':
main_menu = raw_input('Would you like to go back to the main menu? (y/exit): ')
if main_menu == 'y' or main_menu =='yes':
sigploit.mainMenu()
elif main_menu =='exit':
print 'TCAP End...'
sys.exit(0)
except CalledProcessError as e:
print "\033[31m[-]Error:\033[0mInsertSubscriberData Failed to Launch, " + str(e)
time.sleep(2)
ss7main.ss7fraud()
def sai():
jar_file = 'SendAuthenticationInfo.jar'
try:
sendAuth = check_call(['java', '-jar', os.path.join(sai_path, jar_file)])
if sendAuth == 0:
fr = raw_input('\nWould you like to go back to Fraud Menu? (y/n): ')
if fr == 'y' or fr == 'yes':
ss7main.ss7fraud()
elif fr == 'n' or fr == 'no':
attack_menu = raw_input('Would you like to choose another attacks category? (y/n): ')
if attack_menu == 'y' or attack_menu == 'yes':
ss7main.attacksMenu()
elif attack_menu == 'n' or attack_menu == 'no':
main_menu = raw_input('Would you like to go back to the main menu? (y/exit): ')
if main_menu == 'y' or main_menu == 'yes':
sigploit.mainMenu()
elif main_menu == 'exit':
print 'TCAP End...'
sys.exit(0)
except CalledProcessError as e:
print "\033[31m[-]Error:\033[0m%s Failed to Launch, %s" %(jar_file, e.message)
time.sleep(2)
ss7main.ss7fraud()
|
The Peoples Democratic Party (PDP) Presidential candidate, Atiku Abubakar, has again warned the Federal Government and the military against meddling in the Nigerian democratic process, saying the military has no function in the country’s electoral process.
Mr. Abubakar issued the warning while he spoke at his campaign rally in Calabar, Cross River State on Friday at the U. J. Esuene stadium, lamenting the involvement of the Nigerian military during elections.
He said, “Let me caution the Federal Government and the military. The military are not supposed to get involved in elections, only the Police are supposed to maintain law and order.
The PDP Presidential candidate recalled that the first work he got in my life was given to me by someone from Cross River, assuring that, if elected, he will work with Governor Ben Ayade to actualise his industrial revolutions.
|
from ..token import Token
from .node import Node
from .constant import Constant
from .identifier import Identifier
from .expression import Expression
class Operand(Node):
"""
An operand.
"""
def __init__(self):
"""
Create the operand.
"""
self.value = None
@classmethod
def parse(cls, tokenizer, identifiers):
"""
Parse an operand.
"""
operand = Operand()
if tokenizer.get_token() == Token.INTEGER_CONSTANT:
operand.value = Constant.parse(tokenizer, identifiers)
elif tokenizer.get_token() == Token.IDENTIFIER:
operand.value = Identifier.parse(tokenizer, identifiers)
else:
cls.extract_token(tokenizer, Token.OPENING_PARENTHESIS)
operand.value = Expression.parse(tokenizer, identifiers)
cls.extract_token(tokenizer, Token.CLOSING_PARENTHESIS)
return operand
def evaluate(self, identifiers):
"""
Evaluate the operand and return its value.
"""
if isinstance(self.value, Expression):
return self.value.evaluate(identifiers)
elif isinstance(self.value, Identifier):
return identifiers.get_value(self.value.name)
else:
return self.value.value
def __str__(self):
"""
Human-readable string representation.
"""
parts = [self.value]
if isinstance(self.value, Expression):
parts = [
Token.OPENING_PARENTHESIS.value[1],
self.value,
Token.CLOSING_PARENTHESIS.value[1]]
return " ".join(map(lambda d: str(d), parts))
|
Posted on June 2, 2018 by Body. Booze. and Boys.
Ok so last night was a bit of a weird one… but overall fun. Following work, I went to the Trillium Beer Garden on the Greenway to meet up with two different groups of friends. My friend “Ike” was there and he insisted that include him in whatever blog post I write today… so hi Ike.
Following the beer garden, one of the groups went to another bar downtown and then to Felipe’s in Harvard Square, where we met up with Lucky.
He and I hadn’t really talked much since the last time I saw him after the baseball game, but I was glad to see him and I think we both were hoping to get some alone time… which of course didn’t happen.
See at that point people were still trying to do something so I was like “we can all go to my apartment”, not even thinking that would mess up my chances of booking up with Lucky. So a small group of us end up at my apartment and we drank a little and played LIFE (Yes, the game) until 4:00 in the morning. Shockingly I didn’t have any children and only bought one house. Lucky left with the other guys and idk if it was just me thinking it was awkward, but we didn’t even hug goodbye… sooo yeah.
Sooo maybe it doesn’t mean anything… but it seems like I might be subconsciously feeling guilty about wanting to hook up with Lucky again! What is that?!! As we all know, Coach and I are not exclusive and he has made no mention of a desire for us to be exclusive. And I keep going back and forth on if I’d even say yes if he asked. I mean… I think I might, but I’ve gotten so used to the freedom of not being in an exclusive relationship.
I had a long conversation about this whole not being exclusive thing with one of my best friends when he was visiting from DC. Anddddd while I don’t think there’s anything wrong with me wanting to “have my cake (Coach) and eat it too (others, including Lucky), I’m wondering if he has a point about not being able to maintain it.
Even my friend in Seattle just broke up with a guy she’d been seeing… not because she didn’t like him or enjoy spending time with him… but because she didn’t like him enough and didn’t see it going anywhere. Is that where I am with Coach?
If I am guilty, someone needs to offer me a plea deal fast!
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2008-2009 Zuza Software Foundation
#
# This file is part of Virtaal.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>.
from virtaal.support.set_enumerator import UnionSetEnumerator
from virtaal.support.sorted_set import SortedSet
from basemode import BaseMode
class QuickTranslateMode(BaseMode):
"""Quick translate mode - Include only untranslated and fuzzy units."""
name = 'QuickTranslate'
display_name = _("Incomplete")
widgets = []
# INITIALIZERS #
def __init__(self, controller):
"""Constructor.
@type controller: virtaal.controllers.ModeController
@param controller: The ModeController that managing program modes."""
self.controller = controller
# METHODS #
def selected(self):
cursor = self.controller.main_controller.store_controller.cursor
if not cursor or not cursor.model:
return
indices = list(UnionSetEnumerator(
SortedSet(cursor.model.stats['untranslated']),
SortedSet(cursor.model.stats['fuzzy'])
).set)
if not indices:
self.controller.select_default_mode()
return
cursor.indices = indices
def unselected(self):
pass
|
Hello, I have a problem with translation into Spanish of some items.
I have done the translation with poedit. However, after some words appear in English.
You can see it in the captures attached.
|
# coding=utf-8
import re
import logging
from .BaseHandler import BaseHandler
from utils.common import required_logined
from utils.response_code import RET
from utils.image_storage import storage
from config import image_url_prefix
class ProfileHandler(BaseHandler):
"""个人中心"""
@required_logined
def get(self):
user_id = self.session.data["user_id"]
try:
ret = self.db.get(
"select up_name, up_mobile, up_avatar from ih_user_profile where up_user_id=%(user_id)s", user_id=user_id)
except Exception as e:
logging.error(e)
return self.write({"errno": RET.DBERR, "errmsg": "数据库查询错误"})
if not ret:
return self.write({"errno": RET.NODATA, "errmsg": "无该用户信息"})
if ret["up_avatar"]:
img_url = image_url_prefix + ret["up_avatar"]
else:
img_url = None
data = {
"user_id": user_id,
"name": ret["up_name"],
"mobile": ret["up_mobile"],
"avatar": img_url,
}
return self.write({"errno": RET.OK, "errmsg": "OK", "data": data})
class AvatarHandler(BaseHandler):
"""用户头像修改"""
@required_logined
def post(self):
user_id = self.session.data["user_id"]
try:
avatar = self.request.files["avatar"][0]["body"]
except Exception as e:
logging.error(e)
return self.write({"errno": RET.PARAMERR, "errmsg": "参数错误"})
try:
avatar_name = storage(avatar)
except Exception as e:
logging.error(e)
avatar_name = None
return self.write({"errno": RET.THIRDERR, "errmsg": "Qiniu Error"})
try:
ret = self.db.execute(
"update ih_user_profile set up_avatar=%(avatar)s where up_user_id=%(user_id)s", avatar=avatar_name, user_id=user_id)
except Exception as e:
logging.error(e)
return self.write({"errno": RET.DBERR, "errmsg": "数据库错误"})
avatar_url = image_url_prefix + avatar_name
self.write({"errno": RET.OK, "errmsg": "OK", "avatar": avatar_url})
class NameHandler(BaseHandler):
"""
修改用户名
@param: user_id, 从session获取用户id,要求用户登录
@param: user_name, 用户提交的新用户名
@return: errno,返回的消息代码;errmsg,返回结果的消息,以及返回其他数据
"""
@required_logined
def post(self):
user_id = self.session.data["user_id"]
user_name = self.json_args.get("user_name")
if user_name in (None, ""):
return self.write({"errno": RET.PARAMERR, "errmsg": "修改的用户名不能为空"})
try:
self.db.execute("update ih_user_profile set up_name=%(user_name)s where up_user_id=%(user_id)s", user_name=user_name, user_id=user_id)
except Exception as e:
logging.error(e)
return self.write({"errno": RET.DBERR, "errmsg": "用户名已存在"})
self.session.data["name"] = user_name
self.session.save()
return self.write({"errno": RET.OK, "errmsg": "OK", "new_username": user_name})
class AuthHandler(BaseHandler):
"""
用户实名认证
"""
@required_logined
def get(self):
user_id = self.session.data["user_id"]
try:
ret = self.db.get("select up_real_name, up_id_card from ih_user_profile where up_user_id=%(user_id)s", user_id=user_id)
except Exception as e:
logging.error(e)
return self.write({"errno": RET.DBERR, "errmsg": "数据库查询错误"})
if ret["up_id_card"] not in (None, ""):
id_card = ret["up_id_card"]
id_card = id_card[:4] + "*"*len(id_card[4:-4]) + id_card[-4:]
return self.write({"errno": RET.OK, "errmsg": "OK", "real_name": ret["up_real_name"], "id_card": id_card})
@required_logined
def post(self):
real_name = self.json_args.get("real_name")
id_card = self.json_args.get("id_card")
if not all((real_name, id_card)):
return self.write({"errno": RET.PARAMERR, "errmsg": "参数不完整"})
user_id = self.session.data["user_id"]
try:
self.db.execute("update ih_user_profile set up_real_name=%(real_name)s, up_id_card=%(id_card)s where up_user_id=%(user_id)s", real_name=real_name, id_card=id_card, user_id=user_id)
except Exception as e:
logging.error(e)
return self.write({"errno": RET.DBERR, "errmsg": "数据库更新失败"})
id_card = id_card[:4] + "*"*len(id_card[4:-4]) + id_card[-4:]
return self.write({"errno":RET.OK, "errmsg":"OK", "real_name": real_name, "id_card": id_card})
|
Outfit your bedroom in traditional elegance with the Post & Rail 7 Drawer Dresser. Finished in vintage espresso this bedroom dresser exudes antique flair with its smooth grain detailing and inset brass drawer pulls. Spacious drawers allow for storing your wardrobe and accessories neatly.
|
# Copyright 2017, David Wilson
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
from __future__ import absolute_import
import os.path
import sys
try:
import ansible_mitogen.connection
except ImportError:
base_dir = os.path.dirname(__file__)
sys.path.insert(0, os.path.abspath(os.path.join(base_dir, '../../..')))
del base_dir
import ansible_mitogen.connection
import ansible_mitogen.process
if sys.version_info > (3,):
viewkeys = dict.keys
elif sys.version_info > (2, 7):
viewkeys = dict.viewkeys
else:
viewkeys = lambda dct: set(dct)
def dict_diff(old, new):
"""
Return a dict representing the differences between the dicts `old` and
`new`. Deleted keys appear as a key with the value :data:`None`, added and
changed keys appear as a key with the new value.
"""
old_keys = viewkeys(old)
new_keys = viewkeys(dict(new))
out = {}
for key in new_keys - old_keys:
out[key] = new[key]
for key in old_keys - new_keys:
out[key] = None
for key in old_keys & new_keys:
if old[key] != new[key]:
out[key] = new[key]
return out
class Connection(ansible_mitogen.connection.Connection):
transport = 'local'
def get_default_cwd(self):
# https://github.com/ansible/ansible/issues/14489
return self.loader_basedir
def get_default_env(self):
"""
Vanilla Ansible local commands execute with an environment inherited
from WorkerProcess, we must emulate that.
"""
return dict_diff(
old=ansible_mitogen.process.MuxProcess.original_env,
new=os.environ,
)
|
When trying to get job possibilities online, there are specific things that you’ll want to think about. This is a listing of top things to check out before striking the ‘apply’ button.
Look for jobs according to kind of business or job category. Affect groups which are of great interest for you and you are very well qualified for. For instance for those who have experience of retail sales or counter sales, make an application for jobs within the sales category.
Consider the work timings Some jobs have normal 9-5 however, many might have evening shifts which might not be appropriate for those candidates. For those who have a household, night/evening shifts may end up being hard for your loved ones so remember that. Part-time jobs ought to be considered if you’re searching at making extra money.
Get a job near to home. If you reside far from the preferred job consider how lengthy it might take you to obtain to operate as this may affect your projects performance and transport costs.
It’s also important to check out the experience needed. Some employers are searching for freshers while other will require experienced candidates. Always look for employers who would like your height of experience, believe me they’re there.
Search for your preferred salary. When the salary offered is under what you would like, don’t apply to do the job. Employers think it is annoying once they interview candidates who request a greater salary than was quoted within the job description. The perfect wages are one which enables you to cover all of your expenses and gives you some savings. However, don’t reject jobs due to the salary, sometimes the knowledge makes it worth while!
Another mistake is utilizing for income that you’re not educationally qualified for. When a company requests tenth standard and you’ve got a college degree, you’re certainly overqualified to do the job.
While applying for income bear in mind your job goals. Some jobs provides you with an chance to develop from the fresher position for an assistant manager position inside a couple of years while come might help you stay within the same level.
You will find significant variations with regards to how big the organization. Employed by a large company means which you may get access to better facilities along with a better salary. Although some people might businesses can also be known to possess good salaries and therefore are more flexible.
Some companies normally employ fresher simply because they place emphasis at work training. If you’re a fresher this is the perfect company as furthermore obtain a salary but there is also quality training which makes others drawn to you.
You will find firms that give employees additional perks for example free lunch, transport & other benefits. Such benefits result in the work atmosphere better in addition to assisting you cut costs.
Ultimately, your passion determines whether you’re going to get the task or otherwise. If you’re simply applying for income since you are unemployed, the business might find your desperation. However if you simply are passionate and well qualified to do the job a company will probably hire you. Finally have obvious mindset that you’ll stay at work and steer clear of job hopping after every three several weeks.
Babajob.com is India’s largest job portal for that informal sector. We focus on getting better employment job possibilities towards the informal job sector by appropriately connecting the best employers and people looking for work through the web, mobile phone applications, SMS, the mobile web and voice services.
|
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.serialization import Model
class ExpressRouteCircuitServiceProviderProperties(Model):
"""Contains ServiceProviderProperties in an ExpressRouteCircuit.
:param service_provider_name: The serviceProviderName.
:type service_provider_name: str
:param peering_location: The peering location.
:type peering_location: str
:param bandwidth_in_mbps: The BandwidthInMbps.
:type bandwidth_in_mbps: int
"""
_attribute_map = {
'service_provider_name': {'key': 'serviceProviderName', 'type': 'str'},
'peering_location': {'key': 'peeringLocation', 'type': 'str'},
'bandwidth_in_mbps': {'key': 'bandwidthInMbps', 'type': 'int'},
}
def __init__(self, **kwargs):
super(ExpressRouteCircuitServiceProviderProperties, self).__init__(**kwargs)
self.service_provider_name = kwargs.get('service_provider_name', None)
self.peering_location = kwargs.get('peering_location', None)
self.bandwidth_in_mbps = kwargs.get('bandwidth_in_mbps', None)
|
Crystal Sounds is the third album from Thirteen Senses. It was released in the UK on the 21 February 2011, including the single "The Loneliest Star". The album was recorded and produced by the band in their own studio. The third album appears 2 months short of a 4 year gap since 'Contact'.
The band announced the new album on 17th March 2010 via the official e-mail list, stating that a 9 track version was available to hear in full for a limited time only via an audio stream from the official website.
On November 12th 2010, it was announced that the band had signed a new record deal with PIAS Entertainment Group, meaning they were able to release the new record on their own imprint label, B-Sirius Records.
|
# Copyright (c) 2013 OpenStack Foundation.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import random
import sqlalchemy as sa
from sqlalchemy import orm
from sqlalchemy.orm import joinedload
from neutron.common import constants
from neutron.db import agents_db
from neutron.db import agentschedulers_db
from neutron.db import model_base
from neutron.extensions import lbaas_agentscheduler
from neutron.i18n import _LW
from neutron.openstack.common import log as logging
LOG = logging.getLogger(__name__)
class PoolLoadbalancerAgentBinding(model_base.BASEV2):
"""Represents binding between neutron loadbalancer pools and agents."""
pool_id = sa.Column(sa.String(36),
sa.ForeignKey("pools.id", ondelete='CASCADE'),
primary_key=True)
agent = orm.relation(agents_db.Agent)
agent_id = sa.Column(sa.String(36), sa.ForeignKey("agents.id",
ondelete='CASCADE'),
nullable=False)
class LbaasAgentSchedulerDbMixin(agentschedulers_db.AgentSchedulerDbMixin,
lbaas_agentscheduler
.LbaasAgentSchedulerPluginBase):
def get_lbaas_agent_hosting_pool(self, context, pool_id, active=None):
query = context.session.query(PoolLoadbalancerAgentBinding)
query = query.options(joinedload('agent'))
binding = query.get(pool_id)
if (binding and self.is_eligible_agent(
active, binding.agent)):
return {'agent': self._make_agent_dict(binding.agent)}
def get_lbaas_agents(self, context, active=None, filters=None):
query = context.session.query(agents_db.Agent)
query = query.filter_by(agent_type=constants.AGENT_TYPE_LOADBALANCER)
if active is not None:
query = query.filter_by(admin_state_up=active)
if filters:
for key, value in filters.iteritems():
column = getattr(agents_db.Agent, key, None)
if column:
query = query.filter(column.in_(value))
return [agent
for agent in query
if self.is_eligible_agent(active, agent)]
def list_pools_on_lbaas_agent(self, context, id):
query = context.session.query(PoolLoadbalancerAgentBinding.pool_id)
query = query.filter_by(agent_id=id)
pool_ids = [item[0] for item in query]
if pool_ids:
return {'pools': self.get_pools(context, filters={'id': pool_ids})}
else:
return {'pools': []}
def get_lbaas_agent_candidates(self, device_driver, active_agents):
candidates = []
for agent in active_agents:
agent_conf = self.get_configuration_dict(agent)
if device_driver in agent_conf['device_drivers']:
candidates.append(agent)
return candidates
class ChanceScheduler(object):
"""Allocate a loadbalancer agent for a vip in a random way."""
def schedule(self, plugin, context, pool, device_driver):
"""Schedule the pool to an active loadbalancer agent if there
is no enabled agent hosting it.
"""
with context.session.begin(subtransactions=True):
lbaas_agent = plugin.get_lbaas_agent_hosting_pool(
context, pool['id'])
if lbaas_agent:
LOG.debug('Pool %(pool_id)s has already been hosted'
' by lbaas agent %(agent_id)s',
{'pool_id': pool['id'],
'agent_id': lbaas_agent['id']})
return
active_agents = plugin.get_lbaas_agents(context, active=True)
if not active_agents:
LOG.warn(_LW('No active lbaas agents for pool %s'), pool['id'])
return
candidates = plugin.get_lbaas_agent_candidates(device_driver,
active_agents)
if not candidates:
LOG.warn(_LW('No lbaas agent supporting device driver %s'),
device_driver)
return
chosen_agent = random.choice(candidates)
binding = PoolLoadbalancerAgentBinding()
binding.agent = chosen_agent
binding.pool_id = pool['id']
context.session.add(binding)
LOG.debug('Pool %(pool_id)s is scheduled to lbaas agent '
'%(agent_id)s',
{'pool_id': pool['id'],
'agent_id': chosen_agent['id']})
return chosen_agent
|
The instance Providing for consideration of the bill (H.R. 4281) to provide an extension of federal-aid highway, highway safety, motor carrier safety, transit, and other programs funded out of the Highway Trust Fund pending enactment of a multiyear law reauthorizing such programs, and for other purposes : report (to accompany H. Res. 600), (electronic resource) represents a material embodiment of a distinct intellectual or artistic creation found in Biddle Law Library. This resource is a combination of several types including: Instance, Electronic.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.