code
stringlengths 2
1.05M
| repo_name
stringlengths 5
104
| path
stringlengths 4
251
| language
stringclasses 1
value | license
stringclasses 15
values | size
int32 2
1.05M
|
---|---|---|---|---|---|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('booking', '0017_auto_20150309_1910'),
]
operations = [
migrations.AlterField(
model_name='booking',
name='date',
field=models.DateTimeField(auto_now_add=True, db_index=True),
preserve_default=True,
),
migrations.AlterField(
model_name='booking',
name='status',
field=models.CharField(default=b'pending', max_length=30, db_index=True, choices=[(b'pending', '\u041e\u0436\u0438\u0434\u0430\u0435\u0442 \u0438\u0441\u043f\u043e\u043b\u043d\u0438\u0442\u0435\u043b\u044f'), (b'waiting_for_approval', '\u041e\u0436\u0438\u0434\u0430\u0435\u0442 \u043f\u043e\u0434\u0442\u0432\u0435\u0440\u0436\u0434\u0435\u043d\u0438\u044f \u0437\u0430\u043a\u0430\u0437\u0447\u0438\u043a\u043e\u043c'), (b'running', '\u0412\u0437\u044f\u0442 \u043d\u0430 \u0438\u0441\u043f\u043e\u043b\u043d\u0435\u043d\u0438\u0435'), (b'completed', '\u0417\u0430\u0432\u0435\u0440\u0448\u0435\u043d')]),
preserve_default=True,
),
migrations.AlterField(
model_name='comment',
name='date',
field=models.DateTimeField(auto_now_add=True, db_index=True),
preserve_default=True,
),
]
| bo858585/AbstractBooking | Booking/booking/migrations/0018_auto_20150310_1533.py | Python | mit | 1,427 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
file: __main__.py
Description: the entry point to SEM.
author: Yoann Dupont
MIT License
Copyright (c) 2018 Yoann Dupont
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
from __future__ import print_function
import logging
import os.path
import unittest
import sys
import sem
import sem.modules
from sem.logger import logging_format
from sem.misc import find_suggestions
sem_logger = logging.getLogger("sem")
def valid_module(m):
return m.endswith(".py") and not (m.startswith(u"_") or m in ["sem_module.py", "pipeline.py"])
def main(args=None):
def banter():
def username():
import os
return os.environ.get("USERNAME", os.environ.get("USER", os.path.split(os.path.expanduser(u"~"))[-1]))
import random
l = [
u"Do thou mockest me?",
u"Try again?",
u"I'm sorry {0}, I'm afraid I can't do that.".format(username()),
u'The greatest trick this module ever pulled what convincing the users it did not exist.',
u"It's just a typo."
]
random.shuffle(l)
return l[0]
modules = {}
for element in os.listdir(os.path.join(sem.SEM_HOME, "modules")):
m = element[:-3]
if valid_module(element):
modules[m] = sem.modules.get_package(m)
name = os.path.basename(sys.argv[0])
operation = (sys.argv[1] if len(sys.argv) > 1 else "-h")
if operation in modules:
module = modules[operation]
module.main(sem.argument_parser.parse_args())
elif operation in ["-h", "--help"]:
print("Usage: {0} <module> [module arguments]\n".format(name))
print("Module list:")
for module in modules:
print("\t{0}".format(module))
print()
print("for SEM's current version: -v or --version\n")
print("for informations about the last revision: -i or --informations")
print("for playing all tests: --test")
elif operation in ["-v", "--version"]:
print(sem.full_name())
elif operation in ["-i", "--informations"]:
informations = sem.informations()
try:
print(informations)
except UnicodeEncodeError:
print(informations.encode(sys.getfilesystemencoding(), errors="replace"))
elif operation == "--test":
testsuite = unittest.TestLoader().discover(os.path.join(sem.SEM_HOME, "tests"))
unittest.TextTestRunner(verbosity=2).run(testsuite)
else:
print("Module not found: " + operation)
suggestions = find_suggestions(operation, modules)
if len(suggestions) > 0:
print("Did you mean one of the following?")
for suggestion in suggestions:
print("\t{0}".format(suggestion))
else:
print("No suggestions found...", banter())
if __name__ == "__main__":
main()
| YoannDupont/SEM | sem/__main__.py | Python | mit | 3,899 |
from django.conf.urls import patterns, include, url
from darkoob.book import views as book_views
urlpatterns = patterns('',
url(r'^(?P<book_id>\d+)/(?P<book_title>[a-zA-Z0-9\-_]+)/$', book_views.page, name='book_page'),
url(r'^look/$', book_views.book_lookup),
url(r'^author/$', book_views.author_lookup),
# url(r'^rate/$', book_views.rate, name='rate'),
)
| s1na/darkoob | darkoob/book/urls.py | Python | mit | 374 |
"""
Django settings for testproject project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'n$(okl9n*#au0%^wxgu$c#x(f%lby3v_j)wuti&6q-nx_35uj6'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'testproject.urls'
WSGI_APPLICATION = 'testproject.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/
STATIC_URL = '/static/'
| adamhaney/django-ipython-notebook-reports | testproject/testproject/settings.py | Python | mit | 1,987 |
"""
The consumer's code.
It takes HTML from the queue and outputs the URIs found in it.
"""
import asyncio
import json
import logging
from typing import List
from urllib.parse import urljoin
import aioredis
from bs4 import BeautifulSoup
from . import app_cli, redis_queue
_log = logging.getLogger('url_extractor')
def _scrape_urls(html: str, base_url: str) -> List[str]:
"""Gets all valid links from a site and returns them as URIs (some links may be relative.
If the URIs scraped here would go back into the system to have more URIs scraped from their
HTML, we would need to filter out all those who are not HTTP or HTTPS.
Also, assuming that many consumers and many producers would be running at the same time,
connected to one Redis instance, we would need to cache normalized versions or visited URIs
without fragments (https://tools.ietf.org/html/rfc3986#section-3.5) so we don't fall into loops.
For example two sites referencing each other.
The cached entries could have time-to-live (Redis EXPIRE command), so we could refresh our
knowledge about a site eventually.
"""
soup = BeautifulSoup(html, 'html.parser')
href = 'href'
return [urljoin(base_url, link.get(href))
for link in soup.find_all('a') if link.has_attr(href)]
async def _scrape_urls_from_queued_html(redis_pool: aioredis.RedisPool):
_log.info('Processing HTML from queue...')
while True:
try:
html_payload = await redis_queue.pop(redis_pool)
_log.info('Processing HTML from URL %s', html_payload.url)
scraped_urls = _scrape_urls(html_payload.html, html_payload.url)
_log.info('Scraped URIs from URL %s', html_payload.url)
output_json = {html_payload.url: scraped_urls}
# flush for anyone who is watching the stream
print(json.dumps(output_json), flush=True)
except redis_queue.QueueEmptyError:
# wait for work to become available
await asyncio.sleep(1) # pragma: no cover
def main():
"""Run the URL extractor (the consumer).
"""
app_cli.setup_logging()
args_parser = app_cli.get_redis_args_parser(
'Start a worker that will get URL/HTML pairs from a Redis queue and for each of those '
'pairs output (on separate lines) a JSON in format {ORIGINATING_URL: [FOUND_URLS_LIST]}')
args = args_parser.parse_args()
loop = app_cli.get_event_loop()
_log.info('Creating a pool of connections to Redis at %s:%d.',
args.redis_host, args.redis_port)
# the pool won't be closed explicitly, since the process needs to be terminated to stop anyway
redis_pool = loop.run_until_complete(
aioredis.create_pool((args.redis_host, args.redis_port)))
loop.run_until_complete(_scrape_urls_from_queued_html(redis_pool))
if __name__ == '__main__':
main()
| butla/experiments | aiohttp_redis_producer_consumer/txodds_code_test/url_extractor.py | Python | mit | 2,896 |
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType
import copy as _copy
class Legendgrouptitle(_BaseTraceHierarchyType):
# class properties
# --------------------
_parent_path_str = "histogram2d"
_path_str = "histogram2d.legendgrouptitle"
_valid_props = {"font", "text"}
# font
# ----
@property
def font(self):
"""
Sets this legend group's title font.
The 'font' property is an instance of Font
that may be specified as:
- An instance of :class:`plotly.graph_objs.histogram2d.legendgrouptitle.Font`
- A dict of string/value properties that will be passed
to the Font constructor
Supported dict properties:
color
family
HTML font family - the typeface that will be
applied by the web browser. The web browser
will only be able to apply a font if it is
available on the system which it operates.
Provide multiple font families, separated by
commas, to indicate the preference in which to
apply fonts if they aren't available on the
system. The Chart Studio Cloud (at
https://chart-studio.plotly.com or on-premise)
generates images on a server, where only a
select number of fonts are installed and
supported. These include "Arial", "Balto",
"Courier New", "Droid Sans",, "Droid Serif",
"Droid Sans Mono", "Gravitas One", "Old
Standard TT", "Open Sans", "Overpass", "PT Sans
Narrow", "Raleway", "Times New Roman".
size
Returns
-------
plotly.graph_objs.histogram2d.legendgrouptitle.Font
"""
return self["font"]
@font.setter
def font(self, val):
self["font"] = val
# text
# ----
@property
def text(self):
"""
Sets the title of the legend group.
The 'text' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
"""
return self["text"]
@text.setter
def text(self, val):
self["text"] = val
# Self properties description
# ---------------------------
@property
def _prop_descriptions(self):
return """\
font
Sets this legend group's title font.
text
Sets the title of the legend group.
"""
def __init__(self, arg=None, font=None, text=None, **kwargs):
"""
Construct a new Legendgrouptitle object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.histogram2d.Legendgrouptitle`
font
Sets this legend group's title font.
text
Sets the title of the legend group.
Returns
-------
Legendgrouptitle
"""
super(Legendgrouptitle, self).__init__("legendgrouptitle")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
# Validate arg
# ------------
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError(
"""\
The first argument to the plotly.graph_objs.histogram2d.Legendgrouptitle
constructor must be a dict or
an instance of :class:`plotly.graph_objs.histogram2d.Legendgrouptitle`"""
)
# Handle skip_invalid
# -------------------
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
# Populate data dict with properties
# ----------------------------------
_v = arg.pop("font", None)
_v = font if font is not None else _v
if _v is not None:
self["font"] = _v
_v = arg.pop("text", None)
_v = text if text is not None else _v
if _v is not None:
self["text"] = _v
# Process unknown kwargs
# ----------------------
self._process_kwargs(**dict(arg, **kwargs))
# Reset skip_invalid
# ------------------
self._skip_invalid = False
| plotly/plotly.py | packages/python/plotly/plotly/graph_objs/histogram2d/_legendgrouptitle.py | Python | mit | 4,724 |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from dataclasses import dataclass, field
import itertools
import logging
import os
import numpy as np
import torch
from fairseq import metrics
from fairseq.data import (
ConcatDataset,
ConcatSentencesDataset,
data_utils,
Dictionary,
IdDataset,
indexed_dataset,
NestedDictionaryDataset,
NumSamplesDataset,
NumelDataset,
PrependTokenDataset,
RawLabelDataset,
RightPadDataset,
SortDataset,
TruncateDataset,
TokenBlockDataset,
)
from fairseq.dataclass import ChoiceEnum, FairseqDataclass
from fairseq.tasks import FairseqTask, register_task
from omegaconf import II, MISSING
EVAL_BLEU_ORDER = 4
TARGET_METRIC_CHOICES = ChoiceEnum(["bleu", "ter"])
logger = logging.getLogger(__name__)
@dataclass
class DiscriminativeRerankingNMTConfig(FairseqDataclass):
data: str = field(default=MISSING, metadata={"help": "path to data directory"})
num_data_splits: int = field(
default=1, metadata={"help": "total number of data splits"}
)
no_shuffle: bool = field(
default=False, metadata={"help": "do not shuffle training data"}
)
max_positions: int = field(
default=512, metadata={"help": "number of positional embeddings to learn"}
)
include_src: bool = field(
default=False, metadata={"help": "include source sentence"}
)
mt_beam: int = field(default=50, metadata={"help": "beam size of input hypotheses"})
eval_target_metric: bool = field(
default=False,
metadata={"help": "evaluation with the target metric during validation"},
)
target_metric: TARGET_METRIC_CHOICES = field(
default="bleu", metadata={"help": "name of the target metric to optimize for"}
)
train_subset: str = field(
default=II("dataset.train_subset"),
metadata={"help": "data subset to use for training (e.g. train, valid, test)"},
)
seed: int = field(
default=II("common.seed"),
metadata={"help": "pseudo random number generator seed"},
)
class RerankerScorer(object):
"""Scores the target for a given (source (optional), target) input."""
def __init__(self, args, mt_beam):
self.mt_beam = mt_beam
@torch.no_grad()
def generate(self, models, sample, **kwargs):
"""Score a batch of translations."""
net_input = sample["net_input"]
assert len(models) == 1, "does not support model ensemble"
model = models[0]
bs = net_input["src_tokens"].shape[0]
assert (
model.joint_classification == "none" or bs % self.mt_beam == 0
), f"invalid batch size ({bs}) for joint classification with beam size ({self.mt_beam})"
model.eval()
logits = model(**net_input)
batch_out = model.sentence_forward(logits, net_input["src_tokens"])
if model.joint_classification == "sent":
batch_out = model.joint_forward(
batch_out.view(self.mt_beam, bs // self.mt_beam, -1)
)
scores = model.classification_forward(
batch_out.view(bs, 1, -1)
) # input: B x T x C
return scores
@register_task(
"discriminative_reranking_nmt", dataclass=DiscriminativeRerankingNMTConfig
)
class DiscriminativeRerankingNMTTask(FairseqTask):
"""
Translation rerank task.
The input can be either (src, tgt) sentence pairs or tgt sentence only.
"""
cfg: DiscriminativeRerankingNMTConfig
def __init__(self, cfg: DiscriminativeRerankingNMTConfig, data_dictionary=None):
super().__init__(cfg)
self.dictionary = data_dictionary
self._max_positions = cfg.max_positions
# args.tokens_per_sample = self._max_positions
# self.num_classes = 1 # for model
@classmethod
def load_dictionary(cls, cfg, filename):
"""Load the dictionary from the filename"""
dictionary = Dictionary.load(filename)
dictionary.add_symbol("<mask>") # for loading pretrained XLMR model
return dictionary
@classmethod
def setup_task(cls, cfg: DiscriminativeRerankingNMTConfig, **kwargs):
# load data dictionary (assume joint dictionary)
data_path = cfg.data
data_dict = cls.load_dictionary(
cfg, os.path.join(data_path, "input_src/dict.txt")
)
logger.info("[input] src dictionary: {} types".format(len(data_dict)))
return DiscriminativeRerankingNMTTask(cfg, data_dict)
def load_dataset(self, split, epoch=0, combine=False, **kwargs):
"""Load a given dataset split (e.g., train, valid, test)."""
if self.cfg.data.endswith("1"):
data_shard = (epoch - 1) % self.cfg.num_data_splits + 1
data_path = self.cfg.data[:-1] + str(data_shard)
else:
data_path = self.cfg.data
def get_path(type, data_split):
return os.path.join(data_path, str(type), data_split)
def make_dataset(type, dictionary, data_split, combine):
split_path = get_path(type, data_split)
dataset = data_utils.load_indexed_dataset(
split_path,
dictionary,
combine=combine,
)
return dataset
def load_split(data_split, metric):
input_src = None
if self.cfg.include_src:
input_src = make_dataset(
"input_src", self.dictionary, data_split, combine=False
)
assert input_src is not None, "could not find dataset: {}".format(
get_path("input_src", data_split)
)
input_tgt = make_dataset(
"input_tgt", self.dictionary, data_split, combine=False
)
assert input_tgt is not None, "could not find dataset: {}".format(
get_path("input_tgt", data_split)
)
label_path = f"{get_path(metric, data_split)}.{metric}"
assert os.path.exists(label_path), f"could not find dataset: {label_path}"
np_labels = np.loadtxt(label_path)
if self.cfg.target_metric == "ter":
np_labels = -np_labels
label = RawLabelDataset(np_labels)
return input_src, input_tgt, label
src_datasets = []
tgt_datasets = []
label_datasets = []
if split == self.cfg.train_subset:
for k in itertools.count():
split_k = "train" + (str(k) if k > 0 else "")
prefix = os.path.join(data_path, "input_tgt", split_k)
if not indexed_dataset.dataset_exists(prefix, impl=None):
if k > 0:
break
else:
raise FileNotFoundError(f"Dataset not found: {prefix}")
input_src, input_tgt, label = load_split(
split_k, self.cfg.target_metric
)
src_datasets.append(input_src)
tgt_datasets.append(input_tgt)
label_datasets.append(label)
else:
input_src, input_tgt, label = load_split(split, self.cfg.target_metric)
src_datasets.append(input_src)
tgt_datasets.append(input_tgt)
label_datasets.append(label)
if len(tgt_datasets) == 1:
input_tgt, label = tgt_datasets[0], label_datasets[0]
if self.cfg.include_src:
input_src = src_datasets[0]
else:
input_tgt = ConcatDataset(tgt_datasets)
label = ConcatDataset(label_datasets)
if self.cfg.include_src:
input_src = ConcatDataset(src_datasets)
input_tgt = TruncateDataset(input_tgt, self.cfg.max_positions)
if self.cfg.include_src:
input_src = PrependTokenDataset(input_src, self.dictionary.bos())
input_src = TruncateDataset(input_src, self.cfg.max_positions)
src_lengths = NumelDataset(input_src, reduce=False)
src_tokens = ConcatSentencesDataset(input_src, input_tgt)
else:
src_tokens = PrependTokenDataset(input_tgt, self.dictionary.bos())
src_lengths = NumelDataset(src_tokens, reduce=False)
dataset = {
"id": IdDataset(),
"net_input": {
"src_tokens": RightPadDataset(
src_tokens,
pad_idx=self.source_dictionary.pad(),
),
"src_lengths": src_lengths,
},
"nsentences": NumSamplesDataset(),
"ntokens": NumelDataset(src_tokens, reduce=True),
"target": label,
}
dataset = NestedDictionaryDataset(
dataset,
sizes=[src_tokens.sizes],
)
assert (
len(dataset) % self.cfg.mt_beam == 0
), "dataset size (%d) is not a multiple of beam size (%d)" % (
len(dataset),
self.cfg.mt_beam,
)
# no need to shuffle valid/test sets
if not self.cfg.no_shuffle and split == self.cfg.train_subset:
# need to keep all hypothese together
start_idx = np.arange(0, len(dataset), self.cfg.mt_beam)
with data_utils.numpy_seed(self.cfg.seed + epoch):
np.random.shuffle(start_idx)
idx = np.arange(0, self.cfg.mt_beam)
shuffle = np.tile(idx, (len(start_idx), 1)).reshape(-1) + np.tile(
start_idx, (self.cfg.mt_beam, 1)
).transpose().reshape(-1)
dataset = SortDataset(
dataset,
sort_order=[shuffle],
)
logger.info(f"Loaded {split} with #samples: {len(dataset)}")
self.datasets[split] = dataset
return self.datasets[split]
def build_dataset_for_inference(self, src_tokens, src_lengths, **kwargs):
assert not self.cfg.include_src or len(src_tokens[0]) == 2
input_src = None
if self.cfg.include_src:
input_src = TokenBlockDataset(
[t[0] for t in src_tokens],
[l[0] for l in src_lengths],
block_size=None, # ignored for "eos" break mode
pad=self.source_dictionary.pad(),
eos=self.source_dictionary.eos(),
break_mode="eos",
)
input_src = PrependTokenDataset(input_src, self.dictionary.bos())
input_src = TruncateDataset(input_src, self.cfg.max_positions)
input_tgt = TokenBlockDataset(
[t[-1] for t in src_tokens],
[l[-1] for l in src_lengths],
block_size=None, # ignored for "eos" break mode
pad=self.source_dictionary.pad(),
eos=self.source_dictionary.eos(),
break_mode="eos",
)
input_tgt = TruncateDataset(input_tgt, self.cfg.max_positions)
if self.cfg.include_src:
src_tokens = ConcatSentencesDataset(input_src, input_tgt)
src_lengths = NumelDataset(input_src, reduce=False)
else:
input_tgt = PrependTokenDataset(input_tgt, self.dictionary.bos())
src_tokens = input_tgt
src_lengths = NumelDataset(src_tokens, reduce=False)
dataset = {
"id": IdDataset(),
"net_input": {
"src_tokens": RightPadDataset(
src_tokens,
pad_idx=self.source_dictionary.pad(),
),
"src_lengths": src_lengths,
},
"nsentences": NumSamplesDataset(),
"ntokens": NumelDataset(src_tokens, reduce=True),
}
return NestedDictionaryDataset(
dataset,
sizes=[src_tokens.sizes],
)
def build_model(self, cfg: FairseqDataclass, from_checkpoint: bool = False):
return super().build_model(cfg)
def build_generator(self, args):
return RerankerScorer(args, mt_beam=self.cfg.mt_beam)
def max_positions(self):
return self._max_positions
@property
def source_dictionary(self):
return self.dictionary
@property
def target_dictionary(self):
return self.dictionary
def create_dummy_batch(self, device):
dummy_target = (
torch.zeros(self.cfg.mt_beam, EVAL_BLEU_ORDER * 2 + 3).long().to(device)
if not self.cfg.eval_ter
else torch.zeros(self.cfg.mt_beam, 3).long().to(device)
)
return {
"id": torch.zeros(self.cfg.mt_beam, 1).long().to(device),
"net_input": {
"src_tokens": torch.zeros(self.cfg.mt_beam, 4).long().to(device),
"src_lengths": torch.ones(self.cfg.mt_beam, 1).long().to(device),
},
"nsentences": 0,
"ntokens": 0,
"target": dummy_target,
}
def train_step(
self, sample, model, criterion, optimizer, update_num, ignore_grad=False
):
if ignore_grad and sample is None:
sample = self.create_dummy_batch(model.device)
return super().train_step(
sample, model, criterion, optimizer, update_num, ignore_grad
)
def valid_step(self, sample, model, criterion):
if sample is None:
sample = self.create_dummy_batch(model.device)
loss, sample_size, logging_output = super().valid_step(sample, model, criterion)
if not self.cfg.eval_target_metric:
return loss, sample_size, logging_output
scores = logging_output["scores"]
if self.cfg.target_metric == "bleu":
assert sample["target"].shape[1] == EVAL_BLEU_ORDER * 2 + 3, (
"target does not contain enough information ("
+ str(sample["target"].shape[1])
+ "for evaluating BLEU"
)
max_id = torch.argmax(scores, dim=1)
select_id = max_id + torch.arange(
0, sample_size * self.cfg.mt_beam, self.cfg.mt_beam
).to(max_id.device)
bleu_data = sample["target"][select_id, 1:].sum(0).data
logging_output["_bleu_sys_len"] = bleu_data[0]
logging_output["_bleu_ref_len"] = bleu_data[1]
for i in range(EVAL_BLEU_ORDER):
logging_output["_bleu_counts_" + str(i)] = bleu_data[2 + i]
logging_output["_bleu_totals_" + str(i)] = bleu_data[
2 + EVAL_BLEU_ORDER + i
]
elif self.cfg.target_metric == "ter":
assert sample["target"].shape[1] == 3, (
"target does not contain enough information ("
+ str(sample["target"].shape[1])
+ "for evaluating TER"
)
max_id = torch.argmax(scores, dim=1)
select_id = max_id + torch.arange(
0, sample_size * self.cfg.mt_beam, self.cfg.mt_beam
).to(max_id.device)
ter_data = sample["target"][select_id, 1:].sum(0).data
logging_output["_ter_num_edits"] = -ter_data[0]
logging_output["_ter_ref_len"] = -ter_data[1]
return loss, sample_size, logging_output
def reduce_metrics(self, logging_outputs, criterion):
super().reduce_metrics(logging_outputs, criterion)
if not self.cfg.eval_target_metric:
return
def sum_logs(key):
return sum(log.get(key, 0) for log in logging_outputs)
if self.cfg.target_metric == "bleu":
counts, totals = [], []
for i in range(EVAL_BLEU_ORDER):
counts.append(sum_logs("_bleu_counts_" + str(i)))
totals.append(sum_logs("_bleu_totals_" + str(i)))
if max(totals) > 0:
# log counts as numpy arrays -- log_scalar will sum them correctly
metrics.log_scalar("_bleu_counts", np.array(counts))
metrics.log_scalar("_bleu_totals", np.array(totals))
metrics.log_scalar("_bleu_sys_len", sum_logs("_bleu_sys_len"))
metrics.log_scalar("_bleu_ref_len", sum_logs("_bleu_ref_len"))
def compute_bleu(meters):
import inspect
import sacrebleu
fn_sig = inspect.getfullargspec(sacrebleu.compute_bleu)[0]
if "smooth_method" in fn_sig:
smooth = {"smooth_method": "exp"}
else:
smooth = {"smooth": "exp"}
bleu = sacrebleu.compute_bleu(
correct=meters["_bleu_counts"].sum,
total=meters["_bleu_totals"].sum,
sys_len=meters["_bleu_sys_len"].sum,
ref_len=meters["_bleu_ref_len"].sum,
**smooth,
)
return round(bleu.score, 2)
metrics.log_derived("bleu", compute_bleu)
elif self.cfg.target_metric == "ter":
num_edits = sum_logs("_ter_num_edits")
ref_len = sum_logs("_ter_ref_len")
if ref_len > 0:
metrics.log_scalar("_ter_num_edits", num_edits)
metrics.log_scalar("_ter_ref_len", ref_len)
def compute_ter(meters):
score = meters["_ter_num_edits"].sum / meters["_ter_ref_len"].sum
return round(score.item(), 2)
metrics.log_derived("ter", compute_ter)
| pytorch/fairseq | examples/discriminative_reranking_nmt/tasks/discriminative_reranking_task.py | Python | mit | 17,731 |
"""Docstring violation definition."""
from collections import namedtuple
from functools import partial
from itertools import dropwhile
from typing import Any, Callable, Iterable, List, Optional
from .parser import Definition
from .utils import is_blank
__all__ = ('Error', 'ErrorRegistry', 'conventions')
ErrorParams = namedtuple('ErrorParams', ['code', 'short_desc', 'context'])
class Error:
"""Error in docstring style."""
# Options that define how errors are printed:
explain = False
source = False
def __init__(
self,
code: str,
short_desc: str,
context: str,
*parameters: Iterable[str],
) -> None:
"""Initialize the object.
`parameters` are specific to the created error.
"""
self.code = code
self.short_desc = short_desc
self.context = context
self.parameters = parameters
self.definition = None # type: Optional[Definition]
self.explanation = None # type: Optional[str]
def set_context(self, definition: Definition, explanation: str) -> None:
"""Set the source code context for this error."""
self.definition = definition
self.explanation = explanation
filename = property(lambda self: self.definition.module.name)
line = property(lambda self: self.definition.error_lineno)
@property
def message(self) -> str:
"""Return the message to print to the user."""
ret = f'{self.code}: {self.short_desc}'
if self.context is not None:
specific_error_msg = self.context.format(*self.parameters)
ret += f' ({specific_error_msg})'
return ret
@property
def lines(self) -> str:
"""Return the source code lines for this error."""
if self.definition is None:
return ''
source = ''
lines = self.definition.source.splitlines(keepends=True)
offset = self.definition.start # type: ignore
lines_stripped = list(
reversed(list(dropwhile(is_blank, reversed(lines))))
)
numbers_width = len(str(offset + len(lines_stripped)))
line_format = f'{{:{numbers_width}}}:{{}}'
for n, line in enumerate(lines_stripped):
if line:
line = ' ' + line
source += line_format.format(n + offset, line)
if n > 5:
source += ' ...\n'
break
return source
def __str__(self) -> str:
if self.explanation:
self.explanation = '\n'.join(
l for l in self.explanation.split('\n') if not is_blank(l)
)
template = '{filename}:{line} {definition}:\n {message}'
if self.source and self.explain:
template += '\n\n{explanation}\n\n{lines}\n'
elif self.source and not self.explain:
template += '\n\n{lines}\n'
elif self.explain and not self.source:
template += '\n\n{explanation}\n\n'
return template.format(
**{
name: getattr(self, name)
for name in [
'filename',
'line',
'definition',
'message',
'explanation',
'lines',
]
}
)
def __repr__(self) -> str:
return str(self)
def __lt__(self, other: 'Error') -> bool:
return (self.filename, self.line) < (other.filename, other.line)
class ErrorRegistry:
"""A registry of all error codes, divided to groups."""
groups = [] # type: ignore
class ErrorGroup:
"""A group of similarly themed errors."""
def __init__(self, prefix: str, name: str) -> None:
"""Initialize the object.
`Prefix` should be the common prefix for errors in this group,
e.g., "D1".
`name` is the name of the group (its subject).
"""
self.prefix = prefix
self.name = name
self.errors = [] # type: List[ErrorParams]
def create_error(
self,
error_code: str,
error_desc: str,
error_context: Optional[str] = None,
) -> Callable[[Iterable[str]], Error]:
"""Create an error, register it to this group and return it."""
# TODO: check prefix
error_params = ErrorParams(error_code, error_desc, error_context)
factory = partial(Error, *error_params)
self.errors.append(error_params)
return factory
@classmethod
def create_group(cls, prefix: str, name: str) -> ErrorGroup:
"""Create a new error group and return it."""
group = cls.ErrorGroup(prefix, name)
cls.groups.append(group)
return group
@classmethod
def get_error_codes(cls) -> Iterable[str]:
"""Yield all registered codes."""
for group in cls.groups:
for error in group.errors:
yield error.code
@classmethod
def to_rst(cls) -> str:
"""Output the registry as reStructuredText, for documentation."""
max_len = max(
len(error.short_desc)
for group in cls.groups
for error in group.errors
)
sep_line = '+' + 6 * '-' + '+' + '-' * (max_len + 2) + '+\n'
blank_line = '|' + (max_len + 9) * ' ' + '|\n'
table = ''
for group in cls.groups:
table += sep_line
table += blank_line
table += '|' + f'**{group.name}**'.center(max_len + 9) + '|\n'
table += blank_line
for error in group.errors:
table += sep_line
table += (
'|'
+ error.code.center(6)
+ '| '
+ error.short_desc.ljust(max_len + 1)
+ '|\n'
)
table += sep_line
return table
D1xx = ErrorRegistry.create_group('D1', 'Missing Docstrings')
D100 = D1xx.create_error(
'D100',
'Missing docstring in public module',
)
D101 = D1xx.create_error(
'D101',
'Missing docstring in public class',
)
D102 = D1xx.create_error(
'D102',
'Missing docstring in public method',
)
D103 = D1xx.create_error(
'D103',
'Missing docstring in public function',
)
D104 = D1xx.create_error(
'D104',
'Missing docstring in public package',
)
D105 = D1xx.create_error(
'D105',
'Missing docstring in magic method',
)
D106 = D1xx.create_error(
'D106',
'Missing docstring in public nested class',
)
D107 = D1xx.create_error(
'D107',
'Missing docstring in __init__',
)
D2xx = ErrorRegistry.create_group('D2', 'Whitespace Issues')
D200 = D2xx.create_error(
'D200',
'One-line docstring should fit on one line ' 'with quotes',
'found {0}',
)
D201 = D2xx.create_error(
'D201',
'No blank lines allowed before function docstring',
'found {0}',
)
D202 = D2xx.create_error(
'D202',
'No blank lines allowed after function docstring',
'found {0}',
)
D203 = D2xx.create_error(
'D203',
'1 blank line required before class docstring',
'found {0}',
)
D204 = D2xx.create_error(
'D204',
'1 blank line required after class docstring',
'found {0}',
)
D205 = D2xx.create_error(
'D205',
'1 blank line required between summary line and description',
'found {0}',
)
D206 = D2xx.create_error(
'D206',
'Docstring should be indented with spaces, not tabs',
)
D207 = D2xx.create_error(
'D207',
'Docstring is under-indented',
)
D208 = D2xx.create_error(
'D208',
'Docstring is over-indented',
)
D209 = D2xx.create_error(
'D209',
'Multi-line docstring closing quotes should be on a separate line',
)
D210 = D2xx.create_error(
'D210',
'No whitespaces allowed surrounding docstring text',
)
D211 = D2xx.create_error(
'D211',
'No blank lines allowed before class docstring',
'found {0}',
)
D212 = D2xx.create_error(
'D212',
'Multi-line docstring summary should start at the first line',
)
D213 = D2xx.create_error(
'D213',
'Multi-line docstring summary should start at the second line',
)
D214 = D2xx.create_error(
'D214',
'Section is over-indented',
'{0!r}',
)
D215 = D2xx.create_error(
'D215',
'Section underline is over-indented',
'in section {0!r}',
)
D3xx = ErrorRegistry.create_group('D3', 'Quotes Issues')
D300 = D3xx.create_error(
'D300',
'Use """triple double quotes"""',
'found {0}-quotes',
)
D301 = D3xx.create_error(
'D301',
'Use r""" if any backslashes in a docstring',
)
D302 = D3xx.create_error(
'D302',
'Deprecated: Use u""" for Unicode docstrings',
)
D4xx = ErrorRegistry.create_group('D4', 'Docstring Content Issues')
D400 = D4xx.create_error(
'D400',
'First line should end with a period',
'not {0!r}',
)
D401 = D4xx.create_error(
'D401',
'First line should be in imperative mood',
"perhaps '{0}', not '{1}'",
)
D401b = D4xx.create_error(
'D401',
'First line should be in imperative mood; try rephrasing',
"found '{0}'",
)
D402 = D4xx.create_error(
'D402',
'First line should not be the function\'s "signature"',
)
D403 = D4xx.create_error(
'D403',
'First word of the first line should be properly capitalized',
'{0!r}, not {1!r}',
)
D404 = D4xx.create_error(
'D404',
'First word of the docstring should not be `This`',
)
D405 = D4xx.create_error(
'D405',
'Section name should be properly capitalized',
'{0!r}, not {1!r}',
)
D406 = D4xx.create_error(
'D406',
'Section name should end with a newline',
'{0!r}, not {1!r}',
)
D407 = D4xx.create_error(
'D407',
'Missing dashed underline after section',
'{0!r}',
)
D408 = D4xx.create_error(
'D408',
'Section underline should be in the line following the section\'s name',
'{0!r}',
)
D409 = D4xx.create_error(
'D409',
'Section underline should match the length of its name',
'Expected {0!r} dashes in section {1!r}, got {2!r}',
)
D410 = D4xx.create_error(
'D410',
'Missing blank line after section',
'{0!r}',
)
D411 = D4xx.create_error(
'D411',
'Missing blank line before section',
'{0!r}',
)
D412 = D4xx.create_error(
'D412',
'No blank lines allowed between a section header and its content',
'{0!r}',
)
D413 = D4xx.create_error(
'D413',
'Missing blank line after last section',
'{0!r}',
)
D414 = D4xx.create_error(
'D414',
'Section has no content',
'{0!r}',
)
D415 = D4xx.create_error(
'D415',
(
'First line should end with a period, question '
'mark, or exclamation point'
),
'not {0!r}',
)
D416 = D4xx.create_error(
'D416',
'Section name should end with a colon',
'{0!r}, not {1!r}',
)
D417 = D4xx.create_error(
'D417',
'Missing argument descriptions in the docstring',
'argument(s) {0} are missing descriptions in {1!r} docstring',
)
D418 = D4xx.create_error(
'D418',
'Function/ Method decorated with @overload shouldn\'t contain a docstring',
)
class AttrDict(dict):
def __getattr__(self, item: str) -> Any:
return self[item]
all_errors = set(ErrorRegistry.get_error_codes())
conventions = AttrDict(
{
'pep257': all_errors
- {
'D203',
'D212',
'D213',
'D214',
'D215',
'D404',
'D405',
'D406',
'D407',
'D408',
'D409',
'D410',
'D411',
'D413',
'D415',
'D416',
'D417',
'D418',
},
'numpy': all_errors
- {
'D107',
'D203',
'D212',
'D213',
'D402',
'D413',
'D415',
'D416',
'D417',
},
'google': all_errors
- {
'D203',
'D204',
'D213',
'D215',
'D400',
'D401',
'D404',
'D406',
'D407',
'D408',
'D409',
'D413',
},
}
)
| GreenSteam/pep257 | src/pydocstyle/violations.py | Python | mit | 12,345 |
from typing import List, Optional
from fastapi import FastAPI, Header
app = FastAPI()
@app.get("/items/")
async def read_items(x_token: Optional[List[str]] = Header(None)):
return {"X-Token values": x_token}
| tiangolo/fastapi | docs_src/header_params/tutorial003.py | Python | mit | 216 |
import yaml
import tornado.web
import elephunk.handlers
import elephunk.database
import elephunk.ui_methods
import elephunk.ui_modules
def create(port, debug, config_file):
with open(config_file, 'r') as f:
config = yaml.load(f.read())
application = tornado.web.Application(
elephunk.handlers.handlers(),
debug=debug,
template_path="templates",
static_path="static",
ui_modules=elephunk.ui_modules,
ui_methods=elephunk.ui_methods
)
application.db = elephunk.database.DatabaseClients(config['servers'])
application.listen(port)
return application
| pitluga/elephunk | elephunk/application.py | Python | mit | 630 |
#!/usr/bin/env python
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
readme = open('README.md').read()
with open('requirements.txt') as reqs:
requirements = reqs.read().split()
setup(
name='pagseguro',
version='0.3.4',
description='Pagseguro API v2 wrapper',
author='Bruno Rocha',
author_email='[email protected]',
url='https://github.com/rochacbruno/python-pagseguro',
packages=['pagseguro', ],
package_dir={'pagseguro': 'pagseguro'},
include_package_data=True,
install_requires=requirements,
long_description=readme,
long_description_content_type='text/markdown',
license='MIT',
test_suite='tests',
zip_safe=False,
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
],
keywords='pagseguro, payment, payments, credit-card'
)
| rochacbruno/python-pagseguro | setup.py | Python | mit | 1,420 |
from rest_framework import serializers
def serializer_factory(model, serializer_class=serializers.ModelSerializer, attrs=None, meta=None):
"""
Generate a simple serializer for the given model class.
:param model: Model class
:param serializer_class: Serializer base class
:param attrs: Serializer class attrs
:param meta: Serializer Meta class attrs
:return: a Serializer class
"""
attrs = attrs or {}
meta = meta or {}
meta.setdefault("model", model)
attrs.setdefault("Meta", type(str("Meta"), (object,), meta))
return type(str("%sSerializer" % model.__name__), (serializer_class,), attrs)
| kcsry/wurst | wurst/api/utils.py | Python | mit | 646 |
from django.conf.urls import url
from profiles import views
urlpatterns = [
url(
regex=r"^edit/$",
view=views.ProfileEditUpdateView.as_view(),
name="profile_edit"
),
url(
regex="^confirm_role/(?P<membership_id>[-\w]+)/(?P<action>verify|deny)/$",
view=views.profile_confirm_role,
name="profile_confirm_role",
),
url(
regex="^deny_account/(?P<type_name>[\w]+)/(?P<account_name>[-\.\w]+)/$",
view=views.profile_deny_account,
name="profile_deny_account",
),
url(
regex="^confirm/$",
view=views.profile_confirm,
name="profile_confirm",
),
url(r"^$", views.profile_list, name="profile_list"),
url(r"^(?P<github_account>[-\w]+)/$", views.profile_detail, name="profile_detail"),
url(r"^github/(?P<github_account>[-\w]+)/$", views.profile_detail, name="github_profile_detail"),
url(r"^steem/(?P<steem_account>[-\.\w]+)/$", views.profile_detail, name="steem_profile_detail"),
url(r"^id/(?P<id>[-\w]+)/$", views.profile_detail, name="id_profile_detail"),
]
| noisy/steemprojects.com | profiles/urls.py | Python | mit | 1,096 |
from . import NamedEntity
class Application(NamedEntity):
def __init__(self, name, provider):
NamedEntity.__init__(self, name)
self.provider = provider
def get_descendants(self):
return []
| stlemme/python-dokuwiki-export | entities/application.py | Python | mit | 202 |
from shuttl.tests import testbase
from shuttl.Models.User import User, UserDataTakenException, NoOrganizationException, ToManyOrganizations
from shuttl.Models.organization import Organization
from shuttl.Models.Reseller import Reseller
class UserTestCase(testbase.BaseTest):
def _setUp(self):
self.reseller = Reseller(name ="test4", url="test2.com")
self.reseller.save()
pass
def test_create(self):
organization = Organization(name="Test", reseller=self.reseller)
organization.save()
organization = Organization.Get(name="Test", vendor=self.reseller)
data = dict(organization=organization, username="Tester", email="[email protected]", password="Things")
user = User.Create(**data)
self.assertRaises(UserDataTakenException, User.Create, **data)
user2 = User.query.get(user.id)
self.assertEqual(user2.username, user.username)
self.assertEqual(user2, user)
self.assertEqual(user2.password, user.password)
self.assertNotEqual(user2.password, "Things")
self.assertFalse(user.isAdmin)
self.assertFalse(user.isFree)
self.assertFalse(user.isActive)
self.assertFalse(user.is_active)
self.assertFalse(user.is_active)
self.assertIsNotNone(user2.organization)
user.organization = None
self.assertRaises(NoOrganizationException, user.save)
pass
def test_password(self):
org = Organization.Create(name="Test", reseller=self.reseller)
usr = User.Create(organization=org, username="Tester", email="[email protected]", password="Bullshit")
oldPW = usr.password
self.assertNotEqual(usr.password, "Bullshit")
self.assertTrue(usr.checkPassword("Bullshit"))
usr.setPassword("Things")
self.assertNotEqual(usr.password, oldPW)
self.assertTrue(usr.checkPassword("Things"))
pass
| shuttl-io/shuttl | shuttl/tests/test_models/test_user.py | Python | mit | 1,929 |
# coding: utf-8
# Distributed under the terms of the MIT License.
import ababe
import sys, ast
import click
import yaml
from ababe.cmdline.apps import *
def run():
try:
ababe.cmdline.runabalib.exec_from_cmdline()
except KeyboardInterrupt:
pass
except EOFError:
pass
@click.group()
@click.version_option(version='0.1.0')
def exec_from_cmdline():
pass
#######################################################################
## In the module all inputs from cmd-line is checked
## And then call the modules in directory
## ababe/cmdline/command
#######################################################################
@exec_from_cmdline.command()
@click.argument('input', type=click.Path(exists=True))
@click.option('--comment', '-c', default=None)
@click.option('--volumn', '-v', type=int, default=1)
@click.option('--ld/--no-ld', '-L/', default=False)
@click.option('--outmode', '-o', type=click.Choice(['vasp', 'yaml']), default='yaml')
def suplat(input, comment, volumn, ld, outmode):
infile = click.format_filename(input)
appsuperlattice = superlattice.App(infile, comment, volumn, ld, outmode)
appsuperlattice.run()
@exec_from_cmdline.command()
@click.argument('input', type=click.Path(exists=True))
@click.option('--comment', '-c', default=None)
@click.option('--element', '-e', default=None)
@click.option('--speckle', '-s', default=None)
@click.option('--number-speckle', '-n', 'nspeckle', type=int, default=None)
@click.option('--dist-restrict', '-r', 'trs', nargs=2, type=click.Tuple([str, float]), multiple=True)
@click.option('--refined/--no-refined', default=True)
@click.option('--outmode', '-o', type=click.Choice(['vasp', 'yaml']), default='vasp')
@click.option('--move-supercell/--no-move-supercell', '-S/-N', 'mpr', default=True,
help='Whether move no primitive structures')
def ocumaker(input, comment, element, speckle, nspeckle, trs, refined, outmode, mpr):
infile = click.format_filename(input)
appoccupymaker = occupymaker.App(infile, comment, element, speckle,
nspeckle, trs, refined, outmode, mpr)
appoccupymaker.run()
@exec_from_cmdline.command()
@click.argument('input', type=click.Path(exists=True))
@click.option('--comment', '-c', default=None)
@click.option('--element', '-e', default=None)
@click.option('--speckle', '-s', default=None)
@click.option('--number-speckle', '-n', 'nspeckle', type=int, default=None)
@click.option('--dist-restrict', '-r', 'trs', nargs=2, type=click.Tuple([str, float]), multiple=True)
@click.option('--refined/--no-refined', default=True)
@click.option('--outmode', '-o', type=click.Choice(['vasp', 'yaml']), default='vasp')
@click.option('--move-supercell/--no-move-supercell', '-S/-N', 'mpr', default=True,
help='Whether move no primitive structures')
def ocubiter(input, comment, element, speckle, nspeckle, trs, refined, outmode, mpr):
infile=click.format_filename(input)
appoccupybiter = occupybiter.App(infile, comment, element, speckle,
nspeckle, trs, refined, outmode, mpr)
appoccupybiter.run()
@exec_from_cmdline.command()
@click.argument('input', type=click.Path(exists=True))
@click.option('--comment', default=None)
@click.option('--element', default=None)
@click.option('--speckle', nargs=2)
@click.option('--number-speckle', '-n', 'nspeckle', type=int, nargs=2)
@click.option('--zoom', type=float, default=None)
@click.option('--dist-restrict', '-r', 'trs', nargs=2, type=click.Tuple([str, float]), multiple=True)
@click.option('--refined/--no-refined', default=True)
@click.option('--outmode', type=click.Choice(['vasp', 'yaml']), default='vasp')
@click.option('--move-supercell/--no-move-supercell', '-S/-N', 'mpr', default=True,
help='Whether move no primitive structures')
def ocutenter(input, comment, element, speckle, nspeckle, zoom, trs, refined, outmode, mpr):
infile=click.format_filename(input)
y = yaml.load(open(infile, "r"))
appoccupytenter = occupytenter.App(y, comment, element, speckle,
nspeckle, zoom, trs, refined, outmode, mpr)
appoccupytenter.run()
@exec_from_cmdline.command()
@click.argument('input', type=click.Path(exists=True))
@click.option('--comment', '-c', default=None)
@click.option('--element', '-e', default=None)
@click.option('--speckle', '-s', nargs=2)
@click.option('--dist-restrict', '-r', 'trs', nargs=2, type=click.Tuple([str, float]), multiple=True)
@click.option('--refined/--no-refined', default=True)
@click.option('--outmode', '-o', type=click.Choice(['vasp', 'yaml']), default='vasp')
def ocumakert(input, comment, element, speckle, trs, refined, outmode):
infile=click.format_filename(input)
appoccupymakert = occupymakert.App(infile, comment, element, speckle,
trs, refined, outmode)
appoccupymakert.run()
@exec_from_cmdline.command()
@click.argument('input', type=click.Path(exists=True))
@click.option('--comment', default=None)
@click.option('--exch', nargs=2)
@click.option('--number-exchange', '-n', 'nexch', type=int)
@click.option('--dist-restrict', '-r', 'trs', nargs=2, type=click.Tuple([str, float]), multiple=True)
@click.option('--refined/--no-refined', default=True)
@click.option('--outmode', type=click.Choice(['vasp', 'yaml']), default='vasp')
@click.option('--move-supercell/--no-move-supercell', '-S/-N', 'mpr', default=False,
help='Whether move no primitive structures')
def exch(input, comment, exch, nexch, trs, refined, outmode, mpr):
infile=click.format_filename(input)
appoccupyexch = occupyexch.App(infile, comment, exch, nexch,
trs, refined, outmode, mpr)
appoccupyexch.run()
| unkcpz/ababe | ababe/cmdline/runabalib.py | Python | mit | 5,798 |
"""
Provide a common way to import Qt classes used by pytest-qt in a unique manner,
abstracting API differences between PyQt5 and PySide2/6.
.. note:: This module is not part of pytest-qt public API, hence its interface
may change between releases and users should not rely on it.
Based on from https://github.com/epage/PythonUtils.
"""
from collections import namedtuple
import os
import pytest
VersionTuple = namedtuple("VersionTuple", "qt_api, qt_api_version, runtime, compiled")
def _import(name):
"""Think call so we can mock it during testing"""
return __import__(name)
class _QtApi:
"""
Interface to the underlying Qt API currently configured for pytest-qt.
This object lazily loads all class references and other objects when the ``set_qt_api`` method
gets called, providing a uniform way to access the Qt classes.
"""
def __init__(self):
self._import_errors = {}
def _get_qt_api_from_env(self):
api = os.environ.get("PYTEST_QT_API")
supported_apis = [
"pyside6",
"pyside2",
"pyqt6",
"pyqt5",
]
if api is not None:
api = api.lower()
if api not in supported_apis: # pragma: no cover
msg = f"Invalid value for $PYTEST_QT_API: {api}, expected one of {supported_apis}"
raise pytest.UsageError(msg)
return api
def _guess_qt_api(self): # pragma: no cover
def _can_import(name):
try:
_import(name)
return True
except ModuleNotFoundError as e:
self._import_errors[name] = str(e)
return False
# Note, not importing only the root namespace because when uninstalling from conda,
# the namespace can still be there.
if _can_import("PySide6.QtCore"):
return "pyside6"
elif _can_import("PySide2.QtCore"):
return "pyside2"
elif _can_import("PyQt6.QtCore"):
return "pyqt6"
elif _can_import("PyQt5.QtCore"):
return "pyqt5"
return None
def set_qt_api(self, api):
self.pytest_qt_api = self._get_qt_api_from_env() or api or self._guess_qt_api()
self.is_pyside = self.pytest_qt_api in ["pyside2", "pyside6"]
self.is_pyqt = self.pytest_qt_api in ["pyqt5", "pyqt6"]
if not self.pytest_qt_api: # pragma: no cover
errors = "\n".join(
f" {module}: {reason}"
for module, reason in sorted(self._import_errors.items())
)
msg = (
"pytest-qt requires either PySide2, PySide6, PyQt5 or PyQt6 installed.\n"
+ errors
)
raise pytest.UsageError(msg)
_root_modules = {
"pyside6": "PySide6",
"pyside2": "PySide2",
"pyqt6": "PyQt6",
"pyqt5": "PyQt5",
}
_root_module = _root_modules[self.pytest_qt_api]
def _import_module(module_name):
m = __import__(_root_module, globals(), locals(), [module_name], 0)
return getattr(m, module_name)
self.QtCore = QtCore = _import_module("QtCore")
self.QtGui = _import_module("QtGui")
self.QtTest = _import_module("QtTest")
self.QtWidgets = _import_module("QtWidgets")
self._check_qt_api_version()
# qInfo is not exposed in PySide2/6 (#232)
if hasattr(QtCore, "QMessageLogger"):
self.qInfo = lambda msg: QtCore.QMessageLogger().info(msg)
elif hasattr(QtCore, "qInfo"):
self.qInfo = QtCore.qInfo
else:
self.qInfo = None
self.qDebug = QtCore.qDebug
self.qWarning = QtCore.qWarning
self.qCritical = QtCore.qCritical
self.qFatal = QtCore.qFatal
if self.is_pyside:
self.Signal = QtCore.Signal
self.Slot = QtCore.Slot
self.Property = QtCore.Property
elif self.is_pyqt:
self.Signal = QtCore.pyqtSignal
self.Slot = QtCore.pyqtSlot
self.Property = QtCore.pyqtProperty
else:
assert False, "Expected either is_pyqt or is_pyside"
def _check_qt_api_version(self):
if not self.is_pyqt:
# We support all PySide versions
return
if self.QtCore.PYQT_VERSION == 0x060000: # 6.0.0
raise pytest.UsageError(
"PyQt 6.0 is not supported by pytest-qt, use 6.1+ instead."
)
elif self.QtCore.PYQT_VERSION < 0x050B00: # 5.11.0
raise pytest.UsageError(
"PyQt < 5.11 is not supported by pytest-qt, use 5.11+ instead."
)
def exec(self, obj, *args, **kwargs):
# exec was a keyword in Python 2, so PySide2 (and also PySide6 6.0)
# name the corresponding method "exec_" instead.
#
# The old _exec() alias is removed in PyQt6 and also deprecated as of
# PySide 6.1:
# https://codereview.qt-project.org/c/pyside/pyside-setup/+/342095
if hasattr(obj, "exec"):
return obj.exec(*args, **kwargs)
return obj.exec_(*args, **kwargs)
def get_versions(self):
if self.pytest_qt_api == "pyside6":
import PySide6
version = PySide6.__version__
return VersionTuple(
"PySide6", version, self.QtCore.qVersion(), self.QtCore.__version__
)
elif self.pytest_qt_api == "pyside2":
import PySide2
version = PySide2.__version__
return VersionTuple(
"PySide2", version, self.QtCore.qVersion(), self.QtCore.__version__
)
elif self.pytest_qt_api == "pyqt6":
return VersionTuple(
"PyQt6",
self.QtCore.PYQT_VERSION_STR,
self.QtCore.qVersion(),
self.QtCore.QT_VERSION_STR,
)
elif self.pytest_qt_api == "pyqt5":
return VersionTuple(
"PyQt5",
self.QtCore.PYQT_VERSION_STR,
self.QtCore.qVersion(),
self.QtCore.QT_VERSION_STR,
)
assert False, f"Internal error, unknown pytest_qt_api: {self.pytest_qt_api}"
qt_api = _QtApi()
| pytest-dev/pytest-qt | src/pytestqt/qt_compat.py | Python | mit | 6,366 |
# -*- coding: utf-8 -*-
"""
Test suite for django-staticshard.
"""
import uuid
from urlparse import urlparse
from django.conf import settings
from django.test import TestCase
from django.core.exceptions import ImproperlyConfigured
from ..settings import STATICSHARD_HOSTS
from ..utils import get_absolute_url
class StaticShardTests(TestCase):
"""Test case for django-staticshard."""
resources = ['img/%s.jpg' % uuid.uuid4() for i in range(0, 20)]
def test_absolute_url(self):
"""
Test the absolute_url method.
"""
for resource in self.resources:
urls = []
for i in range(0, 5):
url = get_absolute_url(resource)
self.assertNotIn(settings.STATIC_URL, url)
parts = urlparse(url)
self.assertIn(parts.netloc, STATICSHARD_HOSTS)
urls.append(url)
self.assertEqual(urls[0], urls[1])
self.assertEqual(urls[0], urls[2])
self.assertEqual(urls[0], urls[3])
self.assertEqual(urls[0], urls[4])
| tomatohater/django-staticshard | staticshard/tests/__init__.py | Python | mit | 1,089 |
from __future__ import unicode_literals
from sqlalchemy import create_engine, Column, ForeignKey, Integer, String,\
Boolean, Unicode, Date, DateTime, and_, func
from sqlalchemy.orm import relationship, backref, sessionmaker
from sqlalchemy.engine.url import URL
from sqlalchemy.ext.declarative import declarative_base, declared_attr
from sqlalchemy.orm.exc import NoResultFound
from helpers.utils import convert_to_snake_case, as_client_tz, delta_minutes
from helpers.h_logging import get_logger
from datetime import datetime, timedelta
from config import settings
import urlparse
import pytz
engine = create_engine(URL(**settings.DATABASE))
Session = sessionmaker(bind=engine)
Base = declarative_base()
class BaseMixin(object):
@declared_attr
def __tablename__(cls):
return convert_to_snake_case(cls.__name__)
__mapper_args__ = {'always_refresh': True}
pk = Column(Integer, primary_key=True)
class User(BaseMixin, Base):
vk_id = Column(String, nullable=False, unique=True)
data = relationship("UserData", uselist=False, backref='user')
@property
def url(self):
db_session = Session()
db_session.add(self)
if self.vk_id.isdigit():
user_url = urlparse.urljoin(settings.SOURCE_URL, "id" + self.vk_id)
else:
user_url = urlparse.urljoin(settings.SOURCE_URL, self.vk_id)
db_session.close()
return user_url
@property
def last_visit_text(self):
last_log = self.activity_logs[-1]
if last_log.is_online:
last_seen_line = 'Online'
else:
now = pytz.timezone(settings.CLIENT_TZ).localize(datetime.now())
last_visit_in_client_tz = as_client_tz(last_log.last_visit)
minutes_ago = delta_minutes(now, last_visit_in_client_tz)
delta_days = (now.date() - last_visit_in_client_tz.date()).days
if minutes_ago < 60:
last_seen_line = 'last seen {} minutes ago'.format(minutes_ago)
else:
if delta_days == 0:
strftime_tmpl = 'last seen today at %H:%M'
elif delta_days == 1:
strftime_tmpl = 'last seen yesterday at %H:%M'
else:
strftime_tmpl = 'last seen on %B %d at %H:%M'
last_seen_line = last_visit_in_client_tz.strftime(strftime_tmpl)
if last_log.is_mobile:
last_seen_line += ' [Mobile]'
return last_seen_line
@classmethod
def from_vk_id(cls, vk_id):
user = cls.get_by_vk_id(vk_id)
db_session = Session()
if not user:
get_logger('file').debug(
'User with vk_id={} not found. Creating.'.format(vk_id))
user = cls(vk_id=vk_id)
db_session.add(user)
db_session.commit()
else:
db_session.add(user)
if not user.data:
get_logger('file').debug(
'UserData absent. Creating and committing')
user.data = UserData()
db_session.commit()
db_session.close()
return user
@classmethod
def get_by_vk_id(cls, vk_id):
db_session = Session()
try:
user = db_session.query(cls).filter_by(vk_id=vk_id).one()
get_logger('file').debug(
'User with vk_id={} found and retrieved.'.format(vk_id))
except NoResultFound, e:
user = None
db_session.close()
return user
def activity_for(self, start, end):
db_session = Session()
query = db_session.query(
func.count(UserActivityLog.status).label('status_count'),
UserActivityLog.status
).filter(UserActivityLog.user_pk == self.pk)\
.filter(and_(
UserActivityLog.timestamp >= start,
UserActivityLog.timestamp <= end
))\
.group_by(UserActivityLog.status)\
.order_by('status_count DESC')
return query.all()
def get_name(self):
db_session = Session()
db_session.add(self)
user_name = self.data.name
db_session.close()
return user_name
class UserData(BaseMixin, Base):
user_pk = Column(Integer, ForeignKey('user.pk'))
name = Column(String)
birthday = Column(String)
photo = Column(String)
hometown = Column(String)
site = Column(String)
instagram = Column(String)
facebook = Column(String)
twitter = Column(String)
skype = Column(String)
phone = Column(String)
university = Column(String)
studied_at = Column(String)
wallposts = Column(Integer)
photos = Column(Integer)
videos = Column(Integer)
followers = Column(Integer)
communities = Column(Integer)
noteworthy_pages = Column(Integer)
current_city = Column(String)
info_1 = Column(String)
info_2 = Column(String)
info_3 = Column(String)
@classmethod
def from_dict(cls, data):
inst = cls()
keys = set(data.keys()) & set(cls.__dict__.keys())
for key in keys:
setattr(inst, key, data[key])
return inst
@staticmethod
def get_diff(old, new):
changes = {}
excluded_attrs = ['pk', 'user_pk', '_sa_instance_state']
keys = [k for k in old.__dict__.keys()
if k not in excluded_attrs and "__" not in k]
for k in keys:
old_val = getattr(old, k)
new_val = getattr(new, k)
if old_val != new_val:
changes[k] = {'old': old_val, 'new': new_val}
return changes
class UserActivityLog(BaseMixin, Base):
user_pk = Column(Integer, ForeignKey('user.pk'))
user = relationship("User", backref='activity_logs')
is_online = Column(Boolean, default=True)
is_mobile = Column(Boolean, default=False)
status = Column(String)
updates = Column(String)
last_visit_lt_an_hour_ago = Column(Boolean, default=False)
last_visit = Column(DateTime(timezone=True))
timestamp = Column(DateTime(timezone=True),
default=datetime.now)
@classmethod
def from_dict(cls, data):
inst = cls()
keys = set(data.keys()) & set(cls.__dict__.keys())
for key in keys:
setattr(inst, key, data[key])
return inst
@staticmethod
def get_diff(old, new):
changes = {}
excluded_attrs = ['pk', 'user_pk', 'user', 'timestamp',
'_sa_instance_state']
keys = [k for k in old.__dict__.keys()
if k not in excluded_attrs and "__" not in k]
for k in keys:
old_val = getattr(old, k)
new_val = getattr(new, k)
if old_val != new_val:
changes[k] = {'old': old_val, 'new': new_val}
return changes
Base.metadata.create_all(engine)
| lesh1k/VKStalk | src/core/models.py | Python | mit | 6,912 |
# This file is part of Indico.
# Copyright (C) 2002 - 2022 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from indico.core.db import db
from indico.util.string import format_repr
class SuggestedCategory(db.Model):
__tablename__ = 'suggested_categories'
__table_args__ = {'schema': 'users'}
user_id = db.Column(
db.Integer,
db.ForeignKey('users.users.id'),
primary_key=True,
index=True,
autoincrement=False
)
category_id = db.Column(
db.Integer,
db.ForeignKey('categories.categories.id'),
primary_key=True,
index=True,
autoincrement=False
)
is_ignored = db.Column(
db.Boolean,
nullable=False,
default=False
)
score = db.Column(
db.Float,
nullable=False,
default=0
)
category = db.relationship(
'Category',
lazy=False,
backref=db.backref(
'suggestions',
lazy=True,
cascade='all, delete-orphan'
)
)
# relationship backrefs:
# - user (User.suggested_categories)
def __repr__(self):
return format_repr(self, 'user_id', 'category_id', 'score', is_ignored=False)
@classmethod
def merge_users(cls, target, source):
"""Merge the suggestions for two users.
:param target: The target user of the merge.
:param source: The user that is being merged into `target`.
"""
target_suggestions = {x.category: x for x in target.suggested_categories}
for suggestion in source.suggested_categories:
new_suggestion = target_suggestions.get(suggestion.category) or cls(user=target,
category=suggestion.category,
score=0)
new_suggestion.score = max(new_suggestion.score, suggestion.score)
new_suggestion.is_ignored = new_suggestion.is_ignored or suggestion.is_ignored
db.session.flush()
| indico/indico | indico/modules/users/models/suggestions.py | Python | mit | 2,202 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from flask import Flask, jsonify, request
app = Flask(__name__)
from charge.chargeManager import ChargeManager
from data.dataProvider import DataProvider
@app.route('/')
def hello_world():
return jsonify(testPreMa(['棉花'],20))
@app.route('/result')
def get_result():
name = request.args.get('name').encode('utf-8')
print name
return jsonify(testPreMa([name], 20))
def testPreMa(nameArray,period):
for name in nameArray:
print 'preMa----------------%s--%d周期-------------------' % (name, period)
dp = DataProvider(name=name)
p_list = dp.getData(['date', 'close'])
cm = ChargeManager(p_list, period, nodeStat=False)
cm.startCharge('preMa')
return cm.resultJson()
if __name__ == '__main__':
app.run(host='localhost') | AlexYang1949/FuturesMeasure | restful/restfulApi.py | Python | mit | 837 |
import itertools
import os
import os.path as osp
import chainer
import numpy as np
import scipy.misc
from sklearn.model_selection import train_test_split
from base import APC2016DatasetBase
def ids_from_scene_dir(scene_dir, empty_scene_dir):
for i_frame in itertools.count():
empty_file = osp.join(
empty_scene_dir, 'frame-{:06}.color.png'.format(i_frame))
rgb_file = osp.join(
scene_dir, 'frame-{:06}.color.png'.format(i_frame))
segm_file = osp.join(
scene_dir, 'segm/frame-{:06}.segm.png'.format(i_frame))
if not (osp.exists(rgb_file) and osp.exists(segm_file)):
break
data_id = (empty_file, rgb_file, segm_file)
yield data_id
def bin_id_from_scene_dir(scene_dir):
caminfo = open(osp.join(scene_dir, 'cam.info.txt')).read()
loc = caminfo.splitlines()[0].split(': ')[-1]
if loc == 'shelf':
bin_id = caminfo.splitlines()[1][-1]
else:
bin_id = 'tote'
return bin_id
class APC2016mit_benchmarkDataset(APC2016DatasetBase):
def __init__(self, data_type):
assert data_type in ('train', 'val')
self.dataset_dir = chainer.dataset.get_dataset_directory(
'apc2016/benchmark')
data_ids = self._get_ids()
ids_train, ids_val = train_test_split(
data_ids, test_size=0.25, random_state=1234)
if data_type == 'train':
self._ids = ids_train
else:
self._ids = ids_val
def __len__(self):
return len(self._ids)
def _get_ids_from_loc_dir(self, env, loc_dir):
assert env in ('office', 'warehouse')
loc = osp.basename(loc_dir)
data_ids = []
for scene_dir in os.listdir(loc_dir):
scene_dir = osp.join(loc_dir, scene_dir)
bin_id = bin_id_from_scene_dir(scene_dir)
empty_dir = osp.join(
self.dataset_dir, env, 'empty', loc, 'scene-{}'.format(bin_id))
data_ids += list(ids_from_scene_dir(scene_dir, empty_dir))
return data_ids
def _get_ids(self):
data_ids = []
# office
contain_dir = osp.join(self.dataset_dir, 'office/test')
for loc in ['shelf', 'tote']:
loc_dir = osp.join(contain_dir, loc)
data_ids += self._get_ids_from_loc_dir('office', loc_dir)
# warehouse
contain_dir = osp.join(self.dataset_dir, 'warehouse')
for sub in ['practice', 'competition']:
sub_contain_dir = osp.join(contain_dir, sub)
for loc in ['shelf', 'tote']:
loc_dir = osp.join(sub_contain_dir, loc)
data_ids += self._get_ids_from_loc_dir('warehouse', loc_dir)
return data_ids
def _load_from_id(self, data_id):
empty_file, rgb_file, segm_file = data_id
img = scipy.misc.imread(rgb_file, mode='RGB')
img_empty = scipy.misc.imread(empty_file, mode='RGB')
# Label value is multiplied by 9:
# ex) 0: 0/6=0 (background), 54: 54/6=9 (dasani_bottle_water)
lbl = scipy.misc.imread(segm_file, mode='L') / 6
lbl = lbl.astype(np.int32)
img_empty[lbl > 0] = img[lbl > 0]
return img_empty, lbl
def get_example(self, i):
data_id = self._ids[i]
img, lbl = self._load_from_id(data_id)
datum = self.img_to_datum(img)
return datum, lbl
if __name__ == '__main__':
import matplotlib.pyplot as plt
import six
dataset_train = APC2016mit_benchmarkDataset('train')
dataset_val = APC2016mit_benchmarkDataset('val')
print('train: %d, val: %d' % (len(dataset_train), len(dataset_val)))
for i in six.moves.range(len(dataset_val)):
viz = dataset_val.visualize_example(i)
plt.imshow(viz)
plt.show()
| wkentaro/fcn | examples/apc2016/datasets/mit_benchmark.py | Python | mit | 3,797 |
import os
import socket
import struct
from OpenSSL import SSL
from mitmproxy import exceptions
from mitmproxy import flow
from mitmproxy.proxy.protocol import base
from mitmproxy.net import tcp
from mitmproxy.net import websockets
from mitmproxy.websocket import WebSocketFlow, WebSocketBinaryMessage, WebSocketTextMessage
class WebSocketLayer(base.Layer):
"""
WebSocket layer to intercept, modify, and forward WebSocket messages.
Only version 13 is supported (as specified in RFC6455).
Only HTTP/1.1-initiated connections are supported.
The client starts by sending an Upgrade-request.
In order to determine the handshake and negotiate the correct protocol
and extensions, the Upgrade-request is forwarded to the server.
The response from the server is then parsed and negotiated settings are extracted.
Finally the handshake is completed by forwarding the server-response to the client.
After that, only WebSocket frames are exchanged.
PING/PONG frames pass through and must be answered by the other endpoint.
CLOSE frames are forwarded before this WebSocketLayer terminates.
This layer is transparent to any negotiated extensions.
This layer is transparent to any negotiated subprotocols.
Only raw frames are forwarded to the other endpoint.
WebSocket messages are stored in a WebSocketFlow.
"""
def __init__(self, ctx, handshake_flow):
super().__init__(ctx)
self.handshake_flow = handshake_flow
self.flow = None # type: WebSocketFlow
self.client_frame_buffer = []
self.server_frame_buffer = []
def _handle_frame(self, frame, source_conn, other_conn, is_server):
if frame.header.opcode & 0x8 == 0:
return self._handle_data_frame(frame, source_conn, other_conn, is_server)
elif frame.header.opcode in (websockets.OPCODE.PING, websockets.OPCODE.PONG):
return self._handle_ping_pong(frame, source_conn, other_conn, is_server)
elif frame.header.opcode == websockets.OPCODE.CLOSE:
return self._handle_close(frame, source_conn, other_conn, is_server)
else:
return self._handle_unknown_frame(frame, source_conn, other_conn, is_server)
def _handle_data_frame(self, frame, source_conn, other_conn, is_server):
fb = self.server_frame_buffer if is_server else self.client_frame_buffer
fb.append(frame)
if frame.header.fin:
payload = b''.join(f.payload for f in fb)
original_chunk_sizes = [len(f.payload) for f in fb]
message_type = fb[0].header.opcode
compressed_message = fb[0].header.rsv1
fb.clear()
if message_type == websockets.OPCODE.TEXT:
t = WebSocketTextMessage
else:
t = WebSocketBinaryMessage
websocket_message = t(self.flow, not is_server, payload)
length = len(websocket_message.content)
self.flow.messages.append(websocket_message)
self.channel.ask("websocket_message", self.flow)
def get_chunk(payload):
if len(payload) == length:
# message has the same length, we can reuse the same sizes
pos = 0
for s in original_chunk_sizes:
yield payload[pos:pos + s]
pos += s
else:
# just re-chunk everything into 10kB frames
chunk_size = 10240
chunks = range(0, len(payload), chunk_size)
for i in chunks:
yield payload[i:i + chunk_size]
frms = [
websockets.Frame(
payload=chunk,
opcode=frame.header.opcode,
mask=(False if is_server else 1),
masking_key=(b'' if is_server else os.urandom(4)))
for chunk in get_chunk(websocket_message.content)
]
if len(frms) > 0:
frms[-1].header.fin = True
else:
frms.append(websockets.Frame(
fin=True,
opcode=websockets.OPCODE.CONTINUE,
mask=(False if is_server else 1),
masking_key=(b'' if is_server else os.urandom(4))))
frms[0].header.opcode = message_type
frms[0].header.rsv1 = compressed_message
for frm in frms:
other_conn.send(bytes(frm))
return True
def _handle_ping_pong(self, frame, source_conn, other_conn, is_server):
# just forward the ping/pong to the other side
other_conn.send(bytes(frame))
return True
def _handle_close(self, frame, source_conn, other_conn, is_server):
self.flow.close_sender = "server" if is_server else "client"
if len(frame.payload) >= 2:
code, = struct.unpack('!H', frame.payload[:2])
self.flow.close_code = code
self.flow.close_message = websockets.CLOSE_REASON.get_name(code, default='unknown status code')
if len(frame.payload) > 2:
self.flow.close_reason = frame.payload[2:]
other_conn.send(bytes(frame))
# initiate close handshake
return False
def _handle_unknown_frame(self, frame, source_conn, other_conn, is_server):
# unknown frame - just forward it
other_conn.send(bytes(frame))
sender = "server" if is_server else "client"
self.log("Unknown WebSocket frame received from {}".format(sender), "info", [repr(frame)])
return True
def __call__(self):
self.flow = WebSocketFlow(self.client_conn, self.server_conn, self.handshake_flow, self)
self.flow.metadata['websocket_handshake'] = self.handshake_flow
self.handshake_flow.metadata['websocket_flow'] = self.flow
self.channel.ask("websocket_start", self.flow)
client = self.client_conn.connection
server = self.server_conn.connection
conns = [client, server]
close_received = False
try:
while not self.channel.should_exit.is_set():
r = tcp.ssl_read_select(conns, 0.1)
for conn in r:
source_conn = self.client_conn if conn == client else self.server_conn
other_conn = self.server_conn if conn == client else self.client_conn
is_server = (conn == self.server_conn.connection)
frame = websockets.Frame.from_file(source_conn.rfile)
cont = self._handle_frame(frame, source_conn, other_conn, is_server)
if not cont:
if close_received:
return
else:
close_received = True
except (socket.error, exceptions.TcpException, SSL.Error) as e:
s = 'server' if is_server else 'client'
self.flow.error = flow.Error("WebSocket connection closed unexpectedly by {}: {}".format(s, repr(e)))
self.channel.tell("websocket_error", self.flow)
finally:
self.channel.tell("websocket_end", self.flow)
| dwfreed/mitmproxy | mitmproxy/proxy/protocol/websocket.py | Python | mit | 7,347 |
# force python 3.* compability
from __future__ import absolute_import, division, print_function
from builtins import (bytes, str, open, super, range,
zip, round, input, int, pow, object)
# regular imports below:
import unittest
from python_uptimer import up_check
import requests
from datetime import timedelta
class MyTestCase(unittest.TestCase):
def test_response_time(self):
jobs = [
up_check.Response('http://sebastiannilsson.com'),
up_check.Response('http://treplex.se'),
up_check.Response('http://google.com'),
]
for job in jobs:
r = job.check()
print(r)
def test_requests(self):
response = requests.get('http://www.google.com', timeout=2)
self.assertGreater(len(response.content), 0)
self.assertGreater(response.elapsed, timedelta(-1))
if __name__ == '__main__':
unittest.main()
| sebnil/python_uptimer | tests/test_requests.py | Python | mit | 934 |
import stripe
import json
from django.conf import settings
from django.http import HttpResponse
from django.shortcuts import render
from django.views.generic import TemplateView, DetailView, ListView
from carton.cart import Cart
from .models import Sale, SaleProduct, SaleError
from products.models import Product
class AddView(TemplateView):
def get(self, request, *args, **kwargs):
cart = Cart(request.session)
product = Product.objects.get(id=kwargs["pk"])
cart.add(product, price=product.price)
return HttpResponse("Added")
class RemoveSingleView(TemplateView):
def get(self, request, *args, **kwargs):
cart = Cart(request.session)
product = Product.objects.get(id=kwargs["pk"])
cart.remove_single(product)
return HttpResponse("Removed Single " + str(product))
class RemoveView(TemplateView):
def get(self, request, *args, **kwargs):
cart = Cart(request.session)
product = Product.objects.get(id=kwargs["pk"])
cart.remove(product)
return HttpResponse("Removed")
class CartTemplateView(TemplateView):
template_name = "shoppingcontent/cart.html"
def get_context_data(self, **kwargs):
# only return the active products
context = super(CartTemplateView, self).get_context_data(**kwargs)
context['STRIPE_PUBLIC_KEY'] = settings.STRIPE_PUBLIC_KEY
context['cart_stripe_total'] = int(Cart(self.request.session).total * 100)
return context
class SaleDetailView(DetailView):
template_name = "shoppingcontent/sale.html"
model = Sale
class SaleListView(ListView):
template_name = "shoppingcontent/sales_list.html"
model = Sale
class SaleErrorListView(ListView):
template_name = "shoppingcontent/sales_error_list.html"
model = SaleError
def charge(request):
''' This function is split into 4 separate parts, which are all wrapped around a try:
except block.
The first part is where we charge the card through Stripe. Stripe will either
accept the payment or send back various different error messages depending on
what went wrong.
The second thing we do is very simple, empty the user's cart.
The third thing is that we're going to create a Sale object for our own records.
This is where we'll see what items have been sold, and also manage orders.
The last thing is creating the sale items, which is really part of creating the
sale, but it is separated in a different try block so that we are sure to create
the sale item if something goes wrong when creating the items associated with the
sale.
Each try block will writhe to the SaleError model if something goes wrong.
'''
if request.method == "POST":
stripe.api_key = settings.STRIPE_SECRET_KEY
email = request.POST['stripeEmail']
stripe_amount = request.POST['stripeAmount']
sale_products_string = request.POST['products']
# Create the charge on Stripe's servers - this will charge the user's card
try:
charge = stripe.Charge.create(
amount=stripe_amount, # amount in cents, again
currency="usd",
card=request.POST['stripeToken'],
description=email
)
except stripe.CardError as e:
# The card has been declined
text = "There was an error processing your card, and we were not able to charge. "
return render(request, "shoppingcontent/error.html",
{'text': text, 'error': e})
except stripe.InvalidRequestError as e:
# Attempt to use the token multiple times.
text = "Your order has already been processed, and it can only be processed once. " \
"If you refreshed this page, that is why you're seeing this error."
return render(request, "shoppingcontent/error.html",
{'text': text})
except stripe.APIConnectionError as e:
# Connection error with Stripe
text = "There was a connection error with our payment processor. Please try again in a few minutes, your cart should still be intact."
return render(request, "shoppingcontent/error.html",
{'text': text, 'error': e})
finally:
# write to the error log if needed
try:
SaleError.objects.create(message=e, location="C")
except:
pass
try:
# clear the cart. If there is an error just keep going.
cart = Cart(request.session).clear()
except Exception as e:
SaleError.objects.create(message=e, location="A")
pass
try:
# create the sale object
if "test" in stripe.api_key:
live = False
elif "live" in stripe.api_key:
live = True
sale = Sale.objects.create(live=live, email=email, total="%.2f" % (int(stripe_amount) / 100))
except Exception as e:
SaleError.objects.create(message=e, location="S", problem="email -" + email + ", amount - " + amount)
text = "Sorry, there was an error processing your order. You have been billed, and " + \
"we have general information about your order, but will be contacting you to get the details."
return render(request, "shoppingcontent/error.html",
{'text': text})
try:
# create the product sales objects
obj = json.loads(sale_products_string)
for i in obj:
id = i.get('id')
quantity = i.get('quantity')
product = Product.objects.get(id=id)
SaleProduct.objects.create(
product=product,
quantity=quantity,
price=product.price,
sale=sale
)
return render(request, "shoppingcontent/success.html",
{'sale': sale, 'email': email})
except Exception as e:
SaleError.objects.create(message=e, location="I", problem=sale_products_string, sale=sale)
text = "There was a problem processing your purchase. The charge went through successfully, " + \
"and we have recorded the sale. However, the product details we will need to contact you about. " + \
"Sorry for the inconvenience."
return render(request, "shoppingcontent/error.html",
{'text': text})
else:
text = "Error: This page is only meant to be hit by the server after a payment."
return render(request, "shoppingcontent/error.html",
{'text': text})
| azul-cloud/serendipity | shopping/views.py | Python | mit | 6,846 |
#!/usr/bin/env python
from sys import argv
from GeekToolKickassTorrentFeed import GeekToolKickassTorrentFeed
if __name__ == "__main__" and len(argv) > 1:
mode = argv[1]
print(str.format("{0}{1}", "\t" * 4, mode.capitalize()))
feed = GeekToolKickassTorrentFeed(mode)
if feed:
feed_data = feed.get_top_seeded_torrents().fetch().get_formatted_list()
print(feed_data)
else:
print("No torrents available")
| abram777/torrents-from-xml | examples/geektool script/torrents.geektool.py | Python | mit | 449 |
"""empty message
Revision ID: 02ccb3e6a553
Revises: None
Create Date: 2016-05-17 22:15:03.881575
"""
# revision identifiers, used by Alembic.
revision = '02ccb3e6a553'
down_revision = None
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.create_table('roles',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=64), nullable=True),
sa.Column('default', sa.Boolean(), nullable=True),
sa.Column('permissions', sa.Integer(), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('name')
)
op.create_index(op.f('ix_roles_default'), 'roles', ['default'], unique=False)
op.create_table('users',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('email', sa.String(length=64), nullable=True),
sa.Column('username', sa.String(length=64), nullable=True),
sa.Column('role_id', sa.Integer(), nullable=True),
sa.Column('password_hash', sa.String(length=128), nullable=True),
sa.Column('confirmed', sa.Boolean(), nullable=True),
sa.Column('name', sa.String(length=64), nullable=True),
sa.Column('location', sa.String(length=64), nullable=True),
sa.Column('about_me', sa.Text(), nullable=True),
sa.Column('member_since', sa.DateTime(), nullable=True),
sa.Column('last_seen', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['role_id'], ['roles.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_users_email'), 'users', ['email'], unique=True)
op.create_index(op.f('ix_users_username'), 'users', ['username'], unique=True)
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f('ix_users_username'), table_name='users')
op.drop_index(op.f('ix_users_email'), table_name='users')
op.drop_table('users')
op.drop_index(op.f('ix_roles_default'), table_name='roles')
op.drop_table('roles')
### end Alembic commands ###
| answerrrrrrrrr/myflask | migrations/versions/02ccb3e6a553_.py | Python | mit | 2,065 |
"""
Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is used.
Note:
All letters in hexadecimal (a-f) must be in lowercase.
The hexadecimal string must not contain extra leading 0s. If the number is zero, it is represented by a single zero character '0'; otherwise, the first character in the hexadecimal string will not be the zero character.
The given number is guaranteed to fit within the range of a 32-bit signed integer.
You must not use any method provided by the library which converts/formats the number to hex directly.
Example 1:
Input:
26
Output:
"1a"
Example 2:
Input:
-1
Output:
"ffffffff"
"""
class Solution(object):
def toHex(self, num):
"""
:type num: int
:rtype: str
"""
curr = []
ret = []
for i in xrange(32):
curr.append(str(num & 0x01))
num = num >> 1
if len(curr) == 4:
n = int(''.join(reversed(curr)), 2)
if n < 10:
ret.append(str(n))
else:
ret.append(chr(ord('a') + n - 10))
curr = []
cleaned = []
is_ok = False
for i, n in enumerate(reversed(ret)):
if n != '0':
is_ok = True
if is_ok:
cleaned.append(n)
if not cleaned:
return '0'
return ''.join(cleaned) | franklingu/leetcode-solutions | questions/convert-a-number-to-hexadecimal/Solution.py | Python | mit | 1,481 |
# The MIT License (MIT)
# Copyright (c) 2017 Kinga Makowiecka
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation file
# (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do
# so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
# FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import math
import sys
base = -2.0
result = ""
number = int(sys.argv[1])
print "converting number " + str(number) + " to negabinary value:"
while number != 0:
ceilOfDivision = int(math.ceil(number / base))
reminder = int(number % base)
result = result + str(int(math.fabs(reminder)))
number = ceilOfDivision
print result[::-1]
| gynvael/zrozumiec-programowanie-cwiczenia | INT-int-to-negabinary-python/int-to-negabinary-coverter.py | Python | mit | 1,451 |
#import unittest
import mt
import queue
import _thread
import time
class DummySocket:
def __init__(self, ID):
self.id = ID
self.lastMsg = ""
def send(self, msg):
print(self.id+":",msg)
self.lastMsg = msg
def close(self):
print(self.id+": CLOSE CALLED")
self.lastMsg = "CLOSED"
def getpeername(self):
return self.id, 0
##class TestMt(unittest.TestCase):
##
## def test_listener_thread(self):
## data = queue.Queue()
## s1 = DummySocket("0")
## s2 = DummySocket("1")
##
## listenerObj = mt.ListenerThread(data)
##
## def sender():
## time.sleep(1)
## data.put("Hello, World")
## time.sleep(0.1)
## listenerObj.add(s2)
## time.sleep(1)
## data.put("Hello, World 2")
## time.sleep(1)
## listenerObj.removeIP("0")
## data.put("Hello, World 3")
##
## data.put("!!INTERNAL=SHUTDOWN!!")
##
## listenerObj.add(s1)
## _thread.start_new_thread(sender, ())
## listenerObj.main()
##
## self.assertEqual(s1.lastMsg, "CLOSED")
## self.assertEqual(s2.lastMsg, b"Hello, World 3\r\n")
def test_listener_thread():
data = queue.Queue()
s1 = DummySocket("0")
s2 = DummySocket("1")
listenerObj = mt.ListenerThread(data)
def sender():
time.sleep(1)
data.put("Hello, World")
time.sleep(0.1)
listenerObj.add(s2)
time.sleep(1)
data.put("Hello, World 2")
time.sleep(1)
listenerObj.removeIP("0")
data.put("Hello, World 3")
data.put("!!INTERNAL=SHUTDOWN!!")
listenerObj.add(s1)
_thread.start_new_thread(sender, ())
listenerObj.main()
assert s1.lastMsg == "CLOSED"
assert s2.lastMsg == b"Hello, World 3\r\n"
| Griffiths117/TG-s-IRC | server/mtUnitTests.py | Python | mit | 1,945 |
"""Pytrafikverket module."""
# flake8: noqa
from pytrafikverket.trafikverket import (AndFilter, FieldFilter, FieldSort,
Filter, FilterOperation, NodeHelper,
OrFilter, SortOrder, Trafikverket)
from pytrafikverket.trafikverket_train import (StationInfo, TrafikverketTrain,
TrainStop, TrainStopStatus)
from pytrafikverket.trafikverket_weather import (TrafikverketWeather,
WeatherStationInfo)
from pytrafikverket.trafikverket_ferry import (TrafikverketFerry,
FerryStop, FerryStopStatus)
| AnderssonPeter/pytrafikverket | pytrafikverket/__init__.py | Python | mit | 708 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: omi
# @Date: 2014-08-24 22:08:33
# @Last Modified by: omi
# @Last Modified time: 2015-03-30 23:36:21
'''
__ ___________________________________________
| \ ||______ | |______|_____||______|______
| \_||______ | |______| |______||______
________ __________________________ _____ _ _
| | || ||______ | | |_____]| | \___/
| | ||_____|______|__|__|_____ |_____]|_____|_/ \_
+ ------------------------------------------ +
| NetEase-MusicBox 320kbps |
+ ------------------------------------------ +
| |
| ++++++++++++++++++++++++++++++++++++++ |
| ++++++++++++++++++++++++++++++++++++++ |
| ++++++++++++++++++++++++++++++++++++++ |
| ++++++++++++++++++++++++++++++++++++++ |
| ++++++++++++++++++++++++++++++++++++++ |
| |
| A sexy cli musicbox based on Python |
| Music resource from music.163.com |
| |
| Built with love to music by omi |
| |
+ ------------------------------------------ +
'''
from setuptools import setup, find_packages
setup(
name='NetEase-MusicBox',
version='0.1.9.6',
packages=find_packages(),
include_package_data=True,
install_requires=[
'requests',
'BeautifulSoup4',
'pycrypto',
],
entry_points={
'console_scripts': [
'musicbox = NEMbox:start'
],
},
author='omi',
author_email='[email protected]',
url='https://github.com/darknessomi/musicbox',
description='A sexy command line interface musicbox',
keywords=['music', 'netease', 'cli', 'player'],
zip_safe=False,
)
| chaserhkj/musicbox | setup.py | Python | mit | 1,899 |
# -*- coding:utf8 -*-
from __future__ import unicode_literals
from django.contrib import admin
from core.models import Post
from core.models import Category
from core.models import Comment
from core.models import Tag
from core.forms import PostForm
@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
# raw_id_fields = ('tags',)
form = PostForm
class Meta:
model = Post
admin.site.register(Category)
admin.site.register(Comment)
admin.site.register(Tag)
| valbertovc/blog_django_bootstrap_ajax | core/admin.py | Python | mit | 481 |
#Project Euler Problem 4
#A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 * 99.
#Find the largest palindrome made from the product of two 3-digit numbers.
def palindrome(test):
while len(test) > 2:
if test[0] == test[-1]:
test = test.rstrip(test[-1])
test = test.lstrip(test[0])
else:
return False
if test[0] == test[-1]:
return True
#print palindrome(str(99000009))
def palindrome2(test):
if test == "".join(reversed(test)):
return True
else:
return False
#print palindrome2("31213")
def largest_palindrome_from_3digitproducts():
hi_p = 0
t1 = 999
t2 = 999
count = 0
while t1 >= 100:
t2 = 999 - count
#print "t1 = {}".format(t1)
while t2 >= 1:
#print "t2 = {}".format(t2)
test = t1*t2
if palindrome2(str(test)) == True and test > hi_p:
hi_p = test
#print hi_p
t2 -=1
count += 1
t1 -=1
return "hi_p = {}".format(hi_p)
print largest_palindrome_from_3digitproducts()
def largest_palindrome_from_3digitproductsr(test=999): #with recursion (doesn't work yet) (semantic error cos only 999*999 and 999*998 not 999*997)
large_num = test * test
large_num2 = test * (test-1)
if palindrome(str(large_num)) == True:
return large_num
elif palindrome(str(large_num2)) == True:
return large_num2
else:
return largest_palindrome_from_3digitproductsr(test-1)
#print largest_palindrome_from_3digitproductsr()
"""
print 9*9 #highest square #digits involved 1
print 9*8 #new number times highest #because old digits finished, add new digit
print 8*8 #new squared #multiply involved digit by all involved hi to low
print 9*7 #new digit times highest
print 8*7#new times next highest
print 9*6#new2 times highest
print 7*7#new squared #new2 now new
print 8*6#new times next highest
print 9*5#
print 7*6
print 8*5
print 6*6
print 9*4
print 7*5
print 8*4
print 6*5
print 7*4
print 9*3
print 5*5
print 8*3
print 6*4
print 7*3
print 5*4
print 9*2
print 6*3
print 8*2
print 4*4
print 5*3
print 7*2
print 6*2
print 4*3
print 5*2
print 9*1
print 3*3
print 8*1
print 4*2
print 7*1
print 6*1
print 3*2
print 5*1
print 4*1
print 2*2
print 3*1
print 2*1
print 1*1 """
| ieuan1630-cmis/ieuan1630-cmis-cs2 | pep4.py | Python | cc0-1.0 | 2,405 |
"""
Prosta klasa reprezentująca posiłek składający się z wielu innych
obiektów jadalnych.
"""
class BigMeal:
def __init__(self, edibles):
# TODO: zainicjuj obiekt przekazaną listą obiektów jadalnych
# "edibles"
def get_name(self):
# TODO: zaimplementuj metodę zwracającą nazwę obiektu
# składającą się z połączonych spójnikiem "i" nazw wszystkich
# składowych obiektów jadalnych
def get_calories(self):
# TODO: zaimplementuj metodę zwracającą wartość energetyczną
# całego posiłku (jako sumę kalorii składowych obiektów jadalnych)
if __name__ == '__main__':
import food
# proste testy
apple = Food("Jablko", 70)
carrot = Food("Marchewka", 80)
banana = Food("Banan", 60)
fruitmix = BigMeal([apple, carrot, banana])
print (fruitmix.get_name()) # "Jablko i Marchewka i Banan"
print (fruitmix.get_calories()) # 210
| CodeCarrots/warsztaty | sesja07/bigmeal.py | Python | cc0-1.0 | 955 |
from operator import add
f = sc.textFile("data/README.md")
wc = f.flatMap(lambda x: x.split(' ')).map(lambda x: (x, 1)).reduceByKey(add)
wc.saveAsTextFile("wc_out")
| ceteri/intro_spark | src/02.wc.py | Python | cc0-1.0 | 167 |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#
# Cloudant のデータベース作成
#
# Copyright (C) 2016 International Business Machines Corporation
# and others. All Rights Reserved.
#
#
# https://github.com/cloudant/python-cloudant
# pip install cloudant
#
# API Document
# http://python-cloudant.readthedocs.io/en/latest/cloudant.html
#
import json
import csv
import codecs
import uuid
from cloudant.client import Cloudant
from cloudant.result import Result, ResultByKey, QueryResult
from cloudant.query import Query
#import cloudant
# Cloudant認証情報の取得
f = open('cloudant_credentials_id.json', 'r')
cred = json.load(f)
f.close()
print cred
# データベース名の取得
f = open('database_name.json', 'r')
dbn = json.load(f)
f.close()
print dbn['name']
client = Cloudant(cred['credentials']['username'],
cred['credentials']['password'],
url=cred['credentials']['url'])
# Connect to the server
client.connect()
# DB選択
db = client[dbn['name']]
# CSVを読んでループを回す
fn = 'weather_code.csv';
reader = csv.reader(codecs.open(fn),delimiter=',',quoting=csv.QUOTE_NONE)
for id, e_description,j_description in reader:
print id, e_description,j_description
data = {
"_id": id,
"e_description": e_description,
"j_description": j_description
}
print data
rx = db.create_document(data)
if rx.exists():
print "SUCCESS!!"
# Disconnect from the server
client.disconnect()
| takara9/watson_chatbot | weather_report/load3_db_weather.py | Python | epl-1.0 | 1,717 |
#!/usr/bin/python
from txzookeeper.client import ZookeeperClient
from txzookeeper.retry import RetryClient
import zookeeper
import sys
from Crypto.Hash import SHA256
from Crypto.PublicKey import RSA
import os
from twisted.python import log
from twisted.internet import reactor, defer
log.startLogging(sys.stdout)
class Config():
"""
The aim of this class is to centralize and manage most configurations
using Zookeeper
"""
def __init__(self, zkAddr):
"""Initialization of a configuration manager.
create a configuration tree into zookeeper
@param zkAddr: Zookeeper client instance.
"""
self.zk = zkAddr
self.init_nodes()
def init_nodes(self):
self.init_node("/producers")
self.init_node("/consumer")
self.init_node("/mongo")
self.init_node("/solr")
self.init_node("/ssl")
self.init_node("/ssl/ca")
self.init_node("/nodes")
def init_node(self,name):
d = self.zk.create(name)
d.addErrback(self._err)
print "node %s : OK" % name
def _err(self,error):
"""
error handler
@param error: error message
"""
log.msg('node seems to already exists : %s' % error)
def add_producer(self,producer):
"""
add a producer address in the configuration tree
@param producer: producer address
"""
d = self.zk.create("/producers/%s" % str(producer), flags = zookeeper.EPHEMERAL)
d.addErrback(self._err)
def get_mongod_all(self, callback = None):
"""
get all mongoDB addresses from configuration tree
@param callback: function to call after getting data
from the configuration tree
"""
self._get_conf_all("/mongo", callback)
def get_solr_all(self, callback = None):
"""
get all solr addresses from configuration tree
@param callback: call this function after getting data
from the configuration tree
"""
self._get_conf_all("/solr", callback)
def _get_conf_all(self, path, callback = None):
"""
get all configurations from the configuration tree, using a giving path
@param path: path of the configuration to get
@param callback: the function to call after getting the configuration
"""
def _get_value(m):
value = m
if callback:
callback(value)
def _call(m):
dat, m = self.zk.get_children_and_watch(path)
dat.addCallback(_get_value)
m.addCallback(_call)
m.addErrback(self._err)
if not callback:
data = self.zk.get(path)
data.addCallback(_get_value)
data.addErrback(self._err)
else:
data, diff = self.zk.get_children_and_watch(path)
data.addCallback(_get_value)
data.addErrback(self._err)
diff.addCallback(_call)
diff.addErrback(self._err)
def _get_conf_data(self, path, callback = None):
"""
get and watch data from the configuration tree, using a giving path
@param path: path to the configuration to get
@param callback: the function to call after getting the configuration
"""
def _get_value(m):
value = m
if callback:
callback(value)
def _call(m):
dat, m = self.zk.get_and_watch(path)
dat.addCallback(_get_value)
m.addCallback(_call)
m.addErrback(self._err)
if not callback:
data = self.zk.get(path)
data.addCallback(_get_value)
data.addErrback(self._err)
else:
data, diff = self.zk.get_and_watch(path)
data.addCallback(_get_value)
data.addErrback(self._err)
diff.addCallback(_call)
diff.addErrback(self._err)
def _get_data(self, path, callback = None, errback = None):
"""
get data from the configuration tree without watch.
@param path: path to the configuration to get
@param callback: function to call after getting data
@param errback: function to call if getting data fails
"""
def _err(error):
"""
error handler
@param error: error message
"""
log.msg('node seems to already exists : %s' % error)
data = self.zk.get(path)
data.addErrback(_err)
if callback:
data.addCallback(callback)
if errback:
data.addErrback(errback)
| Wallix-Resilience/LogMonitor | resilience/zookeeper/configure/config.py | Python | gpl-2.0 | 4,845 |
# Rekall Memory Forensics
# Copyright 2014 Google Inc. All Rights Reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 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
#
"""The module implements the linux specific address resolution plugin."""
__author__ = "Michael Cohen <[email protected]>"
import re
from rekall import obj
from rekall.plugins.common import address_resolver
from rekall.plugins.linux import common
class LKMModule(address_resolver.Module):
"""A Linux kernel module."""
def __init__(self, module, **kwargs):
self.module = module
super(LKMModule, self).__init__(
name=unicode(module.name),
start=module.base,
end=module.end,
**kwargs)
class KernelModule(address_resolver.Module):
"""A Fake object which makes the kernel look like a module.
This removes the need to treat kernel addresses any different from module
addresses, and allows them to be resolved by this module.
"""
def __init__(self, session=None, **kwargs):
super(KernelModule, self).__init__(
# Check if the address appears in the kernel binary.
start=obj.Pointer.integer_to_address(
session.profile.get_constant("_text")),
end=session.profile.get_constant("_etext"),
name="linux",
profile=session.profile,
session=session, **kwargs)
class LinuxAddressResolver(address_resolver.AddressResolverMixin,
common.LinuxPlugin):
"""A Linux specific address resolver plugin."""
def _EnsureInitialized(self):
if self._initialized:
return
# Insert a psuedo module for the kernel
self.AddModule(KernelModule(session=self.session))
# Add LKMs.
for kmod in self.session.plugins.lsmod().get_module_list():
self.AddModule(LKMModule(kmod, session=self.session))
self._initialized = True
| palaniyappanBala/rekall | rekall-core/rekall/plugins/linux/address_resolver.py | Python | gpl-2.0 | 2,567 |
# Copied from LMC documentation
# Modified to use MPI (but not enable parallelization), to increase the parameter degeneracy, and to disperse the start points
# Here is a simple example. As shown it will run in non-parallel mode; comments indicate what to do for parallelization.
from lmc import *
## for MPI
from mpi4py import MPI
mpi_rank = MPI.COMM_WORLD.Get_rank()
from numpy.random import rand
### Define some parameters.
startx = [-10.0, -10.0, 10.0, 10.0]
starty = [-10.0, 10.0, -10.0, 10.0]
x = Parameter(name='x', value=startx[mpi_rank], width=0.1)
y = Parameter(name='y', value=starty[mpi_rank], width=0.1)
### This is the object that will be passed to the likelihood function.
### In this simple case, it just holds the parameter objects, but in general it could be anything.
### E.g., usually it would also contain or point to the data being used to constrain the model. A good idea is to write the state of any updaters to a file after each adaptation (using the on_adapt functionality), in which case keeping pointers to the updaters here is convenient. Also commonly useful: a DerivedParameter which holds the value of the posterior log-density for each sample.
class Thing:
def __init__(self, x, y):
self.x = x
self.y = y
thing = Thing(x, y)
### The log-posterior function. Here we just assume a bivariate Gaussian posterior with marginal standard deviations s(x)=2 and s(y)=3, correlation coefficient 0.75, and means <x>=-1, <y>=1.
def post(thing):
r = 0.99
sx = 2.0
sy = 3.0
mx = -1.0
my = 1.0
return -0.5/(1.0-r**2)*( (thing.x()-mx)**2/sx**2 + (thing.y()-my)**2/sy**2 - 2.0*r*(thing.x()-mx)/sx*(thing.y()-my)/sy )
### Create a parameter space consisting of x and y, and associate the log-posterior function with it.
space = ParameterSpace([thing.x, thing.y], post)
### If we'd bothered to define a DerivedParameter in Thing which would hold the posterior density, we might want to define a larger ParameterSpace and pass it to the Engine later on to be saved in the Backends (instead of space).
#trace = ParameterSpace([thing.x, thing.y, thing.logP])
### Use slice sampling for robustness. Adapt the proposal distribution every 100 iterations starting with the 100th.
step = Metropolis()
parallel = None
## for MPI parallelization
#parallel = MPI.COMM_WORLD
## for parallelization via the filesystem, this would have to be set to a different value for each concurrently running instance
#parallel = 1
updater = MultiDimSequentialUpdater(space, step, 100, 100, parallel=parallel)
### Create an Engine and tell it to drive this Updater and to store the values of the free parameters.
engine = Engine([updater], space)
### Store the chain in a text file.
#chainfile = open("chain.txt", 'w')
## For filesystem parallelization, each instance should write to a different file.
## For MPI, the same is true, e.g.
chainfile = open("notparallel" + str(MPI.COMM_WORLD.Get_rank()) + ".txt", 'w')
backends = [ textBackend(chainfile) ]
### Print the chain to the terminal as well
#backends.append( stdoutBackend() )
### Run the chain for 10000 iterations
engine(10000, thing, backends)
### Close the text file to clean up.
chainfile.close()
## If this was a parallel run, print the convergence criterion for each parameter.
# print updater.R
| drphilmarshall/StatisticalMethods | lessons/graphics/notparallel_chain_fit.py | Python | gpl-2.0 | 3,306 |
#!/usr/bin/env python
import time
import pyslurm
def reservation_display(reservation):
if reservation:
for key,value in reservation.items():
print("\t{}={}".format(key, value))
if __name__ == "__main__":
try:
end = time.time()
start = end - (30*24*60*60)
print("start={}, end={}".format(start, end))
reservations = pyslurm.slurmdb_reservations()
reservations.set_reservation_condition(start, end)
reservations_dict = reservations.get()
if len(reservations_dict):
for key, value in reservations_dict.items():
print("{} Reservation: {}".format('{', key))
reservation_display(value)
print("}")
else:
print("No reservation found")
except ValueError as e:
print("Error:{}".format(e.args[0]))
| Q-Leap-Networks/pyslurm | examples/listdb_reservations.py | Python | gpl-2.0 | 866 |
#!/usr/bin/python
from math import *
import sys
import string
k = (sqrt(2.)-1.)*4./3.
chars = []
encoding = []
count = 1
first = 1
def append(s):
chars.append(s)
def rint(x):
return int(round(x))
"""
if x>=0:
return int(x+0.5)
else:
return int(x-0.5)
"""
class vec:
def __init__(self, x, y=0):
if type(x) is type(()):
self.x, self.y = x
else:
self.x = x
self.y = y
def set(self, x, y):
self.__init__(x, y)
def move(self, x, y):
self.x = self.x + x
self.y = self.y + y
def __add__(self, v):
return vec(self.x+v.x, self.y+v.y)
def __sub__(self, v):
return vec(self.x-v.x, self.y-v.y)
def int(self):
return vec(rint(self.x), rint(self.y))
def t(self):
return (self.x, self.y)
class pvec(vec):
def __init__(self, l, a):
self.x = l * cos(a)
self.y = l * sin(a)
pen = vec(0,0)
def moveto(x, y=0):
global first
dx = rint(x-pen.x)
dy = rint(y-pen.y)
if dx!=0:
if dy!=0:
append("\t%i %i rmoveto" % (dx, dy))
else:
append("\t%i hmoveto" % (dx))
elif dy!=0:
append("\t%i vmoveto" % (dy))
elif first:
append("\t0 hmoveto")
first = 0
pen.x = pen.x+dx
pen.y = pen.y+dx
def rlineto(v):
if v.x!=0:
if v.y!=0:
append("\t%i %i rlineto" % (v.x, v.y))
else:
append("\t%i hlineto" % (v.x))
elif v.y!=0:
append("\t%i vlineto" % (v.y))
def closepath():
append("\tclosepath")
history = []
def movebase(x, y=0):
history.append((x,y))
pen.move(-x, -y)
def moveback():
x, y = history.pop()
pen.move(x, y)
def ellipse(rx, ry = None, half=0):
# rx>0 => counter-clockwise (filled)
# rx<0 => clockwise
if ry==None: ry = abs(rx)
dx1 = rint(k*rx)
dx2 = rx-dx1
dy1 = rint(k*ry)
dy2 = ry-dy1
rx = abs(rx)
moveto(0, -ry)
append("\t%i 0 %i %i 0 %i rrcurveto" % (+dx1, +dx2, +dy2, +dy1))
append("\t0 %i %i %i %i 0 rrcurveto" % (+dy1, -dx2, +dy2, -dx1))
if not half:
append("\t%i 0 %i %i 0 %i rrcurveto" % (-dx1, -dx2, -dy2, -dy1))
append("\t0 %i %i %i %i 0 rrcurveto" % (-dy1, +dx2, -dy2, +dx1))
closepath()
if half:
pen.set(0, ry)
else:
pen.set(0, -ry)
circle = ellipse
def rect(w, h):
moveto(0, 0)
if w>0:
append("\t%i hlineto" % (w))
append("\t%i vlineto" % (h))
append("\t%i hlineto" % (-w))
pen.set(0, h)
else:
append("\t%i vlineto" % (h))
append("\t%i hlineto" % (-w))
append("\t%i vlineto" % (-h))
pen.set(-w, 0)
closepath()
def poly(p):
moveto(0, 0)
prev = vec(0, 0)
for q in p:
rlineto(vec(q)-prev)
prev = vec(q)
closepath()
pen.set(prev.x, prev.y)
def line(w, l, a):
vw = pvec(w*.5, a-pi*.5)
vl = pvec(l, a)
p = vw
moveto(p.x, p.y)
p0 = p
#print '%%wla %i %i %.3f: %.3f %.3f' % (w, l, a, p0.x, p0.y)
p = p+vl
rlineto((p-p0).int())
p0 = p
#print '%%wla %i %i %.3f: %.3f %.3f' % (w, l, a, p0.x, p0.y)
p = p-vw-vw
rlineto((p-p0).int())
p0 = p
#print '%%wla %i %i %.3f: %.3f %.3f' % (w, l, a, p0.x, p0.y)
p = p-vl
#print '%%wla %i %i %.3f: %.3f %.3f' % (w, l, a, p.x, p.y)
rlineto((p-p0).int())
closepath()
pen.set(p.x, p.y)
def begin(name, code, hsb, w):
global first, count, history
history = []
pen.set(0, 0)
append("""\
/uni%04X { %% %s
%i %i hsbw""" % (code+0xE000, name, hsb, w))
i = len(encoding)
while i<code:
encoding.append('dup %i /.notdef put' % (i,))
i = i+1
encoding.append('dup %i /uni%04X put' % (code, code+0xE000))
count = count + 1
first = 1
def end():
append("""\
endchar
} ND""")
########################################
r = 400
s = 375
hsb = 200 # horizontal side bearing
hsb2 = 30
over = 10 # overshoot
width = 2*r+2*over+2*hsb2
########################################
begin('play', 0x01, hsb, width)
poly(( (s,r),
(0, 2*r),))
end()
########################################
w=150
begin('pause', 0x02, hsb, width)
rect(w, 2*r)
movebase(2*w)
rect(w, 2*r)
end()
########################################
begin('stop', 0x03, hsb, width)
rect(665, 720)
end()
########################################
begin('rewind', 0x04, hsb/2, width)
movebase(2*s+15)
poly(( (0, 2*r),
(-s, r),))
movebase(-s-15)
poly(( (0, 2*r),
(-s, r),))
end()
########################################
begin('fast forward', 0x05, hsb/2, width)
poly(( (s,r),
(0, 2*r),))
movebase(s+15)
poly(( (s,r),
(0, 2*r),))
end()
########################################
begin('clock', 0x06, hsb2, width)
movebase(r, r)
circle(r+over)
wc = 65
r0 = r-3*wc
n = 4
movebase(-wc/2, -wc/2)
rect(-wc, wc)
moveback()
for i in range(n):
a = i*2*pi/n
v = pvec(r0, a)
movebase(v.x, v.y)
line(-wc, r-r0, a)
moveback()
hh = 11
mm = 8
line(-50, r*.5, pi/2-2*pi*(hh+mm/60.)/12)
line(-40, r*.9, pi/2-2*pi*mm/60.)
end()
########################################
begin('contrast', 0x07, hsb2, width)
movebase(r, r)
circle(r+over)
circle(-(r+over-80), half=1)
end()
########################################
begin('saturation', 0x08, hsb2, width)
movebase(r, r)
circle(r+over)
circle(-(r+over-80))
v = pvec(160, pi/2)
movebase(v.x, v.y)
circle(80)
moveback()
v = pvec(160, pi/2+pi*2/3)
movebase(v.x, v.y)
circle(80)
moveback()
v = pvec(160, pi/2-pi*2/3)
movebase(v.x, v.y)
circle(80)
end()
########################################
begin('volume', 0x09, 0, 1000)
poly(( (1000, 0),
(1000, 500),))
end()
########################################
begin('brightness', 0x0A, hsb2, width)
movebase(r, r)
circle(150)
circle(-100)
rb = 375
wb = 50
l = 140
n = 8
for i in range(n):
a = i*2*pi/n
v = pvec(l, a)
movebase(v.x, v.y)
line(wb, rb-l, a)
moveback()
end()
########################################
begin('hue', 0x0B, hsb2, width)
movebase(r, r)
circle(r+over)
ellipse(-(322), 166)
movebase(0, 280)
circle(-(60))
end()
########################################
begin('progress [', 0x10, (334-182)/2, 334)
poly(( (182, 0),
(182, 90),
(145, 90),
(145, 550),
(182, 550),
(182, 640),
(0, 640),
))
end()
########################################
begin('progress |', 0x11, (334-166)/2, 334)
rect(166, 640)
end()
########################################
begin('progress ]', 0x12, (334-182)/2, 334)
poly(( (182, 0),
(182, 640),
(0, 640),
(0, 550),
(37, 550),
(37, 90),
(0, 90),
))
end()
########################################
begin('progress .', 0x13, (334-130)/2, 334)
movebase(0, (640-130)/2)
rect(130, 130)
end()
########################################
print """\
%!PS-AdobeFont-1.0: OSD 1.00
%%CreationDate: Sun Jul 22 12:38:28 2001
%
%%EndComments
12 dict begin
/FontInfo 9 dict dup begin
/version (Version 1.00) readonly def
/Notice (This is generated file.) readonly def
/FullName (OSD) readonly def
/FamilyName (OSD) readonly def
/Weight (Regular) readonly def
/ItalicAngle 0.000000 def
/isFixedPitch false def
/UnderlinePosition -133 def
/UnderlineThickness 49 def
end readonly def
/FontName /OSD def
/PaintType 0 def
/StrokeWidth 0 def
/FontMatrix [0.001 0 0 0.001 0 0] def
/FontBBox {0 -10 1000 810} readonly def
/Encoding 256 array"""
print string.join(encoding, '\n')
i = len(encoding)
while i<256:
print 'dup %i /.notdef put' % i
i = i+1
print """\
readonly def
currentdict end
currentfile eexec
dup /Private 15 dict dup begin
/RD{string currentfile exch readstring pop}executeonly def
/ND{noaccess def}executeonly def
/NP{noaccess put}executeonly def
/ForceBold false def
/BlueValues [ -10 0 800 810 640 650 720 730 ] def
/StdHW [ 65 ] def
/StdVW [ 65 ] def
/StemSnapH [ 65 800 ] def
/StemSnapV [ 65 150 ] def
/MinFeature {16 16} def
/password 5839 def
/Subrs 1 array
dup 0 {
return
} NP
ND
2 index
/CharStrings %i dict dup begin""" % count
print """\
/.notdef {
0 400 hsbw
endchar
} ND"""
print string.join(chars, '\n')
print """\
end
end
readonly put
noaccess put
dup/FontName get exch definefont pop
mark currentfile closefile"""
| GeeXboX/mplayer-ui | TOOLS/subfont-c/osd/gen.py | Python | gpl-2.0 | 8,012 |
from Plugins.Plugin import PluginDescriptor
from Screens.Console import Console
from Screens.ChoiceBox import ChoiceBox
from Screens.MessageBox import MessageBox
from Screens.Screen import Screen
from Screens.Standby import TryQuitMainloop
from Screens.Ipkg import Ipkg
from Screens.SoftwareUpdate import UpdatePlugin
from Components.ActionMap import ActionMap, NumberActionMap
from Components.Input import Input
from Components.Ipkg import IpkgComponent
from Components.Sources.StaticText import StaticText
from Components.ScrollLabel import ScrollLabel
from Components.Pixmap import Pixmap
from Components.MenuList import MenuList
from Components.Sources.List import List
from Components.Slider import Slider
from Components.Harddisk import harddiskmanager
from Components.config import config,getConfigListEntry, ConfigSubsection, ConfigText, ConfigLocations, ConfigYesNo, ConfigSelection
from Components.ConfigList import ConfigListScreen
from Components.Console import Console
from Components.MultiContent import MultiContentEntryText, MultiContentEntryPixmapAlphaTest
from Components.SelectionList import SelectionList
from Components.PluginComponent import plugins
from Components.About import about
from Components.PackageInfo import PackageInfoHandler
from Components.Language import language
from Components.AVSwitch import AVSwitch
from Components.Task import job_manager
from Tools.Directories import pathExists, fileExists, resolveFilename, SCOPE_PLUGINS, SCOPE_CURRENT_PLUGIN, SCOPE_ACTIVE_SKIN, SCOPE_METADIR
from Tools.LoadPixmap import LoadPixmap
from Tools.NumericalTextInput import NumericalTextInput
from enigma import eTimer, RT_HALIGN_LEFT, RT_VALIGN_CENTER, eListboxPythonMultiContent, eListbox, gFont, getDesktop, ePicLoad, eRCInput, getPrevAsciiCode, eEnv, iRecordableService
from cPickle import dump, load
from os import path as os_path, system as os_system, unlink, stat, mkdir, popen, makedirs, listdir, access, rename, remove, W_OK, R_OK, F_OK
from time import time, gmtime, strftime, localtime
from stat import ST_MTIME
from datetime import date
from twisted.web import client
from twisted.internet import reactor
from ImageWizard import ImageWizard
from BackupRestore import BackupSelection, RestoreMenu, BackupScreen, RestoreScreen, getBackupPath, getBackupFilename
from SoftwareTools import iSoftwareTools
config.plugins.configurationbackup = ConfigSubsection()
config.plugins.configurationbackup.backuplocation = ConfigText(default = '/media/hdd/', visible_width = 50, fixed_size = False)
config.plugins.configurationbackup.backupdirs = ConfigLocations(default=[eEnv.resolve('${sysconfdir}/enigma2/'), '/etc/network/interfaces', '/etc/wpa_supplicant.conf', '/etc/wpa_supplicant.ath0.conf', '/etc/wpa_supplicant.wlan0.conf', '/etc/resolv.conf', '/etc/default_gw', '/etc/hostname'])
config.plugins.softwaremanager = ConfigSubsection()
config.plugins.softwaremanager.overwriteConfigFiles = ConfigSelection(
[
("Y", _("Yes, always")),
("N", _("No, never")),
("ask", _("Always ask"))
], "Y")
config.plugins.softwaremanager.onSetupMenu = ConfigYesNo(default=False)
config.plugins.softwaremanager.onBlueButton = ConfigYesNo(default=False)
def write_cache(cache_file, cache_data):
#Does a cPickle dump
if not os_path.isdir( os_path.dirname(cache_file) ):
try:
mkdir( os_path.dirname(cache_file) )
except OSError:
print os_path.dirname(cache_file), 'is a file'
fd = open(cache_file, 'w')
dump(cache_data, fd, -1)
fd.close()
def valid_cache(cache_file, cache_ttl):
#See if the cache file exists and is still living
try:
mtime = stat(cache_file)[ST_MTIME]
except:
return 0
curr_time = time()
if (curr_time - mtime) > cache_ttl:
return 0
else:
return 1
def load_cache(cache_file):
#Does a cPickle load
fd = open(cache_file)
cache_data = load(fd)
fd.close()
return cache_data
class UpdatePluginMenu(Screen):
skin = """
<screen name="UpdatePluginMenu" position="center,center" size="610,410" >
<ePixmap pixmap="buttons/red.png" position="0,0" size="140,40" alphatest="on" />
<widget source="key_red" render="Label" position="0,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
<ePixmap pixmap="border_menu_350.png" position="5,50" zPosition="1" size="350,300" transparent="1" alphatest="on" />
<widget source="menu" render="Listbox" position="15,60" size="330,290" scrollbarMode="showOnDemand">
<convert type="TemplatedMultiContent">
{"template": [
MultiContentEntryText(pos = (2, 2), size = (330, 24), flags = RT_HALIGN_LEFT, text = 1), # index 0 is the MenuText,
],
"fonts": [gFont("Regular", 22)],
"itemHeight": 25
}
</convert>
</widget>
<widget source="menu" render="Listbox" position="360,50" size="240,300" scrollbarMode="showNever" selectionDisabled="1">
<convert type="TemplatedMultiContent">
{"template": [
MultiContentEntryText(pos = (2, 2), size = (240, 300), flags = RT_HALIGN_CENTER|RT_VALIGN_CENTER|RT_WRAP, text = 2), # index 2 is the Description,
],
"fonts": [gFont("Regular", 22)],
"itemHeight": 300
}
</convert>
</widget>
<widget source="status" render="Label" position="5,360" zPosition="10" size="600,50" halign="center" valign="center" font="Regular;22" transparent="1" shadowColor="black" shadowOffset="-1,-1" />
</screen>"""
def __init__(self, session, args = 0):
Screen.__init__(self, session)
Screen.setTitle(self, _("Software management"))
self.skin_path = plugin_path
self.menu = args
self.list = []
self.oktext = _("\nPress OK on your remote control to continue.")
self.menutext = _("Press MENU on your remote control for additional options.")
self.infotext = _("Press INFO on your remote control for additional information.")
self.text = ""
self.backupdirs = ' '.join( config.plugins.configurationbackup.backupdirs.getValue() )
if self.menu == 0:
print "building menu entries"
self.list.append(("install-extensions", _("Manage extensions"), _("\nManage extensions or plugins for your STB_BOX" ) + self.oktext, None))
self.list.append(("software-update", _("Software update"), _("\nOnline update of your STB_BOX software." ) + self.oktext, None))
self.list.append(("software-restore", _("Software restore"), _("\nRestore your STB_BOX with a new firmware." ) + self.oktext, None))
self.list.append(("system-backup", _("Backup system settings"), _("\nBackup your STB_BOX settings." ) + self.oktext + "\n\n" + self.infotext, None))
self.list.append(("system-restore",_("Restore system settings"), _("\nRestore your STB_BOX settings." ) + self.oktext, None))
self.list.append(("ipkg-install", _("Install local extension"), _("\nScan for local extensions and install them." ) + self.oktext, None))
for p in plugins.getPlugins(PluginDescriptor.WHERE_SOFTWAREMANAGER):
if p.__call__.has_key("SoftwareSupported"):
callFnc = p.__call__["SoftwareSupported"](None)
if callFnc is not None:
if p.__call__.has_key("menuEntryName"):
menuEntryName = p.__call__["menuEntryName"](None)
else:
menuEntryName = _('Extended Software')
if p.__call__.has_key("menuEntryDescription"):
menuEntryDescription = p.__call__["menuEntryDescription"](None)
else:
menuEntryDescription = _('Extended Software Plugin')
self.list.append(('default-plugin', menuEntryName, menuEntryDescription + self.oktext, callFnc))
if config.usage.setup_level.index >= 2: # expert+
self.list.append(("advanced", _("Advanced options"), _("\nAdvanced options and settings." ) + self.oktext, None))
elif self.menu == 1:
self.list.append(("advancedrestore", _("Advanced restore"), _("\nRestore your backups by date." ) + self.oktext, None))
self.list.append(("backuplocation", _("Select backup location"), _("\nSelect your backup device.\nCurrent device: " ) + config.plugins.configurationbackup.backuplocation.getValue() + self.oktext, None))
self.list.append(("backupfiles", _("Select backup files"), _("Select files for backup.") + self.oktext + "\n\n" + self.infotext, None))
if config.usage.setup_level.index >= 2: # expert+
self.list.append(("ipkg-manager", _("Packet management"), _("\nView, install and remove available or installed packages." ) + self.oktext, None))
self.list.append(("ipkg-source",_("Select upgrade source"), _("\nEdit the upgrade source address." ) + self.oktext, None))
for p in plugins.getPlugins(PluginDescriptor.WHERE_SOFTWAREMANAGER):
if p.__call__.has_key("AdvancedSoftwareSupported"):
callFnc = p.__call__["AdvancedSoftwareSupported"](None)
if callFnc is not None:
if p.__call__.has_key("menuEntryName"):
menuEntryName = p.__call__["menuEntryName"](None)
else:
menuEntryName = _('Advanced software')
if p.__call__.has_key("menuEntryDescription"):
menuEntryDescription = p.__call__["menuEntryDescription"](None)
else:
menuEntryDescription = _('Advanced software plugin')
self.list.append(('advanced-plugin', menuEntryName, menuEntryDescription + self.oktext, callFnc))
self["menu"] = List(self.list)
self["key_red"] = StaticText(_("Close"))
self["status"] = StaticText(self.menutext)
self["shortcuts"] = NumberActionMap(["ShortcutActions", "WizardActions", "InfobarEPGActions", "MenuActions", "NumberActions"],
{
"ok": self.go,
"back": self.close,
"red": self.close,
"menu": self.handleMenu,
"showEventInfo": self.handleInfo,
"1": self.go,
"2": self.go,
"3": self.go,
"4": self.go,
"5": self.go,
"6": self.go,
"7": self.go,
"8": self.go,
"9": self.go,
}, -1)
self.onLayoutFinish.append(self.layoutFinished)
self.backuppath = getBackupPath()
self.backupfile = getBackupFilename()
self.fullbackupfilename = self.backuppath + "/" + self.backupfile
self.onShown.append(self.setWindowTitle)
self.onChangedEntry = []
self["menu"].onSelectionChanged.append(self.selectionChanged)
def createSummary(self):
from Screens.PluginBrowser import PluginBrowserSummary
return PluginBrowserSummary
def selectionChanged(self):
item = self["menu"].getCurrent()
if item:
name = item[1]
desc = item[2]
else:
name = "-"
desc = ""
for cb in self.onChangedEntry:
cb(name, desc)
def layoutFinished(self):
idx = 0
self["menu"].index = idx
def setWindowTitle(self):
self.setTitle(_("Software management"))
def cleanup(self):
iSoftwareTools.cleanupSoftwareTools()
def getUpdateInfos(self):
if iSoftwareTools.NetworkConnectionAvailable is True:
if iSoftwareTools.available_updates is not 0:
self.text = _("There are at least %s updates available.") % (str(iSoftwareTools.available_updates))
else:
self.text = "" #_("There are no updates available.")
if iSoftwareTools.list_updating is True:
self.text += "\n" + _("A search for available updates is currently in progress.")
else:
self.text = _("No network connection available.")
self["status"].setText(self.text)
def handleMenu(self):
self.session.open(SoftwareManagerSetup)
def handleInfo(self):
current = self["menu"].getCurrent()
if current:
currentEntry = current[0]
if currentEntry in ("system-backup","backupfiles"):
self.session.open(SoftwareManagerInfo, mode = "backupinfo")
def go(self, num = None):
if num is not None:
num -= 1
if not num < self["menu"].count():
return
self["menu"].setIndex(num)
current = self["menu"].getCurrent()
if current:
currentEntry = current[0]
if self.menu == 0:
if (currentEntry == "software-update"):
self.session.open(UpdatePlugin)
elif (currentEntry == "software-restore"):
self.session.open(ImageWizard)
elif (currentEntry == "install-extensions"):
self.session.open(PluginManager, self.skin_path)
elif (currentEntry == "system-backup"):
self.session.openWithCallback(self.backupDone,BackupScreen, runBackup = True)
elif (currentEntry == "system-restore"):
if os_path.exists(self.fullbackupfilename):
self.session.openWithCallback(self.startRestore, MessageBox, _("Are you sure you want to restore the backup?\nYour receiver will restart after the backup has been restored!"))
else:
self.session.open(MessageBox, _("Sorry, no backups found!"), MessageBox.TYPE_INFO, timeout = 10)
elif (currentEntry == "ipkg-install"):
try:
from Plugins.Extensions.MediaScanner.plugin import main
main(self.session)
except:
self.session.open(MessageBox, _("Sorry, %s has not been installed!") % ("MediaScanner"), MessageBox.TYPE_INFO, timeout = 10)
elif (currentEntry == "default-plugin"):
self.extended = current[3]
self.extended(self.session, None)
elif (currentEntry == "advanced"):
self.session.open(UpdatePluginMenu, 1)
elif self.menu == 1:
if (currentEntry == "ipkg-manager"):
self.session.open(PacketManager, self.skin_path)
elif (currentEntry == "backuplocation"):
parts = [ (r.description, r.mountpoint, self.session) for r in harddiskmanager.getMountedPartitions(onlyhotplug = False)]
for x in parts:
if not access(x[1], F_OK|R_OK|W_OK) or x[1] == '/':
parts.remove(x)
if len(parts):
self.session.openWithCallback(self.backuplocation_choosen, ChoiceBox, title = _("Please select medium to use as backup location"), list = parts)
elif (currentEntry == "backupfiles"):
self.session.openWithCallback(self.backupfiles_choosen,BackupSelection)
elif (currentEntry == "advancedrestore"):
self.session.open(RestoreMenu, self.skin_path)
elif (currentEntry == "ipkg-source"):
self.session.open(IPKGMenu, self.skin_path)
elif (currentEntry == "advanced-plugin"):
self.extended = current[3]
self.extended(self.session, None)
def backupfiles_choosen(self, ret):
self.backupdirs = ' '.join( config.plugins.configurationbackup.backupdirs.getValue() )
config.plugins.configurationbackup.backupdirs.save()
config.plugins.configurationbackup.save()
config.save()
def backuplocation_choosen(self, option):
oldpath = config.plugins.configurationbackup.backuplocation.getValue()
if option is not None:
config.plugins.configurationbackup.backuplocation.value = str(option[1])
config.plugins.configurationbackup.backuplocation.save()
config.plugins.configurationbackup.save()
config.save()
newpath = config.plugins.configurationbackup.backuplocation.getValue()
if newpath != oldpath:
self.createBackupfolders()
def createBackupfolders(self):
print "Creating backup folder if not already there..."
self.backuppath = getBackupPath()
try:
if (os_path.exists(self.backuppath) == False):
makedirs(self.backuppath)
except OSError:
self.session.open(MessageBox, _("Sorry, your backup destination is not writeable.\nPlease select a different one."), MessageBox.TYPE_INFO, timeout = 10)
def backupDone(self,retval = None):
if retval is True:
self.session.open(MessageBox, _("Backup completed."), MessageBox.TYPE_INFO, timeout = 10)
else:
self.session.open(MessageBox, _("Backup failed."), MessageBox.TYPE_INFO, timeout = 10)
def startRestore(self, ret = False):
if (ret == True):
self.exe = True
self.session.open(RestoreScreen, runRestore = True)
class SoftwareManagerSetup(Screen, ConfigListScreen):
skin = """
<screen name="SoftwareManagerSetup" position="center,center" size="560,440" title="SoftwareManager setup">
<ePixmap pixmap="buttons/red.png" position="0,0" size="140,40" alphatest="on" />
<ePixmap pixmap="buttons/green.png" position="140,0" size="140,40" alphatest="on" />
<ePixmap pixmap="buttons/yellow.png" position="280,0" size="140,40" alphatest="on" />
<ePixmap pixmap="buttons/blue.png" position="420,0" size="140,40" alphatest="on" />
<widget source="key_red" render="Label" position="0,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
<widget source="key_green" render="Label" position="140,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />
<widget source="key_yellow" render="Label" position="280,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#a08500" transparent="1" />
<widget source="key_blue" render="Label" position="420,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#18188b" transparent="1" />
<widget name="config" position="5,50" size="550,350" scrollbarMode="showOnDemand" />
<ePixmap pixmap="div-h.png" position="0,400" zPosition="1" size="560,2" />
<widget source="introduction" render="Label" position="5,410" size="550,30" zPosition="10" font="Regular;21" halign="center" valign="center" backgroundColor="#25062748" transparent="1" />
</screen>"""
def __init__(self, session, skin_path = None):
Screen.__init__(self, session)
self.session = session
self.skin_path = skin_path
if self.skin_path == None:
self.skin_path = resolveFilename(SCOPE_CURRENT_PLUGIN, "SystemPlugins/SoftwareManager")
self.onChangedEntry = [ ]
self.setup_title = _("Software manager setup")
self.overwriteConfigfilesEntry = None
self.list = [ ]
ConfigListScreen.__init__(self, self.list, session = session, on_change = self.changedEntry)
self["actions"] = ActionMap(["SetupActions", "MenuActions"],
{
"cancel": self.keyCancel,
"save": self.apply,
"menu": self.closeRecursive,
}, -2)
self["key_red"] = StaticText(_("Cancel"))
self["key_green"] = StaticText(_("OK"))
self["key_yellow"] = StaticText()
self["key_blue"] = StaticText()
self["introduction"] = StaticText()
self.createSetup()
self.onLayoutFinish.append(self.layoutFinished)
def layoutFinished(self):
self.setTitle(self.setup_title)
def createSetup(self):
self.list = [ ]
self.overwriteConfigfilesEntry = getConfigListEntry(_("Overwrite configuration files?"), config.plugins.softwaremanager.overwriteConfigFiles)
self.list.append(self.overwriteConfigfilesEntry)
self.list.append(getConfigListEntry(_("show softwaremanager in plugin menu"), config.plugins.softwaremanager.onSetupMenu))
self.list.append(getConfigListEntry(_("show softwaremanager on blue button"), config.plugins.softwaremanager.onBlueButton))
self["config"].list = self.list
self["config"].l.setSeperation(400)
self["config"].l.setList(self.list)
if not self.selectionChanged in self["config"].onSelectionChanged:
self["config"].onSelectionChanged.append(self.selectionChanged)
self.selectionChanged()
def selectionChanged(self):
if self["config"].getCurrent() == self.overwriteConfigfilesEntry:
self["introduction"].setText(_("Overwrite configuration files during software upgrade?"))
else:
self["introduction"].setText("")
def newConfig(self):
pass
def keyLeft(self):
ConfigListScreen.keyLeft(self)
def keyRight(self):
ConfigListScreen.keyRight(self)
def confirm(self, confirmed):
if not confirmed:
print "not confirmed"
return
else:
self.keySave()
plugins.clearPluginList()
plugins.readPluginList(resolveFilename(SCOPE_PLUGINS))
def apply(self):
self.session.openWithCallback(self.confirm, MessageBox, _("Use these settings?"), MessageBox.TYPE_YESNO, timeout = 20, default = True)
def cancelConfirm(self, result):
if not result:
return
for x in self["config"].list:
x[1].cancel()
self.close()
def keyCancel(self):
if self["config"].isChanged():
self.session.openWithCallback(self.cancelConfirm, MessageBox, _("Really close without saving settings?"), MessageBox.TYPE_YESNO, timeout = 20, default = False)
else:
self.close()
# for summary:
def changedEntry(self):
for x in self.onChangedEntry:
x()
self.selectionChanged()
def getCurrentEntry(self):
return self["config"].getCurrent()[0]
def getCurrentValue(self):
return str(self["config"].getCurrent()[1].getValue())
def createSummary(self):
from Screens.Setup import SetupSummary
return SetupSummary
class SoftwareManagerInfo(Screen):
skin = """
<screen name="SoftwareManagerInfo" position="center,center" size="560,440" title="SoftwareManager information">
<ePixmap pixmap="buttons/red.png" position="0,0" size="140,40" alphatest="on" />
<ePixmap pixmap="buttons/green.png" position="140,0" size="140,40" alphatest="on" />
<ePixmap pixmap="buttons/yellow.png" position="280,0" size="140,40" alphatest="on" />
<ePixmap pixmap="buttons/blue.png" position="420,0" size="140,40" alphatest="on" />
<widget source="key_red" render="Label" position="0,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
<widget source="key_green" render="Label" position="140,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />
<widget source="key_yellow" render="Label" position="280,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#a08500" transparent="1" />
<widget source="key_blue" render="Label" position="420,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#18188b" transparent="1" />
<widget source="list" render="Listbox" position="5,50" size="550,340" scrollbarMode="showOnDemand" selectionDisabled="0">
<convert type="TemplatedMultiContent">
{"template": [
MultiContentEntryText(pos = (5, 0), size = (540, 26), font=0, flags = RT_HALIGN_LEFT | RT_HALIGN_CENTER, text = 0), # index 0 is the name
],
"fonts": [gFont("Regular", 24),gFont("Regular", 22)],
"itemHeight": 26
}
</convert>
</widget>
<ePixmap pixmap="div-h.png" position="0,400" zPosition="1" size="560,2" />
<widget source="introduction" render="Label" position="5,410" size="550,30" zPosition="10" font="Regular;21" halign="center" valign="center" backgroundColor="#25062748" transparent="1" />
</screen>"""
def __init__(self, session, skin_path = None, mode = None):
Screen.__init__(self, session)
self.session = session
self.mode = mode
self.skin_path = skin_path
if self.skin_path == None:
self.skin_path = resolveFilename(SCOPE_CURRENT_PLUGIN, "SystemPlugins/SoftwareManager")
self["actions"] = ActionMap(["ShortcutActions", "WizardActions"],
{
"back": self.close,
"red": self.close,
}, -2)
self.list = []
self["list"] = List(self.list)
self["key_red"] = StaticText(_("Close"))
self["key_green"] = StaticText()
self["key_yellow"] = StaticText()
self["key_blue"] = StaticText()
self["introduction"] = StaticText()
self.onLayoutFinish.append(self.layoutFinished)
def layoutFinished(self):
self.setTitle(_("Softwaremanager information"))
if self.mode is not None:
self.showInfos()
def showInfos(self):
if self.mode == "backupinfo":
self.list = []
backupfiles = config.plugins.configurationbackup.backupdirs.getValue()
for entry in backupfiles:
self.list.append((entry,))
self['list'].setList(self.list)
class PluginManager(Screen, PackageInfoHandler):
skin = """
<screen name="PluginManager" position="center,center" size="560,440" >
<ePixmap pixmap="buttons/red.png" position="0,0" size="140,40" alphatest="on" />
<ePixmap pixmap="buttons/green.png" position="140,0" size="140,40" alphatest="on" />
<ePixmap pixmap="buttons/yellow.png" position="280,0" size="140,40" alphatest="on" />
<ePixmap pixmap="buttons/blue.png" position="420,0" size="140,40" alphatest="on" />
<widget source="key_red" render="Label" position="0,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
<widget source="key_green" render="Label" position="140,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />
<widget source="key_yellow" render="Label" position="280,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#a08500" transparent="1" />
<widget source="key_blue" render="Label" position="420,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#18188b" transparent="1" />
<widget source="list" render="Listbox" position="5,50" size="550,360" scrollbarMode="showOnDemand">
<convert type="TemplatedMultiContent">
{"templates":
{"default": (51,[
MultiContentEntryText(pos = (0, 1), size = (470, 24), font=0, flags = RT_HALIGN_LEFT, text = 0), # index 0 is the name
MultiContentEntryText(pos = (0, 25), size = (470, 24), font=1, flags = RT_HALIGN_LEFT, text = 2), # index 2 is the description
MultiContentEntryPixmapAlphaTest(pos = (475, 0), size = (48, 48), png = 5), # index 5 is the status pixmap
MultiContentEntryPixmapAlphaTest(pos = (0, 49), size = (550, 2), png = 6), # index 6 is the div pixmap
]),
"category": (40,[
MultiContentEntryText(pos = (30, 0), size = (500, 22), font=0, flags = RT_HALIGN_LEFT, text = 0), # index 0 is the name
MultiContentEntryText(pos = (30, 22), size = (500, 16), font=2, flags = RT_HALIGN_LEFT, text = 1), # index 1 is the description
MultiContentEntryPixmapAlphaTest(pos = (0, 38), size = (550, 2), png = 3), # index 3 is the div pixmap
])
},
"fonts": [gFont("Regular", 22),gFont("Regular", 20),gFont("Regular", 16)],
"itemHeight": 52
}
</convert>
</widget>
<widget source="status" render="Label" position="5,410" zPosition="10" size="540,30" halign="center" valign="center" font="Regular;22" transparent="1" shadowColor="black" shadowOffset="-1,-1" />
</screen>"""
def __init__(self, session, plugin_path = None, args = None):
Screen.__init__(self, session)
Screen.setTitle(self, _("Extensions management"))
self.session = session
self.skin_path = plugin_path
if self.skin_path == None:
self.skin_path = resolveFilename(SCOPE_CURRENT_PLUGIN, "SystemPlugins/SoftwareManager")
self["shortcuts"] = ActionMap(["ShortcutActions", "WizardActions", "InfobarEPGActions", "HelpActions" ],
{
"ok": self.handleCurrent,
"back": self.exit,
"red": self.exit,
"green": self.handleCurrent,
"yellow": self.handleSelected,
"showEventInfo": self.handleSelected,
"displayHelp": self.handleHelp,
}, -1)
self.list = []
self.statuslist = []
self.selectedFiles = []
self.categoryList = []
self.packetlist = []
self["list"] = List(self.list)
self["key_red"] = StaticText(_("Close"))
self["key_green"] = StaticText("")
self["key_yellow"] = StaticText("")
self["key_blue"] = StaticText("")
self["status"] = StaticText("")
self.cmdList = []
self.oktext = _("\nAfter pressing OK, please wait!")
if not self.selectionChanged in self["list"].onSelectionChanged:
self["list"].onSelectionChanged.append(self.selectionChanged)
self.currList = ""
self.currentSelectedTag = None
self.currentSelectedIndex = None
self.currentSelectedPackage = None
self.saved_currentSelectedPackage = None
self.restartRequired = False
self.onShown.append(self.setWindowTitle)
self.onLayoutFinish.append(self.getUpdateInfos)
def setWindowTitle(self):
self.setTitle(_("Extensions management"))
def exit(self):
if self.currList == "packages":
self.currList = "category"
self.currentSelectedTag = None
self["list"].style = "category"
self['list'].setList(self.categoryList)
self["list"].setIndex(self.currentSelectedIndex)
self["list"].updateList(self.categoryList)
self.selectionChanged()
else:
iSoftwareTools.cleanupSoftwareTools()
self.prepareInstall()
if len(self.cmdList):
self.session.openWithCallback(self.runExecute, PluginManagerInfo, self.skin_path, self.cmdList)
else:
self.close()
def handleHelp(self):
if self.currList != "status":
self.session.open(PluginManagerHelp, self.skin_path)
def setState(self,status = None):
if status:
self.currList = "status"
self.statuslist = []
self["key_green"].setText("")
self["key_blue"].setText("")
self["key_yellow"].setText("")
divpng = LoadPixmap(cached=True, path=resolveFilename(SCOPE_ACTIVE_SKIN, "div-h.png"))
if status == 'update':
statuspng = LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_PLUGIN, "SystemPlugins/SoftwareManager/upgrade.png"))
self.statuslist.append(( _("Updating software catalog"), '', _("Searching for available updates. Please wait..." ),'', '', statuspng, divpng, None, '' ))
elif status == 'sync':
statuspng = LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_PLUGIN, "SystemPlugins/SoftwareManager/upgrade.png"))
self.statuslist.append(( _("Package list update"), '', _("Searching for new installed or removed packages. Please wait..." ),'', '', statuspng, divpng, None, '' ))
elif status == 'error':
self["key_green"].setText(_("Continue"))
statuspng = LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_PLUGIN, "SystemPlugins/SoftwareManager/remove.png"))
self.statuslist.append(( _("Error"), '', _("An error occurred while downloading the packetlist. Please try again." ),'', '', statuspng, divpng, None, '' ))
self["list"].style = "default"
self['list'].setList(self.statuslist)
def getUpdateInfos(self):
if (iSoftwareTools.lastDownloadDate is not None and iSoftwareTools.NetworkConnectionAvailable is False):
self.rebuildList()
else:
self.setState('update')
iSoftwareTools.startSoftwareTools(self.getUpdateInfosCB)
def getUpdateInfosCB(self, retval = None):
if retval is not None:
if retval is True:
if iSoftwareTools.available_updates is not 0:
self["status"].setText(_("There are at least ") + str(iSoftwareTools.available_updates) + ' ' + _("updates available."))
else:
self["status"].setText(_("There are no updates available."))
self.rebuildList()
elif retval is False:
if iSoftwareTools.lastDownloadDate is None:
self.setState('error')
if iSoftwareTools.NetworkConnectionAvailable:
self["status"].setText(_("Updatefeed not available."))
else:
self["status"].setText(_("No network connection available."))
else:
iSoftwareTools.lastDownloadDate = time()
iSoftwareTools.list_updating = True
self.setState('update')
iSoftwareTools.getUpdates(self.getUpdateInfosCB)
def rebuildList(self, retval = None):
if self.currentSelectedTag is None:
self.buildCategoryList()
else:
self.buildPacketList(self.currentSelectedTag)
def selectionChanged(self):
current = self["list"].getCurrent()
self["status"].setText("")
if current:
if self.currList == "packages":
self["key_red"].setText(_("Back"))
if current[4] == 'installed':
self["key_green"].setText(_("Uninstall"))
elif current[4] == 'installable':
self["key_green"].setText(_("Install"))
if iSoftwareTools.NetworkConnectionAvailable is False:
self["key_green"].setText("")
elif current[4] == 'remove':
self["key_green"].setText(_("Undo uninstall"))
elif current[4] == 'install':
self["key_green"].setText(_("Undo install"))
if iSoftwareTools.NetworkConnectionAvailable is False:
self["key_green"].setText("")
self["key_yellow"].setText(_("View details"))
self["key_blue"].setText("")
if len(self.selectedFiles) == 0 and iSoftwareTools.available_updates is not 0:
self["status"].setText(_("There are at least ") + str(iSoftwareTools.available_updates) + ' ' + _("updates available."))
elif len(self.selectedFiles) is not 0:
self["status"].setText(str(len(self.selectedFiles)) + ' ' + _("packages selected."))
else:
self["status"].setText(_("There are currently no outstanding actions."))
elif self.currList == "category":
self["key_red"].setText(_("Close"))
self["key_green"].setText("")
self["key_yellow"].setText("")
self["key_blue"].setText("")
if len(self.selectedFiles) == 0 and iSoftwareTools.available_updates is not 0:
self["status"].setText(_("There are at least ") + str(iSoftwareTools.available_updates) + ' ' + _("updates available."))
self["key_yellow"].setText(_("Update"))
elif len(self.selectedFiles) is not 0:
self["status"].setText(str(len(self.selectedFiles)) + ' ' + _("packages selected."))
self["key_yellow"].setText(_("Process"))
else:
self["status"].setText(_("There are currently no outstanding actions."))
def getSelectionState(self, detailsFile):
for entry in self.selectedFiles:
if entry[0] == detailsFile:
return True
return False
def handleCurrent(self):
current = self["list"].getCurrent()
if current:
if self.currList == "category":
self.currentSelectedIndex = self["list"].index
selectedTag = current[2]
self.buildPacketList(selectedTag)
elif self.currList == "packages":
if current[7] is not '':
idx = self["list"].getIndex()
detailsFile = self.list[idx][1]
if self.list[idx][7] == True:
for entry in self.selectedFiles:
if entry[0] == detailsFile:
self.selectedFiles.remove(entry)
else:
alreadyinList = False
for entry in self.selectedFiles:
if entry[0] == detailsFile:
alreadyinList = True
if not alreadyinList:
if (iSoftwareTools.NetworkConnectionAvailable is False and current[4] in ('installable','install')):
pass
else:
self.selectedFiles.append((detailsFile,current[4],current[3]))
self.currentSelectedPackage = ((detailsFile,current[4],current[3]))
if current[4] == 'installed':
self.list[idx] = self.buildEntryComponent(current[0], current[1], current[2], current[3], 'remove', True)
elif current[4] == 'installable':
if iSoftwareTools.NetworkConnectionAvailable:
self.list[idx] = self.buildEntryComponent(current[0], current[1], current[2], current[3], 'install', True)
elif current[4] == 'remove':
self.list[idx] = self.buildEntryComponent(current[0], current[1], current[2], current[3], 'installed', False)
elif current[4] == 'install':
if iSoftwareTools.NetworkConnectionAvailable:
self.list[idx] = self.buildEntryComponent(current[0], current[1], current[2], current[3], 'installable',False)
self["list"].setList(self.list)
self["list"].setIndex(idx)
self["list"].updateList(self.list)
self.selectionChanged()
elif self.currList == "status":
iSoftwareTools.lastDownloadDate = time()
iSoftwareTools.list_updating = True
self.setState('update')
iSoftwareTools.getUpdates(self.getUpdateInfosCB)
def handleSelected(self):
current = self["list"].getCurrent()
if current:
if self.currList == "packages":
if current[7] is not '':
detailsfile = iSoftwareTools.directory[0] + "/" + current[1]
if (os_path.exists(detailsfile) == True):
self.saved_currentSelectedPackage = self.currentSelectedPackage
self.session.openWithCallback(self.detailsClosed, PluginDetails, self.skin_path, current)
else:
self.session.open(MessageBox, _("Sorry, no details available!"), MessageBox.TYPE_INFO, timeout = 10)
elif self.currList == "category":
self.prepareInstall()
if len(self.cmdList):
self.session.openWithCallback(self.runExecute, PluginManagerInfo, self.skin_path, self.cmdList)
def detailsClosed(self, result = None):
if result is not None:
if result is not False:
self.setState('sync')
iSoftwareTools.lastDownloadDate = time()
for entry in self.selectedFiles:
if entry == self.saved_currentSelectedPackage:
self.selectedFiles.remove(entry)
iSoftwareTools.startIpkgListInstalled(self.rebuildList)
def buildEntryComponent(self, name, details, description, packagename, state, selected = False):
divpng = LoadPixmap(cached=True, path=resolveFilename(SCOPE_ACTIVE_SKIN, "div-h.png"))
installedpng = LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_PLUGIN, "SystemPlugins/SoftwareManager/installed.png"))
installablepng = LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_PLUGIN, "SystemPlugins/SoftwareManager/installable.png"))
removepng = LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_PLUGIN, "SystemPlugins/SoftwareManager/remove.png"))
installpng = LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_PLUGIN, "SystemPlugins/SoftwareManager/install.png"))
if state == 'installed':
return((name, details, description, packagename, state, installedpng, divpng, selected))
elif state == 'installable':
return((name, details, description, packagename, state, installablepng, divpng, selected))
elif state == 'remove':
return((name, details, description, packagename, state, removepng, divpng, selected))
elif state == 'install':
return((name, details, description, packagename, state, installpng, divpng, selected))
def buildPacketList(self, categorytag = None):
if categorytag is not None:
self.currList = "packages"
self.currentSelectedTag = categorytag
self.packetlist = []
for package in iSoftwareTools.packagesIndexlist[:]:
prerequisites = package[0]["prerequisites"]
if prerequisites.has_key("tag"):
for foundtag in prerequisites["tag"]:
if categorytag == foundtag:
attributes = package[0]["attributes"]
if attributes.has_key("packagetype"):
if attributes["packagetype"] == "internal":
continue
self.packetlist.append([attributes["name"], attributes["details"], attributes["shortdescription"], attributes["packagename"]])
else:
self.packetlist.append([attributes["name"], attributes["details"], attributes["shortdescription"], attributes["packagename"]])
self.list = []
for x in self.packetlist:
status = ""
name = x[0].strip()
details = x[1].strip()
description = x[2].strip()
if not description:
description = "No description available."
packagename = x[3].strip()
selectState = self.getSelectionState(details)
if iSoftwareTools.installed_packetlist.has_key(packagename):
if selectState == True:
status = "remove"
else:
status = "installed"
self.list.append(self.buildEntryComponent(name, _(details), _(description), packagename, status, selected = selectState))
else:
if selectState == True:
status = "install"
else:
status = "installable"
self.list.append(self.buildEntryComponent(name, _(details), _(description), packagename, status, selected = selectState))
if len(self.list):
self.list.sort(key=lambda x: x[0])
self["list"].style = "default"
self['list'].setList(self.list)
self["list"].updateList(self.list)
self.selectionChanged()
def buildCategoryList(self):
self.currList = "category"
self.categories = []
self.categoryList = []
for package in iSoftwareTools.packagesIndexlist[:]:
prerequisites = package[0]["prerequisites"]
if prerequisites.has_key("tag"):
for foundtag in prerequisites["tag"]:
attributes = package[0]["attributes"]
if foundtag not in self.categories:
self.categories.append(foundtag)
self.categoryList.append(self.buildCategoryComponent(foundtag))
self.categoryList.sort(key=lambda x: x[0])
self["list"].style = "category"
self['list'].setList(self.categoryList)
self["list"].updateList(self.categoryList)
self.selectionChanged()
def buildCategoryComponent(self, tag = None):
divpng = LoadPixmap(cached=True, path=resolveFilename(SCOPE_ACTIVE_SKIN, "div-h.png"))
if tag is not None:
if tag == 'System':
return(( _("System"), _("View list of available system extensions" ), tag, divpng ))
elif tag == 'Skin':
return(( _("Skins"), _("View list of available skins" ), tag, divpng ))
elif tag == 'Recording':
return(( _("Recordings"), _("View list of available recording extensions" ), tag, divpng ))
elif tag == 'Network':
return(( _("Network"), _("View list of available networking extensions" ), tag, divpng ))
elif tag == 'CI':
return(( _("Common Interface"), _("View list of available CommonInterface extensions" ), tag, divpng ))
elif tag == 'Default':
return(( _("Default settings"), _("View list of available default settings" ), tag, divpng ))
elif tag == 'SAT':
return(( _("Satellite equipment"), _("View list of available Satellite equipment extensions." ), tag, divpng ))
elif tag == 'Software':
return(( _("Software"), _("View list of available software extensions" ), tag, divpng ))
elif tag == 'Multimedia':
return(( _("Multimedia"), _("View list of available multimedia extensions." ), tag, divpng ))
elif tag == 'Display':
return(( _("Display and userinterface"), _("View list of available display and userinterface extensions." ), tag, divpng ))
elif tag == 'EPG':
return(( _("Electronic Program Guide"), _("View list of available EPG extensions." ), tag, divpng ))
elif tag == 'Communication':
return(( _("Communication"), _("View list of available communication extensions." ), tag, divpng ))
else: # dynamically generate non existent tags
return(( str(tag), _("View list of available ") + str(tag) + ' ' + _("extensions." ), tag, divpng ))
def prepareInstall(self):
self.cmdList = []
if iSoftwareTools.available_updates > 0:
self.cmdList.append((IpkgComponent.CMD_UPGRADE, { "test_only": False }))
if self.selectedFiles and len(self.selectedFiles):
for plugin in self.selectedFiles:
detailsfile = iSoftwareTools.directory[0] + "/" + plugin[0]
if (os_path.exists(detailsfile) == True):
iSoftwareTools.fillPackageDetails(plugin[0])
self.package = iSoftwareTools.packageDetails[0]
if self.package[0].has_key("attributes"):
self.attributes = self.package[0]["attributes"]
if self.attributes.has_key("needsRestart"):
self.restartRequired = True
if self.attributes.has_key("package"):
self.packagefiles = self.attributes["package"]
if plugin[1] == 'installed':
if self.packagefiles:
for package in self.packagefiles[:]:
self.cmdList.append((IpkgComponent.CMD_REMOVE, { "package": package["name"] }))
else:
self.cmdList.append((IpkgComponent.CMD_REMOVE, { "package": plugin[2] }))
else:
if self.packagefiles:
for package in self.packagefiles[:]:
self.cmdList.append((IpkgComponent.CMD_INSTALL, { "package": package["name"] }))
else:
self.cmdList.append((IpkgComponent.CMD_INSTALL, { "package": plugin[2] }))
else:
if plugin[1] == 'installed':
self.cmdList.append((IpkgComponent.CMD_REMOVE, { "package": plugin[2] }))
else:
self.cmdList.append((IpkgComponent.CMD_INSTALL, { "package": plugin[2] }))
def runExecute(self, result = None):
if result is not None:
if result[0] is True:
self.session.openWithCallback(self.runExecuteFinished, Ipkg, cmdList = self.cmdList)
elif result[0] is False:
self.cmdList = result[1]
self.session.openWithCallback(self.runExecuteFinished, Ipkg, cmdList = self.cmdList)
else:
self.close()
def runExecuteFinished(self):
self.reloadPluginlist()
if plugins.restartRequired or self.restartRequired:
self.session.openWithCallback(self.ExecuteReboot, MessageBox, _("Install or remove finished.") +" "+_("Do you want to reboot your receiver?"), MessageBox.TYPE_YESNO)
else:
self.selectedFiles = []
self.restartRequired = False
self.detailsClosed(True)
def ExecuteReboot(self, result):
if result:
self.session.open(TryQuitMainloop,retvalue=3)
else:
self.selectedFiles = []
self.restartRequired = False
self.detailsClosed(True)
def reloadPluginlist(self):
plugins.readPluginList(resolveFilename(SCOPE_PLUGINS))
class PluginManagerInfo(Screen):
skin = """
<screen name="PluginManagerInfo" position="center,center" size="560,450" >
<ePixmap pixmap="buttons/red.png" position="0,0" size="140,40" alphatest="on" />
<ePixmap pixmap="buttons/green.png" position="140,0" size="140,40" alphatest="on" />
<widget source="key_red" render="Label" position="0,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
<widget source="key_green" render="Label" position="140,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />
<widget source="list" render="Listbox" position="5,50" size="550,350" scrollbarMode="showOnDemand" selectionDisabled="1">
<convert type="TemplatedMultiContent">
{"template": [
MultiContentEntryText(pos = (50, 0), size = (150, 26), font=0, flags = RT_HALIGN_LEFT, text = 0), # index 0 is the name
MultiContentEntryText(pos = (50, 27), size = (540, 23), font=1, flags = RT_HALIGN_LEFT, text = 1), # index 1 is the state
MultiContentEntryPixmapAlphaTest(pos = (0, 1), size = (48, 48), png = 2), # index 2 is the status pixmap
MultiContentEntryPixmapAlphaTest(pos = (0, 48), size = (550, 2), png = 3), # index 3 is the div pixmap
],
"fonts": [gFont("Regular", 24),gFont("Regular", 22)],
"itemHeight": 50
}
</convert>
</widget>
<ePixmap pixmap="div-h.png" position="0,404" zPosition="10" size="560,2" transparent="1" alphatest="on" />
<widget source="status" render="Label" position="5,408" zPosition="10" size="550,44" halign="center" valign="center" font="Regular;22" transparent="1" shadowColor="black" shadowOffset="-1,-1" />
</screen>"""
def __init__(self, session, plugin_path, cmdlist = None):
Screen.__init__(self, session)
Screen.setTitle(self, _("Plugin manager activity information"))
self.session = session
self.skin_path = plugin_path
self.cmdlist = cmdlist
self["shortcuts"] = ActionMap(["ShortcutActions", "WizardActions"],
{
"ok": self.process_all,
"back": self.exit,
"red": self.exit,
"green": self.process_extensions,
}, -1)
self.list = []
self["list"] = List(self.list)
self["key_red"] = StaticText(_("Cancel"))
self["key_green"] = StaticText(_("Only extensions."))
self["status"] = StaticText(_("Following tasks will be done after you press OK!"))
self.onShown.append(self.setWindowTitle)
self.onLayoutFinish.append(self.rebuildList)
def setWindowTitle(self):
self.setTitle(_("Plugin manager activity information"))
def rebuildList(self):
self.list = []
if self.cmdlist is not None:
for entry in self.cmdlist:
action = ""
info = ""
cmd = entry[0]
if cmd == 0:
action = 'install'
elif cmd == 2:
action = 'remove'
else:
action = 'upgrade'
args = entry[1]
if cmd == 0:
info = args['package']
elif cmd == 2:
info = args['package']
else:
info = _("STB_BOX software because updates are available.")
self.list.append(self.buildEntryComponent(action,info))
self['list'].setList(self.list)
self['list'].updateList(self.list)
def buildEntryComponent(self, action,info):
divpng = LoadPixmap(cached=True, path=resolveFilename(SCOPE_ACTIVE_SKIN, "div-h.png"))
upgradepng = LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_PLUGIN, "SystemPlugins/SoftwareManager/upgrade.png"))
installpng = LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_PLUGIN, "SystemPlugins/SoftwareManager/install.png"))
removepng = LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_PLUGIN, "SystemPlugins/SoftwareManager/remove.png"))
if action == 'install':
return(( _('Installing'), info, installpng, divpng))
elif action == 'remove':
return(( _('Removing'), info, removepng, divpng))
else:
return(( _('Upgrading'), info, upgradepng, divpng))
def exit(self):
self.close()
def process_all(self):
self.close((True,None))
def process_extensions(self):
self.list = []
if self.cmdlist is not None:
for entry in self.cmdlist:
cmd = entry[0]
if entry[0] in (0,2):
self.list.append((entry))
self.close((False,self.list))
class PluginManagerHelp(Screen):
skin = """
<screen name="PluginManagerHelp" position="center,center" size="560,450" >
<ePixmap pixmap="buttons/red.png" position="0,0" size="140,40" alphatest="on" />
<widget source="key_red" render="Label" position="0,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
<widget source="list" render="Listbox" position="5,50" size="550,350" scrollbarMode="showOnDemand" selectionDisabled="1">
<convert type="TemplatedMultiContent">
{"template": [
MultiContentEntryText(pos = (50, 0), size = (540, 26), font=0, flags = RT_HALIGN_LEFT, text = 0), # index 0 is the name
MultiContentEntryText(pos = (50, 27), size = (540, 23), font=1, flags = RT_HALIGN_LEFT, text = 1), # index 1 is the state
MultiContentEntryPixmapAlphaTest(pos = (0, 1), size = (48, 48), png = 2), # index 2 is the status pixmap
MultiContentEntryPixmapAlphaTest(pos = (0, 48), size = (550, 2), png = 3), # index 3 is the div pixmap
],
"fonts": [gFont("Regular", 24),gFont("Regular", 22)],
"itemHeight": 50
}
</convert>
</widget>
<ePixmap pixmap="div-h.png" position="0,404" zPosition="10" size="560,2" transparent="1" alphatest="on" />
<widget source="status" render="Label" position="5,408" zPosition="10" size="550,44" halign="center" valign="center" font="Regular;22" transparent="1" shadowColor="black" shadowOffset="-1,-1" />
</screen>"""
def __init__(self, session, plugin_path):
Screen.__init__(self, session)
Screen.setTitle(self, _("Plugin manager help"))
self.session = session
self.skin_path = plugin_path
self["shortcuts"] = ActionMap(["ShortcutActions", "WizardActions"],
{
"back": self.exit,
"red": self.exit,
}, -1)
self.list = []
self["list"] = List(self.list)
self["key_red"] = StaticText(_("Close"))
self["status"] = StaticText(_("A small overview of the available icon states and actions."))
self.onShown.append(self.setWindowTitle)
self.onLayoutFinish.append(self.rebuildList)
def setWindowTitle(self):
self.setTitle(_("Plugin manager help"))
def rebuildList(self):
self.list = []
self.list.append(self.buildEntryComponent('install'))
self.list.append(self.buildEntryComponent('installable'))
self.list.append(self.buildEntryComponent('installed'))
self.list.append(self.buildEntryComponent('remove'))
self['list'].setList(self.list)
self['list'].updateList(self.list)
def buildEntryComponent(self, state):
divpng = LoadPixmap(cached=True, path=resolveFilename(SCOPE_ACTIVE_SKIN, "div-h.png"))
installedpng = LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_PLUGIN, "SystemPlugins/SoftwareManager/installed.png"))
installablepng = LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_PLUGIN, "SystemPlugins/SoftwareManager/installable.png"))
removepng = LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_PLUGIN, "SystemPlugins/SoftwareManager/remove.png"))
installpng = LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_PLUGIN, "SystemPlugins/SoftwareManager/install.png"))
if state == 'installed':
return(( _('This plugin is installed.'), _('You can remove this plugin.'), installedpng, divpng))
elif state == 'installable':
return(( _('This plugin is not installed.'), _('You can install this plugin.'), installablepng, divpng))
elif state == 'install':
return(( _('This plugin will be installed.'), _('You can cancel the installation.'), installpng, divpng))
elif state == 'remove':
return(( _('This plugin will be removed.'), _('You can cancel the removal.'), removepng, divpng))
def exit(self):
self.close()
class PluginDetails(Screen, PackageInfoHandler):
skin = """
<screen name="PluginDetails" position="center,center" size="600,440" title="Plugin details" >
<ePixmap pixmap="buttons/red.png" position="0,0" size="140,40" alphatest="on" />
<ePixmap pixmap="buttons/green.png" position="140,0" size="140,40" alphatest="on" />
<widget source="key_red" render="Label" position="0,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
<widget source="key_green" render="Label" position="140,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />
<widget source="author" render="Label" position="10,50" size="500,25" zPosition="10" font="Regular;21" transparent="1" />
<widget name="statuspic" position="550,40" size="48,48" alphatest="on"/>
<widget name="divpic" position="0,80" size="600,2" alphatest="on"/>
<widget name="detailtext" position="10,90" size="270,330" zPosition="10" font="Regular;21" transparent="1" halign="left" valign="top"/>
<widget name="screenshot" position="290,90" size="300,330" alphatest="on"/>
</screen>"""
def __init__(self, session, plugin_path, packagedata = None):
Screen.__init__(self, session)
Screen.setTitle(self, _("Plugin details"))
self.skin_path = plugin_path
self.language = language.getLanguage()[:2] # getLanguage returns e.g. "fi_FI" for "language_country"
self.attributes = None
PackageInfoHandler.__init__(self, self.statusCallback, blocking = False)
self.directory = resolveFilename(SCOPE_METADIR)
if packagedata:
self.pluginname = packagedata[0]
self.details = packagedata[1]
self.pluginstate = packagedata[4]
self.statuspicinstance = packagedata[5]
self.divpicinstance = packagedata[6]
self.fillPackageDetails(self.details)
self.thumbnail = ""
self["shortcuts"] = ActionMap(["ShortcutActions", "WizardActions"],
{
"back": self.exit,
"red": self.exit,
"green": self.go,
"up": self.pageUp,
"down": self.pageDown,
"left": self.pageUp,
"right": self.pageDown,
}, -1)
self["key_red"] = StaticText(_("Close"))
self["key_green"] = StaticText("")
self["author"] = StaticText()
self["statuspic"] = Pixmap()
self["divpic"] = Pixmap()
self["screenshot"] = Pixmap()
self["detailtext"] = ScrollLabel()
self["statuspic"].hide()
self["screenshot"].hide()
self["divpic"].hide()
self.package = self.packageDetails[0]
if self.package[0].has_key("attributes"):
self.attributes = self.package[0]["attributes"]
self.restartRequired = False
self.cmdList = []
self.oktext = _("\nAfter pressing OK, please wait!")
self.picload = ePicLoad()
self.picload.PictureData.get().append(self.paintScreenshotPixmapCB)
self.onShown.append(self.setWindowTitle)
self.onLayoutFinish.append(self.setInfos)
def setWindowTitle(self):
self.setTitle(_("Details for plugin: ") + self.pluginname )
def exit(self):
self.close(False)
def pageUp(self):
self["detailtext"].pageUp()
def pageDown(self):
self["detailtext"].pageDown()
def statusCallback(self, status, progress):
pass
def setInfos(self):
if self.attributes.has_key("screenshot"):
self.loadThumbnail(self.attributes)
if self.attributes.has_key("name"):
self.pluginname = self.attributes["name"]
else:
self.pluginname = _("unknown")
if self.attributes.has_key("author"):
self.author = self.attributes["author"]
else:
self.author = _("unknown")
if self.attributes.has_key("description"):
self.description = _(self.attributes["description"].replace("\\n", "\n"))
else:
self.description = _("No description available.")
self["author"].setText(_("Author: ") + self.author)
self["detailtext"].setText(_(self.description))
if self.pluginstate in ('installable', 'install'):
if iSoftwareTools.NetworkConnectionAvailable:
self["key_green"].setText(_("Install"))
else:
self["key_green"].setText("")
else:
self["key_green"].setText(_("Remove"))
def loadThumbnail(self, entry):
thumbnailUrl = None
if entry.has_key("screenshot"):
thumbnailUrl = entry["screenshot"]
if self.language == "de":
if thumbnailUrl[-7:] == "_en.jpg":
thumbnailUrl = thumbnailUrl[:-7] + "_de.jpg"
if thumbnailUrl is not None:
self.thumbnail = "/tmp/" + thumbnailUrl.split('/')[-1]
print "[PluginDetails] downloading screenshot " + thumbnailUrl + " to " + self.thumbnail
if iSoftwareTools.NetworkConnectionAvailable:
client.downloadPage(thumbnailUrl,self.thumbnail).addCallback(self.setThumbnail).addErrback(self.fetchFailed)
else:
self.setThumbnail(noScreenshot = True)
else:
self.setThumbnail(noScreenshot = True)
def setThumbnail(self, noScreenshot = False):
if not noScreenshot:
filename = self.thumbnail
else:
filename = resolveFilename(SCOPE_CURRENT_PLUGIN, "SystemPlugins/SoftwareManager/noprev.png")
sc = AVSwitch().getFramebufferScale()
self.picload.setPara((self["screenshot"].instance.size().width(), self["screenshot"].instance.size().height(), sc[0], sc[1], False, 1, "#00000000"))
self.picload.startDecode(filename)
if self.statuspicinstance != None:
self["statuspic"].instance.setPixmap(self.statuspicinstance.__deref__())
self["statuspic"].show()
if self.divpicinstance != None:
self["divpic"].instance.setPixmap(self.divpicinstance.__deref__())
self["divpic"].show()
def paintScreenshotPixmapCB(self, picInfo=None):
ptr = self.picload.getData()
if ptr != None:
self["screenshot"].instance.setPixmap(ptr.__deref__())
self["screenshot"].show()
else:
self.setThumbnail(noScreenshot = True)
def go(self):
if self.attributes.has_key("package"):
self.packagefiles = self.attributes["package"]
if self.attributes.has_key("needsRestart"):
self.restartRequired = True
self.cmdList = []
if self.pluginstate in ('installed', 'remove'):
if self.packagefiles:
for package in self.packagefiles[:]:
self.cmdList.append((IpkgComponent.CMD_REMOVE, { "package": package["name"] }))
if len(self.cmdList):
self.session.openWithCallback(self.runRemove, MessageBox, _("Do you want to remove the package:\n") + self.pluginname + "\n" + self.oktext)
else:
if iSoftwareTools.NetworkConnectionAvailable:
if self.packagefiles:
for package in self.packagefiles[:]:
self.cmdList.append((IpkgComponent.CMD_INSTALL, { "package": package["name"] }))
if len(self.cmdList):
self.session.openWithCallback(self.runUpgrade, MessageBox, _("Do you want to install the package:\n") + self.pluginname + "\n" + self.oktext)
def runUpgrade(self, result):
if result:
self.session.openWithCallback(self.runUpgradeFinished, Ipkg, cmdList = self.cmdList)
def runUpgradeFinished(self):
self.reloadPluginlist()
if plugins.restartRequired or self.restartRequired:
self.session.openWithCallback(self.UpgradeReboot, MessageBox, _("Installation finished.") +" "+_("Do you want to reboot your receiver?"), MessageBox.TYPE_YESNO)
else:
self.close(True)
def UpgradeReboot(self, result):
if result:
self.session.open(TryQuitMainloop,retvalue=3)
self.close(True)
def runRemove(self, result):
if result:
self.session.openWithCallback(self.runRemoveFinished, Ipkg, cmdList = self.cmdList)
def runRemoveFinished(self):
self.close(True)
def reloadPluginlist(self):
plugins.readPluginList(resolveFilename(SCOPE_PLUGINS))
def fetchFailed(self,string):
self.setThumbnail(noScreenshot = True)
print "[PluginDetails] fetch failed " + string.getErrorMessage()
class IPKGMenu(Screen):
skin = """
<screen name="IPKGMenu" position="center,center" size="560,400" title="Select upgrade source to edit." >
<ePixmap pixmap="buttons/red.png" position="0,0" size="140,40" alphatest="on" />
<ePixmap pixmap="buttons/green.png" position="140,0" size="140,40" alphatest="on" />
<widget source="key_red" render="Label" position="0,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
<widget source="key_green" render="Label" position="140,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />
<widget name="filelist" position="5,50" size="550,340" scrollbarMode="showOnDemand" />
</screen>"""
def __init__(self, session, plugin_path):
Screen.__init__(self, session)
Screen.setTitle(self, _("Select upgrade source to edit."))
self.skin_path = plugin_path
self["key_red"] = StaticText(_("Close"))
self["key_green"] = StaticText(_("Edit"))
self.sel = []
self.val = []
self.entry = False
self.exe = False
self.path = ""
self["actions"] = NumberActionMap(["SetupActions"],
{
"ok": self.KeyOk,
"cancel": self.keyCancel
}, -1)
self["shortcuts"] = ActionMap(["ShortcutActions"],
{
"red": self.keyCancel,
"green": self.KeyOk,
})
self["filelist"] = MenuList([])
self.fill_list()
self.onLayoutFinish.append(self.layoutFinished)
def layoutFinished(self):
self.setWindowTitle()
def setWindowTitle(self):
self.setTitle(_("Select upgrade source to edit."))
def fill_list(self):
flist = []
self.path = '/etc/opkg/'
if (os_path.exists(self.path) == False):
self.entry = False
return
for file in listdir(self.path):
if file.endswith(".conf"):
if file not in ('arch.conf', 'opkg.conf'):
flist.append((file))
self.entry = True
self["filelist"].l.setList(flist)
def KeyOk(self):
if (self.exe == False) and (self.entry == True):
self.sel = self["filelist"].getCurrent()
self.val = self.path + self.sel
self.session.open(IPKGSource, self.val)
def keyCancel(self):
self.close()
def Exit(self):
self.close()
class IPKGSource(Screen):
skin = """
<screen name="IPKGSource" position="center,center" size="560,80" title="Edit upgrade source url." >
<ePixmap pixmap="buttons/red.png" position="0,0" size="140,40" alphatest="on" />
<ePixmap pixmap="buttons/green.png" position="140,0" size="140,40" alphatest="on" />
<widget source="key_red" render="Label" position="0,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
<widget source="key_green" render="Label" position="140,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />
<widget name="text" position="5,50" size="550,25" font="Regular;20" backgroundColor="background" foregroundColor="#cccccc" />
</screen>"""
def __init__(self, session, configfile = None):
Screen.__init__(self, session)
self.session = session
self.configfile = configfile
text = ""
if self.configfile:
try:
fp = file(configfile, 'r')
sources = fp.readlines()
if sources:
text = sources[0]
fp.close()
except IOError:
pass
desk = getDesktop(0)
x= int(desk.size().width())
y= int(desk.size().height())
self["key_red"] = StaticText(_("Cancel"))
self["key_green"] = StaticText(_("Save"))
if (y>=720):
self["text"] = Input(text, maxSize=False, type=Input.TEXT)
else:
self["text"] = Input(text, maxSize=False, visible_width = 55, type=Input.TEXT)
self["actions"] = NumberActionMap(["WizardActions", "InputActions", "TextEntryActions", "KeyboardInputActions","ShortcutActions"],
{
"ok": self.go,
"back": self.close,
"red": self.close,
"green": self.go,
"left": self.keyLeft,
"right": self.keyRight,
"home": self.keyHome,
"end": self.keyEnd,
"deleteForward": self.keyDeleteForward,
"deleteBackward": self.keyDeleteBackward,
"1": self.keyNumberGlobal,
"2": self.keyNumberGlobal,
"3": self.keyNumberGlobal,
"4": self.keyNumberGlobal,
"5": self.keyNumberGlobal,
"6": self.keyNumberGlobal,
"7": self.keyNumberGlobal,
"8": self.keyNumberGlobal,
"9": self.keyNumberGlobal,
"0": self.keyNumberGlobal
}, -1)
self.onLayoutFinish.append(self.layoutFinished)
def layoutFinished(self):
self.setWindowTitle()
self["text"].right()
def setWindowTitle(self):
self.setTitle(_("Edit upgrade source url."))
def go(self):
text = self["text"].getText()
if text:
fp = file(self.configfile, 'w')
fp.write(text)
fp.write("\n")
fp.close()
self.close()
def keyLeft(self):
self["text"].left()
def keyRight(self):
self["text"].right()
def keyHome(self):
self["text"].home()
def keyEnd(self):
self["text"].end()
def keyDeleteForward(self):
self["text"].delete()
def keyDeleteBackward(self):
self["text"].deleteBackward()
def keyNumberGlobal(self, number):
self["text"].number(number)
class PacketManager(Screen, NumericalTextInput):
skin = """
<screen name="PacketManager" position="center,center" size="530,420" title="Packet manager" >
<ePixmap pixmap="buttons/red.png" position="0,0" size="140,40" alphatest="on" />
<ePixmap pixmap="buttons/green.png" position="140,0" size="140,40" alphatest="on" />
<widget source="key_red" render="Label" position="0,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
<widget source="key_green" render="Label" position="140,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />
<widget source="list" render="Listbox" position="5,50" size="520,365" scrollbarMode="showOnDemand">
<convert type="TemplatedMultiContent">
{"template": [
MultiContentEntryText(pos = (5, 1), size = (440, 28), font=0, flags = RT_HALIGN_LEFT, text = 0), # index 0 is the name
MultiContentEntryText(pos = (5, 26), size = (440, 20), font=1, flags = RT_HALIGN_LEFT, text = 2), # index 2 is the description
MultiContentEntryPixmapAlphaTest(pos = (445, 2), size = (48, 48), png = 4), # index 4 is the status pixmap
MultiContentEntryPixmapAlphaTest(pos = (5, 50), size = (510, 2), png = 5), # index 4 is the div pixmap
],
"fonts": [gFont("Regular", 22),gFont("Regular", 14)],
"itemHeight": 52
}
</convert>
</widget>
</screen>"""
def __init__(self, session, plugin_path, args = None):
Screen.__init__(self, session)
NumericalTextInput.__init__(self)
self.session = session
self.skin_path = plugin_path
if config.usage.show_channel_jump_in_servicelist.getValue() == "alpha":
self.setUseableChars(u'abcdefghijklmnopqrstuvwxyz1234567890')
else:
self.setUseableChars(u'1234567890abcdefghijklmnopqrstuvwxyz')
self["shortcuts"] = NumberActionMap(["ShortcutActions", "WizardActions", "NumberActions", "InputActions", "InputAsciiActions", "KeyboardInputActions" ],
{
"ok": self.go,
"back": self.exit,
"red": self.exit,
"green": self.reload,
"gotAsciiCode": self.keyGotAscii,
"1": self.keyNumberGlobal,
"2": self.keyNumberGlobal,
"3": self.keyNumberGlobal,
"4": self.keyNumberGlobal,
"5": self.keyNumberGlobal,
"6": self.keyNumberGlobal,
"7": self.keyNumberGlobal,
"8": self.keyNumberGlobal,
"9": self.keyNumberGlobal,
"0": self.keyNumberGlobal
}, -1)
self.list = []
self.statuslist = []
self["list"] = List(self.list)
self["key_red"] = StaticText(_("Close"))
self["key_green"] = StaticText(_("Reload"))
self.list_updating = True
self.packetlist = []
self.installed_packetlist = {}
self.upgradeable_packages = {}
self.Console = Console()
self.cmdList = []
self.cachelist = []
self.cache_ttl = 86400 #600 is default, 0 disables, Seconds cache is considered valid (24h should be ok for caching ipkgs)
self.cache_file = eEnv.resolve('${libdir}/enigma2/python/Plugins/SystemPlugins/SoftwareManager/packetmanager.cache') #Path to cache directory
self.oktext = _("\nAfter pressing OK, please wait!")
self.unwanted_extensions = ('-dbg', '-dev', '-doc', '-staticdev', 'busybox')
self.ipkg = IpkgComponent()
self.ipkg.addCallback(self.ipkgCallback)
self.onShown.append(self.setWindowTitle)
self.onLayoutFinish.append(self.rebuildList)
rcinput = eRCInput.getInstance()
if config.misc.remotecontrol_text_support.getValue():
rcinput.setKeyboardMode(rcinput.kmNone)
else:
rcinput.setKeyboardMode(rcinput.kmAscii)
def keyNumberGlobal(self, val):
key = self.getKey(val)
if key is not None:
keyvalue = key.encode("utf-8")
if len(keyvalue) == 1:
self.setNextIdx(keyvalue[0])
def keyGotAscii(self):
keyvalue = unichr(getPrevAsciiCode()).encode("utf-8")
if len(keyvalue) == 1:
self.setNextIdx(keyvalue[0])
def setNextIdx(self,char):
if char in ("0", "1", "a"):
self["list"].setIndex(0)
else:
idx = self.getNextIdx(char)
if idx and idx <= self["list"].count:
self["list"].setIndex(idx)
def getNextIdx(self,char):
for idx, i in enumerate(self["list"].list):
if i[0] and (i[0][0] == char):
return idx
def exit(self):
self.ipkg.stop()
if self.Console is not None:
if len(self.Console.appContainers):
for name in self.Console.appContainers.keys():
self.Console.kill(name)
rcinput = eRCInput.getInstance()
rcinput.setKeyboardMode(rcinput.kmNone)
self.close()
def reload(self):
if (os_path.exists(self.cache_file) == True):
remove(self.cache_file)
self.list_updating = True
self.rebuildList()
def setWindowTitle(self):
self.setTitle(_("Packet manager"))
def setStatus(self,status = None):
if status:
self.statuslist = []
divpng = LoadPixmap(cached=True, path=resolveFilename(SCOPE_ACTIVE_SKIN, "div-h.png"))
if status == 'update':
statuspng = LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_PLUGIN, "SystemPlugins/SoftwareManager/upgrade.png"))
self.statuslist.append(( _("Package list update"), '', _("Trying to download a new packetlist. Please wait..." ),'',statuspng, divpng ))
self['list'].setList(self.statuslist)
elif status == 'error':
statuspng = LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_PLUGIN, "SystemPlugins/SoftwareManager/remove.png"))
self.statuslist.append(( _("Error"), '', _("An error occurred while downloading the packetlist. Please try again." ),'',statuspng, divpng ))
self['list'].setList(self.statuslist)
def rebuildList(self):
self.setStatus('update')
self.inv_cache = 0
self.vc = valid_cache(self.cache_file, self.cache_ttl)
if self.cache_ttl > 0 and self.vc != 0:
try:
self.buildPacketList()
except:
self.inv_cache = 1
if self.cache_ttl == 0 or self.inv_cache == 1 or self.vc == 0:
self.run = 0
self.ipkg.startCmd(IpkgComponent.CMD_UPDATE)
def go(self, returnValue = None):
cur = self["list"].getCurrent()
if cur:
status = cur[3]
package = cur[0]
self.cmdList = []
if status == 'installed':
self.cmdList.append((IpkgComponent.CMD_REMOVE, { "package": package }))
if len(self.cmdList):
self.session.openWithCallback(self.runRemove, MessageBox, _("Do you want to remove the package:\n") + package + "\n" + self.oktext)
elif status == 'upgradeable':
self.cmdList.append((IpkgComponent.CMD_INSTALL, { "package": package }))
if len(self.cmdList):
self.session.openWithCallback(self.runUpgrade, MessageBox, _("Do you want to upgrade the package:\n") + package + "\n" + self.oktext)
elif status == "installable":
self.cmdList.append((IpkgComponent.CMD_INSTALL, { "package": package }))
if len(self.cmdList):
self.session.openWithCallback(self.runUpgrade, MessageBox, _("Do you want to install the package:\n") + package + "\n" + self.oktext)
def runRemove(self, result):
if result:
self.session.openWithCallback(self.runRemoveFinished, Ipkg, cmdList = self.cmdList)
def runRemoveFinished(self):
self.session.openWithCallback(self.RemoveReboot, MessageBox, _("Remove finished.") +" "+_("Do you want to reboot your receiver?"), MessageBox.TYPE_YESNO)
def RemoveReboot(self, result):
if result is None:
return
if result is False:
cur = self["list"].getCurrent()
if cur:
item = self['list'].getIndex()
self.list[item] = self.buildEntryComponent(cur[0], cur[1], cur[2], 'installable')
self.cachelist[item] = [cur[0], cur[1], cur[2], 'installable']
self['list'].setList(self.list)
write_cache(self.cache_file, self.cachelist)
self.reloadPluginlist()
if result:
self.session.open(TryQuitMainloop,retvalue=3)
def runUpgrade(self, result):
if result:
self.session.openWithCallback(self.runUpgradeFinished, Ipkg, cmdList = self.cmdList)
def runUpgradeFinished(self):
self.session.openWithCallback(self.UpgradeReboot, MessageBox, _("Upgrade finished.") +" "+_("Do you want to reboot your receiver?"), MessageBox.TYPE_YESNO)
def UpgradeReboot(self, result):
if result is None:
return
if result is False:
cur = self["list"].getCurrent()
if cur:
item = self['list'].getIndex()
self.list[item] = self.buildEntryComponent(cur[0], cur[1], cur[2], 'installed')
self.cachelist[item] = [cur[0], cur[1], cur[2], 'installed']
self['list'].setList(self.list)
write_cache(self.cache_file, self.cachelist)
self.reloadPluginlist()
if result:
self.session.open(TryQuitMainloop,retvalue=3)
def ipkgCallback(self, event, param):
if event == IpkgComponent.EVENT_ERROR:
self.list_updating = False
self.setStatus('error')
elif event == IpkgComponent.EVENT_DONE:
if self.list_updating:
self.list_updating = False
if not self.Console:
self.Console = Console()
cmd = self.ipkg.ipkg + " list"
self.Console.ePopen(cmd, self.IpkgList_Finished)
pass
def IpkgList_Finished(self, result, retval, extra_args = None):
result = result.replace('\n ',' - ')
if result:
self.packetlist = []
last_name = ""
for x in result.splitlines():
tokens = x.split(' - ')
name = tokens[0].strip()
if not any((name.endswith(x) or name.find('locale') != -1) for x in self.unwanted_extensions):
l = len(tokens)
version = l > 1 and tokens[1].strip() or ""
descr = l > 3 and tokens[3].strip() or l > 2 and tokens[2].strip() or ""
if name == last_name:
continue
last_name = name
self.packetlist.append([name, version, descr])
if not self.Console:
self.Console = Console()
cmd = self.ipkg.ipkg + " list_installed"
self.Console.ePopen(cmd, self.IpkgListInstalled_Finished)
def IpkgListInstalled_Finished(self, result, retval, extra_args = None):
if result:
self.installed_packetlist = {}
for x in result.splitlines():
tokens = x.split(' - ')
name = tokens[0].strip()
if not any(name.endswith(x) for x in self.unwanted_extensions):
l = len(tokens)
version = l > 1 and tokens[1].strip() or ""
self.installed_packetlist[name] = version
if not self.Console:
self.Console = Console()
cmd = "opkg list-upgradable"
self.Console.ePopen(cmd, self.OpkgListUpgradeable_Finished)
def OpkgListUpgradeable_Finished(self, result, retval, extra_args = None):
if result:
self.upgradeable_packages = {}
for x in result.splitlines():
tokens = x.split(' - ')
name = tokens[0].strip()
if not any(name.endswith(x) for x in self.unwanted_extensions):
l = len(tokens)
version = l > 2 and tokens[2].strip() or ""
self.upgradeable_packages[name] = version
self.buildPacketList()
def buildEntryComponent(self, name, version, description, state):
divpng = LoadPixmap(cached=True, path=resolveFilename(SCOPE_ACTIVE_SKIN, "div-h.png"))
if not description:
description = "No description available."
if state == 'installed':
installedpng = LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_PLUGIN, "SystemPlugins/SoftwareManager/installed.png"))
return((name, version, _(description), state, installedpng, divpng))
elif state == 'upgradeable':
upgradeablepng = LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_PLUGIN, "SystemPlugins/SoftwareManager/upgradeable.png"))
return((name, version, _(description), state, upgradeablepng, divpng))
else:
installablepng = LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_PLUGIN, "SystemPlugins/SoftwareManager/installable.png"))
return((name, version, _(description), state, installablepng, divpng))
def buildPacketList(self):
self.list = []
self.cachelist = []
if self.cache_ttl > 0 and self.vc != 0:
print 'Loading packagelist cache from ',self.cache_file
try:
self.cachelist = load_cache(self.cache_file)
if len(self.cachelist) > 0:
for x in self.cachelist:
self.list.append(self.buildEntryComponent(x[0], x[1], x[2], x[3]))
self['list'].setList(self.list)
except:
self.inv_cache = 1
if self.cache_ttl == 0 or self.inv_cache == 1 or self.vc == 0:
print 'rebuilding fresh package list'
for x in self.packetlist:
status = ""
if self.installed_packetlist.has_key(x[0]):
if self.upgradeable_packages.has_key(x[0]):
status = "upgradeable"
else:
status = "installed"
else:
status = "installable"
self.list.append(self.buildEntryComponent(x[0], x[1], x[2], status))
self.cachelist.append([x[0], x[1], x[2], status])
write_cache(self.cache_file, self.cachelist)
self['list'].setList(self.list)
def reloadPluginlist(self):
plugins.readPluginList(resolveFilename(SCOPE_PLUGINS))
class IpkgInstaller(Screen):
skin = """
<screen name="IpkgInstaller" position="center,center" size="550,450" title="Install extensions" >
<ePixmap pixmap="buttons/red.png" position="0,0" size="140,40" alphatest="on" />
<ePixmap pixmap="buttons/green.png" position="140,0" size="140,40" alphatest="on" />
<ePixmap pixmap="buttons/yellow.png" position="280,0" size="140,40" alphatest="on" />
<ePixmap pixmap="buttons/blue.png" position="420,0" size="140,40" alphatest="on" />
<widget source="key_red" render="Label" position="0,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
<widget source="key_green" render="Label" position="140,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />
<widget source="key_yellow" render="Label" position="280,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#a08500" transparent="1" />
<widget source="key_blue" render="Label" position="420,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#18188b" transparent="1" />
<widget name="list" position="5,50" size="540,360" />
<ePixmap pixmap="div-h.png" position="0,410" zPosition="10" size="560,2" transparent="1" alphatest="on" />
<widget source="introduction" render="Label" position="5,420" zPosition="10" size="550,30" halign="center" valign="center" font="Regular;22" transparent="1" shadowColor="black" shadowOffset="-1,-1" />
</screen>"""
def __init__(self, session, list):
Screen.__init__(self, session)
self.list = SelectionList()
self["list"] = self.list
for listindex in range(len(list)):
self.list.addSelection(list[listindex], list[listindex], listindex, False)
self["key_red"] = StaticText(_("Close"))
self["key_green"] = StaticText(_("Install"))
self["key_yellow"] = StaticText()
self["key_blue"] = StaticText(_("Invert"))
self["introduction"] = StaticText(_("Press OK to toggle the selection."))
self["actions"] = ActionMap(["OkCancelActions", "ColorActions"],
{
"ok": self.list.toggleSelection,
"cancel": self.close,
"red": self.close,
"green": self.install,
"blue": self.list.toggleAllSelection
}, -1)
def install(self):
list = self.list.getSelectionsList()
cmdList = []
for item in list:
cmdList.append((IpkgComponent.CMD_INSTALL, { "package": item[1] }))
self.session.open(Ipkg, cmdList = cmdList)
def filescan_open(list, session, **kwargs):
filelist = [x.path for x in list]
session.open(IpkgInstaller, filelist) # list
def filescan(**kwargs):
from Components.Scanner import Scanner, ScanPath
return \
Scanner(mimetypes = ["application/x-debian-package"],
paths_to_scan =
[
ScanPath(path = "ipk", with_subdirs = True),
ScanPath(path = "", with_subdirs = False),
],
name = "Ipkg",
description = _("Install extensions."),
openfnc = filescan_open, )
def UpgradeMain(session, **kwargs):
session.open(UpdatePluginMenu)
def startSetup(menuid):
if menuid == "setup" and config.plugins.softwaremanager.onSetupMenu.getValue():
return [(_("Software management"), UpgradeMain, "software_manager", 50)]
return [ ]
def Plugins(path, **kwargs):
global plugin_path
plugin_path = path
list = [
PluginDescriptor(name=_("Software management"), description=_("Manage your STB_BOX's software"), where = PluginDescriptor.WHERE_MENU, needsRestart = False, fnc=startSetup),
PluginDescriptor(name=_("Ipkg"), where = PluginDescriptor.WHERE_FILESCAN, needsRestart = False, fnc = filescan)
]
if not config.plugins.softwaremanager.onSetupMenu.getValue() and not config.plugins.softwaremanager.onBlueButton.getValue():
list.append(PluginDescriptor(name=_("Software management"), description=_("Manage your STB_BOX's software"), where = PluginDescriptor.WHERE_PLUGINMENU, needsRestart = False, fnc=UpgradeMain))
if config.plugins.softwaremanager.onBlueButton.getValue():
list.append(PluginDescriptor(name=_("Software management"), description=_("Manage your STB_BOX's software"), where = PluginDescriptor.WHERE_EXTENSIONSMENU, needsRestart = False, fnc=UpgradeMain))
return list
| popazerty/dvbapp2-gui | lib/python/Plugins/SystemPlugins/SoftwareManager/plugin.py | Python | gpl-2.0 | 81,566 |
# -*- coding: utf-8 -*-
"""
***************************************************************************
utils.py
---------------------
Date : November 2009
Copyright : (C) 2009 by Martin Dobias
Email : wonder dot sk at gmail dot com
***************************************************************************
* *
* 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. *
* *
***************************************************************************
"""
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import str
__author__ = 'Martin Dobias'
__date__ = 'November 2009'
__copyright__ = '(C) 2009, Martin Dobias'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'
"""
QGIS utilities module
"""
from qgis.PyQt.QtCore import QCoreApplication, QLocale
from qgis.PyQt.QtWidgets import QPushButton, QApplication
from qgis.core import Qgis, QgsExpression, QgsMessageLog, qgsfunction, QgsMessageOutput, QgsWkbTypes
from qgis.gui import QgsMessageBar
import sys
import traceback
import glob
import os.path
try:
import configparser
except ImportError:
import ConfigParser as configparser
import warnings
import codecs
import time
import functools
if sys.version_info[0] >= 3:
import builtins
builtins.__dict__['unicode'] = str
builtins.__dict__['basestring'] = str
builtins.__dict__['long'] = int
builtins.__dict__['Set'] = set
# ######################
# ERROR HANDLING
warnings.simplefilter('default')
warnings.filterwarnings("ignore", "the sets module is deprecated")
def showWarning(message, category, filename, lineno, file=None, line=None):
stk = ""
for s in traceback.format_stack()[:-2]:
if hasattr(s, 'decode'):
stk += s.decode(sys.getfilesystemencoding())
else:
stk += s
if hasattr(filename, 'decode'):
decoded_filename = filename.decode(sys.getfilesystemencoding())
else:
decoded_filename = filename
QgsMessageLog.logMessage(
u"warning:{}\ntraceback:{}".format(warnings.formatwarning(message, category, decoded_filename, lineno), stk),
QCoreApplication.translate("Python", "Python warning")
)
warnings.showwarning = showWarning
def showException(type, value, tb, msg, messagebar=False):
if msg is None:
msg = QCoreApplication.translate('Python', 'An error has occurred while executing Python code:')
logmessage = ''
for s in traceback.format_exception(type, value, tb):
logmessage += s.decode('utf-8', 'replace') if hasattr(s, 'decode') else s
title = QCoreApplication.translate('Python', 'Python error')
QgsMessageLog.logMessage(logmessage, title)
try:
blockingdialog = QApplication.instance().activeModalWidget()
window = QApplication.instance().activeWindow()
except:
blockingdialog = QApplication.activeModalWidget()
window = QApplication.activeWindow()
# Still show the normal blocking dialog in this case for now.
if blockingdialog or not window or not messagebar or not iface:
open_stack_dialog(type, value, tb, msg)
return
bar = iface.messageBar()
# If it's not the main window see if we can find a message bar to report the error in
if not window.objectName() == "QgisApp":
widgets = window.findChildren(QgsMessageBar)
if widgets:
# Grab the first message bar for now
bar = widgets[0]
item = bar.currentItem()
if item and item.property("Error") == msg:
# Return of we already have a message with the same error message
return
widget = bar.createMessage(title, msg + " " + QCoreApplication.translate("Python", "See message log (Python Error) for more details."))
widget.setProperty("Error", msg)
stackbutton = QPushButton(QCoreApplication.translate("Python", "Stack trace"), pressed=functools.partial(open_stack_dialog, type, value, tb, msg))
button = QPushButton(QCoreApplication.translate("Python", "View message log"), pressed=show_message_log)
widget.layout().addWidget(stackbutton)
widget.layout().addWidget(button)
bar.pushWidget(widget, QgsMessageBar.WARNING)
def show_message_log(pop_error=True):
if pop_error:
iface.messageBar().popWidget()
iface.openMessageLog()
def open_stack_dialog(type, value, tb, msg, pop_error=True):
if pop_error:
iface.messageBar().popWidget()
if msg is None:
msg = QCoreApplication.translate('Python', 'An error has occurred while executing Python code:')
# TODO Move this to a template HTML file
txt = u'''<font color="red"><b>{msg}</b></font>
<br>
<h3>{main_error}</h3>
<pre>
{error}
</pre>
<br>
<b>{version_label}</b> {num}
<br>
<b>{qgis_label}</b> {qversion} {qgisrelease}, {devversion}
<br>
<h4>{pypath_label}</h4>
<ul>
{pypath}
</ul>'''
error = ''
lst = traceback.format_exception(type, value, tb)
for s in lst:
error += s.decode('utf-8', 'replace') if hasattr(s, 'decode') else s
error = error.replace('\n', '<br>')
main_error = lst[-1].decode('utf-8', 'replace') if hasattr(lst[-1], 'decode') else lst[-1]
version_label = QCoreApplication.translate('Python', 'Python version:')
qgis_label = QCoreApplication.translate('Python', 'QGIS version:')
pypath_label = QCoreApplication.translate('Python', 'Python Path:')
txt = txt.format(msg=msg,
main_error=main_error,
error=error,
version_label=version_label,
num=sys.version,
qgis_label=qgis_label,
qversion=Qgis.QGIS_VERSION,
qgisrelease=Qgis.QGIS_RELEASE_NAME,
devversion=Qgis.QGIS_DEV_VERSION,
pypath_label=pypath_label,
pypath=u"".join(u"<li>{}</li>".format(path) for path in sys.path))
txt = txt.replace(' ', ' ') # preserve whitespaces for nicer output
dlg = QgsMessageOutput.createMessageOutput()
dlg.setTitle(msg)
dlg.setMessage(txt, QgsMessageOutput.MessageHtml)
dlg.showMessage()
def qgis_excepthook(type, value, tb):
showException(type, value, tb, None, messagebar=True)
def installErrorHook():
sys.excepthook = qgis_excepthook
def uninstallErrorHook():
sys.excepthook = sys.__excepthook__
# install error hook() on module load
installErrorHook()
# initialize 'iface' object
iface = None
def initInterface(pointer):
from qgis.gui import QgisInterface
from sip import wrapinstance
global iface
iface = wrapinstance(pointer, QgisInterface)
#######################
# PLUGINS
# list of plugin paths. it gets filled in by the QGIS python library
plugin_paths = []
# dictionary of plugins
plugins = {}
plugin_times = {}
# list of active (started) plugins
active_plugins = []
# list of plugins in plugin directory and home plugin directory
available_plugins = []
# dictionary of plugins providing metadata in a text file (metadata.txt)
# key = plugin package name, value = config parser instance
plugins_metadata_parser = {}
def findPlugins(path):
""" for internal use: return list of plugins in given path """
for plugin in glob.glob(path + "/*"):
if not os.path.isdir(plugin):
continue
if not os.path.exists(os.path.join(plugin, '__init__.py')):
continue
metadataFile = os.path.join(plugin, 'metadata.txt')
if not os.path.exists(metadataFile):
continue
cp = configparser.ConfigParser()
try:
f = codecs.open(metadataFile, "r", "utf8")
cp.read_file(f)
f.close()
except:
cp = None
pluginName = os.path.basename(plugin)
yield (pluginName, cp)
def updateAvailablePlugins():
""" Go through the plugin_paths list and find out what plugins are available. """
# merge the lists
plugins = []
metadata_parser = {}
for pluginpath in plugin_paths:
for pluginName, parser in findPlugins(pluginpath):
if parser is None:
continue
if pluginName not in plugins:
plugins.append(pluginName)
metadata_parser[pluginName] = parser
global available_plugins
available_plugins = plugins
global plugins_metadata_parser
plugins_metadata_parser = metadata_parser
def pluginMetadata(packageName, fct):
""" fetch metadata from a plugin - use values from metadata.txt """
try:
return plugins_metadata_parser[packageName].get('general', fct)
except Exception:
return "__error__"
def loadPlugin(packageName):
""" load plugin's package """
try:
__import__(packageName)
return True
except:
pass # continue...
# snake in the grass, we know it's there
sys.path_importer_cache.clear()
# retry
try:
__import__(packageName)
return True
except:
msgTemplate = QCoreApplication.translate("Python", "Couldn't load plugin '%s'")
msg = msgTemplate % packageName
showException(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2], msg, messagebar=True)
return False
def startPlugin(packageName):
""" initialize the plugin """
global plugins, active_plugins, iface, plugin_times
if packageName in active_plugins:
return False
if packageName not in sys.modules:
return False
package = sys.modules[packageName]
errMsg = QCoreApplication.translate("Python", "Couldn't load plugin %s") % packageName
start = time.clock()
# create an instance of the plugin
try:
plugins[packageName] = package.classFactory(iface)
except:
_unloadPluginModules(packageName)
msg = QCoreApplication.translate("Python", "%s due to an error when calling its classFactory() method") % errMsg
showException(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2], msg, messagebar=True)
return False
# initGui
try:
plugins[packageName].initGui()
except:
del plugins[packageName]
_unloadPluginModules(packageName)
msg = QCoreApplication.translate("Python", "%s due to an error when calling its initGui() method") % errMsg
showException(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2], msg, messagebar=True)
return False
# add to active plugins
active_plugins.append(packageName)
end = time.clock()
plugin_times[packageName] = "{0:02f}s".format(end - start)
return True
def canUninstallPlugin(packageName):
""" confirm that the plugin can be uninstalled """
global plugins, active_plugins
if packageName not in plugins:
return False
if packageName not in active_plugins:
return False
try:
metadata = plugins[packageName]
if "canBeUninstalled" not in dir(metadata):
return True
return bool(metadata.canBeUninstalled())
except:
msg = "Error calling " + packageName + ".canBeUninstalled"
showException(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2], msg, messagebar=True)
return True
def unloadPlugin(packageName):
""" unload and delete plugin! """
global plugins, active_plugins
if packageName not in plugins:
return False
if packageName not in active_plugins:
return False
try:
plugins[packageName].unload()
del plugins[packageName]
active_plugins.remove(packageName)
_unloadPluginModules(packageName)
return True
except Exception as e:
msg = QCoreApplication.translate("Python", "Error while unloading plugin %s") % packageName
showException(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2], msg, messagebar=True)
return False
def _unloadPluginModules(packageName):
""" unload plugin package with all its modules (files) """
global _plugin_modules
mods = _plugin_modules[packageName]
for mod in mods:
# if it looks like a Qt resource file, try to do a cleanup
# otherwise we might experience a segfault next time the plugin is loaded
# because Qt will try to access invalid plugin resource data
try:
if hasattr(sys.modules[mod], 'qCleanupResources'):
sys.modules[mod].qCleanupResources()
except:
pass
# try to remove the module from python
try:
del sys.modules[mod]
except:
pass
# remove the plugin entry
del _plugin_modules[packageName]
def isPluginLoaded(packageName):
""" find out whether a plugin is active (i.e. has been started) """
global plugins, active_plugins
if packageName not in plugins:
return False
return (packageName in active_plugins)
def reloadPlugin(packageName):
""" unload and start again a plugin """
global active_plugins
if packageName not in active_plugins:
return # it's not active
unloadPlugin(packageName)
loadPlugin(packageName)
startPlugin(packageName)
def showPluginHelp(packageName=None, filename="index", section=""):
""" show a help in the user's html browser. The help file should be named index-ll_CC.html or index-ll.html"""
try:
source = ""
if packageName is None:
import inspect
source = inspect.currentframe().f_back.f_code.co_filename
else:
source = sys.modules[packageName].__file__
except:
return
path = os.path.dirname(source)
locale = str(QLocale().name())
helpfile = os.path.join(path, filename + "-" + locale + ".html")
if not os.path.exists(helpfile):
helpfile = os.path.join(path, filename + "-" + locale.split("_")[0] + ".html")
if not os.path.exists(helpfile):
helpfile = os.path.join(path, filename + "-en.html")
if not os.path.exists(helpfile):
helpfile = os.path.join(path, filename + "-en_US.html")
if not os.path.exists(helpfile):
helpfile = os.path.join(path, filename + ".html")
if os.path.exists(helpfile):
url = "file://" + helpfile
if section != "":
url = url + "#" + section
iface.openURL(url, False)
def pluginDirectory(packageName):
""" return directory where the plugin resides. Plugin must be loaded already """
return os.path.dirname(sys.modules[packageName].__file__)
def reloadProjectMacros():
# unload old macros
unloadProjectMacros()
from qgis.core import QgsProject
code, ok = QgsProject.instance().readEntry("Macros", "/pythonCode")
if not ok or not code or code == '':
return
# create a new empty python module
import imp
mod = imp.new_module("proj_macros_mod")
# set the module code and store it sys.modules
exec(str(code), mod.__dict__)
sys.modules["proj_macros_mod"] = mod
# load new macros
openProjectMacro()
def unloadProjectMacros():
if "proj_macros_mod" not in sys.modules:
return
# unload old macros
closeProjectMacro()
# destroy the reference to the module
del sys.modules["proj_macros_mod"]
def openProjectMacro():
if "proj_macros_mod" not in sys.modules:
return
mod = sys.modules["proj_macros_mod"]
if hasattr(mod, 'openProject'):
mod.openProject()
def saveProjectMacro():
if "proj_macros_mod" not in sys.modules:
return
mod = sys.modules["proj_macros_mod"]
if hasattr(mod, 'saveProject'):
mod.saveProject()
def closeProjectMacro():
if "proj_macros_mod" not in sys.modules:
return
mod = sys.modules["proj_macros_mod"]
if hasattr(mod, 'closeProject'):
mod.closeProject()
#######################
# SERVER PLUGINS
#
# TODO: move into server_utils.py ?
# list of plugin paths. it gets filled in by the QGIS python library
server_plugin_paths = []
# dictionary of plugins
server_plugins = {}
# list of active (started) plugins
server_active_plugins = []
# initialize 'serverIface' object
serverIface = None
def initServerInterface(pointer):
from qgis.server import QgsServerInterface
from sip import wrapinstance
sys.excepthook = sys.__excepthook__
global serverIface
serverIface = wrapinstance(pointer, QgsServerInterface)
def startServerPlugin(packageName):
""" initialize the plugin """
global server_plugins, server_active_plugins, serverIface
if packageName in server_active_plugins:
return False
if packageName not in sys.modules:
return False
package = sys.modules[packageName]
errMsg = QCoreApplication.translate("Python", "Couldn't load server plugin %s") % packageName
# create an instance of the plugin
try:
server_plugins[packageName] = package.serverClassFactory(serverIface)
except:
_unloadPluginModules(packageName)
msg = QCoreApplication.translate("Python",
"%s due to an error when calling its serverClassFactory() method") % errMsg
showException(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2], msg)
return False
# add to active plugins
server_active_plugins.append(packageName)
return True
def spatialite_connect(*args, **kwargs):
"""returns a dbapi2.Connection to a spatialite db
either using pyspatialite if it is present
or using the "mod_spatialite" extension (python3)"""
try:
from pyspatialite import dbapi2
except ImportError:
import sqlite3
con = sqlite3.dbapi2.connect(*args, **kwargs)
con.enable_load_extension(True)
cur = con.cursor()
libs = [
# Spatialite >= 4.2 and Sqlite >= 3.7.17, should work on all platforms
("mod_spatialite", "sqlite3_modspatialite_init"),
# Spatialite >= 4.2 and Sqlite < 3.7.17 (Travis)
("mod_spatialite.so", "sqlite3_modspatialite_init"),
# Spatialite < 4.2 (linux)
("libspatialite.so", "sqlite3_extension_init")
]
found = False
for lib, entry_point in libs:
try:
cur.execute("select load_extension('{}', '{}')".format(lib, entry_point))
except sqlite3.OperationalError:
continue
else:
found = True
break
if not found:
raise RuntimeError("Cannot find any suitable spatialite module")
cur.close()
con.enable_load_extension(False)
return con
return dbapi2.connect(*args, **kwargs)
#######################
# IMPORT wrapper
_uses_builtins = True
try:
import builtins
_builtin_import = builtins.__import__
except AttributeError:
_uses_builtins = False
import __builtin__
_builtin_import = __builtin__.__import__
_plugin_modules = {}
def _import(name, globals={}, locals={}, fromlist=[], level=None):
""" wrapper around builtin import that keeps track of loaded plugin modules """
if level is None:
level = -1 if sys.version_info[0] < 3 else 0
mod = _builtin_import(name, globals, locals, fromlist, level)
if mod and '__file__' in mod.__dict__:
module_name = mod.__name__
package_name = module_name.split('.')[0]
# check whether the module belongs to one of our plugins
if package_name in available_plugins:
if package_name not in _plugin_modules:
_plugin_modules[package_name] = set()
_plugin_modules[package_name].add(module_name)
# check the fromlist for additional modules (from X import Y,Z)
if fromlist:
for fromitem in fromlist:
frmod = module_name + "." + fromitem
if frmod in sys.modules:
_plugin_modules[package_name].add(frmod)
return mod
if _uses_builtins:
builtins.__import__ = _import
else:
__builtin__.__import__ = _import
| fritsvanveen/QGIS | python/utils.py | Python | gpl-2.0 | 20,592 |
"""tifis_platform 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
urlpatterns = [
url(r'^i18n/', include('django.conf.urls.i18n')), #perfom translations
url(r'^', include('usermodule.urls', namespace='usermodule')),
url(r'^', include('groupmodule.urls', namespace='groupmodule')),
url(r'^admin/', include(admin.site.urls)),
]
| Sezzh/tifis_platform | tifis_platform/tifis_platform/urls.py | Python | gpl-2.0 | 975 |
item_id = 4986168
user_id = 20000
item_category = 9656
time = 31
| CharLLCH/jianchi_alimobileR | ftrldata/TCReBuild/codes/mylibs/size.py | Python | gpl-2.0 | 65 |
#! /usr/bin/env python
"""
##############################################################################
##
##
## @Name : generateImageWebPage.py
##
## @license : MetPX Copyright (C) 2004-2006 Environment Canada
## MetPX comes with ABSOLUTELY NO WARRANTY; For details type see the file
## named COPYING in the root of the source directory tree.
##
##
## @author: Nicholas Lemay
##
## @since: 22-11-2006, last updated on : 2008-04-30
##
##
## Description : Generates a web pages that gives access to user
## to the daily graphics of the last 7 days for all rx sources
## and tx clients.
##
##
##############################################################################
"""
import os, sys
import cgi
import cgitb; cgitb.enable()
"""
Small function that adds pxStats to the sys path.
"""
sys.path.insert(1, sys.path[0] + '/../../..')
from pxStats.lib.StatsPaths import StatsPaths
from pxStats.lib.LanguageTools import LanguageTools
"""
Small method required to add pxLib to syspath.
"""
PATHS = StatsPaths()
PATHS.setBasicPaths()
sys.path.append( PATHS.PXLIB )
def returnReplyToQuerier( error ="" ):
"""
@summary : Prints an empty reply so that the receiving web page will
not modify it's display.
@param error : Error to return to querier.
@return : None
@note: Method does not actually "return" anything.
It just prints out it's reply that is to be
intercepted by the querier.
"""
if error == "":
reply = "images='';error='';action=showImageWindow"
else:
reply = "images='';error=%s" %error
print """
HTTP/1.0 200 OK
Server: NCSA/1.0a6
Content-type: text/plain
"""
print """%s""" %( reply )
def generateWebPage( images, lang ):
"""
@summary : Generates a web page that simply displays a
series of images one on top of the other.
@param images : List of images to display.
@param lang : language with whom this generator was called.
"""
smallImageWidth = 900
smallImageHeight = 320
statsPaths = StatsPaths()
statsPaths.setPaths( lang )
file = statsPaths.STATSWEBPAGESHTML + "combinedImageWebPage.html"
fileHandle = open( file, "w")
fileHandle.write( """
<html>
<head>
<style type="text/css">
a.photosLink{
display: block;
width: 1200px;
height: 310px;
background: url("") 0 0 no-repeat;
text-decoration: none;
}
</style>
<script type="text/javascript" src="../scripts/js/windowfiles/dhtmlwindow.js">
This is left here to give credit to the original
creators of the dhtml script used for the group pop ups:
/***********************************************
* DHTML Window Widget- Dynamic Drive (www.dynamicdrive.com)
* This notice must stay intact for legal use.
* Visit http://www.dynamicdrive.com/ for full source code
***********************************************/
</script>
<script>
counter =0;
function wopen(url, name, w, h){
// This function was taken on www.boutell.com
w += 32;
h += 96;
counter +=1;
var win = window.open(url,
counter,
'width=' + w + ', height=' + h + ', ' +
'location=no, menubar=no, ' +
'status=no, toolbar=no, scrollbars=no, resizable=no');
win.resizeTo(w, h);
win.focus();
}
function transport( image ){
wopen( image, 'popup', %s, %s);
}
</script>
</head>
<body>
""" %( smallImageWidth, smallImageHeight ) )
relativePathTowardsPxStats = "../../../pxStats/"
for i in range(len(images) ):
pathTowardsImage = str(images[i]).split( "pxStats" )[-1:][0]
fileHandle.write("""
<a href="#" class="photosLink" name="photo%s" onclick="javascript:transport('%s')" id="photo%s" border=0>
</a>
<script>
document.getElementById('photo%s').style.background="url(" + "%s" + ") no-repeat";
</script>
"""%( i, relativePathTowardsPxStats + pathTowardsImage, i, i, relativePathTowardsPxStats + pathTowardsImage ) )
fileHandle.write( """
</body>
</html>
""")
fileHandle.close()
try:
os.chmod(file,0777)
except:
pass
def getImagesLangFromForm():
"""
@summary : Parses form with whom this program was called.
@return: Returns the images and language found within the form.
"""
lang = LanguageTools.getMainApplicationLanguage()
images = []
newForm = {}
form = cgi.FieldStorage()
for key in form.keys():
value = form.getvalue(key, "")
if isinstance(value, list):
newvalue = ",".join(value)
else:
newvalue = value
newForm[key.replace("?","")]= newvalue
try:
images = newForm["images"]
images = images.split(';')
except:
pass
try:
lang = newForm["lang"]
except:
pass
return images, lang
def main():
"""
@summary : Generate an html page displaying all the image received in parameter.
Replies to the querier after generating web page so that querier
is informed the page was generated.
"""
images, lang = getImagesLangFromForm()
#print images
generateWebPage( images, lang )
returnReplyToQuerier()
if __name__ == '__main__':
main()
| khosrow/metpx | pxStats/bin/webPages/generateImageWebPage.py | Python | gpl-2.0 | 6,610 |
#!/usr/bin/python
import sys
import getopt
import time
import os
DATA_DIR='/local/devel/guppy/testing/'
opts, args = getopt.getopt(sys.argv[1:], 'c:t')
transfer = False
listdir = False
for opt, optarg in opts:
if opt == '-c':
if optarg == 'get' or optarg == 'put':
transfer = True
if optarg == 'dir':
listdir = True
if optarg == 'cancel':
os.system("pkill -f 'fakepuppy.py -c get.*'")
if optarg == 'size':
size = True
if transfer:
inc = 10
percent = 0.0
for i in xrange(100/inc):
percent = percent + inc
print >> sys.stderr, "\r%6.2f%%, %5.2f Mbits/s, %02d:%02d:%02d elapsed, %d:%02d:%02d remaining" % (percent, 2.2, 1, 1, 1, 2, 2, 2),
time.sleep(0.5)
print
elif listdir:
listing = open(DATA_DIR + 'puppy-listdir.txt')
for line in listing:
print line,
listing.close()
elif size:
print 'Total %10u kiB %7u MiB %4u GiB' % (0, 0, 120)
print 'Free %10u kiB %7u MiB %4u GiB' % (0, 500, 0)
else:
print opts, '|', args,
| ttsui/guppy | testing/fakepuppy.py | Python | gpl-2.0 | 959 |
# Copyright (c) 2005 Maxim Sobolev. All rights reserved.
# Copyright (c) 2006-2007 Sippy Software, Inc. All rights reserved.
#
# This file is part of SIPPY, a free RFC3261 SIP stack and B2BUA.
#
# SIPPY 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.
#
# For a license to use the SIPPY software under conditions
# other than those described here, or to purchase support for this
# software, please contact Sippy Software, Inc. by e-mail at the
# following addresses: [email protected].
#
# SIPPY 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 SipGenericHF import SipGenericHF
class SipReplaces(SipGenericHF):
hf_names = ('replaces',)
call_id = None
from_tag = None
to_tag = None
early_only = False
params = None
def __init__(self, body = None, call_id = None, from_tag = None, to_tag = None, \
early_only = False, params = None):
SipGenericHF.__init__(self, body)
if body != None:
return
self.parsed = True
self.params = []
self.call_id = call_id
self.from_tag = from_tag
self.to_tag = to_tag
self.early_only = early_only
if params != None:
self.params = params[:]
def parse(self):
self.parsed = True
self.params = []
params = self.body.split(';')
self.call_id = params.pop(0)
for param in params:
if param.startswith('from-tag='):
self.from_tag = param[len('from-tag='):]
elif param.startswith('to-tag='):
self.to_tag = param[len('to-tag='):]
elif param == 'early-only':
self.early_only = True
else:
self.params.append(param)
def __str__(self):
if not self.parsed:
return self.body
res = '%s;from-tag=%s;to-tag=%s' % (self.call_id, self.from_tag, self.to_tag)
if self.early_only:
res += ';early-only'
for param in self.params:
res += ';' + param
return res
def getCopy(self):
if not self.parsed:
return SipReplaces(self.body)
return SipReplaces(call_id = self.call_id, from_tag = self.from_tag, to_tag = self.to_tag, \
early_only = self.early_only, params = self.params)
| lemenkov/sippy | sippy/SipReplaces.py | Python | gpl-2.0 | 2,867 |
#!/Library/Frameworks/Python.framework/Versions/Current/bin/python
import os
from os.path import join, getsize
from random import randint
def addEntry (XMLFile, finfo, dirs, NASPath):
#finfo[1].replace(' ', '_')
finfo[1] = finfo[1].replace('.', '_', finfo.count('.')-1)
title = finfo[1].split('.')[0]
root = ''
genre = 'Tom and Frederika'
pathlist = finfo[0].split('/')
for pathchunk in pathlist:
for dirname in dirs:
if pathchunk == dirname:
genre = dirname
imageRoot = ''
for pathchunk in pathlist:
if pathchunk.find('videos') == -1:
imageRoot = imageRoot + pathchunk + '/'
else:
imageRoot = imageRoot + 'videos/images/'
break
imageFile = imageRoot + title + '.jpg'
if os.path.exists(imageFile):
imageFile = 'images/' + title + '.jpg'
else:
imageFile = 'images/FAM%d.jpg' % randint(1,116)
XMLFile.write("<movie>\n")
XMLFile.write("<num>" + str(finfo[2]) + "</num>\n")
XMLFile.write("<origtitle>" + title + "</origtitle>\n")
XMLFile.write("<year>2009</year>\n")
XMLFile.write("<genre>" + genre + "</genre>\n")
XMLFile.write("<mpaa>Rated G</mpaa>\n")
XMLFile.write("<director></director>\n")
XMLFile.write("<actors></actors>\n")
XMLFile.write("<description></description>\n")
XMLFile.write("<path>" + NASPath + "</path>\n")
XMLFile.write("<length>110</length>\n")
XMLFile.write("<videocodec>MP4</videocodec>\n")
XMLFile.write("<poster>" + imageFile + "</poster>\n")
XMLFile.write("</movie>\n\n")
#------ End of addEntry
videosDir = '/Volumes/Volume_1-1/media/videos'
#videosDir = './videos'
videoXMLFileName = videosDir + '/videos.xml'
NASRoot = "Y:\\media\\videos\\"
allfiles = []
allDirs = []
print 'Reading in files from ' + videosDir;
for root, dirs, files in os.walk(videosDir):
for dirname in dirs:
allDirs.append(dirname)
for name in files:
if (name.find('mp4') > -1 or name.find('MP4') > -1) and name.find('._') == -1:
allfiles.append([root, name, len(allfiles)])
if (name.find('mkv') > -1 or name.find('MKV') > -1) and name.find('._') == -1:
allfiles.append([root, name, len(allfiles)])
if (name.find('avi') > -1 or name.find('AVI') > -1) and name.find('._') == -1:
allfiles.append([root, name, len(allfiles)])
videoXMLFile = open(videoXMLFileName, 'w')
videoXMLFile.write("<xml>\n")
videoXMLFile.write("<viddb>\n")
videoXMLFile.write("<movies>" + str(len(allfiles)) +"</movies>\n\n")
print '...read in ' + str(len(allfiles) + 1) + ' files'
print 'Building XML media file at ' + videoXMLFileName
for finfo in allfiles:
pathlist = finfo[0].split('/')
NASPath = NASRoot
for pathchunk in pathlist[5:]:
NASPath = NASPath + pathchunk + "\\"
NASPath = NASPath + finfo[1]
#print NASPath + " - " + finfo[0] + "/" + finfo[1]
addEntry (videoXMLFile, finfo, allDirs, NASPath)
videoXMLFile.write("</viddb>\n")
videoXMLFile.write("</xml>\n")
videoXMLFile.close()
print 'Built XML media file for ' + str(len(allfiles) + 1) + ' movies'
| trafferty/utils | python/buildVideoXML.py | Python | gpl-2.0 | 3,204 |
def comb(xs):
if len(xs) == 0:
return [""]
else:
return comb2(xs) + [""]
def comb2(xs):
if len(xs) == 1:
return [ xs ]
else:
subwo = comb2( xs[1:] )
head = xs[0]
subwith = [ head + zs for zs in subwo ]
return subwo + subwith + [ head ]
result = comb( "abcde" )
result.sort()
print result
print len( result )
| greatmazinger/programming-interview-code | Python/comb.py | Python | gpl-2.0 | 382 |
# -*- coding: utf-8 -*-
#
# sympa documentation build configuration file, created by
# sphinx-quickstart on Mon Aug 25 18:11:49 2014.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
from datetime import date
import sys
import os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.doctest',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'sympa'
copyright = u'%s, Direction Informatique' % date.today().strftime("%Y")
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '0.1'
# The full version, including alpha/beta/rc tags.
release = '0.1'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'sympadoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
('index', 'sympa.tex', u'sympa Documentation',
u'Direction Informatique', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'sympa', u'sympa Documentation',
[u'Direction Informatique'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'sympa', u'sympa Documentation',
u'Direction Informatique', 'sympa', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
| unistra/django-sympa | docs/conf.py | Python | gpl-2.0 | 8,528 |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
from __future__ import print_function
import datetime
import glob
import os
import re
import sys
import subprocess
from picard import __version__, compat
if sys.version_info < (2, 6):
print("*** You need Python 2.6 or higher to use Picard.")
args = {}
try:
from py2app.build_app import py2app
do_py2app = True
except ImportError:
do_py2app = False
# this must be imported *after* py2app, because py2app imports setuptools
# which "patches" (read: screws up) the Extension class
from distutils import log
from distutils.command.build import build
from distutils.command.install import install as install
from distutils.core import setup, Command, Extension
from distutils.dep_util import newer
from distutils.dist import Distribution
from distutils.spawn import find_executable
ext_modules = [
Extension('picard.util.astrcmp', sources=['picard/util/astrcmp.c']),
]
py2app_exclude_modules = [
'pydoc',
'PyQt4.QtDeclarative', 'PyQt4.QtDesigner', 'PyQt4.QtHelp', 'PyQt4.QtMultimedia',
'PyQt4.QtOpenGL', 'PyQt4.QtScript', 'PyQt4.QtScriptTools', 'PyQt4.QtSql', 'PyQt4.QtSvg',
'PyQt4.QtTest', 'PyQt4.QtWebKit', 'PyQt4.QtXml', 'PyQt4.QtXmlPatterns', 'PyQt4.phonon'
]
py2exe_exclude_modules = [
'socket', 'select',
]
exclude_modules = [
'ssl', 'bz2',
'distutils', 'unittest',
'bdb', 'calendar', 'difflib', 'doctest', 'dummy_thread', 'gzip',
'optparse', 'pdb', 'plistlib', 'pyexpat', 'quopri', 'repr',
'stringio', 'tarfile', 'uu', 'zipfile'
]
if do_py2app:
args['app'] = ['tagger.py']
args['name'] = 'Picard'
args['options'] = { 'py2app' :
{
'optimize' : 2,
'argv_emulation' : True,
'iconfile' : 'picard.icns',
'frameworks' : ['libiconv.2.dylib', 'libdiscid.0.dylib'],
'resources' : ['locale'],
'includes' : ['json', 'sip', 'PyQt4', 'ntpath'] + [e.name for e in ext_modules],
'excludes' : exclude_modules + py2app_exclude_modules,
'plist' : { 'CFBundleName' : 'MusicBrainz Picard',
'CFBundleGetInfoString' : 'Picard, the next generation MusicBrainz tagger (see http://musicbrainz.org/doc/MusicBrainz_Picard)',
'CFBundleIdentifier':'org.musicbrainz.picard',
'CFBundleShortVersionString':__version__,
'CFBundleVersion': 'Picard ' + __version__,
'LSMinimumSystemVersion':'10.4.3',
'LSMultipleInstancesProhibited':'true',
# RAK: It biffed when I tried to include your accented characters, luks. :-(
'NSHumanReadableCopyright':'Copyright 2008 Lukas Lalinsky, Robert Kaye',
},
'qt_plugins': ['imageformats/libqgif.dylib',
'imageformats/libqjpeg.dylib',
'imageformats/libqtiff.dylib',
'accessible/libqtaccessiblewidgets.dylib']
},
}
tx_executable = find_executable('tx')
class picard_test(Command):
description = "run automated tests"
user_options = [
("tests=", None, "list of tests to run (default all)"),
("verbosity=", "v", "verbosity"),
]
def initialize_options(self):
self.tests = []
self.verbosity = 1
def finalize_options(self):
if self.tests:
self.tests = self.tests.split(",")
if self.verbosity:
self.verbosity = int(self.verbosity)
def run(self):
import unittest
import sip
sip.setapi("QString", 2)
sip.setapi("QVariant", 2)
names = []
for filename in glob.glob("test/test_*.py"):
name = os.path.splitext(os.path.basename(filename))[0]
if not self.tests or name in self.tests:
names.append("test." + name)
tests = unittest.defaultTestLoader.loadTestsFromNames(names)
t = unittest.TextTestRunner(verbosity=self.verbosity)
testresult = t.run(tests)
if not testresult.wasSuccessful():
sys.exit("At least one test failed.")
class picard_build_locales(Command):
description = 'build locale files'
user_options = [
('build-dir=', 'd', "directory to build to"),
('inplace', 'i', "ignore build-lib and put compiled locales into the 'locale' directory"),
]
def initialize_options(self):
self.build_dir = None
self.inplace = 0
def finalize_options(self):
self.set_undefined_options('build', ('build_locales', 'build_dir'))
self.locales = self.distribution.locales
def run(self):
for domain, locale, po in self.locales:
if self.inplace:
path = os.path.join('locale', locale, 'LC_MESSAGES')
else:
path = os.path.join(self.build_dir, locale, 'LC_MESSAGES')
mo = os.path.join(path, '%s.mo' % domain)
self.mkpath(path)
self.spawn(['msgfmt', '-o', mo, po])
Distribution.locales = None
class picard_install_locales(Command):
description = "install locale files"
user_options = [
('install-dir=', 'd', "directory to install locale files to"),
('build-dir=', 'b', "build directory (where to install from)"),
('force', 'f', "force installation (overwrite existing files)"),
('skip-build', None, "skip the build steps"),
]
boolean_options = ['force', 'skip-build']
def initialize_options(self):
self.install_dir = None
self.build_dir = None
self.force = 0
self.skip_build = None
self.outfiles = []
def finalize_options(self):
self.set_undefined_options('build', ('build_locales', 'build_dir'))
self.set_undefined_options('install',
('install_locales', 'install_dir'),
('force', 'force'),
('skip_build', 'skip_build'),
)
def run(self):
if not self.skip_build:
self.run_command('build_locales')
self.outfiles = self.copy_tree(self.build_dir, self.install_dir)
def get_inputs(self):
return self.locales or []
def get_outputs(self):
return self.outfiles
class picard_install(install):
user_options = install.user_options + [
('install-locales=', None,
"installation directory for locales"),
('localedir=', None, ''),
('disable-autoupdate', None, ''),
('disable-locales', None, ''),
]
sub_commands = install.sub_commands
def initialize_options(self):
install.initialize_options(self)
self.install_locales = None
self.localedir = None
self.disable_autoupdate = None
self.disable_locales = None
def finalize_options(self):
install.finalize_options(self)
if self.install_locales is None:
self.install_locales = '$base/share/locale'
self._expand_attrs(['install_locales'])
self.install_locales = os.path.normpath(self.install_locales)
self.localedir = self.install_locales
# can't use set_undefined_options :/
self.distribution.get_command_obj('build').localedir = self.localedir
self.distribution.get_command_obj('build').disable_autoupdate = self.disable_autoupdate
if self.root is not None:
self.change_roots('locales')
if self.disable_locales is None:
self.sub_commands.append(('install_locales', None))
def run(self):
install.run(self)
class picard_build(build):
user_options = build.user_options + [
('build-locales=', 'd', "build directory for locale files"),
('localedir=', None, ''),
('disable-autoupdate', None, ''),
('disable-locales', None, ''),
]
sub_commands = build.sub_commands
def initialize_options(self):
build.initialize_options(self)
self.build_locales = None
self.localedir = None
self.disable_autoupdate = None
self.disable_locales = None
def finalize_options(self):
build.finalize_options(self)
if self.build_locales is None:
self.build_locales = os.path.join(self.build_base, 'locale')
if self.localedir is None:
self.localedir = '/usr/share/locale'
if self.disable_autoupdate is None:
self.disable_autoupdate = False
if self.disable_locales is None:
self.sub_commands.append(('build_locales', None))
def run(self):
if 'bdist_nsis' not in sys.argv: # somebody shoot me please
log.info('generating scripts/picard from scripts/picard.in')
generate_file('scripts/picard.in', 'scripts/picard', {'localedir': self.localedir, 'autoupdate': not self.disable_autoupdate})
build.run(self)
def py_from_ui(uifile):
return "ui_%s.py" % os.path.splitext(os.path.basename(uifile))[0]
def py_from_ui_with_defaultdir(uifile):
return os.path.join("picard", "ui", py_from_ui(uifile))
def ui_files():
for uifile in glob.glob("ui/*.ui"):
yield (uifile, py_from_ui_with_defaultdir(uifile))
class picard_build_ui(Command):
description = "build Qt UI files and resources"
user_options = [
("files=", None, "comma-separated list of files to rebuild"),
]
def initialize_options(self):
self.files = []
def finalize_options(self):
if self.files:
files = []
for f in self.files.split(","):
head, tail = os.path.split(f)
m = re.match(r'(?:ui_)?([^.]+)', tail)
if m:
name = m.group(1)
else:
log.warn('ignoring %r (cannot extract base name)' % f)
continue
uiname = name + '.ui'
uifile = os.path.join(head, uiname)
if os.path.isfile(uifile):
pyfile = os.path.join(os.path.dirname(uifile),
py_from_ui(uifile))
files.append((uifile, pyfile))
else:
uifile = os.path.join('ui', uiname)
if os.path.isfile(uifile):
files.append((uifile,
py_from_ui_with_defaultdir(uifile)))
else:
log.warn('ignoring %r' % f)
self.files = files
def run(self):
from PyQt4 import uic
_translate_re = (
re.compile(
r'QtGui\.QApplication.translate\(.*?, (.*?), None, '
r'QtGui\.QApplication\.UnicodeUTF8\)'),
re.compile(
r'\b_translate\(.*?, (.*?), None\)')
)
def compile_ui(uifile, pyfile):
log.info("compiling %s -> %s", uifile, pyfile)
tmp = compat.StringIO()
uic.compileUi(uifile, tmp)
source = tmp.getvalue()
rc = re.compile(r'\n\n#.*?(?=\n\n)', re.MULTILINE|re.DOTALL)
comment = (u"\n\n# Automatically generated - don't edit.\n"
u"# Use `python setup.py %s` to update it."
% _get_option_name(self))
for r in list(_translate_re):
source = r.sub(r'_(\1)', source)
source = rc.sub(comment, source)
f = open(pyfile, "w")
f.write(source)
f.close()
if self.files:
for uifile, pyfile in self.files:
compile_ui(uifile, pyfile)
else:
for uifile, pyfile in ui_files():
if newer(uifile, pyfile):
compile_ui(uifile, pyfile)
from resources import compile, makeqrc
makeqrc.main()
compile.main()
class picard_clean_ui(Command):
description = "clean up compiled Qt UI files and resources"
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
from PyQt4 import uic
for uifile, pyfile in ui_files():
try:
os.unlink(pyfile)
log.info("removing %s", pyfile)
except OSError:
log.warn("'%s' does not exist -- can't clean it", pyfile)
pyfile = os.path.join("picard", "resources.py")
try:
os.unlink(pyfile)
log.info("removing %s", pyfile)
except OSError:
log.warn("'%s' does not exist -- can't clean it", pyfile)
class picard_get_po_files(Command):
description = "Retrieve po files from transifex"
minimum_perc_default = 5
user_options = [
('minimum-perc=', 'm',
"Specify the minimum acceptable percentage of a translation (default: %d)" % minimum_perc_default)
]
def initialize_options(self):
self.minimum_perc = self.minimum_perc_default
def finalize_options(self):
self.minimum_perc = int(self.minimum_perc)
def run(self):
if tx_executable is None:
sys.exit('Transifex client executable (tx) not found.')
txpull_cmd = [
tx_executable,
'pull',
'--force',
'--all',
'--minimum-perc=%d' % self.minimum_perc
]
self.spawn(txpull_cmd)
_regen_pot_description = "Regenerate po/picard.pot, parsing source tree for new or updated strings"
try:
from babel import __version__ as babel_version
from babel.messages import frontend as babel
def versiontuple(v):
return tuple(map(int, (v.split("."))))
# input_dirs are incorrectly handled in babel versions < 1.0
# http://babel.edgewall.org/ticket/232
input_dirs_workaround = versiontuple(babel_version) < (1, 0, 0)
class picard_regen_pot_file(babel.extract_messages):
description = _regen_pot_description
def initialize_options(self):
# cannot use super() with old-style parent class
babel.extract_messages.initialize_options(self)
self.output_file = 'po/picard.pot'
self.input_dirs = 'contrib, picard'
if self.input_dirs and input_dirs_workaround:
self._input_dirs = self.input_dirs
def finalize_options(self):
babel.extract_messages.finalize_options(self)
if input_dirs_workaround and self._input_dirs:
self.input_dirs = re.split(',\s*', self._input_dirs)
except ImportError:
class picard_regen_pot_file(Command):
description = _regen_pot_description
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
sys.exit("Babel is required to use this command (see po/README.md)")
def _get_option_name(obj):
"""Returns the name of the option for specified Command object"""
for name, klass in obj.distribution.cmdclass.iteritems():
if obj.__class__ == klass:
return name
raise Exception("No such command class")
class picard_update_constants(Command):
description = "Regenerate attributes.py and countries.py"
user_options = [
('skip-pull', None, "skip the tx pull steps"),
]
boolean_options = ['skip-pull']
def initialize_options(self):
self.skip_pull = None
def finalize_options(self):
self.locales = self.distribution.locales
def run(self):
if tx_executable is None:
sys.exit('Transifex client executable (tx) not found.')
from babel.messages import pofile
if not self.skip_pull:
txpull_cmd = [
tx_executable,
'pull',
'--force',
'--resource=musicbrainz.attributes,musicbrainz.countries',
'--source',
'--language=none',
]
self.spawn(txpull_cmd)
countries = dict()
countries_potfile = os.path.join('po', 'countries', 'countries.pot')
isocode_comment = u'iso.code:'
with open(countries_potfile, 'rb') as f:
log.info('Parsing %s' % countries_potfile)
po = pofile.read_po(f)
for message in po:
if not message.id or not isinstance(message.id, unicode):
continue
for comment in message.auto_comments:
if comment.startswith(isocode_comment):
code = comment.replace(isocode_comment, u'')
countries[code] = message.id
if countries:
self.countries_py_file(countries)
else:
sys.exit('Failed to extract any country code/name !')
attributes = dict()
attributes_potfile = os.path.join('po', 'attributes', 'attributes.pot')
extract_attributes = (
u'DB:cover_art_archive.art_type/name',
u'DB:medium_format/name',
u'DB:release_group_primary_type/name',
u'DB:release_group_secondary_type/name',
)
with open(attributes_potfile, 'rb') as f:
log.info('Parsing %s' % attributes_potfile)
po = pofile.read_po(f)
for message in po:
if not message.id or not isinstance(message.id, unicode):
continue
for loc, pos in message.locations:
if loc in extract_attributes:
attributes[u"%s:%03d" % (loc, pos)] = message.id
if attributes:
self.attributes_py_file(attributes)
else:
sys.exit('Failed to extract any attribute !')
def countries_py_file(self, countries):
header = (u"# -*- coding: utf-8 -*-\n"
u"# Automatically generated - don't edit.\n"
u"# Use `python setup.py {option}` to update it.\n"
u"\n"
u"RELEASE_COUNTRIES = {{\n")
line = u" u'{code}': u'{name}',\n"
footer = u"}}\n"
filename = os.path.join('picard', 'const', 'countries.py')
with open(filename, 'w') as countries_py:
def write_utf8(s, **kwargs):
countries_py.write(s.format(**kwargs).encode('utf-8'))
write_utf8(header, option=_get_option_name(self))
for code, name in sorted(countries.items(), key=lambda t: t[0]):
write_utf8(line, code=code, name=name.replace("'", "\\'"))
write_utf8(footer)
log.info("%s was rewritten (%d countries)" % (filename,
len(countries)))
def attributes_py_file(self, attributes):
header = (u"# -*- coding: utf-8 -*-\n"
u"# Automatically generated - don't edit.\n"
u"# Use `python setup.py {option}` to update it.\n"
u"\n"
u"MB_ATTRIBUTES = {{\n")
line = u" u'{key}': u'{value}',\n"
footer = u"}}\n"
filename = os.path.join('picard', 'const', 'attributes.py')
with open(filename, 'w') as attributes_py:
def write_utf8(s, **kwargs):
attributes_py.write(s.format(**kwargs).encode('utf-8'))
write_utf8(header, option=_get_option_name(self))
for key, value in sorted(attributes.items(), key=lambda i: i[0]):
write_utf8(line, key=key, value=value.replace("'", "\\'"))
write_utf8(footer)
log.info("%s was rewritten (%d attributes)" % (filename,
len(attributes)))
class picard_patch_version(Command):
description = "Update PICARD_BUILD_VERSION_STR for daily builds"
user_options = [
('platform=', 'p', "platform for the build version, ie. osx or win"),
]
def initialize_options(self):
self.platform = 'unknown'
def finalize_options(self):
pass
def run(self):
self.patch_version('picard/__init__.py')
def patch_version(self, filename):
regex = re.compile(r'^PICARD_BUILD_VERSION_STR\s*=.*$', re.MULTILINE)
with open(filename, 'r+b') as f:
source = f.read()
build = self.platform + '_' + datetime.datetime.utcnow().strftime('%Y%m%d%H%M%S')
patched_source = regex.sub('PICARD_BUILD_VERSION_STR = "%s"' % build, source)
f.seek(0)
f.write(patched_source)
f.truncate()
def cflags_to_include_dirs(cflags):
cflags = cflags.split()
include_dirs = []
for cflag in cflags:
if cflag.startswith('-I'):
include_dirs.append(cflag[2:])
return include_dirs
def _picard_get_locale_files():
locales = []
path_domain = {
'po': 'picard',
os.path.join('po', 'countries'): 'picard-countries',
os.path.join('po', 'attributes'): 'picard-attributes',
}
for path, domain in path_domain.items():
for filepath in glob.glob(os.path.join(path, '*.po')):
filename = os.path.basename(filepath)
locale = os.path.splitext(filename)[0]
locales.append((domain, locale, filepath))
return locales
def _explode_path(path):
"""Return a list of components of the path (ie. "/a/b" -> ["a", "b"])"""
components = []
while True:
(path,tail) = os.path.split(path)
if tail == "":
components.reverse()
return components
components.append(tail)
def _picard_packages():
"Build a tuple containing each module under picard/"
packages = []
for subdir, dirs, files in os.walk("picard"):
packages.append(".".join(_explode_path(subdir)))
return tuple(sorted(packages))
args2 = {
'name': 'picard',
'version': __version__,
'description': 'The next generation MusicBrainz tagger',
'url': 'http://musicbrainz.org/doc/MusicBrainz_Picard',
'package_dir': {'picard': 'picard'},
'packages': _picard_packages(),
'locales': _picard_get_locale_files(),
'ext_modules': ext_modules,
'data_files': [],
'cmdclass': {
'test': picard_test,
'build': picard_build,
'build_locales': picard_build_locales,
'build_ui': picard_build_ui,
'clean_ui': picard_clean_ui,
'install': picard_install,
'install_locales': picard_install_locales,
'update_constants': picard_update_constants,
'get_po_files': picard_get_po_files,
'regen_pot_file': picard_regen_pot_file,
'patch_version': picard_patch_version,
},
'scripts': ['scripts/picard'],
}
args.update(args2)
def generate_file(infilename, outfilename, variables):
with open(infilename, "rt") as f_in:
with open(outfilename, "wt") as f_out:
f_out.write(f_in.read() % variables)
def contrib_plugin_files():
plugin_files = {}
dist_root = os.path.join("contrib", "plugins")
for root, dirs, files in os.walk(dist_root):
file_root = os.path.join('plugins', os.path.relpath(root, dist_root)) \
if root != dist_root else 'plugins'
for file in files:
if file.endswith(".py"):
if file_root in plugin_files:
plugin_files[file_root].append(os.path.join(root, file))
else:
plugin_files[file_root] = [os.path.join(root, file)]
data_files = [(x, sorted(y)) for x, y in plugin_files.iteritems()]
return sorted(data_files, key=lambda x: x[0])
try:
from py2exe.build_exe import py2exe
class bdist_nsis(py2exe):
def run(self):
generate_file('scripts/picard.py2exe.in', 'scripts/picard', {})
self.distribution.data_files.append(
("", ["discid.dll", "fpcalc.exe", "msvcr90.dll", "msvcp90.dll"]))
for locale in self.distribution.locales:
self.distribution.data_files.append(
("locale/" + locale[1] + "/LC_MESSAGES",
["build/locale/" + locale[1] + "/LC_MESSAGES/" + locale[0] + ".mo"]))
self.distribution.data_files.append(
("imageformats", [find_file_in_path("PyQt4/plugins/imageformats/qgif4.dll"),
find_file_in_path("PyQt4/plugins/imageformats/qjpeg4.dll"),
find_file_in_path("PyQt4/plugins/imageformats/qtiff4.dll")]))
self.distribution.data_files.append(
("accessible", [find_file_in_path("PyQt4/plugins/accessible/qtaccessiblewidgets4.dll")]))
self.distribution.data_files += contrib_plugin_files()
py2exe.run(self)
print("*** creating the NSIS setup script ***")
pathname = "installer\picard-setup.nsi"
generate_file(pathname + ".in", pathname,
{'name': 'MusicBrainz Picard',
'version': __version__,
'description': 'The next generation MusicBrainz tagger.',
'url': 'http://musicbrainz.org/doc/MusicBrainz_Picard', })
print("*** compiling the NSIS setup script ***")
subprocess.call([self.find_nsis(), pathname])
def find_nsis(self):
import _winreg
with _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, "Software\\NSIS") as reg_key:
nsis_path = _winreg.QueryValueEx(reg_key, "")[0]
return os.path.join(nsis_path, "makensis.exe")
args['cmdclass']['bdist_nsis'] = bdist_nsis
args['windows'] = [{
'script': 'scripts/picard',
'icon_resources': [(1, 'picard.ico')],
}]
args['options'] = {
'bdist_nsis': {
'includes': ['json', 'sip'] + [e.name for e in ext_modules],
'excludes': exclude_modules + py2exe_exclude_modules,
'optimize': 2,
},
}
except ImportError:
py2exe = None
def find_file_in_path(filename):
for include_path in sys.path:
file_path = os.path.join(include_path, filename)
if os.path.exists(file_path):
return file_path
if do_py2app:
from py2app.util import copy_file, find_app
from PyQt4 import QtCore
class BuildAPP(py2app):
def run(self):
py2app.run(self)
# XXX Find and bundle fpcalc, since py2app can't.
fpcalc = find_app("fpcalc")
if fpcalc:
dest_fpcalc = os.path.abspath("dist/MusicBrainz Picard.app/Contents/MacOS/fpcalc")
copy_file(fpcalc, dest_fpcalc)
os.chmod(dest_fpcalc, 0o755)
args['scripts'] = ['tagger.py']
args['cmdclass']['py2app'] = BuildAPP
# FIXME: this should check for the actual command ('install' vs. 'bdist_nsis', 'py2app', ...), not installed libraries
if py2exe is None and do_py2app is False:
args['data_files'].append(('share/icons/hicolor/16x16/apps', ['resources/images/16x16/picard.png']))
args['data_files'].append(('share/icons/hicolor/24x24/apps', ['resources/images/24x24/picard.png']))
args['data_files'].append(('share/icons/hicolor/32x32/apps', ['resources/images/32x32/picard.png']))
args['data_files'].append(('share/icons/hicolor/48x48/apps', ['resources/images/48x48/picard.png']))
args['data_files'].append(('share/icons/hicolor/128x128/apps', ['resources/images/128x128/picard.png']))
args['data_files'].append(('share/icons/hicolor/256x256/apps', ['resources/images/256x256/picard.png']))
args['data_files'].append(('share/applications', ('picard.desktop',)))
setup(**args)
| dufferzafar/picard | setup.py | Python | gpl-2.0 | 27,977 |
# -*- coding:utf-8 -*-
from django.conf.urls import url, patterns
from rango import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^about/$', views.about, name='about'),
# 匹配URL斜杠前所有的字母数字
# 例如 a-z, A-Z, 或者 0-9)和连字符(-
# 然后把这个值作为category_name_slug参数传递给views.category(),
url(r'^category/(?P<category_name_slug>[\w\-]+)/$',views.category, name='category'),
url(r'^add_category/$', views.add_category, name='add_category'),
url(r'^category/(?P<category_name_slug>[\w\-]+)/add_page/$',views.add_page, name='add_page'),
)
| chen2aaron/TangoWithDjangoProject | rango/urls.py | Python | gpl-2.0 | 646 |
__author__ = 'ramuta'
a = 1
b = 2
if a < b:
a = b
print a
print b
"""
Java equivalent
if (a < b) {
a = b;
}
If you delete parenthesis, brackets and semicolons you get python.
""" | ramuta/python101 | slide4.py | Python | gpl-2.0 | 193 |
# -*- coding: utf-8 -*-
from celery import Celery
from datetime import timedelta
import os
BROKER_URL = 'redis://localhost:6379/0'
celery = Celery('EOD_TASKS', broker=BROKER_URL)
# Loads settings for Backend to store results of tweets
celery.config_from_object('celeryconfig')
CELERY_RESULT_BACKEND = 'redis'
CELERY_IMPORTS = ("task",)
CELERYBEAT_SCHEDULE = {
'fetch-tweets': {
'task': 'task.search',
'schedule': timedelta(seconds=10),
'args': [os.environ.get('HASHTAG')],
},
} | nicolasteodosio/PySent | celeryconfig.py | Python | gpl-2.0 | 514 |
## begin license ##
#
# "Meresco Distributed" has components for group management based on "Meresco Components."
#
# Copyright (C) 2018, 2021 Seecr (Seek You Too B.V.) https://seecr.nl
# Copyright (C) 2021 Data Archiving and Network Services https://dans.knaw.nl
# Copyright (C) 2021 SURF https://www.surf.nl
# Copyright (C) 2021 Stichting Kennisnet https://www.kennisnet.nl
# Copyright (C) 2021 The Netherlands Institute for Sound and Vision https://beeldengeluid.nl
#
# This file is part of "Meresco Distributed"
#
# "Meresco Distributed" 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.
#
# "Meresco Distributed" 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 "Meresco Distributed"; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
## end license ##
from os.path import join, isfile
from uuid import uuid4
from seecr.test import SeecrTestCase, CallTrace
from weightless.core import be, asString, consume, NoneOfTheObserversRespond, retval
from meresco.core import Observable
from meresco.distributed.constants import WRITABLE, READABLE
from meresco.distributed.utils import usrSharePath
from meresco.distributed.failover import MatchesVersion, Proxy, ServiceConfig
from meresco.distributed.failover._matchesversion import betweenVersionCondition
class MatchesVersionTest(SeecrTestCase):
def setUp(self):
SeecrTestCase.setUp(self)
self.matchesVersion = MatchesVersion(minVersion='1', untilVersion='3')
self.observer = CallTrace('observer', methods=dict(somemessage=lambda: (x for x in ['result'])), emptyGeneratorMethods=['updateConfig'])
self.top = be((Observable(),
(self.matchesVersion,
(self.observer,)
)
))
def testDoesNotMatchNoConfig(self):
self.assertEqual('', asString(self.top.all.somemessage()))
self.assertEqual([], self.observer.calledMethodNames())
def testDoesNotMatchNoVersion(self):
consume(self.matchesVersion.updateConfig(config={'foo': 'bar'}))
self.assertEqual('', asString(self.top.all.somemessage()))
self.assertEqual(['updateConfig'], self.observer.calledMethodNames())
def testDoesNotMatch(self):
consume(self.matchesVersion.updateConfig(**{'software_version': '0.1', 'config':{'foo': 'bar'}}))
self.assertEqual('', asString(self.top.all.somemessage()))
self.assertEqual(['updateConfig'], self.observer.calledMethodNames())
def testDoesMatch(self):
consume(self.matchesVersion.updateConfig(software_version='2'))
self.assertEqual('result', asString(self.top.all.somemessage()))
self.assertEqual(['updateConfig', 'somemessage'], self.observer.calledMethodNames())
def testDeterminesConfig(self):
newId = lambda: str(uuid4())
services = {
newId(): {'type': 'service1', 'ipAddress': '10.0.0.2', 'infoport': 1234, 'active': True, 'readable': True, 'writable': True, 'data': {'VERSION': '1.5'}},
newId(): {'type': 'service2', 'ipAddress': '10.0.0.3', 'infoport': 1235, 'active': True, 'readable': True, 'writable': True, 'data': {'VERSION': '1.8'}},
}
config = {
'service1.frontend': {
'fqdn': 'service1.front.example.org',
'ipAddress': '1.2.3.4',
},
'service2.frontend': {
'fqdn': 'service2.front.example.org',
'ipAddress': '1.2.3.5',
},
}
configFile = join(self.tempdir, 'server.conf')
top = be(
(Proxy(nginxConfigFile=configFile),
(MatchesVersion(
minVersion='1.4',
untilVersion='2.0'),
(ServiceConfig(
type='service1',
minVersion='1.4',
untilVersion='2.0',
flag=WRITABLE),
),
),
(MatchesVersion(
minVersion='1.4',
untilVersion='4.0'),
(ServiceConfig(
type='service2',
minVersion='1.4',
untilVersion='2.0',
flag=READABLE),
)
)
)
)
mustUpdate, sleeptime = top.update(software_version='3.0', config=config, services=services, verbose=False)
self.assertTrue(mustUpdate)
self.assertEqual(30, sleeptime)
self.assertTrue(isfile(configFile))
with open(configFile) as fp:
self.assertEqualText("""## Generated by meresco.distributed.failover.Proxy
upstream __var_3ff29304e7437997bf4171776e1fe282_service2 {
server 10.0.0.3:1235;
}
server {
listen 1.2.3.5:80;
server_name service2.front.example.org;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
location / {
proxy_pass http://__var_3ff29304e7437997bf4171776e1fe282_service2;
}
error_page 500 502 503 504 =503 /unavailable.html;
location /unavailable.html {
root %s/failover;
}
client_max_body_size 0;
}
""" % usrSharePath, fp.read())
# MatchesVersion is expected to be invoked with 'all', but testing for 'do', 'call' and 'any' invocation just in case
def testDoesNotMatchDo(self):
consume(self.matchesVersion.updateConfig(**{'software_version': '0.1'}))
self.top.do.somemessage()
self.assertEqual(['updateConfig'], self.observer.calledMethodNames())
def testDoesMatchDo(self):
consume(self.matchesVersion.updateConfig(**{'software_version': '2'}))
self.top.do.anothermessage()
self.assertEqual(['updateConfig', 'anothermessage'], self.observer.calledMethodNames())
def testDoesNotMatchCall(self):
consume(self.matchesVersion.updateConfig(**{'software_version': '0.1'}))
try:
_ = self.top.call.somemessage()
self.fail()
except NoneOfTheObserversRespond:
pass
self.assertEqual(['updateConfig'], self.observer.calledMethodNames())
def testDoesMatchCall(self):
consume(self.matchesVersion.updateConfig(**{'software_version': '2'}))
_ = self.top.call.somemessage()
self.assertEqual(['updateConfig', 'somemessage'], self.observer.calledMethodNames())
def testDoesNotMatchAny(self):
consume(self.matchesVersion.updateConfig(**{'software_version': '0.1'}))
try:
_ = retval(self.top.any.somemessage())
self.fail()
except NoneOfTheObserversRespond:
pass
self.assertEqual(['updateConfig'], self.observer.calledMethodNames())
def testDoesMatchAny(self):
consume(self.matchesVersion.updateConfig(**{'software_version': '2'}))
_ = retval(self.top.any.somemessage())
self.assertEqual(['updateConfig', 'somemessage'], self.observer.calledMethodNames())
def testBetweenVersionCondition(self):
inbetween = betweenVersionCondition('1.3', '8')
self.assertTrue(inbetween('1.3'))
self.assertTrue(inbetween('1.3.x'))
self.assertTrue(inbetween('7.9'))
self.assertFalse(inbetween('8.0'))
self.assertFalse(inbetween('8'))
self.assertFalse(inbetween('77'))
self.assertFalse(inbetween('1.2.x'))
| seecr/meresco-distributed | test/failover/matchesversiontest.py | Python | gpl-2.0 | 7,957 |
from jinja2 import Template
class SupervisorJob(object):
"""docstring for SupervisorJob"""
def __init__(self, config):
""" Specify the configuration options for a job.
'config' must be a dictionary containing the following keys:
- env_vars: dict containing the key/value pairs to be specified as
environment variables
e.g. {"ES_HOME" : "/home/es"}
- name: job name, as used by Supervisor to uniquely identify the job
e.g. "elasticsearch"
- base_dir: Base directory for the supervisor job
e.g. "/home/es"
- cmd: Full command (with args) that supervisor will run
e.g. "elasticsearch -p /home/es/es.pid"
- stdout_file: Full path to the file where stdout will be dumped to by
Supervisor
e.g. "/home/es/logs/es.out"
- stderr_file: Full path to the file where stderr will be dumped to by
Supervisor
e.g. "/home/es/logs/es.err"
"""
super(SupervisorJob, self).__init__()
self.config = config
self['env_vars'] = config.get('env_vars', {})
# self.env_vars = env_vars
# self.base_dir = base_dir
# self.cmd = cmd
# self.name = name
# self.stdout_file = stdout_file
# self.stderr_file = stderr_file
def prepare(self):
raise NotImplementedError("base class")
def __getitem__(self, k):
return self.config[k]
def __setitem__(self, k, v):
self.config[k] = v
def __contains__(self, k):
return k in self.config
def add_env(self, k, v):
self['env_vars'][k] = v
def as_supervisor_program(self):
config = """[program:{{program_name}}]
command = {{cmd}}
directory = {{base_dir}}
autostart = true
autorestart = true
stopsignal = KILL
killasgroup = true
stopasgroup = true
environment = {{env}}
stdout_logfile = {{stdout}}
stderr_logfile = {{stderr}}
"""
env = Template(config)
return env.render({
"program_name" : self.config['name'],
"base_dir" : self.config['base_dir'],
"env" : self.get_env_str(),
"cmd" : self.config['cmd'],
"stdout" : self.config['stdout_file'],
"stderr" : self.config['stderr_file'],
})
def as_exports(self):
res = ""
for k, v in self['env_vars'].items():
res += "export %s=%s\n" % (k, v)
return res
def get_env_str(self):
return ", ".join([k + "=\"" + str(v) + "\"" for k,v in self['env_vars'].items()])
| jjuanda/cuco | cuco/SupervisorJob.py | Python | gpl-2.0 | 2,735 |
from distutils.core import setup
setup(
name = "cnccontrol-driver",
description = "CNC-Control device driver",
author = "Michael Buesch",
author_email = "[email protected]",
py_modules = [ "cnccontrol_driver", ],
)
| mbuesch/cnc-control | driver/setup_driver.py | Python | gpl-2.0 | 215 |
from xbmctorrentV2 import plugin
from xbmctorrentV2.scrapers import scraper
from xbmctorrentV2.ga import tracked
from xbmctorrentV2.caching import cached_route
from xbmctorrentV2.utils import ensure_fanart
from xbmctorrentV2.library import library_context
BASE_URL = "%s/" % plugin.get_setting("base_bitsnoop")
HEADERS = {
"Referer": BASE_URL,
}
# Cache TTLs
DEFAULT_TTL = 24 * 3600 # 24 hours
@scraper("BitSnoop - Search Engine", "%s/i/logo.png" % BASE_URL)
@plugin.route("/bitsnoop")
@ensure_fanart
@tracked
def bitsnoop_index():
plugin.redirect(plugin.url_for("bitsnoop_search"))
@plugin.route("/bitsnoop/browse/<root>/<page>")
@library_context
@ensure_fanart
@tracked
def bitsnoop_page(root, page):
from urlparse import urljoin
from xbmctorrentV2.scrapers import rss
from xbmctorrentV2.utils import url_get
content_type = plugin.request.args_dict.get("content_type")
if content_type:
plugin.set_content(content_type)
page = int(page)
page_data = url_get(urljoin(BASE_URL, "%s/%d/" % (root, page)), headers=HEADERS, params={
"fmt": "rss",
"sort": "n_s",
"dir": "desc",
})
return rss.parse(page_data)
@plugin.route("/bitsnoop/search")
@tracked
def bitsnoop_search():
import urllib
from xbmctorrentV2.utils import first
query = plugin.request.args_dict.pop("query", None)
if not query:
query = plugin.keyboard("", "xbmctorrentV2 - Bitsnoop - Search")
if query:
plugin.redirect(plugin.url_for("bitsnoop_page", root="/search/video/%s/c/d/" % urllib.quote("%s safe:no" % query, safe=""), page=1, **plugin.request.args_dict))
| Mafarricos/Mafarricos-modded-xbmc-addons | plugin.video.xbmctorrentV2/resources/site-packages/xbmctorrentV2/scrapers/bitsnoop.py | Python | gpl-2.0 | 1,646 |
"""
Python module defining a class for creating movies of matplotlib figures.
This code and information is provided 'as is' without warranty of any kind,
either express or implied, including, but not limited to, the implied
warranties of non-infringement, merchantability or fitness for a particular
purpose.
"""
from functools import partial
import shutil
import subprocess
import tempfile
import matplotlib as mpl
import matplotlib.pyplot as plt
def invert_color(color):
""" Returns the inverted value of a matplotlib color """
# get the color value
c = invert_color.cc.to_rgba(color)
# keep alpha value intact!
return (1-c[0], 1-c[1], 1-c[2], c[3])
# initialize the color converted and keep it as a static variable
invert_color.cc = mpl.colors.ColorConverter()
def invert_colors(fig):
""" Changes the colors of a figure to their inverted values """
# keep track of the object that have been changed
visited = set()
def get_filter(name):
""" construct a specific filter for `findobj` """
return lambda x: hasattr(x, 'set_%s'%name) and hasattr(x, 'get_%s'%name)
for o in fig.findobj(get_filter('facecolor')):
if o not in visited:
o.set_facecolor(invert_color(o.get_facecolor()))
if hasattr(o, 'set_edgecolor') and hasattr(o, 'get_edgecolor'):
o.set_edgecolor(invert_color(o.get_edgecolor()))
visited.add(o)
for o in fig.findobj(get_filter('color')):
if o not in visited:
o.set_color(invert_color(o.get_color()))
visited.add(o)
class Movie(object):
""" Class for creating movies from matplotlib figures using ffmpeg """
def __init__(self,
width=None, filename=None, inverted=False, verbose=True,
framerate=None
):
self.width = width #< pixel width of the movie
self.filename = filename #< filename used to save the movie
self.inverted = inverted #< colors inverted?
self.verbose = verbose #< verbose encoding information?
self.framerate = framerate #< framerate of the movie
# internal variables
self.recording = False
self.tempdir = None
self.frame = 0
self._start()
def __del__(self):
self._end()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, exc_tb):
if self.filename is not None:
self.save(self.filename)
self._end()
return False
def _start(self):
""" initializes the video recording """
# create temporary directory for the image files of the movie
self.tempdir = tempfile.mkdtemp(prefix='movie_')
self.frame = 0
self.recording = True
def _end(self):
""" clear up temporary things if necessary """
if self.recording:
shutil.rmtree(self.tempdir)
self.recording = False
def clear(self):
""" delete current status and start from scratch """
self._end()
self._start()
def _add_file(self, save_function):
"""
Adds a file to the current movie
"""
if not self.recording:
raise ValueError('Movie is not initialized.')
save_function("%s/frame_%09d.png" % (self.tempdir, self.frame))
self.frame += 1
def add_image(self, image):
"""
Adds the data of a PIL image as a frame to the current movie.
"""
if self.inverted:
try:
import ImageOps
except ImportError:
from PIL import ImageOps
image_inv = ImageOps.invert(image)
self._add_file(image_inv.save)
else:
self._add_file(image.save)
def add_array(self, data, colormap=None):
"""
Adds the data from the array as a frame to the current movie.
The array is assumed to be scaled to [0, 1].
(0, 0) lies in the upper left corner of the image.
The first axis extends toward the right, the second toward the bottom
"""
# get colormap
if colormap is None:
import matplotlib.cm as cm
colormap = cm.gray
# produce image
try:
import Image
except ImportError:
from PIL import Image
import numpy as np
grey_data = colormap(np.clip(data.T, 0, 1))
im = Image.fromarray(np.uint8(grey_data*255))
# save image
self.add_image(im)
def add_figure(self, fig=None):
""" adds the figure `fig` as a frame to the current movie """
if fig is None:
fig = plt.gcf()
if self.width is None:
dpi = None
else:
dpi = self.width/fig.get_figwidth()
# save image
if self.inverted:
invert_colors(fig)
save_function = partial(
fig.savefig,
dpi=dpi, edgecolor='none',
facecolor=invert_color(fig.get_facecolor())
)
self._add_file(save_function)
invert_colors(fig)
else:
save_function = partial(fig.savefig, dpi=dpi)
self._add_file(save_function)
def save_frames(self, filename_pattern='./frame_%09d.png', frames='all'):
""" saves the given `frames` as images using the `filename_pattern` """
if not self.recording:
raise ValueError('Movie is not initialized.')
if 'all' == frames:
frames = range(self.frame)
for f in frames:
shutil.copy(
"%s/frame_%09d.png" % (self.tempdir, f),
filename_pattern % f
)
def save(self, filename, extra_args=None):
""" convert the recorded images to a movie using ffmpeg """
if not self.recording:
raise ValueError('Movie is not initialized.')
# set parameters
if extra_args is None:
extra_args = []
if self.framerate is not None:
extra_args += ["-r", self.framerate]
if filename is None:
filename = self.filename
# construct the call to ffmpeg
# add the `-pix_fmt yuv420p` switch for compatibility reasons
# -> http://ffmpeg.org/trac/ffmpeg/wiki/x264EncodingGuide
args = ["ffmpeg"]
if extra_args:
args += extra_args
args += [
"-y", # don't ask questions
"-f", "image2", # input format
"-i", "%s/frame_%%09d.png" % self.tempdir, # input data
"-pix_fmt", "yuv420p", # pixel format for compatibility
"-b:v", "1024k", # high bit rate for good quality
filename # output file
]
# spawn the subprocess and capture its output
p = subprocess.Popen(args, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
out = p.stdout.read()
err = p.stderr.read()
# check if error occurred
if p.wait():
print(out)
print(err)
raise RuntimeError('An error occurred while producing the movie.')
# do output anyway, when verbosity is requested
if self.verbose:
print(out)
print(err)
def test_movie_making():
""" Simple test code for movie making """
try:
# try python2 version
filename = raw_input('Choose a file name: ')
except NameError:
# python3 fallback
filename = input('Choose a file name: ')
import numpy as np
# prepare data
x = np.linspace(0, 10, 100)
lines, = plt.plot(x, np.sin(x))
plt.ylim(-1, 1)
with Movie(filename=filename) as movie:
for k in range(30):
lines.set_ydata(np.sin(x + 0.1*k))
movie.add_frame()
if __name__ == "__main__":
print('This file is intended to be used as a module.')
print('This code serves as a test for the defined methods.')
test_movie_making()
| david-zwicker/python-functions | movie_making.py | Python | gpl-2.0 | 8,083 |
__author__ = 'andrucuna'
# Ball motion with an explicit timer
import simplegui
# Initialize globals
WIDTH = 600
HEIGHT = 400
BALL_RADIUS = 20
init_pos = [WIDTH / 2, HEIGHT / 2]
vel = [0, 3] # pixels per tick
time = 0
# define event handlers
def tick():
global time
time = time + 1
def draw(canvas):
# create a list to hold ball position
ball_pos = [0, 0]
# calculate ball position
ball_pos[0] = init_pos[0] + time * vel[0]
ball_pos[1] = init_pos[1] + time * vel[1]
# draw ball
canvas.draw_circle(ball_pos, BALL_RADIUS, 2, "Red", "White")
# create frame
frame = simplegui.create_frame("Motion", WIDTH, HEIGHT)
# register event handlers
frame.set_draw_handler(draw)
timer = simplegui.create_timer(100, tick)
# start frame
frame.start()
timer.start() | andrucuna/python | interactivepython-coursera/interactivepython/week4/Motion.py | Python | gpl-2.0 | 796 |
from supervisorerrormiddleware import SupervisorErrorMiddleware
import os
import sys
import paste.fixture
class DummyOutput:
def __init__(self):
self._buffer = []
def write(self, data):
self._buffer.append(data)
def flush(self):
self._buffer = []
def bad_app(environ, start_response):
if environ['PATH_INFO'] != '/good':
raise Exception("Bad Kitty")
else:
start_response("200 OK", [('Content-type', 'text/html')])
return ["Good Kitty"]
def test_without_supervisor():
old_stdout = sys.stdout
try:
sys.stdout = DummyOutput()
app = bad_app
app = SupervisorErrorMiddleware(app)
app = paste.fixture.TestApp(app)
failed = False
try:
app.get("/")
except:
failed = True
assert failed
output = "".join(sys.stdout._buffer)
sys.stdout.flush()
assert not "Bad Kitty" in output
assert not "GET" in output
response = app.get("/good")
output = "".join(sys.stdout._buffer)
sys.stdout.flush()
response.mustcontain("Good Kitty")
assert not "Bad Kitty" in output
assert not "GET" in output
finally:
sys.stdout = old_stdout
def test_with_supervisor():
#Why is there output when stdout is redirected? Because
#paste.fixture.TestApp gets around the redirection.
old_stdout = sys.stdout
try:
os.environ['SUPERVISOR_ENABLED'] = "1" #fake supervisor
sys.stdout = DummyOutput()
app = bad_app
app = SupervisorErrorMiddleware(app)
app = paste.fixture.TestApp(app)
failed = False
try:
app.get("/")
except:
failed = True
assert failed
output = "".join(sys.stdout._buffer)
sys.stdout.flush()
assert "Bad Kitty" in output
assert "GET" in output
response = app.get("/good")
output = "".join(sys.stdout._buffer)
sys.stdout.flush()
response.mustcontain("Good Kitty")
assert not "Bad Kitty" in output
assert not "GET" in output
finally:
sys.stdout = old_stdout
del os.environ['SUPERVISOR_ENABLED']
| socialplanning/SupervisorErrorMiddleware | supervisorerrormiddleware/tests/test.py | Python | gpl-2.0 | 2,244 |
import os
import sys
import time
import numpy as np
import bge.logic as GameLogic
import settings
import nicomedilib as ncl
import arduino_serial
import serial
import xinput
import random
import copy
from PIL import Image
import gnoomcomm as gc
import gnoomio as gio
import gnoomutils as gu
import chooseWalls
if settings.gratings:
import chooseWalls
import cues
if settings.cues:
import chooseCues
import cues
def init():
scene = GameLogic.getCurrentScene()
if settings.looming:
scene.replace("Looming")
GameLogic.Object = {}
print("BLENDER: GameLogic object created")
# Store visibility / position / scale of all objects
for object in scene.objects:
viskey = object.name + "_default_visible"
GameLogic.Object[viskey] = copy.deepcopy(object.visible)
poskey = object.name + "_default_position"
GameLogic.Object[poskey] = copy.deepcopy(object.localPosition)
scalekey = object.name + "_default_scale"
GameLogic.Object[scalekey] = copy.deepcopy(object.localScale)
GameLogic.Object['closed'] = False
GameLogic.Object['lapCounter'] = 0
GameLogic.Object['frameCounter'] = 0
GameLogic.setLogicTicRate(100)
GameLogic.setMaxLogicFrame(100)
GameLogic.setMaxPhysicsFrame(100)
sys.stdout.write("BLENDER: Maximum number of logic frames per render frame: %d\n" % GameLogic.getMaxLogicFrame() )
sys.stdout.write("BLENDER: Logic tic rate: %d\n" % GameLogic.getLogicTicRate() )
sys.stdout.write("BLENDER: Maximum number of physics frames per render frame: %d\n" % GameLogic.getMaxPhysicsFrame() )
sys.stdout.write("BLENDER: Physics update frequency: %d Hz\n" % GameLogic.getPhysicsTicRate() )
# open arduino and pump
try:
arduino = arduino_serial.SerialPort(settings.arduino_port, 19200)
sys.stdout.write("BLENDER: Successfully opened arduino on {0}\n".format(settings.arduino_port))
except OSError:
sys.stdout.write("BLENDER: Failed to open arduino\n")
arduino = None
GameLogic.Object['arduino'] = arduino
if arduino is not None:
arduino.write(b'd')
# Set all valves to low
arduino.write(b'6')
arduino.write(b'8')
arduino.write(b'0')
arduino.write(b'f')
try:
pumppy = serial.Serial(settings.pump_port, 19200, timeout=1)
sys.stdout.write("BLENDER: Successfully opened pump\n")
gc.setPumpVolume(pumppy, settings.reward_volume)
except:
sys.stdout.write("BLENDER: Failed to open pump\n")
pumppy = None
if settings.replay_track is not None:
fn_pos = settings.replay_track + '.position'
if not os.path.exists(fn_pos):
print("BLENDER: Could not find " + fn_pos)
settings.replay_track = None
else:
sys.path.append(os.path.expanduser("~/../cs/py2p/tools"))
import training
print("BLENDER: Reading replay track from " + fn_pos)
GameLogic.Object['replay_pos'] = training.read_pos(
fn_pos, 1e9, False, meters=False)
posy = GameLogic.Object['replay_pos'][1]
replay_time, _, _, _, _ = training.read_move(
settings.replay_track + ".move")
evlist, timeev = training.read_events(
settings.replay_track + ".events", teleport_times=None)
GameLogic.Object['replay_rewards'] = np.array([
ev.time for ev in evlist if ev.evcode == b'RE'])
GameLogic.Object['replay_rewards'] = np.sort(GameLogic.Object['replay_rewards'])
if settings.replay_rewards_shuffle:
intervals = np.diff([0] + GameLogic.Object['replay_rewards'].tolist())
intervals = np.random.permutation(intervals)
print(intervals)
GameLogic.Object['replay_rewards'] = np.cumsum(intervals)
print("Replay reward times: ", GameLogic.Object['replay_rewards'])
print("Total number of replay rewards: ", len(GameLogic.Object['replay_rewards']))
print("Total duration of replay file: ", replay_time[-1])
GameLogic.Object['nreplay'] = 0
if settings.gratings:
if not "grating1" in GameLogic.Object.keys():
GameLogic.Object["grating1"] = chooseWalls.grating(
ori=settings.verticalGratingAngle, sf=settings.verticalGratingScale)
GameLogic.Object["grating2"] = chooseWalls.grating(
ori=settings.obliqueGratingAngle, sf=settings.obliqueGratingScale)
chooseWalls.initWalls()
else:
GameLogic.Object["reward_zone_start"] = settings.reward_zone_start
GameLogic.Object["reward_zone_end"] = settings.reward_zone_end
# for wallkey in ["LW1", "RW1"]:
# chooseWalls.set_texture_buffer(
# GameLogic.Object["grating1"], wallkey)
# for wallkey in ["LW2", "RW2"]:
# chooseWalls.set_texture_buffer(
# GameLogic.Object["grating2"], wallkey)
#
if ncl.has_comedi:
print("BLENDER: Found comedi library")
gOuttrigsubdev = 2
gOuttrigchan = 0
gOutfrchan = 1
gOutleftchan = 2
gOutrightchan = 3
gOutexpchan = 4
gIntrigsubdev = 7
gIntrigchan = 0
gDevrange = 0
# open ni trigger channels
devintrigch, fdintrigch, nameintrigch = ncl.open_dev("/dev/comedi0_subd2")
devouttrigch, fdouttrigch, nameouttrigch = ncl.open_dev("/dev/comedi0_subd11")
intrigch = ncl.nichannel(devintrigch, gIntrigchan, gIntrigsubdev, fdintrigch, gDevrange)
outtrigch = ncl.nichannel(devouttrigch, gOuttrigchan, gOuttrigsubdev, fdouttrigch, gDevrange)
outfrch = ncl.nichannel(devouttrigch, gOutfrchan, gOuttrigsubdev, fdouttrigch, gDevrange)
outleftch = ncl.nichannel(devouttrigch, gOutleftchan, gOuttrigsubdev, fdouttrigch, gDevrange)
outrightch = ncl.nichannel(devouttrigch, gOutrightchan, gOuttrigsubdev, fdouttrigch, gDevrange)
outexpch = ncl.nichannel(devouttrigch, gOutexpchan, gOuttrigsubdev, fdouttrigch, gDevrange) #MC2015
ncl.init_comedi_dig(intrigch, outtrigch, outfrch, outleftch, outrightch,
outexpch #MC2015
)
else:
intrigch = None
outtrigch = None
outfrch = None
outleftch = None
outrightch = None
outexpch = None #MC2015
GameLogic.Object['intrigch'] = intrigch
GameLogic.Object['outtrigch'] = outtrigch
GameLogic.Object['outfrch'] = outfrch
GameLogic.Object['outleftch'] = outleftch
GameLogic.Object['outrightch'] = outrightch
GameLogic.Object['outexpch'] = outexpch #MC2015
GameLogic.Object['pumppy'] = pumppy
GameLogic.Object['left_on'] = False
GameLogic.Object['right_on'] = False
GameLogic.Object['file_open'] = False
GameLogic.Object['train_open'] = False
GameLogic.Object['bcstatus'] = False
gio.create_data_dir()
GameLogic.Object['time0'] = time.time()
GameLogic.Object['prevtime'] = time.time()
GameLogic.Object['nframes'] = 0
GameLogic.Object['rewcount'] = 0
GameLogic.Object['rewfail'] = 0
GameLogic.Object['puffcount'] = 0
GameLogic.Object['puffthistrial'] = 0
GameLogic.Object['isloom'] = 0
GameLogic.Object['loomcounter']=0
GameLogic.Object['totalLooms'] = 0
GameLogic.Object['loom_first_trial']=0
GameLogic.Object['rewpos'] = [0.98] # 1.0 # np.zeros((16))
GameLogic.Object['boundx'] = 8.0
GameLogic.Object['boundy'] = 158.0
GameLogic.Object['hysteresis'] = 0.5
GameLogic.Object['speed_tracker'] = np.zeros((100))
GameLogic.Object['in_running_period'] = False
GameLogic.Object['in_running_period_counter'] = 0
GameLogic.Object['minloomtrigger'] = 0
GameLogic.Object['loomtrigger'] = -1
GameLogic.Object['loomunlocked'] = False
GameLogic.Object['playThisLoom'] = False
GameLogic.Object['lapCounter'] = 0
GameLogic.Object['isRotating'] = False
GameLogic.Object['lapRotated'] = False
blenderpath = GameLogic.expandPath('//')
if not settings.cpp:
s1, conn1, addr1, p1 = gc.spawn_process("\0mouse0socket", ['python3', '%s/py/usbclient.py' % blenderpath, '0'])
s2, conn2, addr2, p2 = gc.spawn_process("\0mouse1socket", ['python3', '%s/py/usbclient.py' % blenderpath, '1'])
else:
if settings.readlib=="xinput":
mice = xinput.find_mice(model=settings.mouse)
for mouse in mice:
# xinput.set_owner(mouse) # Don't need this if using correct udev rule
xinput.switch_mode(mouse)
if settings.usezmq:
procname = 'readout_zmq'
else:
procname = 'readout'
if len(mice)>=1:
s1, conn1, addr1, p1 = \
gc.spawn_process(
"\0mouse0socket",
[('%s/cpp/generic-ev/' % blenderpath) + procname, '%d' % mice[0].evno, '0'],
usezmq=settings.usezmq)
else:
s1, conn1, addr1, p1 = None, None, None, None
if len(mice)>=3:
s2, conn2, addr2, p2 = \
gc.spawn_process(
"\0mouse1socket",
[('%s/cpp/generic-ev/readout' % blenderpath) + procname, '%d' % mice[2].evno, '1'],
usezmq=settings.usezmq)
else:
s2, conn2, addr2, p2 = None, None, None, None
elif settings.readlib=="libusb":
s1, conn1, addr1, p1 = \
gc.spawn_process("\0mouse1socket",
['%s/cpp/g500-usb/readout' % blenderpath, '1'])
s2, conn2, addr2, p2 = \
gc.spawn_process("\0mouse0socket",
['%s/cpp/g500-usb/readout' % blenderpath, '0'])
else:
s1, conn1, addr1, p1, s2, conn2, add2, p2 = \
None, None, None, None, None, None, None, None
if settings.has_fw:
if not settings.fw_local:
GameLogic.Object['fwip'] = '' #"128.40.202.203"
sfw, connfw, addrfw = gc.spawn_process_net(GameLogic.Object['fwip'])
if connfw is None:
settings.has_fw = False
else:
sys.stdout.write("BLENDER: Starting fw... ")
sys.stdout.flush()
sfw, connfw, addrfw, pfw = \
gc.spawn_process("\0fwsocket", ['%s/cpp/dc1394/dc1394' % blenderpath,], #MC2015
system=False, addenv={"SDL_VIDEO_WINDOW_POS":"\"1280,480\""})
print("done")
connfw.send(GameLogic.Object['fw_trunk'].encode('latin-1'))
gc.recv_ready(connfw)
connfw.setblocking(0)
GameLogic.Object['fwconn'] = connfw
GameLogic.Object['has_fw'] = settings.has_fw
if settings.has_usb3:
sys.stdout.write("BLENDER: Starting usb3... ")
sys.stdout.flush()
susb3, connusb3, addrusb3, pusb3 = \
gc.spawn_process(
"\0" + settings.usb3_pupil,
['{0}/cpp/usb3/arv-camera-test'.format(blenderpath),
'-n', settings.usb3_pupil], #MC2015
system=False, addenv={"SDL_VIDEO_WINDOW_POS":"\"1280,480\""})
print("done")
print("Sending usb3 file name " + GameLogic.Object['fw_trunk'])
connusb3.send(GameLogic.Object['fw_trunk'].encode('latin-1'))
gc.recv_ready(connusb3)
connusb3.setblocking(0)
GameLogic.Object['usb3conn'] = connusb3
if settings.usb3_body is not None:
s2usb3, conn2usb3, addr2usb3, p2usb3 = \
gc.spawn_process(
"\0" + settings.usb3_body,
['{0}/cpp/usb3/arv-camera-test'.format(blenderpath),
'-n', settings.usb3_body], #MC2015
system=False, addenv={"SDL_VIDEO_WINDOW_POS":"\"1280,480\""})
print("done")
print("Sending usb3 file name " + GameLogic.Object['fw_trunk'] + 'body')
conn2usb3.send((GameLogic.Object['fw_trunk'] + 'body').encode('latin-1'))
gc.recv_ready(conn2usb3)
conn2usb3.setblocking(0)
GameLogic.Object['usb3conn2'] = conn2usb3
GameLogic.Object['has_usb3'] = settings.has_usb3
if settings.has_comedi and ncl.has_comedi:
scomedi, conncomedi, addrcomedi, pcomedi = \
gc.spawn_process("\0comedisocket", ['python3', '%s/py/nicomedi.py' % blenderpath,])
conncomedi.send(blenderpath.encode('latin-1'))
gc.recv_ready(conncomedi)
conncomedi.setblocking(0)
GameLogic.Object['comediconn'] = conncomedi
if settings.has_licksensor:
slick, connlick, addrlick, plick = \
gc.spawn_process("\0licksocket", ['python3', '%s/py/licksensor.py' % blenderpath,])
connlick.send(blenderpath.encode('latin-1'))
gc.recv_ready(connlick)
connlick.setblocking(0)
GameLogic.Object['lickconn'] = connlick
if settings.has_licksensor_piezo:
slickpiezo, connlickpiezo, addrlickpiezo, plickpiezo = \
gc.spawn_process("\0lickpiezosocket", ['python3', '%s/py/licksensorpiezo.py' % blenderpath,])
connlickpiezo.send(blenderpath.encode('latin-1'))
gc.recv_ready(connlickpiezo)
connlickpiezo.setblocking(0)
GameLogic.Object['lickpiezoconn'] = connlickpiezo
if settings.cpp:
for mconn in [conn1, conn2]:
if mconn is not None:
mconn.send(b'start')
gc.recv_ready(mconn, usezmq=settings.usezmq)
if not settings.usezmq:
mconn.setblocking(0)
if len(mice):
GameLogic.Object['m1conn'] = conn1
GameLogic.Object['m2conn'] = conn2
else:
GameLogic.Object['m1conn'] = None
GameLogic.Object['m2conn'] = None
GameLogic.Object['tmprec'] = False
GameLogic.Object['trainrec'] = False
GameLogic.Object['RewardTicksCounter'] = None
GameLogic.Object['RewardChange'] = False
GameLogic.Object['WallTouchTicksCounter'] = None
GameLogic.Object['OdorTicksCounter'] = None
GameLogic.Object['piezolicks'] = 0
GameLogic.Object['piezoframes'] = 0
GameLogic.Object['piezoframepause'] = 0
GameLogic.Object['lapCounter'] = 0
scene = GameLogic.getCurrentScene()
if scene.name == "Scene":
playerName = 'MovingCube'
legName = 'LeftLeg'
elif scene.name == "Looming":
playerName = 'MovingCube.002'
legName = 'LeftLeg.002'
else:
playerName = 'MovingCube.001'
legName = 'LeftLeg.001'
rew_sensor = scene.objects[playerName]
touch_sensor = scene.objects[legName]
rew_sensor.sensors['SReward'].usePosPulseMode = True
touch_sensor.sensors['SLeftTouch'].usePosPulseMode = True
GameLogic.Object['scene_changed'] = 0
GameLogic.Object['scene_name'] = scene.name
GameLogic.Object['reset_pulse'] = False
#current injection variables
#variables for current injection - MC2015
GameLogic.Object['start_pulse_y'] = 50
GameLogic.Object['inj_amp'] = 50
GameLogic.Object['do_tbs1'] = False
GameLogic.Object['do_tbs2'] = False
gu.zeroPos()
gc.zeroPump()
| neurodroid/gnoom | py/gnoominit.py | Python | gpl-2.0 | 15,471 |
import Gears as gears
from .. import *
from .Base import *
class Solid(Base) :
def applyWithArgs(
self,
spass,
functionName,
*,
color : 'Solid pattern color, or Interactive.*'
= 'white'
) :
color = processColor(color, self.tb)
if not isGrey(color):
spass.enableColorMode()
stimulus = spass.getStimulus()
self.registerInteractiveControls(
spass, stimulus,
functionName+'_',
color = color,
)
spass.setShaderFunction( name = functionName, src = self.glslEsc( '''
vec3 @<X>@ (vec2 x, float time){
return @<X>@_color; }
''').format( X=functionName ) )
| szecsi/Gears | GearsPy/Project/Components/Pif/Solid.py | Python | gpl-2.0 | 882 |
#!/usr/bin/python
# LICENSE: GPL2
# (c) 2013 Tom Schouten <[email protected]>
# (c) 2014, Kamil Wartanowicz <[email protected]>
import logging
import os
import threading
import time
import usb
import plac
import sim_shell
import sim_ctrl_2g
import sim_ctrl_3g
import sim_reader
import sim_card
from util import types_g
from util import types
from util import hextools
ROUTER_MODE_DISABLED = 0
ROUTER_MODE_INTERACTIVE = 1
ROUTER_MODE_TELNET = 2
ROUTER_MODE_DBUS = 3
_version_ = 1.1
# SIMtrace slave commands and events, see iso7816_slave.h
CMD_SET_ATR = 0
CMD_SET_SKIP = 1
CMD_HALT = 2
CMD_POLL = 3
CMD_R_APDU = 4
# TODO: check why this event is received, at best remove it
EVT_UNKNOWN = 0
EVT_RESET = 2
EVT_C_APDU = 4
SIMTRACE_OFFLINE = 0
SIMTRACE_ONLINE = 1
MAIN_INTERFACE = 0
CTRL_INTERFACE = 1
INJECT_READY = 0
INJECT_NO_FORWARD = 1
INJECT_WITH_FORWARD = 2
INJECT_RESET = 3
TRY_ANOTHER_CARD_ON_AUTH_FAILURE = True
LOG_NONE_APDU_IN_FILE = True
class SimRouter(object):
def __init__(self,
cards,
atr=None,
type=types.TYPE_USIM,
mode=SIMTRACE_ONLINE):
self.loggingApdu = self.setupLogger()
if LOG_NONE_APDU_IN_FILE:
self.logging = self.loggingApdu
else:
self.logging = logging
self.atr = atr
self.simType = type
self.mode = mode
self.cardsDict = self.addControlCard(cards)
self.lastUpdate = 0
self.apduInjectedCard = None
self.apduInjectedData = None
self.interpreter = None
self.routerMode = ROUTER_MODE_DISABLED
if self.mode != SIMTRACE_OFFLINE:
self.dev = self.usb_find(0x03eb, 0x6119)
if self.dev is None:
self.logging.warning("Simtrace not connected!")
self.mode = SIMTRACE_OFFLINE
self.simCtrl = None
self.loop = None
self.shell = None
self.lock = threading.Lock()
self.rapduInject = None
self.inject = INJECT_READY
def addControlCard(self, cards):
cardDicts = []
for cardMain in cards:
cardCtrl = sim_card.SimCard(mode=cardMain.mode, type=self.simType)
if cardMain.mode == sim_reader.MODE_SIM_SOFT:
#TODO: try to remove
cardCtrl.simReader = cardMain.simReader
#TODO: reimplement to not copy all parameter
cardCtrl.index = cardMain.index
cardCtrl.atr = cardMain.atr
#cardCtrl.swNoError = cardMain.swNoError
cardCtrl.type = cardMain.type
cardCtrl.logicalChannelClosed = cardMain.logicalChannelClosed
# Do not apply ins and file forwarding rules on control interface.
cardCtrl.removeRoutingAttr()
cardDict = {MAIN_INTERFACE : cardMain, CTRL_INTERFACE : cardCtrl}
cardDicts.append(cardDict)
return cardDicts
def usbCtrlOut(self, req, buf):
if self.mode == SIMTRACE_OFFLINE:
return []
return self.dev.ctrl_transfer(0x40,
bRequest=req, # R-APDU
data_or_wLength=buf,
timeout=500)
def usbCtrlIn(self, req):
return self.dev.ctrl_transfer(0xC0,
bRequest=req,
data_or_wLength=512,
timeout=512)
def receiveData(self, cmd):
if self.mode == SIMTRACE_OFFLINE:
return []
try:
return self.usbCtrlIn(cmd)
except:
time.sleep(0.2)
return self.usbCtrlIn(cmd)
def sendData(self, msg):
return self.usbCtrlOut(CMD_R_APDU, msg)
def resetCards(self, soft=True):
if soft:
resetThread = ResetThread(self)
resetThread.setDaemon(True)
# Start handling C-APDUs.
resetThread.start()
else:
for cardDict in self.cardsDict:
cardDict[MAIN_INTERFACE].reset()
def receiveCommandApdu(self):
msg = []
# FIXME: This is the main event loop. Move it to top level.
msg = list(self.receiveData(CMD_POLL))
if not len(msg):
return None, None
data = None
evt = msg[0]
if evt == EVT_C_APDU:
data = msg[4:]
elif evt == EVT_RESET:
pass
elif evt == EVT_UNKNOWN:
return None, None
else:
self.loggingApdu.info("unknown event: %s\n" % hextools.bytes2hex(msg))
return (evt, data)
def sendResponseApdu(self, msg):
self.sendData(msg)
def command(self, tag, payload=[]): # dummy byte
self.loggingApdu.debug("CMD %d %s" % (tag, hextools.bytes2hex(payload)))
self.usbCtrlOut(tag, payload)
def aidCommon(self, card):
if not card.routingAttr:
return False
return set(sim_card.FILES_AID).issubset(set(card.routingAttr.filesCommon))
def getSoftCardDict(self):
for cardDict in self.cardsDict:
if cardDict[MAIN_INTERFACE].mode == sim_reader.MODE_SIM_SOFT:
return cardDict
return None
def getFileHandler(self, file):
#by default execute apdu in card 0
cards = [self.cardsDict[0][MAIN_INTERFACE]]
for cardDict in self.cardsDict:
if cardDict == self.cardsDict[0]:
#cardDict already in cards
continue
card = cardDict[MAIN_INTERFACE]
if file in card.routingAttr.filesCommon:
cards.append(card)
elif file in card.routingAttr.filesReplaced:
return [card]
return cards
def getInsHandler(self, ins, apdu):
#by default execute apdu in card 0
cards = [self.cardsDict[0][MAIN_INTERFACE]]
for cardDict in self.cardsDict:
if cardDict == self.cardsDict[0]:
#cardDict already in cards
continue
card = cardDict[MAIN_INTERFACE]
if (ins == 'GET_RESPONSE' and
card.routingAttr.getFileSelected(apdu[0]) == 'AUTH' and
'INTERNAL_AUTHENTICATE' in card.routingAttr.insReplaced):
return [card]
elif ins in card.routingAttr.insCommon:
if (ins in ['GET_RESPONSE','SELECT_FILE'] and
card.routingAttr.getFileSelected(apdu[0]) in card.routingAttr.filesReplaced):
cards.insert(0, card)
else:
cards.append(card)
elif ins in card.routingAttr.insReplaced:
if ins == 'INTERNAL_AUTHENTICATE':
card.routingAttr.setFileSelected('AUTH', apdu[0])
return [card]
return cards
def addLeftHandlers(self, cards):
for cardDict in self.cardsDict:
card = cardDict[MAIN_INTERFACE]
if card in cards:
continue
cards.append(card)
return cards
def getHandlers(self, apdu, inject=None):
cardsData = []
if inject == INJECT_NO_FORWARD:
if self.apduInjectedCard:
cardsData.append([self.apduInjectedCard, 0])
else:
cardsData.append([self.getCtrlCard(0), 0])
return cardsData
ins = types.insName(apdu)
if ins == 'SELECT_FILE':
for cardDict in self.cardsDict:
card = cardDict[MAIN_INTERFACE]
#TODO: handle read/write/update command with SFI in P1
card.routingAttr.setFileSelected(self.fileName(apdu), apdu[0])
if ins in sim_card.FILE_INS:
cards = self.getFileHandler(self.cardsDict[0][MAIN_INTERFACE].routingAttr.getFileSelected(apdu[0]))
else:
cards = self.getInsHandler(ins, apdu)
i = 0;
forwardApdu = True
for card in cards:
if i != 0:
forwardApdu = False
cardsData.append([card, forwardApdu])
i += 1
return cardsData
def handleApdu(self, cardData, apdu):
card = cardData[0]
sendData = cardData[1]
if card == None:
raise Exception("card not initialized")
ins = types.insName(apdu)
if card != self.getMainCard(0):
origApdu = apdu
if ( self.aidCommon(card) and
card.routingAttr.aidToSelect and
self.getMainCard(0).routingAttr.aidToSelect == hextools.bytes2hex(apdu) and #origin apdu is AID
int(card.routingAttr.aidToSelect[0:2], 16) == apdu[0]): #check the same class
apdu = hextools.hex2bytes(card.routingAttr.aidToSelect)
card.routingAttr.aidToSelect = None
elif ( self.aidCommon(card) and
card.routingAttr.getFileSelected(apdu[0]) == 'EF_DIR' and
ins == 'READ_RECORD' and
card.routingAttr.recordEfDirLength):
apdu[4] = card.routingAttr.recordEfDirLength
if origApdu != apdu:
self.loggingApdu.info("")
self.loggingApdu.info("*C-APDU%d: %s" %(self.getSimId(card), hextools.bytes2hex(apdu)))
if self.simType == types.TYPE_SIM and (apdu[0] & 0xF0) != 0xA0:
#force 2G on USIM cards
sw = types_g.sw.CLASS_NOT_SUPPORTED
sw1 = sw>>8
sw2 = sw & 0x00FF
responseApdu = [sw1, sw2]
elif ins == 'GET_RESPONSE' and card.routingAttr.getResponse:
responseApdu = card.routingAttr.getResponse
card.routingAttr.getResponse = None
else:
responseApdu = card.apdu(apdu)
if card != self.getMainCard(0):
if (self.aidCommon(card) and
card.routingAttr.getFileSelected(apdu[0]) == 'EF_DIR' and
ins == 'GET_RESPONSE' and
types.swNoError(responseApdu) and
len(responseApdu) > 7):
card.routingAttr.recordEfDirLength = responseApdu[7]
if (TRY_ANOTHER_CARD_ON_AUTH_FAILURE and
self.getNbrOfCards() > 1 and
card.routingAttr.getFileSelected(apdu[0]) == 'AUTH' and
types.sw(responseApdu) == types_g.sw.AUTHENTICATION_ERROR_APPLICATION_SPECIFIC):
sw1Name, swName = types.swName(types.sw(responseApdu) >> 8, types.sw(responseApdu) & 0x00FF)
self.logging.warning("Response not expected. SW1: %s, SW: %s" %(sw1Name, swName))
self.logging.warning("Change card to process AUTHENTICATION")
if card == self.getMainCard(0):
cardTmp = self.getMainCard(1)
else:
cardTmp = self.getMainCard(0)
responseApdu = cardTmp.apdu(apdu)
cardTmp.routingAttr.setFileSelected('AUTH', apdu[0])
card.routingAttr.setFileSelected(None, apdu[0])
# TODO: check if exist
cardTmp.routingAttr.insReplaced.append('INTERNAL_AUTHENTICATE')
if types.sw1(responseApdu) in [types_g.sw1.RESPONSE_DATA_AVAILABLE_2G, types_g.sw1.RESPONSE_DATA_AVAILABLE_3G]:
# cache 'GET_RESPONSE'
getResponseLength = types.sw2(responseApdu)
cla = apdu[0]
apduTmp = "%02XC00000%02X" %(cla, getResponseLength)
self.loggingApdu.info("**C-APDU%d: %s" %(self.getSimId(cardTmp), apduTmp))
cardTmp.routingAttr.getResponse = cardTmp.apdu(apduTmp)
if card.routingAttr.getFileSelected(apdu[0]) == 'EF_IMSI' and types.swNoError(responseApdu):
#cache imsi
responseData = types.responseData(responseApdu)
if ins == 'READ_BINARY' and types.p1(apdu) == 0 and types.p2(apdu) == 0:
#When P1=8X then SFI is used to select the file.
#Remove the check when SFI checking is implemented
imsi = hextools.decode_BCD(responseData)[3:]
#TODO: remove length check when name for the file comes from
#the whole path and not fid. 6f07 is also in ADF_ISIM
if len(imsi) > 10:
card.imsi = imsi
#update associated interface
if self.isCardCtrl(card):
self.getRelatedMainCard(card).imsi = imsi
else:
self.getRelatedCtrlCard(card).imsi = imsi
elif ins == 'UPDATE_BINARY':
card.imsi = None
responseApduHex = hextools.bytes2hex(responseApdu)
#example of APDU modification
if responseApduHex == "02542D4D6F62696C652E706CFFFFFFFFFF9000":
#change SPN name 'T-mobile.pl' for 'Tmobile-SPN'
responseApdu = hextools.hex2bytes("02546D6F62696C652D53504EFFFFFFFFFF9000")
if sendData:
if ((types.sw(responseApdu) == types_g.sw.NO_ERROR or
types.sw1(responseApdu) == types_g.sw1.NO_ERROR_PROACTIVE_DATA) and
self.getNbrOfCards() > 1):
# Check for pending SAT command
for cardDict in self.cardsDict:
cardTmp = cardDict[MAIN_INTERFACE]
if card == cardTmp:
continue
if set(sim_card.SAT_INS) <= set(cardTmp.routingAttr.insReplaced):
swNoError = cardTmp.swNoError
if types.unpackSw(swNoError)[0] == types_g.sw1.NO_ERROR_PROACTIVE_DATA:
#update r-apdu with proactive data information
responseApdu[-2] = swNoError >> 8
responseApdu[-1] = swNoError & 0x00FF
break
self.sendResponseApdu(responseApdu)
if card == self.getMainCard(0) or sendData:
self.pretty_apdu(apdu)
responseApduHex = hextools.bytes2hex(responseApdu)
self.loggingApdu.info("R-APDU%d: %s" %(self.getSimId(card), responseApduHex))
# gsmtap.log(apdu,responseApdu) # Uncomment for wireshark
return responseApdu
def updateHandler(self, cardData, apdu, rapdu):
if ( self.aidCommon(cardData[0]) and not
cardData[0].routingAttr.aidToSelect and
cardData[0].routingAttr.getFileSelected(apdu[0]) == 'EF_DIR' and
types.insName(apdu) == 'READ_RECORD' and
len(rapdu) > 3 and rapdu[3] != 0xFF and
types.swNoError(rapdu)):
# keep the same class - apdu[0], change length and avalue of selected AID
cardData[0].routingAttr.aidToSelect = "%02XA40404%s" %(apdu[0], hextools.bytes2hex(rapdu[3 : (rapdu[3] + 4)]))
if types.sw1(rapdu) in [types_g.sw1.RESPONSE_DATA_AVAILABLE_2G, types_g.sw1.RESPONSE_DATA_AVAILABLE_3G]:
# cache 'GET_RESPONSE'
getResponseLength = types.sw2(rapdu)
cla = apdu[0]
apdu = "%02XC00000%02X" %(cla, getResponseLength)
cardData[0].routingAttr.getResponse = cardData[0].apdu(apdu)
def tick(self):
with self.lock:
inject = INJECT_READY
evt, apdu = self.receiveCommandApdu()
if evt == EVT_RESET:
self.resetCards()
return
if not apdu:
if (not self.inject or
self.rapduInject): # Wait until rapduInject is consumed
return
else:
inject = self.inject
apdu = self.apduInjectedData
self.apduInjectedData = None
if not apdu:
raise Exception("APDU is empty")
self.lastUpdate = time.time()
cardsData = self.getHandlers(apdu, inject)
responseApdu = None
for cardData in cardsData:
if cardData == cardsData[0]:
apduHex = hextools.bytes2hex(apdu)
self.loggingApdu.info("")
self.loggingApdu.info("C-APDU%d: %s" %(self.getSimId(cardData[0]), apduHex))
responseApduTemp = self.handleApdu(cardData, apdu)
if cardData[1]:
if cardData[0] != self.getMainCard(0):
self.loggingApdu.info("*R-APDU%d" %self.getSimId(cardData[0]))
responseApdu = responseApduTemp
self.updateHandler(cardData, apdu, responseApduTemp)
if not responseApdu and not inject:
raise Exception("No response received")
if inject:
self.rapduInject = responseApduTemp
def mainloop(self):
while 1:
if self.mode == ROUTER_MODE_DBUS:
import gevent
gevent.sleep(0.001)
self.tick()
if time.time() - self.lastUpdate > 0.1:
time.sleep(0.1)
def getNbrOfCards(self):
return len(self.cardsDict)
def getSimId(self, card):
i = 0
for cardDict in self.cardsDict:
if card in [cardDict[MAIN_INTERFACE], cardDict[CTRL_INTERFACE]]:
return i
i += 1
raise Exception("Card not found")
def getCardDictFromId(self, simId):
if simId >= self.getNbrOfCards() or simId < 0:
raise Exception("simId: " + str(simId) + " not found")
return self.cardsDict[simId]
def isCardCtrl(self, card):
for cardDict in self.cardsDict:
if cardDict[CTRL_INTERFACE] == card:
return True
return False
def getMainCard(self, simId):
cardDict = self.getCardDictFromId(simId)
return cardDict[MAIN_INTERFACE]
def getCtrlCard(self, simId):
cardDict = self.getCardDictFromId(simId)
return cardDict[CTRL_INTERFACE]
def getRelatedMainCard(self, cardCtrl):
for cardDict in self.cardsDict:
if cardDict[CTRL_INTERFACE] == cardCtrl:
return cardDict[MAIN_INTERFACE]
return None
def getRelatedCtrlCard(self, cardMain):
for cardDict in self.cardsDict:
if cardDict[MAIN_INTERFACE] == cardMain:
return cardDict[CTRL_INTERFACE]
return None
def swapCards(self, simId1, simId2):
cardDict1 = self.getCardDictFromId(simId1)
cardDict2 = self.getCardDictFromId(simId2)
#with self.lock:
self.cardsDict[simId1] = cardDict2
self.cardsDict[simId2] = cardDict1
def copyFiles(self, cardMainFrom, cardMainTo, files):
simIdFrom = self.getSimId(self.getRelatedCtrlCard(cardMainFrom))
simIdTo = self.getSimId(self.getRelatedCtrlCard(cardMainTo))
self.shell.select_sim_card(simIdFrom)
fileDict = {}
for file in files:
status, data = self.shell.read(file)
self.shell.assertOk(status, data)
value = types.getDataValue(data)
fileDict.update({file : value})
self.shell.select_sim_card(simIdTo)
for fileName, value in fileDict.iteritems():
status, data = self.shell.write(fileName, value)
self.shell.assertOk(status, data)
def getATR(self):
if self.atr is not None:
return self.atr
else:
return self.getMainCard(0).getATR()
def waitInjectReady(self, timeout=15):
startTime = time.time()
while True:
with self.lock:
if self.inject == INJECT_READY and not self.rapduInject:
break
currentTime = time.time()
if currentTime - startTime > timeout: #sec
if self.rapduInject:
logging.error("RAPDU injected response not consumed")
self.logging.error("Timeout. Previous apdu injected has not finished within %ds" %timeout)
self.rapduInject = None
self.inject = INJECT_READY
break
time.sleep(0.001)
def waitRapduInject(self, timeout=30):
startTime = time.time()
while True:
with self.lock:
rapduInject = self.rapduInject
if rapduInject:
self.rapduInject = None
self.inject = INJECT_READY
return rapduInject
currentTime = time.time()
if currentTime - startTime > timeout:
self.inject = INJECT_READY
raise Exception("Timeout. No rapdu for injected data received within %ds" %timeout)
time.sleep(0.001)
def injectApdu(self, apdu, card, mode=INJECT_NO_FORWARD):
# TODO: add inject tag to logs
self.waitInjectReady()
with self.lock:
self.apduInjectedCard = card
self.apduInjectedData = hextools.hex2bytes(apdu)
self.inject = mode
return self.waitRapduInject()
def setPowerSkip(self, skip):
self.command(CMD_SET_SKIP, hextools.u32(skip))
def powerHalt(self):
self.command(CMD_HALT)
def run(self, mode=ROUTER_MODE_INTERACTIVE):
if self.loop and self.routerMode == ROUTER_MODE_DISABLED:
self.shell.updateInteractive(self.getInteractiveFromMode(mode))
self.startPlacServer(mode)
return
self.routerMode = mode
time.sleep(0.1) # Truncated logs
self.loggingApdu.info("============")
self.loggingApdu.info("== simLAB ==")
self.loggingApdu.info("== ver %s==" %_version_)
self.loggingApdu.info("============")
self.command(CMD_SET_ATR, self.getATR())
self.setPowerSkip(skip=1)
self.powerHalt()
self.loop = MainLoopThread(self)
self.loop.setDaemon(True)
# Start handling incoming phone C-APDUs.
self.loop.start()
# Default card control interface.
if self.simType == types.TYPE_SIM:
self.simCtrl = sim_ctrl_2g.SimCtrl(self)
else:
self.simCtrl = sim_ctrl_3g.SimCtrl(self)
self.simCtrl.init()
interactive = self.getInteractiveFromMode(mode)
# Plac telnet server works without interactive mode
self.shell = sim_shell.SimShell(self.simCtrl, interactive)
self.startPlacServer(mode)
def getInteractiveFromMode(self, mode):
if mode in [ROUTER_MODE_INTERACTIVE, ROUTER_MODE_DBUS]:
return True
return False
def startPlacServer(self, mode):
if mode == ROUTER_MODE_DISABLED:
return
self.interpreter = plac.Interpreter(self.shell)
if mode == ROUTER_MODE_TELNET:
self.interpreter.start_server() # Loop
elif mode == ROUTER_MODE_DBUS:
from util import dbus_ctrl
dbus_ctrl.startDbusProcess(self) # Loop
elif mode == ROUTER_MODE_INTERACTIVE:
path = self.simCtrl.getCurrentFile().path
self.interpreter.interact(prompt="\n%s>"%path)
else:
raise Exception("Unexpected mode")
def setShellPrompt(self, prompt):
if self.interpreter != None:
self.interpreter.prompt = prompt
def setupLogger(self):
logger = logging.getLogger("router")
#dont't propagate to root logger
logger.propagate=False
logger.handlers = []
consoleHandler = logging.StreamHandler()
consoleHandler.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
dir = os.path.dirname(__file__)
resultFile = dir + "/../apdu.log"
fileHandler = logging.FileHandler(resultFile, mode='w')
fileHandler.setLevel(logging.INFO)
# create formatter and add it to the handlers
consoleFormatter = logging.Formatter(fmt='%(message)s')
fileFormatter = logging.Formatter(fmt='%(asctime)s %(message)s', datefmt='%H:%M:%S')
consoleHandler.setFormatter(consoleFormatter)
fileHandler.setFormatter(fileFormatter)
# add the handlers to the logger
logger.addHandler(consoleHandler)
logger.addHandler(fileHandler)
if extHandler:
#add handler for test runner
logger.addHandler(extHandler)
return logger
def fileName(self, apdu):
if types.p1(apdu) != types.SELECT_BY_DF_NAME:
fid = types.fileId(apdu)
fid = "%04X" %fid
if fid == "7FFF":
return "ADF"
try:
fileName = self.simCtrl.simFiles.getNameFromFid(fid)
except:
#TODO: try to remove
fileName = fid
else:
# AID
fileName = hextools.bytes2hex(types.aid(apdu)) #'A000'
return fileName
def pretty_apdu(self, apdu):
str = types.insName(apdu)
if str == 'SELECT_FILE':
str += " " + self.fileName(apdu)
self.loggingApdu.info(str)
def usb_find(self, idVendor, idProduct):
LIBUSB_PATH = "/usr/lib/libusb-1.0.so"
try:
dev = usb.core.find(idVendor=idVendor, idProduct=idProduct)
except:
backend = usb.backend.libusb1.get_backend(find_library=lambda x: LIBUSB_PATH)
if not backend:
logging.error("libusb-1.0 not found")
return None
dev = usb.core.find(idVendor=idVendor, idProduct=idProduct, backend=backend)
return dev
extHandler = None
def setLoggerExtHandler(handler):
global extHandler
extHandler = handler
class MainLoopThread(threading.Thread):
def __init__(self, simRouter):
threading.Thread.__init__(self)
self.simRouter = simRouter
threading.Thread.setName(self, 'MainLoopThread')
self.__lock = threading.Lock()
def run(self):
self.__lock.acquire()
for cardDict in self.simRouter.cardsDict:
if cardDict[MAIN_INTERFACE].mode == sim_reader.MODE_SIM_SOFT:
# Set SimRouter class in SatCtrl.
card = cardDict[CTRL_INTERFACE].simReader.getHandler().getCard(cardDict[CTRL_INTERFACE].index)
card.satCtrl.setSimRouter(self.simRouter)
self.simRouter.mainloop()
self.__lock.release()
def stop(self):
self.join()
class ResetThread(threading.Thread):
def __init__(self, simRouter):
threading.Thread.__init__(self)
self.simRouter = simRouter
threading.Thread.setName(self, 'ResetThread')
self.__lock = threading.Lock()
def run(self):
self.__lock.acquire()
self.softReset()
self.__lock.release()
def softReset(self):
self.simRouter.logging.info("\n")
self.simRouter.logging.info("<- Soft reset")
for cardDict in self.simRouter.cardsDict:
if (not cardDict[MAIN_INTERFACE].routingAttr or
#skip SIM with no common instruction
cardDict[MAIN_INTERFACE].routingAttr.insCommon == [] or
not self.simRouter.simCtrl):
continue
#select MF
if self.simRouter.simType == types.TYPE_USIM:
apdu = "00A40004023F00"
else:
apdu = "A0A40000023F00"
rapdu = self.simRouter.injectApdu(apdu, cardDict[MAIN_INTERFACE], mode=INJECT_NO_FORWARD)
if not rapdu:
#Skip resetting if there is USB apdu to handle
self.simRouter.logging.info("Soft reset not completed, USB apdu ongoing")
return
# Close opened logical channel so the are not exhousted when UE
# assign new channels after SIM reset.
ctrlLogicalChannel = self.simRouter.simCtrl.logicalChannel
for channel in range(1,4):
if channel != ctrlLogicalChannel: #skip control logical channel
originChannel = 0
if self.simRouter.simType == types.TYPE_SIM:
cla = 0xA0
else:
cla = 0x00
cla = cla | (originChannel & 0x0F)
apdu = "%02X7080%02X00" %(cla, channel)
rapdu = self.simRouter.injectApdu(apdu, cardDict[MAIN_INTERFACE], mode=INJECT_NO_FORWARD)
if not rapdu:
#Skip resetting if there is USB apdu to handle
self.simRouter.logging.info("Soft reset not completed, USB apdu ongoing")
break
self.simRouter.logging.info("-> reset end")
def stop(self):
self.join()
| kamwar/simLAB | sim/sim_router.py | Python | gpl-2.0 | 28,870 |
import re
import sys
sys.path.append('..')
from src.link import Link
from src.node import Node
class Network(object):
def __init__(self, config):
self.config = config
self.nodes = {}
self.address = 1
self.build()
def build(self):
state = 'network'
with open(self.config) as f:
for line in f.readlines():
if line.startswith('#'):
continue
if line == "\n":
state = 'links'
if state == 'network':
self.create_network(line)
elif state == 'links':
self.configure_link(line)
def create_network(self, line):
fields = line.split()
if len(fields) < 2:
return
start = self.get_node(fields[0])
for i in range(1, len(fields)):
end = self.get_node(fields[i])
l = Link(self.address, start, endpoint=end)
self.address += 1
start.add_link(l)
def configure_link(self, line):
fields = line.split()
if len(fields) < 3:
return
start = self.get_node(fields[0])
l = start.get_link(fields[1])
for i in range(2, len(fields)):
if fields[i].endswith("bps"):
self.set_bandwidth(l, fields[i])
if fields[i].endswith("ms"):
self.set_delay(l, fields[i])
if fields[i].endswith("seconds"):
self.set_delay(l, fields[i])
if fields[i].endswith("pkts"):
self.set_queue(l, fields[i])
if fields[i].endswith("loss"):
self.set_loss(l, fields[i])
def get_node(self, name):
if name not in self.nodes:
self.nodes[name] = Node(name)
return self.nodes[name]
def loss(self, loss):
for node in self.nodes.values():
for link in node.links:
link.loss = loss
def set_bandwidth(self, link, rate):
numeric_rate = self.convert(rate)
if rate.endswith("Gbps"):
link.bandwidth = numeric_rate * 1000000000
elif rate.endswith("Mbps"):
link.bandwidth = numeric_rate * 1000000
elif rate.endswith("Kbps"):
link.bandwidth = numeric_rate * 1000
elif rate.endswith("bps"):
link.bandwidth = numeric_rate
def set_delay(self, link, delay):
numeric_delay = self.convert(delay)
if delay.endswith("ms"):
link.propagation = numeric_delay / 1000.0
if delay.endswith("seconds"):
link.propagation = numeric_delay
def set_queue(self, link, size):
numeric_size = self.convert(size)
if size.endswith("pkts"):
link.queue_size = numeric_size
def set_loss(self, link, loss):
numeric_loss = self.convert(loss)
if loss.endswith("loss"):
link.loss = numeric_loss
@staticmethod
def convert(value):
return float(re.sub("[^0-9.]", "", value))
| ihartung/460-Lab1 | networks/network.py | Python | gpl-2.0 | 3,070 |
from frontend import views
from rest_framework import routers
from django.conf.urls import patterns, url, include
router = routers.DefaultRouter()
router.register(r'categories', views.CategoryViewSet)
router.register(r'packages', views.PackageViewSet)
router.register(r'files', views.FileViewSet)
router.register(r'clients', views.ClientViewSet)
router.register(r'jobs', views.JobViewSet)
router.register(r'packageavailability', views.ClientPackageAvailabilityViewSet)
router.register(r'fileavailability', views.ClientFileAvailabilityViewSet)
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^login/$', views.user_login, name='user_login'),
url(r'^logout/$', views.user_logout, name='user_logout'),
url(r'^profile/$', views.user_profile, name='user_profile'),
url(r'^categories/$', views.categories, name='categories'),
url(r'^categories/add/$', views.category_add, name='category_add'),
url(r'^categories/(?P<category_name>\w+)/change/$', views.category_change,
name='category_change'),
url(r'^categories/(?P<category_name>\w+)/delete/$', views.category_delete,
name='category_delete'),
url(r'^packages/$', views.packages, name='packages'),
url(r'^packages/add/$', views.package_add, name='package_add'),
url(r'^packages/(?P<package_id>\d+)/$', views.package_view, name='package_view'),
url(r'^packages/(?P<package_id>\d+)/change/$', views.package_change, name='package_change'),
url(r'^packages/(?P<package_id>\d+)/delete/$', views.package_delete, name='package_delete'),
url(r'^clients/$', views.clients, name='clients'),
url(r'^clients/add/$', views.client_add, name='client_add'),
url(r'^clients/(?P<client_id>\d+)/change/$', views.client_change, name='client_change'),
url(r'^clients/(?P<client_id>\d+)/delete/$', views.client_delete, name='client_delete'),
url(r'^clients/(?P<client_id>\d+)/discover/$', views.client_discover, name='client_discover'),
url(r'^clients/(?P<client_id>\d+)/history/$', views.client_history, name='client_history'),
url(r'^jobs/$', views.jobs, name='jobs'),
url(r'^jobs/add/$', views.job_add, name='job_add'),
url(r'^jobs/history/$', views.job_history, name='job_history'),
url(r'^jobs/(?P<job_id>\d+)/$', views.job_view, name='job_view'),
url(r'^jobs/(?P<job_id>\d+)/delete/$', views.job_delete, name='job_delete'),
url(r'api/', include(router.urls))
)
| michael-robbins/jobqueue_frontend | frontend/urls.py | Python | gpl-2.0 | 2,971 |
from olpc import db
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80))
email = db.Column(db.String(120), unique=True)
def __init__(self, name, email):
self.name = name
self.email = email
def __repr__(self):
return '<Name %r>' % self.name
| LeotisBuchanan/olpc-datavisualization- | models.py | Python | gpl-2.0 | 341 |
#!/usr/bin/env python
import distribute_setup
# User may not have setuptools installed on their machines.
# This script will automatically install the right version from PyPI.
distribute_setup.use_setuptools()
import setuptools
setuptools.setup(
name='gae-console',
description=('Powerful Interactive Console for App Engine applications.'),
version='0.1.0',
packages=setuptools.find_packages(),
author='Dmitry Sadovnychyi',
author_email='[email protected]',
keywords=['google app engine', 'gae', 'appengine', 'console', 'terminal'],
url='https://github.com/sadovnychyi/gae-console',
license='GNU General Public License v2.0',
include_package_data=True,
exclude_package_data={'': ['README.md']},
)
| sadovnychyi/gae-console | setup.py | Python | gpl-2.0 | 723 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Unit tests for script argument utilities. """
from __future__ import print_function, unicode_literals
import pytest
import argparse
from Cerebrum.utils.scriptargs import build_callback_action
class CallbackCalled(Exception):
pass
def test_build_callback_action():
def callback(*args, **kwargs):
raise CallbackCalled
def noop(*args, **kwargs):
pass
parser = argparse.ArgumentParser()
parser.add_argument('--foo',
action=build_callback_action(callback, exit=False),
help="Foo")
parser.add_argument('--bar',
action=build_callback_action(noop, exit=True),
help="Bar")
with pytest.raises(CallbackCalled):
parser.parse_args(['this', '--foo'])
with pytest.raises(SystemExit):
parser.parse_args(['this', '--bar'])
| unioslo/cerebrum | testsuite/tests/test_core/test_utils/test_scriptargs.py | Python | gpl-2.0 | 925 |
###############################################################################
# This file is part of openWNS (open Wireless Network Simulator)
# _____________________________________________________________________________
#
# Copyright (C) 2004-2007
# Chair of Communication Networks (ComNets)
# Kopernikusstr. 16, D-52074 Aachen, Germany
# phone: ++49-241-80-27910,
# fax: ++49-241-80-22242
# email: [email protected]
# www: http://www.openwns.org
# _____________________________________________________________________________
#
# openWNS is free software; you can redistribute it and/or modify it under the
# terms of the GNU Lesser General Public License version 2 as published by the
# Free Software Foundation;
#
# openWNS 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 Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
###############################################################################
import openwns
import openwns.logger
from openwns.pyconfig import attrsetter
import openwns.interface
class NeedsFilename(openwns.interface.Interface):
@openwns.interface.abstractmethod
def setFilename(self, filename):
pass
class MeasurementSource(object):
def __init__(self):
object.__init__(self)
self.observers = []
def addObserver(self, probeBus):
self.observers.append(probeBus)
return probeBus
class ProbeBus(MeasurementSource):
def __init__(self):
MeasurementSource.__init__(self)
def observe(self, probeBus):
probeBus.addObserver(self)
return probeBus
class ProbeBusRegistry(object):
def __init__(self):
super(ProbeBusRegistry, self).__init__()
self.measurementSources = {}
self.logger = openwns.logger.Logger("WNS", "ProbeBusRegistry", True)
def getMeasurementSource(self, probeBusID):
if not self.measurementSources.has_key(probeBusID):
self.measurementSources[probeBusID] = MeasurementSource()
return self.measurementSources[probeBusID]
def removeMeasurementSource(self, probeBusID):
self.measurementSources.pop(probeBusID)
def getMeasurementSources(self):
return self.measurementSources
class PassThroughProbeBus(ProbeBus):
""" The PassThroughProbeBus always accepts and always forwards. """
nameInFactory = "PassThroughProbeBus"
def __init__(self):
ProbeBus.__init__(self)
class SettlingTimeGuardProbeBus(ProbeBus):
""" The SettlingTimeGuardProbeBus only accepts if the global settling time (transient phase)
has elapsed"""
nameInFactory = "SettlingTimeGuardProbeBus"
def __init__(self, settlingTime):
ProbeBus.__init__(self)
self.settlingTime = settlingTime
class LoggingProbeBus(ProbeBus):
""" The LoggingProbeBus always accepts and logs the message to the logging subsystem.
"""
nameInFactory = "LoggingProbeBus"
def __init__(self, probeName='', parentLogger=None):
ProbeBus.__init__(self)
if len(probeName) > 0:
probeName = '.' + probeName
self.logger = openwns.logger.Logger("WNS", "LoggingProbeBus"+probeName, True, parentLogger)
class PythonProbeBus(ProbeBus):
""" Use the PythonProbeBus to do all your probing work in python. Specify what to do
in accepts, onMeasurement, output from within your configuration file."""
nameInFactory = "PythonProbeBus"
def _dummyOnMeasurement(timestamp, value, reg):
pass
def _dummyOutput():
pass
def __init__(self, acceptsFunction, onMeasurementFunction = _dummyOnMeasurement, outputFunction = _dummyOutput):
ProbeBus.__init__(self)
self.accepts = acceptsFunction
self.onMeasurement = onMeasurementFunction
self.output = outputFunction
self.reportErrors = True
class TimeWindowProbeBus(ProbeBus):
""" Only accepts for a certain time window given by start and end time"""
nameInFactory = "TimeWindowProbeBus"
def __init__(self, start, end):
ProbeBus.__init__(self)
self.start = start
self.end = end
class TimeSeriesProbeBus(ProbeBus):
""" The LogEval ProbeBus always accepts and logs the values into a file.
"""
nameInFactory = "TimeSeriesProbeBus"
outputFilename = None
format = None
timePrecision = None
valuePrecision = None
name = None
description = None
contextKeys = None
def __init__(self, outputFilename, format, timePrecision, valuePrecision, name, desc, contextKeys):
ProbeBus.__init__(self)
self.outputFilename = outputFilename
self.format = format
self.timePrecision = timePrecision
self.valuePrecision = valuePrecision
self.name = name
self.description = desc
self.contextKeys = contextKeys
class ContextFilterProbeBus(ProbeBus):
nameInFactory = "ContextFilterProbeBus"
idName = None
idValues = None
def __init__(self, _idName, _idValues, _outputName = None):
ProbeBus.__init__(self)
self.idName = _idName
self.idValues = _idValues
class ConstantContextProvider(object):
__plugin__ = "wns.ProbeBus.ConstantContextProvider"
""" Name in the static factory """
key = None
""" The name of the context """
value = None
""" A constant integer value """
def __init__(self, key, value):
super(ConstantContextProvider, self).__init__()
self.key = key
self.value = value
class StatEvalProbeBus(ProbeBus):
nameInFactory = "StatEvalProbeBus"
statEval = None
appendFlag = None
def __init__(self, outputFilename, statEvalConfig):
ProbeBus.__init__(self)
self.outputFilename = outputFilename
self.statEval = statEvalConfig
if (statEvalConfig.appendFlag == None):
self.appendFlag = False
else:
self.appendFlag = statEvalConfig.appendFlag
class TabPar:
"""
Helper Class to configure the TableProbeBus.
Configure one of these for each dimension of your table.
Parameters:
idName: the name in the IDregistry/Context under which the
value for this axis should be searched
minimum: min value of the axis
maximum: max value of the axis
resolution: number of equidistant intervals into which the
range from min to max will be divided. Note that
the maximum value will be counted into the last interval
"""
idName = None
minimum = None
maximum = None
resolution = None
def __init__(self, idName, minimum, maximum, resolution):
self.idName = idName
self.minimum = minimum
self.maximum = maximum
self.resolution = resolution
class TableProbeBus(ProbeBus):
"""
The TableProbeBus consumes measurement values and sorts them
into n-dimensional tables of statistical evaluation objects.
Parameters:
axisParams: list of TabPar objecst, one for each dimension of the desired table
outputFilename: base name of the output files produced by the TableProbeBus
evals: list of strings with the requested statistics, possible values are:
'mean', 'variance', 'relativeVariance', 'coeffOfVariation', 'M2', 'M3', 'Z3',
'skewness', 'deviation', 'relativeDeviation', 'trials', 'min', 'max'
formats: list of strings with the requested output formats, possible values are:
'HumanReadable', 'PythonReadable', 'MatlabReadable', 'MatlabReadableSparse'
"""
nameInFactory = "TableProbeBus"
axisParams = None
outputFilename = None
evals = None
formats = None
def __init__(self, axisParams, outputFilename, evals = ['mean'], formats = ['HumanReadable']):
ProbeBus.__init__(self)
self.axisParams = axisParams
self.outputFilename = outputFilename
self.evals = list(set(evals)) # filter out potential duplicates
self.formats = list(set(formats)) # filter out potential duplicates
class TextProbeBus(ProbeBus):
"""
Wrapper for a ProbeText StatEval
"""
nameInFactory = "TextProbeBus"
key = None
outputFilename = None
evalConfig = None
writeHeader = None
prependSimTimeFlag = None
simTimePrecision = None
simTimeWidth = None
skipInterval = None
def __init__(self, outputFilename, key, description):
ProbeBus.__init__(self)
self.key = key
self.outputFilename = outputFilename
self.writeHeader = True
self.prependSimTimeFlag = True
self.simTimePrecision = 7
self.simTimeWidth = 10
self.skipInterval = 0
self.isJSON = False
class JSONProbeBus(TextProbeBus):
def __init__(self, name, key, description):
TextProbeBus.__init__(self, name, key, description)
self.isJSON = True | creasyw/IMTAphy | framework/library/PyConfig/openwns/probebus.py | Python | gpl-2.0 | 9,523 |
#!/usr/bin/env python2.6
from BaseHTTPServer import HTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
import cgi
import SocketServer
import ssl
import re
import setproctitle
import others.dict2xml as dict2xml
import sober.config
import sober.settings
import sober.rule
__version__ = 'Sober HTTP/1.0'
__service__ = 'sober'
class WSHandler(SimpleHTTPRequestHandler):
value = None
def load_blacklist(self):
return self.settings.get_blacklist()
def load_whitelist(self):
return {'item': self.value}
def load_settings(self):
return self.settings.get()
def return_error(self):
return 'error'
def do_POST(self):
self.do_GET()
def do_GET(self):
try:
path = self.path.strip().split('/')
if len(path) > 5 and self.command == 'GET':
self.value = path[5]
self.object_type = path[2]
resource = path[3]
resource = 'self.do_'+ resource.upper() + '()'
response = eval(resource)
self.send_ok_response(self.to_xml(response, resource))
elif self.command == 'POST':
self.action = path[3]
resource = path[2]
resource = 'self.do_'+ resource.upper() + '()'
response = eval(resource)
self.send_ok_response(self.to_xml(response, resource))
else:
self.send_ok_response(self.to_xml(self.error_data('missing_arguments'), 'webservices'))
except Exception, e:
self.send_ok_response(self.to_xml(self.error_data(str(e)), resource))
def do_SETTINGS(self):
settings = sober.settings.Settings().get(self.object_type, self.value)
if type(settings).__name__ == 'instance':
response = {'settings': {
'type': self.object_type,
'name': settings.get_cn()[0],
'surename': settings.get_sn()[0],
'uid': settings.get_uid()[0],
'homeDirectory': settings.get_homeDirectory()[0],
'mail': settings.get_mail()[0],
'soberMailConditions': settings.get_soberMailConditions(),
'soberMailVirusCheck': settings.get_soberMailVirusCheck()[0],
'soberMailVirusAction': settings.get_soberMailVirusAction()[0],
'soberMailSpamCheck': settings.get_soberMailSpamCheck()[0],
'soberMailSpamKillLevel': settings.get_soberMailSpamKillLevel()[0],
'soberMailSpamTagLevel': settings.get_soberMailSpamTagLevel()[0],
'soberMailSpamTag2Level': settings.get_soberMailSpamTag2Level()[0],
}
}
return response
return self.error_data('not_found')
def do_BLACKLIST(self):
settings = sober.settings.Settings().get(self.object_type, self.value)
rules = settings.get_soberMailRule()
blacklist = {}
for rule in rules:
if re.search("blacklist[0-9]+", rule[1]['cn'][0]):
i = 0
for cond in rule[1]['soberMailRuleCondition']:
cond = eval(cond)
blacklist['item' + str(i)] = cond[0]['From']
i = i + 1
response = {'blacklist': {'from': blacklist } }
return response
return self.error_data('not_found')
def do_WHITELIST(self):
settings = sober.settings.Settings().get(self.object_type, self.value)
try:
rules = settings.get_soberMailRule()
except AttributeError:
return self.error_data('not_found')
whitelist = {}
for rule in rules:
if re.search("whitelist[0-9]+", rule[1]['cn'][0]):
i = 0
for cond in rule[1]['soberMailRuleCondition']:
cond = eval(cond)
for addr in cond[0]['From']:
whitelist['item' + str(i)] = addr
i = i + 1
response = {'whitelist': {'from': whitelist } }
return response
return self.error_data('not_found')
def do_RULE(self):
# POST
if self.command == 'POST':
postvars = None
ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
length = int(self.headers.getheader('content-length'))
data = self.rfile.read(length)
if ctype == 'multipart/form-data':
postvars = cgi.parse_multipart(data, pdict)
elif ctype == 'application/x-www-form-urlencoded':
postvars = cgi.parse_qs(data, keep_blank_values=1)
name = postvars['name'][0]
direction = tuple(postvars['direction'])
sentence = {}
items = {}
conditions = {}
for key, val in postvars.iteritems():
reg = re.search(r'(item|condition)\[(.*)\]', key)
if reg:
i = int(reg.group(2))
if reg.group(1).strip() == 'item':
items[i] = tuple(val)
elif reg.group(1) == 'condition':
try:
parts = val[0].split(':')
conditions[i] = {parts[0]: { parts[1]: None}}
except:
conditions[i] = {val[0]: None}
temp = {}
for key, val in conditions.iteritems():
for skey, sval in val.iteritems():
if type(sval).__name__ == 'dict':
temp[skey] = {sval.keys()[0]: ('in', items[key])}
else:
temp[skey] = ('in', items[key])
sobermailrulecondition = '(%s)' % str(temp)
return {'rule': { 'name': name, 'directions': direction, 'conditions': sobermailrulecondition } }
# GET
rule = sober.rule.Rule().get(self.value)
name = rule.get_cn()[0]
directions = eval(rule.get_soberMailRuleDirection()[0])
actions = {}
conditions = {}
i = 0
for action in eval(rule.get_soberMailRuleAction()[0]):
actions['action' + str(i)] = action
i = i + 1
i = 0
x = 0
for condition in rule.get_soberMailRuleCondition():
cond = eval(condition)[0]
rtype = cond.keys()[0]
if not rtype in conditions:
conditions[rtype] = {}
if type(cond[rtype]).__name__ == 'tuple':
items = {}
if len(cond[rtype]) > 2 :
x = 0
for item in cond[rtype]:
items['item'+ str(x)] = item
x = x + 1
conditions[rtype] = items
elif len(cond[rtype]) == 1:
x = 0
for item in cond[rtype]:
items['item'+ str(x)] = item
x = x + 1
conditions[rtype] = items
else:
op = cond[rtype][0]
items = {}
x = 0
for item in cond[rtype][1]:
items['word'+ str(x)] = item
x = x + 1
conditions[rtype][op] = items
else:
for item in cond[rtype].iteritems():
if item[0] not in conditions[rtype]:
x = 0
conditions[rtype][item[0]] = {}
for word in item[1][1]:
if item[1][0] not in conditions[rtype][item[0]]:
conditions[rtype][item[0]][item[1][0]] = {}
conditions[rtype][item[0]][item[1][0]]['word' + str(x)] = word
x = x + 1
# end main conditions loop
i = i + 1
drt = {}
x = 0
for direction in directions:
drt['direction' + str(x)] = direction
response = {'rule': {'name': name, 'directions': drt, 'conditions': conditions, 'actions': actions } }
return response
def send_ok_response(self, data):
self.send_response(200)
self.send_header('Content-type','text/xml;')
self.end_headers()
self.wfile.write(data)
def to_xml(self, data, name):
pre = '<?xml version="1.0" encoding="UTF-8"?>\n'
xml = dict2xml.dict2Xml({'sober': data}, pre)
return xml
def error_data(self, error):
data = {'response': {'attribute': self.value, 'error': error.upper()} }
return data
class WSServer(SocketServer.ThreadingMixIn, HTTPServer): pass
if __name__ == 'webservice':
config = sober.config.Config()
cfg = config.get_config()
server_address = (cfg.get(__name__, 'listen_address'), int(cfg.get(__name__,'listen_port')))
httpd = WSServer(server_address, WSHandler)
httpd.socket = ssl.wrap_socket(httpd.socket, certfile=cfg.get(__name__, 'ssl_certificate'), server_side=True, ssl_version=ssl.PROTOCOL_SSLv23)
setproctitle.setproctitle('sober (%s: SSL listening)' % (__name__))
httpd.serve_forever()
| theflockers/sober-filter | programs/webservice/__init__.py | Python | gpl-2.0 | 9,399 |
__author__ = 'eduardoluz'
| luzeduardo/antonov225 | flyer/flyerapp/templatetags/__init__.py | Python | gpl-2.0 | 26 |
#
# Copyright 2011-2017 Red Hat, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#
# Refer to the README and COPYING files for full details of the license
#
"""
hooking - various stuff useful when writing vdsm hooks
A vm hook expects domain xml in a file named by an environment variable called
_hook_domxml. The hook may change the xml, but the "china store rule" applies -
if you break something, you own it.
before_migration_destination hook receives the xml of the domain from the
source host. The xml of the domain at the destination will differ in various
details.
Return codes:
0 - the hook ended successfully.
1 - the hook failed, other hooks should be processed.
2 - the hook failed, no further hooks should be processed.
>2 - reserved
"""
from vdsm import hooks
import json
import os
import sys
from xml.dom import minidom
from vdsm.commands import execCmd
from vdsm.common.conv import tobool
# make pyflakes happy
execCmd
tobool
def read_domxml():
with open(os.environ['_hook_domxml']) as f:
return minidom.parseString(f.read())
def write_domxml(domxml):
with open(os.environ['_hook_domxml'], 'w') as f:
f.write(domxml.toxml(encoding='utf-8'))
def read_json():
with open(os.environ['_hook_json']) as f:
return json.loads(f.read())
def write_json(data):
with open(os.environ['_hook_json'], 'w') as f:
f.write(json.dumps(data))
def log(message):
sys.stderr.write(message + '\n')
def exit_hook(message, return_code=2):
"""
Exit the hook with a given message, which will be printed to the standard
error stream. A newline will be printed at the end.
The default return code is 2 for signaling that an error occurred.
"""
sys.stderr.write(message + "\n")
sys.exit(return_code)
def load_vm_launch_flags_from_file(vm_id):
return hooks.load_vm_launch_flags_from_file(vm_id)
def dump_vm_launch_flags_to_file(vm_id, flags):
hooks.dump_vm_launch_flags_to_file(vm_id, flags)
| EdDev/vdsm | vdsm/hooking.py | Python | gpl-2.0 | 2,647 |
#
# Copyright 2016-2017 Red Hat, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#
# Refer to the README and COPYING files for full details of the license
#
from __future__ import absolute_import
import os
import six
from nose.plugins.attrib import attr
from vdsm.network import errors as ne
from vdsm.network.link import iface as link_iface
from .netfunctestlib import NetFuncTestCase, NOCHK, SetupNetworksError
from .nettestlib import dummy_device, dummy_devices
from .nmnettestlib import iface_name, nm_connections, is_networkmanager_running
NETWORK_NAME = 'test-network'
NET_1 = NETWORK_NAME + '1'
NET_2 = NETWORK_NAME + '2'
VLANID = 100
class NetworkBasicTemplate(NetFuncTestCase):
__test__ = False
def test_add_net_based_on_nic(self):
with dummy_device() as nic:
NETCREATE = {NETWORK_NAME: {'nic': nic, 'switch': self.switch}}
with self.setupNetworks(NETCREATE, {}, NOCHK):
self.assertNetwork(NETWORK_NAME, NETCREATE[NETWORK_NAME])
def test_remove_net_based_on_nic(self):
with dummy_device() as nic:
NETCREATE = {NETWORK_NAME: {'nic': nic, 'switch': self.switch}}
NETREMOVE = {NETWORK_NAME: {'remove': True}}
with self.setupNetworks(NETCREATE, {}, NOCHK):
self.setupNetworks(NETREMOVE, {}, NOCHK)
self.assertNoNetwork(NETWORK_NAME)
def test_add_bridged_net_twice(self):
self._test_add_net_twice(bridged=True)
def test_add_bridgeless_net_twice(self):
self._test_add_net_twice(bridged=False)
def test_add_bridgeless_net_missing_nic_fails(self):
self._test_add_net_missing_nic_fails(bridged=False)
def test_add_bridged_net_missing_nic_fails(self):
self._test_add_net_missing_nic_fails(bridged=True)
def test_remove_missing_net_fails(self):
NETREMOVE = {NETWORK_NAME: {'remove': True}}
with self.assertRaises(SetupNetworksError) as cm:
with self.setupNetworks(NETREMOVE, {}, NOCHK):
pass
self.assertEqual(cm.exception.status, ne.ERR_BAD_BRIDGE)
def test_add_net_based_on_vlan(self):
with dummy_device() as nic:
NETCREATE = {NETWORK_NAME: {'nic': nic, 'vlan': VLANID,
'switch': self.switch}}
with self.setupNetworks(NETCREATE, {}, NOCHK):
self.assertNetwork(NETWORK_NAME, NETCREATE[NETWORK_NAME])
def test_remove_net_based_on_vlan(self):
with dummy_device() as nic:
NETCREATE = {NETWORK_NAME: {'nic': nic, 'vlan': VLANID,
'switch': self.switch}}
NETREMOVE = {NETWORK_NAME: {'remove': True}}
with self.setupNetworks(NETCREATE, {}, NOCHK):
self.setupNetworks(NETREMOVE, {}, NOCHK)
self.assertNoNetwork(NETWORK_NAME)
self.assertNoVlan(nic, VLANID)
def test_add_bridged_net_with_multiple_vlans_over_a_nic(self):
self._test_add_net_with_multiple_vlans_over_a_nic(bridged=True)
def test_add_bridgeless_net_with_multiple_vlans_over_a_nic(self):
self._test_add_net_with_multiple_vlans_over_a_nic(bridged=False)
def test_add_bridged_vlaned_and_non_vlaned_nets_same_nic(self):
self._test_add_vlaned_and_non_vlaned_nets_same_nic(bridged=True)
def test_add_bridgeless_vlaned_and_non_vlaned_nets_same_nic(self):
self._test_add_vlaned_and_non_vlaned_nets_same_nic(bridged=False)
def test_add_multiple_bridged_nets_on_the_same_nic_fails(self):
self._test_add_multiple_nets_fails(bridged=True)
def test_add_multiple_bridgeless_nets_on_the_same_nic_fails(self):
self._test_add_multiple_nets_fails(bridged=False)
def test_add_identical_vlan_id_bridged_nets_same_nic_fails(self):
self._test_add_multiple_nets_fails(bridged=True, vlan_id=VLANID)
def test_add_identical_vlan_id_bridgeless_nets_same_nic_fails(self):
self._test_add_multiple_nets_fails(bridged=False, vlan_id=VLANID)
def test_add_identical_vlan_id_bridged_nets_with_two_nics(self):
self._test_add_identical_vlan_id_nets_with_two_nics(bridged=True)
def test_add_identical_vlan_id_bridgeless_nets_with_two_nics(self):
self._test_add_identical_vlan_id_nets_with_two_nics(bridged=False)
def _test_add_net_with_multiple_vlans_over_a_nic(self, bridged):
VLAN_COUNT = 3
with dummy_device() as nic:
netsetup = {}
for tag in range(VLAN_COUNT):
netname = '{}{}'.format(NETWORK_NAME, tag)
netsetup[netname] = {'vlan': tag,
'nic': nic,
'switch': self.switch,
'bridged': bridged}
with self.setupNetworks(netsetup, {}, NOCHK):
for netname, netattrs in six.viewitems(netsetup):
self.assertNetwork(netname, netattrs)
def _test_add_vlaned_and_non_vlaned_nets_same_nic(self, bridged):
with dummy_device() as nic:
net_1_attrs = self._create_net_attrs(nic, bridged)
net_2_attrs = self._create_net_attrs(nic, bridged, VLANID)
self._assert_nets(net_1_attrs, net_2_attrs)
def _test_add_multiple_nets_fails(self, bridged, vlan_id=None):
with dummy_device() as nic:
net_1_attrs = net_2_attrs = self._create_net_attrs(
nic, bridged, vlan_id)
with self.setupNetworks({NET_1: net_1_attrs}, {}, NOCHK):
with self.assertRaises(SetupNetworksError) as cm:
with self.setupNetworks({NET_2: net_2_attrs}, {}, NOCHK):
pass
self.assertEqual(cm.exception.status, ne.ERR_BAD_PARAMS)
def _test_add_identical_vlan_id_nets_with_two_nics(self, bridged):
with dummy_devices(2) as (nic_1, nic_2):
net_1_attrs = self._create_net_attrs(nic_1, bridged, VLANID)
net_2_attrs = self._create_net_attrs(nic_2, bridged, VLANID)
self._assert_nets(net_1_attrs, net_2_attrs)
def _test_add_net_twice(self, bridged):
with dummy_device() as nic:
NETCREATE = {NETWORK_NAME: {'nic': nic,
'bridged': bridged,
'switch': self.switch}}
with self.setupNetworks(NETCREATE, {}, NOCHK):
self.setupNetworks(NETCREATE, {}, NOCHK)
self.assertNetwork(NETWORK_NAME, NETCREATE[NETWORK_NAME])
def _test_add_net_missing_nic_fails(self, bridged):
NETCREATE = {NETWORK_NAME: {'nic': 'missing_nic',
'bridged': bridged,
'switch': self.switch}}
with self.assertRaises(SetupNetworksError) as cm:
with self.setupNetworks(NETCREATE, {}, NOCHK):
pass
self.assertEqual(cm.exception.status, ne.ERR_BAD_NIC)
def _assert_nets(self, net_1_attrs, net_2_attrs):
with self.setupNetworks({NET_1: net_1_attrs}, {}, NOCHK):
with self.setupNetworks({NET_2: net_2_attrs}, {}, NOCHK):
self.assertNetwork(NET_1, net_1_attrs)
self.assertNetwork(NET_2, net_2_attrs)
def _create_net_attrs(self, nic, bridged, vlan_id=None):
attrs = {'nic': nic,
'bridged': bridged,
'switch': self.switch}
if vlan_id is not None:
attrs['vlan'] = vlan_id
return attrs
@attr(type='functional', switch='legacy')
class NetworkBasicLegacyTest(NetworkBasicTemplate):
__test__ = True
switch = 'legacy'
NET_CONF_DIR = '/etc/sysconfig/network-scripts/'
NET_CONF_PREF = NET_CONF_DIR + 'ifcfg-'
def test_add_net_based_on_device_with_non_standard_ifcfg_file(self):
if is_networkmanager_running():
self.skipTest('NetworkManager is running.')
with dummy_device() as nic:
NETCREATE = {NETWORK_NAME: {'nic': nic, 'switch': self.switch}}
NETREMOVE = {NETWORK_NAME: {'remove': True}}
with self.setupNetworks(NETCREATE, {}, NOCHK):
self.setupNetworks(NETREMOVE, {}, NOCHK)
self.assertNoNetwork(NETWORK_NAME)
nic_ifcfg_file = self.NET_CONF_PREF + nic
self.assertTrue(os.path.exists(nic_ifcfg_file))
nic_ifcfg_badname_file = nic_ifcfg_file + 'tail123'
os.rename(nic_ifcfg_file, nic_ifcfg_badname_file)
# Up until now, we have set the test setup, now start the test.
with self.setupNetworks(NETCREATE, {}, NOCHK):
self.assertNetwork(NETWORK_NAME, NETCREATE[NETWORK_NAME])
self.assertTrue(os.path.exists(nic_ifcfg_file))
self.assertFalse(os.path.exists(nic_ifcfg_badname_file))
@attr(type='functional', switch='ovs')
class NetworkBasicOvsTest(NetworkBasicTemplate):
__test__ = True
switch = 'ovs'
@attr(type='functional', switch='legacy')
class NetworkManagerLegacyTest(NetFuncTestCase):
switch = 'legacy'
def setUp(self):
if not is_networkmanager_running():
self.skipTest('NetworkManager is not running.')
self.iface = iface_name()
def tearDown(self):
# The bond was acquired, therefore VDSM needs to clean it.
BONDREMOVE = {self.iface: {'remove': True}}
self.setupNetworks({}, BONDREMOVE, NOCHK)
def test_add_net_based_on_device_with_multiple_nm_connections(self):
IPv4_ADDRESS = '192.0.2.1'
NET = {NETWORK_NAME: {'bonding': self.iface, 'switch': self.switch}}
with dummy_devices(1) as nics:
with nm_connections(
self.iface, IPv4_ADDRESS, con_count=3, slaves=nics):
with self.setupNetworks(NET, {}, NOCHK):
self.assertNetwork(NETWORK_NAME, NET[NETWORK_NAME])
def test_add_net_based_on_existing_vlan_bond_nm_setup(self):
vlan_id = '101'
NET = {NETWORK_NAME: {'bonding': self.iface, 'vlan': int(vlan_id),
'switch': self.switch}}
with dummy_devices(1) as nics:
with nm_connections(
self.iface, ipv4addr=None, vlan=vlan_id, slaves=nics):
bond_hwaddress = link_iface.mac_address(self.iface)
vlan_iface = '.'.join([self.iface, vlan_id])
vlan_hwaddress = link_iface.mac_address(vlan_iface)
self.assertEqual(vlan_hwaddress, bond_hwaddress)
with self.setupNetworks(NET, {}, NOCHK):
self.assertNetwork(NETWORK_NAME, NET[NETWORK_NAME])
# Check if the mac has been preserved.
bridge_hwaddress = link_iface.mac_address(NETWORK_NAME)
self.assertEqual(vlan_hwaddress, bridge_hwaddress)
| EdDev/vdsm | tests/network/func_net_basic_test.py | Python | gpl-2.0 | 11,637 |
"""
WSGI config for yookan_todo project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'yookan_todo.settings')
application = get_wsgi_application()
| ankitjavalkar/algosutra | yookan_todo_proj/yookan_todo/yookan_todo/wsgi.py | Python | gpl-2.0 | 399 |
#********************************************************************************
#* Dionaea
#* - catches bugs -
#*
#*
#*
#* Copyright (C) 2010 Markus Koetter & Tan Kean Siong
#* Copyright (C) 2009 Paul Baecher & Markus Koetter & Mark Schloesser
#*
#* This program is free software; you can redistribute it and/or
#* modify it under the terms of the GNU General Public License
#* as published by the Free Software Foundation; either version 2
#* of the License, or (at your option) any later version.
#*
#* This program is distributed in the hope that it will be useful,
#* but WITHOUT ANY WARRANTY; without even the implied warranty of
#* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#* GNU General Public License for more details.
#*
#* You should have received a copy of the GNU General Public License
#* along with this program; if not, write to the Free Software
#* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#*
#*
#* contact [email protected]
#*
#*******************************************************************************/
import logging
import os
import imp
from dionaea.core import g_dionaea
# service imports
import dionaea.tftp
import dionaea.cmd
import dionaea.emu
import dionaea.store
import dionaea.test
import dionaea.ftp
logger = logging.getLogger('ihandlers')
logger.setLevel(logging.DEBUG)
# reload service imports
#imp.reload(dionaea.tftp)
#imp.reload(dionaea.ftp)
#imp.reload(dionaea.cmd)
#imp.reload(dionaea.emu)
#imp.reload(dionaea.store)
# global handler list
# keeps a ref on our handlers
# allows restarting
global g_handlers
def start():
logger.warn("START THE IHANDLERS")
for i in g_handlers:
method = getattr(i, "start", None)
if method != None:
method()
def new():
global g_handlers
g_handlers = []
if "hpfeeds" in g_dionaea.config()['modules']['python']['ihandlers']['handlers'] and 'hpfeeds' in g_dionaea.config()['modules']['python']:
import dionaea.hpfeeds
for client in g_dionaea.config()['modules']['python']['hpfeeds']:
conf = g_dionaea.config()['modules']['python']['hpfeeds'][client]
x = dionaea.hpfeeds.hpfeedihandler(conf)
g_handlers.append(x)
if "ftpdownload" in g_dionaea.config()['modules']['python']['ihandlers']['handlers']:
import dionaea.ftp
g_handlers.append(dionaea.ftp.ftpdownloadhandler('dionaea.download.offer'))
if "tftpdownload" in g_dionaea.config()['modules']['python']['ihandlers']['handlers']:
g_handlers.append(dionaea.tftp.tftpdownloadhandler('dionaea.download.offer'))
if "emuprofile" in g_dionaea.config()['modules']['python']['ihandlers']['handlers']:
g_handlers.append(dionaea.emu.emuprofilehandler('dionaea.module.emu.profile'))
if "cmdshell" in g_dionaea.config()['modules']['python']['ihandlers']['handlers']:
g_handlers.append(dionaea.cmd.cmdshellhandler('dionaea.service.shell.*'))
if "store" in g_dionaea.config()['modules']['python']['ihandlers']['handlers']:
g_handlers.append(dionaea.store.storehandler('dionaea.download.complete'))
if "uniquedownload" in g_dionaea.config()['modules']['python']['ihandlers']['handlers']:
g_handlers.append(dionaea.test.uniquedownloadihandler('dionaea.download.complete.unique'))
if "surfids" in g_dionaea.config()['modules']['python']['ihandlers']['handlers']:
import dionaea.surfids
g_handlers.append(dionaea.surfids.surfidshandler('*'))
if "logsql" in g_dionaea.config()['modules']['python']['ihandlers']['handlers']:
import dionaea.logsql
g_handlers.append(dionaea.logsql.logsqlhandler("*"))
if "p0f" in g_dionaea.config()['modules']['python']['ihandlers']['handlers']:
import dionaea.p0f
g_handlers.append(dionaea.p0f.p0fhandler(g_dionaea.config()['modules']['python']['p0f']['path']))
if "logxmpp" in g_dionaea.config()['modules']['python']['ihandlers']['handlers']:
import dionaea.logxmpp
from random import choice
import string
for client in g_dionaea.config()['modules']['python']['logxmpp']:
conf = g_dionaea.config()['modules']['python']['logxmpp'][client]
if 'resource' in conf:
resource = conf['resource']
else:
resource = ''.join([choice(string.ascii_letters) for i in range(8)])
print("client %s \n\tserver %s:%s username %s password %s resource %s muc %s\n\t%s" % (client, conf['server'], conf['port'], conf['username'], conf['password'], resource, conf['muc'], conf['config']))
x = dionaea.logxmpp.logxmpp(conf['server'], int(conf['port']), conf['username'], conf['password'], resource, conf['muc'], conf['config'])
g_handlers.append(x)
if "nfq" in g_dionaea.config()['modules']['python']['ihandlers']['handlers']:
import dionaea.nfq
g_handlers.append(dionaea.nfq.nfqhandler())
if "virustotal" in g_dionaea.config()['modules']['python']['ihandlers']['handlers']:
import dionaea.virustotal
g_handlers.append(dionaea.virustotal.virustotalhandler('*'))
if "mwserv" in g_dionaea.config()['modules']['python']['ihandlers']['handlers']:
import dionaea.mwserv
g_handlers.append(dionaea.mwserv.mwservhandler('*'))
if "submit_http" in g_dionaea.config()['modules']['python']['ihandlers']['handlers']:
import dionaea.submit_http
g_handlers.append(dionaea.submit_http.handler('*'))
if "fail2ban" in g_dionaea.config()['modules']['python']['ihandlers']['handlers']:
import dionaea.fail2ban
g_handlers.append(dionaea.fail2ban.fail2banhandler())
def stop():
global g_handlers
for i in g_handlers:
logger.debug("deleting %s" % str(i))
i.stop()
del i
del g_handlers
| chenjj/dionaea | modules/python/scripts/ihandlers.py | Python | gpl-2.0 | 5,570 |
#
# This is a parser that generates the document tree for you.
#
# To use this parser, create an instance of XElementParser:
# parser = saxexts.make_parser()
# xp = XElementParser(parser)
#
# If you have defined classes in the current environment, you might want ot
# pass this environment *to* the parser, so your classes will be created as
# tree nodes instead of the default (base) XElement class instances:
#
#
# def MyElementClass1(XElement): ...
# def MyElementClass2(XElement): ...
# ...
#
# parser = saxexts.make_parser()
# xp = XElementParser(parser, vars())
#
# Once your parser is constructed, you can parse one or more documents as
# follows:
# doc_list = ['f1','f2','f3']
# -or-
# doc_list = ['url1','url2','url3']
#
# for doc in doc_list:
# doc_tree = xp.process(doc)
# print doc_tree.toXML()
import string
import sys
import types
from xml.sax import saxexts
from xml.sax import saxlib
from xelement import XElement, XTreeHandler
class XElementParser:
def __init__(self, outer_env={}, parser=None):
if parser == None:
self.parser = saxexts.XMLValParserFactory.make_parser()
else:
self.parser = parser
self.parser_error_handler = ErrorPrinter()
self.parser.setErrorHandler(self.parser_error_handler)
self.xth = XTreeHandler(IgnoreWhiteSpace='yes',
RemoveWhiteSpace='yes',
CreateElementMap='yes',
RequireUserClasses='yes')
for x in outer_env.keys():
if type(outer_env[x]) == types.ClassType or isinstance(x, object):
self.xth.registerElementClass(outer_env[x], x)
self.parser.setDocumentHandler(self.xth)
def process(self, document_uri):
Ok=None
try:
self.parser_error_handler.reset()
self.parser.parse(document_uri)
if self.parser_error_handler.has_errors():
raise "validation failed"
return self.xth.getDocument().getChild()
except IOError,e:
print "\nI/O Error: " + document_uri + ": " + str(e)
except saxlib.SAXException,e:
print "\nParse Error: " + document_uri + ": " + str(e)
class ErrorPrinter:
"A simple class that just prints error messages to standard out."
def __init__(self):
self.error_count = 0
def reset(self):
self.error_count = 0
def has_errors(self):
return self.error_count
def warning(self, exception):
print "Warning: %s %s" % (str(exception), exception.getMessage())
sys.exit(1)
def error(self, exception):
self.error_count = self.error_count + 1
print "Error: %s %s" % (str(exception), exception.getMessage())
def fatalError(self, exception):
self.error_count = self.error_count + 1
print "Fatal Error: %s %s" % (str(exception), exception.getMessage())
| aarestad/gradschool-stuff | xml-class/python-xml/JobMarkupLanguage/xparser.py | Python | gpl-2.0 | 2,877 |
#!bin/python
# TSV to Dublin Core/McMaster Repository conversion tool
# Matt McCollow <[email protected]>, 2011
# Nick Ruest <[email protected]>, 2011
from DublinCore import DublinCore
import csv
from sys import argv
from xml.dom.minidom import Document
from os.path import basename
DC_NS = 'http://purl.org/dc/elements/1.1/'
XSI_NS = 'http://www.w3.org/2001/XMLSchema-instance'
MACREPO_NS = 'http://repository.mcmaster.ca/schema/macrepo/elements/1.0/'
class TabFile(object):
""" A dialect for the csv.DictReader constructor """
delimiter = '\t'
def parse(fn):
""" Parse a TSV file """
try:
fp = open(fn)
fields = fp.readline().rstrip('\n').split('\t')
tsv = csv.DictReader(fp, fieldnames=fields, dialect=TabFile)
for row in tsv:
dc = makedc(row)
writefile(row['dc:identifier'], dc)
xml = makexml(row)
writefile(row['dc:identifier'], xml)
except IOError as (errno, strerror):
print "Error ({0}): {1}".format(errno, strerror)
raise SystemExit
fp.close()
def makedc(row):
""" Generate a Dublin Core XML file from a TSV """
metadata = DublinCore()
metadata.Contributor = row.get('dc:contributor', '')
metadata.Coverage = row.get('dc:coverage', '')
metadata.Creator = row.get('dc:creator', '')
metadata.Date = row.get('dc:date', '')
metadata.Description = row.get('dc:description', '')
metadata.Format = row.get('dc:format', '')
metadata.Identifier = row.get('dc:identifier', '')
metadata.Language = row.get('dc:language', '')
metadata.Publisher = row.get('dc:publisher', '')
metadata.Relation = row.get('dc:relation', '').split('|')
metadata.Rights = row.get('dc:rights', '')
metadata.Source = row.get('dc:source', '')
metadata.Subject = row.get('dc:subject', '')
metadata.Title = row.get('dc:title', '')
return metadata
def makexml(row):
""" Generate an XML file conforming to the macrepo schema from a TSV """
doc = Document()
root = doc.createElement('metadata')
root.setAttribute('xmlns:xsi', XSI_NS)
root.setAttribute('xmlns:macrepo', MACREPO_NS)
doc.appendChild(root)
oldnid = doc.createElement('macrepo:oldNid')
oldnid.appendChild(doc.createTextNode(row.get('macrepo:oldNid', '')))
root.appendChild(oldnid)
notes = doc.createElement('macrepo:notes')
notes.appendChild(doc.createTextNode(row.get('macrepo:notes', '')))
root.appendChild(notes)
scale = doc.createElement('macrepo:scale')
scale.appendChild(doc.createTextNode(row.get('macrepo:scale', '')))
root.appendChild(scale)
return doc
def writefile(name, obj):
""" Writes Dublin Core or Macrepo XML object to a file """
if isinstance(obj, DublinCore):
fp = open(name + '-DC.xml', 'w')
fp.write(obj.makeXML(DC_NS))
elif isinstance(obj, Document):
fp = open(name + '-macrepo.xml', 'w')
fp.write(obj.toprettyxml())
fp.close()
def chkarg(arg):
""" Was a TSV file specified? """
return False if len(arg) < 2 else True
def usage():
""" Print a nice usage message """
print "Usage: bin/python " + basename(__file__) + " <filename>.tsv"
if __name__ == "__main__":
if chkarg(argv):
parse(argv[1])
else:
usage()
| mmccollow/TSV-Convert | tsv-convert.py | Python | gpl-2.0 | 3,059 |
from abc import abstractmethod
class VIFDriver(object):
@abstractmethod
def after_device_destroy(self, environ, domxml):
return domxml
@abstractmethod
def after_device_create(self, environ, domxml):
return domxml
@abstractmethod
def after_network_setup(self, environ, json_content):
return json_content
@abstractmethod
def after_nic_hotplug(self, environ, domxml):
return domxml
@abstractmethod
def after_nic_unplug(self, environ, domxml):
return domxml
@abstractmethod
def after_get_caps(self, environ, json_content):
return json_content
@abstractmethod
def after_get_stats(self, environ, json_content):
return json_content
@abstractmethod
def after_vm_start(self, environ, domxml):
return domxml
def after_migration_source(self, environ, domxml):
return domxml
def after_migration_destination(self, environ, domxml):
return domxml
@abstractmethod
def before_get_caps(self, environ, json_content):
return json_content
@abstractmethod
def before_get_stats(self, environ, json_content):
return json_content
@abstractmethod
def before_nic_hotplug(self, environ, domxml):
return domxml
@abstractmethod
def before_nic_unplug(self, environ, domxml):
return domxml
@abstractmethod
def before_device_create(self, environ, domxml):
return domxml
@abstractmethod
def before_device_destroy(self, environ, domxml):
return domxml
@abstractmethod
def before_migration_source(self, environ, domxml):
return domxml
@abstractmethod
def before_migration_destination(self, environ, domxml):
return domxml
@abstractmethod
def before_network_setup(self, environ, json_content):
return json_content
@abstractmethod
def before_vm_start(self, environ, domxml):
return domxml
| mmirecki/ovirt-provider-mock | vifdriver/vif_driver.py | Python | gpl-2.0 | 1,986 |
#!/usr/bin/env python
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot as plt
import numpy as np
import os.path as op
import util
import yt
import MPI_taskpull2
import logging
logging.getLogger('yt').setLevel(logging.ERROR)
# Scan for files
dirs = ['/home/ychen/data/0only_0529_h1/',\
'/home/ychen/data/0only_0605_h0/',\
'/home/ychen/data/0only_0605_hinf/',\
'/home/ychen/data/0only_0602_hydro/']
dirs = ['/home/ychen/data/0only_0602_hydro/']
#dirs = ['/home/ychen/data/0only_1022_h1_10Myr/',\
# '/home/ychen/data/0only_0204_h0_10Myr/',\
# '/home/ychen/data/0only_0204_hinf_10Myr/',\
# '/home/ychen/data/0only_0413_hydro_10Myr/']
regex = 'MHD_Jet*_hdf5_plt_cnt_[0-9][0-9][0-9][0-9]'
def rescan(dir, printlist=False):
files = util.scan_files(dir, regex=regex, walk=True, reverse=False)
return files
def worker_fn(dirname, filepath):
ds = yt.load(filepath)
factor = 4 if '10Myr' in dirname else 8
box = ds.box(ds.domain_left_edge/factor, ds.domain_right_edge/factor)
enstrophy = sum(box['vorticity_squared']*box['cell_mass'])
return int(ds.basename[-4:]), ds.current_time.in_units('Myr'), enstrophy
def tasks_gen(dirs):
for dir in dirs:
files = rescan(dir)
for file in reversed(files[:]):
yield file.pathname, file.fullpath
tasks = tasks_gen(dirs)
results = MPI_taskpull2.taskpull(worker_fn, tasks, print_result=True)
if results:
collected = {}
for key, item in results.items():
dirname, fname = key
if 'restart' in dirname:
dirname = op.dirname(dirname) + '/'
if dirname in collected:
collected[dirname].append(item)
else:
collected[dirname] = [item]
for key, item in collected.items():
collected[key] = sorted(item)
print collected.keys()
#picklename = time.strftime("Bflux_table_%Y%m%d_%H%M%S.pickle")
#pickle.dump(collected, open( picklename, "wb" ))
fmt = '%04d %6.3f %8.3e'
header = 'file t(Myr) enstrophy'
for dirname in collected.keys():
#print np.asarray(collected[dirname])
np.savetxt(dirname+'/GridAnalysis_Enstrophy.txt', np.asarray(collected[dirname]), fmt=fmt, header=header)
#if MPI_taskpull2.rank == 0:
# for key, item in results.items():
# print item
| yihaochen/FLASHtools | grid_analysis/GridAnalysis_Vorticity.py | Python | gpl-2.0 | 2,344 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function, absolute_import
"""JSON flat file database system."""
import codecs
import os
import os.path
import re
from fcntl import flock, LOCK_EX, LOCK_SH, LOCK_UN
import redis
import json
import time
from rophako.settings import Config
from rophako.utils import handle_exception
from rophako.log import logger
redis_client = None
cache_lifetime = 60*60 # 1 hour
def get(document, cache=True):
"""Get a specific document from the DB."""
logger.debug("JsonDB: GET {}".format(document))
# Exists?
if not exists(document):
logger.debug("Requested document doesn't exist")
return None
path = mkpath(document)
stat = os.stat(path)
# Do we have it cached?
data = get_cache(document) if cache else None
if data:
# Check if the cache is fresh.
if stat.st_mtime > get_cache(document+"_mtime"):
del_cache(document)
del_cache(document+"_mtime")
else:
return data
# Get a lock for reading.
lock = lock_cache(document)
# Get the JSON data.
data = read_json(path)
# Unlock!
unlock_cache(lock)
# Cache and return it.
if cache:
set_cache(document, data, expires=cache_lifetime)
set_cache(document+"_mtime", stat.st_mtime, expires=cache_lifetime)
return data
def commit(document, data, cache=True):
"""Insert/update a document in the DB."""
# Only allow one commit at a time.
lock = lock_cache(document)
# Need to create the file?
path = mkpath(document)
if not os.path.isfile(path):
parts = path.split("/")
parts.pop() # Remove the file part
directory = list()
# Create all the folders.
for part in parts:
directory.append(part)
segment = "/".join(directory)
if len(segment) > 0 and not os.path.isdir(segment):
logger.debug("JsonDB: mkdir {}".format(segment))
os.mkdir(segment, 0o755)
# Write the JSON.
write_json(path, data)
# Update the cached document.
if cache:
set_cache(document, data, expires=cache_lifetime)
set_cache(document+"_mtime", time.time(), expires=cache_lifetime)
# Release the lock.
unlock_cache(lock)
def delete(document):
"""Delete a document from the DB."""
path = mkpath(document)
if os.path.isfile(path):
logger.debug("Delete DB document: {}".format(path))
os.unlink(path)
del_cache(document)
def exists(document):
"""Query whether a document exists."""
path = mkpath(document)
return os.path.isfile(path)
def list_docs(path, recursive=False):
"""List all the documents at the path."""
root = os.path.join(Config.db.db_root, path)
docs = list()
if not os.path.isdir(root):
return []
for item in sorted(os.listdir(root)):
target = os.path.join(root, item)
db_path = os.path.join(path, item)
# Descend into subdirectories?
if os.path.isdir(target):
if recursive:
docs += [
os.path.join(item, name) for name in list_docs(db_path)
]
else:
continue
if target.endswith(".json"):
name = re.sub(r'\.json$', '', item)
docs.append(name)
return docs
def mkpath(document):
"""Turn a DB path into a JSON file path."""
if document.endswith(".json"):
# Let's not do that.
raise Exception("mkpath: document path already includes .json extension!")
return "{}/{}.json".format(Config.db.db_root, str(document))
def read_json(path):
"""Slurp, decode and return the data from a JSON document."""
path = str(path)
if not os.path.isfile(path):
raise Exception("Can't read JSON file {}: file not found!".format(path))
# Don't allow any fishy looking paths.
if ".." in path:
logger.error("ERROR: JsonDB tried to read a path with two dots: {}".format(path))
raise Exception()
# Open and lock the file.
fh = codecs.open(path, 'r', 'utf-8')
flock(fh, LOCK_SH)
text = fh.read()
flock(fh, LOCK_UN)
fh.close()
# Decode.
try:
data = json.loads(text)
except:
logger.error("Couldn't decode JSON data from {}".format(path))
handle_exception(Exception("Couldn't decode JSON from {}\n{}".format(
path,
text,
)))
data = None
return data
def write_json(path, data):
"""Write a JSON document."""
path = str(path)
# Don't allow any fishy looking paths.
if ".." in path:
logger.error("ERROR: JsonDB tried to write a path with two dots: {}".format(path))
raise Exception()
logger.debug("JsonDB: WRITE > {}".format(path))
# Open and lock the file.
fh = codecs.open(path, 'w', 'utf-8')
flock(fh, LOCK_EX)
# Write it.
fh.write(json.dumps(data, indent=4, separators=(',', ': ')))
# Unlock and close.
flock(fh, LOCK_UN)
fh.close()
############################################################################
# Redis Caching Functions #
############################################################################
disable_redis = False
def get_redis():
"""Connect to Redis or return the existing connection."""
global redis_client
global disable_redis
if not redis_client and not disable_redis:
try:
redis_client = redis.StrictRedis(
host = Config.db.redis_host,
port = Config.db.redis_port,
db = Config.db.redis_db,
)
redis_client.ping()
except Exception as e:
logger.error("Couldn't connect to Redis; memory caching will be disabled! {}".format(e))
redis_client = None
disable_redis = True
return redis_client
def set_cache(key, value, expires=None):
"""Set a key in the Redis cache."""
key = Config.db.redis_prefix + key
client = get_redis()
if not client:
return
try:
client.set(key, json.dumps(value))
# Expiration date?
if expires:
client.expire(key, expires)
except:
logger.error("Redis exception: couldn't set_cache {}".format(key))
def get_cache(key):
"""Get a cached item."""
key = Config.db.redis_prefix + key
value = None
client = get_redis()
if not client:
return
try:
value = client.get(key)
if value:
value = json.loads(value)
except:
logger.debug("Redis exception: couldn't get_cache {}".format(key))
value = None
return value
def del_cache(key):
"""Delete a cached item."""
key = Config.db.redis_prefix + key
client = get_redis()
if not client:
return
client.delete(key)
def lock_cache(key, timeout=5, expire=20):
"""Cache level 'file locking' implementation.
The `key` will be automatically suffixed with `_lock`.
The `timeout` is the max amount of time to wait for a lock.
The `expire` is how long a lock may exist before it's considered stale.
Returns True on success, None on failure to acquire lock."""
client = get_redis()
if not client:
return
# Take the lock.
lock = client.lock(key, timeout=expire)
lock.acquire()
logger.debug("Cache lock acquired: {}, expires in {}s".format(key, expire))
return lock
def unlock_cache(lock):
"""Release the lock on a cache key."""
if lock:
lock.release()
logger.debug("Cache lock released")
| kirsle/rophako | rophako/jsondb.py | Python | gpl-2.0 | 7,743 |
from pymuco.midiio import *
from pymuco.midi import representation
class MidiParser(MidiOutStream.MidiOutStream):
"""
This class listens to a select few midi events relevant for a simple midifile containing a pianomelody
"""
def __init__(self, midifile):
self.midifile = midifile
self.notes_on = {}
self.ctrack = -1
self.mformat = -1
pass
# Event Listeners
def channel_message(self, message_type, channel, data):
pass
def note_on(self, channel=0, pitch=0x40, onvel=0x40):
if not str(channel) in self.midifile[str(self.ctrack)].channels:
self.midifile[str(self.ctrack)].channels[str(channel)] = 1
program = self.midifile[str(self.ctrack)].channels[str(channel)]
note = representation.Note(self.abs_time(), self.abs_time(), pitch, onvel, channel=channel, program=program)
if self.ctrack == -1:
print 'Midiparser: no track currently active.'
return
self.midifile[str(self.ctrack)].notes.append(note)
if not (pitch, channel) in self.notes_on:
self.notes_on[pitch, channel] = note
def note_off(self, channel=0, pitch=0x40, offvel=0x40):
if (pitch, channel) not in self.notes_on:
# print 'Midiparser: Note off before note on?'
return
note = self.notes_on[pitch, channel]
note.off = self.abs_time()
note.offvel = offvel
#self.midifile[str(self.ctrack)].insert(Note(on, self.abs_time(), pitch, onvel, offvel))
del self.notes_on[pitch, channel]
def header(self, format=0, nTracks=1, division=96):
self.midifile.division = division
self.mformat = format
self.midifile.format = format
def sequence_name(self, text):
self.midifile[str(self.ctrack)].name = text
def tempo(self, value):
self.midifile.tempo = value
def smtp_offset(self, hour, minute, second, frame, framePart):
self.midifile.smtp_offset = (hour, minute, second, frame, framePart)
def time_signature(self, nn, dd, cc, bb):
self.midifile.time_signature = (nn, dd, cc, bb)
def key_signature(self, sf, mi):
self.midifile.key_signature = (sf, mi)
def program_name(self, data):pass
def sequencer_specific(self, data):pass
def aftertouch(self, channel=0, note=0x40, velocity=0x40):pass
def continuous_controller(self, channel, controller, value):pass
def patch_change(self, channel, patch):
self.midifile[str(self.ctrack)].channels[str(channel)] = patch
def channel_pressure(self, channel, pressure):pass
def pitch_bend(self, channel, value):pass
def system_exclusive(self, data):pass
def song_position_pointer(self, value):pass
def song_select(self, songNumber):pass
def tuning_request(self):pass
def midi_time_code(self, msg_type, values):pass
def eof(self):pass
def start_of_track(self, n_track=0):
self.midifile[str(n_track)] = representation.Track(self.midifile, n_track)
self.ctrack = n_track
def end_of_track(self):
self.ctrack=-1
def sysex_event(self, data):pass
def meta_event(self, meta_type, data):pass
def sequence_number(self, value):pass
def text(self, text):pass
def copyright(self, text):pass
def instrument_name(self, text):pass
def lyric(self, text):pass
def marker(self, text):pass
def cuepoint(self, text):pass
def midi_ch_prefix(self, channel):pass
def midi_port(self, value):pass
| bjvanderweij/pymuco | pymuco/midi/parser.py | Python | gpl-2.0 | 3,303 |
# -*- coding: utf-8 -*-
# MouseTrap
#
# Copyright 2009 Flavio Percoco Premoli
#
# This file is part of mouseTrap.
#
# MouseTrap is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License v2 as published
# by the Free Software Foundation.
#
# mouseTrap 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 mouseTrap. If not, see <http://www.gnu.org/licenses/>.
"""MouseTrap's settings handler."""
__id__ = "$Id$"
__version__ = "$Revision$"
__date__ = "$Date$"
__copyright__ = "Copyright (c) 2008 Flavio Percoco Premoli"
__license__ = "GPLv2"
import os
import ConfigParser
import mousetrap.app.environment as env
class Settings( ConfigParser.ConfigParser ):
def optionxform( self, optionstr ):
"""
Keeps the options cases instead of
converting them in lowercase.
Arguments:
- self: The main object pointer.
- optionstr: The option string.
"""
return optionstr
def getList(self, section, option):
"""
Gets a section parsed as string
and returns it as list
Arguments:
- self: The main object pointer.
- section: The section where option is.
- option: The needed option value.
"""
return [ val for val in self.get(section, option).split("|") if val != "" ]
def setList(self, section, option, arr):
"""
Sets a new list type option.
Arguments:
- self: The main object pointer.
- section: The section where option will be.
- option: The option to set.
- arr: The List to transform in string.
"""
self.set(section, option, "|".join(arr))
def write_first(self, conf_file):
"""
Writes the first configuration file in case it doesn't exists.
Arguments:
self: The main object pointer
conf_file: The config file to write.
"""
with open(conf_file, "w") as conf:
conf.write("[gui]")
conf.write("\nshowCapture = True")
conf.write("\nshowMainGui = True")
conf.write("\nshowPointMapper = True")
conf.write("\n\n[access]")
conf.write("\nreqMovement = 10")
conf.write("\n\n[scripts]")
conf.write("\nname = joystick")
conf.write("\n\n[cam]")
conf.write("\nmouseMode = forehead")
conf.write("\ninputDevIndex = 0")
conf.write("\nflipImage = False")
conf.write("\n\n[main]")
conf.write("\ndebugLevel = 10")
conf.write("\nalgorithm = forehead")
conf.write("\nstartCam = True")
conf.write("\naddon = ")
conf.write("\n\n[mouse]")
conf.write("\ndefClick = b1c")
conf.write("\nstepSpeed = 5")
def load():
cfg = Settings()
created = False
if not os.path.exists( env.configPath ):
os.mkdir( env.configPath )
if not os.path.exists( env.configFile ):
cfg.write_first(env.configFile)
created = True
cfg.readfp(open( env.configFile ))
return created, cfg
| amberheilman/mousetrap | src/mousetrap/app/lib/settings.py | Python | gpl-2.0 | 3,450 |
from django.conf.urls import patterns, url
from iyoume.waybill import views as dr
urlpatterns = patterns('',
url(r'^add/', dr.make_waybill),
url(r'^del/', dr.remove_waybill),
url(r'^find/', dr.search_waybill),
url(r'^take/', dr.take_place),
url(r'^trips/', dr.trips),
url(r'^cancel_trip/', dr.cancel_trip),
url(r'^passangers/', dr.passangers),
url(r'^travel/', dr.travel),
)
| rasmadeus/iyoume | iyoume/waybill/urls.py | Python | gpl-2.0 | 408 |
#! /usr/bin/env python
""" cryptopy.cipher.rijndael_test
Tests for the rijndael encryption algorithm
Copyright (c) 2002 by Paul A. Lambert
Read LICENSE.txt for license information.
"""
from cryptopy.cipher.rijndael import Rijndael
from cryptopy.cipher.base import noPadding
from binascii import a2b_hex
import unittest
class Rijndael_TestVectors(unittest.TestCase):
""" Test Rijndael algorithm using know values."""
def testGladman_dev_vec(self):
""" All 25 combinations of block and key size.
These test vectors were generated by Dr Brian Gladman
using the program aes_vec.cpp <[email protected]> 24th May 2001.
vectors in file: dev_vec.txt
http://fp.gladman.plus.com/cryptography_technology/rijndael/index.htm
"""
def RijndaelTestVec(i, key, pt, ct):
""" Run single AES test vector with any legal blockSize
and any legal key size. """
bkey, plainText, cipherText = a2b_hex(key), a2b_hex(pt), a2b_hex(ct)
kSize = len(bkey)
bSize = len(cipherText) # set block size to length of block
alg = Rijndael(bkey, keySize=kSize, blockSize=bSize, padding=noPadding())
self.assertEqual( alg.encrypt(plainText), cipherText )
self.assertEqual( alg.decrypt(cipherText), plainText )
RijndaelTestVec( i = 'dev_vec.txt 16 byte block, 16 byte key',
key = '2b7e151628aed2a6abf7158809cf4f3c',
pt = '3243f6a8885a308d313198a2e0370734',
ct = '3925841d02dc09fbdc118597196a0b32')
RijndaelTestVec( i = 'dev_vec.txt 16 byte block, 20 byte key',
key = '2b7e151628aed2a6abf7158809cf4f3c762e7160',
pt = '3243f6a8885a308d313198a2e0370734',
ct = '231d844639b31b412211cfe93712b880')
RijndaelTestVec( i = 'dev_vec.txt 16 byte block, 24 byte key',
key = '2b7e151628aed2a6abf7158809cf4f3c762e7160f38b4da5',
pt = '3243f6a8885a308d313198a2e0370734',
ct = 'f9fb29aefc384a250340d833b87ebc00')
RijndaelTestVec( i = 'dev_vec.txt 16 byte block, 28 byte key',
key = '2b7e151628aed2a6abf7158809cf4f3c762e7160f38b4da56a784d90',
pt = '3243f6a8885a308d313198a2e0370734',
ct = '8faa8fe4dee9eb17caa4797502fc9d3f')
RijndaelTestVec( i = 'dev_vec.txt 16 byte block, 32 byte key',
key = '2b7e151628aed2a6abf7158809cf4f3c762e7160f38b4da56a784d9045190cfe',
pt = '3243f6a8885a308d313198a2e0370734',
ct = '1a6e6c2c662e7da6501ffb62bc9e93f3')
RijndaelTestVec( i = 'dev_vec.txt 20 byte block, 16 byte key',
key = '2b7e151628aed2a6abf7158809cf4f3c',
pt = '3243f6a8885a308d313198a2e03707344a409382',
ct = '16e73aec921314c29df905432bc8968ab64b1f51')
RijndaelTestVec( i = 'dev_vec.txt 20 byte block, 20 byte key',
key = '2b7e151628aed2a6abf7158809cf4f3c762e7160',
pt = '3243f6a8885a308d313198a2e03707344a409382',
ct = '0553eb691670dd8a5a5b5addf1aa7450f7a0e587')
RijndaelTestVec( i = 'dev_vec.txt 20 byte block, 24 byte key',
key = '2b7e151628aed2a6abf7158809cf4f3c762e7160f38b4da5',
pt = '3243f6a8885a308d313198a2e03707344a409382',
ct = '73cd6f3423036790463aa9e19cfcde894ea16623')
RijndaelTestVec( i = 'dev_vec.txt 20 byte block, 28 byte key',
key = '2b7e151628aed2a6abf7158809cf4f3c762e7160f38b4da56a784d90',
pt = '3243f6a8885a308d313198a2e03707344a409382',
ct = '601b5dcd1cf4ece954c740445340bf0afdc048df')
RijndaelTestVec( i = 'dev_vec.txt 20 byte block, 32 byte key',
key = '2b7e151628aed2a6abf7158809cf4f3c762e7160f38b4da56a784d9045190cfe',
pt = '3243f6a8885a308d313198a2e03707344a409382',
ct = '579e930b36c1529aa3e86628bacfe146942882cf')
RijndaelTestVec( i = 'dev_vec.txt 24 byte block, 16 byte key',
key = '2b7e151628aed2a6abf7158809cf4f3c',
pt = '3243f6a8885a308d313198a2e03707344a4093822299f31d',
ct = 'b24d275489e82bb8f7375e0d5fcdb1f481757c538b65148a')
RijndaelTestVec( i = 'dev_vec.txt 24 byte block, 20 byte key',
key = '2b7e151628aed2a6abf7158809cf4f3c762e7160',
pt = '3243f6a8885a308d313198a2e03707344a4093822299f31d',
ct = '738dae25620d3d3beff4a037a04290d73eb33521a63ea568')
RijndaelTestVec( i = 'dev_vec.txt 24 byte block, 24 byte key',
key = '2b7e151628aed2a6abf7158809cf4f3c762e7160f38b4da5',
pt = '3243f6a8885a308d313198a2e03707344a4093822299f31d',
ct = '725ae43b5f3161de806a7c93e0bca93c967ec1ae1b71e1cf')
RijndaelTestVec( i = 'dev_vec.txt 24 byte block, 28 byte key',
key = '2b7e151628aed2a6abf7158809cf4f3c762e7160f38b4da56a784d90',
pt = '3243f6a8885a308d313198a2e03707344a4093822299f31d',
ct = 'bbfc14180afbf6a36382a061843f0b63e769acdc98769130')
RijndaelTestVec( i = 'dev_vec.txt 24 byte block, 32 byte key',
key = '2b7e151628aed2a6abf7158809cf4f3c762e7160f38b4da56a784d9045190cfe',
pt = '3243f6a8885a308d313198a2e03707344a4093822299f31d',
ct = '0ebacf199e3315c2e34b24fcc7c46ef4388aa475d66c194c')
RijndaelTestVec( i = 'dev_vec.txt 28 byte block, 16 byte key',
key = '2b7e151628aed2a6abf7158809cf4f3c',
pt = '3243f6a8885a308d313198a2e03707344a4093822299f31d0082efa9',
ct = 'b0a8f78f6b3c66213f792ffd2a61631f79331407a5e5c8d3793aceb1')
RijndaelTestVec( i = 'dev_vec.txt 28 byte block, 20 byte key',
key = '2b7e151628aed2a6abf7158809cf4f3c762e7160',
pt = '3243f6a8885a308d313198a2e03707344a4093822299f31d0082efa9',
ct = '08b99944edfce33a2acb131183ab0168446b2d15e958480010f545e3')
RijndaelTestVec( i = 'dev_vec.txt 28 byte block, 24 byte key',
key = '2b7e151628aed2a6abf7158809cf4f3c762e7160f38b4da5',
pt = '3243f6a8885a308d313198a2e03707344a4093822299f31d0082efa9',
ct = 'be4c597d8f7efe22a2f7e5b1938e2564d452a5bfe72399c7af1101e2')
RijndaelTestVec( i = 'dev_vec.txt 28 byte block, 28 byte key',
key = '2b7e151628aed2a6abf7158809cf4f3c762e7160f38b4da56a784d90',
pt = '3243f6a8885a308d313198a2e03707344a4093822299f31d0082efa9',
ct = 'ef529598ecbce297811b49bbed2c33bbe1241d6e1a833dbe119569e8')
RijndaelTestVec( i = 'dev_vec.txt 28 byte block, 32 byte key',
key = '2b7e151628aed2a6abf7158809cf4f3c762e7160f38b4da56a784d9045190cfe',
pt = '3243f6a8885a308d313198a2e03707344a4093822299f31d0082efa9',
ct = '02fafc200176ed05deb8edb82a3555b0b10d47a388dfd59cab2f6c11')
RijndaelTestVec( i = 'dev_vec.txt 32 byte block, 16 byte key',
key = '2b7e151628aed2a6abf7158809cf4f3c',
pt = '3243f6a8885a308d313198a2e03707344a4093822299f31d0082efa98ec4e6c8',
ct = '7d15479076b69a46ffb3b3beae97ad8313f622f67fedb487de9f06b9ed9c8f19')
RijndaelTestVec( i = 'dev_vec.txt 32 byte block, 20 byte key',
key = '2b7e151628aed2a6abf7158809cf4f3c762e7160',
pt = '3243f6a8885a308d313198a2e03707344a4093822299f31d0082efa98ec4e6c8',
ct = '514f93fb296b5ad16aa7df8b577abcbd484decacccc7fb1f18dc567309ceeffd')
RijndaelTestVec( i = 'dev_vec.txt 32 byte block, 24 byte key',
key = '2b7e151628aed2a6abf7158809cf4f3c762e7160f38b4da5',
pt = '3243f6a8885a308d313198a2e03707344a4093822299f31d0082efa98ec4e6c8',
ct = '5d7101727bb25781bf6715b0e6955282b9610e23a43c2eb062699f0ebf5887b2')
RijndaelTestVec( i = 'dev_vec.txt 32 byte block, 28 byte key',
key = '2b7e151628aed2a6abf7158809cf4f3c762e7160f38b4da56a784d90',
pt = '3243f6a8885a308d313198a2e03707344a4093822299f31d0082efa98ec4e6c8',
ct = 'd56c5a63627432579e1dd308b2c8f157b40a4bfb56fea1377b25d3ed3d6dbf80')
RijndaelTestVec( i = 'dev_vec.txt 32 byte block, 32 byte key',
key = '2b7e151628aed2a6abf7158809cf4f3c762e7160f38b4da56a784d9045190cfe',
pt = '3243f6a8885a308d313198a2e03707344a4093822299f31d0082efa98ec4e6c8',
ct = 'a49406115dfb30a40418aafa4869b7c6a886ff31602a7dd19c889dc64f7e4e7a')
# Make this test module runnable from the command prompt
if __name__ == "__main__":
unittest.main()
| repotvsupertuga/tvsupertuga.repository | script.module.cryptolib/lib/cryptopy/cipher/rijndael_test.py | Python | gpl-2.0 | 9,568 |
import csv, os
from Products.CMFCore.utils import getToolByName
def get_folder(self, type, name):
folder_brains = self.queryCatalog({'portal_type':type, 'title':name})[0]
return folder_brains.getObject()
def create_object_in_directory(self, container, type):
id = container.generateUniqueId(type)
container.invokeFactory(id=id, type_name=type)
return container[id]
def get_type_or_create(self, type, folder, cmp, val):
brains = self.queryCatalog({'portal_type':type, cmp:val})
if len(brains) > 0:
return brains[0].getObject()
else:
return create_object_in_directory(self, folder, type)
def set_reference(self, object, visit):
existing_visits = object.getVisits()
if visit not in existing_visits:
existing_visits.append(visit)
object.setVisits(existing_visits)
def import_visits(self):
reader = csv.reader(self.REQUEST.get('csv-file-contents').split(os.linesep), delimiter="\t")
for row in reader:
if not row: continue
header = ['School', 'Student Name', 'Instrument', 'Student Email', 'Student Phone', 'Student Address', 'Student City',
'Student Zip', 'Contact Name', 'Contact Title', 'Contact Phone', 'Contact Email', 'Is Contact Alumni', 'Date']
school_name = row[0].strip().strip('"').strip("'")
student_name = row[1].strip().strip('"').strip("'")
instrument = row[2].strip().strip('"').strip("'")
student_email = row[3].strip().strip('"').strip("'")
student_phone = row[4].strip().strip('"').strip("'")
student_address = row[5].strip().strip('"').strip("'")
student_city = row[6].strip().strip('"').strip("'")
student_zip = row[7].strip().strip('"').strip("'")
contact_name = row[8].strip().strip('"').strip("'")
contact_title = row[9].strip().strip('"').strip("'")
contact_phone = row[10].strip().strip('"').strip("'")
contact_email = row[11].strip().strip('"').strip("'")
is_contact_alumni = row[12].strip().upper() == 'TRUE'
date = row[13].strip().strip('"').strip("'")
user_id = self.portal_membership.getAuthenticatedMember().id
student = get_type_or_create(self, 'Student', get_folder(self, 'StudentFolder', 'Students'), 'title', student_name)
contact = get_type_or_create(self, 'Contact', get_folder(self, 'ContactFolder', 'Contacts'), 'title', contact_name)
faculty = get_type_or_create(self, 'FacultyMember', get_folder(self, 'FacultyMemberFolder', 'FacultyMembers'), 'title', user_id)
school = get_type_or_create(self, 'School', get_folder(self, 'SchoolFolder', 'Schools'), 'title', school_name)
visit = create_object_in_directory(self, get_folder(self,'VisitFolder', 'Visits'), 'Visit')
set_reference(student, visit)
set_reference(contact, visit)
set_reference(faculty, visit)
set_reference(school, visit)
school.edit(title = school_name)
student.edit(title=student_name, instrument=instrument, email=student_email, phone=student_phone, address=student_address, city=student_city, zip=student_zip)
contact.edit(title=contact_name, type=contact_title, phone=contact_phone, email=contact_email, isAlumni=is_contact_alumni)
faculty.edit(title=user_id)
visit_title = "%s-%s-%s-%s" % (school_name, student_name, contact_name, user_id)
visit.edit(title=visit_title, dateOfVisit = date, schools = school, contacts = contact, students = student, facultymembers = faculty)
| uwosh/UWOshMusicRecruiting | Extensions/import_visits.py | Python | gpl-2.0 | 3,594 |
#!/usr/bin/python
import glob,re,sys,math,pyfits
import numpy as np
import utils
if len( sys.argv ) < 2:
print '\nconvert basti SSP models to ez_gal fits format'
print 'Run in directory with SED models for one metallicity'
print 'Usage: convert_basti.py ez_gal.ascii\n'
sys.exit(2)
fileout = sys.argv[1]
# try to extract meta data out of fileout
sfh = ''; tau = ''; met = ''; imf = ''
# split on _ but get rid of the extension
parts = '.'.join( fileout.split( '.' )[:-1] ).split( '_' )
# look for sfh
for (check,val) in zip( ['ssp','exp'], ['SSP','Exponential'] ):
if parts.count( check ):
sfh = val
sfh_index = parts.index( check )
break
# tau?
if sfh:
tau = parts[sfh_index+1] if sfh == 'exp' else ''
# metallicity
if parts.count( 'z' ):
met = parts[ parts.index( 'z' ) + 1 ]
# imf
for (check,val) in zip( ['krou','salp','chab'], ['Kroupa', 'Salpeter', 'Chabrier'] ):
if parts.count( check ):
imf = val
break
if parts.count( 'n' ):
n = parts[ parts.index( 'n' ) + 1 ]
ae = False
if parts.count( 'ae' ): ae = True
# does the file with masses exist?
has_masses = False
mass_file = glob.glob( 'MLR*.txt' )
if len( mass_file ):
# read it in!
print 'Loading masses from %s' % mass_file[0]
data = utils.rascii( mass_file[0], silent=True )
masses = data[:,10:14].sum( axis=1 )
has_masses = True
files = glob.glob( 'SPEC*agb*' )
nages = len( files )
ages = []
for (i,file) in enumerate(files):
ls = []
this = []
# extract the age from the filename and convert to years
m = re.search( 't60*(\d+)$', file )
ages.append( int( m.group(1) )*1e6 )
# read in this file
fp = open( file, 'r' )
for line in fp:
parts = line.strip().split()
ls.append( float( parts[0].strip() ) )
this.append( float( parts[1].strip() ) )
if i == 0:
# if this is the first file, generate the data table
nls = len( ls )
seds = np.empty( (nls,nages) )
# convert to ergs/s/angstrom
seds[:,i] = np.array( this )/4.3607e-33/1e10
# convert to numpy
ages = np.array( ages )
ls = np.array( ls )*10.0
# make sure we are sorted in age
sinds = ages.argsort()
ages = ages[sinds]
seds = seds[:,sinds]
# speed of light
c = utils.convert_length( utils.c, incoming='m', outgoing='a' )
# convert from angstroms to hertz
vs = c/ls
# convert from ergs/s/A to ergs/s/Hz
seds *= ls.reshape( (ls.size,1) )**2.0/c
# and now from ergs/s/Hz to ergs/s/Hz/cm^2.0
seds /= (4.0*math.pi*utils.convert_length( 10, incoming='pc', outgoing='cm' )**2.0)
# sort in frequency space
sinds = vs.argsort()
# generate fits frame with sed in it
primary_hdu = pyfits.PrimaryHDU(seds[sinds,:])
primary_hdu.header.update( 'units', 'ergs/s/cm^2/Hz' )
primary_hdu.header.update( 'has_seds', True )
primary_hdu.header.update( 'nfilters', 0 )
primary_hdu.header.update( 'nzfs', 0 )
# store meta data
if sfh and met and imf:
primary_hdu.header.update( 'has_meta', True )
primary_hdu.header.update( 'model', 'BaSTI', comment='meta data' )
primary_hdu.header.update( 'met', met, comment='meta data' )
primary_hdu.header.update( 'imf', imf, comment='meta data' )
primary_hdu.header.update( 'sfh', sfh, comment='meta data' )
if sfh == 'Exponential': primary_hdu.header.update( 'tau', tau, comment='meta data' )
primary_hdu.header.update( 'n', n, comment='meta data' )
primary_hdu.header.update( 'ae', ae, comment='meta data' )
# store the list of frequencies in a table
vs_hdu = pyfits.new_table(pyfits.ColDefs([pyfits.Column(name='vs', array=vs[sinds], format='D', unit='hertz')]))
vs_hdu.header.update( 'units', 'hertz' )
# and the list of ages
cols = [pyfits.Column(name='ages', array=ages, format='D', unit='years')]
# and masses
if has_masses: cols.append( pyfits.Column(name='masses', array=masses, format='D', unit='m_sun') )
ages_hdu = pyfits.new_table(pyfits.ColDefs( cols ))
if has_masses: ages_hdu.header.update( 'has_mass', True )
# make the fits file in memory
hdulist = pyfits.HDUList( [primary_hdu,vs_hdu,ages_hdu] )
# and write it out
hdulist.writeto( fileout, clobber=True ) | drdangersimon/EZgal | examples/convert/convert_basti.py | Python | gpl-2.0 | 3,979 |
max = A[1]
for i in range(len(A)):
if A.count(A[i]) > A.count(max):
max = A[i]
print(max)
| chelberserker/mipt_cs_on_python | exes/ex4.py | Python | gpl-2.0 | 93 |
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 29 15:52:33 2014
@author: raffaelerainone
"""
from time import clock
from math import sqrt
def is_prime(n):
check=True
i=2
while check and i<=sqrt(n):
if n%i==0:
check=False
i+=1
return check
start = clock()
lim=50*(10**6)
A=[]
prime_2 = [i for i in range(2,int(lim**(0.5))) if is_prime(i)]
prime_3 = [i for i in prime_2 if i<(int(lim**(0.34)))]
prime_4 = [i for i in prime_3 if i<(int(lim**(0.25)))]
for i in prime_2:
for j in prime_3:
for k in prime_4:
x=(i**2)+(j**3)+(k**4)
if x<lim:
A.append(x)
print len(set(A))
print clock() - start | raffo85h/projecteuler | 87. Prime power triples.py | Python | gpl-2.0 | 692 |
def main():
print "hola"
print "Como te llmas?"
nombre = raw_input()
print "Buenos dias", nombre
print "Que edad tienes?"
edad = raw_input()
print "que bien te conservas para tener", edad
main()
| Djhacker18/Python | Practica1Conver.py | Python | gpl-2.0 | 202 |
"""
EDENetworks, a genetic network analyzer
Copyright (C) 2011 Aalto University
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""
"""
Collection of dialogue windows
"""
import pynet,os,netio,netext,visuals,eden,transforms
import random
import heapq
import string
import percolator
import shutil
from math import ceil
from Tkinter import *
import tkMessageBox
#from pylab import *
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg,NavigationToolbar2TkAgg
# NEW DIALOGUE WINDOWS / JS / MAY-JUNE 09
class MySimpleDialog(Toplevel):
'''Master class for a dialog popup window.
Functions body() and apply() to be overridden
with whatever the dialog should be doing.'''
def __init__(self,parent,title=None):
Toplevel.__init__(self,parent)
self.transient(parent)
self.title(title)
self.parent=parent
self.result=None
body=Frame(self)
self.initial_focus=self.body(self,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()+50,parent.winfo_rooty()+50))
self.initial_focus.focus_set()
self.wait_window(self)
def body(self,masterclass,masterwindow):
pass
def buttonbox(self):
"""OK and Cancel 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()
def ok(self,event=None):
if not self.validate():
self.initial_focus.focus_set()
return
self.withdraw()
self.update_idletasks()
self.applyme()
self.cancel()
def cancel(self,event=None):
self.parent.focus_set()
self.destroy()
def validate(self):
return 1
def applyme(self):
pass
def displayBusyCursor(self):
self.parent.configure(cursor='watch')
self.parent.update()
self.parent.after_idle(self.removeBusyCursor)
def removeBusyCursor(self):
self.parent.configure(cursor='arrow')
class WLogbinDialog(MySimpleDialog):
"""Asks for the number of bins for log binning
and allows linear bins for 1...10"""
def __init__(self,parent,title=None):
Toplevel.__init__(self,parent)
self.configure(bg='Gray80')
self.transient(parent)
if title:
self.title=title
self.parent=parent
self.result=None
self.linfirst=IntVar()
self.numbins=StringVar()
body=Frame(self,bg='Gray80')
self.initial_focus=self.body(self,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()+50,parent.winfo_rooty()+50))
self.initial_focus.focus_set()
self.wait_window(self)
def body(self,masterclass,masterwindow):
self.b1=Checkbutton(masterwindow,text='Use linear bins for 1..10',variable=masterclass.linfirst,state=ACTIVE,bg='Gray80')
self.b1.grid(row=0,column=0,columnspan=2)
Label(masterwindow,text='Number of bins:',bg='Gray80').grid(row=1,column=0)
self.c1=Entry(masterwindow,textvariable=masterclass.numbins,bg='Gray95')
masterclass.numbins.set('30')
self.c1.grid(row=1,column=1)
return self.c1
def applyme(self):
self.result=[self.linfirst.get(),float(self.numbins.get())]
class LoadMatrixDialog(MySimpleDialog):
"""Asks for the number of bins for log binning
and allows linear bins for 1...10"""
def __init__(self,parent,title='Please provide information:'):
Toplevel.__init__(self,parent)
# self.configure(bg='Gray80')
# self.transient(parent)
self.title(title)
self.parent=parent
self.result=None
self.clones=StringVar()
self.measuretype=StringVar()
body=Frame(self)
self.initial_focus=self.body(self,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()+50,parent.winfo_rooty()+50))
self.initial_focus.focus_set()
self.wait_window(self)
def body(self,masterclass,masterwindow):
self.c1=Label(masterwindow,text='What distance measure has been used?',bg='DarkOliveGreen2',anchor=W)
self.c1.grid(row=0,column=0)
r1=Radiobutton(masterwindow,text='Non-shared alleles',value='nsa',variable=masterclass.measuretype)
r2=Radiobutton(masterwindow,text='Linear Manhattan',value='lm',variable=masterclass.measuretype)
r3=Radiobutton(masterwindow,text='Allele parsimony',value='ap',variable=masterclass.measuretype)
r4=Radiobutton(masterwindow,text='Hybrid',value="hybrid",variable=masterclass.measuretype)
r5=Radiobutton(masterwindow,text='Other',value="other",variable=masterclass.measuretype)
r1.grid(row=1,column=0,sticky=W)
r2.grid(row=2,column=0,sticky=W)
r3.grid(row=3,column=0,sticky=W)
r4.grid(row=4,column=0,sticky=W)
r5.grid(row=5,column=0,sticky=W)
self.c2=Label(masterwindow,text='How have clones been handled?',bg='DarkOliveGreen2',anchor=W)
self.c2.grid(row=6,column=0)
r6=Radiobutton(masterwindow,text='Removed',value='collapsed',variable=masterclass.clones)
r7=Radiobutton(masterwindow,text='Kept',value='included',variable=masterclass.clones)
r8=Radiobutton(masterwindow,text='Unknown',value='unknown',variable=masterclass.clones)
r6.grid(row=7,column=0,sticky=W)
r7.grid(row=8,column=0,sticky=W)
r8.grid(row=9,column=0,sticky=W)
masterclass.measuretype.set('other')
masterclass.clones.set('unknown')
return self.c1
def applyme(self):
self.result=[self.measuretype.get(),self.clones.get()]
class MetaHelpWindow(MySimpleDialog):
def __init__(self,parent,title=None,datatype='msat'):
Toplevel.__init__(self,parent)
self.configure(bg='Gray80')
self.transient(parent)
self.datatype=datatype
if title:
self.title=title
self.parent=parent
self.result=None
self.linfirst=IntVar()
self.numbins=StringVar()
body=Frame(self,bg='Gray80')
self.initial_focus=self.body(self,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()+50,parent.winfo_rooty()+50))
self.initial_focus.focus_set()
self.wait_window(self)
def body(self,masterclass,masterwindow):
self.text=Text(self,bg='Gray90')
self.text.pack(expand=YES,fill=BOTH)
str1="Auxiliary data files are used for reading node properties, such as labels, classes, and sampling sites. "
str2="File format is ASCII, such that each row lists properties for a node. \n"
str3="The first row must contain HEADERS, i.e. labels for the properties. \n\n"
str4="Example for the first row: \n node_label node_site node_latitude node_longitude node_geoclass \n"
if self.datatype=='net':
str4=str4+"\nWhen the input data is a network (.edg,.gml), THE FIRST HEADER COLUMN MUST BE node_label, "
str4=str4+"and there must be a row for each node in the original network, using original node labels."
str4=str4+"If you have saved the node properties in EDEN Analyzer, this has been taken care of already."
if self.datatype=='msat':
str4=str4+"\nThere must be one row for each row in the original microsatellite data file. "
if self.datatype=="dmat":
str4=str4+"\nThere must be one row for each row in the original distance matrix file. "
self.text.insert(INSERT,str1+str2+str3+str4)
class AskNumberOfBins(MySimpleDialog):
"""Asks for number of bins for binning"""
def __init__(self,parent,title=None):
Toplevel.__init__(self,parent)
#self.configure(bg='Gray80')
# self.transient(parent)
if title:
self.title=title
self.parent=parent
self.result=None
# self.linfirst=IntVar()
self.numbins=StringVar()
body=Frame(self)
self.initial_focus=self.body(self,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()+50,parent.winfo_rooty()+50))
self.initial_focus.focus_set()
self.wait_window(self)
def body(self,masterclass,masterwindow):
# self.b1=Checkbutton(masterwindow,text='Use linear bins for 1..10',variable=masterclass.linfirst,state=ACTIVE,bg='Gray80')
# self.b1.grid(row=0,column=0,columnspan=2)
Label(masterwindow,text='Number of bins:').grid(row=1,column=0)
self.c1=Entry(masterwindow,textvariable=masterclass.numbins,bg='Gray95')
masterclass.numbins.set('30')
self.c1.grid(row=1,column=1)
return self.c1
def applyme(self):
self.result=float(self.numbins.get())
def validate(self):
userstr=self.numbins.get()
try:
nbins=int(userstr)
except Exception:
tkMessageBox.showerror(
"Error:",
"Number of bins must be an integer.")
return 0
if nbins<2:
tkMessageBox.showerror(
"Error:",
"Number of bins must be larger than one.")
return 0
return 1
class ProjectLaunchDialog(MySimpleDialog):
"""First window shown when launching a new analysis wizard.
Inquires if the user wants to load microsatellite data,
a distance matrix, or a network file."""
def __init__(self,parent,title=None):
Toplevel.__init__(self,parent)
#self.configure(bg='Gray80')
# self.transient(parent)
self.title("New analysis project")
self.parent=parent
self.result=None
self.datatype=StringVar()
# self.linfirst=IntVar()
body=Frame(self)
self.initial_focus=self.body(self,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()+50,parent.winfo_rooty()+50))
self.initial_focus.focus_set()
self.wait_window(self)
def body(self,masterclass,masterwindow):
# self.b1=Checkbutton(masterwindow,text='Use linear bins for 1..10',variable=masterclass.linfirst,state=ACTIVE,bg='Gray80')
# self.b1.grid(row=0,column=0,columnspan=2)
self.wholeframe=Frame(masterwindow,relief='sunken',borderwidth=2)
self.clabel=Label(self.wholeframe,text="Select input data type:",justify=LEFT,anchor=W,bg='gray90',relief='groove',borderwidth=1)
self.clabel.pack(side=TOP,expand=YES,fill=X,ipadx=5,ipady=5)
self.bottompart=Frame(self.wholeframe)
r1=Radiobutton(self.bottompart,text='Genotype matrix, haploid, individual centred',value='ms_haploid',variable=masterclass.datatype)
r125=Radiobutton(self.bottompart,text='Genotype matrix, diploid, individual centred',value='ms_diploid',variable=masterclass.datatype)
r15=Radiobutton(self.bottompart,text='Genotype matrix, haploid, sampling site based',value='mpop_haploid',variable=masterclass.datatype)
r175=Radiobutton(self.bottompart,text='Genotype matrix, diploid, sampling site based',value='mpop_diploid',variable=masterclass.datatype)
r1875=Radiobutton(self.bottompart,text='Presence/absence matrix',value='presabs',variable=masterclass.datatype)
r19=Radiobutton(self.bottompart,text='Presence/abundancy matrix',value='presabu',variable=masterclass.datatype)
r2=Radiobutton(self.bottompart,text='Distance matrix',value='dmat',variable=masterclass.datatype)
r3=Radiobutton(self.bottompart,text='Network data',value='net',variable=masterclass.datatype)
r1.grid(row=1,column=0,sticky=W)
r125.grid(row=3,column=0,sticky=W)
r15.grid(row=2,column=0,sticky=W)
r175.grid(row=4,column=0,sticky=W)
r1875.grid(row=5,column=0,sticky=W)
r19.grid(row=6,column=0,sticky=W)
r2.grid(row=7,column=0,sticky=W)
r3.grid(row=8,column=0,sticky=W)
self.bottompart.pack(side=TOP,expand=YES,fill=BOTH,ipadx=7,ipady=7)
masterclass.datatype.set('ms_haploid')
self.wholeframe.pack(side=TOP,expand=YES,fill=BOTH)
return self.wholeframe
def applyme(self):
self.result=(self.datatype.get())
class ChooseMatrixNodeNames(MySimpleDialog):
"""First window shown when launching a new analysis wizard.
Inquires if the user wants to load microsatellite data,
a distance matrix, or a network file."""
def __init__(self,parent,title=None,titlemsg="How to set node labels?"):
Toplevel.__init__(self,parent)
#self.configure(bg='Gray80')
# self.transient(parent)
self.title(title)
self.titlemsg=titlemsg
self.parent=parent
self.result=None
self.measuretype=StringVar()
# self.linfirst=IntVar()
body=Frame(self)
self.initial_focus=self.body(self,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()+50,parent.winfo_rooty()+50))
self.initial_focus.focus_set()
self.wait_window(self)
def body(self,masterclass,masterwindow,titlemsg="How to set node labels?"):
self.wholeframe=Frame(masterwindow,relief='sunken',borderwidth=2)
self.clabel=Label(self.wholeframe,text=self.titlemsg,justify=LEFT,anchor=W,bg='gray90',relief='groove',borderwidth=1)
self.clabel.pack(side=TOP,expand=YES,fill=X,ipadx=5,ipady=5)
self.bottompart=Frame(self.wholeframe)
r1=Radiobutton(self.bottompart,text='From file',value='file',variable=masterclass.measuretype)
r2=Radiobutton(self.bottompart,text='1..N',value='numbers',variable=masterclass.measuretype)
r1.grid(row=1,column=0,sticky=W)
r2.grid(row=2,column=0,sticky=W)
self.bottompart.pack(side=TOP,expand=YES,fill=BOTH,ipadx=7,ipady=7)
masterclass.measuretype.set('nsa')
self.wholeframe.pack(side=TOP,expand=YES,fill=BOTH)
return self.wholeframe
def applyme(self):
self.result=(self.measuretype.get())
class ChooseDistanceMeasure(MySimpleDialog):
"""First window shown when launching a new analysis wizard.
Inquires if the user wants to load microsatellite data,
a distance matrix, or a network file."""
def __init__(self,parent,title=None,titlemsg="Choose genetic distance measure"):
Toplevel.__init__(self,parent)
#self.configure(bg='Gray80')
# self.transient(parent)
self.title(title)
self.titlemsg=titlemsg
self.parent=parent
self.result=None
self.measuretype=StringVar()
# self.linfirst=IntVar()
body=Frame(self)
self.initial_focus=self.body(self,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()+50,parent.winfo_rooty()+50))
self.initial_focus.focus_set()
self.wait_window(self)
def body(self,masterclass,masterwindow,titlemsg="Choose genetic distance measure"):
# self.b1=Checkbutton(masterwindow,text='Use linear bins for 1..10',variable=masterclass.linfirst,state=ACTIVE,bg='Gray80')
# self.b1.grid(row=0,column=0,columnspan=2)
self.wholeframe=Frame(masterwindow,relief='sunken',borderwidth=2)
self.clabel=Label(self.wholeframe,text=self.titlemsg,justify=LEFT,anchor=W,bg='gray90',relief='groove',borderwidth=1)
self.clabel.pack(side=TOP,expand=YES,fill=X,ipadx=5,ipady=5)
self.bottompart=Frame(self.wholeframe)
#r1=Radiobutton(self.bottompart,text='Non-shared alleles',value='nsa',variable=masterclass.measuretype)
r1=Radiobutton(self.bottompart,text='Allele Sharing',value='ap',variable=masterclass.measuretype)
r2=Radiobutton(self.bottompart,text='Linear Manhattan',value='lm',variable=masterclass.measuretype)
#r3=Radiobutton(self.bottompart,text='Allele parsimony',value='ap',variable=masterclass.measuretype)
#r4=Radiobutton(self.bottompart,text='Hybrid',value="hybrid",variable=masterclass.measuretype)
r1.grid(row=1,column=0,sticky=W)
r2.grid(row=2,column=0,sticky=W)
#r3.grid(row=3,column=0,sticky=W)
#r4.grid(row=4,column=0,sticky=W)
self.bottompart.pack(side=TOP,expand=YES,fill=BOTH,ipadx=7,ipady=7)
masterclass.measuretype.set('nsa')
self.wholeframe.pack(side=TOP,expand=YES,fill=BOTH)
return self.wholeframe
def applyme(self):
self.result=(self.measuretype.get())
class ImportMetadataYesNo(MySimpleDialog):
"""First window shown when launching a new analysis wizard.
Inquires if the user wants to load microsatellite data,
a distance matrix, or a network file."""
def __init__(self,parent,title=None,titlemsg="Do you want to import auxiliary node data?",datatype='msat'):
Toplevel.__init__(self,parent)
#self.configure(bg='Gray80')
# self.transient(parent)
self.title(title)
self.datatype=datatype
self.titlemsg=titlemsg
self.parent=parent
self.result=None
self.metatype=IntVar()
# self.linfirst=IntVar()
body=Frame(self)
self.initial_focus=self.body(self,body)
body.pack(padx=5,pady=5)
self.buttonbox(self.datatype)
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()+50,parent.winfo_rooty()+50))
self.initial_focus.focus_set()
self.wait_window(self)
def buttonbox(self,datatype='msat'):
"""OK, Cancel and Help 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)
w=Button(box,text="Help",width=10,command=lambda s=self,t=datatype: s.displayhelp(t))
w.pack(side=LEFT,padx=5,pady=5)
self.bind("<Return>",self.ok)
self.bind("<Escape",self.cancel)
box.pack()
def body(self,masterclass,masterwindow,titlemsg="Do you want to import auxiliary node data?"):
# self.b1=Checkbutton(masterwindow,text='Use linear bins for 1..10',variable=masterclass.linfirst,state=ACTIVE,bg='Gray80')
# self.b1.grid(row=0,column=0,columnspan=2)
self.wholeframe=Frame(masterwindow,relief='sunken',borderwidth=2)
self.clabel=Label(self.wholeframe,text=self.titlemsg,justify=LEFT,anchor=W,bg='gray90',relief='groove',borderwidth=1)
self.clabel.pack(side=TOP,expand=YES,fill=X,ipadx=5,ipady=5)
self.bottompart=Frame(self.wholeframe)
r1=Radiobutton(self.bottompart,text='Yes',value=1,variable=masterclass.metatype)
r2=Radiobutton(self.bottompart,text='No',value=0,variable=masterclass.metatype)
r1.grid(row=1,column=0,sticky=W)
r2.grid(row=2,column=0,sticky=W)
masterclass.metatype.set(1)
self.bottompart.pack(side=TOP,expand=YES,fill=BOTH,ipadx=7,ipady=7)
self.wholeframe.pack(side=TOP,expand=YES,fill=BOTH)
return self.wholeframe
def applyme(self):
self.result=(self.metatype.get())
def displayhelp(self,datatype):
MetaHelpWindow(self,datatype)
class MatrixDialog(MySimpleDialog):
"""Used when loading a matrix. Asks if the matrix contains weights or distances"""
def __init__(self,parent,title=None):
Toplevel.__init__(self,parent)
#self.configure(bg='Gray80')
# self.transient(parent)
if title:
self.title=title
self.parent=parent
self.result=None
self.mattype=IntVar()
# self.linfirst=IntVar()
body=Frame(self)
self.initial_focus=self.body(self,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()+50,parent.winfo_rooty()+50))
self.initial_focus.focus_set()
self.wait_window(self)
def body(self,masterclass,masterwindow):
# self.b1=Checkbutton(masterwindow,text='Use linear bins for 1..10',variable=masterclass.linfirst,state=ACTIVE,bg='Gray80')
# self.b1.grid(row=0,column=0,columnspan=2)
self.c1=Label(masterwindow,text='Matrix type:')
self.c1.grid(row=0,column=0)
r1=Radiobutton(masterwindow,text='Weight matrix',value=1,variable=masterclass.mattype)
r2=Radiobutton(masterwindow,text='Distance matrix',value=0,variable=masterclass.mattype)
r1.grid(row=0,column=1,sticky=W)
r2.grid(row=1,column=1,sticky=W)
masterclass.mattype.set(0)
return self.c1
def applyme(self):
self.result=(self.mattype.get())
class MsatDialog(MySimpleDialog):
"""Used when loading a matrix. Asks if the matrix contains weights or distances"""
def __init__(self,parent,title=None,titlemsg="Handling clones"):
Toplevel.__init__(self,parent)
#self.configure(bg='Gray80')
# self.transient(parent)
self.title(title)
self.titlemsg=titlemsg
self.parent=parent
self.result=None
self.mattype=IntVar()
# self.linfirst=IntVar()
body=Frame(self)
self.initial_focus=self.body(self,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()+50,parent.winfo_rooty()+50))
self.initial_focus.focus_set()
self.wait_window(self)
def body(self,masterclass,masterwindow,titlemsg="Handling clones"):
# self.b1=Checkbutton(masterwindow,text='Use linear bins for 1..10',variable=masterclass.linfirst,state=ACTIVE,bg='Gray80')
# self.b1.grid(row=0,column=0,columnspan=2)
self.wholeframe=Frame(masterwindow,relief='sunken',borderwidth=2)
self.clabel=Label(self.wholeframe,text=self.titlemsg,justify=LEFT,anchor=W,bg='gray90',relief='groove',borderwidth=1)
self.clabel.pack(side=TOP,expand=YES,fill=X,ipadx=5,ipady=5)
self.bottompart=Frame(self.wholeframe)
r1=Radiobutton(self.bottompart,text='Collapse clones',value=1,variable=masterclass.mattype)
r2=Radiobutton(self.bottompart,text='Leave clones',value=0,variable=masterclass.mattype)
r1.grid(row=1,column=0,sticky=W)
r2.grid(row=2,column=0,sticky=W)
self.bottompart.pack(side=TOP,expand=YES,fill=BOTH,ipadx=7,ipady=7)
self.wholeframe.pack(side=TOP,expand=YES,fill=BOTH)
masterclass.mattype.set(1)
return self.wholeframe
def applyme(self):
self.result=(self.mattype.get())
class VisualizationDialog(MySimpleDialog):
"""Asks options for network visualization"""
def __init__(self,parent,title=None):
Toplevel.__init__(self,parent)
#self.configure(bg='Gray80')
# self.transient(parent)
if title:
self.title=title
self.parent=parent
self.result=None
self.winsize=IntVar()
self.vtxsize=StringVar()
self.vtxcolor=StringVar()
self.bgcolor=StringVar()
self.showlabels=StringVar()
# self.linfirst=IntVar()
body=Frame(self)
self.initial_focus=self.body(self,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()+50,parent.winfo_rooty()+50))
self.initial_focus.focus_set()
self.wait_window(self)
def body(self,masterclass,masterwindow):
# self.b1=Checkbutton(masterwindow,text='Use linear bins for 1..10',variable=masterclass.linfirst,state=ACTIVE,bg='Gray80')
# self.b1.grid(row=0,column=0,columnspan=2)
self.c1=Label(masterwindow,text='Vertex color:')
self.c1.grid(row=0,column=0)
rowcount=-1
for text, value in [('Black','000000'),('White','999999'),('Red','990000'),('Green','009900'),('Blue','000099'),('By strength','-1')]:
rowcount+=1
Radiobutton(masterwindow,text=text,value=value,variable=masterclass.vtxcolor).grid(row=rowcount,column=1,sticky=W)
masterclass.vtxcolor.set('-1')
Label(masterwindow,text='Vertex size:').grid(row=rowcount+1,column=0)
for text, value in [('Small','0.4'),('Medium','0.7'),('Large','0.99'),('By strength','-1.0')]:
rowcount=rowcount+1
Radiobutton(masterwindow,text=text,value=value,variable=masterclass.vtxsize).grid(row=rowcount,column=1,sticky=W)
masterclass.vtxsize.set('-1.0')
Label(masterwindow,text='Show with:').grid(row=rowcount+1,column=0)
for text, value in [('White background','white'),('Black background','black')]:
rowcount=rowcount+1
Radiobutton(masterwindow,text=text,value=value,variable=masterclass.bgcolor).grid(row=rowcount,column=1,sticky=W)
masterclass.bgcolor.set('black')
Label(masterwindow,text="Vertex labels:").grid(row=rowcount+1,column=0)
for text, value in [('None','none'),('All','all'),('Top 10','top10')]:
rowcount=rowcount+1
Radiobutton(masterwindow,text=text,value=value,variable=masterclass.showlabels).grid(row=rowcount,column=1,sticky=W)
masterclass.showlabels.set('all')
return self.c1
def applyme(self):
self.result=(self.vtxcolor.get(),self.vtxsize.get(),self.bgcolor.get(),self.showlabels.get())
class AskThreshold(MySimpleDialog):
"""Asks threshold for thresholding"""
def __init__(self,parent,title=None):
Toplevel.__init__(self,parent)
#self.configure(bg='Gray80')
# self.transient(parent)
if title:
self.title=title
self.parent=parent
self.result=None
# self.linfirst=IntVar()
self.threshold=StringVar()
body=Frame(self)
self.initial_focus=self.body(self,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()+50,parent.winfo_rooty()+50))
self.initial_focus.focus_set()
self.wait_window(self)
def body(self,masterclass,masterwindow):
# self.b1=Checkbutton(masterwindow,text='Use linear bins for 1..10',variable=masterclass.linfirst,state=ACTIVE,bg='Gray80')
# self.b1.grid(row=0,column=0,columnspan=2)
Label(masterwindow,text='Threshold:').grid(row=1,column=0)
self.c1=Entry(masterwindow,textvariable=masterclass.threshold,bg='Gray95')
masterclass.threshold.set('0')
self.c1.grid(row=1,column=1)
return self.c1
def applyme(self):
self.result=float(self.threshold.get())
class PercolationDialog(MySimpleDialog):
"""First window shown when launching a new analysis wizard.
Inquires if the user wants to load microsatellite data,
a distance matrix, or a network file."""
def __init__(self,parent,title=None,titlemsg="Set threshold distance",pdata=[],suscmax_thresh=0.0):
Toplevel.__init__(self,parent)
#self.configure(bg='Gray80')
# self.transient(parent)
self.title(title)
self.titlemsg=titlemsg
self.parent=parent
self.result=None
self.data=pdata
self.default_thresh=suscmax_thresh
self.threshold=StringVar()
# self.linfirst=IntVar()
body=Frame(self)
self.initial_focus=self.body(self,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()+50,parent.winfo_rooty()+50))
self.initial_focus.focus_set()
self.wait_window(self)
def body(self,masterclass,masterwindow,titlemsg="Choose genetic distance measure"):
# self.b1=Checkbutton(masterwindow,text='Use linear bins for 1..10',variable=masterclass.linfirst,state=ACTIVE,bg='Gray80')
# self.b1.grid(row=0,column=0,columnspan=2)
self.wholeframe=Frame(masterwindow,relief='groove',borderwidth=2,bg="Gray95")
# self.clabel=Label(self.wholeframe,text=self.titlemsg,bg='DarkOliveGreen2',relief='groove',borderwidth=1)
# self.clabel.pack(side=TOP,expand=YES,fill=X,ipadx=5,ipady=5)
self.midpart=Frame(self.wholeframe)
myplot=visuals.ReturnPlotObject(self.data,plotcommand="plot",addstr=",color=\"#9e0b0f\"",titlestring="Largest component size:Susceptibility",xstring="Threshold distance",ystring="GCC size:Susceptibility",fontsize=9)
myplot.canvas=FigureCanvasTkAgg(myplot.thisFigure,master=self.midpart)
myplot.canvas.show()
myplot.canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=YES, padx=10,pady=10)
self.midpart.pack(side=TOP,expand=YES,fill=BOTH)
self.bottompart=Frame(self.wholeframe)
Label(self.bottompart,text='Estimated percolation threshold = %2.2f' % self.default_thresh).grid(row=1,column=0,columnspan=2)
Label(self.bottompart,text='Threshold: ').grid(row=2,column=0)
self.c1=Entry(self.bottompart,textvariable=masterclass.threshold,bg='Gray95')
masterclass.threshold.set(str(self.default_thresh))
self.c1.grid(row=2,column=1)
self.bottompart.pack(side=TOP,expand=YES,fill=BOTH,ipadx=7,ipady=7)
self.wholeframe.pack(side=TOP,expand=YES,fill=BOTH)
return self.wholeframe
def applyme(self):
self.result=(self.threshold.get())
class VisualizationOptions(MySimpleDialog):
"""First window shown when launching a new analysis wizard.
Inquires if the user wants to load microsatellite data,
a distance matrix, or a network file."""
def __init__(self,parent,network,title=None,titlemsg="Choose visualization options"):
Toplevel.__init__(self,parent)
#self.configure(bg='Gray80')
# self.transient(parent)
self.title(title)
self.titlemsg=titlemsg
self.parent=parent
self.result=None
self.vcolor=StringVar()
self.vsize=StringVar()
self.bgcolor=IntVar()
# self.linfirst=IntVar()
body=Frame(self)
self.initial_focus=self.body(self,body)
body.pack(padx=5,pady=5)
self.buttonbox(self.datatype)
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()+50,parent.winfo_rooty()+50))
self.initial_focus.focus_set()
self.wait_window(self)
def buttonbox(self,datatype='msat'):
"""OK, Cancel and Help 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()
def body(self,masterclass,masterwindow,titlemsg="Select visualization options"):
# self.b1=Checkbutton(masterwindow,text='Use linear bins for 1..10',variable=masterclass.linfirst,state=ACTIVE,bg='Gray80')
# self.b1.grid(row=0,column=0,columnspan=2)
self.wholeframe=Frame(masterwindow,relief='sunken',borderwidth=2)
self.clabel=Label(self.wholeframe,text=self.titlemsg,justify=LEFT,anchor=W,bg='gray90',relief='groove',borderwidth=1)
self.clabel.pack(side=TOP,expand=YES,fill=X,ipadx=5,ipady=5)
self.bottompart=Frame(self.wholeframe)
scrollbar = Scrollbar(self.bottompart, orient=VERTICAL)
listbox = Listbox(self.bottompart, yscrollcommand=scrollbar.set)
scrollbar.config(command=listbox.yview)
scrollbar.pack(side=RIGHT, fill=Y)
listbox.pack(side=LEFT, fill=BOTH, expand=1)
listbox.insert(END,'none')
listbox.insert(END,'by degree')
plist=netext.getNumericProperties(network)
for prop in plist:
listbox.insert(END,prop)
self.bottompart.pack(side=TOP,expand=YES,fill=BOTH,ipadx=7,ipady=7)
self.wholeframe.pack(side=TOP,expand=YES,fill=BOTH)
return self.wholeframe
def applyme(self):
#self.result=(self.metatype.get())
pass
def displayhelp(self,datatype):
MetaHelpWindow(self,datatype)
class SliderDialog(MySimpleDialog):
"""Dialog for inputting a value using a slider (e.g. for font sizes etc)"""
def __init__(self,parent,title=None,titlemsg="Select label font size",minval=0,maxval=100,currval=7):
Toplevel.__init__(self,parent)
#self.configure(bg='Gray80')
# self.transient(parent)
self.title(title)
self.titlemsg=titlemsg
self.parent=parent
self.result=None
self.slidertype=IntVar()
self.minval=minval
self.maxval=maxval
self.currval=currval
# self.linfirst=IntVar()
body=Frame(self)
self.initial_focus=self.body(self,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()+50,parent.winfo_rooty()+50))
self.initial_focus.focus_set()
self.wait_window(self)
def body(self,masterclass,masterwindow,titlemsg="Select label font size"):
# self.b1=Checkbutton(masterwindow,text='Use linear bins for 1..10',variable=masterclass.linfirst,state=ACTIVE,bg='Gray80')
# self.b1.grid(row=0,column=0,columnspan=2)
self.wholeframe=Frame(masterwindow,relief='sunken',borderwidth=2)
self.clabel=Label(self.wholeframe,text=self.titlemsg,justify=LEFT,anchor=W,bg='gray90',relief='groove',borderwidth=1)
self.clabel.pack(side=TOP,expand=YES,fill=X,ipadx=5,ipady=5)
self.bottompart=Frame(self.wholeframe)
self.scale=Scale(self.bottompart, from_=self.minval, to=self.maxval, orient=HORIZONTAL)
self.scale.set(self.currval)
self.scale.pack()
self.bottompart.pack(side=TOP,expand=YES,fill=BOTH,ipadx=7,ipady=7)
self.wholeframe.pack(side=TOP,expand=YES,fill=BOTH)
return self.wholeframe
def applyme(self):
self.result=(self.scale.get())
class DoubleSliderDialog(MySimpleDialog):
"""Dialog for inputting a value using a slider (e.g. for font sizes etc)"""
def __init__(self,parent,title=None,titlemsg="Select label font size",resolution=1,minval_1=0,maxval_1=100,currval_1=7,minval_2=0,maxval_2=0,currval_2=7,slidertext_1='min',slidertext_2='max'):
Toplevel.__init__(self,parent)
#self.configure(bg='Gray80')
# self.transient(parent)
self.title(title)
self.titlemsg=titlemsg
self.parent=parent
self.result=None
self.slidertype_1=IntVar()
self.minval_1=minval_1
self.maxval_1=maxval_1
self.currval_1=currval_1
self.slidertext_1=slidertext_1
self.resolution=resolution
self.slidertype_2=IntVar()
self.minval_2=minval_2
self.maxval_2=maxval_2
self.currval_2=currval_2
self.slidertext_2=slidertext_2
# self.linfirst=IntVar()
body=Frame(self)
self.initial_focus=self.body(self,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()+50,parent.winfo_rooty()+50))
self.initial_focus.focus_set()
self.wait_window(self)
def body(self,masterclass,masterwindow,titlemsg="Select label font size"):
# self.b1=Checkbutton(masterwindow,text='Use linear bins for 1..10',variable=masterclass.linfirst,state=ACTIVE,bg='Gray80')
# self.b1.grid(row=0,column=0,columnspan=2)
self.wholeframe=Frame(masterwindow,relief='sunken',borderwidth=2)
self.clabel=Label(self.wholeframe,text=self.titlemsg,justify=LEFT,anchor=W,bg='gray90',relief='groove',borderwidth=1)
self.clabel.pack(side=TOP,expand=YES,fill=X,ipadx=5,ipady=5)
self.bottompart=Frame(self.wholeframe)
Label(self.bottompart,text=self.slidertext_1,justify=LEFT,anchor=W,bg='gray90',relief='groove',borderwidth=1).grid(row=0,column=0)
self.scale_1=Scale(self.bottompart, from_=self.minval_1, to=self.maxval_1, orient=HORIZONTAL,resolution=self.resolution)
self.scale_1.set(self.currval_1)
self.scale_1.grid(row=0,column=1)
Label(self.bottompart,text=self.slidertext_2,justify=LEFT,anchor=W,bg='gray90',relief='groove',borderwidth=1).grid(row=1,column=0)
self.scale_2=Scale(self.bottompart, from_=self.minval_2, to=self.maxval_2, orient=HORIZONTAL,resolution=self.resolution)
self.scale_2.set(self.currval_2)
self.scale_2.grid(row=1,column=1)
self.bottompart.pack(side=TOP,expand=YES,fill=BOTH,ipadx=7,ipady=7)
self.wholeframe.pack(side=TOP,expand=YES,fill=BOTH)
return self.wholeframe
def applyme(self):
self.result=[self.scale_1.get(),self.scale_2.get()]
class ColorMapDialog(MySimpleDialog):
"""Lists color maps and asks to choose one"""
def __init__(self,parent,title='Select color map:',current_map='orange'):
Toplevel.__init__(self,parent)
# self.configure(bg='Gray80')
# self.transient(parent)
self.title(title)
self.parent=parent
self.result=None
self.current_map=current_map
self.colormap=StringVar()
body=Frame(self)
self.initial_focus=self.body(self,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()+50,parent.winfo_rooty()+50))
self.initial_focus.focus_set()
self.wait_window(self)
def body(self,masterclass,masterwindow):
self.c1=Label(masterwindow,text='Please choose color map',anchor=W)
self.c1.grid(row=0,column=0)
colormaps=["orange","hsv","jet","spectral","winter","Accent","Paired","binary","gray"]
rowcounter=1
curr_frame=[]
curr_plot=[]
for cmap in colormaps:
Radiobutton(masterwindow,text=cmap,value=cmap,variable=masterclass.colormap).grid(row=rowcounter,column=0,sticky=W)
curr_frame.append(Frame(masterwindow))
curr_plot.append(visuals.ReturnColorMapPlot(cmap))
curr_plot[-1].canvas=FigureCanvasTkAgg(curr_plot[-1],curr_frame[-1])
curr_plot[-1].canvas.show()
curr_plot[-1].canvas.get_tk_widget().grid(row=rowcounter,column=1)
curr_frame[-1].grid(row=rowcounter,column=1,sticky=W)
rowcounter=rowcounter+1
if self.current_map in colormaps:
masterclass.colormap.set(self.current_map)
else:
masterclass.colormap.set('orange')
return self.c1
def applyme(self):
self.result=self.colormap.get()
class WaitWindow(MySimpleDialog):
"""Used when loading a matrix. Asks if the matrix contains weights or distances"""
def __init__(self,parent,title=None,titlemsg="Please wait...",hasProgressbar=False):
Toplevel.__init__(self,parent)
#self.configure(bg='Gray80')
#self.transient(parent)
self.title(title)
self.titlemsg=titlemsg
self.parent=parent
self.hasProgressbar=hasProgressbar
self.result=None
body=Frame(self)
self.initial_focus=self.body(self,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()+50,parent.winfo_rooty()+50))
self.initial_focus.focus_set()
def go(self,lambda_operation):
self.result=lambda_operation()
self.ok()
#self.wait_window(self)
def body(self,masterclass,masterwindow,titlemsg="Please wait..."):
self.wholeframe=Frame(masterwindow,relief='sunken',borderwidth=2)
self.clabel=Label(self.wholeframe,text=self.titlemsg,
justify=LEFT,
anchor=W,
bg='darkolivegreen2',
relief='groove',borderwidth=1,padx=3,pady=3,width=40)
self.clabel.pack(side=TOP,expand=YES,fill=X,ipadx=5,ipady=5)
self.bottompart=Frame(self.wholeframe)
self.l1=Label(self.bottompart,text=self.titlemsg,justify=LEFT,
anchor=W,bg='white',relief='flat',padx=3,pady=3)
self.l1.grid(row=1,column=0,sticky=W)
self.l1['fg']='black'
if self.hasProgressbar:
self.progressbar=Meter(self.bottompart,value=0.0)
self.progressbar.grid(row=4,column=0,sticky=W)
self.updatePointer=self.progressbar.set
self.bottompart.pack(side=TOP,expand=YES,fill=BOTH,ipadx=7,ipady=7)
self.wholeframe.pack(side=TOP,expand=YES,fill=BOTH)
return self.wholeframe
def applyme(self):
return self.result
class MsLoadWaiter(MySimpleDialog):
"""Used when loading a matrix. Asks if the matrix contains weights or distances"""
def __init__(self,parent,inputfile,removeclones,measuretype,title="Processing microsatellite data",titlemsg="Please wait",nodeNames=None,datatype=None):
Toplevel.__init__(self,parent)
self.title(title)
self.titlemsg=titlemsg
self.parent=parent
self.datatype=datatype
self.result=None
body=Frame(self)
self.initial_focus=self.body(self,body)
body.pack(padx=5,pady=5)
#self.buttonbox()
self.grab_set()
self.points=['.','..','...']
self.pointcounter=0
self.displayBusyCursor()
if not self.initial_focus:
self.initial_focus(self)
self.protocol("WM_DELETE_WINDOW",self.cancel)
self.geometry("+%d+%d" % (parent.winfo_rootx()+50,parent.winfo_rooty()+50))
self.initial_focus.focus_set()
self.l1['fg']='#b0b0b0'
self.l1.update()
if removeclones:
self.l2['text']='Removing clones...'
self.l2['fg']='black'
self.l2.update()
if datatype=="ms_diploid":
msdata_initial=eden.MicrosatelliteData(inputfile)
else:
msdata_initial=eden.MicrosatelliteDataHaploid(inputfile)
if removeclones:
[msdata,keeptheserows]=msdata_initial.getUniqueSubset(returnOldIndices=True)
clones='collapsed'
if nodeNames!=None:
newNodeNames=[]
keeptheserows=sorted(keeptheserows)
for row in keeptheserows:
newNodeNames.append(nodeNames[row])
nodeNames=newNodeNames
else:
nodeNames=sorted(keeptheserows)
# trick to accommodate for (possible) node properties - we will use only "keeptheserows" containing indices to non-clonal samples
else:
msdata=msdata_initial
clones='included'
keeptheserows=None
self.clones=clones
self.keeptheserows=keeptheserows
self.l3['text']='Calculating distance matrix...'
self.l3['fg']='black'
self.l3.update()
self.l2['fg']='#b0b0b0'
self.l2.update()
m=msdata.getDistanceMatrix(measuretype,nodeNames=nodeNames,progressUpdater=self.progressbar.set)
if removeclones:
Nclones=msdata_initial.getNumberOfNodes()-len(keeptheserows)
else:
Nclones=None
self.Nclones=Nclones
self.m=m
self.msdata=msdata
self.ok()
def animate(self):
self.pointcounter=self.pointcounter+1
if self.pointcounter==3:
self.pointcounter=0
self.clabel['text']=self.titlemsg+self.points[self.pointcounter]
self.clabel.update()
self.after(500,self.animate)
def body(self,masterclass,masterwindow,titlemsg="Please wait!"):
# self.b1=Checkbutton(masterwindow,text='Use linear bins for 1..10',variable=masterclass.linfirst,state=ACTIVE,bg='Gray80')
# self.b1.grid(row=0,column=0,columnspan=2)
self.wholeframe=Frame(masterwindow,relief='sunken',borderwidth=2)
self.clabel=Label(self.wholeframe,text=self.titlemsg,
justify=LEFT,
anchor=W,
bg='darkolivegreen2',
relief='groove',borderwidth=1,padx=3,pady=3,width=40)
self.clabel.pack(side=TOP,expand=YES,fill=X,ipadx=5,ipady=5)
self.bottompart=Frame(self.wholeframe)
self.l1=Label(self.bottompart,text='Reading file...',justify=LEFT,
anchor=W,bg='white',relief='flat',padx=3,pady=3)
self.l1.grid(row=1,column=0,sticky=W)
self.l1['fg']='black'
self.l2=Label(self.bottompart,text='-',justify=LEFT,
anchor=W,bg='white',relief='flat',padx=3,pady=3)
self.l2.grid(row=2,column=0,sticky=W)
self.l3=Label(self.bottompart,text='-',justify=LEFT,
anchor=W,bg='white',relief='flat',padx=3,pady=3)
self.l3.grid(row=3,column=0,sticky=W)
self.progressbar=Meter(self.bottompart,value=0.0)
self.progressbar.grid(row=4,column=0,sticky=W)
self.bottompart.pack(side=TOP,expand=YES,fill=BOTH,ipadx=7,ipady=7)
self.wholeframe.pack(side=TOP,expand=YES,fill=BOTH)
return self.wholeframe
def applyme(self):
self.result=[self.Nclones,self.clones,self.keeptheserows,self.m,self.msdata]
class LoadWaiter(MySimpleDialog):
"""Display progress bar while doing something."""
def __init__(self,parent,function,args=[],kwargs=None,callback_function_parameter="progressUpdater",bodymsg="Processing...",titlemsg="Please wait"):
Toplevel.__init__(self,parent)
title=titlemsg
if kwargs==None:
kwargs={}
self.title(title)
self.titlemsg=titlemsg
self.parent=parent
self.result=None
body=Frame(self)
self.initial_focus=self.body(self,body,titlemsg=titlemsg,bodymsg=bodymsg)
body.pack(padx=5,pady=5)
#self.buttonbox()
self.grab_set()
self.points=['.','..','...']
self.pointcounter=0
self.displayBusyCursor()
if not self.initial_focus:
self.initial_focus(self)
self.protocol("WM_DELETE_WINDOW",self.cancel)
self.geometry("+%d+%d" % (parent.winfo_rootx()+50,parent.winfo_rooty()+50))
self.initial_focus.focus_set()
self.l1['fg']='#b0b0b0'
self.l1.update()
kwargs[callback_function_parameter]=self.progressbar.set
self.output=function(*args,**kwargs)
self.ok()
def animate(self):
self.pointcounter=self.pointcounter+1
if self.pointcounter==3:
self.pointcounter=0
self.clabel['text']=self.titlemsg+self.points[self.pointcounter]
self.clabel.update()
self.after(500,self.animate)
def body(self,masterclass,masterwindow,titlemsg="",bodymsg=""):
self.wholeframe=Frame(masterwindow,relief='sunken',borderwidth=2)
self.clabel=Label(self.wholeframe,text=self.titlemsg,
justify=LEFT,
anchor=W,
bg='darkolivegreen2',
relief='groove',borderwidth=1,padx=3,pady=3,width=40)
self.clabel.pack(side=TOP,expand=YES,fill=X,ipadx=5,ipady=5)
self.bottompart=Frame(self.wholeframe)
self.l1=Label(self.bottompart,text=bodymsg,justify=LEFT,
anchor=W,bg='white',relief='flat',padx=3,pady=3)
self.l1.grid(row=1,column=0,sticky=W)
self.l1['fg']='black'
"""
self.l2=Label(self.bottompart,text='-',justify=LEFT,
anchor=W,bg='white',relief='flat',padx=3,pady=3)
self.l2.grid(row=2,column=0,sticky=W)
self.l3=Label(self.bottompart,text='-',justify=LEFT,
anchor=W,bg='white',relief='flat',padx=3,pady=3)
self.l3.grid(row=3,column=0,sticky=W)
"""
self.progressbar=Meter(self.bottompart,value=0.0)
self.progressbar.grid(row=4,column=0,sticky=W)
self.bottompart.pack(side=TOP,expand=YES,fill=BOTH,ipadx=7,ipady=7)
self.wholeframe.pack(side=TOP,expand=YES,fill=BOTH)
return self.wholeframe
def applyme(self):
self.result=self.output
class GenericLoadWaiter(MySimpleDialog):
"""Generic class for wait windows displaying one item"""
def __init__(self,parent,filename,removeclones,measuretype,title=None,titlemsg="Please wait",specmsg="Processing"):
Toplevel.__init__(self,parent)
#self.configure(bg='Gray80')
# self.transient(parent)
self.title(title)
self.titlemsg=titlemsg
self.specmsg=specmsg
self.parent=parent
self.result=None
body=Frame(self)
self.initial_focus=self.body(self,body)
body.pack(padx=5,pady=5)
#self.buttonbox()
self.grab_set()
self.points=['.','..','...']
self.pointcounter=0
self.displayBusyCursor()
if not self.initial_focus:
self.initial_focus(self)
self.protocol("WM_DELETE_WINDOW",self.cancel)
self.geometry("+%d+%d" % (parent.winfo_rootx()+50,parent.winfo_rooty()+50))
self.initial_focus.focus_set()
# INSERT YOUR FUNCTIONALITY HERE
self.ok()
def body(self,masterclass,masterwindow,titlemsg="Please wait!"):
self.wholeframe=Frame(masterwindow,relief='sunken',borderwidth=2)
self.clabel=Label(self.wholeframe,text=self.titlemsg,justify=LEFT,anchor=W,bg='darkolivegreen2',relief='groove',borderwidth=1,padx=3,pady=3,width=40)
self.clabel.pack(side=TOP,expand=YES,fill=X,ipadx=5,ipady=5)
self.bottompart=Frame(self.wholeframe)
self.l1=Label(self.bottompart,text=self.specmsg,justify=LEFT,anchor=W,bg='white',relief='flat',padx=3,pady=3)
self.l1.grid(row=1,column=0,sticky=W)
self.l1['fg']='black'
self.bottompart.pack(side=TOP,expand=YES,fill=BOTH,ipadx=7,ipady=7)
self.wholeframe.pack(side=TOP,expand=YES,fill=BOTH)
return self.wholeframe
class MetaLoadWaiter(GenericLoadWaiter):
"""Generic class for wait windows displaying one item"""
def __init__(self,parent,m,keeptheserows,title=None,titlemsg="Please wait",specmsg="Processing"):
Toplevel.__init__(self,parent)
#self.configure(bg='Gray80')
# self.transient(parent)
self.title(title)
self.titlemsg=titlemsg
self.specmsg=specmsg
self.parent=parent
self.result=None
body=Frame(self)
self.initial_focus=self.body(self,body)
body.pack(padx=5,pady=5)
# self.buttonbox()
self.grab_set()
self.points=['.','..','...']
self.pointcounter=0
self.displayBusyCursor()
if not self.initial_focus:
self.initial_focus(self)
self.protocol("WM_DELETE_WINDOW",self.cancel)
self.geometry("+%d+%d" % (parent.winfo_rootx()+50,parent.winfo_rooty()+50))
self.initial_focus.focus_set()
self.distancematrix=transforms.filterNet(m,keeptheserows)
self.ok()
def applyme(self):
self.result=self.distancematrix
class HimmeliWaiter(GenericLoadWaiter):
"""Generic class for wait windows displaying one item"""
def __init__(self,parent,net,time,usemst,coordinates=None,title=None,titlemsg="Please wait",specmsg="Processing..."):
Toplevel.__init__(self,parent)
#self.configure(bg='Gray80')
self.transient(parent)
self.title(title)
self.titlemsg=titlemsg
self.specmsg=specmsg
self.parent=parent
self.result=None
body=Frame(self)
self.initial_focus=self.body(self,body)
body.pack(padx=5,pady=5)
# self.buttonbox()
self.grab_set()
self.points=['.','..','...']
self.pointcounter=0
self.displayBusyCursor()
if not self.initial_focus:
self.initial_focus(self)
self.protocol("WM_DELETE_WINDOW",self.cancel)
self.geometry("+%d+%d" % (parent.winfo_rootx()+50,parent.winfo_rooty()+50))
self.initial_focus.focus_set()
if usemst:
h=visuals.Himmeli(net,time=time,coordinates=coordinates,useMST=usemst)
else:
h=visuals.Himmeli(net,time=time,useMST=usemst)
self.coords=h.getCoordinates()
del h
self.ok()
def applyme(self):
self.result=self.coords
class Meter(Frame):
'''A simple progress bar widget.
Made by Michael'''
def __init__(self, master, fillcolor='orchid1', text='',
value=0.0, **kw):
Frame.__init__(self, master, bg='white', width=350,
height=20)
self.configure(**kw)
self._c = Canvas(self, bg=self['bg'],
width=self['width'], height=self['height'],\
highlightthickness=0, relief='flat',
bd=0)
self._c.pack(fill='x', expand=1)
self._r = self._c.create_rectangle(0, 0, 0,
int(self['height']), fill=fillcolor, width=0)
self._t = self._c.create_text(int(self['width'])/2,
int(self['height'])/2, text='')
self.set(value, text)
def set(self, value=0.0, text=None):
#make the value failsafe:
if value < 0.0:
value = 0.0
elif value > 1.0:
value = 1.0
if text == None:
#if no text is specified get the default percentage string:
text = str(int(round(100 * value))) + ' %'
self._c.coords(self._r, 0, 0, int(self['width']) * value,
int(self['height']))
self._c.itemconfigure(self._t, text=text)
self.update()
class BootstrapPopulationsDialog(MySimpleDialog):
"""Asks for the number of bins for log binning
and allows linear bins for 1...10"""
def __init__(self,parent,title='Please provide information:',initRuns=100):
Toplevel.__init__(self,parent)
self.title(title)
self.parent=parent
self.result=None
self.initRuns=initRuns
self.nRuns=StringVar()
body=Frame(self)
self.initial_focus=self.body(self,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()+50,parent.winfo_rooty()+50))
self.initial_focus.focus_set()
self.wait_window(self)
def body(self,masterclass,masterwindow):
self.c1=Label(masterwindow,text='Number of repetitions?',
anchor=W)
self.c1.grid(row=0,column=0)
self.e1=Entry(masterwindow,textvariable=self.nRuns,bg='Gray95')
self.nRuns.set(str(self.initRuns))
self.e1.grid(row=1,column=0)
self.c2=Label(masterwindow,text='Percentage of nodes in each location?',
anchor=W)
self.c2.grid(row=2,column=0)
self.scale_1=Scale(masterwindow, from_=0.0, to=1.0,
orient=HORIZONTAL,resolution=0.01)
self.scale_1.set(0.5)
self.scale_1.grid(row=3,column=0)
return self.c1
def applyme(self):
self.result=[self.scale_1.get(),self.e1.get()]
class SliderDialog2(MySimpleDialog):
"""Asks for the number of bins for log binning
and allows linear bins for 1...10"""
def __init__(self,parent,sMin,sMax,sRes,sStart,title='Please provide information:',bodyText="How much?"):
Toplevel.__init__(self,parent)
self.title(title)
self.sMin=sMin
self.sMax=sMax
self.sRes=sRes
self.sStart=sStart
self.bodyText=bodyText
self.parent=parent
self.result=None
self.clones=StringVar()
self.measuretype=StringVar()
body=Frame(self)
self.initial_focus=self.body(self,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()+50,parent.winfo_rooty()+50))
self.initial_focus.focus_set()
self.wait_window(self)
def body(self,masterclass,masterwindow):
self.c=Label(masterwindow,text='Percentage of nodes in each location?',
anchor=W)
self.c.grid(row=0,column=0)
self.scale=Scale(masterwindow, from_=self.sMin, to=self.sMax,
orient=HORIZONTAL,resolution=self.sRes)
self.scale.set(self.sStart)
self.scale.grid(row=1,column=0)
return self.c
def applyme(self):
self.result=self.scale.get()
class AskNumberDialog(MySimpleDialog):
"""Asks for a number
"""
def __init__(self,parent,title='Please provide information:',bodyText="Number: ",initNumber=100):
Toplevel.__init__(self,parent)
self.title(title)
self.bodyText=bodyText
self.parent=parent
self.result=None
self.initNumber=initNumber
self.theNumber=StringVar()
#self.measuretype=StringVar()
body=Frame(self)
self.initial_focus=self.body(self,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()+50,parent.winfo_rooty()+50))
self.initial_focus.focus_set()
self.wait_window(self)
def body(self,masterclass,masterwindow):
self.c1=Label(masterwindow,text=self.bodyText,
anchor=W)
self.c1.grid(row=0,column=0)
self.e1=Entry(masterwindow,textvariable=self.theNumber,bg='Gray95')
self.theNumber.set(str(self.initNumber))
self.e1.grid(row=1,column=0)
return self.c1
def applyme(self):
self.result=self.e1.get()
class EDENRadioDialog(MySimpleDialog):
"""A dialog with a radio selector."""
def __init__(self,parent,title=None,titlemsg="Choose one:",options=["Default"]):
Toplevel.__init__(self,parent)
self.title(title)
self.titlemsg=titlemsg
self.parent=parent
self.options=options
self.result=StringVar()
body=Frame(self)
self.initial_focus=self.body(self,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()+50,parent.winfo_rooty()+50))
self.initial_focus.focus_set()
self.wait_window(self)
def body(self,masterclass,masterwindow,titlemsg="Choose genetic distance measure"):
self.wholeframe=Frame(masterwindow,relief='sunken',borderwidth=2)
self.clabel=Label(self.wholeframe,text=self.titlemsg,justify=LEFT,anchor=W,bg='gray90',relief='groove',borderwidth=1)
self.clabel.pack(side=TOP,expand=YES,fill=X,ipadx=5,ipady=5)
self.bottompart=Frame(self.wholeframe)
buttons=[]
for i,value in enumerate(masterclass.options):
r=Radiobutton(self.bottompart,text=value,value=value,variable=masterclass.result)
r.grid(row=i+1,column=0,sticky=W)
masterclass.result.set(masterclass.options[0])
self.bottompart.pack(side=TOP,expand=YES,fill=BOTH,ipadx=7,ipady=7)
self.wholeframe.pack(side=TOP,expand=YES,fill=BOTH)
return self.wholeframe
def applyme(self):
self.result=(self.result.get())
| bolozna/EDENetworks | netpython/dialogues.py | Python | gpl-2.0 | 64,787 |
import os
from glob import glob
from pyramid.path import AssetResolver
from reportlab.lib.units import mm
from reportlab.pdfgen import canvas
from ..models import generate_random_digest
__all__ = [
'generate_random_filename',
'delete_files',
'NumberedCanvas'
]
def generate_random_filename(path=None, extension='pdf'):
r = AssetResolver('erp')
path = path or r.resolve('static/temp').abspath()
if not os.path.exists(path):
os.mkdir(path)
filename = generate_random_digest()
return '/'.join([path, '{filename}.{extension}'.format(filename=filename, extension=extension)])
def delete_files(expression):
files = glob(expression)
if files:
os.remove(*files)
class NumberedCanvas(canvas.Canvas):
def __init__(self, *args, **kwargs):
canvas.Canvas.__init__(self, *args, **kwargs)
self._saved_page_states = []
def showPage(self):
self._saved_page_states.append(dict(self.__dict__))
self._startPage()
def save(self):
"""add page info to each page (page x of y)"""
num_pages = len(self._saved_page_states)
for state in self._saved_page_states:
self.__dict__.update(state)
self.draw_page_number(num_pages)
canvas.Canvas.showPage(self)
canvas.Canvas.save(self)
def draw_page_number(self, page_count):
self.setFont("Helvetica", 7)
self.drawRightString(200*mm, 10*mm,
"Page %d of %d" % (self._pageNumber, page_count))
| dbbaleva/ERP-Forwarding | erp/reports/util.py | Python | gpl-2.0 | 1,516 |
# -*- coding: utf-8 -*-
"""
***************************************************************************
ExportGeometryInfo.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
***************************************************************************
* *
* 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. *
* *
***************************************************************************
"""
__author__ = 'Victor Olaya'
__date__ = 'August 2012'
__copyright__ = '(C) 2012, Victor Olaya'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'
import os
from qgis.PyQt.QtGui import QIcon
from qgis.PyQt.QtCore import QVariant
from qgis.core import (QgsCoordinateTransform,
QgsField,
QgsFields,
QgsWkbTypes,
QgsFeatureSink,
QgsDistanceArea,
QgsProcessingUtils,
QgsProcessingParameterFeatureSource,
QgsProcessingParameterEnum,
QgsProcessingParameterFeatureSink)
from processing.algs.qgis.QgisAlgorithm import QgisAlgorithm
from processing.tools import vector
pluginPath = os.path.split(os.path.split(os.path.dirname(__file__))[0])[0]
class ExportGeometryInfo(QgisAlgorithm):
INPUT = 'INPUT'
METHOD = 'CALC_METHOD'
OUTPUT = 'OUTPUT'
def icon(self):
return QIcon(os.path.join(pluginPath, 'images', 'ftools', 'export_geometry.png'))
def tags(self):
return self.tr('export,add,information,measurements,areas,lengths,perimeters,latitudes,longitudes,x,y,z,extract,points,lines,polygons').split(',')
def group(self):
return self.tr('Vector geometry')
def __init__(self):
super().__init__()
self.export_z = False
self.export_m = False
self.distance_area = None
self.calc_methods = [self.tr('Layer CRS'),
self.tr('Project CRS'),
self.tr('Ellipsoidal')]
def initAlgorithm(self, config=None):
self.addParameter(QgsProcessingParameterFeatureSource(self.INPUT,
self.tr('Input layer')))
self.addParameter(QgsProcessingParameterEnum(self.METHOD,
self.tr('Calculate using'), options=self.calc_methods, defaultValue=0))
self.addParameter(QgsProcessingParameterFeatureSink(self.OUTPUT, self.tr('Added geom info')))
def name(self):
return 'exportaddgeometrycolumns'
def displayName(self):
return self.tr('Export geometry columns')
def processAlgorithm(self, parameters, context, feedback):
source = self.parameterAsSource(parameters, self.INPUT, context)
method = self.parameterAsEnum(parameters, self.METHOD, context)
wkb_type = source.wkbType()
fields = source.fields()
new_fields = QgsFields()
if QgsWkbTypes.geometryType(wkb_type) == QgsWkbTypes.PolygonGeometry:
new_fields.append(QgsField('area', QVariant.Double))
new_fields.append(QgsField('perimeter', QVariant.Double))
elif QgsWkbTypes.geometryType(wkb_type) == QgsWkbTypes.LineGeometry:
new_fields.append(QgsField('length', QVariant.Double))
else:
new_fields.append(QgsField('xcoord', QVariant.Double))
new_fields.append(QgsField('ycoord', QVariant.Double))
if QgsWkbTypes.hasZ(source.wkbType()):
self.export_z = True
new_fields.append(QgsField('zcoord', QVariant.Double))
if QgsWkbTypes.hasM(source.wkbType()):
self.export_m = True
new_fields.append(QgsField('mvalue', QVariant.Double))
fields = QgsProcessingUtils.combineFields(fields, new_fields)
(sink, dest_id) = self.parameterAsSink(parameters, self.OUTPUT, context,
fields, wkb_type, source.sourceCrs())
coordTransform = None
# Calculate with:
# 0 - layer CRS
# 1 - project CRS
# 2 - ellipsoidal
self.distance_area = QgsDistanceArea()
if method == 2:
self.distance_area.setSourceCrs(source.sourceCrs())
self.distance_area.setEllipsoid(context.project().ellipsoid())
elif method == 1:
coordTransform = QgsCoordinateTransform(source.sourceCrs(), context.project().crs())
features = source.getFeatures()
total = 100.0 / source.featureCount() if source.featureCount() else 0
for current, f in enumerate(features):
if feedback.isCanceled():
break
outFeat = f
attrs = f.attributes()
inGeom = f.geometry()
if inGeom:
if coordTransform is not None:
inGeom.transform(coordTransform)
if inGeom.type() == QgsWkbTypes.PointGeometry:
attrs.extend(self.point_attributes(inGeom))
elif inGeom.type() == QgsWkbTypes.PolygonGeometry:
attrs.extend(self.polygon_attributes(inGeom))
else:
attrs.extend(self.line_attributes(inGeom))
outFeat.setAttributes(attrs)
sink.addFeature(outFeat, QgsFeatureSink.FastInsert)
feedback.setProgress(int(current * total))
return {self.OUTPUT: dest_id}
def point_attributes(self, geometry):
pt = None
if not geometry.isMultipart():
pt = geometry.geometry()
else:
if geometry.numGeometries() > 0:
pt = geometry.geometryN(0)
attrs = []
if pt:
attrs.append(pt.x())
attrs.append(pt.y())
# add point z/m
if self.export_z:
attrs.append(pt.z())
if self.export_m:
attrs.append(pt.m())
return attrs
def line_attributes(self, geometry):
return [self.distance_area.measureLength(geometry)]
def polygon_attributes(self, geometry):
area = self.distance_area.measureArea(geometry)
perimeter = self.distance_area.measurePerimeter(geometry)
return [area, perimeter]
| GeoCat/QGIS | python/plugins/processing/algs/qgis/ExportGeometryInfo.py | Python | gpl-2.0 | 6,865 |
import vim
def func_header_snippet(row):
cmt = "//!"
cb = vim.current.buffer
start = row
while start >= 0:
line = cb[start-1].strip()
if not line.startswith(cmt):
break
start -= 1
print("HDR")
def select_snippet(line):
line = line.strip()
if line.startswith("//!"):
return func_header_snippet
def main():
row, col = vim.current.window.cursor
row -= 1
cline = vim.current.buffer[row]
func = select_snippet(cline)
if func:
func(row)
#! @brief
#! @details
main()
| peter1010/my_vim | vimfiles/py_scripts/snippet.py | Python | gpl-2.0 | 569 |
#!/bin/env python
#-*- coding=utf-8 -*-
import yaml
data = """
f5:
# 蓝汛f5信息
- ip: 192.168.0.1
dc: lx
credentials:
username: huzichun
password: huzichun!@#
role: master
# 世纪互联f5信息
- ip: 192.168.0.2
dc: sjhl
credentials:
username: huzichun
password: huzichun!@#
role: slave
# 移动f5信息
- ip: 192.168.0.3
dc: yd
credentials:
username: huzichun
password: huzichun!@#
role: master
"""
print yaml.dump(yaml.load(data))
f = file('f5.yaml', 'w')
yaml.dump(yaml.load(data), f)
f.close()
f = file('f5.yaml', 'r')
infos = yaml.load(f)
#print infos
for info in infos["f5"]:
if info["ip"] == "192.168.0.2":
print info["credentials"]["username"], info["credentials"]["password"]
f.close()
| huzichunjohn/2014 | test_yaml.py | Python | gpl-2.0 | 810 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('taxonomy', '0003_auto_20150720_1937'),
]
operations = [
migrations.AddField(
model_name='taxon',
name='extant',
field=models.NullBooleanField(default=True),
),
migrations.AddField(
model_name='taxon',
name='notes',
field=models.TextField(null=True, blank=True),
),
]
| wabarr/taxonomy | taxonomy/migrations/0004_auto_20150721_2058.py | Python | gpl-2.0 | 563 |
"""
Authorization module that allow users listed in
/etc/cobbler/users.conf to be permitted to access resources, with
the further restriction that cobbler objects can be edited to only
allow certain users/groups to access those specific objects.
Copyright 2008-2009, Red Hat, Inc and Others
Michael DeHaan <michael.dehaan AT gmail>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA
"""
import ConfigParser
import os
from cobbler.cexceptions import CX
from cobbler.utils import _
def register():
"""
The mandatory cobbler module registration hook.
"""
return "authz"
def __parse_config():
etcfile = '/etc/cobbler/users.conf'
if not os.path.exists(etcfile):
raise CX(_("/etc/cobbler/users.conf does not exist"))
config = ConfigParser.ConfigParser()
# Make users case sensitive to handle kerberos
config.optionxform = str
config.read(etcfile)
alldata = {}
sections = config.sections()
for g in sections:
alldata[str(g)] = {}
opts = config.options(g)
for o in opts:
alldata[g][o] = 1
return alldata
def __authorize_autoinst(api_handle, groups, user, autoinst):
# the authorization rules for automatic installation file editing are a bit
# of a special case. Non-admin users can edit a automatic installation file
# only if all objects that depend on that automatic installation file are
# editable by the user in question.
#
# Example:
# if Pinky owns ProfileA
# and the Brain owns ProfileB
# and both profiles use the same automatic installation template
# and neither Pinky nor the Brain is an admin
# neither is allowed to edit the automatic installation template
# because they would make unwanted changes to each other
#
# In the above scenario the UI will explain the problem
# and ask that the user asks the admin to resolve it if required.
# NOTE: this function is only called by authorize so admin users are
# cleared before this function is called.
lst = api_handle.find_profile(autoinst=autoinst, return_list=True)
lst.extend(api_handle.find_system(autoinst=autoinst, return_list=True))
for obj in lst:
if not __is_user_allowed(obj, groups, user, "write_autoinst", autoinst, None):
return 0
return 1
def __authorize_snippet(api_handle, groups, user, autoinst):
# only allow admins to edit snippets -- since we don't have detection to see
# where each snippet is in use
for group in groups:
if group not in ["admins", "admin"]:
return False
return True
def __is_user_allowed(obj, groups, user, resource, arg1, arg2):
if user == "<DIRECT>":
# system user, logged in via web.ss
return True
for group in groups:
if group in ["admins", "admin"]:
return True
if obj.owners == []:
return True
for allowed in obj.owners:
if user == allowed:
# user match
return True
# else look for a group match
for group in groups:
if group == allowed:
return True
return 0
def authorize(api_handle, user, resource, arg1=None, arg2=None):
"""
Validate a user against a resource.
All users in the file are permitted by this module.
"""
if user == "<DIRECT>":
# CLI should always be permitted
return True
# everybody can get read-only access to everything
# if they pass authorization, they don't have to be in users.conf
if resource is not None:
# FIXME: /cobbler/web should not be subject to user check in any case
for x in ["get", "read", "/cobbler/web"]:
if resource.startswith(x):
return 1 # read operation is always ok.
user_groups = __parse_config()
# classify the type of operation
modify_operation = False
for criteria in ["save", "copy", "rename", "remove", "modify", "edit", "xapi", "background"]:
if resource.find(criteria) != -1:
modify_operation = True
# FIXME: is everyone allowed to copy? I think so.
# FIXME: deal with the problem of deleted parents and promotion
found_user = False
found_groups = []
grouplist = user_groups.keys()
for g in grouplist:
for x in user_groups[g]:
if x == user:
found_groups.append(g)
found_user = True
# if user is in the admin group, always authorize
# regardless of the ownership of the object.
if g == "admins" or g == "admin":
return True
if not found_user:
# if the user isn't anywhere in the file, reject regardless
# they can still use read-only XMLRPC
return 0
if not modify_operation:
# sufficient to allow access for non save/remove ops to all
# users for now, may want to refine later.
return True
# now we have a modify_operation op, so we must check ownership
# of the object. remove ops pass in arg1 as a string name,
# saves pass in actual objects, so we must treat them differently.
# automatic installaton files are even more special so we call those
# out to another function, rather than going through the rest of the
# code here.
if resource.find("write_autoinstall_template") != -1:
return __authorize_autoinst(api_handle, found_groups, user, arg1)
elif resource.find("read_autoinstall_template") != -1:
return True
# the API for editing snippets also needs to do something similar.
# as with automatic installation files, though since they are more
# widely used it's more restrictive
if resource.find("write_autoinstall_snippet") != -1:
return __authorize_snippet(api_handle, found_groups, user, arg1)
elif resource.find("read_autoinstall_snipppet") != -1:
return True
obj = None
if resource.find("remove") != -1:
if resource == "remove_distro":
obj = api_handle.find_distro(arg1)
elif resource == "remove_profile":
obj = api_handle.find_profile(arg1)
elif resource == "remove_system":
obj = api_handle.find_system(arg1)
elif resource == "remove_repo":
obj = api_handle.find_repo(arg1)
elif resource == "remove_image":
obj = api_handle.find_image(arg1)
elif resource.find("save") != -1 or resource.find("modify") != -1:
obj = arg1
# if the object has no ownership data, allow access regardless
if obj is None or obj.owners is None or obj.owners == []:
return True
return __is_user_allowed(obj, found_groups, user, resource, arg1, arg2)
| shenson/cobbler | cobbler/modules/authz_ownership.py | Python | gpl-2.0 | 7,391 |
#Copyright Intrepidus Group 2010
#All Rights Reserved
#Released under the following license
#
#PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
#--------------------------------------------
#
#0. This Python Software Foundation License (the "License") applies to
#any original work of authorship (the "Software") whose owner (the
#"Licensor") has placed the following notice immediately following the
#copyright notice for the Software:
#
# "Licensed under the Python Software Foundation License Version 2"
#
#1. This LICENSE AGREEMENT is between the Licensor, and the Individual
#or Organization ("Licensee") accessing or otherwise using the
#Software in source or binary form and its associated documentation.
#
#2. Subject to the terms and conditions of this License Agreement,
#Licensor hereby grants Licensee a nonexclusive, royalty-free,
#world-wide license to reproduce, analyze, test, perform and/or display
#publicly, prepare derivative works, distribute, and otherwise use the
#Software alone or in any derivative version, provided, however, that
#Licensor's License Agreement and Licensor's notice of copyright are
#retained in the Software alone or in any derivative version prepared
#by Licensee.
#
#3. In the event Licensee prepares a derivative work that is based on
#or incorporates the Software or any part thereof, and wants to make
#the derivative work available to others as provided herein, then
#Licensee hereby agrees to include in any such work a brief summary of
#the changes made to the Software.
#
#4. Licensor is making the Software available to Licensee on an "AS IS"
#basis. Licensor MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
#IMPLIED, WITH RESPECT TO THE SOFTWARE, TO Licensee OR TO ANY OTHER USERS
#OF THE SOFTWARE. BY WAY OF EXAMPLE, BUT NOT LIMITATION, Licensor MAKES
#NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR
#FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL
#NOT INFRINGE ANY THIRD PARTY RIGHTS.
#
#5.Licensor SHALL NOT BE LIABLE TO Licensee OR ANY OTHER USERS OF THE
#SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS
#(INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS,
#BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION, OR OTHER PECUNIARY
#LOSS) AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR
#ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
#
#6. This License Agreement will automatically terminate upon a material
#breach of its terms and conditions.
#
#7. Nothing in this License Agreement shall be deemed to create any
#relationship of agency, partnership, or joint venture between Licensor
#and Licensee. This License Agreement does not grant permission to use
#Licensor trademarks or trade name in a trademark sense to endorse or
#promote products or services of Licensee, or any third party.
#
#8. By accessing, copying, installing or otherwise using the Software,
#Licensee agrees to be bound by the terms and conditions of this License
#Agreement.
#! /usr/bin/env python
"""
Usage: %s [ database_filename ]
"""
import config
import copy
import os
import os.path
import re
import socket
import sqlite3
import ssl
import sys
import thread
import time
import Queue
import select
import xmlrpclib
import logging
import traceback
import struct
import rpc
### MALLORY IMPORTS ###
import netfilter
import malloryevt
import config_proto
import config_rule
from cmdlineopts import CmdLineOpts
from trafficdb import TrafficDb
from observer import Subject
from debug import DebugEvent, Debugger
from binascii import hexlify, unhexlify
import cert_auth
# These protocols have no dependencies and are safe to import
from protocol import base, dnsp
try:
# These protocols have dependencies and may not be safe to import
from protocol import sslproto, http, ssh, https
from plugin_managers import http_plugin_manager
except ImportError:
print "ImportError: Trouble importing protocols with dependencies. " \
"Proceeding with minimal protocol support."
# Config object is global. Buyer beware.
config = config.Config()
FLIP_IMAGES = True
def usage():
sys.stderr.write ( __doc__ % os.path.basename(sys.argv[0]) )
class ConnData():
"""This class encapsulates all of the information about a connection it
is mostly designed to be a data holding class and provide convenience
methods to turn the data into a string for easy logging, etc."""
# TODO: Use the defines...
DIR_C2S = 'c2s'
DIR_S2C = 's2c'
DIR_NONE = ''
def __init__(self, data={'clientip':'', 'clientport':0, \
'serverip':'', 'serverport':0, \
'conncount':'', 'direction':''}):
"""
Initialize the connection data.
@param data: This is the data associated with the connection.
clientip: the client's (victim's) ip address).
clientport: the victim's source port.
serverip: the destination IP address.
serverport: the destination port.
conncount: Used to track connections in the data store.
direction: C2S or S2C (client to server or server to client).
@return: No return value
"""
self.clientip = data['clientip']
self.clientport = data['clientport']
self.serverip = data['serverip']
self.serverport = data['serverport']
self.conncount = data['conncount']
self.direction = data['direction']
def __str__(self):
return "clientip:%s, clientport:%d, serverip:%s, serverport:%d " \
"conncount:%d, direction:%s" % (self.clientip, self.clientport, \
self.serverip, self.serverport, self.conncount, self.direction)
class Mallory(Subject):
"""
The main Mallory class used to instantiate and start the proxy. Protocols
can be configured through methods in the main Mallory class. This is
where it all starts.
"""
def __init__(self, options):
Subject.__init__(self)
self.log = logging.getLogger("mallorymain")
config.logsetup(self.log)
self.configured_protos = []
self.configured_plugin_managers = []
self.protoinstances = []
self.opts = options.options
self.dbname = self.opts.trafficdb
self.debugon = False
self.debugger = Debugger()
self.config_protocols = config_proto.ConfigProtocols()
self.config_rules = config_rule.ConfigRules()
self.rpcserver = rpc.RPCServer()
self.nftool = netfilter.NetfilterTool()
def configure_protocol(self, protocol, action):
"""
Configure a protocol. Use this method to configure Mallory protocols.
@param protocol: The Mallory protocol, from the protocol module, to
be configured.
@param action: when the value is "add" the protocol will be added to the
protocol classes Mallory uses to decode protocols
@type action: string
@return: No return value
"""
if action == "add":
self.configured_protos.append(protocol)
def configure_protocols(self):
self.log.debug("Mallory:configure_protocols - Entry")
protocols = self.config_protocols.get_protocols()
self.configured_protos = []
for protocol in protocols:
self.configure_protocol(protocol, "add")
def add_plugin_manager(self, pluginManager):
"""
Add a new plugin manager to Mallory's configured plugin managers.
@param plugin_manager: The plugin manager to be added.
@type plugin_manager:
plugin_managers.plugin_managers_base.PluginManagerBase.
"""
self.configured_plugin_managers.append (pluginManager)
def configure_socket(self, mevt, **kwargs):
"""
Private method to configure a socket.
@param mevt: This is a mallory event from module malloryevt
@param kwargs: keyworded arguments. Currently expects one named
argument, protoinst. The protoinst must be a protocol instance.
@type kwargs: protoinst=L{Protocol<src.protocol.base.Protocol>}
"""
protoinst = kwargs["protoinst"]
if not protoinst:
return
for proto in self.configured_protos:
if mevt in proto.supports:
if proto.serverPort == protoinst.serverPort:
if mevt == malloryevt.CSACCEPT or mevt == malloryevt.CSAFTERSS:
protoinst.configure_client_socket()
elif mevt == malloryevt.SSCREATE:
protoinst.configure_server_socket()
def forward(self, protoinst, conndata):
"""
Internal method for setting up data pumps for sockets.
@param protoinst: A protocol instance to set up.
@type protoinst: L{Protocol <src.protocol.base.Protocol>}
"""
if malloryevt.STARTS2C in protoinst.supports and conndata.direction == "s2c":
protoinst.forward_s2c(conndata)
elif malloryevt.STARTC2S in protoinst.supports and conndata.direction == "c2s":
protoinst.forward_c2s(conndata)
else:
protoinst.forward_any(conndata)
def update(self, publisher, **kwargs):
if "action" not in kwargs:
return
if kwargs["action"] == "load_protos":
self.configure_protocols()
def cleanup_proto(self):
#self.log.info("Mallory.cleanup_proto()")
# List of proto instances that are done
done_list = []
for proto in self.protoinstances:
if proto.is_done():
done_list.append(proto)
#self.log.info("Mallory.cleanup_proto():%s" % (done_list))
for proto in done_list:
"""
TODO: Figure out why we still leak socket handles
Current behavior is to slowly leak a few handles per minute
under heavy load. Especially when the remote server
disappears.
This fixes up the majority of the issues for now
"""
proto.close()
self.protoinstances.remove(proto)
def main(self):
"""
Mallory's main method. When this is called the following activities
occur.
- A new traffic database is created
- A new thread for debugger RPC is created
- a listening socket for the proxy is created
- A UDP socket is created
- A new thread for processing the DB Queue is created
- The proxy begins listening for incoming connections
"""
dbConn = TrafficDb(self.dbname)
self.dbname = dbConn.getDbName() #get the trafficDb being used
self.debugger.setdatabase(self.dbname)
# Kick off a thread for the debugger
#thread.start_new_thread(self.debugger.rpcserver, ())
# Mallory needs to know if the protocol config changes
self.config_protocols.attach(self)
self.rpcserver.add_remote_obj(self.debugger, "debugger")
self.rpcserver.add_remote_obj(self.config_protocols, "config_proto")
self.rpcserver.add_remote_obj(self.config_rules, "config_rules")
self.configure_protocols()
thread.start_new_thread(self.rpcserver.start_server, ())
try:
# Create proxy and wait for connections
proxy = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
proxy.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
udpproxy = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
if self.opts.listen:
bindaddr = ('', int(self.opts.listen))
self.log.info("Binding mallory to: %s:%d" \
% (bindaddr[0], bindaddr[1]))
proxy.bind(bindaddr)
udpproxy.bind(bindaddr)
proxy.listen(5)
if config.debug == 1:
self.log.debug("main: Waiting for connection")
connCount = 0
# This thread puts data in the database.
thread.start_new_thread(dbConn.fillDB, ())
try:
# Not a standard part of mallory. For ssh ownage only.
sshshellpwn = ssh.SSHProtocol(None, None, None)
thread.start_new_thread(sshshellpwn.provideshell, (self, ))
except NameError:
self.log.warn("main: SSHProtocol not defined. sshshellpwn "
"unavailable")
# Handle UDP
udp = base.UdpProtocol(dbConn, udpproxy, self.configured_protos)
udp.setrules(self.config_rules.get_rules())
self.config_rules.attach(udp)
# Setup bi-directional pub/sub setup for debugger events. This
# is a very important step. Without it the debugging client and or
# mallory will not know when an event has occured
#self.debugger.attach(udp)
#udp.attach(self.debugger)
thread.start_new_thread(udp.forward_any, ())
# Handle TCP
while 1:
# Clean up first
self.cleanup_proto()
# Main accept
(csock, caddr) = proxy.accept()
if config.debug == 1:
self.log.info("main: got connection from: %s:%s" %
(caddr[0], caddr[1]))
try:
# TODO: Move this option into the netfilter class
# destination lookup methods
if self.opts.notransparent:
shost,sport = self.opts.notransparent.split(":")
sport = int(sport)
self.log.debug("Sending to:%s:%d" % (shost, sport))
else:
(shost,sport) = self.nftool.getrealdest(csock)
except:
traceback.print_exc()
self.log.warn("main: error getting real destination")
try:
# Create protocol instance using server port as guide
protoinst = None
for proto in self.configured_protos:
if sport == proto.serverPort:
protoinst = proto.__class__(dbConn, csock,
None)
if not protoinst:
protoinst = base.TcpProtocol(dbConn, csock, None)
self.log.debug("Mallory.main: created a %s class" % (protoinst.__class__))
protoinst.setrules(self.config_rules.get_rules())
# Set the proper debugging flag.
protoinst.debugon = self.debugger.debugon
## You always *pass* the object interested in updates
## see observer.py
# Protocols are interested in updates from mallory
self.attach(protoinst)
# Protocols are interested in updates from rule_config
self.config_rules.attach(protoinst)
# Protocols are interested in updates from the debugger
self.debugger.attach(protoinst)
# The debugger is interested in events from protos as well
protoinst.attach(self.debugger)
# Which Protocol manager to which protocol
for plugin_manager in self.configured_plugin_managers:
if sport == plugin_manager.server_port:
protoinst.attach_plugin_manager(plugin_manager)
# Subscribe updates between mallory and the proto instance
protoinst.attach(self)
self.protoinstances.append(protoinst)
# Create the server socket (victim's destination)
ssock = socket.socket(socket.AF_INET, \
socket.SOCK_STREAM)
# Set server sock data in protocol instance then config it
protoinst.destination = ssock
protoinst.serverPort = sport
self.configure_socket(malloryevt.SSCREATE,
protoinst=protoinst)
if self.opts.proxify:
shost,sport = self.opts.proxify.split(":")
sport = int(sport)
# Connect the server socket
protoinst.destination.connect((shost, int(sport)))
# Client socket configuration after server socket creation
protoinst.source = csock
# buf = ""
# hack = csock.recv(1024, socket.MSG_PEEK)
# print "Hack Bits: " + repr(hack)
self.configure_socket(malloryevt.CSAFTERSS,
protoinst=protoinst)
except KeyboardInterrupt:
self.log.warn("mallory: got keyboard interrupt in" \
" conn attempt")
sys.exit(0)
except:
# Force clean up soon
protoinst.set_done(True)
# Deal with the freaky folks
self.log.error("main: error connecting to remote")
traceback.print_exc()
print sys.exc_info()
continue
# Retrieve the connection data.
clientconn = ConnData({'clientip' : caddr[0], \
'clientport' : caddr[1], \
'serverip' : shost, 'serverport' : sport, \
'conncount' : connCount, 'direction' : 'c2s' })
# Store the connection data
dbConn.qConn.put((connCount, shost, sport, \
caddr[0], caddr[1]))
# Kick off the s2c and c2s data pumps
thread.start_new_thread(self.forward, (protoinst, clientconn))
serverconn = copy.deepcopy(clientconn)
serverconn.direction = 's2c'
thread.start_new_thread(self.forward, (protoinst, serverconn))
connCount = connCount + 1
except KeyboardInterrupt:
self.log.info("Mallory: Goodbye.")
proxy.close()
sys.exit(0)
except:
self.log.error("Mallory: Blanket exception handler got an " \
"exception")
traceback.print_exc()
print sys.exc_info()
proxy.close()
if __name__ == '__main__':
print "MALLLLORYYY!!!!!!!!!!"
opts = CmdLineOpts()
mallory = Mallory(opts)
mallory.add_plugin_manager(http_plugin_manager.HttpPluginManager())
# Pull in the protocol configured on the command line for use with the
# no-transparent option when the proxy is not being used transparently
if opts.options.proto:
import protocol
print "Proto is %s" % (opts.options.proto)
modulename,protoname = opts.options.proto.split(".")
try:
protomodule = getattr(protocol, modulename)
protoinstance = getattr(protomodule, protoname)(None, None, None)
mallory.configure_protocol(protoinstance, "add")
mallory.log.info("Configuring command line protocol instance: %s "
"for port %d" \
% (protoinstance, protoinstance.serverPort))
except:
print "Invalid protocol specified at command line"
mallory.main()
| ausarbluhd/EternalLLC | scripts/mallory/src/mallory.py | Python | gpl-2.0 | 21,144 |
Subsets and Splits
Unique Repositories with URLs
Lists unique repository names along with their GitHub URLs, providing basic identification information for each repository.