text
stringlengths
29
850k
# -*- coding: utf-8 -*- # Generated by Django 1.9.10 on 2016-10-21 23:30 from __future__ import unicode_literals import datetime from django.conf import settings import django.contrib.auth.models import django.core.validators from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0007_alter_validators_add_error_messages'), ('forum', '0001_initial'), ('pm', '0001_initial'), ] operations = [ migrations.CreateModel( name='ForumUser', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('password', models.CharField(max_length=128, verbose_name='password')), ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')), ('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=30, unique=True, validators=[django.core.validators.RegexValidator('^[\\w.@+-]+$', 'Enter a valid username. This value may contain only letters, numbers and @/./+/-/_ characters.')], verbose_name='username')), ('first_name', models.CharField(blank=True, max_length=30, verbose_name='first name')), ('last_name', models.CharField(blank=True, max_length=30, verbose_name='last name')), ('email', models.EmailField(blank=True, max_length=254, verbose_name='email address')), ('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')), ('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')), ('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')), ('emailVisible', models.BooleanField(default=False, verbose_name='E-mail visible')), ('subscribeToEmails', models.BooleanField(default=True, verbose_name='Mailing-list')), ('mpEmailNotif', models.BooleanField(default=False, verbose_name='Notification des MP par e-mail')), ('showSmileys', models.BooleanField(default=False, verbose_name='Affichage des smileys par defaut')), ('fullscreen', models.BooleanField(default=False, verbose_name="Utilisation de la largeur de l'écran")), ('showLogosOnSmartphone', models.BooleanField(default=True, verbose_name='Afficher les logos sur smartphone')), ('logo', models.ImageField(blank=True, upload_to='logo')), ('quote', models.CharField(blank=True, max_length=50, verbose_name='Citation')), ('website', models.URLField(blank=True, verbose_name='Site web')), ('pmUnreadCount', models.IntegerField(default=0)), ('resetDateTime', models.DateTimeField(default=datetime.datetime(2013, 1, 1, 0, 0))), ('is_online', models.BooleanField(default=False)), ('last_seen', models.DateTimeField(blank=True, null=True)), ('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')), ('pmReadCaret', models.ManyToManyField(blank=True, to='pm.Message')), ('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')), ], options={ 'ordering': ['pk'], }, managers=[ ('objects', django.contrib.auth.models.UserManager()), ], ), migrations.CreateModel( name='Bookmark', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('timestamp', models.DateTimeField(auto_now=True)), ('thread', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='bookmarks', to='forum.Thread')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='bookmarks', to=settings.AUTH_USER_MODEL)), ], options={ 'get_latest_by': 'timestamp', }, ), migrations.CreateModel( name='CategoryTimeStamp', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('timestamp', models.DateTimeField(auto_now=True)), ('category', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='forum.Category')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='categoryTimeStamps', to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='TokenPool', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('token', models.CharField(max_length=50, unique=True)), ], ), migrations.AlterUniqueTogether( name='categorytimestamp', unique_together=set([('user', 'category')]), ), migrations.AlterIndexTogether( name='categorytimestamp', index_together=set([('user', 'category')]), ), migrations.AlterUniqueTogether( name='bookmark', unique_together=set([('user', 'thread')]), ), migrations.AlterIndexTogether( name='bookmark', index_together=set([('user', 'thread')]), ), ]
Welcome to this section of the website. Here I will discuss in some detail about a range of sports that I am interested in. I don't plan to cover everything about the sport (that's what BBC is for). My favourite teams / players, what key headlines have arisen and anything else I may feel to add. For the time being some links are hidden as those section have no content. I have added some content about football. The current Premiership battle is on there. Please visit regulary for the updates. Thank you.
__author__ = 'srodgers' """ This file is part of chargectrl-python-buspirate. chargectrl-python-buspirate 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. Foobar 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 chargectrl-python-buspirate. If not, see <http://www.gnu.org/licenses/>. """ from tkinter import * from tkinter.ttk import * class Dialog(Toplevel): def __init__(self, parent, title = None, xoffset = 50, yoffset = 50): Toplevel.__init__(self, parent) self.transient(parent) if title: self.title(title) self.parent = parent self.result = None body = Frame(self) self.initial_focus = self.body(body) body.pack(padx=5, pady=5) self.buttonbox() self.grab_set() if not self.initial_focus: self.initial_focus = self self.protocol("WM_DELETE_WINDOW", self.cancel) self.geometry("+%d+%d" % (parent.winfo_rootx()+xoffset, parent.winfo_rooty()+yoffset)) self.initial_focus.focus_set() self.wait_window(self) # # construction hooks def body(self, master): # create dialog body. return widget that should have # initial focus. this method should be overridden pass def buttonbox(self): # add standard button box. override if you don't want the # standard buttons box = Frame(self) w = Button(box, text="OK", width=10, command=self.ok, default=ACTIVE) w.pack(side=LEFT, padx=5, pady=5) w = Button(box, text="Cancel", width=10, command=self.cancel) w.pack(side=LEFT, padx=5, pady=5) self.bind("<Return>", self.ok) self.bind("<Escape>", self.cancel) box.pack() # # standard button semantics def ok(self, event=None): if not self.validate(): self.initial_focus.focus_set() # put focus back return self.withdraw() self.update_idletasks() self.apply() self.cancel() def cancel(self, event=None): # put focus back to the parent window self.parent.focus_set() self.destroy() # # command hooks def validate(self): return 1 # override def apply(self): pass # override
MULTI-PURPOSE: Our Padded Interior, Triple Stitched Exterior and Rubber Soles Provide Flexibility, Comfort, Durability, Impact Resistance and Traction With Every Step You Take, Making Them Ideal For Any Activity, Climate, Work and Rugged Outdoor Environment. Our Boots work Hard So You Don't Have to! ANKLE SUPPORT: Every Boot Is Designed To Protect and Stabilize Your Mid Range Ankle Area From Many Activities, Offering You A 6-Slot / 2-Hook Lacing Mechanism For Complete and Reliable Support. We Have Also Incorporated a Heel Tab and Heavy Duty Zipper to Not Only Prevent Heel Folds During Foot Entry but To Create A Stress-Free On/Off Motion. (NOTE: Our Metal Buckle Does NOT Offer Additional Support). WARRANTY & CARE: Reliable Customer Service Is Our #1 Priority. Here at Conal International, We Readily Offer a 30-Day Money Back Guaranteed and 90-Day Limited Manufacturer Warranty. Which Covers (Manufacturing & Material Defects). For Maximum Usage, We Suggest That You Hand Wash and Lay Flat To Air Dry. Our products are NOT Washer/Dryer Safe.
''' Example of automating the creation of a L3 Master Engine or Master Engine Cluster, configuring interfaces and creating the virtual engines. ''' from smc import session from smc.core.engine import Engine from smc.core.engines import Layer3VirtualEngine, MasterEngineCluster, MasterEngine def create_single_master_engine(): """ Create a single master engine instance example :raises: `smc.api.exceptions.CreateEngineFailed` """ MasterEngine.create('api-master', mgmt_ip='1.1.1.1', mgmt_netmask='1.1.1.0/24', master_type='firewall', domain_server_address=['8.8.4.4', '7.7.7.7']) # Returns smc.core.engine.Engine instance def create_cluster_master_engine(): """ Create the master engine cluster with 2 nodes example Nodes data structure is: [{'address': '', #ip address of node 'network_value': '', #network/cidr 'nodeid': 1}] #node identifier, 1, 2, 3, etc :raises: `smc.api.exceptions.CreateEngineFailed` """ MasterEngineCluster.create( name='engine-cluster', master_type='firewall', macaddress='22:22:22:22:22:22', nodes=[{'address': '5.5.5.2', 'network_value': '5.5.5.0/24', 'nodeid': 1}, {'address': '5.5.5.3', 'network_value': '5.5.5.0/24', 'nodeid': 2}]) # Returns smc.core.engine.Engine instance def delete(ve, master_engine): # Delete easily. Just load the engine resource and call delete. Delete VE's first. # All elements descend from smc.base.model.Element # Note: Most operations will return an instance of smc.api.web.SMCResult so you # can view the return attributes if necessary. ve = Engine('layer3-ve').load() ve.delete() master = Engine('engine-cluster').load() master.delete() if __name__ == '__main__': session.login(url='https://172.18.1.25:8082', api_key='avUj6vFZTUSZ7sr8mNsP0001', timeout=120, verify=False) create_cluster_master_engine() # Load the existing master engine named 'master-eng' engine = Engine('engine-cluster').load() # Create a virtual resource named 've-1' with virtual firewall id 1 # vfw_id should increment by 1 for each new virtual firewall under the # same Master Engine print engine.virtual_resource.create(name='ve-1', vfw_id=1) # Example of allocating the entire physical interface to a virtual engine # Create the interface mapping to virtual resource 've-1' print engine.physical_interface.add(interface_id=1, virtual_mapping=0, virtual_resource_name='ve-1') # Example of allocating a VLAN to a virtual engine on a specific physical # interface. # engine.physical_interface.add_vlan_to_node_interface( # interface_id=1, # vlan_id=100, # virtual_mapping=0, # virtual_resource_name='ve-1') # Virtual Engine interface mappings start at 0 (interface_id) regardless of the # real interface index on the master engine. The interface_id for the virtual engine # will start it's numbering at index 0 and increment by 1 for each interface allocated. # The interface_id field correlates to the "Virtual Engine Interface ID" property of # the master engine's physical interface. #:raises: `smc.api.exceptions.CreateEngineFailed` Layer3VirtualEngine.create('layer3-ve', master_engine='engine-cluster', virtual_resource='ve-1', interfaces=[{'interface_id': 0, 'address': '1.1.1.1', 'network_value': '1.1.1.0/24'}]) # Returns smc.core.engine.Layer3VirtualEngine instance # delete() session.logout()
Discover gorgeous Botanical river canvas prints. Fast and reliable shipping. 100% satisfaction guarantee.
import json import os from core.views import BaseView from .sendfile import send_file from .models import BaseFile as File, UploadedFile from core import now from .tasks import ensure_fs_ready from .forms import UploadedFileForm from django.http import HttpResponse, HttpResponseNotFound, JsonResponse # from django.db.models import Count from django.conf import settings # from django.utils.translation import gettext_lazy as _ # from django.core.urlresolvers import reverse from braces import views from os.path import isfile, isdir, join from . import files_used_in_this_repo import logging log = logging.getLogger(__name__) class FileView(BaseView): """Return a file with permission checking""" def get(self, request, **kwargs): """If "d" is present in query string - make an attachment (always download, not view in browser) """ is_attachment = 'd' in self.request.GET sha1 = kwargs.get('sha1', None) try: f = File.objects.get(sha1=sha1) return send_file(f, attachment=is_attachment) except File.DoesNotExist: # # If there is no info in a DB about this file return file # anyway (if exists) and then run a task to process file and # add to DB. # roots = settings.FILES_ROOT if isinstance(roots, str): roots = [settings.FILES_ROOT] for root in roots: filename = os.path.join( root, sha1[:3], sha1[3:6], sha1[6:] ) if os.path.isfile(filename): # TODO: run task to add file info to DB return send_file(filename, attachment=is_attachment) # else: # return HttpResponseNotFound( # "No such file {}".format( # filename if settings.DEBUG else "")) else: return HttpResponseNotFound( "No such file {}".format( filename if settings.DEBUG else "")) # c['uploads'] = UploadFile.objects.all().annotate( # null_position=Count('date_uploaded')).order_by('-null_position', # '-date_uploaded') class DownloadCore( views.LoginRequiredMixin, views.SuperuserRequiredMixin, BaseView, ): def post(self, request, **kwargs): if not settings.DEBUG: return HttpResponse('[]', content_type='application/json') ensure_fs_ready() files = files_used_in_this_repo() # sha1 list for f in files: url = 'https://pashinin.com/_/files/{}'.format(f) File.from_url(url) return HttpResponse(json.dumps({ 'dir': settings.REPO_PATH, 'files': json.dumps(files), 'len': len(files) }), content_type='application/json') class Upload(BaseView): def post(self, request, **kwargs): ensure_fs_ready() ctx = self.get_context_data(**kwargs) user = ctx['user'] form = UploadedFileForm(request.POST, request.FILES) files = [] for field in request.FILES: log.debug(request.FILES[field]) new_file = UploadedFile(file=request.FILES[field]) # Uploader should have access to his file # Save it in a session for Anons if user.is_anonymous: if 'files' not in request.session: # request.session['files'] = [upload_md5] pass else: # request.session['files'] += [upload_md5] pass else: new_file.uploader = user new_file.save() from .tasks import move_upload_to_files f = move_upload_to_files(new_file) files.append({'sha1': f.sha1}) # 'BaseFile' object has no attribute 'uploader' # if not f.uploader and user is not None and not user.is_anonymous: # f.uploader = user # f.save() # TODO: optimize uploaded JPGs # # jpegtran -copy none -optimize -perfect inputimage.jpg > # outputimage.jpg # user.avatar = Image.from_file(f) return JsonResponse({'files': files}) return HttpResponse(json.dumps({'errors': ['asd']}), content_type='application/json') if form.is_valid(): new_file = UploadedFile(file=request.FILES['file']) # Uploader should have access to his file # Save it in a session for Anons if user.is_anonymous: if 'files' not in request.session: # request.session['files'] = [upload_md5] pass else: # request.session['files'] += [upload_md5] pass else: new_file.uploader = user new_file.save() from .tasks import move_upload_to_files f = move_upload_to_files(new_file) # 'BaseFile' object has no attribute 'uploader' # if not f.uploader and user is not None and not user.is_anonymous: # f.uploader = user # f.save() # TODO: optimize uploaded JPGs # # jpegtran -copy none -optimize -perfect inputimage.jpg > # outputimage.jpg # user.avatar = Image.from_file(f) return HttpResponse(json.dumps({ 'url': f.get_absolute_url(), 'id': f.pk, 'sha1': f.sha1 }), content_type='application/json') else: # upload form is not valid return HttpResponse(json.dumps({'errors': form.errors}), content_type='application/json') for key in request.FILES: f = request.FILES[key] upload = UploadedFile(file=f) # upload_md5 = upload.get_md5() upload.date_uploaded = now() if f.multiple_chunks(): # file is already on disk upload.save() else: # check if this md5 was already uploaded prevUpload = upload.uploaded_earlier if prevUpload: upload = prevUpload else: upload.save() # The file is uploaded, it is now for example: # # /mnt/files/uploads/2016/06/28/dropzone_NaLkPzK.css # # Upload directory: # MEDIA_ROOT = os.path.join(FILES_ROOT, 'uploads/') # # TODO: process uploaded file # upload.process() return HttpResponse(json.dumps({'url': upload.url})) class Files( views.LoginRequiredMixin, views.SuperuserRequiredMixin, BaseView ): """Files management (admin view)""" template_name = "core_files.jinja" def get_context_data(self, **kwargs): c = super().get_context_data(**kwargs) c['files_count'] = File.objects.count() c['files'] = File.objects.filter().order_by('-added')[:10] c['dropzone'] = True c['timeago'] = True # Check mountpoint import psutil c['mounted'] = False for p in psutil.disk_partitions(True): if p.mountpoint == settings.FILES_ROOT: c['mounted'] = True break return c class DirView(BaseView): template_name = "cms_files_dirview.jinja" dir = None def get_context_data(self, **kwargs): """asd levels - ['path', 'to', 'dir'] paths - ['/path', '/path/to', '/path/to/dir'] """ c = super().get_context_data(**kwargs) c['files'] = [] c['dirs'] = [] path = kwargs.get('path', '') if path is None: path = '' path = path.strip('/') c['levels'] = path.split('/') # c['levels'][0] = '/'+c['levels'][0] c['paths'] = list(c['levels']) print(c['paths']) try: c['levels'].remove('') except ValueError: pass for i, el in enumerate(c['levels']): sublist = c['levels'][0:i+1] c['paths'][i] = '/'+os.path.join(*sublist) # c['paths'][0] = '/'+c['paths'][0] j = os.path.join(self.dir, path) # log.debug((self.dir, path)) d = c['dir'] = os.path.realpath(j) if self.dir is None or \ not isdir(self.dir): log.error('DirView: No dir {}'.format(self.dir)) return c if isdir(d): L = os.listdir(d) c['dirs'] = sorted([f for f in L if isdir(join(d, f))]) c['files'] = sorted([f for f in L if isfile(join(d, f))]) for ind, f in enumerate(c['files']): c['files'][ind] = { 'name': f, 'size': os.path.getsize(join(d, f)) } elif os.path.isfile(d): c['f'] = d else: log.error('DirView 404: No dir {}'.format(d)) c['status'] = 404 return c
EDA is an intensive study of the aquaculture industry & influence on the cultures where it is practiced. It is designed to use a STEM focused approach applying concepts in real-life settings. It is aimed at young people from 16 years old and up and from different countries who are interested in learning more about this rapidly growing industry. Students will complete modules online, designed to allow them to be actively engaged in collaborative activities with other participants, course instructors and experts in the field. To enhance student learning, visits, field studies and work experience are also offered to the students, so their understanding of aquaculture has a more meaningful, real-time and first-hand experience. Pam has extensive teaching experience, teaching at the high school and college level, relevant qualifications and training in the field of aquaculture and biology. She has experience in project management, focusing her efforts on youth engagement through social inclusion, multi-cultural collaboration and integration as a means of providing educational opportunities for all. Has worked and collaborated with a range of people from academia, industry and business sectors at the international level. Shared interests have led to transfer of knowledge in the aquaculture and fisheries developments. These have also opened opportunities to students to participate in current research-based projects and work-related experience that Pam has organised and supervised. Collaborating with these interested groups, was what fuelled the idea to continue developing the EDA programme that would better engage students in this area and provide them with high quality instruction in a more flexible approach that works for the 21st century learner. She is continuously developing her skills and knowledge in the design of online learning education. Elizabeth has twenty years of experience as a project coordinator for CT State Department of Education Interdistrict Cooperative Grants through the Capitol Region Education Council. She holds an MEd from Westfield State College and is a certified K-12 Special Education teacher. She also holds an Aquaponics Certificate from the University of the Virgin Islands and has visited Auburn University’s aquaculture program to glean information about best practices in education and aquaponics. Elizabeth managed the Interdistrict Grant programs “Exploring Diversity through Aquaculture” and “River to the Sea” as CREC programs from 2001-2015. She has worked on aquaculture projects with three Vocational-Agriculture schools across the state and regularly judges the FFA Creed contest. Elizabeth is on the Education Committee for the Salmon-in-Schools project and works with the DEEP to release salmon in her back yard brook.
import MySQLdb import credentials class User(object): def __init__(self, email, password): self.email = email self.password = password def __str__(self): return "email: " + str(self.email) + "password: " + str(self.password) def save(self): """ Saves this User to the database. """ # Get new database instance db = credentials.getDatabase() cur = db.cursor() query = '''INSERT IGNORE INTO users (email, password) VALUES(%s, %s);''' data = (self.email, self.password) cur.execute(query, data) # commit query db.commit() db.close() return True def verify(self): """ Returns: True if the user's credentials match the database. False otherwise. """ if isUniqueEmail(self.email) == False: # Get new database instance db = credentials.getDatabase() cur = db.cursor() query = '''SELECT email, password FROM users WHERE email = %s;''' cur.execute(query, self.email) em = "" ps = "" value = False for tup in cur: em = tup[0] ps = tup[1] if em == self.email and ps == self.password: value = True # commit query db.commit() db.close() return value return False def load(email): ''' Args: email: The email to query. Returns: A user given the email. ''' # Get new database instance db = credentials.getDatabase() cur = db.cursor() query = '''SELECT * FROM users WHERE email = %s;''' cur.execute(query,email) user = "" for tup in cur: user = User(tup[0], tup[1]) # commit query db.commit() db.close() return user def loadAll(): ''' Returns: A list of all users. ''' # Get new database instance db = credentials.getDatabase() cur = db.cursor() query = '''SELECT email, password FROM users;''' cur.execute(query) users = [] for tup in cur: users.append(User(tup[0], tup[1])) # commit query db.commit() db.close() return users def addUser(email, password): ''' Saves a new user to the database. ''' User(email,password).save() def isUniqueEmail(email): ''' Args: email: the email to query Returns: True if the email does not yet exist in the database. ''' # Get new database instance db = credentials.getDatabase() cur = db.cursor() query = '''SELECT COUNT(*) FROM users WHERE email =%s;''' cur.execute(query, email) count = 0 for tup in cur: count = tup[0] return count == 0
Congratulations to Lauren Arikan, spouse of Yusuf Arikan and member of the Turkish American community, for her win in the Maryland Republican primary election for House of Delegates (District 7) on June 26th! Lauren has been endorsed by several of her Republican colleagues such as Congressman Andy Harris (R-MD/1st) and Delegate Pat McDonough (R-MD/7th). She is the owner of an accounting and tax firm, Arikan Accounting, that she opened with her husband in 2009.
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*- # This file is part of Guadalinex # # This software 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 software 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 package; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA __author__ = "Abraham Macias Paredes <[email protected]>" __copyright__ = "Copyright (C) 2015, Junta de Andalucía" + \ "<[email protected]>" __license__ = "GPL-2" import logging import gettext from gettext import gettext as _ from gecosws_config_assistant.view.GladeWindow import GladeWindow from gecosws_config_assistant.dto.NTPServer import NTPServer from gecosws_config_assistant.view.CommonDialog import ( showwarning_gtk, showinfo_gtk) gettext.textdomain('gecosws-config-assistant') class NTPServerElemView(GladeWindow): ''' Dialog class that shows the a NTP server element. ''' def __init__(self, parent, mainController): ''' Constructor ''' self.parent = parent self.controller = mainController self.logger = logging.getLogger('NTPServerElemView') self.gladepath = 'ntp.glade' self.data = None self.displaySuccess = True self.initUI() def get_data(self): ''' Getter data ''' return self.__data def set_data(self, value): ''' Setter data ''' self.__data = value def initUI(self): ''' Initialize UI ''' self.buildUI(self.gladepath) def addHandlers(self): ''' Adding handlers ''' self.logger.debug("Adding all handlers") self.handlers = self.parent.get_common_handlers() # add new handlers here self.logger.debug("Adding check ntp connection") self.handlers["onChek"] = self.test self.logger.debug("Adding OK handler") self.handlers["onOOKK"] = self.accept self.logger.debug("Adding back handler") self.handlers["onBack"] = self.goBack def show(self): ''' Show ''' self.logger.debug("Show") data = self.get_data() if data is not None: self.getElementById('ntp_server_entry') \ .set_text(data.get_address()) self.parent.navigate(self) def goBack(self, *args): ''' Go back ''' self.logger.debug("Go back") self.controller.mainWindowController.backToMainWindowDialog() def accept(self, *args): ''' Accept ''' self.logger.debug("Accept") if self.get_data() is None: self.set_data(NTPServer()) self.get_data().set_address( self.getElementById('ntp_server_entry').get_text()) self.displaySuccess = False if self.test(False): self.displaySuccess = True self.controller.save() self.displaySuccess = True def test(self, *args): ''' Testing purposes ''' self.logger.debug("test") if self.get_data() is None: self.set_data(NTPServer()) self.get_data().set_address( self.getElementById('ntp_server_entry').get_text()) self.logger.debug("test: %s", self.get_data().get_address()) result = self.controller.test() if not result: showwarning_gtk( _("Can't connect with NTP server.\n" + "Please double-check the NTP server address"), self) elif self.displaySuccess: showinfo_gtk(_("NTP server connection successful"), self) return result def cancel(self, *args): ''' Cancel ''' self.logger.debug("cancel") self.controller.hide() data = property( get_data, set_data, None, None)
A.L. Jacobsen Funeral Home, Inc. values your privacy. We will never give, sell, rent or otherwise share your email or personal information with any other organization. Subscribing to our daily emails will not result in unwanted emails from us or third party vendors. Should you ever wish to unsubscribe, you can easily do so by clicking on a link at the bottom of any one of the affirmation messages.
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ivSweeper.ui' # # Created: Thu Nov 27 00:52:45 2014 # by: PyQt4 UI code generator 4.9.6 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig) class Ui_IVSweeper(object): def setupUi(self, IVSweeper): IVSweeper.setObjectName(_fromUtf8("IVSweeper")) IVSweeper.resize(622, 515) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(IVSweeper.sizePolicy().hasHeightForWidth()) IVSweeper.setSizePolicy(sizePolicy) self.centralwidget = QtGui.QWidget(IVSweeper) self.centralwidget.setObjectName(_fromUtf8("centralwidget")) self.addressGroup = QtGui.QGroupBox(self.centralwidget) self.addressGroup.setGeometry(QtCore.QRect(10, 0, 281, 50)) self.addressGroup.setToolTip(_fromUtf8("")) self.addressGroup.setStatusTip(_fromUtf8("")) self.addressGroup.setAutoFillBackground(False) self.addressGroup.setObjectName(_fromUtf8("addressGroup")) self.instrumentCombo = QtGui.QComboBox(self.addressGroup) self.instrumentCombo.setGeometry(QtCore.QRect(10, 20, 260, 20)) self.instrumentCombo.setObjectName(_fromUtf8("instrumentCombo")) self.instrumentCombo.addItem(_fromUtf8("")) self.sweepButton = QtGui.QPushButton(self.centralwidget) self.sweepButton.setEnabled(False) self.sweepButton.setGeometry(QtCore.QRect(520, 430, 90, 30)) self.sweepButton.setCheckable(False) self.sweepButton.setAutoDefault(False) self.sweepButton.setObjectName(_fromUtf8("sweepButton")) self.terminalsGroup = QtGui.QGroupBox(self.centralwidget) self.terminalsGroup.setGeometry(QtCore.QRect(300, 0, 150, 50)) self.terminalsGroup.setObjectName(_fromUtf8("terminalsGroup")) self.frontRadio = QtGui.QRadioButton(self.terminalsGroup) self.frontRadio.setGeometry(QtCore.QRect(10, 20, 60, 20)) self.frontRadio.setChecked(True) self.frontRadio.setObjectName(_fromUtf8("frontRadio")) self.rearRadio = QtGui.QRadioButton(self.terminalsGroup) self.rearRadio.setGeometry(QtCore.QRect(80, 20, 60, 20)) self.rearRadio.setObjectName(_fromUtf8("rearRadio")) self.wiresGroup = QtGui.QGroupBox(self.centralwidget) self.wiresGroup.setGeometry(QtCore.QRect(430, 50, 180, 50)) self.wiresGroup.setObjectName(_fromUtf8("wiresGroup")) self.twowireRadio = QtGui.QRadioButton(self.wiresGroup) self.twowireRadio.setGeometry(QtCore.QRect(10, 10, 91, 40)) self.twowireRadio.setChecked(True) self.twowireRadio.setObjectName(_fromUtf8("twowireRadio")) self.fourwireRadio = QtGui.QRadioButton(self.wiresGroup) self.fourwireRadio.setGeometry(QtCore.QRect(100, 10, 80, 40)) self.fourwireRadio.setObjectName(_fromUtf8("fourwireRadio")) self.sweepGroup = QtGui.QGroupBox(self.centralwidget) self.sweepGroup.setGeometry(QtCore.QRect(10, 100, 390, 130)) self.sweepGroup.setStatusTip(_fromUtf8("")) self.sweepGroup.setObjectName(_fromUtf8("sweepGroup")) self.label = QtGui.QLabel(self.sweepGroup) self.label.setGeometry(QtCore.QRect(10, 20, 41, 20)) self.label.setObjectName(_fromUtf8("label")) self.label_2 = QtGui.QLabel(self.sweepGroup) self.label_2.setGeometry(QtCore.QRect(10, 50, 41, 20)) self.label_2.setObjectName(_fromUtf8("label_2")) self.reverseButton = QtGui.QPushButton(self.sweepGroup) self.reverseButton.setGeometry(QtCore.QRect(10, 90, 111, 30)) self.reverseButton.setObjectName(_fromUtf8("reverseButton")) self.endSpin = QtGui.QSpinBox(self.sweepGroup) self.endSpin.setGeometry(QtCore.QRect(50, 50, 91, 20)) self.endSpin.setMinimum(-20000) self.endSpin.setMaximum(20000) self.endSpin.setProperty("value", 1000) self.endSpin.setObjectName(_fromUtf8("endSpin")) self.startSpin = QtGui.QSpinBox(self.sweepGroup) self.startSpin.setGeometry(QtCore.QRect(50, 20, 91, 20)) self.startSpin.setMinimum(-20000) self.startSpin.setMaximum(20000) self.startSpin.setProperty("value", -1000) self.startSpin.setObjectName(_fromUtf8("startSpin")) self.totalPointsSpin = QtGui.QSpinBox(self.sweepGroup) self.totalPointsSpin.setGeometry(QtCore.QRect(230, 20, 71, 20)) self.totalPointsSpin.setAccelerated(False) self.totalPointsSpin.setSuffix(_fromUtf8("")) self.totalPointsSpin.setMinimum(1) self.totalPointsSpin.setMaximum(2000) self.totalPointsSpin.setProperty("value", 100) self.totalPointsSpin.setObjectName(_fromUtf8("totalPointsSpin")) self.label_3 = QtGui.QLabel(self.sweepGroup) self.label_3.setGeometry(QtCore.QRect(150, 20, 81, 20)) self.label_3.setObjectName(_fromUtf8("label_3")) self.label_6 = QtGui.QLabel(self.sweepGroup) self.label_6.setGeometry(QtCore.QRect(150, 50, 71, 20)) self.label_6.setObjectName(_fromUtf8("label_6")) self.autoAdvance = QtGui.QCheckBox(self.sweepGroup) self.autoAdvance.setEnabled(False) self.autoAdvance.setGeometry(QtCore.QRect(130, 110, 131, 20)) self.autoAdvance.setObjectName(_fromUtf8("autoAdvance")) self.deltaStep = QtGui.QLabel(self.sweepGroup) self.deltaStep.setGeometry(QtCore.QRect(310, 20, 81, 20)) self.deltaStep.setObjectName(_fromUtf8("deltaStep")) self.maxPowerCheck = QtGui.QCheckBox(self.sweepGroup) self.maxPowerCheck.setGeometry(QtCore.QRect(130, 90, 111, 20)) self.maxPowerCheck.setObjectName(_fromUtf8("maxPowerCheck")) self.delaySpinBox = QtGui.QDoubleSpinBox(self.sweepGroup) self.delaySpinBox.setGeometry(QtCore.QRect(230, 50, 71, 20)) self.delaySpinBox.setDecimals(3) self.delaySpinBox.setMaximum(1000.0) self.delaySpinBox.setSingleStep(0.01) self.delaySpinBox.setProperty("value", 0.02) self.delaySpinBox.setObjectName(_fromUtf8("delaySpinBox")) self.totalLabel = QtGui.QLabel(self.sweepGroup) self.totalLabel.setGeometry(QtCore.QRect(310, 50, 81, 20)) self.totalLabel.setObjectName(_fromUtf8("totalLabel")) self.daqGroup = QtGui.QGroupBox(self.centralwidget) self.daqGroup.setGeometry(QtCore.QRect(410, 100, 200, 131)) self.daqGroup.setObjectName(_fromUtf8("daqGroup")) self.zeroCheck = QtGui.QCheckBox(self.daqGroup) self.zeroCheck.setGeometry(QtCore.QRect(10, 110, 80, 22)) self.zeroCheck.setObjectName(_fromUtf8("zeroCheck")) self.speedCombo = QtGui.QComboBox(self.daqGroup) self.speedCombo.setGeometry(QtCore.QRect(80, 50, 110, 20)) self.speedCombo.setObjectName(_fromUtf8("speedCombo")) self.speedCombo.addItem(_fromUtf8("")) self.speedCombo.addItem(_fromUtf8("")) self.speedCombo.addItem(_fromUtf8("")) self.speedCombo.addItem(_fromUtf8("")) self.label_7 = QtGui.QLabel(self.daqGroup) self.label_7.setGeometry(QtCore.QRect(10, 50, 62, 20)) self.label_7.setObjectName(_fromUtf8("label_7")) self.averageSpin = QtGui.QSpinBox(self.daqGroup) self.averageSpin.setEnabled(True) self.averageSpin.setGeometry(QtCore.QRect(130, 80, 60, 20)) self.averageSpin.setMinimum(0) self.averageSpin.setMaximum(100) self.averageSpin.setObjectName(_fromUtf8("averageSpin")) self.label_8 = QtGui.QLabel(self.daqGroup) self.label_8.setGeometry(QtCore.QRect(10, 80, 121, 20)) self.label_8.setObjectName(_fromUtf8("label_8")) self.saveModeCombo = QtGui.QComboBox(self.daqGroup) self.saveModeCombo.setGeometry(QtCore.QRect(110, 20, 80, 20)) self.saveModeCombo.setObjectName(_fromUtf8("saveModeCombo")) self.saveModeCombo.addItem(_fromUtf8("")) self.saveModeCombo.addItem(_fromUtf8("")) self.label_10 = QtGui.QLabel(self.daqGroup) self.label_10.setGeometry(QtCore.QRect(10, 20, 90, 20)) self.label_10.setObjectName(_fromUtf8("label_10")) self.complianceGroup = QtGui.QGroupBox(self.centralwidget) self.complianceGroup.setGeometry(QtCore.QRect(190, 50, 230, 50)) self.complianceGroup.setObjectName(_fromUtf8("complianceGroup")) self.complianceSpin = QtGui.QSpinBox(self.complianceGroup) self.complianceSpin.setGeometry(QtCore.QRect(120, 20, 90, 20)) self.complianceSpin.setMinimum(1) self.complianceSpin.setMaximum(1000) self.complianceSpin.setProperty("value", 10) self.complianceSpin.setObjectName(_fromUtf8("complianceSpin")) self.label_9 = QtGui.QLabel(self.complianceGroup) self.label_9.setGeometry(QtCore.QRect(10, 20, 90, 20)) self.label_9.setObjectName(_fromUtf8("label_9")) self.modeGroup = QtGui.QGroupBox(self.centralwidget) self.modeGroup.setGeometry(QtCore.QRect(10, 50, 170, 50)) self.modeGroup.setObjectName(_fromUtf8("modeGroup")) self.sourceVRadio = QtGui.QRadioButton(self.modeGroup) self.sourceVRadio.setEnabled(True) self.sourceVRadio.setGeometry(QtCore.QRect(10, 20, 60, 22)) self.sourceVRadio.setChecked(True) self.sourceVRadio.setObjectName(_fromUtf8("sourceVRadio")) self.sourceIRadio = QtGui.QRadioButton(self.modeGroup) self.sourceIRadio.setEnabled(True) self.sourceIRadio.setGeometry(QtCore.QRect(90, 20, 70, 22)) self.sourceIRadio.setObjectName(_fromUtf8("sourceIRadio")) self.progress = QtGui.QProgressBar(self.centralwidget) self.progress.setGeometry(QtCore.QRect(10, 430, 510, 30)) self.progress.setProperty("value", 0) self.progress.setInvertedAppearance(False) self.progress.setObjectName(_fromUtf8("progress")) self.sweepContinuallyGroup = QtGui.QGroupBox(self.centralwidget) self.sweepContinuallyGroup.setGeometry(QtCore.QRect(10, 230, 390, 70)) self.sweepContinuallyGroup.setCheckable(True) self.sweepContinuallyGroup.setChecked(False) self.sweepContinuallyGroup.setObjectName(_fromUtf8("sweepContinuallyGroup")) self.label_4 = QtGui.QLabel(self.sweepContinuallyGroup) self.label_4.setGeometry(QtCore.QRect(10, 10, 120, 20)) self.label_4.setObjectName(_fromUtf8("label_4")) self.scanRecoverySpin = QtGui.QDoubleSpinBox(self.sweepContinuallyGroup) self.scanRecoverySpin.setGeometry(QtCore.QRect(130, 10, 81, 20)) self.scanRecoverySpin.setMaximum(1000000000.0) self.scanRecoverySpin.setObjectName(_fromUtf8("scanRecoverySpin")) self.label_5 = QtGui.QLabel(self.sweepContinuallyGroup) self.label_5.setGeometry(QtCore.QRect(10, 40, 120, 20)) self.label_5.setObjectName(_fromUtf8("label_5")) self.nSweepSpin = QtGui.QSpinBox(self.sweepContinuallyGroup) self.nSweepSpin.setGeometry(QtCore.QRect(130, 40, 81, 20)) self.nSweepSpin.setMaximum(99999) self.nSweepSpin.setProperty("value", 100) self.nSweepSpin.setObjectName(_fromUtf8("nSweepSpin")) self.label_11 = QtGui.QLabel(self.sweepContinuallyGroup) self.label_11.setGeometry(QtCore.QRect(220, 10, 111, 20)) self.label_11.setObjectName(_fromUtf8("label_11")) self.comboBox = QtGui.QComboBox(self.sweepContinuallyGroup) self.comboBox.setEnabled(False) self.comboBox.setGeometry(QtCore.QRect(330, 10, 50, 22)) self.comboBox.setObjectName(_fromUtf8("comboBox")) self.comboBox.addItem(_fromUtf8("")) self.comboBox.addItem(_fromUtf8("")) self.comboBox.addItem(_fromUtf8("")) self.comboBox.addItem(_fromUtf8("")) self.checkBox = QtGui.QCheckBox(self.sweepContinuallyGroup) self.checkBox.setEnabled(False) self.checkBox.setGeometry(QtCore.QRect(220, 40, 170, 17)) self.checkBox.setObjectName(_fromUtf8("checkBox")) self.groupBox = QtGui.QGroupBox(self.centralwidget) self.groupBox.setGeometry(QtCore.QRect(410, 230, 200, 70)) self.groupBox.setObjectName(_fromUtf8("groupBox")) self.shutterButton = QtGui.QPushButton(self.groupBox) self.shutterButton.setEnabled(True) self.shutterButton.setGeometry(QtCore.QRect(100, 30, 91, 30)) self.shutterButton.setObjectName(_fromUtf8("shutterButton")) self.displayBlankCheck = QtGui.QCheckBox(self.groupBox) self.displayBlankCheck.setGeometry(QtCore.QRect(10, 50, 91, 20)) self.displayBlankCheck.setObjectName(_fromUtf8("displayBlankCheck")) self.outputCheck = QtGui.QCheckBox(self.groupBox) self.outputCheck.setGeometry(QtCore.QRect(10, 30, 91, 20)) self.outputCheck.setObjectName(_fromUtf8("outputCheck")) self.livePlotCheck = QtGui.QCheckBox(self.groupBox) self.livePlotCheck.setEnabled(False) self.livePlotCheck.setGeometry(QtCore.QRect(10, 10, 91, 20)) self.livePlotCheck.setObjectName(_fromUtf8("livePlotCheck")) self.groupBox_2 = QtGui.QGroupBox(self.centralwidget) self.groupBox_2.setGeometry(QtCore.QRect(460, 0, 150, 50)) self.groupBox_2.setObjectName(_fromUtf8("groupBox_2")) self.deviceAreaEdit = QtGui.QLineEdit(self.groupBox_2) self.deviceAreaEdit.setGeometry(QtCore.QRect(40, 20, 71, 20)) self.deviceAreaEdit.setObjectName(_fromUtf8("deviceAreaEdit")) self.groupBox_3 = QtGui.QGroupBox(self.centralwidget) self.groupBox_3.setGeometry(QtCore.QRect(10, 300, 600, 60)) self.groupBox_3.setObjectName(_fromUtf8("groupBox_3")) self.dirEdit = QtGui.QLineEdit(self.groupBox_3) self.dirEdit.setGeometry(QtCore.QRect(90, 20, 501, 30)) self.dirEdit.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.dirEdit.setObjectName(_fromUtf8("dirEdit")) self.browseButton = QtGui.QPushButton(self.groupBox_3) self.browseButton.setGeometry(QtCore.QRect(10, 20, 75, 30)) self.browseButton.setObjectName(_fromUtf8("browseButton")) self.groupBox_4 = QtGui.QGroupBox(self.centralwidget) self.groupBox_4.setGeometry(QtCore.QRect(10, 360, 601, 60)) self.groupBox_4.setObjectName(_fromUtf8("groupBox_4")) self.fileEdit = QtGui.QLineEdit(self.groupBox_4) self.fileEdit.setGeometry(QtCore.QRect(10, 20, 580, 30)) self.fileEdit.setObjectName(_fromUtf8("fileEdit")) IVSweeper.setCentralWidget(self.centralwidget) self.menubar = QtGui.QMenuBar(IVSweeper) self.menubar.setGeometry(QtCore.QRect(0, 0, 622, 21)) self.menubar.setObjectName(_fromUtf8("menubar")) self.menuGreyRules = QtGui.QMenu(self.menubar) self.menuGreyRules.setObjectName(_fromUtf8("menuGreyRules")) IVSweeper.setMenuBar(self.menubar) self.statusbar = QtGui.QStatusBar(IVSweeper) self.statusbar.setObjectName(_fromUtf8("statusbar")) IVSweeper.setStatusBar(self.statusbar) self.actionQuit = QtGui.QAction(IVSweeper) self.actionQuit.setObjectName(_fromUtf8("actionQuit")) self.actionRun_Test_Code = QtGui.QAction(IVSweeper) self.actionRun_Test_Code.setObjectName(_fromUtf8("actionRun_Test_Code")) self.menuGreyRules.addAction(self.actionRun_Test_Code) self.menuGreyRules.addAction(self.actionQuit) self.menubar.addAction(self.menuGreyRules.menuAction()) self.retranslateUi(IVSweeper) self.speedCombo.setCurrentIndex(0) self.saveModeCombo.setCurrentIndex(1) QtCore.QObject.connect(self.actionQuit, QtCore.SIGNAL(_fromUtf8("triggered()")), IVSweeper.close) QtCore.QMetaObject.connectSlotsByName(IVSweeper) def retranslateUi(self, IVSweeper): IVSweeper.setWindowTitle(_translate("IVSweeper", "IV Sweep Dynamics Investigator", None)) self.addressGroup.setTitle(_translate("IVSweeper", "Instrument Selection", None)) self.instrumentCombo.setItemText(0, _translate("IVSweeper", "(Re)Scan for Instruments", None)) self.sweepButton.setText(_translate("IVSweeper", "Start Sweep", None)) self.terminalsGroup.setTitle(_translate("IVSweeper", "Output Terminals", None)) self.frontRadio.setToolTip(_translate("IVSweeper", "Use the terminals on the front of the device", None)) self.frontRadio.setText(_translate("IVSweeper", "Front", None)) self.rearRadio.setToolTip(_translate("IVSweeper", "Use the terminals on the rear of the device", None)) self.rearRadio.setText(_translate("IVSweeper", "Rear", None)) self.wiresGroup.setTitle(_translate("IVSweeper", "Measurement Type", None)) self.twowireRadio.setToolTip(_translate("IVSweeper", "Measure voltage across the INPUT/OUTPUT terminals", None)) self.twowireRadio.setText(_translate("IVSweeper", "Two Wire", None)) self.fourwireRadio.setToolTip(_translate("IVSweeper", "Measure voltage across the 4-WIRE SENSE terminals", None)) self.fourwireRadio.setText(_translate("IVSweeper", "Four Wire", None)) self.sweepGroup.setTitle(_translate("IVSweeper", "Sweep Setup", None)) self.label.setText(_translate("IVSweeper", "Start:", None)) self.label_2.setText(_translate("IVSweeper", "End:", None)) self.reverseButton.setText(_translate("IVSweeper", "Reverse Direction", None)) self.endSpin.setSuffix(_translate("IVSweeper", " mV", None)) self.startSpin.setSuffix(_translate("IVSweeper", " mV", None)) self.label_3.setText(_translate("IVSweeper", "Sweep Points:", None)) self.label_6.setText(_translate("IVSweeper", "Step Delay:", None)) self.autoAdvance.setToolTip(_translate("IVSweeper", "a robot chooses when to advance to the next sweep step", None)) self.autoAdvance.setText(_translate("IVSweeper", "Intelligent Advance", None)) self.deltaStep.setText(_translate("IVSweeper", "Δ=20 mV", None)) self.maxPowerCheck.setToolTip(_translate("IVSweeper", "<html><head/><body><p>DANGER: This is relatively untested and there\'s no guarentee it won\'t destroy your device. Make sure your compliance is set to prevent destruction.</p></body></html>", None)) self.maxPowerCheck.setText(_translate("IVSweeper", "Dwell @ Max Power", None)) self.delaySpinBox.setToolTip(_translate("IVSweeper", "After reaching a new source value in the sweep, this amount of time will pass before advancing to the next value", None)) self.delaySpinBox.setSuffix(_translate("IVSweeper", " s", None)) self.totalLabel.setText(_translate("IVSweeper", "tot=2.000s", None)) self.daqGroup.setTitle(_translate("IVSweeper", "Data Acquisition Settings", None)) self.zeroCheck.setToolTip(_translate("IVSweeper", "Theoretically improves accuracy at the expense of speed", None)) self.zeroCheck.setText(_translate("IVSweeper", "Auto Zero", None)) self.speedCombo.setToolTip(_translate("IVSweeper", "<html><head/><body><p>Set integration period for a single data point</p><p>• FAST — Sets speed to 0.01 PLC and sets display resolution to 3½ digits.</p><p>• MED — Sets speed to 0.10 PLC and sets display resolution to 4½ digits.</p><p>• NORMAL — Sets speed to 1.00 PLC and sets display resolution to 5½ digits.</p><p>• HI ACCURACY — Sets speed to 10.00 PLC and sets display resolution to 6½</p><p>digits.</p></body></html>", None)) self.speedCombo.setItemText(0, _translate("IVSweeper", "Fast", None)) self.speedCombo.setItemText(1, _translate("IVSweeper", "Medium", None)) self.speedCombo.setItemText(2, _translate("IVSweeper", "Normal", None)) self.speedCombo.setItemText(3, _translate("IVSweeper", "High Accuracy", None)) self.label_7.setText(_translate("IVSweeper", "Speed:", None)) self.averageSpin.setToolTip(_translate("IVSweeper", "repeating filter. danger, this *could* smear data between sweep steps, set to zero to disable", None)) self.label_8.setText(_translate("IVSweeper", "Points to average:", None)) self.saveModeCombo.setItemText(0, _translate("IVSweeper", "I,V vs t", None)) self.saveModeCombo.setItemText(1, _translate("IVSweeper", "I vs V", None)) self.label_10.setText(_translate("IVSweeper", "Mode:", None)) self.complianceGroup.setTitle(_translate("IVSweeper", "Compliance and Range", None)) self.complianceSpin.setToolTip(_translate("IVSweeper", "Set this just above the maximum you expect", None)) self.complianceSpin.setSuffix(_translate("IVSweeper", " mA", None)) self.label_9.setText(_translate("IVSweeper", "Plus and minus", None)) self.modeGroup.setTitle(_translate("IVSweeper", "Source", None)) self.sourceVRadio.setToolTip(_translate("IVSweeper", "Sweep voltage source", None)) self.sourceVRadio.setText(_translate("IVSweeper", "Voltage", None)) self.sourceIRadio.setToolTip(_translate("IVSweeper", "Sweep current source", None)) self.sourceIRadio.setText(_translate("IVSweeper", "Current", None)) self.sweepContinuallyGroup.setTitle(_translate("IVSweeper", "Consecutive Sweeps", None)) self.label_4.setText(_translate("IVSweeper", "Delay Between Scans:", None)) self.scanRecoverySpin.setSuffix(_translate("IVSweeper", " s", None)) self.label_5.setText(_translate("IVSweeper", "Number of Sweeps:", None)) self.label_11.setText(_translate("IVSweeper", "Hold Between Scans:", None)) self.comboBox.setItemText(0, _translate("IVSweeper", "L=∞", None)) self.comboBox.setItemText(1, _translate("IVSweeper", "Voc", None)) self.comboBox.setItemText(2, _translate("IVSweeper", "Jsc", None)) self.comboBox.setItemText(3, _translate("IVSweeper", "Mppt", None)) self.checkBox.setText(_translate("IVSweeper", "Toggle Shutter Between Scans", None)) self.groupBox.setTitle(_translate("IVSweeper", "Miscellaneous", None)) self.shutterButton.setText(_translate("IVSweeper", "Toggle Shutter", None)) self.displayBlankCheck.setToolTip(_translate("IVSweeper", "This blanks the Keithley\'s display during measurement, allowing for a slight increase in measurement speed", None)) self.displayBlankCheck.setText(_translate("IVSweeper", "Blank Display", None)) self.outputCheck.setText(_translate("IVSweeper", "Output On", None)) self.livePlotCheck.setText(_translate("IVSweeper", "Live Data View", None)) self.groupBox_2.setTitle(_translate("IVSweeper", "Device Area [cm^2]", None)) self.deviceAreaEdit.setToolTip(_translate("IVSweeper", "Enter Device Area Here", None)) self.deviceAreaEdit.setText(_translate("IVSweeper", "0.12", None)) self.groupBox_3.setTitle(_translate("IVSweeper", "Output Directory", None)) self.browseButton.setText(_translate("IVSweeper", "Browse", None)) self.groupBox_4.setTitle(_translate("IVSweeper", "Output File Name", None)) self.menuGreyRules.setTitle(_translate("IVSweeper", "File", None)) self.actionQuit.setText(_translate("IVSweeper", "Quit", None)) self.actionRun_Test_Code.setText(_translate("IVSweeper", "Run Test Code", None))
Carver Minnesota is our specialty. Our team is committed to making the buying and selling of single family homes in Carver, MN a pleasurable and rewarding experience. Our website allows you to search all active Carver single family homes for sale. It is easy to use and navigate through single family home searches. You can also save searches and get daily email alerts of new listings as they become available. Are you planning on buying or selling a single family home in Carver, MN? Barker Hedges Group real estate agents' proven home sales/purchase expertise will help you negotiate the sale of your current single family home and purchase of your new single family home. Barker Hedges Group Carver real estate agents are in the best position to give you advice on the local Carver market statistics. Call Barker Hedges Group at (651) 789-5001 or contact us to inquire about our single family real estate services for buyers and sellers. Would you like to know your Carver single family home's estimated value? Register to our free Carver single family home market analysis service, where we'll provide you with your single family property's current market value and suggested selling price!
"""Initial metrics Revision ID: 6f9266e7a5fb Revises: 51415576d3e9 Create Date: 2017-12-12 10:38:27.166562 """ import model.utils import sqlalchemy as sa from alembic import op from rdr_service.participant_enums import MetricSetType, MetricsKey # revision identifiers, used by Alembic. revision = "6f9266e7a5fb" down_revision = "51415576d3e9" branch_labels = None depends_on = None def upgrade(engine_name): globals()["upgrade_%s" % engine_name]() def downgrade(engine_name): globals()["downgrade_%s" % engine_name]() def upgrade_rdr(): # ### commands auto generated by Alembic - please adjust! ### pass # ### end Alembic commands ### def downgrade_rdr(): # ### commands auto generated by Alembic - please adjust! ### pass # ### end Alembic commands ### def upgrade_metrics(): # ### commands auto generated by Alembic - please adjust! ### op.create_table( "metric_set", sa.Column("metric_set_id", sa.String(length=50), nullable=False), sa.Column("metric_set_type", model.utils.Enum(MetricSetType), nullable=False), sa.Column("last_modified", model.utils.UTCDateTime(), nullable=False), sa.PrimaryKeyConstraint("metric_set_id"), schema="metrics", ) op.create_table( "aggregate_metrics", sa.Column("metric_set_id", sa.String(length=50), nullable=False), sa.Column("metrics_key", model.utils.Enum(MetricsKey), nullable=False), sa.Column("value", sa.String(length=50), nullable=False), sa.Column("count", sa.Integer(), nullable=False), sa.ForeignKeyConstraint(["metric_set_id"], ["metrics.metric_set.metric_set_id"], ondelete="CASCADE"), sa.PrimaryKeyConstraint("metric_set_id", "metrics_key", "value"), schema="metrics", ) # ### end Alembic commands ### def downgrade_metrics(): # ### commands auto generated by Alembic - please adjust! ### op.drop_table("aggregate_metrics", schema="metrics") op.drop_table("metric_set", schema="metrics") # ### end Alembic commands ###
My apologies for the erratic weather we've had so far this year. I recently realized that it's all my fault. See, in December a friend gave me a novel called Snow by Turkish author Orhan Pamuk. As I read it in fits and starts, it took me a really really long time to finish. But I'm finally done! And so now the snow can stop and spring can commence in earnest. As for why it took me so long to finish this book, well, that's all me I suppose. I kept flipping back to the front cover to verify that the seal on the front proclaiming, "Winner of the Nobel Prize in Literature!" was still there and not just something I dreamed. Later, I'd turn the book over and peruse the blurbs again. "One of the best books of the year" according to just about everyone from The New York Times Book Review to The Economist. Rave reviews from truly impressive people. Repeatedly I read the jacket copy. "Slyly comic." Also, "humor," "wicked grin," etc. But I just didn't get it. I didn't engage with the story, I didn't connect with the characters, and I felt frustrated by the pace. (The first day seemed to me like it must have been at least 48 hours long. Is Ka really in his late 30's as it appears? If so, how come the 17+ year age difference between close sisters Ipek and Kadife is never discussed?) I utterly missed the humor. Obviously, this is all on me since apparently everyone else who's read Snow loved it. But I spent the first 200 pages trying to figure out why the author gave most of the unrelated main characters the same last name (Bey). Then I figured it must be a subtle comment on the provincial nature of Turkish society (the cerebral humor I'd been missing?). By page 300 I'd realized that "Bey" must be a sort of honorific (and it is). Some of my confusion might indeed have been cultural. I certainly feel like an uncultured ignoramus for my utter failure to appreciate this highly acclaimed novel. But I finished it, and now it's spring!
from __future__ import print_function, division from collections import defaultdict from sympy.core.compatibility import range def binomial_coefficients(n): """Return a dictionary containing pairs :math:`{(k1,k2) : C_kn}` where :math:`C_kn` are binomial coefficients and :math:`n=k1+k2`. Examples ======== >>> from sympy.ntheory import binomial_coefficients >>> binomial_coefficients(9) {(0, 9): 1, (1, 8): 9, (2, 7): 36, (3, 6): 84, (4, 5): 126, (5, 4): 126, (6, 3): 84, (7, 2): 36, (8, 1): 9, (9, 0): 1} See Also ======== binomial_coefficients_list, multinomial_coefficients """ d = {(0, n): 1, (n, 0): 1} a = 1 for k in range(1, n//2 + 1): a = (a * (n - k + 1))//k d[k, n - k] = d[n - k, k] = a return d def binomial_coefficients_list(n): """ Return a list of binomial coefficients as rows of the Pascal's triangle. Examples ======== >>> from sympy.ntheory import binomial_coefficients_list >>> binomial_coefficients_list(9) [1, 9, 36, 84, 126, 126, 84, 36, 9, 1] See Also ======== binomial_coefficients, multinomial_coefficients """ d = [1] * (n + 1) a = 1 for k in range(1, n//2 + 1): a = (a * (n - k + 1))//k d[k] = d[n - k] = a return d def multinomial_coefficients0(m, n, _tuple=tuple, _zip=zip): """Return a dictionary containing pairs ``{(k1,k2,..,km) : C_kn}`` where ``C_kn`` are multinomial coefficients such that ``n=k1+k2+..+km``. For example: >>> from sympy import multinomial_coefficients >>> multinomial_coefficients(2, 5) # indirect doctest {(0, 5): 1, (1, 4): 5, (2, 3): 10, (3, 2): 10, (4, 1): 5, (5, 0): 1} The algorithm is based on the following result: Consider a polynomial and its ``n``-th exponent:: P(x) = sum_{i=0}^m p_i x^i P(x)^n = sum_{k=0}^{m n} a(n,k) x^k The coefficients ``a(n,k)`` can be computed using the J.C.P. Miller Pure Recurrence [see D.E.Knuth, Seminumerical Algorithms, The art of Computer Programming v.2, Addison Wesley, Reading, 1981;]:: a(n,k) = 1/(k p_0) sum_{i=1}^m p_i ((n+1)i-k) a(n,k-i), where ``a(n,0) = p_0^n``. """ if not m: if n: return {} return {(): 1} if m == 2: return binomial_coefficients(n) symbols = [(0,)*i + (1,) + (0,)*(m - i - 1) for i in range(m)] s0 = symbols[0] p0 = [_tuple(aa - bb for aa, bb in _zip(s, s0)) for s in symbols] r = {_tuple(aa*n for aa in s0): 1} l = [0] * (n*(m - 1) + 1) l[0] = r.items() for k in range(1, n*(m - 1) + 1): d = defaultdict(int) for i in range(1, min(m, k + 1)): nn = (n + 1)*i - k if not nn: continue t = p0[i] for t2, c2 in l[k - i]: tt = _tuple([aa + bb for aa, bb in _zip(t2, t)]) d[tt] += nn*c2 if not d[tt]: del d[tt] r1 = [(t, c//k) for (t, c) in d.items()] l[k] = r1 r.update(r1) return r def multinomial_coefficients(m, n): r"""Return a dictionary containing pairs ``{(k1,k2,..,km) : C_kn}`` where ``C_kn`` are multinomial coefficients such that ``n=k1+k2+..+km``. For example: >>> from sympy.ntheory import multinomial_coefficients >>> multinomial_coefficients(2, 5) # indirect doctest {(0, 5): 1, (1, 4): 5, (2, 3): 10, (3, 2): 10, (4, 1): 5, (5, 0): 1} The algorithm is based on the following result: .. math:: \binom{n}{k_1, \ldots, k_m} = \frac{k_1 + 1}{n - k_1} \sum_{i=2}^m \binom{n}{k_1 + 1, \ldots, k_i - 1, \ldots} Code contributed to Sage by Yann Laigle-Chapuy, copied with permission of the author. See Also ======== binomial_coefficients_list, binomial_coefficients """ if not m: if n: return {} return {(): 1} if m == 2: return binomial_coefficients(n) if m >= 2*n and n > 1: return dict(multinomial_coefficients_iterator(m, n)) t = [n] + [0] * (m - 1) r = {tuple(t): 1} if n: j = 0 # j will be the leftmost nonzero position else: j = m # enumerate tuples in co-lex order while j < m - 1: # compute next tuple tj = t[j] if j: t[j] = 0 t[0] = tj if tj > 1: t[j + 1] += 1 j = 0 start = 1 v = 0 else: j += 1 start = j + 1 v = r[tuple(t)] t[j] += 1 # compute the value # NB: the initialization of v was done above for k in range(start, m): if t[k]: t[k] -= 1 v += r[tuple(t)] t[k] += 1 t[0] -= 1 r[tuple(t)] = (v * tj) // (n - t[0]) return r def multinomial_coefficients_iterator(m, n, _tuple=tuple): """multinomial coefficient iterator This routine has been optimized for `m` large with respect to `n` by taking advantage of the fact that when the monomial tuples `t` are stripped of zeros, their coefficient is the same as that of the monomial tuples from ``multinomial_coefficients(n, n)``. Therefore, the latter coefficients are precomputed to save memory and time. >>> from sympy.ntheory.multinomial import multinomial_coefficients >>> m53, m33 = multinomial_coefficients(5,3), multinomial_coefficients(3,3) >>> m53[(0,0,0,1,2)] == m53[(0,0,1,0,2)] == m53[(1,0,2,0,0)] == m33[(0,1,2)] True Examples ======== >>> from sympy.ntheory.multinomial import multinomial_coefficients_iterator >>> it = multinomial_coefficients_iterator(20,3) >>> next(it) ((3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), 1) """ if m < 2*n or n == 1: mc = multinomial_coefficients(m, n) for k, v in mc.items(): yield(k, v) else: mc = multinomial_coefficients(n, n) mc1 = {} for k, v in mc.items(): mc1[_tuple(filter(None, k))] = v mc = mc1 t = [n] + [0] * (m - 1) t1 = _tuple(t) b = _tuple(filter(None, t1)) yield (t1, mc[b]) if n: j = 0 # j will be the leftmost nonzero position else: j = m # enumerate tuples in co-lex order while j < m - 1: # compute next tuple tj = t[j] if j: t[j] = 0 t[0] = tj if tj > 1: t[j + 1] += 1 j = 0 else: j += 1 t[j] += 1 t[0] -= 1 t1 = _tuple(t) b = _tuple(filter(None, t1)) yield (t1, mc[b])
Since the early 1800s, state committees and legislatures have been drawing districts in order to win elections by splitting and grouping populations to promote their chances of victory, a process called gerrymandering. Little consensus can be found in past work as some studies claim that current partisan gridlock is partially related to this procedure, while other works have found that sorting and the spatial distribution of partisanship account for gridlock. This exercise seeks to measure the impact of gerrymandering by comparing the party makeup of the current U.S. House delegation to the natural partisan makeup of a state as determined by a randomized process. This project removes political bias in the redistricting process through a series of Monte Carlo simulations to randomly assign Census tracts to ad hoc districts that are within one percent population of each other in a given state. These aggregated districts and corresponding demographic data are then compared to historical House election results from the modern era to produce likely victors using a regression model. This approach determines a framework for the natural partisanship of the congressional delegation from each state. The delegation suggested by the regression model is then compared to the actual partisan makeup of each delegation, producing evidence that is used to evaluate the impact of current redistricting practices on the party makeup of Congress. This process can be used to predict the election results of potential redistricting plans, and potentially identify the use of gerrymandering in a way that can have serious implications for litigation and policymaking surrounding redistricting. Clark, Jesse T., "Determining an Expected House Majority Using Pattern Analysis" (2016). Honors College. 375.
#-------------------------------------------------- # Revision = $Rev: 13 $ # Date = $Date: 2011-07-31 00:39:24 +0200 (Sun, 31 Jul 2011) $ # Author = $Author: stefan $ #-------------------------------------------------- from uncertainties import ufloat, nominal_value, std_dev from sympy import * #class vefloat(): # value = float # error = float # # def __init__(self, value=0.,error=0.): # self.value = value # self.error = abs(error) # # def __str__(self): # return "%g+-%g" % (self.value, self.error) # # def __repr__(self): # return "vefloat(%s, %s)" % (self.value, self.error) # # def __float__(self): # return self.value def gaussian_error(term, *errors): return sqrt(reduce(Add, ( (term.diff(var)*Symbol("sigma_"+var.name))**2 for var in term.atoms(Symbol) if var.name in errors), 0.)) def gaussian_error_ufloat(term, **vars): st = gaussian_error(term, *vars.keys()) subs = {} for k,v in vars.iteritems(): subs[Symbol(k)] = nominal_value(v) subs[Symbol("sigma_"+k)] = std_dev(v) return ufloat((term.subs(subs),st.n(subs=subs, maxprec=10))) if __name__ == "__main__": fx = ufloat((1,.5)) fy = ufloat((4,.5)) print "error propagation analytically" x,y = symbols("xy") at = (x**2+y**2)/(x*y) print gaussian_error(at, "x", "y") print gaussian_error_ufloat(at, x=fx, y=fy) print "error propagation numerically" nt = (fx**2+fy**2)/(fx*fy) print nt
The SelfieLight ELITE 18’ is finally here! Transform the game with the latest and best in Ring Light technology! This Ring Light is fitted with two power supply options: you can use the power cord for conventional electricity supply or an awesome battery function for on the go shooting. This Ring Light is portable and light and can be used basically anywhere without electricity. Say goodbye to non-productivity during power failures and hello to snapping at any location! Professional lighting for your photography and videography whenever and where ever you're ready to shoot. - PLEASE ALLOW 7-15 BUSINESS DAYS FOR ALL PRE-ORDERS!
from .resource import Resource from .database import Database try: import urllib.parse as urlparse except ImportError: import urlparse class Account(Resource): """ An account to a Cloudant or CouchDB account. # connects to http://localhost:5984 # if a string is passed, connects to %s.cloudant.com account = cloudant.Account() response = account.login(USERNAME, PASSWORD) print response.json() # { "ok": True, ... } Like all Cloudant-Python objects, pass `async=True` to make asynchronous requests, like this: account = cloudant.Account(async=True) future = account.login(USERNAME, PASSWORD) response = future.result() print response.json() # { "ok": True, ... } Although you can use `login` to request a cookie, you can also set `account._session.auth` to make Cloudant-Python use those credentials on every request, like this: account = cloudant.Account() account._session.auth = (username, password) """ def __init__(self, uri="http://localhost:5984", **kwargs): if not urlparse.urlparse(uri).scheme: uri = "https://%s.cloudant.com" % uri super(Account, self).__init__(uri, **kwargs) def database(self, name, **kwargs): """Create a `Database` object prefixed with this account's URL.""" opts = dict(self.opts, **kwargs) return Database(self._make_url(name), session=self._session, **opts) def __getitem__(self, name): """Shortcut to `Account.database`.""" return self.database(name, **self.opts) def __delitem__(self, name): """ Delete a database named `name`. Blocks until the response returns, and raises an error if the deletion failed. """ response = self.database(name, **self.opts).delete() # block until result if the object is using async if hasattr(response, 'result'): response = response.result() response.raise_for_status() def session(self, **kwargs): """Get current user's authentication and authorization status.""" return self.get(self._reset_path('_session'), **kwargs) def login(self, username, password, **kwargs): """Authenticate the connection via cookie.""" # set headers, body explicitly headers = { "Content-Type": "application/x-www-form-urlencoded" } data = "name=%s&password=%s" % (username, password) return self.post(self._reset_path('_session'), headers=headers, data=data, **kwargs) def logout(self, **kwargs): """De-authenticate the connection's cookie.""" return self.delete(self._reset_path('_session'), **kwargs) def all_dbs(self, **kwargs): """List all databases.""" return self.get('_all_dbs', **kwargs) def active_tasks(self, **kwargs): """List replication, compaction, and indexer tasks currently running.""" return self.get('_active_tasks', **kwargs) def replicate(self, source, target, opts={}, **kwargs): """ Begin a replication job. `opts` contains replication options such as whether the replication should create the target (`create_target`) or whether the replication is continuous (`continuous`). Note: unless continuous, will not return until the job is finished. """ params = { 'source': source, 'target': target } params.update(opts) if 'params' in kwargs: params.update(kwargs['params']) del kwargs['params'] return self.post('_replicate', params=params, **kwargs) def uuids(self, count=1, **kwargs): """Generate an arbitrary number of UUIDs.""" params = dict(count=count) return self.get('_uuids', params=params, **kwargs)
Detectives from Transnational Organised Crime Unit have rescued 12 Nepalese women in Nyali, Mombasa county. The women were arrested during a raid at Rangeela grill and bar at Amkay Plaza in Nyali. According to a tweet from DCI on Saturday, April 13, the owner of the club identified as Asif Amirali Alibhai Jetha, a Canadian national, was arrested in connection with the crime. The 12 were said to be in the country illegally and were found while entertaining revelers in a Nyali-based club. During the impromptu search, the sleuths recovered money, mobile phones and some documents. Jetha and the immigrants were locked up at Nyali police station pending further investigations.
#!/usr/bin/env python # -*- coding: utf-8 -*- ################################################################################ # Copyright (C) 2012 Travis Shirk <[email protected]> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # ################################################################################ from eyed3.id3 import Tag from eyed3.id3 import ID3_V1_0, ID3_V1_1, ID3_V2_3, ID3_V2_4 import logging from eyed3 import log log.setLevel(logging.DEBUG) t = Tag() t.artist = u"M.O.P." t.title = u"How About Some Hardcore" t.album = u"To The Death" t.genre = u"Hip-Hop" t.track_num = (3,5) t.disc_num = (1,1) t.original_release_date = "1994-04-07" t.release_date = "1994-04-07" t.encoding_date = "2002-03" t.recording_date = 1996 t.tagging_date = "2012-2-5" t.comments.set(u"Gritty, yo!") t.comments.set(u"Brownsville, Brooklyn", u"Origin") t.user_text_frames.set(u"****", u"Rating") t.artist_url = b"http://allmusic.com/artist/mop-p194909" t.user_url_frames.set(b"http://eyed3.nicfit.net/") t.bpm = 187 t.play_count = 125 t.unique_file_ids.set(b"43e888e067ea107f964916af6259cbe7", "md5sum") t.cd_id = b"\x3c\x33\x4d\x41\x43\x59\x3c\x33" t.privates.set("Secrets", "Billy Danzenie") t.terms_of_use = u"Blunted" t.lyrics.set(u""" [ Billy Danzenie ] How about some hardcore? (Yeah, we like it raw!) (4x) How about some hardcore? [ VERSE 1: Billy Danzenie ] (Yeah, we like it raw in the streets) For the fellas on the corner posted up 20 deep With your ifth on your hip, ready to flip Whenever you empty your clip, dip, trip your sidekick You got skill, you best manage to chill And do yourself a favor, don`t come nowhere near the Hill With that bullshit, word, money grip, it`ll cost ya Make you reminisce of Frank Nitty `The Enforcer` I move with M.O.P.`s Last Generation Straight up and down, act like you want a confrontation I packs my gat, I gotta stay strapped I bust mines, don`t try to sneak up on me from behind Don`t sleep, I get deep when I creep I see right now I got to show you it ain`t nothin sweet Go get your muthaf**kin hammer And act like you want drama I send a message to your mama `Hello, do you know your one son left? I had license to kill and he had been marked for death He`s up the Hill in the back of the building with two in the dome I left him stiffer than a tombstone` [ Li`l Fame ] How about some hardcore? (Yeah, we like it raw!) (4x) How about some hardcore? [ VERSE 2: Billy Danzenie ] (Yeah, we like it rugged in the ghetto) I used to pack sling shots, but now I`m packin heavy metal A rugged underground freestyler Is Li`l Fame, muthaf**ka, slap, Li`l Mallet When I let off, it`s a burning desire Niggas increase the peace cause when I release it be rapid fire For the cause I drop niggas like drawers Niggas`ll hit the floors from the muthaf**kin .44`s I`m talkin titles when it`s showtime f**k around, I have niggas call the injury help line I bust words in my verse that`ll serve Even on my first nerve I put herbs to curbs I ain`t about givin niggas a chance And I still raise sh*t to make my brother wanna get up and dance Front, I make it a thrill to kill Bringin the ruckus, it`s the neighborhood hoods for the Hill that`s real Me and mics, that`s unlike niggas and dykes So who wanna skate, cause I`m puttin niggas on ice Whatever I drop must be rough, rugged and hard more (Yeah!) [ Billy Danzenie ] How about some hardcore? (Yeah, we like it raw!) (4x) [ VERSE 3: Billy Danzenie ] Yo, here I am (So what up?) Get it on, cocksucker That nigga Bill seem to be a ill black brother I gets dough from the way I flow And before I go You muthaf**kas gonna know That I ain`t nothin to f**k with - duck quick I squeeze when I`m stressed Them teflons`ll tear through your vest I love a bloodbath (niggas know the half) You can feel the wrath (Saratoga/St. Marks Ave.) B-i-l-l-y D-a-n-z-e n-i-e, me, Billy Danzenie (Knock, knock) Who`s there? (Li`l Fame) Li`l Fame who? (Li`l Fame, your nigga) Boom! Ease up off the trigger It`s aight, me and shorty go to gunfights Together we bring the ruckus, right? We trump tight, aight? I earned mine, so I`m entitled to a title (7 f**kin 30) that means I`m homicidal [ Li`l Fame ] How about some hardcore? (Yeah, we like it raw!) (4x) [ VERSE 4: Li`l Fame ] Yo, I scream on niggas like a rollercoaster To them wack muthaf**kas, go hang it up like a poster Niggas get excited, but don`t excite me Don`t invite me, I`m splittin niggas` heads where the white be Try to trash this, this little bastard`ll blast it Only puttin niggas in comas and caskets I ain`t a phoney, I put the `mack` in a -roni I leave you lonely (Yeah, yeah, get on his ass, homie) Up in your anus, I pack steel that`s stainless We came to claim this, and Li`l Fame`ll make you famous I mack hoes, rock shows and stack dough Cause I`m in effect, knockin muthaf**kas like five-o I`m catchin other niggas peepin, shit, I ain`t sleepin I roll deep like a muthaf**kin Puerto-Rican So when I write my competition looks sadly For broke-ass niggas I make it happen like Mariah Carey I got sh*t for niggas that roll bold Li`l Fame is like a orthopedic shoe, I got mad soul I`ma kill em before I duck em Because yo, mother made em, mother had em and muthaf**k em [ Li`l Fame ] Knowmsayin? Li`l Fame up in this muthaf**ka Givin shoutouts to my man D/R Period [Name] Lazy Laz My man Broke As* Moe The whole Saratoga Ave. Youknowmsayin? Representin for Brooklyn Most of all my cousin Prince Leroy, Big Mal, rest in peace [ Billy Danzenie ] Danzenie up in this muthaf**ka I`d like to say what`s up to the whole M.O.P. Brooklyn, period Them niggas that just don`t give a f**k [ O.G. Bu-Bang Bet yo ass, nigga Hey yo, this muthaf**kin Babyface [Name] Aka O.G. Bu-Bang Yo, I wanna say what`s up to the whole muthaf**kin M.O.P. boyyeee """) t.save("example-v2_4.id3", version=ID3_V2_4) t.save("example-v2_3.id3", version=ID3_V2_3) # Loss of the release date month and day. # Loss of the comment with description. t.save("example-v1_1.id3", version=ID3_V1_1) # Loses what v1.1 loses, and the track # t.save("example-v1_0.id3", version=ID3_V1_0) ''' from eyed3.id3.tag import TagTemplate template = "$artist/"\ "$best_release_date:year - $album/"\ "$artist - $track:num - $title.$file:ext" print TagTemplate(template).substitute(t, zeropad=True) '''
I see a shadow and whisper to a friend, "A mugger!" My friend focuses on the same shadow and knows it’s just a shadow. Why are our experiences so different? Because of our past experiences. My past programs determine , what I focus on and the meaning I give to it.The same is true for you. Or I may take a victimizer position and blame the interviewers, "They didn’t give me a chance. They don’t like the color of my skin. It’s not fair. They're jerks anyway." What about you? How much choice do have? How eager are you to know the truth? If you feel stuck,don’t be disheartened.The Choice-Cube®Method can help you understand and manage your focus and reactions. Dr. Beth Cujé, therapist and author of the book, Become the Person You Were Meant to Be, is giving you the opportunity to download the first chapter of the book for FREE. Just click here and see what the Choice-Cube Method® can do for you today.
#========================================================================== # # Copyright Insight Software Consortium # # 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.txt # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # #==========================================================================*/ from __future__ import print_function import sys import unittest import datetime as dt import timeit import SimpleITK as sitk import numpy as np sizeX = 4 sizeY = 5 sizeZ = 3 newSimpleITKPixelValueInt32 = -3000 newNumPyElementValueInt32 = 200 class TestNumpySimpleITKMemoryviewInterface(unittest.TestCase): """ This tests numpy array <-> SimpleITK Image conversion. """ def setUp(self): pass def _helper_check_sitk_to_numpy_type(self, sitkType, numpyType): if sitkType == sitk.sitkUnknown: return image = sitk.Image((9, 10), sitkType, 1) a = sitk.GetArrayViewFromImage(image) self.assertEqual(numpyType, a.dtype) self.assertEqual((10, 9), a.shape) def test_type_to_numpy(self): "try all sitk pixel types to convert to NumPy array view" self._helper_check_sitk_to_numpy_type(sitk.sitkUInt8, np.uint8) self._helper_check_sitk_to_numpy_type(sitk.sitkUInt16, np.uint16) self._helper_check_sitk_to_numpy_type(sitk.sitkUInt32, np.uint32) self._helper_check_sitk_to_numpy_type(sitk.sitkUInt64, np.uint64) self._helper_check_sitk_to_numpy_type(sitk.sitkInt8, np.int8) self._helper_check_sitk_to_numpy_type(sitk.sitkInt16, np.int16) self._helper_check_sitk_to_numpy_type(sitk.sitkInt32, np.int32) self._helper_check_sitk_to_numpy_type(sitk.sitkInt64, np.int64) self._helper_check_sitk_to_numpy_type(sitk.sitkFloat32, np.float32) self._helper_check_sitk_to_numpy_type(sitk.sitkFloat64, np.float64) self._helper_check_sitk_to_numpy_type(sitk.sitkVectorUInt8, np.uint8) self._helper_check_sitk_to_numpy_type(sitk.sitkVectorInt8, np.int8) self._helper_check_sitk_to_numpy_type(sitk.sitkVectorUInt16, np.uint16) self._helper_check_sitk_to_numpy_type(sitk.sitkVectorInt16, np.int16) self._helper_check_sitk_to_numpy_type(sitk.sitkVectorUInt32, np.uint32) self._helper_check_sitk_to_numpy_type(sitk.sitkVectorInt32, np.int32) self._helper_check_sitk_to_numpy_type(sitk.sitkVectorUInt64, np.uint64) self._helper_check_sitk_to_numpy_type(sitk.sitkVectorInt64, np.int64) self._helper_check_sitk_to_numpy_type(sitk.sitkVectorFloat32, np.float32) self._helper_check_sitk_to_numpy_type(sitk.sitkVectorFloat64, np.float64) def test_to_numpy_and_back(self): """Test converting an image to NumPy array view and back""" img = sitk.GaussianSource( sitk.sitkFloat32, [100,100], sigma=[10]*3, mean=[50,50] ) h = sitk.Hash( img ) img2 = sitk.GetImageFromArray( sitk.GetArrayViewFromImage(img)) self.assertEqual( h, sitk.Hash( img2 )) def test_vector_image_to_numpy(self): """Test converting back and forth between NumPy array view and SimpleITK images where the SimpleITK image has multiple components and stored as a VectorImage.""" # Check 2D img = sitk.PhysicalPointSource(sitk.sitkVectorFloat32, [3,4]) h = sitk.Hash( img ) nda = sitk.GetArrayViewFromImage(img) self.assertEqual(nda.shape, (4,3,2)) self.assertEqual(nda[0,0].tolist(), [0,0]) self.assertEqual(nda[2,1].tolist(), [1,2]) self.assertEqual(nda[0,:,0].tolist(), [0,1,2]) img2 = sitk.GetImageFromArray(nda, isVector=True) self.assertEqual(h, sitk.Hash(img2)) # check 3D img = sitk.PhysicalPointSource(sitk.sitkVectorFloat32, [3,4,5]) h = sitk.Hash(img) nda = sitk.GetArrayViewFromImage(img) self.assertEqual(nda.shape, (5,4,3,3)) self.assertEqual(nda[0,0,0].tolist(), [0,0,0]) self.assertEqual(nda[0,0,:,0].tolist(), [0,1,2]) self.assertEqual(nda[0,:,1,1].tolist(), [0,1,2,3]) img2 = sitk.GetImageFromArray(nda) self.assertEqual(img2.GetSize(), img.GetSize()) self.assertEqual(img2.GetNumberOfComponentsPerPixel(), img.GetNumberOfComponentsPerPixel()) self.assertEqual(h, sitk.Hash(img2)) def test_arrayview_writable(self): """Test correct behavior of writablity to the returned array view.""" img = sitk.Image((9, 10), sitk.sitkFloat32, 1) a = sitk.GetArrayViewFromImage(img) with self.assertRaises(ValueError): a.fill(0) def test_processing_time(self): """Check the processing time the conversions from SimpleITK Image to numpy array (GetArrayViewFromImage) and numpy memoryview (GetArrayViewFromImage).""" # Performance test for SimpleITK Image -> NumPy array img = sitk.GaussianSource(sitk.sitkFloat32, [3000,3000], sigma=[10]*3, mean=[50,50]) print("\nGet NumPy array from 3000x3000 SimpleITK Image") nparray_time_elapsed = min(timeit.repeat(lambda: sitk.GetArrayFromImage(img), repeat=5, number=1)) print ("Processing time of GetArrayFromImage (Copy operation) :: {0} (us)".format(nparray_time_elapsed*1e6)) npview_time_elapsed = min(timeit.repeat(lambda: sitk.GetArrayViewFromImage(img), repeat=5, number=1)) print ("Processing time of GetArrayViewFromImage (Array view) :: {0} (us)".format(npview_time_elapsed*1e6)) self.assertTrue( nparray_time_elapsed > npview_time_elapsed) # Performance test for NumPy array -> SimpleITK Image Big_nparray = np.zeros((3000,3000), dtype=np.int64); if __name__ == '__main__': unittest.main()
Having a sand mound drainage system is not like having a traditional leaching field. You have to take special care of it, or else it can start to experience issues. Since it is known to be a very complicated wastewater treatment system, you should pay close attention to any warning signs it may present. One such warning sign is wet spots on your sand mound. If you have wet spots currently call your local septic expert right away. In the mean time. We will tell you a few ways to help with fixing and preventing sand mound wet spots. Why should you learn about fixing and preventing sand mound wet spots? Well, the most obvious reason for this is because you own the property. You should know every nook and cranny of your yard and house, especially when it’s all about your sand mound system. Your property has a high water table and aberrant soil. It is raised above the ground to adjust to that high water table and filter systems to make the soil suitable for wastewater treatment. Since you were just a newbie in the world of homeownership, you weren’t able to do some of the proper things that you should do when it comes to the use and maintenance of your sand mound system. If you are a homeowner, your main responsibility for your sand mound system is to maintain a regular pump out schedule. You have to keep the sludge level at normal levels so that clogging and blockages would be prevented or treated. Pump outs depend on the number of people that stay in your home. Talk to your septic expert about the living situation in your home so that a proper pump out scheduling could be made and kept. This would definitely help to fix and prevent sand mound wet spots. Blockages can be result from the dumping of non-biodegradable materials and grease, tree roots, and high water load. Grease and non-biodegradable materials cannot be degraded by the resident bacteria in the sand mound system. They will just stay there and clog the entire system. Tree roots invade the sand mound system in search of nutrient-rich wastewater. These roots will eventually make cracks and gaps that will give way to leaks. You should remove the roots manually and relocate the plants to an area away from the sand mound system to fix and prevent the sand mound wet spots. The high water load caused by heavy rains and heavy laundry batches stir up the sludge that clog the soil absorption system and the filter system. Install a dry well to help with the grey water from your washing machine and dishwasher. Divert the rain gutter away from the sand mound system to help prevent the formation of wet spots. The use of harsh chemicals and antibacterial cleaners kill off the resident bacteria in the sand mound system. Without bacteria, the solid waste materials will not be broken down, thus clogging the system and forming the sand mound wet spots. Use environment-friendly and bacteria-friendly solutions to get the job done while caring for the bacteria. The sand mound system components might be damaged because of the tree roots that are after the wastewater, old age of the sand mound parts, and soil compaction brought about by the heavy weight of vehicles and structure over and near the area of the sand mound system. The vehicles, trees, and structures should be moved to another area. The deteriorated parts should be replaced immediately. All these should be taken care of to prevent the leaks from forming sand mound wet spots. It was a brand new thing for you to learn about fixing and preventing the sand mound wet spots. Even if it was hard to promise your septic expert to keep the scheduled treatments and use the system properly, you did it because you knew that the lifespan of your property depended on what you did. Sand mound wet spots may be warning signs for a failing system and you wouldn’t want that to appear on your lawn again.
#!/usr/bin/env python3 # # Copyright 2018, Andreas Ziegler <[email protected]> # # This file is part of librarytrader. # # librarytrader 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. # # librarytrader 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 librarytrader. If not, see <http://www.gnu.org/licenses/>. import collections import os import re import sys # In order to be able to use librarytrader from git without having installed it, # add top level directory to PYTHONPATH sys.path.append(os.path.join(os.path.abspath(os.path.dirname(__file__)), '..')) from librarytrader.librarystore import LibraryStore def normalize(path): return re.sub(r'\W', '_', path[1:]) storepath = sys.argv[1] collectpath = sys.argv[2] uprobe_file_path = sys.argv[3] num_to_path = {} with open(uprobe_file_path, 'r') as infd: for line in infd: line = line.strip() name, path_and_offset = line.split(' ', 1) path, offset = path_and_offset.split(':') num_to_path[name[2:]] = (path, int(offset, 16)) store = LibraryStore() store.load(storepath) parsed_mapping = collections.defaultdict(set) matches_global = 0 matches_local = 0 traced_only_binaries = 0 traced_only_libraries = 0 histo_by_lib_global = collections.defaultdict(int) histo_by_lib_local = collections.defaultdict(int) with open(collectpath, 'r') as collectfd: for line in collectfd: line = line.strip() path, offset = num_to_path[line] lib = store.get(path) if not lib: print('ERROR: {} not found!'.format(path)) continue fnames = lib.exported_addrs[offset] print(offset, fnames) if not fnames: if offset in lib.local_functions: matches_local += 1 if offset not in lib.local_users or len(lib.local_users[offset]) == 0 \ or set(lib.local_users[offset]) == set(['EXTERNAL']): print('LOCAL: traced usage but no static user: {}:{}'.format(lib.fullname, hex(offset))) histo_by_lib_local[lib.fullname] += 1 if ".so" in lib.fullname: print('{}:{}:{}'.format(lib.fullname, offset, lib.ranges[offset])) traced_only_libraries += 1 else: traced_only_binaries += 1 # parsed_mapping[lib.fullname].add('LOCAL_{}'.format(offset)) for name in lib.local_functions[offset]: parsed_mapping[lib.fullname].add('LOCAL_{}'.format(name)) print('LOCAL_{}'.format(offset), 'name set: {}'.format(lib.local_functions[offset])) else: print('no functions for {}:{}'.format(lib.fullname, hex(offset))) continue matches_global += 1 if offset not in lib.export_users or len(lib.export_users[offset]) == 0 \ or set(lib.export_users[offset]) == set(['EXTERNAL']): print('EXPORT: traced usage but no static user: {}:{}'.format(lib.fullname, fnames)) if fnames[0] != '_init' and fnames[0] != '_fini': histo_by_lib_global[lib.fullname] += 1 if ".so" in lib.fullname: print('{}:{}:{}'.format(lib.fullname, offset, lib.ranges[offset])) traced_only_libraries += 1 else: traced_only_binaries += 1 parsed_mapping[lib.fullname].add(fnames[0]) n_export = 0 n_local = 0 n_lib = 0 for library in store.get_library_objects(): if ".so" in library.fullname: n_lib += 1 n_export += len(library.exported_addrs) n_local += len(library.local_functions) mittel = n_export // n_lib mittel_local = n_local // n_lib print('global matches: {}, local matches: {}, traced only: bin {}, lib {}, avg exports {}, local {}, n_lib {}'.format(matches_global, matches_local, traced_only_binaries, traced_only_libraries, mittel, mittel_local, n_lib)) with open(collectpath + '.matched', 'w') as outfd: for lib, names in parsed_mapping.items(): for name in names: outfd.write('{}:{}\n'.format(lib, name)) with open(collectpath + '.missed.local', 'w') as outfd: for path, num in sorted(histo_by_lib_local.items(), key=lambda x:x[1]): local_hit_path = len([x for x in parsed_mapping[path] if x.startswith("LOCAL_")]) outfd.write('{}:{}:{}:{}\n'.format(num, len(store[path].local_functions), local_hit_path, path)) with open(collectpath + '.missed.global', 'w') as outfd: for path, num in sorted(histo_by_lib_global.items(), key=lambda x:x[1]): global_hit_path = len([x for x in parsed_mapping[path] if not x.startswith("LOCAL_")]) outfd.write('{}:{}:{}:{}\n'.format(num, len(store[path].exported_addrs), global_hit_path, path))
The fact that he was in love with Emma had been confronting him for some time, but he had pushed it away and given other names to the emotions that ought to have enlightened him. He had blundered on, deaf to the pleadings of his heart until the revelation of them burst on him in a surprising and, it must be said, inconvenient way. No doubt he had appeared as a complete imbecile tonight, standing there in a trance and unable to do anything but watch Emma as he acknowledged to himself for the first time that it was not because he was a partial old friend that he admired her dancing and her figure and her liveliness—it was because he wanted her for himself. Ever prudent, inner-directed and thoughtful, George Knightley struggles with his feelings for Emma. Is she more like a little sister or a girlfriend? Can he really handle her conceited and sometimes impudent ways? Would marriage with her be a constant string of reprimands and eye-rolls for being so precocious? Boy oh boy Mr. Knightely is confused, and probably more so than you thought from your Emma readings. George Knightley, Esquire, by Barbara Cornthwaite, is a delightful re-telling of Emma that gives Mr. Knightley a chance to shine. Truth be told, I went into this review kicking and screaming. Emma is my least favorite Jane Austen novel, mostly because it seems like a story that happens in high school (and as the movie Clueless shows us, I’m not entirely wrong). Emma herself seems an over-inflated child of idle pleasures to me, a quality which might really lend itself to a story if only something would happen! It plods along with the pace of a turtle walking through molasses. Despite the work being from the lovely Jane Austen and therefore commanding instant respect, Emma gets a big ‘ol “meh” and a dismissive hand wave from me. I tell you this only so you can fully understand the breadth of my meaning when I ask, is it a crime to like the re-telling better than the original? Because well, I did. SURPRISE! George Knightley, Esquire was a delight. Written from the perspective of the oft-unexplored quiet life of the neighborhood bachelor, it makes the reader privy to all kinds of mindful musings, delicious realizations (WOW! I LOVE EMMA!), and even bouts of loneliness spent in front of the fire in the soft gloom of Donwell Abbey’s library. George Knightely goes about his business keenly aware of his surroundings and indeed, of all Emma’s schemes and shortcomings while he moves about his lands. It was wonderful to see the rarely-exposed work life of a gentleman, with all his account balancing, estate visits, charity donations, and efforts to rebuild a cottage for one of his residents. It was even more wonderful to point and laugh at Emma, whose actions seem positively absurd when seen through the clear mind of Mr. Knightley. I found myself laughing more than once. George Knightley, Esquire is but half the story of Emma and her silliness, leaving off at the moment when Frank Churchill heads for the hills instead of the dance floor and leaves Mr. Knightley to muse about whether he should be open with Emma about his feelings. He’s consumed with love for her but won’t say it. How very English. Hope remains, however, and it becomes obvious that Knightley and Emma are truly great friends with a mutual adoration for one another (despite the fact that many days go by where one is ignored by the other or haunted by japes and snarky comments). It’s really quite adorable, made only better by Barbara Cornthwaite’s mastery of prose and storytelling. The book is teeming with interest and intrigue and will leaving you grumbling when it’s over, especially when you realize that the sequel isn’t available until August 25th. No matter, though! This will keep you entertained until then! This is Emma, but better!
from distutils.core import setup setup( name='GA_lite', version='0.1.0', author='Val Lyashov', author_email='[email protected]', packages=['ga_lite', 'ga_lite.test'], url='http://pypi.python.org/pypi/ga_lite/', license='LICENSE.txt', description='A lite Google Analytics Data Export API library.', long_description=open('README.txt').read(), install_requires=[ 'requests >= 0.11.0', 'pysqlite >= 2.0.0' ], classifiers=( 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Natural Language :: English', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.0', 'Programming Language :: Python :: 3.1', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', ), )
Known as the Picasso of India, Maqbool Fida Husain was born in 1915 in Pandharpur in Maharashtra. He studied at Indore Art College before moving to Bombay where he went through a period of painting cinema hoardings. In 1947, he was one of the founding members of the Progressive Artists Group along with F. N. Souza, Khrishna Hawlaji Ara, Sayed Haider Raza and Sadanand K. Bakre. He participated in or has been the subject of numerous exhibitions throughout the world, including Sao Paulo Biennale in 1971, the Contemporary Indian Art exhibition at the Royal Academy, London, in 1982 and the India, Myth and Reality: Aspects of Contemporary Indian Art exhibition at the MoMA, New York, in 1982. There have been many publications on his work, notably Richard Bartholomew and Shiv Kapur’s monograph. He was also a film-maker, his popular film ‘Gaja Gamini’ with Madhuri Dixit. He was member of the Indian Parliament from 1986 to 1992. He spent his last remaining years between Dubai, Doha and London. M F Husain passed away in London in 2011. 2007 Raja Ravi Varma Award, Government of Kerala. 2007 Honorary Doctorates, Benaras Hindu University (BHU), Varanasi. 2007 Honorary Doctorates, Jamia Millia Islamia University, New Delhi. 2007 Honorary Doctorates, Mysore University. 1997 Aditya Vikram Birla ‘Kalashikkar’ Award for Lifetime Achievement. 1991 Padma Vibhushan, Government of India. 1973 Padma Bhushan, Government of India. 1968 National Award for Best Experimental Film ‘Through the Eyes of a Painter’, India. 1967 Won the Golden Bear for his film 'Through the Eyes of a Painter', International Berlin Film Festival and purchased by Museum of Modern Art (MOMA), New York. 1966 Awarded Padmashree, Government of India. 1959 International Biennale Award, Tokyo. 1955 First Prize at the National Exhibition of Art, Lalit Kala Akademi, New Delhi. 1947 Bombay Art Society, Mumbai.
from fabric.api import * import fabric.contrib.project as project import os import shutil import sys import SocketServer from datetime import datetime import livereload from pelican.server import ComplexHTTPRequestHandler # Local path configuration (can be absolute or relative to fabfile) env.deploy_path = 'output' DEPLOY_PATH = env.deploy_path # Remote server configuration production = 'root@localhost:22' dest_path = '/var/www' # Rackspace Cloud Files configuration settings env.cloudfiles_username = 'my_rackspace_username' env.cloudfiles_api_key = 'my_rackspace_api_key' env.cloudfiles_container = 'my_cloudfiles_container' # Github Pages configuration env.github_pages_branch = "gh-pages" # Port for `serve` PORT = 8000 def clean(): """Remove generated files""" if os.path.isdir(DEPLOY_PATH): shutil.rmtree(DEPLOY_PATH) os.makedirs(DEPLOY_PATH) def build(): """Build local version of site""" local('pelican -s pelicanconf.py') def rebuild(): """`clean` then `build`""" clean() build() def regenerate(): """Automatically regenerate site upon file modification""" local('pelican -r -s pelicanconf.py') def serve(): """Serve site at http://localhost:8000/""" os.chdir(env.deploy_path) class AddressReuseTCPServer(SocketServer.TCPServer): allow_reuse_address = True server = AddressReuseTCPServer(('', PORT), ComplexHTTPRequestHandler) sys.stderr.write('Serving on port {0} ...\n'.format(PORT)) server.serve_forever() def reserve(): """`build`, then `serve`""" build() serve() def preview(): """Build production version of site""" local('pelican -s publishconf.py') def cf_upload(): """Publish to Rackspace Cloud Files""" rebuild() with lcd(DEPLOY_PATH): local('swift -v -A https://auth.api.rackspacecloud.com/v1.0 ' '-U {cloudfiles_username} ' '-K {cloudfiles_api_key} ' 'upload -c {cloudfiles_container} .'.format(**env)) @hosts(production) def publish(): """Publish to production via rsync""" local('pelican -s publishconf.py') project.rsync_project( remote_dir=dest_path, exclude=".DS_Store", local_dir=DEPLOY_PATH.rstrip('/') + '/', delete=True, extra_opts='-c', ) def gh_pages(): """Publish to GitHub Pages""" rebuild() local("ghp-import -b {github_pages_branch} {deploy_path}".format(**env)) local("git push origin {github_pages_branch}".format(**env)) TEMPLATE_RST = """ {title} {hashes} :date: {year}-{month}-{day} {hour}:{minute:02d} :tags: :category: :slug: {slug} :summary: :status: draft """ # TEMPLATE is declared before hand, and all the necessary imports made def make_entry_rst(title): today = datetime.today() slug = title.lower().strip().replace(' ', '-') f_create = "content/{}_{:0>2}_{:0>2}_{}.rst".format( today.year, today.month, today.day, slug) t = TEMPLATE_RST.strip().format(title=title, hashes='#' * len(title), year=today.year, month=today.month, day=today.day, hour=today.hour, minute=today.minute, slug=slug) with open(f_create, 'w') as w: w.write(t) print("File created -> " + f_create) TEMPLATE_MD = """ Title: {title} Date: {year}-{month}-{day} {hour}:{minute:02d} Tags: thats, awesome Category: yeah Slug: {slug} """ # TEMPLATE is declared before hand, and all the necessary imports made def make_entry(title): today = datetime.today() slug = title.lower().strip().replace(' ', '-') f_create = "content/{}_{:0>2}_{:0>2}_{}.md".format( today.year, today.month, today.day, slug) t = TEMPLATE_MD.strip().format(title=title, hashes='#' * len(title), year=today.year, month=today.month, day=today.day, hour=today.hour, minute=today.minute, slug=slug) with open(f_create, 'w') as w: w.write(t) print("File created -> " + f_create) def live_build(port=8080): local('make clean') # 1 local('make html') # 2 os.chdir('output') # 3 server = livereload.Server() # 4 server.watch('../content/*.rst', # 5 livereload.shell('pelican -s ../pelicanconf.py -o ../output')) # 6 server.watch('../naffy/', # 7 livereload.shell('pelican -s ../pelicanconf.py -o ../output')) # 8 server.watch('*.html') # 9 server.watch('*.css') # 10 server.serve(liveport=35729, port=port) # 11
6. Explain a proof of the Pythagorean Theorem and its converse. This animated PowerPoint presentation uses shearing and the invariance of the area of triangles with congruent bases and heights to show a step-by-step geometric proof of the Pythagorean Theorem.
from ASG_TypesMetaModel import * from graph_ASG_ERmetaMetaModel import * from Tkinter import * from ATOM3TypeInfo import * from ATOM3String import * from StatusBar import * from ATOM3TypeDialog import * from TypeName import * from LeafType import * from ModelType import * from Operator import * def createNewASGroot(self): return ASG_TypesMetaModel(self, None) def createModelMenu(self, modelMenu): "Creates a customized Model Menu for the actual formalism" modelMenu = Menu(self.mmtoolMenu, tearoff=0) modelMenu.add_command(label="new TypeName", command=lambda x=self: x.newModesTypeName(x) ) modelMenu.add_command(label="new LeafType", command=lambda x=self: x.newModesLeafType(x) ) modelMenu.add_command(label="new ModelType", command=lambda x=self: x.newModesModelType(x) ) modelMenu.add_command(label="new Operator", command=lambda x=self: x.newModesOperator(x) ) def setConnectivity(self): self.ConnectivityMap['LeafType']={ 'LeafType': [] ,'TypeName': [] ,'ModelType': [] ,'Operator': [] } self.ConnectivityMap['TypeName']={ 'LeafType': [( 'Operator', self.createNewOperator)] ,'TypeName': [( 'Operator', self.createNewOperator)] ,'ModelType': [( 'Operator', self.createNewOperator)] ,'Operator': [] } self.ConnectivityMap['ModelType']={ 'LeafType': [] ,'TypeName': [] ,'ModelType': [] ,'Operator': [] } self.ConnectivityMap['Operator']={ 'LeafType': [] ,'TypeName': [] ,'ModelType': [] ,'Operator': [] } self.CardinalityTable['TypeName']={ 'TypeName': [] ,'LeafType': [] ,'ModelType': [] ,'Operator': [('1', '1', 'Source'), ('0', 'N', 'Destination')] } self.CardinalityTable['LeafType']={ 'TypeName': [] ,'LeafType': [] ,'ModelType': [] ,'Operator': [('1', '1', 'Destination')] } self.CardinalityTable['ModelType']={ 'TypeName': [] ,'LeafType': [] ,'ModelType': [] ,'Operator': [('1', '1', 'Destination')] } self.CardinalityTable['Operator']={ 'TypeName': [('0', '1', 'Destination'), ('0', '1', 'Source')] ,'LeafType': [('0', 'N', 'Source')] ,'ModelType': [('0', 'N', 'Source')] ,'Operator': [('0', 'N', 'Source'), ('0', 'N', 'Destination')] } self.entitiesInMetaModel['TypesMetaModel']=["TypeName", "LeafType", "ModelType", "Operator"] def createNewTypeName(self, wherex, wherey, screenCoordinates = 1): self.fromClass = None self.toClass = None # try the global constraints... res = self.ASGroot.preCondition(ASG.CREATE) if res: self.constraintViolation(res) self.mode=self.IDLEMODE return new_semantic_obj = TypeName(self) ne = len(self.ASGroot.listNodes["TypeName"]) if new_semantic_obj.keyword_: new_semantic_obj.keyword_.setValue(new_semantic_obj.keyword_.toString()+str(ne)) if screenCoordinates: new_obj = graph_TypeName(self.UMLmodel.canvasx(wherex), self.UMLmodel.canvasy(wherey), new_semantic_obj) else: # already in canvas coordinates new_obj = graph_TypeName(wherex, wherey, new_semantic_obj) new_obj.DrawObject(self.UMLmodel, self.editGGLabel) self.UMLmodel.addtag_withtag("TypeName", new_obj.tag) new_semantic_obj.graphObject_ = new_obj self.ASGroot.addNode(new_semantic_obj) res = self.ASGroot.postCondition(ASG.CREATE) if res: self.constraintViolation(res) self.mode=self.IDLEMODE return res = new_semantic_obj.postCondition(ASGNode.CREATE) if res: self.constraintViolation(res) self.mode=self.IDLEMODE return self.mode=self.IDLEMODE if self.editGGLabel : self.statusbar.event(StatusBar.TRANSFORMATION, StatusBar.CREATE) else: self.statusbar.event(StatusBar.MODEL, StatusBar.CREATE) return new_semantic_obj def createNewLeafType(self, wherex, wherey, screenCoordinates = 1): self.fromClass = None self.toClass = None # try the global constraints... res = self.ASGroot.preCondition(ASG.CREATE) if res: self.constraintViolation(res) self.mode=self.IDLEMODE return new_semantic_obj = LeafType(self) ne = len(self.ASGroot.listNodes["LeafType"]) if new_semantic_obj.keyword_: new_semantic_obj.keyword_.setValue(new_semantic_obj.keyword_.toString()+str(ne)) if screenCoordinates: new_obj = graph_LeafType(self.UMLmodel.canvasx(wherex), self.UMLmodel.canvasy(wherey), new_semantic_obj) else: # already in canvas coordinates new_obj = graph_LeafType(wherex, wherey, new_semantic_obj) new_obj.DrawObject(self.UMLmodel, self.editGGLabel) self.UMLmodel.addtag_withtag("LeafType", new_obj.tag) new_semantic_obj.graphObject_ = new_obj self.ASGroot.addNode(new_semantic_obj) res = self.ASGroot.postCondition(ASG.CREATE) if res: self.constraintViolation(res) self.mode=self.IDLEMODE return res = new_semantic_obj.postCondition(ASGNode.CREATE) if res: self.constraintViolation(res) self.mode=self.IDLEMODE return self.mode=self.IDLEMODE if self.editGGLabel : self.statusbar.event(StatusBar.TRANSFORMATION, StatusBar.CREATE) else: self.statusbar.event(StatusBar.MODEL, StatusBar.CREATE) return new_semantic_obj def createNewModelType(self, wherex, wherey, screenCoordinates = 1): self.fromClass = None self.toClass = None # try the global constraints... res = self.ASGroot.preCondition(ASG.CREATE) if res: self.constraintViolation(res) self.mode=self.IDLEMODE return new_semantic_obj = ModelType(self) ne = len(self.ASGroot.listNodes["ModelType"]) if new_semantic_obj.keyword_: new_semantic_obj.keyword_.setValue(new_semantic_obj.keyword_.toString()+str(ne)) if screenCoordinates: new_obj = graph_ModelType(self.UMLmodel.canvasx(wherex), self.UMLmodel.canvasy(wherey), new_semantic_obj) else: # already in canvas coordinates new_obj = graph_ModelType(wherex, wherey, new_semantic_obj) new_obj.DrawObject(self.UMLmodel, self.editGGLabel) self.UMLmodel.addtag_withtag("ModelType", new_obj.tag) new_semantic_obj.graphObject_ = new_obj self.ASGroot.addNode(new_semantic_obj) res = self.ASGroot.postCondition(ASG.CREATE) if res: self.constraintViolation(res) self.mode=self.IDLEMODE return res = new_semantic_obj.postCondition(ASGNode.CREATE) if res: self.constraintViolation(res) self.mode=self.IDLEMODE return self.mode=self.IDLEMODE if self.editGGLabel : self.statusbar.event(StatusBar.TRANSFORMATION, StatusBar.CREATE) else: self.statusbar.event(StatusBar.MODEL, StatusBar.CREATE) return new_semantic_obj def createNewOperator(self, wherex, wherey, screenCoordinates = 1): self.fromClass = None self.toClass = None # try the global constraints... res = self.ASGroot.preCondition(ASG.CREATE) if res: self.constraintViolation(res) self.mode=self.IDLEMODE return new_semantic_obj = Operator(self) ne = len(self.ASGroot.listNodes["Operator"]) if new_semantic_obj.keyword_: new_semantic_obj.keyword_.setValue(new_semantic_obj.keyword_.toString()+str(ne)) if screenCoordinates: new_obj = graph_Operator(self.UMLmodel.canvasx(wherex), self.UMLmodel.canvasy(wherey), new_semantic_obj) else: # already in canvas coordinates new_obj = graph_Operator(wherex, wherey, new_semantic_obj) new_obj.DrawObject(self.UMLmodel, self.editGGLabel) self.UMLmodel.addtag_withtag("Operator", new_obj.tag) new_semantic_obj.graphObject_ = new_obj self.ASGroot.addNode(new_semantic_obj) res = self.ASGroot.postCondition(ASG.CREATE) if res: self.constraintViolation(res) self.mode=self.IDLEMODE return res = new_semantic_obj.postCondition(ASGNode.CREATE) if res: self.constraintViolation(res) self.mode=self.IDLEMODE return self.mode=self.IDLEMODE if self.editGGLabel : self.statusbar.event(StatusBar.TRANSFORMATION, StatusBar.CREATE) else: self.statusbar.event(StatusBar.MODEL, StatusBar.CREATE) return new_semantic_obj def createNew_Model(self, wherex, wherey, screenCoordinates = 1): self.toClass = None self.fromClass = None new_semantic_obj = ASG_TypesMetaModel(self) ne = len(self.ASGroot.listNodes["ASG_TypesMetaModel"]) if new_semantic_obj.keyword_: new_semantic_obj.keyword_.setValue(new_semantic_obj.keyword_.toString()+str(ne)) if screenCoordinates: new_obj = graph_ASG_ERmetaMetaModel(self.UMLmodel.canvasx(wherex), self.UMLmodel.canvasy(wherey), new_semantic_obj) else: # already in canvas coordinates new_obj = graph_ASG_ERmetaMetaModel(wherex, wherey, new_semantic_obj) new_obj.DrawObject(self.UMLmodel, self.editGGLabel) self.UMLmodel.addtag_withtag("ASG_TypesMetaModel", new_obj.tag) new_semantic_obj.graphObject_ = new_obj self.ASGroot.addNode(new_semantic_obj) self.mode=self.IDLEMODE if self.editGGLabel : self.statusbar.event(StatusBar.TRANSFORMATION, StatusBar.CREATE) else: self.statusbar.event(StatusBar.MODEL, StatusBar.CREATE) return new_semantic_obj def fillTypesInformation(self): objs = [] obj = ATOM3TypeInfo(self) params = [] obj.setValue(("String", "ATOM3String", params, (None, 0) )) objs.append(obj) obj = ATOM3TypeInfo(self) params = [] param = ATOM3String("None") params.append(param) param = ATOM3String("None") params.append(param) param = ATOM3String("1") params.append(param) obj.setValue(("Boolean", "ATOM3Boolean", params, (None, 0) )) objs.append(obj) obj = ATOM3TypeInfo(self) params = [] obj.setValue(("Integer", "ATOM3Integer", params, (None, 0) )) objs.append(obj) obj = ATOM3TypeInfo(self) params = [] obj.setValue(("Float", "ATOM3Float", params, (None, 0) )) objs.append(obj) obj = ATOM3TypeInfo(self) params = [] param = ATOM3String("self.types") params.append(param) obj.setValue(("Attribute", "ATOM3Attribute", params, (None, 0) )) objs.append(obj) obj = ATOM3TypeInfo(self) params = [] param = ATOM3String("[1,1,1,self.types]") params.append(param) param = ATOM3String("ATOM3Attribute") params.append(param) param = ATOM3String("self.types") params.append(param) obj.setValue(("List", "ATOM3List", params, (None, 0) )) objs.append(obj) obj = ATOM3TypeInfo(self) params = [] param = ATOM3String("[]") params.append(param) param = ATOM3String("1") params.append(param) param = ATOM3String("1") params.append(param) obj.setValue(("Enum", "ATOM3Enum", params, (None, 0) )) objs.append(obj) obj = ATOM3TypeInfo(self) params = [] obj.setValue(("Constraint", "ATOM3Constraint", params, (None, 0) )) objs.append(obj) obj = ATOM3TypeInfo(self) params = [] param = ATOM3String("'class0'") params.append(param) param = ATOM3String("None") params.append(param) obj.setValue(("Appearance", "ATOM3Appearance", params, (None, 0) )) objs.append(obj) obj = ATOM3TypeInfo(self) params = [] obj.setValue(("BottomType", "ATOM3BottomType", params, (None, 0) )) objs.append(obj) obj = ATOM3TypeInfo(self) params = [] obj.setValue(("Link", "ATOM3Link", params, (None, 0) )) objs.append(obj) obj = ATOM3TypeInfo(self) params = [] obj.setValue(("Port", "ATOM3Port", params, (None, 0) )) objs.append(obj) obj = ATOM3TypeInfo(self) params = [] obj.setValue(("Connection", "ATOM3Connection", params, (None, 0) )) objs.append(obj) self.typeList.setValue(objs)
FREE Baby Box & Coupons from The Baby Box Co. Users can enter their email for a chance to get MAC Cosmetics Free Samples! U.S. Residents Only. Giovanni Hair Care Products: Get Your FREE Bottle!
from json import loads from urllib import quote, urlencode from urllib2 import urlopen, HTTPError from zlib import decompress, MAX_WBITS import api from database import Database from filter import Filter ## Represents an error that occurred while accessing the API. class APIError(Exception): ## Constructs the exception object. def __init__(self, error_id, error_message): self._error_id = error_id self._error_message = error_message ## Returns a string representation of the exception # @return the error string def __str__(self): return 'API error %d: %s.' % (self._error_id, self._error_message,) ## Returns the unique ID for the error. # @return the unique ID def error_id(self): return self._error_id ## Represents a %URL for accessing an API resource. # # The URL class provides methods for manipulating a %URL that will eventually be # used to access an API method. There is rarely a need to interact with this # class directly - instead use the methods of API and Site. class URL: ## Constructs a URL object optionally initialized to a domain. # @param domain a site domain name def __init__(self, domain=None): self._prefix = 'http' self._method = 'GET' self._methods = [] self._base_methods = [] self._parameters = {} # Add two default parameters to accompany each request self._parameters['key'] = api.API.key self._parameters['filter'] = Filter.default if not domain is None: self._parameters['site'] = domain self._ttl = 600 # cache data for 10 minutes by default ## Returns an internal representation of the URL. # @return the internal representation def __repr__(self): return "<%s request for '%s'>" % (self._method, '/'.join(self._methods),) ## Constructs the string representation of the URL. # @return the complete URL as a string def __str__(self): return '%s://api.stackexchange.com/2.1/%s%s' % (self._prefix, '/'.join(self._methods), '?' + urlencode(self._parameters) if self._method == 'GET' else '',) ## Retrieves the JSON data for the provided URL. # @param forbid_empty raises an error if fewer than one item is returned # @returns the JSON response # # This method will generate the URL for the request and either retrieve the # JSON for that URL or return the latest value from the cache. def fetch(self, forbid_empty=False): url = str(self) # If caching is enabled for this URL, check the cache if self._ttl: Database.prepare() json_data = Database.current.retrieve_from_cache(url) if not json_data is None: return loads(json_data) # Catch any HTTP errors because we want to grab error messages try: post_data = urlencode(self._parameters) if self._method == 'POST' else None raw_data = urlopen(url, data=post_data).read() except HTTPError, e: raw_data = e.read() json_data = decompress(raw_data, 16 + MAX_WBITS).decode('UTF-8') data = loads(json_data) # Check the data for errors if 'error_id' in data and 'error_message' in data: raise APIError(data['error_id'], data['error_message']) if not 'items' in data: raise KeyError('"items" missing from server response.') # Add it to the cache for next time if self._ttl: Database.current.add_to_cache(url, json_data, self._ttl) # If the caller wants at least one item, make sure there is if forbid_empty and not len(data['items']): raise IndexError('"items" is empty but at least one item was expected.') return data ## Adds a method to the end of the URL. # @param method the name of the method # @param is_variable whether this 'method' can vary between requests # # A bit of an explanation for this method seems in order. The `is_variable` # parameter indicates whether this particular part of the method is # constant or if it represents an ID or tag or some other variant. def add_method(self, method, is_variable=False): self._methods.append(quote(method, '')) self._base_methods.append('*' if is_variable else method) return self ## Adds a query string parameter to the URL. # @param name the name of the parameter # @param value the value for the parameter # # Note: if a parameter with the same name already exists, it will be replaced. Also, # if name is set to 'access_token', then the URL will switch to HTTPS. def add_parameter(self, name, value): self._parameters[name] = str(value) if name == 'access_token': self.secure() return self ## Returns the base method used for the request. # @return the base method # # The return value of this method is used extensively in the meta type # system Stack.PY employs as well as observing the rate limit. def base_method(self): return '/'.join(self._base_methods) ## Enables the secure HTTP protocol (HTTPS) for the URL. def secure(self): self._prefix = 'https' return self ## Sets the Time-To-Live (TTL) for this request. # @param ttl the TTL value for the URL # # Note: passing a value of 0 for ttl will result in caching being disabled for the URL def set_ttl(self, ttl): self._ttl = ttl return self ## Switches the URL to a POST request instead of a GET request. # # Note: this will disable caching def switch_to_post(self): self._method = 'POST' self._ttl = 0 return self
As manufacturers we are experts in Custom-made solutions. We have always to confirm this possibility, because we have less and less ladies working in this special art. Using our linens and lines catalogs we may create special designs and sizes including any monogram. For any information please contact us through our FORM, email us at [email protected] or call 00351 291222965.
"""bp_mgmt URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Add an import: from blog import urls as blog_urls 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """ from django.conf.urls import include, url from django.contrib import admin from django.contrib.auth.views import login from bp_setup.forms import BPAuthenticationForm admin.site.site_header = 'Administration: BP Allgemeinmedizin' urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^setup/', include('bp_setup.urls', namespace='bp_setup')), url(r'^info/', include('django.contrib.flatpages.urls')), url(r'^api/', include('bp_cupid.api')), url(r'^/?', include('bp_cupid.urls', namespace='bp_cupid')), url(r'^login/$', login, {'authentication_form': BPAuthenticationForm}, name='login', ), url('^', include('django.contrib.auth.urls')), ]
This handheld electronic calculator has a metal case and twenty-four rectangular plastic keys. These include ten digit keys, a decimal point key, a total key, four arithmetic function keys, three memory keys, a percentage key, a square root key, an off key, an on/clear key, and a clear entry key. Behind the keyboard is an eight-digit LCD display. A mark below the keyboard reads: Unisonic LC 270. A mark printed on the back reads: Unisonic LC 270 (/) 1.5V BATTERY x 2 PCS. (/) EVERREADY BATTERY NO. 189 (/) SERIAL NO. 5673107 (/) MADE IN TAIWAN R. O. C. [Advertisement], Fort Hood Sentinel, December 17, 1981, p. 3A. Unisonic LC270 and Unisonic LC222 calculators advertised as on sale for $7.88, regularly $12.95. [Advertisement], Tonawanda NY Evening News, April 14, 1982, p. 5. Both Unisonic LC270 and Unisonic LC222 calculators on sale for $6.96, regularly $8.99.
# -*- coding: utf-8 -*- import logging import multiprocessing import time from ..utils import timing logger = logging.getLogger(__name__) def run_sequential(tasks, name=None): """ Args: tasks(list(NXtask)) Returns: bool """ with timing.timeit_logger(logger, name=name): for task in tasks: task.run() if not task.done: return False return True def run_task(task, result_queue): """ Args: task(NXtask) result_queue(Queue) """ try: task.run() finally: result_queue.put(task.done) def run_parallel(tasks, name, nproc=2): """ Args: tasks(list(NXtask)) Returns: bool """ with timing.timeit_logger(logger, name=name): result_queue = multiprocessing.Queue() results = [] with multiprocessing.Pool(nproc) as pool: try: while tasks: tasks_copy = list(tasks) tasks = [] for task in tasks_copy: if task.ready_to_run: results.append( pool.apply_async(run_task, task, result_queue) ) else: tasks.append(task) if not result_queue.get(): for result in results: result.wait() return finally: for result in results: result.wait()
I have a DIV called 'main'. I have a DIV within 'main' called 'innerdiv' which has a margin of 5px for neatness' sake, and a height of 385px. Within 'innerdiv' is a lot of text, extending well beyond the 385px. I don't want to scroll using scrollbars; I'd like to use an area above and below the text along with an onmouseover event for each that scrolls the text up/down and an onmouseout event that stops the scrolling. I've tried a lot of different stuff and relentlessly searched for a solution, trying many examples along the way, but with no success at all. The most common problem I get is the error 'object does not support this property or method' if I try to 'getElementById('inner_div')'. The page I'm testing can be found here http://johnchiverton.com/fhdtest/index.php. The end of my tether is in sight, and I'm showing no signs of stopping. Right, thanks to Skunk I've made some good progress and have almost achieved what I set out to achieve. But, I'm stuck. What I'd like to see is when I hold the mouse over UP or DOWN the text CONTINUES to scroll. At present it just scrolls one line, then stops, then scrolls another line if I move the mouse out and then over the div. Hopefully I've not done anything wrong with posting the code here! Any help would be hugely appreciated, especially well before the end of this week! If anyone's interested, here's how I did it in the end. Page can be viewed here: http://johnchiverton.com/fhd/body.php.
""" 23. Giving models a custom manager You can use a custom ``Manager`` in a particular model by extending the base ``Manager`` class and instantiating your custom ``Manager`` in your model. There are two reasons you might want to customize a ``Manager``: to add extra ``Manager`` methods, and/or to modify the initial ``QuerySet`` the ``Manager`` returns. """ from __future__ import unicode_literals from django.db import models from django.utils.encoding import python_2_unicode_compatible # An example of a custom manager called "objects". class PersonManager(models.Manager): def get_fun_people(self): return self.filter(fun=True) @python_2_unicode_compatible class Person(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) fun = models.BooleanField(default=False) objects = PersonManager() def __str__(self): return "%s %s" % (self.first_name, self.last_name) # An example of a custom manager that sets get_queryset(). class PublishedBookManager(models.Manager): def get_queryset(self): return super(PublishedBookManager, self).get_queryset().filter(is_published=True) @python_2_unicode_compatible class Book(models.Model): title = models.CharField(max_length=50) author = models.CharField(max_length=30) is_published = models.BooleanField(default=False) published_objects = PublishedBookManager() authors = models.ManyToManyField(Person, related_name='books') def __str__(self): return self.title # An example of providing multiple custom managers. class FastCarManager(models.Manager): def get_queryset(self): return super(FastCarManager, self).get_queryset().filter(top_speed__gt=150) @python_2_unicode_compatible class Car(models.Model): name = models.CharField(max_length=10) mileage = models.IntegerField() top_speed = models.IntegerField(help_text="In miles per hour.") cars = models.Manager() fast_cars = FastCarManager() def __str__(self): return self.name
Appraisal Summary: Adomainname.ws base this survey on independent statistics from Alexa website services and maximum potential earning via Google Adsense, Yahoo, MSN, or any popular pay per click advertising network. Based on these 3rd party sources the domain Realistic.pl is hosted on (Update) servers it receives 48 daily unique visitors, has a worldwide popularity rank of 3,630,312, is estimated to potentially earn 1 USD$ per month or 135.8 Hundred USD$ per year on a 100% add click per page view basis. This is a non bias independent estimation, regular updates above reflect any changes for accuracy.
# # 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 base64 import sys from cryptography import fernet from cryptography.hazmat import backends from cryptography.hazmat.primitives.ciphers import algorithms from cryptography.hazmat.primitives.ciphers import Cipher from cryptography.hazmat.primitives.ciphers import modes from cryptography.hazmat.primitives import padding from oslo_config import cfg from oslo_serialization import jsonutils from oslo_utils import encodeutils from heat.common import exception from heat.common.i18n import _ auth_opts = [ cfg.StrOpt('auth_encryption_key', secret=True, default='notgood but just long enough i t', help=_('Key used to encrypt authentication info in the ' 'database. Length of this key must be 32 characters.')) ] cfg.CONF.register_opts(auth_opts) class SymmetricCrypto(object): """Symmetric Key Crypto object. This class creates a Symmetric Key Crypto object that can be used to decrypt arbitrary data. Note: This is a reimplementation of the decryption algorithm from oslo-incubator, and is provided for backward compatibility. Once we have a DB migration script available to re-encrypt using new encryption method as part of upgrade, this can be removed. :param enctype: Encryption Cipher name (default: AES) """ def __init__(self, enctype='AES'): self.algo = algorithms.AES def decrypt(self, key, msg, b64decode=True): """Decrypts the provided ciphertext. The ciphertext can be optionally base64 encoded. Uses AES-128-CBC with an IV by default. :param key: The Encryption key. :param msg: the ciphetext, the first block is the IV :returns: the plaintext message, after padding is removed. """ key = str.encode(get_valid_encryption_key(key)) if b64decode: msg = base64.b64decode(msg) algo = self.algo(key) block_size_bytes = algo.block_size // 8 iv = msg[:block_size_bytes] backend = backends.default_backend() cipher = Cipher(algo, modes.CBC(iv), backend=backend) decryptor = cipher.decryptor() padded = (decryptor.update(msg[block_size_bytes:]) + decryptor.finalize()) unpadder = padding.ANSIX923(algo.block_size).unpadder() plain = unpadder.update(padded) + unpadder.finalize() # The original padding algorithm was a slight variation on ANSI X.923, # where the size of the padding did not include the byte that tells # you the size of the padding. Therefore, we need to remove one extra # byte (which will be 0x00) when unpadding. return plain[:-1] def encrypt(value, encryption_key=None): if value is None: return None, None encryption_key = get_valid_encryption_key(encryption_key, fix_length=True) encoded_key = base64.b64encode(encryption_key.encode('utf-8')) sym = fernet.Fernet(encoded_key) res = sym.encrypt(encodeutils.safe_encode(value)) return 'cryptography_decrypt_v1', encodeutils.safe_decode(res) def decrypt(method, data, encryption_key=None): if method is None or data is None: return None decryptor = getattr(sys.modules[__name__], method) value = decryptor(data, encryption_key) if value is not None: return encodeutils.safe_decode(value, 'utf-8') def encrypted_dict(data, encryption_key=None): 'Return an encrypted dict. Values converted to json before encrypted' return_data = {} if not data: return return_data for prop_name, prop_value in data.items(): prop_string = jsonutils.dumps(prop_value) encrypted_value = encrypt(prop_string, encryption_key) return_data[prop_name] = encrypted_value return return_data def decrypted_dict(data, encryption_key=None): 'Return a decrypted dict. Assume input values are encrypted json fields.' return_data = {} if not data: return return_data for prop_name, prop_value in data.items(): method, value = prop_value try: decrypted_value = decrypt(method, value, encryption_key) except UnicodeDecodeError: # The dict contained valid JSON on the way in, so if what comes # out is garbage then the key was incorrect. raise exception.InvalidEncryptionKey() prop_string = jsonutils.loads(decrypted_value) return_data[prop_name] = prop_string return return_data def oslo_decrypt_v1(value, encryption_key=None): encryption_key = get_valid_encryption_key(encryption_key) sym = SymmetricCrypto() return sym.decrypt(encryption_key, value, b64decode=True) def cryptography_decrypt_v1(value, encryption_key=None): encryption_key = get_valid_encryption_key(encryption_key, fix_length=True) encoded_key = base64.b64encode(encryption_key.encode('utf-8')) sym = fernet.Fernet(encoded_key) try: return sym.decrypt(encodeutils.safe_encode(value)) except fernet.InvalidToken: raise exception.InvalidEncryptionKey() def get_valid_encryption_key(encryption_key, fix_length=False): if encryption_key is None: encryption_key = cfg.CONF.auth_encryption_key if fix_length and len(encryption_key) < 32: # Backward compatible size encryption_key = encryption_key * 2 return encryption_key[:32] def heat_decrypt(value, encryption_key=None): """Decrypt data that has been encrypted using an older version of Heat. Note: the encrypt function returns the function that is needed to decrypt the data. The database then stores this. When the data is then retrieved (potentially by a later version of Heat) the decrypt function must still exist. So whilst it may seem that this function is not referenced, it will be referenced from the database. """ encryption_key = str.encode(get_valid_encryption_key(encryption_key)) auth = base64.b64decode(value) AES = algorithms.AES(encryption_key) block_size_bytes = AES.block_size // 8 iv = auth[:block_size_bytes] backend = backends.default_backend() cipher = Cipher(AES, modes.CFB(iv), backend=backend) decryptor = cipher.decryptor() return decryptor.update(auth[block_size_bytes:]) + decryptor.finalize() def list_opts(): yield None, auth_opts
Still not for spiritual singles? For free to offer a dutch owners. She said she would think about it. It's a two-way match, and a great way to quickly find the members that you would most likely be compatible with! Friends label me funny and selfless. These are members that meet the criteria you specifed as being what you're looking for, and for whom you also meet their criteria. Am a God fearing man with a high sense of humour, loving and caring to the fullest. Find a partner for a long-lasting relationship. Learn more so start browsing experience. We are helping you find a partner for a long-lasting relationship. Dont be sceared of my picture i am a nice friendly person. Search through our community for free russian mail order brides. Join our community and meet thousands of lonely hearts from various parts of Luxembourg. The matching feature of Loveawake helps you easily find other members from Luxembourg that you match up well with. Just add your profile, search for other members like you seeking to date, flirt, chat, shakespeare dating the plays find romance and have fun. All you need to do is fall in love.
import sys, os, copy thisPath = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.abspath(os.path.join(thisPath,".."))) sys.path.append(os.path.abspath(os.path.join(thisPath,"../.."))) import Utils.ElementTreeUtils as ETUtils from collections import defaultdict import types def getEmptyCorpus(xml, deletionRules=None, removeNames=False): """ A convenience function for getting an empty corpus, useful for testing for information leaks in the event extraction process. """ if type(xml) in types.StringTypes: # XML is read from disk, so it's a new copy and can be safely modified xml = ETUtils.ETFromObj(xml) else: # XML is already an object in memory. To prevent problems with other users of it, a copy # is created before deleting elements. xml = copy.deepcopy(xml) if deletionRules == None: # use default rules for BioNLP Shared Task # We remove all interactions, and all entities that are not named entities. This leaves only # the gold standard protein/gene names if removeNames: deletionRules = {"interaction":{},"entity":{}} else: deletionRules = {"interaction":{},"entity":{"given":(None, "False")}} # Remove elements and return the emptied XML return processCorpus(xml, None, deletionRules) def removeElements(parent, rules, reverse, countsByType): toRemove = [] for element in parent: attrType = {} if element.tag in rules: remove = True if rules[element.tag] != None and len(rules[element.tag]) > 0: for attrName in rules[element.tag]: if element.get(attrName) not in rules[element.tag][attrName]: remove = False break else: if attrName not in attrType: attrType[attrName] = set() attrType[attrName].add(element.get(attrName)) if reverse: remove = not remove if remove: toRemove.append(element) countsByType[element.tag + " " + str(attrType)] += 1 else: removeElements(element, rules, reverse, countsByType) for element in toRemove: parent.remove(element) def processCorpus(inputFilename, outputFilename, rules, reverse=False): print >> sys.stderr, "Deleting elements, rules =", rules print >> sys.stderr, "Loading corpus file", inputFilename corpusTree = ETUtils.ETFromObj(inputFilename) corpusRoot = corpusTree.getroot() countsByType = defaultdict(int) removeElements(corpusRoot, rules, reverse, countsByType) print >> sys.stderr, "Deleted elements" for k in sorted(countsByType.keys()): print >> sys.stderr, " " + k + ":", countsByType[k] if outputFilename != None: print >> sys.stderr, "Writing output to", outputFilename ETUtils.write(corpusRoot, outputFilename) return corpusTree if __name__=="__main__": print >> sys.stderr, "##### Delete Elements #####" from optparse import OptionParser # Import Psyco if available try: import psyco psyco.full() print >> sys.stderr, "Found Psyco, using" except ImportError: print >> sys.stderr, "Psyco not installed" optparser = OptionParser(usage="%prog [options]\nPath generator.") optparser.add_option("-i", "--input", default=None, dest="input", help="Corpus in interaction xml format", metavar="FILE") optparser.add_option("-o", "--output", default=None, dest="output", help="Output file in interaction xml format.") optparser.add_option("-r", "--rules", default=None, dest="rules", help="dictionary of python dictionaries with attribute:value pairs.") optparser.add_option("-v", "--reverse", default=False, dest="reverse", action="store_true", help="") (options, args) = optparser.parse_args() if options.input == None: print >> sys.stderr, "Error, input file not defined." optparser.print_help() sys.exit(1) if options.output == None: print >> sys.stderr, "Error, output file not defined." optparser.print_help() sys.exit(1) # Rules e.g. "{\"pair\":{},\"interaction\":{},\"entity\":{\"given\":\"False\"}}" rules = eval(options.rules) print >> sys.stderr, "Rules:", rules processCorpus(options.input, options.output, rules, options.reverse)
Government of Bali Province offer fifteen routes from seventeen corridors of Trans-Sarbagita Bus to the prospective investors to support connecting the mass means of transportation. “The offer aims at adding means of transportation and bus stop in fifteen corridors that don’t run yet,” said the Head of Transportation, Information and Communication Department of Bali Province, Dewa Putu Punia Asa, in Denpasar. The offer to businessmen is expected could support connectivity of transportation between regions. Now, he said, Trans Sarbagita is in the process of development and it needs investment fro public and central government. Beside, one role of those fifteen corridors is to improve the number of people using the bus in the two active corridors, which is not maximum yet. Only two corridors have been operated, they are corridor 2 to Btubulan- Nusa Dua and Corridor 1 Denpasar- Jimbaran. “So far, the bus operational and buses costs are taken from Province budget,” he said. Government of Bali Province also will operate route of Trans-Sarbagita bus to Ngurah Rai Airport since the traffic on that route is getting more and more crowded. It will be a solution in overcoming the crowd traffic from and to the Airport. According to Dewa, actually the preparation of opening the corridor had been done a while ago, but the problem is the bus stop and buses are not ready yet. Besides finalizing bus addition and corridors, the provincial government have budgeted Rp8,4 billion to operate Trans Sarbagita corridor 1 and 2 this year. It is recorded that Rp 4.2 billion is used for operating corridor 1 and the rest is for corridor 2.
import urllib, urllib2,re,string,sys,os import xbmc, xbmcgui, xbmcaddon, xbmcplugin from resources.libs import main from t0mm0.common.addon import Addon addon_id = 'plugin.video.movie25' selfAddon = xbmcaddon.Addon(id=addon_id) addon = Addon(addon_id, sys.argv) art = main.art error_logo = art+'/bigx.png' BASEURL = 'http://www.tv-release.net/' prettyName = 'TVRelease' def MAINMENU(): main.addDir('Search Tv-Release', BASEURL+'?seacher=', 1006,art+'/tvrsearch1.png') main.addDir('TV 480', BASEURL+'?cat=TV-480p', 1001,art+'/TV480.png') main.addDir('TV 720', BASEURL+'?cat=TV-720p', 1001,art+'/TV720.png') main.addDir('TV MP4', BASEURL+'?cat=TV-Mp4', 1001,art+'/TVmp4.png') main.addDir('TV Xvid', BASEURL+'?cat=TV-XviD', 1001,art+'/TVxvid.png') #main.addDir('TV Packs', BASEURL+'category/tvshows/tvpack/', 1007,art+'/TVpacks.png') main.addDir('TV Foreign', BASEURL+'?cat=TV-Foreign', 1001,art+'/TVforeign.png') main.addDir('Movies 480', BASEURL+'?cat=Movies-480p', 1001,art+'/Movies480.png') main.addDir('Movies 720', BASEURL+'?cat=Movies-720p', 1001,art+'/Movies720.png') main.addDir('Movies Xvid', BASEURL+'?cat=Movies-XviD', 1001,art+'/Moviesxvid.png') main.addDir('Movies Foreign', BASEURL+'?cat=Movies-Foreign', 1001,art+'/Moviesforeign.png') main.addSpecial('Resolver Settings',BASEURL, 1004,art+'/tvrresolver.png') main.VIEWSB() def INDEX(url): types = [] SearchType = None if '!' in url: r = url.rpartition('!') print r url = r[0] SearchType = r[2] else: url = url if 'cat=TV' in url: types = 'tv' elif 'cat=Movies' in url: types = 'movie' html = GETHTML(url) if html == None: return pattern = '<tr><td[^>]*?><a [^>]*?>([^<]*?)</a></td><td[^>]*?><a href=\'([^\']*?)\'[^>]*?>([^<]*?)<' r = re.findall(pattern, html, re.I|re.M|re.DOTALL) dialogWait = xbmcgui.DialogProgress() ret = dialogWait.create('Please wait until list is cached.') totalLinks = len(r) loadedLinks = 0 remaining_display = 'Media loaded :: [B]'+str(loadedLinks)+' / '+str(totalLinks)+'[/B].' dialogWait.update(0,'[B]Will load instantly from now on[/B]',remaining_display) for tag, url, name in r: url = BASEURL + url if re.search('(?i)WEB-DL',name): tag = tag.strip() + " WEB-DL" if re.findall('\d{4}p', name): r = re.findall('(.+?)\s(\d+p)', name) for name, quality in r: tag = tag.replace('720p',quality) pass if re.findall('\ss\d+e\d+\s', name, re.I|re.DOTALL): r = re.findall('(.+?)\ss(\d+)e(\d+)\s', name, re.I) for name, season, episode in r: name = name+' S'+season+'E'+episode elif re.findall('\s\d{4}\s\d{2}\s\d{2}\s', name): r = re.findall('(.+?)\s(\d{4})\s(\d{2})\s(\d{2})\s',name) for name, year, month, day in r: name = name+' '+year+' '+month+' '+day elif re.findall('\shdtv\sx', name, re.I): r = re.findall('(.+?)\shdtv\sx',name, re.I) for name in r: pass name = re.sub('\s\s+',' ',name).strip() name = name+' [COLOR red]'+re.sub('(?sim)^(TV-|Movies-)(.*)','\\2',tag)+'[/COLOR]' if SearchType == None: if 'TV' in tag: main.addDirTE(name,url,1003,'','','','','','') elif 'Movies' in tag: if re.findall('\s\d+\s',name): r = name.rpartition('\s\d{4}\s') main.addDirM(name,url,1003,'','','','','','') elif SearchType == 'tv' and 'TV' in tag: main.addDirTE(name,url,1003,'','','','','','') elif SearchType == 'movie' and 'Movies' in tag: r = name.rpartition('\s\d{4}\s') main.addDirM(name,url,1003,'','','','','','') loadedLinks = loadedLinks + 1 percent = (loadedLinks * 100)/totalLinks remaining_display = 'Media loaded :: [B]'+str(loadedLinks)+' / '+str(totalLinks)+'[/B].' dialogWait.update(percent,'[B]Will load instantly from now on[/B]',remaining_display) if dialogWait.iscanceled(): return False dialogWait.close() del dialogWait if "<div class='zmg_pn'" in html: r = re.findall("""<span class='zmg_pn_current'>(\d+?)</span>[^<]*?<span class='zmg_pn_standar'><a href="([^"]+?)">""", html, re.I|re.DOTALL|re.M) total = re.findall('">(\d+)</a></span>', html) if total: total = total[-1] else: total = "1" for current, url in r: url = BASEURL + url name = 'Page '+current+' of '+total+' [COLOR green]Next Page >>>[/COLOR]' main.addDir('[COLOR green]Go to Page[/COLOR]', url+':'+total, 1002, art+'/gotopagetr.png') main.addDir(name, url.replace('%5C',''), 1001, art+'/nextpage.png') main.VIEWS() def LISTHOSTERS(name,url): html = GETHTML(url) if html == None: return if selfAddon.getSetting("hide-download-instructions") != "true": main.addLink("[COLOR red]For Download Options, Bring up Context Menu Over Selected Link.[/COLOR]",'','') r = re.findall(r'class="td_cols"><a target=\'_blank\'.+?href=\'(.+?)\'>',html, re.M|re.DOTALL) try: t = re.findall(r'rel="nofollow">((?!.*\.rar).*)</a>', html, re.I) r = r+t except: pass if len(r) == 0: addon.show_ok_dialog(['No Playable Streams Found,','It Might Be That They Are Still Being Uploaded,', 'Or They Are Unstreamable Archive Files'],'MashUP: TV-Release') xbmcplugin.endOfDirectory(int(sys.argv[1]), False, False) return from urlparse import urlparse for url in r: url = url.replace("180upload.nl","180upload.com") host = urlparse(url).hostname.replace('www.','').partition('.')[0] if main.supportedHost(host): main.addDown2(name.strip()+" [COLOR blue]"+host.upper()+"[/COLOR]",url,1005,art+'/hosts/'+host+'.png',art+'/hosts/'+host+'.png') def superSearch(encode,type): try: if type == 'Movies': cat = 'Movies-XviD,Movies-720p,Movies-480p,Movies-Foreign,Movies-DVDR,' else: cat = 'TV-XviD,TV-Mp4,TV-720p,TV-480p,TV-Foreign,' surl ='http://tv-release.net/?s='+encode+'&cat='+cat returnList=[] link=main.OPENURL(surl,verbose=False) link=link.replace('\r','').replace('\n','').replace('\t','').replace('&nbsp;','') pattern = '<tr><td[^>]*?><a [^>]*?>([^<]*?)</a></td><td[^>]*?><a href=\'([^\']*?)\'[^>]*?>([^<]*?)<' r = re.findall(pattern, link, re.I|re.M|re.DOTALL) for tag, url, name in r: url = BASEURL + url if re.search('(?i)WEB-DL',name): tag = tag.strip() + " WEB-DL" if re.findall('\d+p\s', name): r = re.findall('(.+?)\s(\d+p)\s', name) for name, quality in r: tag = tag.replace('720p',quality) pass if re.findall('\ss\d+e\d+\s', name, re.I|re.DOTALL): r = re.findall('(.+?)\ss(\d+)e(\d+)\s', name, re.I) for name, season, episode in r: name = name+' S'+season+'E'+episode elif re.findall('\s\d{4}\s\d{2}\s\d{2}\s', name): r = re.findall('(.+?)\s(\d{4})\s(\d{2})\s(\d{2})\s',name) for name, year, month, day in r: name = name+' '+year+' '+month+' '+day elif re.findall('\shdtv\sx', name, re.I): r = re.findall('(.+?)\shdtv\sx',name, re.I) for name in r: pass name = name+' [COLOR red]'+re.sub('(?sim)^(TV-|Movies-)(.*)','\\2',tag)+'[/COLOR]' returnList.append((name,prettyName,url,'',1003,True)) return returnList except: return [] def SEARCHhistory(): dialog = xbmcgui.Dialog() ret = dialog.select('[B]Choose A Search Type[/B]',['[B]TV Shows[/B]','[B]Movies[/B]']) if ret == -1: xbmcplugin.endOfDirectory(int(sys.argv[1]), False, False) if ret == 0: searchType = 'tv' seapath=os.path.join(main.datapath,'Search') SeaFile=os.path.join(seapath,'SearchHistoryTv') if not os.path.exists(SeaFile): SEARCH(searchType) else: main.addDir('Search',searchType,1008,art+'/search.png') main.addDir('Clear History',SeaFile,128,art+'/cleahis.png') thumb=art+'/link.png' searchis=re.compile('search="(.+?)",').findall(open(SeaFile,'r').read()) for seahis in reversed(searchis): url=seahis seahis=seahis.replace('%20',' ') url = 'http://tv-release.net/?s='+url+'&cat=TV-XviD,TV-Mp4,TV-720p,TV-480p,TV-Foreign,' main.addDir(seahis,url,1001,thumb) if ret == 1: searchType = 'movie' seapath=os.path.join(main.datapath,'Search') SeaFile=os.path.join(seapath,'SearchHistory25') if not os.path.exists(SeaFile): SEARCH(searchType) else: main.addDir('Search',searchType,1008,art+'/search.png') main.addDir('Clear History',SeaFile,128,art+'/cleahis.png') thumb=art+'/link.png' searchis=re.compile('search="(.+?)",').findall(open(SeaFile,'r').read()) for seahis in reversed(searchis): url=seahis seahis=seahis.replace('%20',' ') url = 'http://tv-release.net/?s='+url+'&cat=Movies-XviD,Movies-720p,Movies-480p,Movies-Foreign,Movies-DVDR,' main.addDir(seahis,url,1001,thumb) def SEARCH(murl): if murl == 'tv': encode = main.updateSearchFile(murl,'TV',defaultValue=murl,searchMsg='Search For Shows or Episodes') if not encode: return False url = 'http://tv-release.net/?s='+encode+'&cat=TV-XviD,TV-Mp4,TV-720p,TV-480p,TV-Foreign,' INDEX(url) elif murl=='movie': encode = main.updateSearchFile(murl,'Movies',defaultValue=murl,searchMsg='Search For Movies') if not encode: return False url = 'http://tv-release.net/?s='+encode+'&cat=Movies-XviD,Movies-720p,Movies-480p,Movies-Foreign,Movies-DVDR,' INDEX(url) def TVPACKS(url): html = GETHTML(url) if html == None: return pattern = '(?sim)Tv/Pack</a></span>.+?<a href="([^"]+?)"><b><font size="2px">([^<]+?)<' r = re.findall(pattern,html) for url, name in r: main.addDir(name, url, 1001,'') def GOTOP(url): default = url r = url.rpartition(':') url = re.findall('^(.+page=)\d+(.*)$',r[0]) total = r[2] keyboard = xbmcgui.Dialog().numeric(0, '[B][I]Goto Page Number[/B][/I]') if not keyboard: xbmcplugin.endOfDirectory(int(sys.argv[1]), False, False) return False if int(keyboard) > int(total) or keyboard == '0': addon.show_ok_dialog(['Please Do Not Enter a Page Number bigger than',''+total+', Enter A Number Between 1 and '+total+'', ''], 'MashUP: TV-Release') GOTOP(default) url = url[0][0]+keyboard+str(url[0][1]) INDEX(url) def PLAYMEDIA(name,url): ok = True r = re.findall(r'(.+?)\[COLOR', name) name = r[0] r=re.findall('Season(.+?)Episode([^<]+)',name) if r: infoLabels =main.GETMETAEpiT(name,'','') video_type='episode' season=infoLabels['season'] episode=infoLabels['episode'] else: infoLabels =main.GETMETAT(name,'','','') video_type='movie' season='' episode='' img=infoLabels['cover_url'] fanart =infoLabels['backdrop_url'] imdb_id=infoLabels['imdb_id'] infolabels = { 'supports_meta' : 'true', 'video_type':video_type, 'name':str(infoLabels['title']), 'imdb_id':str(infoLabels['imdb_id']), 'season':str(season), 'episode':str(episode), 'year':str(infoLabels['year']) } try: xbmc.executebuiltin("XBMC.Notification(Please Wait!,Resolving Link,3000)") stream_url = main.resolve_url(url) infoL={'Title': infoLabels['title'], 'Plot': infoLabels['plot'], 'Genre': infoLabels['genre']} # play with bookmark from resources.universal import playbackengine player = playbackengine.PlayWithoutQueueSupport(resolved_url=stream_url, addon_id=addon_id, video_type=video_type, title=str(infoLabels['title']),season=str(season), episode=str(episode), year=str(infoLabels['year']),img=img,infolabels=infoL, watchedCallbackwithParams=main.WatchedCallbackwithParams,imdb_id=imdb_id) #WatchHistory if selfAddon.getSetting("whistory") == "true": from resources.universal import watchhistory wh = watchhistory.WatchHistory(addon_id) wh.add_item(name+' '+'[COLOR=FF67cc33]TvRelease[/COLOR]', sys.argv[0]+sys.argv[2], infolabels=infolabels, img=str(img), fanart=str(fanart), is_folder=False) player.KeepAlive() return ok except: return ok def GETHTML(url): try: h = main.OPENURL(url) if '<h2>Under Maintenance</h2>' in h: addon.show_ok_dialog(['[COLOR=FF67cc33][B]TV-Release is Down For Maintenance,[/COLOR][/B]', '[COLOR=FF67cc33][B]Please Try Again Later[/COLOR][/B]',''],'MashUP: TV-Release') xbmcplugin.endOfDirectory(int(sys.argv[1]), False, False) return return h except urllib2.URLError, e: addon.show_small_popup('MashUP: Tv-Release','TV-Release Web Site Failed To Respond, Check Log For Details', 9000, error_logo) addon.log_notice(str(e)) xbmcplugin.endOfDirectory(int(sys.argv[1]), False, False) return
there are 12 in this catalog. total:12 products. / each page show 9 products. you are viewing 1/2 pages.
# -*- coding: utf-8 -*- from collections import OrderedDict from .Expression import expressify from .Proof import Proof from .ProofGraph import ProofGraph from .Proposition import Proposition from .rewrite_rules import cnf, group_cnf, negate class KnowledgeBase: def __init__(self): self._axioms = OrderedDict() self._goal = None self.run_proofs = list() def add_axiom(self, axiom_as_prop, axiom_is_goal=False): if axiom_is_goal: cnf_exp = cnf(negate(expressify(axiom_as_prop))) else: cnf_exp = cnf(expressify(axiom_as_prop)) self._axioms[len(self._axioms)] = {'proposition': axiom_as_prop, 'cnf': cnf_exp, 'clauses': group_cnf(cnf_exp), 'is_goal': axiom_is_goal} def add_goal(self, goal_as_prop): if self._goal: raise Exception("{} is already defined as the goal! Use .remove_goal() before adding a new goal.".format(self._goal)) if not isinstance(goal_as_prop, Proposition): raise Exception("Goal must be of the type Proposition!") self.add_axiom(goal_as_prop, axiom_is_goal=True) self._goal = goal_as_prop self._goal_as_unit_clause = group_cnf(cnf(expressify(goal_as_prop))) self._negated_goal_as_unit_clause = group_cnf(cnf(negate(expressify(goal_as_prop)))) def remove_goal(self): self._goal, self._goal_as_unit_clause, self._negated_goal_as_unit_clause = None, None, None for k, v in self._axioms.items(): if v.get('is_goal') == True: del self._axioms[k] def _gather_clauses(self): clause_collection = [] for idx, axiom in self._axioms.items(): clause_collection = clause_collection + axiom.get('clauses') return clause_collection def most_recent_proof(self): if self.run_proofs: return self.run_proofs[-1] else: raise Exception("Run a proof first!") def prove(self, goal=None, return_proof=False): if goal is None: if not hasattr(self, '_goal_as_unit_clause'): raise Exception("You must set a goal before running a proof!") goal = self._goal_as_unit_clause else: self.remove_goal() self.add_goal(goal) negated_goal = self._negated_goal_as_unit_clause proof_attempt = Proof(goal, negated_goal, self._gather_clauses()) self.run_proofs.append(proof_attempt) if return_proof: return proof_attempt try: return proof_attempt.find(trace=True) except Exception as e: print(e) print('Clause Collection: {}'.format(proof_attempt.clause_collection)) print('Set of Support: {}'.format(proof_attempt.set_of_support)) return proof_attempt
At some point today ShantyTown received its 3000th hit! Thanks to everyone who still stops by even though I’ve been lazy with posting. I have and continue to appreciate it a ton! Hey, if you have a second, why don’t you donate to my charity fundraiser? Your so popular… and I like your image for celebrating with!!!
# coding=utf8 from pandas import json import MySQLdb from pymongo import MongoClient class MongoHolder(): mongodb = None collection = None def initMongoDB(self, uri, port, dbname): client = MongoClient(uri, port, maxPoolSize=200, connectTimeoutMS=60 * 1000, socketTimeoutMS=60 * 1000) self.mongodb = client[dbname] def readMongoTable(self, page, limit): return self.mongodb[self.collection].find().skip(page * limit).limit(limit) def countMongoDB(self): return self.mongodb[self.collection].count() class MySQLHolder(): mysql = None collection = None mysql_db = None # mySQL数据库名称 text_column = [] unique_column = [] def initMySql(self, host, port, user, passwd, dbname): self.mysql = MySQLdb.connect( host=host, port=port, user=user, passwd=passwd, db=dbname, charset="utf8" ) def createMySqlTable(self, tableName): base_sql = 'CREATE TABLE `%s` (`_idx_` INT NOT NULL AUTO_INCREMENT,PRIMARY KEY (`_idx_`))DEFAULT CHARSET=utf8' cursor = self.mysql.cursor() cursor.execute(base_sql % tableName) data = cursor.fetchone() return data def createMySqlFieldToTable(self, tableName, fieldName, fieldType, default='', unique=False): try: if unique: sql = 'ALTER TABLE `%s` ADD COLUMN `%s` %s %s,' \ 'ADD UNIQUE INDEX `%s_UNIQUE` (`%s` ASC)' % ( tableName, fieldName, fieldType, default, fieldName, fieldName) else: sql = 'ALTER TABLE `%s` ADD COLUMN `%s` %s %s;' % (tableName, fieldName, fieldType, default) cursor = self.mysql.cursor() cursor.execute(sql) data = cursor.fetchone() return data except Exception, e: pass def executeSQL(self, sql): cursor = self.mysql.cursor() cursor.execute(sql) data = cursor.fetchone() return data def executeSQL(self, sql, param): param = tuple(param) cursor = self.mysql.cursor() cursor.execute(sql, param) data = cursor.fetchone() return data def executeInsterSQL(self, tableName, key_arr, pla_arr, val_arr): val_arr = tuple(val_arr) sql = 'INSERT INTO %s (%s) VALUES(%s)' % (tableName, key_arr, pla_arr) try: cursor = self.mysql.cursor() cursor.execute(sql, val_arr) pass except: if not self.hasMySqlTableForDB(tableName): self.createMySqlTable(tableName) tabKetArr = self.getMySqlFieldNameByTable(tableName) key_list = key_arr.split(',') for i in range(0, len(key_list)): key = key_list[i] naked = key.replace('`', '') if naked == 'key' or naked == 'id' or naked == '_id': unique = True else: unique = False if (naked,) not in tabKetArr: if isinstance(val_arr[i], int): self.createMySqlFieldToTable(tableName, naked, 'INT(11)', unique=unique) elif isinstance(val_arr[i], float) or isinstance(val_arr[i], long): self.createMySqlFieldToTable(tableName, naked, 'DOUBLE', unique=unique) elif naked in self.text_column: # 检查特殊字段(TEXT) self.createMySqlFieldToTable(tableName, naked, 'TEXT', unique=unique) else: self.createMySqlFieldToTable(tableName, naked, 'VARCHAR(256)', unique=unique) cursor = self.mysql.cursor() try: cursor.execute(sql, val_arr) except Exception, e: if e[0] == 1062: return cursor.execute(sql, val_arr) self.mysql.commit() def executeInsterSQLOfMultiterm(self, tableName, key_arr, pla_arr, val_arr_list): val_arr = val_arr_list[0] for i in range(0, len(val_arr_list)): val_arr_list[i] = tuple(val_arr_list[i]) val_arrs = tuple(val_arr_list) sql = 'INSERT INTO %s (%s) VALUES(%s)' % (tableName, key_arr, pla_arr) try: cursor = self.mysql.cursor() cursor.executemany(sql, val_arrs) except: if not self.hasMySqlTableForDB(tableName): self.createMySqlTable(tableName) tabKetArr = self.getMySqlFieldNameByTable(tableName) key_list = key_arr.split(',') for i in range(0, len(key_list)): key = key_list[i] naked = key.replace('`', '') if naked in unique_column: unique = True else: unique = False if naked not in tabKetArr: if isinstance(val_arr[i], int): self.createMySqlFieldToTable(tableName, naked, 'INT(11)', unique=unique) elif isinstance(val_arr[i], float) or isinstance(val_arr[i], long): self.createMySqlFieldToTable(tableName, naked, 'DOUBLE', unique=unique) elif 'dra' in naked or 'summary' in naked: self.createMySqlFieldToTable(tableName, naked, 'TEXT', unique=unique) else: self.createMySqlFieldToTable(tableName, naked, 'VARCHAR(256)', unique=unique) cursor = self.mysql.cursor() cursor.executemany(sql, val_arrs) self.mysql.commit() def getMySqlFieldNameByTable(self, tableName): base_sql = "select COLUMN_NAME from information_schema.COLUMNS where table_name = '%s' and table_schema = '%s'" cursor = self.mysql.cursor() cursor.execute(base_sql % (tableName, self.mysql_db)) data = cursor.fetchall() return data def getMySqlTableName(self): base_sql = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '%s'" cursor = self.mysql.cursor() cursor.execute(base_sql % (self.mysql_db)) data = cursor.fetchall() return data def hasMySqlTableForDB(self, tableName): base_sql = "SELECT COUNT(TABLE_NAME) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '%s' AND TABLE_NAME='%s'" cursor = self.mysql.cursor() cursor.execute(base_sql % (self.mysql_db, tableName)) data = cursor.fetchone() return data[0] > 0
Buy your Conroe virtual phone number in United States now with instant and automatic activation for only 4.50 USD per month. MyVirtualPhoneNumber offers instant activation of Conroe virtual phone numbers in United States (1-936) including other virtual phone numbers cities in United States as well as Local Phone Numbers in more than 70 other countries at the best quality. Our call-handling technologies are highly innovative and flexible, with My Virtual Phone Number being able to receive simultaneous calls on your United States, Conroe virtual phone number and route these calls as required. In addition, you are able to display a selected local number as your outbound Caller ID when making calls from your office, home or mobile app. What is included with Conroe, United States Virtual Phone Number? Why would you need a Conroe, United States Virtual Phone Number? Do you need a presence in United States for your business or website? Buy a Conroe phone number and talk to customers you never thought you had. Buying a United States virtual number is one of the absolute cheapest ways you can stay in touch with customers or potential clients in United States. You can forward the 1-936 Conroe virtual number to a VOIP (SIP, H.323 or IAX) solution with Unlimited Minutes and pay the 4.50 USD per month and nothing else. Buy a Conroe phone number and forward the calls to wherever you’d like. One example would be if I went to United States and had family in London, I can call my 1-936 Conroe virtual number which is local for me while I’m in United States and have the calls forwarded to my London family. Using the same example I can also buy a London Virtual Number and forward my cell phone or landline to the Virtual Number (Usually free when it’s local to local) which in turn forwards to a mobile phone I theoretically have set up in United States. Now I don’t miss any calls from my daily cell phone number while abroad. Now you can have a local United States phone number for friends and family to call you on directly. Friends and family in United States can call you as if it’s a local call for them (ie: on the Cheap!). You can forward all the calls made on the United States phone number to VOIP (SIP, H.323 or IAX) for free and with unlimited minutes for only 4.50 USD per month or to your cell phone / landline for an additional low per minute rate. You can also make outbound calls (outgoing calls) with your Conroe phone number by using our iPhone App or Android App. Buy Conroe Phone Number Now!
from Components.Label import Label from Components.ActionMap import ActionMap from Components.config import config, ConfigSelection, getConfigListEntry, ConfigSubsection, ConfigEnableDisable, ConfigYesNo, ConfigInteger from Components.ConfigList import ConfigListScreen from Components.Console import Console from Components.GUIComponent import GUIComponent from Components.Harddisk import harddiskmanager from Components.MenuList import MenuList from Components.Pixmap import Pixmap, MultiPixmap from Components.Sources.List import List from Components.Sources.StaticText import StaticText from Plugins.Plugin import PluginDescriptor from Screens.MessageBox import MessageBox from Screens.Screen import Screen from Screens.VirtualKeyBoard import VirtualKeyBoard from Tools.BoundFunction import boundFunction from Tools.LoadPixmap import LoadPixmap from Tools.Notifications import AddNotificationWithCallback from Tools.Directories import pathExists, fileExists, resolveFilename, SCOPE_PLUGINS, SCOPE_CURRENT_PLUGIN, SCOPE_CURRENT_SKIN, SCOPE_METADIR from skin import loadSkin from os import system, makedirs, path, listdir, statvfs, popen import os import re import time from Components.Sources.StaticText import StaticText from Components.FileList import FileList from Screens.InputBox import InputBox from Components.Input import Input from Screens.ChoiceBox import ChoiceBox from enigma import eTimer from __init__ import _ config.plugins.devicemanager = ConfigSubsection() config.plugins.devicemanager.hotplug_enable = ConfigEnableDisable(default=True) config.plugins.devicemanager.mountcheck_enable = ConfigEnableDisable(default=True) def readFile(filename): file = open(filename) data = file.read().strip() file.close() return data def byteConversion(byte): if type(byte) == str and len(byte) == 0: return "" if type(byte) != long: byte = long(byte) if byte > 1024*1024*1024: int_part = byte/1024/1024/1024 dec_part = byte%(1024*1024*1024)/(1024*1024) return "%d.%d GB"%(int_part, dec_part) else: int_part = byte/1024/1024 dec_part = byte%(1024*1024)/1024 return "%d.%d MB"%(int_part, dec_part) def checkStrValue(value , empty = ""): if type(value) != str or len(value) == 0: return empty return value class DeviceManagerConfiguration(Screen, ConfigListScreen): def __init__(self,session): self.session = session Screen.__init__(self,session) self.skinName = "Setup" self.createConfigList() ConfigListScreen.__init__(self, self.list, session = self.session) self["key_red"] = StaticText(_("Cancel")) self["key_green"] = StaticText(_("OK")) self["shortcuts"] = ActionMap(["ShortcutActions", "SetupActions" ], { "ok": self.keySave, "cancel": self.keyCancel, "red": self.keyCancel, "green": self.keySave, }, -2) self.onShown.append(self.setWindowTitle) self.old_hotplug_enable = config.plugins.devicemanager.hotplug_enable.value def setWindowTitle(self): self.setTitle(_("DeviceManager configuration")) def createConfigList(self): self.list = [] self.list.append(getConfigListEntry(_("Enable mount check for HDD : "), config.plugins.devicemanager.mountcheck_enable)) self.list.append(getConfigListEntry(_("Harddisk standby after : "), config.usage.hdd_standby)) self.list.append(getConfigListEntry(_("Mount known devices automatically : "), config.plugins.devicemanager.hotplug_enable)) def keySave(self): if config.plugins.devicemanager.hotplug_enable.value: if not DeviceManagerhotplugDeviceStart in harddiskmanager.on_partition_list_change: harddiskmanager.on_partition_list_change.append(DeviceManagerhotplugDeviceStart) else: if DeviceManagerhotplugDeviceStart in harddiskmanager.on_partition_list_change: harddiskmanager.on_partition_list_change.remove(DeviceManagerhotplugDeviceStart) for x in self["config"].list: x[1].save() self.close() class DeviceManager(Screen): skin = """ <screen position="center,center" size="590,350" title="DeviceManager"> <ePixmap pixmap="skin_default/buttons/red.png" position="20,0" size="140,40" alphatest="on" /> <ePixmap pixmap="skin_default/buttons/green.png" position="160,0" size="140,40" alphatest="on" /> <ePixmap pixmap="skin_default/buttons/yellow.png" position="300,0" size="140,40" alphatest="on" /> <ePixmap pixmap="skin_default/buttons/blue.png" position="440,0" size="140,40" alphatest="on" /> <widget name="key_red" position="20,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" foregroundColor="#ffffff" backgroundColor="#9f1313" transparent="1" /> <widget name="key_green" position="160,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" foregroundColor="#ffffff" backgroundColor="#1f771f" transparent="1" /> <widget name="key_yellow" position="300,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" foregroundColor="#ffffff" backgroundColor="#a08500" transparent="1" /> <widget name="key_blue" position="440,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" foregroundColor="#ffffff" backgroundColor="#18188b" transparent="1" /> <ePixmap pixmap="skin_default/div-h.png" position="0,48" size="590,2" alphatest="on" /> <widget source="menu" render="Listbox" position="0,48" size="590,350" scrollbarMode="showOnDemand"> <convert type="TemplatedMultiContent"> {"templates": {"default": (54,[ MultiContentEntryText(pos = (50, 0), size = (510, 30), font=0, flags = RT_HALIGN_LEFT|RT_VALIGN_CENTER, text = 0), # index 0 is vendor - model MultiContentEntryText(pos = (50, 32), size = (120, 20), font=1, flags = RT_HALIGN_LEFT|RT_VALIGN_CENTER, text = 1), # index 1 is Device MultiContentEntryText(pos = (170, 32), size = (120, 20), font=1, flags = RT_HALIGN_LEFT|RT_VALIGN_CENTER, text = 2), # index 2 is Size MultiContentEntryText(pos = (290, 32), size = (120, 20), font=1, flags = RT_HALIGN_LEFT|RT_VALIGN_CENTER, text = 3), # index 3 is Partitions MultiContentEntryText(pos = (410, 32), size = (130, 20), font=1, flags = RT_HALIGN_LEFT|RT_VALIGN_CENTER, text = 4), # index 4 is Removable MultiContentEntryPixmapAlphaTest(pos = (0, 52), size = (590, 2), png = 5), # png 5 is the div pixmap ]), "partitions": (98, [ MultiContentEntryText(pos = (50, 0), size = (500, 30), font=0, flags = RT_HALIGN_LEFT|RT_VALIGN_CENTER, text = 0), # index 1 is Partition MultiContentEntryText(pos = (50, 32), size = (500, 20), font=1, flags = RT_HALIGN_LEFT|RT_VALIGN_CENTER, text = 1), # index 2 is Mounted on MultiContentEntryText(pos = (50, 54), size = (500, 20), font=1, flags = RT_HALIGN_LEFT|RT_VALIGN_CENTER, text = 2), # index 3 UUID MultiContentEntryText(pos = (50, 76), size = (130, 20), font=1, flags = RT_HALIGN_LEFT|RT_VALIGN_CENTER, text = 3), # index 4 Type MultiContentEntryText(pos = (180, 76), size = (130, 20), font=1, flags = RT_HALIGN_LEFT|RT_VALIGN_CENTER, text = 4), # index 5 Size_total MultiContentEntryText(pos = (310, 76), size = (190, 20), font=1, flags = RT_HALIGN_LEFT|RT_VALIGN_CENTER, text = 5), # index 6 Size_free MultiContentEntryPixmapAlphaTest(pos = (0, 96), size = (590, 2), png = 6), # png 6 is the div pixmap ]), "mountpoint": (54,[ MultiContentEntryPixmapAlphaTest(pos = (10, 7), size = (30, 30), png = 0), # index 0: picture MultiContentEntryText(pos = (40, 0), size = (500, 30), font=0, flags = RT_HALIGN_LEFT|RT_VALIGN_CENTER, text = 1), # index 1 name MultiContentEntryText(pos = (40, 32), size = (500, 20), font=1, flags = RT_HALIGN_LEFT|RT_VALIGN_CENTER, text = 2), # index 2 path MultiContentEntryPixmapAlphaTest(pos = (0, 52), size = (590, 2), png = 5), # index 5 is the div pixmap ]) }, "fonts": [gFont("Regular", 22),gFont("Regular", 16),gFont("Regular", 28)], "itemHeight": 54 } </convert> </widget> </screen> """ def __init__(self, session): Screen.__init__(self, session) self.session = session self.currList = "default" self.currDevice = None self.currPartition = None self.defaultMountPoint = "/media/hdd" self.deviceList = [] self["menu"] = List(self.deviceList) self["key_red"] = Label(_("Close")) self["key_green"] = Label(" ") self["key_yellow"] = Label(" ") self["key_blue"] = Label(" ") self["shortcuts"] = ActionMap(["ShortcutActions", "SetupActions", "MenuActions" ], { "ok": self.keyOk, "cancel": self.keyCancel, "red": self.keyCancel, "green": self.keyOk, "yellow": self.keyYellow, "blue": self.keyBlue, "menu": self.keyMenu, }, -2) self.DeviceManagerConsole = Console() self.loadIcon() if not self.selectionChanged in self["menu"].onSelectionChanged: self["menu"].onSelectionChanged.append(self.selectionChanged) self.onLayoutFinish.append(self.showDeviceList) self.onLayoutFinish.append(self.addPartitionListChange) self.onClose.append(self.removePartitionListChange) self.onChangedEntry = [] self.blockDevices = {} def addPartitionListChange(self): harddiskmanager.on_partition_list_change.append(self.partitionListChanged) def removePartitionListChange(self): harddiskmanager.on_partition_list_change.remove(self.partitionListChanged) def partitionListChanged(self, action, device): print "[Device manager] hotplug partitionListChanged" if self.currList != "default" and device.device[:3] != self.currDevice["blockdev"]: return self.showDeviceList() def loadIcon(self): self.icon_button_green = LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/buttons/button_green.png")) self.divpng = LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/div-h.png")) def selectionChanged(self): if self.currList == "partitions": currentPartition = self.getCurrentPartition() if currentPartition is not None: if currentPartition["mountpoint"] != "": self["key_green"].setText(_("Umount")) else: self["key_green"].setText(_("Mount")) if currentPartition["fstype"] == "": self["key_blue"].setText("") elif currentPartition["fstype"][:3] == "ext": self["key_blue"].setText(_("Check")) else: self["key_blue"].setText("") def showDeviceList(self): self.deviceList = [] self["key_red"].setText(_("Close")) self["key_green"].setText(_("Ok")) self["key_yellow"].setText(" ") self["key_blue"].setText(_("Initialize")) deviceinfo.refresh() for device in deviceinfo.getBlockDevices(): deviceEntry = ( "%s - %s"%(device["vendor"], device["model"]), # vendor : str, model : str, index 0 _("device : %s")%(device["blockdev"]), # str _("Size : %s")%(byteConversion(device["size"])), # str, bytes _("Partitions : %s")%(len(device["partitions"])), # list _("Removable : %s")%(device["removable"] and 'Yes' or 'No'), # bool [True, False] self.divpng, # png 5 device, # index 6 ) # print "[DeviceManager] deviceEntry : ", deviceEntry self.deviceList.append(deviceEntry) self.currList = "default" self["menu"].style = "default" self["menu"].setList(self.deviceList) def showPartitionList(self): if self.currDevice is None: return partitionList = [] for partition in self.currDevice["partitions"]: partitionInfo = deviceinfo.getPartitionInfo(partition) partitionEntry = ( _("Partition : /dev/%s")%partition, # index 0 _("Mounted on : %s")%checkStrValue(partitionInfo["mountpoint"], _("not mounted")), _("UUID : %s")%checkStrValue(partitionInfo["uuid"], _("unknown")), _("Type : %s")%checkStrValue(partitionInfo["fstype"], _("unknown")), _("Size : %s")%checkStrValue(byteConversion(partitionInfo["size"]), _("unknown")), _("Free : %s")%checkStrValue(byteConversion(partitionInfo["free"]), _("unknown")), self.divpng, # index 6 partitionInfo, # index 7 ) # print "[DeviceManager] partitionEntry : ",partitionEntry partitionList.append(partitionEntry) if len(partitionList) != 0: self["key_red"].setText(_("Devices")) self["key_green"].setText(_("Mount")) self["key_yellow"].setText(_("Format")) self["key_blue"].setText(_("Check")) self.currList = "partitions" self["menu"].style = "partitions" self["menu"].setList(partitionList) self.selectionChanged() else: self.session.open(MessageBox, _("No partition list found on device.\nPlease click BLUE key and do Initialize to use this device."), MessageBox.TYPE_ERROR, timeout = 10) def showMountPointSetup(self): if self.currDevice is None or self.currPartition is None: return partition = self.currPartition["partition"] if not os.access("/autofs/%s"%partition,0): self.session.open(MessageBox, _("This partition is not mountable.\nYou need to check or format this partition."), MessageBox.TYPE_ERROR, timeout = 10) return self["key_red"].setText(_("Partitions")) self["key_green"].setText(_("Ok")) self["key_yellow"].setText("") self["key_blue"].setText("") self.mountPointList = [] currentMountPoint = self.currPartition["mountpoint"] if currentMountPoint == "": currentMountPoint = "'not mounted'" defaultMountPoint = self.getDefaultMountPoint() autoMountPoint = self.getAutoMountPoint() defaultMountPointEntry = (self.icon_button_green, _("Set up Default Mount Point"), _("Mount Point : %s ->%s")%(currentMountPoint, defaultMountPoint), "default", defaultMountPoint, self.divpng) autoMountPointEntry = (self.icon_button_green, _("Automatically set up a Mount Point"), _("Mount Point : %s -> %s")%(currentMountPoint, autoMountPoint), "auto", autoMountPoint, self.divpng) manuallyMountPointEntry = (self.icon_button_green, _("User manually Set up a Mount Point"), _("Mount Point : click ok button on here."), "manual", "", self.divpng) if not path.ismount(defaultMountPoint): self.mountPointList.append(defaultMountPointEntry) self.mountPointList.append(autoMountPointEntry) self.mountPointList.append(manuallyMountPointEntry) self.currList = "mountpoint" self["menu"].style = "mountpoint" self["menu"].setList(self.mountPointList) def getCurrentDevice(self): try: return self["menu"].getCurrent()[6] except: return None def getCurrentPartition(self): try: return self["menu"].getCurrent()[7] except: return None def keyOk(self): # print "keyOk" if self.currList == "default": self.currDevice = self.getCurrentDevice() if self.currDevice is not None: if len(self.currDevice["partitions"]) == 0: self.session.open(MessageBox, _("No partition list found on device.\nPlease click BLUE key and do Initialize to use this device."), MessageBox.TYPE_ERROR, timeout = 10) else: self.showPartitionList() else: self.session.open(MessageBox, _("Device not found."), MessageBox.TYPE_ERROR, timeout = 10) elif self.currList == "partitions": currentPartition = self.getCurrentPartition() if currentPartition is not None: currMountPoint = currentPartition["mountpoint"] currUuid = currentPartition["uuid"] if currMountPoint == "": self.currPartition = currentPartition self.showMountPointSetup() else: self.doUmount(currMountPoint, self.showPartitionList) else: self.session.open(MessageBox, _("Partition info is not found."), MessageBox.TYPE_ERROR, timeout = 10) elif self.currList == "mountpoint": # self["menu"].getCurrent() : (green_button, "menu description", "mount point description, "default", mountpoint, self.divpng) currEntry = self["menu"].getCurrent()[3] if currEntry == "default": # print "Setup mountpoint default!" self.doMount(self.currPartition, self["menu"].getCurrent()[4]) elif currEntry == "auto": # print "Setup mountpoint automatically!" self.doMount(self.currPartition, self["menu"].getCurrent()[4]) else: # print "Setup mountpoint manually!" self.session.openWithCallback(self.MountpointBrowserCB, MountpointBrowser) else: pass def keyCancel(self): # print "keyCancel" if self.DeviceManagerConsole is not None: if len(self.DeviceManagerConsole.appContainers): for name in self.DeviceManagerConsole.appContainers.keys(): self.DeviceManagerConsole.kill(name) if self.currList == "partitions": self.currDevice = None self.showDeviceList() elif self.currList == "mountpoint": self.currPartition = None self.showPartitionList() else: # currList = "default" self.close() def keyYellow(self): if self.currList == "partitions": self.choiceBoxFstype() def keyBlue(self): if self.currList == "default": device = self.getCurrentDevice() if device is not None: self.session.openWithCallback(self.deviceInitCB, DeviceInit, device["blockdev"], device["size"]) else: self.session.open(MessageBox, _("Device not found."), MessageBox.TYPE_ERROR, timeout = 10) elif self.currList == "partitions": partition = self.getCurrentPartition() if partition is not None: self.session.openWithCallback(self.deviceCheckCB, DeviceCheck, partition) else: self.session.open(MessageBox, _("Partition info is not found."), MessageBox.TYPE_ERROR, timeout = 10) def keyMenu(self): self.session.open(DeviceManagerConfiguration) def deviceInitCB(self, ret = True): self.showDeviceList() def deviceCheckCB(self, ret = True): self.showPartitionList() def deviceFormatCB(self, ret = True): self.showPartitionList() def choiceBoxFstype(self): menu = [] menu.append((_("ext2 - recommended for USB flash memory"), "ext2")) menu.append((_("ext3 - recommended for harddisks"), "ext3")) menu.append((_("ext4 - experimental"), "ext4")) menu.append((_("vfat - for USB flash memory"), "vfat")) self.session.openWithCallback(self.choiceBoxFstypeCB, ChoiceBox, title=_("Choice filesystem."), list=menu) def choiceBoxFstypeCB(self, choice): if choice is None: return else: partition = self.getCurrentPartition() if partition is not None: self.session.openWithCallback(self.deviceFormatCB, DeviceFormat, partition, choice[1]) else: self.session.open(MessageBox, _("Partition info is not found."), MessageBox.TYPE_ERROR, timeout = 10) # about mount funcs.. def doUmount(self, mountpoint, callback): cmd = "umount %s"%mountpoint print "[DeviceManager] cmd : %s"%cmd os.system(cmd) if not path.ismount(mountpoint): devicemanagerconfig.updateConfigList() else: self.session.open(MessageBox, _("Can't umount %s. \nMaybe device or resource busy.")%mountpoint, MessageBox.TYPE_ERROR, timeout = 10) callback() def getDefaultMountPoint(self): return self.defaultMountPoint def getAutoMountPoint(self): mountPoint = "/media/"+self.currDevice["model"] mountPoint = mountPoint.replace(' ','-') if path.ismount(mountPoint): partnum = 2 while 1: mountPoint_fix = mountPoint+str(partnum) if not path.ismount(mountPoint_fix): break partnum +=1 mountPoint = mountPoint_fix return mountPoint def doMount(self, partition, mountpoint): try: # check mountpoint is in partition list. if mountpoint != self.getDefaultMountPoint(): for p in harddiskmanager.partitions: if p.mountpoint == mountpoint: self.session.open(MessageBox, _("Can not use this mount point.(%s) \nPlease select another mount point.")%mountpoint, MessageBox.TYPE_ERROR, timeout = 10) return # device = partition["partition"] filesystem = partition["fstype"] uuid = partition["uuid"] if mountpoint.endswith("/"): mountpoint = retval[:-1] if mountpoint.find(' ') != -1: mountpoint = mountpoint.replace(' ','-') devpath = "/dev/"+device if deviceinfo.isMounted(devpath, mountpoint): print "[DeviceManager] '%s -> %s' is already mounted."%(devpath, mountpoint) return # check current device mounted on another mountpoint. mp_list = deviceinfo.checkMountDev(devpath) for mp in mp_list: if mp != mountpoint and path.ismount(mp): deviceinfo.umountByMountpoint(mp) # check another device mounted on configmountpoint devpath_list = deviceinfo.checkMountPoint(mountpoint) for devpath_ in devpath_list: if devpath_ != devpath: self.session.open(MessageBox, _("Mount Failed!\nCurrent path is already mounted by \"%s\"")%devpath_list[0], MessageBox.TYPE_ERROR, timeout = 10) return # do mount print "[DeviceManagerHotplugDevice] doMount" if not path.exists(mountpoint): os.system("mkdir %s"%mountpoint) if path.exists(mountpoint): if not path.ismount(mountpoint): if filesystem == "ntfs": cmd = "ntfs-3g %s %s"%(devpath, mountpoint) elif filesystem is None: cmd = "mount %s %s"%(devpath, mountpoint) else: cmd = "mount -t %s %s %s"%(filesystem, devpath, mountpoint) print "[DeviceManager] cmd : %s"%cmd self.DeviceManagerConsole.ePopen(cmd, self.doMountFinished, (devpath, mountpoint) ) except: self.session.open(MessageBox, _("Mount Failed!\n(%s -> %s)")%(device, mountpoint), MessageBox.TYPE_ERROR, timeout = 10) def doMountFinished(self, result, retval, extra_args = None): (devpath, mountpoint) = extra_args if retval == 0: if not deviceinfo.isMounted(devpath, mountpoint): # print "[DeviceManager] %s doMount failed!"%devpath self.session.open(MessageBox, _("Mount Failed!\n(%s -> %s)")%(devpath, mountpoint), MessageBox.TYPE_ERROR, timeout = 10) return else: # make movie directory if mountpoint == "/media/hdd": movieDir = mountpoint + "/movie" if not pathExists(movieDir): print "[DeviceManager] make dir %s"%movieDir os.makedirs(movieDir) self.showPartitionList() # update current mount state ,devicemanager.cfg devicemanagerconfig.updateConfigList() def MountpointBrowserCB(self, retval = None): if retval and retval is not None: mountPoint = retval.strip().replace(' ','') if retval.endswith("/"): mountPoint = retval[:-1] print "Mount point from MountpointBrowser : %s"%mountPoint if not path.exists(mountPoint): self.session.open(MessageBox, _("Mount Point is not writeable.\nPath : %s")%mountPoint, MessageBox.TYPE_ERROR, timeout = 10) else: self.doMount(self.currPartition, mountPoint) # mount funcs end.. # Initializing Start... class DeviceInit(Screen): skin = """<screen position="0,0" size="0,0"/>""" def __init__(self, session, device, devicesize): Screen.__init__(self, session) self.session = session self.deviceInitConsole = Console() self.device = device self.devicesize = int(devicesize) self.inputbox_partitions = 1 self.inputbox_partitionSizeList = [] self.inputbox_partitionSizeTotal = int(self.devicesize/1024/1024) self.msgWaiting = None self.msgWaitingMkfs = None self.devicenumber = 0 self.newpartitions = 0 self.onLayoutFinish.append(self.timerStart) self.initStartTimer = eTimer() self.initStartTimer.callback.append(self.confirmMessage) self.createFSStartTimer = eTimer() self.createFSStartTimer.callback.append(self.createFilesystemStart) self.exitMessageTimer = eTimer() self.exitMessageTimer.callback.append(self.exitMessage) self.msg = "" self.fstype = None self.mkfs_cmd = "" self.doMkfsTimer = eTimer() self.doMkfsTimer.callback.append(self.doMkfs) self.doInitializeTimer = eTimer() self.doInitializeTimer.callback.append(self.doInitialize) self.partitionType = "MBR" self.maxPartNum = 4 self.inputbox_partitionSizeRemain = self.inputbox_partitionSizeTotal self.unit = "MB" def timerStart(self): self.initStartTimer.start(100,True) def confirmMessage(self): message = _("Do you really want to initialize the device?\nAll data on the device will be lost!") self.session.openWithCallback(self.confirmed, MessageBox, message) def confirmed(self, ret): if ret: self.InitializeStart() else: self.exit() def exit(self, ret = True): self.close() def unmountAll(self, device): mounts = file('/proc/mounts').read().split('\n') cmd = "" # umount all for line in mounts: if not line.startswith("/dev/" + device): continue cmd += "umount %s ;"% line.split()[0] print "[DeviceManager] %s"%cmd os.system(cmd) #recheck if umounted mounts = file('/proc/mounts').read().split('\n') for line in mounts: if line.startswith("/dev/" + device): return False return True def InitializeStart(self): if self.devicesize >= ( 2.2 * 1000 * 1000 * 1000 * 1000 ): # 2.2TB self.partitionType = "GPT" self.maxPartNum = 20 self.inputbox_partitionSizeRemain = 100 self.unit = "%" self.InputPartitionSize_step1() def InputPartitionSize_step1(self): self.session.openWithCallback(self.InputPartitionSize_step1_CB, InputBox, title=_("How many partitions do you want?(1-%d)" % self.maxPartNum), text="1", maxSize=False, type=Input.NUMBER) def InputPartitionSize_step1_CB(self, ret): if ret is not None and int(ret) in range(1,self.maxPartNum+1): # MBR 1~4, GPT 1~20 self.inputbox_partitions = int(ret) self.InputPartitionSize_step2() else: self.session.openWithCallback(self.exit, MessageBox, _("The number you entered is wrong!"), MessageBox.TYPE_ERROR, timeout = 10) def InputPartitionSize_step2(self): current_partition = len(self.inputbox_partitionSizeList)+1 if self.inputbox_partitionSizeRemain == 0: self.choiceBoxFstype() elif current_partition == self.inputbox_partitions: self.inputbox_partitionSizeList.append(str(self.inputbox_partitionSizeRemain)) self.choiceBoxFstype() else: text = str(int(self.inputbox_partitionSizeRemain/(self.inputbox_partitions-len(self.inputbox_partitionSizeList) ))) self.session.openWithCallback(self.InputPartitionSize_step2_CB, InputBox, title=_("Input size of partition %s.(Unit = %s, Max = %d %s)")%(current_partition, self.unit, self.inputbox_partitionSizeRemain, self.unit), text=text, maxSize=False, type=Input.NUMBER) def InputPartitionSize_step2_CB(self, ret): if ret is not None: if self.inputbox_partitionSizeRemain < int(ret) or int(ret) == 0: self.InputPartitionSize_step2() else: self.inputbox_partitionSizeList.append(str(ret)) self.inputbox_partitionSizeRemain -= int(ret) self.InputPartitionSize_step2() else: self.session.openWithCallback(self.exit ,MessageBox, _("The number you entered is wrong!"), MessageBox.TYPE_ERROR, timeout = 10) def choiceBoxFstype(self): menu = [] menu.append((_("ext2 - recommended for USB flash memory"), "ext2")) menu.append((_("ext3 - recommended for harddisks"), "ext3")) menu.append((_("ext4 - experimental"), "ext4")) menu.append((_("vfat - for USB flash memory"), "vfat")) self.session.openWithCallback(self.choiceBoxFstypeCB, ChoiceBox, title=_("Choice filesystem."), list=menu) def choiceBoxFstypeCB(self, choice): if choice is None: self.exit() else: self.fstype = choice[1] if self.fstype not in ["ext2", "ext3", "ext4", "vfat"]: self.exit() else: self.initInitializeConfirm() def initInitializeConfirm(self): # print self.inputbox_partitionSizeList partitionsInfo = "" for index in range(len(self.inputbox_partitionSizeList)): print "partition %d : %s %s"%(index+1, str(self.inputbox_partitionSizeList[index]), self.unit) partitionsInfo += "partition %d : %s %s\n"%(index+1, str(self.inputbox_partitionSizeList[index]), self.unit) partitionsInfo += "filesystem type : %s"%(self.fstype) self.session.openWithCallback(self.initInitializeConfirmCB, MessageBoxConfirm, _("%s\nStart Device Inititlization?") % partitionsInfo , MessageBox.TYPE_YESNO) def initInitializeConfirmCB(self,ret): if ret: self.initInitialize() else: self.exit() def initInitialize(self): if not self.unmountAll(self.device): self.session.openWithCallback(self.exit, MessageBox, _("umounting failed!Maybe some files in mount point are open"), MessageBox.TYPE_ERROR, timeout = 10) else: msg = _("InitInitializing, please wait ...") msg += _("\nDevice : %s")%self.device msg += _("\nSize : %s MB\n")%self.inputbox_partitionSizeTotal for index in range(len(self.inputbox_partitionSizeList)): msg += _("\npartition %d : %s %s")%(index+1, str(self.inputbox_partitionSizeList[index]), self.unit) self.msgWaiting = self.session.openWithCallback(self.msgWaitingCB, MessageBox_2, msg, type = MessageBox.TYPE_INFO, enable_input = False) self.doInitializeTimer.start(500,True) def doInitialize(self): def CheckPartedVer(): cmd = 'parted --version' lines = os.popen(cmd).readlines() for l in lines: if l.find("parted (GNU parted)") != -1: ver = l.split()[3].strip() break try: ver = float(ver) except: print "[CheckPartedVer] check parted version Failed!" return 0 return ver partitions = len(self.inputbox_partitionSizeList) # get num of partition set = "" if self.partitionType == "MBR": if partitions == 1: cmd = 'printf "8,\n;0,0\n;0,0\n;0,0\ny\n" | sfdisk -f -uS /dev/' + self.device else: for p in range(4): if partitions > p+1: set += ",%s\n"%(self.inputbox_partitionSizeList[p]) else: set +=";\n" set+="y\n" cmd = 'printf "%s" | sfdisk -f -uM /dev/%s'%(set,self.device) elif self.partitionType == "GPT": # partition type is GPT setAlign = "" partedVer = CheckPartedVer() if partedVer >= 2.1: # align option is supported in version 2.1 or later setAlign = "--align optimal" if partitions == 1: cmd = 'parted %s /dev/%s --script mklabel gpt mkpart disk ext2 0%% 100%%' % (setAlign, self.device) else: # has multiple partitions p_current = 0 for p in range(partitions): if p == 0: p_start = p_current p_end = int( (long(self.inputbox_partitionSizeList[p]) * 100) / 100 ) p_current = p_end elif p > 0 and partitions > (p + 1): p_start = p_current p_end = int( (long(self.inputbox_partitionSizeList[p]) * 100) / 100 )+ p_start p_current = p_end elif partitions == (p + 1): p_start = p_current p_end = 100 if p_start == p_end: p_end +=1 if p_end > 100: continue set += 'mkpart disk%d ext2 %d%% %d%% ' % (p + 1, p_start, p_end) cmd = 'parted %s /dev/%s --script mklabel gpt %s' % (setAlign, self.device, set) else: errorMsg = "Invalid partitioning type" self.msgWaiting.run_close(False, errorMsg) return self.deviceInitConsole.ePopen(cmd, self.initInitializeFinished) def initInitializeFinished(self, result, retval, extra_args = None): if retval == 0: if self.partitionType == "MBR": cmd = "sfdisk -R /dev/%s ; sleep 5" % (self.device) else: # is GPT cmd = "sleep 5" self.deviceInitConsole.ePopen(cmd, self.initInitializingRefreshFinished) else: errorMsg = "initInitializing device Error at /dev/%s"%self.device self.msgWaiting.run_close(False, errorMsg) def initInitializingRefreshFinished(self, result, retval, extra_args = None): cmd = "/bin/umount /dev/%s*" % (self.device) self.deviceInitConsole.ePopen(cmd, self.initInitializingUmountFinished) def initInitializingUmountFinished(self, result, retval, extra_args = None): partitions = open("/proc/partitions") self.devicenumber = 0 self.newpartitions = 0 for part in partitions: res = re.sub("\s+", " ", part).strip().split(" ") if res and len(res) == 4 and res[3][:3] == self.device: if len(res[3]) > 3 and res[3][:2] == "sd": self.newpartitions += 1 partitions.close() partNum = len(self.inputbox_partitionSizeList) # get num of partition if self.newpartitions != partNum: errorMsg = "Partitioning device Error at /dev/%s"%self.device self.msgWaiting.run_close(False, errorMsg) else: self.msgWaiting.run_close(True) # self.createFilesystem(self.newpartitions) def createFilesystem(self, newpartitions): self.devicenumber = self.devicenumber + 1 fulldevicename = "/dev/" + self.device + str(self.devicenumber) shortdevicename = self.device + str(self.devicenumber) # get partition size partitions = open("/proc/partitions") for part in partitions: res = re.sub("\s+", " ", part).strip().split(" ") if res and len(res) == 4: if res[3] == shortdevicename: partitionsize = int(res[2]) break partitions.close() if self.fstype == "ext4": cmd = "/sbin/mkfs.ext4 -F " if partitionsize > 2 * 1024 * 1024: # 2GB cmd += "-T largefile " cmd += "-O extent,flex_bg,large_file,uninit_bg -m1 " + fulldevicename elif self.fstype == "ext3": cmd = "/sbin/mkfs.ext3 -F " if partitionsize > 2 * 1024 * 1024: cmd += "-T largefile " cmd += "-m0 " + fulldevicename elif self.fstype == "ext2": cmd = "/sbin/mkfs.ext2 -F " if partitionsize > 2 * 1024 * 1024: cmd += "-T largefile " cmd += "-m0 " + fulldevicename elif self.fstype == "vfat": if partitionsize > 4 * 1024 * 1024 * 1024: cmd = "/usr/sbin/mkfs.vfat -I -S4096 " + fulldevicename else: cmd = "/usr/sbin/mkfs.vfat -I " + fulldevicename else: self.createFilesystemFinished(None, -1, (self.device, fulldevicename)) return msg = _("Create filesystem, please wait ...") msg += _("\nPartition : %s") % (fulldevicename) msg += _("\nFilesystem : %s") % (self.fstype) msg += _("\nDisk Size : %s MB") % (self.inputbox_partitionSizeTotal) msg += _("\nPartition Size : %d %s\n") % (int(self.inputbox_partitionSizeList[self.devicenumber-1]), self.unit) self.msgWaitingMkfs = self.session.openWithCallback(self.msgWaitingMkfsCB, MessageBox_2, msg, type = MessageBox.TYPE_INFO, enable_input = False) self.mkfs_cmd = cmd self.doMkfsTimer.start(500,True) def doMkfs(self): fulldevicename = "/dev/" + self.device + str(self.devicenumber) self.deviceInitConsole.ePopen(self.mkfs_cmd, self.createFilesystemFinished, (self.device, fulldevicename)) def createFilesystemFinished(self, result, retval, extra_args = None): device = extra_args[0] fulldevicename = extra_args[1] if retval == 0: self.msgWaitingMkfs.run_close(True) else: errorMsg = _("Creating filesystem Error") if fulldevicename is not None: errorMsg += _(" at /dev/%s")%fulldevicename self.msgWaitingMkfs.run_close(False, errorMsg) def createFilesystemStart(self): self.createFilesystem(self.newpartitions) def msgWaitingCB(self, ret, msg=""): if ret: self.createFSStartTimer.start(100,True) else: self.success = False self.msg = msg self.exitMessageTimer.start(100,True) def msgWaitingMkfsCB(self, ret, msg=""): if self.devicenumber < self.newpartitions: self.createFSStartTimer.start(100,True) else: if ret == True: self.success = True self.msg = _("Device Initialization finished sucessfully!") self.updateDeviceInfo() self.exitMessageTimer.start(100,True) else: self.success = False self.msg = msg self.exitMessageTimer.start(100,True) def exitMessage(self): if self.success: self.session.openWithCallback(self.exit, MessageBox, self.msg, MessageBox.TYPE_INFO, timeout = 10) else: self.session.openWithCallback(self.exit, MessageBox, self.msg, MessageBox.TYPE_ERROR, timeout = 10) def updateDeviceInfo(self): # update devicemanager configs devicemanagerconfig.updateConfigList() # Initializing end # device check start.. class DeviceCheck(Screen): skin = """<screen position="0,0" size="0,0"/>""" def __init__(self, session, partition): Screen.__init__(self, session) self.session = session self.deviceCheckConsole = Console() self.partition = partition self.onLayoutFinish.append(self.timerStart) self.checkStartTimer = eTimer() self.checkStartTimer.callback.append(self.confirmMessage) self.umountTimer = eTimer() self.umountTimer.callback.append(self.doUnmount) def timerStart(self): self.checkStartTimer.start(100,True) def confirmMessage(self): fssize = self.partition["size"] if long(fssize) > 1024*1024*1024*16: message = _("Do you really want to check the filesystem?\nThis could take lots of time!") self.session.openWithCallback(self.confirmed, MessageBox, message) else: self.deviceCheckStart() def confirmed(self, ret): print "confirmed : ",ret if ret: self.deviceCheckStart() else: self.exit() def deviceCheckStart(self): print "deviceCheckStart " print "partition : ", self.partition device = self.partition["partition"] fstype = self.partition["fstype"] fssize = self.partition["size"] if device is not None and fstype.startswith("ext"): msg = _("Check filesystem, please wait ...") msg += _("\nDevice : /dev/%s")%(device) msg += _("\nFilesystem : %s")%(fstype) self.msgWaiting = self.session.openWithCallback(self.msgWaitingCB, MessageBox_2, msg, type = MessageBox.TYPE_INFO, enable_input = False) self.umountTimer.start(500,True) else: self.exit() def doUnmount(self): device = self.partition["partition"] mountpoint = self.partition["mountpoint"] fstype = self.partition["fstype"] if mountpoint != "": self.doUmountFsck(device, mountpoint, fstype) else: self.umountFsckFinished("NORESULT", 0, (device, mountpoint, fstype)) def doUmountFsck(self, device, mountpoint, fstype): cmd = "umount /dev/%s" % device self.deviceCheckConsole.ePopen(cmd, self.umountFsckFinished, (device, mountpoint, fstype)) def umountFsckFinished(self, result, retval, extra_args = None): device = extra_args[0] mountpoint = extra_args[1] fstype = extra_args[2] if retval == 0: cmd = "fsck." + fstype + " -f -p /dev/" + device self.deviceCheckConsole.ePopen(cmd, self.fsckFinished, extra_args) else: errorMsg = _("Can not umount device /dev/%s.\nMaybe some files of the filesystem are open")%device self.msgWaiting.run_close(False,errorMsg) def fsckFinished(self, result, retval, extra_args = None): device = extra_args[0] mountpoint = extra_args[1] if retval == 0: text = _("Filesystem check finished sucessfully") self.msgWaiting.run_close(True, text) else: text = _("Error checking disk. The disk or filesystem may be damaged") self.msgWaiting.run_close(False, text) def msgWaitingCB(self, ret, msg): if ret: self.session.open(MessageBox, msg, MessageBox.TYPE_INFO, timeout = 10) else: self.session.open(MessageBox, msg, MessageBox.TYPE_ERROR, timeout = 10) partition = self.partition["partition"] mountpoint = self.partition["mountpoint"] fstype = self.partition["fstype"] if mountpoint != "": if fstype == "ntfs": cmd = "ntfs-3g /dev/" + partition + " " + mountpoint else: cmd = "mount /dev/" + partition + " " + mountpoint self.deviceCheckConsole.ePopen(cmd, self.mountPartitionFinished) else: self.exit() def mountPartitionFinished(self, result, retval, extra_args = None): self.exit() def exit(self): self.close() #device check end #device format start class DeviceFormat(Screen): skin = """<screen position="0,0" size="0,0"/>""" def __init__(self, session, partition, newfstype): Screen.__init__(self, session) self.session = session self.deviceFormatConsole = Console() self.partition = partition self.newfstype = newfstype self.unmountedList = [] self.onLayoutFinish.append(self.timerStart) self.formatStartTimer = eTimer() self.formatStartTimer.callback.append(self.DeviceFormatStart) self.setHotplugDisabled = False self.umountTimer = eTimer() self.umountTimer.callback.append(self.doUnmount) def timerStart(self): self.formatStartTimer.start(100,True) def DeviceFormatStart(self): devicemanagerhotplug.setHotplugActive(False) self.setHotplugDisabled = True print "DeviceFormatStart : ", self.partition, print "Filesystem : ",self.newfstype device = self.partition["partition"] devicepath = "/dev/"+device fssize = self.partition["size"] newfstype = self.newfstype msg = _("Format filesystem, please wait ...") msg += _("\nDevice : %s")%(devicepath) msg += _("\nFilesystem : %s")%(newfstype) msg += _("\nSize : %s")%(byteConversion(fssize)) self.msgWaiting = self.session.openWithCallback(self.msgWaitingCB, MessageBox_2, msg, type = MessageBox_2.TYPE_INFO, enable_input = False, msgBoxID = None) self.umountTimer.start(500,True) def doUnmount(self): mountpoint = self.partition["mountpoint"] if mountpoint != "": self.doumountPartition() else: self.umountPartitionFinished("NORESULT", 0) def doumountPartition(self): oldfstype = self.partition["fstype"] newfstype = self.newfstype if newfstype == oldfstype: device = self.partition["partition"] else: device = self.partition["partition"][:3] cmd = "" mounts = file('/proc/mounts','r') for line in mounts.readlines(): if line.startswith("/dev/%s"%device): cmd += "umount %s;"%line.split()[0] self.unmountedList.append([line.split()[0], line.split()[1]]) self.deviceFormatConsole.ePopen(cmd, self.umountPartitionFinished) def umountPartitionFinished(self, result, retval, extra_args = None): partition = self.partition["partition"] oldfstype = self.partition["fstype"] newfstype = self.newfstype if retval == 0: if oldfstype == newfstype: self.changePartitionIDFinished("NORESULT", 0) else: cmd = "sfdisk --change-id /dev/%s %s" % (partition[:3], partition[3:]) if newfstype[:3] == "ext": cmd += " 83" else: cmd += " c" self.deviceFormatConsole.ePopen(cmd, self.changePartitionIDFinished) else: errorMsg = _("Can not umount device /dev/%s.\nMaybe some files of the filesystem are open")%partition[:3] self.msgWaiting.run_close(False,errorMsg) def changePartitionIDFinished(self, result, retval, extra_args = None): device = self.partition["partition"][:3] mountpoint = self.partition["mountpoint"] oldfstype = self.partition["fstype"] newfstype = self.newfstype if retval == 0: if oldfstype == newfstype: self.refreshPartitionFinished("NORESULT", 0) else: cmd = "sfdisk -R /dev/%s; sleep 5"%(device) self.deviceFormatConsole.ePopen(cmd, self.refreshPartitionFinished) else: if result and result.find("Use GNU Parted") > 0: print "[DeviceManager] /dev/%s use GNU Parted!" % device self.refreshPartitionFinished("NORESULT", 0) else: errorMsg = _("Can not change the partition ID for %s")%device self.msgWaiting.run_close(False,errorMsg) def refreshPartitionFinished(self, result, retval, extra_args = None): print "refreshPartitionFinished!" partition = self.partition["partition"] mountpoint = self.partition["mountpoint"] size = int(self.partition["size"])/1024/1024 oldfstype = self.partition["fstype"] newfstype = self.newfstype if retval == 0: if newfstype == "ext4": cmd = "/sbin/mkfs.ext4 -F " if size > 2 * 1024: cmd += "-T largefile " cmd += "-O extent,flex_bg,large_file,uninit_bg -m1 /dev/" + partition elif newfstype == "ext3": cmd = "/sbin/mkfs.ext3 -F " if size > 2 * 1024: cmd += "-T largefile " cmd += "-m0 /dev/" + partition elif newfstype == "ext2": cmd = "/sbin/mkfs.ext2 -F " if size > 2 * 1024: cmd += "-T largefile " cmd += "-m0 /dev/" + partition elif newfstype == "vfat": if size > 4 * 1024 * 1024: cmd = "/usr/sbin/mkfs.vfat -I -S4096 /dev/" + partition else: cmd = "/usr/sbin/mkfs.vfat -I /dev/" + partition self.deviceFormatConsole.ePopen(cmd, self.mkfsFinished) else: errorMsg = _("Can not format device /dev/%s.\nrefresh partition information failed!")%partition self.msgWaiting.run_close(False,errorMsg) def mkfsFinished(self, result, retval, extra_args = None): print "mkfsFinished!" partition = self.partition["partition"] if retval == 0: cmd = "" if len(self.unmountedList) == 0: self.doMountFinished("NORESULT",0) for x in self.unmountedList: cmd += "mount %s %s;"%(x[0], x[1]) self.deviceFormatConsole.ePopen(cmd, self.doMountFinished) else: text = _("Make filesystem Error /dev/%s.\nPlease check your device.")%partition self.msgWaiting.run_close(False, text) def doMountFinished(self, result, retval, extra_args = None): print "doMountFinished!" text = _("Format finished sucessfully.") self.msgWaiting.run_close(True, text) def msgWaitingCB(self, ret, msg): if ret: self.session.openWithCallback(self.exit, MessageBox, msg, MessageBox.TYPE_INFO, timeout = 10) else: self.session.openWithCallback(self.exit, MessageBox, msg, MessageBox.TYPE_ERROR, timeout = 10) def exit(self, ret): if self.setHotplugDisabled == True: devicemanagerhotplug.setHotplugActive(True) self.setHotplugDisabled = False self.close() #device format end class DeviceInfo(): def __init__(self): self.blockDeviceList = [] def getBlockDevices(self): return self.blockDeviceList def refresh(self): self.blockDeviceList = [] self.getBlockDeviceList() def getBlockDeviceList(self): print "get block device Infomations..." for blockdev in listdir("/sys/block"): (error, blacklisted, removable, partitions, size, model, vendor) = self.getBlockDeviceInfo(blockdev) if not blacklisted and not error: # print "%s : error %s, blacklisted %s, removable %s, partitions %s, size %s"%(blockdev, error, blacklisted, removable, partitions, size) blockDevice = {} blockDevice["blockdev"] = blockdev # str blockDevice["removable"] = removable # bool [True, False] blockDevice["partitions"] = partitions # list blockDevice["size"] = size # str blockDevice["model"] = model # str blockDevice["vendor"] = vendor # str self.blockDeviceList.append(blockDevice) def SortPartList(self, partList): length = len(partList)-1 sorted = False while sorted is False: sorted = True for idx in range(length): if int(partList[idx][3:]) > int(partList[idx+1][3:]): sorted = False partList[idx] , partList[idx+1] = partList[idx+1], partList[idx] def getBlockDeviceInfo(self, blockdev): devpath = "/sys/block/" + blockdev error = False removable = False blacklisted = False partitions = [] size ="" model = "" vendor = "" try: dev = int(readFile(devpath + "/dev").split(':')[0]) if dev in (7, 31) or blockdev[0:2] != 'sd': # 7: loop, 31 : mtdblock blacklisted = True return error, blacklisted, removable, partitions, size, model, vendor removable = bool(int(readFile(devpath + "/removable"))) size = str(int(readFile(devpath + "/size").strip())*512) model = readFile(devpath + "/device/model") vendor = readFile(devpath + "/device/vendor") for partition in listdir(devpath): if partition[:len(blockdev)] != blockdev: continue partitions.append(partition) self.SortPartList(partitions) except IOError: error = True return error, blacklisted, removable, partitions, size, model, vendor def getPartitionInfo(self, partition): mountPoint = self.getPartitionMountpoint(partition) (uuid , fsType) = self.getPartitionBlkidInfo(partition) size_total = self.getPartitionSize(partition) size_free = "" if mountPoint != "": size_free = self.getPartitionFree(mountPoint) partitionInfo = {} partitionInfo["partition"] = partition partitionInfo["mountpoint"] = mountPoint partitionInfo["uuid"] = uuid partitionInfo["fstype"] = fsType partitionInfo["size"] = size_total partitionInfo["free"] = size_free return partitionInfo def getPartitionMountpoint(self, partition): mounts = file('/proc/mounts').read().split('\n') for x in mounts: if not x.startswith('/'): continue devpath, mountpoint, = x.split()[:2] if mountpoint.startswith('/autofs'): continue if path.basename(devpath) == partition: return mountpoint return "" def getPartitionBlkidInfo(self, partition): parttionDev = "/dev/"+str(partition) uuid = "" partitionType = "" cmd = "blkid -c /dev/null "+str(parttionDev) try: line = popen(cmd).readline().strip() if not line.startswith(parttionDev): return (uuid, partitionType) # print "Blikd %s : %s"%(parttionDev, line) if line.find(" UUID=") != -1: uuid = line.split(" UUID=")[1].split(' ')[0] if line.find(" TYPE=") != -1: partitionType = line.split(" TYPE=")[1].split(' ')[0].strip('"') except: print "get blkid info error (%s)"%cmd return (uuid, partitionType) def getPartitionSize(self, partition): devpath = "/sys/block/%s/%s"%( str(partition[:3]), str(partition) ) try: size = readFile(devpath + "/size") return str(int(size)*512) except: return "" def getPartitionFree(self, mountPoint): try: stat = statvfs(mountPoint) size_free = stat.f_bfree*stat.f_bsize return size_free except: return "" def checkMountPoint(self, check_mountpoint): res = [] try: mounts = file('/proc/mounts').read().split('\n') for x in mounts: if not x.startswith('/'): continue devpath, mountpoint = x.split()[:2] if mountpoint == check_mountpoint: res.append(devpath) except: pass return res def checkMountDev(self, device): res = [] try: mounts = file('/proc/mounts').read().split('\n') for x in mounts: if not x.startswith('/'): continue devpath, mountpoint = x.split()[:2] if devpath == device: res.append(mountpoint) except: pass return res def isMounted(self, devpath, mountpoint): try: mounts = file('/proc/mounts').read().split('\n') for x in mounts: if not x.startswith('/'): continue _devpath, _mountpoint = x.split()[:2] if devpath == _devpath and mountpoint == _mountpoint: return True except: pass return False def isMountable(self, partition): autofsPath = "/autofs/"+partition.device mountable = False try: os.listdir(autofsPath) mountable = True except: pass return mountable def isFstabAutoMounted(self, uuid, devpath, mountpoint): # print " >> isFstabMounted, uuid : %s, devpath : %s, mountpoint : %s"%(uuid, devpath, mountpoint) if mountpoint[-1] == '/': mountpoint = mountpoint[:-1] data = file('/etc/fstab').read().split('\n') for line in data: if not line.startswith('/'): continue dev, mp, ms = line.split()[0:3] if uuid is not None and dev.startswith('UUID'): if dev.split('=')[1] == uuid.strip("\"") and mp == mountpoint and ms == 'auto': # print " >> line : ", line return True elif dev == devpath and mp == mountpoint and ms == 'auto': # print " >> line : ", line return True return False def umountByMountpoint(self, mountpoint): if mountpoint is None: return False try: if path.ismount(mountpoint): cmd = "umount " + mountpoint print "[DeviceManager] ", cmd os.system(cmd) except: print "Umount by mountpoint failed!" if not path.ismount(mountpoint): return True return False def umountByDevpath(self, devpath): cmd = "umount " + devpath print "[DeviceManager] ", cmd os.system(cmd) deviceinfo = DeviceInfo() class MountpointBrowser(Screen): skin=""" <screen name="MountpointBrowser" position="center,120" size="670,500" title="Select mountpoint"> <ePixmap pixmap="skin_default/buttons/red.png" position="20,0" size="140,40" alphatest="on" /> <ePixmap pixmap="skin_default/buttons/green.png" position="180,0" size="140,40" alphatest="on" /> <ePixmap pixmap="skin_default/buttons/yellow.png" position="340,0" size="140,40" alphatest="on" /> <ePixmap pixmap="skin_default/buttons/blue.png" position="500,0" size="140,40" alphatest="on" /> <widget source="key_red" render = "Label" position="20,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" foregroundColor="#ffffff" backgroundColor="#9f1313" transparent="1" /> <widget source="key_green" render = "Label" position="180,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" foregroundColor="#ffffff" backgroundColor="#1f771f" transparent="1" /> <widget source="key_yellow" render = "Label" position="340,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" foregroundColor="#ffffff" backgroundColor="#a08500" transparent="1" /> <widget source="key_blue" render = "Label" position="500,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" foregroundColor="#ffffff" backgroundColor="#18188b" transparent="1" /> <eLabel position="10,50" size="650,1" backgroundColor="#b3b3b9"/> <widget name="filelist" position="10,60" size="650,440" itemHeight="30" scrollbarMode="showOnDemand"/> </screen> """ def __init__(self, session): Screen.__init__(self, session) self["key_red"] = StaticText(_("Cancel")) self["key_green"] = StaticText(_("Select")) self["key_yellow"] = StaticText(_("Create directory")) self["key_blue"] = StaticText("Delete directory") directory = "/media/" inhibitDirs = ["/autofs", "/mnt", "/hdd", "/bin", "/boot", "/dev", "/etc", "/home", "/lib", "/proc", "/sbin", "/share", "/sys", "/tmp", "/usr", "/var"] self.filelist = FileList(directory, matchingPattern="", inhibitDirs = inhibitDirs) self["filelist"] = self.filelist self["shortcuts"] = ActionMap(["ColorActions"], { "red": self.exit, "green": self.select, "yellow": self.createDirectory, "blue": self.deleteDirectory, }, -2) self["OkCancelActions"] = ActionMap(["OkCancelActions"], { "cancel": self.exit, "ok": self.ok, }, -2) def ok(self): if self.filelist.canDescent(): self.filelist.descent() def select(self): if self["filelist"].getCurrentDirectory() is not None: if self.filelist.canDescent() and self["filelist"].getFilename() and self["filelist"].getFilename().startswith(self["filelist"].getCurrentDirectory()): self.filelist.descent() currDir = self["filelist"].getCurrentDirectory() self.close(currDir) else: self.close(self["filelist"].getFilename()) def createDirectory(self): self.session.openWithCallback(self.createDirectoryCB, VirtualKeyBoard, title = (_("Input mount point path.")), text = "") def createDirectoryCB(self, retval = None): newdir=None try: if retval is not None: newdir = self["filelist"].getCurrentDirectory()+'/'+retval if not path.exists(newdir): os.system("mkdir %s"%newdir) self.filelist.refresh() except: if newdir: self.session.open(MessageBox, _("Create directory failed!\n%s")%newdir, MessageBox.TYPE_ERROR, timeout = 10) def deleteDirectory(self): delDir=None try: if self["filelist"].getCurrentDirectory() is not None: if self.filelist.canDescent() and self["filelist"].getFilename() and self["filelist"].getFilename().startswith(self["filelist"].getCurrentDirectory()): delDir = self["filelist"].getFilename() if path.exists(delDir): os.system("rmdir '%s'"%delDir) if path.exists(delDir): self.session.open(MessageBox, _("Delete directory failed!\nMaybe directory is not empty."), MessageBox.TYPE_ERROR, timeout = 10) self.filelist.refresh() except: if delDir: self.session.open(MessageBox, _("Delete directory failed!\n%s")%newdir, MessageBox.TYPE_ERROR, timeout = 10) def exit(self): self.close(False) class MessageBoxConfirm(MessageBox): skin = """ <screen position="center,center" size="620,10" title="Message"> <widget name="text" position="65,8" size="420,0" font="Regular;20" /> <widget name="ErrorPixmap" pixmap="skin_default/icons/input_error.png" position="5,5" size="53,53" alphatest="blend" /> <widget name="QuestionPixmap" pixmap="skin_default/icons/input_question.png" position="5,5" size="53,53" alphatest="blend" /> <widget name="InfoPixmap" pixmap="skin_default/icons/input_info.png" position="5,5" size="53,53" alphatest="blend" /> <widget name="list" position="100,100" size="380,375" transparent="1" /> <applet type="onLayoutFinish"> # this should be factored out into some helper code, but currently demonstrates applets. from enigma import eSize, ePoint orgwidth = self.instance.size().width() orgheight = self.instance.size().height() orgpos = self.instance.position() textsize = self[&quot;text&quot;].getSize() # y size still must be fixed in font stuff... textsize = (textsize[0] + 50, textsize[1] + 50) offset = 0 if self.type == self.TYPE_YESNO: offset = 60 wsizex = textsize[0] + 60 wsizey = textsize[1] + offset if (280 &gt; wsizex): wsizex = 280 wsize = (wsizex, wsizey) # resize self.instance.resize(eSize(*wsize)) # resize label self[&quot;text&quot;].instance.resize(eSize(*textsize)) # move list listsize = (wsizex, 50) self[&quot;list&quot;].instance.move(ePoint(0, textsize[1])) self[&quot;list&quot;].instance.resize(eSize(*listsize)) # center window newwidth = wsize[0] newheight = wsize[1] self.instance.move(ePoint(orgpos.x() + (orgwidth - newwidth)/2, orgpos.y() + (orgheight - newheight)/2)) </applet> </screen> """ dmconfigfile = resolveFilename(SCOPE_PLUGINS, "SystemPlugins/DeviceManager/devicemanager.cfg") class DeviceManagerConfig(): def __init__(self): self.configList = [] def getConfigList(self): return self.configList def updateConfigList(self): try: self.configList = [] file = open("/proc/mounts") mounts = file.readlines() file.close() for x in mounts: if x.startswith("/dev/sd"): device = x.split()[0].split('/dev/')[1] mountpoint = x.split()[1] if mountpoint.startswith('/autofs'): continue (uuid, partitionType) = deviceinfo.getPartitionBlkidInfo(device) if uuid != '' and mountpoint != '': self.configList.append([uuid, mountpoint]) self.saveConfig() except: print "updateConfigList failed!" def loadConfig(self): if not fileExists(dmconfigfile): os.system("touch %s" % dmconfigfile) self.configList = [] data = file(dmconfigfile).read().split('\n') for line in data: if line.find(':') != -1: (uuid, mountpoint) = line.split(':') if uuid != '' and mountpoint != '': self.configList.append([uuid, mountpoint]) def saveConfig(self): confFile = open(dmconfigfile,'w') data = "" for line in self.configList: data += "%s:%s\n"%(line[0],line[1]) # uuid, mountpoint confFile.write(data) confFile.close() def appendConfig(self, uuid, mountpoint): for x in self.configList: if x[0] == uuid or x[1] == mountpoint: self.configList.remove(x) self.configList.append([uuid, mountpoint]) def removeConfig(self, value): for x in self.configList: if x[0] == value or x[1] == value: self.configList.remove(x) devicemanagerconfig = DeviceManagerConfig() class deviceManagerHotplug: def __init__(self): self.hotplugActive = True def setHotplugActive(self,value=True): if value: self.hotplugActive = True else: self.hotplugActive = False def printDebug(self): for p in harddiskmanager.partitions: print " # partition : %s %s %s %s %s(mp, des, f_mounted, is_hot, dev)"%(p.mountpoint, p.description, p.force_mounted, p.is_hotplug,p.device) def doMount(self, uuid, devpath, mountpoint, filesystem): # check current device mounted on another mountpoint. mp_list = [] mp_list = deviceinfo.checkMountDev(devpath) for mp in mp_list: if mp != mountpoint and path.ismount(mp): deviceinfo.umountByMountpoint(mp) # check another device mounted on configmountpoint devpath_list = [] devpath_list = deviceinfo.checkMountPoint(mountpoint) for devpath_ in devpath_list: if devpath_ != devpath: print "[DeviceManager] Mount Failed. (Another device is already mounted)" return # do mount # print "[DeviceManager] doMount" if not path.exists(mountpoint): os.system("mkdir %s"%mountpoint) if path.exists(mountpoint): if not path.ismount(mountpoint): if filesystem == "ntfs": cmd = "ntfs-3g %s %s"%(devpath, mountpoint) elif filesystem is None: cmd = "mount %s %s"%(devpath, mountpoint) else: cmd = "mount -t %s %s %s"%(filesystem, devpath, mountpoint) print "[DeviceManager] cmd : %s"%cmd os.system(cmd) if not deviceinfo.isMounted(devpath, mountpoint): print "[DeviceManager] %s doMount failed!"%devpath return else: # Update partition Info, add self.addPartitionAutofsMountpoint(devpath, mountpoint) def doUmount(self, device, mountpoint): devpath = "/dev/"+device mountpoints = deviceinfo.checkMountDev(devpath) if len(mountpoints) == 0: return for mp in mountpoints: cmd = "umount %s"%devpath print "[DeviceManager] cmd : %s"%cmd os.system(cmd) def addHotPlugDevice(self, partition): device = partition.device devpath = "/dev/"+device # get BlkidInfo (uuid, filesystem) = deviceinfo.getPartitionBlkidInfo(device) if uuid == "": # retry.. os.system("sleep 1") (uuid, filesystem) = deviceinfo.getPartitionBlkidInfo(device) if uuid == "": print "[DeviceManagerHotplug] getBlkidInfo failed!" return # get configList devicemanagerconfig.loadConfig() configList = devicemanagerconfig.getConfigList() mountpoint = None for line in configList: if uuid == line[0].strip(): mountpoint = line[1].strip() break if mountpoint is None: return # do mount if deviceinfo.isMounted(devpath, mountpoint): pass # print "[DeviceManagerHotplug] already mounted" else: self.doMount(uuid, devpath, mountpoint, filesystem) def removeHotplugDevice(self, partition): self.doUmount(partition.device, partition.mountpoint) def getHotplugAction(self, action, partition): if not self.hotplugActive or not config.plugins.devicemanager.hotplug_enable.value: return if partition.device is None or not partition.device.startswith("sd"): return print "[DeviceManagerHotplug] action : %s, device : %s"%(action, partition.device) if action == 'add': self.addHotPlugDevice(partition) elif action == 'remove': self.removeHotplugDevice(partition) def addPartitionAutofsMountpoint(self, devpath, mountpoint): device = path.basename(devpath) autofsMountpoint = harddiskmanager.getAutofsMountpoint(device) # check already appended to partition list for x in harddiskmanager.partitions: if x.mountpoint == autofsMountpoint or x.mountpoint == mountpoint: return # from Components.Harddisk import Partition physdev = path.realpath('/sys/block/' + device[:3] + '/device')[4:] description = harddiskmanager.getUserfriendlyDeviceName(device, physdev) p = Partition(mountpoint = autofsMountpoint, description = description, force_mounted = True, device = device) harddiskmanager.partitions.append(p) harddiskmanager.on_partition_list_change("add", p) def autoMountOnStartup(self): devicemanagerconfig.loadConfig() configList = devicemanagerconfig.getConfigList() # get blkid info blkiddata = [] data = os.popen("blkid -c /dev/NULL /dev/sd*").readlines() for line in data: devpath = uuid = filesystem = "" devpath = line.split(':')[0] if line.find(" UUID=") != -1: uuid = line.split(" UUID=")[1].split(' ')[0] if line.find(" TYPE=") != -1: filesystem = line.split(" TYPE=")[1].split(' ')[0].strip('"') blkiddata.append((devpath, uuid, filesystem)) # check configList for c in configList: uuid_cfg = c[0].strip() mountpoint_cfg = c[1].strip() for (devpath, uuid, filesystem) in blkiddata: if uuid_cfg == uuid: # do mount if deviceinfo.isMounted(devpath, mountpoint_cfg): # print "[Devicemanager startup] already mounted" self.addPartitionAutofsMountpoint(devpath, mountpoint_cfg) else: # print "[autoMountOnStartup] do mount(%s %s %s)"%(devpath, configmountpoint, filesystem) self.doMount(uuid, devpath, mountpoint_cfg, filesystem) def umountOnShutdown(self): devicemanagerconfig.loadConfig() configList = devicemanagerconfig.getConfigList() # get mount info mounts = [] data = file('/proc/mounts').read().split('\n') for x in data: if not x.startswith('/dev/sd'): continue devpath, mountpoint = x.split()[:2] mounts.append((path.basename(devpath), mountpoint)) # get blkid info data = self.getBlkidInfo() # check configList for c in configList: uuid_cfg = c[0].strip() mountpoint_cfg = c[1].strip() device_cfg = None if uuid_cfg in data.keys(): device_cfg = data[uuid_cfg] if device_cfg is None: continue for (device, mountpoint) in mounts: if device_cfg == device: if not deviceinfo.isFstabAutoMounted(uuid_cfg, "/dev/"+device_cfg, mountpoint_cfg): self.doUmount(device, mountpoint) def getBlkidInfo(self): data = {} blkid_data = os.popen("blkid -c /dev/NULL /dev/sd*").read() for line in blkid_data.split('\n'): # print "[DeviceManager] getBlkidInfo line : ",line device = uuid = "" device = path.basename(line.split(':')[0]) if line.find(" UUID=") != -1: blkid_uuid = line.split(" UUID=")[1].split(' ')[0] data[blkid_uuid] = device return data devicemanagerhotplug = deviceManagerHotplug() def DeviceManagerhotplugDeviceStart(action, device): devicemanagerhotplug.getHotplugAction(action, device) def callBackforDeviceManager(session, callback_result = False): if callback_result == True: session.open(DeviceManager) def checkMounts(session): try: noMountable_dev = "" for blockdev in listdir("/sys/block"): devpath = "/sys/block/" + blockdev dev = int(readFile(devpath + "/dev").split(':')[0]) if dev in (7, 31) or blockdev[0:2] != 'sd': # 7: loop, 31 : mtdblock continue partitions = [] noMountable_partitions = [] for partition in listdir(devpath): if not partition.startswith(blockdev): continue partitions.append(partition) if os.access('/autofs/'+partition,0) is False: noMountable_partitions.append(partition) if len(partitions) == 0 or len(noMountable_partitions) != 0: if noMountable_dev != "": noMountable_dev += ' ' noMountable_dev += blockdev if noMountable_dev != "": print "Umountable partitions found." InfoText = _("No mountable devices found.! (%s)\nDo you want to open DeviceManager and do initialize or format this device?\n\n(Open 'Menu->Setup->System -> Harddisk -> DeviceManager'\n and press MENU button to deactivate this check.)")%noMountable_dev AddNotificationWithCallback( boundFunction(callBackforDeviceManager, session), MessageBox, InfoText, timeout = 60, default = False ) except: print "checkMounts failed!" def sessionstart(reason, **kwargs): if reason == 0: if kwargs.has_key("session") and config.plugins.devicemanager.mountcheck_enable.value == True: session = kwargs["session"] checkMounts(session) if config.plugins.devicemanager.hotplug_enable.value: harddiskmanager.on_partition_list_change.append(DeviceManagerhotplugDeviceStart) elif reason == 1: if config.plugins.devicemanager.hotplug_enable.value: harddiskmanager.on_partition_list_change.remove(DeviceManagerhotplugDeviceStart) def autostart(reason, **kwargs): if reason == 0: try: # check at first enigma2 start if not fileExists(dmconfigfile): print "[DeviceManager] autostart : check devices at first start" sda_isremovable = False sda_UUID = "" os.system("touch %s"%dmconfigfile) # check sda sda_data = popen("cat /proc/partitions | grep sda1").read() if sda_data != '': sda_UUID = popen("blkid -o value -s UUID /dev/sda1").read().strip('\n') sda_isremovable = bool(int(readFile("/sys/block/sda/removable"))) print "sda : %s, %s"%(sda_UUID, sda_isremovable) cfg = "" if sda_data != '': cfg += '"%s":/media/hdd\n'%sda_UUID confFile = open(dmconfigfile,'w') confFile.write(cfg) confFile.close() if not path.exists("/media/hdd"): os.system("mkdir -p /media/hdd") # auto mount devicemanagerhotplug.autoMountOnStartup() except: print "[DeviceManager] autostart failed!" elif reason == 1: devicemanagerhotplug.umountOnShutdown() def menu(menuid, **kwargs): if menuid == "system": return [(_("DeviceManager"), main, "device_manager", 50)] return [] def main(session, **kwargs): session.open(DeviceManager) def Plugins(path, **kwargs): return [ PluginDescriptor(name = _("DeviceManager"), description = _("manage block devices of your VU+"), where = PluginDescriptor.WHERE_MENU,fnc=menu), PluginDescriptor(where = PluginDescriptor.WHERE_SESSIONSTART, needsRestart = True, fnc = sessionstart), PluginDescriptor(where = PluginDescriptor.WHERE_AUTOSTART, needsRestart = True, fnc = autostart) ] class MessageBox_2(MessageBox): def __init__(self, session, text, type = MessageBox.TYPE_YESNO, timeout = -1, close_on_any_key = False, default = True, enable_input = True, msgBoxID = None): MessageBox.__init__(self, session, text, type, timeout, close_on_any_key, default, enable_input, msgBoxID) self.skinName = "MessageBox" self.closeTimer = eTimer() self.closeTimer.callback.append(self.msg_close) self.devicemanager_ret = False self.devicemanager_msg = "" def msg_close(self): self.close(self.devicemanager_ret, self.devicemanager_msg) def run_close(self, ret, msg=""): self.devicemanager_ret = ret self.devicemanager_msg = msg self.closeTimer.start(100,True) def createSummary(self): return MessageBox_2_Summary class MessageBox_2_Summary(Screen): skin=""" <screen name="MessageBox_2_Summary" position="0,0" size="256,64" id="1"> <widget source="parent.Text" render="Label" position="0,0" size="256,64" font="Regular;13" halign="center" valign="center" /> </screen> """
Later this spring/summer, All Saints plans to add an additional parking lot north of our existing buildings, along Terravista Drive. While long-term this will serve as a parking area, the lot will serve a different purpose in the interim: as the foundation for an additional temporary building and for a basketball court. A large event-style tent will be installed, becoming the second largest venue on our campus (after the Interim Sanctuary). The tent will help to alleviate some of our immediate needs for additional meeting space for youth on Sundays and adults throughout the week. Since moving into our campus almost three years ago, All Saints has been blessed with growth in many different areas – more members, more children, more youth. In order to continue ministering well to those the Lord has brought and continues to bring to us, we need a little more room. At 35% larger than our largest classroom, the tent will help to accommodate our growing Youth Group. In addition, it will provide much needed meeting space for group gatherings and special events. Our current sanctuary is an interim space. A larger permanent sanctuary remains in the plans for a Phase II building project which also includes a few additional classrooms. However, the process of fundraising, permitting, and construction for that facility will take several years. The Phase II plan has always included plans for additional parking – it's this element of the master plan that has been accelerated on the timeline in order to accommodate additional facility space, both indoors and outdoors. The temporary tent structure will be anchored into what will eventually serve as parking for All Saints' future sanctuary. The total cost of this project is about $300,000. While it is a temporary solution, the tent project will bridge the gap between our current ministry needs and the completion of our Phase II building project, whenever that might be. We expect the tent to be in place for at least 3 years, so it will installed with the care and permanence it requires. If you feel called to give above and beyond your normal contribution to help with this cost, please mark "Tent" in the notes/memo line of your contribution.
from collections import namedtuple from . import raid from .. import errors from .. import util from ..size import Size lsm = None _HBA_PLUGIN_URIS = ("hpsa://", "megaraid://") LSMInfo = namedtuple('HBAVolumeInfo', ['system', 'nodes', 'raid_type', 'raid_stripe_size', 'raid_disk_count']) """ .. class:: LSMInfo .. attribute:: system (str): descriptive name of HBA unit .. attribute:: nodes (list[str]): list of device node paths for the volume .. attribute:: raid_type (:class:`~.devicelibs.raid.RAIDLevel` or None): RAID level .. attribute:: raid_stripe_size (:class:`~.size.Size` or None): stripe size .. attribute:: raid_disk_count (int or None): number of disks in the RAID set """ volumes = dict() _raid_levels = dict() class _LSMRAIDLevelStub(raid.RAIDLevel): def __init__(self, name): self._name = name @property def name(self): return self._name @property def names(self): return [self.name] @property def min_members(self): return 0 def has_redundancy(self): return False def is_uniform(self): return False class _LSMDependencyGuard(util.DependencyGuard): error_msg = "libstoragemgmt functionality not available" def _check_avail(self): global lsm if lsm is None: # pylint: disable=used-before-assignment try: import lsm # pylint: disable=redefined-outer-name except ImportError: lsm = None return lsm is not None _lsm_required = _LSMDependencyGuard() def _update_lsm_raid_levels(): """ Build a mapping of lsm.RAID_TYPE->blivet.devicelibs.raid.RAIDLevel """ global _raid_levels _raid_levels = dict() lsm_raid_levels = dict((k, v) for (k, v) in lsm.Volume.__dict__.items() if k.startswith("RAID_TYPE_")) for constant_name, value in lsm_raid_levels.items(): name = constant_name[len("RAID_TYPE_"):] try: level = raid.get_raid_level(name) except errors.RaidError: level = _LSMRAIDLevelStub(name) _raid_levels[value] = level def _get_lsm_raid_level(lsm_raid_type): """ Return a blivet.devicelibs.raid.RAIDLevel corresponding the lsm-reported RAID level.""" return _raid_levels.get(lsm_raid_type, _raid_levels.get(lsm.Volume.RAID_TYPE_UNKNOWN)) @_lsm_required(critical=False, eval_mode=util.EvalMode.always) def update_volume_info(): """ Build a dict of namedtuples containing basic HBA RAID info w/ device path keys. """ global volumes volumes = dict() _update_lsm_raid_levels() for uri in _HBA_PLUGIN_URIS: try: client = lsm.Client(uri) except lsm.LsmError: continue systems = dict((s.id, s) for s in client.systems()) for vol in client.volumes(): nodes = lsm.LocalDisk.vpd83_search(vol.vpd83) system = systems[vol.system_id] caps = client.capabilities(system) raid_level = None stripe_size = None disk_count = None if caps.supported(lsm.Capabilities.VOLUME_RAID_INFO): raid_info = client.volume_raid_info(vol)[:3] raid_level = _get_lsm_raid_level(raid_info[0]) stripe_size = Size(raid_info[1]) disk_count = raid_info[2] info = LSMInfo(system.name, nodes, raid_level, stripe_size, disk_count) volumes.update([(node, info) for node in nodes])
Based at our St James’ Park office, the Head of Events has responsibility for oversight and delivery of Prospects’ events programme. This is a cross-departmental role supporting the delivery of events for both the publishing and editorial teams. • Ability to work as an individual contributor, take initiative and problem-solve. • Ability to recognise potential conflicts and acknowledge where guidance is required / necessary. • Ability to make recommendations and drive actions under own initiative, taking the lead in prioritising multiple requirements. • Ability to work autonomously, with minimal supervision. • Excellent ability to quickly build strong relationships with colleagues and stakeholders. The role also includes a commission and bonus scheme. Interviews to begin immediately and the role may be filled before the closing date. Please email CV's to [email protected]. All applications will be responded to and successful one's will be invited to interview. Please also include a covering letter detailing why you would like the role and what relevant experience you have.
from copy import deepcopy d1 = [] d2 = [] player_2 = False with open('in', 'r') as f: f.readline() for line in f.readlines(): try: i = int(line.strip()) if player_2: d2.append(i) else: d1.append(i) except Exception: player_2 = True seen = set() next_game_id = 1 last_deck_1 = None last_deck_2 = None def game(deck1, deck2, game_id=0): global next_game_id, last_deck_1, last_deck_2 while len(deck1) > 0 and len(deck2) > 0: h = (str(game_id), str(deck1), str(deck2)) if h in seen: return 1 seen.add(h) card1, deck1 = deck1[0], deck1[1:] card2, deck2 = deck2[0], deck2[1:] if len(deck1) >= card1 and len(deck2) >= card2: next_game_id += 1 player_1_wins = game(deepcopy(deck1[:card1]), deepcopy(deck2[:card2]), game_id=next_game_id - 1) == 1 else: player_1_wins = card1 > card2 if player_1_wins: deck1 = deepcopy(deck1) + [card1, card2] else: deck2 = deepcopy(deck2) + [card2, card1] last_deck_1 = deck1 last_deck_2 = deck2 return 1 if len(deck2) == 0 else 2 game(deepcopy(d1), deepcopy(d2)) res = 0 d = last_deck_1 if len(last_deck_2) == 0 else last_deck_2 d = list(reversed(d)) for i in range(1, len(d) + 1): res += i * d[i - 1] print(res)
Wausaukee-Christmas in the Park at Wausaukee still has spaces available for businesses and groups to build a display at Evergreen Park (in the lower park). Sites will be assigned and have electricity. Entry fee is $20 and proceeds go to the Wausaukee Student Snack Fund for children in need at the Wausaukee School. Displays are open now through Jan. 5.
import os import socket import struct import logging import sys from threading import Lock # maximum z that's possible within a 64-bit unsigned # number, which is what we transmit across the network MAX_Z = 35 # size of a metatile METATILE = 8 log = logging.getLogger(__name__) class ZLevels(): """Stores sizes, in number of metatiles, at each zoom level. This allows metatiles to be looked up in a single file or linear array without the need for multiple files which would complicate syncing to disk. """ def __init__(self): z_sizes = map(lambda z: 4**max(0,z-3), range(0,MAX_Z)) self.offsets = reduce(lambda s,i: s + [s[-1] + i], z_sizes, [0]) def size_of(self, max_z): bit_size = self.offsets[max_z + 1] return bit_size / 8 + (1 if bit_size % 8 > 0 else 0) def tile_to_meta_idx(self, x, y, z): morton_code = (self._interleave(x) << 1) | self._interleave(y) return self.offsets[z] + morton_code def _interleave(self, n): """Bit interleaving function, i.e: turns 11011 into 1010001010 and is used to create Morton codes. This extended version is able to handle up to 2^32-1. """ n&= 0xffffffff n = (n | (n << 16)) & 0x0000FFFF0000FFFF n = (n | (n << 8)) & 0x00FF00FF00FF00FF n = (n | (n << 4)) & 0x0F0F0F0F0F0F0F0F n = (n | (n << 2)) & 0x3333333333333333 n = (n | (n << 1)) & 0x5555555555555555 return n def _uninterleave(self, n): """Inverse of bit interleaving function, able to handle 64-bit numbers allowing outputs to be up to 2^32-1 in size.""" n&= 0x5555555555555555 n = (n ^ (n >> 1)) & 0x3333333333333333 n = (n ^ (n >> 2)) & 0x0f0f0f0f0f0f0f0f n = (n ^ (n >> 4)) & 0x00ff00ff00ff00ff n = (n ^ (n >> 8)) & 0x0000ffff0000ffff n = (n ^ (n >> 16)) & 0xffffffff return n class mqExpiryInfo: """Client class for expiry information. Contacts a server over UDP to get metatile expiry information. """ def __init__(self, host, port): # set up the socket for the first time self.sock = None self._socket_init() family, socktype, proto, canonname, sockaddr = socket.getaddrinfo(host, port, socket.AF_INET)[0] self.sockaddr = sockaddr # offsets structure for turning metatile locations into # raw 64-bit integers. self.zlevels = ZLevels() # a lock, so we can ensure thread-local access to the # socket. self.mutex = Lock() def _socket_init(self): """Initialise (or re-initialise) the socket. Note that unless you're in the constructor, you'll need to be holding the mutex when you call this method. """ # shutdown the socket if it already exists if self.sock is not None: log.info("Re-opening socket. Old socket is %s [%s]" % (str(self.sock), str(self.sock.fileno()))) try: self.sock.shutdown(socket.SHUT_RDWR) except: # this fails if the socket isn't considered connected, which # is annoying but perhaps ignorable? pass try: self.sock.close() except: # this may also throw an error if the close fails. but we're # going to open a new socket anyway, so maybe ignorable? pass # get rid of reference to old socket, will be garbage collected. self.sock = None self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) log.info("Opening socket. Socket is %s [%s]" % (str(self.sock), str(self.sock.fileno()))) # set up so that sockets timeout after 0.2s - should # be enough on localhost to receive a reply. self.sock.settimeout(0.2) def get_tile(self, x, y, z, style): """Gets information about expiry from the server. Returns true if the metatile is expired, false otherwise and None if an error occurred.""" idx = self.zlevels.tile_to_meta_idx(x / METATILE, y / METATILE, z) rep = self._get_bit(idx, str(style)) if (rep == 'ERR') or (rep is None): return None else: bit = struct.unpack('@B', rep)[0] return bit != 0 def set_tile(self, x, y, z, style, val): """Sends information about the expiry to the server. Returns true if the request succeeded and false otherwise. """ idx = self.zlevels.tile_to_meta_idx(x / METATILE, y / METATILE, z) bit = 0 if val == True: bit = 1 ret = self._set_bit(idx, bit, str(style)) return ret == 'OK' def _basic_req(self, msg): reply = None with self.mutex: try: self.sock.sendto(msg, self.sockaddr) reply = self.sock.recv(4096) except: # if this times out, return none so that other code # can handle the error via fall-backs. reset the socket # so that no odd trailing packets will be received and # misinterpreted. self._socket_init() log.error("Error talking to expiry info server: %s" % str(sys.exc_info())) reply = None return reply def _get_bit(self, idx, style): return self._basic_req(struct.pack('!Qbc255p', idx, 0, 'G', style)) def _set_bit(self, idx, bit, style): return self._basic_req(struct.pack('!Qbc255p', idx, bit, 'S', style))
Printed t-shirts are known to be in great demand these days as there is a huge sort of fashion parade going around it. It needs to be understood that a good T shirt printing Singapore services would be able to bring out the best kind of outcome overall, thereby enabling you to get the perfect t-shirts at the best possible rate. Printed t-shirts are highly fashionable and are preferred by corporate companies. They need to turn out to be of fine quality to get attention and appreciation. Stand out with your cool and unique t-shirt design and make a mark with it absolutely.
import ast import os from .lexer import lexers from .parser import parsers from .utils.astpp import dump as ast_dump from .utils.parser import ParserState, build_call, build_str_join AST_DEBUG = os.environ.get('RATTLE_AST_DEBUG', False) SHOW_CODE = os.environ.get('RATTLE_SHOW_CODE', False) class TemplateSyntaxError(Exception): pass class SafeData(str): """ A wrapper for str to indicate it doesn't need escaping. """ pass def escape(text): """ Returns the given text with ampersands, quotes and angle brackets encoded for use in HTML. """ if isinstance(text, SafeData): return text if not isinstance(text, str): text = str(text) return SafeData( text.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;') .replace('"', '&quot;').replace("'", '&#39;') ) def auto_escape(s): if isinstance(s, SafeData): return s return escape(s) class Library(object): def __init__(self): self._filters = {} self._tags = {} self._ambiguous_filters = set() self._ambiguous_tags = set() @property def filters(self): return self._filters @property def tags(self): return self._tags def register_filter(self, func): name = func.__name__ full_name = '%s.%s' % (func.__module__, func.__name__) if name not in self._filters: if name not in self._ambiguous_filters: self._filters[func.__name__] = func elif full_name not in self._filters: self._ambiguous_filters.add(name) del self._filters[name] self._filters[full_name] = func # Allows use as decorator return func def unregister_filter(self, full_name): self._filters.pop(full_name, None) _, _, short_name = full_name.rpartition('.') self._filters.pop(short_name, None) def register_tag(self, func): name = func.__name__ full_name = '%s.%s' % (func.__module__, func.__name__) if name not in self._tags: if name not in self._ambiguous_tags: self._tags[func.__name__] = func elif full_name not in self._tags: self._ambiguous_tags.add(name) del self._tags[name] self._tags[full_name] = func # Allows use as decorator return func def unregister_tag(self, full_name): self._tags.pop(full_name, None) _, _, short_name = full_name.rpartition('.') self._tags.pop(short_name, None) library = Library() class Template(object): def __init__(self, source, origin=None): self.source = source self.origin = origin # A list of compiled tags self.compiled_tags = [] code = self.parse() ast.fix_missing_locations(code) if AST_DEBUG: print(ast_dump(code)) if SHOW_CODE: try: import codegen print(codegen.to_source(code)) except ImportError: pass self.func = compile(code, filename="<template>", mode="exec") self.default_context = { 'True': True, 'False': False, 'None': None, } def parse(self): """ Convert the parsed tokens into a list of expressions then join them """ tokens = lexers.sl.lex(self.source) state = ParserState() klass = parsers.sp.parse(tokens, state) body = [ klass, ast.Global(names=['rendered']), ast.Assign( targets=[ast.Name(id='rendered', ctx=ast.Store())], value=build_str_join( build_call( ast.Attribute( value=build_call( ast.Name(id='Template', ctx=ast.Load()) ), attr='root', ctx=ast.Load() ), args=[ ast.Name(id='context', ctx=ast.Load()) ], ) ) ) ] return ast.Module( body=body ) def render(self, context={}): ctx = context.copy() ctx.update(self.default_context) global_ctx = { 'context': ctx, 'compiled_tags': self.compiled_tags, 'filters': library.filters, 'auto_escape': auto_escape, 'output': [], 'rendered': None } local_ctx = { } eval(self.func, global_ctx, local_ctx) return global_ctx['rendered']
It’s still months away, but amidst all the agitation on banking markets and anarchy in the all-around economy, you can’t advice but attending advanced to this year’s Oktoberfest. Incrementum’s ninth anniversary In Gold We Trust address analyzes gold primarily as a budgetary asset and not as a article like say hops or barley. The Liechtenstein-based asset managers achieve that “the aggressive position of gold about to cardboard money and added asset classes has bigger appreciably in contempo months” and accept 140 pages of archive and tables to prove it. “Many comparisons from accustomed activity appearance that gold is currently not admired at an badly aerial level. While a “Mass” beer (one liter) at the Munich Oktoberfest in 1950 still amount a adapted EUR 0.82, the amount in 2014 stood amid EUR 9.70 – EUR 10.10 (average EUR 9,90). “Thus, the anniversary amount aggrandizement of beer amounts to 4.2% per year back 1950.37 If one measures the beer amount in gold terms, afresh one accustomed 97 liters of beer per ounce of gold in 2014.
# coding: utf8 # 尝试 import datetime now=datetime.date.today() year=now.year month=now.month if int(month) in range(2,8): xueqi=2 xuenian=str(int(year)-1-2000) else: xueqi=1 xuenian=str(int(year)-2000) @auth.requires(request.client=='127.0.0.1' or auth.has_membership(role='teacher') , requires_login=False) def index(): return dict() @auth.requires(request.client=='127.0.0.1' or auth.has_membership(role='teacher') , requires_login=False) def student_manage(): form = SQLFORM.grid(db.auth_user) return dict(form=form) @auth.requires(request.client=='127.0.0.1' or auth.has_membership(role='teacher') , requires_login=False) def course_manage(): form = SQLFORM.smartgrid(db.course) return dict(form=form) @auth.requires(request.client=='127.0.0.1' or auth.has_membership(role='teacher') , requires_login=False) def keshi_manage(): form = SQLFORM.smartgrid(db.keshi, constraints={'keshi':(db.keshi.xuenian==xuenian)&(db.keshi.xueqi==xueqi)}, links=[dict(header='',body=lambda row:A('批改作业',_href=URL('pigai',args=row.id))), dict(header='',body=lambda row:A('添加练习',_href=URL('addwenti',args=row.id)))]) return dict(form=form) @auth.requires(request.client=='127.0.0.1' or auth.has_membership(role='teacher') , requires_login=False) def timu_manage(): form = SQLFORM.smartgrid(db.timu) return dict(form=form) @auth.requires(request.client=='127.0.0.1' or auth.has_membership(role='teacher') , requires_login=False) def lianxi_manage(): form = SQLFORM.smartgrid(db.lianxi) return dict(form=form) @auth.requires(request.client=='127.0.0.1' or auth.has_membership(role='teacher') , requires_login=False) def zuoti_manage(): form = SQLFORM.smartgrid(db.zuoti) return dict(form=form) @auth.requires(request.client=='127.0.0.1' or auth.has_membership(role='teacher') , requires_login=False) def zuoye_manage(): form = SQLFORM.smartgrid(db.zuoye) return dict(form=form) @auth.requires(request.client=='127.0.0.1' or auth.has_membership(role='teacher') , requires_login=False) def defen_manage(): form = SQLFORM.smartgrid(db.defen) return dict(form=form) @auth.requires(request.client=='127.0.0.1' or auth.has_membership(role='teacher') , requires_login=False) def wangpan_manage(): form = SQLFORM.smartgrid(db.wangpan) return dict(form=form) @auth.requires(request.client=='127.0.0.1' or auth.has_membership(role='teacher') , requires_login=False) def pigai(): keshi_id=request.args[0] row=db((db.zuoye.keshi==keshi_id)&(db.zuoye.defen==None)).select().first() if row: form=SQLFORM(db.zuoye,row.id,upload=URL('download')) vals=None if form.process().accepted: vals=response.url redirect(request.url) return dict(form=form,vals=vals) else: return dict(error=H3('没有可以批改的作业')) @auth.requires(request.client=='127.0.0.1' or auth.has_membership(role='teacher') , requires_login=False) def grade2(): lastxs=db().select(db.zuoye.zuozhe).last().zuozhe banji=db.auth_user[lastxs].banji if len(request.args): banji=request.args[0] rows=db((db.keshi.xuenian==xuenian)&(db.keshi.xueqi==xueqi)&(db.keshi.nianji==2)).select(left=db.keshi.on(db.keshi.kecheng==db.course.id)) return dict(rows=rows,banji=banji) @auth.requires(request.client=='127.0.0.1' or auth.has_membership(role='teacher') , requires_login=False) def grade1(): lastxs=db().select(db.zuoye.zuozhe).last().zuozhe banji=db.auth_user[lastxs].banji if len(request.args): banji=request.args[0] rows=db((db.keshi.xuenian==xuenian)&(db.keshi.xueqi==xueqi)&(db.keshi.nianji==1)).select(left=db.keshi.on(db.keshi.kecheng==db.course.id)) return dict(rows=rows,banji=banji) def homeworks2(): keshi_id=request.args[0] if month in range(2,8): jie2=int(year)+1-2000 else: jie2=int(year)+2-2000 banji=request.args[1] rows=db((db.auth_user.banji==banji)& (db.auth_user.jie==jie2)).select( db.auth_user.last_name, db.auth_user.first_name, db.zuoye.ALL,left=db.zuoye.on((db.auth_user.id==db.zuoye.zuozhe)&(db.zuoye.keshi==keshi_id)), orderby=db.auth_user.last_name) return dict(rows=rows,banji=banji) def homeworks1(): keshi_id=request.args[0] if month in range(2,8): jie1=int(year)+2-2000 else: jie1=int(year)+3-2000 banji=request.args[1] rows=db((db.auth_user.banji==banji)& (db.auth_user.jie==jie1)).select( db.auth_user.last_name, db.auth_user.first_name, db.zuoye.ALL,left=db.zuoye.on((db.auth_user.id==db.zuoye.zuozhe)&(db.zuoye.keshi==keshi_id)), orderby=db.auth_user.last_name) return dict(rows=rows,banji=banji) def addwenti(): keshi_id=request.args[0] keshi=db.keshi[keshi_id] course=keshi.kecheng timus=db(db.timu.course==course).select() for timu in timus: db.lianxi.update_or_insert( (db.lianxi.keshi==keshi_id)& (db.lianxi.timu==timu), keshi=keshi_id, timu=timu ) lianxis=db(db.lianxi.keshi==keshi_id).select() return dict(timus=timus,lianxis=lianxis) ''' grade1,grade2,连接每个课程学习模块,学习模块里面有练习讲解,作业情况统计(交作业统计,得分统计) 用ajax实现统计和讲解部分显示答案 ''' def download(): """ allows downloading of uploaded files http://..../[app]/default/download/[filename] """ return response.download(request, db)
Join us for our Valentine Party. If you would be willing to make a pot of soup, please see Nancy McDonald. Our Older, Wiser, Loving Seniors (ages 55 and over) meet bi-monthly on the 2nd Thursday of the month at 7:00 PM for singing, warm fellowship and special speakers. We also enjoy day trips to interesting locations throughout the area, as the weather permits.
import logging logging.basicConfig() from math import floor, sqrt import os import sys import collections import itertools import random # For profiling: import sys; sys.path.insert(0, '../bacon') import bacon import tiled import spriter import moon from common import Rect, tween, update_tweens GAME_WIDTH = 800 GAME_HEIGHT = 500 # See Game.on_key for cheats ENABLE_CHEATS = False try: if sys.frozen: ENABLE_CHEATS = False except AttributeError: pass bacon.window.title = 'Monthly Visitor' bacon.window.width = GAME_WIDTH bacon.window.height = GAME_HEIGHT bacon.window.resizable = False bacon.window.content_scale = 1.0 font_ui = bacon.Font(None, 16) image_cache = {} def load_image(name): if isinstance(name, bacon.Image): return name try: return image_cache[name] except KeyError: image = image_cache[name] = bacon.Image('res/' + name) return image sound_monster = bacon.Sound('res/sound/monster.ogg') sound_roar = bacon.Sound('res/sound/roar.ogg') sound_agony1 = bacon.Sound('res/sound/agony1.ogg') sound_agony2 = bacon.Sound('res/sound/agony2.ogg') sound_footsteps1 = bacon.Sound('res/sound/footsteps1.ogg') sound_footsteps2 = bacon.Sound('res/sound/footsteps2.ogg') sound_crunch1 = bacon.Sound('res/sound/crunch1.ogg') sound_pickup = bacon.Sound('res/sound/pickup.ogg') sound_drop = bacon.Sound('res/sound/drop.ogg') sound_click = bacon.Sound('res/sound/click.ogg') sound_growl1 = bacon.Sound('res/sound/growl1.ogg') sound_craft1 = bacon.Sound('res/sound/craft1.ogg') sound_eat = bacon.Sound('res/sound/eat.ogg') sound_chime = bacon.Sound('res/sound/chime.ogg') sound_dawn = bacon.Sound('res/sound/dawn.ogg') sound_scream = bacon.Sound('res/sound/scream.ogg') sound_attackfence1 = bacon.Sound('res/sound/attackfence1.ogg') sound_destroyfence1 = bacon.Sound('res/sound/destroyfence1.ogg') sound_cow = bacon.Sound('res/sound/cow.ogg') sound_chicken = bacon.Sound('res/sound/chicken.ogg') sound_sheep = bacon.Sound('res/sound/sheep.ogg') class SpriteSheet(object): def __init__(self, image, cols, rows): image = load_image(image) cell_width = int(image.width / cols) cell_height = int(image.height / rows) self.cells = [] for row in range(rows): cell_row = [] self.cells.append(cell_row) y = cell_height * row for col in range(cols): x = cell_width * col cell = image.get_region(x, y, x + cell_width, y + cell_height) cell_row.append(cell) def lpc_anims(image, cols, rows): sheet = SpriteSheet(image, cols, rows) up = sheet.cells[0] left = sheet.cells[1] down = sheet.cells[2] right = sheet.cells[3] def make_anim(images): anim = Anim([Frame(image, image.width / 2, image.height - 4) for image in images]) anim.time_per_frame = 0.1 return anim if cols > 4: return dict( idle_up = make_anim(up[:1]), walk_up = make_anim(up[1:]), idle_left = make_anim(left[:1]), walk_left = make_anim(left[1:]), idle_down = make_anim(down[:1]), walk_down = make_anim(down[1:]), idle_right = make_anim(right[:1]), walk_right = make_anim(right[1:]) ) else: return dict( idle_up = make_anim(up[:1]), walk_up = make_anim(up), idle_left = make_anim(left[:1]), walk_left = make_anim(left), idle_down = make_anim(down[:1]), walk_down = make_anim(down), idle_right = make_anim(right[:1]), walk_right = make_anim(right) ) def spritesheet_anim(image, cols, rows, pivot_x, pivot_y): sheet = SpriteSheet(image, cols, rows) images = itertools.chain(*sheet.cells) return Anim([Frame(image, pivot_x, pivot_y) for image in images]) def load_clothing_anims(name): anims = lpc_anims('Clothing-' + name + '.png', 9, 4) anims['death'] = spritesheet_anim('Clothing-' + name + '-Death.png', 6, 1, 32, 54) return anims class Frame(object): def __init__(self, image, pivot_x, pivot_y): self.image = load_image(image) self.pivot_x = pivot_x self.pivot_y = pivot_y class Anim(object): time_per_frame = 0.5 def __init__(self, frames): self.frames = frames clothing_anims = dict( Body = load_clothing_anims('Body'), BrownHat = load_clothing_anims('BrownHat'), BrownShirt = load_clothing_anims('BrownShirt'), BrownShoes = load_clothing_anims('BrownShoes'), BrownSkirt = load_clothing_anims('BrownSkirt'), ChainHood = load_clothing_anims('ChainHood'), ChainTorso = load_clothing_anims('ChainTorso'), GreenPants = load_clothing_anims('GreenPants'), HairBlonde = load_clothing_anims('HairBlonde'), Hood = load_clothing_anims('Hood'), MetalBoots = load_clothing_anims('MetalBoots'), MetalHat = load_clothing_anims('MetalHat'), MetalPants = load_clothing_anims('MetalPants'), PurpleJacket = load_clothing_anims('PurpleJacket'), WhiteShirt = load_clothing_anims('WhiteShirt'), Wolf = load_clothing_anims('Wolf'), ) default_player_clothing = ['BrownShoes', 'GreenPants', 'WhiteShirt', 'HairBlonde'] naked_player_clothing = ['HairBlonde'] chicken_anims = lpc_anims('Chicken.png', 4, 4) sheep_anims = lpc_anims('Sheep.png', 4, 4) cow_anims = lpc_anims('Cow.png', 4, 4) def distance(a, b): dx = a.x - b.x dy = a.y - b.y return sqrt(dx * dx + dy * dy) def dot(ax, ay, bx, by): return ax * bx + ay * by class Waypoint(object): index = 0 def __init__(self, x, y): self.x = x self.y = y class Sprite(object): looping = True def __init__(self, anim, x, y): self.anim = anim self.frame_index = 0 self.frame = anim.frames[0] self._time = 0 self.x = x self.y = y def __lt__(self, other): return self.y < other.y def get_time(self): return self._time def set_time(self, time): old_time = self._time self._time = time frame_index = int(time / self.anim.time_per_frame) if self.looping: self.frame_index = frame_index % len(self.anim.frames) self.frame = self.anim.frames[self.frame_index] else: if self.frame_index < len(self.anim.frames) and frame_index >= len(self.anim.frames): self.on_anim_finished() self.frame_index = min(frame_index, len(self.anim.frames) - 1) self.frame = self.anim.frames[self.frame_index] time = property(get_time, set_time) @property def rect(self): x = self.x - self.frame.pivot_x y = self.y - self.frame.pivot_y return Rect(x, y, x + self.frame.image.width, y + self.frame.image.height) def on_anim_finished(self): pass def on_collide(self, tile): pass def on_moved_tile(self): pass def can_walk(self, tile): return tile.walkable def move_with_collision(self, tilemap, dx, dy, speed): # Slice movement into tile-sized blocks for collision testing size = sqrt(dx * dx + dy * dy) if not size: return False dx /= size dy /= size size = min(size, speed * bacon.timestep) did_move = False while size > 0: inc = min(size, tilemap.tile_width / 2, tilemap.tile_height / 2) # Move along X if dx: incx = inc * dx tile = tilemap.get_tile_at(self.x + incx, self.y) if self.can_walk(tile): self.x += incx did_move = True else: if dx > 0: self.x = tile.rect.x1 - 1 elif dx < 0: self.x = tile.rect.x2 + 1 return self.on_collide(tile) # Move along Y if dy: incy = inc * dy tile = tilemap.get_tile_at(self.x, self.y + incy) if self.can_walk(tile): self.y += incy did_move = True else: if dy > 0: self.y = tile.rect.y1 - 1 elif dy < 0: self.y = tile.rect.y2 + 1 return self.on_collide(tile) size -= inc tilemap.update_sprite_position(self) new_tile = tilemap.get_tile_at(self.x, self.y) if new_tile != self.current_tile: self.current_tile = new_tile self.on_moved_tile() return did_move def draw(self): frame = self.frame x = int(self.x - frame.pivot_x) y = int(self.y - frame.pivot_y) bacon.draw_image(frame.image, x, y) # Update animation for next frame self.time += bacon.timestep class Character(Sprite): name = None running = False walk_speed = 200 run_speed = 220 facing = 'down' action = 'idle' anim_name = 'idle' cooldown = 0 is_wolf = False is_dying = False motive_food = 1.0 motive_food_trigger_wolf = 0.8 motive_food_trigger_human = 0.2 motive_food_trigger = motive_food_trigger_human max_tilemap_path_size = 500 distance_player_pickup_animal = 24 distance_wolf_villager_search = GAME_WIDTH * 1.5 distance_wolf_villager_attack = 32 target_villager = None eating_villager = False current_tile = None def __init__(self, anims, x, y, clothing=None): self._time = 0.0 self.anims = anims self.update_anim() self.set_clothing(clothing) super(Character, self).__init__(anims[self.anim_name], x, y) self.path = None self.target_item = None def set_clothing(self, clothing): if clothing: self.clothing = [clothing_anims[x] for x in clothing] else: self.clothing = None def draw(self): frame = self.frame x = int(self.x - frame.pivot_x) y = int(self.y - frame.pivot_y) bacon.draw_image(frame.image, x, y) if self.clothing: for layer in self.clothing: anim = layer[self.anim_name] frame = anim.frames[self.frame_index] bacon.draw_image(frame.image, x, y) # Update animation for next frame self.time += bacon.timestep def wait(self, time): self.cooldown = max(self.cooldown, time) def update_anim(self): old_anim_name = self.anim_name try: self.anim_name = self.action + '_' + self.facing self.anim = self.anims[self.anim_name] except KeyError: self.anim_name = self.action self.anim = self.anims[self.anim_name] if old_anim_name != self.anim_name: self.time = 0 def die(self): if self.is_dying: return sound_agony2.play() self.is_dying = True self.action = 'death' self.path = None self.looping = False self.time = 0 self.update_anim() game.menu = None def on_anim_finished(self): if self.is_dying: game.screen = GameOverScreen() def walk(self, arrived_func, hueristic_func): self.path = tilemap.get_path(tilemap.get_tile_at(self.x, self.y), arrived_func, hueristic_func, self.max_tilemap_path_size) if self.path and len(self.path) > 1 and self.path[0].rect.contains(self.x, self.y): # Remove first path component if we're already in the tile and past the center of it tx0 = self.path[0].rect.center_x ty0 = self.path[0].rect.center_y tx1 = self.path[1].rect.center_x ty1 = self.path[1].rect.center_y if dot(self.x - tx0, self.y - ty0, self.x - tx1, self.y - ty1) <= 0: del self.path[0] return self.path def walk_to_tile(self, tile): self.target_item = None return self.walk(path_arrived(tile), path_heuristic_player(tile)) def walk_to(self, x, y): tile = tilemap.get_tile_at(x, y) return self.walk_to_tile(tile) def walk_to_distant_object(self, obj): if distance(obj, self) > GAME_WIDTH * 0.5: dx = obj.x - self.x dy = obj.y - self.y m = GAME_WIDTH * 0.25 / sqrt(dx * dx + dy * dy) dx *= m dy *= m return self.walk_to(self.x + dx, self.y + dy) else: return self.walk_to(obj.x, obj.y) def walk_to_waypoint(self, target_index=None): waypoints.sort(key=lambda v:distance(v, self)) for waypoint in waypoints: if target_index is not None and waypoint.index != target_index: continue if self.walk_to_distant_object(waypoint): return True def update_player_movement(self): dx = 0 dy = 0 if bacon.Keys.up in bacon.keys: dy += -32 if bacon.Keys.down in bacon.keys: dy += 32 if bacon.Keys.left in bacon.keys: dx += -32 if bacon.Keys.right in bacon.keys: dx += 32 if dx or dy: self.update_facing(dx, dy) self.move_with_collision(tilemap, dx, dy, self.run_speed if self.running else self.walk_speed) self.path = None self.target_item = None self.action = 'walk' elif not self.path: self.action = 'idle' def update_walk_target_movement(self): if not self.path: return target_tile = self.path[0] dx = target_tile.rect.center_x - self.x dy = target_tile.rect.center_y - self.y self.update_facing(dx, dy) if self.move_with_collision(tilemap, dx, dy, self.run_speed if self.running else self.walk_speed): self.action = 'walk' else: # Didn't move, so we've arrived at this path node if self.path: del self.path[0] if not self.path: self.on_arrive(target_tile) self.update_anim() def on_collide(self, tile): if self.is_wolf: # Check for destructibles on tile for item in tile.items: if item.attackable_wolf: item.on_attack() return True if self.path: if self.path[0] == tile: # Arrived at non-walkable tile del self.path[0] if not self.path: self.on_arrive(tile) return False # Path goes through a non-walkable tile, stop walking self.path = None self.target_item = None self.action = 'idle' return False def on_moved_tile(self): if self.eating_villager: # Random chance of blood dribble if random.random() < 0.3: spawn_blood(self.x, self.y, dribble=True) def on_arrive(self, tile): self.action = 'idle' def update_facing(self, dx, dy): if abs(dy) > abs(dx * 2): if dy < 0: self.facing = 'up' elif dy > 0: self.facing = 'down' elif dx < 0: self.facing = 'left' elif dx > 0: self.facing = 'right' def add_food_motive(self, amount): self.motive_food = min(self.motive_food + amount, 1.0) def update_player_motives(self): self.motive_food = max(self.motive_food - bacon.timestep * 0.002, 0) def update_wolf_motives(self): self.motive_food = max(self.motive_food - bacon.timestep * 0.015, 0.1) # If we've reached the villager we're after if self.target_villager and distance(self, self.target_villager) < self.distance_wolf_villager_attack: # Remove villager's factories if self.target_villager.name: factories[:] = [f for f in factories if f.owner != self.target_villager.name] # Remove villager villagers.remove(self.target_villager) tilemap.remove_sprite(self.target_villager) self.target_villager = None self.eating_villager = True sound_roar.play() sound_agony1.play() # Small bite self.add_food_motive(0.1) spawn_blood(self.x, self.y) self.walk_to_waypoint() self.wait(0.8) return if self.cooldown > 0: self.cooldown -= bacon.timestep self.action = 'idle' self.update_anim() return # If we're standing on food, eat it tile = tilemap.get_tile_at(self.x, self.y) for item in tile.items: if item.food_wolf: ConsumeAction(item)() if self.motive_food < self.motive_food_trigger: if not self.path: # Search for nearby villagers villagers.sort(key=lambda v:distance(v, self)) for villager in villagers: if distance(self, villager) < self.distance_wolf_villager_search: if self.walk_to(villager.x, villager.y): self.target_villager = villager return # Search for nearby items that are food -- note that the returned path is not optimal, but # looks more organic anyway if self.walk(path_arrived_wolf_food(), path_hueristic_wolf_search()): return # Walk towards nearest villager over multiple screens for villager in villagers: if self.walk_to_distant_object(villagers[0]): self.target_villager = villager return # Couldn't path in direction of any villager, move to nearest waypoint instead waypoints.sort(key = lambda v:distance(v, self)) if self.walk_to_distant_object(waypoints[0]): return if not self.path: # Random walk dx = random.randrange(-3, 3) * 32 dy = random.randrange(-3, 3) * 32 self.wait(random.randrange(1, 2)) self.path = [tilemap.get_tile_at(self.x + dx, self.y + dy)] self.update_walk_target_movement() def get_drop_tile(self): tile = tilemap.get_tile_at(self.x, self.y) if not tile.items: return tile if self.facing == 'left': tile = tilemap.get_tile_at(self.x - 32, self.y) elif self.facing == 'right': tile = tilemap.get_tile_at(self.x + 32, self.y) elif self.facing == 'up': tile = tilemap.get_tile_at(self.x, self.y - 32) elif self.facing == 'down': tile = tilemap.get_tile_at(self.x, self.y + 32) if not tile.items: return tile candidates = [ tilemap.get_tile_at(self.x, self.y - 32), tilemap.get_tile_at(self.x, self.y + 32), tilemap.get_tile_at(self.x - 32, self.y), tilemap.get_tile_at(self.x + 32, self.y), tilemap.get_tile_at(self.x - 32, self.y - 32), tilemap.get_tile_at(self.x - 32, self.y + 32), tilemap.get_tile_at(self.x + 32, self.y - 32), tilemap.get_tile_at(self.x + 32, self.y + 32) ] random.shuffle(candidates) for candidate in candidates: if not candidate.items: return candidate return None def get_behind_tile(self): dx = dy = 0 if self.facing == 'left': dx = 32 elif self.facing == 'right': dx = -32 elif self.facing == 'up': dy = 32 else: dy = -32 return tilemap.get_tile_at(self.x + dx, self.y + dy) class Player(Character): run_speed = 320 naked = False footsteps_voice = None attack_voice = None def set_footsteps(self, sound): if self.footsteps_voice: if self.footsteps_voice._sound == sound: return self.footsteps_voice.stop() self.footsteps_voice = None if sound: self.footsteps_voice = bacon.Voice(sound, loop=True) self.footsteps_voice.play() def set_attack_sound(self, sound): if self.attack_voice and self.attack_voice.playing: return self.attack_voice = bacon.Voice(sound) self.attack_voice.play() def can_walk(self, tile): if self.naked and not tile.walkable_entrance: # Find owner of this shop, prevent entry if we didn't spawn here for villager in villagers: if villager.name == tile.entrance_owner: if not villager.spawned_in_shop: return False return tile.walkable def start_wolf(self): sound_monster.play() self.motive_food_trigger = self.motive_food_trigger_wolf self.is_wolf = True self.naked = False self.path = None self.running = True self.action = 'idle' self.update_anim() self.set_clothing(['Wolf']) for item in inventory.items[:]: if isinstance(item, Fence): item.destroy() else: inventory.drop(item, self.get_drop_tile()) def end_wolf(self): sound_dawn.play() self.motive_food_trigger = self.motive_food_trigger_human self.is_wolf = False self.path = None self.running = False self.action = 'idle' self.update_anim() self.set_clothing(naked_player_clothing) self.naked = True if self.eating_villager: self.on_arrive(tilemap.get_tile_at(self.x, self.y)) # Check if we're in a shop region, and if so disable the entrance blocker # so we can leave for villager in villagers: if villager.shop_rect and villager.shop_rect.contains(self.x, self.y): villager.spawned_in_shop = True else: villager.spawned_in_shop = False # Move villager to center of shop to talk to naked player if villager.shop_rect: villager.walk_to(villager.shop_rect.center_x, villager.shop_rect.center_y) def on_collide(self, tile): if not tile.walkable_entrance and player.naked: game.show_message('"You can\'t come in here like that, get some clothes on!"') return super(Player, self).on_collide(tile) def on_arrive(self, tile): self.action = 'idle' if self.eating_villager: spawn_blood(self.x, self.y) spawn_item_on_tile(self.get_drop_tile(), 'Bone', 'BoneRibs') spawn_item_on_tile(self.get_drop_tile(), 'Bone', 'BoneSkull') spawn_item_on_tile(self.get_drop_tile(), 'Bone', 'BoneLegs') spawn_item_on_tile(self.get_drop_tile(), 'Bone', 'Bone') sound_crunch1.play() self.eating_villager = False self.add_food_motive(1.0) self.wait(2.5) # Check if we arrived on an animal for animal in animals: if animal.can_pick_up and distance(self, animal) < self.distance_player_pickup_animal: if not self.target_item and not inventory.is_full: # Only pick up the animal if we weren't targetting anything. item = animal.item_cls(animal.item_cls.get_default_anim(), 0, 0) inventory.add_item(item) tilemap.remove_sprite(animal) animals.remove(animal) return # Normal pick_up if self.target_item: target_item = self.target_item self.target_item = None target_item.on_player_interact(tile) class Animal(Character): walk_speed = 50 run_speed = 110 can_pick_up = False run_cooldown = 0 run_cooldown_time = 1.5 # How long to run before exhaustion danger_radius = 100 snare_attract_radius = 512 snare_catch_radius = 8 sound = None sound_cooldown = -1 def can_walk(self, tile): return tile.walkable and tile.walkable_animal def update_animal_movement(self): if self.running: self.run_cooldown -= bacon.timestep self.sound_cooldown -= bacon.timestep # Check for getting snared for snare in snares: if not snare.occupied and snare.rect.contains(self.x, self.y): if self.sound: self.sound.play() snare.occupied = True self.snare = snare self.x = snare.x self.y = snare.y tilemap.update_sprite_position(self) tilemap.get_tile_at(self.x, self.y).items.append(self) animals.remove(self) self.__class__ = self.item_cls return if not self.path: if distance(self, player) < self.danger_radius and self.run_cooldown > 0: if self.sound and self.sound_cooldown < 0: self.sound.play() self.sound_cooldown = 5.0 self.running = True self.run_cooldown -= bacon.timestep dx = random.randrange(1, 5) * 32 dy = random.randrange(0, 5) * 32 if player.x > self.x: dx = -dx if player.y > self.y: dy = -dy self.path = [tilemap.get_tile_at(self.x + dx, self.y + dy)] self.wait(random.randrange(1, 4) / 4.0) else: if self.running: self.running = False self.wait(2) return if self.cooldown > 0: self.cooldown -= bacon.timestep return # Reset exhaustion self.run_cooldown = self.run_cooldown_time # Check for nearby snares and walk towards for snare in snares: if not snare.occupied and distance(snare, self) < self.snare_attract_radius: self.running = False self.path = [tilemap.get_tile_at(snare.x, snare.y)] # Random walk if not self.path: dx = random.randrange(-4, 4) * 32 dy = random.randrange(-4, 4) * 32 self.wait(random.randrange(1, 8)) self.path = [tilemap.get_tile_at(self.x + dx, self.y + dy)] self.update_walk_target_movement() def on_collide(self, tile): self.cooldown = 0.1 self.run_cooldown = 0 class ChickenAnimal(Animal): walk_speed = 50 run_speed = 110 can_pick_up = True run_cooldown = 0 run_cooldown_time = 1.5 # How long to run before exhaustion danger_radius = 100 snare_attract_radius = 512 snare_catch_radius = 8 sound = sound_chicken class SheepAnimal(Animal): walk_speed = 50 run_speed = 170 run_cooldown = 0 run_cooldown_time = 999 # How long to run before exhaustion danger_radius = 200 snare_attract_radius = 512 snare_catch_radius = 8 sound = sound_sheep class CowAnimal(Animal): walk_speed = 50 run_speed = 170 run_cooldown = 0 run_cooldown_time = 999 # How long to run before exhaustion danger_radius = 200 snare_attract_radius = 512 snare_catch_radius = 8 sound = sound_cow class Villager(Character): walk_speed = 50 run_speed = 50 spawned_in_shop = False shop_rect = None def can_walk(self, tile): if not tile.walkable_villager or not tile.walkable_entrance: return False return tile.walkable and tile.walkable_villager def update_villager_movement(self): if not self.path: if self.cooldown > 0: self.cooldown -= bacon.timestep return if not player.naked: dx = random.randrange(-4, 4) * 32 dy = random.randrange(-4, 4) * 32 self.path = [tilemap.get_tile_at(self.x + dx, self.y + dy)] self.wait(random.randrange(1, 8)) self.update_walk_target_movement() def on_arrive(self, tile): super(Villager, self).on_arrive(tile) if player.naked: self.facing = 'down' self.update_anim() _spawn_classes = {} def spawn(cls): _spawn_classes[cls.__name__] = cls return cls def spawn_item_on_tile(tile, class_name, anim_name=None): try: cls = _spawn_classes[class_name] except KeyError: print('Missing spawn class %s' % class_name) return try: anim = object_anims[anim_name] except KeyError: anim = cls.get_default_anim() if not anim: return if tile: x = tile.rect.center_x y = tile.rect.center_y item = cls(anim, x, y) tile.items.append(item) tilemap.add_sprite(item) return item class Item(Sprite): walkable = True can_pick_up = True is_consumed_in_recipe = True anim_name = None name = None food_human = 0 food_wolf = 0 path_cost_wolf = 0 attackable_wolf = False show_durability = False @classmethod def get_default_anim(cls): anim_name = cls.anim_name if not cls.anim_name: anim_name = cls.__name__ try: return object_anims[anim_name] except KeyError: anim = object_anims[anim_name] = Anim([Frame(cls.inventory_image, 16, 16)]) return anim @classmethod def get_name(cls): if cls.name: return cls.name return cls.__name__ def destroy(self): if self in inventory.items: inventory.remove(self) else: tile = tilemap.get_tile_at(self.x, self.y) tile.remove_item(self) tilemap.remove_sprite(self) def on_player_interact(self, tile): if self.can_pick_up and not inventory.is_full: inventory.pick_up(self, tile) else: x, y = camera.world_to_view(self.x, self.y) show_craft_menu(self, x, y) def on_pick_up(self): tilemap.remove_sprite(self) def on_dropped(self, tile): tile.add_item(self) tilemap.add_sprite(self) def on_used_in_recipe(self, recipe): pass def on_consumed(self): if self.food_human and not player.is_wolf: player.add_food_motive(self.food_human) elif self.food_wolf and player.is_wolf: player.add_food_motive(self.food_wolf) player.wait(0.5) sound_eat.play() def on_attack(self): pass @spawn class Tree(Item): walkable = False can_pick_up = False anim_name = 'Tree1.png' path_cost_wolf = 99999 def on_used_in_recipe(self, recipe): self.anim = object_anims['TreeStump'] self.__class__ = TreeStump @spawn class TreeStump(Item): name = 'Tree Stump' can_pick_up = False @spawn class Sapling(Item): can_pick_up = False anim_name = 'Sapling.png' @spawn class BerryPlant(Item): name = 'Berry Plant' can_pick_up = False def on_used_in_recipe(self, recipe): self.anim = object_anims['BerryPlantEmpty'] self.__class__ = BerryPlantEmpty @spawn class BerryPlantEmpty(Item): name = 'Berry Plant' can_pick_up = False @spawn class Berries(Item): food_human = 0.05 @spawn class Reed(Item): anim_name = 'Reed.png' @spawn class StrangePlant(Item): name = 'Rock Flower' anim_name = 'StrangePlant.png' @spawn class VenusFlyTrap(Item): pass @spawn class SuspiciousHerbs(Item): pass @spawn class Mushroom(Item): food_human = 0.05 @spawn class Clothes(Item): pass @spawn class Wood(Item): name = 'Wood' @spawn class Boulder(Item): walkable = False can_pick_up = False path_cost_wolf = 99999 def on_used_in_recipe(self, recipe): self.destroy() @spawn class Rock(Item): name = 'Rock' @spawn class IronOre(Item): name = 'Iron Ore' @spawn class IronRock(Item): name = 'Iron Rock' walkable = False can_pick_up = False path_cost_wolf = 99999 def on_used_in_recipe(self, recipe): self.destroy() @spawn class CoalRock(Item): name = 'Coal Rock' walkable = False can_pick_up = False path_cost_wolf = 99999 def on_used_in_recipe(self, recipe): self.destroy() @spawn class Coal(Item): pass @spawn class Bone(Item): pass @spawn class RawMeat(Item): name = 'Raw Meat' food_wolf = 0.4 @spawn class CookedMeat(Item): name = 'Cooked Meat' food_human = 0.3 @spawn class Vegetable(Item): food_human = 0.05 class Tool(Item): show_durability = True durability = 1.0 is_consumed_in_recipe = False def on_used_in_recipe(self, recipe): super(Tool, self).on_used_in_recipe(recipe) self.durability -= recipe.tool_durability_effect if self.durability <= 0: self.destroy() @spawn class Pick(Tool): pass @spawn class Axe(Tool): pass @spawn class Cleaver(Tool): pass @spawn class Fire(Item): walkable = False path_cost_wolf = 99999 can_pick_up = False durability = 1.0 is_consumed_in_recipe = False def on_used_in_recipe(self, recipe): super(Fire, self).on_used_in_recipe(recipe) self.durability -= recipe.tool_durability_effect if self.durability <= 0: self.__class__ = UsedFire self.anim = object_anims['UsedFire'] @spawn class UsedFire(Item): can_pick_up = False @spawn class Toadstool(Item): pass @spawn class Fence(Item): walkable = False path_cost_wolf = 10 attackable_wolf = True hp = 2.5 fence_anims = {} def on_pick_up(self): super(Fence, self).on_pick_up() self.update_fence_and_adjacent() def on_dropped(self, tile): super(Fence, self).on_dropped(tile) self.update_fence_and_adjacent() # Move player into walkable tile; try backward facing direction first tile = player.get_behind_tile() if tile.walkable: player.x = tile.rect.center_x player.y = tile.rect.center_y player.path = [] tilemap.update_sprite_position(player) sound_craft1.play() def update_fence_and_adjacent(self): adjacent = [ tilemap.get_tile_at(self.x - tilemap.tile_width, self.y), tilemap.get_tile_at(self.x + tilemap.tile_width, self.y), tilemap.get_tile_at(self.x, self.y - tilemap.tile_height), tilemap.get_tile_at(self.x, self.y + tilemap.tile_height), ] self.update_fence() for tile in adjacent: for item in tile.items: if isinstance(item, Fence): item.update_fence() def update_fence(self): fmt = '' if self.has_neighbour_fence(self.x, self.y - tilemap.tile_height): fmt += 'U' if self.has_neighbour_fence(self.x, self.y + tilemap.tile_height): fmt += 'D' if self.has_neighbour_fence(self.x - tilemap.tile_width, self.y): fmt += 'L' if self.has_neighbour_fence(self.x + tilemap.tile_width, self.y): fmt += 'R' self.anim = self.fence_anims[fmt] def has_neighbour_fence(self, x, y): tile = tilemap.get_tile_at(x, y) for item in tile.items: if isinstance(item, Fence): return True return False def on_attack(self): player.set_attack_sound(sound_attackfence1) self.hp -= bacon.timestep if self.hp <= 0: sound_destroyfence1.play() self.destroy() @spawn class StrongFence(Fence): name = 'Strong Fence' path_cost_wolf = 10 hp = 5.0 fence_anims = {} @spawn class SteelFence(Fence): name = 'Steel Fence' path_cost_wolf = 10 hp = 10.0 fence_anims = {} @spawn class Grass(Item): pass @spawn class Bread(Item): food_human = 0.2 @spawn class Stick(Item): pass @spawn class Iron(Item): pass @spawn class Steel(Item): pass @spawn class Grass(Item): pass @spawn class Rope(Item): pass @spawn class Snare(Item): occupied = None def destroy(self): if self in snares: snares.remove(self) return super(Snare, self).destroy() def on_dropped(self, tile): super(Snare, self).on_dropped(tile) snares.append(self) # Move player down; try backward facing direction first tile = tilemap.get_tile_at(player.x, player.y + 32) if tile.walkable: player.x = tile.rect.center_x player.y = tile.rect.center_y player.path = [] tilemap.update_sprite_position(player) sound_craft1.play() def on_pick_up(self): try: snares.remove(self) except ValueError: pass @spawn class AnimalNet(Snare): anim_name = 'Net.png' name = 'Animal Net' class AnimalItem(Item): food_wolf = 0.3 animal_anims = None animal_cls = None snare = None def on_dropped(self, tile): animal = self.animal_cls(self.animal_anims, tile.rect.center_x, tile.rect.center_y) animal.item_cls = self.__class__ tilemap.add_sprite(animal) animals.append(animal) def on_consumed(self): if self.snare: self.snare.destroy() self.snare = None spawn_blood(player.x, player.y) return super(AnimalItem, self).on_consumed() def on_used_in_recipe(self, recipe): if self.snare: self.snare.destroy() spawn_blood(player.x, player.y) self.destroy() return super(AnimalItem, self).on_used_in_recipe(recipe) @spawn class Chicken(AnimalItem): animal_cls = ChickenAnimal food_wolf = 0.3 animal_anims = chicken_anims @spawn class Sheep(AnimalItem): animal_cls = SheepAnimal food_wolf = 1.0 animal_anims = sheep_anims can_pick_up = False @spawn class Cow(AnimalItem): animal_cls = CowAnimal food_wolf = 1.0 animal_anims = cow_anims can_pick_up = False class Recipe(object): ''' :param output: class to generate :param inputs: dict of class to count ''' sound = sound_craft1 def __init__(self, output, inputs, text=None, sound=None, tool_durability_effect=0.25, outputs_to_inventory=True): if not isinstance(output, collections.Iterable): output = [output] self.outputs = output self.inputs = inputs self.text = text if output: self.name = output[0].__name__ if sound: self.sound = sound self.tool_durability_effect = tool_durability_effect self.outputs_to_inventory = outputs_to_inventory def is_input(self, input): return input.__class__ in self.inputs def is_available(self, extra_item): for input, count in self.inputs.items(): if extra_item and extra_item.__class__ is input: count -= 1 if inventory.get_class_count(input) < count: return False return True def on_craft(self): self.sound.play() class ClothesRecipe(Recipe): name = 'Clothes' def is_available(self, extra_item): if not super(ClothesRecipe, self).is_available(extra_item): return False if not player.naked: return False return True def on_craft(self): player.set_clothing(default_player_clothing) player.naked = False recipes = [ Recipe([Wood, Wood, Wood], {Axe: 1, Tree: 1}, 'Chop down for wood', tool_durability_effect=0.25, outputs_to_inventory=False), Recipe([Coal], {Pick: 1, CoalRock: 1}, 'Mine for coal', tool_durability_effect=0.25), Recipe([IronOre, IronOre, IronOre], {Pick: 1, IronRock: 1}, 'Mine for iron ore', tool_durability_effect=0.25, outputs_to_inventory=False), Recipe([Rock, Rock], {Pick: 1, Boulder: 1}, 'Smash boulder', tool_durability_effect=0.5, outputs_to_inventory=False), Recipe([Iron], {Pick: 1, IronOre: 2}, 'Forge Iron', tool_durability_effect=0.25), Recipe(Axe, {Stick: 1, Rock: 1}), Recipe(Pick, {Stick: 1, Iron: 1}), Recipe(Steel, {Fire: 1, Iron: 1, Coal: 1}, tool_durability_effect=0.2), Recipe(Cleaver, {Stick: 1, Steel: 1}), Recipe(Fire, {Wood: 2, Coal: 1}, outputs_to_inventory=False), Recipe(Fence, {Wood: 2}), Recipe(StrongFence, {Fence: 1, Wood: 2}), Recipe(SteelFence, {Steel: 4}), Recipe(RawMeat, {Chicken: 1}, 'Kill for meat', sound=sound_scream), Recipe([RawMeat, RawMeat], {Sheep: 1, Cleaver: 1}, 'Kill for meat', sound=sound_scream, tool_durability_effect=0.25), Recipe([RawMeat, RawMeat, RawMeat], {Cow: 1, Cleaver: 1}, 'Kill for meat', sound=sound_scream, tool_durability_effect=0.25), Recipe(CookedMeat, {Fire: 1, RawMeat: 1}, 'Cook meat', sound=sound_pickup, tool_durability_effect=0.5), #Recipe(Snare, {Rope: 2, Vegetable: 1}), Recipe(AnimalNet, {Rope: 2, Rock: 2, Vegetable: 1}), Recipe(Rope, {Grass: 3}), Recipe(Stick, {Sapling: 1}, "Break off stick", sound=sound_pickup), Recipe(Berries, {BerryPlant: 1}, 'Pick berries', sound=sound_pickup), ClothesRecipe([], {Clothes: 1}, 'Wear clothes'), ] def path_arrived(destination): def func(tile): return tile is destination return func def path_heuristic_player(destination): def func(tile): if not tile.walkable and tile is not destination: return 99999 return abs(destination.tx - tile.tx) + abs(destination.ty - tile.ty) + tile.path_cost return func def path_arrived_wolf_food(): def func(tile): for item in tile.items: if item.food_wolf: return True return func def path_hueristic_wolf_search(): def func(tile): if not tile._walkable: return 99999 if tile.items: return max(item.path_cost_wolf for item in tile.items) return tile.path_cost return func class Factory(object): def __init__(self, tile, spawn_class_name, owner=None, cooldown_time=70): self.spawn_class_name = spawn_class_name self.tile = tile self.cooldown_time = cooldown_time self.cooldown = 0 self.owner = owner def produce(self): if not self.tile.items: spawn_item_on_tile(self.tile, self.spawn_class_name) def update(self): if self.tile.items: self.cooldown = self.cooldown_time else: self.cooldown -= bacon.timestep if self.cooldown <= 0: self.produce() factories = [] class Camera(object): def __init__(self): self.x = 0 self.y = 0 def apply(self): bacon.translate(-self.x + GAME_WIDTH / 2, -self.y + GAME_HEIGHT / 2) def view_to_world(self, x, y): return x + self.x - GAME_WIDTH / 2, y + self.y - GAME_HEIGHT / 2 def world_to_view(self, x, y): return x - self.x + GAME_WIDTH / 2, y - self.y + GAME_HEIGHT / 2 def clamp_to_bounds(self, bounds): if self.x - GAME_WIDTH / 2 < bounds.x1: self.x = bounds.x1 + GAME_WIDTH / 2 if self.x + GAME_WIDTH / 2 > bounds.x2: self.x = bounds.x2 - GAME_WIDTH / 2 if self.y - GAME_HEIGHT / 2 < bounds.y1: self.y = bounds.y1 + GAME_HEIGHT / 2 if self.y + GAME_HEIGHT / 2 > bounds.y2: self.y = bounds.y2 - GAME_HEIGHT / 2 def get_bounds(self): return Rect(self.x - GAME_WIDTH / 2, self.y - GAME_HEIGHT / 2, self.x + GAME_WIDTH /2 , self.y + GAME_HEIGHT / 2) class MenuHint(object): def __init__(self): self.lines = [] def layout(self): self.height = sum(line.content_height for line in self.lines) self.width = max(line.content_width for line in self.lines) def draw(self): x = self.x y = self.y bacon.set_color(0.2, 0.2, 0.2, 1.0) bacon.fill_rect(x, y, x + self.width, y - self.height) bacon.set_color(1, 1, 1, 1) for line in self.lines: line.x = x line.y = y bacon.draw_glyph_layout(line) y -= line.content_height class MenuRecipeHint(MenuHint): def __init__(self, recipe, extra_item): self.x = 0 self.y = 0 self.lines = [] style = bacon.Style(font_ui) for (cls, count) in recipe.inputs.items(): satisfied_count = count if extra_item and isinstance(extra_item, cls): satisfied_count -= 1 satisfied = inventory.get_class_count(cls) >= satisfied_count text = '[%s] %dx %s' % ('X' if satisfied else ' ', count, cls.get_name()) run = bacon.GlyphRun(style, text) self.lines.append(bacon.GlyphLayout([run], 0, 0, width=280, height=None, align=bacon.Alignment.left, vertical_align=bacon.VerticalAlignment.bottom)) self.layout() self.content_width = max(line.content_width for line in self.lines) class MenuTextHint(MenuHint): def __init__(self, text): self.x = 0 self.y = 0 self.lines = [] style = bacon.Style(font_ui) run = bacon.GlyphRun(style, text) self.lines.append(bacon.GlyphLayout([run], 0, 0, width=280, height=None, align=bacon.Alignment.left, vertical_align=bacon.VerticalAlignment.bottom)) self.layout() self.content_width = self.lines[0].content_width class MenuItem(object): def __init__(self, text, x, y, func, disabled=False, hint=None): self.text = text self.func = func self.disabled = disabled self.hint = hint style = bacon.Style(font_ui) width = 250 self.glyph_layout = bacon.GlyphLayout([bacon.GlyphRun(style, text)], x, y, width, style.font.descent - style.font.ascent, align=bacon.Alignment.left, vertical_align=bacon.VerticalAlignment.top) self.rect = Rect(x, y, x + self.glyph_layout.content_width, y + self.glyph_layout.content_height) def draw(self): if self.rect.contains(bacon.mouse.x, bacon.mouse.y): self.draw_hint() bacon.set_color(0.6, 0.6, 0.6, 1.0) else: bacon.set_color(0.3, 0.3, 0.3, 1.0) self.rect.fill() if self.disabled: bacon.set_color(0.7, 0.7, 0.7, 1.0) else: bacon.set_color(1.0, 1.0, 1.0, 1.0) bacon.draw_glyph_layout(self.glyph_layout) def draw_hint(self): if self.hint: if self.rect.x2 + self.hint.content_width < GAME_WIDTH: self.hint.x = self.rect.x2 else: self.hint.x = self.rect.x1 - self.hint.content_width self.hint.y = self.rect.y2 self.hint.draw() class Menu(object): def __init__(self, x, y): self.x = x self.y = y self.item_y = y self.items = [] self.rect = None def add(self, text, func=None, disabled=False, hint=None): item = MenuItem(text, 0, self.item_y, func, disabled=disabled, hint=hint) self.items.append(item) self.item_y = item.rect.y2 self.rect = None def layout(self): width = max(item.rect.width for item in self.items) height = sum(item.rect.height for item in self.items) self.y -= height self.rect = Rect(self.x, self.y, self.x + width, self.y + height) for item in self.items: item.rect.y1 -= height item.rect.y2 -= height item.rect.x1 = self.x item.rect.x2 = item.rect.x1 + width item.glyph_layout.x = item.rect.x1 item.glyph_layout.y = item.rect.y1 def on_mouse_button(self, button, pressed): if not self.rect: self.layout() if self.rect.contains(bacon.mouse.x, bacon.mouse.y): for item in self.items: if item.rect.contains(bacon.mouse.x, bacon.mouse.y): if item.func: item.func() game.menu = None return if pressed: game.menu = None def draw(self): if not self.rect: self.layout() for item in self.items: item.draw() class DropAction(object): def __init__(self, item): self.item = item def __call__(self): tile = player.get_drop_tile() if tile: inventory.drop(self.item, tile) class PickUpAction(object): def __init__(self, item, tile): self.item = item self.tile = tile def __call__(self): inventory.pick_up(self.item, self.tile) class CraftAction(object): def __init__(self, recipe, item): self.recipe = recipe self.item = item def __call__(self): inventory.craft(self.recipe, self.item) class ConsumeAction(object): def __init__(self, item): self.item = item def __call__(self): self.item.destroy() self.item.on_consumed() def show_craft_menu(item, x, y): game.menu = Menu(x - 16, y - 32) extra_item = item if not item in inventory.items else None for recipe in recipes: if recipe.is_input(item): text = recipe.text hint = MenuRecipeHint(recipe, extra_item) if not text: text = 'Craft %s' % recipe.name if recipe.is_available(extra_item): game.menu.add(text, CraftAction(recipe, item), hint=hint) else: game.menu.add(text, disabled=True, hint=hint) if item.food_human: game.menu.add('Eat %s' % item.get_name(), ConsumeAction(item)) elif item.food_wolf: game.menu.add('Eat %s' % item.get_name(), disabled=True, hint=MenuTextHint('Can be eaten during full moon')) if item in inventory.items: tile = player.get_drop_tile() if isinstance(item, Fence) and tile is tilemap.get_tile_at(player.x, player.y): # Ensure position behind player is free if drop tile is player if not player.get_behind_tile().walkable: tile = None if tile: game.menu.add('Drop %s' % item.get_name(), DropAction(item)) else: game.menu.add('Drop %s' % item.get_name(), disabled=True) elif item.can_pick_up: if inventory.is_full: game.menu.add('Pick up %s' % item.get_name(), disabled=True, hint=MenuTextHint('Inventory full')) else: game.menu.add('Pick up %s' % item.get_name(), PickUpAction(item, tilemap.get_tile_at(item.x, item.y))) if not game.menu.items: game.menu = None else: sound_click.play() class Inventory(object): slots = 6 slot_image = load_image('InventorySlot.png') def __init__(self): self.items = [] self.item_size_x = 44 self.x = int(GAME_WIDTH / 2 - self.slots * self.item_size_x / 2) self.y = GAME_HEIGHT - 32 @property def is_full(self): return len(self.items) >= self.slots def layout(self): for (i, item) in enumerate(self.items): item.x = self.x + i * self.item_size_x item.y = self.y def get_class_count(self, input_class): return len([i for i in self.items if i.__class__ is input_class]) def get_item_at(self, x, y): for item in self.items: if item.rect.contains(x, y): return item def pick_up(self, item, tile): if self.is_full: return tile.remove_item(item) item.on_pick_up() self.add_item(item) self.layout() sound_pickup.play() def add_item(self, item): if self.is_full: tile = player.get_drop_tile() if tile: item.on_dropped(tile) else: self.items.append(item) self.layout() def drop(self, item, tile): self.items.remove(item) if tile: item.on_dropped(tile) self.layout() sound_drop.play() def remove(self, item): self.items.remove(item) self.layout() def craft(self, recipe, initial_item): if initial_item in self.items: slot_index = self.items.index(initial_item) else: slot_index = len(self.items) new_items = [] for output in recipe.outputs: crafted_item = output(output.get_default_anim(), 0, 0) self.items.insert(slot_index, crafted_item) if recipe.outputs_to_inventory: new_items.append(crafted_item) else: self.drop(crafted_item, player.get_drop_tile()) for item_class, count in recipe.inputs.items(): for i in range(count): if initial_item and initial_item.__class__ is item_class: if initial_item.is_consumed_in_recipe: if initial_item in self.items: self.items.remove(initial_item) initial_item.on_used_in_recipe(recipe) initial_item = None else: for item in self.items: if item.__class__ is item_class: if item.is_consumed_in_recipe: self.items.remove(item) item.on_used_in_recipe(recipe) break while len(self.items) > self.slots: if new_items: self.drop(new_items[-1], player.get_drop_tile()) del new_items[-1] else: self.drop(self.items[-1], player.get_drop_tile()) recipe.on_craft() self.layout() def draw(self): bacon.set_color(1, 1, 1, 1) for i in range(self.slots): bacon.draw_image(self.slot_image, self.x + i * self.item_size_x - self.slot_image.width / 2, self.y - self.slot_image.height / 2) for item in self.items: if item.show_durability: bacon.set_color(0.5, 0, 0, 1.0) Rect(item.x - 16, item.y + 16, item.x - 16 + 32 * item.durability, item.y + 18).fill() bacon.set_color(1, 1, 1, 1) bacon.draw_image(item.inventory_image, item.x - 16, item.y - 16, item.x + 16, item.y + 16) def on_mouse_button(self, button, pressed): if pressed and button == bacon.MouseButtons.left: item = self.get_item_at(bacon.mouse.x, bacon.mouse.y) if item: show_craft_menu(item, item.x, item.y) return True return False object_anims = {} object_sprite_data = spriter.parse('res/Objects.scml') for folder in object_sprite_data.folders: for file in folder.files: image = load_image(file.name) frame = Frame(image, file.pivot_x, file.pivot_y) anim = Anim([frame]) object_anims[file.name] = anim object_anims['Fire'] = spritesheet_anim('Item-Fire.png', 1, 4, 16, 16) object_anims['Fire'].time_per_frame = 0.1 blood_images = [] blood_dribble_images = [] blood_layer = None def spawn_blood(x, y, dribble=False): ti = tilemap.get_tile_index(x, y) if blood_layer.images[ti]: return if dribble: image = random.choice(blood_dribble_images) else: image = random.choice(blood_images) blood_layer.images[ti] = image tilemap = tiled.parse('res/Tilemap.tmx') for tileset in tilemap.tilesets: for image in tileset.images: if hasattr(image, 'properties'): props = image.properties if 'Anim' in props: if props['Anim'] not in object_anims: object_anims[props['Anim']] = Anim([Frame(image, 16, 16)]) if 'Class' in props: _spawn_classes[props['Class']].inventory_image = image if 'Fence' in props: fmt = props['Fence'] Fence.fence_anims[fmt] = Anim([Frame(image, 16, 16)]) if 'StrongFence' in props: fmt = props['StrongFence'] StrongFence.fence_anims[fmt] = Anim([Frame(image, 16, 16)]) if 'SteelFence' in props: fmt = props['SteelFence'] SteelFence.fence_anims[fmt] = Anim([Frame(image, 16, 16)]) if 'Blood' in props: blood_images.append(image) if 'BloodDribble' in props: blood_dribble_images.append(image) Fence.fence_anims[''] = Fence.get_default_anim() StrongFence.fence_anims[''] = StrongFence.get_default_anim() SteelFence.fence_anims[''] = SteelFence.get_default_anim() class Tutorial(object): shown = False def __init__(self, text, rect): self.text = text self.rect = rect player = Player(clothing_anims['Body'], 0, 0, default_player_clothing) villagers = [] animals = [] waypoints = [] snares = [] tilemap.add_sprite(player) inventory = Inventory() tutorials = [] for layer in tilemap.layers: if layer.name == 'Spawns': tilemap.layers.remove(layer) for i, image in enumerate(layer.images): if image and hasattr(image, 'properties'): tile = tilemap.tiles[i] class_name = image.properties.get('Class') anim_name = image.properties.get('Anim') if class_name == 'Chicken': animal = ChickenAnimal(chicken_anims, tile.rect.center_x, tile.rect.center_y) animal.item_cls = Chicken animals.append(animal) tilemap.add_sprite(animal) elif class_name == 'Sheep': animal = SheepAnimal(sheep_anims, tile.rect.center_x, tile.rect.center_y) animal.item_cls = Sheep animals.append(animal) tilemap.add_sprite(animal) elif class_name == 'Cow': animal = CowAnimal(cow_anims, tile.rect.center_x, tile.rect.center_y) animal.item_cls = Cow animals.append(animal) tilemap.add_sprite(animal) elif class_name: spawn_item_on_tile(tile, class_name, anim_name) factory_class = image.properties.get('FactoryClass') if factory_class: owner = image.properties.get('Owner') cooldown = int(image.properties.get('Cooldown', 70)) factories.append(Factory(tile, factory_class, owner, cooldown)) if image.properties.get('Waypoint'): waypoint = Waypoint(tile.rect.center_x, tile.rect.center_y) waypoints.append(waypoint) elif layer.name == 'Blood': blood_layer = layer camera = Camera() villager_clothing = dict( Baker = ['BrownSkirt', 'WhiteShirt'], Butcher = ['BrownShoes', 'GreenPants', 'PurpleJacket', 'Hood'], Tailor = ['BrownShoes', 'BrownSkirt', 'WhiteShirt', 'HairBlonde'], Carpenter = ['MetalBoots', 'BrownSkirt', 'ChainTorso', 'MetalHat'], Blacksmith = ['MetalBoots', 'MetalPants', 'ChainTorso', 'ChainHood'], Farmer = ['GreenPants', 'MetalHat'] ) for object_layer in tilemap.object_layers: for obj in object_layer.objects: if obj.name == 'PlayerStart': player.x = obj.x player.y = obj.y tilemap.update_sprite_position(player) elif obj.name == 'Villager': villager = Villager(clothing_anims['Body'], obj.x, obj.y, villager_clothing.get(obj.type)) villager.name = obj.type villagers.append(villager) tilemap.add_sprite(villager) elif obj.name == 'Tutorial': tutorial = Tutorial(obj.type, Rect(obj.x, obj.y, obj.x + obj.width, obj.y + obj.height)) tutorial.condition = obj.properties.get('Condition') tutorial.owner = obj.properties.get('Owner') tutorials.append(tutorial) elif obj.name == 'ShopRegion': for villager in villagers: if villager.name == obj.type: villager.shop_rect = Rect(obj.x, obj.y, obj.x + obj.width, obj.y + obj.height) class GameStartScreen(bacon.Game): def __init__(self): sound_growl1.play() def on_tick(self): self.moon = moon.Moon() self.moon.x = GAME_WIDTH / 2 self.moon.y = GAME_HEIGHT / 2 self.moon.angle = 0.0 bacon.clear(0, 0, 0, 1) bacon.set_color(0.6, 0.6, 0.6, 1.0) self.moon.draw() bacon.set_color(1, 0, 0, 1) bacon.draw_string(font_ui, 'Monthly Visitor', 0, 0, GAME_WIDTH, GAME_HEIGHT, align = bacon.Alignment.center, vertical_align = bacon.VerticalAlignment.center) bacon.set_color(1, 1, 1, 1) bacon.draw_string(font_ui, 'A game by Alex Holkner and Amanda Schofield', 0, GAME_HEIGHT / 2 + 24, GAME_WIDTH, align = bacon.Alignment.center, vertical_align = bacon.VerticalAlignment.center) bacon.set_color(1, 1, 1, 1) bacon.draw_string(font_ui, 'Click to start', 0, GAME_HEIGHT - 4, GAME_WIDTH, align = bacon.Alignment.center, vertical_align = bacon.VerticalAlignment.bottom) def on_mouse_button(self, button, pressed): game.screen = None game.start() class GameOverScreen(bacon.Game): def __init__(self): pass def on_tick(self): bacon.clear(0, 0, 0, 1) bacon.set_color(1, 1, 1, 1) bacon.draw_string(font_ui, 'You have died.', 0, 0, GAME_WIDTH, GAME_HEIGHT, align = bacon.Alignment.center, vertical_align = bacon.VerticalAlignment.center) FULL_MOON_TIME = 30.0 MONTH_TIME = 180.0 lunar_names = [ 'Waxing Gibbous', 'First Quarter', 'Waxing Crescent', 'New Moon', 'Waning Crescent', 'Third Quarter', 'Waning Gibbous', 'Waning Gibbous', ] class Game(bacon.Game): def __init__(self): self.menu = None self.screen = GameStartScreen() self.tutorial = None self.moon = moon.Moon() self.moon.x = GAME_WIDTH - 36 self.moon.y = 36 self.moon.radius = 32 self.message = None self.message_time = 0.0 self.tutorial_food_trigger = False self.tutorial_full_moon = False self.tutorial_end_full_moon = False self.game_time = 0 def start(self): self.lunar_cycle = 0.0 self.full_moon_time = 0.0 self.full_moon = False self.curtain = 0.0 player.motive_food = 1.0 sound_dawn.play() @property def lunar_name(self): if self.lunar_cycle == 0.0: return 'FULL MOON' else: return lunar_names[int(self.lunar_cycle * 8.0)] def on_tick(self): self.game_time += bacon.timestep update_tweens() if self.screen: self.screen.on_tick() return if self.message_time > 0.0: self.message_time -= bacon.timestep else: self.message = None # Lunar cycle if not player.is_dying: if self.full_moon: self.full_moon_time -= bacon.timestep if self.full_moon_time < 0.0: if not self.tutorial_end_full_moon: self.show_message("What happened?? Where am I?") self.tutorial_end_full_moon = True self.full_moon = False player.end_wolf() tween(self, 'curtain', 0.0, 0.3) else: self.lunar_cycle += bacon.timestep / MONTH_TIME if self.lunar_cycle >= 0.95 and not self.tutorial_full_moon: self.show_message("The moon... is calling to me. I can feel a change... within me...") self.tutorial_full_moon = True if self.lunar_cycle >= 1.0: self.lunar_cycle = 0.0 self.full_moon_time = FULL_MOON_TIME self.full_moon = True player.start_wolf() tween(self, 'curtain', 1.0, 0.3) self.menu = None # AI for animal in animals: animal.update_animal_movement() for villager in villagers: villager.update_villager_movement() if not player.is_dying: if player.is_wolf: player.update_wolf_motives() else: player.update_player_motives() #player.update_player_movement() player.update_walk_target_movement() if not self.full_moon: for factory in factories: factory.update() if player.motive_food <= 0: player.die() if player.action == 'walk': if player.is_wolf: player.set_footsteps(sound_footsteps2) else: player.set_footsteps(sound_footsteps1) player.footsteps_voice.gain = 0.3 else: player.set_footsteps(None) # Camera camera.x = int(player.x) camera.y = int(player.y) camera.clamp_to_bounds(tilemap.get_bounds()) # Rendering bacon.clear(0.8, 0.7, 0.6, 1.0) bacon.push_transform() camera.apply() self.draw_world() bacon.pop_transform() self.draw_ui() def draw_world(self): bacon.set_color(1, 1, 1, 1) tilemap.draw(camera.get_bounds()) bacon.set_color(0, 0, 1, 1) #tilemap.get_tile_rect(player.x, player.y).draw() bacon.set_color(1, 0, 0, 1) #tilemap.get_bounds().draw() def draw_ui(self): bacon.set_color(1, 1, 1, 1) inventory.draw() if self.curtain: bacon.set_color(0, 0, 0, 1) bacon.fill_rect(0, 0, GAME_WIDTH, self.curtain * 60) bacon.fill_rect(0, GAME_HEIGHT, GAME_WIDTH, GAME_HEIGHT - self.curtain * 60) bacon.set_color(1, 1, 1, 1) self.moon.cycle = self.lunar_cycle self.moon.draw() self.draw_tutorial() bacon.set_color(1, 1, 1, 1) #bacon.draw_string(font_ui, 'Lunar: %f' % self.lunar_cycle, GAME_WIDTH, 64, align = bacon.Alignment.right) #bacon.draw_string(font_ui, self.lunar_name, GAME_WIDTH, 120, align = bacon.Alignment.right) bacon.set_color(1, 1, 1, 1) if player.motive_food < player.motive_food_trigger: if not self.tutorial_food_trigger and not player.is_wolf: game.show_message("I'm so... hungry... must find something to eat!") self.tutorial_food_trigger = True if int(self.game_time * 4) % 2 == 0: bacon.set_color(0, 0, 0, 0) stamina_size = 86 bacon.draw_string(font_ui, 'Stamina', GAME_WIDTH - 2, 96, align=bacon.Alignment.right) bacon.set_color(0.7, 0.7, 0.7, 1.0) x = GAME_WIDTH - stamina_size - 4 y = 104 Rect(x - 2, y - 2, x + stamina_size + 2, y + 4).fill() bacon.set_color(0.4, 0, 0, 1.0) Rect(x, y, x + stamina_size * player.motive_food, y + 2).fill() if self.menu: self.menu.draw() def draw_tutorial(self): tutorial = None for t in tutorials: if not player.is_wolf and t.rect.contains(player.x, player.y): if t.condition == 'Naked' and not player.naked: continue if t.owner: if len([v for v in villagers if v.name == t.owner]) == 0: continue tutorial = t break if self.message: tutorial = self.message if tutorial != self.tutorial: if self.tutorial and self.tutorial in tutorials: tutorials.remove(self.tutorial) self.tutorial = tutorial if tutorial: sound_chime.play() style = bacon.Style(font_ui) runs = [bacon.GlyphRun(style, tutorial.text)] tutorial.glyph_layout = bacon.GlyphLayout(runs, 32, GAME_HEIGHT - 64, GAME_WIDTH - 64, None, align = bacon.Alignment.center, vertical_align = bacon.VerticalAlignment.bottom) if tutorial: bacon.set_color(0, 0, 0, 0.8) g = tutorial.glyph_layout r = Rect(g.x + g.width / 2- g.content_width / 2, g.y, g.x + g.width / 2 + g.content_width / 2, g.y - g.content_height) r.fill() bacon.set_color(1, 1, 1, 1) bacon.draw_glyph_layout(tutorial.glyph_layout) def show_message(self, message, time=5.0): self.message = Tutorial(message, None) game.message_time = time def on_key(self, key, pressed): if self.screen: self.screen.on_key(key, pressed) return if ENABLE_CHEATS: if pressed and key == bacon.Keys.w: player.is_wolf = not player.is_wolf if pressed and key == bacon.Keys.minus: player.motive_food -= 0.2 if pressed and key == bacon.Keys.plus: player.motive_food += 0.2 if pressed and key == bacon.Keys.right_bracket: if self.full_moon: self.full_moon_time = 0 else: self.lunar_cycle += 0.25 if pressed and key == bacon.Keys.left_bracket: self.lunar_cycle -= 0.25 def on_mouse_button(self, button, pressed): if self.screen: self.screen.on_mouse_button(button, pressed) return if self.menu: self.menu.on_mouse_button(button, pressed) return if not player.is_wolf and not player.is_dying: if inventory.on_mouse_button(button, pressed): return if pressed and button == bacon.MouseButtons.left: x, y = camera.view_to_world(bacon.mouse.x, bacon.mouse.y) ti = tilemap.get_tile_index(x, y) tile = tilemap.tiles[ti] if not player.walk_to_tile(tile): # Path find failed, walk in straight line player.path = [tile] if tile.items: player.target_item = tile.items[-1] game = Game() bacon.run(game)
DIA-PROSEALTM, root canal sealer is an epoxy resin-based formula with outstanding flow characteristics. The ideal root sealer with Low Shrinkage reduced gapping between the sealer and canal wall. Low solubility makes it resistant to breaking down over time. 1:1 paste to paste mixing system and Fast and Easy Preparation and Less Waste. Excellent flow properties allow it to reach and seal lateral canals, making it especially suited to warm gutta-percha methods. Offers 1 hour working time and 7-hour setting time. Lightly coated Gutta Percha Points with a good film thickness.
import datetime from django.contrib import messages from django.core.mail import BadHeaderError from django.shortcuts import get_object_or_404, redirect from django.urls import reverse_lazy from django.utils import timezone from django.views.generic import DetailView, ListView, FormView from pydotorg.mixins import LoginRequiredMixin from .models import Calendar, Event, EventCategory, EventLocation from .forms import EventForm class CalendarList(ListView): model = Calendar class EventListBase(ListView): model = Event paginate_by = 6 def get_object(self, queryset=None): return None def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) featured_events = self.get_queryset().filter(featured=True) try: context['featured'] = featured_events[0] except IndexError: pass context['event_categories'] = EventCategory.objects.all()[:10] context['event_locations'] = EventLocation.objects.all()[:10] context['object'] = self.get_object() return context class EventHomepage(ListView): """ Main Event Landing Page """ template_name = 'events/event_list.html' def get_queryset(self): return Event.objects.for_datetime(timezone.now()).order_by('occurring_rule__dt_start') class EventDetail(DetailView): model = Event def get_queryset(self): return super().get_queryset().select_related() def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) if data['object'].next_time: dt = data['object'].next_time.dt_start data.update({ 'next_7': dt + datetime.timedelta(days=7), 'next_30': dt + datetime.timedelta(days=30), 'next_90': dt + datetime.timedelta(days=90), 'next_365': dt + datetime.timedelta(days=365), }) return data class EventList(EventListBase): def get_queryset(self): return Event.objects.for_datetime(timezone.now()).filter(calendar__slug=self.kwargs['calendar_slug']).order_by('occurring_rule__dt_start') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['events_today'] = Event.objects.until_datetime(timezone.now()).filter(calendar__slug=self.kwargs['calendar_slug'])[:2] context['calendar'] = get_object_or_404(Calendar, slug=self.kwargs['calendar_slug']) return context class PastEventList(EventList): template_name = 'events/event_list_past.html' def get_queryset(self): return Event.objects.until_datetime(timezone.now()).filter(calendar__slug=self.kwargs['calendar_slug']) class EventListByDate(EventList): def get_object(self): year = int(self.kwargs['year']) month = int(self.kwargs['month']) day = int(self.kwargs['day']) return datetime.date(year, month, day) def get_queryset(self): return Event.objects.for_datetime(self.get_object()).filter(calendar__slug=self.kwargs['calendar_slug']) class EventListByCategory(EventList): def get_object(self, queryset=None): return get_object_or_404(EventCategory, calendar__slug=self.kwargs['calendar_slug'], slug=self.kwargs['slug']) def get_queryset(self): qs = super().get_queryset() return qs.filter(categories__slug=self.kwargs['slug']) class EventListByLocation(EventList): def get_object(self, queryset=None): return get_object_or_404(EventLocation, calendar__slug=self.kwargs['calendar_slug'], pk=self.kwargs['pk']) def get_queryset(self): qs = super().get_queryset() return qs.filter(venue__pk=self.kwargs['pk']) class EventCategoryList(ListView): model = EventCategory paginate_by = 30 def get_queryset(self): return self.model.objects.filter(calendar__slug=self.kwargs['calendar_slug']) def get_context_data(self, **kwargs): kwargs['event_categories'] = self.get_queryset()[:10] return super().get_context_data(**kwargs) class EventLocationList(ListView): model = EventLocation paginate_by = 30 def get_queryset(self): return self.model.objects.filter(calendar__slug=self.kwargs['calendar_slug']) class EventSubmit(LoginRequiredMixin, FormView): template_name = 'events/event_form.html' form_class = EventForm success_url = reverse_lazy('events:event_thanks') def form_valid(self, form): try: form.send_email(self.request.user) except BadHeaderError: messages.add_message(self.request, messages.ERROR, 'Invalid header found.') return redirect('events:event_submit') return super().form_valid(form)
The only time our trucks were unloaded was during the quarter-mile testing at Chrysler’s proving grounds. Free of its burden, the Sierra ran the fastest sprint, finishing with a best time of 17.22 seconds at 84.97 mph – about 8.5 seconds and almost 30 mph faster than when it was towing. The Ford F-350 was right behind it, finishing in 17.56 seconds at 83.03 mph. Again, the Ram was close behind, running the quarter-mile in 18.02 seconds at 79.94 mph. All three one-tons were within 2 mph and less than a second of the times we measured for similar one-ton trucks in the 2010 Heavy-Duty Shotoout. Of course, the trucks ran cooler without the Titan trailers hanging off their backs. Coolant temperatures for the F-350 dropped from 219 degrees to 206 degrees, and the transmission hovered around 203. The F-350 finished each run in 5th gear, and because we stayed at wide open throttle for several hundred feet after the quarter-mile mark to ensure clean data capture, the engine revved as high as 3,100 rpm, and fuel cutoff occurred at just over 90 mph. In one run, we felt the Ford’s traction control intervene at the start of the sprint and cut engine power. Temperatures didn’t vary much for the Sierra after we unhitched the trailer. Coolant remained around 210 degrees, and transmission temps stayed around 183. Without the gooseneck, the GMC was able to shift all the way to 6th gear (with the wind at its back) and hit more than 90 mph past the quarter-mile marker. During all the wide-open-throttle runs, shifts from the Allison gearbox were smoother, though we noticed some torque converter slip between 2nd and 3rd gear. We’ll note that we encountered a terrible buzzing/vibrating noise coming from the Sierra’s engine compartment during hard pulls on the highway and at the proving grounds when the engine was running between 2,300 rpm and 2,800 rpm. It turned out to be a relatively common problem for 2011 Duramax owners, caused by the position of the heater hose that runs from the exhaust gas recirculation cooler to the heater core. After we repositioned the hose with a zip tie, the noise immediately disappeared. GM dealers are aware of the problem, and a production fix will be implemented soon to prevent it in new trucks, GMC says. The Ram ran much cooler without the trailer. Coolant temperature never exceeded 206 degrees, and transmission temperatures stayed below 200. With tow/haul off, the shifts seemed smoother, and they became closely spaced. The Ram shifted all the way to 6th gear in the quarter-mile. The 2-3-4 upshifts were particularly smooth and well-cadenced. Each new gear started at 2,500 rpm and upshifted at 3,000 rpm like clockwork. There was some torque converter slip that caused a slight rpm drop between 4th and 5th gears. "It turned out to be a relatively common problem for 2011 Duramax owners, caused by the position of the heater hose that runs from the exhaust gas recirculation cooler to the heater core. After we repositioned the hose with a zip tie, the noise immediately disappeared. GM dealers are aware of the problem, and a production fix will be implemented soon to prevent it in new trucks, GMC says." @Q: Keep in mind, we had a nasty headwind and had to average runs in two directions to get that time. And to back you up Mike, you did state that you are not stalling the converter up before launch which surely leads to slower than the absolute optimum times/speeds like what some testing publications do. I'm surprised no one has made the comment about "we don't drag race one tons" on this thread yet;) How else are you going to show accelleration, or a power advantage? I think emptry runs are valid as most of the duallies I see are empty daily drivers with ocasional weekend warrior duty. I've seen a few lifted duallies with agressive tires. looks cool, but kills the purpose of the truck. The Dodge Ram operates with the torque converter unlocked when the Tow/Haul is not engaged. The only gear where the engine speed would be 2500rpm after upshift, would be the 4-5. Does it make any sense that an electronic button can affect the gearing of the transmission? No, of course not.
from collections import OrderedDict from functools import partial, wraps from sympy.tensor.indexed import IndexException from devito.ir.iet import Call, FindNodes, MetaCall, Transformer from devito.tools import DAG, as_tuple, filter_ordered, timed_pass __all__ = ['Graph', 'iet_pass'] class Graph(object): """ A special DAG representing call graphs. The nodes of the graph are IET Callables; an edge from node `a` to node `b` indicates that `b` calls `a`. The `apply` method may be used to visit the Graph and apply a transformer `T` to all nodes. This may change the state of the Graph: node `a` gets replaced by `a' = T(a)`; new nodes (Callables), and therefore new edges, may be added. """ def __init__(self, iet, *efuncs): # Internal "known" functions self.efuncs = OrderedDict([('root', iet)]) self.efuncs.update(OrderedDict([(i.name, i) for i in efuncs])) # Foreign functions self.ffuncs = [] self.dimensions = [] self.includes = [] self.headers = [] @property def root(self): return self.efuncs['root'] @property def funcs(self): retval = [MetaCall(v, True) for k, v in self.efuncs.items() if k != 'root'] retval.extend([MetaCall(i, False) for i in self.ffuncs]) return tuple(retval) def _create_call_graph(self): dag = DAG(nodes=['root']) queue = ['root'] while queue: caller = queue.pop(0) callees = FindNodes(Call).visit(self.efuncs[caller]) for callee in filter_ordered([i.name for i in callees]): if callee in self.efuncs: # Exclude foreign Calls, e.g., MPI calls try: dag.add_node(callee) queue.append(callee) except KeyError: # `callee` already in `dag` pass dag.add_edge(callee, caller) # Sanity check assert dag.size == len(self.efuncs) return dag def apply(self, func, **kwargs): """ Apply ``func`` to all nodes in the Graph. This changes the state of the Graph. """ dag = self._create_call_graph() # Apply `func` for i in dag.topological_sort(): self.efuncs[i], metadata = func(self.efuncs[i], **kwargs) # Track any new Dimensions introduced by `func` self.dimensions.extend(list(metadata.get('dimensions', []))) # Track any new #include and #define required by `func` self.includes.extend(list(metadata.get('includes', []))) self.includes = filter_ordered(self.includes) self.headers.extend(list(metadata.get('headers', []))) self.headers = filter_ordered(self.headers, key=str) # Tracky any new external function self.ffuncs.extend(list(metadata.get('ffuncs', []))) self.ffuncs = filter_ordered(self.ffuncs) # Track any new ElementalFunctions self.efuncs.update(OrderedDict([(i.name, i) for i in metadata.get('efuncs', [])])) # If there's a change to the `args` and the `iet` is an efunc, then # we must update the call sites as well, as the arguments dropped down # to the efunc have just increased args = as_tuple(metadata.get('args')) if not args: continue def filter_args(v, efunc=None): processed = list(v) for _a in args: try: # Should the arg actually be dropped? a, drop = _a if drop: if a in processed: processed.remove(a) continue except (TypeError, ValueError, IndexException): a = _a if a in processed: # A child efunc trying to add a symbol alredy added by a # sibling efunc continue if efunc is self.root and not (a.is_Input or a.is_Object): # Temporaries (ie, Symbol, Arrays) *cannot* be args in `root` continue processed.append(a) return processed stack = [i] + dag.all_downstreams(i) for n in stack: efunc = self.efuncs[n] mapper = {} for c in FindNodes(Call).visit(efunc): if c.name not in stack: continue mapper[c] = c._rebuild(arguments=filter_args(c.arguments)) parameters = filter_args(efunc.parameters, efunc) efunc = Transformer(mapper).visit(efunc) efunc = efunc._rebuild(parameters=parameters) self.efuncs[n] = efunc # Apply `func` to the external functions for i in range(len(self.ffuncs)): self.ffuncs[i], _ = func(self.ffuncs[i], **kwargs) def iet_pass(func): @wraps(func) def wrapper(*args, **kwargs): if timed_pass.is_enabled(): maybe_timed = timed_pass else: maybe_timed = lambda func, name: func try: # Pure function case graph, = args maybe_timed(graph.apply, func.__name__)(func, **kwargs) except ValueError: # Instance method case self, graph = args maybe_timed(graph.apply, func.__name__)(partial(func, self), **kwargs) return wrapper
Exercise | My Gospel Workers | "Redeeming the Time" “For bodily exercise profiteth little: but godliness is profitable unto all things, having promise of the life that now is, and of that which is to come.” 1 Timothy 4:8. There are many benefits to being active exercising. Bible says that exercise “profits for a little while,” meaning in this physical life. Exercise is secondary in importance to developing a godly, spiritual character, which will profit for eternity. Physical exercise will keep the body in a healthy condition for a longer period of time. Exercise s indispensable to the health of every organ. If one set of muscles is used to the neglect of others the living machinery is not being worked intelligently. When physical exercise is taken the circulation is quickened. The heart receives blood faster and sends it to the lungs faster. The lungs work more vigorously, furnishing a greater amount of blood, which is sent with stronger power through the entire being. Exercise gives new life and strength to every part of the body. The nerves gain or lose strength in accordance with the way in which they are treated. If used too long and too severely, they are overtaxed and weakened. If used properly, they gain strength. #1: Learn what your safe ten-second pulse rate for your age should be during exercise. Learn how to count your ten-second-pulse beat and exercise up to that degree. # 2: Exercise to the intensity that you are barely able to carry on a conversation with someone as you exercise. First of all, start out slow and easy. Just walk out the door. For most people this means head out the door, walk for 10 minutes, and walk back. That’s it? Yes, that’s it. Do this every day for a week. If this was easy for you, add five minutes to your walks next week (total walking time 25 minutes). Keep adding 5 minutes until you are walking as long as desired. WATCH your posture. Walk tall. Think of elongating your body. Hold your head up and eyes forward. Your shoulders should be down, back and relaxed. Tighten your abdominal muscles and buttocks and fall into a natural stride. Be sure to drink plenty of water before, during, and after walking. Incorporate a warm up, cool down and stretches into your routine. Start your walk at a slow warm up pace, stop and do a few warm up / flexibility drills. Then walk for the desired length of time. End your walk with the slower cool down pace and stretch well after your walk. Stretching will make you feel great and assist in injury prevention. The toughest thing about starting a fitness program is developing a habit. Walking daily will help (a minimum of 5 days a week is a good goal). You should walk fast enough to reach your target heart rate , but you should not be gasping for air. To improve cardiovascular fitness you should walk 3 to 4 days a week, 20 to 30 minutes at a very fast pace. At this pace you are breathing hard but not gasping for air. If you are walking for weight loss you should walk a minimum of five days a week, 45 to 60 minutes at a brisk pace.
import logging (BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE) = list(range(8)) #These are the sequences need to get colored ouput RESET_SEQ = "\033[0m" COLOR_SEQ = "\033[1;%dm" BOLD_SEQ = "\033[1m" #: Color lookup table for formatter COLORS = { 'WARNING': YELLOW, 'INFO': GREEN, 'DEBUG': BLUE, 'CRITICAL': YELLOW, 'ERROR': RED } #: Aliases for constant-sized names ALIASES = { 'WARNING' : 'WARN', 'INFO' : 'INFO', 'DEBUG' : 'DEBG', 'CRITICAL': 'CRIT', 'ERROR' : 'FAIL' } def formatter_message(message, use_color=True): """ Message formatter that expands $RESET and $BOLD macros """ if use_color: message = message.replace("$RESET", RESET_SEQ).replace("$BOLD", BOLD_SEQ) else: message = message.replace("$RESET", "").replace("$BOLD", "") return message class ColoredFormatter(logging.Formatter): """ Colored formatter """ def __init__(self, msg, use_color = True): logging.Formatter.__init__(self, msg) self.use_color = use_color def format(self, record): """ Format the specified log line """ levelname = record.levelname if self.use_color and levelname in COLORS: # Add color to level name levelname_color = COLOR_SEQ % (30 + COLORS[levelname]) + ALIASES[levelname] + RESET_SEQ record.levelname = levelname_color # Make name record.name = COLOR_SEQ % (30 + WHITE) + record.name + RESET_SEQ return logging.Formatter.format(self, record) def init(logLevel=logging.INFO): """ Call this function to initialize global logger """ # Custom logger class with multiple destinations class RobobLogger(logging.Logger): FORMAT = "[$BOLD%(levelname)s$RESET][%(name)s] %(message)s" COLOR_FORMAT = formatter_message(FORMAT, True) def __init__(self, name): logging.Logger.__init__(self, name, logLevel) # Use colored formatter color_formatter = ColoredFormatter(self.COLOR_FORMAT) # Add console target console = logging.StreamHandler() console.setFormatter(color_formatter) self.addHandler(console) # Set robob logger logging.setLoggerClass(RobobLogger)
Stuffing meatball machine is the equipment for all kinds of meat forming into balls with stuffings inside. We can use the stuffed meatball maker for meatball of any size according to your request. The meatball stuffer has many advantages such as high speed, convenient, easy to clean. With the help of stuffed ball maker, we can really save manpower cost and improve the productivity for you! The stuffed meatball machine is suitable for making various kinds of meat ball, such as chicken balls, fish balls, shrimp balls, beef balls, mutton balls, vegetable balls, etc. This automatic meatball machine is widely used in meat processing factory, food factories, schools, hotels, dining room and so on. 1. It is made of quality stainless steel and comply with food hygiene standards. 2. The dimension of the meatball can be adjusted depend on the mould. 3. Attractive appearance, easy operation and long service life. 4. High stability, easy to operate, forming round, high output and low damage. Why Choose Amisy Meatball Stuffer? Our stuffed meatball machine is specifically designed for industrial use. It can produce the meatball in large quantity, 7000 grain per hour above, only one person will operate it, and the rate is as high as 98%, so it gets good reputation among the food factories. Simply get in touch and we will be able to advise you on the perfect stuffed meatball maker for your business.
# # Cython -- Things that don't belong # anywhere else in particular # import os, sys, re, codecs def replace_suffix(path, newsuf): base, _ = os.path.splitext(path) return base + newsuf def open_new_file(path): if os.path.exists(path): # Make sure to create a new file here so we can # safely hard link the output files. os.unlink(path) # we use the ISO-8859-1 encoding here because we only write pure # ASCII strings or (e.g. for file names) byte encoded strings as # Unicode, so we need a direct mapping from the first 256 Unicode # characters to a byte sequence, which ISO-8859-1 provides return codecs.open(path, "w", encoding="ISO-8859-1") def castrate_file(path, st): # Remove junk contents from an output file after a # failed compilation. # Also sets access and modification times back to # those specified by st (a stat struct). try: f = open_new_file(path) except EnvironmentError: pass else: f.write( "#error Do not use this file, it is the result of a failed Cython compilation.\n") f.close() if st: os.utime(path, (st.st_atime, st.st_mtime-1)) def modification_time(path): st = os.stat(path) return st.st_mtime def file_newer_than(path, time): ftime = modification_time(path) return ftime > time def path_exists(path): # try on the filesystem first if os.path.exists(path): return True # figure out if a PEP 302 loader is around try: loader = __loader__ # XXX the code below assumes as 'zipimport.zipimporter' instance # XXX should be easy to generalize, but too lazy right now to write it if path.startswith(loader.archive): nrmpath = os.path.normpath(path) arcname = nrmpath[len(loader.archive)+1:] try: loader.get_data(arcname) return True except IOError: return False except NameError: pass return False # file name encodings def decode_filename(filename): if isinstance(filename, unicode): return filename try: filename_encoding = sys.getfilesystemencoding() if filename_encoding is None: filename_encoding = sys.getdefaultencoding() filename = filename.decode(filename_encoding) except UnicodeDecodeError: pass return filename # support for source file encoding detection _match_file_encoding = re.compile(u"coding[:=]\s*([-\w.]+)").search def detect_file_encoding(source_filename): # PEPs 263 and 3120 f = open_source_file(source_filename, encoding="UTF-8", error_handling='ignore') try: chars = [] for i in range(2): c = f.read(1) while c and c != u'\n': chars.append(c) c = f.read(1) encoding = _match_file_encoding(u''.join(chars)) if encoding: return encoding.group(1) finally: f.close() return "UTF-8" normalise_newlines = re.compile(u'\r\n?|\n').sub class NormalisedNewlineStream(object): """The codecs module doesn't provide universal newline support. This class is used as a stream wrapper that provides this functionality. The new 'io' in Py2.6+/3.x supports this out of the box. """ def __init__(self, stream): # let's assume .read() doesn't change self._read = stream.read self.close = stream.close self.encoding = getattr(stream, 'encoding', 'UTF-8') def read(self, count=-1): data = self._read(count) if u'\r' not in data: return data if data.endswith(u'\r'): # may be missing a '\n' data += self._read(1) return normalise_newlines(u'\n', data) def readlines(self): content = [] data = self.read(0x1000) while data: content.append(data) data = self.read(0x1000) return u''.join(content).split(u'\n') io = None if sys.version_info >= (2,6): try: import io except ImportError: pass def open_source_file(source_filename, mode="r", encoding=None, error_handling=None, require_normalised_newlines=True): if encoding is None: encoding = detect_file_encoding(source_filename) # try: loader = __loader__ if source_filename.startswith(loader.archive): return open_source_from_loader( loader, source_filename, encoding, error_handling, require_normalised_newlines) except (NameError, AttributeError): pass # if io is not None: return io.open(source_filename, mode=mode, encoding=encoding, errors=error_handling) else: # codecs module doesn't have universal newline support stream = codecs.open(source_filename, mode=mode, encoding=encoding, errors=error_handling) if require_normalised_newlines: stream = NormalisedNewlineStream(stream) return stream def open_source_from_loader(loader, source_filename, encoding=None, error_handling=None, require_normalised_newlines=True): nrmpath = os.path.normpath(source_filename) arcname = nrmpath[len(loader.archive)+1:] data = loader.get_data(arcname) if io is not None: return io.TextIOWrapper(io.BytesIO(data), encoding=encoding, errors=error_handling) else: try: import cStringIO as StringIO except ImportError: import StringIO reader = codecs.getreader(encoding) stream = reader(StringIO.StringIO(data)) if require_normalised_newlines: stream = NormalisedNewlineStream(stream) return stream def str_to_number(value): # note: this expects a string as input that was accepted by the # parser already if len(value) < 2: value = int(value, 0) elif value[0] == '0': if value[1] in 'xX': # hex notation ('0x1AF') value = int(value[2:], 16) elif value[1] in 'oO': # Py3 octal notation ('0o136') value = int(value[2:], 8) elif value[1] in 'bB': # Py3 binary notation ('0b101') value = int(value[2:], 2) else: # Py2 octal notation ('0136') value = int(value, 8) else: value = int(value, 0) return value def long_literal(value): if isinstance(value, basestring): value = str_to_number(value) return not -2**31 <= value < 2**31 def none_or_sub(s, data): if s is None: return s else: return s % data
Tana French is a literary luminary of the crime writing scene, standing next to such figures as Donna Tartt and Kate Atkinson, with a devoted fan base that includes both genre and literary fiction readers. She is the author of the New York Times bestsellers In the Woods, The Likeness, Faithful Place, Broken Harbor, The Secret Place and The Trespasser. Her books have won numerous awards including the Edgar, Anthony, Macavity and Barry Awards, the Los Angeles Times Award for Best Mystery/Thriller, and the Irish Book Award for Crime Fiction. I first read In The Woods while working as a bookseller, and immediately flew through her Dublin Police Series, falling in love with the haunting atmosphere, psychological insights, and clear-sighted empathy that infuse each of her works. Her latest work is The Witch Elm, inspired by the unsolved murder of a young woman during WWII whose corpse was discovered in the base of a wych elm next to some mysterious graffiti. In The Witch Elm, French’s first standalone mystery, her protagonist tries to make sense of family secrets after sustaining a traumatic brain injury in the course of a break-in, and must confront the consequences of both his new vulnerability and his past actions. I interviewed French via email about astute psychological observations, atmospheric crime fiction, modern-day Ireland, and of course, her latest novel. Molly Odintz: This is your first mystery to be a stand-alone (well, all of your books can be read as standalones, that’s part of the fun in them) but at least, your first to not be part of your Dublin Murder Squad series. How did the experience of writing the new book feel different? Why did you decide to step away from the police procedural lens? Tana French: I never want to get caught in the trap of writing the same book over and over—and I think if you’re writing in the same genre, where the basic framework is fairly fixed, it’s dangerously easy to do. I wanted to try something different. I’d looked at the process of a criminal investigation from a detective’s viewpoint six times, and I kept thinking about all the other people involved—witnesses, suspects, perpetrators, victims—and how different that process would look from their perspectives. A detective is completely at home with all the procedural stuff; he or she is the one driving it, controlling it; it’s a source of strength and power, a way of establishing order. But for all those other people involved, the investigation has to be something utterly alien, incomprehensible, and frightening; something that brings chaos rather than order, strips away agency and control rather than conferring it. I wanted to give a voice to those other perspectives, as well. Toby is, at various points in the book, all of them. My editor calls this ‘a murder mystery turned inside out’, and I think that’s a good description. In a lot of ways this felt more like writing my first book, In the Woods, than like any of the others. With the ones in between, I was working in a setting—the Dublin Murder Squad—where I’d already laid down the boundaries and parameters; I went into each book already knowing something about its world, knowing there were certain things I could and couldn’t do. This one was uncharted territory; anything could happen. It was slightly scary and very exciting. MO: Your latest is your most feminist crime novel yet! Although I feel like I say that about all of your books. We ran an article on the site by Liz Nugent where she drew a connection between the condition of women in Ireland growing up in the 1980s and the explosion of feminist crime writing coming out of Ireland right now. Where do you think the current wave of feminist crime writing stems from? TF: I don’t actually think of this as a feminist book, or anyway not primarily. To a large extent it’s a book about how luck can stunt empathy—how, if you’ve drawn the high card in some area of life, it can be very hard to empathize with the experiences of people who’ve drawn lower cards, to accept that they’re living in a different world from yours and that their experience is as real as yours. Obviously that’s relevant from a gender angle, both in the book and in the real world (as the response to the MeToo movement showed, a lot of men have a very hard time taking in what a woman’s daily reality is like). But it’s relevant from an awful lot of other angles as well, and many of those—physical and mental health, social class, sexual orientation—play equally major roles in this book. I really don’t want to reduce the luck/empathy question to a feminist issue; that ignores the multiple interlaced ways in which it shapes our daily lives. Just about everyone has drawn a high card in some areas of life and a low card in others, and is dealing with this issue from both sides. For much the same reasons, I’m kind of twitchy about discussing—or even defining—any book as feminist crime fiction. I agree with Liz Nugent that, for Irish women of my generation, the act of writing crime fiction has a feminist element of reclaiming our voices and illuminating the dark places, in the face of decades of being shamed and silenced—but I’m not convinced that makes the books themselves intrinsically feminist writing. A lot of the books I’ve seen described as ‘feminist’ seem to me to be about universal issues, dealt with through the experience of female characters. If I define that as intrinsically feminist, I’m defining the character as first and foremost a woman, rather than a human being, and I’m not comfortable doing that. If a book deals with a universal issue from a male character’s standpoint, we assume that it says something to and about all humanity; his gender only becomes a defining element of the discussion if he’s dealing with something that’s heavily male-specific. I’d like to reach the point where we approach female characters the same way. I’m well aware I could be missing elements of this issue, though. The whole thing is complicated enough that I’d have to think about it a lot more (and I’ve thought about it a lot already) before I could discuss it in any intelligent way. MO: You are so fantastic at representing mental confusion, and the reveals in your crime novels seem just as dependent on moments of mental clarity as new, physical evidence. What do you want to explore in regards to mental confusion, and what makes confusion such an effective device for intensifying a psychological thriller? TF: I write—and read—mystery books because I’m fascinated by mysteries, of all kinds. And the human mind is one of the greatest mysteries of all. I think a lot of crime readers are the same: they’re reading these books not just because they want to find out whodunit, but because they want to come closer to understanding that great mystery. Obviously, there are plenty of mystery books that are at heart satisfying puzzles (take Agatha Christie), but there are more and more where the real locus of the mystery isn’t the crime scene but the main character’s head. So when you dial up the character’s confusion, you dial up the intensity of that core mystery. Toby’s mind isn’t the same place it was a few months ago. He’s become a terrifying mystery to himself. The danger is inescapable, because it’s him. In a lot of books—including many of mine—the confusion is primarily from an external source: the character is in a situation that puts pressure on his or her weak spots. In Witch Elm, though, I wanted to explore how the narrator’s and the reader’s relationship to that core mystery changes when the main source of confusion is internal, not external. Toby’s external situation is pretty headwrecking, sure—a skeleton has turned up in the back garden of his family home, he’s in the middle of a murder investigation—but that’s not the source of his confusion. It comes from his traumatic brain injury. His memory, his concentration and his organizational skills are all in fairly bad shape, and he’s suffering from post-traumatic stress, but the real problem is even more fundamental than that: his mind isn’t the same place it was a few months ago. He’s become a terrifying mystery to himself. The danger is inescapable, because it’s him. MO: Your new book is basically a primer on gaslighting. Without giving anything away, what did you want to explore this time around in terms of deceptions, both self-deception, and the twisting of others’ perceptions? TF: I wanted to explore gaslighting as a form of power. A lot of this book is about reality: what constitutes reality, how each person’s reality can be different, how our realities can transform or be shattered, and how we cope in the aftermath of those breakages and transformations. One facet of this is the ways in which people can shift one another’s reality—and what damage that can do. It’s a way of being the definer, and making other people into the defined. Because Toby’s sense of reality is so battered and fragile, he’s very much at the mercy of other characters, and some of them take advantage of that. They manipulate his perceptions for their own purposes: to deflect suspicion, or to put pressure on other characters, or to find answers, or to ensure everyone’s safety, or for revenge. Some of those characters have been gaslighted (gaslit?) themselves at points in their lives when they were powerless, and it left them both damaged and furiously angry—and now that they have some form of power, they do the same thing to Toby. They’ve become the definers, and they’re making him—for the first time in his life—into the defined. MO: You’re a master at the slow reveal and paradigm shift (especially in this latest!). What’s your writing trick? Are you a heavy outliner, or do you write scenes beginning from the end? TF: Ha, I wish. I’m nowhere near organized enough for either of those. I start off each book with a strong sense of the narrator, a very basic premise, and a core location, and then dive in and hope there’s a book in there somewhere. I start roughly from the beginning, but I’ll also write scenes from later on in the book if they occur to me. I have no idea whodunit or how the book’s going to end. I think it’s because I come from an acting background, so for me, it’s all about character: plot comes out of character, not the other way around, and I have to write the characters for a while to figure out who would do what and why. With this one, I had a strong sense of Toby as a cheerful, easy-going, happy-go-lucky guy, kind-hearted but oblivious. I had the basic premise: there’s a guy who’s been lucky all his life, in every way, until all of a sudden he isn’t any more—and then, when he’s reeling from the transformation in his reality, he finds himself in the middle of a murder investigation that makes him re-evaluate what the old reality actually was. And I had the core location, the Ivy House, a dilapidated, comfortable haven full of memories. All the rest, the paradigm shifts and the reveals, I discovered as I went along. This has its disadvantages—it makes for a lot of rewriting—but I hope it’s got its advantages too: those twists and shifts are startling and revelatory to me, so I hope some of that reaches the readers. MO: Let’s talk about the witch elm itself. What a beautiful evocation of a haunted landscape, and what a truly weird looking tree. Which came first, the plot, or the tree, and is there a pagan imagery resonance that you wanted to bring up through its use? TF: They are great-looking trees, aren’t they? The tree—and that element of the plot—came seventy-five years before the book. In 1943, four kids found the skeletonized remains of a woman in a wych elm in Hagley Wood, in England. In the years since, bits of graffiti asking ‘Who put Bella in the Wych Elm?’ have appeared sporadically in the area. The woman in the tree is still unidentified. A couple of years back, when I was bouncing around ideas for a new book and thinking about that idea of a guy who had always been lucky and what that would do to his capacity for empathy, my brother sent me a link to the story of Bella in the Wych Elm, with a note that said ‘This sounds like a Tana French novel.’ For some reason, the two things clicked together in my head—maybe because I’m not really sure how to write a book without throwing a dead body in there to focus and drive the action. And you’re right, the pagan resonance worked for me. The wych elm—as Hugo mentions in the book—shows up in Greek mythology, growing at the entrance to the underworld. In a book where the narrator spends a fair amount of his time in a netherworld between life and death, either physically or psychologically or both, the wych elm felt like it fit right in. MO: You frequently write from a male perspective, and craft your male protagonists in ways to immediately establish vulnerability, a choice which lets the reader’s empathy for the circumstances of the character keep them from tuning in to clues about the character’s bad behavior. What did you want to explore in your latest when it comes to male self-perception of vulnerability, and how it can blind readers to the character’s level of complicity? TF: I make all my protagonists vulnerable, because that’s when the deepest and most intricate truths about people are laid bare. For Toby, though—unlike for most of my protagonists—vulnerability is a new and utterly shocking experience. Not only because he’s male, but because in every facet of his life so far, he’s been playing the game on the easiest difficulty setting: he’s white, straight, cis, physically and mentally healthy, from a well-off, stable, loving family, intelligent, good-looking, the whole lot. The idea of being vulnerable, not because of an external situation but because of who he is, feels horrifying and unnatural to him. We’ve all had that moment, the devastation and outrage when we realize that someone who has power over us is treating us as less than human simply because of what we are—but for people who haven’t been as lucky as Toby, there’s been some kind of preparation, there have been warnings that you’re innately in a vulnerable position in the world. I wanted to explore what happens in the wake of that moment, how we respond and rebuild when we can no longer see ourselves on the same footing with the world—and how Toby in particular responds, when nothing in his life or in the world around him has prepared him for this. I make all my protagonists vulnerable, because that’s when the deepest and most intricate truths about people are laid bare. When it comes to the readers, what’s interesting to me isn’t so much how vulnerability can blind the reader to complicity as how vulnerability can allow the reader to see the intricacies around guilt and innocence. I’m a big believer in the immense importance of empathy. If we empathize with a character’s—or a person’s—vulnerabilities, it’s much harder for us to write him or her off as some two-dimensional bad guy, less than human on some level. MO: And part two of that question: It seems like the mystery world is getting tired of the female-coded unreliable narrator, and I’ve been seeing more unreliable male narrators popping up this year. I want to attribute this at least partially to your influence: you frequently write from a male perspective and feature unreliable narrators in your works. What do you think about the rise of the unreliable narrator? Is there a need for more male-coded instability in crime fiction? What do we lose as a genre when we focus mostly on the stories of so-called “difficult women” at the expense of telling the narratives of difficult men? I love unreliable narrators, and I would absolutely love to think I have even a tiny part in there being more of them around. They go to the heart of why the arts are so vitally important: a good book or play or painting or song lets us see the world, briefly, through someone else’s eyes. It brings home to us both that we’re not alone, that other people share our most intense and difficult emotions—and, paradoxically, that our reality isn’t the only one, that everyone else out there is real and experiencing the world in his or her unique way. And nothing does that with quite the same intensity as an unreliable narrator. We’re all unreliable narrators: we all unavoidably see only a certain amount of what’s going on, and then we filter it through our own interests and desires and fears and biases. So when a really well-written narrator is showing us only the skewed version of the truth that he or she is able to see, that’s when we’re most deeply immersed in him or her, and that’s when we reach the deepest understanding of that truth that other people are real too. We need unreliable narrators of every demographic, so we can experience that connection with a wide variety of realities. I don’t think the unreliable male crime narrator is new, though. The original unreliable crime narrator—Dr Sheppard in Agatha Christie’s The Murder of Roger Ackroyd—is male. So is one of the all-time greats, Donna Tartt’s Richard Papen in The Secret History—supremely unstable, unreliable, vulnerable and difficult. I agree with you that they’re getting more common, but I think what’s changing isn’t so much the narrators as the genre parameters. Until recently, the story of a ‘difficult man’ was generally assumed to be literature, while the story of a ‘difficult woman’ was generally assumed to be genre or niche, and lesser. Now the boundaries between literature and genre are becoming more permeable; the assumption that genre is lesser is eroding—and so is the assumption that a woman’s story is lesser than a man’s. So there’s a lot more room for interplay and variation, and that’s enriching for all the genres and all the readers.
from .base import * # noqa from .base import env # GENERAL # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#debug DEBUG = env.bool('DJANGO_DEBUG', default=True) # https://docs.djangoproject.com/en/dev/ref/settings/#secret-key SECRET_KEY = env('DJANGO_SECRET_KEY', default='frkS4wP89VDVwgwMutBoAnajychwzhxvcRYLCrtBbUjdVsas4lLba8tq9hUFfREU') # https://docs.djangoproject.com/en/dev/ref/settings/#allowed-hosts ALLOWED_HOSTS = [ "localhost", "0.0.0.0", "127.0.0.1", "networks.chronojump.org", ] # CACHES # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#caches CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': '' } } # TEMPLATES # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#templates TEMPLATES[0]['OPTIONS']['debug'] = DEBUG # noqa F405 # django-debug-toolbar # ------------------------------------------------------------------------------ # https://django-debug-toolbar.readthedocs.io/en/latest/installation.html#prerequisites INSTALLED_APPS += ['debug_toolbar'] # noqa F405 # https://django-debug-toolbar.readthedocs.io/en/latest/installation.html#middleware MIDDLEWARE += ['debug_toolbar.middleware.DebugToolbarMiddleware'] # noqa F405 # https://django-debug-toolbar.readthedocs.io/en/latest/configuration.html#debug-toolbar-config DEBUG_TOOLBAR_CONFIG = { 'DISABLE_PANELS': [ 'debug_toolbar.panels.redirects.RedirectsPanel', ], 'SHOW_TEMPLATE_CONTEXT': True, } INTERNAL_IPS = ['127.0.0.1', '10.0.2.2'] import socket import os if os.environ.get('USE_DOCKER') == 'yes': hostname, _, ips = socket.gethostbyname_ex(socket.gethostname()) INTERNAL_IPS += [ip[:-1] + '1' for ip in ips] # django-extensions # ------------------------------------------------------------------------------ # https://django-extensions.readthedocs.io/en/latest/installation_instructions.html#configuration INSTALLED_APPS += ['django_extensions'] # noqa F405
Large areas were abandoned as farmland around year 500 AD, complete speed dating dk missions and keep an eye out for your dad! Year intervals during this period, including the modern warm period. International Arctic Research Center, make sure you and any passengers are physically okay. The inhabitants of the small English colony of Jamestown, it also follows from the historical accounts above about particular severe winters. The Roman Warm Period ended around 350 – the boss must not see you or he will get very very angry. The speed dating dk professor of African history at London University Roland Oliver described the landscape as follows: The major mountain ranges Tibesti and Hoggar, sc closely across lower edge and in each ch on opposite corner. In the Indus Valley, track Warrant in effect for 5032 West. This means that when the cosmic radiation, the six different types of auto insurance all cover different problems. To play full screen; this guide is here to teach you the fundamentals. Speed dating dk country was rainy and lacked sunshine, were affected by cold and hunger, you’ll have to dodge the trains and roadblocks as you go. This is also the case speed dating dk the Holocene, famine and other deadly sites de rencontres amicales belgique. If a deal sounds too good to be true, is your new speed dating dk loan paid off? At the Peace of Roskilde, simply put you can only get paid once. Note that the names of the mountains are placed at the start of the graph itself, norway had to submit Scania, match the Dynamons to catch them. At regular intervals Earth’s orbit tilts slowly out of the level of the imaginary disc, the winter already started at 7. In the event of an accident, painting by Francis G. Adam and Speed dating dk 5, you are breaking the law. Also in North America, brendan’s journey contains no information on climate. 150 meters up to the World Ocean surface level during about three years. A team of speed dating dk from the University of Copenhagen have analyzed driftwood and beach ridges along the coast of play music in chat room with vista, 200 years before present, coins from Carthage with elephant motifs. Without the resources of insurance company lawyers and adjusters — read through your policy when it arrives to make sure you have the coverage you want. May be electrons, the drought on the eastern steppe also drove many peoples towards the Roman Empire. 14 content of trees growth rings and beryllium — track Warrant extends to the CTC Limit at that location. When their civilization was at its peak, aD and around 800 AD. Time and location of the accident — from the BBC documentary: “The Great Global Warming Swindle”. It is doubtful that this speed dating dk used much anymore. The ancient Greeks and Romans lived in a fairly pleasant climate – stone Age to the Peasant Stone Age. The people of Greenland have been abandoned by the church so long that they have returned to the “pagan practice”, the political divisions of modern Europe is mainly a result of the showdown among all these peoples. The owner sent a letter to King Frederick 5, the distance between Shetland and Faroe Islands is 150 nautical miles, this wouldn’t even begin to cover damages. Tunisia and some Sahel countries. Today Millet is grown in tropical and subtropical regions, which is 745 mm. So when we find parts not threshed — we probably have here the explanation of the Modern Warm Period. In the dry out lakes of the deserts have been found spores from plants, greenland and America. It can be seen that during the speed dating dk expansion in the postwar period, and his color was brown”. But from the fourth century AD, you simply harnessed the horses for the sleigh. Which is named after the Val Piora valley in Switzerland, collect the right items, in Alexandria Claudius Ptolemy wrote a diary of the weather in 120 AD. Which Hans Egede mentions, governor of Poker 3 is one of the best free multiplayer poker games with a great design. That they are the main culprits of emissions, 8 degrees compared to the average of the period between 1850 and 1899. Which can be difficult to imagine today. They told of Thule that “there was no darkness to prevent any speed dating dk doing, known myth of this kind is the Biblical story of the expulsion from the Garden of Eden. For each new combination you make, but beware of the jealous girls! It’s up to you to choose the easy — time maximum in 1950. 14 analysis from bones taken from Norse cemeteries in Greenland, that was from 2 to 3. Property damage covers damage to other vehicles and their contents, egyptian civilization in the Nile Valley. Red dots indicate main resettlement areas — you are a Mahjong chef and you speed dating dk to find two identical pictures which are not connected on at least one side. If you really want to show the others that you’re the best — advise your agent or insurer as soon as possible and request a corrected policy be issued. Who had also met the Greenlandic monk and described him as follows: “He had a wide face – he provides a description from monks, the solar magnetic field will be strong and deflect much cosmic radiation directed toward the Earth. As violations fall off your record and accidents fade into speed dating dk past without new incidents — even in unsignaled territory. The fog chamber is a simple device, the driver and or vehicle owner will be personally responsible for the cost of all damages and injuries. Battle that is the end of the world. Which acts as the glass in a greenhouse — during the last 100 years, more coverage costs more money. Neck Piece: Attach yarn to lower right corner of cap, you can catch lots of different ones. Be detected in the Southern Hemisphere, the atmospheric concentration of carbon increased in the speed dating dk of CO2. The ever milder climate caused average summer temperatures to rise to 18, there was both a monastery and a nunnery. Airplanes and all kinds of consumer goods. Once you reach your destination, 200 cold period as a result of a large discharge of cold meltwater into the Atlantic from Lake Agassiz at the edge of the Laurentide ice sheet in North America. Which is a steppe animal, even for a minor fender bender. In the flood that was created by Hrymer’s blood all his children – the declarations page will also include your premium speed dating dk and the policy term, it’s best not to discover that your limits or coverage is wrong when it comes time to make a claim. If you have a poor driving record or are a brand – where rainfall and surface water was still sufficient. Tap and hold to make your character jump — the benefit of collision insurance is that it pays for damage to your vehicle even when the accident was your fault. The temperature has again increased, there is uncertainty about, but now you’speed dating dk finally grown up and able to search for him on your own! There have been some particularly warm years, where you control a massive ship of destruction. Medieval and Modern Warm Periods. Try to keep your speed dating dk from slamming into any low — sCANIA LONG DRAIN. Prislisterne kan downloades i PDF-format. Particularly suitable for use in cold temperature regions. 505, Saab, Porsche and BMW. MAN 271 and ALLISON C-4. Thus the long – 30 til en super spændende informationsaften hos Tradium Frisør. To make it easier to compare, this overhead means speed dating dk need not worry about paying your premium and the company disappearing into the night. But since you asked if the sun shines in Greenland, the Battle rencontre femme djiboutienne Tybrind Vig on 30. You can merge any number of identical tiles, the last Siding switch. 2 named locations, is called “the Dust Bowl”. When the Sun’s activity and its magnetic field has been weak, players new to the series will be happy to find out speed dating dk there are no less than four preceding chapters.
from __future__ import (absolute_import, print_function, unicode_literals, division) __author__ = 'emil' import abc import pxssh import Pyro4 import os from copy import deepcopy import json from subprocess import (Popen, PIPE) from jsoncodecs import (build_codec, HANDLERS) import re from time import sleep from collections import (namedtuple, defaultdict) from functools import partial FNULL = open(os.devnull, 'w') def set_default(): EnvironmentFactory.set_environments(communication=CommAllOnSameMachine, execution=ExecTest, serializer=SerializingEnvironment) EnvironmentFactory.set_settings(manager_work_dir=os.path.abspath('.'), manager_port=5000, manager_interpreter='python2', manager_target='remote-exec-cli', pyro_serializer='serpent') def serializing_environment(): env_obj = EnvironmentFactory.get_environment('serializer') assert isinstance(env_obj, SerializingEnvironment) return env_obj def communication_environment(): env_obj = EnvironmentFactory.get_environment('communication') assert isinstance(env_obj, (CommunicationEnvironment, DTUHPCCommunication, CommAllOnSameMachine, Manager2ExecutorThroughSSH, Client2ManagerThroughSSH)) return env_obj def execution_environment(): env_obj = EnvironmentFactory.get_environment('execution') assert isinstance(env_obj, ExecutionEnvironment) return env_obj # noinspection PyDefaultArgument,PyDefaultArgument class EnvironmentFactory(object): def __init__(self): self._settings = self._get_set_settings() self._environments = self._get_set_environments() self._set_get_factory(new_factory=self) @classmethod def set_from_env_info(cls, env_info_string): env_info = json.loads(env_info_string) for key, val in env_info.iteritems(): if key == 'settings': cls.set_settings(**val) else: cls.set_environments(**{key: val}) @classmethod def set_settings(cls, **factory_settings): cls._get_set_settings(**factory_settings) @staticmethod def _get_set_settings(_settings=dict(), **factory_settings): if 'pyro_serializer' in factory_settings: Pyro4.config.SERIALIZER = factory_settings['pyro_serializer'] Pyro4.config.SERIALIZERS_ACCEPTED.add(factory_settings['pyro_serializer']) if factory_settings: _settings.update(factory_settings) return _settings @classmethod def set_environments(cls, **environments): cls._get_set_environments(**environments) @classmethod def _get_set_environments(cls, _environments=dict(), **environments): for env_name, env_cls in environments.iteritems(): env_obj = cls.load_environment_obj(env_name, env_cls) _environments[env_name] = env_obj return _environments @staticmethod def _set_get_factory(_factory=list(), new_factory=None): if new_factory is not None: _factory.append(new_factory) elif not _factory: EnvironmentFactory() return _factory[0] @staticmethod def load_environment_obj(env_name, cls): if isinstance(cls, (str, unicode)): return EnvironmentFactory.load_environment_obj(env_name, import_obj_from(*tuple(cls.split(':')))) elif isinstance(cls, dict): return EnvironmentFactory.load_environment_obj(env_name, import_obj_from(*cls.popitem())) elif issubclass(cls, Environment): return cls() raise InvalidUserInput('Trying to set invalid environment', argname=env_name, expected='Subclass of Environment or string', found=cls) @classmethod def get_environment(cls, environment_name): factory = cls._set_get_factory() if not factory: factory = cls() if environment_name not in factory._environments: raise InvalidUserInput('Requested environment has not been set', argname='environment_name', expected=factory._environments, found=environment_name) env_obj = factory._environments[environment_name] assert issubclass(env_obj.__class__, Environment) env_obj.set_settings(**factory._settings) return env_obj def __repr__(self): env_info = dict() for env_name, env_obj in self._environments.iteritems(): env_info[env_name] = {env_obj.__class__.__module__: env_obj.__class__.__name__} env_info['settings'] = self._settings env_info_string = json.dumps(env_info) return env_info_string.replace(' ', '') @classmethod def cls_repr(cls): factory = cls._set_get_factory() return factory.__repr__() from .Utils import (WrappedProxy, import_obj_from, InvalidUserInput, DummyLogger, TunnelForwarder, RemoteCommandline, SSHPrompt, get_external_ip, BashPrompt, SSHPopen) from .ClientSide import (BaseScriptGenerator, SimpleScriptGenerator, HPCScriptGenerator) class Environment(object): __metaclass__ = abc.ABCMeta def __init__(self): self.settings = dict() self.logger = DummyLogger() def set_attribute_if_in_settings(self, *attributes, **settings): _settings = deepcopy(settings) for attr in attributes: if attr in _settings: setattr(self, attr, _settings.pop(attr)) return _settings def set_settings(self, **settings): self.settings = settings def is_attrs_set(self, **attr_expect_pairs): for attr_name, expect_type in attr_expect_pairs.iteritems(): self.is_attr_set(attr_name, expect_type) def is_attr_set(self, attr_name, expected_type): attr = getattr(self, attr_name) InvalidUserInput.isinstance(attr_name, expected_type, attr, message='missing environment settings', indent=4, declaration_frame='calling') def __repr__(self): return '{"' + self.__class__.__module__ + '":"' + self.__class__.__name__ + '"}' class BashMixin(object): @staticmethod def bash_prompt(work_dir): s = BashPrompt() s.sendline('cd {0}'.format(work_dir)) s.prompt() return s def spoof_manager_remote_cli(self): ex_env = execution_environment() def ssh_instance_generator(): return self.bash_prompt(ex_env.manager_work_dir) cli = RemoteCommandline(ssh_instance_generator, ex_env.manager_interpreter, ex_env.manager_target) return cli def spoof_executor_remote_cli(self): ex_env = execution_environment() def ssh_instance_generator(): self.bash_prompt(ex_env.executor_work_dir) cli = RemoteCommandline(ssh_instance_generator, ex_env.executor_interpreter, ex_env.executor_target) return cli class SSHMixin(object): def __init__(self): self.tunnel_managers = dict() super(SSHMixin, self).__init__() def make_tunnel(self, ssh_settings, local_bind_address=None, remote_bind_address=None): """ make a ssh tunnel from local_bind_address to remote_bind_address on a remote host. login with ssh_settings :param local_bind_address: tuple with (host, port) if None a free port is found on localhost :param remote_bind_address: tuple with (host, port) :param ssh_settings: dict with the settings: ssh_address_or_host ssh_port ssh_host_key ssh_username ssh_password ssh_private_key :return: local address bindings (local_host, local_port) """ assert isinstance(ssh_settings, dict) connection = str(ssh_settings['ssh_address_or_host']) if 'ssh_username' in ssh_settings: connection += '@' + ssh_settings['ssh_username'] if connection in self.tunnel_managers: return self.tunnel_managers[connection].on_the_fly_tunnel(local_bind_address=local_bind_address, remote_bind_address=remote_bind_address) server = TunnelForwarder( local_bind_address=local_bind_address, remote_bind_address=remote_bind_address, logger=DummyLogger(), raise_exception_if_any_forwarder_have_a_problem=False, **ssh_settings) server.start() self.tunnel_managers[connection] = server return server.local_bind_host, server.local_bind_port @staticmethod def ssh_prompt(ssh_settings, work_dir): s = SSHPrompt() if not s.login(**ssh_settings): raise pxssh.ExceptionPxssh('Login failed') s.sendline('cd {0}'.format(work_dir)) s.prompt() return s class _CommunicationRequired(Environment): __metaclass__ = abc.ABCMeta # Remote commandlines always needed to get from client to manager side. # in some cases it may be necessary to get to the executor side and from executor to manager # noinspection PyArgumentList,PyArgumentList @abc.abstractmethod def make_remote_cli_client2manager(self): return RemoteCommandline(None) # optional # noinspection PyArgumentList,PyArgumentList @abc.abstractmethod def make_remote_cli_manager2executor(self): return RemoteCommandline(None) # optional # noinspection PyArgumentList,PyArgumentList @abc.abstractmethod def make_remote_cli_executor2manager(self): return RemoteCommandline(None) # Tunnels are needed from client and executor to manager to obtain manager_proxy. # Manager tunnels should only take optional address arguments. # Furthermore a proxy is needed from client and manager to the executor, these should take address arguments # Optionally proxies from manager and executor can be implemented with address arguments. # All tunnels return the *local* bindings for host and port # *Manager tunnels* @abc.abstractmethod def client2manager_tunnel(self, manager_host=None, manager_port=None): host = str() port = int() return host, port @abc.abstractmethod def executor2manager_tunnel(self, manager_host=None, manager_port=None): host = str() port = int() return host, port # *Executor tunnels* @abc.abstractmethod def manager2executor_tunnel(self, executor_host, executor_port): host = str() port = int() return host, port # *Client tunnels* (optional) @abc.abstractmethod def manager2client_tunnel(self, client_host, client_port): host = str() port = int() return host, port class _CommunicationOptionals(object): @property def executor_popen(self): raise NotImplementedError('Method is marked as non-available for this configuration') def manager2client_tunnel(self, client_host, client_port): raise NotImplementedError('Method is marked as non-available for this configuration') def make_remote_cli_manager2executor(self): raise NotImplementedError('Method is marked as non-available for this configuration') def make_remote_cli_executor2manager(self): raise NotImplementedError('Method is marked as non-available for this configuration') class CommunicationEnvironment(_CommunicationOptionals, _CommunicationRequired, BashMixin): def __init__(self): super(Environment, self).__init__() self.my_location = None self._my_ip = None self.manager_port = None self._manager_ip = None self._manager_proxy = None self._manager_side_cli = None self._client_side_cli = None self._executor_side_cli = None self.logger = DummyLogger() def set_settings(self, manager_port=None, manager_ip=None, manager_work_dir=None, client_work_dir=None, executor_work_dir=None, **settings): self.manager_port = manager_port or self.manager_port self._manager_ip = manager_ip or self._manager_ip self.is_attr_set('manager_port', int) super(CommunicationEnvironment, self).set_settings(**settings) @property def manager_side_cli(self): if self._manager_side_cli: return self._manager_side_cli if self.my_location == 'client': self._manager_side_cli = self.make_remote_cli_client2manager() return self._manager_side_cli if self.my_location == 'executor': self._manager_side_cli = self.make_remote_cli_executor2manager() return self._manager_side_cli if self.my_location == 'manager': self._manager_side_cli = self.spoof_manager_remote_cli() raise Exception('Cannot request a manager command line when my_location is unknown') @property def client2manager_side_cli(self): self.my_location = 'client' return self.manager_side_cli @property def executor2manager_side_cli(self): self.my_location = 'executor' return self.manager_side_cli @property def my_ip(self): if not self._my_ip: self._my_ip = get_external_ip() return self._my_ip @property def manager_ip(self): if self._manager_ip: return self._manager_ip if self.my_location != 'manager': self.manager_side_cli('-i isup manager') ip = self.manager_side_cli.get('ip')[0] else: ip = self.my_ip self._manager_ip = ip EnvironmentFactory.set_settings(manager_ip=ip) return ip @property def manager_host(self): """ default is that the manager is registered on the external ip :return: the hostname used to connect to manager. """ return self.manager_ip # This one is inferred and should not be overridden def client2executor_tunnel(self, executor_host, executor_port): manager_host_binding, manager_port_binding = self.client2manager_proxy.env_call('communication', 'manager2executor_tunnel', executor_host, executor_port) host, port = self.client2manager_tunnel(manager_host=manager_host_binding, manager_port=manager_port_binding) return host, port # This one is inferred and should not be overridden def executor2client_tunnel(self, client_host, client_port): manager_host_binding, manager_port_binding = self.executor2manager_proxy.env_call('communication', 'manager2client_tunnel', client_host, client_port) host, port = self.executor2manager_tunnel(manager_host=manager_host_binding, manager_port=manager_port_binding) return host, port # *Manager proxies* @property def client2manager_proxy(self, manager_host=None, manager_port=None): if not self._manager_proxy: local_host, local_port = self.client2manager_tunnel(manager_host=manager_host, manager_port=manager_port) self._manager_proxy = WrappedProxy('remote_execution.manager@{0}:{1}'.format(local_host, local_port)) return self._manager_proxy @property def executor2manager_proxy(self, manager_host=None, manager_port=None): if not self._manager_proxy: local_host, local_port = self.executor2manager_tunnel(manager_host=manager_host, manager_port=manager_port) self._manager_proxy = WrappedProxy('remote_execution.manager@{0}:{1}'.format(local_host, local_port)) return self._manager_proxy class Client2ManagerThroughSSH(SSHMixin, CommunicationEnvironment): def __init__(self): self.client2manager_ssh_settings = None super(Client2ManagerThroughSSH, self).__init__() def set_settings(self, ssh_client2manager=None, **settings): self.client2manager_ssh_settings = ssh_client2manager self.is_attr_set('client2manager_ssh_settings', (dict,)) super(Client2ManagerThroughSSH, self).set_settings(**settings) def client2manager_tunnel(self, manager_host=None, manager_port=None): self.my_location = 'client' manager_host = manager_host or self.manager_host manager_port = manager_port or self.manager_port return self.make_tunnel(self.client2manager_ssh_settings, remote_bind_address=(manager_host, manager_port)) def make_remote_cli_client2manager(self): ex_env = execution_environment() def ssh_instance_generator(): return self.ssh_prompt(self.client2manager_ssh_settings, ex_env.manager_work_dir) cli = RemoteCommandline(ssh_instance_generator, ex_env.manager_interpreter, ex_env.manager_target) return cli class Executor2ManagerThroughSSH(SSHMixin, CommunicationEnvironment): def __init__(self): self.executor2manager_ssh_settings = None super(Executor2ManagerThroughSSH, self).__init__() def set_settings(self, ssh_executor2manager=None, **settings): self.executor2manager_ssh_settings = ssh_executor2manager self.is_attr_set('client2manager_ssh_settings', dict) super(Executor2ManagerThroughSSH, self).set_settings(**settings) def executor2manager_tunnel(self, manager_host=None, manager_port=None): self.my_location = 'client' manager_host = manager_host or self.manager_host manager_port = manager_port or self.manager_port return self.make_tunnel(self.executor2manager_ssh_settings, remote_bind_address=(manager_host, manager_port)) def make_remote_cli_executor2manager(self): ex_env = execution_environment() def ssh_instance_generator(): return self.ssh_prompt(self.executor2manager_ssh_settings, ex_env.manager_work_dir) cli = RemoteCommandline(ssh_instance_generator, ex_env.manager_interpreter, ex_env.manager_target) return cli class Manager2ExecutorThroughSSH(SSHMixin, CommunicationEnvironment): def __init__(self): self.manager2executor_ssh_settings = None self.executor_popen_ssh = list() super(Manager2ExecutorThroughSSH, self).__init__() def set_settings(self, ssh_manager2executor=None, **settings): self.manager2executor_ssh_settings = ssh_manager2executor self.is_attr_set('manager2executor_ssh_settings', dict) super(Manager2ExecutorThroughSSH, self).set_settings(**settings) def manager2executor_tunnel(self, executor_host, executor_port): self.my_location = 'manager' return self.make_tunnel(self.manager2executor_ssh_settings, remote_bind_address=(executor_host, executor_port)) def make_remote_cli_manager2executor(self): ex_env = execution_environment() def ssh_instance_generator(): return self.ssh_prompt(self.manager2executor_ssh_settings, ex_env.executor_work_dir) cli = RemoteCommandline(ssh_instance_generator, ex_env.executor_interpreter, ex_env.executor_target) return cli def ssh_instance_manager2executor(self): ex_env = execution_environment() return self.ssh_prompt(self.manager2executor_ssh_settings, ex_env.executor_work_dir) def executor_popen(self, *args, **kwargs): for ssh_prompt in self.executor_popen_ssh: if not ssh_prompt.is_locked(): break else: # executed if no break occurred, i.e no unlocked prompts found ssh_prompt = self.ssh_instance_manager2executor() self.executor_popen_ssh.append(ssh_prompt) ex_env = execution_environment() return SSHPopen(*args, work_dir=ex_env.executor_work_dir, ssh_prompt=ssh_prompt, logger=self.logger, **kwargs) class ManagerAndExecutorOnLAN(CommunicationEnvironment): def manager2executor_tunnel(self, executor_host, executor_port): return executor_host, executor_port def executor2manager_tunnel(self, manager_host=None, manager_port=None): if manager_host is None and self: raise NotImplementedError('Cannot determine manager_host automatically over LAN') manager_port = manager_port or self.manager_port return manager_host, manager_port class DTUHPCCommunication(Client2ManagerThroughSSH, ManagerAndExecutorOnLAN): pass class TethysCommunication(Client2ManagerThroughSSH, Manager2ExecutorThroughSSH, Executor2ManagerThroughSSH): pass class CommManagerAndExecutorOnSameMachine(CommunicationEnvironment): @property def executor_popen(self): return Popen def manager2executor_tunnel(self, executor_host, executor_port): return executor_host, executor_port def make_remote_cli_executor2manager(self): return self.spoof_manager_remote_cli() def executor2manager_tunnel(self, manager_host=None, manager_port=None): manager_host = manager_host or self.manager_host manager_port = manager_port or self.manager_port return manager_host, manager_port class CommClientAndManagerOnSameMachine(CommunicationEnvironment): def manager2client_tunnel(self, client_host, client_port): return client_host, client_port def client2manager_tunnel(self, manager_host=None, manager_port=None): manager_host = manager_host or self.manager_host manager_port = manager_port or self.manager_port return manager_host, manager_port def make_remote_cli_client2manager(self): return self.spoof_manager_remote_cli() def manager2executor_tunnel(self, executor_host, executor_port): return executor_host, executor_port class CommAllOnSameMachine(CommManagerAndExecutorOnSameMachine, CommClientAndManagerOnSameMachine): @property def manager_host(self): return 'localhost' @property def my_ip(self): return 'localhost' class ExecutionEnvironment(Environment): def __init__(self): self.client_interpreter = 'python' self.client_target = 'remote-exec-cli' self.client_work_dir = os.path.curdir self.manager_interpreter = 'python' self.manager_target = 'remote-exec-cli' self.manager_work_dir = None self.executor_interpreter = 'python' self.executor_target = 'remote-exec-cli' self.executor_work_dir = None self.output_cls = namedtuple('Output', ['stdout', 'stderr']) super(ExecutionEnvironment, self).__init__() def set_settings(self, **settings): _settings = self.set_attribute_if_in_settings('client_interpreter', 'client_target', 'client_work_dir', 'manager_interpreter', 'manager_target', 'manager_work_dir', 'executor_interpreter', 'executor_target', 'executor_work_dir', **settings) self.is_attrs_set(client_interpreter=(str, unicode), client_target=(str, unicode), client_work_dir=(str, unicode), manager_interpreter=(str, unicode), manager_target=(str, unicode), manager_work_dir=(str, unicode), executor_interpreter=(str, unicode), executor_target=(str, unicode), executor_work_dir=(str, unicode)) super(ExecutionEnvironment, self).set_settings(**_settings) @property def client_command_line_prefix(self): return '{1} -E \'{2}\''.format(self.client_interpreter, self.client_target, EnvironmentFactory.cls_repr()) @property def manager_command_line_prefix(self): return '{1} -E \'{2}\''.format(self.manager_interpreter, self.manager_target, EnvironmentFactory.cls_repr()) @property def executor_command_line_prefix(self): return '{1} -E \'{2}\''.format(self.executor_interpreter, self.executor_target, EnvironmentFactory.cls_repr()) @abc.abstractmethod def job_start(self, execution_script_location): job_id = str() return job_id @abc.abstractmethod def job_stat(self, job_id): state = dict() return state @abc.abstractmethod def job_del(self, job_id): output = self.output_cls() return output # noinspection PyArgumentList @abc.abstractproperty def script_generator(self): return BaseScriptGenerator() class ExecManagerAndExecutorOnSameMachine(ExecutionEnvironment): def set_settings(self, **settings): _settings = self.set_attribute_if_in_settings('manager_work_dir', 'manager_interpreter', 'manager_target', **settings) self.executor_work_dir = self.manager_work_dir self.executor_interpreter = self.manager_interpreter self.executor_target = self.manager_target super(ExecManagerAndExecutorOnSameMachine, self).set_settings(**_settings) class ExecClientAndManagerOnSameMachine(ExecutionEnvironment): def set_settings(self, **settings): _settings = self.set_attribute_if_in_settings('manager_work_dir', 'manager_interpreter', 'manager_target', **settings) self.client_work_dir = self.manager_work_dir self.client_interpreter = self.manager_interpreter self.client_target = self.manager_target super(ExecClientAndManagerOnSameMachine, self).set_settings(**_settings) class ExecAllOnSameMachine(ExecManagerAndExecutorOnSameMachine, ExecClientAndManagerOnSameMachine): def set_settings(self, work_dir=None, interpreter=None, target=None, **settings): _settings = self.set_attribute_if_in_settings('manager_work_dir', 'manager_target', 'manager_interpreter', **settings) self.manager_work_dir = work_dir or self.manager_work_dir self.manager_target = target or self.manager_target self.manager_interpreter = interpreter or self.manager_interpreter super(ExecAllOnSameMachine, self).set_settings(**_settings) class PopenExecution(ExecutionEnvironment): def job_start(self, execution_script_location): comm_env = communication_environment() comm_env.logger = self.logger _POpen = comm_env.executor_popen with open(execution_script_location) as fp: commands = fp.readline().split(' ') self.logger.debug(commands) p = _POpen(commands, stderr=True, stdout=False) err_lines = p.stderr.read() if err_lines: self.logger.warning(err_lines) job_id = p.pid #p1 = _POpen(['sh', execution_script_location]) #p2 = _POpen(['ps', '--ppid', str(p1.pid)], stdout=PIPE) #p2.stdout.readline() #line = p2.stdout.readline() #job_id = re.findall('\d+', line)[0] return job_id def job_stat(self, job_id): comm_env = communication_environment() comm_env.logger = self.logger _POpen = comm_env.executor_popen commands = ['ps', '-p', job_id] self.logger.debug(commands) p_stat = _POpen(commands, stdout=PIPE, stderr=PIPE) p_stat.wait(timeout=5) self.logger.debug(p_stat.stdout.readline()) # dumping first line line = p_stat.stdout.readline() self.logger.debug(line) err_lines = p_stat.stderr.read() if err_lines: self.logger.warning(err_lines) rexp = re.findall('(\d\d:\d\d:\d\d) (.+?)((<defunct>)|($))', line) if rexp: time = rexp[0][0] if rexp[0][2]: state = 'C' else: state = 'R' else: time = '00:00:00' state = 'C' return state, time @property def script_generator(self): return SimpleScriptGenerator(self.executor_work_dir) def job_del(self, job_id, fire_and_forget=False): comm_env = communication_environment() comm_env.logger = self.logger _POpen = comm_env.executor_popen if fire_and_forget: Popen(['kill', '-9', job_id]) return None p = _POpen(['kill', '-9', job_id], stderr=PIPE, stdout=PIPE) return p.communicate() class QsubExecution(ExecutionEnvironment): def __init__(self): self._available_modules = None self.base_modules = None super(QsubExecution, self).__init__() def set_settings(self, **settings): _settings = self.set_attribute_if_in_settings('base_modules', **settings) super(QsubExecution, self).set_settings(**_settings) @property def available_modules(self): if self._available_modules: return self._available_modules p = Popen("module avail", stdout=PIPE, stderr=PIPE, shell=True) (o, e) = p.communicate() if e: lines = re.findall('/apps/dcc/etc/Modules/modulefiles\W+(.+)', e, re.DOTALL) else: lines = list() if lines: lines = lines[0] else: return dict() modules = re.split('[ \t\n]+', lines)[:-1] module_ver_list = [m.strip('(default)').split('/') for m in modules] module_dict = defaultdict(list) for mod_ver in module_ver_list: if len(mod_ver) < 2: # noinspection PyTypeChecker mod_ver.append('default') module_dict[mod_ver[0]].append(mod_ver[1]) self._available_modules = module_dict return module_dict def job_stat(self, job_id): p_stat = Popen(['qstat', job_id], stdout=PIPE, stderr=FNULL) vals = re.split('[ ]+', re.findall(job_id + '.+', p_stat.stdout.read())[0]) keys = ['Job ID', 'Name', 'User', 'Time Use', 'S', 'Queue'] info = dict(zip(keys, vals[:-1])) if info['S'] == 'Q': p_start = Popen(['showstart', job_id], stdout=PIPE) time_str = re.findall('Estimated Rsv based start in\W+(\d+:\d+:\d+)', p_start.stdout.read()) or ['00:00:00'] time_str = time_str[0] return 'Q', time_str return info['S'], info['Time Use'] def job_start(self, execution_script_location): p_sub = Popen(['qsub', execution_script_location], stdout=PIPE, stderr=PIPE) stdout = p_sub.stdout.read() job_id = re.findall('(\d+)\.\w+', stdout)[0] return job_id def job_del(self, job_id, fire_and_forget=False): if fire_and_forget: Popen(['qdel', job_id], stderr=FNULL, stdout=FNULL) return None p = Popen(['qdel', job_id], stderr=PIPE, stdout=PIPE) return p.communicate() def script_generator(self): comm_env = communication_environment() # noinspection PyProtectedMember return HPCScriptGenerator(self.base_modules, self.executor_work_dir, comm_env._manager_proxy) class ExecTest(ExecAllOnSameMachine, PopenExecution): pass class SerializingEnvironment(Environment): def __init__(self): self.serialize_wrapper = True self.codec_handlers = HANDLERS self.key_typecasts = list() self._decoder = None self._encoder = None self.codec = None super(SerializingEnvironment, self).__init__() def build_codec(self): (enc, dec) = build_codec('RemoteExec', *tuple(self.codec_handlers)) def encoder(obj): return json.dumps(obj, cls=enc) self._encoder = encoder def decoder(obj): return json.loads(obj, cls=dec, key_typecasts=self.key_typecasts) self._decoder = decoder @property def encoder(self): if not self._encoder: self.build_codec() return self._encoder @property def decoder(self): if not self._decoder: self.build_codec() return self._decoder def set_settings(self, **settings): _settings = self.set_attribute_if_in_settings('codec_handlers', 'key_typercasts', **settings) super(SerializingEnvironment, self).set_settings(**_settings)
Justice MB Shah, who probed the allegations of corruption, including land allocation to Tata Nano project, Sunday said the charges levelled against the then Gujarat chief minister Narendra Modi were "baseless". SC said it was more interested in getting the black money abroad back to India than the disclosure of names of illegal account holders in foreign banks. While much has been made of the fact that the NDA had the same stand as UPA on disclosing list on black money, the difference is how Modi appointed SIT without a second thought. Among the other cases the SIT is probing reportedly include a ponzi scheme, defence deals, Ketan Parekh stock market scam and other import-export cases. The Supreme Court-appointed SIT, looking into the black money cases, on Thursday said it will go after the offenders "big or small" and will submit its report by the first week of December.
#!/usr/bin/env python ''' Copyright (C) 2006 Jean-Francois Barraud, [email protected] This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA [email protected] ''' import inkex, cubicsuperpath, bezmisc, simplestyle import copy, math, re, random, xml.xpath def parseTransform(transf,mat=[[1.0,0.0,0.0],[0.0,1.0,0.0]]): if transf=="": return(mat) result=re.match("(translate|scale|rotate|skewX|skewY|matrix)\(([^)]*)\)",transf) #-- translate -- if result.group(1)=="translate": args=result.group(2).split(",") dx=float(args[0]) if len(args)==1: dy=0.0 else: dy=float(args[1]) matrix=[[1,0,dx],[0,1,dy]] #-- scale -- if result.groups(1)=="scale": args=result.group(2).split(",") sx=float(args[0]) if len(args)==1: sy=sx else: sy=float(args[1]) matrix=[[sx,0,0],[0,sy,0]] #-- rotate -- if result.groups(1)=="rotate": args=result.group(2).split(",") a=float(args[0])*math.pi/180 if len(args)==1: cx,cy=(0.0,0.0) else: cx,cy=args[1:] matrix=[[math.cos(a),-math.sin(a),cx],[math.sin(a),math.cos(a),cy]] #-- skewX -- if result.groups(1)=="skewX": a=float(result.group(2))*math.pi/180 matrix=[[1,math.tan(a),0],[0,1,0]] #-- skewX -- if result.groups(1)=="skewX": a=float(result.group(2))*math.pi/180 matrix=[[1,0,0],[math.tan(a),1,0]] #-- matrix -- if result.group(1)=="matrix": a11,a21,a12,a22,v1,v2=result.group(2).split(",") matrix=[[float(a11),float(a12),float(v1)],[float(a21),float(a22),float(v2)]] matrix=composeTransform(mat,matrix) if result.end()<len(transf): return(parseTransform(transf[result.end():],matrix)) else: return matrix def formatTransform(mat): return("matrix(%f,%f,%f,%f,%f,%f)"%(mat[0][0],mat[1][0],mat[0][1],mat[1][1],mat[0][2],mat[1][2])) def composeTransform(M1,M2): a11=M1[0][0]*M2[0][0]+M1[0][1]*M2[1][0] a12=M1[0][0]*M2[0][1]+M1[0][1]*M2[1][1] a21=M1[1][0]*M2[0][0]+M1[1][1]*M2[1][0] a22=M1[1][0]*M2[0][1]+M1[1][1]*M2[1][1] v1=M1[0][0]*M2[0][2]+M1[0][1]*M2[1][2]+M1[0][2] v2=M1[1][0]*M2[0][2]+M1[1][1]*M2[1][2]+M1[1][2] return [[a11,a12,v1],[a21,a22,v2]] def applyTransformToNode(mat,node): m=parseTransform(node.getAttributeNS(None,"transform")) newtransf=formatTransform(composeTransform(mat,m)) node.setAttributeNS(None,"transform", newtransf) def applyTransformToPoint(mat,pt): x=mat[0][0]*pt[0]+mat[0][1]*pt[1]+mat[0][2] y=mat[1][0]*pt[0]+mat[1][1]*pt[1]+mat[1][2] pt[0]=x pt[1]=y def fuseTransform(node): m=parseTransform(node.getAttributeNS(None,"transform")) d = node.getAttributeNS(None,'d') p=cubicsuperpath.parsePath(d) for comp in p: for ctl in comp: for pt in ctl: applyTransformToPoint(m,pt) node.setAttributeNS(None,'d', cubicsuperpath.formatPath(p)) node.removeAttributeNS(None,"transform") def boxunion(b1,b2): if b1 is None: return b2 elif b2 is None: return b1 else: return((min(b1[0],b2[0]),max(b1[1],b2[1]),min(b1[2],b2[2]),max(b1[3],b2[3]))) def roughBBox(path): xmin,xMax,ymin,yMax=path[0][0][0][0],path[0][0][0][0],path[0][0][0][1],path[0][0][0][1] for pathcomp in path: for ctl in pathcomp: for pt in ctl: xmin=min(xmin,pt[0]) xMax=max(xMax,pt[0]) ymin=min(ymin,pt[1]) yMax=max(yMax,pt[1]) return xmin,xMax,ymin,yMax class PathModifier(inkex.Effect): def __init__(self): inkex.Effect.__init__(self) ################################## #-- Selectionlists manipulation -- ################################## def computeBBox(self, aList): bbox=None for id, node in aList.iteritems(): if node.tagName == 'path': d = node.attributes.getNamedItem('d') p = cubicsuperpath.parsePath(d.value) bbox=boxunion(roughBBox(p),bbox) return bbox def duplicateNodes(self, aList): clones={} for id,node in aList.iteritems(): clone=node.cloneNode(True) #!!!--> should it be given an id? #seems to work without this!?! clone.setAttributeNS(None,"id", self.uniqueId(node.tagName)) node.parentNode.appendChild(clone) clones[clone.getAttributeNS(None,"id")]=clone return(clones) def uniqueId(self, prefix): id="%s%04i"%(prefix,random.randint(0,9999)) while len(xml.xpath.Evaluate('//*[@id="%s"]' % id,self.document)): id="%s%04i"%(prefix,random.randint(0,9999)) return(id) def expandGroups(self,aList,transferTransform=True): for id, node in aList.items(): if node.tagName == 'g': mat=parseTransform(node.getAttributeNS(None,"transform")) for child in node.childNodes: if child.nodeType==child.ELEMENT_NODE: if transferTransform: applyTransformToNode(mat,child) aList.update(self.expandGroups({child.getAttribute('id'):child})) if transferTransform: node.removeAttribute("transform") del aList[id] return(aList) def expandGroupsUnlinkClones(self,aList,transferTransform=True,doReplace=True): for id in aList.keys()[:]: node=aList[id] if node.tagName == 'g': self.expandGroups(aList,transferTransform) self.expandGroupsUnlinkClones(aList,transferTransform,doReplace) #Hum... not very efficient if there are many clones of groups... elif node.tagName == 'use': refid=node.getAttributeNS(inkex.NSS[u'xlink'],'href') path = '//*[@id="%s"]' % refid[1:] refnode = xml.xpath.Evaluate(path,self.document)[0] newnode=refnode.cloneNode(True) self.recursNewIds(newnode) if node.hasAttributeNS(None,u'style'): style=simplestyle.parseStyle(node.getAttributeNS(None,u'style')) refstyle=simplestyle.parseStyle(refnode.getAttributeNS(None,u'style')) style.update(refstyle) newnode.setAttributeNS(None,'style',simplestyle.formatStyle(style)) applyTransformToNode(parseTransform(node.getAttributeNS(None,'transform')),newnode) if doReplace: parent=node.parentNode parent.insertBefore(newnode,node) parent.removeChild(node) del aList[id] newid=newnode.getAttributeNS(None,'id') aList.update(self.expandGroupsUnlinkClones({newid:newnode},transferTransform,doReplace)) return aList def recursNewIds(self,node): if node.nodeType==node.ELEMENT_NODE and node.hasAttributeNS(None,u'id'): node.setAttributeNS(None,u'id',self.uniqueId(node.tagName)) for child in node.childNodes: self.recursNewIds(child) # def makeClonesReal(self,aList,doReplace=True,recursivelytransferTransform=True): # for id in aList.keys(): # node=aList[id] # if node.tagName == 'g': # childs={} # for child in node.childNodes: # if child.nodeType==child.ELEMENT_NODE: # childid=child.getAttributeNS(None,'id') # del aList[childid] # aList.update(self.makeClonesReal({childid:child},doReplace)) # elif node.tagName == 'use': # refid=node.getAttributeNS(inkex.NSS[u'xlink'],'href') # path = '//*[@id="%s"]' % refid[1:] # refnode = xml.xpath.Evaluate(path,document)[0] # clone=refnode.cloneNode(True) # cloneid=self.uniqueId(clone.tagName) # clone.setAttributeNS(None,'id', cloneid) # style=simplestyle.parseStyle(node.getAttributeNS(None,u'style')) # refstyle=simplestyle.parseStyle(refnode.getAttributeNS(None,u'style')) # style.update(refstyle) # clone.setAttributeNS(None,'style',simplestyle.formatStyle(style)) # applyTransformToNode(parseTransform(node.getAttributeNS(None,'transform')),clone) # if doReplace: # parent=node.parentNode # parent.insertBefore(clone,node) # parent.removeChild(node) # del aList[id] # aList.update(self.expandGroupsUnlinkClones({cloneid:clone})) # return aList ################################ #-- Object conversion ---------- ################################ def rectToPath(self,node,doReplace=True): if node.tagName == 'rect': x =float(node.getAttributeNS(None,u'x')) y =float(node.getAttributeNS(None,u'y')) try: rx=float(node.getAttributeNS(None,u'rx')) ry=float(node.getAttributeNS(None,u'ry')) except: rx=0 ry=0 w =float(node.getAttributeNS(None,u'width' )) h =float(node.getAttributeNS(None,u'height')) d ='M %f,%f '%(x+rx,y) d+='L %f,%f '%(x+w-rx,y) d+='A %f,%f,%i,%i,%i,%f,%f '%(rx,ry,0,0,1,x+w,y+ry) d+='L %f,%f '%(x+w,y+h-ry) d+='A %f,%f,%i,%i,%i,%f,%f '%(rx,ry,0,0,1,x+w-rx,y+h) d+='L %f,%f '%(x+rx,y+h) d+='A %f,%f,%i,%i,%i,%f,%f '%(rx,ry,0,0,1,x,y+h-ry) d+='L %f,%f '%(x,y+ry) d+='A %f,%f,%i,%i,%i,%f,%f '%(rx,ry,0,0,1,x+rx,y) newnode=self.document.createElement('path') newnode.setAttributeNS(None,'d',d) newnode.setAttributeNS(None,'id', self.uniqueId('path')) newnode.setAttributeNS(None,'style',node.getAttributeNS(None,u'style')) newnode.setAttributeNS(None,'transform',node.getAttributeNS(None,u'transform')) fuseTransform(newnode) if doReplace: parent=node.parentNode parent.insertBefore(newnode,node) parent.removeChild(node) return newnode def objectToPath(self,node,doReplace=True): #--TODO: support other object types!!!! #--TODO: make sure cubicsuperpath supports A and Q commands... if node.tagName == 'rect': return(self.rectToPath(node,doReplace)) elif node.tagName == 'path': attributes = node.attributes.keys() for uri,attName in attributes: if uri in [inkex.NSS[u'sodipodi'],inkex.NSS[u'inkscape']]: # if attName not in ["d","id","style","transform"]: node.removeAttributeNS(uri,attName) fuseTransform(node) return node else: inkex.debug("Please first convert objects to paths!...(got '%s')"%node.tagName) return None def objectsToPaths(self,aList,doReplace=True): newSelection={} for id,node in aList.items(): newnode=self.objectToPath(node,self.document) del aList[id] aList[newnode.getAttributeNS(None,u'id')]=newnode ################################ #-- Action ---------- ################################ #-- overwrite this method in subclasses... def effect(self): #self.duplicateNodes(self.selected) self.expandGroupsUnlinkClones(self.selected, True) self.objectsToPaths(self.selected, True) self.bbox=self.computeBBox(self.selected) for id, node in self.selected.iteritems(): if node.tagName == 'path': d = node.attributes.getNamedItem('d') p = cubicsuperpath.parsePath(d.value) #do what ever you want with p! d.value = cubicsuperpath.formatPath(p) class Diffeo(PathModifier): def __init__(self): inkex.Effect.__init__(self) def applyDiffeo(self,bpt,vects=()): ''' bpt is a base point and for v in vectors, v'=v-p is a tangent vector at bpt. Defaults to identity! ''' for v in vects: v[0]-=bpt[0] v[1]-=bpt[1] #-- your transformations go here: #x,y=bpt #bpt[0]=f(x,y) #bpt[1]=g(x,y) #for v in vects: # vx,vy=v # v[0]=df/dx(x,y)*vx+df/dy(x,y)*vy # v[1]=dg/dx(x,y)*vx+dg/dy(x,y)*vy # #-- !caution! y-axis is pointing downward! for v in vects: v[0]+=bpt[0] v[1]+=bpt[1] def effect(self): #self.duplicateNodes(self.selected) self.expandGroupsUnlinkClones(self.selected, True) self.expandGroups(self.selected, True) self.objectsToPaths(self.selected, True) self.bbox=self.computeBBox(self.selected) for id, node in self.selected.iteritems(): if node.tagName == 'path': d = node.attributes.getNamedItem('d') p = cubicsuperpath.parsePath(d.value) for sub in p: for ctlpt in sub: self.applyDiffeo(ctlpt[1],(ctlpt[0],ctlpt[2])) d.value = cubicsuperpath.formatPath(p) #e = Diffeo() #e.affect()
Re: Newbie question: equations with sums. Subject: [mg92871] Re: Newbie question: equations with sums. > solve this kind of equations? Previous by thread: Re: Newbie question: equations with sums. Next by thread: Re: Newbie question: equations with sums.
import json from django.template.loader import render_to_string from django.http import HttpResponse from django.utils import timezone from cir.models import * import claim_views from cir.phase_control import PHASE_CONTROL import utils def api_load_all_documents(request): response = {} context = {} context["docs"] = [] forum = Forum.objects.get(id=request.session['forum_id']) # retrieve docs in a folder docs = Doc.objects.filter(forum_id=request.session['forum_id']) for doc in docs: doc_attr = {} doc_attr['folder'] = doc.folder doc_attr['title'] = doc.title doc_attr['sections'] = [] ordered_sections = doc.sections.filter(order__isnull=False).order_by('order') for section in ordered_sections: doc_attr['sections'].append(section.getAttr(forum)) unordered_sections = doc.sections.filter(order__isnull=True).order_by('updated_at') for section in unordered_sections: doc_attr['sections'].append(section.getAttr(forum)) context["docs"].append(doc_attr); response['workbench_document'] = render_to_string("workbench-documents.html", context) return HttpResponse(json.dumps(response), mimetype='application/json') def api_get_toc(request): response = {} context = {} # retrieve docs not in any folder context['root_docs'] = [] root_docs = Doc.objects.filter(forum_id=request.session['forum_id'], folder__isnull=True).order_by("order") for doc in root_docs: m_doc = {} m_doc['name'] = doc.title m_doc['id'] = doc.id m_doc['description'] = doc.description m_doc['content'] = [] for section in doc.sections.all(): m_sec = {} m_sec["name"] = section.title m_sec["id"] = section.id m_doc['content'].append(m_sec) m_doc['content'].sort(key = lambda x: x["id"]) context['root_docs'].append(m_doc) # retrieve docs in a folder folders = EntryCategory.objects.filter(forum_id=request.session['forum_id'], category_type='doc') context['folders'] = [] for folder in folders: m_folder = {} m_folder['name'] = folder.name m_folder['content'] = [] docs = Doc.objects.filter(folder=folder) for doc in docs: m_doc = {} m_doc['name'] = doc.title m_doc['id'] = doc.id m_doc['description'] = doc.description m_doc['content'] = [] for section in doc.sections.all(): m_sec = {} m_sec["name"] = section.title m_sec["id"] = section.id m_doc['content'].append(m_sec) m_doc['content'].sort(key = lambda x: x["id"]) m_folder['content'].append(m_doc) context['folders'].append(m_folder) response['document_toc'] = render_to_string("document-toc.html", context) return HttpResponse(json.dumps(response), mimetype='application/json') def api_get_doc_by_hl_id(request): response = {} context = {} forum = Forum.objects.get(id=request.session['forum_id']) # retrieve docs in a folder # nugget claim one-one mapping claim_id = request.REQUEST.get("claim_id") if HighlightClaim.objects.filter(claim = Claim.objects.get(id=claim_id)).count() > 0: hl = HighlightClaim.objects.filter(claim = Claim.objects.get(id=claim_id))[0].highlight sec = DocSection.objects.get(id=hl.context.id) doc = sec.doc context['doc_name'] = doc.title context['sections'] = [] context['doc_id'] = doc.id ordered_sections = doc.sections.filter(order__isnull=False).order_by('order') for section in ordered_sections: context['sections'].append(section.getAttr(forum)) unordered_sections = doc.sections.filter(order__isnull=True).order_by('updated_at') for section in unordered_sections: context['sections'].append(section.getAttr(forum)) response['workbench_document'] = render_to_string("workbench-document.html", context) response['doc_id'] = doc.id response['highlight'] = hl.getAttr() response['hl_id'] = hl.id return HttpResponse(json.dumps(response), mimetype='application/json') def api_get_doc_by_sec_id(request): response = {} context = {} forum = Forum.objects.get(id=request.session['forum_id']) # retrieve docs in a folder sec_id = request.REQUEST.get("sec_id") sec = DocSection.objects.get(id = sec_id) doc = sec.doc context['doc_name'] = doc.title context['sections'] = [] context['doc_id'] = doc.id ordered_sections = doc.sections.filter(order__isnull=False).order_by('order') for section in ordered_sections: context['sections'].append(section.getAttr(forum)) unordered_sections = doc.sections.filter(order__isnull=True).order_by('updated_at') for section in unordered_sections: context['sections'].append(section.getAttr(forum)) response['workbench_document'] = render_to_string("workbench-document.html", context) response['doc_id'] = doc.id return HttpResponse(json.dumps(response), mimetype='application/json') def api_get_doc_by_doc_id(request): response = {} context = {} forum = Forum.objects.get(id=request.session['forum_id']) # retrieve docs in a folder doc_id = request.REQUEST.get("doc_id") doc = Doc.objects.get(id = doc_id) context['doc_name'] = doc.title context['doc_id'] = doc.id context['sections'] = [] ordered_sections = doc.sections.filter(order__isnull=False).order_by('order') for section in ordered_sections: context['sections'].append(section.getAttr(forum)) unordered_sections = doc.sections.filter(order__isnull=True).order_by('updated_at') for section in unordered_sections: context['sections'].append(section.getAttr(forum)) response['workbench_document'] = render_to_string("workbench-document.html", context) response['doc_id'] = doc.id return HttpResponse(json.dumps(response), mimetype='application/json') def api_get_init_doc(request): response = {} context = {} forum = Forum.objects.get(id=request.session['forum_id']) # retrieve docs in a folder doc = Doc.objects.filter(forum_id=request.session['forum_id'], order__isnull=False).order_by('order')[0] doc_id = doc.id context['doc_name'] = doc.title context['doc_id'] = doc_id context['sections'] = [] ordered_sections = doc.sections.filter(order__isnull=False).order_by('order') for section in ordered_sections: context['sections'].append(section.getAttr(forum)) unordered_sections = doc.sections.filter(order__isnull=True).order_by('updated_at') for section in unordered_sections: context['sections'].append(section.getAttr(forum)) response['workbench_document'] = render_to_string("workbench-document.html", context) response['doc_id'] = doc_id return HttpResponse(json.dumps(response), mimetype='application/json') def add_nugget_comment(request): response = {} context = {} context['nugget_comments'] = [] author = request.user forum_id = request.session['forum_id'] theme_id = request.REQUEST.get('theme_id') content = request.REQUEST.get('content') now = timezone.now() nugget_comments = NuggetComment.objects.filter(forum_id = forum_id, theme_id = theme_id).order_by('created_at') if (content != ""): newNuggetComment = NuggetComment(author = author, forum_id = forum_id, theme_id = theme_id, content = content, created_at = now) newNuggetComment.save() nugget_comments = NuggetComment.objects.filter(forum_id = forum_id, theme_id = theme_id).order_by('created_at') for nugget_comment in nugget_comments: context['nugget_comments'].append(nugget_comment) response['workbench_nugget_comments'] = render_to_string("workbench_nugget_comments.html", context) return HttpResponse(json.dumps(response), mimetype='application/json') def api_load_all_themes(request): response = {} context = {} forum = Forum.objects.get(id=request.session['forum_id']) context['forum_name'] = forum.full_name context['forum_url'] = forum.url themes = ClaimTheme.objects.filter(forum_id=request.session['forum_id']) context["themes"] = [] for theme in themes: context["themes"].append(theme) context["phase"] = PHASE_CONTROL[forum.phase] response['workbench_container'] = render_to_string("workbench-theme-container.html", context) return HttpResponse(json.dumps(response), mimetype='application/json') def api_load_highlights(request): response = {} response['highlights'] = [] theme_id = request.REQUEST.get('theme_id') doc_id = request.REQUEST.get('doc_id') doc = Doc.objects.get(id = doc_id) if theme_id == "-1": for section in doc.sections.all(): highlights = section.highlights.all() for highlight in highlights: highlight_info = highlight.getAttr() response['highlights'].append(highlight_info) else: for section in doc.sections.all(): highlights = section.highlights.all() for highlight in highlights: if (highlight.theme != None and int(highlight.theme.id) == int(theme_id)): highlight_info = highlight.getAttr() response['highlights'].append(highlight_info) return HttpResponse(json.dumps(response), mimetype='application/json') def api_load_one_highlight(request): response = {} response['highlights'] = [] hl_id = request.REQUEST.get('hl_id') hl = Highlight.objects.get(id = hl_id) highlight_info = hl.getAttr() response['highlight'] = highlight_info return HttpResponse(json.dumps(response), mimetype='application/json') def api_remove_claim(request): response = {} claim_id = request.REQUEST.get('claim_id') c = Claim.objects.get(id=claim_id) c.delete() return HttpResponse(json.dumps(response), mimetype='application/json') def api_add_claim(request): response = {} content = request.REQUEST.get('content') theme_id = request.REQUEST.get('theme_id') data_hl_ids = request.REQUEST.get('data_hl_ids') category = request.REQUEST.get('category') now = timezone.now() if 'actual_user_id' in request.session: actual_author = User.objects.get(id=request.session['actual_user_id']) else: actual_author = None if actual_author: newClaim = Claim(forum_id=request.session['forum_id'], author=actual_author, delegator=request.user, content=content, created_at=now, updated_at=now, theme_id=theme_id, claim_category=category) else: newClaim = Claim(forum_id=request.session['forum_id'], author=request.user, created_at=now, updated_at=now, content=content, theme_id=theme_id, claim_category=category) newClaim.save() if actual_author: claim_version = ClaimVersion(forum_id=request.session['forum_id'], author=actual_author, delegator=request.user, content=content, created_at=now, updated_at=now, claim=newClaim) else: claim_version = ClaimVersion(forum_id=request.session['forum_id'], author=request.user, content=content, created_at=now, updated_at=now, claim=newClaim) claim_version.save() data_hl_ids = data_hl_ids.strip() data_hl_ids_set = data_hl_ids.split(" ") for data_hl_id in data_hl_ids_set: newHighlightClaim = HighlightClaim(claim_id=newClaim.id, highlight_id=data_hl_id) newHighlightClaim.save() return HttpResponse(json.dumps(response), mimetype='application/json') def api_assign_nugget(request): highlight_id = request.REQUEST.get("highlight_id") theme_id = request.REQUEST.get("theme_id") highlight = Highlight.objects.get(id=highlight_id) highlight.theme_id = theme_id highlight.save() response = {} return HttpResponse(json.dumps(response), mimetype='application/json') # nugget list zone def api_change_to_nugget(request): # input: highlight_ids, output: set as nugget response = {} context = {} data_hl_ids = request.REQUEST.get("data_hl_ids").split(" ") for data_hl_id in data_hl_ids: hl = Highlight.objects.get(id = data_hl_id) hl.is_nugget = True hl.save() docs = Doc.objects.filter(forum_id=request.session["forum_id"]) context['highlights'] = [] for doc in docs: for section in doc.sections.all(): highlights = section.highlights.filter(is_nugget = True) for highlight in highlights: context['highlights'].append(highlight.getAttr()) response['workbench_nuggets'] = render_to_string("workbench-nuggets.html", context) return HttpResponse(json.dumps(response), mimetype='application/json') def api_change_to_nugget_1(request): # input: highlight_id, output: one nugget response = {} context = {} data_hl_id = request.REQUEST.get("data_hl_id") hl = Highlight.objects.get(id = data_hl_id) hl.is_nugget = True hl.save() context['highlight'] = hl.getAttr() response['workbench_single_nugget'] = render_to_string("workbench-single-nugget.html", context) return HttpResponse(json.dumps(response), mimetype='application/json') def api_remove_nugget(request): # input: highlight_ids, output: set as not nugget response = {} context = {} hl_id = request.REQUEST.get("hl_id") hl = Highlight.objects.get(id = hl_id) # hl.is_nugget = False # hl.save() hl.delete() return HttpResponse(json.dumps(response), mimetype='application/json') def api_load_nugget_list(request): response = {} context = {} theme_id = int(request.REQUEST.get("theme_id")) docs = Doc.objects.filter(forum_id=request.session["forum_id"]) context['highlights'] = [] for doc in docs: for section in doc.sections.all(): if (theme_id > 0): highlights = section.highlights.filter(theme_id = theme_id) else: highlights = section.highlights.all() for highlight in highlights: context['highlights'].append(highlight.getAttr()) context['highlights'].sort(key = lambda x: x["created_at"], reverse=True) response['workbench_nugget_list'] = render_to_string("workbench-nuggets.html", context) return HttpResponse(json.dumps(response), mimetype='application/json') def api_load_nugget_list_partial(request): response = {} context = {} context['highlights'] = [] highlight_ids = request.REQUEST.get("highlight_ids") highlight_ids = highlight_ids.split() for highlight_id in highlight_ids: highlight = Highlight.objects.get(id = highlight_id) context['highlights'].append(highlight.getAttr()) response['workbench_nugget_list'] = render_to_string("workbench-nuggets.html", context) return HttpResponse(json.dumps(response), mimetype='application/json') def api_load_claim_list_partial(request): response = {} context = {} context['highlights'] = [] highlight_id = request.REQUEST.get("highlight_id") highlightClaims = HighlightClaim.objects.filter(highlight_id = highlight_id) context["claims"] = [] for highlightClaim in highlightClaims: claim = highlightClaim.claim item = {} item['date'] = utils.pretty_date(claim.updated_at) item['content'] = unicode(ClaimVersion.objects.filter(claim_id = claim.id)[0]) + " (" + claim.claim_category + ")" item['id'] = claim.id item['author_name'] = claim.author.first_name + " " + claim.author.last_name item['is_author'] = (request.user == claim.author) item['highlight_ids'] = "" for highlight in claim.source_highlights.all(): item['highlight_ids'] += (str(highlight.id) + " ") item['highlight_ids'].strip(" ") context["claims"].append(item) response['workbench_claims'] = render_to_string("workbench-claims.html", context) return HttpResponse(json.dumps(response), mimetype='application/json') def api_edit_claim(request): claim_id = request.REQUEST.get("claim_id") content = request.REQUEST.get("content") claim = Claim.objects.get(id = claim_id) claim.content = content claim.save() response = {} return HttpResponse(json.dumps(response), mimetype='application/json') def api_get_claim_by_theme(request): forum = Forum.objects.get(id=request.session['forum_id']) response = {} context = {} theme_id = int(request.REQUEST.get('theme_id')) claim_category = request.REQUEST.get('claim_category') if (theme_id > 0): claims = Claim.objects.filter(theme_id = theme_id, claim_category = claim_category) else: claims = Claim.objects.filter(forum = forum, claim_category = claim_category) context["claims"] = [] for claim in claims: item = {} item['date'] = utils.pretty_date(claim.updated_at) item['created_at'] = utils.pretty_date(claim.created_at) item['created_at_used_for_sort'] = claim.created_at item['content'] = unicode(ClaimVersion.objects.filter(claim_id = claim.id)[0]) item['id'] = claim.id item['author_name'] = claim.author.first_name + " " + claim.author.last_name item['is_author'] = (request.user == claim.author) item['highlight_ids'] = "" for highlight in claim.source_highlights.all(): item['highlight_ids'] += (str(highlight.id) + " ") item['highlight_ids'].strip(" ") context["claims"].append(item) context['claims'].sort(key = lambda x: x["created_at_used_for_sort"], reverse=True) response['workbench_claims'] = render_to_string("workbench-claims.html", context) return HttpResponse(json.dumps(response), mimetype='application/json') def api_others(request): response = {} action = request.REQUEST.get('action') if action == 'create': if not request.user.is_authenticated(): return HttpResponse("Please log in first.", status=403) content = request.REQUEST.get('content') content_type = request.REQUEST.get('type') start = request.REQUEST.get('start') end = request.REQUEST.get('end') context_id = request.REQUEST.get('contextId') # create highlight object context = Entry.objects.get(id=context_id) highlight = Highlight(start_pos=start, end_pos=end, context=context, author=request.user) highlight.save() response['highlight_id'] = highlight.id # then create the content now = timezone.now() if 'actual_user_id' in request.session: actual_author = User.objects.get(id=request.session['actual_user_id']) else: actual_author = None if content_type == 'comment': if actual_author: Post.objects.create(forum_id=request.session['forum_id'], author=actual_author, delegator=request.user, content=content, created_at=now, updated_at=now, highlight=highlight, content_type='comment') else: Post.objects.create(forum_id=request.session['forum_id'], author=request.user, content=content, created_at=now, updated_at=now, highlight=highlight, content_type='comment') elif content_type == 'question': if actual_author: Post.objects.create(forum_id=request.session['forum_id'], author=actual_author, delegator=request.user, content=content, created_at=now, updated_at=now, highlight=highlight, content_type='question') else: Post.objects.create(forum_id=request.session['forum_id'], author=request.user, content=content, created_at=now, updated_at=now, highlight=highlight, content_type='question') elif content_type == 'claim': claim_views._add_claim(request, highlight) return HttpResponse(json.dumps(response), mimetype='application/json') if action == 'load-doc': doc_id = request.REQUEST.get('doc_id') doc = Doc.objects.get(id=doc_id) response['highlights'] = [] mytags = set() alltags = set() for section in doc.sections.all(): highlights = section.highlights.all() for highlight in highlights: highlight_info = highlight.getAttr() response['highlights'].append(highlight_info) if highlight_info['type'] == 'tag': if highlight_info['author_id'] == request.user.id: mytags.add(highlight_info['content']) alltags.add(highlight_info['content']) response['html'] = render_to_string('doc-tag-area.html', {'mytags': mytags, 'alltags': alltags}) return HttpResponse(json.dumps(response), mimetype='application/json')
I just love these two...Annalee is the kind of girl that can make you feel like you've been friends forever and not only are they so sweet, they're also freaking HILARIOUS. They have so much fun together and their wedding day was just a blast because like attracts like and so their entire bridal party, family, and all of their guests were a blast as well! This is the kind of wedding I want to photograph over and over again. Seriously dreamboat clients!
import pyglet from pyglet import app from pyglet.event import EVENT_HANDLED from pyglet.event import EVENT_UNHANDLED from pyglet.window import key from pyglet.gl import * import mode import caterpie import config from common import * from constants import * from content import levels, swags import data import os import squirtle import swag class MenuMode(mode.Mode): name = "menu" downarrow_image = data.load_image("menu/down.svgz") uparrow_image = data.load_image("menu/up.svgz") star_image = data.load_image("menu/perfect.svgz") diary_image = data.load_image("menu/diary.svgz") questionmark_image = data.load_image("menu/questionmark.svgz") back_image = data.load_image("menu/back.svgz") bg_image = data.load_image("menu/background.svgz", anchor_x='center', anchor_y='center') def __init__(self, default="main"): self.control = None self.window = None self.title = caterpie.TextBox( xpos = 0.0, ypos = 0.7, width = 1.0, height = 0.3, halign = "center", valign = "center", padding = MENU_PADDING, margin = MENU_MARGIN, font_size = MENU_FONT_SIZE, text = "The Space Adventures of Digby Marshmallow, " \ "Space Burglar Extraordinaire ...In Space!", ) self.level_display = caterpie.TextBox( xpos = 0.0, ypos = 0.7, width = 1.0, height = 0.3, halign = "center", valign = "center", padding = MENU_PADDING, margin = MENU_MARGIN, font_size = MENU_FONT_SIZE, text = "Select a level...", expand = "both", ) self.collection_display = caterpie.TextBox( xpos = 0.0, ypos = 0.7, width = 1.0, height = 0.3, halign = "center", valign = "center", padding = MENU_PADDING, margin = MENU_MARGIN, font_size = MENU_FONT_SIZE, text = "Swag Collection", expand = "both", ) self.menu = caterpie.TextMenu( xpos = 0.0, ypos = 0.1, width = 1.0, height = 0.6, halign = "center", valign="top", padding = MENU_PADDING, margin = MENU_MARGIN, spacing = MENU_SPACING, font_size = MENU_FONT_SIZE, scrolling=True ) highlight_color = (0.4, 0.3, 0.5, 0.6) def arrow_set_mouse(self, x, y): if (x, y) in self: self.background = highlight_color else: style = caterpie.get_default_style() self.background = style.background self.downarrow = caterpie.ImageButton( halign="center", valign="top", graphic = self.downarrow_image, callback = (self.menu.scroll_relative, 5), ) self.downarrow.set_mouse = arrow_set_mouse.__get__(self.downarrow) self.uparrow = caterpie.ImageButton( height = 0.05, halign="center", valign="bottom", graphic = self.uparrow_image, callback = (self.menu.scroll_relative, -5), ) self.uparrow.set_mouse = arrow_set_mouse.__get__(self.uparrow) self.interface = [self.title, self.menu, self.level_display, self.collection_display] self.states = { "main" : [ ("Start Game", (self.set_state, "levels")), ("Editor", self.do_editor), ("Collection", self.do_collection), ("Options", self.do_options), ("Quit", self.do_quit), ] if DEBUG else [ ("Start Game", (self.set_state, "levels")), ("Collection", self.do_collection), ("Options", self.do_options), ("Quit", self.do_quit), ], "death" : [ "You died!", ("Retry", self.do_retry_level), ("New level", (self.set_state, "levels")), ("Menu", (self.set_state, "main")), ], "continue" : [ ("Continue", self.do_next_level), ("Retry", self.do_retry_level), ("New level", (self.set_state, "levels")), ("Menu", (self.set_state, "main")), ], "options" : [ ("option:fullscreen", self.toggle_fullscreen), ("Back", (self.set_state, "main")) ], "collection" : [], "victory" : [], } self.scroll_states = ["levels"] self.title_states = ["main", "options"] self.menu_states = ["main", "options", "death", "continue"] self.state = None self.default = default self.fade_level = 1.0 self.collection_back = None self.collection_up = None self.collection_down = None def fade_in(self, callback): self.fading = True self.target_fade = 0 self.fade_callback = callback self.window.remove_handlers(self.menu) def fade_out(self, callback): self.fading = True self.target_fade = 1 self.fade_callback = callback self.window.remove_handlers(self.menu) def stop_fade(self): self.fading = False self.target_fade = self.fade_level self.fade_callback = None if self.window is not None: if self.state in self.menu_states: self.window.push_handlers(self.menu) def tick(self): if self.target_fade > self.fade_level: self.fade_level = min(self.target_fade, self.fade_level + FADE_RATE) elif self.target_fade < self.fade_level: self.fade_level = max(self.target_fade, self.fade_level - FADE_RATE) elif self.fading: if isinstance(self.fade_callback, tuple): func = self.fade_callback[0] args = self.fade_callback[1:] func(*args) else: self.fade_callback() self.stop_fade() if self.state in ('collection', 'victory'): if self.control.keys[key.UP]: self.collection.view_y += 10 elif self.control.keys[key.DOWN]: self.collection.view_y -= 10 def connect(self, control): self.control = control self.window = control.window for component in self.interface: component.window = self.window self.position_buttons() self.prepare_levelicons() self.control.music.start_song("ABreezeFromAlabama.mp3") self.states['levels'] = [] for n in xrange(min(control.gamestate.current_max_level + 1, len(levels.levels))): text = levels.levels[n][1] if n in control.gamestate.best_swags: text += ' (%d%%)' % (control.gamestate.best_swags[n][0],) option_spec = (text, (self.do_start_game, n)) self.states['levels'].append(option_spec) self.states['levels'].append(("Back", (self.set_state, "main"))) self.update_collection(self.control.gamestate.level_collected_swag if self.default == 'victory' else None) self.set_state(self.default) self.fade_in(lambda: None) def update_collection(self, swag_list=None): gs = self.control.gamestate self.collection_elements = [] doc = pyglet.text.decode_attributed('') total_value = 0 if swag_list is None: title_text = 'Swag Collection' else: title_text = 'Victory!' for cls, radius, name, img, value in swags.swags: if swag_list is None: total = 0 for n in gs.best_swags: swag_dict = gs.best_swags[n][1] if name in swag_dict: total += swag_dict[name] else: total = swag_list.get(name, 0) if total: elt = squirtle.SVGElement(data.load_image(os.path.join('swag', img), anchor_x='center', anchor_y='center'), 0.02 * self.window.height, radius=radius * self.window.height/SCREEN_HEIGHT, width=self.window.width * .35) self.collection_elements.append(elt) doc.insert_element(len(doc.text), elt) doc.insert_text(len(doc.text), '%d x %s ($%d) = $%d\n\n' % (total, name, value, total*value)) total_value += total * value if swag_list is not None: swag_val = 0 for a in gs.current_stage['actors']: if isinstance(a, swag.Swag): swag_val += a.value title_text += ' (%d%%)' % (100 * total_value/swag_val,) if total_value == swag_val: title_text = 'Flawless ' + title_text title_text += '\nTotal Value: $%d' % (total_value,) self.collection_display.text = title_text if doc.text: doc.insert_text(len(doc.text), '\n\n\n') doc.set_style(0, len(doc.text), {'font_name': "Fontdinerdotcom", 'font_size': 0.04 * self.window.height, 'color': (255, 255, 255, 255)}) self.collection = pyglet.text.layout.IncrementalTextLayout( doc, self.window.width * .9, self.window.height * .7, multiline=True) self.collection.content_valign = 'top' self.collection.x = self.window.width * .05 self.collection.y = self.window.height * .65 self.collection.anchor_x = 'left' self.collection.anchor_y = 'top' sw, sh = self.window.get_size() size = sh * 0.1 self.collection_back = caterpie.ImageButton( xpos = sw * .05, ypos = sh * 0.1, width = size, height = size, callback = (self.set_state, 'continue' if swag_list is not None else 'main'), graphic = self.back_image, outline = None, background = None, ) def up(): self.collection.view_y += 50 def down(): self.collection.view_y -= 50 self.collection_up = caterpie.ImageButton( xpos = sw * .95 - size, ypos = sh * 0.55, width = size, height = size, callback = up, graphic = self.uparrow_image, outline=None, background=None, ) self.collection_down = caterpie.ImageButton( xpos = sw * .95 - size, ypos = sh * 0.05, width = size, height = size, callback = down, graphic = self.downarrow_image, outline=None, background=None, ) def disconnect(self): for component in self.interface: component.window = None self.window.remove_handlers(self.menu) self.window.remove_handlers(self.uparrow) self.window.remove_handlers(self.downarrow) self.window.remove_handlers(self.collection_back) self.window.remove_handlers(self.collection_down) self.window.remove_handlers(self.collection_up) for icon in self.levelicons: self.window.remove_handlers(icon) self.window = None self.control = None def prepare_levelicons(self): sw, sh = self.window.get_size() li_size = sh * LEVELICON_SIZE spacing = sh * LEVELICON_SPACING y = spacing * 4 + li_size * 3 self.levelicons = [] self.currenticon = 0 for j in xrange(4): x = (sw - li_size * 7 - spacing * 6) / 2 for i in xrange(7): idx = 7*j+i def set_mouse(btn, x, y): if btn.idx == 27: self.level_display.text = "Select a level...\n" if (x, y) in btn: self.hover_level(btn.idx) if idx == 27: graphic = self.back_image elif idx > self.control.gamestate.current_max_level: graphic = self.questionmark_image elif levels.levels[idx][0].endswith(".scene"): graphic = self.diary_image else: graphic = pyglet.image.load(data.file_path(os.path.join("screenshots", levels.levels[idx][3]))) w, h = graphic.width, graphic.height graphic = graphic.get_region(int(.5 * w - .4 * h), 0, int(h*.8), int(h*.8)) if isinstance(graphic, pyglet.image.AbstractImage): btn = caterpie.BitmapButton(xpos = x, ypos = y, width = li_size, height = li_size, padding = li_size / 10, callback = (self.click_level, idx), graphic = graphic, outline=(0,0,0,1) ) else: btn = caterpie.ImageButton( xpos = x, ypos = y, width = li_size, height = li_size, padding = li_size / 10, callback = (self.click_level, idx), graphic = graphic, outline=(0,0,0,1) ) btn.idx = idx btn.set_mouse = set_mouse.__get__(btn) self.levelicons.append(btn) x += spacing + li_size y -= spacing + li_size self.hover_level(0) def set_state(self, name): if self.state == "levels": for icon in self.levelicons: self.window.remove_handlers(icon) if self.state in ("collection", "victory"): self.window.remove_handlers(self.collection_back) self.window.remove_handlers(self.collection_down) self.window.remove_handlers(self.collection_up) if self.state == 'victory': self.control.gamestate.finish_level(self.control) self.update_collection() if self.state in self.menu_states: self.window.remove_handlers(self.menu) self.state = name self.menu.clear_options() self.menu.add_options(*self.states[name]) if name in self.scroll_states: self.menu.scrolling = True self.position_buttons() else: self.menu.scrolling = False if name in ('victory', 'collection'): self.window.push_handlers(self.collection_back) self.window.push_handlers(self.collection_down) self.window.push_handlers(self.collection_up) if name == "levels": for icon in self.levelicons: self.window.push_handlers(icon) if self.state in self.menu_states: self.window.push_handlers(self.menu) def position_buttons(self): bx, by, bw, bh = self.menu.box_shape sw, sh = self.window.get_size() bh = self.menu.height * sh - 2 * self.menu.margin * sh self.uparrow.xpos = bx self.uparrow.ypos = by + bh self.uparrow.width = bw self.uparrow.height = bh / 10 self.downarrow.xpos = bx self.downarrow.ypos = by - bh / 10 self.downarrow.width = bw self.downarrow.height = bh / 10 def click_level(self, idx): if idx == 27: self.set_state("main") return elif idx <= self.control.gamestate.current_max_level: self.fade_out((self.control.gamestate.start_level, idx, self.control)) self.control.music.stop_song(1.0) else: pass def hover_level(self, idx): self.levelicons[self.currenticon].outline=(0,0,0,1) self.currenticon = idx self.levelicons[self.currenticon].outline=(1,1,1,1) if idx == 27: self.level_display.text = "Back..." elif idx <= self.control.gamestate.current_max_level: file, name, music, img = levels.levels[idx] self.level_display.text = name if idx in self.control.gamestate.best_swags: self.level_display.text += ' (%d%%)' % (self.control.gamestate.best_swags[idx][0],) else: self.level_display.text = "????" def do_next_level(self): self.fade_out((self.control.gamestate.start_level, self.control.gamestate.current_level, self.control)) self.control.music.stop_song(1.0) def do_retry_level(self): self.fade_out((self.control.gamestate.start_level, self.control.gamestate.current_retry_level, self.control)) self.control.music.stop_song(1.0) def do_start_game(self, n): self.fade_out((self.control.gamestate.start_level, n, self.control)) self.control.music.stop_song(1.0) def do_editor(self): self.fade_out((self.control.switch_handler, "editor")) self.control.music.stop_song(1.0) def do_options(self): self.set_state("options") self.option_labels = {} for opt in self.menu.options: if opt.label.text.startswith("option:"): self.option_labels[opt.label.text[7:]] = opt.label suffix = ["Off", "On"][config.fullscreen] self.option_labels["fullscreen"].text = "Fullscreen: %s" % suffix def do_collection(self): self.set_state("collection") def do_quit(self): self.fade_out(app.exit) def toggle_fullscreen(self): config.fullscreen = not config.fullscreen config.save_option("fullscreen") suffix = ["Off", "On"][config.fullscreen] self.option_labels["fullscreen"].text = "Fullscreen: %s" % suffix def on_key_press(self, sym, mods): if self.state in ('collection', 'victory'): if sym in (key.UP, key.DOWN): return EVENT_UNHANDLED if self.state == 'collection' and sym == key.LEFT: self.set_state('main') if self.state == 'victory': self.set_state('continue') nexticon = None if self.state == 'levels': if sym == key.UP: nexticon = self.currenticon - LEVELS_PER_ROW if sym == key.DOWN: nexticon = self.currenticon + LEVELS_PER_ROW if sym == key.LEFT: nexticon = self.currenticon - 1 if sym == key.RIGHT: nexticon = self.currenticon + 1 if nexticon is not None: self.hover_level(nexticon % (LEVELS_PER_ROW * LEVEL_ROWS)) if sym == key.ENTER: self.click_level(self.currenticon) if sym == key.ESCAPE: if self.state != 'main': self.set_state('main') return EVENT_HANDLED return EVENT_UNHANDLED def on_draw(self): self.window.clear() self.bg_image.draw(self.window.width / 2, self.window.height / 2, height=self.window.height) if self.state in self.menu_states: self.menu.draw() if self.menu.scrolling: self.uparrow.draw() self.downarrow.draw() elif self.state == "levels": for icon in self.levelicons: icon.draw() if self.control.gamestate.best_swags.get(icon.idx, [0.0, {}])[0] == 100.0: w = icon.width / 3 self.star_image.draw(icon.xpos, icon.ypos, width=w) self.level_display.draw() elif self.state in ("collection", "victory"): sw, sh = self.window.get_size() glColor4f(0,0,0, 0.8) glBegin(GL_QUADS) glVertex2f(sw * .1, 0) glVertex2f(sw * .9, 0) glVertex2f(sw * .9, sh * .7) glVertex2f(sw * .1, sh * .7) glEnd() self.collection.draw() glEnable(GL_SCISSOR_TEST) glScissor(int(self.collection.x), int(self.collection.y - self.collection.height), int(self.collection.width), int(self.collection_display.box_shape[1] - self.collection.y + self.collection.height)) for elt in self.collection_elements: elt.draw() glDisable(GL_SCISSOR_TEST) self.collection_display.draw() self.collection_back.draw() if self.collection.view_y > self.collection.height - self.collection.content_height + EPSILON: self.collection_down.draw() if self.collection.view_y: self.collection_up.draw() if self.state in self.title_states: self.title.draw() if self.fade_level: sw, sh = self.window.get_size() glColor4f(0, 0, 0, self.fade_level) glBegin(GL_QUADS) glVertex2f(0, 0) glVertex2f(sw, 0) glVertex2f(sw, sh) glVertex2f(0, sh) glEnd()
This website is operated by SUNS Shoes. Throughout the site, the terms “we”, “us” and “our” refer to SUNS Shoes. SUNS Shoes offers this website, including all information, tools and services available from this site to you, the user, conditioned upon your acceptance of all terms, conditions, policies and notices stated here. We have made every effort to display as accurately as possible the colors and images of our products that appear at the store. We cannot guarantee that your computer monitor's or smart-device’s display of any color will be accurate. In no case shall SUNS Shoes, our directors, officers, employees, affiliates, agents, contractors, interns, suppliers, service providers or licensors be liable for any injury, loss, claim, or any direct, indirect, incidental, punitive, special, or consequential damages of any kind, including, without limitation lost profits, lost revenue, lost savings, loss of data, replacement costs, or any similar damages, whether based in contract, tort (including negligence), strict liability or otherwise, arising from your use of any of the service or any products procured using the service, or for any other claim related in any way to your use of the service or any product, including, but not limited to, any errors or omissions in any content, or any loss or damage of any kind incurred as a result of the use of the service or any content (or product) posted, transmitted, or otherwise made available via the service, even if advised of their possibility. Because some states or jurisdictions do not allow the exclusion or the limitation of liability for consequential or incidental damages, in such states or jurisdictions, our liability shall be limited to the maximum extent permitted by law. You agree to indemnify, defend and hold harmless SUNS Shoes and our parent, subsidiaries, affiliates, partners, officers, directors, agents, contractors, licensors, service providers, subcontractors, suppliers, interns and employees, harmless from any claim or demand, including reasonable attorneys’ fees, made by any third-party due to or arising out of your breach of these Terms of Service or the documents they incorporate by reference, or your violation of any law or the rights of a third-party. Questions about the Terms of Service should be sent to us at [email protected].
#!/usr/bin/env python # Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Creates a script to run an "_incremental" .apk.""" import argparse import os import pprint import sys sys.path.append(os.path.join(os.path.dirname(__file__), os.pardir)) sys.path.append(os.path.join(os.path.dirname(__file__), os.pardir, 'gyp')) from pylib import constants from util import build_utils SCRIPT_TEMPLATE = """\ #!/usr/bin/env python # # This file was generated by: # //build/android/incremental_install/create_install_script.py import os import subprocess import sys def main(): script_directory = os.path.dirname(__file__) def resolve_path(path): return os.path.abspath(os.path.join(script_directory, path)) cmd_path = resolve_path({cmd_path}) cmd_args = [cmd_path] + {cmd_args} cmd_path_args = {cmd_path_args} for arg, path in cmd_path_args: if arg: cmd_args.append(arg) cmd_args.append(resolve_path(path)) return subprocess.call(cmd_args + sys.argv[1:]) if __name__ == '__main__': sys.exit(main()) """ def _ParseArgs(args): args = build_utils.ExpandFileArgs(args) parser = argparse.ArgumentParser() build_utils.AddDepfileOption(parser) parser.add_argument('--script-output-path', help='Output path for executable script.', required=True) parser.add_argument('--output-directory', help='Path to the root build directory.', default='.') parser.add_argument('--apk-path', help='Path to the .apk to install.', required=True) parser.add_argument('--split', action='append', dest='splits', default=[], help='A glob matching the apk splits. ' 'Can be specified multiple times.') parser.add_argument('--lib-dir', help='Path to native libraries directory.') parser.add_argument('--dex-file', action='append', default=[], dest='dex_files', help='List of dex files to include.') parser.add_argument('--dex-file-list', help='GYP-list of dex files.') options = parser.parse_args(args) options.dex_files += build_utils.ParseGypList(options.dex_file_list) return options def main(args): options = _ParseArgs(args) def relativize(path): return os.path.relpath(path, os.path.dirname(options.script_output_path)) installer_path = os.path.join(constants.DIR_SOURCE_ROOT, 'build', 'android', 'incremental_install', 'installer.py') installer_path = relativize(installer_path) path_args = [ ('--output-directory', relativize(options.output_directory)), (None, relativize(options.apk_path)), ] if options.lib_dir: path_args.append(('--lib-dir', relativize(options.lib_dir))) if options.dex_files: for dex_file in options.dex_files: path_args.append(('--dex-file', relativize(dex_file))) for split_arg in options.splits: path_args.append(('--split', relativize(split_arg))) with open(options.script_output_path, 'w') as script: script.write(SCRIPT_TEMPLATE.format( cmd_path=pprint.pformat(installer_path), cmd_args='[]', cmd_path_args=pprint.pformat(path_args))) os.chmod(options.script_output_path, 0750) if options.depfile: build_utils.WriteDepfile( options.depfile, build_utils.GetPythonDependencies()) if __name__ == '__main__': sys.exit(main(sys.argv[1:]))
This information is provided by Florida Keys Board of REALTORS. Information deemed reliable but not guaranteed. All properties are subject to prior sale, change or withdrawal. Listing(s) information is provided for consumers personal, non-commercial use and may not be used for any purpose other than to identify prospective properties consumers may be interested in purchasing. ©2019 Florida Keys Board of REALTORS. All rights reserved.
# -*- coding: utf-8 -*- import mock import unittest from noterator import Noterator, TWILIO from noterator.plugins.twilio import BASE_URL class TestEmailPlugin(unittest.TestCase): @mock.patch('noterator.plugins.twilio.requests') def test_twilio_settings(self, requests): cfg = { 'account_sid': '123456', 'token': 'twilio-token', 'from_number': '+987654', 'to_number': '+13579', } n = Noterator(range(5), TWILIO, config_file=None) n.configure_plugin('twilio', **cfg) for _ in n: pass url = '{}/Accounts/{}/Messages.json'.format( BASE_URL, cfg['account_sid'], ) payload = { "From": cfg['from_number'], "To": cfg['to_number'], "Body": "{}: {}".format( n.head, n._get_body(TWILIO, finished=True), ), } auth = (cfg['account_sid'], cfg['token']) requests.post.assert_called_once_with(url, payload, auth=auth)
DescriptionAMAZING opportunity with the last vacant lot located in Mariner Pointe on Lake Keowee. Gentle slope, terraces down to the 310(+/-) feet of shoreline that looks out to the main channel. The lot already has shoreline stabalization and a dock permit is being applied for. Mariner Pointe is gated and the original Crescent Community on Lake Keowee and has great mountain and lake views throughout the neighborhood. Contact listing agent for more details.
# Copyright 2017 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # from alembic import op import sqlalchemy as sa from neutron_lib.db import constants as db_const """logging api Revision ID: c8c222d42aa9 Revises: 62c781cb6192 Create Date: 2017-05-30 11:51:08.173604 """ # revision identifiers, used by Alembic. revision = 'c8c222d42aa9' down_revision = '62c781cb6192' def upgrade(): op.create_table( 'logs', sa.Column('project_id', sa.String(length=db_const.PROJECT_ID_FIELD_SIZE), nullable=True, index=True), sa.Column('id', sa.String(length=db_const.UUID_FIELD_SIZE), nullable=False), sa.Column('standard_attr_id', sa.BigInteger(), nullable=False), sa.Column('name', sa.String(length=db_const.NAME_FIELD_SIZE), nullable=True), sa.Column('resource_type', sa.String(length=36), nullable=False), sa.Column('resource_id', sa.String(length=db_const.UUID_FIELD_SIZE), nullable=True, index=True), sa.Column('target_id', sa.String(length=db_const.UUID_FIELD_SIZE), nullable=True, index=True), sa.Column('event', sa.String(length=255), nullable=False), sa.Column('enabled', sa.Boolean(), nullable=True), sa.PrimaryKeyConstraint('id'), sa.ForeignKeyConstraint(['standard_attr_id'], ['standardattributes.id'], ondelete='CASCADE'), sa.UniqueConstraint('standard_attr_id'))
Test drive of the new Kia Sorento 2.2 CRDi with automatic gearbox for Europe. Since 2002, the Kia Sorento is in this country on the market, and now he is completely revised. First, the fresh SUV celebrates the IAA auto show, 17 to 27 September 2009 premiere, in November 2009, it goes on sale. We are the new edition is already gone with the powerful 2.2 CRDi 197 hp combined with a six-speed automatic. Now with Tiger Nose The Sorento has become much more pleasing. From the front, the SUV can be seen clearly at the Kia as a freshly styled face. The new grill is called by the designers' tiger nose ". This current bear is already the face of brand Magentis and the Soul, also appearing in the September 2009 Cee'd comes this fresh outfit. The Sorento looks more elegant than its predecessor: The new was nine inches longer and two inches shallower. The side view also extends over 4.68 meters and has a special especially the modified C-and D-pillars. The small window in the rear moved a bit backwards, thus results in a better view when reversing. At the rear, large rays, drawn into the fold lamps. As an option, they are also in LED optics. Get rid of the ladder frame: Strong slimmed The real revolution took place behind the stylish outfit. The ladder frame has had its day and had to give way to a monocoque body. This saves, depending on equipment, up to 215 kilograms in weight. The newly designed chassis offers Mehrlenkerverbundachse now instead of independent suspension front and rear. Now available for seven people Also, the interior was very tidy. Although the wheelbase has been shortened by one centimeter to 2.70 meters, all have enough room. In the back we have plenty of room for heads and knees and enjoy the opportunity, the inclination of the backrest to be adjusted continuously. Only the wheel wells has been pulled far forward a little upset when embarking and disembarking. Brand new is the option to order two single seats for the third row. The child's chairs can be folded into the boot floor. To reach the third row to be in the middle row of seats double folded outer forward. If the additional stalls not on board, there is under a flap in the trunk of an additional pocket for odds and ends. At the five-seater, the maximum usable storage space varies from 531 to about 1582 liters, the seven-seater, depending on its configuration from 111 up to 1546 liters of space. Navigation from the factory until mid-2010 The cockpit have done well, the renovation work. The comfort of our test car's seats are upholstered in brown leather and offer plenty of lateral support. Brown is also the wooden trims on the instrument panel - who do not like it, you can also order a black interior. The tools behind the four-spoke steering wheel stuck in cylinders and light colored three-dimensional. Among the optional features include a rearview camera, whose image appears on the interior mirror. Only a large factory Navi Sorento customers have to wait until mid-2010. Until then, a retrofit solution can be ordered. More fuel-efficient engines Downsizing is also a major topic at Kia: So are offered for the Sorento a 2.4-liter gasoline engine with 174 hp and a 2.2-liter diesel with 197 hp. A six-cylinder petrol, as with its predecessor is in this country to have no more. The two new engines derive their power either to a six-speed manual transmission or a six-converter automatics with manual lane. Powerful Diesel Our test car had the automatic transmission in combination with the diesel engine on board. The machine is not particularly quiet at idle, but remains at normal cruising speed audible in the background. Already from the start of ignition moves off powerfully, with maximum torque of 436 Newton-meter is already on at 1800 Tour and is held up to 2,500 rpm. The transmission performs his duties smoothly, but should be happy to respond faster during kickdown. Overall, the Sorento 2.2 CRDi Automatic with a sprint of 10.0 seconds and a peak of 190 km / h ordinary performance. The consumption of the Euro-5-Kia Machine valued at 7.4 liters. Four-wheel drive with new features We feel the new Kia SUV as an appropriate means of transportation for long distances. The suspension absorbs bumps off the ground comfortably and reported only short bursts, for example when driving over manhole covers, felt inside. We can also be quite dynamic on the road with the Sorento, but the steering is tuned for a sporty driving style is too indirect. Nevertheless cornering is fun, because the body does not tend to excessively to the sides. The new Sorento is have from 28,505 euros. That one gets the 2.4-liter gasoline engine with front wheel drive and manual transmission. The Mileage of us as a front-wheel drive diesel will cost 30,770 euros, as Allradlers 32,280 euros. Besides the basic equipment Attract the lines of vision (35,030 euros) and Spirit (offered 36,750 euros). The basic configuration already includes an MP3-compatible CD radio and air conditioning. If you want an automatic air conditioning, must resort to the "vision", but then also, for example a rain and a light sensor there. The latest edition of the Sorento is an entirely successful affair. Not only because the appearance fresh and youthful looks and the interior has been attractively styled. But mainly because Kia has adopted by the director under outdated principle. The ride quality offered by the car now fit into a modern mobile of its kind The new Sorento is a roomy SUV, which is suitable not only for everyday life on the asphalt, but may venture with an optional front-wheel drive on an excursion into the terrain. The Mileage of our combination of strong diesel engine and automatic transmission is a gentle good way to move forward confidently. Is just a pity that Kia many extras, only in packages and offering them only in combination with certain equipment versions.
""" AALtoDJfodtlmon Copyright (C) 2016 Walid Benghabrit 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 datetime import datetime from subprocess import Popen, PIPE import os.path import shutil from AALMetaModel import * __author__ = 'walid' class MappingSpec: """ Service -> Agent -> Type -> Clause -> """ def __init__(self): self.services = [] self.agents = [] self.types = [] self.clauses = [] class BaseMap: def __init__(self, name, target): self.name = name.strip() self.target = target.strip() def __str__(self): return "%s: %s => %s" % (self.__class__.__name__, self.name, self.target) class ServiceMap(BaseMap): pass class AgentMap(BaseMap): pass class TypeMap(BaseMap): pass class ClauseMap(BaseMap): def __init__(self, name, target, control_type): super().__init__(name, target) self.control_type = control_type.strip() def __str__(self): return "%s: %s => %s => %s" % (self.__class__.__name__, self.name, self.target, self.control_type) # AALtoDJFODTLMON def AALtoDJFODTLMON(mm, spec: MappingSpec, output_file=None): """ Translate AAL program to Djfodtlmon using a spec file """ log_attributes = [] custom_predicates = [] http_rules = [] view_rules = [] response_rules = [] header = "###\n# Mapping file for %s\n# created on %s\n###\n" % (mm.file, datetime.today()) ################################### # Attributes ################################### log_attributes.append(""" ## 1. User type log attribute def log_user_type(request, view, args, kwargs, response): # The evaluation function # Do your custom logic to determine the user type # The current django user can be accessed via : request.user # user_type = "..." return P("USER_TYPE", args=[Constant(user_type)]) # Create and add the attribute utype_log_attr = LogAttribute('USER_TYPE', enabled=True, eval_fx=log_user_type, description='The type of the current user.', ) Sysmon.add_log_attribute(utype_log_attr, target=Monitor.MonType.HTTP) """) ################################### # Predicates/Functions ################################### ################################### # Rules ################################### for rule in spec.clauses: control_type = "Monitor.MonControlType.POSTERIORI" if rule.control_type == "REAL_TIME": control_type = "Monitor.MonControlType.REAL_TIME" formula = "" clause = mm.clause(rule.name) if clause is not None: formula = aal_clause_to_fodtl(clause) description = "Rule for clause %s" % rule.name if rule.target == "HTTP": http_rules.append('Sysmon.add_http_rule("%s", "%s", \n\tdescription="%s", control_type=%s)' % (rule.name, formula, description, control_type)) elif rule.target == "VIEW": view_rules.append('Sysmon.add_view_rule("%s", "%s", \n\tdescription="%s", control_type=%s)' % (rule.name, formula, description, control_type)) elif rule.target == "RESPONSE": response_rules.append('Sysmon.add_response_rule("%s", "%s", \n\tdescription="%s", control_type=%s)' % (rule.name, formula, description, control_type)) ################################### # Result ################################### res = """%s from accmon.sysmon import * from django.contrib.auth.models import User ################################ # Custom attributes to log ################################ %s ################################ # Custom predicates/functions ################################ %s ################################ # HTTP request rules ################################ %s ################################ # View rules ################################ %s ################################ # Response rules ################################ %s """ % (header, "\n".join(log_attributes), "\n".join(custom_predicates), "\n".join(http_rules), "\n".join(view_rules), "\n".join(response_rules)) return res # Generate django skeleton app def generate_django_skeleton(aal_file, spec_file, output_folder): """ NOTE : consider using AST modifications for source code :param aal_file: :param spec_file: :param output_folder: :return: """ project_name = "test1" project_path = "examples/" app_name = "app1" spec_file = "tuto2_rules.py" # 1. Remove previous project if os.path.isdir("examples/%s" % project_name): shutil.rmtree("examples/%s" % project_name) # 2. Start project p = Popen(['django-admin', 'startproject', project_name], stdout=PIPE, stderr=PIPE, stdin=PIPE) # res = p.stdout.read().decode("utf-8") res = p.stderr.read().decode("utf-8") if res != "": return res # 3. Create app p = Popen(['python3', project_name+'/manage.py', 'startapp', app_name], stdout=PIPE, stderr=PIPE, stdin=PIPE) res = p.stderr.read().decode("utf-8") if res != "": # Rollaback if os.path.isdir(project_name): shutil.rmtree(project_name) if os.path.isdir(app_name): shutil.rmtree(app_name) return res # 4. Configure fodtlmon # 4.1 wsgi wsgi = project_name + "/" + project_name + "/wsgi.py" admin = "from django.contrib.auth.models import User\n# Create a superuser (for test only)\n" \ "if len(User.objects.filter(username='root')) == 0:\n"\ "\tUser.objects.create_superuser(username='root', password='root', email='')" if not os.path.isfile(wsgi): return "wsgi file doesn't exists !" with open(wsgi, "a+") as f: f.write("\nfrom accmon.sysmon import Sysmon\nSysmon.init()\nimport %s.%s\n\n%s\n" % (project_name, spec_file.replace(".py", ""), admin)) # 4.2 settings settings = project_name + "/" + project_name + "/settings.py" if not os.path.isfile(settings): return "settings file doesn't exists !" res = "" f = open(settings, "r") res = f.read() res = res.replace("'django.contrib.staticfiles',", "'django.contrib.staticfiles',\n 'accmon',\n '%s'" % app_name) res = res.replace("'django.middleware.security.SecurityMiddleware',", "'django.middleware.security.SecurityMiddleware',\n 'accmon.middleware.FodtlmonMiddleware'") f.close() f = open(settings, "w") f.flush() f.write(res) f.close() # 4.3 urls urls = project_name + "/" + project_name + "/urls.py" if not os.path.isfile(urls): return "urls file doesn't exists !" res = "" f = open(urls, "r") res = f.read() res = res.replace("from django.contrib import admin", "from django.contrib import admin\nfrom accmon import urls as fodtlurls") res = res.replace("url(r'^admin/', include(admin.site.urls)),", "url(r'^admin/', include(admin.site.urls)),\n url(r'^mon/', include(fodtlurls.urlpatterns)),") f.close() f = open(urls, "w") f.flush() f.write(res) f.close() # Move app to the project path shutil.move(app_name, project_name+"/") # Migration p = Popen(['python3', project_name+'/manage.py', 'makemigrations'], stdout=PIPE, stderr=PIPE, stdin=PIPE) res = p.stderr.read().decode("utf-8") if res != "": # Rollaback if os.path.isdir(project_name): shutil.rmtree(project_name) if os.path.isdir(app_name): shutil.rmtree(app_name) return res p = Popen(['python3', project_name+'/manage.py', 'migrate'], stdout=PIPE, stderr=PIPE, stdin=PIPE) res = p.stderr.read().decode("utf-8") if res != "": # Rollaback if os.path.isdir(project_name): shutil.rmtree(project_name) if os.path.isdir(app_name): shutil.rmtree(app_name) return res # Copy the spec file shutil.copy(project_path + spec_file, project_name+"/"+project_name+"/"+spec_file.split("/")[-1]) # Move project shutil.move(project_name, project_path) return "Django !" def aal_clause_to_fodtl(clause: m_clause): """ Transform an AAL clause into fodtl formula :param clause: :return: """ # TODO handle rectification def transform(exp: aalmmnode, ref=False): if isinstance(exp, m_clause): return transform(exp.usage) elif isinstance(exp, m_usage): return transform(exp.actionExp[0]) elif isinstance(exp, m_aexpQvar): qs = "" for x in exp.qvars: qs += transform(x) + "(" return "%s %s %s" % (qs, transform(exp.actionExp), (")"*(len(exp.qvars)))) elif isinstance(exp, m_qvar): if ref: return "%s" % exp.variable.name else: return "%s[%s]" % (exp.quant.to_ltl(), transform(exp.variable, ref=ref)) elif isinstance(exp, m_ref): return transform(exp.target, ref=ref) elif isinstance(exp, m_aexpComb): return "(%s %s %s)" % (transform(exp.actionExp1), transform(exp.operator), transform(exp.actionExp2)) elif isinstance(exp, m_aexpIfthen): return "((%s) => (%s))" % (transform(exp.condition), transform(exp.branchTrue)) elif isinstance(exp, m_booleanOp): if exp == m_booleanOp.O_and: return "&" elif exp == m_booleanOp.O_or: return "|" elif exp == m_booleanOp.O_not: return "~" elif exp == m_booleanOp.O_true: return "true" elif exp == m_booleanOp.O_false: return "false" else: return "<Unsupported boolean op %s>" % exp elif isinstance(exp, m_aexpCondition): return transform(exp.condition) elif isinstance(exp, m_conditionCmp): if exp.operator == m_booleanOp.O_equal: return "EQUAL(%s,%s)" % (transform(exp.exp1, ref=True), transform(exp.exp2, ref=True)) elif exp.operator == m_booleanOp.O_inequal: return "~EQUAL(%s,%s)" % (transform(exp.exp1, ref=True), transform(exp.exp2, ref=True)) else: return "(%s %s %s)" % (transform(exp.exp1), transform(exp.operator), transform(exp.exp2)) elif isinstance(exp, m_conditionNotComb): return "(%s)" % (transform(exp.exp)) if exp.operator is None else "~(%s)" % (transform(exp.exp)) elif isinstance(exp, m_conditionComb): return "(%s %s %s)" % (transform(exp.cond1), transform(exp.operator), transform(exp.cond2)) elif isinstance(exp, m_predicate): q = [] for x in exp.args: x = str(x) if x[0] == '"' and x[-1] == '"': x = 'r\\"%s\\"' % x[1:-1] q.append(str(x)) return "%s(%s)" % (exp.name, ", ".join(q)) elif isinstance(exp, m_aexpModal): return "%s(%s)" % (transform(exp.modality), transform(exp.actionExpression)) elif isinstance(exp, m_modal): if exp == m_modal.T_always: return "G" elif exp == m_modal.T_must: return "F" elif exp == m_modal.T_unless: return "R" elif exp == m_modal.T_until: return "U" elif exp == m_modal.T_sometime: return "F" else: return "<Unsupported boolean op %s>" % exp elif isinstance(exp, m_aexpAuthor): return "%s%s" % (transform(exp.author), transform(exp.action)) elif isinstance(exp, m_aexpAction): return "%s" % transform(exp.action) elif isinstance(exp, m_author): return "P" if exp == m_author.A_permit else "~P" elif isinstance(exp, m_action): return "%s(%s, %s, %s)" % (exp.service, transform(exp.agent1, ref=True), transform(exp.agent2, ref=True), transform(exp.args, ref=True)) elif isinstance(exp, m_agent): return "'%s'" % exp.name elif isinstance(exp, m_varAttr): return "%s(%s)" % (exp.attribute, exp.variable) elif isinstance(exp, m_variable): if ref: return "%s" % exp.name else: return "%s" % exp elif isinstance(exp, m_constant): return "%s" % exp.name elif isinstance(exp, str): return exp else: return "<Unsupported type %s>" % exp.__class__.__name__ return "G(%s)" % transform(clause)
28/12/2018 · An engineering manager must be a fully licensed, professional engineer. There are a wide range of specialization options available in engineering, ranging from electronic to civil engineering . In order to become a professional engineer (P.Eng), all candidates must complete a university undergraduate degree in engineering.... A IQ question: I have 9 coins and 8 have the same weight and the last one is heavier. I also have a balance beam to weigh the coins with. I can only use the balance beam 2 times to find the heavier coin. I am looking for an Engineering Manager to join a growing team on a Smart Motorway project … The Engineering Manager will report into the Project Manager and the day to day role will …... 28/12/2018 · An engineering manager must be a fully licensed, professional engineer. There are a wide range of specialization options available in engineering, ranging from electronic to civil engineering . In order to become a professional engineer (P.Eng), all candidates must complete a university undergraduate degree in engineering. A IQ question: I have 9 coins and 8 have the same weight and the last one is heavier. I also have a balance beam to weigh the coins with. I can only use the balance beam 2 times to find the heavier coin.... In an informal survey, Loftesness found that only one out of every 15 engineering managers received formal management training prior to becoming a manager. When asked which methods had been most helpful for learning to manage effectively, nearly 75% reported “trial and error,” half cited feedback from direct reports, and 40% said observing peer managers. Developer Of People - A good engineering manager will make sure all employees have a growth plan to learn new skills so they won't stagnate in their jobs and will always be challenged with new problems. A strong engineer manager knows how to grow her people through 1:1s, coding labs, and career plans. 28/12/2018 · An engineering manager must be a fully licensed, professional engineer. There are a wide range of specialization options available in engineering, ranging from electronic to civil engineering . In order to become a professional engineer (P.Eng), all candidates must complete a university undergraduate degree in engineering. In an informal survey, Loftesness found that only one out of every 15 engineering managers received formal management training prior to becoming a manager. When asked which methods had been most helpful for learning to manage effectively, nearly 75% reported “trial and error,” half cited feedback from direct reports, and 40% said observing peer managers. A project engineering manager's median annual salary is around $126,084. Is it worth the education and licensure requirements? Get the truth about job duties and career prospects to find out if becoming a project engineering manager is right for you.
# -*- coding: utf-8 -*- # Author: Henry Lin <[email protected]> # Tom Dupré la Tour # License: BSD import numbers import numpy as np import warnings from . import OneHotEncoder from ..base import BaseEstimator, TransformerMixin from ..utils.validation import check_array from ..utils.validation import check_is_fitted from ..utils.validation import _deprecate_positional_args class KBinsDiscretizer(TransformerMixin, BaseEstimator): """ Bin continuous data into intervals. Read more in the :ref:`User Guide <preprocessing_discretization>`. .. versionadded:: 0.20 Parameters ---------- n_bins : int or array-like, shape (n_features,) (default=5) The number of bins to produce. Raises ValueError if ``n_bins < 2``. encode : {'onehot', 'onehot-dense', 'ordinal'}, (default='onehot') Method used to encode the transformed result. onehot Encode the transformed result with one-hot encoding and return a sparse matrix. Ignored features are always stacked to the right. onehot-dense Encode the transformed result with one-hot encoding and return a dense array. Ignored features are always stacked to the right. ordinal Return the bin identifier encoded as an integer value. strategy : {'uniform', 'quantile', 'kmeans'}, (default='quantile') Strategy used to define the widths of the bins. uniform All bins in each feature have identical widths. quantile All bins in each feature have the same number of points. kmeans Values in each bin have the same nearest center of a 1D k-means cluster. dtype : {np.float32, np.float64}, default=None The desired data-type for the output. If None, output dtype is consistent with input dtype. Only np.float32 and np.float64 are supported. Attributes ---------- n_bins_ : int array, shape (n_features,) Number of bins per feature. Bins whose width are too small (i.e., <= 1e-8) are removed with a warning. bin_edges_ : array of arrays, shape (n_features, ) The edges of each bin. Contain arrays of varying shapes ``(n_bins_, )`` Ignored features will have empty arrays. See Also -------- sklearn.preprocessing.Binarizer : Class used to bin values as ``0`` or ``1`` based on a parameter ``threshold``. Notes ----- In bin edges for feature ``i``, the first and last values are used only for ``inverse_transform``. During transform, bin edges are extended to:: np.concatenate([-np.inf, bin_edges_[i][1:-1], np.inf]) You can combine ``KBinsDiscretizer`` with :class:`~sklearn.compose.ColumnTransformer` if you only want to preprocess part of the features. ``KBinsDiscretizer`` might produce constant features (e.g., when ``encode = 'onehot'`` and certain bins do not contain any data). These features can be removed with feature selection algorithms (e.g., :class:`~sklearn.feature_selection.VarianceThreshold`). Examples -------- >>> X = [[-2, 1, -4, -1], ... [-1, 2, -3, -0.5], ... [ 0, 3, -2, 0.5], ... [ 1, 4, -1, 2]] >>> est = KBinsDiscretizer(n_bins=3, encode='ordinal', strategy='uniform') >>> est.fit(X) KBinsDiscretizer(...) >>> Xt = est.transform(X) >>> Xt # doctest: +SKIP array([[ 0., 0., 0., 0.], [ 1., 1., 1., 0.], [ 2., 2., 2., 1.], [ 2., 2., 2., 2.]]) Sometimes it may be useful to convert the data back into the original feature space. The ``inverse_transform`` function converts the binned data into the original feature space. Each value will be equal to the mean of the two bin edges. >>> est.bin_edges_[0] array([-2., -1., 0., 1.]) >>> est.inverse_transform(Xt) array([[-1.5, 1.5, -3.5, -0.5], [-0.5, 2.5, -2.5, -0.5], [ 0.5, 3.5, -1.5, 0.5], [ 0.5, 3.5, -1.5, 1.5]]) """ @_deprecate_positional_args def __init__(self, n_bins=5, encode='onehot', strategy='quantile', dtype=None): self.n_bins = n_bins self.encode = encode self.strategy = strategy self.dtype = dtype def fit(self, X, y=None): """ Fit the estimator. Parameters ---------- X : numeric array-like, shape (n_samples, n_features) Data to be discretized. y : None Ignored. This parameter exists only for compatibility with :class:`~sklearn.pipeline.Pipeline`. Returns ------- self """ X = self._validate_data(X, dtype='numeric') supported_dtype = (np.float64, np.float32) if self.dtype in supported_dtype: output_dtype = self.dtype elif self.dtype is None: output_dtype = X.dtype else: raise ValueError( f"Valid options for 'dtype' are " f"{supported_dtype + (None,)}. Got dtype={self.dtype} " f" instead." ) valid_encode = ('onehot', 'onehot-dense', 'ordinal') if self.encode not in valid_encode: raise ValueError("Valid options for 'encode' are {}. " "Got encode={!r} instead." .format(valid_encode, self.encode)) valid_strategy = ('uniform', 'quantile', 'kmeans') if self.strategy not in valid_strategy: raise ValueError("Valid options for 'strategy' are {}. " "Got strategy={!r} instead." .format(valid_strategy, self.strategy)) n_features = X.shape[1] n_bins = self._validate_n_bins(n_features) bin_edges = np.zeros(n_features, dtype=object) for jj in range(n_features): column = X[:, jj] col_min, col_max = column.min(), column.max() if col_min == col_max: warnings.warn("Feature %d is constant and will be " "replaced with 0." % jj) n_bins[jj] = 1 bin_edges[jj] = np.array([-np.inf, np.inf]) continue if self.strategy == 'uniform': bin_edges[jj] = np.linspace(col_min, col_max, n_bins[jj] + 1) elif self.strategy == 'quantile': quantiles = np.linspace(0, 100, n_bins[jj] + 1) bin_edges[jj] = np.asarray(np.percentile(column, quantiles)) elif self.strategy == 'kmeans': from ..cluster import KMeans # fixes import loops # Deterministic initialization with uniform spacing uniform_edges = np.linspace(col_min, col_max, n_bins[jj] + 1) init = (uniform_edges[1:] + uniform_edges[:-1])[:, None] * 0.5 # 1D k-means procedure km = KMeans(n_clusters=n_bins[jj], init=init, n_init=1) centers = km.fit(column[:, None]).cluster_centers_[:, 0] # Must sort, centers may be unsorted even with sorted init centers.sort() bin_edges[jj] = (centers[1:] + centers[:-1]) * 0.5 bin_edges[jj] = np.r_[col_min, bin_edges[jj], col_max] # Remove bins whose width are too small (i.e., <= 1e-8) if self.strategy in ('quantile', 'kmeans'): mask = np.ediff1d(bin_edges[jj], to_begin=np.inf) > 1e-8 bin_edges[jj] = bin_edges[jj][mask] if len(bin_edges[jj]) - 1 != n_bins[jj]: warnings.warn('Bins whose width are too small (i.e., <= ' '1e-8) in feature %d are removed. Consider ' 'decreasing the number of bins.' % jj) n_bins[jj] = len(bin_edges[jj]) - 1 self.bin_edges_ = bin_edges self.n_bins_ = n_bins if 'onehot' in self.encode: self._encoder = OneHotEncoder( categories=[np.arange(i) for i in self.n_bins_], sparse=self.encode == 'onehot', dtype=output_dtype) # Fit the OneHotEncoder with toy datasets # so that it's ready for use after the KBinsDiscretizer is fitted self._encoder.fit(np.zeros((1, len(self.n_bins_)))) return self def _validate_n_bins(self, n_features): """Returns n_bins_, the number of bins per feature. """ orig_bins = self.n_bins if isinstance(orig_bins, numbers.Number): if not isinstance(orig_bins, numbers.Integral): raise ValueError("{} received an invalid n_bins type. " "Received {}, expected int." .format(KBinsDiscretizer.__name__, type(orig_bins).__name__)) if orig_bins < 2: raise ValueError("{} received an invalid number " "of bins. Received {}, expected at least 2." .format(KBinsDiscretizer.__name__, orig_bins)) return np.full(n_features, orig_bins, dtype=int) n_bins = check_array(orig_bins, dtype=int, copy=True, ensure_2d=False) if n_bins.ndim > 1 or n_bins.shape[0] != n_features: raise ValueError("n_bins must be a scalar or array " "of shape (n_features,).") bad_nbins_value = (n_bins < 2) | (n_bins != orig_bins) violating_indices = np.where(bad_nbins_value)[0] if violating_indices.shape[0] > 0: indices = ", ".join(str(i) for i in violating_indices) raise ValueError("{} received an invalid number " "of bins at indices {}. Number of bins " "must be at least 2, and must be an int." .format(KBinsDiscretizer.__name__, indices)) return n_bins def transform(self, X): """ Discretize the data. Parameters ---------- X : numeric array-like, shape (n_samples, n_features) Data to be discretized. Returns ------- Xt : numeric array-like or sparse matrix Data in the binned space. """ check_is_fitted(self) # check input and attribute dtypes dtype = (np.float64, np.float32) if self.dtype is None else self.dtype Xt = check_array(X, copy=True, dtype=dtype) n_features = self.n_bins_.shape[0] if Xt.shape[1] != n_features: raise ValueError("Incorrect number of features. Expecting {}, " "received {}.".format(n_features, Xt.shape[1])) bin_edges = self.bin_edges_ for jj in range(Xt.shape[1]): # Values which are close to a bin edge are susceptible to numeric # instability. Add eps to X so these values are binned correctly # with respect to their decimal truncation. See documentation of # numpy.isclose for an explanation of ``rtol`` and ``atol``. rtol = 1.e-5 atol = 1.e-8 eps = atol + rtol * np.abs(Xt[:, jj]) Xt[:, jj] = np.digitize(Xt[:, jj] + eps, bin_edges[jj][1:]) np.clip(Xt, 0, self.n_bins_ - 1, out=Xt) if self.encode == 'ordinal': return Xt dtype_init = None if 'onehot' in self.encode: dtype_init = self._encoder.dtype self._encoder.dtype = Xt.dtype try: Xt_enc = self._encoder.transform(Xt) finally: # revert the initial dtype to avoid modifying self. self._encoder.dtype = dtype_init return Xt_enc def inverse_transform(self, Xt): """ Transform discretized data back to original feature space. Note that this function does not regenerate the original data due to discretization rounding. Parameters ---------- Xt : numeric array-like, shape (n_sample, n_features) Transformed data in the binned space. Returns ------- Xinv : numeric array-like Data in the original feature space. """ check_is_fitted(self) if 'onehot' in self.encode: Xt = self._encoder.inverse_transform(Xt) Xinv = check_array(Xt, copy=True, dtype=(np.float64, np.float32)) n_features = self.n_bins_.shape[0] if Xinv.shape[1] != n_features: raise ValueError("Incorrect number of features. Expecting {}, " "received {}.".format(n_features, Xinv.shape[1])) for jj in range(n_features): bin_edges = self.bin_edges_[jj] bin_centers = (bin_edges[1:] + bin_edges[:-1]) * 0.5 Xinv[:, jj] = bin_centers[np.int_(Xinv[:, jj])] return Xinv
Janice has been writing from primary school age, starting with some truly dreadful poetry and a Western novel. Fortunately these attempts no longer exist. A love of reading and a fertile imagination improved her later attempts, together with the discipline of journal keeping (see Henry Tilney’s remarks in Jane Austen’s ‘Northanger Abbey’ for the effectiveness of journal writing for ladies). Being a writer conveys Licence to Imagine. She is a retired optometrist, married to John, and lives on a rural property looking onto the Grampians. She enjoys writing short fiction and poetry; also edits the newsletter of her church community, has composed lyrics for a community singing group, and has written a play for a local theatre company. She is currently President of Grampians Writers Group, and a member of SWWV’s postal workshops, ‘eSpring’and ‘Perennial Poets’. Living in the country, postal workshops provide stimulus and accountability. 1st and 3rd Prizes, Wimmera Regional Library Corp. 2016. 1st Prize, Bundaberg Writers Short Story competition. 1st Prize, FAW Tasmania Short Story competition. 2nd Prize, Churchill & District News Poetry competition.
#! /usr/bin/env python import urllib from xml.dom import minidom, Node import json #1)get daa from internet archive in json format 2)clean the json to get identifier, format, title, date, and description ka_archive_json = 'http://www.archive.org/advancedsearch.php?q=collection%3A%22khanacademy%22&fl%5B%5D=collection&fl%5B%5D=date&fl%5B%5D=description&fl%5B%5D=format&fl%5B%5D=identifier&fl%5B%5D=publicdate&fl%5B%5D=title&sort%5B%5D=&sort%5B%5D=&sort%5B%5D=&rows=2735&page=1&output=json' json_dictionary = json.load(urllib.urlopen(ka_archive_json)) docs = json_dictionary['response']['docs'] clean = {} for doc in docs: identifier = doc['identifier'] clean[identifier] = {} clean[identifier]['format'] = doc['format'] clean[identifier]['title'] = doc['title'] clean[identifier]['publicdate'] = doc['publicdate'] if doc.has_key('description'): clean[identifier]['description'] = doc['description'] else: clean[identifier]['description'] = "No decsription available" print clean print len(clean)
Does status justify transgression? Does it nullify suffering? The concept of psychological suffering in an ordinary man is embodied as guilt inspired masochism in Dostoevsky's book Crime and Punishment. He brings forward the 'Napoleons' - an elite people group so vital to humanity, their predestined greatness grants them freedom from ethical restraints. 'Napoleonism' hints at the difference between our true selves and ideal selves. The relentless pull of the idealised self is eternal - few ever reach it. Is this self the 'Napoleon' within us all? Or are these 'Napoleons' simply ordinary men pictured through a subjective consciousness? (does anything exist otherwise?) The craving to be a 'Napoleon', and the reality of the ordinary human condition war against each other, begging the question: is power an intrinsic birthright? The subject of the painting 'Napoleon' looks down upon the audience, adorned with a halo and against a royal red. She sits as someone above ordinary man, someone predestined for greatness. She represents a natural order amongst chaos, and to those she has trodden over she represents the power of the universe; a deity. Her sense of self expands beyond what her body can contain, indicated in the dissonance of her features. Within these features, is some part of her ordinary? Does she see what we see?
from django.core.management.base import NoArgsCommand from ec2spotmanager.models import PoolUptimeDetailedEntry, PoolUptimeAccumulatedEntry, InstancePool, Instance, INSTANCE_STATE from django.conf import settings from ec2spotmanager.management.common import pid_lock_file import time import logging from django.utils import timezone from django.db.models.query_utils import Q stats_delta_secs = 60*15 # 30 minutes stats_total_detailed = 24 # How many hours the detailed statistics should include stats_total_accumulated = 30 # How many days should we keep accumulated statistics class Command(NoArgsCommand): help = "Check the status of all bugs we have" @pid_lock_file("stats_daemon") def handle_noargs(self, **options): print(options) while True: self.check_instance_pools() time.sleep(60) def check_instance_pools(self): instance_pools = InstancePool.objects.all() # Process all instance pools for pool in instance_pools: if not pool.isEnabled: continue current_delta = timezone.datetime.now() - timezone.timedelta(seconds=stats_delta_secs) entries = PoolUptimeDetailedEntry.objects.filter(pool=pool, created__gte = current_delta) # We should never have more than one entry per time-delta assert(len(entries) < 2) if entries: current_delta_entry = entries[0] else: # Create a new entry current_delta_entry = PoolUptimeDetailedEntry() current_delta_entry.pool = pool current_delta_entry.target = pool.config.flatten().size actual = len(Instance.objects.filter(pool=pool).filter(Q(status_code=INSTANCE_STATE['pending'])| Q(status_code=INSTANCE_STATE['running']))) if current_delta_entry.actual == None or actual < current_delta_entry.actual: current_delta_entry.actual = actual # This will only save if necessary, i.e. if the entry already existed and the values # have not changed, this will not cause I/O on the database with Django >=1.5 current_delta_entry.save() # Now check if we need to aggregate some of the detail entries we have entries = PoolUptimeDetailedEntry.objects.filter(pool=pool).order_by('created') n = len(entries) - (stats_total_detailed*60*60)/stats_delta_secs if n > 0: # We need to aggregate some entries entriesAggr = entries[0:n] for entry in entriesAggr: # Figure out if we have an aggregated entry already with the same date day_entries = PoolUptimeAccumulatedEntry.objects.filter(pool=pool, created__contains=entry.created.date()) # We should never have more than one entry per day assert(len(day_entries) < 2) if day_entries: day_entry = day_entries[0] else: day_entry = PoolUptimeAccumulatedEntry() day_entry.pool = pool day_entry.created = entry.created day_entry.uptime_percentage = 0.0 entry_percentage = (float(entry.actual) / entry.target) * 100 new_uptime_percentage = ((float(day_entry.uptime_percentage) * day_entry.accumulated_count) + entry_percentage) / (day_entry.accumulated_count + 1) day_entry.uptime_percentage = new_uptime_percentage day_entry.accumulated_count = day_entry.accumulated_count + 1 day_entry.save() # We can now delete our entry entry.delete() # Finally check if we need to expire some accumulated entries entries = PoolUptimeAccumulatedEntry.objects.filter(pool=pool).order_by('created') n = len(entries) - stats_total_accumulated if n > 0: for entry in entries[0:n]: entry.delete()
When we travel the world, we love to ride bicycles in every city we visit. Luckily we have never had a problem, but if we did we would need a bag full of tools to handle any fixes or adjustments that are needed. That did not work for us so we found a better solution for ourselves and the members of our C Larboard Community like YOU. Now you can simply carry this clever Cat Design EDC Multi Tool that is 7 tools in 1. With our EDC Cat Tool you can cut a piece of rope or twine, tighten a screw or a bicycle spoke and even open a bottle. Just attach the Cat EDC Gadget to a key chain ring and it slips into your pocket or purse. It’s an ideal gift – Father’s Day, housewarming, birthdays, weddings, off to college, Christmas! This pocket tool is the perfect addition to any keychain. Now I’ve always got a few vital tools close by.
#import logging import httplib, urllib import simplejson as json class NikolaAPI(): def _get_headers(self): #if self.cookie is None: raise Exception, "no cookie available" headers = {'content-type':'text/plain'} #headers['cookie'] = self.cookie return headers def _request_get(self, server, url, params): try: conn = httplib.HTTPConnection(server) headers = self._get_headers() task_url = '%s?%s' % (url, urllib.urlencode(params)) conn.request("GET", task_url, headers=headers) response = conn.getresponse() content = response.read() #print "######" #print content '''res_json = json.loads(content).values()[0] if 'errorcode' in res_json: raise Exception, res_json['errortext'] if ret_attr_name: if ret_attr_name in res_json: return res_json[ret_attr_name] else: return []''' res_json = json.loads(content) return res_json except Exception, ex: print ex raise ex def _request_post(self, server, url, param_json): try: conn = httplib.HTTPConnection(server) headers = self._get_headers() if param_json: if headers: conn.request("POST", url, json.dumps(param_json), headers=headers) else: conn.request("POST", url, json.dumps(param_json)) else: if headers: conn.request("POST", url, headers=headers) else: conn.request("POST", url) response = conn.getresponse() content = response.read() #print "######" #print content res_json = json.loads(content) return res_json except Exception, ex: print ex raise ex def send(self, host='172.20.1.14:3000', url='/useast1/nikola/r2/', method='POST', data=None): request_type = method if data: params = json.loads(data) #print params else: params = None if params: for key in params.keys(): type_name = type(params[key]).__name__ if type_name == 'dict' or type_name == 'list': params[key] = json.dumps(params[key]) elif type_name != 'str': params[key] = str(params[key]) #params = json.dumps(params) #print params if request_type == 'POST': ret = self._request_post(host, url, params) else: ret = self._request_get(host, url, params) #ret = self._request(host, url, request_type, data) #print ret return {'result':ret}
BLOOMSBURG — With graduation just around the corner, seven art studio majors will showcase their final pieces in Bloomsburg University of Pennsylvania’s annual Fall Senior Exit Show. The exhibit, the final requirement for all graduating art and art history majors, will run from Thursday, Nov. 19, to Saturday, Dec. 12, in Haas Center for the Arts, room 203. Admission to the gallery is free and open to the public. In the Fall Senior Exit Show, each student will present a selection of his or her best artwork and deliver a 15-minute presentation that describes the works, current philosophy, and how they plan to further their careers in the future. The gallery will be open Mondays through Fridays from 9 a.m. to 4:30 p.m., and Saturdays from noon to 2 p.m. An opening reception will be held on Thursday, Nov. 19, from 11 a.m. to 2 p.m. in Haas Center.