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 |
|---|---|---|---|---|---|
#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
#
# FabLabKasse, a Point-of-Sale Software for FabLabs and other public and trust-based workshops.
# Copyright (C) 2015 Julian Hammer <julian.hammer@fablab.fau.de>
# Maximilian Gaukler <max@fablab.fau.de>
# Timo Voigt <timo@fablab.fau.de>
#
# This program is free software: you can redistribute it and/or modify it under the terms of the GNU
# General Public License as published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with this program. If not,
# see <http://www.gnu.org/licenses/>.
from PyQt4 import Qt, QtGui, QtCore
from .uic_generated.PaymentMethodDialog import Ui_PaymentMethodDialog
from ..shopping.payment_methods import PAYMENT_METHODS
import functools
class PaymentMethodDialog(QtGui.QDialog, Ui_PaymentMethodDialog):
def __init__(self, parent, cfg, amount):
QtGui.QDialog.__init__(self, parent)
self.setupUi(self)
self.cfg = cfg
self.method = None
# Clear all method buttons
for i in range(self.layout_methods.count()):
self.layout_methods.itemAt(i).widget().setVisible(False)
self.layout_methods.itemAt(i).widget().deleteLater()
# select available methods (according to config file)
first_button = True
for method in PAYMENT_METHODS:
button = Qt.QPushButton(method.get_title())
button.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
# cannot use lambda here because the variable 'method' will change
# in the next iteration... python is counterintuitive here....
button.clicked.connect(functools.partial(self.acceptAndSetMethod, method))
button.setVisible(method.is_enabled(self.cfg))
# highlight the first choice with bold font
if first_button:
font = button.font()
font.setWeight(QtGui.QFont.Bold)
button.setFont(font)
button.setDefault(True)
first_button = False
self.layout_methods.addWidget(button)
self.label_betrag.setText(self.parent().shoppingBackend.format_money(amount))
self.update()
def acceptAndSetMethod(self, method):
self.method = method
self.accept()
def getSelectedMethodInstance(self, parent, shopping_backend, amount_to_pay):
return self.method(parent, shopping_backend, amount_to_pay, self.cfg)
| fau-fablab/FabLabKasse | FabLabKasse/UI/PaymentMethodDialogCode.py | Python | gpl-3.0 | 2,875 |
__author__ = 'Debha'
from read_data import read_data, read_map, gene_muts, make_GO_map
from cluster import make_cluster_mat, make_sub_mut_map, make_GO_cluster_mat, cluster_main, clean, pairwiseDist, clustered_GOs, sim_matrix
import numpy as np
data_file = "../inputs/somatic.csv"
map_file = "../inputs/mart_export.csv"
GO_file = "../inputs/c5.all.v5.0.symbols.gmt"
#data = read_data(data_file)
#gene_map = read_map(map_file)
#gene_mut = gene_muts(data, gene_map)
#GO_map = make_GO_map(GO_file)
#[cluster_mat, cluster_mat_nonbinary, subjects, genes, gene_length_map] = make_cluster_mat(data, list(gene_mut.keys()))
cluster_mat = np.load("../intermediates/cluster_mat.npy")
subjects = np.load("../intermediates/subjects.npy"); genes = np.load("../intermediates/genes.npy")
GO_terms = np.load("../intermediates/GO_terms.npy")
# sub_mut_map = make_sub_mut_map(cluster_mat, subjects, genes)
# GO_cluster_mat = make_GO_cluster_mat(sub_mut_map, GO_map, subjects)
GO_cluster_mat = np.load("../intermediates/GO_cluster_mat.npy")
[c_GO_cluster_mat, c_GO_terms] = clean(GO_cluster_mat, GO_terms)
agg_sub_clusters = []
k = 3
iterations = 20
runs = 5
for i in range(runs):
print "Run " + str(i+1) + " out of " + str(runs)
[mu, clusters, distortion, subject_clusters] = cluster_main(c_GO_cluster_mat.tolist(), k, iterations, subjects)
agg_sub_clusters.append(subject_clusters)
#for key in clusters:
# print key, len(clusters[key]), len(subject_clusters[key])
#clustered_GOs(clusters, c_GO_terms, mu)
#pairwiseDist(c_GO_cluster_mat)
#sim_matrix(c_GO_cluster_mat)
| kspham/coldnet | src/OntologyBasedClustering/code/OBC_main.py | Python | gpl-3.0 | 1,574 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of PyDownTV.
#
# PyDownTV is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PyDownTV 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 PyDownTV. If not, see <http://www.gnu.org/licenses/>.
# Pequeña descripción de qué canal de tv es el módulo
__author__="aabilio"
__date__ ="$15-may-2011 11:03:38$"
from Descargar import Descargar
from utiles import salir, formatearNombre, printt
import sys
class TeleVigo(object):
'''
Clase que maneja la descarga los vídeos de TeleVigo
'''
URL_TeleVigo = "http://www.televigo.com/"
def __init__(self, url=""):
self._URL_recibida = url
def getURL(self):
return self._URL_recibida
def setURL(self, url):
self._URL_recibida = url
url = property(getURL, setURL)
# Funciones privadas que ayuden a procesarDescarga(self):
def __descHTML(self, url2down):
''' Método que utiliza la clase descargar para descargar el HTML '''
D = Descargar(url2down)
return D.descargar()
def procesarDescarga(self):
'''
Procesa lo necesario para obtener la url final del vídeo a descargar y devuelve
esta y el nombre como se quiere que se descarge el archivo de la siguiente forma:
return [ruta_url, nombre]
Si no se quiere especificar un nombre para el archivo resultante en disco, o no se
conoce un procedimiento para obtener este automáticamente se utilizará:
return [ruta_url, None]
Y el método de Descargar que descarga utilizará el nombre por defecto según la url.
Tanto "ruta_url" como "nombre" pueden ser listas (por supuesto, el nombre del ruta_url[0]
tiene que ser nombre[0] y así sucesivamente).
'''
streamHTML = self.__descHTML(self._URL_recibida)
xmlURL = streamHTML.split("_url_xml_datos:\"")[1].split("\"")[0]
streamXML = self.__descHTML(xmlURL)
url = streamXML.split("<url>")[1].split("<")[0]
ext = "." + url.split(".")[-1]
name = streamXML.split("<title><![CDATA[")[1].split("]")[0] + ext
if name:
name = formatearNombre(name)
return [url, name]
| aabilio/PyDownTV | Servers/televigo.py | Python | gpl-3.0 | 2,787 |
from django import forms
from django.core.urlresolvers import reverse
from django.forms.widgets import RadioFieldRenderer
from django.utils.encoding import force_text
from django.utils.html import format_html
from django.utils.safestring import mark_safe
class BootstrapChoiceFieldRenderer(RadioFieldRenderer):
"""
An object used by RadioSelect to enable customization of radio widgets.
"""
def render(self):
"""
Outputs a <div> for this set of choice fields.
If an id was given to the field, it is applied to the <di> (each
item in the list will get an id of `$id_$i`).
"""
id_ = self.attrs.get('id', None)
start_tag = format_html('<div id="{0}">', id_) if id_ else '<div>'
output = [start_tag]
for widget in self:
output.append(format_html('<div class="radio">{0}</div>', force_text(widget)))
output.append('</div>')
return mark_safe('\n'.join(output))
class UseCustomRegWidget(forms.MultiWidget):
"""
This widget is for three fields on event add/edit under Registration:
* use_custom_reg_form
* reg_form
* bind_reg_form_to_conf_only
"""
def __init__(self, attrs=None, reg_form_choices=None, event_id=None):
self.attrs = attrs
self.reg_form_choices = reg_form_choices
self.event_id = event_id
if not self.attrs:
self.attrs = {'id': 'use_custom_reg'}
self.widgets = (
forms.CheckboxInput(),
forms.Select(attrs={'class': 'form-control'}),
forms.RadioSelect(renderer=BootstrapChoiceFieldRenderer)
)
super(UseCustomRegWidget, self).__init__(self.widgets, attrs)
def render(self, name, value, attrs=None):
if not isinstance(value, list):
value = self.decompress(value)
final_attrs = self.build_attrs(attrs)
id_ = final_attrs.get('id', None)
use_custom_reg_form_widget = self.widgets[0]
rendered_use_custom_reg_form = self.render_widget(
use_custom_reg_form_widget,
name, value, final_attrs,
0, id_
)
reg_form_widget = self.widgets[1]
reg_form_widget.choices = self.reg_form_choices
#reg_form_widget.attrs = {'size':'8'}
rendered_reg_form = self.render_widget(
reg_form_widget,
name, value, final_attrs,
1, id_
)
bind_reg_form_to_conf_only_widget = self.widgets[2]
choices = (
('1', mark_safe('Use one form for all pricings %s' % rendered_reg_form)),
)
bind_reg_form_to_conf_only_widget.choices = choices
rendered_bind_reg_form_to_conf_only = self.render_widget(
bind_reg_form_to_conf_only_widget,
name, value, final_attrs,
2, id_
)
rendered_bind_reg_form_to_conf_only = rendered_bind_reg_form_to_conf_only.replace(
'%s</label>' % rendered_reg_form, "</label>%s" % rendered_reg_form
)
if self.event_id:
manage_custom_reg_link = """
<div>
<a href="%s" target="_blank">Manage Custom Registration Form</a>
</div>
""" % reverse('event.event_custom_reg_form_list', args=[self.event_id])
else:
manage_custom_reg_link = ''
output_html = """
<div id="t-events-use-customreg-box">
<div id="t-events-use-customreg-checkbox" class="checkbox">
<label for="id_%s_%s">%s Use Custom Registration Form</label>
</div>
<div id="t-events-one-or-separate-form">%s</div>
%s
</div>
""" % (
name, '0',
rendered_use_custom_reg_form,
rendered_bind_reg_form_to_conf_only,
manage_custom_reg_link
)
return mark_safe(output_html)
def render_widget(self, widget, name, value, attrs, index=0, id=None):
i = index
id_ = id
if value:
try:
widget_value = value[i]
except IndexError:
self.fields['use_reg_form'].initial = None
else:
widget_value = None
if id_:
final_attrs = dict(attrs, id='%s_%s' % (id_, i))
if widget.__class__.__name__.lower() != 'select':
classes = final_attrs.get('class', None)
if classes:
classes = classes.split(' ')
classes.remove('form-control')
classes = ' '.join(classes)
final_attrs['class'] = classes
return widget.render(name+'_%s' %i, widget_value, final_attrs)
def decompress(self, value):
if value:
data_list = value.split(',')
if data_list[0] == '1':
data_list[0] = 'on'
return data_list
return None
| alirizakeles/tendenci | tendenci/apps/events/widgets.py | Python | gpl-3.0 | 4,968 |
# -- coding: utf-8 --
###########################################################################
# #
# WebText #
# #
# Lucca Hirschi #
# <lucca.hirschi@ens-lyon.fr> #
# #
# Copyright 2014 Lucca Hirschi #
# #
# This file is part of OwnShare. #
# OwnShare is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
# the Free Software Foundation, either version 3 of the License, or #
# (at your option) any later version. #
# #
# OwnShare 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 OwnShare. If not, see <http://www.gnu.org/licenses/>. #
# #
###########################################################################
from __future__ import unicode_literals # implicitly declaring all strings as unicode strings
import logging
import wikipedia
from mainClass import *
from static import *
# -- Setup Logging --
logging = logging.getLogger(__name__)
CHOSENNUMBER = "numero"
LIST = "liste"
RECHERCHE = "recherche"
FR = "fr"
EN = "en"
FOUND = "Voici tous les titres d'articles que l'on a trouvé: "
NOT_FOUND_LIST = "Nous n'avons pas réussi à trouver l'article le plus pertinent parmis cette liste: "
NOT_FOUND_LIST_CHOOSE = "Vous pouvez maintenant affiner votre recherche."
NOT_FOUND = "Aucun article ne correspond à votre requête. Essayez avec une requête plus petite."
FOUND_LIST_DESCR = "%d articles répondent à votre requête. Voici la liste des %d premiers: "
def wikiSummary(request):
"""Fetch the summary of Wikipadia's articles. """
wikipedia.set_lang("fr") # in French by default
# -- PARSING --
searchText = request.argsList[0]
detailsList = None
chosenNumber = None
onlyResearch = None
# 'LIST' (ask for the list of matched articles)
if LIST in map(lambda s: s.strip().lower(), request.argsList[1:]):
detailsList = True
# 'CHOSENNUMBER i' (ask for the i-nth article of the matched articles)
if CHOSENNUMBER in map(lambda s: s.strip().lower().split()[0], request.argsList[1:]):
chosenNumber = int(filter(lambda s: s.strip().lower().split()[0] == CHOSENNUMBER, request.argsList[1:])[0].split()[1])
#'RECHERCHE' (make a research instead of looking for the summary)
if RECHERCHE in map(lambda s: s.strip().lower(), request.argsList[1:]):
onlyResearch = True
# languages: "fr" or "en" for the moment
if EN in map(lambda s: s.strip().lower(), request.argsList[1:]):
wikipedia.set_lang(EN)
if FR in map(lambda s: s.strip().lower(), request.argsList[1:]):
wikipedia.set_lang(FR)
# -- FECTHING --
max_nb_results = 10
max_nb_searchs = 20
options = None
failSuggest = None
answ = ""
if onlyResearch:
searchs = wikipedia.search(searchText, results = max_nb_searchs)
answ += (FOUND + "[" +
",".join(searchs) + "].")
return(answ)
# safe access to the Wiki'API
try:
# fails if there is an ambiguity
try:
# this does not fail if ther is no ambiguity on the required article
summary = wikipedia.summary(searchText, auto_suggest = False)
suggest = wikipedia.suggest(searchText)
title = suggest if suggest else searchText
except wikipedia.exceptions.DisambiguationError as e:
nbOptions = len(e.options)
options = e.options[:(min(len(e.options), max_nb_results))]
# there is an ambiguity -> choose the number-nth
number = chosenNumber if chosenNumber else 1
if len(options) > number - 1:
try:
newSearchText = options[number - 1]
if newSearchText.strip() == searchText.strip() and not(chosenNumber) and len(options) > 1:
newSearchText = options[1]
summary = wikipedia.summary(newSearchText, auto_suggest = False)
title = newSearchText
# In that case, we failed to disambiguate the request
except wikipedia.exceptions.DisambiguationError as e:
failSuggest = True
# results = wikipedia.search(searchtext, results=max_nb_results)
except IOError as e:
logging.error("wikiSummary > wikipedia.search | I/O error({0}): {1}".format(e.errno, e.strerror))
return(MESS_BUG())
# -- ANSWER --
# Fail to resolve ambiguity
if failSuggest:
answ += (NOT_FOUND_LIST +
"[" + ", ".join(options) + "]. " +
NOT_FOUND_LIST_CHOOSE)
return(answ)
# No articles matched the request
if options and (len(options) == 0 or not(len(options) > number - 1)):
answ += NOT_FOUND
return(answ)
# Strictly more than 1 article matches the request
if options and len(options) > 1:
if detailsList:
answ += ((FOUND_LIST_DESCR % (nbOptions, max_nb_results))
+ "[" + ", ".join(options) + "]. ")
if chosenNumber:
answ += ("Voici le %d-ème: " % chosenNumber)
else:
answ += ("Voici le premier: ")
else:
if chosenNumber:
answ += ("%d articles répondent à votre requête. Voici le %d-ème: " % (nbOptions, chosenNumber))
else:
answ += ("%d articles répondent à votre requête. Voici le premier: " % nbOptions)
# Exactly one article matched the request
else:
answ += "Voici le seul article qui répond à votre requête: "
answ += ("[%s] -- " % title) + summary
return(answ)
def likelyCorrect(a):
return(("Amboise" in a or "libertin" in a or "commune" in a) or # Bussy
("Git" in a and "Ruby" in a) or # Github
("Battle" in a or "Sunweb-Napoleon" in a) or # Napoleon
("cathédrale" in a)) # Sully
class BackendWiki(Backend):
backendName = WIKI # defined in static.py
def answer(self, request, config):
if len(request.argsList) > 0:
return(wikiSummary(request))
else:
return("Vous avez mal tapé votre requête. Rappel: " + self.help())
def test(self, user):
r1 = Request(user, "wiki", ["Bussy"], [], "")
r2 = Request(user, "wiki", ["Bussy", "liste"], [], "")
r2 = Request(user, "wiki", ["Bussy", "recherche"], [], "")
r3 = Request(user, "wiki", ["Bussy", "liste", "numero 3"], [], "")
r4 = Request(user, "wiki", ["Bussy", "numero 3"], [], "")
r5 = Request(user, "wiki", ["Bussy", "en"], [], "")
r6 = Request(user, "wiki", ["Napoleon", "en", "liste"], [], "")
r7 = Request(user, "wiki", ["Napoleon", "recherche"], [], "")
r8 = Request(user, "wiki", ["Github", "fr"], [], "")
r9 = Request(user, "wiki", ["Sully"], [], "")
for r in [r1,r2,r3,r4,r5, r6, r7, r8, r9]:
logging.info("Checking a request [%s]" % r)
a = self.answer(r, {})
logging.info(a + "\n")
if not(likelyCorrect(a)):
return False
return True
def help(self):
return("Tapez 'wiki; texte' pour recevoir le résumé du premier article trouvé avec la recherche 'texte'. "
" Vous pouvez changer la langue comme ceci: 'wiki; Sully; en' (pour l'anglais). "
" Vous pouvez recevoir la liste des autres articles (en cas d'ambiguité) avec l'argument 'liste': "
"ex. 'wiki; Sully; liste'. Vous pouvez choisir de recevoir le n-ième de la liste comme ceci: "
"'wiki Sully; liste; numero n' ou 'wiki Sully; numero n'. "
"Finalement, vous pouvez recherchez tous les titres d'articles se rapprochant de votre texte avec l'option "
"'recherche': ex. 'wiki; Napoleon; recherche'.")
bWiki = BackendWiki()
| lutcheti/webtext | src/request/backends/BackendWiki.py | Python | gpl-3.0 | 9,114 |
import re, requests, collections, praw, time
words=list()
syl=collections.OrderedDict()
###############################################################################################################
# Generate syllables dictionary using Carnegie Mellon University's pronunciation dictionary (n=133,389 words) #
###############################################################################################################
cmudict=urllib.request.urlopen('http://svn.code.sf.net/p/cmusphinx/code/trunk/cmudict/cmudict.0.7a').read()
cmudict=cmudict.decode('utf8')
cmudict=cmudict.lower().split('\n')
unclutter=[i for j in (range(66), range(71, 73), range(75,83), range(86,118), range(119,125), range(133383,133388)) for i in j]
cmudict=[cmudict[i] for i in range(0,133388) if i not in unclutter] # Clean file from headers and footers.
x=[re.findall('\s{2}', i) for i in cmudict]
print('Length of word/phonemes divisions is same as length of list: ', len(x)==len(cmudict)) # If true it means that every word
del x # has indeed two whitespaces
# before the actual pronunciation,
# so we can safely use these spaces
# as separators.
words=[re.findall('(\w*\'?-?\w+?)\s{2}(.*)', i) for i in cmudict] # Separate cmudict into words and its phonemes. Words with many
# acceptions will have (1), (2) or (3) in their name, indicating
# the number of acceptions. These cases are eliminated in
# the next loop with the 'if' test.
for i in list(range(len(words))): # For each word/phoneme pair, generate a dictionary entry
if words[i]: # with the word as key, and number of lexical stresses
syl[words[i][0][0]] = len(re.sub('[a-z\s+]', '', words[i][0][1])) # (number of syllables) as value.
#########################################
## Login to Reddit and retrieve \r\all ##
#########################################
### Using requests instead of urllib ###
headers={'User-Agent': 'Script to find and post accidental haikus in user comments by your_user_name'}
req = requests.get('http://www.reddit.com/r/all/.json', allow_redirects=False, headers=headers)
links=re.findall('permalink\": \"(.*?)\"', req.text)
# Login and retrieve first 25 submission in \r\all
user_agent='Script to find and post accidental haikus in user comments by /u/pinchewero'
r=praw.Reddit(user_agent=user_agent)
username='your_user_name'
password='your_password'
r.login(username=username, password=password)
#submissions = r.get_subreddit('test').get_hot(limit=5)
submissions = r.get_subreddit('all').get_hot(limit=25)
submission = next(submissions)
already_done=set()
banned=['funny','politics','atheism', 'AskReddit', 'aww', 'wheredidthesodago', 'Minecraft', 'comics', 'technology', 'pics', 'IAmA'] # Add subreddits that might ban your bot
#########################
# Find and reply haikus #
#########################
for link in links:
urljson='http://www.reddit.com'+link+'.json'
if not re.findall('/r/(\w+)/', urljson)[0] in banned:
comments_raw=requests.get(urljson, allow_redirects=False, headers=headers)
comments_raw.connection.close()
comments=re.findall('"body": "(.*?)",', comments_raw.text) # Extract comments from json file
for i in range(len(comments)):
for ch in ['\\n']: # Clean up text a bit
if ch in comments[i]:
comments[i]=comments[i].replace(ch, ' ')
for ch in [',', '\\']:
if ch in comments[i]:
comments[i]=comments[i].replace(ch, '')
haikus=[]
line_markers_for_haikus=[]
haikus_found=0
for c in range(len(comments)):
sentence_markers=[dots.start() for dots in re.finditer('(?<!\.)[.?!](?!\.)', comments[c])] #(?<!\.)[\.\!\?](?=\s+\w+)
start_sentence=0
for s in range(len(sentence_markers)):
end_sentence=sentence_markers[s]
sentence=''.join([comments[c][i] for i in range(start_sentence,end_sentence)])
words_per_sentence=''.join([comments[c][i] for i in range(start_sentence,end_sentence)]).split()
syl_per_sentence=[syl[word.lower()] if word.lower() in syl.keys() else -100 for word in words_per_sentence]
if sum(syl_per_sentence) == 17: # Minimal number of syllables for a haiku to appear
word=0 # Counter for words index in each comment
syllables=0 # Counter for syllables
while syllables<5:
syllables+=syl_per_sentence[word]
word+=1
line_marker_1=word
if syllables==5: # 5 syllables
syllables=0
while syllables<7:
syllables+=syl_per_sentence[word]
word+=1
line_marker_2=word
if syllables==7: # 7 syllables
syllables=0
while syllables<5:
syllables+=syl_per_sentence[word]
word+=1
if syllables==5: # 5 syllables
haikus.append([sentence])
line_markers_for_haikus.append([line_marker_1,line_marker_2])
haikus_found+=1
start_sentence=end_sentence+2 # The period and the space after that.
print(haikus)
if len(haikus)>0:
flat_comments = praw.helpers.flatten_tree(submission.comments)
for h in range(len(haikus)):
words_in_haiku=str(haikus[h]).strip('["]').split()
line1=' '.join(words_in_haiku[:line_markers_for_haikus[h][0]])
line2=' '.join(words_in_haiku[line_markers_for_haikus[h][0]:line_markers_for_haikus[h][1]])
line3=' '.join(words_in_haiku[line_markers_for_haikus[h][1]:])
for i in range(len(flat_comments)):
if (not isinstance(flat_comments[i], praw.objects.MoreComments) and str(haikus[h]).strip('["]')[3:20] in flat_comments[i].body):
text_replied=' '+line1+'\n '+line2+'\n '+line3
flat_comments[i].reply(text_replied)
time.sleep(5)
time.sleep(5)
try:
submission = next(submissions)
except StopIteration:
r.clear_authentication()
r.http.close()
print("\n\n\nNo more links to search. Bye!\n\n\n")
break
| AlexRuizE/haiku_finder_bot | haiku_finder_bot.py | Python | gpl-3.0 | 7,590 |
# -*- coding: utf-8 -*-
#------------------------------------------------------------
# seriesly - XBMC Plugin
# Conector para Wupload
# http://blog.tvalacarta.info/plugin-xbmc/seriesly/
#------------------------------------------------------------
import urlparse,urllib2,urllib,re
import os
from core import scrapertools
from core import logger
from core import config
def test_video_exists( page_url ):
logger.info("[wupload.py] test_video_exists(page_url='%s')" % page_url)
# Existe: http://www.wupload.com/file/2666595132
# No existe: http://www.wupload.es/file/2668162342
location = scrapertools.get_header_from_response(page_url,header_to_get="location")
logger.info("location="+location)
if location!="":
page_url = location
data = scrapertools.downloadpageWithoutCookies(page_url)
logger.info("data="+data)
patron = '<p class="fileInfo filename"><span>Filename: </span> <strong>([^<]+)</strong></p>'
matches = re.compile(patron,re.DOTALL).findall(data)
if len(matches)>0:
return True,""
else:
patron = '<p class="deletedFile">(Sorry, this file has been removed.)</p>'
matches = re.compile(patron,re.DOTALL).findall(data)
if len(matches)>0:
return False,matches[0]
patron = '<div class="section CL3 regDownloadMessage"> <h3>(File does not exist)</h3> </div>'
matches = re.compile(patron,re.DOTALL).findall(data)
if len(matches)>0:
return False,matches[0]
return True,""
# Returns an array of possible video url's from the page_url
def get_video_url( page_url , premium = False , user="" , password="", video_password="" ):
logger.info("[wupload.py] get_video_url( page_url='%s' , user='%s' , password='%s', video_password=%s)" % (page_url , user , "**************************"[0:len(password)] , video_password) )
if not premium:
#return get_free_url(page_url)
logger.info("[wupload.py] free no soportado")
else:
# Hace el login y consigue la cookie
#login_url = "http://www.wupload.es/account/login"
login_url = "http://www.wupload.com/account/login"
post = "email="+user.replace("@","%40")+"&redirect=%2F&password="+password+"&rememberMe=1"
location = scrapertools.get_header_from_response( url=login_url, header_to_get="location", post=post)
logger.info("location="+location)
if location!="":
login_url = location
data = scrapertools.cache_page(url=login_url, post=post)
# Obtiene la URL final
headers = scrapertools.get_headers_from_response(page_url)
location1 = ""
for header in headers:
logger.info("header1="+str(header))
if header[0]=="location":
location1 = header[1]
logger.info("location1="+str(header))
# Obtiene la URL final
headers = scrapertools.get_headers_from_response(location1)
location2 = ""
content_disposition = ""
for header in headers:
logger.info("header2="+str(header))
if header[0]=="location":
location2 = header[1]
location = location2
if location=="":
location = location1
return [ ["(Premium) [wupload]",location + "|" + "User-Agent="+urllib.quote("Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; es-ES; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12") ] ]
return []
def get_free_url(page_url):
location = scrapertools.get_header_from_response(page_url,header_to_get="location")
if location!="":
page_url = location
logger.info("[wupload.py] location=%s" % page_url)
video_id = extract_id(page_url)
logger.info("[wupload.py] video_id=%s" % video_id)
data = scrapertools.cache_page(url=page_url)
patron = 'href="(.*?start=1.*?)"'
matches = re.compile(patron).findall(data)
scrapertools.printMatches(matches)
if len(matches)==0:
logger.error("[wupload.py] No encuentra el enlace Free")
return []
# Obtiene link de descarga free
download_link = matches[0]
if not download_link.startswith("http://"):
download_link = urlparse.urljoin(page_url,download_link)
logger.info("[wupload.py] Link descarga: "+ download_link)
# Descarga el enlace
headers = []
headers.append( ["X-Requested-With", "XMLHttpRequest"] )
headers.append( ["Referer" , page_url ])
headers.append( ["User-Agent" , "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; es-ES; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12" ])
headers.append( ["Content-Type" , "application/x-www-form-urlencoded; charset=UTF-8"])
headers.append( ["Accept-Encoding" , "gzip, deflate"])
headers.append( ["Accept","*/*"])
headers.append( ["Accept-Language","es-es,es;q=0.8,en-us;q=0.5,en;q=0.3"])
headers.append( ["Accept-Charset","ISO-8859-1,utf-8;q=0.7,*;q=0.7"])
headers.append( ["Connection","keep-alive"])
headers.append( ["Pragma","no-cache"])
headers.append( ["Cache-Control","no-cache"])
data = scrapertools.cache_page( download_link , headers=headers, post="" )
logger.info(data)
while True:
# Detecta el tiempo de espera
patron = "countDownDelay = (\d+)"
matches = re.compile(patron).findall(data)
if len(matches)>0:
tiempo_espera = int(matches[0])
logger.info("[wupload.py] tiempo de espera %d segundos" % tiempo_espera)
#import time
#time.sleep(tiempo_espera)
from platformcode.xbmc import xbmctools
resultado = xbmctools.handle_wait(tiempo_espera+5,"Progreso","Conectando con servidor Wupload (Free)")
if resultado == False:
break
tm = get_match(data,"name='tm' value='([^']+)'")
tm_hash = get_match(data,"name='tm_hash' value='([^']+)'")
post = "tm=" + tm + "&tm_hash=" + tm_hash
data = scrapertools.cache_page( download_link , headers=headers, post=post )
logger.info(data)
else:
logger.info("[wupload.py] no encontrado tiempo de espera")
# Detecta captcha
patron = "Recaptcha\.create"
matches = re.compile(patron).findall(data)
if len(matches)>0:
logger.info("[wupload.py] est� pidiendo el captcha")
recaptcha_key = get_match( data , 'Recaptcha\.create\("([^"]+)"')
logger.info("[wupload.py] recaptcha_key="+recaptcha_key)
data_recaptcha = scrapertools.cache_page("http://www.google.com/recaptcha/api/challenge?k="+recaptcha_key)
patron="challenge.*?'([^']+)'"
challenges = re.compile(patron, re.S).findall(data_recaptcha)
if(len(challenges)>0):
challenge = challenges[0]
image = "http://www.google.com/recaptcha/api/image?c="+challenge
#CAPTCHA
exec "import seriesly.captcha as plugin"
tbd = plugin.Keyboard("","",image)
tbd.doModal()
confirmed = tbd.isConfirmed()
if (confirmed):
tecleado = tbd.getText()
#logger.info("")
#tecleado = raw_input('Grab ' + image + ' : ')
post = "recaptcha_challenge_field=%s&recaptcha_response_field=%s" % (challenge,tecleado.replace(" ","+"))
data = scrapertools.cache_page( download_link , headers=headers, post=post )
logger.info(data)
else:
logger.info("[wupload.py] no encontrado captcha")
# Detecta captcha
patron = '<p><a href="(http\:\/\/.*?wupload[^"]+)">'
matches = re.compile(patron).findall(data)
if len(matches)>0:
final_url = matches[0]
'''
'GET /download/2616019677/4f0391ba/9bed4add/0/1/580dec58/3317afa30905a31794733c6a32da1987719292ff
HTTP/1.1
Accept-Language: es-es,es;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Connection: close\r\nAccept: */*\r\nUser-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; es-ES; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Host: s107.wupload.es
Referer: http://www.wupload.es/file/2616019677
Pragma: no-cache
Cache-Control: no-cache
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
00:39:39 T:2956623872 NOTICE: reply:
00:39:39 T:2956623872 NOTICE: 'HTTP/1.1 200 OK\r\n'
00:39:39 T:2956623872 NOTICE: header:
00:39:39 T:2956623872 NOTICE: Server: nginx
00:39:39 T:2956623872 NOTICE: header:
00:39:39 T:2956623872 NOTICE: Date: Tue, 03 Jan 2012 23:39:39 GMT
00:39:39 T:2956623872 NOTICE: header:
00:39:39 T:2956623872 NOTICE: Content-Type: "application/octet-stream"
00:39:39 T:2956623872 NOTICE: header:
00:39:39 T:2956623872 NOTICE: Content-Length: 230336429
00:39:39 T:2956623872 NOTICE: header:
00:39:39 T:2956623872 NOTICE: Last-Modified: Tue, 06 Sep 2011 01:07:26 GMT
00:39:39 T:2956623872 NOTICE: header:
00:39:39 T:2956623872 NOTICE: Connection: close
00:39:39 T:2956623872 NOTICE: header:
00:39:39 T:2956623872 NOTICE: Set-Cookie: dlc=1; expires=Thu, 02-Feb-2012 23:39:39 GMT; path=/; domain=.wupload.es
00:39:39 T:2956623872 NOTICE: header:
00:39:39 T:2956623872 NOTICE: : attachment; filename="BNS609.mp4"
'''
logger.info("[wupload.py] link descarga " + final_url)
return [["(Free)",final_url + '|' + 'Referer=' + urllib.quote(page_url) + "&Content-Type=" + urllib.quote("application/x-www-form-urlencoded; charset=UTF-8")+"&Cookie="+urllib.quote("lastUrlLinkId="+video_id)]]
else:
logger.info("[wupload.py] no detectado link descarga")
def extract_id(url):
return get_match(url, 'wupload.*?/file/(\d+)')
def get_match(data, regex) :
match = "";
m = re.search(regex, data)
if m != None :
match = m.group(1)
return match
def find_videos(data):
encontrados = set()
devuelve = []
patronvideos = '(http://www.wupload.*?/file/\d+)'
logger.info("[wupload.py] find_videos #"+patronvideos+"#")
matches = re.compile(patronvideos).findall(data)
for match in matches:
titulo = "[wupload]"
url = match
if url not in encontrados:
logger.info(" url="+url)
devuelve.append( [ titulo , url , 'wupload' ] )
encontrados.add(url)
else:
logger.info(" url duplicada="+url)
# Encontrado en animeflv
#s=mediafire.com%2F%3F7fsmmq2144fx6t4|-|wupload.com%2Ffile%2F2653904582
patronvideos = 'wupload.com\%2Ffile\%2F(\d+)'
logger.info("[wupload.py] find_videos #"+patronvideos+"#")
matches = re.compile(patronvideos).findall(data)
for match in matches:
titulo = "[wupload]"
url = "http://www.wupload.com/file/"+match
if url not in encontrados:
logger.info(" url="+url)
devuelve.append( [ titulo , url , 'wupload' ] )
encontrados.add(url)
else:
logger.info(" url duplicada="+url)
return devuelve | conejoninja/xbmc-seriesly | servers/wupload.py | Python | gpl-3.0 | 11,622 |
#! /usr/bin/env python3
import contextlib
import threading
import mwparserfromhell
import ws.ArchWiki.lang as lang
from ws.utils import LazyProperty
from ws.parser_helpers.title import canonicalize
from ws.parser_helpers.wikicode import get_parent_wikicode, get_adjacent_node
__all__ = ["get_edit_summary_tracker", "localize_flag", "CheckerBase"]
# WARNING: using the context manager is not thread-safe
def get_edit_summary_tracker(wikicode, summary_parts):
@contextlib.contextmanager
def checker(summary):
text = str(wikicode)
try:
yield
finally:
if text != str(wikicode):
summary_parts.append(summary)
return checker
def localize_flag(wikicode, node, template_name):
"""
If a ``node`` in ``wikicode`` is followed by a template with the same base
name as ``template_name``, this function changes the adjacent template's
name to ``template_name``.
:param wikicode: a :py:class:`mwparserfromhell.wikicode.Wikicode` object
:param node: a :py:class:`mwparserfromhell.nodes.Node` object
:param str template_name: the name of the template flag, potentially
including a language name
"""
parent = get_parent_wikicode(wikicode, node)
adjacent = get_adjacent_node(parent, node, ignore_whitespace=True)
if isinstance(adjacent, mwparserfromhell.nodes.Template):
adjname = lang.detect_language(str(adjacent.name))[0]
basename = lang.detect_language(template_name)[0]
if canonicalize(adjname) == canonicalize(basename):
adjacent.name = template_name
class CheckerBase:
def __init__(self, api, db, *, interactive=False, **kwargs):
self.api = api
self.db = db
self.interactive = interactive
# lock used for synchronizing access to the wikicode AST
# FIXME: the lock should not be an attribute of the checker, but of the wikicode
# maybe we can create a wrapper class (e.g. ThreadSafeWikicode) which would transparently synchronize all method calls: https://stackoverflow.com/a/17494777
# (we would still have to manually lock for wrapper functions and longer parts in the checkers)
self.lock_wikicode = threading.RLock()
@LazyProperty
def _alltemplates(self):
result = self.api.generator(generator="allpages", gapnamespace=10, gaplimit="max", gapfilterredir="nonredirects")
return {page["title"].split(":", maxsplit=1)[1] for page in result}
def get_localized_template(self, template, language="English"):
assert(canonicalize(template) in self._alltemplates)
localized = lang.format_title(template, language)
if canonicalize(localized) in self._alltemplates:
return localized
# fall back to English
return template
def handle_node(self, src_title, wikicode, node, summary_parts):
raise NotImplementedError("the handle_node method was not implemented in the derived class")
| lahwaacz/wiki-scripts | ws/checkers/CheckerBase.py | Python | gpl-3.0 | 3,021 |
#### initials.py ####
#
# Given a person's name, return the person's initials (uppercase)
#
def get_initials(fullname):
fullname = fullname.split(' ')
initials = ''
# accumulator pattern
for eachName in fullname:
initials = initials + eachName[0].upper()
return initials
def main():
inputName = input("What is your full name?\n")
print(get_initials(inputName))
if __name__ == '__main__':
main()
# test stub
## uncomment to validate code
#from testEqual import testEqual
### test: "First Last"
#testEqual.testEqual(get_initials("Ozzie Smith"), "OS")
### test: "first last"
#testEqual.testEqual(get_initials("bonnie blair"), "BB")
### test: "First Middle Last"
#testEqual.testEqual(get_initials("Daniel Day Lewis"), "DDL")
| e-inquirer/crypto | initials.py | Python | gpl-3.0 | 772 |
#!/usr/bin/python
# coding=utf-8
# region License
# Findeco is dually licensed under GPLv3 or later and MPLv2.
#
################################################################################
# Copyright (c) 2012 Klaus Greff <klaus.greff@gmx.net>
# This file is part of Findeco.
#
# Findeco is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; either version 3 of the License, or (at your option) any later
# version.
#
# Findeco 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
# Findeco. If not, see <http://www.gnu.org/licenses/>.
################################################################################
#
################################################################################
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#endregion #####################################################################
from __future__ import division, print_function, unicode_literals
| Qwlouse/Findeco | node_storage/tests/__init__.py | Python | gpl-3.0 | 1,410 |
from main.management.commands._private import SharedCommand
from main.models import Destination
class Command(SharedCommand):
model = Destination
| huseyinkabil/coral-ci | main/management/commands/insert_destination_data.py | Python | gpl-3.0 | 152 |
"""Tests for UnauthenticatedReddit class."""
from __future__ import print_function, unicode_literals
from mock import patch
from praw import handlers
from random import choice
from six.moves import cStringIO
from .helper import PRAWTest, betamax, replace_handler
class HandlerTest(PRAWTest):
def setUp(self):
super(HandlerTest, self).setUp()
self.cache_store = cStringIO()
def _cache_hit_callback(self, key):
pass
@replace_handler(handlers.RateLimitHandler())
def test_ratelimit_handlers(self):
to_evict = self.r.config[choice(list(self.r.config.API_PATHS.keys()))]
self.assertIs(0, self.r.handler.evict(to_evict))
@betamax()
def test_cache_hit_callback(self):
with patch.object(HandlerTest, '_cache_hit_callback') as mock:
self.r.handler.cache_hit_callback = self._cache_hit_callback
# ensure there won't be a difference in the cache key
self.r.login(self.un, self.un_pswd, disable_warning=True)
before_cache = list(self.r.get_new(limit=5))
after_cache = list(self.r.get_new(limit=5))
self.assertTrue(mock.called)
self.assertEqual(before_cache, after_cache)
self.r.handler.cache_hit_callback = None
| michael-lazar/praw3 | tests/test_handlers.py | Python | gpl-3.0 | 1,274 |
#!/bin/python
# gofed-ng - Golang system
# Copyright (C) 2016 Fridolin Pokorny, fpokorny@redhat.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.
#
# 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 sys
import os
def service_path2service_name(service_path):
basename = os.path.basename(service_path)
return basename[:-len('.py')]
if __name__ == "__main__":
sys.exit(1)
| gofed/gofed-ng | testsuite/helpers/utils.py | Python | gpl-3.0 | 1,073 |
"""
Fichier main qui lance le programme
"""
from Game import *
game = Game()
game.play()
| Vodak/SINS | src/main.py | Python | gpl-3.0 | 91 |
#-------------------------------------------------------------------------------
# PROJECT: VHDL Code Generator
# NAME: Dynamic AND Gate
#
# LICENSE: GNU-GPL V3
#-------------------------------------------------------------------------------
__isBlock__ = True
__className__ = "ANDGate"
__win__ = "ANDGateWindow"
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4 import uic
from lib.Block import *
class ANDGate(Block):
""" AND Gate
PORTS SPECIFICATIONS
"""
# TODO: Specifications of AND Gate (Documentation)
def __init__(self,system,numInput,sizeInput):
"""
:param name:
:param numInput: Number of input
:param size: Size of each input
:param system:
"""
self.numInput = numInput
self.name = "AND_GATE"
self.sizeInput = sizeInput
input_vector = [sizeInput]*self.numInput
output_vector = [sizeInput]
super().__init__(input_vector,output_vector,system,self.name)
def generate(self):
filetext = ""
if self.getOutputSignalSize(0) == 1:
filetext += "%s <= %s"%(self.getOutputSignalName(0),self.getInputSignalName(0))
for i in range(1,self.numInput):
filetext += " and %s"%(self.getInputSignalName(i))
else:
filetext += "%s <= "%self.getOutputSignalName(0)
for i in range (self.sizeInput):
filetext += "%s[%d]"%(self.getInputSignalName(0),self.sizeInput-i-1)
for j in range(1,self.numInput):
filetext += " and %s[%d]"%(self.getInputSignalName(j),self.sizeInput-i-1)
if i != self.sizeInput - 1:
filetext += " & "
filetext += ";\n"
return filetext
class ANDGateWindow(QWidget):
accept = pyqtSignal(list)
def __init__(self,parent = None):
super().__init__()
self.ui = uic.loadUi("blocks\\Standard Library\\Gate.ui",self)
self.ui.acceptButton.clicked.connect(self.accepted)
self.ui.setWindowTitle("AND GATE")
def accepted(self):
numInput = self.ui.numInput.value()
sizeInput = self.ui.sizeInput.value()
self.accept.emit([numInput,sizeInput])
self.close()
| BlakeTeam/VHDLCodeGenerator | blocks/Standard Library/Gate AND.py | Python | gpl-3.0 | 2,291 |
#
# Copyright (C) 2009, 2010 JAGSAT Development Team (see below)
#
# This file is part of JAGSAT.
#
# JAGSAT is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# JAGSAT is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# JAGSAT Development Team is:
# - Juan Pedro Bolivar Puente
# - Alberto Villegas Erce
# - Guillem Medina
# - Sarah Lindstrom
# - Aksel Junkkila
# - Thomas Forss
#
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from base.error import *
class CoreError (LoggableError):
pass
| arximboldi/jagsat | src/core/error.py | Python | gpl-3.0 | 1,072 |
# -*- coding: utf-8 -*-
"""Unit tests of assorted base data structures and common functions."""
import pytest
from simtools.base import Dict, is_iterable, is_string
def test_is_iterable():
# List of integers
obj = [1, 2, 3]
assert is_iterable(obj) == True
# Tuple of integers
obj = 1, 2, 3
assert is_iterable(obj) == True
# List of strings
obj = ["abc", "def", "ghi"]
assert is_iterable(obj) == True
# Tuple of strings
obj = "abc", "def", "ghi"
assert is_iterable(obj) == True
# Dictionary
obj = {1: "abc", 2: "def", 3: "ghi"}
assert is_iterable(obj) == True
# Integer
obj = 1
assert is_iterable(obj) == False
# String
obj = "abc"
assert is_iterable(obj) == True
def test_is_string():
# String
obj = "abc"
assert is_string(obj) == True
# Integer
obj = 1
assert is_string(obj) == False
# List of strings
obj = ["abc", "def", "ghi"]
assert is_string(obj) == False
# Dictionary
obj = {"abc": 1, "def": 2, "ghi": 3}
assert is_string(obj) == False
def test_dict_attr_access():
d = Dict()
d['a'] = 1
assert d.a == 1
d.b = 2
assert d['b'] == 2
with pytest.raises(AttributeError):
d.c
def test_dict_attr_deletion():
d = Dict()
d['a'] = 1
del d.a
with pytest.raises(KeyError):
d['a']
with pytest.raises(AttributeError):
d.a
| macknowak/simtools | simtools/tests/test_base.py | Python | gpl-3.0 | 1,438 |
# -*- coding: utf-8 -*-
__author__ = 'AminHP'
# python imports
import os
import shutil
import zipfile
import StringIO
import base64
# flask imports
from flask import jsonify, request, g, send_file, abort
# project imports
from project import app
from project.extensions import db, auth
from project.modules.datetime import utcnowts
from project.modules.paginator import paginate
from project.models.contest import Contest, Problem, ContestDateTimeError
from project.models.team import Team
from project.models.user import User
from project.forms.problem import UploadProblemBody, UploadTestCase
@app.api_route('', methods=['POST'])
@app.api_validate('contest.create_schema')
@auth.authenticate
def create():
"""
Create Contest
---
tags:
- contest
parameters:
- name: body
in: body
description: Contest information
required: true
schema:
id: ContestCreation
required:
- name
- starts_at
- ends_at
properties:
name:
type: string
example: babyknight
minLength: 1
maxLength: 32
starts_at:
type: integer
description: Contest starts_at (utc timestamp)
ends_at:
type: integer
description: Contest ends_at (utc timestamp)
recaptcha:
type: string
- name: Access-Token
in: header
type: string
required: true
description: Token of current user
responses:
201:
description: Successfully created
schema:
$ref: "#/definitions/api_1_contest_list_owner_get_ContestInfo"
400:
description: Bad request
401:
description: Token is invalid or has expired
406:
description: EndTime must be greater than StartTime and StartTime must be greater than CreationTime
409:
description: Contest already exists
"""
json = request.json
try:
obj = Contest()
obj.owner = User.objects.get(pk=g.user_id)
obj.populate(json)
obj.save()
return jsonify(obj.to_json()), 201
except db.NotUniqueError:
return abort(409, "Contest already exists")
except ContestDateTimeError:
return abort(406, "EndTime must be greater than StartTime and StartTime must be greater than CreationTime")
@app.api_route('<string:cid>', methods=['GET'])
@auth.authenticate
def info(cid):
"""
Get Contest Info
---
tags:
- contest
parameters:
- name: cid
in: path
type: string
required: true
description: Id of contest
- name: Access-Token
in: header
type: string
required: true
description: Token of current user
responses:
200:
description: Contest information
schema:
id: ContestInfoUser
type: object
properties:
id:
type: string
description: Contest id
name:
type: string
description: Contest name
owner:
description: Owner info
schema:
id: ContestOwnerInfo
type: object
properties:
id:
type: string
description: Owner id
username:
type: string
description: Owner username
created_at:
type: integer
description: Contest created_at (utc timestamp)
starts_at:
type: integer
description: Contest starts_at (utc timestamp)
ends_at:
type: integer
description: Contest ends_at (utc timestamp)
is_active:
type: boolean
description: Contest is_active
is_ended:
type: boolean
description: Contest is_ended
is_owner:
type: boolean
description: Contest is_owner
is_admin:
type: boolean
description: Contest is_admin
pending_teams_num:
type: integer
description: Contest number of pending teams
accepted_teams_num:
type: integer
description: Contest number of accepted teams
joining_status:
type: object
description: Contest user joining status
schema:
properties:
status:
type: integer
description: joining status (0=not_joined, 1=waiting, 2=joined)
team:
schema:
id: TeamAbsInfo
properties:
id:
type: string
description: Team id
name:
type: string
description: Team name
owner:
description: Owner info
schema:
$ref: "#/definitions/api_1_team_info_get_UserAbsInfo"
401:
description: Token is invalid or has expired
404:
description: Contest does not exist
"""
try:
obj = Contest.objects.get(pk=cid)
user_obj = User.objects.get(pk=g.user_id)
return jsonify(obj.to_json_user(user_obj)), 200
except (db.DoesNotExist, db.ValidationError):
return abort(404, "Contest does not exist")
@app.api_route('<string:cid>', methods=['PUT'])
@app.api_validate('contest.edit_schema')
@auth.authenticate
def edit(cid):
"""
Edit Contest
---
tags:
- contest
parameters:
- name: cid
in: path
type: string
required: true
description: Id of contest
- name: body
in: body
description: Contest information
required: true
schema:
id: ContestEdition
properties:
name:
type: string
example: babyknight
minLength: 1
maxLength: 32
starts_at:
type: integer
description: Contest starts_at (utc timestamp)
ends_at:
type: integer
description: Contest ends_at (utc timestamp)
- name: Access-Token
in: header
type: string
required: true
description: Token of current user
responses:
200:
description: Successfully edited
schema:
$ref: "#/definitions/api_1_contest_list_owner_get_ContestInfo"
400:
description: Bad request
401:
description: Token is invalid or has expired
403:
description: You aren't owner or admin of the contest
404:
description: Contest does not exist
406:
description: EndTime must be greater than StartTime and StartTime must be greater than CreationTime
409:
description: Contest name already exists
"""
json = request.json
try:
obj = Contest.objects.get(pk=cid)
user_obj = User.objects.get(pk=g.user_id)
if (user_obj != obj.owner) and (not user_obj in obj.admins):
return abort(403, "You aren't owner or admin of the contest")
obj.populate(json)
obj.save()
return jsonify(obj.to_json()), 200
except db.NotUniqueError:
return abort(409, "Contest name already exists")
except (db.DoesNotExist, db.ValidationError):
return abort(404, "Contest does not exist")
except ContestDateTimeError:
return abort(406, "EndTime must be greater than StartTime and StartTime must be greater than CreationTime")
@app.api_route('<string:cid>/', methods=['DELETE'])
@auth.authenticate
def delete(cid):
"""
Contest Delete
---
tags:
- contest
parameters:
- name: cid
in: path
type: string
required: true
description: Id of contest
- name: Access-Token
in: header
type: string
required: true
description: Token of current user
responses:
200:
description: Successfully deleted
401:
description: Token is invalid or has expired
403:
description: You aren't owner of the contest
404:
description: Contest does not exist
"""
try:
obj = Contest.objects.get(pk=cid)
user_obj = User.objects.get(pk=g.user_id)
if user_obj != obj.owner:
return abort(403, "You aren't owner of the contest")
obj.delete()
return '', 200
except (db.DoesNotExist, db.ValidationError):
return abort(404, "Contest does not exist")
@app.api_route('', methods=['GET'])
@paginate('contests', 20)
@auth.authenticate
def list():
"""
Get All Contests List
---
tags:
- contest
parameters:
- name: page
in: query
type: integer
required: false
description: Page number
- name: per_page
in: query
type: integer
required: false
description: Contest amount per page (default is 10)
- name: Access-Token
in: header
type: string
required: true
description: Token of current user
responses:
200:
description: List of contests
schema:
id: ContestsListUser
type: object
properties:
contests:
type: array
items:
$ref: "#/definitions/api_1_contest_info_get_ContestInfoUser"
meta:
type: object
description: Pagination meta data
properties:
first:
type: string
description: Url for first page of results
last:
type: string
description: Url for last page of results
next:
type: string
description: Url for next page of results
prev:
type: string
description: Url for previous page of results
page:
type: integer
description: Number of the current page
pages:
type: integer
description: All pages count
per_page:
type: integer
description: Item per each page
total:
type: integer
description: Total count of all items
401:
description: Token is invalid or has expired
"""
user_obj = User.objects.get(pk=g.user_id)
contests = Contest.objects.order_by('-starts_at')
result_func = lambda obj: Contest.to_json_user(obj, user_obj)
return contests, result_func
@app.api_route('owner', methods=['GET'])
@paginate('contests', 20)
@auth.authenticate
def list_owner():
"""
Get Owner Contests
---
tags:
- contest
parameters:
- name: page
in: query
type: integer
required: false
description: Page number
- name: per_page
in: query
type: integer
required: false
description: Contest amount per page (default is 10)
- name: Access-Token
in: header
type: string
required: true
description: Token of current user
responses:
200:
description: List of contests
schema:
id: ContestsList
type: object
properties:
contests:
type: array
items:
schema:
id: ContestInfo
type: object
properties:
id:
type: string
description: Contest id
name:
type: string
description: Contest name
owner:
description: Owner info
schema:
id: ContestOwnerInfo
type: object
properties:
id:
type: string
description: Owner id
username:
type: string
description: Owner username
created_at:
type: integer
description: Contest created_at (utc timestamp)
starts_at:
type: integer
description: Contest starts_at (utc timestamp)
ends_at:
type: integer
description: Contest ends_at (utc timestamp)
is_active:
type: boolean
description: Contest is_active
is_ended:
type: boolean
description: Contest is_ended
pending_teams_num:
type: integer
description: Contest number of pending teams
accepted_teams_num:
type: integer
description: Contest number of accepted teams
401:
description: Token is invalid or has expired
"""
user_obj = User.objects.get(pk=g.user_id)
contests = Contest.objects.filter(owner=user_obj).order_by('-starts_at')
result_func = lambda obj: Contest.to_json(obj)
return contests, result_func
@app.api_route('<string:cid>/result', methods=['GET'])
@auth.authenticate
def result(cid):
"""
Get Result
---
tags:
- contest
parameters:
- name: cid
in: path
type: string
required: true
description: Id of contest
- name: Access-Token
in: header
type: string
required: true
description: Token of current user
responses:
200:
description: Result information
schema:
id: ContestResult
type: object
properties:
result:
type: object
properties:
team_id*:
type: object
description: Teams result dictionary (team_id => team_data).
Teams without submission aren't in this dictionary
properties:
penalty:
type: integer
solved_count:
type: integer
problems:
type: object
properties:
problem_id*:
type: object
description: Problems result dictionary (problem_id => problem_data).
Problems without submission aren't in this dictionary
properties:
submitted_at:
type: integer
description: Last submission time (utc timestmap) (default=null)
failed_tries:
type: integer
penalty:
type: integer
solved:
type: boolean
teams:
type: array
description: Teams list (sorted by rank in contest)
items:
schema:
properties:
id:
type: string
description: Team id
name:
type: string
description: Team name
problems:
type: array
description: Problems list
items:
schema:
properties:
id:
type: string
description: Problem id
title:
type: string
description: Problem title
401:
description: Token is invalid or has expired
403:
description: You aren't allowed to see result
404:
description: Contest does not exist
"""
try:
obj = Contest.objects.get(pk=cid)
user_obj = User.objects.get(pk=g.user_id)
now = utcnowts()
if not (user_obj == obj.owner or user_obj in obj.admins or \
(now >= obj.starts_at and obj.is_user_in_contest(user_obj)) or \
(now > obj.ends_at)):
return abort(403, "You aren't allowed to see result")
return jsonify(obj.to_json_result()), 200
except (db.DoesNotExist, db.ValidationError):
return abort(404, "Contest does not exist")
################################# Team #################################
@app.api_route('team/<string:tid>', methods=['GET'])
@auth.authenticate
def list_team(tid):
"""
Get Contests List of a Team
---
tags:
- contest
parameters:
- name: tid
in: path
type: string
required: true
description: Id of team
- name: Access-Token
in: header
type: string
required: true
description: Token of current user
responses:
200:
description: Team contests list
schema:
id: TeamContestsList
type: object
properties:
waiting_contests:
type: array
items:
schema:
$ref: "#/definitions/api_1_contest_list_owner_get_ContestInfo"
joined_contests:
type: array
items:
schema:
$ref: "#/definitions/api_1_contest_list_owner_get_ContestInfo"
401:
description: Token is invalid or has expired
404:
description: Team does not exist
"""
try:
obj = Team.objects.get(pk=tid)
wc = Contest.objects.filter(pending_teams=obj)
wc = [c.to_json() for c in wc]
jc = Contest.objects.filter(accepted_teams=obj)
jc = [c.to_json() for c in jc]
return jsonify(waiting_contests=wc, joined_contests=jc), 200
except (db.DoesNotExist, db.ValidationError):
return abort(404, "Team does not exist")
@app.api_route('<string:cid>/team', methods=['POST'])
@app.api_validate('contest.team_join_schema')
@auth.authenticate
def team_join(cid):
"""
Team Join
---
tags:
- contest
parameters:
- name: cid
in: path
type: string
required: true
description: Id of contest
- name: body
in: body
description: Team Identification
required: true
schema:
id: TeamIdentification
properties:
team_id:
type: string
- name: Access-Token
in: header
type: string
required: true
description: Token of current user
responses:
200:
description: Join request sent
400:
description: Bad request
401:
description: Token is invalid or has expired
403:
description: You aren't owner of the team
404:
description: Contest or Team does not exist
409:
description: You are already accepted
"""
json = request.json
try:
obj = Contest.objects.get(pk=cid)
team_obj = Team.objects.get(pk=json['team_id'])
if str(team_obj.owner.pk) != g.user_id:
return abort(403, "You aren't owner of the team")
if team_obj in obj.accepted_teams:
return abort(409, "You are already accepted")
obj.update(add_to_set__pending_teams=team_obj)
return '', 200
except (db.DoesNotExist, db.ValidationError):
return abort(404, "Contest or Team does not exist")
@app.api_route('<string:cid>/team/<string:tid>', methods=['DELETE'])
@auth.authenticate
def team_unjoin(cid, tid):
"""
Team Unjoin
---
tags:
- contest
parameters:
- name: cid
in: path
type: string
required: true
description: Id of contest
- name: tid
in: path
type: string
required: true
description: Id of team
- name: Access-Token
in: header
type: string
required: true
description: Token of current user
responses:
200:
description: Successfully unjoined
400:
description: Bad request
401:
description: Token is invalid or has expired
403:
description: You aren't owner of the team
404:
description: Contest or Team does not exist
"""
try:
team_obj = Team.objects.get(pk=tid)
obj = Contest.objects.get(pk=cid, pending_teams=team_obj)
if str(team_obj.owner.pk) != g.user_id:
return abort(403, "You aren't owner of the team")
obj.update(pull__pending_teams=team_obj)
return '', 200
except (db.DoesNotExist, db.ValidationError):
return abort(404, "Contest or Team does not exist")
@app.api_route('<string:cid>/pending_teams', methods=['GET'])
@auth.authenticate
def team_list_pending(cid):
"""
Team Get Pending List
---
tags:
- contest
parameters:
- name: cid
in: path
type: string
required: true
description: Id of contest
- name: Access-Token
in: header
type: string
required: true
description: Token of current user
responses:
200:
description: List of pending teams
schema:
id: ContestTeamsList
type: object
properties:
teams:
type: array
items:
schema:
$ref: "#/definitions/api_1_team_info_get_TeamInfo"
401:
description: Token is invalid or has expired
403:
description: You aren't owner or admin of the contest
404:
description: Contest does not exist
"""
try:
obj = Contest.objects.get(pk=cid)
user_obj = User.objects.get(pk=g.user_id)
if (user_obj != obj.owner) and (not user_obj in obj.admins):
return abort(403, "You aren't owner or admin of the contest")
return jsonify(obj.to_json_teams('pending')), 200
except (db.DoesNotExist, db.ValidationError):
return abort(404, "Contest does not exist")
@app.api_route('<string:cid>/accepted_teams', methods=['GET'])
@auth.authenticate
def team_list_accepted(cid):
"""
Team Get Accepted List
---
tags:
- contest
parameters:
- name: cid
in: path
type: string
required: true
description: Id of contest
- name: Access-Token
in: header
type: string
required: true
description: Token of current user
responses:
200:
description: List of accepted teams
schema:
$ref: "#/definitions/api_1_contest_team_list_pending_get_ContestTeamsList"
401:
description: Token is invalid or has expired
403:
description: You aren't owner or admin of the contest
404:
description: Contest does not exist
"""
try:
obj = Contest.objects.get(pk=cid)
user_obj = User.objects.get(pk=g.user_id)
if (user_obj != obj.owner) and (not user_obj in obj.admins):
return abort(403, "You aren't owner or admin of the contest")
return jsonify(obj.to_json_teams('accepted')), 200
except (db.DoesNotExist, db.ValidationError):
return abort(404, "Contest does not exist")
@app.api_route('<string:cid>/team/<string:tid>/acceptation', methods=['PATCH'])
@auth.authenticate
def team_accept(cid, tid):
"""
Team Accept
---
tags:
- contest
parameters:
- name: cid
in: path
type: string
required: true
description: Id of contest
- name: tid
in: path
type: string
required: true
description: Id of team
- name: Access-Token
in: header
type: string
required: true
description: Token of current user
responses:
200:
description: Successfully accepted
401:
description: Token is invalid or has expired
403:
description: You aren't owner or admin of the contest
404:
description: Contest or Team does not exist
"""
try:
team_obj = Team.objects.get(pk=tid)
obj = Contest.objects.get(pk=cid, pending_teams=team_obj)
user_obj = User.objects.get(pk=g.user_id)
if (user_obj != obj.owner) and (not user_obj in obj.admins):
return abort(403, "You aren't owner or admin of the contest")
obj.update(pull__pending_teams=team_obj, add_to_set__accepted_teams=team_obj)
return '', 200
except (db.DoesNotExist, db.ValidationError):
return abort(404, "Contest or Team does not exist")
@app.api_route('<string:cid>/team/<string:tid>/acceptation', methods=['DELETE'])
@auth.authenticate
def team_reject(cid, tid):
"""
Team Reject
---
tags:
- contest
parameters:
- name: cid
in: path
type: string
required: true
description: Id of contest
- name: tid
in: path
type: string
required: true
description: Id of team
- name: Access-Token
in: header
type: string
required: true
description: Token of current user
responses:
200:
description: Successfully rejected
401:
description: Token is invalid or has expired
403:
description: You aren't owner or admin of the contest
404:
description: Contest or Team does not exist
"""
try:
team_obj = Team.objects.get(pk=tid)
obj = Contest.objects.get(pk=cid, pending_teams=team_obj)
user_obj = User.objects.get(pk=g.user_id)
if (user_obj != obj.owner) and (not user_obj in obj.admins):
return abort(403, "You aren't owner or admin of the contest")
obj.update(pull__pending_teams=team_obj)
return '', 200
except (db.DoesNotExist, db.ValidationError):
return abort(404, "Contest or Team does not exist")
@app.api_route('<string:cid>/team/<string:tid>/kick', methods=['DELETE'])
@auth.authenticate
def team_kick(cid, tid):
"""
Team Kick
---
tags:
- contest
parameters:
- name: cid
in: path
type: string
required: true
description: Id of contest
- name: tid
in: path
type: string
required: true
description: Id of team
- name: Access-Token
in: header
type: string
required: true
description: Token of current user
responses:
200:
description: Successfully kicked
401:
description: Token is invalid or has expired
403:
description: You aren't owner or admin of the contest
404:
description: Contest or Team does not exist
"""
try:
team_obj = Team.objects.get(pk=tid)
obj = Contest.objects.get(pk=cid, accepted_teams=team_obj)
user_obj = User.objects.get(pk=g.user_id)
if (user_obj != obj.owner) and (not user_obj in obj.admins):
return abort(403, "You aren't owner or admin of the contest")
obj.update(pull__accepted_teams=team_obj)
return '', 200
except (db.DoesNotExist, db.ValidationError):
return abort(404, "Contest or Team does not exist")
################################# Problem #################################
@app.api_route('<string:cid>/problem', methods=['POST'])
@app.api_validate('contest.problem_create_schema')
@auth.authenticate
def problem_create(cid):
"""
Problem Create
Maximum number of problems can be created is 20
---
tags:
- contest
parameters:
- name: cid
in: path
type: string
required: true
description: Id of contest
- name: body
in: body
description: Problem information
required: true
schema:
id: ProblemCreation
required:
- title
- time_limit
- space_limit
properties:
title:
type: string
example: babyknight
minLength: 1
maxLength: 32
time_limit:
type: number
minimum: 0.1
maximum: 10
description: Problem time limit (seconds)
space_limit:
type: integer
minimum: 16
maximum: 256
description: Problem space limit (mega bytes)
- name: Access-Token
in: header
type: string
required: true
description: Token of current user
responses:
201:
description: Successfully created
schema:
$ref: "#/definitions/api_1_contest_problem_info_get_ProblemInfo"
400:
description: Bad request
401:
description: Token is invalid or has expired
403:
description: You aren't owner or admin of the contest
404:
description: Contest does not exist
406:
description: You can't create more problems
"""
json = request.json
try:
obj = Contest.objects.get(pk=cid)
user_obj = User.objects.get(pk=g.user_id)
if (user_obj != obj.owner) and (not user_obj in obj.admins):
return abort(403, "You aren't owner or admin of the contest")
if len(obj.problems) >= 20:
return abort(406, "You can't create more problems")
problem_obj = Problem()
problem_obj.populate(json)
problem_obj.save()
obj.update(push__problems=problem_obj)
return jsonify(problem_obj.to_json()), 201
except (db.DoesNotExist, db.ValidationError):
return abort(404, "Contest does not exist")
@app.api_route('<string:cid>/problem/<string:pid>', methods=['GET'])
@auth.authenticate
def problem_info(cid, pid):
"""
Problem Get Info
---
tags:
- contest
parameters:
- name: cid
in: path
type: string
required: true
description: Id of contest
- name: pid
in: path
type: string
required: true
description: Id of problem
- name: Access-Token
in: header
type: string
required: true
description: Token of current user
responses:
200:
description: Problem information
schema:
id: ProblemInfo
type: object
properties:
id:
type: string
description: Problem id
title:
type: string
description: Problem title
time_limit:
type: number
description: Problem time limit (seconds)
space_limit:
type: integer
description: Problem space limit (mega bytes)
401:
description: Token is invalid or has expired
403:
description: You aren't allowed to see problem
404:
description: Contest or problem does not exist
"""
try:
problem_obj = Problem.objects.get(pk=pid)
obj = Contest.objects.get(pk=cid, problems=problem_obj)
user_obj = User.objects.get(pk=g.user_id)
now = utcnowts()
if not (user_obj == obj.owner or user_obj in obj.admins or \
(now >= obj.starts_at and obj.is_user_in_contest(user_obj)) or \
(now > obj.ends_at)):
return abort(403, "You aren't allowed to see problem")
return jsonify(problem_obj.to_json()), 200
except (db.DoesNotExist, db.ValidationError):
return abort(404, "Contest or problem does not exist")
@app.api_route('<string:cid>/problem', methods=['GET'])
@auth.authenticate
def problem_list(cid):
"""
Problem Get List
---
tags:
- contest
parameters:
- name: cid
in: path
type: string
required: true
description: Id of contest
- name: Access-Token
in: header
type: string
required: true
description: Token of current user
responses:
200:
description: List of problems
schema:
id: ContestProblemsList
type: object
properties:
problems:
type: array
items:
schema:
id: ProblemAbsInfo
type: object
properties:
id:
type: string
description: Problem id
title:
type: string
description: Problem title
401:
description: Token is invalid or has expired
403:
description: You aren't allowed to see problems
404:
description: Contest does not exist
"""
try:
obj = Contest.objects.get(pk=cid)
user_obj = User.objects.get(pk=g.user_id)
now = utcnowts()
if not (user_obj == obj.owner or user_obj in obj.admins or \
(now >= obj.starts_at and obj.is_user_in_contest(user_obj)) or \
(now > obj.ends_at)):
return abort(403, "You aren't allowed to see problems")
return jsonify(obj.to_json_problems()), 200
except (db.DoesNotExist, db.ValidationError):
return abort(404, "Contest does not exist")
@app.api_route('<string:cid>/problem/<string:pid>', methods=['PUT'])
@app.api_validate('contest.problem_edit_schema')
@auth.authenticate
def problem_edit(cid, pid):
"""
Problem Edit
---
tags:
- contest
parameters:
- name: cid
in: path
type: string
required: true
description: Id of contest
- name: pid
in: path
type: string
required: true
description: Id of problem
- name: body
in: body
description: Problem information
required: true
schema:
id: ProblemEdition
properties:
title:
type: string
example: babyknight
minLength: 1
maxLength: 32
time_limit:
type: number
minimum: 0.1
maximum: 10
description: Problem time limit (seconds)
space_limit:
type: integer
minimum: 16
maximum: 256
description: Problem space limit (mega bytes)
- name: Access-Token
in: header
type: string
required: true
description: Token of current user
responses:
200:
description: Successfully edited
schema:
$ref: "#/definitions/api_1_contest_problem_info_get_ProblemInfo"
400:
description: Bad request
401:
description: Token is invalid or has expired
403:
description: You aren't owner or admin of the contest
404:
description: Contest or problem does not exist
"""
json = request.json
try:
problem_obj = Problem.objects.get(pk=pid)
obj = Contest.objects.get(pk=cid, problems=problem_obj)
user_obj = User.objects.get(pk=g.user_id)
if (user_obj != obj.owner) and (not user_obj in obj.admins):
return abort(403, "You aren't owner or admin of the contest")
problem_obj.populate(json)
problem_obj.save()
return jsonify(problem_obj.to_json()), 200
except (db.DoesNotExist, db.ValidationError):
return abort(404, "Contest or problem does not exist")
@app.api_route('<string:cid>/problem', methods=['PATCH'])
@app.api_validate('contest.problem_change_order_schema')
@auth.authenticate
def problem_change_order(cid):
"""
Problem Change Order
---
tags:
- contest
parameters:
- name: cid
in: path
type: string
required: true
description: Id of contest
- name: body
in: body
description: Problems order
required: true
schema:
id: ProblemsOrder
required:
- order
properties:
order:
type: array
items:
type: integer
description: order number
- name: Access-Token
in: header
type: string
required: true
description: Token of current user
responses:
200:
description: List of problems
schema:
$ref: "#/definitions/api_1_contest_problem_list_get_ContestProblemsList"
400:
description: Bad request
401:
description: Token is invalid or has expired
403:
description: You aren't owner or admin of the contest
404:
description: Contest does not exist
406:
description: Bad order format
"""
json = request.json
try:
obj = Contest.objects.get(pk=cid)
user_obj = User.objects.get(pk=g.user_id)
if (user_obj != obj.owner) and (not user_obj in obj.admins):
return abort(403, "You aren't owner or admin of the contest")
if len(list(set(json['order']))) != len(json['order']) or \
len(json['order']) != len(obj.problems):
return abort(406, "Bad order format")
new_problems = []
for i in json['order']:
new_problems.append(obj.problems[i])
obj.problems = new_problems
obj.save()
return jsonify(obj.to_json_problems()), 200
except IndexError:
return abort(406, "Bad order format")
except (db.DoesNotExist, db.ValidationError):
return abort(404, "Contest does not exist")
@app.api_route('<string:cid>/problem/<string:pid>', methods=['DELETE'])
@auth.authenticate
def problem_delete(cid, pid):
"""
Problem Delete
---
tags:
- contest
parameters:
- name: cid
in: path
type: string
required: true
description: Id of contest
- name: pid
in: path
type: string
required: true
description: Id of problem
- name: Access-Token
in: header
type: string
required: true
description: Token of current user
responses:
200:
description: Successfully deleted
schema:
$ref: "#/definitions/api_1_contest_problem_list_get_ContestProblemsList"
401:
description: Token is invalid or has expired
403:
description: You aren't owner or admin of the contest
404:
description: Contest or problem does not exist
"""
try:
problem_obj = Problem.objects.get(pk=pid)
obj = Contest.objects.get(pk=cid, problems=problem_obj)
user_obj = User.objects.get(pk=g.user_id)
if (user_obj != obj.owner) and (not user_obj in obj.admins):
return abort(403, "You aren't owner or admin of the contest")
problem_obj.delete()
obj.reload()
return jsonify(obj.to_json_problems()), 200
except (db.DoesNotExist, db.ValidationError):
return abort(404, "Contest or problem does not exist")
@app.api_route('<string:cid>/problem/<string:pid>/body', methods=['POST'])
@auth.authenticate
def problem_upload_body(cid, pid):
"""
Problem Upload Body File
---
tags:
- contest
parameters:
- name: cid
in: path
type: string
required: true
description: Id of contest
- name: pid
in: path
type: string
required: true
description: Id of problem
- name: body
in: formData
type: file
required: true
description: Problem body file (pdf) (max size is 16M)
- name: Access-Token
in: header
type: string
required: true
description: Token of current user
responses:
200:
description: Successfully uploaded
400:
description: Bad request
401:
description: Token is invalid or has expired
403:
description: You aren't owner or admin of the contest
404:
description: Contest or problem does not exist
413:
description: Request entity too large. (max size is 16M)
415:
description: Supported file type is only application/pdf
"""
try:
problem_obj = Problem.objects.get(pk=pid)
obj = Contest.objects.get(pk=cid, problems=problem_obj)
user_obj = User.objects.get(pk=g.user_id)
if (user_obj != obj.owner) and (not user_obj in obj.admins):
return abort(403, "You aren't owner or admin of the contest")
form = UploadProblemBody()
if not form.validate():
return abort(400, "Bad request")
if not form.validate_file():
return abort(415, "Supported file type is only application/pdf")
file_obj = form.body.data
file_obj.save(problem_obj.body_path)
return "", 200
except (db.DoesNotExist, db.ValidationError):
return abort(404, "Contest or problem does not exist")
@app.api_route('<string:cid>/problem/<string:pid>/testcase', methods=['POST'])
@auth.authenticate
def problem_upload_testcase(cid, pid):
"""
Problem Upload Testcase File
---
tags:
- contest
parameters:
- name: cid
in: path
type: string
required: true
description: Id of contest
- name: pid
in: path
type: string
required: true
description: Id of problem
- name: testcase
in: formData
type: file
required: true
description: Problem testcase file (zip) (max size is 16M)
- name: Access-Token
in: header
type: string
required: true
description: Token of current user
responses:
200:
description: Successfully uploaded
400:
description: Bad request
401:
description: Token is invalid or has expired
403:
description: You aren't owner or admin of the contest
404:
description: Contest or problem does not exist
413:
description: Request entity too large. (max size is 16M)
415:
description: Supported file type is only application/zip
"""
try:
problem_obj = Problem.objects.get(pk=pid)
obj = Contest.objects.get(pk=cid, problems=problem_obj)
user_obj = User.objects.get(pk=g.user_id)
if (user_obj != obj.owner) and (not user_obj in obj.admins):
return abort(403, "You aren't owner or admin of the contest")
form = UploadTestCase()
if not form.validate():
return abort(400, "Bad request")
if not form.validate_file():
return abort(415, "Supported file type is only application/zip")
if os.path.exists(problem_obj.testcase_dir):
shutil.rmtree(problem_obj.testcase_dir)
file_obj = form.testcase.data
with zipfile.ZipFile(file_obj) as zf:
zf.extractall(problem_obj.testcase_dir)
return "", 200
except (db.DoesNotExist, db.ValidationError):
return abort(404, "Contest or problem does not exist")
@app.api_route('<string:cid>/problem/<string:pid>/body', methods=['GET'])
@auth.authenticate
def problem_download_body(cid, pid):
"""
Problem Download Body File
---
tags:
- contest
parameters:
- name: cid
in: path
type: string
required: true
description: Id of contest
- name: pid
in: path
type: string
required: true
description: Id of problem
- name: Access-Token
in: header
type: string
required: true
description: Token of current user
responses:
200:
description: Problem body file
401:
description: Token is invalid or has expired
403:
description: You aren't allowed to see problem body
404:
description: (Contest or problem does not exist, File does not exist)
"""
try:
problem_obj = Problem.objects.get(pk=pid)
obj = Contest.objects.get(pk=cid, problems=problem_obj)
user_obj = User.objects.get(pk=g.user_id)
now = utcnowts()
if not (user_obj == obj.owner or user_obj in obj.admins or \
(now >= obj.starts_at and obj.is_user_in_contest(user_obj)) or \
(now > obj.ends_at)):
return abort(403, "You aren't allowed to see problem body")
data = open(problem_obj.body_path).read()
data = base64.b64encode(data)
data_io = StringIO.StringIO(data)
return send_file(data_io, mimetype='application/pdf')
except IOError:
return abort(404, "File does not exist")
except (db.DoesNotExist, db.ValidationError):
return abort(404, "Contest or problem does not exist")
################################# Admin #################################
@app.api_route('<string:cid>/admin', methods=['POST'])
@app.api_validate('contest.admin_add_schema')
@auth.authenticate
def admin_add(cid):
"""
Admin Add
---
tags:
- contest
parameters:
- name: cid
in: path
type: string
required: true
description: Id of contest
- name: body
in: body
description: Problem information
required: true
schema:
id: AdminIdentificationName
required:
- username
properties:
username:
type: string
- name: Access-Token
in: header
type: string
required: true
description: Token of current user
responses:
201:
description: Admin added
schema:
$ref: "#/definitions/api_1_contest_admin_list_get_AdminsList"
400:
description: Bad request
401:
description: Token is invalid or has expired
403:
description: You aren't owner of the contest
404:
description: Contest or user does not exist
"""
json = request.json
try:
obj = Contest.objects.get(pk=cid)
if str(obj.owner.pk) != g.user_id:
return abort(403, "You aren't owner of the contest")
user_obj = User.objects.get(username=json['username'])
if user_obj != obj.owner:
obj.update(add_to_set__admins=user_obj)
obj.reload()
return jsonify(obj.to_json_admins()), 201
except (db.DoesNotExist, db.ValidationError):
return abort(404, "Contest or user does not exist")
@app.api_route('<string:cid>/admin/<string:uid>', methods=['DELETE'])
@auth.authenticate
def admin_remove(cid, uid):
"""
Admin Remove
---
tags:
- contest
parameters:
- name: cid
in: path
type: string
required: true
description: Id of contest
- name: uid
in: path
type: string
required: true
description: Id of user
- name: Access-Token
in: header
type: string
required: true
description: Token of current user
responses:
200:
description: Successully removed
schema:
$ref: "#/definitions/api_1_contest_admin_list_get_AdminsList"
400:
description: Bad request
401:
description: Token is invalid or has expired
403:
description: You aren't owner of the contest
404:
description: Contest or user does not exist
"""
try:
obj = Contest.objects.get(pk=cid)
if str(obj.owner.pk) != g.user_id:
return abort(403, "You aren't owner of the contest")
user_obj = User.objects.get(pk=uid)
obj.update(pull__admins=user_obj)
obj.reload()
return jsonify(obj.to_json_admins()), 200
except (db.DoesNotExist, db.ValidationError):
return abort(404, "Contest or user does not exist")
@app.api_route('<string:cid>/admin', methods=['GET'])
@auth.authenticate
def admin_list(cid):
"""
Admin List
---
tags:
- contest
parameters:
- name: cid
in: path
type: string
required: true
description: Id of contest
- name: Access-Token
in: header
type: string
required: true
description: Token of current user
responses:
200:
description: List of admins
schema:
id: AdminsList
properties:
admins:
type: array
items:
schema:
$ref: "#/definitions/api_1_team_info_get_UserAbsInfo"
401:
description: Token is invalid or has expired
403:
description: You aren't owner of the contest
404:
description: Contest does not exist
"""
try:
obj = Contest.objects.get(pk=cid)
if str(obj.owner.pk) != g.user_id:
return abort(403, "You aren't owner of the contest")
return jsonify(obj.to_json_admins()), 200
except (db.DoesNotExist, db.ValidationError):
return abort(404, "Contest does not exist")
@app.api_route('admin', methods=['GET'])
@paginate('contests', 20)
@auth.authenticate
def admin_contests():
"""
Get Admin Contests
---
tags:
- contest
parameters:
- name: page
in: query
type: integer
required: false
description: Page number
- name: per_page
in: query
type: integer
required: false
description: Contest amount per page (default is 10)
- name: Access-Token
in: header
type: string
required: true
description: Token of current user
responses:
200:
description: List of contests
schema:
$ref: "#/definitions/api_1_contest_list_owner_get_ContestsList"
401:
description: Token is invalid or has expired
"""
user_obj = User.objects.get(pk=g.user_id)
contests = Contest.objects.filter(admins=user_obj).order_by('-starts_at')
result_func = lambda obj: Contest.to_json(obj)
return contests, result_func
| k04la/ijust_server | project/controllers/api_1/contest.py | Python | gpl-3.0 | 51,483 |
#!/usr/bin/python
# Copyright (c) 2015 IBM Corporation
#
# This module is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This software is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this software. If not, see <http://www.gnu.org/licenses/>.
try:
import shade
HAS_SHADE = True
except ImportError:
HAS_SHADE = False
DOCUMENTATION = '''
---
module: os_project
short_description: Manage OpenStack Projects
extends_documentation_fragment: openstack
version_added: "2.0"
author: "Alberto Gireud (@agireud)"
description:
- Manage OpenStack Projects. Projects can be created,
updated or deleted using this module. A project will be updated
if I(name) matches an existing project and I(state) is present.
The value for I(name) cannot be updated without deleting and
re-creating the project.
options:
name:
description:
- Name for the project
required: true
description:
description:
- Description for the project
required: false
default: None
domain_id:
description:
- Domain id to create the project in if the cloud supports domains
required: false
default: None
aliases: ['domain']
enabled:
description:
- Is the project enabled
required: false
default: True
state:
description:
- Should the resource be present or absent.
choices: [present, absent]
default: present
requirements:
- "python >= 2.6"
- "shade"
'''
EXAMPLES = '''
# Create a project
- os_project:
cloud: mycloud
state: present
name: demoproject
description: demodescription
domain_id: demoid
enabled: True
# Delete a project
- os_project:
cloud: mycloud
state: absent
name: demoproject
'''
RETURN = '''
project:
description: Dictionary describing the project.
returned: On success when I(state) is 'present'
type: dictionary
contains:
id:
description: Project ID
type: string
sample: "f59382db809c43139982ca4189404650"
name:
description: Project name
type: string
sample: "demoproject"
description:
description: Project description
type: string
sample: "demodescription"
enabled:
description: Boolean to indicate if project is enabled
type: bool
sample: True
'''
def _needs_update(module, project):
keys = ('description', 'enabled')
for key in keys:
if module.params[key] is not None and module.params[key] != project.get(key):
return True
return False
def _system_state_change(module, project):
state = module.params['state']
if state == 'present':
if project is None:
changed = True
else:
if _needs_update(module, project):
changed = True
else:
changed = False
elif state == 'absent':
if project is None:
changed=False
else:
changed=True
return changed;
def main():
argument_spec = openstack_full_argument_spec(
name=dict(required=True),
description=dict(required=False, default=None),
domain_id=dict(required=False, default=None, aliases=['domain']),
enabled=dict(default=True, type='bool'),
state=dict(default='present', choices=['absent', 'present'])
)
module_kwargs = openstack_module_kwargs()
module = AnsibleModule(
argument_spec,
supports_check_mode=True,
**module_kwargs
)
if not HAS_SHADE:
module.fail_json(msg='shade is required for this module')
name = module.params['name']
description = module.params['description']
domain = module.params.pop('domain_id')
enabled = module.params['enabled']
state = module.params['state']
try:
if domain:
opcloud = shade.operator_cloud(**module.params)
try:
# We assume admin is passing domain id
dom = opcloud.get_domain(domain)['id']
domain = dom
except:
# If we fail, maybe admin is passing a domain name.
# Note that domains have unique names, just like id.
try:
dom = opcloud.search_domains(filters={'name': domain})[0]['id']
domain = dom
except:
# Ok, let's hope the user is non-admin and passing a sane id
pass
cloud = shade.openstack_cloud(**module.params)
project = cloud.get_project(name)
if module.check_mode:
module.exit_json(changed=_system_state_change(module, project))
if state == 'present':
if project is None:
project = cloud.create_project(
name=name, description=description,
domain_id=domain,
enabled=enabled)
changed = True
else:
if _needs_update(module, project):
project = cloud.update_project(
project['id'], description=description,
enabled=enabled)
changed = True
else:
changed = False
module.exit_json(changed=changed, project=project)
elif state == 'absent':
if project is None:
changed=False
else:
cloud.delete_project(project['id'])
changed=True
module.exit_json(changed=changed)
except shade.OpenStackCloudException as e:
module.fail_json(msg=e.message, extra_data=e.extra_data)
from ansible.module_utils.basic import *
from ansible.module_utils.openstack import *
if __name__ == '__main__':
main()
| StackPointCloud/ansible-modules-extras | cloud/openstack/os_project.py | Python | gpl-3.0 | 6,372 |
from openstates.utils import LXMLMixin
from billy.scrape.votes import VoteScraper, Vote
from billy.scrape.utils import convert_pdf
import datetime
import subprocess
import lxml
import os
import re
journals = "http://www.leg.state.co.us/CLICS/CLICS%s/csljournals.nsf/" \
"jouNav?Openform&%s"
date_re = re.compile(
r"(?i).*(?P<dt>(monday|tuesday|wednesday|thursday|friday|saturday|sunday)"
".*, \d{4}).*"
)
vote_re = re.compile((r"\s*"
"YES\s*(?P<yes_count>\d+)\s*"
"NO\s*(?P<no_count>\d+)\s*"
"EXCUSED\s*(?P<excused_count>\d+)\s*"
"ABSENT\s*(?P<abs_count>\d+).*"))
votes_re = r"(?P<name>\w+(\s\w\.)?)\s+(?P<vote>Y|N|A|E|-)"
def fix_typos(data):
return data.replace('Tueday', 'Tuesday') # Spelling is hard
class COVoteScraper(VoteScraper, LXMLMixin):
jurisdiction = 'co'
def scrape_house(self, session):
url = journals % (session, 'House')
page = self.lxmlize(url)
hrefs = page.xpath("//font//a")
for href in hrefs:
(path, response) = self.urlretrieve(href.attrib['href'])
data = convert_pdf(path, type='text')
data = fix_typos(data)
in_vote = False
cur_vote = {}
known_date = None
cur_vote_count = None
in_question = False
cur_question = None
cur_bill_id = None
for line in data.split("\n"):
if known_date is None:
dt = date_re.findall(line)
if dt != []:
dt, dow = dt[0]
known_date = datetime.datetime.strptime(dt,
"%A, %B %d, %Y")
non_std = False
if re.match("(\s+)?\d+.*", line) is None:
non_std = True
l = line.lower().strip()
skip = False
blacklist = [
"house",
"page",
"general assembly",
"state of colorado",
"session",
"legislative day"
]
for thing in blacklist:
if thing in l:
skip = True
if skip:
continue
found = re.findall(
"(?P<bill_id>(H|S|SJ|HJ)(B|M|R)\d{2}-\d{3,4})",
line
)
if found != []:
found = found[0]
cur_bill_id, chamber, typ = found
try:
if not non_std:
_, line = line.strip().split(" ", 1)
line = line.strip()
except ValueError:
in_vote = False
in_question = False
continue
if in_question:
cur_question += " " + line.strip()
continue
if ("The question being" in line) or \
("On motion of" in line) or \
("the following" in line) or \
("moved that the" in line):
cur_question = line.strip()
in_question = True
if in_vote:
if line == "":
likely_garbage = True
likely_garbage = False
if "co-sponsor" in line.lower():
likely_garbage = True
if 'the speaker' in line.lower():
likely_garbage = True
votes = re.findall(votes_re, line)
if likely_garbage:
votes = []
for person, _, v in votes:
cur_vote[person] = v
last_line = False
for who, _, vote in votes:
if who.lower() == "speaker":
last_line = True
if votes == [] or last_line:
in_vote = False
# save vote
yes, no, other = cur_vote_count
if cur_bill_id is None or cur_question is None:
continue
bc = {
"H": "lower",
"S": "upper",
"J": "joint"
}[cur_bill_id[0].upper()]
vote = Vote('lower',
known_date,
cur_question,
(yes > no),
yes,
no,
other,
session=session,
bill_id=cur_bill_id,
bill_chamber=bc)
vote.add_source(href.attrib['href'])
vote.add_source(url)
for person in cur_vote:
if not person:
continue
vot = cur_vote[person]
if person.endswith("Y"):
vot = "Y"
person = person[:-1]
if person.endswith("N"):
vot = "N"
person = person[:-1]
if person.endswith("E"):
vot = "E"
person = person[:-1]
if not person:
continue
if vot == 'Y':
vote.yes(person)
elif vot == 'N':
vote.no(person)
elif vot == 'E' or vot == '-':
vote.other(person)
self.save_vote(vote)
cur_vote = {}
in_question = False
cur_question = None
in_vote = False
cur_vote_count = None
continue
summ = vote_re.findall(line)
if summ == []:
continue
summ = summ[0]
yes, no, exc, ab = summ
yes, no, exc, ab = \
int(yes), int(no), int(exc), int(ab)
other = exc + ab
cur_vote_count = (yes, no, other)
in_vote = True
continue
os.unlink(path)
def scrape_senate(self, session):
url = journals % (session, 'Senate')
page = self.lxmlize(url)
hrefs = page.xpath("//font//a")
for href in hrefs:
(path, response) = self.urlretrieve(href.attrib['href'])
data = convert_pdf(path, type='text')
data = fix_typos(data)
cur_bill_id = None
cur_vote_count = None
in_vote = False
cur_question = None
in_question = False
known_date = None
cur_vote = {}
for line in data.split("\n"):
if not known_date:
dt = date_re.findall(line)
if dt != []:
dt, dow = dt[0]
dt = dt.replace(',', '')
known_date = datetime.datetime.strptime(dt, "%A %B %d %Y")
if in_question:
line = line.strip()
if re.match("\d+", line):
in_question = False
continue
try:
line, _ = line.rsplit(" ", 1)
cur_question += line.strip()
except ValueError:
in_question = False
continue
cur_question += line.strip()
if not in_vote:
summ = vote_re.findall(line)
if summ != []:
cur_vote = {}
cur_vote_count = summ[0]
in_vote = True
continue
if ("The question being" in line) or \
("On motion of" in line) or \
("the following" in line) or \
("moved that the" in line):
cur_question, _ = line.strip().rsplit(" ", 1)
cur_question = cur_question.strip()
in_question = True
if line.strip() == "":
continue
first = line[0]
if first != " ":
if " " not in line:
# wtf
continue
bill_id, kruft = line.split(" ", 1)
if len(bill_id) < 3:
continue
if bill_id[0] != "H" and bill_id[0] != "S":
continue
if bill_id[1] not in ['B', 'J', 'R', 'M']:
continue
cur_bill_id = bill_id
else:
line = line.strip()
try:
line, lineno = line.rsplit(" ", 1)
except ValueError:
in_vote = False
if cur_question is None:
continue
if cur_bill_id is None:
continue
yes, no, exc, ab = cur_vote_count
other = int(exc) + int(ab)
yes, no, other = int(yes), int(no), int(other)
bc = {'H': 'lower', 'S': 'upper'}[cur_bill_id[0]]
vote = Vote('upper',
known_date,
cur_question,
(yes > no),
yes,
no,
other,
session=session,
bill_id=cur_bill_id,
bill_chamber=bc)
for person in cur_vote:
if person is None:
continue
howvote = cur_vote[person]
if person.endswith("Y"):
howvote = "Y"
person = person[:-1]
if person.endswith("N"):
howvote = "N"
person = person[:-1]
if person.endswith("E"):
howvote = "E"
person = person[:-1]
howvote = howvote.upper()
if howvote == 'Y':
vote.yes(person)
elif howvote == 'N':
vote.no(person)
else:
vote.other(person)
vote.add_source(href.attrib['href'])
self.save_vote(vote)
cur_vote, cur_question, cur_vote_count = (
None, None, None)
continue
votes = re.findall(votes_re, line)
for person in votes:
name, li, vot = person
cur_vote[name] = vot
os.unlink(path)
def scrape(self, chamber, session):
if chamber == 'upper':
self.scrape_senate(session)
if chamber == 'lower':
self.scrape_house(session)
| cliftonmcintosh/openstates | openstates/co/votes.py | Python | gpl-3.0 | 12,425 |
from PyQt5 import QtCore
from src.business.configuration.constants import project as p
from src.ui.commons.verification import cb
class ConfigProject:
def __init__(self):
self._settings = QtCore.QSettings(p.CONFIG_FILE, QtCore.QSettings.IniFormat)
def get_value(self, menu, value):
return self._settings.value(menu + '/' + value)
def set_site_settings(self, name, site_id, imager_id):
self._settings.beginGroup(p.SITE_TITLE)
self._settings.setValue(p.NAME, name)
self._settings.setValue(p.SITE_ID, site_id)
self._settings.setValue(p.IMAGER_ID, imager_id)
self._settings.endGroup()
def set_geographic_settings(self, lat, long, elev, press, temp):
self._settings.beginGroup(p.GEOGRAPHIC_TITLE)
self._settings.setValue(p.LATITUDE, lat)
self._settings.setValue(p.LONGITUDE, long)
self._settings.setValue(p.ELEVATION, elev)
self._settings.setValue(p.PRESSURE, press)
self._settings.setValue(p.TEMPERATURE, temp)
self._settings.endGroup()
def set_moonsun_settings(self, solarelev, ignoreLunar, lunarph, lunarpos):
self._settings.beginGroup(p.SUN_MOON_TITLE)
self._settings.setValue(p.MAX_SOLAR_ELEVATION, solarelev)
self._settings.setValue(p.IGNORE_LUNAR_POSITION, ignoreLunar)
self._settings.setValue(p.MAX_LUNAR_PHASE, lunarph)
self._settings.setValue(p.MAX_LUNAR_ELEVATION, lunarpos)
self._settings.endGroup()
def save_settings(self):
self._settings.sync()
def get_site_settings(self):
return self.get_value(p.SITE_TITLE, p.NAME),\
self.get_value(p.SITE_TITLE, p.SITE_ID),\
self.get_value(p.SITE_TITLE, p.IMAGER_ID)
def get_geographic_settings(self):
m = p.GEOGRAPHIC_TITLE
return self.get_value(m, p.LATITUDE),\
self.get_value(m, p.LONGITUDE),\
self.get_value(m, p.ELEVATION),\
self.get_value(m, p.PRESSURE),\
self.get_value(m, p.TEMPERATURE)
def get_moonsun_settings(self):
m = p.SUN_MOON_TITLE
return self.get_value(m, p.MAX_SOLAR_ELEVATION),\
cb(self.get_value(m, p.IGNORE_LUNAR_POSITION)),\
self.get_value(m, p.MAX_LUNAR_PHASE),\
self.get_value(m, p.MAX_LUNAR_ELEVATION)
| pliniopereira/ccd10 | src/business/configuration/configProject.py | Python | gpl-3.0 | 2,363 |
import sys
import typing
import click
import glotaran as gta
from . import util
@click.option('--dataformat', '-dfmt', default=None,
type=click.Choice(gta.io.reader.known_reading_formats.keys()),
help='The input format of the data. Will be infered from extension if not set.')
@click.option('--data', '-d', multiple=True,
type=(str, click.Path(exists=True, dir_okay=False)),
help="Path to a dataset in the form '--data DATASET_LABEL PATH_TO_DATA'")
@click.option('--out', '-o', default=None, type=click.Path(file_okay=False),
help='Path to an output directory.', show_default=True)
@click.option('--nfev', '-n', default=None, type=click.IntRange(min=1),
help='Maximum number of function evaluations.', show_default=True)
@click.option('--nnls', is_flag=True,
help='Use non-negative least squares.')
@click.option('--yes', '-y', is_flag=True,
help="Don't ask for confirmation.")
@util.signature_analysis
def optimize_cmd(dataformat: str, data: typing.List[str], out: str, nfev: int, nnls: bool,
yes: bool, parameter: str, model: str, scheme: str):
"""Optimizes a model.
e.g.:
glotaran optimize --
"""
if scheme is not None:
scheme = util.load_scheme_file(scheme, verbose=True)
if nfev is not None:
scheme.nfev = nfev
else:
if model is None:
click.echo('Error: Neither scheme nor model specified', err=True)
sys.exit(1)
model = util.load_model_file(model, verbose=True)
if parameter is None:
click.echo('Error: Neither scheme nor parameter specified', err=True)
sys.exit(1)
parameter = util.load_parameter_file(parameter, verbose=True)
if len(data) == 0:
click.echo('Error: Neither scheme nor data specified', err=True)
sys.exit(1)
dataset_files = {arg[0]: arg[1] for arg in data}
datasets = {}
for label in model.dataset:
if label not in dataset_files:
click.echo(f"Missing dataset for '{label}'", err=True)
sys.exit(1)
path = dataset_files[label]
datasets[label] = util.load_dataset_file(path, fmt=dataformat, verbose=True)
scheme = gta.analysis.scheme.Scheme(model=model, parameter=parameter, data=datasets,
nnls=nnls, nfev=nfev)
click.echo(scheme.validate())
click.echo(f"Use NNLS: {scheme.nnls}")
click.echo(f"Max Nr Function Evaluations: {scheme.nfev}")
click.echo(f"Saving directory: is '{out if out is not None else 'None'}'")
if yes or click.confirm('Do you want to start optimization?', abort=True, default=True):
# try:
# click.echo('Preparing optimization...', nl=False)
# optimizer = gta.analysis.optimizer.Optimizer(scheme)
# click.echo(' Success')
# except Exception as e:
# click.echo(" Error")
# click.echo(e, err=True)
# sys.exit(1)
try:
click.echo('Optimizing...')
result = gta.analysis.optimize.optimize(scheme)
click.echo('Optimization done.')
click.echo(result.markdown(with_model=False))
click.echo('Optimized Parameter:')
click.echo(result.optimized_parameter.markdown())
except Exception as e:
click.echo(f"An error occured during optimization: \n\n{e}", err=True)
sys.exit(1)
if out is not None:
try:
click.echo(f"Saving directory is '{out}'")
if yes or click.confirm('Do you want to save the data?', default=True):
paths = result.save(out)
click.echo(f"File saving successfull, the follwing files have been written:\n")
for p in paths:
click.echo(f"* {p}")
except Exception as e:
click.echo(f"An error occured during optimization: \n\n{e}", err=True)
sys.exit(1)
click.echo('All done, have a nice day!')
| glotaran/glotaran | glotaran/cli/commands/optimize.py | Python | gpl-3.0 | 4,194 |
#-------------------------------------------------------------------------
#
# Copyright (c) 2009, IMB, RWTH Aachen.
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in simvisage/LICENSE.txt and may be redistributed only
# under the conditions described in the aforementioned license. The license
# is also available online at http://www.simvisage.com/licenses/BSD.txt
#
# Thanks for using Simvisage open source!
#
# Created on Nov 18, 2011 by: matthias
from traits.api import \
provides
from oricreate.opt import \
IFu
from .fu import \
Fu
@provides(IFu)
class FuPotEngBending(Fu):
'''Optimization criteria based on minimum Bending energy of gravity.
This plug-in class lets the crease pattern operators evaluate the
integral over the spatial domain in an instantaneous configuration
'''
def get_f(self, t=0):
'''Get the bending energy of gravity.
'''
return self.forming_task.formed_object.V
def get_f_du(self, t=0):
'''Get the derivatives with respect to individual displacements.
'''
return self.forming_task.formed_object.V_du
| simvisage/oricreate | oricreate/fu/fu_poteng_bending.py | Python | gpl-3.0 | 1,193 |
# generated from catkin/cmake/template/pkg.context.pc.in
CATKIN_PACKAGE_PREFIX = ""
PROJECT_PKG_CONFIG_INCLUDE_DIRS = "/home/jorge/tum_simulator_ws/install/include".split(';') if "/home/jorge/tum_simulator_ws/install/include" != "" else []
PROJECT_CATKIN_DEPENDS = "message_runtime".replace(';', ' ')
PKG_CONFIG_LIBRARIES_WITH_PREFIX = "".split(';') if "" != "" else []
PROJECT_NAME = "cvg_sim_msgs"
PROJECT_SPACE_DIR = "/home/jorge/tum_simulator_ws/install"
PROJECT_VERSION = "0.0.0"
| aslab/rct | mrt/src/tum_simulator_ws/build/tum_simulator-master/cvg_sim_msgs/catkin_generated/pkg.installspace.context.pc.py | Python | gpl-3.0 | 485 |
from src import model as mdl
class LaTeXPrinter(object):
def __init__(self, target_file_path):
self._target_file_path = target_file_path
def run(self):
with open(self._target_file_path, 'w') as output:
text = self._generate_text()
output.write(text)
def _generate_text(self):
raise NotImplementedError('Override me!')
class TablePrinter(LaTeXPrinter):
def __init__(self, target_file_path):
super(TablePrinter, self).__init__(target_file_path)
def _generate_text(self):
text = '\\rowcolors{3}{aubergine}{white}\n'
text += self._get_table_definition()
text += '\\toprule\n'
text += self._get_headers()
text += '\\midrule\n\\endhead\n'
for element in self._get_content():
text += ' & '.join(element) + '\\\\\n'
text += '\\bottomrule\n'
caption, label = self._get_caption_and_label()
text += ('\\rowcolor{white}' + '\\caption{' + caption +
'}\\label{' + label + '}\n')
text += '\\end{longtable}\n'
return text
def _get_table_definition(self):
raise NotImplementedError('Override me!')
def _get_headers(self):
raise NotImplementedError('Override me!')
def _get_content(self):
"""Returns an iterable of 3-tuples with the ID, the description and the
parent of the item that needs to be printed.
"""
raise NotImplementedError('Override me!')
def _get_caption_and_label(self):
"""Returns the caption and label of the table to print.
"""
raise NotImplementedError('Override me!')
class UseCaseTablePrinter(TablePrinter):
def __init__(self, target_file_path):
super(UseCaseTablePrinter, self).__init__(target_file_path)
self._uc_id_list = mdl.dal.get_all_use_case_ids()
def _get_table_definition(self):
return '\\begin{longtable}{lp{.5\\textwidth}l}\n'
def _get_headers(self):
return ('\\sffamily\\bfseries ID & \\sffamily\\bfseries Descrizione '
'& \\sffamily\\bfseries Padre\\\n')
def _get_content(self):
"""Returns an iterable (generator) containing a 3-tuple with the
ID, description and parent of every use case.
"""
for uc_id in self._uc_id_list:
uc = mdl.dal.get_use_case(uc_id)
yield (uc.uc_id, uc.description, uc.parent_id or '--')
def _get_caption_and_label(self):
return ('Prospetto riepilogativo dei casi d\'uso', 'tab:uclist')
class RequirementTablePrinter(TablePrinter):
def __init__(self, req_type, priority, target_file_path):
super(RequirementTablePrinter, self).__init__(target_file_path)
self._req_type = req_type
self._priority = priority
self._req_id_list = mdl.dal.get_all_requirement_ids_spec(
req_type, priority)
def _get_table_definition(self):
return '\\begin{longtable}{lp{.5\\textwidth}ll}\n'
def _get_headers(self):
return ('\\sffamily\\bfseries ID & \\sffamily\\bfseries Descrizione & '
'\\sffamily\\bfseries Fonte & '
'\\sffamily\\bfseries Padre\\\\\n')
def _get_content(self):
for req_id in self._req_id_list:
req = mdl.dal.get_requirement(req_id)
source = mdl.dal.get_source(req.source_id)
yield (req.req_id, req.description, source.name,
req.parent_id or '--')
def _get_caption_and_label(self):
return ('Elenco dei requisiti {0} {1}.'.format(
('funzionali' if self._req_type == 'F' else
'dichiarativi' if self._req_type == 'D' else
'prestazionali' if self._req_type == 'P' else 'qualitativi'),
('obbligatori' if self._priority == 'O' else
'facoltativi' if self._priority == 'F' else 'desiderabili')),
'tab:reqlist{0}{1}'.format(self._req_type, self._priority))
class UseCaseRequirementTrackPrinter(TablePrinter):
def __init__(self, target_file_path):
super(UseCaseRequirementTrackPrinter, self).__init__(target_file_path)
self._uc_id_list = mdl.dal.get_all_use_case_ids()
def _get_table_definition(self):
return '\\begin{longtable}{lp{.8\textwidth}}\n'
def _get_headers(self):
return ('\\sffamily\\bfseries Caso d\'uso & '
'\\sffamily\\bfseries Requisiti associati\\\\\n')
def _get_content(self):
for uc_id in self._uc_id_list:
req_ids = mdl.dal.get_use_case_associated_requirements(uc_id)
yield (uc_id, ', '.join(req_ids))
def _get_caption_and_label(self):
return ('Tracciamento requisiti -- casi d\'uso.', 'tab:ucreqtrack')
| diegoberaldin/PyRequirementManager | src/controller/printers.py | Python | gpl-3.0 | 4,793 |
#!/usr/bin/env python3
# Copyright (C) 2013 LiuLang <gsushzhsosgsu@gmail.com>
# Use of this source code is governed by GPLv3 license that can be found
# in the LICENSE file.
from distutils.core import setup
from distutils.core import Command
from distutils.command.clean import clean as distutils_clean
from distutils.command.sdist import sdist as distutils_sdist
import glob
import os
import shutil
from qr_gui import Config
def build_data_files():
data_files = []
for dir, dirs, files in os.walk('share'):
#target = os.path.join('share', dir)
target = dir
if files:
files = [os.path.join(dir, f) for f in files]
data_files.append((target, files))
return data_files
# will be installed to /usr/local/bin
scripts = ['qr-gui', ]
if __name__ == '__main__':
setup(
name = 'qr-gui',
description = Config.DESCRIPTION,
version = Config.VERSION,
license = 'GPLv3',
url = Config.HOMEPAGE,
author = 'LiuLang',
author_email = 'gsushzhsosgsu@gmail.com',
packages = ['qr_gui', ],
scripts = scripts,
data_files = build_data_files(),
)
| toby20130333/qr-gui | setup.py | Python | gpl-3.0 | 1,183 |
# Copyright (C) 2016
# Jakub Krajniak (jkrajniak at gmail.com)
#
# This file is part of ChemLab
#
# ESPResSo++ is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ESPResSo++ is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
import unittest
import sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
import chemlab.gromacs_topology
class TestTopologyReader(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.topol_file = 'topol.top'
cls.gt = chemlab.gromacs_topology.GromacsTopology(cls.topol_file, generate_exclusions=True)
cls.gt.read()
def test_replicated_molecules(self):
"""Test the molecule replication"""
total_nr_atoms = len(self.gt.atoms)
expected_nr_atoms = 0
for mol_name, nmols in self.gt.gt.molecules:
mol_atoms = len(self.gt.gt.molecules_data[mol_name]['atoms'])
expected_nr_atoms += nmols * mol_atoms
self.assertEqual(total_nr_atoms, expected_nr_atoms)
total_nr_bonds = len(self.gt.bonds)
expected_nr_bonds = 0
for mol_name, nmols in self.gt.gt.molecules:
mol_bonds = len(self.gt.gt.molecules_data[mol_name].get('bonds', []))
expected_nr_bonds += nmols * mol_bonds
self.assertEqual(total_nr_bonds, expected_nr_bonds)
total_nr_angles = len(self.gt.angles)
expected_nr_angles = 0
for mol_name, nmols in self.gt.gt.molecules:
mol_angles = len(self.gt.gt.molecules_data[mol_name].get('angles', []))
expected_nr_angles += nmols * mol_angles
self.assertEqual(total_nr_angles, expected_nr_angles)
total_nr_dihedrals = len(self.gt.dihedrals)
expected_nr_dihedrals = 0
for mol_name, nmols in self.gt.gt.molecules:
mol_dihedrals = len(self.gt.gt.molecules_data[mol_name].get('dihedrals',[]))
expected_nr_dihedrals += nmols * mol_dihedrals
self.assertEqual(total_nr_dihedrals, expected_nr_dihedrals)
total_nr_pairs = len(self.gt.pairs)
expected_nr_pairs = 0
for mol_name, nmols in self.gt.gt.molecules:
mol_pairs = len(self.gt.gt.molecules_data[mol_name].get('pairs', []))
expected_nr_pairs += nmols * mol_pairs
self.assertEqual(total_nr_pairs, expected_nr_pairs)
if __name__ == '__main__':
unittest.main()
| cgchemlab/chemlab | src/tests/test_topology_reader.py | Python | gpl-3.0 | 2,938 |
"""
OpenSfM related utils
"""
import os, shutil, sys, json, argparse
import yaml
from opendm import io
from opendm import log
from opendm import system
from opendm import context
from opendm import camera
from opendm.utils import get_depthmap_resolution
from opendm.photo import find_largest_photo_dim
from opensfm.large import metadataset
from opensfm.large import tools
from opensfm.actions import undistort
from opensfm.dataset import DataSet
from opendm.multispectral import get_photos_by_band
class OSFMContext:
def __init__(self, opensfm_project_path):
self.opensfm_project_path = opensfm_project_path
def run(self, command):
system.run('%s/bin/opensfm %s "%s"' %
(context.opensfm_path, command, self.opensfm_project_path))
def is_reconstruction_done(self):
tracks_file = os.path.join(self.opensfm_project_path, 'tracks.csv')
reconstruction_file = os.path.join(self.opensfm_project_path, 'reconstruction.json')
return io.file_exists(tracks_file) and io.file_exists(reconstruction_file)
def reconstruct(self, rerun=False):
tracks_file = os.path.join(self.opensfm_project_path, 'tracks.csv')
reconstruction_file = os.path.join(self.opensfm_project_path, 'reconstruction.json')
if not io.file_exists(tracks_file) or rerun:
self.run('create_tracks')
else:
log.ODM_WARNING('Found a valid OpenSfM tracks file in: %s' % tracks_file)
if not io.file_exists(reconstruction_file) or rerun:
self.run('reconstruct')
else:
log.ODM_WARNING('Found a valid OpenSfM reconstruction file in: %s' % reconstruction_file)
# Check that a reconstruction file has been created
if not self.reconstructed():
log.ODM_ERROR("The program could not process this dataset using the current settings. "
"Check that the images have enough overlap, "
"that there are enough recognizable features "
"and that the images are in focus. "
"You could also try to increase the --min-num-features parameter."
"The program will now exit.")
exit(1)
def setup(self, args, images_path, reconstruction, append_config = [], rerun=False):
"""
Setup a OpenSfM project
"""
if rerun and io.dir_exists(self.opensfm_project_path):
shutil.rmtree(self.opensfm_project_path)
if not io.dir_exists(self.opensfm_project_path):
system.mkdir_p(self.opensfm_project_path)
list_path = os.path.join(self.opensfm_project_path, 'image_list.txt')
if not io.file_exists(list_path) or rerun:
if reconstruction.multi_camera:
photos = get_photos_by_band(reconstruction.multi_camera, args.primary_band)
if len(photos) < 1:
raise Exception("Not enough images in selected band %s" % args.primary_band.lower())
log.ODM_INFO("Reconstruction will use %s images from %s band" % (len(photos), args.primary_band.lower()))
else:
photos = reconstruction.photos
# create file list
has_alt = True
has_gps = False
with open(list_path, 'w') as fout:
for photo in photos:
if not photo.altitude:
has_alt = False
if photo.latitude is not None and photo.longitude is not None:
has_gps = True
fout.write('%s\n' % os.path.join(images_path, photo.filename))
# check for image_groups.txt (split-merge)
image_groups_file = os.path.join(args.project_path, "image_groups.txt")
if io.file_exists(image_groups_file):
log.ODM_INFO("Copied image_groups.txt to OpenSfM directory")
io.copy(image_groups_file, os.path.join(self.opensfm_project_path, "image_groups.txt"))
# check for cameras
if args.cameras:
try:
camera_overrides = camera.get_opensfm_camera_models(args.cameras)
with open(os.path.join(self.opensfm_project_path, "camera_models_overrides.json"), 'w') as f:
f.write(json.dumps(camera_overrides))
log.ODM_INFO("Wrote camera_models_overrides.json to OpenSfM directory")
except Exception as e:
log.ODM_WARNING("Cannot set camera_models_overrides.json: %s" % str(e))
use_bow = args.matcher_type == "bow"
feature_type = "SIFT"
# GPSDOP override if we have GPS accuracy information (such as RTK)
if 'gps_accuracy_is_set' in args:
log.ODM_INFO("Forcing GPS DOP to %s for all images" % args.gps_accuracy)
log.ODM_INFO("Writing exif overrides")
exif_overrides = {}
for p in photos:
if 'gps_accuracy_is_set' in args:
dop = args.gps_accuracy
elif p.get_gps_dop() is not None:
dop = p.get_gps_dop()
else:
dop = args.gps_accuracy # default value
if p.latitude is not None and p.longitude is not None:
exif_overrides[p.filename] = {
'gps': {
'latitude': p.latitude,
'longitude': p.longitude,
'altitude': p.altitude if p.altitude is not None else 0,
'dop': dop,
}
}
with open(os.path.join(self.opensfm_project_path, "exif_overrides.json"), 'w') as f:
f.write(json.dumps(exif_overrides))
# Check image masks
masks = []
for p in photos:
if p.mask is not None:
masks.append((p.filename, os.path.join(images_path, p.mask)))
if masks:
log.ODM_INFO("Found %s image masks" % len(masks))
with open(os.path.join(self.opensfm_project_path, "mask_list.txt"), 'w') as f:
for fname, mask in masks:
f.write("{} {}\n".format(fname, mask))
# Compute feature_process_size
feature_process_size = 2048 # default
if 'resize_to_is_set' in args:
# Legacy
log.ODM_WARNING("Legacy option --resize-to (this might be removed in a future version). Use --feature-quality instead.")
feature_process_size = int(args.resize_to)
else:
feature_quality_scale = {
'ultra': 1,
'high': 0.5,
'medium': 0.25,
'low': 0.125,
'lowest': 0.0675,
}
max_dim = find_largest_photo_dim(photos)
if max_dim > 0:
log.ODM_INFO("Maximum photo dimensions: %spx" % str(max_dim))
feature_process_size = int(max_dim * feature_quality_scale[args.feature_quality])
else:
log.ODM_WARNING("Cannot compute max image dimensions, going with defaults")
depthmap_resolution = get_depthmap_resolution(args, photos)
# create config file for OpenSfM
config = [
"use_exif_size: no",
"flann_algorithm: KDTREE", # more stable, faster than KMEANS
"feature_process_size: %s" % feature_process_size,
"feature_min_frames: %s" % args.min_num_features,
"processes: %s" % args.max_concurrency,
"matching_gps_neighbors: %s" % args.matcher_neighbors,
"matching_gps_distance: %s" % args.matcher_distance,
"depthmap_method: %s" % args.opensfm_depthmap_method,
"depthmap_resolution: %s" % depthmap_resolution,
"depthmap_min_patch_sd: %s" % args.opensfm_depthmap_min_patch_sd,
"depthmap_min_consistent_views: %s" % args.opensfm_depthmap_min_consistent_views,
"optimize_camera_parameters: %s" % ('no' if args.use_fixed_camera_params or args.cameras else 'yes'),
"undistorted_image_format: tif",
"bundle_outlier_filtering_type: AUTO",
"align_orientation_prior: vertical",
"triangulation_type: ROBUST"
]
if args.camera_lens != 'auto':
config.append("camera_projection_type: %s" % args.camera_lens.upper())
if not has_gps:
log.ODM_INFO("No GPS information, using BOW matching")
use_bow = True
feature_type = args.feature_type.upper()
if use_bow:
config.append("matcher_type: WORDS")
# Cannot use SIFT with BOW
if feature_type == "SIFT":
log.ODM_WARNING("Using BOW matching, will use HAHOG feature type, not SIFT")
feature_type = "HAHOG"
config.append("feature_type: %s" % feature_type)
if has_alt:
log.ODM_INFO("Altitude data detected, enabling it for GPS alignment")
config.append("use_altitude_tag: yes")
gcp_path = reconstruction.gcp.gcp_path
if has_alt or gcp_path:
config.append("align_method: auto")
else:
config.append("align_method: orientation_prior")
if args.use_hybrid_bundle_adjustment:
log.ODM_INFO("Enabling hybrid bundle adjustment")
config.append("bundle_interval: 100") # Bundle after adding 'bundle_interval' cameras
config.append("bundle_new_points_ratio: 1.2") # Bundle when (new points) / (bundled points) > bundle_new_points_ratio
config.append("local_bundle_radius: 1") # Max image graph distance for images to be included in local bundle adjustment
else:
config.append("local_bundle_radius: 0")
if gcp_path:
config.append("bundle_use_gcp: yes")
if not args.force_gps:
config.append("bundle_use_gps: no")
io.copy(gcp_path, self.path("gcp_list.txt"))
config = config + append_config
# write config file
log.ODM_INFO(config)
config_filename = self.get_config_file_path()
with open(config_filename, 'w') as fout:
fout.write("\n".join(config))
else:
log.ODM_WARNING("%s already exists, not rerunning OpenSfM setup" % list_path)
def get_config_file_path(self):
return os.path.join(self.opensfm_project_path, 'config.yaml')
def reconstructed(self):
if not io.file_exists(self.path("reconstruction.json")):
return False
with open(self.path("reconstruction.json"), 'r') as f:
return f.readline().strip() != "[]"
def extract_metadata(self, rerun=False):
metadata_dir = self.path("exif")
if not io.dir_exists(metadata_dir) or rerun:
self.run('extract_metadata')
def is_feature_matching_done(self):
features_dir = self.path("features")
matches_dir = self.path("matches")
return io.dir_exists(features_dir) and io.dir_exists(matches_dir)
def feature_matching(self, rerun=False):
features_dir = self.path("features")
matches_dir = self.path("matches")
if not io.dir_exists(features_dir) or rerun:
self.run('detect_features')
else:
log.ODM_WARNING('Detect features already done: %s exists' % features_dir)
if not io.dir_exists(matches_dir) or rerun:
self.run('match_features')
else:
log.ODM_WARNING('Match features already done: %s exists' % matches_dir)
def align_reconstructions(self, rerun):
alignment_file = self.path('alignment_done.txt')
if not io.file_exists(alignment_file) or rerun:
log.ODM_INFO("Aligning submodels...")
meta_data = metadataset.MetaDataSet(self.opensfm_project_path)
reconstruction_shots = tools.load_reconstruction_shots(meta_data)
transformations = tools.align_reconstructions(reconstruction_shots,
tools.partial_reconstruction_name,
True)
tools.apply_transformations(transformations)
self.touch(alignment_file)
else:
log.ODM_WARNING('Found a alignment done progress file in: %s' % alignment_file)
def touch(self, file):
with open(file, 'w') as fout:
fout.write("Done!\n")
def path(self, *paths):
return os.path.join(self.opensfm_project_path, *paths)
def extract_cameras(self, output, rerun=False):
if not os.path.exists(output) or rerun:
try:
reconstruction_file = self.path("reconstruction.json")
with open(output, 'w') as fout:
fout.write(json.dumps(camera.get_cameras_from_opensfm(reconstruction_file), indent=4))
except Exception as e:
log.ODM_WARNING("Cannot export cameras to %s. %s." % (output, str(e)))
else:
log.ODM_INFO("Already extracted cameras")
def convert_and_undistort(self, rerun=False, imageFilter=None, image_list=None, runId="nominal"):
log.ODM_INFO("Undistorting %s ..." % self.opensfm_project_path)
done_flag_file = self.path("undistorted", "%s_done.txt" % runId)
if not io.file_exists(done_flag_file) or rerun:
ds = DataSet(self.opensfm_project_path)
if image_list is not None:
ds._set_image_list(image_list)
undistort.run_dataset(ds, "reconstruction.json",
0, None, "undistorted", imageFilter)
self.touch(done_flag_file)
else:
log.ODM_WARNING("Already undistorted (%s)" % runId)
def restore_reconstruction_backup(self):
if os.path.exists(self.recon_backup_file()):
# This time export the actual reconstruction.json
# (containing only the primary band)
if os.path.exists(self.recon_file()):
os.remove(self.recon_file())
os.rename(self.recon_backup_file(), self.recon_file())
log.ODM_INFO("Restored reconstruction.json")
def backup_reconstruction(self):
if os.path.exists(self.recon_backup_file()):
os.remove(self.recon_backup_file())
log.ODM_INFO("Backing up reconstruction")
shutil.copyfile(self.recon_file(), self.recon_backup_file())
def recon_backup_file(self):
return self.path("reconstruction.backup.json")
def recon_file(self):
return self.path("reconstruction.json")
def add_shots_to_reconstruction(self, p2s):
with open(self.recon_file()) as f:
reconstruction = json.loads(f.read())
# Augment reconstruction.json
for recon in reconstruction:
shots = recon['shots']
sids = list(shots)
for shot_id in sids:
secondary_photos = p2s.get(shot_id)
if secondary_photos is None:
log.ODM_WARNING("Cannot find secondary photos for %s" % shot_id)
continue
for p in secondary_photos:
shots[p.filename] = shots[shot_id]
with open(self.recon_file(), 'w') as f:
f.write(json.dumps(reconstruction))
def update_config(self, cfg_dict):
cfg_file = self.get_config_file_path()
log.ODM_INFO("Updating %s" % cfg_file)
if os.path.exists(cfg_file):
try:
with open(cfg_file) as fin:
cfg = yaml.safe_load(fin)
for k, v in cfg_dict.items():
cfg[k] = v
log.ODM_INFO("%s: %s" % (k, v))
with open(cfg_file, 'w') as fout:
fout.write(yaml.dump(cfg, default_flow_style=False))
except Exception as e:
log.ODM_WARNING("Cannot update configuration file %s: %s" % (cfg_file, str(e)))
else:
log.ODM_WARNING("Tried to update configuration, but %s does not exist." % cfg_file)
def name(self):
return os.path.basename(os.path.abspath(self.path("..")))
def get_submodel_argv(args, submodels_path = None, submodel_name = None):
"""
Gets argv for a submodel starting from the args passed to the application startup.
Additionally, if project_name, submodels_path and submodel_name are passed, the function
handles the <project name> value and --project-path detection / override.
When all arguments are set to None, --project-path and project name are always removed.
:return the same as argv, but removing references to --split,
setting/replacing --project-path and name
removing --rerun-from, --rerun, --rerun-all, --sm-cluster
removing --pc-las, --pc-csv, --pc-ept, --tiles flags (processing these is wasteful)
adding --orthophoto-cutline
adding --dem-euclidean-map
adding --skip-3dmodel (split-merge does not support 3D model merging)
tweaking --crop if necessary (DEM merging makes assumption about the area of DEMs and their euclidean maps that require cropping. If cropping is skipped, this leads to errors.)
removing --gcp (the GCP path if specified is always "gcp_list.txt")
reading the contents of --cameras
"""
assure_always = ['orthophoto_cutline', 'dem_euclidean_map', 'skip_3dmodel']
remove_always = ['split', 'split_overlap', 'rerun_from', 'rerun', 'gcp', 'end_with', 'sm_cluster', 'rerun_all', 'pc_csv', 'pc_las', 'pc_ept', 'tiles']
read_json_always = ['cameras']
argv = sys.argv
result = [argv[0]] # Startup script (/path/to/run.py)
args_dict = vars(args).copy()
set_keys = [k[:-len("_is_set")] for k in args_dict.keys() if k.endswith("_is_set")]
# Handle project name and project path (special case)
if "name" in set_keys:
del args_dict["name"]
set_keys.remove("name")
if "project_path" in set_keys:
del args_dict["project_path"]
set_keys.remove("project_path")
# Remove parameters
set_keys = [k for k in set_keys if k not in remove_always]
# Assure parameters
for k in assure_always:
if not k in set_keys:
set_keys.append(k)
args_dict[k] = True
# Read JSON always
for k in read_json_always:
if k in set_keys:
try:
if isinstance(args_dict[k], str):
args_dict[k] = io.path_or_json_string_to_dict(args_dict[k])
if isinstance(args_dict[k], dict):
args_dict[k] = json.dumps(args_dict[k])
except ValueError as e:
log.ODM_WARNING("Cannot parse/read JSON: {}".format(str(e)))
# Handle crop (cannot be zero for split/merge)
if "crop" in set_keys:
crop_value = float(args_dict["crop"])
if crop_value == 0:
crop_value = 0.015625
args_dict["crop"] = crop_value
# Populate result
for k in set_keys:
result.append("--%s" % k.replace("_", "-"))
# No second value for booleans
if isinstance(args_dict[k], bool) and args_dict[k] == True:
continue
result.append(str(args_dict[k]))
if submodels_path:
result.append("--project-path")
result.append(submodels_path)
if submodel_name:
result.append(submodel_name)
return result
def get_submodel_args_dict(args):
submodel_argv = get_submodel_argv(args)
result = {}
i = 0
while i < len(submodel_argv):
arg = submodel_argv[i]
next_arg = None if i == len(submodel_argv) - 1 else submodel_argv[i + 1]
if next_arg and arg.startswith("--"):
if next_arg.startswith("--"):
result[arg[2:]] = True
else:
result[arg[2:]] = next_arg
i += 1
elif arg.startswith("--"):
result[arg[2:]] = True
i += 1
return result
def get_submodel_paths(submodels_path, *paths):
"""
:return Existing paths for all submodels
"""
result = []
if not os.path.exists(submodels_path):
return result
for f in os.listdir(submodels_path):
if f.startswith('submodel'):
p = os.path.join(submodels_path, f, *paths)
if os.path.exists(p):
result.append(p)
else:
log.ODM_WARNING("Missing %s from submodel %s" % (p, f))
return result
def get_all_submodel_paths(submodels_path, *all_paths):
"""
:return Existing, multiple paths for all submodels as a nested list (all or nothing for each submodel)
if a single file is missing from the submodule, no files are returned for that submodel.
(i.e. get_multi_submodel_paths("path/", "odm_orthophoto.tif", "dem.tif")) -->
[["path/submodel_0000/odm_orthophoto.tif", "path/submodel_0000/dem.tif"],
["path/submodel_0001/odm_orthophoto.tif", "path/submodel_0001/dem.tif"]]
"""
result = []
if not os.path.exists(submodels_path):
return result
for f in os.listdir(submodels_path):
if f.startswith('submodel'):
all_found = True
for ap in all_paths:
p = os.path.join(submodels_path, f, ap)
if not os.path.exists(p):
log.ODM_WARNING("Missing %s from submodel %s" % (p, f))
all_found = False
if all_found:
result.append([os.path.join(submodels_path, f, ap) for ap in all_paths])
return result | OpenDroneMap/OpenDroneMap | opendm/osfm.py | Python | gpl-3.0 | 22,421 |
def search(L, e):
def bSearch(L, e, low, high):
if high == low:
return L[low] == e
mid = (low + high) // 2
if L[mid] == e:
return True
elif L[mid] > e:
if low == mid:
return False
else:
return bSearch(L, e, low, mid - 1)
else:
return bSearch(L, e, mid + 1, high)
if len(L) == 0:
return False
else:
return bSearch(L, e, 0, len(L) - 1)
L = [1, 2, 5, 3, 6, 7, 9, 10]
search(L, 8)
| Rjerk/snippets | python/ICPUP/二分查找.py | Python | gpl-3.0 | 540 |
# vim: tabstop=4 expandtab shiftwidth=4 autoindent
import INN
import datetime
import logging
import logging.handlers
import os
import os.path
import re
import shelve
import sys
import time
import traceback
# In Python2.4, utils was called Utils
try:
from email.utils import parseaddr
except ImportError:
from email.Utils import parseaddr
# Python 2.4 doesn't have hashlib
try:
from hashlib import md5
except ImportError:
from md5 import md5
try:
import configparser
except ImportError:
import ConfigParser
configparser=ConfigParser
try:
from sys import intern
except ImportError:
pass
# First, define some high-level date/time functions
def now():
return datetime.datetime.utcnow()
# return datetime.datetime.now()
def timestamp(stamp):
return stamp.strftime("%Y-%m-%d %H:%M:%S")
def dateobj(datestr):
"""Take a string formated date (yyyymmdd) and return a datetime object."""
# Python 2.4 compatibility
return datetime.datetime(*(time.strptime(datestr, '%Y%m%d')[0:6]))
# return datetime.datetime.strptime(datestr, '%Y%m%d')
def nowstamp():
"""A shortcut function to return a textual representation of now."""
return timestamp(now())
def last_midnight():
return now().replace(hour=0, minute=0, second=0, microsecond=0)
def next_midnight():
"""Return a datetime object relating to the next midnight.
"""
return last_midnight() + datetime.timedelta(days=1)
def future(days=0, hours=0, mins=0, secs=0):
return now() + datetime.timedelta(days=days, hours=hours,
minutes=mins, seconds=secs)
# -----This section is concerned with setting up a default configuration
def makedir(d):
"""Check if a given directory exists. If it doesn't, check if the
parent exists. If it does then the new directory will be created. If
not then sensible options are exhausted and the program aborts.
"""
if not os.path.isdir(d):
parent = os.path.dirname(d)
if os.path.isdir(parent):
os.mkdir(d, 0o700)
sys.stdout.write("%s: Directory created.\n" % d)
else:
msg = "%s: Unable to make directory. Aborting.\n" % d
sys.stdout.write(msg)
sys.exit(1)
def init_config():
# Configure the Config Parser.
config = configparser.RawConfigParser()
# Logging
config.add_section('logging')
config.set('logging', 'level', 'info')
config.set('logging',
'format', '%(asctime)s %(levelname)s %(message)s')
config.set('logging', 'datefmt', '%Y-%m-%d %H:%M:%S')
config.set('logging', 'retain', 7)
config.set('logging', 'logart_maxlines', 20)
# Binary
config.add_section('binary')
config.set('binary', 'lines_allowed', 15)
config.set('binary', 'allow_pgp', 'true')
config.set('binary', 'reject_suspected', 'false')
config.set('binary', 'fasttrack_references', 'true')
# EMP
config.add_section('emp')
config.set('emp', 'ph_coarse', 'true')
config.set('emp', 'body_threshold', 5)
config.set('emp', 'body_ceiling', 85)
config.set('emp', 'body_maxentries', 5000)
config.set('emp', 'body_timed_trim', 3600)
config.set('emp', 'body_fuzzy', 'true')
config.set('emp', 'phn_threshold', 100)
config.set('emp', 'phn_ceiling', 150)
config.set('emp', 'phn_maxentries', 5000)
config.set('emp', 'phn_timed_trim', 1800)
config.set('emp', 'lphn_threshold', 20)
config.set('emp', 'lphn_ceiling', 30)
config.set('emp', 'lphn_maxentries', 200)
config.set('emp', 'lphn_timed_trim', 1800)
config.set('emp', 'phl_threshold', 20)
config.set('emp', 'phl_ceiling', 80)
config.set('emp', 'phl_maxentries', 5000)
config.set('emp', 'phl_timed_trim', 3600)
config.set('emp', 'fsl_threshold', 20)
config.set('emp', 'fsl_ceiling', 40)
config.set('emp', 'fsl_maxentries', 5000)
config.set('emp', 'fsl_timed_trim', 3600)
config.set('emp', 'ihn_threshold', 10)
config.set('emp', 'ihn_ceiling', 15)
config.set('emp', 'ihn_maxentries', 1000)
config.set('emp', 'ihn_timed_trim', 7200)
config.add_section('groups')
config.set('groups', 'max_crosspost', 10)
config.set('groups', 'max_low_crosspost', 3)
config.add_section('control')
config.set('control', 'reject_cancels', 'false')
config.set('control', 'reject_redundant', 'true')
config.add_section('filters')
config.set('filters', 'newsguy', 'true')
config.set('filters', 'reject_html', 'true')
config.set('filters', 'reject_multipart', 'false')
config.add_section('hostnames')
config.set('hostnames', 'path_hostname', 'true')
# The path section is a bit tricky. First off we try to read a default
# config file. This can define the path to everything, including the
# pyclean.cfg config file. For this reason, all the path entries that
# could generate directories need to come after the config files have
# been read.
config.add_section('paths')
# In accordance with Debian standards, we'll look for
# /etc/default/pyclean. This file can define the path for pyclean's
# etc, which includes the pyclean.cfg file. The location of the
# default file can be overridden by setting the 'PYCLEAN' environment
# variable.
if 'PYCLEAN' in os.environ:
default = os.environ['PYCLEAN']
else:
default = os.path.join('/', 'etc', 'default', 'pyclean')
if os.path.isfile(default):
config.read(default)
# By default, all the paths are subdirectories of the homedir.
homedir = os.path.expanduser('~')
# Define the basedir for pyclean. By default this will be ~/pyclean
basedir = os.path.join(homedir, 'pyclean')
# If the default file hasn't specified an etc path, we need to assume a
# default. Usually /usr/local/news/pyclean/etc.
if not config.has_option('paths', 'etc'):
config.set('paths', 'etc', os.path.join(basedir, 'etc'))
# At this point, we know the basedir is going to be required so we
# attempt to create it.
makedir(basedir)
makedir(config.get('paths', 'etc'))
# Under all circumstances, we now have an etc path. Now to check
# if the config file exists and if so, read it.
configfile = os.path.join(config.get('paths', 'etc'), 'pyclean.cfg')
if os.path.isfile(configfile):
config.read(configfile)
if not config.has_option('paths', 'log'):
config.set('paths', 'log', os.path.join(basedir, 'log'))
# As with the etc section above, we know basedir is required now. No
# harm in trying to create it multiple times.
makedir(basedir)
makedir(config.get('paths', 'log'))
if not config.has_option('paths', 'logart'):
config.set('paths', 'logart', os.path.join(basedir, 'articles'))
makedir(config.get('paths', 'logart'))
if not config.has_option('paths', 'lib'):
config.set('paths', 'lib', os.path.join(basedir, 'lib'))
makedir(config.get('paths', 'lib'))
# The following lines can be uncommented in order to write a config
# file. This is useful for creating an example file.
# with open('example.cfg', 'wb') as configfile:
# config.write(configfile)
return config
class InndFilter:
"""Provide filtering callbacks to innd."""
def __init__(self):
"""This runs every time the filter is loaded or reloaded.
This is a good place to initialize variables and precompile
regular expressions, or maybe reload stats from disk.
"""
self.traceback_loop = 0
try:
self.pyfilter = Filter()
except:
fn = os.path.join(config.get('paths', 'log'), 'init_traceback')
f = open(fn, 'a')
traceback.print_exc(file=f)
f.close()
def filter_before_reload(self):
"""Runs just before the filter gets reloaded.
You can use this method to save state information to be
restored by the __init__() method or down in the main module.
"""
try:
self.pyfilter.closetasks()
logging.info("Re-reading config file")
global config
config = init_config()
except:
fn = os.path.join(config.get('paths', 'log'), 'close_traceback')
f = open(fn, 'a')
traceback.print_exc(file=f)
f.close()
return ""
def filter_close(self):
"""Runs when innd exits.
You can use this method to save state information to be
restored by the __init__() method or down in the main module.
"""
try:
self.pyfilter.closetasks()
except:
fn = os.path.join(config.get('paths', 'log'), 'close_traceback')
f = open(fn, 'a')
traceback.print_exc(file=f)
f.close()
return ""
INN.syslog('notice', "filter_close running, bye!")
def filter_messageid(self, msgid):
"""Filter articles just by their Message-IDs.
This method interacts with the CHECK, IHAVE and TAKETHIS
NNTP commands.
If you return a non-empty string here, the offered article
will be refused before you ever have to waste any bandwidth
looking at it (unless TAKETHIS is used before an earlier CHECK).
Make sure that such a message is properly encoded in UTF-8
so as to comply with the NNTP protocol.
"""
return "" # Deactivate the samples.
def filter_art(self, art):
"""Decide whether to keep offered articles.
art is a dictionary with a bunch of headers, the article's
body, and innd's reckoning of the line count. Items not
in the article will have a value of None.
The available headers are the ones listed near the top of
innd/art.c. At this writing, they are:
Also-Control, Approved, Archive, Archived-At, Bytes, Cancel-Key,
Cancel-Lock, Content-Base, Content-Disposition,
Content-Transfer-Encoding, Content-Type, Control, Date,
Date-Received, Distribution, Expires, Face, Followup-To, From,
In-Reply-To, Injection-Date, Injection-Info, Keywords, Lines,
List-ID, Message-ID, MIME-Version, Newsgroups, NNTP-Posting-Date,
NNTP-Posting-Host, NNTP-Posting-Path, Organization,
Original-Sender, Originator, Path, Posted, Posting-Version,
Received, References, Relay-Version, Reply-To, Sender, Subject,
Summary, Supersedes, User-Agent, X-Auth, X-Auth-Sender,
X-Canceled-By, X-Cancelled-By, X-Complaints-To, X-Face,
X-HTTP-UserAgent, X-HTTP-Via, X-Mailer, X-Modbot, X-Modtrace,
X-Newsposter, X-Newsreader, X-No-Archive, X-Original-Message-ID,
X-Original-NNTP-Posting-Host, X-Original-Trace, X-Originating-IP,
X-PGP-Key, X-PGP-Sig, X-Poster-Trace, X-Postfilter, X-Proxy-User,
X-Submissions-To, X-Trace, X-Usenet-Provider, X-User-ID, Xref.
The body is the buffer in art[__BODY__] and the INN-reckoned
line count is held as an integer in art[__LINES__]. (The
Lines: header is often generated by the poster, and large
differences can be a good indication of a corrupt article.)
If you want to keep an article, return None or "". If you
want to reject, return a non-empty string. The rejection
string will appear in transfer and posting response banners,
and local posters will see them if their messages are
rejected (make sure that such a response is properly encoded
in UTF-8 so as to comply with the NNTP protocol).
"""
try:
return self.pyfilter.filter(art)
except:
if not self.traceback_loop:
fn = os.path.join(config.get('paths', 'log'), 'traceback')
f = open(fn, 'a')
traceback.print_exc(file=f)
f.close()
self.traceback_loop = 1
return ""
def filter_mode(self, oldmode, newmode, reason):
"""Capture server events and do something useful.
When the admin throttles or pauses innd (and lets it go
again), this method will be called. oldmode is the state we
just left, and newmode is where we are going. reason is
usually just a comment string.
The possible values of newmode and oldmode are the five
strings 'running', 'paused', 'throttled', 'shutdown' and
'unknown'. Actually 'unknown' shouldn't happen; it's there
in case feeping creatures invade innd.
"""
INN.syslog('n', 'state change from %s to %s - %s'
% (oldmode, newmode, reason))
class Binary:
"""Perform binary content checking of articles.
"""
def __init__(self):
# Binaries
self.regex_yenc = re.compile('^=ybegin.*', re.M)
self.regex_uuenc = re.compile('^begin[ \t]+\d{3,4}[ \t]+\w+\.\w', re.M)
self.regex_base64 = re.compile('[a-zA-Z0-9+/]{59}')
self.regex_numeric = re.compile('[0-9]{59}')
self.regex_binary = re.compile('[ \t]*\S{40}')
# Feedhosts keeps a tally of how many binary articles are received
# from each upstream peer.
self.feedhosts = {}
self.tagged = 0
def increment(self, pathhost):
"""Increment feedhosts."""
if pathhost in self.feedhosts:
self.feedhosts[pathhost] += 1
else:
self.feedhosts[pathhost] = 1
def report(self):
fn = os.path.join(config.get('paths', 'log'), 'binfeeds')
f = open(fn, 'w')
f.write('# Binary feeders report - %s\n\n'
% nowstamp())
for e in self.feedhosts.keys():
f.write('%s: %s\n' % (e, self.feedhosts[e]))
f.close()
self.feedhosts = {}
def isbin(self, art):
"""The primary function of the Binary class. An article's body is
compared against a number of checks. If the conclusion is that the
payload is binary, the type of binary is returned. Non-binary content
will return False.
"""
# Ignore base64 encoded content.
if 'base64' in str(art[Content_Transfer_Encoding]).lower():
return False
if self.regex_uuenc.search(art[__BODY__]):
return 'uuEnc'
yenc = self.regex_yenc.search(art[__BODY__])
if yenc:
# Extract the matching line
l = yenc.group(0)
if 'line=' in l and 'size=' in l and 'name=' in l:
return 'yEnc'
# Avoid costly checks where articles are shorter than the allowed
# number of binary lines.
if int(art[__LINES__]) < config.getint('binary', 'lines_allowed'):
return False
# Also avoid these costly checks where a References header is present.
skip_refs = ('References' in art and
str(art['References']).startswith('<') and
config.getboolean('binary', 'fasttrack_references') and
int(art[__LINES__]) > 500)
if skip_refs:
return False
# Base64 and suspect binary matching
b64match = 0
suspect = 0
for line in str(art[__BODY__]).split('\n'):
skip_pgp = (line.startswith('-----BEGIN PGP')
and config.getboolean('binary', 'allow_pgp'))
if skip_pgp:
break
if line == "-- ":
# Don't include signatures in binary testing
break
# Resetting the next counter to zero on a non-matching line
# dictates the counted binary lines must be consecutive. We also
# test that a numeric line doesn't trigger a Base64 match.
if (self.regex_base64.match(line) and
not self.regex_numeric.match(line)):
b64match += 1
else:
b64match = 0
if self.regex_binary.match(line):
suspect += 1
else:
suspect = 0
if b64match > config.get('binary', 'lines_allowed'):
return 'base64'
if suspect > config.get('binary', 'lines_allowed'):
return 'binary'
return False
class Filter:
def __init__(self):
"""This runs every time the filter is loaded or reloaded.
This is a good place to initialize variables and precompile
regular expressions, or maybe reload stats from disk.
"""
# Initialize Group Analizer
self.groups = Groups()
# Initialize Binary Filters
self.binary = Binary()
# Posting Host and Posting Account
self.regex_ph = re.compile('posting-host *= *"?([^";]+)')
self.regex_pa = re.compile('posting-account *= *"?([^";]+)')
# Match lines in regex_files formated /regex/ timestamp(YYYYMMDD)
self.regex_fmt = re.compile('/(.+)/[ \t]+(\d{8})')
# A dictionary of files containing regexs that need to be reloaded and
# compiled if the timestamp on them changes. The dict content is the
# timestamp (initially zeroed).
regex_file_list = [
'bad_body',
'bad_cp_groups',
'bad_crosspost_host',
'bad_from',
'bad_groups',
'bad_groups_dizum',
'bad_posthost',
'bad_subject',
'good_posthost',
'ihn_hosts',
'local_bad_body',
'local_bad_cp_groups',
'local_bad_from',
'local_bad_groups',
'local_bad_subject',
'local_hosts',
'log_from']
# Each regex_files key contains a timestamp of last-modified time.
# Setting all keys to zero ensures they are processed on first run.
regex_files = dict((f, 0) for f in regex_file_list)
# Python >= 2.7 has dict comprehension but not earlier versions
# regex_files = {f: 0 for f in regex_file_list}
self.regex_files = regex_files
# A dict of the regexs compiled from the regex_files defined above.
self.etc_re = {}
# Hostname - Not a 100% perfect regex but probably good enough.
self.regex_hostname = re.compile('([a-zA-Z0-9]|[a-zA-Z0-9]'
'[a-zA-Z0-9\-]+[a-zA-Z0-9])'
'(\.[a-zA-Z0-9\-]+)+')
# Path replacement regexs
self.regex_pathhost = re.compile('(![^\.]+)+$') # Strip RH non-FQDNs
# Match email addresses
self.regex_email = \
re.compile('([\w\-][\w\-\.]*)@[\w\-][\w\-\.]+[a-zA-Z]{1,4}')
# Colon/Space seperated fields
self.regex_fields = re.compile('[ \t]*([^:]+):[ \t]+(\S+)')
# Content-Type: text/plain; charset=utf-8
self.regex_ct = re.compile("\s*([^;]+)")
self.regex_ctcs = re.compile('charset="?([^"\s;]+)')
# Symbol matching for ratio-based rejects
self.regex_symbols = re.compile("\\_/ |_\|_|[a-z]\.{2,}[a-z]")
# Match lines that start with a CR
self.regex_crspace = re.compile("^\r ", re.MULTILINE)
# Redundant control message types
self.redundant_controls = ['sendsys', 'senduuname', 'version',
'whogets']
# Set up the EMP filters
self.emp_body = EMP(name='emp_body',
threshold=config.getint('emp', 'body_threshold'),
ceiling=config.getint('emp', 'body_ceiling'),
maxentries=config.getint('emp', 'body_maxentries'),
timedtrim=config.getint('emp', 'body_timed_trim'),
dofuzzy=config.getboolean('emp', 'body_fuzzy'))
self.emp_phn = EMP(name='emp_phn',
threshold=config.getint('emp', 'phn_threshold'),
ceiling=config.getint('emp', 'phn_ceiling'),
maxentries=config.getint('emp', 'phn_maxentries'),
timedtrim=config.getint('emp', 'phn_timed_trim'))
self.emp_lphn = EMP(name='emp_lphn',
threshold=config.getint('emp', 'lphn_threshold'),
ceiling=config.getint('emp', 'lphn_ceiling'),
maxentries=config.getint('emp', 'lphn_maxentries'),
timedtrim=config.getint('emp', 'lphn_timed_trim'))
self.emp_phl = EMP(name='emp_phl',
threshold=config.getint('emp', 'phl_threshold'),
ceiling=config.getint('emp', 'phl_ceiling'),
maxentries=config.getint('emp', 'phl_maxentries'),
timedtrim=config.getint('emp', 'phl_timed_trim'))
self.emp_fsl = EMP(name='emp_fsl',
threshold=config.getint('emp', 'fsl_threshold'),
ceiling=config.getint('emp', 'fsl_ceiling'),
maxentries=config.getint('emp', 'fsl_maxentries'),
timedtrim=config.getint('emp', 'fsl_timed_trim'))
self.emp_ihn = EMP(name='emp_ihn',
threshold=config.getint('emp', 'ihn_threshold'),
ceiling=config.getint('emp', 'ihn_ceiling'),
maxentries=config.getint('emp', 'ihn_maxentries'),
timedtrim=config.getint('emp', 'ihn_timed_trim'))
# Initialize timed events
self.hourly_events(startup=True)
# Set a datetime object for next midnight
self.midnight_trigger = next_midnight()
def filter(self, art):
# Initialize the posting info dict
post = {}
# Trigger timed reloads
if now() > self.hourly_trigger:
self.hourly_events()
if now() > self.midnight_trigger:
self.midnight_events()
# Attempt to split the From address into component parts
if 'From' in art:
post['from_name'], \
post['from_email'] = self.addressParse(art['From'])
if art[Content_Type] is not None:
ct = self.regex_ct.match(art[Content_Type])
if ct:
post['content_type'] = ct.group(1).lower()
ctcs = self.regex_ctcs.search(art[Content_Type])
if ctcs:
post['charset'] = ctcs.group(1).lower()
# Try to establish the injection-host, posting-host and
# posting-account
if art[Injection_Info] is not None:
# Establish Posting Account
ispa = self.regex_pa.search(art[Injection_Info])
if ispa:
post['posting-account'] = ispa.group(1)
# Establish Posting Host
isph = self.regex_ph.search(art[Injection_Info])
if isph:
post['posting-host'] = isph.group(1)
# Establish injection host
isih = self.regex_hostname.match(art[Injection_Info])
if isih:
post['injection-host'] = isih.group(0)
# posting-host might be obtainable from NNTP-Posting-Host
if 'posting-host' not in post and art[NNTP_Posting_Host] is not None:
post['posting-host'] = str(art[NNTP_Posting_Host])
# If the injection-host wasn't found in Injection-Info, try the X-Trace
# header. We only look for a hostname as the first field in X-Trace,
# otherwise it's regex hell.
if 'injection-host' not in post and art[X_Trace] is not None:
isih = self.regex_hostname.match(art[X_Trace])
if isih:
post['injection-host'] = isih.group(0)
# Try to extract a hostname from the Path header
if config.getboolean('hostnames', 'path_hostname'):
# First, check for a !.POSTED tag, as per RFC5537
if 'injection-host' not in post and "!.POSTED" in str(art[Path]):
postsplit = str(art[Path]).split("!.POSTED", 1)
pathhost = postsplit[0].split("!")[-1]
if pathhost:
post['injection-host'] = pathhost
# Last resort, try the right-most entry in the Path header
if 'injection-host' not in post:
subhost = re.sub(self.regex_pathhost, '', art[Path])
pathhost = subhost.split("!")[-1]
if pathhost:
post['injection-host'] = pathhost
# Some services (like Google) use dozens of Injection Hostnames.
# This section looks for substring matches and replaces the entire
# Injection-Host with the substring.
if 'injection-host' in post:
for ihsub in self.ihsubs:
if ihsub in post['injection-host']:
logging.debug("Injection-Host: Replacing %s with %s",
post['injection-host'], ihsub)
post['injection-host'] = ihsub
# Ascertain if the posting-host is meaningful
if 'posting-host' in post:
isbad_ph = self.groups.regex.bad_ph.search(post['posting-host'])
if isbad_ph:
post['bad-posting-host'] = isbad_ph.group(0)
logging.debug('Bad posting host: %s',
post['bad-posting-host'])
# Dizum deserves a scalar all to itself!
dizum = False
if ('injection-host' in post and
post['injection-host'] == 'sewer.dizum.com'):
dizum = True
# The host that fed us this article is first in the Path header.
post['feed-host'] = str(art[Path]).split('!', 1)[0]
# Analyze the Newsgroups header
self.groups.analyze(art[Newsgroups], art[Followup_To])
# Is the source of the post considered local?
local = False
if ('injection-host' in post and
'local_hosts' in self.etc_re and
self.etc_re['local_hosts'].search(post['injection-host'])):
local = True
# --- Everything below is accept / reject code ---
# Reject any messages that don't have a Message-ID
if Message_ID not in art:
logging.warn("Wot no Message-ID! Rejecting message because the "
"implications of accepting it are unpredictable.")
return self.reject(art, post, "No Message-ID header")
# We use Message-ID strings so much, it's useful to have a shortcut.
mid = str(art[Message_ID])
# Now we're convinced we have a MID, log it for local posts.
if local:
logging.debug("Local post: %s", mid)
# Control message handling
if art[Control] is not None:
ctrltype = str(art[Control]).split(" ", 1)[0]
# Reject control messages with supersedes headers
if art[Supersedes] is not None:
return self.reject(
art, post,
'Control %s with Supersedes header' % ctrltype)
if (ctrltype == 'cancel' and
config.getboolean('control', 'reject_cancels')):
return self.reject(art, post, "Control cancel")
elif (ctrltype in self.redundant_controls and
config.getboolean('control', 'reject_redundant')):
return self.reject(
art, post,
"Redundant Control Type: %s" % ctrltype)
else:
logging.info('Control: %s, mid=%s' % (art[Control], mid))
return ''
# No followups is a reject as is more than 2 groups.
if self.groups['futcount'] < 1 or self.groups['futcount'] > 2:
# Max-crosspost check
if self.groups['count'] > config.get('groups', 'max_crosspost'):
return self.reject(art, post, "Crosspost Limit Exceeded")
# Max low crosspost check
if self.groups['count'] > config.get('groups',
'max_low_crosspost'):
if self.groups['lowcp'] > 0:
return self.reject(art, post,
"Crosspost Low Limit Exceeded")
# Lines check
if art[Lines] and int(art[Lines]) != int(art[__LINES__]):
logmes = "Lines Mismatch: Header=%s, INN=%s, mid=%s"
if art[User_Agent] is not None:
logmes += ", Agent=%s"
logging.debug(logmes % (art[Lines], art[__LINES__],
mid, art[User_Agent]))
else:
logging.debug(logmes % (art[Lines], art[__LINES__], mid))
# Newsguy are evil sex spammers
if ('newsguy.com' in mid and
config.getboolean('filters', 'newsguy') and
'sex_groups' in self.groups and
self.groups['sex_groups'] > 0):
return self.reject(art, post, "Newsguy Sex")
# For some reason, this OS2 group has become kook central
if ('comp.os.os2.advocacy' in self.groups['groups'] and
self.groups['count'] > 1):
return self.reject(art, post, "OS2 Crosspost")
if (art[Followup_To] and
'comp.os.os2.advocacy' in str(art[Followup_To])):
return self.reject(art, post, "OS2 Followup")
# Poor snipe is getting the Greg Hall treatment
if 'injection-host' in post:
if post['injection-host'].startswith(
"snipe.eternal-september.org"):
pass
# self.logart("Snipe Post", art, post, 'log_snipe')
else:
if ("sn!pe" in post['from_name'] or
"snipeco" in post['from_email']):
return self.reject(art, post, "Snipe Forge")
# Compare headers against regex files
# Check if posting-host is whitelisted
gph = False
if('posting-host' in post and 'good_posthost' in self.etc_re):
gph = self.etc_re['good_posthost'].search(post['posting-host'])
if gph:
logging.info("Whitelisted posting. host=%s, msgid=%s",
post['posting-host'],
art[Message_ID])
# Reject these posting-hosts
if ('posting-host' in post and not gph and
'bad_posting-host' not in post and
'bad_posthost' in self.etc_re):
bph = self.etc_re['bad_posthost'].search(post['posting-host'])
if bph:
return self.reject(
art, post,
"Bad Posting-Host (%s)" % bph.group(0))
# Test posting-hosts that are not allowed to crosspost
if ('posting-host' in post and not gph and
self.groups['count'] > 1 and
'bad_crosspost_host' in self.etc_re):
ph = post['posting-host']
bph = self.etc_re['bad_crosspost_host'].search(ph)
if bph:
return self.reject(
art, post,
"Bad Crosspost Host (%s)" % bph.group(0))
# Groups where crossposting is not allowed
if (self.groups['count'] > 1 and not gph and
'bad_cp_groups' in self.etc_re):
bcg = self.etc_re['bad_cp_groups'].search(art[Newsgroups])
if bcg:
return self.reject(
art, post,
"Bad Crosspost Group (%s)" % bcg.group(0))
if 'log_from' in self.etc_re:
lf_result = self.etc_re['log_from'].search(art[From])
if lf_result:
self.logart(lf_result.group(0), art, post, 'log_from',
trim=False)
if 'bad_groups' in self.etc_re and not gph:
bg_result = self.etc_re['bad_groups'].search(art[Newsgroups])
if bg_result:
return self.reject(
art, post,
"Bad Group (%s)" % bg_result.group(0))
if dizum and 'bad_groups_dizum' in self.etc_re:
bgd = self.etc_re['bad_groups_dizum'].search(art[Newsgroups])
if bgd:
return self.reject(
art, post,
"Bad Dizum Group (%s)" % bgd.group(0))
# AUK bad crossposts
#if self.groups['kooks'] > 0:
# if ('alt.free.newsservers' in self.groups['groups'] or
# 'alt.privacy.anon-server' in self.groups['groups']):
# return self.reject(art, post, "AUK Bad Crosspost")
if 'bad_from' in self.etc_re and not gph:
bf_result = self.etc_re['bad_from'].search(art[From])
if bf_result:
return self.reject(
art, post,
"Bad From (%s)" % bf_result.group(0))
# Bad subject checking (Currently only on Dizum posts)
if dizum and 'bad_subject' in self.etc_re and not gph:
bs_result = self.etc_re['bad_subject'].search(art[Subject])
if bs_result:
return self.reject(
art, post,
"Bad Subject (%s)" % bs_result.group(0))
if 'bad_body' in self.etc_re and not gph:
bb_result = self.etc_re['bad_body'].search(art[__BODY__])
if bb_result:
return self.reject(
art, post,
"Bad Body (%s)" % bb_result.group(0), "Bad Body")
# The following checks are for locally posted articles
# Groups where crossposting is not allowed
if (local and not gph and self.groups['count'] > 1 and
'local_bad_cp_groups' in self.etc_re):
b = self.etc_re['local_bad_cp_groups'].search(art[Newsgroups])
if b:
return self.reject(
art, post,
"Local Bad Crosspost Group (%s)" % b.group(0))
# Local Bad From
if local and not gph and 'local_bad_from' in self.etc_re:
reg = self.etc_re['local_bad_from']
bf_result = reg.search(art[From])
if bf_result:
return self.reject(
art, post,
"Local Bad From (%s)" % bf_result.group(0),
"Local Reject")
# Local Bad Subject
if local and not gph and 'local_bad_subject' in self.etc_re:
reg = self.etc_re['local_bad_subject']
bs_result = reg.search(art[Subject])
if bs_result:
return self.reject(
art, post,
"Local Bad Subject (%s)" % bs_result.group(0),
"Local Reject")
# Local Bad Groups
if local and not gph and 'local_bad_groups' in self.etc_re:
reg = self.etc_re['local_bad_groups']
bg_result = reg.search(art[Newsgroups])
if bg_result:
return self.reject(
art, post,
"Local Bad Group (%s)" % bg_result.group(0))
# Local Bad Body
if local and not gph and 'local_bad_body' in self.etc_re:
reg = self.etc_re['local_bad_body']
bb_result = reg.search(art[__BODY__])
if bb_result:
return self.reject(
art, post,
"Local Bad Body (%s)" % bb_result.group(0),
"Local Reject")
# Misplaced binary check
if self.groups['bin_allowed_bool']:
# All groups in the post match bin_allowed groups
isbin = False
else:
# Potentially expensive check if article contains binary
isbin = self.binary.isbin(art)
# Generic 'binary' means it looks binary-like but doesn't match any
# known encoding method.
if isbin == 'binary':
if config.getboolean('binary', 'reject_suspected'):
return self.reject(
art, post, "Binary (%s)" % isbin)
else:
self.logart("Binary Suspect", art, post, "bin_suspect",
trim=False)
elif isbin:
self.binary.increment(post['feed-host'])
return self.reject(
art, post, "Binary (%s)" % isbin)
# Misplaced HTML check
if (not self.groups['html_allowed_bool'] and
config.getboolean('filters', 'reject_html') and
'content_type' in post):
if 'text/html' in post['content_type']:
return self.reject(art, post, "HTML Misplaced")
if 'multipart' in post['content_type']:
if config.getboolean('filters', 'reject_multipart'):
return self.reject(art, post, "MIME Multpart")
else:
logging.debug('Multipart: %s' % mid)
# Symbol ratio test
symlen = len(self.regex_symbols.findall(art[__BODY__]))
if symlen > 100:
return self.reject(art, post, "Symbols (%s)" % symlen)
# Start of EMP checks
if (not self.groups['emp_exclude_bool'] and
not self.groups['test_bool']):
ngs = ','.join(self.groups['groups'])
# If a substring matches the Newsgroups header, use just that
# substring as EMP fodder where a Newsgroups name is normally used.
for ngsub in self.ngsubs:
if ngsub in ngs:
logging.debug("Newsgroup substring match: %s", ngsub)
ngs = ngsub
break
# Start of posting-host based checks.
# First try and seed some filter fodder.
if 'posting-account' in post:
# If a Posting-Account is known, it makes better filter fodder
# than the hostname/address which could be dynamic.
fodder = post['posting-account']
elif 'bad-posting-host' in post:
# If we can't trust the info in posting-host, use the
# injection-host. This is a worst-case scenario.
if ('injection-host' in post and
config.getboolean('emp', 'ph_coarse')):
fodder = post['injection-host']
else:
fodder = None
elif 'posting-host' in post:
fodder = post['posting-host']
else:
fodder = None
if fodder:
# Beginning of PHN filters
if 'moderated' in self.groups and self.groups['moderated']:
logging.debug("Bypassing PHN filter due to moderated "
"group in distribution")
elif local:
# Beginning of PHN_Local filter
do_lphn = True
if self.groups['phn_exclude_bool']:
do_lphn = False
if (not do_lphn and art['References'] is None and
'Subject' in art and
str(art['Subject']).startswith("Re:")):
logging.info("emp_lphn: Exclude overridden - "
"Subject Re but no Reference")
do_lphn = True
if (not do_lphn and
self.regex_crspace.search(art[__BODY__])):
logging.info("emp_lphn: Exclude overridden - "
"Carriage Return starts line")
do_lphn = True
if do_lphn and self.emp_lphn.add(fodder + ngs):
return self.reject(art, post, "EMP Local PHN Reject")
else:
# Beginning of standard PHN filter
if self.groups['phn_exclude_bool']:
logging.debug("emp_phn exclude for: %s",
art['Newsgroups'])
elif self.emp_phn.add(fodder + ngs):
return self.reject(art, post, "EMP PHN Reject")
# Beginning of PHL filter
if self.emp_phl.add(fodder + str(art[__LINES__])):
return self.reject(art, post, "EMP PHL Reject")
# Beginning of FSL filter
fsl = str(art[From]) + str(art[Subject]) + str(art[__LINES__])
if self.emp_fsl.add(fsl):
return self.reject(art, post, "EMP FSL Reject")
# Beginning of IHN filter
if ('injection-host' in post and
'ihn_hosts' in self.etc_re and
not self.groups['ihn_exclude_bool']):
ihn_result = self.etc_re['ihn_hosts']. \
search(post['injection-host'])
if ihn_result:
logging.debug("emp_ihn hit: %s", ihn_result.group(0))
if self.emp_ihn.add(post['injection-host'] + ngs):
return self.reject(art, post, "EMP IHN Reject")
# Beginning of EMP Body filter. Do this last, it's most
# expensive in terms of processing.
if art[__BODY__] is not None:
if self.emp_body.add(art[__BODY__]):
return self.reject(art, post, "EMP Body Reject")
if local:
# All tests passed. Log the locally posted message.
logging.info("post: mid=%s, from=%s, groups=%s",
art[Message_ID], art[From], art[Newsgroups])
self.logart('Local Post', art, post, 'local_post')
# The article passed all checks. Return an empty string.
return ""
def addressParse(self, addr):
name, email = parseaddr(addr)
return name.lower(), email.lower()
def xreject(self, reason, art, post):
for logrule in self.log_rules.keys():
if reason.startswith(logrule):
self.logart(reason, art, post, self.log_rules[logrule])
break
logging.info("reject: mid=%s, reason=%s" % (art[Message_ID], reason))
return reason
def reject(self, art, post, reason, short_reason=None):
rulehit = False
for logrule in self.log_rules.keys():
if reason.startswith(logrule):
self.logart(reason, art, post, self.log_rules[logrule])
rulehit = True
break
if rulehit:
logging.info("reject: mid=%s, reason=%s" % (art[Message_ID], reason))
else:
msg = "reject: No matched logging rule: mid={}, reason={}"
logging.warn(msg.format(art[Message_ID], reason))
if short_reason is None:
# Sometimes we don't want to provide the source with a detailed
# reason of why a message was rejected. They could then just
# tweak their payload to circumvent the cause.
return reason
return short_reason
def logart(self, reason, art, post, filename, trim=True):
f = open(os.path.join(config.get('paths', 'logart'), filename), 'a')
f.write('From foo@bar Thu Jan 1 00:00:01 1970\n')
f.write('Info: %s\n' % reason)
for hdr in art.keys():
if hdr == '__BODY__' or hdr == '__LINES__' or art[hdr] is None:
continue
f.write('%s: %s\n' % (hdr, art[hdr]))
for hdr in post.keys():
f.write('%s: %s\n' % (hdr, post[hdr]))
f.write('\n')
if (not trim or
art[__LINES__] <= config.get('logging', 'logart_maxlines')):
f.write(art[__BODY__])
else:
maxlines = config.get('logging', 'logart_maxlines')
loglines = 0
for line in str(art[__BODY__]).split('\n', 1000)[:-1]:
# Ignore quoted lines
if line.startswith(">"):
continue
f.write(line + "\n")
loglines += 1
if loglines >= maxlines:
f.write('[snip]')
break
f.write('\n\n')
f.close
def hourly_events(self, startup=False):
"""Carry out hourly events. Some of these events may be to check if
it's time to do other, less frequent events. Timed events are also
triggered on startup. The "startup" flag enables special handling of
this instance.
"""
if startup:
logging.info("Performing startup tasks")
else:
logging.info('Performing hourly tasks')
self.emp_body.statlog()
self.emp_fsl.statlog()
self.emp_phl.statlog()
self.emp_phn.statlog()
self.emp_lphn.statlog()
self.emp_ihn.statlog()
# Reload logging directives
self.log_rules = self.file2dict('log_rules')
logging.info('Reloaded %s logging directives', len(self.log_rules))
# Reload Injection-Host substrings
self.ihsubs = self.file2list('ih_substrings')
logging.info('Reloaded %s Injection-Host substrings', len(self.ihsubs))
self.ngsubs = self.file2list('ng_emp_subst')
logging.info('Reloaded %s Newsgroup substrings', len(self.ngsubs))
# Set up Regular Expressions
for fn in self.regex_files.keys():
new_regex = self.regex_file(fn)
if new_regex:
self.etc_re[fn] = new_regex
if not startup:
# Re-read the config file.
configfile = os.path.join(config.get('paths', 'etc'),
'pyclean.cfg')
logging.info("Reloading config file: %s" % configfile)
if os.path.isfile(configfile):
config.read(configfile)
else:
logging.info("%s: File not found. Using defaults settings."
% configfile)
# Reset the next timed trigger.
self.hourly_trigger = future(hours=1)
def midnight_events(self):
"""Events that need to occur at midnight each day.
"""
logging.info('Performing midnight tasks')
self.binary.report()
self.emp_body.reset()
self.emp_fsl.reset()
self.emp_phl.reset()
self.emp_phn.reset()
self.emp_lphn.reset()
self.emp_ihn.reset()
# Set the midnight trigger for next day.
self.midnight_trigger = next_midnight()
def regex_file(self, filename):
"""Read a given file and return a regular expression composed of
individual regex's on each line that have not yet expired.
"""
logging.debug('Testing %s regex condition', filename)
fqfn = os.path.join(config.get('paths', 'etc'), filename)
if not os.path.isfile(fqfn):
logging.info('%s: Regex file not found' % filename)
if filename in self.etc_re:
logging.info("%s: Regex file has been deleted", filename)
# The file has been deleted so delete the regex.
self.etc_re.pop(filename, None)
# Reset the last_modified date to zero
self.regex_files[filename] = 0
return False
current_mod_stamp = os.path.getmtime(fqfn)
recorded_mod_stamp = self.regex_files[filename]
if current_mod_stamp <= recorded_mod_stamp:
logging.info('%s: File not modified so not recompiling',
filename)
return False
# The file has been modified: Recompile the regex
logging.info('%s: Recompiling Regular Expression.', filename)
# Reset the file's modstamp
self.regex_files[filename] = current_mod_stamp
# Make a local datetime object for now, just to save setting now in
# the coming loop.
bad_items = []
n = now()
f = open(fqfn, 'r')
for line in f:
valid = self.regex_fmt.match(line)
if valid:
try:
# Is current time beyond that of the datestamp? If it is,
# the entry is considered expired and processing moves to
# the next entry.
if n > dateobj(valid.group(2)):
continue
except ValueError:
# If the timestamp is invalid, just ignore the entry
logging.warn("Invalid timestamp in %s. Line=%s",
filename, line)
continue
# If processing gets here, the entry is a valid regex.
bad_items.append(valid.group(1))
elif line.lstrip().startswith('#'):
# Don't do anything, it's a comment line
pass
elif len(line.strip()) == 0:
# Blank lines are fine
pass
else:
logging.warn("Invalid line in %s: %s", filename, line)
f.close()
num_bad_items = len(bad_items)
if num_bad_items == 0:
# No valid entires exist in the file.
logging.debug('%s: No valid entries found' % filename)
return False
regex = '|'.join(bad_items)
# This should never happen but best to check as || will match
# everything.
regex = regex.replace('||', '|')
logging.info("Compiled %s rules from %s", num_bad_items, filename)
return re.compile(regex)
def file2list(self, filename):
fqfn = os.path.join(config.get('paths', 'etc'), filename)
if not os.path.isfile(fqfn):
logging.info('%s: File not found' % filename)
return []
f = open(fqfn, 'r')
lines = f.readlines()
f.close()
valid = []
for line in lines:
# Strip comments (including inline)
content = line.split('#', 1)[0].strip()
# Ignore empty lines
if len(content) > 0:
valid.append(content)
return valid
def file2dict(self, filename, numeric=False):
"""Read a file and split each line at the first space encountered. The
first element is the key, the rest is the content. If numeric is True
then only integer values will be acccepted."""
d = {}
for line in self.file2list(filename):
valid = self.regex_fields.match(line)
if valid:
k = valid.group(1)
c = valid.group(2)
if numeric:
try:
c = int(c)
except ValueError:
c = 0
d[k] = c
return d
def closetasks(self):
"""Things to do on filter closing.
"""
logging.info("Running shutdown tasks")
# Write to file any entries in the stack
self.emp_body.dump()
self.emp_fsl.dump()
self.emp_phl.dump()
self.emp_phn.dump()
self.emp_lphn.dump()
self.emp_ihn.dump()
class Groups:
def __init__(self):
self.regex = Regex()
# List of tests (that will become zeroed dict items).
self.grps = [
'bin_allowed',
'emp_exclude',
'html_allowed',
'ihn_exclude',
'kooks',
'lowcp',
'moderated',
'phn_exclude',
'sex_groups',
'test'
]
def __getitem__(self, grptest):
return self.grp[grptest]
def __contains__(self, item):
if item in self.grp:
return True
return False
def analyze(self, newsgroups, followupto):
# Zero all dict items we'll use in this post
grp = dict((f, 0) for f in self.grps)
# This will become a list of newsgroups
nglist = []
for ng in str(newsgroups).lower().split(','):
# Strip whitespace from individual Newsgroups
ng = ng.strip()
# Populate a list of newsgroups after stripping spaces
nglist.append(ng)
if self.regex.test.search(ng):
grp['test'] += 1
if self.regex.bin_allowed.search(ng):
grp['bin_allowed'] += 1
if self.regex.emp_exclude.search(ng):
grp['emp_exclude'] += 1
if self.regex.ihn_exclude.search(ng):
grp['ihn_exclude'] += 1
if self.regex.html_allowed.search(ng):
grp['html_allowed'] += 1
if self.regex.kooks.search(ng):
grp['kooks'] += 1
if self.regex.lowcp.search(ng):
grp['lowcp'] += 1
if self.regex.phn_exclude.search(ng):
grp['phn_exclude'] += 1
if self.regex.sex_groups.search(ng):
grp['sex_groups'] += 1
if INN.newsgroup(ng) == 'm':
grp['moderated'] += 1
# Not all bools will be meaningful but it's easier to create them
# generically then specifically.
count = len(nglist)
for ngelement in grp.keys():
ngbool = '%s_bool' % ngelement
grp[ngbool] = grp[ngelement] == count
grp['groups'] = sorted(nglist)
grp['count'] = count
# Create a list of Followup-To groups and count them.
grp['futcount'] = 0
if followupto is not None:
futlist = str(followupto).lower().split(',')
grp['futcount'] = len(futlist)
self.grp = grp
class Regex:
def __init__(self):
# Test groups
test = ['\.test(ing)?(?:$|\.)',
'^es\.pruebas',
'^borland\.public\.test2',
'^cern\.testnews']
self.test = self.regex_compile(test)
# Binary groups
bin_allowed = ['^bin[a.]', '\.bin[aei.]', '\.bin$', '^fur\.artwork',
'^alt\.anonymous\.messages$', '^de\.alt\.dateien',
'^rec\.games\.bolo$', '^comp\.security\.pgp\.test$',
'^sfnet\.tiedostot', '^fido\.', '^unidata\.',
'^alt\.security\.keydist', '^mailing\.',
'^linux\.', '^lucky\.freebsd', '^gnus\.',
'\.lists\.freebsd\.']
self.bin_allowed = self.regex_compile(bin_allowed)
html_allowed = ['^pgsql\.', '^relcom\.', '^gmane', 'microsoft',
'^mailing\.', '^gnus\.']
self.html_allowed = self.regex_compile(html_allowed)
# Exclude from all EMP filters
emp_exclude = ['^alt\.anonymous\.messages', '^free\.', '^local\.',
'^relcom\.', '^mailing\.', '^fa\.', '\.cvs\.',
'^gnu\.', 'lists\.freebsd\.ports\.bugs']
self.emp_exclude = self.regex_compile(emp_exclude)
# Exclude groups from IHN filter
ihn_exclude = ['^alt\.anonymous',
'^alt\.privacy',
'^alt\.prophecies\.nostradamus']
self.ihn_exclude = self.regex_compile(ihn_exclude)
# Exclude groups from PHN filter
phn_exclude = ['^alt\.privacy\.']
self.phn_exclude = self.regex_compile(phn_exclude)
# Bad posting-hosts
bad_ph = ['newsguy\.com', 'tornevall\.net']
self.bad_ph = self.regex_compile(bad_ph)
# Sex groups
sex_groups = ['^alt\.sex']
self.sex_groups = self.regex_compile(sex_groups)
# Kook groups
kooks = ['^alt\.usenet\.kooks',
'^alt\.checkmate',
'^alt\.fan\.cyberchicken',
'^alt\.fan\.karl-malden\.nose']
self.kooks = self.regex_compile(kooks)
# Low cross post groups
lowcp = ['^alt\.free\.newsservers']
self.lowcp = self.regex_compile(lowcp)
def regex_compile(self, regexlist):
textual = '|'.join(regexlist).replace('||', '|')
return re.compile(textual)
class EMP:
def __init__(self,
threshold=3,
ceiling=100,
maxentries=5000,
timedtrim=3600,
dofuzzy=False,
name=False):
# Statistics relating to this EMP instance
if threshold > ceiling:
raise ValueError('Threshold cannot exceed ceiling')
# The hash table itself. Keyed by MD5 hash and containing a hit
# count.
self.table = {}
# Attempt to restore a previous EMP dump
self.restore(name)
self.fuzzy_15char = re.compile('\S{15,}')
self.fuzzy_notletters = re.compile('[^a-zA-Z]')
# Initialize some defaults
self.stats = {'name': name,
'nexttrim': future(secs=timedtrim),
'lasttrim': now(),
'processed': 0,
'accepted': 0,
'rejected': 0,
'threshold': threshold,
'ceiling': ceiling,
'maxentries': maxentries,
'timedtrim': timedtrim,
'dofuzzy': dofuzzy}
logmes = '%(name)s initialized. '
logmes += 'threshold=%(threshold)s, '
logmes += 'ceiling=%(ceiling)s, '
logmes += 'maxentries=%(maxentries)s, '
logmes += 'timedtrim=%(timedtrim)s'
logging.info(logmes % self.stats)
def add(self, content):
"""The content, in this context, is any string we want to hash and
check for EMP collisions. In various places we refer to it as
'hash fodder'.
"""
self.stats['processed'] += 1
if self.stats['dofuzzy']:
# Strip long strings
content = re.sub(self.fuzzy_15char, '', content)
# Remove everything except a-zA-Z
content = re.sub(self.fuzzy_notletters, '', content).lower()
# Bail out if the byte length of the content isn't sufficient for
# generating an effective, unique hash.
if len(content) < 1:
logging.debug("Null content in %s hashing fodder.",
self.stats['name'])
return False
# See if it's time to perform a trim.
n = now()
if n > self.stats['nexttrim']:
secs_since_lasttrim = (n - self.stats['lasttrim']).seconds
decrement = int(secs_since_lasttrim / self.stats['timedtrim'])
logmes = "%s: Trim decrement factor=%s"
logging.debug(logmes % (self.stats['name'], decrement))
if decrement > 0:
self._trim(decrement)
else:
logmes = "%s: Invalid attempt to trim by less than 1"
logging.error(logmes % (self.stats['name'], decrement))
elif len(self.table) > self.stats['maxentries']:
logmes = '%(name)s: Exceeded maxentries of %(maxentries)s'
logging.warn(logmes % self.stats)
self._trim(1)
# MD5 is weak in cryptographic terms, but do I care for the purpose
# of EMP collision checking? Obviously not or I'd use something else.
h = md5(content).digest()
if h in self.table:
# When the ceiling is reached, stop incrementing the count.
if self.table[h] < self.stats['ceiling']:
self.table[h] += 1
else:
logging.debug("%s hash ceiling hit. Not incrementing counter.",
self.stats['name'])
else:
# Initialize the md5 entry.
self.table[h] = 1
if self.table[h] > self.stats['threshold']:
# Houston, we have an EMP reject.
self.stats['rejected'] += 1
return True
self.stats['accepted'] += 1
return False
def _trim(self, decrement):
"""Decrement the counter against each hash. If the counter reaches
zero, delete the hash entry.
"""
# As the EMP table is about to be modified, oldsize records it prior
# to doing any changes. This is only used for reporting purposes.
self.stats['oldsize'] = len(self.table)
# Keep a running check of the largest count against a key.
self.stats['high'] = 0
for h in self.table.keys():
self.table[h] -= decrement
if self.table[h] > self.stats['high']:
self.stats['high'] = self.table[h]
if self.table[h] <= 0:
del self.table[h]
self.stats['size'] = len(self.table)
self.stats['decrement'] = decrement
logging.info("%(name)s: Trim complete. was=%(oldsize)s, now=%(size)s, "
"high=%(high)s, decrement=%(decrement)s",
self.stats)
self.stats['nexttrim'] = \
future(secs=self.stats['timedtrim'])
self.stats['lasttrim'] = now()
def statlog(self):
"""Log details of the EMP hash."""
self.stats['size'] = len(self.table)
logging.info("%(name)s: size=%(size)s, processed=%(processed)s, "
"accepted=%(accepted)s, rejected=%(rejected)s",
self.stats)
def dump(self):
"""Dump the EMP table to disk so we can reload it after a restart.
"""
dumpfile = os.path.join(config.get('paths', 'lib'),
self.stats['name'] + ".db")
dump = shelve.open(dumpfile, flag='n')
for k in self.table:
dump[k] = self.table[k]
dump.close()
def restore(self, name):
"""Restore an EMP dump from disk.
"""
dumpfile = os.path.join(config.get('paths', 'lib'), name + ".db")
if os.path.isfile(dumpfile):
logging.info("Attempting restore of %s dump", name)
dump = shelve.open(dumpfile, flag='r')
# We seem unable to use copy functions between shelves and dicts
# so we do it per record. Speed is not essential at these times.
for k in dump:
self.table[k] = dump[k]
dump.close()
logging.info("Restored %s records to %s", len(self.table), name)
else:
logging.debug("%s: Dump file does not exist. Doing a clean "
"initialzation.", dumpfile)
def reset(self):
"""Reset counters for this emp filter.
"""
self.stats['processed'] = 0
self.stats['accepted'] = 0
self.stats['rejected'] = 0
"""
Okay, that's the end of our class definition. What follows is the
stuff you need to do to get it all working inside innd.
"""
if 'python_filter' not in dir():
python_version = sys.version_info
config = init_config()
logfmt = config.get('logging', 'format')
datefmt = config.get('logging', 'datefmt')
loglevels = {'debug': logging.DEBUG, 'info': logging.INFO,
'warn': logging.WARN, 'error': logging.ERROR}
logging.getLogger().setLevel(logging.DEBUG)
logfile = logging.handlers.TimedRotatingFileHandler(
os.path.join(config.get('paths', 'log'), 'pyclean.log'),
when='midnight',
interval=1,
backupCount=config.getint('logging', 'retain'))
logfile.setLevel(loglevels[config.get('logging', 'level')])
logfile.setFormatter(logging.Formatter(logfmt, datefmt=datefmt))
logging.getLogger().addHandler(logfile)
python_filter = InndFilter()
try:
INN.set_filter_hook(python_filter)
INN.syslog('n', "pyclean successfully hooked into INN")
except Exception as errmsg:
INN.syslog('e', "Cannot obtain INN hook for pyclean: %s" % errmsg[0])
# This looks weird, but creating and interning these strings should let us get
# faster access to header keys (which innd also interns) by losing some strcmps
# under the covers.
Also_Control = intern("Also-Control")
Approved = intern("Approved")
Archive = intern("Archive")
Archived_At = intern("Archived-At")
Bytes = intern("Bytes")
Cancel_Key = intern("Cancel-Key")
Cancel_Lock = intern("Cancel-Lock")
Comments = intern("Comments")
Content_Base = intern("Content-Base")
Content_Disposition = intern("Content-Disposition")
Content_Transfer_Encoding = intern("Content-Transfer-Encoding")
Content_Type = intern("Content-Type")
Control = intern("Control")
Date = intern("Date")
Date_Received = intern("Date-Received")
Distribution = intern("Distribution")
Expires = intern("Expires")
Face = intern("Face")
Followup_To = intern("Followup-To")
From = intern("From")
In_Reply_To = intern("In-Reply-To")
Injection_Date = intern("Injection-Date")
Injection_Info = intern("Injection-Info")
Keywords = intern("Keywords")
Lines = intern("Lines")
List_ID = intern("List-ID")
Message_ID = intern("Message-ID")
MIME_Version = intern("MIME-Version")
Newsgroups = intern("Newsgroups")
NNTP_Posting_Date = intern("NNTP-Posting-Date")
NNTP_Posting_Host = intern("NNTP-Posting-Host")
NNTP_Posting_Path = intern("NNTP-Posting-Path")
Organization = intern("Organization")
Original_Sender = intern("Original-Sender")
Originator = intern("Originator")
Path = intern("Path")
Posted = intern("Posted")
Posting_Version = intern("Posting-Version")
Received = intern("Received")
References = intern("References")
Relay_Version = intern("Relay-Version")
Reply_To = intern("Reply-To")
Sender = intern("Sender")
Subject = intern("Subject")
Summary = intern("Summary")
Supersedes = intern("Supersedes")
User_Agent = intern("User-Agent")
X_Auth = intern("X-Auth")
X_Auth_Sender = intern("X-Auth-Sender")
X_Canceled_By = intern("X-Canceled-By")
X_Cancelled_By = intern("X-Cancelled-By")
X_Complaints_To = intern("X-Complaints-To")
X_Face = intern("X-Face")
X_HTTP_UserAgent = intern("X-HTTP-UserAgent")
X_HTTP_Via = intern("X-HTTP-Via")
X_Mailer = intern("X-Mailer")
X_Modbot = intern("X-Modbot")
X_Modtrace = intern("X-Modtrace")
X_Newsposter = intern("X-Newsposter")
X_Newsreader = intern("X-Newsreader")
X_No_Archive = intern("X-No-Archive")
X_Original_Message_ID = intern("X-Original-Message-ID")
X_Original_NNTP_Posting_Host = intern("X-Original-NNTP-Posting-Host")
X_Original_Trace = intern("X-Original-Trace")
X_Originating_IP = intern("X-Originating-IP")
X_PGP_Key = intern("X-PGP-Key")
X_PGP_Sig = intern("X-PGP-Sig")
X_Poster_Trace = intern("X-Poster-Trace")
X_Postfilter = intern("X-Postfilter")
X_Proxy_User = intern("X-Proxy-User")
X_Submissions_To = intern("X-Submissions-To")
X_Trace = intern("X-Trace")
X_Usenet_Provider = intern("X-Usenet-Provider")
X_User_ID = intern("X-User-ID")
Xref = intern("Xref")
__BODY__ = intern("__BODY__")
__LINES__ = intern("__LINES__")
| crooks/PyClean | pyclean.py | Python | gpl-3.0 | 67,006 |
#!/usr/bin/env python
# coding: utf8
# (c) 2014 Dominic Springer
# File licensed under GNU GPL (see HARP_License.txt)
import re
import numpy as np
#look for: import re, re.search
# HOW TO ==================================
# 1) Paste line to https://pythex.org/
# 2) Create function to wrap
#==========================================
#==========================================
def get_DimX_DimY_from_Filename(FN):
#==========================================
res = re.search(r"(\d*)x(\d*)", FN)
return (np.int32(res.group(1)), np.int32(res.group(2)))
#==========================================
def fromStartToBracket(Str):
#==========================================
res = re.search(r"::(.*)\sat", Str)
return (res.group(1))
#get DimX and DimY from header in file
# line = FH.readline()
# DimX = int( re.search(r"DimX=([-|\d]*)", line).group(1))
# DimY = int( re.search(r"DimY=([-|\d]*)", line).group(1))
| pixlra/HARP-fork | PythonLib/Regex.py | Python | gpl-3.0 | 961 |
# -*- encoding: utf-8 -*-
"""Test class for Locations UI"""
from fauxfactory import gen_ipaddr, gen_string
from nailgun import entities
from robottelo.config import settings
from robottelo.datafactory import generate_strings_list, invalid_values_list
from robottelo.decorators import run_only_on, tier1, tier2
from robottelo.constants import (
ANY_CONTEXT,
INSTALL_MEDIUM_URL,
LIBVIRT_RESOURCE_URL,
OS_TEMPLATE_DATA_FILE,
)
from robottelo.helpers import get_data_file
from robottelo.test import UITestCase
from robottelo.ui.factory import make_loc, make_templates, set_context
from robottelo.ui.locators import common_locators, locators, tab_locators
from robottelo.ui.session import Session
def valid_org_loc_data():
"""Returns a list of valid org/location data"""
return [
{'org_name': gen_string('alpha', 10),
'loc_name': gen_string('alpha', 10)},
{'org_name': gen_string('numeric', 10),
'loc_name': gen_string('numeric', 10)},
{'org_name': gen_string('alphanumeric', 10),
'loc_name': gen_string('alphanumeric', 10)},
{'org_name': gen_string('utf8', 10),
'loc_name': gen_string('utf8', 10)},
{'org_name': gen_string('latin1', 20),
'loc_name': gen_string('latin1', 10)},
{'org_name': gen_string('html', 20),
'loc_name': gen_string('html', 10)}
]
def valid_env_names():
"""Returns a list of valid environment names"""
return [
gen_string('alpha'),
gen_string('numeric'),
gen_string('alphanumeric'),
]
class LocationTestCase(UITestCase):
"""Implements Location tests in UI"""
location = None
# Auto Search
@run_only_on('sat')
@tier1
def test_positive_auto_search(self):
"""Can auto-complete search for location by partial name
@feature: Locations
@assert: Created location can be auto search by its partial name
"""
loc_name = gen_string('alpha')
with Session(self.browser) as session:
page = session.nav.go_to_loc
make_loc(session, name=loc_name)
auto_search = self.location.auto_complete_search(
page,
locators['location.select_name'],
loc_name[:3],
loc_name,
search_key='name'
)
self.assertIsNotNone(auto_search)
# Positive Create
@run_only_on('sat')
@tier1
def test_positive_create_with_name(self):
"""Create Location with valid name only
@feature: Locations
@assert: Location is created, label is auto-generated
"""
with Session(self.browser) as session:
for loc_name in generate_strings_list():
with self.subTest(loc_name):
make_loc(session, name=loc_name)
self.assertIsNotNone(self.location.search(loc_name))
@run_only_on('sat')
@tier1
def test_negative_create_with_invalid_names(self):
"""Create location with invalid name
@feature: Locations
@assert: location is not created
"""
with Session(self.browser) as session:
for loc_name in invalid_values_list(interface='ui'):
with self.subTest(loc_name):
make_loc(session, name=loc_name)
error = session.nav.wait_until_element(
common_locators['name_haserror'])
self.assertIsNotNone(error)
@run_only_on('sat')
@tier1
def test_negative_create_with_same_name(self):
"""Create location with valid values, then create a new one
with same values.
@feature: Locations
@assert: location is not created
"""
loc_name = gen_string('utf8')
with Session(self.browser) as session:
make_loc(session, name=loc_name)
self.assertIsNotNone(self.location.search(loc_name))
make_loc(session, name=loc_name)
error = session.nav.wait_until_element(
common_locators['name_haserror'])
self.assertIsNotNone(error)
@run_only_on('sat')
@tier2
def test_positive_create_with_location_and_org(self):
"""Create and select both organization and location.
@feature: Locations
@assert: Both organization and location are selected.
"""
with Session(self.browser) as session:
for test_data in valid_org_loc_data():
with self.subTest(test_data):
org_name = test_data['org_name']
loc_name = test_data['loc_name']
org = entities.Organization(name=org_name).create()
self.assertEqual(org.name, org_name)
make_loc(session, name=loc_name)
self.assertIsNotNone(self.location.search(loc_name))
location = session.nav.go_to_select_loc(loc_name)
organization = session.nav.go_to_select_org(org_name)
self.assertEqual(location, loc_name)
self.assertEqual(organization, org_name)
# Positive Update
@run_only_on('sat')
@tier1
def test_positive_update_name(self):
"""Create Location with valid values then update its name
@feature: Locations
@assert: Location name is updated
"""
loc_name = gen_string('alpha')
with Session(self.browser) as session:
make_loc(session, name=loc_name)
self.assertIsNotNone(self.location.search(loc_name))
for new_name in generate_strings_list():
with self.subTest(new_name):
self.location.update(loc_name, new_name=new_name)
self.assertIsNotNone(self.location.search(new_name))
loc_name = new_name # for next iteration
# Negative Update
@run_only_on('sat')
@tier1
def test_negative_update_with_too_long_name(self):
"""Create Location with valid values then fail to update
its name
@feature: Locations
@assert: Location name is not updated
"""
loc_name = gen_string('alphanumeric')
with Session(self.browser) as session:
make_loc(session, name=loc_name)
self.assertIsNotNone(self.location.search(loc_name))
new_name = gen_string('alpha', 247)
self.location.update(loc_name, new_name=new_name)
error = session.nav.wait_until_element(
common_locators['name_haserror'])
self.assertIsNotNone(error)
@run_only_on('sat')
@tier1
def test_positive_delete(self):
"""Create location with valid values then delete it.
@feature: Location Positive Delete test.
@assert: Location is deleted
"""
with Session(self.browser) as session:
for loc_name in generate_strings_list():
with self.subTest(loc_name):
entities.Location(name=loc_name).create()
session.nav.go_to_loc()
self.location.delete(loc_name)
@run_only_on('sat')
@tier2
def test_positive_add_subnet(self):
"""Add a subnet by using location name and subnet name
@feature: Locations
@assert: subnet is added
"""
strategy, value = common_locators['entity_deselect']
with Session(self.browser) as session:
for subnet_name in generate_strings_list():
with self.subTest(subnet_name):
loc_name = gen_string('alpha')
subnet = entities.Subnet(
name=subnet_name,
network=gen_ipaddr(ip3=True),
mask='255.255.255.0',
).create()
self.assertEqual(subnet.name, subnet_name)
make_loc(session, name=loc_name)
self.assertIsNotNone(self.location.search(loc_name))
self.location.update(loc_name, new_subnets=[subnet_name])
self.location.search(loc_name).click()
session.nav.click(tab_locators['context.tab_subnets'])
element = session.nav.wait_until_element(
(strategy, value % subnet_name))
self.assertIsNotNone(element)
@run_only_on('sat')
@tier2
def test_positive_add_domain(self):
"""Add a domain to a Location
@feature: Locations
@assert: Domain is added to Location
"""
strategy, value = common_locators['entity_deselect']
with Session(self.browser) as session:
for domain_name in generate_strings_list():
with self.subTest(domain_name):
loc_name = gen_string('alpha')
domain = entities.Domain(name=domain_name).create()
self.assertEqual(domain.name, domain_name)
make_loc(session, name=loc_name)
self.assertIsNotNone(self.location.search(loc_name))
self.location.update(loc_name, new_domains=[domain_name])
self.location.search(loc_name).click()
session.nav.click(tab_locators['context.tab_domains'])
element = session.nav.wait_until_element(
(strategy, value % domain_name))
self.assertIsNotNone(element)
@run_only_on('sat')
@tier2
def test_positive_add_user(self):
"""Create user then add that user by using the location name
@feature: Locations
@assert: User is added to location
"""
strategy, value = common_locators['entity_deselect']
with Session(self.browser) as session:
# User names does not accept html values
for user_name in generate_strings_list(
length=10,
exclude_types=['html']):
with self.subTest(user_name):
loc_name = gen_string('alpha')
password = gen_string('alpha')
user = entities.User(
login=user_name,
firstname=user_name,
lastname=user_name,
password=password,
).create()
self.assertEqual(user.login, user_name)
make_loc(session, name=loc_name)
self.assertIsNotNone(self.location.search(loc_name))
self.location.update(loc_name, new_users=[user_name])
self.location.search(loc_name).click()
session.nav.click(tab_locators['context.tab_users'])
element = session.nav.wait_until_element(
(strategy, value % user_name))
self.assertIsNotNone(element)
@run_only_on('sat')
@tier1
def test_positive_check_all_values_hostgroup(self):
"""check whether host group has the 'All values' checked.
@feature: Locations
@assert: host group 'All values' checkbox is checked.
"""
loc_name = gen_string('alpha')
with Session(self.browser) as session:
make_loc(session, name=loc_name)
self.assertIsNotNone(self.location.search(loc_name))
selected = self.location.check_all_values(
session.nav.go_to_loc,
loc_name,
locators['location.select_name'],
tab_locators['context.tab_hostgrps'],
context='location',
)
self.assertIsNotNone(selected)
@run_only_on('sat')
@tier2
def test_positive_add_hostgroup(self):
"""Add a hostgroup by using the location name and hostgroup name
@feature: Locations
@assert: hostgroup is added to location
"""
strategy, value = common_locators['all_values_selection']
with Session(self.browser) as session:
for host_grp_name in generate_strings_list():
with self.subTest(host_grp_name):
loc_name = gen_string('alpha')
host_grp = entities.HostGroup(name=host_grp_name).create()
self.assertEqual(host_grp.name, host_grp_name)
make_loc(session, name=loc_name)
self.assertIsNotNone(self.location.search(loc_name))
self.location.search(loc_name).click()
session.nav.click(tab_locators['context.tab_hostgrps'])
element = session.nav.wait_until_element(
(strategy, value % host_grp_name))
self.assertIsNotNone(element)
@run_only_on('sat')
@tier2
def test_positive_add_org(self):
"""Add a organization by using the location name
@feature: Locations
@assert: organization is added to location
"""
strategy, value = common_locators['entity_deselect']
with Session(self.browser) as session:
for org_name in generate_strings_list():
with self.subTest(org_name):
loc_name = gen_string('alpha')
org = entities.Organization(name=org_name).create()
self.assertEqual(org.name, org_name)
make_loc(session, name=loc_name)
self.assertIsNotNone(self.location.search(loc_name))
self.location.update(
loc_name, new_organizations=[org_name])
self.location.search(loc_name).click()
session.nav.click(
tab_locators['context.tab_organizations'])
element = session.nav.wait_until_element(
(strategy, value % org_name))
self.assertIsNotNone(element)
@run_only_on('sat')
@tier2
def test_add_environment(self):
"""Add environment by using location name and environment name
@feature: Locations
@assert: environment is added
"""
strategy, value = common_locators['entity_deselect']
with Session(self.browser) as session:
for env_name in valid_env_names():
with self.subTest(env_name):
loc_name = gen_string('alpha')
env = entities.Environment(name=env_name).create()
self.assertEqual(env.name, env_name)
make_loc(session, name=loc_name)
self.assertIsNotNone(self.location.search(loc_name))
self.location.update(loc_name, new_envs=[env_name])
self.location.search(loc_name).click()
session.nav.click(tab_locators['context.tab_env'])
element = session.nav.wait_until_element(
(strategy, value % env_name))
self.assertIsNotNone(element)
@run_only_on('sat')
@tier2
def test_add_compresource(self):
"""Add compute resource using the location name and
compute resource name
@feature: Locations
@assert: compute resource is added successfully
"""
strategy, value = common_locators['entity_deselect']
with Session(self.browser) as session:
for resource_name in generate_strings_list():
with self.subTest(resource_name):
loc_name = gen_string('alpha')
url = LIBVIRT_RESOURCE_URL % settings.server.hostname
resource = entities.LibvirtComputeResource(
name=resource_name, url=url).create()
self.assertEqual(resource.name, resource_name)
make_loc(session, name=loc_name)
self.assertIsNotNone(self.location.search(loc_name))
self.location.update(
loc_name, new_resources=[resource_name])
self.location.search(loc_name).click()
session.nav.click(tab_locators['context.tab_resources'])
element = session.nav.wait_until_element(
(strategy, value % resource_name))
self.assertIsNotNone(element)
@run_only_on('sat')
@tier2
def test_positive_add_medium(self):
"""Add medium by using the location name and medium name
@feature: Locations
@assert: medium is added
"""
strategy, value = common_locators['entity_deselect']
with Session(self.browser) as session:
for medium_name in generate_strings_list():
with self.subTest(medium_name):
loc_name = gen_string('alpha')
medium = entities.Media(
name=medium_name,
path_=INSTALL_MEDIUM_URL % gen_string('alpha', 6),
os_family='Redhat',
).create()
self.assertEqual(medium.name, medium_name)
make_loc(session, name=loc_name)
self.assertIsNotNone(self.location.search(loc_name))
self.location.update(loc_name, new_medias=[medium_name])
self.location.search(loc_name).click()
session.nav.click(tab_locators['context.tab_media'])
element = session.nav.wait_until_element(
(strategy, value % medium_name))
self.assertIsNotNone(element)
@run_only_on('sat')
@tier1
def test_positive_check_all_values_template(self):
"""check whether config template has the 'All values' checked.
@feature: Locations
@assert: configtemplate 'All values' checkbox is checked.
"""
loc_name = gen_string('alpha')
with Session(self.browser) as session:
page = session.nav.go_to_loc
make_loc(session, name=loc_name)
self.assertIsNotNone(self.location.search(loc_name))
selected = self.location.check_all_values(
page, loc_name, locators['location.select_name'],
tab_locators['context.tab_template'], context='location')
self.assertIsNotNone(selected)
@run_only_on('sat')
@tier2
def test_positive_add_template(self):
"""Add config template by using location name and config
template name.
@feature: Locations
@assert: config template is added.
"""
strategy, value = common_locators['all_values_selection']
with Session(self.browser) as session:
for template in generate_strings_list():
with self.subTest(template):
loc_name = gen_string('alpha')
make_loc(session, name=loc_name)
self.assertIsNotNone(self.location.search(loc_name))
make_templates(
session,
name=template,
template_path=get_data_file(OS_TEMPLATE_DATA_FILE),
custom_really=True,
template_type='provision',
)
self.assertIsNotNone(self.template.search(template))
self.location.search(loc_name).click()
session.nav.click(tab_locators['context.tab_template'])
element = session.nav.wait_until_element(
(strategy, value % template))
self.assertIsNotNone(element)
@run_only_on('sat')
@tier2
def test_positive_remove_environment(self):
"""Remove environment by using location name & environment name
@feature: Locations
@assert: environment is removed from Location
"""
strategy, value = common_locators['entity_select']
strategy1, value1 = common_locators['entity_deselect']
with Session(self.browser) as session:
for env_name in valid_env_names():
with self.subTest(env_name):
loc_name = gen_string('alpha')
env = entities.Environment(name=env_name).create()
self.assertEqual(env.name, env_name)
set_context(session, org=ANY_CONTEXT['org'])
make_loc(session, name=loc_name, envs=[env_name])
self.location.search(loc_name).click()
session.nav.click(tab_locators['context.tab_env'])
element = session.nav.wait_until_element(
(strategy1, value1 % env_name))
# Item is listed in 'Selected Items' list and not
# 'All Items' list.
self.assertIsNotNone(element)
self.location.update(loc_name, envs=[env_name])
self.location.search(loc_name).click()
session.nav.click(tab_locators['context.tab_env'])
element = session.nav.wait_until_element(
(strategy, value % env_name))
# Item is listed in 'All Items' list and not
# 'Selected Items' list.
self.assertIsNotNone(element)
@run_only_on('sat')
@tier2
def test_positive_remove_subnet(self):
"""Remove subnet by using location name and subnet name
@feature: Locations
@assert: subnet is added then removed
"""
strategy, value = common_locators['entity_select']
strategy1, value1 = common_locators['entity_deselect']
with Session(self.browser) as session:
for subnet_name in generate_strings_list():
with self.subTest(subnet_name):
loc_name = gen_string('alpha')
subnet = entities.Subnet(
name=subnet_name,
network=gen_ipaddr(ip3=True),
mask='255.255.255.0',
).create()
self.assertEqual(subnet.name, subnet_name)
set_context(session, org=ANY_CONTEXT['org'])
make_loc(session, name=loc_name, subnets=[subnet_name])
self.location.search(loc_name).click()
session.nav.click(tab_locators['context.tab_subnets'])
element = session.nav.wait_until_element(
(strategy1, value1 % subnet_name))
# Item is listed in 'Selected Items' list and not
# 'All Items' list.
self.assertIsNotNone(element)
self.location.update(loc_name, subnets=[subnet_name])
self.location.search(loc_name).click()
self.location.click(tab_locators['context.tab_subnets'])
element = session.nav.wait_until_element(
(strategy, value % subnet_name))
# Item is listed in 'All Items' list and not
# 'Selected Items' list.
self.assertIsNotNone(element)
@run_only_on('sat')
@tier2
def test_positive_remove_domain(self):
"""Add a domain to an location and remove it by location name
and domain name
@feature: Locations
@assert: the domain is removed from the location
"""
strategy, value = common_locators['entity_select']
strategy1, value1 = common_locators['entity_deselect']
with Session(self.browser) as session:
for domain_name in generate_strings_list():
with self.subTest(domain_name):
loc_name = gen_string('alpha')
domain = entities.Domain(name=domain_name).create()
self.assertEqual(domain.name, domain_name)
set_context(session, org=ANY_CONTEXT['org'])
make_loc(session, name=loc_name, domains=[domain_name])
self.location.search(loc_name).click()
session.nav.click(tab_locators['context.tab_domains'])
element = session.nav.wait_until_element(
(strategy1, value1 % domain_name))
# Item is listed in 'Selected Items' list and not
# 'All Items' list.
self.assertIsNotNone(element)
self.location.update(loc_name, domains=[domain_name])
self.location.search(loc_name).click()
session.nav.click(tab_locators['context.tab_domains'])
element = session.nav.wait_until_element(
(strategy, value % domain_name))
# Item is listed in 'All Items' list and not
# 'Selected Items' list.
self.assertIsNotNone(element)
@run_only_on('sat')
@tier2
def test_positive_remove_user(self):
"""Create admin users then add user and remove it by using the
location name
@feature: Locations
@assert: The user is added then removed from the location
"""
strategy, value = common_locators['entity_select']
strategy1, value1 = common_locators['entity_deselect']
with Session(self.browser) as session:
# User names does not accept html values
for user_name in generate_strings_list(
length=10,
exclude_types=['html']):
with self.subTest(user_name):
loc_name = gen_string('alpha')
user = entities.User(
login=user_name,
firstname=user_name,
lastname=user_name,
password=gen_string('alpha'),
).create()
self.assertEqual(user.login, user_name)
set_context(session, org=ANY_CONTEXT['org'])
make_loc(session, name=loc_name, users=[user_name])
self.location.search(loc_name).click()
session.nav.click(tab_locators['context.tab_users'])
element = session.nav.wait_until_element(
(strategy1, value1 % user_name))
# Item is listed in 'Selected Items' list and not
# 'All Items' list.
self.assertIsNotNone(element)
self.location.update(loc_name, users=[user_name])
self.location.search(loc_name).click()
session.nav.click(tab_locators['context.tab_users'])
element = session.nav.wait_until_element(
(strategy, value % user_name))
# Item is listed in 'All Items' list and not
# 'Selected Items' list.
self.assertIsNotNone(element)
@run_only_on('sat')
@tier2
def test_positive_remove_hostgroup(self):
"""Add a hostgroup and remove it by using the location name and
hostgroup name
@feature: Locations
@assert: hostgroup is added to location then removed
"""
strategy, value = common_locators['all_values_selection']
with Session(self.browser) as session:
for host_grp_name in generate_strings_list():
with self.subTest(host_grp_name):
loc_name = gen_string('alpha')
host_grp = entities.HostGroup(name=host_grp_name).create()
self.assertEqual(host_grp.name, host_grp_name)
set_context(session, org=ANY_CONTEXT['org'])
make_loc(session, name=loc_name)
self.location.search(loc_name).click()
session.nav.click(tab_locators['context.tab_hostgrps'])
element = session.nav.wait_until_element(
(strategy, value % host_grp_name))
# Item is listed in 'Selected Items' list and not
# 'All Items' list.
self.assertIsNotNone(element)
self.hostgroup.delete(host_grp_name)
self.location.search(loc_name).click()
session.nav.click(tab_locators['context.tab_hostgrps'])
element = session.nav.wait_until_element(
(strategy, value % host_grp_name))
# Item is listed in 'All Items' list and not
# 'Selected Items' list.
self.assertIsNone(element)
@run_only_on('sat')
@tier2
def test_positive_remove_compresource(self):
"""Remove compute resource by using the location name and
compute resource name
@feature: Locations
@assert: compute resource is added then removed
"""
strategy, value = common_locators['entity_select']
strategy1, value1 = common_locators['entity_deselect']
with Session(self.browser) as session:
for resource_name in generate_strings_list():
with self.subTest(resource_name):
loc_name = gen_string('alpha')
url = LIBVIRT_RESOURCE_URL % settings.server.hostname
resource = entities.LibvirtComputeResource(
name=resource_name, url=url
).create()
self.assertEqual(resource.name, resource_name)
set_context(session, org=ANY_CONTEXT['org'])
make_loc(session, name=loc_name, resources=[resource_name])
self.location.search(loc_name).click()
session.nav.click(tab_locators['context.tab_resources'])
element = self.location.wait_until_element(
(strategy1, value1 % resource_name))
# Item is listed in 'Selected Items' list and not
# 'All Items' list.
self.assertIsNotNone(element)
self.location.update(loc_name, resources=[resource_name])
self.location.search(loc_name).click()
session.nav.click(tab_locators['context.tab_resources'])
element = session.nav.wait_until_element(
(strategy, value % resource_name))
# Item is listed in 'All Items' list and not
# 'Selected Items' list.
self.assertIsNotNone(element)
@run_only_on('sat')
@tier2
def test_positive_remove_medium(self):
"""Remove medium by using location name and medium name
@feature: Locations
@assert: medium is added then removed
"""
strategy, value = common_locators['entity_select']
strategy1, value1 = common_locators['entity_deselect']
with Session(self.browser) as session:
for medium_name in generate_strings_list():
with self.subTest(medium_name):
loc_name = gen_string('alpha')
medium = entities.Media(
name=medium_name,
path_=INSTALL_MEDIUM_URL % gen_string('alpha', 6),
os_family='Redhat',
).create()
self.assertEqual(medium.name, medium_name)
set_context(session, org=ANY_CONTEXT['org'])
make_loc(session, name=loc_name, medias=[medium_name])
self.location.search(loc_name).click()
session.nav.click(tab_locators['context.tab_media'])
element = session.nav.wait_until_element(
(strategy1, value1 % medium_name))
# Item is listed in 'Selected Items' list and not
# 'All Items' list.
self.assertIsNotNone(element)
self.location.update(loc_name, medias=[medium_name])
self.location.search(loc_name).click()
session.nav.click(tab_locators['context.tab_media'])
element = session.nav.wait_until_element(
(strategy, value % medium_name))
# Item is listed in 'All Items' list and not
# 'Selected Items' list.
self.assertIsNotNone(element)
@run_only_on('sat')
@tier2
def test_positive_remove_template(self):
"""
Remove config template
@feature: Locations
@assert: config template is added and then removed
"""
strategy, value = common_locators['all_values_selection']
with Session(self.browser) as session:
for template_name in generate_strings_list(length=8):
with self.subTest(template_name):
loc_name = gen_string('alpha')
set_context(session, org=ANY_CONTEXT['org'])
make_templates(
session,
name=template_name,
template_path=get_data_file(OS_TEMPLATE_DATA_FILE),
template_type='provision',
custom_really=True,
)
self.assertIsNotNone(self.template.search(template_name))
make_loc(session, name=loc_name)
self.location.search(loc_name).click()
session.nav.click(tab_locators['context.tab_template'])
element = session.nav.wait_until_element(
(strategy, value % template_name))
# Item is listed in 'Selected Items' list and not
# 'All Items' list.
self.assertIsNotNone(element)
self.template.delete(template_name)
self.location.search(loc_name).click()
session.nav.click(tab_locators['context.tab_template'])
element = session.nav.wait_until_element(
(strategy, value % template_name))
# Item is listed in 'All Items' list and not
# 'Selected Items' list.
self.assertIsNone(element)
| anarang/robottelo | tests/foreman/ui/test_location.py | Python | gpl-3.0 | 34,753 |
"""litchi URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/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. Import the include() function: from django.conf.urls import url, include
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'^admin/', admin.site.urls),
url(r'^captcha/', include('captcha.urls')),
url(r'^session/', include('apps.session.urls', namespace='session')),
]
| enfancemill/litchi | litchi/urls.py | Python | gpl-3.0 | 894 |
# https://www.codewars.com/kata/roman-numerals-encoder/train/python
def solution(n):
# Print the arguments
print('n = {}'.format(n))
roman_blueprint = [] # List of lists to store format structure: [[<letter>, <count>], ...]
result = [] # Store the final roman numeral result
# Calculate for roman numerals
# Calculate the I's -- 1
numI = n % 5 # Do modulo 5, since we want to look at the I's
if (numI == 4): # If the modul result is 4, then we just want 1 roman numeral, before the previous digit
numI = -1 # Set it to '-1' to track the position, and we can use abs() to get the value/count
roman_blueprint.append(['I', numI])
# Calculate the V's -- 5
numV = n % 10 # Do modulo 10, since we want to look at the V's
if (4 <= numV <= 8):
numV = 1
else:
numV = 0
roman_blueprint.append(['V', numV])
# Calculate the X's -- 10
numX = n % 50 # Do modulo 10, since we want to look at the X's
if (numX <= 8):
numX = 0
elif (9 <= numX <= 18): # (0 * 10) + 0 <= (numX - 9) <= (0 * 10) + 9
numX = 1
elif (19 <= numX <= 28): # (1 * 10) + 0 <= (numX - 9) <= (1 * 10) + 9
numX = 2
elif (29 <= numX <= 38): # (2 * 10) + 0 <= (numX - 9) <= (2 * 10) + 9
numX = 3
elif (numX == 39): # (numX - 9) == (3 * 10) + 0
numX = 4
elif (40 <= numX <= 48): # (3 * 10) + 1 <= (numX - 9) <= (3 * 10) + 9
numX = -1
else: # (numX - 9) == (4 * 10) + 0
numX = -2
roman_blueprint.append(['X', numX])
# Calculate the L's -- 50
numL = n % 100 # Do modulo 100, since we want to look at the L's
if (40 <= numL <= 89):
numL = 1
else:
numL = 0
roman_blueprint.append(['L', numL])
# Calculate the C's -- 100
numC = n % 500 # Do modulo 10, since we want to look at the C's
if (numC <= 89):
numC = 0
elif (90 <= numC <= 189): # (0 * 100) + 0 <= (numC - 90) <= (0 * 100) + 99
numC = 1
elif (190 <= numC <= 289): # (1 * 100) + 0 <= (numC - 90) <= (1 * 100) + 99
numC = 2
elif (290 <= numC <= 389): # (2 * 100) + 0 <= (numC - 90) <= (2 * 100) + 99
numC = 3
elif (390 <= numC <= 399): # (3 * 100) + 0 <= (numC - 90) <= (3 * 100) + 9
numC = 4
elif (400 <= numC <= 489): # (3 * 100) + 10 <= (numC - 90) <= (3 * 100) + 99
numC = -1
else: # (4 * 100) + 0 <= (numC - 90) <= (4 * 100) + 9
numC = -2
roman_blueprint.append(['C', numC])
# Calculate the D's -- 500
numD = n % 1000 # Do modulo 1000, since we want to look at the D's
if (400 <= numD <= 899):
numD = 1
else:
numD = 0
roman_blueprint.append(['D', numD])
# Calculate the M's -- 1000
numM = n % 5000 # Do modulo 10, since we want to look at the M's
if (numM <= 899):
numM = 0
elif (900 <= numM <= 1899): # (0 * 1000) + 0 <= (numM - 900) <= (0 * 1000) + 999
numM = 1
elif (1900 <= numM <= 2899): # (1 * 1000) + 0 <= (numM - 900) <= (1 * 1000) + 999
numM = 2
elif (2900 <= numM <= 3899): # (2 * 1000) + 0 <= (numM - 900) <= (2 * 1000) + 999
numM = 3
elif (3900 <= numM <= 4899): # (3 * 1000) + 0 <= (numM - 900) <= (3 * 1000) + 99
numM = 4
else:
numM = 5
roman_blueprint.append(['M', numM])
# Format the output
# Format from largest to smallest
for numeral, count in roman_blueprint[::-1]:
if (count < 0): # We have an M to be used for subtraction
result.insert(-1, numeral)
count = abs(count + 1) # Increment number of positive M's to add, take the ABS value
if (count >= 0): # If we have M's
result.extend([numeral] * count)
# Join the final result
result = ''.join(result)
# Show the final result
print('result = {}'.format(result))
return result | pcampese/codewars | roman_numerals3.py | Python | gpl-3.0 | 3,539 |
################################################################################
## ##
## This file is a part of TADEK. ##
## ##
## TADEK - Test Automation in a Distributed Environment ##
## (http://tadek.comarch.com) ##
## ##
## Copyright (C) 2011 Comarch S.A. ##
## All rights reserved. ##
## ##
## TADEK is free software for non-commercial purposes. For commercial ones ##
## we offer a commercial license. Please check http://tadek.comarch.com for ##
## details or write to tadek-licenses@comarch.com ##
## ##
## You can redistribute it and/or modify it under the terms of the ##
## GNU General Public License as published by the Free Software Foundation, ##
## either version 3 of the License, or (at your option) any later version. ##
## ##
## TADEK 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 TADEK bundled with this file in the file LICENSE. ##
## If not, see http://www.gnu.org/licenses/. ##
## ##
## Please notice that Contributor Agreement applies to any contribution ##
## you make to TADEK. The Agreement must be completed, signed and sent ##
## to Comarch before any contribution is made. You should have received ##
## a copy of Contribution Agreement along with TADEK bundled with this file ##
## in the file CONTRIBUTION_AGREEMENT.pdf or see http://tadek.comarch.com ##
## or write to tadek-licenses@comarch.com ##
## ##
################################################################################
import os
import sys
from tadek import models
from tadek import teststeps
from tadek import testcases
from tadek import testsuites
from tadek.core import locale
from tadek.core.structs import ErrorBox
_DIRS_MAP = {
"models": models,
"teststeps": teststeps,
"testcases": testcases,
"testsuites": testsuites
}
_LOCALE_DIR = "locale"
class NameConflictError(Exception):
'''
Raised when a name conflict module takes place inside some.
'''
def __init__(self, module, name):
Exception.__init__(self, '.'.join([module.__name__, name]))
def add(path, enabled=True):
'''
Adds a location of models and test cases specified by the path.
:param path: A path to a location directory
:type path: string
:param enabled: True if an added location should be enabled, False otherwise
:type enabled: boolean
'''
path = os.path.abspath(path)
if path in _cache:
return None
_cache[path] = enabled
if enabled:
return enable(path)
return []
def remove(path):
'''
Removes a location of models and test cases specified by the path.
:param path: A path to a location directory
:type path: string
'''
path = os.path.abspath(path)
if path not in _cache:
return
disable(path)
del _cache[path]
def get(enabled=None):
'''
Gets a list of all locations.
'''
if enabled is None:
return _cache.keys()
elif enabled:
return [path for path in _cache if _cache[path]]
else:
return [path for path in _cache if not _cache[path]]
def enable(path):
'''
Enables a location of models and test cases specified by the path.
:param path: A path to a location directory
:type path: string
'''
path = os.path.abspath(path)
if path not in _cache:
return None
_cache[path] = True
errors = []
for dirname, module in _DIRS_MAP.iteritems():
errors.extend(_addModuleDir(module, os.path.join(path, dirname)))
# Add a corresponding locale
locale.add(os.path.join(path, _LOCALE_DIR))
if errors:
disable(path)
return errors
def disable(path):
'''
Disables a location of models and test cases specified by the path.
:param path: A path to a location directory
:type path: string
'''
path = os.path.abspath(path)
for dirname, module in _DIRS_MAP.iteritems():
_removeModuleDir(module, os.path.join(path, dirname))
# Remove a corresponding locale
locale.remove(os.path.join(path, _LOCALE_DIR))
_cache[path] = False
def clear():
'''
Clears imported modules from all locations.
'''
for module in _DIRS_MAP.itervalues():
_clearModule(module)
# A locations cache
_cache = {}
# Location directories oriented functions:
def getModels():
'''
Gets a dictionary containing all currently avalaible models modules.
:return: A dictionary with models modules
:rtype: dictionary
'''
content = _getModuleContent(models)
content.pop("__init__", None)
return content
def getSteps():
'''
Gets a dictionary containing all currently avalaible root test steps
modules.
:return: A dictionary with test steps modules
:rtype: dictionary
'''
content = _getModuleContent(teststeps)
content.pop("__init__", None)
return content
def getCases():
'''
Gets a dictionary containing all currently avalaible root test cases
modules.
:return: A dictionary with test cases modules
:rtype: dictionary
'''
content = _getModuleContent(testcases)
content.pop("__init__", None)
return content
def getSuites():
'''
Gets a dictionary containing all currently avalaible root test suites
modules.
:return: A dictionary with test suites modules
:rtype: dictionary
'''
content = _getModuleContent(testsuites)
content.pop("__init__", None)
return content
_MODULE_EXTS = (".py", ".pyc", ".pyo")
def _getDirContent(dir, package=None):
'''
Gets content of the given directory.
'''
content = {}
for file in sorted(os.listdir(dir)):
name = None
path = os.path.join(dir, file)
if os.path.isfile(path):
name, ext = os.path.splitext(file)
if ext not in _MODULE_EXTS or (package and name == "__init__"):
continue
name = '.'.join([package, name]) if package else name
elif os.path.isdir(path):
pkg = False
for ext in _MODULE_EXTS:
if os.path.exists(os.path.join(path, "__init__" + ext)):
pkg = True
break
if not pkg:
continue
name = '.'.join([package, file]) if package else file
content.update(_getDirContent(path, name))
path = os.path.join(path, "__init__" + ext)
if name and name not in content:
content[name] = path
return content
def _getModuleContent(module):
'''
Gets content of the given module from the specified directory.
'''
content = {}
for path in module.__path__:
for name, path in _getDirContent(path).iteritems():
if name not in content:
content[name] = path
return content
def _addModuleDir(module, path):
'''
Adds a directory of the given path to the specified module object.
'''
errors = []
if not os.path.isdir(path) or path is module.__path__:
return errors
content = _getModuleContent(module)
for name in _getDirContent(path):
try:
if name in content:
raise NameConflictError(module, name)
except NameConflictError:
errors.append(ErrorBox(name=name, path=path))
if not errors:
module.__path__.append(path)
return errors
def _clearModule(module, path=None):
'''
Clears the imported module.
'''
patterns = []
if not path:
patterns.append(module.__name__ + '.')
elif path in module.__path__:
for name in _getDirContent(path):
patterns.append('.'.join([module.__name__, name]))
for name in sys.modules.keys():
for pattern in patterns:
if pattern in name:
del sys.modules[name]
break
def _removeModuleDir(module, path):
'''
Removes a directory of the given path from the specified module object.
'''
if path not in module.__path__ or path == module.__path__[0]:
return
_clearModule(module, path)
module.__path__.remove(path)
| tadek-project/tadek-common | tadek/core/location.py | Python | gpl-3.0 | 9,460 |
# Mantid Repository : https://github.com/mantidproject/mantid
#
# Copyright © 2017 ISIS Rutherford Appleton Laboratory UKRI,
# NScD Oak Ridge National Laboratory, European Spallation Source
# & Institut Laue - Langevin
# SPDX - License - Identifier: GPL - 3.0 +
# This file is part of the mantidqt package
#
#
from __future__ import (absolute_import, unicode_literals)
from mantidqt.utils.qt import import_qt
WorkspaceTreeWidget = import_qt('..._common', 'mantidqt.widgets.workspacewidget', 'WorkspaceTreeWidgetSimple')
| mganeva/mantid | qt/python/mantidqt/widgets/workspacewidget/workspacetreewidget.py | Python | gpl-3.0 | 536 |
from ll1_symbols import *
YAML_OUTPUT = """terminals: %s
non-terminals: %s
eof-marker: %s
error-marker: %s
start-symbol: %s
productions: %s
table: %s"""
YAML_OUTPUT_NO_TABLE = """terminals: %s
non-terminals: %s
eof-marker: %s
error-marker: %s
start-symbol: %s
productions: %s"""
class YamlGenerator(object):
"""docstring for yaml_generator"""
def __init__(self, grammar):
self.grammar = grammar
def print_yaml(self, ll1_table = None):
def convert_list_str(a_list):
return "[%s]" % (", ".join(a_list))
def convert_dict_str(a_dict):
return "{%s}" % ", ".join(["%s: %s" % (key, value)
for key, value in a_dict.items()])
def convert_dict_dict_str(a_dict):
return "\n %s" % ("\n ".join(["%s: %s" % (key, convert_dict_str(value))
for key, value in a_dict.items()]))
def convert_dict_list_str(a_dict):
return "{%s}" % (", \n ".join(["%s: %s" % (key, convert_list_str(value))
for key, value in a_dict.items()]))
def convert_dict_dict_list_str(a_dict):
return "\n %s" % ("\n ".join(["%s: %s" % (key, convert_dict_list_str(value))
for key, value in a_dict.items()]))
if ll1_table:
return YAML_OUTPUT % (convert_list_str(list(self.grammar.term)),
convert_list_str(list(self.grammar.non_term)),
EOF,
ERROR_MARKER,
self.grammar.goal,
convert_dict_dict_list_str(self.convert_production()),
convert_dict_dict_str(ll1_table))
else:
return YAML_OUTPUT_NO_TABLE % (convert_list_str(list(self.grammar.term)),
convert_list_str(list(self.grammar.non_term)),
EOF,
ERROR_MARKER,
self.grammar.goal,
convert_dict_dict_list_str(self.convert_production()))
def convert_production(self):
return {idx : {production.left_hand.lexeme : [item.lexeme for item in production.right_hand if item.lexeme is not EPSILON]} for idx, production in enumerate(self.grammar.production)}
| liuxue1990/python-ll1-parser-generator | yaml_generator.py | Python | gpl-3.0 | 1,932 |
"""
Unit tests over SQLite backend for Crash Database
"""
from apport.report import Report
import os
from unittest import TestCase
from sqlite import CrashDatabase
class CrashDatabaseTestCase(TestCase):
def setUp(self):
self.crash_base = os.path.sep + 'tmp'
self.crash_base_url = 'file://' + self.crash_base + '/'
self.crash_path = os.path.join(self.crash_base, 'test.crash')
self.r = Report()
self.r['ExecutablePath'] = '/usr/bin/napoleon-solod'
self.r['Package'] = 'libnapoleon-solo1 1.2-1'
self.r['Signal'] = '11'
self.r['StacktraceTop'] = """foo_bar (x=2) at crash.c:28
d01 (x=3) at crash.c:29
raise () from /lib/libpthread.so.0
<signal handler called>
__frob (x=4) at crash.c:30"""
def tearDown(self):
if os.path.exists(self.crash_path):
os.unlink(self.crash_path)
exe_crash_base = os.path.join(self.crash_base, '1_usr_bin_napoleon-solod')
if os.path.exists(exe_crash_base):
os.unlink(exe_crash_base)
def test_create_db_default(self):
try:
CrashDatabase(None, {})
self.assertTrue(os.path.isfile(os.path.expanduser('~/crashdb.sqlite')))
finally:
os.unlink(os.path.expanduser('~/crashdb.sqlite'))
def test_crashes_base_url(self):
cb = CrashDatabase(None, {'dbfile': ':memory:', 'crashes_base_url': self.crash_base_url})
self.assertEqual(cb.base_url, self.crash_base_url)
def test_crashes_base_url_is_none(self):
cb = CrashDatabase(None, {'dbfile': ':memory:'})
self.assertIsNone(cb.base_url)
def test_upload_download(self):
cb = CrashDatabase(None, {'dbfile': ':memory:', 'crashes_base_url': self.crash_base_url})
crash_id = cb.upload(self.r)
self.assertEqual(crash_id, 1)
report = cb.download(1)
self.assertIsInstance(report, Report)
self.assertIn('Signal', report)
self.assertEqual(report['Signal'], '11')
def test_failed_upload_no_URL(self):
cb = CrashDatabase(None, {'dbfile': ':memory:'})
self.assertRaises(ValueError, cb.upload, self.r)
def test_failed_upload_invalid_URL_scheme(self):
cb = CrashDatabase(None, {'dbfile': ':memory:'})
self.r['_URL'] = 'invalid://scheme/path'
self.assertRaises(ValueError, cb.upload, self.r)
def test_failed_download(self):
cb = CrashDatabase(None, {'dbfile': ':memory:'})
self.assertRaises(Exception, cb.download, 23232)
def test_get_id_url(self):
cb = CrashDatabase(None, {'dbfile': ':memory:'})
self.assertEqual("#1", cb.get_id_url(None, 1))
self.assertEqual("#1: napoleon-solod crashed with SIGSEGV in foo_bar()",
cb.get_id_url(self.r, 1))
def test_update(self):
"""
Test complete update
"""
cb = CrashDatabase(None, {'dbfile': ':memory:', 'crashes_base_url': self.crash_base_url})
crash_id = cb.upload(self.r)
self.r['SourcePackage'] = 'adios'
self.r['Signal'] = u'9'
cb.update(crash_id, self.r, 'a comment to add')
report = cb.download(crash_id)
self.assertIn('SourcePackage', report)
self.assertEqual(report['Signal'], u'9')
def test_update_with_key_filter(self):
"""
Test a partial update
"""
cb = CrashDatabase(None, {'dbfile': ':memory:', 'crashes_base_url': self.crash_base_url})
crash_id = cb.upload(self.r)
self.r['SourcePackage'] = 'adios'
self.r['Signal'] = u'9'
cb.update(crash_id, self.r, 'a comment to add', key_filter=('Package', 'SourcePackage'))
report = cb.download(crash_id)
self.assertIn('SourcePackage', report)
self.assertNotEqual(report['Signal'], u'9')
def test_failed_update_no_URL(self):
cb = CrashDatabase(None, {'dbfile': ':memory:'})
self.r['_URL'] = self.crash_base_url + 'test.crash'
crash_id = cb.upload(self.r)
del self.r['_URL']
self.assertRaises(ValueError, cb.update, *(crash_id, self.r, 'comment'))
def test_get_distro_release(self):
cb = CrashDatabase(None, {'dbfile': ':memory:', 'crashes_base_url': self.crash_base_url})
crash_id = cb.upload(self.r)
self.assertIsNone(cb.get_distro_release(crash_id))
self.r['DistroRelease'] = 'Ubuntu 14.04'
crash_id = cb.upload(self.r)
self.assertEqual(cb.get_distro_release(crash_id), 'Ubuntu 14.04')
def test_get_unretraced(self):
cb = CrashDatabase(None, {'dbfile': ':memory:', 'crashes_base_url': self.crash_base_url})
self.assertEqual(cb.get_unretraced(), [])
crash_id = cb.upload(self.r)
self.assertEqual(cb.get_unretraced(), [crash_id])
self.r['Stacktrace'] = """
#0 0x00007f96dcfb9f77 in __GI_raise (sig=sig@entry=6) at ../nptl/sysdeps/unix/sysv/linux/raise.c:56
resultvar = 0
pid = 1427
selftid = 1427
#1 0x00007f96dcfbd5e8 in __GI_abort () at abort.c:90
save_stage = 2
act = {__sigaction_handler = {sa_handler = 0x0, sa_sigaction = 0x0}, sa_mask = {__val = {140286034336064, 140285996709792, 140285998988405, 5, 0, 752786625060479084, 140285929102568, 140285994568476, 140285996709792, 140285459489344, 140285999015717, 140285994520128, 140285996776629, 140285996776368, 140733249635424, 6}}, sa_flags = 56247888, sa_restorer = 0x18}
sigs = {__val = {32, 0 <repeats 15 times>}}
#2 0x00007f96e0deccbc in smb_panic_default (why=0x7f96e0df8b1c "internal error") at ../lib/util/fault.c:149
No locals.
#3 smb_panic (why=why@entry=0x7f96e0df8b1c "internal error") at ../lib/util/fault.c:162
No locals.
#4 0x00007f96e0dece76 in fault_report (sig=<optimized out>) at ../lib/util/fault.c:77
counter = 1
#5 sig_fault (sig=<optimized out>) at ../lib/util/fault.c:88
No locals.
#6 <signal handler called>
No locals.
#7 0x00007f96b9bae711 in sarray_get_safe (indx=<optimized out>, array=<optimized out>) at /build/buildd/gcc-4.8-4.8.1/src/libobjc/objc-private/sarray.h:237
No locals.
#8 objc_msg_lookup (receiver=0x7f96e3485278, op=0x7f96c0fae240 <_OBJC_SELECTOR_TABLE+128>) at /build/buildd/gcc-4.8-4.8.1/src/libobjc/sendmsg.c:448
No locals.
#9 0x00007f96c0da737a in sogo_table_get_row (table_object=<optimized out>, mem_ctx=0x7f96e33e5940, query_type=MAPISTORE_PREFILTERED_QUERY, row_id=1, data=0x7fff035a4e00) at MAPIStoreSOGo.m:1464
e = <optimized out>
ret = MAPISTORE_SUCCESS
wrapper = <optimized out>
pool = 0x7f96e3485278
table = <optimized out>
rc = 0
__FUNCTION__ = "sogo_table_get_row"
__PRETTY_FUNCTION__ = "sogo_table_get_row"
"""
cb.update(crash_id, self.r, "")
self.assertEqual(cb.get_unretraced(), [])
self.r['Stacktrace'] = """#8 0x00007ff5aae8e159 in ldb_msg_find_ldb_val (msg=<optimised out>, attr_name=<optimised out>) at ../common/ldb_msg.c:399
el = <optimised out>
#9 0x00007ff5aae8e669 in ldb_msg_find_attr_as_string (msg=<optimised out>, attr_name=<optimised out>, default_value=0x0) at ../common/ldb_msg.c:584
v = <optimised out>
#10 0x00007ff5905d0e5f in ?? ()
No symbol table info available.
#11 0x0000000000000081 in ?? ()
No symbol table info available.
#12 0x0000000000000000 in ?? ()
No symbol table info available."""
cb.update(crash_id, self.r, "")
self.assertEqual(cb.get_unretraced(), [crash_id])
def test_get_unfixed(self):
cb = CrashDatabase(None, {'dbfile': ':memory:', 'crashes_base_url': self.crash_base_url})
self.assertEqual(cb.get_unfixed(), set())
crash_id = cb.upload(self.r)
self.assertEqual(cb.get_unfixed(), set([crash_id]))
cb.close_duplicate(self.r, crash_id, crash_id)
self.assertEqual(cb.get_unfixed(), set())
def test_close_duplicate(self):
cb = CrashDatabase(None, {'dbfile': ':memory:', 'crashes_base_url': self.crash_base_url})
crash_id = cb.upload(self.r)
self.assertIsNone(cb.duplicate_of(crash_id))
crash_id2 = cb.upload(self.r)
self.assertIsNone(cb.duplicate_of(crash_id2))
cb.close_duplicate(self.r, crash_id2, crash_id)
self.assertEqual(cb.duplicate_of(crash_id2), crash_id)
# Remove current duplicate thing
cb.close_duplicate(self.r, crash_id2, None)
self.assertIsNone(cb.duplicate_of(crash_id2))
# Tests related with components
def test_app_components_get_set(self):
cb = CrashDatabase(None, {'dbfile': ':memory:', 'crashes_base_url': self.crash_base_url})
crash_id = cb.upload(self.r)
self.assertEqual(cb.get_app_components(crash_id), [])
cb.set_app_components(crash_id, ['sand'])
self.assertEqual(cb.get_app_components(crash_id), ['sand'])
cb.set_app_components(crash_id, ['sand'])
self.assertEqual(cb.get_app_components(crash_id), ['sand'])
def test_app_components_remove(self):
cb = CrashDatabase(None, {'dbfile': ':memory:', 'crashes_base_url': self.crash_base_url})
crash_id = cb.upload(self.r)
self.assertRaises(ValueError, cb.remove_app_component, *(crash_id, 'sand'))
self.assertIsNone(cb.remove_app_component(crash_id))
cb.set_app_components(crash_id, ['sand'])
self.assertIsNone(cb.remove_app_component(crash_id, 'sand'))
self.assertEqual(cb.get_app_components(crash_id), [])
cb.set_app_components(crash_id, ['sand'])
self.assertIsNone(cb.remove_app_component(crash_id))
self.assertEqual(cb.get_app_components(crash_id), [])
| icandigitbaby/openchange | script/bug-analysis/test_sqlite.py | Python | gpl-3.0 | 9,687 |
# -*- coding: utf-8 -*-
from django.test import Client
from django.urls import reverse
from nmkapp import views
from .nmk_unit_test_case import NmkUnitTestCase
class ResultsTests(NmkUnitTestCase):
def test_anon_user(self):
"""
Test result view with anonymous user
"""
self.client = Client()
response = self.client.get(reverse(views.results))
self.assertEqual(response.status_code, 302)
def test_regular_user(self):
"""
Test result view with logged user
"""
self.client = Client()
self.assertTrue(self.client.login(username='kokan@mail.com', password='12345'))
response = self.client.get(reverse(views.results))
self.assertEqual(response.status_code, 200)
| stalker314314/nasa_mala_kladionica | tests/unit/tests_view_results.py | Python | gpl-3.0 | 772 |
# val for type checking (literal or ENUM style)
from pyrser import fmt
from pyrser.type_system.signature import *
from pyrser.type_system.type_name import *
class Val(Signature):
"""
Describe a value signature for the language
"""
nvalues = 0
valuniq = dict()
def __init__(self, value, tret: str):
if not isinstance(value, str):
value = str(value)
self.value = value
if not isinstance(tret, TypeName):
tret = TypeName(tret)
self.tret = tret
k = self.value + "$" + tret
idx = 0
if k not in Val.valuniq:
Val.nvalues += 1
Val.valuniq[k] = Val.nvalues
idx = Val.nvalues
else:
idx = Val.valuniq[k]
super().__init__('$' + str(idx))
def internal_name(self):
"""
Return the unique internal name
"""
unq = super().internal_name()
if self.tret is not None:
unq += "_" + self.tret
return unq
| payet-s/pyrser | pyrser/type_system/val.py | Python | gpl-3.0 | 1,017 |
import time
from unittest import TestCase
from formalign.settings import CHROME_DRIVER, SERVER_URL
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import pyperclip
from helper_funcs.helpers_test import file_to_string
class BasicUserTestCaseChrome(TestCase):
def setUp(self):
self.browser = webdriver.Chrome(
CHROME_DRIVER
)
self.sleep = 0
def tearDown(self):
self.browser.quit()
def test_basic_user_experience(self):
"""
Tests basic user interaction with formalign.eu site
:return:
"""
# Lambda user is a biologist who has to make a nice figure containing a multiple alignment for a presentation.
# She visits the formalign.eu site.
self.browser.get(SERVER_URL + '/')
# User sees she's on the right page because she can see the name of the site in the heading.
self.assertEqual(self.browser.title, 'Formalign.eu Home', self.browser.title)
brand_element = self.browser.find_element_by_css_selector('.navbar-brand')
self.assertEqual('Formalign.eu', brand_element.text)
# She sees a form that says 'Paste in your alignment in FASTA format:'
alignment_input = self.browser.find_element_by_css_selector('textarea#id_align_input')
self.assertIsNotNone(self.browser.find_element_by_css_selector('label[for="id_align_input"]'))
self.assertEqual(
'Alignment (FASTA, clustalw, stockholm or phylip)',
alignment_input.get_attribute('placeholder'),
)
# She sees two radio buttons for DNA and protein
dna_button = self.browser.find_element_by_css_selector('input#id_seq_type_1')
self.assertIsNotNone(dna_button)
protein_button = self.browser.find_element_by_css_selector('input#id_seq_type_0')
self.assertIsNotNone(protein_button)
# She sees that the DNA button is selected by default
self.assertEqual(dna_button.is_selected(), True)
# She clicks the Protein radio button and sees that it gets selected and the DNA button gets unselected
protein_button.click()
self.assertEqual(protein_button.is_selected(), True)
self.assertEqual(dna_button.is_selected(), False)
# She pastes in a protein alignment to see what happens
alignment_string = file_to_string('spa_protein_alignment.fasta')
pyperclip.copy(alignment_string)
alignment_input = self.browser.find_element_by_css_selector('textarea#id_align_input')
alignment_input.send_keys(Keys.CONTROL, 'v')
self.browser.find_element_by_id('submit-align').click()
# Wait for Firefox
time.sleep(self.sleep)
# She is redirected to a page showing the submitted sequences from her alignment and a simple consensus sequence
self.assertEqual(self.browser.title, 'Formalign.eu Sequence Display', self.browser.title)
seq_content = self.browser.find_elements_by_css_selector('.query_seq_display')
self.assertIsNotNone(seq_content)
for f in seq_content:
self.assertTrue(len(f.text) <= 80)
first_seq_info = self.browser.find_elements_by_css_selector('.query_seq_meta')[0]
self.assertEqual(
'NP_175717 NP_175717.1 SPA1-related 4 protein [Arabidopsis thaliana].:',
first_seq_info.text,
first_seq_info.text
)
first_seq_content = self.browser.find_elements_by_css_selector('.query_seq_display')[0]
self.assertIsNotNone(first_seq_content)
self.assertEqual(first_seq_content.text, '-' * 80)
consensus_seq = self.browser.find_elements_by_xpath(
'//div[@class="query_seq bg-color-body"]'
)[-1].find_elements_by_xpath('./p[@class="query_seq_display"]')[0]
self.assertIsNotNone(consensus_seq)
cons_seq = file_to_string('consensus.txt')
self.assertEqual(consensus_seq.text, cons_seq[:80])
consensus_meta = self.browser.find_elements_by_xpath('//h3[@class="query_seq_meta bg-color-body"]')[-1]
self.assertEqual(consensus_meta.text, 'consensus 70%:')
# She is happy with the result, sees a "Render" button and clicks it.
render_button = self.browser.find_element_by_css_selector('button#render-align')
self.assertIsNotNone(render_button)
render_button.click()
# Wait for Firefox
time.sleep(self.sleep)
# She is redirected to the alignment display page
self.assertEqual('Formalign.eu Alignment Display', self.browser.title, self.browser.title)
# She sees the alignment displayed with 80 characters per line in blocks of 10 with sequence ids
s0 = self.browser.find_elements_by_xpath(
'//tr[@class="al_ln"]'
)[10].find_elements_by_xpath('./td[@class="residue S0"]')
s1 = self.browser.find_elements_by_xpath(
'//tr[@class="al_ln"]'
)[10].find_elements_by_xpath('./td[@class="residue S1"]')
self.assertEqual(len(s0) + len(s1), 80)
sep = self.browser.find_elements_by_xpath(
'//tr[@class="al_ln"]'
)[10].find_elements_by_xpath('./td[@class="block_sep"]')
self.assertEqual(len(sep), 8)
# She is quite happy with the result and decides to try with another alignment so she navigates back to the
# home page
home_button = self.browser.find_element_by_css_selector('.navbar-brand')
home_button.click()
self.assertEqual(self.browser.title, 'Formalign.eu Home', self.browser.title)
# She wants to upload a protein stockholm alignment this time from a file
# She clicks the Protein radio button and sees that it gets selected and the DNA button gets unselected
protein_button = self.browser.find_element_by_css_selector('input#id_seq_type_0')
protein_button.click()
self.assertEqual(protein_button.is_selected(), True)
# She sees a file upload button
self.fail('Incomplete Test')
def test_file_upload(self):
# User visits the formalign.eu site
self.browser.get(SERVER_URL + '/')
# She wants to upload a protein stockholm alignment this time from a file
# She clicks the Protein radio button and sees that it gets selected and the DNA button gets unselected
protein_button = self.browser.find_element_by_css_selector('input#id_seq_type_0')
protein_button.click()
self.assertEqual(protein_button.is_selected(), True)
# She sees a file upload button
alignment_input = self.browser.find_element_by_css_selector('file_upload#id_align_input')
alignment_input.click()
# She browses to her file and selects it
# She submits her file
self.browser.find_element_by_id('submit-align').click()
self.fail('Incomplete Test')
| globz-eu/formalign | acceptance_tests/pending_tests/test_basic_user_interaction_pending.py | Python | gpl-3.0 | 6,904 |
#!/usr/bin/env python
import os
from os import path
import logging
import shutil
from sqlalchemy import create_engine
from . import config
from .config import TestBase
import taxtastic
from taxtastic.taxonomy import Taxonomy, TaxonIntegrityError
import taxtastic.ncbi
import taxtastic.utils
log = logging
datadir = config.datadir
echo = False
dbname = config.ncbi_master_db
class TestTaxonomyBase(TestBase):
def setUp(self):
self.engine = create_engine('sqlite:///' + self.dbname, echo=echo)
self.tax = Taxonomy(self.engine)
def tearDown(self):
self.engine.dispose()
class TestAddNode(TestTaxonomyBase):
def setUp(self):
self.dbname = path.join(self.mkoutdir(), 'taxonomy.db')
log.info(self.dbname)
shutil.copyfile(dbname, self.dbname)
super(TestAddNode, self).setUp()
def tearDown(self):
pass
def test01(self):
self.tax.add_node(
tax_id='1280_1',
parent_id='1280',
rank='subspecies',
names=[{'tax_name': 'foo'}],
source_name='ncbi'
)
lineage = self.tax.lineage('1280_1')
self.assertEqual(lineage['tax_id'], '1280_1')
self.assertEqual(lineage['tax_name'], 'foo')
def test02(self):
new_taxid = '1279_1'
new_taxname = 'between genus and species'
children = ['1280', '1281']
self.tax.add_node(
tax_id=new_taxid,
parent_id='1279',
rank='species_group',
names=[{'tax_name': new_taxname}],
children=children,
source_name='foo'
)
lineage = self.tax.lineage(new_taxid)
self.assertTrue(lineage['tax_id'] == new_taxid)
self.assertTrue(lineage['tax_name'] == new_taxname)
for taxid in children:
lineage = self.tax.lineage(taxid)
self.assertTrue(lineage['parent_id'] == new_taxid)
def test03(self):
new_taxid = '1279_1'
new_taxname = 'between genus and species'
children = ['1280', '1281']
self.assertRaises(
TaxonIntegrityError,
self.tax.add_node,
tax_id=new_taxid,
parent_id='1279',
rank='genus',
names=[{'tax_name': new_taxname}],
children=children,
source_name='ncbi')
def test04(self):
# existing node
self.assertRaises(
ValueError,
self.tax.add_node,
tax_id='1280',
parent_id='1279',
rank='species',
names=[{'tax_name': 'I already exist'}],
source_name='ncbi'
)
def test05(self):
self.tax.add_node(
tax_id='1280_1',
parent_id='1280',
rank='subspecies',
names=[
{'tax_name': 'foo', 'is_primary': True},
{'tax_name': 'bar'},
],
source_name='ncbi'
)
lineage = self.tax.lineage('1280_1')
self.assertEqual(lineage['tax_id'], '1280_1')
self.assertEqual(lineage['tax_name'], 'foo')
def test06(self):
# multiple names, none primary
self.assertRaises(
ValueError,
self.tax.add_node,
tax_id='1280_1',
parent_id='1280',
rank='subspecies',
names=[
{'tax_name': 'foo'},
{'tax_name': 'bar'},
],
source_name='ncbi')
def test07(self):
self.tax.add_node(
tax_id='1280_1',
parent_id='1280',
rank='subspecies',
names=[
{'tax_name': 'foo', 'is_primary': True},
{'tax_name': 'bar'},
],
source_name='ncbi',
execute=False
)
self.assertRaises(ValueError, self.tax.lineage, '1280_1')
def test08(self):
# test has_node()
self.assertTrue(self.tax.has_node('1280'))
self.assertFalse(self.tax.has_node('foo'))
class TestAddName(TestTaxonomyBase):
"""
test tax.add_node
"""
def count_names(self, tax_id):
with self.tax.engine.connect() as con:
result = con.execute(
'select count(*) from names where tax_id = ?', (tax_id,))
return result.fetchone()[0]
def count_primary_names(self, tax_id):
with self.tax.engine.connect() as con:
result = con.execute(
'select count(*) from names where tax_id = ? and is_primary',
(tax_id,))
return result.fetchone()[0]
def primary_name(self, tax_id):
with self.tax.engine.connect() as con:
result = con.execute(
'select tax_name from names where tax_id = ? and is_primary',
(tax_id,))
val = result.fetchone()
return val[0] if val else None
def setUp(self):
self.dbname = path.join(self.mkoutdir(), 'taxonomy.db')
log.info(self.dbname)
shutil.copyfile(dbname, self.dbname)
super(TestAddName, self).setUp()
def test_name01(self):
names_before = self.count_names('1280')
self.tax.add_name(tax_id='1280', tax_name='SA', source_name='ncbi')
self.assertEqual(names_before + 1, self.count_names('1280'))
def test_name02(self):
# number of primary names should remain 1
names_before = self.count_names('1280')
self.assertEqual(self.count_primary_names('1280'), 1)
self.tax.add_name(tax_id='1280', tax_name='SA', is_primary=True,
source_name='ncbi')
self.tax.add_name(tax_id='1280', tax_name='SA2', is_primary=True,
source_name='ncbi')
self.assertEqual(names_before + 2, self.count_names('1280'))
self.assertEqual(self.count_primary_names('1280'), 1)
def test_name03(self):
# insertion of duplicate row fails
self.tax.add_name(tax_id='1280', tax_name='SA', is_primary=True,
source_name='ncbi')
self.assertRaises(
ValueError, self.tax.add_name, tax_id='1280', tax_name='SA',
is_primary=True, source_name='ncbi')
self.assertEqual(self.primary_name('1280'), 'SA')
class TestGetSource(TestTaxonomyBase):
def setUp(self):
self.dbname = dbname
super(TestGetSource, self).setUp()
def test01(self):
self.assertRaises(ValueError, self.tax.get_source)
def test02(self):
self.assertRaises(ValueError, self.tax.get_source, 1, 'ncbi')
def test03(self):
result = self.tax.get_source(source_id=1)
self.assertDictEqual(result, {
'description': 'ftp://ftp.ncbi.nih.gov/pub/taxonomy/taxdmp.zip',
'id': 1, 'name': 'ncbi'})
def test04(self):
result = self.tax.get_source(source_name='ncbi')
self.assertDictEqual(result, {
'description': 'ftp://ftp.ncbi.nih.gov/pub/taxonomy/taxdmp.zip',
'id': 1, 'name': 'ncbi'})
def test05(self):
self.assertRaises(ValueError, self.tax.get_source, source_id=2)
class TestAddSource(TestTaxonomyBase):
def setUp(self):
self.dbname = path.join(self.mkoutdir(), 'taxonomy.db')
log.info(self.dbname)
shutil.copyfile(dbname, self.dbname)
super(TestAddSource, self).setUp()
def tearDown(self):
pass
def sources(self):
with self.tax.engine.connect() as con:
result = con.execute('select * from source')
return result.fetchall()
def test01(self):
self.tax.add_source('foo')
self.assertEqual(self.sources()[1], (2, 'foo', None))
def test02(self):
self.tax.add_source('ncbi')
self.assertEqual(
self.sources(),
[(1, 'ncbi', 'ftp://ftp.ncbi.nih.gov/pub/taxonomy/taxdmp.zip')])
def test__node():
engine = create_engine(
'sqlite:///../testfiles/small_taxonomy.db', echo=False)
tax = Taxonomy(engine, taxtastic.ncbi.RANKS)
assert tax._node(None) is None
assert tax._node('91061') == ('1239', 'class')
def test_sibling_of():
engine = create_engine('sqlite:///../testfiles/taxonomy.db', echo=False)
tax = Taxonomy(engine, taxtastic.ncbi.RANKS)
assert tax.sibling_of(None) is None
assert tax.sibling_of('91061') == '186801'
assert tax.sibling_of('1696') is None
def test_child_of():
engine = create_engine(
'sqlite:///../testfiles/small_taxonomy.db', echo=False)
tax = Taxonomy(engine, taxtastic.ncbi.RANKS)
assert tax.child_of(None) is None
assert tax.child_of('1239') == '91061'
assert tax.children_of('1239', 2) == ['91061', '186801']
def test_is_ancestor_of():
engine = create_engine('sqlite:///../testfiles/taxonomy.db', echo=False)
tax = Taxonomy(engine, taxtastic.ncbi.RANKS)
assert tax.is_ancestor_of('1280', '1239')
assert tax.is_ancestor_of(None, '1239') is False
assert tax.is_ancestor_of('1239', None) is False
def test_rank_and_parent():
engine = create_engine('sqlite:///../testfiles/taxonomy.db', echo=False)
tax = Taxonomy(engine, taxtastic.ncbi.RANKS)
assert tax.rank(None) is None
assert tax.rank('1239') == 'phylum'
assert tax.rank('1280') == 'species'
assert tax.parent_id(None) is None
assert tax.parent_id('1239') == '2'
def test_species_below():
engine = create_engine('sqlite:///../testfiles/taxonomy.db', echo=False)
tax = Taxonomy(engine, taxtastic.ncbi.RANKS)
t = tax.species_below('1239')
parent_id, rank = tax._node(t)
for t in [None, '1239', '186801', '1117']:
s = tax.species_below(t)
assert t is None or s is None or tax.is_ancestor_of(s, t)
assert s is None or tax.rank(s) == 'species'
def test_is_below():
assert Taxonomy.is_below('species', 'family')
assert Taxonomy.is_below('family', 'kingdom')
assert not Taxonomy.is_below('kingdom', 'family')
assert Taxonomy.ranks_below('species') == []
assert Taxonomy.ranks_below('family') == ['species', 'genus']
def test_nary_subtree():
engine = create_engine(
'sqlite:///../testfiles/small_taxonomy.db', echo=False)
tax = Taxonomy(engine, taxtastic.ncbi.RANKS)
assert tax.nary_subtree(None) is None
t = tax.nary_subtree('1239')
assert t == ['1280', '372074', '1579', '1580',
'37734', '420335', '166485', '166486']
| fhcrc/taxtastic | tests/test_taxonomy.py | Python | gpl-3.0 | 10,512 |
# Copyright 2016-2021 Peppy Player peppy.player@gmail.com
#
# This file is part of Peppy Player.
#
# Peppy Player is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Peppy Player 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 Peppy Player. If not, see <http://www.gnu.org/licenses/>.
from ui.navigator.language import LanguageNavigator
from ui.screen.screen import Screen, PERCENT_TOP_HEIGHT
from ui.menu.languagemenu import LanguageMenu
from util.config import LABELS, LANGUAGE
class LanguageScreen(Screen):
""" Genre Screen. Extends base Screen class """
def __init__(self, util, change_language, listeners, voice_assistant):
""" Initializer
:param util: utility object
:param listener: screen menu event listener
"""
Screen.__init__(self, util, "", PERCENT_TOP_HEIGHT, voice_assistant)
self.language_menu = LanguageMenu(util, None, self.layout.CENTER)
self.language_menu.add_listener(change_language)
self.add_menu(self.language_menu)
self.label = util.config[LABELS][LANGUAGE]
l_name = util.get_current_language_translation()
txt = self.label + ": " + l_name
self.screen_title.set_text(txt)
self.navigator = LanguageNavigator(util, self.layout.BOTTOM, listeners)
self.add_navigator(self.navigator)
self.link_borders()
def add_screen_observers(self, update_observer, redraw_observer):
""" Add screen observers
:param update_observer: observer for updating the screen
:param redraw_observer: observer to redraw the whole screen
"""
Screen.add_screen_observers(self, update_observer, redraw_observer)
self.language_menu.add_menu_observers(update_observer, redraw_observer, release=False)
self.navigator.add_observers(update_observer, redraw_observer)
| project-owner/Peppy | ui/screen/language.py | Python | gpl-3.0 | 2,333 |
"""Module defining ``Eigensolver`` classes."""
import numpy as np
from gpaw.utilities.blas import axpy
from gpaw.eigensolvers.eigensolver import Eigensolver
from gpaw import extra_parameters
class RMM_DIIS(Eigensolver):
"""RMM-DIIS eigensolver
It is expected that the trial wave functions are orthonormal
and the integrals of projector functions and wave functions
``nucleus.P_uni`` are already calculated
Solution steps are:
* Subspace diagonalization
* Calculation of residuals
* Improvement of wave functions: psi' = psi + lambda PR + lambda PR'
* Orthonormalization"""
def __init__(self, keep_htpsit=True, blocksize=10,
fixed_trial_step=None):
self.fixed_trial_step = fixed_trial_step
Eigensolver.__init__(self, keep_htpsit, blocksize)
def iterate_one_k_point(self, hamiltonian, wfs, kpt):
"""Do a single RMM-DIIS iteration for the kpoint"""
psit_nG, R_nG = self.subspace_diagonalize(hamiltonian, wfs, kpt)
self.timer.start('RMM-DIIS')
if self.keep_htpsit:
self.calculate_residuals(kpt, wfs, hamiltonian, psit_nG,
kpt.P_ani, kpt.eps_n, R_nG)
def integrate(a_G, b_G):
return np.real(wfs.integrate(a_G, b_G, global_integral=False))
comm = wfs.gd.comm
B = self.blocksize
dR_xG = wfs.empty(B, q=kpt.q)
P_axi = wfs.pt.dict(B)
error = 0.0
for n1 in range(0, wfs.bd.mynbands, B):
n2 = n1 + B
if n2 > wfs.bd.mynbands:
n2 = wfs.bd.mynbands
B = n2 - n1
P_axi = dict((a, P_xi[:B]) for a, P_xi in P_axi.items())
dR_xG = dR_xG[:B]
n_x = range(n1, n2)
psit_xG = psit_nG[n1:n2]
if self.keep_htpsit:
R_xG = R_nG[n1:n2]
else:
R_xG = wfs.empty(B, q=kpt.q)
wfs.apply_pseudo_hamiltonian(kpt, hamiltonian, psit_xG, R_xG)
wfs.pt.integrate(psit_xG, P_axi, kpt.q)
self.calculate_residuals(kpt, wfs, hamiltonian, psit_xG,
P_axi, kpt.eps_n[n_x], R_xG, n_x)
for n in n_x:
if kpt.f_n is None:
weight = kpt.weight
else:
weight = kpt.f_n[n]
if self.nbands_converge != 'occupied':
if wfs.bd.global_index(n) < self.nbands_converge:
weight = kpt.weight
else:
weight = 0.0
error += weight * integrate(R_xG[n - n1], R_xG[n - n1])
# Precondition the residual:
self.timer.start('precondition')
ekin_x = self.preconditioner.calculate_kinetic_energy(
psit_xG, kpt)
dpsit_xG = self.preconditioner(R_xG, kpt, ekin_x)
self.timer.stop('precondition')
# Calculate the residual of dpsit_G, dR_G = (H - e S) dpsit_G:
wfs.apply_pseudo_hamiltonian(kpt, hamiltonian, dpsit_xG, dR_xG)
self.timer.start('projections')
wfs.pt.integrate(dpsit_xG, P_axi, kpt.q)
self.timer.stop('projections')
self.calculate_residuals(kpt, wfs, hamiltonian, dpsit_xG,
P_axi, kpt.eps_n[n_x], dR_xG, n_x,
calculate_change=True)
# Find lam that minimizes the norm of R'_G = R_G + lam dR_G
RdR_x = np.array([integrate(dR_G, R_G)
for R_G, dR_G in zip(R_xG, dR_xG)])
dRdR_x = np.array([integrate(dR_G, dR_G) for dR_G in dR_xG])
comm.sum(RdR_x)
comm.sum(dRdR_x)
lam_x = -RdR_x / dRdR_x
if extra_parameters.get('PK', False):
lam_x[:] = np.where(lam_x>0.0, lam_x, 0.2)
# Calculate new psi'_G = psi_G + lam pR_G + lam2 pR'_G
# = psi_G + p((lam+lam2) R_G + lam*lam2 dR_G)
for lam, R_G, dR_G in zip(lam_x, R_xG, dR_xG):
if self.fixed_trial_step is None:
lam2 = lam
else:
lam2 = self.fixed_trial_step
R_G *= lam + lam2
axpy(lam * lam2, dR_G, R_G)
self.timer.start('precondition')
psit_xG[:] += self.preconditioner(R_xG, kpt, ekin_x)
self.timer.stop('precondition')
self.timer.stop('RMM-DIIS')
error = comm.sum(error)
return error, psit_nG
| robwarm/gpaw-symm | gpaw/eigensolvers/rmm_diis_old.py | Python | gpl-3.0 | 4,714 |
# -*- coding:utf-8 -*-
## src/gajim-remote.py
##
## Copyright (C) 2005-2006 Dimitur Kirov <dkirov AT gmail.com>
## Nikos Kouremenos <kourem AT gmail.com>
## Copyright (C) 2005-2014 Yann Leboulanger <asterix AT lagaule.org>
## Copyright (C) 2006 Junglecow <junglecow AT gmail.com>
## Travis Shirk <travis AT pobox.com>
## Copyright (C) 2006-2008 Jean-Marie Traissard <jim AT lapin.org>
## Copyright (C) 2007 Julien Pivotto <roidelapluie AT gmail.com>
##
## This file is part of Gajim.
##
## Gajim 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; version 3 only.
##
## Gajim 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 Gajim. If not, see <http://www.gnu.org/licenses/>.
##
# gajim-remote help will show you the D-BUS API of Gajim
import sys
import locale
import urllib
import signal
signal.signal(signal.SIGINT, signal.SIG_DFL) # ^C exits the application
from common import exceptions
from common import i18n # This installs _() function
from common.i18n import Q_
try:
PREFERRED_ENCODING = locale.getpreferredencoding()
except Exception:
PREFERRED_ENCODING = 'UTF-8'
def send_error(error_message):
'''Writes error message to stderr and exits'''
print(error_message, file=sys.stderr)
sys.exit(1)
try:
import dbus
import dbus.service
import dbus.glib
# test if dbus-x11 is installed
bus = dbus.SessionBus()
except Exception:
print(_('D-Bus is not present on this machine or python module is missing'))
sys.exit(1)
OBJ_PATH = '/org/gajim/dbus/RemoteObject'
INTERFACE = 'org.gajim.dbus.RemoteInterface'
SERVICE = 'org.gajim.dbus'
BASENAME = 'gajim-remote'
class GajimRemote:
def __init__(self):
self.argv_len = len(sys.argv)
# define commands dict. Prototype :
# {
# 'command': [comment, [list of arguments] ]
# }
#
# each argument is defined as a tuple:
# (argument name, help on argument, is mandatory)
#
self.commands = {
'help': [
_('Shows a help on specific command'),
[
#User gets help for the command, specified by this parameter
(_('command'),
_('show help on command'), False)
]
],
'toggle_roster_appearance': [
_('Shows or hides the roster window'),
[]
],
'show_next_pending_event': [
_('Pops up a window with the next pending event'),
[]
],
'list_contacts': [
_('Prints a list of all contacts in the roster. Each contact '
'appears on a separate line'),
[
(Q_('?CLI:account'), _('show only contacts of the given account'),
False)
]
],
'list_accounts': [
_('Prints a list of registered accounts'),
[]
],
'change_status': [
_('Changes the status of account or accounts'),
[
#offline, online, chat, away, xa, dnd, invisible should not be translated
(Q_('?CLI:status'), _('one of: offline, online, chat, away, xa, dnd, invisible. If not set, use account\'s previous status'), False),
(Q_('?CLI:message'), _('status message'), False),
(Q_('?CLI:account'), _('change status of account "account". '
'If not specified, try to change status of all accounts that have '
'"sync with global status" option set'), False)
]
],
'set_priority': [
_('Changes the priority of account or accounts'),
[
(Q_('?CLI:priority'), _('priority you want to give to the account'),
True),
(Q_('?CLI:account'), _('change the priority of the given account. '
'If not specified, change status of all accounts that have'
' "sync with global status" option set'), False)
]
],
'open_chat': [
_('Shows the chat dialog so that you can send messages to a contact'),
[
('jid', _('JID of the contact that you want to chat with'),
True),
(Q_('?CLI:account'), _('if specified, contact is taken from the '
'contact list of this account'), False),
(Q_('?CLI:message'),
_('message content. The account must be specified or ""'),
False)
]
],
'send_chat_message': [
_('Sends new chat message to a contact in the roster. Both OpenPGP key '
'and account are optional. If you want to set only \'account\', '
'without \'OpenPGP key\', just set \'OpenPGP key\' to \'\'.'),
[
('jid', _('JID of the contact that will receive the message'), True),
(Q_('?CLI:message'), _('message contents'), True),
(_('pgp key'), _('if specified, the message will be encrypted '
'using this public key'), False),
(Q_('?CLI:account'), _('if specified, the message will be sent '
'using this account'), False),
]
],
'send_single_message': [
_('Sends new single message to a contact in the roster. Both OpenPGP key '
'and account are optional. If you want to set only \'account\', '
'without \'OpenPGP key\', just set \'OpenPGP key\' to \'\'.'),
[
('jid', _('JID of the contact that will receive the message'), True),
(_('subject'), _('message subject'), True),
(Q_('?CLI:message'), _('message contents'), True),
(_('pgp key'), _('if specified, the message will be encrypted '
'using this public key'), False),
(Q_('?CLI:account'), _('if specified, the message will be sent '
'using this account'), False),
]
],
'send_groupchat_message': [
_('Sends new message to a groupchat you\'ve joined.'),
[
('room_jid', _('JID of the room that will receive the message'), True),
(Q_('?CLI:message'), _('message contents'), True),
(Q_('?CLI:account'), _('if specified, the message will be sent '
'using this account'), False),
]
],
'contact_info': [
_('Gets detailed info on a contact'),
[
('jid', _('JID of the contact'), True)
]
],
'account_info': [
_('Gets detailed info on a account'),
[
('account', _('Name of the account'), True)
]
],
'send_file': [
_('Sends file to a contact'),
[
(_('file'), _('File path'), True),
('jid', _('JID of the contact'), True),
(Q_('?CLI:account'), _('if specified, file will be sent using this '
'account'), False)
]
],
'prefs_list': [
_('Lists all preferences and their values'),
[ ]
],
'prefs_put': [
_('Sets value of \'key\' to \'value\'.'),
[
(_('key=value'), _('\'key\' is the name of the preference, '
'\'value\' is the value to set it to'), True)
]
],
'prefs_del': [
_('Deletes a preference item'),
[
(_('key'), _('name of the preference to be deleted'), True)
]
],
'prefs_store': [
_('Writes the current state of Gajim preferences to the .config '
'file'),
[ ]
],
'remove_contact': [
_('Removes contact from roster'),
[
('jid', _('JID of the contact'), True),
(Q_('?CLI:account'), _('if specified, contact is taken from the '
'contact list of this account'), False)
]
],
'add_contact': [
_('Adds contact to roster'),
[
(_('jid'), _('JID of the contact'), True),
(Q_('?CLI:account'), _('Adds new contact to this account'), False)
]
],
'get_status': [
_('Returns current status (the global one unless account is specified)'),
[
(Q_('?CLI:account'), '', False)
]
],
'get_status_message': [
_('Returns current status message (the global one unless account is specified)'),
[
(Q_('?CLI:account'), '', False)
]
],
'get_unread_msgs_number': [
_('Returns number of unread messages'),
[ ]
],
'start_chat': [
_('Opens \'Start Chat\' dialog'),
[
(Q_('?CLI:account'), _('Starts chat, using this account'), True)
]
],
'send_xml': [
_('Sends custom XML'),
[
('xml', _('XML to send'), True),
('account', _('Account in which the xml will be sent; '
'if not specified, xml will be sent to all accounts'),
False)
]
],
'change_avatar': [
_('Change the avatar'),
[
('picture', _('Picture to use'), True),
('account', _('Account in which the avatar will be set; '
'if not specified, the avatar will be set for all accounts'),
False)
]
],
'handle_uri': [
_('Handle a xmpp:/ uri'),
[
(Q_('?CLI:uri'), _('URI to handle'), True),
(Q_('?CLI:account'), _('Account in which you want to handle it'),
False),
(Q_('?CLI:message'), _('Message content'), False)
]
],
'join_room': [
_('Join a MUC room'),
[
(Q_('?CLI:room'), _('Room JID'), True),
(Q_('?CLI:nick'), _('Nickname to use'), False),
(Q_('?CLI:password'), _('Password to enter the room'), False),
(Q_('?CLI:account'), _('Account from which you want to enter the '
'room'), False)
]
],
'check_gajim_running': [
_('Check if Gajim is running'),
[]
],
'toggle_ipython': [
_('Shows or hides the ipython window'),
[]
],
}
self.sbus = None
if self.argv_len < 2 or sys.argv[1] not in self.commands.keys():
# no args or bad args
send_error(self.compose_help())
self.command = sys.argv[1]
if self.command == 'help':
if self.argv_len == 3:
print(self.help_on_command(sys.argv[2]).encode(
PREFERRED_ENCODING))
else:
print(self.compose_help().encode(PREFERRED_ENCODING))
sys.exit(0)
if self.command == 'handle_uri':
self.handle_uri()
if self.command == 'check_gajim_running':
print(self.check_gajim_running())
sys.exit(0)
self.init_connection()
self.check_arguments()
if self.command == 'contact_info':
if self.argv_len < 3:
send_error(_('Missing argument "contact_jid"'))
try:
res = self.call_remote_method()
except exceptions.ServiceNotAvailable:
# At this point an error message has already been displayed
sys.exit(1)
else:
self.print_result(res)
def print_result(self, res):
"""
Print retrieved result to the output
"""
if res is not None:
if self.command in ('open_chat', 'send_chat_message',
'send_single_message', 'start_chat'):
if self.command in ('send_message', 'send_single_message'):
self.argv_len -= 2
if res is False:
if self.argv_len < 4:
send_error(_('\'%s\' is not in your roster.\n'
'Please specify account for sending the message.') % sys.argv[2])
else:
send_error(_('You have no active account'))
elif self.command == 'list_accounts':
if isinstance(res, list):
for account in res:
print(account)
elif self.command == 'account_info':
if res:
print(self.print_info(0, res, True))
elif self.command == 'list_contacts':
for account_dict in res:
print(self.print_info(0, account_dict, True))
elif self.command == 'prefs_list':
pref_keys = sorted(res.keys())
for pref_key in pref_keys:
result = '%s = %s' % (pref_key, res[pref_key])
print(result)
elif self.command == 'contact_info':
print(self.print_info(0, res, True))
elif res:
print(res)
def check_gajim_running(self):
if not self.sbus:
try:
self.sbus = dbus.SessionBus()
except Exception:
raise exceptions.SessionBusNotPresent
test = False
if hasattr(self.sbus, 'name_has_owner'):
if self.sbus.name_has_owner(SERVICE):
test = True
elif dbus.dbus_bindings.bus_name_has_owner(self.sbus.get_connection(),
SERVICE):
test = True
return test
def init_connection(self):
"""
Create the onnection to the session dbus, or exit if it is not possible
"""
try:
self.sbus = dbus.SessionBus()
except Exception:
raise exceptions.SessionBusNotPresent
if not self.check_gajim_running():
send_error(_('It seems Gajim is not running. So you can\'t use gajim-remote.'))
obj = self.sbus.get_object(SERVICE, OBJ_PATH)
interface = dbus.Interface(obj, INTERFACE)
# get the function asked
self.method = interface.__getattr__(self.command)
def make_arguments_row(self, args):
"""
Return arguments list. Mandatory arguments are enclosed with:
'<', '>', optional arguments - with '[', ']'
"""
s = ''
for arg in args:
if arg[2]:
s += ' <' + arg[0] + '>'
else:
s += ' [' + arg[0] + ']'
return s
def help_on_command(self, command):
"""
Return help message for a given command
"""
if command in self.commands:
command_props = self.commands[command]
arguments_str = self.make_arguments_row(command_props[1])
str_ = _('Usage: %(basename)s %(command)s %(arguments)s \n\t %(help)s')\
% {'basename': BASENAME, 'command': command,
'arguments': arguments_str, 'help': command_props[0]}
if len(command_props[1]) > 0:
str_ += '\n\n' + _('Arguments:') + '\n'
for argument in command_props[1]:
str_ += ' ' + argument[0] + ' - ' + argument[1] + '\n'
return str_
send_error(_('%s not found') % command)
def compose_help(self):
"""
Print usage, and list available commands
"""
s = _('Usage:\n %s command [arguments]\n\nCommand is one of:\n' ) % (
BASENAME)
for command in sorted(self.commands):
s += ' ' + command
for arg in self.commands[command][1]:
if arg[2]:
s += ' <' + arg[0] + '>'
else:
s += ' [' + arg[0] + ']'
s += '\n'
return s
def print_info(self, level, prop_dict, encode_return = False):
"""
Return formated string from data structure
"""
if prop_dict is None or not isinstance(prop_dict, (dict, list, tuple)):
return ''
ret_str = ''
if isinstance(prop_dict, (list, tuple)):
ret_str = ''
spacing = ' ' * level * 4
for val in prop_dict:
if val is None:
ret_str +='\t'
elif isinstance(val, int):
ret_str +='\t' + str(val)
elif isinstance(val, str):
ret_str +='\t' + val
elif isinstance(val, (list, tuple)):
res = ''
for items in val:
res += self.print_info(level+1, items)
if res != '':
ret_str += '\t' + res
elif isinstance(val, dict):
ret_str += self.print_info(level+1, val)
ret_str = '%s(%s)\n' % (spacing, ret_str[1:])
elif isinstance(prop_dict, dict):
for key in prop_dict.keys():
val = prop_dict[key]
spacing = ' ' * level * 4
if isinstance(val, (int, str)):
if val is not None:
val = val.strip()
ret_str += '%s%-10s: %s\n' % (spacing, key, val)
elif isinstance(val, (list, tuple)):
res = ''
for items in val:
res += self.print_info(level+1, items)
if res != '':
ret_str += '%s%s: \n%s' % (spacing, key, res)
elif isinstance(val, dict):
res = self.print_info(level+1, val)
if res != '':
ret_str += '%s%s: \n%s' % (spacing, key, res)
if (encode_return):
try:
ret_str = ret_str.encode(PREFERRED_ENCODING)
except Exception:
pass
return ret_str
def check_arguments(self):
"""
Make check if all necessary arguments are given
"""
argv_len = self.argv_len - 2
args = self.commands[self.command][1]
if len(args) < argv_len:
send_error(_('Too many arguments. \n'
'Type "%(basename)s help %(command)s" for more info') % {
'basename': BASENAME, 'command': self.command})
if len(args) > argv_len:
if args[argv_len][2]:
send_error(_('Argument "%(arg)s" is not specified. \n'
'Type "%(basename)s help %(command)s" for more info') %
{'arg': args[argv_len][0], 'basename': BASENAME,
'command': self.command})
self.arguments = []
i = 0
for arg in sys.argv[2:]:
i += 1
if i < len(args):
self.arguments.append(arg)
else:
# it's latest argument with spaces
self.arguments.append(' '.join(sys.argv[i+1:]))
break
# add empty string for missing args
self.arguments += ['']*(len(args)-i)
def handle_uri(self):
if len(sys.argv) < 3:
send_error(_('No uri given'))
if not sys.argv[2].startswith('xmpp:'):
send_error(_('Wrong uri'))
sys.argv[2] = sys.argv[2][5:]
uri = sys.argv[2]
if not '?' in uri:
self.command = sys.argv[1] = 'open_chat'
return
jid, args = uri.split('?', 1)
try:
jid = urllib.unquote(jid)
except UnicodeDecodeError:
pass
args = args.split(';')
action = None
options = {}
if args:
action = args[0]
for arg in args[1:]:
opt = arg.split('=', 1)
if len(opt) != 2:
continue
options[opt[0]] = opt[1]
if action == 'message':
self.command = sys.argv[1] = 'open_chat'
sys.argv[2] = jid
if 'body' in options:
# Open chat window and paste the text in the input message
# dialog
message = options['body']
try:
message = urllib.unquote(message)
except UnicodeDecodeError:
pass
if len(sys.argv) == 4:
# jid in the sys.argv
sys.argv.append(message)
else:
sys.argv.append('')
sys.argv.append(message)
sys.argv[3] = ''
sys.argv[4] = message
return
sys.argv[2] = jid
if action == 'join':
self.command = sys.argv[1] = 'join_room'
# Move account parameter from position 3 to 5
sys.argv.append('')
sys.argv.append(sys.argv[3])
sys.argv[3] = ''
return
if action == 'roster':
# Add contact to roster
self.command = sys.argv[1] = 'add_contact'
return
sys.exit(0)
def call_remote_method(self):
"""
Calls self.method with arguments from sys.argv[2:]
"""
args = [i.decode(PREFERRED_ENCODING) for i in self.arguments]
args = [dbus.String(i) for i in args]
try:
res = self.method(*args)
return res
except Exception:
raise exceptions.ServiceNotAvailable
return None
if __name__ == '__main__':
GajimRemote()
| irl/gajim | src/gajim-remote.py | Python | gpl-3.0 | 26,570 |
import bpy
from ... base_types.node import AnimationNode
class CombineVectorNode(bpy.types.Node, AnimationNode):
bl_idname = "an_CombineVectorNode"
bl_label = "Combine Vector"
dynamicLabelType = "HIDDEN_ONLY"
def create(self):
self.newInput("Float", "X", "x")
self.newInput("Float", "Y", "y")
self.newInput("Float", "Z", "z")
self.newOutput("Vector", "Vector", "vector")
def drawLabel(self):
label = "<X, Y, Z>"
for axis in "XYZ":
if self.inputs[axis].isUnlinked:
label = label.replace(axis, str(round(self.inputs[axis].value, 4)))
return label
def getExecutionCode(self):
return "vector = Vector((x, y, z))"
| Thortoise/Super-Snake | Blender/animation_nodes-master/nodes/vector/combine_vector.py | Python | gpl-3.0 | 729 |
from os.path import dirname, join, exists, isfile, splitext, basename, isdir, relpath
from nose import SkipTest
from . import BaseTargQC, info
class UnitTests(BaseTargQC):
def test_01_simple(self):
self._test('simple', [self.samples[0]], bams=[self.bams[0]], bed=self.bed4)
def test_02_bed3(self):
self._test('bed3', bams=self.bams, bed=self.bed3)
def test_03_bed4(self):
self._test('bed4', bams=self.bams, bed=self.bed4)
def test_04_bed4_reannotate(self):
self._test('bed4_reannotate', bams=self.bams, bed=self.bed4, reannotate=True)
def test_05_wgs(self):
self._test('wgs', bams=self.bams)
def test_06_threads(self):
self._test('threads', bams=self.bams, bed=self.bed4, threads='2')
def test_07_ipython(self):
self._test('ipython', bams=self.bams, bed=self.bed4, ipython=True, threads='2')
def test_08_debug_and_reuse(self):
self._test('debug_and_reuse', bams=self.bams, bed=self.bed4, debug=True, reuse_intermediate=True)
def test_09_reuse_output(self):
self._test('reuse_output_dir', bams=self.bams, bed=self.bed4, reuse_output_dir=True)
def test_10_full_hg19(self):
raise SkipTest
def test_11_full_hg38(self):
raise SkipTest
# def test_13_api(self):
# import targqc
# import targqc.utilz.reference_data as ref
# from targqc.utilz.file_utils import safe_mkdir
# from targqc.utilz.parallel import ParallelCfg
#
# genome = 'hg19-chr21'
# fai_fpath = ref.get_fai(genome)
# output_dirname = 'api'
# output_dir = join(self.results_dir, output_dirname)
# work_dir = join(output_dir, 'work')
# samples = sorted([targqc.Sample(s.name,
# dirpath=safe_mkdir(join(output_dir, s.name)),
# work_dir=safe_mkdir(join(work_dir, s.name)),
# bam=join(self.syn3_dir, s.bam))
# for s in self.samples], key=lambda _s: _s.key_to_sort())
# parallel_cfg = ParallelCfg(None, None, None, 1, None)
# info('-' * 100)
# targqc.start_targqc(work_dir, output_dir, samples, self.bed4,
# parallel_cfg, self.bwa_path,
# fai_fpath=fai_fpath,
# genome=genome)
# info('-' * 100)
# info('')
#
# info()
# self._check_results(output_dir, self.samples)
| vladsaveliev/TargQC | tests/test.py | Python | gpl-3.0 | 2,453 |
"""
>>> sd = SliceDump()
>>> sd[1]
1
>>> sd[2:5]
slice(2, 5, None)
>>> sd[:2]
slice(None, 2, None)
>>> sd[7:]
slice(7, None, None)
>>> sd[:]
slice(None, None, None)
>>> sd[1:9:3]
slice(1, 9, 3)
>>> sd[1:9:3, 2:3]
(slice(1, 9, 3), slice(2, 3, None))
>>> s = sd[1:9:3]
>>> s.indices(20)
(1, 9, 3)
>>> s.indices(5)
(1, 5, 3)
>>> s.indices(1)
(1, 1, 3)
>>> s.indices(0)
(0, 0, 3)
"""
class SliceDump:
def __getitem__(self, pos):
return pos
| YuxuanLing/trunk | trunk/code/study/python/Fluent-Python-example-code/attic/sequences/slice_dump.py | Python | gpl-3.0 | 581 |
print '''
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10,001st prime number?
'''
def problem():
x,limit = 1,0
while limit != 10001:
x += 1
if isprime(x): limit += 1
print x
problem()
| willybh11/python | projectEuler/problems/e7.py | Python | gpl-3.0 | 287 |
# Copyright (C) 2013 Lunatixz
#
#
# This file is part of PseudoTV.
#
# PseudoTV is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PseudoTV 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 PseudoTV. If not, see <http://www.gnu.org/licenses/>.
import xbmc, xbmcgui, xbmcaddon
import subprocess, os
import time, threading
import datetime, traceback
import sys, re
import urllib
import urllib2
import fanarttv
from Playlist import Playlist
from Globals import *
from Channel import Channel
from ChannelList import ChannelList
from FileAccess import FileLock, FileAccess
from xml.etree import ElementTree as ET
from fanarttv import *
from Downloader import *
class EPGWindow(xbmcgui.WindowXMLDialog):
def __init__(self, *args, **kwargs):
self.focusRow = 0
self.focusIndex = 0
self.focusTime = 0
self.focusEndTime = 0
self.shownTime = 0
self.centerChannel = 0
self.rowCount = 6
self.channelButtons = [None] * self.rowCount
self.buttonCache = []
self.buttonCount = 0
self.actionSemaphore = threading.BoundedSemaphore()
self.lastActionTime = time.time()
self.channelLogos = ''
self.textcolor = "FFFFFFFF"
self.focusedcolor = "FF7d7d7d"
self.clockMode = 0
self.textfont = "font14"
self.startup = time.time()
self.showingInfo = False
self.infoOffset = 0
self.infoOffsetV = 0
self.Downloader = Downloader()
self.log('Using EPG Coloring = ' + str(REAL_SETTINGS.getSetting('EPGcolor_enabled')))
self.AltmediaPath = xbmc.translatePath(os.path.join(ADDON_INFO, 'resources', 'skins', 'default', 'media')) + '/'
#Set skin media folder, else default
if os.path.exists(xbmc.translatePath(os.path.join(ADDON_INFO, 'resources', 'skins', Skin_Select, 'media'))):
self.mediaPath = xbmc.translatePath(os.path.join(ADDON_INFO, 'resources', 'skins', Skin_Select, 'media')) + '/'
else:
self.mediaPath = self.AltmediaPath
self.log('Mediapath is ' + self.mediaPath)
# Use the given focus and non-focus textures if they exist. Otherwise use the defaults.
if os.path.exists(self.mediaPath + BUTTON_FOCUS):
self.textureButtonFocus = self.mediaPath + BUTTON_FOCUS
elif xbmc.skinHasImage(self.mediaPath + BUTTON_FOCUS):
self.textureButtonFocus = self.mediaPath + BUTTON_FOCUS
else:
self.textureButtonFocus = 'pstvlButtonFocus.png'
if os.path.exists(self.mediaPath + BUTTON_NO_FOCUS):
self.textureButtonNoFocus = self.mediaPath + BUTTON_NO_FOCUS
elif xbmc.skinHasImage(self.mediaPath + BUTTON_NO_FOCUS):
self.textureButtonNoFocus = self.mediaPath + BUTTON_NO_FOCUS
else:
self.textureButtonNoFocus = 'pstvlButtonNoFocus.png'
for i in range(self.rowCount):
self.channelButtons[i] = []
self.clockMode = ADDON_SETTINGS.getSetting("ClockMode")
self.toRemove = []
def onFocus(self, controlid):
pass
# set the time labels
def setTimeLabels(self, thetime):
self.log('setTimeLabels')
now = datetime.datetime.fromtimestamp(thetime)
self.getControl(104).setLabel(now.strftime('%A, %b %d'))
delta = datetime.timedelta(minutes=30)
for i in range(3):
if self.clockMode == "0":
self.getControl(101 + i).setLabel(now.strftime("%I:%M%p").lower())
else:
self.getControl(101 + i).setLabel(now.strftime("%H:%M"))
now = now + delta
self.log('setTimeLabels return')
self.log('thetime ' + str(now))
def log(self, msg, level = xbmc.LOGDEBUG):
log('EPGWindow: ' + msg, level)
def logDebug(self, msg, level = xbmc.LOGDEBUG):
if REAL_SETTINGS.getSetting('enable_Debug') == "true":
log('EPGWindow: ' + msg, level)
def onInit(self):
self.log('onInit')
timex, timey = self.getControl(120).getPosition()
timew = self.getControl(120).getWidth()
timeh = self.getControl(120).getHeight()
#Set timebar path, else use alt. path
if os.path.exists(xbmc.translatePath(os.path.join(ADDON_INFO, 'resources', 'skins', Skin_Select, 'media', TIME_BAR))):
self.currentTimeBar = xbmcgui.ControlImage(timex, timey, timew, timeh, self.mediaPath + TIME_BAR)
else:
self.currentTimeBar = xbmcgui.ControlImage(timex, timey, timew, timeh, self.AltmediaPath + TIME_BAR)
self.log('Mediapath Time_Bar = ' + self.mediaPath + TIME_BAR)
self.addControl(self.currentTimeBar)
### Skin labels, Set textcolor, focusedcolor and font. Rowcount todo ###
try:
textcolor = int(self.getControl(100).getLabel(), 16)
if textcolor > 0:
self.textcolor = hex(textcolor)[2:]
self.logDebug("onInit.Self.textcolor = " + str(self.textcolor))
except:
pass
try:
focusedcolor = int(self.getControl(99).getLabel(), 16)
if focusedcolor > 0:
self.focusedcolor = hex(focusedcolor)[2:]
self.logDebug("onInit.Self.focusedcolor = " + str(self.focusedcolor))
except:
pass
try:
self.textfont = self.getControl(105).getLabel()
self.logDebug("onInit.Self.textfont = " + str(self.textfont))
except:
pass
# try:
# self.rowCount = self.getControl(106).getLabel()
# self.logDebug("onInit, Self.rowCount = " + str(self.rowCount))
# except:
# pass
##################################################################
try:
if self.setChannelButtons(time.time(), self.MyOverlayWindow.currentChannel) == False:
self.log('Unable to add channel buttons')
return
curtime = time.time()
self.focusIndex = -1
basex, basey = self.getControl(113).getPosition()
baseh = self.getControl(113).getHeight()
basew = self.getControl(113).getWidth()
# set the button that corresponds to the currently playing show
for i in range(len(self.channelButtons[2])):
left, top = self.channelButtons[2][i].getPosition()
width = self.channelButtons[2][i].getWidth()
left = left - basex
starttime = self.shownTime + (left / (basew / 5400.0))
endtime = starttime + (width / (basew / 5400.0))
if curtime >= starttime and curtime <= endtime:
self.focusIndex = i
self.setFocus(self.channelButtons[2][i])
self.focusTime = int(time.time())
self.focusEndTime = endtime
break
# If nothing was highlighted, just select the first button
if self.focusIndex == -1:
self.focusIndex = 0
self.setFocus(self.channelButtons[2][0])
left, top = self.channelButtons[2][0].getPosition()
width = self.channelButtons[2][0].getWidth()
left = left - basex
starttime = self.shownTime + (left / (basew / 5400.0))
endtime = starttime + (width / (basew / 5400.0))
self.focusTime = int(starttime + 30)
self.focusEndTime = endtime
self.focusRow = 2
self.setShowInfo()
except:
self.log("Unknown EPG Initialization Exception", xbmc.LOGERROR)
self.log(traceback.format_exc(), xbmc.LOGERROR)
try:
self.close()
except:
self.log("Error closing", xbmc.LOGERROR)
self.MyOverlayWindow.sleepTimeValue = 1
self.MyOverlayWindow.startSleepTimer()
return
self.log('onInit return')
# setup all channel buttons for a given time
def setChannelButtons(self, starttime, curchannel, singlerow = -1):
self.log('setChannelButtons ' + str(starttime) + ', ' + str(curchannel))
self.centerChannel = self.MyOverlayWindow.fixChannel(curchannel)
# This is done twice to guarantee we go back 2 channels. If the previous 2 channels
# aren't valid, then doing a fix on curchannel - 2 may result in going back only
# a single valid channel.
curchannel = self.MyOverlayWindow.fixChannel(curchannel - 1, False)
curchannel = self.MyOverlayWindow.fixChannel(curchannel - 1, False)
starttime = self.roundToHalfHour(int(starttime))
self.setTimeLabels(starttime)
self.shownTime = starttime
basex, basey = self.getControl(111).getPosition()
basew = self.getControl(111).getWidth()
tmpx, tmpy = self.getControl(110 + self.rowCount).getPosition()
timex, timey = self.getControl(120).getPosition()
timew = self.getControl(120).getWidth()
timeh = self.getControl(120).getHeight()
basecur = curchannel
self.toRemove.append(self.currentTimeBar)
myadds = []
for i in range(self.rowCount):
if singlerow == -1 or singlerow == i:
self.setButtons(starttime, basecur, i)
myadds.extend(self.channelButtons[i])
basecur = self.MyOverlayWindow.fixChannel(basecur + 1)
basecur = curchannel
for i in range(self.rowCount):
self.getControl(301 + i).setLabel(self.MyOverlayWindow.channels[basecur - 1].name)
basecur = self.MyOverlayWindow.fixChannel(basecur + 1)
for i in range(self.rowCount):
try:
self.getControl(311 + i).setLabel(str(curchannel))
except:
pass
try:
if REAL_SETTINGS.getSetting("ColorEPG") == "true":
self.getControl(321 + i).setImage(self.channelLogos + self.MyOverlayWindow.channels[curchannel - 1].name + '_c.png')
else:
self.getControl(321 + i).setImage(self.channelLogos + self.MyOverlayWindow.channels[curchannel - 1].name + '.png')
except:
pass
curchannel = self.MyOverlayWindow.fixChannel(curchannel + 1)
if time.time() >= starttime and time.time() < starttime + 5400:
dif = int((starttime + 5400 - time.time()))
self.currentTimeBar.setPosition(int((basex + basew - 2) - (dif * (basew / 5400.0))), timey)
else:
if time.time() < starttime:
self.currentTimeBar.setPosition(basex + 2, timey)
else:
self.currentTimeBar.setPosition(basex + basew - 2 - timew, timey)
myadds.append(self.currentTimeBar)
try:
self.removeControls(self.toRemove)
except:
for cntrl in self.toRemove:
try:
self.removeControl(cntrl)
except:
pass
self.addControls(myadds)
self.toRemove = []
self.log('setChannelButtons return')
# round the given time down to the nearest half hour
def roundToHalfHour(self, thetime):
n = datetime.datetime.fromtimestamp(thetime)
delta = datetime.timedelta(minutes=30)
if n.minute > 29:
n = n.replace(minute=30, second=0, microsecond=0)
else:
n = n.replace(minute=0, second=0, microsecond=0)
return time.mktime(n.timetuple())
# create the buttons for the specified channel in the given row
def setButtons(self, starttime, curchannel, row):
self.log('setButtons ' + str(starttime) + ", " + str(curchannel) + ", " + str(row))
try:
curchannel = self.MyOverlayWindow.fixChannel(curchannel)
basex, basey = self.getControl(111 + row).getPosition()
baseh = self.getControl(111 + row).getHeight()
basew = self.getControl(111 + row).getWidth()
chtype = int(ADDON_SETTINGS.getSetting('Channel_' + str(curchannel) + '_type'))
self.lastExitTime = (ADDON_SETTINGS.getSetting("LastExitTime"))
self.log('chtype = ' + str(chtype))
if xbmc.Player().isPlaying() == False:
self.log('No video is playing, not adding buttons')
self.closeEPG()
return False
# Backup all of the buttons to an array
self.toRemove.extend(self.channelButtons[row])
del self.channelButtons[row][:]
# if the channel is paused, then only 1 button needed
nowDate = datetime.datetime.now()
self.log("setbuttonnowtime " + str(nowDate))
if self.MyOverlayWindow.channels[curchannel - 1].isPaused:
self.channelButtons[row].append(xbmcgui.ControlButton(basex, basey, basew, baseh, self.MyOverlayWindow.channels[curchannel - 1].getCurrentTitle() + " (paused)", focusTexture=self.textureButtonFocus, noFocusTexture=self.textureButtonNoFocus, alignment=4, textColor=self.textcolor, focusedColor=self.focusedcolor))
else:
# Find the show that was running at the given time
# Use the current time and show offset to calculate it
# At timedif time, channelShowPosition was playing at channelTimes
# The only way this isn't true is if the current channel is curchannel since
# it could have been fast forwarded or rewinded (rewound)?
if curchannel == self.MyOverlayWindow.currentChannel: #currentchannel epg
#Live TV pull date from the playlist entry
if chtype == 8:
playlistpos = int(xbmc.PlayList(xbmc.PLAYLIST_VIDEO).getposition())
#episodetitle is actually the start time of each show that the playlist gets from channellist.py
tmpDate = self.MyOverlayWindow.channels[curchannel - 1].getItemtimestamp(playlistpos)
self.log("setButtons.setbuttonnowtime2 " + str(tmpDate))
t = time.strptime(tmpDate, '%Y-%m-%d %H:%M:%S')
epochBeginDate = time.mktime(t)
#beginDate = datetime.datetime(t.tm_year, t.tm_mon, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec)
#videotime = (nowDate - beginDate).seconds
videotime = time.time() - epochBeginDate
reftime = time.time()
else:
playlistpos = int(xbmc.PlayList(xbmc.PLAYLIST_VIDEO).getposition())
videotime = xbmc.Player().getTime()
reftime = time.time()
else:
#Live TV pull date from the playlist entry
if chtype == 8:
playlistpos = self.MyOverlayWindow.channels[curchannel - 1].playlistPosition
#playlistpos = int(xbmc.PlayList(xbmc.PLAYLIST_VIDEO).getposition())
#episodetitle is actually the start time of each show that the playlist gets from channellist.py
tmpDate = self.MyOverlayWindow.channels[curchannel - 1].getItemtimestamp(playlistpos)
self.log("setButtons.setbuttonnowtime2 " + str(tmpDate))
t = time.strptime(tmpDate, '%Y-%m-%d %H:%M:%S')
epochBeginDate = time.mktime(t)
#beginDate = datetime.datetime(t.tm_year, t.tm_mon, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec)
#videotime = (nowDate - beginDate).seconds
#loop to ensure we get the current show in the playlist
while epochBeginDate + self.MyOverlayWindow.channels[curchannel - 1].getItemDuration(playlistpos) < time.time():
epochBeginDate += self.MyOverlayWindow.channels[curchannel - 1].getItemDuration(playlistpos)
playlistpos = self.MyOverlayWindow.channels[curchannel - 1].fixPlaylistIndex(playlistpos + 1)
videotime = time.time() - epochBeginDate
reftime = time.time()
else:
playlistpos = self.MyOverlayWindow.channels[curchannel - 1].playlistPosition #everyotherchannel epg
videotime = self.MyOverlayWindow.channels[curchannel - 1].showTimeOffset
reftime = self.MyOverlayWindow.channels[curchannel - 1].lastAccessTime
self.log('videotime & reftime + starttime + channel === ' + str(videotime) + ', ' + str(reftime) + ', ' + str(starttime) + ', ' + str(curchannel))
# normalize reftime to the beginning of the video
reftime -= videotime
while reftime > starttime:
playlistpos -= 1
# No need to check bounds on the playlistpos, the duration function makes sure it is correct
reftime -= self.MyOverlayWindow.channels[curchannel - 1].getItemDuration(playlistpos)
while reftime + self.MyOverlayWindow.channels[curchannel - 1].getItemDuration(playlistpos) < starttime:
reftime += self.MyOverlayWindow.channels[curchannel - 1].getItemDuration(playlistpos)
playlistpos += 1
# create a button for each show that runs in the next hour and a half
endtime = starttime + 5400
totaltime = 0
totalloops = 0
while reftime < endtime and totalloops < 1000:
xpos = int(basex + (totaltime * (basew / 5400.0)))
tmpdur = self.MyOverlayWindow.channels[curchannel - 1].getItemDuration(playlistpos)
shouldskip = False
# this should only happen the first time through this loop
# it shows the small portion of the show before the current one
if reftime < starttime:
tmpdur -= starttime - reftime
reftime = starttime
if tmpdur < 60 * 3:
shouldskip = True
# Don't show very short videos
if self.MyOverlayWindow.hideShortItems and shouldskip == False and chtype <= 7:
if self.MyOverlayWindow.channels[curchannel - 1].getItemDuration(playlistpos) < self.MyOverlayWindow.shortItemLength:
shouldskip = True
tmpdur = 0
else:
nextlen = self.MyOverlayWindow.channels[curchannel - 1].getItemDuration(playlistpos + 1)
prevlen = self.MyOverlayWindow.channels[curchannel - 1].getItemDuration(playlistpos - 1)
if nextlen < 60:
tmpdur += nextlen / 2
if prevlen < 60:
tmpdur += prevlen / 2
width = int((basew / 5400.0) * tmpdur)
if width < 30 and shouldskip == False:
width = 30
tmpdur = int(30.0 / (basew / 5400.0))
if width + xpos > basex + basew:
width = basex + basew - xpos
if shouldskip == False and width >= 30:
mylabel = self.MyOverlayWindow.channels[curchannel - 1].getItemTitle(playlistpos)
mygenre = self.MyOverlayWindow.channels[curchannel - 1].getItemgenre(playlistpos)
chtype = int(ADDON_SETTINGS.getSetting('Channel_' + str(curchannel) + '_type'))
self.logDebug('setButtons.mygenre = ' + str(mygenre))
if REAL_SETTINGS.getSetting('EPGcolor_enabled') == '1':
if FileAccess.exists(EPGGENRE_LOC + mygenre + '.png'):
self.textureButtonNoFocusGenre = (EPGGENRE_LOC + mygenre + '.png')
else:
self.textureButtonNoFocusGenre = (EPGGENRE_LOC + 'Unknown' + '.png')
self.channelButtons[row].append(xbmcgui.ControlButton(xpos, basey, width, baseh, mylabel, focusTexture=self.textureButtonFocus, noFocusTexture=self.textureButtonNoFocusGenre, alignment=4, font=self.textfont, textColor=self.textcolor, focusedColor=self.focusedcolor))
elif REAL_SETTINGS.getSetting('EPGcolor_enabled') == '2':
if FileAccess.exists(EPGGENRE_LOC + str(chtype) + '.png'):
self.textureButtonNoFocusChtype = (EPGGENRE_LOC + str(chtype) + '.png')
else:
self.textureButtonNoFocusGenre = (EPGGENRE_LOC + 'Unknown' + '.png')
self.channelButtons[row].append(xbmcgui.ControlButton(xpos, basey, width, baseh, mylabel, focusTexture=self.textureButtonFocus, noFocusTexture=self.textureButtonNoFocusChtype, alignment=4, font=self.textfont, textColor=self.textcolor, focusedColor=self.focusedcolor))
else:
self.channelButtons[row].append(xbmcgui.ControlButton(xpos, basey, width, baseh, mylabel, focusTexture=self.textureButtonFocus, noFocusTexture=self.textureButtonNoFocus, alignment=4, font=self.textfont, textColor=self.textcolor, focusedColor=self.focusedcolor))
totaltime += tmpdur
reftime += tmpdur
playlistpos += 1
totalloops += 1
if totalloops >= 1000:
self.log("Broken big loop, too many loops, reftime is " + str(reftime) + ", endtime is " + str(endtime))
# If there were no buttons added, show some default button
if len(self.channelButtons[row]) == 0:
self.channelButtons[row].append(xbmcgui.ControlButton(basex, basey, basew, baseh, self.MyOverlayWindow.channels[curchannel - 1].name, focusTexture=self.textureButtonFocus, noFocusTexture=self.textureButtonNoFocus, alignment=4, textColor=self.textcolor, focusedColor=self.focusedcolor))
except:
self.log("Exception in setButtons", xbmc.LOGERROR)
self.log(traceback.format_exc(), xbmc.LOGERROR)
self.log('setButtons return')
return True
def onAction(self, act):
self.log('onAction ' + str(act.getId()))
if self.actionSemaphore.acquire(False) == False:
self.log('Unable to get semaphore')
return
action = act.getId()
try:
if action in ACTION_PREVIOUS_MENU:
self.closeEPG()
if self.showingInfo:
self.infoOffset = 0
self.infoOffsetV = 0
elif action == ACTION_MOVE_DOWN:
self.GoDown()
if self.showingInfo:
self.infoOffsetV -= 1
elif action == ACTION_MOVE_UP:
self.GoUp()
if self.showingInfo:
self.infoOffsetV += 1
elif action == ACTION_MOVE_LEFT:
self.GoLeft()
if self.showingInfo:
self.infoOffset -= 1
elif action == ACTION_MOVE_RIGHT:
self.GoRight()
if self.showingInfo:
self.infoOffset += 1
elif action == ACTION_STOP:
self.closeEPG()
if self.showingInfo:
self.infoOffset = 0
self.infoOffsetV = 0
elif action == ACTION_SELECT_ITEM:
lastaction = time.time() - self.lastActionTime
if self.showingInfo:
self.infoOffset = 0
self.infoOffsetV = 0
if lastaction >= 2:
self.selectShow()
self.closeEPG()
self.lastActionTime = time.time()
elif action == ACTION_MOVE_DOWN:
self.GoDown()
if self.showingInfo:
self.infoOffsetV -= 1
elif action == ACTION_PAGEDOWN:
self.GoPgDown()
elif action == ACTION_MOVE_UP:
self.GoUp()
if self.showingInfo:
self.infoOffsetV += 1
elif action == ACTION_PAGEUP:
self.GoPgUp()
except:
self.log("Unknown EPG Exception", xbmc.LOGERROR)
self.log(traceback.format_exc(), xbmc.LOGERROR)
try:
self.close()
except:
self.log("Error closing", xbmc.LOGERROR)
self.MyOverlayWindow.sleepTimeValue = 1
self.MyOverlayWindow.startSleepTimer()
return
self.actionSemaphore.release()
self.log('onAction return')
def closeEPG(self):
self.log('closeEPG')
try:
self.removeControl(self.currentTimeBar)
self.MyOverlayWindow.startSleepTimer()
except:
pass
self.close()
def onControl(self, control):
self.log('onControl')
# Run when a show is selected, so close the epg and run the show
def onClick(self, controlid):
self.log('onClick')
if self.actionSemaphore.acquire(False) == False:
self.log('Unable to get semaphore')
return
lastaction = time.time() - self.lastActionTime
if lastaction >= 2:
try:
selectedbutton = self.getControl(controlid)
except:
self.actionSemaphore.release()
self.log('onClick unknown controlid ' + str(controlid))
return
for i in range(self.rowCount):
for x in range(len(self.channelButtons[i])):
mycontrol = 0
mycontrol = self.channelButtons[i][x]
if selectedbutton == mycontrol:
self.focusRow = i
self.focusIndex = x
self.selectShow()
self.closeEPG()
self.lastActionTime = time.time()
self.actionSemaphore.release()
self.log('onClick found button return')
return
self.lastActionTime = time.time()
self.closeEPG()
self.actionSemaphore.release()
self.log('onClick return')
def GoPgDown(self):
self.log('GoPgDown')
newchannel = self.centerChannel
for x in range(0, 6):
newchannel = self.MyOverlayWindow.fixChannel(newchannel + 1)
self.setChannelButtons(self.shownTime, self.MyOverlayWindow.fixChannel(newchannel))
self.setProperButton(0)
self.log('GoPgDown return')
def GoPgUp(self):
self.log('GoPgUp')
newchannel = self.centerChannel
for x in range(0, 6):
newchannel = self.MyOverlayWindow.fixChannel(newchannel - 1, False)
self.setChannelButtons(self.shownTime, self.MyOverlayWindow.fixChannel(newchannel))
self.setProperButton(0)
self.log('GoPgUp return')
def GoDown(self):
self.log('goDown')
# change controls to display the proper junks
if self.focusRow == self.rowCount - 1:
self.setChannelButtons(self.shownTime, self.MyOverlayWindow.fixChannel(self.centerChannel + 1))
self.focusRow = self.rowCount - 2
self.setProperButton(self.focusRow + 1)
self.log('goDown return')
def GoUp(self):
self.log('goUp')
# same as godown
# change controls to display the proper junks
if self.focusRow == 0:
self.setChannelButtons(self.shownTime, self.MyOverlayWindow.fixChannel(self.centerChannel - 1, False))
self.focusRow = 1
self.setProperButton(self.focusRow - 1)
self.log('goUp return')
def GoLeft(self):
self.log('goLeft')
basex, basey = self.getControl(111 + self.focusRow).getPosition()
basew = self.getControl(111 + self.focusRow).getWidth()
# change controls to display the proper junks
if self.focusIndex == 0:
left, top = self.channelButtons[self.focusRow][self.focusIndex].getPosition()
width = self.channelButtons[self.focusRow][self.focusIndex].getWidth()
left = left - basex
starttime = self.shownTime + (left / (basew / 5400.0))
self.setChannelButtons(self.shownTime - 1800, self.centerChannel)
curbutidx = self.findButtonAtTime(self.focusRow, starttime + 30)
if(curbutidx - 1) >= 0:
self.focusIndex = curbutidx - 1
else:
self.focusIndex = 0
else:
self.focusIndex -= 1
left, top = self.channelButtons[self.focusRow][self.focusIndex].getPosition()
width = self.channelButtons[self.focusRow][self.focusIndex].getWidth()
left = left - basex
starttime = self.shownTime + (left / (basew / 5400.0))
endtime = starttime + (width / (basew / 5400.0))
self.setFocus(self.channelButtons[self.focusRow][self.focusIndex])
self.setShowInfo()
self.focusEndTime = endtime
self.focusTime = starttime + 30
self.log('goLeft return')
def GoRight(self):
self.log('goRight')
basex, basey = self.getControl(111 + self.focusRow).getPosition()
basew = self.getControl(111 + self.focusRow).getWidth()
# change controls to display the proper junks
if self.focusIndex == len(self.channelButtons[self.focusRow]) - 1:
left, top = self.channelButtons[self.focusRow][self.focusIndex].getPosition()
width = self.channelButtons[self.focusRow][self.focusIndex].getWidth()
left = left - basex
starttime = self.shownTime + (left / (basew / 5400.0))
self.setChannelButtons(self.shownTime + 1800, self.centerChannel)
curbutidx = self.findButtonAtTime(self.focusRow, starttime + 30)
if(curbutidx + 1) < len(self.channelButtons[self.focusRow]):
self.focusIndex = curbutidx + 1
else:
self.focusIndex = len(self.channelButtons[self.focusRow]) - 1
else:
self.focusIndex += 1
left, top = self.channelButtons[self.focusRow][self.focusIndex].getPosition()
width = self.channelButtons[self.focusRow][self.focusIndex].getWidth()
left = left - basex
starttime = self.shownTime + (left / (basew / 5400.0))
endtime = starttime + (width / (basew / 5400.0))
self.setFocus(self.channelButtons[self.focusRow][self.focusIndex])
self.setShowInfo()
self.focusEndTime = endtime
self.focusTime = starttime + 30
self.log('goRight return')
def findButtonAtTime(self, row, selectedtime):
self.log('findButtonAtTime ' + str(row))
basex, basey = self.getControl(111 + row).getPosition()
baseh = self.getControl(111 + row).getHeight()
basew = self.getControl(111 + row).getWidth()
for i in range(len(self.channelButtons[row])):
left, top = self.channelButtons[row][i].getPosition()
width = self.channelButtons[row][i].getWidth()
left = left - basex
starttime = self.shownTime + (left / (basew / 5400.0))
endtime = starttime + (width / (basew / 5400.0))
if selectedtime >= starttime and selectedtime <= endtime:
return i
return -1
# based on the current focus row and index, find the appropriate button in
# the new row to set focus to
def setProperButton(self, newrow, resetfocustime = False):
self.log('setProperButton ' + str(newrow))
self.focusRow = newrow
basex, basey = self.getControl(111 + newrow).getPosition()
baseh = self.getControl(111 + newrow).getHeight()
basew = self.getControl(111 + newrow).getWidth()
for i in range(len(self.channelButtons[newrow])):
left, top = self.channelButtons[newrow][i].getPosition()
width = self.channelButtons[newrow][i].getWidth()
left = left - basex
starttime = self.shownTime + (left / (basew / 5400.0))
endtime = starttime + (width / (basew / 5400.0))
if self.focusTime >= starttime and self.focusTime <= endtime:
self.focusIndex = i
self.setFocus(self.channelButtons[newrow][i])
self.setShowInfo()
self.focusEndTime = endtime
if resetfocustime:
self.focusTime = starttime + 30
self.log('setProperButton found button return')
return
self.focusIndex = 0
self.setFocus(self.channelButtons[newrow][0])
left, top = self.channelButtons[newrow][0].getPosition()
width = self.channelButtons[newrow][0].getWidth()
left = left - basex
starttime = self.shownTime + (left / (basew / 5400.0))
endtime = starttime + (width / (basew / 5400.0))
self.focusEndTime = endtime
if resetfocustime:
self.focusTime = starttime + 30
self.setShowInfo()
self.log('setProperButton return')
def setShowInfo(self):
self.log('setShowInfo')
self.showingInfo = True
basex, basey = self.getControl(111 + self.focusRow).getPosition()
baseh = self.getControl(111 + self.focusRow).getHeight()
basew = self.getControl(111 + self.focusRow).getWidth()
# use the selected time to set the video
left, top = self.channelButtons[self.focusRow][self.focusIndex].getPosition()
width = self.channelButtons[self.focusRow][self.focusIndex].getWidth()
left = left - basex + (width / 2)
starttime = self.shownTime + (left / (basew / 5400.0))
chnoffset = self.focusRow - 2
newchan = self.centerChannel
while chnoffset != 0:
if chnoffset > 0:
newchan = self.MyOverlayWindow.fixChannel(newchan + 1, True)
chnoffset -= 1
else:
newchan = self.MyOverlayWindow.fixChannel(newchan - 1, False)
chnoffset += 1
plpos = self.determinePlaylistPosAtTime(starttime, newchan)
if plpos == -1:
self.log('Unable to find the proper playlist to set from EPG')
return
if REAL_SETTINGS.getSetting("tvdb.enabled") == "true" and REAL_SETTINGS.getSetting("tmdb.enabled") == "true" and REAL_SETTINGS.getSetting("fandb.enabled") == "true":
self.apis = True
else:
self.apis = False
if REAL_SETTINGS.getSetting("art.enable") == "true" or REAL_SETTINGS.getSetting("Live.art.enable") == "true":
if self.infoOffset > 0:
self.getControl(522).setLabel('COMING UP:')
elif self.infoOffset < 0:
self.getControl(522).setLabel('ALREADY SEEN:')
elif self.infoOffset == 0 and self.infoOffsetV == 0:
self.getControl(522).setLabel('NOW WATCHING:')
elif self.infoOffsetV < 0 and self.infoOffset == 0:
self.getControl(522).setLabel('ON NOW:')
elif self.infoOffsetV > 0 and self.infoOffset == 0:
self.getControl(522).setLabel('ON NOW:')
elif self.infoOffset == 0 and self.infoOffsetV == 0:
self.getControl(522).setLabel('NOW WATCHING:')
else:
self.getControl(522).setLabel('NOW WATCHING:')
tvdbid = 0
imdbid = 0
dbid = 0
Artpath = xbmc.translatePath(os.path.join(ART_LOC))
self.logDebug('setShowInfo.Artpath.1 = ' + uni(Artpath))
mediapath = uni(self.MyOverlayWindow.channels[newchan - 1].getItemFilename(plpos))
self.logDebug('setShowInfo.mediapath.1 = ' + uni(mediapath))
chtype = int(ADDON_SETTINGS.getSetting('Channel_' + str(newchan) + '_type'))
genre = uni(self.MyOverlayWindow.channels[newchan - 1].getItemgenre(plpos))
title = uni(self.MyOverlayWindow.channels[newchan - 1].getItemTitle(plpos))
LiveID = uni(self.MyOverlayWindow.channels[newchan - 1].getItemLiveID(plpos))
self.logDebug('setShowInfo.LiveID.1 = ' + uni(LiveID))
try:
type1 = str(self.getControl(507).getLabel())
self.logDebug('setShowInfo.type1 = ' + str(type1))
except:
pass
try:
type2 = str(self.getControl(509).getLabel())
self.logDebug('setShowInfo.type2 = ' + str(type2))
except:
pass
jpg = ['banner', 'fanart', 'folder', 'landscape', 'poster']
png = ['character', 'clearart', 'logo']
if type1 in jpg:
type1EXT = (type1 + '.jpg')
else:
type1EXT = (type1 + '.png')
self.logDebug('setShowInfo.type1.ext = ' + str(type1EXT))
if type2 in jpg:
type2EXT = (type2 + '.jpg')
else:
type2EXT = (type2 + '.png')
self.logDebug('setShowInfo.type2.ext = ' + str(type2EXT))
#rename art types for script.artwork.downloader
arttype1 = type1.replace("folder", "poster").replace("landscape", "thumb").replace("character", "characterart").replace("logo", "clearlogo")
arttype2 = type2.replace("folder", "poster").replace("landscape", "thumb").replace("character", "characterart").replace("logo", "clearlogo")
if not 'LiveID' in LiveID:
try:
LiveLST = LiveID.split("|", 4)
self.logDebug('setShowInfo.LiveLST = ' + str(LiveLST))
imdbid = LiveLST[0]
self.logDebug('setShowInfo.LiveLST.imdbid.1 = ' + str(imdbid))
imdbid = imdbid.split('imdb_', 1)[-1]
self.logDebug('setShowInfo.LiveLST.imdbid.2 = ' + str(imdbid))
tvdbid = LiveLST[1]
self.logDebug('setShowInfo.LiveLST.tvdbid.1 = ' + str(tvdbid))
tvdbid = tvdbid.split('tvdb_', 1)[-1]
self.logDebug('setShowInfo.LiveLST.tvdbid.2 = ' + str(tvdbid))
SBCP = LiveLST[2]
self.logDebug('setShowInfo.LiveLST.SBCP = ' + str(SBCP))
if 'dbid_' in LiveLST[3]:
dbidTYPE = LiveLST[3]
self.logDebug('setShowInfo.LiveLST.dbidTYPE.1 = ' + str(dbidTYPE))
dbidTYPE = dbidTYPE.split('dbid_', 1)[-1]
self.logDebug('setShowInfo.LiveLST.dbidTYPE.2 = ' + str(dbidTYPE))
dbid = dbidTYPE.split(',')[0]
self.logDebug('setShowInfo.LiveLST.dbid = ' + str(dbid))
type = dbidTYPE.split(',', 1)[-1]
self.logDebug('setShowInfo.LiveLST.type = ' + str(type))
if arttype1 == 'thumb' and type == 'tvshow':
arttype1 = ('tv' + arttype1)
if arttype2 == 'thumb' and type == 'tvshow':
arttype2 = ('tv' + arttype2)
if type == 'tvshow':
id = tvdbid
elif type == 'movie':
id = imdbid
else:
Unaired = LiveLST[3]
self.logDebug('setShowInfo.LiveLST.Unaired = ' + str(Unaired))
except:
self.log('setShowInfo.LiveLST Failed')
pass
try:
#Try, and pass if label isn't found (Backward compatibility with PTV Skins)
#Sickbeard/Couchpotato
if SBCP == 'SB':
self.getControl(511).setImage(self.mediaPath + 'SB.png')
elif SBCP == 'CP':
self.getControl(511).setImage(self.mediaPath + 'CP.png')
else:
self.getControl(511).setImage(self.mediaPath + 'NA.png')
except:
self.getControl(511).setImage(self.mediaPath + 'NA.png')
pass
try:
#Try, and pass if label isn't found (Backward compatibility with PTV Skins)
#Unaired/aired
if Unaired == 'NEW':
self.getControl(512).setImage(self.mediaPath + 'NEW.png')
elif Unaired == 'OLD':
self.getControl(512).setImage(self.mediaPath + 'OLD.png')
else:
self.getControl(512).setImage(self.mediaPath + 'NA.png')
except:
self.getControl(512).setImage(self.mediaPath + 'NA.png')
pass
if REAL_SETTINGS.getSetting("art.enable") == "true":
self.log('setShowInfo.Dynamic artwork enabled')
if chtype <= 7:
mediapathSeason, filename = os.path.split(mediapath)
self.logDebug('setShowInfo.mediapathSeason = ' + uni(mediapathSeason))
mediapathSeries = os.path.dirname(mediapathSeason)
self.logDebug('setShowInfo.mediapathSeries = ' + uni(mediapathSeries))
mediapathSeries1 = ascii(mediapathSeries + '/' + type1EXT)
mediapathSeason1 = ascii(mediapathSeason + '/' + type1EXT)
if FileAccess.exists(mediapathSeries1):
self.getControl(508).setImage(mediapathSeries1)
elif FileAccess.exists(mediapathSeason1):
self.getControl(508).setImage(mediapathSeason1)
else:
self.getControl(508).setImage(self.mediaPath + type1 + '.png')
# if REAL_SETTINGS.getSetting("EnableDown") == "1" and (REAL_SETTINGS.getSetting("TVFileSys") == "0" or REAL_SETTINGS.getSetting("MovieFileSys") == "0") and self.apis == True:
# self.Downloader.ArtDownloader(type, id, type1, type1EXT, Mpath1, Ipath1)
# elif REAL_SETTINGS.getSetting("EnableDown") == "1" and (REAL_SETTINGS.getSetting("TVFileSys") == "1" or REAL_SETTINGS.getSetting("MovieFileSys") == "1") and self.apis == True:
# self.Downloader.ArtDownloader(type, id, type2, type2EXT, Mpath1, Ipath1)
if REAL_SETTINGS.getSetting("EnableDown") == "2" and REAL_SETTINGS.getSetting("EnableDownSilent") == "false" and chtype != 7:
xbmc.executebuiltin('XBMC.runscript(script.artwork.downloader, mode=gui, mediatype='+type+', dbid='+dbid+', '+arttype1+')')
elif REAL_SETTINGS.getSetting("EnableDown") == "2" and REAL_SETTINGS.getSetting("EnableDownSilent") == "true" and chtype != 7:
xbmc.executebuiltin('XBMC.runscript(script.artwork.downloader, silent=true, mediatype='+type+', dbid='+dbid+', '+arttype1+')')
mediapathSeries2 = ascii(mediapathSeries + '/' + type2EXT)
mediapathSeason2 = ascii(mediapathSeason + '/' + type2EXT)
if FileAccess.exists(mediapathSeries2):
self.getControl(510).setImage(mediapathSeries2)
elif FileAccess.exists(mediapathSeason2):
self.getControl(510).setImage(mediapathSeason2)
else:
self.getControl(510).setImage(self.mediaPath + type2 + '.png')
# if REAL_SETTINGS.getSetting("EnableDown") == "1" and (REAL_SETTINGS.getSetting("TVFileSys") == "0" or REAL_SETTINGS.getSetting("MovieFileSys") == "0") and self.apis == True:
# self.Downloader.ArtDownloader(type, id, type2, type2EXT, Mpath2, Ipath2)
# elif REAL_SETTINGS.getSetting("EnableDown") == "1" and (REAL_SETTINGS.getSetting("TVFileSys") == "1" or REAL_SETTINGS.getSetting("MovieFileSys") == "1") and self.apis == True:
# self.Downloader.ArtDownloader(type, id, type2, type2EXT, Mpath2, Ipath2)
if REAL_SETTINGS.getSetting("EnableDown") == "2" and REAL_SETTINGS.getSetting("EnableDownSilent") == "false" and chtype != 7:
xbmc.executebuiltin('XBMC.runscript(script.artwork.downloader, mode=gui, mediatype='+type+', dbid='+dbid+', '+arttype2+')')
elif REAL_SETTINGS.getSetting("EnableDown") == "2" and REAL_SETTINGS.getSetting("EnableDownSilent") == "true" and chtype != 7:
xbmc.executebuiltin('XBMC.runscript(script.artwork.downloader, silent=true, mediatype='+type+', dbid='+dbid+', '+arttype2+')')
#LiveTV w/ TVDBID via Fanart.TV
elif chtype == 8:
if REAL_SETTINGS.getSetting('Live.art.enable') == 'true' and self.apis == True:
try:
print '1'
# if tvdbid != 0 and genre != 'Movie': #TV
# elif imdbid != 0 and genre == 'Movie':#Movie
except:
self.getControl(508).setImage(self.mediaPath + type1 + '.png')
self.getControl(510).setImage(self.mediaPath + type2 + '.png')
pass
else:#fallback all artwork because live art disabled
self.getControl(508).setImage(self.mediaPath + type1 + '.png')
self.getControl(510).setImage(self.mediaPath + type2 + '.png')
elif chtype == 9:
self.getControl(508).setImage(self.mediaPath + 'EPG.Internet.508.png')
self.getControl(510).setImage(self.mediaPath + 'EPG.Internet.510.png')
elif chtype == 10:
self.getControl(508).setImage(self.mediaPath + 'EPG.Youtube.508.png')
self.getControl(510).setImage(self.mediaPath + 'EPG.Youtube.510.png')
elif chtype == 11:
self.getControl(508).setImage(self.mediaPath + 'EPG.RSS.508.png')
self.getControl(510).setImage(self.mediaPath + 'EPG.RSS.510.png')
elif chtype == 13:
self.getControl(508).setImage(self.mediaPath + 'EPG.LastFM.508.png')
self.getControl(510).setImage(self.mediaPath + 'EPG.LastFM.510.png')
self.getControl(500).setLabel(self.MyOverlayWindow.channels[newchan - 1].getItemTitle(plpos))
#code to display "Live TV" instead of date (date does confirm sync)
#if chtype == 8:
# self.getControl(501).setLabel("LiveTV")
#else:
self.getControl(501).setLabel(self.MyOverlayWindow.channels[newchan - 1].getItemEpisodeTitle(plpos))
self.getControl(502).setLabel(self.MyOverlayWindow.channels[newchan - 1].getItemDescription(plpos))
if REAL_SETTINGS.getSetting("ColorEPG") == "true":
self.getControl(503).setImage(self.channelLogos + ascii(self.MyOverlayWindow.channels[newchan - 1].name) + '_c.png')
else:
self.getControl(503).setImage(self.channelLogos + ascii(self.MyOverlayWindow.channels[newchan - 1].name) + '.png')
self.log('setShowInfo return')
# using the currently selected button, play the proper shows
def selectShow(self):
self.log('selectShow')
basex, basey = self.getControl(111 + self.focusRow).getPosition()
baseh = self.getControl(111 + self.focusRow).getHeight()
basew = self.getControl(111 + self.focusRow).getWidth()
# use the selected time to set the video
left, top = self.channelButtons[self.focusRow][self.focusIndex].getPosition()
width = self.channelButtons[self.focusRow][self.focusIndex].getWidth()
left = left - basex + (width / 2)
starttime = self.shownTime + (left / (basew / 5400.0))
chnoffset = self.focusRow - 2
newchan = self.centerChannel
nowDate = datetime.datetime.now()
while chnoffset != 0:
if chnoffset > 0:
newchan = self.MyOverlayWindow.fixChannel(newchan + 1, True)
chnoffset -= 1
else:
newchan = self.MyOverlayWindow.fixChannel(newchan - 1, False)
chnoffset += 1
plpos = self.determinePlaylistPosAtTime(starttime, newchan)
chtype = int(ADDON_SETTINGS.getSetting('Channel_' + str(newchan) + '_type'))
if plpos == -1:
self.log('Unable to find the proper playlist to set from EPG', xbmc.LOGERROR)
return
timedif = (time.time() - self.MyOverlayWindow.channels[newchan - 1].lastAccessTime)
pos = self.MyOverlayWindow.channels[newchan - 1].playlistPosition
showoffset = self.MyOverlayWindow.channels[newchan - 1].showTimeOffset
#code added for "LiveTV" types
#Get the Start time of the show from "episodeitemtitle"
#we just passed this from channellist.py ; just a fill in to get value
#Start at the beginning of the playlist get the first epoch date
#position pos of the playlist convert the string add until we get to the current item in the playlist
if chtype == 8:
tmpDate = self.MyOverlayWindow.channels[newchan - 1].getItemtimestamp(pos)
self.log("selectshow tmpdate " + str(tmpDate))
t = time.strptime(tmpDate, '%Y-%m-%d %H:%M:%S')
epochBeginDate = time.mktime(t)
#beginDate = datetime.datetime(t.tm_year, t.tm_mon, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec)
#loop till we get to the current show
while epochBeginDate + self.MyOverlayWindow.channels[newchan - 1].getItemDuration(pos) < time.time():
epochBeginDate += self.MyOverlayWindow.channels[newchan - 1].getItemDuration(pos)
pos = self.MyOverlayWindow.channels[newchan - 1].fixPlaylistIndex(pos + 1)
self.log('live tv while loop')
# adjust the show and time offsets to properly position inside the playlist
else:
while showoffset + timedif > self.MyOverlayWindow.channels[newchan - 1].getItemDuration(pos):
self.log('duration ' + str(self.MyOverlayWindow.channels[newchan - 1].getItemDuration(pos)))
timedif -= self.MyOverlayWindow.channels[newchan - 1].getItemDuration(pos) - showoffset
pos = self.MyOverlayWindow.channels[newchan - 1].fixPlaylistIndex(pos + 1)
showoffset = 0
self.log('pos + plpos ' + str(pos) +', ' + str(plpos))
if self.MyOverlayWindow.currentChannel == newchan:
if plpos == xbmc.PlayList(xbmc.PLAYLIST_MUSIC).getposition():
self.log('selectShow return current show')
return
if chtype == 8:
self.log('selectShow return current LiveTV channel')
return
if pos != plpos:
if chtype == 8:
self.log('selectShow return different LiveTV channel')
return
else:
self.MyOverlayWindow.channels[newchan - 1].setShowPosition(plpos)
self.MyOverlayWindow.channels[newchan - 1].setShowTime(0)
self.MyOverlayWindow.channels[newchan - 1].setAccessTime(time.time())
self.MyOverlayWindow.newChannel = newchan
self.log('selectShow return')
def determinePlaylistPosAtTime(self, starttime, channel):
self.log('determinePlaylistPosAtTime ' + str(starttime) + ', ' + str(channel))
channel = self.MyOverlayWindow.fixChannel(channel)
chtype = int(ADDON_SETTINGS.getSetting('Channel_' + str(channel) + '_type'))
self.lastExitTime = ADDON_SETTINGS.getSetting("LastExitTime")
nowDate = datetime.datetime.now()
# if the channel is paused, then it's just the current item
if self.MyOverlayWindow.channels[channel - 1].isPaused:
self.log('determinePlaylistPosAtTime paused return')
return self.MyOverlayWindow.channels[channel - 1].playlistPosition
else:
# Find the show that was running at the given time
# Use the current time and show offset to calculate it
# At timedif time, channelShowPosition was playing at channelTimes
# The only way this isn't true is if the current channel is curchannel since
# it could have been fast forwarded or rewinded (rewound)?
if channel == self.MyOverlayWindow.currentChannel: #currentchannel epg
#Live TV pull date from the playlist entry
if chtype == 8:
playlistpos = int(xbmc.PlayList(xbmc.PLAYLIST_VIDEO).getposition())
#episodetitle is actually the start time of each show that the playlist gets from channellist.py
tmpDate = self.MyOverlayWindow.channels[channel - 1].getItemtimestamp(playlistpos)
self.log("setbuttonnowtime2 " + str(tmpDate))
t = time.strptime(tmpDate, '%Y-%m-%d %H:%M:%S')
epochBeginDate = time.mktime(t)
#beginDate = datetime.datetime(t.tm_year, t.tm_mon, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec)
#videotime = (nowDate - beginDate).seconds
videotime = time.time() - epochBeginDate
reftime = time.time()
else:
playlistpos = int(xbmc.PlayList(xbmc.PLAYLIST_VIDEO).getposition())
videotime = xbmc.Player().getTime()
reftime = time.time()
else:
#Live TV pull date from the playlist entry
if chtype == 8:
playlistpos = self.MyOverlayWindow.channels[channel - 1].playlistPosition
#playlistpos = int(xbmc.PlayList(xbmc.PLAYLIST_VIDEO).getposition())
#episodetitle is actually the start time of each show that the playlist gets from channellist.py
tmpDate = self.MyOverlayWindow.channels[channel - 1].getItemtimestamp(playlistpos)
self.log("setbuttonnowtime2 " + str(tmpDate))
t = time.strptime(tmpDate, '%Y-%m-%d %H:%M:%S')
epochBeginDate = time.mktime(t)
#beginDate = datetime.datetime(t.tm_year, t.tm_mon, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec)
#videotime = (nowDate - beginDate).seconds
while epochBeginDate + self.MyOverlayWindow.channels[channel - 1].getItemDuration(playlistpos) < time.time():
epochBeginDate += self.MyOverlayWindow.channels[channel - 1].getItemDuration(playlistpos)
playlistpos = self.MyOverlayWindow.channels[channel - 1].fixPlaylistIndex(playlistpos + 1)
videotime = time.time() - epochBeginDate
self.log('videotime ' + str(videotime))
reftime = time.time()
else:
playlistpos = self.MyOverlayWindow.channels[channel - 1].playlistPosition
videotime = self.MyOverlayWindow.channels[channel - 1].showTimeOffset
reftime = self.MyOverlayWindow.channels[channel - 1].lastAccessTime
# normalize reftime to the beginning of the video
reftime -= videotime
while reftime > starttime:
playlistpos -= 1
reftime -= self.MyOverlayWindow.channels[channel - 1].getItemDuration(playlistpos)
while reftime + self.MyOverlayWindow.channels[channel - 1].getItemDuration(playlistpos) < starttime:
reftime += self.MyOverlayWindow.channels[channel - 1].getItemDuration(playlistpos)
playlistpos += 1
self.log('determinePlaylistPosAtTime return' + str(self.MyOverlayWindow.channels[channel - 1].fixPlaylistIndex(playlistpos)))
return self.MyOverlayWindow.channels[channel - 1].fixPlaylistIndex(playlistpos)
| DrSpaceMonkey/script.pseudotv.live | resources/lib/EPGWindow.py | Python | gpl-3.0 | 58,386 |
'''Created by rj as part of the Pytnam Project'''
from analysis.Reportable import Reportable
class HighPassFilter(Reportable):
def return_as_node(self):
pass
# TODO
| pytnam/pytnam | analysis/processing/HighPassFilter.py | Python | gpl-3.0 | 181 |
#!/usr/bin/python
#coding: utf8
import sys, struct
data_size = 2*1024*1024
if len(sys.argv) != 3:
print 'Using: ./pack_usb.py input.bin output.bin'
sys.exit(0)
fin = file(sys.argv[1], 'rb')
data = fin.read()
print 'Size: %d bytes' % len(data)
if len(data) > data_size-2:
print 'Error: too big'
sys.exit(0)
data += b'\xa5'*(data_size-2-len(data))
fout = file(sys.argv[-1], 'wb')
fout.write(data)
checksum = sum([struct.unpack('<H', data[i:i+2])[0] for i in range(0, len(data), 2)]) % 0x10000
#fout.write(b'\0'*(data_size-2-len(data)))
print 'Checksum: 0x%04x' % checksum
fout.write(struct.pack('<H', (0x1aa55-checksum)%0x10000))
fout.close()
| petrmikheev/miksys | miksys_soft/pack_usb.py | Python | gpl-3.0 | 662 |
####################################################################################################
#
# PySpice - A Spice Package for Python
# Copyright (C) 2014 Fabrice Salvaire
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
####################################################################################################
####################################################################################################
import os
import subprocess
####################################################################################################
def file_name_has_extension(file_name, extension):
return file_name.endswith(extension)
####################################################################################################
def file_extension(filename):
# index = filename.rfind(os.path.extsep)
# if index == -1:
# return None
# else:
# return filename[index:]
return os.path.splitext(filename)[1]
####################################################################################################
def run_shasum(filename, algorithm=1, text=False, binary=False, portable=False):
if algorithm not in (1, 224, 256, 384, 512, 512224, 512256):
raise ValueError
args = ['shasum', '--algorithm=' + str(algorithm)]
if text:
args.append('--text')
elif binary:
args.append('--binary')
elif portable:
args.append('--portable')
args.append(filename)
output = subprocess.check_output(args)
shasum = output[:output.find(' ')]
return shasum
####################################################################################################
class Path:
##############################################
def __init__(self, path):
self._path = str(path)
##############################################
def __bool__(self):
return os.path.exists(self._path)
##############################################
def __str__(self):
return self._path
##############################################
@property
def path(self):
return self._path
##############################################
def is_absolut(self):
return os.path.isabs(self._path)
##############################################
def absolut(self):
return self.clone_for_path(os.path.abspath(self._path))
##############################################
def normalise(self):
return self.clone_for_path(os.path.normpath(self._path))
##############################################
def normalise_case(self):
return self.clone_for_path(os.path.normcase(self._path))
##############################################
def expand_vars_and_user(self):
return self.clone_for_path(os.path.expandvars(os.path.expanduser(self._path)))
##############################################
def real_path(self):
return self.clone_for_path(os.path.realpath(self._path))
##############################################
def relative_to(self, directory):
return self.clone_for_path(os.path.relpath(self._path, str(directory)))
##############################################
def clone_for_path(self, path):
return self.__class__(path)
##############################################
def split(self):
return self._path.split(os.path.sep)
##############################################
def directory_part(self):
return Directory(os.path.dirname(self._path))
##############################################
def filename_part(self):
return os.path.basename(self._path)
##############################################
def is_directory(self):
return os.path.isdir(self._path)
##############################################
def is_file(self):
return os.path.isfile(self._path)
##############################################
@property
def inode(self):
return os.stat(self._path).st_ino
##############################################
@property
def creation_time(self):
return os.stat(self._path).st_ctime
####################################################################################################
class Directory(Path):
##############################################
def __bool__(self):
return super().__nonzero__() and self.is_directory()
##############################################
def join_directory(self, directory):
return self.__class__(os.path.join(self._path, str(directory)))
##############################################
def join_filename(self, filename):
return File(filename, self._path)
##############################################
def iter_file(self, followlinks=False):
for root, directories, files in os.walk(self._path, followlinks=followlinks):
for filename in files:
yield File(filename, root)
##############################################
def iter_directories(self, followlinks=False):
for root, directories, files in os.walk(self._path, followlinks=followlinks):
for directory in directories:
yield Path(os.path.join(root, directory))
####################################################################################################
class File(Path):
default_shasum_algorithm = 256
##############################################
def __init__(self, filename, path=''):
super().__init__(os.path.join(str(path), str(filename)))
self._filename = self.filename_part()
if not self._filename:
raise ValueError
self._directory = self.directory_part()
self._shasum = None # lazy computation
##############################################
def __bool__(self):
return super().__nonzero__() and os.path.isfile(self._path)
##############################################
@property
def directory(self):
return self._directory
##############################################
@property
def filename(self):
return self._filename
##############################################
@property
def extension(self):
return file_extension(self._filename)
##############################################
@property
def shasum(self):
if self._shasum is None:
return self.compute_shasum()
else:
return self._shasum
##############################################
def compute_shasum(self, algorithm=None):
if algorithm is None:
algorithm = self.default_shasum_algorithm
self._shasum = run_shasum(self._path, algorithm, portable=True)
return self._shasum
####################################################################################################
#
# End
#
####################################################################################################
| thomaslima/PySpice | PySpice/Tools/File.py | Python | gpl-3.0 | 7,812 |
from .stt import ApiRobot
from .stt import BingRobot
from .stt import WatsonRobot
from .stt import WitaiRobot
from .stt import GoogleRobot
class RobotFactory:
@staticmethod
def produce(config, speaker, actions):
configSTT = config['stt']
if configSTT == 'bing':
return BingRobot(config['bing'], speaker, actions)
if configSTT == 'watson':
return WatsonRobot(config['watson-stt'], speaker, actions)
if configSTT == 'witai':
return WitaiRobot(config['witai-stt'], speaker, actions)
if configSTT == 'google':
return GoogleRobot(config['google-stt'], speaker, actions)
return ApiRobot(config['apiai'], speaker, actions)
| lowdev/alfred | robot/robotFactory.py | Python | gpl-3.0 | 721 |
import threading
import time
from lib.Message import Message
class Bot(threading.Thread):
controller = None
username = None
message = None
status = False
event = None
counter = 0
def __init__ (self, controller, username):
"""
"""
self.controller = controller
self.username = username
self.event = threading.Condition()
super().__init__(group=None)
#
#
#
def getUsername(self):
"""
"""
return self.username
#
#
#
def matchMessage(self, message):
"""
"""
return message.getSenderUsername() == self.getUsername()
| GiovanniCardamone/tg-client_2 | lib/bot/Bot.py | Python | gpl-3.0 | 789 |
""" Module matching %GC compo distribution b/w fg and bg. """
import sys
import random
from Bio import SeqIO
from utils import GC
def fg_GC_bins(fg_file):
"""
Compute G+C content for all sequences in the foreground.
It computes the %GC content and store the information in a list. To each
G+C percentage bin, we associate the number of sequences falling in the
corresponding bin.
Return lists of GC contents, GC bins, and lengths distrib.
"""
stream = open(fg_file)
gc_bins = [0] * 101
gc_list = []
lengths = []
for record in SeqIO.parse(stream, "fasta"):
gc = GC(record.seq)
gc_list.append(gc)
gc_bins[gc] += 1
lengths.append(len(record.seq))
stream.close()
return gc_list, gc_bins, lengths
def fg_len_GC_bins(fg_file):
"""
Compute G+C content for all sequences in the foreground.
Computes %GC contant and store the information in a list. To each G+C
percentage bin, we associate the number of sequences falling in the
corresponding bin.
Return lists of GC contents, GC bins, and lengths distrib.
"""
stream = open(fg_file)
gc_bins = []
for _ in range(0, 101):
gc_bins.append({})
gc_list = []
lengths = []
for record in SeqIO.parse(stream, "fasta"):
gc = GC(record.seq)
gc_list.append(gc)
length = len(record)
lengths.append(length)
if length in gc_bins[gc]:
gc_bins[gc][length] += 1
else:
gc_bins[gc][length] = 1
stream.close()
return gc_list, gc_bins, lengths
def print_rec(rec, stream):
""" Print a record to a stream output. """
stream.write("{0}\n".format(rec.format("fasta")))
def print_in_bg_dir(gc_bins, bg_dir, with_len=False):
""" Print the sequences in the bg directory in bin files. """
for percent in xrange(0, 101):
with open("{0}/bg_bin_{1}.txt".format(bg_dir, percent), 'w') as stream:
if with_len:
for length in gc_bins[percent]:
for rec in gc_bins[percent][length]:
print_rec(rec, stream)
else:
for rec in gc_bins[percent]:
print_rec(rec, stream)
def bg_GC_bins(bg_file, bg_dir):
"""
Compute G+C content for all sequences in the background.
Compute and store the GC information in a list. To each G+C percentage bin,
we associate the corresponding sequence names.
Files representing the binning are stored in the "bg_dir" directory.
Return lists of GC contents, GC bins, and lengths distrib.
"""
stream = open(bg_file)
gc_bins = []
gc_list = []
lengths = []
for _ in xrange(0, 101):
gc_bins.append([])
for record in SeqIO.parse(stream, "fasta"):
gc = GC(record.seq)
gc_list.append(gc)
gc_bins[gc].append(record)
lengths.append(len(record.seq))
stream.close()
print_in_bg_dir(gc_bins, bg_dir)
return gc_list, gc_bins, lengths
def bg_len_GC_bins(bg_file, bg_dir):
"""
Compute G+C content for all sequences in the background.
Compute and store the %GC information in a list. To each G+C percentage
bin, we associate the corresponding sequence names.
Return lists of GC contents, GC bins, and lengths distrib.
"""
stream = open(bg_file)
gc_bins = []
gc_list = []
lengths = []
for _ in range(0, 101):
gc_bins.append({})
for record in SeqIO.parse(stream, "fasta"):
gc = GC(record.seq)
gc_list.append(gc)
if len(record) in gc_bins[gc]:
gc_bins[gc][len(record)].append(record)
else:
gc_bins[gc][len(record)] = [record]
lengths.append(len(record.seq))
stream.close()
print_in_bg_dir(gc_bins, bg_dir, True)
return gc_list, gc_bins, lengths
def get_bins_from_bg_dir(bg_dir, percent):
""" Return the sequences from the corresponding bin file. """
with open("{0}/bg_bin_{1:d}.txt".format(bg_dir, percent)) as stream:
bin_seq = []
for record in SeqIO.parse(stream, "fasta"):
bin_seq.append(record)
return bin_seq
def generate_sequences(fg_bins, bg_bins, bg_dir, nfold):
"""
Choose randomly the background sequences in each bin of %GC.
Follow the same distribution as the one of foreground sequences with a
nfold ratio.
Return the list of %GC and length distrib.
"""
lengths = []
gc_list = []
for percent in range(0, 101):
if fg_bins[percent]:
random.seed()
try:
nb = fg_bins[percent] * nfold
if bg_bins:
bin_seq = bg_bins[percent]
else:
bin_seq = get_bins_from_bg_dir(bg_dir, percent)
sample = random.sample(bin_seq, nb)
gc_list.extend([percent] * nb)
except ValueError:
sys.stderr.write("""*** WARNING ***
Sample larger than population for {0:d}% G+C content:
{1:d} needed and {2:d} obtained\n""".format(
percent, fg_bins[percent] * nfold, len(bin_seq)))
sample = bin_seq
gc_list.extend([percent] * len(bin_seq))
for r in sample:
print r.format("fasta"),
lengths.append(len(r.seq))
return gc_list, lengths
def extract_seq_rec(size, nb, bg_keys, bg, accu, index):
"""
Extract "nb" sequences with sizes equal to "size" nt.
We try to get exact size or as close as possible to "size" nt. This is a
tail recursive function with the accumulator "accu" looking for sizes
"bg_keys" in the bg set "bg".
Return the accumulator and the number of found sequences.
"""
if not (bg_keys and nb): # End of the recursion since we have no sequence
# in the bg or enough retrieved (nb=0)
return accu, nb
if index > len(bg_keys) - 1:
return extract_seq_rec(size, nb, bg_keys, bg, accu, index - 1)
if not bg_keys: # No more size in the background to be checked so return
# what was in the previous size bin
if bg[bg_keys[index - 1]]:
random.shuffle(bg[bg_keys[index - 1]])
accu.extend(bg[bg_keys[index - 1]][0:nb])
bg[bg_keys[index - 1]] = bg[index - 1][nb:]
return accu, nb - len(bg[bg_keys[index - 1]][0:nb])
else:
return accu, nb
if bg_keys[index] >= size: # No need to go further in the different sizes
# within the background
if (index == 0 or not bg[bg_keys[index - 1]] or
bg_keys[index] - size < size - bg_keys[index - 1]): # Which
# size is the closest to the expected one? => we go for the current one
# if YES
random.shuffle(bg[bg_keys[index]])
accu.extend(bg[bg_keys[index]][0:nb])
new_nb = nb - len(bg[bg_keys[index]][0:nb])
if bg[bg_keys[index]][nb:]: # Check that there is sequences in the
# background for this size bin
bg[bg_keys[index]] = bg[bg_keys[index]][nb:]
return extract_seq_rec(size, new_nb, bg_keys, bg, accu, index)
else:
bg[bg_keys[index]] = bg[bg_keys[index]][nb:]
del bg_keys[index]
return extract_seq_rec(size, new_nb, bg_keys, bg, accu, index)
else: # The previous size was the closest
random.shuffle(bg[bg_keys[index - 1]])
accu.extend(bg[bg_keys[index - 1]][0:nb])
new_nb = nb - len(bg[bg_keys[index - 1]][0:nb])
if bg[bg_keys[index - 1]][nb:]: # Check that there is sequences in
# the background for this size bin
bg[bg_keys[index - 1]] = bg[bg_keys[index - 1]][nb:]
return extract_seq_rec(size, new_nb, bg_keys, bg, accu, index)
else:
bg[bg_keys[index - 1]] = bg[bg_keys[index - 1]][nb:]
del bg_keys[index - 1]
return extract_seq_rec(size, new_nb, bg_keys, bg, accu,
index - 1)
elif index == len(bg_keys) - 1:
random.shuffle(bg[bg_keys[index]])
accu.extend(bg[bg_keys[index]][0:nb])
new_nb = nb - len(bg[bg_keys[index]][0:nb])
if bg[bg_keys[index]][nb:]:
bg[bg_keys[index]] = bg[bg_keys[index]][nb:]
return extract_seq_rec(size, new_nb, bg_keys, bg, accu, index)
else:
bg[bg_keys[index]] = bg[bg_keys[index]][nb:]
del bg_keys[index]
return extract_seq_rec(size, new_nb, bg_keys, bg, accu, index)
else:
return extract_seq_rec(size, nb, bg_keys, bg, accu, index + 1)
def get_bins_len_from_bg_dir(bg_dir, percent):
""" Return the sequences from the corresponding bin file. """
with open("{0}/bg_bin_{1:d}.txt".format(bg_dir, percent)) as stream:
bin_seq = {}
for record in SeqIO.parse(stream, "fasta"):
length = len(record)
if length in bin_seq:
bin_seq[length].append(record)
else:
bin_seq[length] = [record]
return bin_seq
def generate_len_sequences(fg, bg, bg_dir, nfold):
"""
Extract the sequences from the bg with similar sizes as in the fg.
Return the %GC list and length distrib.
"""
sys.setrecursionlimit(10000)
random.seed()
lengths = []
gc_list = []
for percent in range(0, 101):
if fg[percent]:
nb = sum(fg[percent].values()) * nfold
sequences = []
for size in fg[percent].keys():
nb_to_retrieve = fg[percent][size] * nfold
if bg:
bg_bins = bg[percent]
else:
bg_bins = get_bins_len_from_bg_dir(bg_dir, percent)
bg_keys = sorted(bg_bins.keys())
seqs, _ = extract_seq_rec(size, nb_to_retrieve, bg_keys,
bg_bins, [], 0)
sequences.extend(seqs)
nb_match = len(sequences)
gc_list.extend([percent] * nb_match)
if nb_match != nb:
sys.stderr.write("""*** WARNING ***
Sample larger than population for {0:d}% G+C content:
{1:d} needed and {2:d} obtained\n""".format(percent,
nb,
nb_match))
for s in sequences:
lengths.append(len(s))
print "{0:s}".format(s.format("fasta")),
return gc_list, lengths
| wassermanlab/BiasAway | GC_compo_matching.py | Python | gpl-3.0 | 10,757 |
import logging
from errbot import BotPlugin, botcmd, SeparatorArgParser, ShlexArgParser
from errbot.backends.base import RoomNotJoinedError
log = logging.getLogger(__name__)
class ChatRoom(BotPlugin):
connected = False
def callback_connect(self):
self.log.info('Connecting bot chatrooms')
if not self.connected:
self.connected = True
for room in self.bot_config.CHATROOM_PRESENCE:
self.log.debug('Try to join room %s', repr(room))
try:
self._join_room(room)
except Exception:
# Ensure failure to join a room doesn't crash the plugin
# as a whole.
self.log.exception(f'Joining room {repr(room)} failed')
def _join_room(self, room):
username = self.bot_config.CHATROOM_FN
password = None
if isinstance(room, (tuple, list)):
room, password = room # unpack
self.log.info('Joining room %s with username %s and pass ***.', room, username)
else:
self.log.info('Joining room %s with username %s.', room, username)
self.query_room(room).join(username=self.bot_config.CHATROOM_FN, password=password)
def deactivate(self):
self.connected = False
super().deactivate()
@botcmd(split_args_with=SeparatorArgParser())
def room_create(self, message, args):
"""
Create a chatroom.
Usage:
!room create <room>
Examples (XMPP):
!room create example-room@chat.server.tld
Examples (IRC):
!room create #example-room
"""
if len(args) < 1:
return "Please tell me which chatroom to create."
room = self.query_room(args[0])
room.create()
return f'Created the room {room}.'
@botcmd(split_args_with=ShlexArgParser())
def room_join(self, message, args):
"""
Join (creating it first if needed) a chatroom.
Usage:
!room join <room> [<password>]
Examples (XMPP):
!room join example-room@chat.server.tld
!room join example-room@chat.server.tld super-secret-password
Examples (IRC):
!room join #example-room
!room join #example-room super-secret-password
!room join #example-room "password with spaces"
"""
arglen = len(args)
if arglen < 1:
return "Please tell me which chatroom to join."
args[0].strip()
room_name, password = (args[0], None) if arglen == 1 else (args[0], args[1])
room = self.query_room(room_name)
if room is None:
return f'Cannot find room {room_name}.'
room.join(username=self.bot_config.CHATROOM_FN, password=password)
return f'Joined the room {room_name}.'
@botcmd(split_args_with=SeparatorArgParser())
def room_leave(self, message, args):
"""
Leave a chatroom.
Usage:
!room leave <room>
Examples (XMPP):
!room leave example-room@chat.server.tld
Examples (IRC):
!room leave #example-room
"""
if len(args) < 1:
return 'Please tell me which chatroom to leave.'
self.query_room(args[0]).leave()
return f'Left the room {args[0]}.'
@botcmd(split_args_with=SeparatorArgParser())
def room_destroy(self, message, args):
"""
Destroy a chatroom.
Usage:
!room destroy <room>
Examples (XMPP):
!room destroy example-room@chat.server.tld
Examples (IRC):
!room destroy #example-room
"""
if len(args) < 1:
return "Please tell me which chatroom to destroy."
self.query_room(args[0]).destroy()
return f'Destroyed the room {args[0]}.'
@botcmd(split_args_with=SeparatorArgParser())
def room_invite(self, message, args):
"""
Invite one or more people into a chatroom.
Usage:
!room invite <room> <identifier1> [<identifier2>, ..]
Examples (XMPP):
!room invite room@conference.server.tld bob@server.tld
Examples (IRC):
!room invite #example-room bob
"""
if len(args) < 2:
return 'Please tell me which person(s) to invite into which room.'
self.query_room(args[0]).invite(*args[1:])
return f'Invited {", ".join(args[1:])} into the room {args[0]}.'
@botcmd
def room_list(self, message, args):
"""
List chatrooms the bot has joined.
Usage:
!room list
Examples:
!room list
"""
rooms = [str(room) for room in self.rooms()]
if len(rooms):
rooms_str = '\n\t'.join(rooms)
return f"I'm currently in these rooms:\n\t{rooms_str}"
else:
return "I'm not currently in any rooms."
@botcmd(split_args_with=ShlexArgParser())
def room_occupants(self, message, args):
"""
List the occupants in a given chatroom.
Usage:
!room occupants <room 1> [<room 2> ..]
Examples (XMPP):
!room occupants room@conference.server.tld
Examples (IRC):
!room occupants #example-room #another-example-room
"""
if len(args) < 1:
yield "Please supply a room to list the occupants of."
return
for room in args:
try:
occupants = [o.person for o in self.query_room(room).occupants]
occupants_str = "\n\t".join(map(str, occupants))
yield f'Occupants in {room}:\n\t{occupants_str}.'
except RoomNotJoinedError as e:
yield f'Cannot list occupants in {room}: {e}.'
@botcmd(split_args_with=ShlexArgParser())
def room_topic(self, message, args):
"""
Get or set the topic for a room.
Usage:
!room topic <room> [<new topic>]
Examples (XMPP):
!room topic example-room@chat.server.tld
!room topic example-room@chat.server.tld "Err rocks!"
Examples (IRC):
!room topic #example-room
!room topic #example-room "Err rocks!"
"""
arglen = len(args)
if arglen < 1:
return "Please tell me which chatroom you want to know the topic of."
if arglen == 1:
try:
topic = self.query_room(args[0]).topic
except RoomNotJoinedError as e:
return f'Cannot get the topic for {args[0]}: {e}.'
if topic is None:
return f'No topic is set for {args[0]}.'
else:
return f'Topic for {args[0]}: {topic}.'
else:
try:
self.query_room(args[0]).topic = args[1]
except RoomNotJoinedError as e:
return f'Cannot set the topic for {args[0]}: {e}.'
return f"Topic for {args[0]} set."
def callback_message(self, msg):
try:
if msg.is_direct:
username = msg.frm.person
if username in self.bot_config.CHATROOM_RELAY:
self.log.debug('Message to relay from %s.', username)
body = msg.body
rooms = self.bot_config.CHATROOM_RELAY[username]
for roomstr in rooms:
self.send(self.query_room(roomstr), body)
elif msg.is_group:
fr = msg.frm
chat_room = str(fr.room)
if chat_room in self.bot_config.REVERSE_CHATROOM_RELAY:
users_to_relay_to = self.bot_config.REVERSE_CHATROOM_RELAY[chat_room]
self.log.debug('Message to relay to %s.', users_to_relay_to)
body = f'[{fr.person}] {msg.body}'
for user in users_to_relay_to:
self.send(user, body)
except Exception as e:
self.log.exception(f'crashed in callback_message {e}')
| gbin/err | errbot/core_plugins/chatRoom.py | Python | gpl-3.0 | 8,056 |
import os
import gflags
from textwrap import dedent
import hashlib
import zipfile
from ..exceptions import UsageError
from ..Bunch import Bunch
from ..TreeScanner import TreeScanner
from ..PakManifest import PakManifest, PakFile, PakFolder
def help():
return dedent("""\
Command Usage: pak install pkg_name-1.0.pak /target/path
""")
def run(args):
if len(args) != 2:
raise UsageError("Got %d arguments, but I only expected 2 (%s)" % (len(args), ' '.join(args)))
else:
pak_path, target_path = args
# Validate target_path path
target_path = os.path.abspath(target_path)
if not os.path.exists(target_path):
raise UsageError("Target path doesn't exist: " + target_path)
if not os.path.isdir(target_path):
raise UsageError("Target path isn't a directory: " + target_path)
# Examine pak path
pak_path = os.path.abspath(pak_path)
if not os.path.exists(pak_path):
raise UsageError("Package doesn't exist: " + pak_path)
if not os.path.isfile(pak_path):
raise UsageError("Package path is not a file: " + pak_path)
# Open package
pak = zipfile.ZipFile(pak_path, 'r')
# Get manifest
manifest = PakManifest()
with pak.open('manifest.json', 'r') as fh:
manifest.load_string(fh.read())
# List files in target
existing = Bunch(
files = dict(),
dirs = dict(),
paths = set(),
scanner = TreeScanner(target_path),
)
for target_obj in existing.scanner.scan():
existing.paths.add(target_obj.path)
if target_obj.obj_type == 'folder':
existing.dirs[target_obj.path] = target_obj
elif target_obj.obj_type == 'file':
existing.files[target_obj.path] = target_obj
| shearern/pak | src/paklib/cmds/install_cmd.py | Python | gpl-3.0 | 1,786 |
"""
Runs OCR on a given file.
"""
from os import system, listdir
from PIL import Image
from pytesseract import image_to_string
import editdistance
from constants import DATA_DIR
def classify(image, people_class, max_classify_distance=1, min_nonclassify_distance=3):
"""
Runs an OCR classifier on a given image file, drawing from a dictionary
"""
read = image_to_string(Image.open(image)).lower()
result = None
for person in people_class:
dist = editdistance.eval(person, read)
if dist <= max_classify_distance:
if result is not None:
return None
result = people_class[person]
elif max_classify_distance < dist <= min_nonclassify_distance:
return None
return result
def setup_ocr(raw_data, progress):
"""
Grabs names from a pdf to an image
"""
system("unzip {} -d {}/extract".format(raw_data, DATA_DIR))
base = DATA_DIR + "/extract/"
mainfolder = base + listdir(base)[0]
files = sorted(listdir(mainfolder))
p_bar = progress(len(files))
for index, path in enumerate(files):
p_bar.update(index)
fullpath = mainfolder + "/" + path
system("mkdir {}/ocr".format(DATA_DIR))
basic_format = r"pdftoppm -png -f 3 -l 3 -x 170 -y %s -W 900 -H 100 {} > {}/ocr/%s{}.png" \
.format(fullpath, DATA_DIR, index)
system(basic_format % (1030, "left"))
system(basic_format % (1115, "right"))
| kavigupta/61a-analysis | src/ocr.py | Python | gpl-3.0 | 1,475 |
# Copyright 2014-2016 The ODL development group
#
# This file is part of ODL.
#
# ODL is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ODL 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 ODL. If not, see <http://www.gnu.org/licenses/>.
"""Radon transform (ray transform) in 2d using skimage.transform."""
from odl.discr import uniform_discr_frompartition, uniform_partition
import numpy as np
try:
from skimage.transform import radon, iradon
SCIKIT_IMAGE_AVAILABLE = True
except ImportError:
SCIKIT_IMAGE_AVAILABLE = False
__all__ = ('scikit_radon_forward', 'scikit_radon_back_projector',
'SCIKIT_IMAGE_AVAILABLE')
def scikit_theta(geometry):
"""Calculate angles in degrees with ODL scikit conventions."""
return np.asarray(geometry.motion_grid).squeeze() * 180.0 / np.pi
def scikit_sinogram_space(geometry, volume_space, sinogram_space):
"""Create a range adapted to the scikit radon geometry."""
padded_size = int(np.ceil(volume_space.shape[0] * np.sqrt(2)))
det_width = volume_space.domain.extent()[0] * np.sqrt(2)
scikit_detector_part = uniform_partition(-det_width / 2.0,
det_width / 2.0,
padded_size)
scikit_range_part = geometry.motion_partition.insert(1,
scikit_detector_part)
scikit_range = uniform_discr_frompartition(scikit_range_part,
interp=sinogram_space.interp,
dtype=sinogram_space.dtype)
return scikit_range
def clamped_interpolation(scikit_range, sinogram):
"""Interpolate in a possibly smaller space
Sets all points that would be outside ofthe domain to match the boundary
values.
"""
min_x = scikit_range.domain.min()[1]
max_x = scikit_range.domain.max()[1]
def interpolation_wrapper(x):
x = (x[0], np.maximum(min_x, np.minimum(max_x, x[1])))
return sinogram.interpolation(x)
return interpolation_wrapper
def scikit_radon_forward(volume, geometry, range, out=None):
"""Calculate forward projection using scikit
Parameters
----------
volume : `DiscreteLpElement`
The volume to project
geometry : `Geometry`
The projection geometry to use
range : `DiscreteLp`
range of this projection (sinogram space)
out : ``range`` element, optional
An element in range that the result should be written to
Returns
-------
sinogram : ``range`` element
Sinogram given by the projection.
"""
# Check basic requirements. Fully checking should be in wrapper
assert volume.shape[0] == volume.shape[1]
theta = scikit_theta(geometry)
scikit_range = scikit_sinogram_space(geometry, volume.space, range)
sinogram = scikit_range.element(radon(volume.asarray(), theta=theta).T)
if out is None:
out = range.element()
out.sampling(clamped_interpolation(scikit_range, sinogram))
scale = volume.space.cell_sides[0]
out *= scale
return out
def scikit_radon_back_projector(sinogram, geometry, range, out=None):
"""Calculate forward projection using scikit
Parameters
----------
sinogram : `DiscreteLpElement`
Sinogram (projections) to backproject.
geometry : `Geometry`
The projection geometry to use.
range : `DiscreteLp`
range of this projection (volume space).
out : ``range`` element, optional
An element in range that the result should be written to.
Returns
-------
sinogram : ``range`` element
Sinogram given by the projection.
"""
theta = scikit_theta(geometry)
scikit_range = scikit_sinogram_space(geometry, range, sinogram.space)
scikit_sinogram = scikit_range.element()
scikit_sinogram.sampling(clamped_interpolation(range, sinogram))
if out is None:
out = range.element()
else:
# Only do asserts here since these are backend functions
assert out in range
out[:] = iradon(scikit_sinogram.asarray().T, theta,
output_size=range.shape[0], filter=None)
# Empirically determined value, gives correct scaling
scale = 4.0 * float(geometry.motion_params.length) / (2 * np.pi)
out *= scale
return out
| bgris/ODL_bgris | lib/python3.5/site-packages/odl/tomo/backends/scikit_radon.py | Python | gpl-3.0 | 4,830 |
from django.contrib.auth import views as auth
def login(request):
return auth.login(request, template_name="registration/login.haml")
def password_change(request):
return auth.password_change(request, template_name="registration/password_change_form.haml")
def password_change_done(request):
return auth.password_change_done(request, template_name="registration/password_change_done.haml")
| Psycojoker/hackeragenda | authentication/views.py | Python | gpl-3.0 | 408 |
import csv
__author__ = "Aaron Eppert <aaron.eppert@packetsled.com>"
def process(options, results, output_handle):
headers = options['select'].split(',')
writer = csv.writer(output_handle)
writer.writerow(headers)
for result in results:
row = []
for header in headers:
if header in result:
if isinstance(result[header], list):
result[header] = ', '.join(result[header])
row.append(result[header])
else:
row.append('')
writer.writerow(row) | jmdevince/cifpy3 | lib/cif/client/formatters/csv.py | Python | gpl-3.0 | 573 |
# -*- coding: utf-8 -*-
#
# This file is part of the VecNet OpenMalaria Portal.
# For copyright and licensing information about this package, see the
# NOTICE.txt and LICENSE.txt files in its top-level directory; they are
# available at https://github.com/vecnet/om
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License (MPL), version 2.0. If a copy of the MPL was not distributed
# with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
from django.test.testcases import TestCase
from django.urls.base import reverse
class Http500Test(TestCase):
def test(self):
url = reverse("test_http_code_500")
self.assertRaises(RuntimeError, self.client.get, url)
class IndexViewTest(TestCase):
def test(self):
response = self.client.get(reverse("index"))
self.assertEqual(response.status_code, 200)
| vecnet/om | website/tests/test_views.py | Python | mpl-2.0 | 874 |
#!/usr/bin/env python
# Script to capture the screen with GTK, and format and send
# to a TV backlighting system.
#
# Copyright 2013 Daniel Foote.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import time
import gtk.gdk
import struct
import sys
import socket
import json
import os
# Configuration defaults.
configuration = {
# Target host and port number.
'host': "10.0.14.200",
'port': 8888,
# The number of pixels actually attached to the TV.
'size_x': 46,
'size_y': 26,
# The number of frames to average together (to stop flashing/flickering)
'average_frames': 16,
# How many pixels to probe looking for black bars.
'black_bar_search_height': 8,
# The number of frames to consider the black bar height for.
# The minimum detected bottom from this length is used.
# For example, with this at 1024, if we capture at 50fps, then the black bar mininum
# for the last 20 seconds is used. This makes it a little slow
# to detect the start of movies, but should allow the detection to work through
# the movie better, and also deal with non-black-bar videos as well.
'black_bar_candidate_length': 1024,
# Divide the colours by this number. This is because the LED
# strip tends to be super bright, so this crudely dims it down somewhat.
'colour_divisor': 2,
}
# Load the configuration.
if not os.path.exists('config.json'):
print "No config.json found - please create and try again."
sys.exit()
configuration.update(json.loads(open('config.json').read()))
# Get the window size.
window = gtk.gdk.get_default_root_window()
size = window.get_size()
print "The size of the window is %d x %d" % size
# Calculations for later on.
scale_x = float(configuration['size_x']) / float(size[0])
scale_y = float(configuration['size_y']) / float(size[1])
current_buffer = 0
composite_alpha = (255 / configuration['average_frames'])
arduino_pixels = ((configuration['size_x'] * 2) + (configuration['size_y'] * 2)) - 4
black_bar_probe_points = [0, configuration['size_x'] / 4, configuration['size_x'] / 2, int(configuration['size_x'] * 0.75), configuration['size_x'] - 1]
black_bar_top_candidates = [0] * configuration['black_bar_candidate_length']
black_bar_bottom_candidates = [0] * configuration['black_bar_candidate_length']
black_bar_top_candidate_index = 0
black_bar_bottom_candidate_index = 0
print "Sending %d pixels each screen." % arduino_pixels
# Set up the buffers - only once, and we'll reuse them.
screen_contents = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8, size[0], size[1])
screen_buffers = []
for i in range(configuration['average_frames']):
screen_buffers.append(gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8, configuration['size_x'], configuration['size_y']))
scaled_contents = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8, configuration['size_x'], configuration['size_y'])
def colourfor(pa, x, y, scale = 1):
"""
Helper function to get a pixel from a Numpy pixel array and
reassemble it.
"""
raw_pixel = pa[y][x]
red = raw_pixel[0] / scale
green = raw_pixel[1] / scale
blue = raw_pixel[2] / scale
colour = (red * 256 * 256) + (green * 256) + blue
return colour
while True:
start = time.time()
# Fetch, scale down.
screen_contents = screen_contents.get_from_drawable(window, window.get_colormap(), 0, 0, 0, 0, size[0], size[1])
captime = time.time()
# Scale into the current buffer.
screen_contents.scale(screen_buffers[current_buffer], 0, 0, configuration['size_x'], configuration['size_y'], 0, 0, scale_x, scale_y, gtk.gdk.INTERP_NEAREST)
# Wrap the buffer number around, if needed.
current_buffer += 1
if current_buffer >= configuration['average_frames']:
current_buffer = 0
# Clear the scaled contents, then composite the last frames on top of it.
scaled_contents.fill(0x00000000)
for i in range(configuration['average_frames']):
screen_buffers[i].composite(scaled_contents, 0, 0, configuration['size_x'], configuration['size_y'], 0, 0, 1.0, 1.0, gtk.gdk.INTERP_NEAREST, composite_alpha)
scaletime = time.time()
# Debugging code to save the frame that we're just composited.
#screen_contents.scale(scaled_contents, 0, 0, minisize_x, minisize_y, 0, 0, scale_x, scale_y, gtk.gdk.INTERP_NEAREST)
#scaled_contents.save("screenshot%d.png" % time.time(), "png")
real_height = scaled_contents.get_height() - 1
real_width = scaled_contents.get_width() - 1
pixel_array = scaled_contents.pixel_array
# Search for the black bars.
black_top = 0
black_bottom = real_height
top_candidates = []
bottom_candidates = []
for x in black_bar_probe_points:
this_top = 0
this_bottom = real_height
for y in range(configuration['black_bar_search_height']):
colour = colourfor(pixel_array, x, y)
if colour == 0x0:
this_top = y + 1
colour = colourfor(pixel_array, x, real_height - y)
if colour == 0x0:
this_bottom = (real_height - y) - 1
top_candidates.append(this_top)
bottom_candidates.append(this_bottom)
black_top = min(*top_candidates)
black_bottom = max(*bottom_candidates)
black_bar_top_candidates[black_bar_top_candidate_index] = black_top
black_bar_bottom_candidates[black_bar_bottom_candidate_index] = black_bottom
black_bar_top_candidate_index += 1
if black_bar_top_candidate_index == configuration['black_bar_candidate_length']:
black_bar_top_candidate_index = 0
black_bar_bottom_candidate_index += 1
if black_bar_bottom_candidate_index == configuration['black_bar_candidate_length']:
black_bar_bottom_candidate_index = 0
black_top = min(*black_bar_top_candidates)
black_bottom = max(*black_bar_bottom_candidates)
# print "Black bars: %d -> %d" % (black_top, black_bottom)
searchtime = time.time()
network_message = 'P'
network_message += struct.pack('<B', configuration['input'])
network_message += struct.pack('<H', arduino_pixels)
# Bottom of image first, left to right.
y = black_bottom
for x in range(real_width):
colour = colourfor(pixel_array, x, y, configuration['colour_divisor'])
# print "%d, %d: %X" % (x, y, colour)
network_message += struct.pack('<I', colour)
# Right side, bottom to top.
x = real_width
for y in range(real_height, 0, -1):
colour = colourfor(pixel_array, x, y, configuration['colour_divisor'])
# print "%d, %d: %X" % (x, y, colour)
network_message += struct.pack('<I', colour)
# Top side, right to left.
y = black_top
for x in range(real_width, 0, -1):
colour = colourfor(pixel_array, x, y, configuration['colour_divisor'])
# print "%d, %d: %X" % (x, y, colour)
network_message += struct.pack('<I', colour)
# Left side, top to bottom.
x = 0
for y in range(real_height):
colour = colourfor(pixel_array, x, y, configuration['colour_divisor'])
# print "%d, %d: %X" % (x, y, colour)
network_message += struct.pack('<I', colour)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.sendto(network_message, (configuration['host'], configuration['port']))
# print "Sent %d bytes." % len(network_message)
end = time.time()
print "Total time %0.4fs. Cap %0.4fs, Scale %0.4fs, Search %0.4fs, Proc %0.4fs, FPS %0.2f" % (
end - start,
captime - start,
scaletime - captime,
searchtime - scaletime,
end - searchtime,
1 / (end - start)
) | freefoote/tv-backlight | capture-and-send.py | Python | mpl-2.0 | 7,667 |
# Generated by Django 2.2.13 on 2020-10-23 00:43
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('community', '0032_accesslevel'),
]
operations = [
migrations.CreateModel(
name='ApiAccess',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('status_limit', models.IntegerField(blank=True, default=0, help_text='Total number of status.', null=True, verbose_name='Status limit')),
('status_rate', models.IntegerField(blank=True, default=0, help_text='Number of status per minute.', null=True, verbose_name='Status rate (per minute)')),
('author_category', models.BooleanField(default=False, help_text='Category of the author of the status.', verbose_name='Author category')),
('author_specialty', models.BooleanField(default=False, help_text='Specialty of the author of the status.', verbose_name='Author specialty')),
('search_datetime', models.BooleanField(default=False, help_text='Search status by date and time.', verbose_name='Date and Time search')),
('search_category', models.BooleanField(default=False, help_text='Search status by category.', verbose_name='Category search')),
('search_tag', models.BooleanField(default=False, help_text='Search status by tag.', verbose_name='Tag search')),
('status_category', models.BooleanField(default=False, help_text='Access status category.', verbose_name='Status category')),
('status_tag', models.BooleanField(default=False, help_text='Access status tag.', verbose_name='Status tag')),
('status_protected', models.BooleanField(default=False, help_text='Access status from protected account.', verbose_name='Protected status')),
('community', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='api_access', to='community.Community')),
('level', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='api_access', to='community.AccessLevel')),
],
options={
'unique_together': {('community', 'level')},
},
),
]
| jeromecc/doctoctocbot | src/community/migrations/0033_apiaccess.py | Python | mpl-2.0 | 2,376 |
#!/bin/false
# This file is part of Espruino, a JavaScript interpreter for Microcontrollers
#
# Copyright (C) 2013 Gordon Williams <gw@pur3.co.uk>
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#
# ----------------------------------------------------------------------------------------
# This file contains information for a specific board - the available pins, and where LEDs,
# Buttons, and other in-built peripherals are. It is used to build documentation as well
# as various source and header files for Espruino.
# ----------------------------------------------------------------------------------------
import pinutils;
# placeholder
info = {
'name' : "RedBear Duo",
'link' : [ "http://www.RedBear.cc/Duo" ],
'default_console' : "EV_SERIAL1",
'variables' : 2250,
'bootloader' : 0,
'binary_name' : 'espruino_%v_redbearduo.bin',
'build' : {
'defines' : [
]
}
};
chip = {
'part' : "STM32F205RGT6",
'family' : "STM32F2",
'package' : "WLCSP64",
'ram' : 60, # just a guess left for user part
'flash' : 1024,
'speed' : 120,
'usart' : 2,
'spi' : 2,
'i2c' : 1,
'adc' : 8,
'dac' : 2,
'saved_code' : {
'address' : 0x08010000, # internal EEPROM flash
'page_size' : 131072, # size of pages
'pages' : 0.5, # number of pages we're using
'flash_available' : 256 # 256KB internal flash used for user part
},
};
devices = {
'LED1' : { 'pin' : 'B11' }, # R
'LED2' : { 'pin' : 'B1' }, # G
'LED3' : { 'pin' : 'B0' }, # B
'LED4' : { 'pin' : 'A13' }, # user led
'BTN1' : { 'pin' : 'B2' },
};
def get_pins():
pins = pinutils.scan_pin_file([], 'stm32f20x.csv', 6, 9, 10)
pins = pinutils.scan_pin_af_file(pins, 'stm32f20x_af.csv', 0, 1)
return pinutils.only_from_package(pinutils.fill_gaps_in_pin_list(pins), chip["package"])
| redbear/Espruino | boards/REDBEARDUO.py | Python | mpl-2.0 | 1,944 |
import mock
from nose.tools import eq_, ok_, assert_raises
from collector.unittest.testbase import TestCase
from configman import (
class_converter,
Namespace,
command_line,
ConfigFileFutureProxy,
)
from configman.dotdict import DotDict
from collector.app.socorro_app import (
SocorroApp,
SocorroWelcomeApp,
main,
klass_to_pypath,
)
from collector.app.for_application_defaults import ApplicationDefaultsProxy
#==============================================================================
class TestSocorroApp(TestCase):
#--------------------------------------------------------------------------
def test_instantiation(self):
config = DotDict()
sa = SocorroApp(config)
eq_(sa.get_application_defaults(), {})
assert_raises(NotImplementedError, sa.main)
assert_raises(NotImplementedError, sa._do_run)
#--------------------------------------------------------------------------
def test_run(self):
class SomeOtherApp(SocorroApp):
@classmethod
def _do_run(klass, config_path=None, values_source_list=None):
klass.config_path = config_path
return 17
eq_(SomeOtherApp._do_run(), 17)
ok_(SomeOtherApp.config_path is None)
x = SomeOtherApp.run()
eq_(x, 17)
#--------------------------------------------------------------------------
def test_run_with_alternate_config_path(self):
class SomeOtherApp(SocorroApp):
@classmethod
def _do_run(klass, config_path=None, values_source_list=None):
klass.values_source_list = values_source_list
klass.config_path = config_path
return 17
eq_(SomeOtherApp._do_run('my/path'), 17)
eq_(SomeOtherApp.config_path, 'my/path')
x = SomeOtherApp.run('my/other/path')
eq_(x, 17)
eq_(SomeOtherApp.config_path, 'my/other/path')
#--------------------------------------------------------------------------
def test_run_with_alternate_values_source_list(self):
class SomeOtherApp(SocorroApp):
@classmethod
def _do_run(klass, config_path=None, values_source_list=None):
klass.values_source_list = values_source_list
klass.config_path = config_path
return 17
eq_(SomeOtherApp._do_run('my/path', [{}, {}]), 17)
eq_(SomeOtherApp.config_path, 'my/path')
eq_(SomeOtherApp.values_source_list, [{}, {}])
x = SomeOtherApp.run('my/other/path', [])
eq_(x, 17)
eq_(SomeOtherApp.config_path, 'my/other/path')
eq_(SomeOtherApp.values_source_list, [])
#--------------------------------------------------------------------------
def test_do_run(self):
config = DotDict()
with mock.patch('collector.app.socorro_app.ConfigurationManager') as cm:
cm.return_value.context.return_value = mock.MagicMock()
with mock.patch('collector.app.socorro_app.signal') as s:
class SomeOtherApp(SocorroApp):
app_name='SomeOtherApp'
app_verision='1.2.3'
app_description='a silly app'
def main(self):
ok_(
self.config
is cm.return_value.context.return_value.__enter__
.return_value
)
return 17
result = main(SomeOtherApp)
args = cm.call_args_list
args, kwargs = args[0]
ok_(isinstance(args[0], Namespace))
ok_(isinstance(kwargs['values_source_list'], list))
eq_(kwargs['app_name'], SomeOtherApp.app_name)
eq_(kwargs['app_version'], SomeOtherApp.app_version)
eq_(kwargs['app_description'], SomeOtherApp.app_description)
eq_(kwargs['config_pathname'], './config')
ok_(kwargs['values_source_list'][-1], command_line)
ok_(isinstance(kwargs['values_source_list'][-2], DotDict))
ok_(kwargs['values_source_list'][-3] is ConfigFileFutureProxy)
ok_(isinstance(
kwargs['values_source_list'][0],
ApplicationDefaultsProxy
))
eq_(result, 17)
#--------------------------------------------------------------------------
def test_do_run_with_alternate_class_path(self):
config = DotDict()
with mock.patch('collector.app.socorro_app.ConfigurationManager') as cm:
cm.return_value.context.return_value = mock.MagicMock()
with mock.patch('collector.app.socorro_app.signal') as s:
class SomeOtherApp(SocorroApp):
app_name='SomeOtherApp'
app_verision='1.2.3'
app_description='a silly app'
def main(self):
ok_(
self.config
is cm.return_value.context.return_value.__enter__
.return_value
)
return 17
result = main(SomeOtherApp, 'my/other/path')
args = cm.call_args_list
args, kwargs = args[0]
ok_(isinstance(args[0], Namespace))
ok_(isinstance(kwargs['values_source_list'], list))
eq_(kwargs['app_name'], SomeOtherApp.app_name)
eq_(kwargs['app_version'], SomeOtherApp.app_version)
eq_(kwargs['app_description'], SomeOtherApp.app_description)
eq_(kwargs['config_pathname'], 'my/other/path')
ok_(kwargs['values_source_list'][-1], command_line)
ok_(isinstance(kwargs['values_source_list'][-2], DotDict))
ok_(kwargs['values_source_list'][-3] is ConfigFileFutureProxy)
ok_(isinstance(
kwargs['values_source_list'][0],
ApplicationDefaultsProxy
))
eq_(result, 17)
#--------------------------------------------------------------------------
def test_do_run_with_alternate_values_source_list(self):
config = DotDict()
with mock.patch('collector.app.socorro_app.ConfigurationManager') as cm:
cm.return_value.context.return_value = mock.MagicMock()
with mock.patch('collector.app.socorro_app.signal') as s:
class SomeOtherApp(SocorroApp):
app_name='SomeOtherApp'
app_verision='1.2.3'
app_description='a silly app'
def main(self):
ok_(
self.config
is cm.return_value.context.return_value.__enter__
.return_value
)
return 17
result = main(
SomeOtherApp,
config_path='my/other/path',
values_source_list=[{"a": 1}, {"b": 2}]
)
args = cm.call_args_list
args, kwargs = args[0]
ok_(isinstance(args[0], Namespace))
eq_(kwargs['app_name'], SomeOtherApp.app_name)
eq_(kwargs['app_version'], SomeOtherApp.app_version)
eq_(kwargs['app_description'], SomeOtherApp.app_description)
eq_(kwargs['config_pathname'], 'my/other/path')
ok_(isinstance(kwargs['values_source_list'], list))
ok_(isinstance(
kwargs['values_source_list'][0],
ApplicationDefaultsProxy
))
eq_(kwargs['values_source_list'][1], {"a": 1})
eq_(kwargs['values_source_list'][2], {"b": 2})
eq_(result, 17)
| willkg/socorro-collector | collector/unittest/app/test_socorro_app.py | Python | mpl-2.0 | 8,093 |
import typing
from pros.conductor import Project
class SystemDevice(object):
def upload_project(self, project: Project, **kwargs):
raise NotImplementedError
def write_program(self, file: typing.BinaryIO, quirk: int = 0, **kwargs):
raise NotImplementedError
| purduesigbots/pros-cli | pros/serial/devices/system_device.py | Python | mpl-2.0 | 285 |
# -*- coding: utf-8 -*-
#
# This file is part of the VecNet OpenMalaria Portal.
# For copyright and licensing information about this package, see the
# NOTICE.txt and LICENSE.txt files in its top-level directory; they are
# available at https://github.com/vecnet/om
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License (MPL), version 2.0. If a copy of the MPL was not distributed
# with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
from django.conf import settings
import subprocess
import sys
import os
import logging
from website.apps.ts_om.models import Simulation
logger = logging.getLogger(__name__)
def submit(simulation):
logger.debug("dispatcher.submit: simulation id %s" % simulation.id)
assert isinstance(simulation, Simulation)
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
executable = sys.executable
if hasattr(settings, "PYTHON_EXECUTABLE"):
executable = settings.PYTHON_EXECUTABLE
run_script_filename = os.path.join(base_dir, "run.py")
try:
logger.debug("dispatcher.submit: before Popen")
p = subprocess.Popen(
[executable, run_script_filename, str(simulation.id)],
cwd=base_dir, shell=False
)
logger.debug("dispatcher.submit: after Popen")
except (OSError, IOError) as e:
logger.exception("subprocess failed: %s", sys.exc_info())
simulation.status = Simulation.FAILED
simulation.last_error_message = "Subprocess failed: %s" % e
simulation.pid = ""
simulation.save(update_fields=["status", "pid", "last_error_message"])
return None
simulation.status = Simulation.QUEUED
simulation.pid = str(p.pid)
simulation.last_error_message = ""
simulation.save(update_fields=["status", "pid", "last_error_message"])
logger.debug("dispatcher.submit: success, PID: %s" % p.pid)
return str(p.pid)
| vecnet/om | sim_services_local/dispatcher.py | Python | mpl-2.0 | 1,944 |
# encoding: utf-8
#
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Author: Kyle Lahnakoski (kyle@lahnakoski.com)
#
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from collections import Mapping
import os
from pyLibrary import dot
from pyLibrary.dot import set_default, wrap, unwrap
from pyLibrary.parsers import URL
DEBUG = False
_convert = None
_Log = None
_Except = None
def _late_import():
global _convert
global _Log
global _Except
from pyLibrary import convert as _convert
from pyLibrary.debugs.logs import Log as _Log
from pyLibrary.debugs.exceptions import Except as _Except
_ = _convert
_ = _Log
_ = _Except
def get(url):
"""
USE json.net CONVENTIONS TO LINK TO INLINE OTHER JSON
"""
if not _Log:
_late_import()
if url.find("://") == -1:
_Log.error("{{url}} must have a prototcol (eg http://) declared", url=url)
base = URL("")
if url.startswith("file://") and url[7] != "/":
if os.sep=="\\":
base = URL("file:///" + os.getcwd().replace(os.sep, "/").rstrip("/") + "/.")
else:
base = URL("file://" + os.getcwd().rstrip("/") + "/.")
elif url[url.find("://") + 3] != "/":
_Log.error("{{url}} must be absolute", url=url)
phase1 = _replace_ref(wrap({"$ref": url}), base) # BLANK URL ONLY WORKS IF url IS ABSOLUTE
try:
phase2 = _replace_locals(phase1, [phase1])
return wrap(phase2)
except Exception, e:
_Log.error("problem replacing locals in\n{{phase1}}", phase1=phase1)
def expand(doc, doc_url):
"""
ASSUMING YOU ALREADY PULED THE doc FROM doc_url, YOU CAN STILL USE THE
EXPANDING FEATURE
"""
if doc_url.find("://") == -1:
_Log.error("{{url}} must have a prototcol (eg http://) declared", url= doc_url)
phase1 = _replace_ref(doc, URL(doc_url)) # BLANK URL ONLY WORKS IF url IS ABSOLUTE
phase2 = _replace_locals(phase1, [phase1])
return wrap(phase2)
def _replace_ref(node, url):
if url.path.endswith("/"):
url.path = url.path[:-1]
if isinstance(node, Mapping):
ref = None
output = {}
for k, v in node.items():
if k == "$ref":
ref = URL(v)
else:
output[k] = _replace_ref(v, url)
if not ref:
return output
node = output
if not ref.scheme and not ref.path:
# DO NOT TOUCH LOCAL REF YET
output["$ref"] = ref
return output
if not ref.scheme:
# SCHEME RELATIVE IMPLIES SAME PROTOCOL AS LAST TIME, WHICH
# REQUIRES THE CURRENT DOCUMENT'S SCHEME
ref.scheme = url.scheme
# FIND THE SCHEME AND LOAD IT
if ref.scheme in scheme_loaders:
new_value = scheme_loaders[ref.scheme](ref, url)
else:
raise _Log.error("unknown protocol {{scheme}}", scheme=ref.scheme)
if ref.fragment:
new_value = dot.get_attr(new_value, ref.fragment)
if DEBUG:
_Log.note("Replace {{ref}} with {{new_value}}", ref=ref, new_value=new_value)
if not output:
output = new_value
else:
output = unwrap(set_default(output, new_value))
if DEBUG:
_Log.note("Return {{output}}", output=output)
return output
elif isinstance(node, list):
output = [_replace_ref(n, url) for n in node]
# if all(p[0] is p[1] for p in zip(output, node)):
# return node
return output
return node
def _replace_locals(node, doc_path):
if isinstance(node, Mapping):
# RECURS, DEEP COPY
ref = None
output = {}
for k, v in node.items():
if k == "$ref":
ref = v
else:
output[k] = _replace_locals(v, [v] + doc_path)
if not ref:
return output
# REFER TO SELF
frag = ref.fragment
if frag[0] == ".":
# RELATIVE
for i, p in enumerate(frag):
if p != ".":
if i>len(doc_path):
_Log.error("{{frag|quote}} reaches up past the root document", frag=frag)
new_value = dot.get_attr(doc_path[i-1], frag[i::])
break
else:
new_value = doc_path[len(frag) - 1]
else:
# ABSOLUTE
new_value = dot.get_attr(doc_path[-1], frag)
new_value = _replace_locals(new_value, [new_value] + doc_path)
if not output:
return new_value # OPTIMIZATION FOR CASE WHEN node IS {}
else:
return unwrap(set_default(output, new_value))
elif isinstance(node, list):
candidate = [_replace_locals(n, [n] + doc_path) for n in node]
# if all(p[0] is p[1] for p in zip(candidate, node)):
# return node
return candidate
return node
###############################################################################
## SCHEME LOADERS ARE BELOW THIS LINE
###############################################################################
def get_file(ref, url):
from pyLibrary.env.files import File
if ref.path.startswith("~"):
home_path = os.path.expanduser("~")
if os.sep == "\\":
home_path = "/" + home_path.replace(os.sep, "/")
if home_path.endswith("/"):
home_path = home_path[:-1]
ref.path = home_path + ref.path[1::]
elif not ref.path.startswith("/"):
# CONVERT RELATIVE TO ABSOLUTE
ref.path = "/".join(url.path.rstrip("/").split("/")[:-1]) + "/" + ref.path
path = ref.path if os.sep != "\\" else ref.path[1::].replace("/", "\\")
try:
if DEBUG:
_Log.note("reading file {{path}}", path=path)
content = File(path).read()
except Exception, e:
content = None
_Log.error("Could not read file {{filename}}", filename=path, cause=e)
try:
new_value = _convert.json2value(content, params=ref.query, flexible=True, leaves=True)
except Exception, e:
if not _Except:
_late_import()
e = _Except.wrap(e)
try:
new_value = _convert.ini2value(content)
except Exception, f:
raise _Log.error("Can not read {{file}}", file=path, cause=e)
new_value = _replace_ref(new_value, ref)
return new_value
def get_http(ref, url):
from pyLibrary.env import http
params = url.query
new_value = _convert.json2value(http.get(ref), params=params, flexible=True, leaves=True)
return new_value
def get_env(ref, url):
# GET ENVIRONMENT VARIABLES
ref = ref.host
try:
new_value = _convert.json2value(os.environ[ref])
except Exception, e:
new_value = os.environ[ref]
return new_value
def get_param(ref, url):
# GET PARAMETERS FROM url
param = url.query
new_value = param[ref.host]
return new_value
scheme_loaders = {
"http": get_http,
"file": get_file,
"env": get_env,
"param": get_param
}
| klahnakoski/MoDataSubmission | pyLibrary/jsons/ref.py | Python | mpl-2.0 | 7,353 |
"""A block Davidson solver for finding a fixed number of eigenvalues.
Adapted from https://joshuagoings.com/2013/08/23/davidsons-method/
"""
import time
from typing import Tuple
import numpy as np
from tqdm import tqdm
def davidson(A: np.ndarray, k: int, eig: int) -> Tuple[np.ndarray, np.ndarray]:
assert len(A.shape) == 2
assert A.shape[0] == A.shape[1]
n = A.shape[0]
## set up subspace and trial vectors
# set of k unit vectors as guess
t = np.eye(n, k)
# hold guess vectors
V = np.zeros((n, n))
I = np.eye(n)
for m in tqdm(range(k, mmax, k)):
if m <= k:
for j in range(k):
V[:, j] = t[:, j] / np.linalg.norm(t[:, j])
theta_old = 1
elif m > k:
theta_old = theta[:eig]
V, R = np.linalg.qr(V)
T = V[:, : (m + 1)].T @ A @ V[:, : (m + 1)]
THETA, S = np.linalg.eig(T)
idx = THETA.argsort()
theta = THETA[idx]
s = S[:, idx]
for j in range(k):
w = (A - theta[j] * I) @ V[:, : (m + 1)] @ s[:, j]
q = w / (theta[j] - A[j, j])
V[:, (m + j + 1)] = q
norm = np.linalg.norm(theta[:eig] - theta_old)
if norm < tol:
break
return theta, V
if __name__ == "__main__":
# dimension of problem
n = 1200
# convergence tolerance
tol = 1e-8
# maximum number of iterations
mmax = n // 2
## set up fake Hamiltonian
sparsity = 1.0e-4
A = np.zeros((n, n))
for i in range(0, n):
A[i, i] = i + 1
A = A + sparsity * np.random.randn(n, n)
A = (A.T + A) / 2
# number of initial guess vectors
k = 8
# number of eigenvalues to solve
eig = 4
start_davidson = time.time()
theta, V = davidson(A, k, eig)
end_davidson = time.time()
print(f"davidson = {theta[:eig]}; {end_davidson - start_davidson} seconds")
start_numpy = time.time()
E, Vec = np.linalg.eig(A)
E = np.sort(E)
end_numpy = time.time()
print(f"numpy = {E[:eig]}; {end_numpy - start_numpy} seconds")
| berquist/programming_party | eric/project12/davidson.py | Python | mpl-2.0 | 2,084 |
import os
import re
from setuptools import setup, find_packages
THIS_DIR = os.path.dirname(os.path.realpath(__name__))
def read(*parts):
with open(os.path.join(THIS_DIR, *parts)) as f:
return f.read()
def get_version():
return re.findall("__version__ = '([\d\.]+)'",
read('marionette', '__init__.py'), re.M)[0]
setup(name='marionette_client',
version=get_version(),
description="Marionette test automation client",
long_description='See http://marionette-client.readthedocs.org/',
classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers
keywords='mozilla',
author='Jonathan Griffin',
author_email='jgriffin@mozilla.com',
url='https://wiki.mozilla.org/Auto-tools/Projects/Marionette',
license='MPL',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
package_data={'marionette': ['touch/*.js']},
include_package_data=True,
zip_safe=False,
entry_points="""
# -*- Entry points: -*-
[console_scripts]
marionette = marionette.runtests:cli
""",
install_requires=read('requirements.txt').splitlines(),
)
| cstipkovic/spidermonkey-research | testing/marionette/harness/setup.py | Python | mpl-2.0 | 1,214 |
# -*- coding: utf-8 -*-
#
# This file is part of the VecNet OpenMalaria Portal.
# For copyright and licensing information about this package, see the
# NOTICE.txt and LICENSE.txt files in its top-level directory; they are
# available at https://github.com/vecnet/om
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License (MPL), version 2.0. If a copy of the MPL was not distributed
# with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
import os
from django.test.testcases import TestCase
from django.conf import settings
import run
from website.apps.ts_om.models import Simulation
class RunNewTest(TestCase):
def test_failure(self):
simulation = Simulation.objects.create()
simulation.set_input_file("")
run.main(simulation.id)
simulation.refresh_from_db()
self.assertEqual(simulation.status, Simulation.FAILED)
self.assertEqual("Exit code: 66", simulation.last_error_message)
model_stdout = simulation.model_stdout.read().decode("utf-8")
self.assertIn("XSD error", model_stdout)
self.assertIn("invalid document structure", model_stdout)
def test_success(self):
simulation = Simulation.objects.create()
with open(os.path.join(settings.BASE_DIR, "website", "apps", "ts_om", "tests", "data", "default.xml")) as fp:
simulation.set_input_file(fp)
run.main(simulation.id)
simulation.refresh_from_db()
self.assertEqual(simulation.status, Simulation.COMPLETE)
self.assertEqual("", simulation.last_error_message)
model_stdout = simulation.model_stdout.read().decode("utf-8")
self.assertIn("100%", model_stdout)
output = simulation.output_file.read().decode("utf-8")
self.assertNotEqual(output, "")
ctsout = simulation.ctsout_file.read().decode("utf-8")
self.assertNotEqual(ctsout, "")
| vecnet/om | website/apps/ts_om/tests/test_run_new.py | Python | mpl-2.0 | 1,914 |
"""Import an Irish NaPTAN XML file, obtainable from
https://data.dublinked.ie/dataset/national-public-transport-nodes/resource/6d997756-4dba-40d8-8526-7385735dc345
"""
import warnings
import zipfile
import xml.etree.cElementTree as ET
from django.contrib.gis.geos import Point
from django.core.management.base import BaseCommand
from ...models import Locality, AdminArea, StopPoint
class Command(BaseCommand):
ns = {'naptan': 'http://www.naptan.org.uk/'}
@staticmethod
def add_arguments(parser):
parser.add_argument('filenames', nargs='+', type=str)
def handle_stop(self, element):
stop = StopPoint(
atco_code=element.find('naptan:AtcoCode', self.ns).text,
locality_centre=element.find('naptan:Place/naptan:LocalityCentre', self.ns).text == 'true',
active=element.get('Status') == 'active',
)
for subelement in element.find('naptan:Descriptor', self.ns):
tag = subelement.tag[27:]
if tag == 'CommonName':
stop.common_name = subelement.text
elif tag == 'Street':
stop.street = subelement.text
elif tag == 'Indicator':
stop.indicator = subelement.text.lower()
else:
warnings.warn('Stop {} has an unexpected property: {}'.format(stop.atco_code, tag))
stop_classification_element = element.find('naptan:StopClassification', self.ns)
stop_type = stop_classification_element.find('naptan:StopType', self.ns).text
if stop_type != 'class_undefined':
stop.stop_type = stop_type
bus_element = stop_classification_element.find('naptan:OnStreet/naptan:Bus', self.ns)
if bus_element is not None:
stop.bus_stop_type = bus_element.find('naptan:BusStopType', self.ns).text
stop.timing_status = bus_element.find('naptan:TimingStatus', self.ns).text
compass_point_element = bus_element.find(
'naptan:MarkedPoint/naptan:Bearing/naptan:CompassPoint', self.ns
)
if compass_point_element is not None:
stop.bearing = compass_point_element.text
if stop.bus_stop_type == 'type_undefined':
stop.bus_stop_type = ''
place_element = element.find('naptan:Place', self.ns)
location_element = place_element.find('naptan:Location', self.ns)
longitude_element = location_element.find('naptan:Longitude', self.ns)
latitude_element = location_element.find('naptan:Latitude', self.ns)
if longitude_element is None:
warnings.warn('Stop {} has no location'.format(stop.atco_code))
else:
stop.latlong = Point(float(longitude_element.text), float(latitude_element.text))
admin_area_id = element.find('naptan:AdministrativeAreaRef', self.ns).text
if not AdminArea.objects.filter(atco_code=admin_area_id).exists():
AdminArea.objects.create(id=admin_area_id, atco_code=admin_area_id, region_id='NI')
stop.admin_area_id = admin_area_id
locality_element = place_element.find('naptan:NptgLocalityRef', self.ns)
if locality_element is not None:
if not Locality.objects.filter(id=locality_element.text).exists():
Locality.objects.create(id=locality_element.text, admin_area_id=admin_area_id)
stop.locality_id = locality_element.text
stop.save()
def handle_file(self, archive, filename):
with archive.open(filename) as open_file:
iterator = ET.iterparse(open_file)
for _, element in iterator:
tag = element.tag[27:]
if tag == 'StopPoint':
self.handle_stop(element)
element.clear()
def handle(self, *args, **options):
for filename in options['filenames']:
with zipfile.ZipFile(filename) as archive:
for filename in archive.namelist():
self.handle_file(archive, filename)
| stev-0/bustimes.org.uk | busstops/management/commands/import_ie_naptan_xml.py | Python | mpl-2.0 | 4,087 |
# This is added to the reduction object dictionary, but only one reduction
# object per AstroData Type. NOTE: primitives are the member functions of a
# Reduction Object.
localPrimitiveIndex = {
"NIRI": ("primitives_NIRI.py", "NIRIPrimitives"),
"NIRI_IMAGE": ("primitives_NIRI_IMAGE.py", "NIRI_IMAGEPrimitives"),
}
| pyrrho314/recipesystem | trunk/dontload-astrodata_Gemini/RECIPES_Gemini/primitives/primitivesIndex.NIRI.py | Python | mpl-2.0 | 328 |
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2012-2013 Elanz (<http://www.openelanz.fr>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import wizard
| noemis-fr/old-custom | e3z_compute_parent_left_right/__init__.py | Python | agpl-3.0 | 997 |
# -*- encoding: utf-8 -*-
import argparse
import sys
import traceback
from hashlib import md5
import mailchimp_marketing as MailchimpMarketing
import requests
from consolemsg import step, error, success
from erppeek import Client
import time
import configdb
ERP_CLIENT = Client(**configdb.erppeek)
MAILCHIMP_CLIENT = MailchimpMarketing.Client(
dict(api_key=configdb.MAILCHIMP_APIKEY, server=configdb.MAILCHIMP_SERVER_PREFIX)
)
def get_member_category_id():
module = 'som_partner_account'
semantic_id = 'res_partner_category_soci'
IrModelData = ERP_CLIENT.model('ir.model.data')
member_category_relation = IrModelData.get_object_reference(
module, semantic_id
)
if member_category_relation:
return member_category_relation[-1]
def get_not_members_email_list():
Soci = ERP_CLIENT.model('somenergia.soci')
ResPartnerAddress = ERP_CLIENT.model('res.partner.address')
category_id = get_member_category_id()
not_members = Soci.search([
('category_id', 'not in', [category_id]),
('ref', 'like', 'S%')
])
not_members_partner_ids = [
soci['partner_id'][0] for soci in Soci.read(not_members, ['partner_id'])
]
address_list = ResPartnerAddress.search(
[('partner_id', 'in', not_members_partner_ids)]
)
emails_list = [
address.get('email', 'not found')
for address in ResPartnerAddress.read(address_list, ['email'])
]
return emails_list
def get_mailchimp_list_id(list_name):
all_lists = MAILCHIMP_CLIENT.lists.get_all_lists(
fields=['lists.id,lists.name'],
count=100
)['lists']
for l in all_lists:
if l['name'] == list_name:
return l['id']
raise Exception("List: <{}> not found".format(list_name))
def get_subscriber_hash(email):
subscriber_hash = md5(email.lower()).hexdigest()
return subscriber_hash
def archive_members_from_list(list_name, email_list):
list_id = get_mailchimp_list_id(list_name)
operations = []
for email in email_list:
operation = {
"method": "DELETE",
"path": "/lists/{list_id}/members/{subscriber_hash}".format(
list_id=list_id,
subscriber_hash=get_subscriber_hash(email)
),
"operation_id": email,
}
operations.append(operation)
payload = {
"operations": operations
}
try:
response = MAILCHIMP_CLIENT.batches.start(payload)
except ApiClientError as error:
msg = "An error occurred an archiving batch request, reason: {}"
error(msg.format(error.text))
else:
batch_id = response['id']
while response['status'] != 'finished':
time.sleep(2)
response = MAILCHIMP_CLIENT.batches.status(batch_id)
step("Archived operation finished!!")
step("Total operations: {}, finished operations: {}, errored operations: {}".format(
response['total_operations'],
response['finished_operations'],
response['errored_operations']
))
result_summary = requests.get(response['response_body_url'])
result_summary.raise_for_status()
return result_summary.content
def archieve_members_in_list(list_name):
email_list = get_not_members_email_list()
result = archive_members_from_list(list_name, email_list)
return result
def main(list_name, output):
result = archieve_members_in_list(list_name.strip())
with open(output, 'w') as f:
f.write(result)
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='Archivieren Sie E-Mails in großen Mengen'
)
parser.add_argument(
'--list',
dest='list_name',
required=True,
help="nom de la llista de mailchimp"
)
parser.add_argument(
'--output',
dest='output',
required=True,
help="Fitxer de sortida amb els resultats"
)
args = parser.parse_args()
try:
main(args.list_name, args.output)
except Exception as e:
traceback.print_exc(file=sys.stdout)
error("El proceso no ha finalizado correctamente: {}", str(e))
else:
success("Script finalizado")
| Som-Energia/invoice-janitor | admin/Baixa_Socis/unsubscribe_members.py | Python | agpl-3.0 | 4,279 |
# ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2018, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Affero Public License for more details.
#
# You should have received a copy of the GNU Affero Public License
# along with this program. If not, see http://www.gnu.org/licenses.
#
# http://numenta.org/licenses/
# ----------------------------------------------------------------------
"""
The methods here contain factories to create networks of multiple layers for
experimenting with grid cell location layer (L6a)
"""
import copy
import json
from htmresearch.frameworks.location.path_integration_union_narrowing import (
computeRatModuleParametersFromReadoutResolution,
computeRatModuleParametersFromCellCount)
from nupic.engine import Network
def createL4L6aLocationColumn(network, L4Params, L6aParams,
inverseReadoutResolution=None,
baselineCellsPerAxis=6, suffix=""):
"""
Create a single column network containing L4 and L6a layers. L4 layer
processes sensor inputs while L6a processes motor commands using grid cell
modules. Sensory input is represented by the feature's active columns and
motor input is represented by the displacement vector [dx, dy].
The grid cell modules used by this network are based on
:class:`ThresholdedGaussian2DLocationModule` where the firing rate is computed
from on one or more Gaussian activity bumps. The cells are distributed
uniformly through the rhombus, packed in the optimal hexagonal arrangement.
::
Phase
----- +-------+
+---------->| |<------------+
[2] | +---->| L4 |--winner---+ |
| | | | | |
| | +-------+ | |
| | | ^ | |
| | | | | |
| | | | | |
| | v | | |
| | +-------+ | |
| | | | | |
[1,3] | +---->| L6a |<----------+ |
| | | |--learnable--+
| | +-------+
| | ^
feature reset |
| | |
| | |
[0] [sensorInput] [motorInput]
.. note::
Region names are "motorInput", "sensorInput", "L4", and "L6a".
Each name has an optional string suffix appended to it.
:param network: network to add the column
:type network: Network
:param L4Params: constructor parameters for :class:`ApicalTMPairRegion`
:type L4Params: dict
:param L6aParams: constructor parameters for :class:`Guassian2DLocationRegion`
:type L6aParams: dict
:param inverseReadoutResolution: Optional readout resolution.
The readout resolution specifies the diameter of the circle of phases in the
rhombus encoded by a bump. See `createRatModuleFromReadoutResolution.
:type inverseReadoutResolution: int
:param baselineCellsPerAxis: The baselineCellsPerAxis implies the readout
resolution of a grid cell module. If baselineCellsPerAxis=6, that implies
that the readout resolution is approximately 1/3. If baselineCellsPerAxis=8,
the readout resolution is approximately 1/4
:type baselineCellsPerAxis: int or float
:param suffix: optional string suffix appended to region name. Useful when
creating multicolumn networks.
:type suffix: str
:return: Reference to the given network
:rtype: Network
"""
L6aParams = copy.deepcopy(L6aParams)
if inverseReadoutResolution is not None:
# Configure L6a based on 'resolution'
params = computeRatModuleParametersFromReadoutResolution(inverseReadoutResolution)
L6aParams.update(params)
else:
params = computeRatModuleParametersFromCellCount(L6aParams["cellsPerAxis"],
baselineCellsPerAxis)
L6aParams.update(params)
numOfcols = L4Params["columnCount"]
cellsPerCol = L4Params["cellsPerColumn"]
L6aParams["anchorInputSize"] = numOfcols * cellsPerCol
# Configure L4 'basalInputSize' to be compatible L6a output
moduleCount = L6aParams["moduleCount"]
cellsPerAxis = L6aParams["cellsPerAxis"]
L4Params = copy.deepcopy(L4Params)
L4Params["basalInputWidth"] = moduleCount * cellsPerAxis * cellsPerAxis
# Configure sensor output to be compatible with L4 params
columnCount = L4Params["columnCount"]
# Add regions to network
motorInputName = "motorInput" + suffix
sensorInputName = "sensorInput" + suffix
L4Name = "L4" + suffix
L6aName = "L6a" + suffix
network.addRegion(sensorInputName, "py.RawSensor",
json.dumps({"outputWidth": columnCount}))
network.addRegion(motorInputName, "py.RawValues",
json.dumps({"outputWidth": 2}))
network.addRegion(L4Name, "py.ApicalTMPairRegion", json.dumps(L4Params))
network.addRegion(L6aName, "py.Guassian2DLocationRegion",
json.dumps(L6aParams))
# Link sensory input to L4
network.link(sensorInputName, L4Name, "UniformLink", "",
srcOutput="dataOut", destInput="activeColumns")
# Link motor input to L6a
network.link(motorInputName, L6aName, "UniformLink", "",
srcOutput="dataOut", destInput="displacement")
# Link L6a to L4
network.link(L6aName, L4Name, "UniformLink", "",
srcOutput="activeCells", destInput="basalInput")
network.link(L6aName, L4Name, "UniformLink", "",
srcOutput="learnableCells", destInput="basalGrowthCandidates")
# Link L4 feedback to L6a
network.link(L4Name, L6aName, "UniformLink", "",
srcOutput="activeCells", destInput="anchorInput")
network.link(L4Name, L6aName, "UniformLink", "",
srcOutput="winnerCells", destInput="anchorGrowthCandidates")
# Link reset signal to L4 and L6a
network.link(sensorInputName, L4Name, "UniformLink", "",
srcOutput="resetOut", destInput="resetIn")
network.link(sensorInputName, L6aName, "UniformLink", "",
srcOutput="resetOut", destInput="resetIn")
# Set phases appropriately
network.setPhases(motorInputName, [0])
network.setPhases(sensorInputName, [0])
network.setPhases(L4Name, [2])
network.setPhases(L6aName, [1, 3])
return network
def createL246aLocationColumn(network, L2Params, L4Params, L6aParams,
baselineCellsPerAxis=6,
inverseReadoutResolution=None, suffix=""):
"""
Create a single column network composed of L2, L4 and L6a layers.
L2 layer computes the object representation using :class:`ColumnPoolerRegion`,
L4 layer processes sensors input while L6a processes motor commands using grid
cell modules. Sensory input is represented by the feature's active columns and
motor input is represented by the displacement vector [dx, dy].
The grid cell modules used by this network are based on
:class:`ThresholdedGaussian2DLocationModule` where the firing rate is computed
from on one or more Gaussian activity bumps. The cells are distributed
uniformly through the rhombus, packed in the optimal hexagonal arrangement.
::
Phase +-------+
----- reset | |
+----->| L2 |<------------------+
[3] | | | |
| +-------+ |
| | ^ |
| | | |
| +1 | | |
| v | |
| +-------+ |
+----------->| |--winnerCells------+
[2] | | | L4 |<------------+
| +----->| |--winner---+ |
| | +-------+ | |
| | | ^ | |
| | | | | |
| | | | | |
| | v | | |
| | +-------+ | |
| | | | | |
[1,3] | +----->| L6a |<----------+ |
| | | |--learnable--+
| | +-------+
feature reset ^
| | |
| | |
[0] [sensorInput] [motorInput]
.. note::
Region names are "motorInput", "sensorInput". "L2", "L4", and "L6a".
Each name has an optional string suffix appended to it.
:param network: network to add the column
:type network: Network
:param L2Params: constructor parameters for :class:`ColumnPoolerRegion`
:type L2Params: dict
:param L4Params: constructor parameters for :class:`ApicalTMPairRegion`
:type L4Params: dict
:param L6aParams: constructor parameters for :class:`Guassian2DLocationRegion`
:type L6aParams: dict
:param inverseReadoutResolution: Optional readout resolution.
The readout resolution specifies the diameter of the circle of phases in the
rhombus encoded by a bump. See `createRatModuleFromReadoutResolution.
:type inverseReadoutResolution: int
:param baselineCellsPerAxis: The baselineCellsPerAxis implies the readout
resolution of a grid cell module. If baselineCellsPerAxis=6, that implies
that the readout resolution is approximately 1/3. If baselineCellsPerAxis=8,
the readout resolution is approximately 1/4
:type baselineCellsPerAxis: int or float
:param suffix: optional string suffix appended to region name. Useful when
creating multicolumn networks.
:type suffix: str
:return: Reference to the given network
:rtype: Network
"""
# Configure L2 'inputWidth' to be compatible with L4
numOfcols = L4Params["columnCount"]
cellsPerCol = L4Params["cellsPerColumn"]
L2Params = copy.deepcopy(L2Params)
L2Params["inputWidth"] = numOfcols * cellsPerCol
# Configure L4 'apicalInputWidth' to be compatible L2 output
L4Params = copy.deepcopy(L4Params)
L4Params["apicalInputWidth"] = L2Params["cellCount"]
# Add L4 - L6a location layers
network = createL4L6aLocationColumn(network=network,
L4Params=L4Params,
L6aParams=L6aParams,
inverseReadoutResolution=inverseReadoutResolution,
baselineCellsPerAxis=baselineCellsPerAxis,
suffix=suffix)
L4Name = "L4" + suffix
sensorInputName = "sensorInput" + suffix
# Add L2 - L4 object layers
L2Name = "L2" + suffix
network.addRegion(L2Name, "py.ColumnPoolerRegion", json.dumps(L2Params))
# Link L4 to L2
network.link(L4Name, L2Name, "UniformLink", "",
srcOutput="activeCells", destInput="feedforwardInput")
network.link(L4Name, L2Name, "UniformLink", "",
srcOutput="winnerCells",
destInput="feedforwardGrowthCandidates")
# Link L2 feedback to L4
network.link(L2Name, L4Name, "UniformLink", "",
srcOutput="feedForwardOutput", destInput="apicalInput",
propagationDelay=1)
# Link reset output to L2
network.link(sensorInputName, L2Name, "UniformLink", "",
srcOutput="resetOut", destInput="resetIn")
# Set L2 phase to be after L4
network.setPhases(L2Name, [3])
return network
def createMultipleL246aLocationColumn(network, numberOfColumns, L2Params,
L4Params, L6aParams,
inverseReadoutResolution=None,
baselineCellsPerAxis=6):
"""
Create a network consisting of multiple columns. Each column contains one L2,
one L4 and one L6a layers identical in structure to the network created by
:func:`createL246aLocationColumn`. In addition all the L2 columns are fully
connected to each other through their lateral inputs.
::
+----lateralInput--+
| +--------------+ |
| | +1 | |
Phase v | v |
----- +-------+ +-------+
reset | | | | reset
[3] +----->| L2 | | L2 |<----+
| | | | | |
| +-------+ +-------+ |
| | ^ | ^ |
| +1 | | +1 | | |
| | | | | |
| v | v | |
| +-------+ +-------+ |
[2] +----------->| | | |<----------+
| | | L4 | | L4 | | |
| +----->| | | |<----+ |
| | +-------+ +-------+ | |
| | | ^ | ^ | |
| | | | | | | |
| | | | | | | |
| | v | v | | |
| | +-------+ +-------+ | |
| | | | | | | |
[1,3] | +----->| L6a | | L6a |<----+ |
| | | | | | | |
| | +-------+ +-------+ | |
feature reset ^ ^ reset feature
| | | | | |
| | | | | |
[0] [sensorInput] [motorInput] [motorInput] [sensorInput]
.. note::
Region names are "motorInput", "sensorInput". "L2", "L4", and "L6a".
Each name has column number appended to it.
For example: "sensorInput_0", "L2_1", "L6a_0" etc.
:param network: network to add the column
:type network: Network
:param numberOfColumns: Number of columns to create
:type numberOfColumns: int
:param L2Params: constructor parameters for :class:`ColumnPoolerRegion`
:type L2Params: dict
:param L4Params: constructor parameters for :class:`ApicalTMPairRegion`
:type L4Params: dict
:param L6aParams: constructor parameters for :class:`Guassian2DLocationRegion`
:type L6aParams: dict
:param inverseReadoutResolution: Optional readout resolution.
The readout resolution specifies the diameter of the circle of phases in the
rhombus encoded by a bump. See `createRatModuleFromReadoutResolution.
:type inverseReadoutResolution: int
:param baselineCellsPerAxis: The baselineCellsPerAxis implies the readout
resolution of a grid cell module. If baselineCellsPerAxis=6, that implies
that the readout resolution is approximately 1/3. If baselineCellsPerAxis=8,
the readout resolution is approximately 1/4
:type baselineCellsPerAxis: int or float
:return: Reference to the given network
:rtype: Network
"""
L2Params = copy.deepcopy(L2Params)
L4Params = copy.deepcopy(L4Params)
L6aParams = copy.deepcopy(L6aParams)
# Update L2 numOtherCorticalColumns parameter
L2Params["numOtherCorticalColumns"] = numberOfColumns - 1
for i in xrange(numberOfColumns):
# Make sure random seed is different for each column
L2Params["seed"] = L2Params.get("seed", 42) + i
L4Params["seed"] = L4Params.get("seed", 42) + i
L6aParams["seed"] = L6aParams.get("seed", 42) + i
# Create column
network = createL246aLocationColumn(network=network,
L2Params=L2Params,
L4Params=L4Params,
L6aParams=L6aParams,
inverseReadoutResolution=inverseReadoutResolution,
baselineCellsPerAxis=baselineCellsPerAxis,
suffix="_" + str(i))
# Now connect the L2 columns laterally
if numberOfColumns > 1:
for i in xrange(numberOfColumns):
src = str(i)
for j in xrange(numberOfColumns):
if i != j:
dest = str(j)
network.link(
"L2_" + src, "L2_" + dest,
"UniformLink", "",
srcOutput="feedForwardOutput", destInput="lateralInput",
propagationDelay=1)
return network
| neuroidss/nupic.research | htmresearch/frameworks/location/location_network_creation.py | Python | agpl-3.0 | 17,520 |
from copy import deepcopy, copy
from django.contrib import admin
from django.contrib.admin.views.main import ChangeList
from django.contrib.contenttypes.admin import GenericTabularInline, GenericStackedInline
from django.forms import ModelForm, NumberInput
from django.db import models
class SortableModelAdminBase(object):
"""
Base class for SortableTabularInline and SortableModelAdmin
"""
sortable = 'order'
class Media:
js = ('suit/js/suit.sortables.js',)
class SortableListForm(ModelForm):
"""
Just Meta holder class
"""
class Meta:
widgets = {
'order': NumberInput(
attrs={'class': 'hidden-xs-up suit-sortable'})
}
class SortableChangeList(ChangeList):
"""
Class that forces ordering by sortable param only
"""
def get_ordering(self, request, queryset):
if self.model_admin.sortable_is_enabled():
return [self.model_admin.sortable, '-' + self.model._meta.pk.name]
return super(SortableChangeList, self).get_ordering(request, queryset)
class SortableTabularInlineBase(SortableModelAdminBase):
"""
Sortable tabular inline
"""
def __init__(self, *args, **kwargs):
super(SortableTabularInlineBase, self).__init__(*args, **kwargs)
self.ordering = (self.sortable,)
self.fields = self.fields or []
if self.fields and self.sortable not in self.fields:
self.fields = list(self.fields) + [self.sortable]
def formfield_for_dbfield(self, db_field, **kwargs):
if db_field.name == self.sortable:
kwargs['widget'] = SortableListForm.Meta.widgets['order']
return super(SortableTabularInlineBase, self).formfield_for_dbfield(
db_field, **kwargs)
class SortableTabularInline(SortableTabularInlineBase, admin.TabularInline):
pass
class SortableGenericTabularInline(SortableTabularInlineBase,
GenericTabularInline):
pass
class SortableStackedInlineBase(SortableModelAdminBase):
"""
Sortable stacked inline
"""
def __init__(self, *args, **kwargs):
super(SortableStackedInlineBase, self).__init__(*args, **kwargs)
self.ordering = (self.sortable,)
def get_fieldsets(self, *args, **kwargs):
"""
Iterate all fieldsets and make sure sortable is in the first fieldset
Remove sortable from every other fieldset, if by some reason someone
has added it
"""
fieldsets = super(SortableStackedInlineBase, self).get_fieldsets(*args, **kwargs)
sortable_added = False
for fieldset in fieldsets:
for line in fieldset:
if not line or not isinstance(line, dict):
continue
fields = line.get('fields')
if self.sortable in fields:
fields.remove(self.sortable)
# Add sortable field always as first
if not sortable_added:
fields.insert(0, self.sortable)
sortable_added = True
break
return fieldsets
def formfield_for_dbfield(self, db_field, **kwargs):
if db_field.name == self.sortable:
kwargs['widget'] = deepcopy(SortableListForm.Meta.widgets['order'])
kwargs['widget'].attrs['class'] += ' suit-sortable-stacked'
kwargs['widget'].attrs['rowclass'] = ' suit-sortable-stacked-row'
return super(SortableStackedInlineBase, self).formfield_for_dbfield(db_field, **kwargs)
class SortableStackedInline(SortableStackedInlineBase, admin.StackedInline):
pass
class SortableGenericStackedInline(SortableStackedInlineBase,
GenericStackedInline):
pass
class SortableModelAdmin(SortableModelAdminBase, admin.ModelAdmin):
"""
Sortable change list
"""
def __init__(self, *args, **kwargs):
super(SortableModelAdmin, self).__init__(*args, **kwargs)
# Keep originals for restore
self._original_ordering = copy(self.ordering)
self._original_list_display = copy(self.list_display)
self._original_list_editable = copy(self.list_editable)
self._original_exclude = copy(self.exclude)
self._original_list_per_page = self.list_per_page
self.enable_sortable()
def merge_form_meta(self, form):
"""
Prepare Meta class with order field widget
"""
if not getattr(form, 'Meta', None):
form.Meta = SortableListForm.Meta
if not getattr(form.Meta, 'widgets', None):
form.Meta.widgets = {}
form.Meta.widgets[self.sortable] = SortableListForm.Meta.widgets[
'order']
def get_changelist_form(self, request, **kwargs):
form = super(SortableModelAdmin, self).get_changelist_form(request,
**kwargs)
self.merge_form_meta(form)
return form
def get_changelist(self, request, **kwargs):
return SortableChangeList
def enable_sortable(self):
self.list_per_page = 500
self.ordering = (self.sortable,)
if self.list_display and self.sortable not in self.list_display:
self.list_display = list(self.list_display) + [self.sortable]
self.list_editable = self.list_editable or []
if self.sortable not in self.list_editable:
self.list_editable = list(self.list_editable) + [self.sortable]
self.exclude = self.exclude or []
if self.sortable not in self.exclude:
self.exclude = list(self.exclude) + [self.sortable]
def disable_sortable(self):
if not self.sortable_is_enabled():
return
self.ordering = self._original_ordering
self.list_display = self._original_list_display
self.list_editable = self._original_list_editable
self.exclude = self._original_exclude
self.list_per_page = self._original_list_per_page
def sortable_is_enabled(self):
return self.list_display and self.sortable in self.list_display
def save_model(self, request, obj, form, change):
if not obj.pk:
max_order = obj.__class__.objects.aggregate(
models.Max(self.sortable))
try:
next_order = max_order['%s__max' % self.sortable] + 1
except TypeError:
next_order = 1
setattr(obj, self.sortable, next_order)
super(SortableModelAdmin, self).save_model(request, obj, form, change)
| 82Flex/DCRM | suit/sortables.py | Python | agpl-3.0 | 6,638 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-03-26 10:54
from __future__ import unicode_literals
from django.db import migrations, models
import uuid
class Migration(migrations.Migration):
dependencies = [
('news', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='person',
name='token',
field=models.UUIDField(default=uuid.uuid4, editable=False, null=True),
),
]
| helfertool/helfertool | src/news/migrations/0002_person_token.py | Python | agpl-3.0 | 478 |
# -*- coding: utf-8 -*-
###############################################################################
# License, author and contributors information in: #
# __manifest__.py file at the root folder of this module. #
###############################################################################
from odoo import models, fields, api, _
from odoo.exceptions import UserError, ValidationError
from itertools import groupby
from operator import itemgetter
from collections import defaultdict
class WizardValuationStockInventory(models.TransientModel):
_name = 'wizard.valuation.stock.inventory'
_description = 'Wizard that opens the stock Inventory by Location'
location_id = fields.Many2one('stock.location', string='Location', required=True)
product_categ_id = fields.Many2one('product.category', string='Category')
product_sub_categ_id = fields.Many2one('product.category', string='Sub Category')
line_ids = fields.One2many('wizard.valuation.stock.inventory.line', 'wizard_id', required=True, ondelete='cascade')
@api.multi
def print_pdf_stock_inventory(self, data):
line_ids_all_categ = []
line_ids_filterd_categ = []
line_ids = []
# Unlink All one2many Line Ids from same wizard
for wizard_id in self.env['wizard.valuation.stock.inventory.line'].search([('wizard_id', '=', self.id)]):
if wizard_id.wizard_id.id == self.id:
self.write({'line_ids': [(3, wizard_id.id)]})
child_loc_ids = []
if self.location_id:
child_loc_ids = self.env['stock.location'].sudo().search([('location_id', 'child_of', self.location_id.id)]).mapped('id')
# Creating Temp dictionry for Product List
if data["product_sub_categ_id"]:
for resource in self.env['stock.quant'].search(
['|', ('location_id', '=', self.location_id.id), ('location_id', 'in', child_loc_ids)]):
if resource.product_id.categ_id.id == data[
"product_sub_categ_id"] or resource.product_id.categ_id.parent_id.id == data[
"product_sub_categ_id"]:
line_ids_filterd_categ.append({
'location_id': resource.location_id.id,
'product_id': resource.product_id.id,
'product_categ_id': resource.product_id.categ_id.parent_id.id,
'product_sub_categ_id': resource.product_id.categ_id.id,
'product_uom_id': resource.product_id.uom_id.id,
'qty': resource.qty,
'standard_price': resource.product_id.standard_price,
})
else:
for resource in self.env['stock.quant'].search(
['|', ('location_id', '=', self.location_id.id), ('location_id', 'in', child_loc_ids)]):
line_ids_all_categ.append({
'location_id': resource.location_id.id,
'product_id': resource.product_id.id,
'product_categ_id': resource.product_id.categ_id.parent_id.id,
'product_sub_categ_id': resource.product_id.categ_id.id,
'product_uom_id': resource.product_id.uom_id.id,
'qty': resource.qty,
'standard_price': resource.product_id.standard_price,
})
if data["product_sub_categ_id"]:
# Merging stock moves into single product item line
grouper = itemgetter("product_id", "product_categ_id", "product_sub_categ_id", "location_id",
"product_uom_id", "standard_price")
for key, grp in groupby(sorted(line_ids_filterd_categ, key=grouper), grouper):
temp_dict = dict(zip(
["product_id", "product_categ_id", "product_sub_categ_id", "location_id", "product_uom_id",
"standard_price"], key))
temp_dict["qty"] = sum(item["qty"] for item in grp)
temp_dict["amount"] = temp_dict["standard_price"] * temp_dict["qty"]
line_ids.append((0, 0, temp_dict))
else:
# Merging stock moves into single product item line
grouper = itemgetter("product_id", "product_categ_id", "product_sub_categ_id", "location_id",
"product_uom_id", "standard_price")
for key, grp in groupby(sorted(line_ids_all_categ, key=grouper), grouper):
temp_dict = dict(zip(
["product_id", "product_categ_id", "product_sub_categ_id", "location_id", "product_uom_id",
"standard_price"], key))
temp_dict["qty"] = sum(item["qty"] for item in grp)
temp_dict["amount"] = temp_dict["standard_price"] * temp_dict["qty"]
line_ids.append((0, 0, temp_dict))
if len(line_ids) == 0:
raise ValidationError(_('Material is not available on this location.'))
# writing to One2many line_ids
self.write({'line_ids': line_ids})
context = {
'lang': 'en_US',
'active_ids': [self.id],
}
return {
'context': context,
'data': None,
'type': 'ir.actions.report.xml',
'report_name': 'dvit_report_inventory_valuation_multi_uom.report_stock_inventory_location',
'report_type': 'qweb-pdf',
'report_file': 'dvit_report_inventory_valuation_multi_uom.report_stock_inventory_location',
'name': 'Stock Inventory',
'flags': {'action_buttons': True},
}
class WizardValuationStockInventoryLine(models.TransientModel):
_name = 'wizard.valuation.stock.inventory.line'
wizard_id = fields.Many2one('wizard.valuation.stock.inventory', required=True, ondelete='cascade')
location_id = fields.Many2one('stock.location', 'Location')
product_id = fields.Many2one('product.product', 'Product')
product_categ_id = fields.Many2one('product.category', string='Category')
product_sub_categ_id = fields.Many2one('product.category', string='Sub Category')
product_uom_id = fields.Many2one('product.uom')
qty = fields.Float('Quantity')
standard_price = fields.Float('Rate')
amount = fields.Float('Amount')
@api.model
def convert_qty_in_uom(self, from_uom, to_uom, qty):
return (qty / from_uom.factor) * to_uom.factor
| mohamedhagag/dvit-odoo | dvit_report_inventory_valuation_multi_uom/wizard/stock_quant_report.py | Python | agpl-3.0 | 6,534 |
"""
This module contains signals related to enterprise.
"""
import logging
import six
from django.conf import settings
from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user
from django.db.models.signals import post_save, pre_save
from django.dispatch import receiver
from enterprise.models import EnterpriseCourseEnrollment, EnterpriseCustomer, EnterpriseCustomerUser
from integrated_channels.integrated_channel.tasks import (
transmit_single_learner_data,
transmit_single_subsection_learner_data
)
from slumber.exceptions import HttpClientError
from lms.djangoapps.email_marketing.tasks import update_user
from openedx.core.djangoapps.commerce.utils import ecommerce_api_client
from openedx.core.djangoapps.signals.signals import COURSE_GRADE_NOW_PASSED, COURSE_ASSESSMENT_GRADE_CHANGED
from openedx.features.enterprise_support.api import enterprise_enabled
from openedx.features.enterprise_support.tasks import clear_enterprise_customer_data_consent_share_cache
from openedx.features.enterprise_support.utils import clear_data_consent_share_cache, is_enterprise_learner
from common.djangoapps.student.signals import UNENROLL_DONE
log = logging.getLogger(__name__)
@receiver(post_save, sender=EnterpriseCustomerUser)
def update_email_marketing_user_with_enterprise_vars(sender, instance, **kwargs): # pylint: disable=unused-argument, invalid-name
"""
Update the SailThru user with enterprise-related vars.
"""
user = User.objects.get(id=instance.user_id)
# perform update asynchronously
update_user.delay(
sailthru_vars={
'is_enterprise_learner': True,
'enterprise_name': instance.enterprise_customer.name,
},
email=user.email
)
@receiver(post_save, sender=EnterpriseCourseEnrollment)
def update_dsc_cache_on_course_enrollment(sender, instance, **kwargs): # pylint: disable=unused-argument
"""
clears data_sharing_consent_needed cache after Enterprise Course Enrollment
"""
clear_data_consent_share_cache(
instance.enterprise_customer_user.user_id,
instance.course_id
)
@receiver(pre_save, sender=EnterpriseCustomer)
def update_dsc_cache_on_enterprise_customer_update(sender, instance, **kwargs):
"""
clears data_sharing_consent_needed cache after enable_data_sharing_consent flag is changed.
"""
old_instance = sender.objects.filter(pk=instance.uuid).first()
if old_instance: # instance already exists, so it's updating.
new_value = instance.enable_data_sharing_consent
old_value = old_instance.enable_data_sharing_consent
if new_value != old_value:
kwargs = {'enterprise_customer_uuid': six.text_type(instance.uuid)}
result = clear_enterprise_customer_data_consent_share_cache.apply_async(kwargs=kwargs)
log.info(u"DSC: Created {task_name}[{task_id}] with arguments {kwargs}".format(
task_name=clear_enterprise_customer_data_consent_share_cache.name,
task_id=result.task_id,
kwargs=kwargs,
))
@receiver(COURSE_GRADE_NOW_PASSED, dispatch_uid="new_passing_enterprise_learner")
def handle_enterprise_learner_passing_grade(sender, user, course_id, **kwargs): # pylint: disable=unused-argument
"""
Listen for a learner passing a course, transmit data to relevant integrated channel
"""
if enterprise_enabled() and is_enterprise_learner(user):
kwargs = {
'username': six.text_type(user.username),
'course_run_id': six.text_type(course_id)
}
transmit_single_learner_data.apply_async(kwargs=kwargs)
@receiver(COURSE_ASSESSMENT_GRADE_CHANGED)
def handle_enterprise_learner_subsection(sender, user, course_id, subsection_id, subsection_grade, **kwargs): # pylint: disable=unused-argument
"""
Listen for an enterprise learner completing a subsection, transmit data to relevant integrated channel.
"""
if enterprise_enabled() and is_enterprise_learner(user):
kwargs = {
'username': str(user.username),
'course_run_id': str(course_id),
'subsection_id': str(subsection_id),
'grade': str(subsection_grade),
}
transmit_single_subsection_learner_data.apply_async(kwargs=kwargs)
@receiver(UNENROLL_DONE)
def refund_order_voucher(sender, course_enrollment, skip_refund=False, **kwargs): # pylint: disable=unused-argument
"""
Call the /api/v2/enterprise/coupons/create_refunded_voucher/ API to create new voucher and assign it to user.
"""
if skip_refund:
return
if not course_enrollment.refundable():
return
if not EnterpriseCourseEnrollment.objects.filter(
enterprise_customer_user__user_id=course_enrollment.user_id,
course_id=str(course_enrollment.course.id)
).exists():
return
service_user = User.objects.get(username=settings.ECOMMERCE_SERVICE_WORKER_USERNAME)
client = ecommerce_api_client(service_user)
order_number = course_enrollment.get_order_attribute_value('order_number')
if order_number:
error_message = u"Encountered {} from ecommerce while creating refund voucher. Order={}, enrollment={}, user={}"
try:
client.enterprise.coupons.create_refunded_voucher.post({"order": order_number})
except HttpClientError as ex:
log.info(
error_message.format(type(ex).__name__, order_number, course_enrollment, course_enrollment.user)
)
except Exception as ex: # pylint: disable=broad-except
log.exception(
error_message.format(type(ex).__name__, order_number, course_enrollment, course_enrollment.user)
)
| stvstnfrd/edx-platform | openedx/features/enterprise_support/signals.py | Python | agpl-3.0 | 5,796 |
from django.core.management.base import BaseCommand, CommandError
from mangaki.models import Work, Rating
from django.db import connection
from django.db.models import Count
from collections import Counter
import sys
class Command(BaseCommand):
args = ''
help = 'Lookup some work'
def handle(self, *args, **options):
work = Work.objects.filter(title__icontains=args[0]).annotate(Count('rating')).order_by('-rating__count')[0]
print(work.title, work.id)
nb = Counter()
for rating in Rating.objects.filter(work=work):
nb[rating.choice] += 1
print(nb)
| RaitoBezarius/mangaki | mangaki/mangaki/management/commands/lookup.py | Python | agpl-3.0 | 616 |
"""
Settings for Bok Choy tests that are used when running LMS.
Bok Choy uses two different settings files:
1. test_static_optimized is used when invoking collectstatic
2. bok_choy is used when running the tests
Note: it isn't possible to have a single settings file, because Django doesn't
support both generating static assets to a directory and also serving static
from the same directory.
"""
import os
from path import Path as path
from tempfile import mkdtemp
from openedx.core.release import RELEASE_LINE
CONFIG_ROOT = path(__file__).abspath().dirname()
TEST_ROOT = CONFIG_ROOT.dirname().dirname() / "test_root"
########################## Prod-like settings ###################################
# These should be as close as possible to the settings we use in production.
# As in prod, we read in environment and auth variables from JSON files.
# Unlike in prod, we use the JSON files stored in this repo.
# This is a convenience for ensuring (a) that we can consistently find the files
# and (b) that the files are the same in Jenkins as in local dev.
os.environ['SERVICE_VARIANT'] = 'bok_choy'
os.environ['CONFIG_ROOT'] = CONFIG_ROOT
from .aws import * # pylint: disable=wildcard-import, unused-wildcard-import
######################### Testing overrides ####################################
# Redirect to the test_root folder within the repo
GITHUB_REPO_ROOT = (TEST_ROOT / "data").abspath()
LOG_DIR = (TEST_ROOT / "log").abspath()
# Configure modulestore to use the test folder within the repo
update_module_store_settings(
MODULESTORE,
module_store_options={
'fs_root': (TEST_ROOT / "data").abspath(),
},
xml_store_options={
'data_dir': (TEST_ROOT / "data").abspath(),
},
default_store=os.environ.get('DEFAULT_STORE', 'draft'),
)
############################ STATIC FILES #############################
# Enable debug so that static assets are served by Django
DEBUG = True
# Serve static files at /static directly from the staticfiles directory under test root
# Note: optimized files for testing are generated with settings from test_static_optimized
STATIC_URL = "/static/"
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
)
STATICFILES_DIRS = [
(TEST_ROOT / "staticfiles" / "lms").abspath(),
]
DEFAULT_FILE_STORAGE = 'django.core.files.storage.FileSystemStorage'
MEDIA_ROOT = TEST_ROOT / "uploads"
# Webpack loader must use webpack output setting
WEBPACK_LOADER['DEFAULT']['STATS_FILE'] = TEST_ROOT / "staticfiles" / "lms" / "webpack-stats.json"
# Don't use compression during tests
PIPELINE_JS_COMPRESSOR = None
################################# CELERY ######################################
CELERY_ALWAYS_EAGER = True
CELERY_RESULT_BACKEND = 'djcelery.backends.cache:CacheBackend'
BLOCK_STRUCTURES_SETTINGS = dict(
# We have CELERY_ALWAYS_EAGER set to True, so there's no asynchronous
# code running and the celery routing is unimportant.
# It does not make sense to retry.
TASK_MAX_RETRIES=0,
# course publish task delay is irrelevant is because the task is run synchronously
COURSE_PUBLISH_TASK_DELAY=0,
# retry delay is irrelevent because we never retry
TASK_DEFAULT_RETRY_DELAY=0,
)
###################### Grade Downloads ######################
GRADES_DOWNLOAD = {
'STORAGE_TYPE': 'localfs',
'BUCKET': 'edx-grades',
'ROOT_PATH': os.path.join(mkdtemp(), 'edx-s3', 'grades'),
}
# Configure the LMS to use our stub XQueue implementation
XQUEUE_INTERFACE['url'] = 'http://localhost:8040'
# Configure the LMS to use our stub EdxNotes implementation
EDXNOTES_PUBLIC_API = 'http://localhost:8042/api/v1'
EDXNOTES_INTERNAL_API = 'http://localhost:8042/api/v1'
EDXNOTES_CONNECT_TIMEOUT = 10 # time in seconds
EDXNOTES_READ_TIMEOUT = 10 # time in seconds
NOTES_DISABLED_TABS = []
# Silence noisy logs
import logging
LOG_OVERRIDES = [
('track.middleware', logging.CRITICAL),
('edxmako.shortcuts', logging.ERROR),
('dd.dogapi', logging.ERROR),
('edx.discussion', logging.CRITICAL),
]
for log_name, log_level in LOG_OVERRIDES:
logging.getLogger(log_name).setLevel(log_level)
# Enable milestones app
FEATURES['MILESTONES_APP'] = True
# Enable oauth authentication, which we test.
FEATURES['ENABLE_OAUTH2_PROVIDER'] = True
# Enable pre-requisite course
FEATURES['ENABLE_PREREQUISITE_COURSES'] = True
# Enable Course Discovery
FEATURES['ENABLE_COURSE_DISCOVERY'] = True
# Enable student notes
FEATURES['ENABLE_EDXNOTES'] = True
# Enable teams feature
FEATURES['ENABLE_TEAMS'] = True
# Enable custom content licensing
FEATURES['LICENSING'] = True
# Use the auto_auth workflow for creating users and logging them in
FEATURES['AUTOMATIC_AUTH_FOR_TESTING'] = True
# Open up endpoint for faking Software Secure responses
FEATURES['ENABLE_SOFTWARE_SECURE_FAKE'] = True
FEATURES['ENABLE_ENROLLMENT_TRACK_USER_PARTITION'] = True
########################### Entrance Exams #################################
FEATURES['ENTRANCE_EXAMS'] = True
FEATURES['ENABLE_SPECIAL_EXAMS'] = True
# Point the URL used to test YouTube availability to our stub YouTube server
YOUTUBE_PORT = 9080
YOUTUBE['TEST_TIMEOUT'] = 5000
YOUTUBE['API'] = "http://127.0.0.1:{0}/get_youtube_api/".format(YOUTUBE_PORT)
YOUTUBE['METADATA_URL'] = "http://127.0.0.1:{0}/test_youtube/".format(YOUTUBE_PORT)
YOUTUBE['TEXT_API']['url'] = "127.0.0.1:{0}/test_transcripts_youtube/".format(YOUTUBE_PORT)
############################# SECURITY SETTINGS ################################
# Default to advanced security in common.py, so tests can reset here to use
# a simpler security model
FEATURES['ENFORCE_PASSWORD_POLICY'] = False
FEATURES['ENABLE_MAX_FAILED_LOGIN_ATTEMPTS'] = False
FEATURES['SQUELCH_PII_IN_LOGS'] = False
FEATURES['PREVENT_CONCURRENT_LOGINS'] = False
FEATURES['ADVANCED_SECURITY'] = False
FEATURES['ENABLE_MOBILE_REST_API'] = True # Show video bumper in LMS
FEATURES['ENABLE_VIDEO_BUMPER'] = True # Show video bumper in LMS
FEATURES['SHOW_BUMPER_PERIODICITY'] = 1
PASSWORD_MIN_LENGTH = None
PASSWORD_COMPLEXITY = {}
# Enable courseware search for tests
FEATURES['ENABLE_COURSEWARE_SEARCH'] = True
# Enable dashboard search for tests
FEATURES['ENABLE_DASHBOARD_SEARCH'] = True
# discussion home panel, which includes a subscription on/off setting for discussion digest emails.
FEATURES['ENABLE_DISCUSSION_HOME_PANEL'] = True
# Enable support for OpenBadges accomplishments
FEATURES['ENABLE_OPENBADGES'] = True
# Use MockSearchEngine as the search engine for test scenario
SEARCH_ENGINE = "search.tests.mock_search_engine.MockSearchEngine"
# Path at which to store the mock index
MOCK_SEARCH_BACKING_FILE = (
TEST_ROOT / "index_file.dat"
).abspath()
# Verify student settings
VERIFY_STUDENT["SOFTWARE_SECURE"] = {
"API_ACCESS_KEY": "BBBBBBBBBBBBBBBBBBBB",
"API_SECRET_KEY": "CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC",
}
# this secret key should be the same as cms/envs/bok_choy.py's
SECRET_KEY = "very_secret_bok_choy_key"
# Set dummy values for profile image settings.
PROFILE_IMAGE_BACKEND = {
'class': 'storages.backends.overwrite.OverwriteStorage',
'options': {
'location': os.path.join(MEDIA_ROOT, 'profile-images/'),
'base_url': os.path.join(MEDIA_URL, 'profile-images/'),
},
}
# Make sure we test with the extended history table
FEATURES['ENABLE_CSMH_EXTENDED'] = True
INSTALLED_APPS += ('coursewarehistoryextended',)
BADGING_BACKEND = 'lms.djangoapps.badges.backends.tests.dummy_backend.DummyBackend'
# Configure the LMS to use our stub eCommerce implementation
ECOMMERCE_API_URL = 'http://localhost:8043/api/v2/'
LMS_ROOT_URL = "http://localhost:8000"
if RELEASE_LINE == "master":
# On master, acceptance tests use edX books, not the default Open edX books.
HELP_TOKENS_BOOKS = {
'learner': 'http://edx.readthedocs.io/projects/edx-guide-for-students',
'course_author': 'http://edx.readthedocs.io/projects/edx-partner-course-staff',
}
# TODO: TNL-6546: Remove this waffle and flag code.
from django.db.utils import ProgrammingError
from waffle.models import Flag
try:
flag, created = Flag.objects.get_or_create(name='unified_course_view')
WAFFLE_OVERRIDE = True
except ProgrammingError:
# during initial reset_db, the table for the flag doesn't yet exist.
pass
#####################################################################
# Lastly, see if the developer has any local overrides.
try:
from .private import * # pylint: disable=import-error
except ImportError:
pass
| fintech-circle/edx-platform | lms/envs/bok_choy.py | Python | agpl-3.0 | 8,553 |
from django.contrib.auth.models import User
from django.db import models
from django.utils import timezone
from website.models import Issue
# Create your models here.
class Comment(models.Model):
parent = models.ForeignKey('self', null=True, on_delete=models.CASCADE)
issue = models.ForeignKey(Issue, on_delete=models.CASCADE, related_name='comments')
author = models.CharField(max_length=200)
author_url = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.text
def children(self):
return Comment.objects.filter(parent=self)
| Bugheist/website | comments/models.py | Python | agpl-3.0 | 679 |
# -*- coding: utf-8 -*-
# © 2016 Therp BV <http://therp.nl>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from psycopg2 import ProgrammingError
from openerp.modules.registry import RegistryManager
from openerp.tools import config
from openerp.tests.common import TransactionCase, at_install, post_install
# Use post_install to get all models loaded more info: odoo/odoo#13458
@at_install(False)
@post_install(True)
class TestDatabaseCleanup(TransactionCase):
def setUp(self):
super(TestDatabaseCleanup, self).setUp()
self.module = None
self.model = None
def test_database_cleanup(self):
# create an orphaned column
self.cr.execute(
'alter table res_partner add column database_cleanup_test int')
# We need use a model that is not blocked (Avoid use res.users)
partner_model = self.env['ir.model'].search([
('model', '=', 'res.partner')], limit=1)
purge_columns = self.env['cleanup.purge.wizard.column'].create({
'purge_line_ids': [(0, 0, {
'model_id': partner_model.id, 'name': 'database_cleanup_test'}
)]})
purge_columns.purge_all()
# must be removed by the wizard
with self.assertRaises(ProgrammingError):
with self.registry.cursor() as cr:
cr.execute('select database_cleanup_test from res_partner')
# create a data entry pointing nowhere
self.cr.execute('select max(id) + 1 from res_users')
self.env['ir.model.data'].create({
'module': 'database_cleanup',
'name': 'test_no_data_entry',
'model': 'res.users',
'res_id': self.cr.fetchone()[0],
})
purge_data = self.env['cleanup.purge.wizard.data'].create({})
purge_data.purge_all()
# must be removed by the wizard
with self.assertRaises(ValueError):
self.env.ref('database_cleanup.test_no_data_entry')
# create a nonexistent model
self.model = self.env['ir.model'].create({
'name': 'Database cleanup test model',
'model': 'x_database.cleanup.test.model',
})
self.env.cr.execute(
'insert into ir_attachment (name, res_model, res_id, type) values '
"('test attachment', 'database.cleanup.test.model', 42, 'binary')")
self.registry.models.pop('x_database.cleanup.test.model')
self.registry._pure_function_fields.pop(
'x_database.cleanup.test.model')
purge_models = self.env['cleanup.purge.wizard.model'].create({})
with self.assertRaisesRegexp(KeyError,
'x_database.cleanup.test.model'):
# TODO: Remove with-assert of KeyError after fix:
# https://github.com/odoo/odoo/pull/13978/files#r88654967
purge_models.purge_all()
# must be removed by the wizard
self.assertFalse(self.env['ir.model'].search([
('model', '=', 'x_database.cleanup.test.model'),
]))
# create a nonexistent module
self.module = self.env['ir.module.module'].create({
'name': 'database_cleanup_test',
'state': 'to upgrade',
})
purge_modules = self.env['cleanup.purge.wizard.module'].create({})
# this reloads our registry, and we don't want to run tests twice
# we also need the original registry for further tests, so save a
# reference to it
original_registry = RegistryManager.registries[self.env.cr.dbname]
config.options['test_enable'] = False
purge_modules.purge_all()
config.options['test_enable'] = True
# must be removed by the wizard
self.assertFalse(self.env['ir.module.module'].search([
('name', '=', 'database_cleanup_test'),
]))
# reset afterwards
RegistryManager.registries[self.env.cr.dbname] = original_registry
# create an orphaned table
self.env.cr.execute('create table database_cleanup_test (test int)')
purge_tables = self.env['cleanup.purge.wizard.table'].create({})
purge_tables.purge_all()
with self.assertRaises(ProgrammingError):
with self.registry.cursor() as cr:
self.env.cr.execute('select * from database_cleanup_test')
def tearDown(self):
super(TestDatabaseCleanup, self).tearDown()
with self.registry.cursor() as cr2:
# Release blocked tables with pending deletes
self.env.cr.rollback()
if self.module:
cr2.execute(
"DELETE FROM ir_module_module WHERE id=%s",
(self.module.id,))
if self.model:
cr2.execute(
"DELETE FROM ir_model WHERE id=%s",
(self.model.id,))
cr2.commit()
| be-cloud-be/horizon-addons | server-tools/database_cleanup/tests/test_database_cleanup.py | Python | agpl-3.0 | 4,939 |
from flask_wtf import FlaskForm
from . import app
from wtforms import StringField, PasswordField, SelectField, DateField, IntegerField
from wtforms.validators import DataRequired, Length, Email, EqualTo, Optional, NumberRange
from wtfrecaptcha.fields import RecaptchaField
from flask_wtf.file import FileField, FileAllowed, FileRequired
class LoginForm(FlaskForm):
email = StringField('Email', validators=[DataRequired(), Email(), Length(min=6, max=40)])
password = PasswordField('Password', validators=[DataRequired()])
class RegistrationForm(FlaskForm):
first_name = StringField('First Name', validators=[DataRequired(), Length(min=2, max=40)])
last_name = StringField('Last Name', validators=[DataRequired(), Length(min=2, max=40)])
email = StringField('Email', validators=[DataRequired(), Email(), Length(min=6, max=40)])
username = StringField('Username', validators=[DataRequired(), Length(min=4, max=40)])
password = PasswordField('New Password', [
DataRequired(),
EqualTo('confirm', message='Passwords must match')
])
confirm = PasswordField('Repeat Password')
captcha = RecaptchaField(public_key=app.config['RECAPTCHA_PUB_KEY'], private_key=app.config['RECAPTCHA_PRIV_KEY'],
secure=True)
class LicenseKeyForm(FlaskForm):
category = SelectField('Category', choices=[(1, 'Premium'), (2, 'VIP')], coerce=int)
license_key = StringField('License Key', validators=[DataRequired(), Length(min=29, max=29)])
username = StringField('Sender Username', validators=[DataRequired(), Length(min=4, max=40)])
class CreditKeyForm(FlaskForm):
license_key = StringField('License Key', validators=[DataRequired(), Length(min=29, max=29)])
username = StringField('Sender Username', validators=[DataRequired(), Length(min=4, max=40)])
class ImageUpload(FlaskForm):
upload = FileField('Image Upload', validators=[FileRequired(), FileAllowed(['jpg', 'png'], 'Images only!')])
class BuyLicense(FlaskForm):
category = SelectField('Category', choices=[(1, 'VIP'), (2, 'Premium')], coerce=int)
qty = SelectField('Qty', choices=[(1, '30 Days'), (2, '60 Days'), (3, '90 Days')], coerce=int)
class CreateLicense(FlaskForm):
category = SelectField('Category', choices=[(1, 'Premium'), (2, 'VIP')], coerce=int)
qty = SelectField('Qty', choices=[(1, '30 Days'), (2, '60 Days'), (3, '90 Days')], coerce=int)
valid_date = DateField('Expiration Date', format='%d/%m/%Y', validators=(DataRequired(),))
class ShareCredits(FlaskForm):
qty = SelectField('Credits', choices=[(1, '10'), (2, '20'), (3, '25')], coerce=int)
class ShareKey(FlaskForm):
category = SelectField('Category', choices=[(1, 'Premium'), (2, 'VIP')], coerce=int)
qty = IntegerField('Qty', validators=[DataRequired(), NumberRange(min=1, max=100)])
valid_date = DateField('Expiration Date', format='%d/%m/%Y', validators=(DataRequired(),))
class GenerateCredits(FlaskForm):
qty = IntegerField('Credits', validators=[DataRequired(), NumberRange(min=1, max=100)])
class TrialForm(FlaskForm):
password = StringField('Password', validators=[DataRequired(), Length(min=6, max=29)])
class MyPage(FlaskForm):
facebook_url = StringField('Facebook', validators=[DataRequired(), Length(min=6, max=29)])
twitter_url = StringField('Twitter', validators=[Optional(), Length(min=6, max=29)])
class MyPageInfo(FlaskForm):
info = StringField('Information', validators=[DataRequired()])
payment_method = StringField('Payment Method', validators=[DataRequired()])
class ChangePassword(FlaskForm):
password = PasswordField('New Password', [
DataRequired(),
EqualTo('confirm', message='Passwords must match')
])
confirm = PasswordField('Repeat Password')
class LockAccount(FlaskForm):
confirm = StringField('Confirm', validators=[DataRequired(), Length(min=3, max=50)])
class ProfileSettings(FlaskForm):
first_name = StringField('First Name', validators=[DataRequired(), Length(min=2, max=40)])
last_name = StringField('Last Name', validators=[DataRequired(), Length(min=2, max=40)]) | lfasmpao/safecore-api | dashboard/forms.py | Python | agpl-3.0 | 4,140 |
"""
Grades related signals.
"""
from django.dispatch import Signal
# Signal that indicates that a user's score for a problem has been updated.
# This signal is generated when a scoring event occurs either within the core
# platform or in the Submissions module. Note that this signal will be triggered
# regardless of the new and previous values of the score (i.e. it may be the
# case that this signal is generated when a user re-attempts a problem but
# receives the same score).
PROBLEM_SCORE_CHANGED = Signal(
providing_args=[
'user_id', # Integer User ID
'course_id', # Unicode string representing the course
'usage_id', # Unicode string indicating the courseware instance
'points_earned', # Score obtained by the user
'points_possible', # Maximum score available for the exercise
'only_if_higher', # Boolean indicating whether updates should be
# made only if the new score is higher than previous.
]
)
# Signal that indicates that a user's score for a problem has been published
# for possible persistence and update. Typically, most clients should listen
# to the PROBLEM_SCORE_CHANGED signal instead, since that is signalled only after the
# problem's score is changed.
SCORE_PUBLISHED = Signal(
providing_args=[
'block', # Course block object
'user', # User object
'raw_earned', # Score obtained by the user
'raw_possible', # Maximum score available for the exercise
'only_if_higher', # Boolean indicating whether updates should be
# made only if the new score is higher than previous.
]
)
# Signal that indicates that a user's score for a subsection has been updated.
# This is a downstream signal of PROBLEM_SCORE_CHANGED sent for each affected containing
# subsection.
SUBSECTION_SCORE_CHANGED = Signal(
providing_args=[
'course', # Course object
'user', # User object
'subsection_grade', # SubsectionGrade object
]
)
| itsjeyd/edx-platform | lms/djangoapps/grades/signals/signals.py | Python | agpl-3.0 | 2,050 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2012 Adriano Monteiro Marques
#
# Author: Piotrek Wasilewski <wasilewski.piotrek@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
from djangoappengine.settings_base import *
DEBUG = True
# By default Django disables debug mode when running test. However in webapi
# tests we need to know if DEBUG was set to True, otherwise testing this
# application would be difficult.
API_TEST_DEBUG = True if DEBUG else False
if DEBUG:
STATICFILES_DIRS = (
os.path.join(os.path.dirname(__file__), 'static'),
)
else:
STATIC_ROOT = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'static')
STATIC_URL = '/static/'
ADMIN_MEDIA_PREFIX = '%sadmin/' % STATIC_URL
SECRET_KEY = '=r-$b*8hglm+858&9t043hlm6-&6-3d3vfc4((7yd0dbrakhvi'
AUTH_PROFILE_MODULE = 'users.UserProfile'
SITE_ID = 1
SITE_DOMAIN = 'example.appspot.com'
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'America/Chicago'
USE_I18N = True
USE_L10N = True
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.contenttypes',
'django.contrib.auth',
'django.contrib.sessions',
'piston',
)
if DEBUG:
INSTALLED_APPS += ('django.contrib.staticfiles',)
NETADMIN_APPS = (
'netadmin',
'netadmin.reportmeta',
'netadmin.webapi',
'netadmin.networks',
'netadmin.events',
'netadmin.users',
'netadmin.permissions',
'netadmin.notifier',
'netadmin.utils.charts',
'netadmin.plugins'
)
INSTALLED_APPS += NETADMIN_APPS
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
)
TEMPLATE_CONTEXT_PROCESSORS = (
'django.contrib.auth.context_processors.auth',
'django.core.context_processors.static',
'django.core.context_processors.request',
'django.core.context_processors.media',
)
TEMPLATE_DIRS = (
os.path.join(os.path.dirname(__file__), 'templates'),
)
ROOT_URLCONF = 'urls'
LOGIN_URL = '/login/'
ACTIVATION_FROM_EMAIL = 'your_email@example.com'
DATABASES['native'] = DATABASES['default']
DATABASES['default'] = {'ENGINE': 'dbindexer', 'TARGET': 'native'}
GAE_APPS = (
'djangotoolbox',
'dbindexer',
'permission_backend_nonrel',
'autoload',
'search',
'djangoappengine',
)
INSTALLED_APPS += GAE_APPS
AUTHENTICATION_BACKENDS = (
'permission_backend_nonrel.backends.NonrelPermissionBackend',
)
MIDDLEWARE_CLASSES += (
'autoload.middleware.AutoloadMiddleware',
)
TEST_RUNNER = 'djangotoolbox.test.CapturingTestSuiteRunner'
GAE_MAIL_ACCOUNT = 'your_email@example.com'
AUTOLOAD_SITECONF = 'search_indexes'
if DEBUG:
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
else:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
try:
from local_settings import *
except ImportError:
pass
| umitproject/network-admin | gae_settings.py | Python | agpl-3.0 | 3,537 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10b1 on 2016-09-17 02:14
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('timeblob', '0006_auto_20160820_1908'),
]
operations = [
migrations.AddField(
model_name='project',
name='description',
field=models.TextField(default=''),
preserve_default=False,
),
migrations.AddField(
model_name='task',
name='description',
field=models.TextField(default=''),
preserve_default=False,
),
]
| dkieffer/timeblob | timeblob/migrations/0007_add_descriptions_to_project_and_tasks.py | Python | agpl-3.0 | 676 |
from builtins import str
from builtins import object
import smtplib
import email.utils
from biomaj.workflow import Workflow
import logging
import sys
if sys.version < '3':
from email.MIMEText import MIMEText
else:
from email.mime.text import MIMEText
class Notify(object):
"""
Send notifications
"""
@staticmethod
def notifyBankAction(bank):
if not bank.config.get('mail.smtp.host') or bank.session is None:
logging.info('Notify:none')
return
admins = bank.config.get('mail.admin')
if not admins:
logging.info('Notify: no mail.admin defined')
return
admin_list = admins.split(',')
logging.info('Notify:' + bank.config.get('mail.admin'))
mfrom = bank.config.get('mail.from')
log_file = bank.config.log_file
msg = MIMEText('')
if log_file:
fp = None
if sys.version < '3':
fp = open(log_file, 'rb')
else:
fp = open(log_file, 'r')
msg = MIMEText(fp.read(2000000))
fp.close()
msg['From'] = email.utils.formataddr(('Author', mfrom))
msg['Subject'] = 'BANK[' + bank.name + '] - STATUS[' + str(bank.session.get_status(Workflow.FLOW_OVER)) + '] - UPDATE[' + str(bank.session.get('update')) + '] - REMOVE[' + str(bank.session.get('remove')) + ']' + ' - RELEASE[' + str(bank.session.get('release')) + ']'
logging.info(msg['subject'])
server = None
for mto in admin_list:
msg['To'] = email.utils.formataddr(('Recipient', mto))
try:
server = smtplib.SMTP(bank.config.get('mail.smtp.host'))
if bank.config.get('mail.tls') is not None and str(bank.config.get('mail.tls')) == 'true':
server.starttls()
if bank.config.get('mail.user') is not None and str(bank.config.get('mail.user')) != '':
server.login(bank.config.get('mail.user'), bank.config.get('mail.password'))
server.sendmail(mfrom, [mto], msg.as_string())
except Exception as e:
logging.error('Could not send email: ' + str(e))
finally:
if server is not None:
server.quit()
| horkko/biomaj | biomaj/notify.py | Python | agpl-3.0 | 2,306 |
# Copyright 2020 ScyllaDB
#
# This file is part of Scylla.
#
# Scylla is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Scylla 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 Affero General Public License
# along with Scylla. If not, see <http://www.gnu.org/licenses/>.
# Tests for stream operations: ListStreams, DescribeStream, GetShardIterator,
# GetRecords.
import pytest
import time
import urllib.request
from botocore.exceptions import ClientError
from util import list_tables, test_table_name, create_test_table, random_string, freeze
from contextlib import contextmanager
from urllib.error import URLError
from boto3.dynamodb.types import TypeDeserializer
stream_types = [ 'OLD_IMAGE', 'NEW_IMAGE', 'KEYS_ONLY', 'NEW_AND_OLD_IMAGES']
def disable_stream(dynamodbstreams, table):
while True:
try:
table.update(StreamSpecification={'StreamEnabled': False});
while True:
streams = dynamodbstreams.list_streams(TableName=table.name)
if not streams.get('Streams'):
return
# when running against real dynamodb, modifying stream
# state has a delay. need to wait for propagation.
print("Stream(s) lingering. Sleep 10s...")
time.sleep(10)
except ClientError as ce:
# again, real dynamo has periods when state cannot yet
# be modified.
if ce.response['Error']['Code'] == 'ResourceInUseException':
print("Stream(s) in use. Sleep 10s...")
time.sleep(10)
continue
raise
#
# Cannot use fixtures. Because real dynamodb cannot _remove_ a stream
# once created. It can only expire 24h later. So reusing test_table for
# example works great for scylla/local testing, but once we run against
# actual aws instances, we get lingering streams, and worse: cannot
# create new ones to replace it, because we have overlapping types etc.
#
# So we have to create and delete a table per test. And not run this
# test to often against aws.
@contextmanager
def create_stream_test_table(dynamodb, StreamViewType=None):
spec = { 'StreamEnabled': False }
if StreamViewType != None:
spec = {'StreamEnabled': True, 'StreamViewType': StreamViewType}
table = create_test_table(dynamodb, StreamSpecification=spec,
KeySchema=[ { 'AttributeName': 'p', 'KeyType': 'HASH' },
{ 'AttributeName': 'c', 'KeyType': 'RANGE' }
],
AttributeDefinitions=[
{ 'AttributeName': 'p', 'AttributeType': 'S' },
{ 'AttributeName': 'c', 'AttributeType': 'S' },
])
yield table
while True:
try:
table.delete()
return
except ClientError as ce:
# if the table has a stream currently being created we cannot
# delete the table immediately. Again, only with real dynamo
if ce.response['Error']['Code'] == 'ResourceInUseException':
print('Could not delete table yet. Sleeping 5s.')
time.sleep(5)
continue;
raise
def wait_for_active_stream(dynamodbstreams, table, timeout=60):
exp = time.process_time() + timeout
while time.process_time() < exp:
streams = dynamodbstreams.list_streams(TableName=table.name)
for stream in streams['Streams']:
desc = dynamodbstreams.describe_stream(StreamArn=stream['StreamArn'])['StreamDescription']
if not 'StreamStatus' in desc or desc.get('StreamStatus') == 'ENABLED':
arn = stream['StreamArn']
if arn != None:
return arn;
# real dynamo takes some time until a stream is usable
print("Stream not available. Sleep 5s...")
time.sleep(5)
assert False
# Local java dynamodb server version behaves differently from
# the "real" one. Most importantly, it does not verify a number of
# parameters, and consequently does not throw when called with borked
# args. This will try to check if we are in fact running against
# this test server, and if so, just raise the error here and be done
# with it. All this just so we can run through the tests on
# aws, scylla and local.
def is_local_java(dynamodbstreams):
# no good way to check, but local server runs on a Jetty,
# so check for that.
url = dynamodbstreams.meta.endpoint_url
try:
urllib.request.urlopen(url)
except URLError as e:
return e.info()['Server'].startswith('Jetty')
return False
def ensure_java_server(dynamodbstreams, error='ValidationException'):
# no good way to check, but local server has a "shell" builtin,
# so check for that.
if is_local_java(dynamodbstreams):
if error != None:
raise ClientError({'Error': { 'Code' : error }}, '')
return
assert False
def test_list_streams_create(dynamodb, dynamodbstreams):
for type in stream_types:
with create_stream_test_table(dynamodb, StreamViewType=type) as table:
wait_for_active_stream(dynamodbstreams, table)
def test_list_streams_alter(dynamodb, dynamodbstreams):
for type in stream_types:
with create_stream_test_table(dynamodb, StreamViewType=None) as table:
res = table.update(StreamSpecification={'StreamEnabled': True, 'StreamViewType': type});
wait_for_active_stream(dynamodbstreams, table)
def test_list_streams_paged(dynamodb, dynamodbstreams):
for type in stream_types:
with create_stream_test_table(dynamodb, StreamViewType=type) as table1:
with create_stream_test_table(dynamodb, StreamViewType=type) as table2:
wait_for_active_stream(dynamodbstreams, table1)
wait_for_active_stream(dynamodbstreams, table2)
streams = dynamodbstreams.list_streams(Limit=1)
assert streams
assert streams.get('Streams')
assert streams.get('LastEvaluatedStreamArn')
tables = [ table1.name, table2.name ]
while True:
for s in streams['Streams']:
name = s['TableName']
if name in tables: tables.remove(name)
if not tables:
break
streams = dynamodbstreams.list_streams(Limit=1, ExclusiveStartStreamArn=streams['LastEvaluatedStreamArn'])
@pytest.mark.skip(reason="Python driver validates Limit, so trying to test it is pointless")
def test_list_streams_zero_limit(dynamodb, dynamodbstreams):
with create_stream_test_table(dynamodb, StreamViewType='KEYS_ONLY') as table:
with pytest.raises(ClientError, match='ValidationException'):
wait_for_active_stream(dynamodbstreams, table)
dynamodbstreams.list_streams(Limit=0)
def test_create_streams_wrong_type(dynamodb, dynamodbstreams, test_table):
with pytest.raises(ClientError, match='ValidationException'):
# should throw
test_table.update(StreamSpecification={'StreamEnabled': True, 'StreamViewType': 'Fisk'});
# just in case the test fails, disable stream again
test_table.update(StreamSpecification={'StreamEnabled': False});
def test_list_streams_empty(dynamodb, dynamodbstreams, test_table):
streams = dynamodbstreams.list_streams(TableName=test_table.name)
assert 'Streams' in streams
assert not streams['Streams'] # empty
def test_list_streams_with_nonexistent_last_stream(dynamodb, dynamodbstreams):
with create_stream_test_table(dynamodb, StreamViewType='KEYS_ONLY') as table:
with pytest.raises(ClientError, match='ValidationException'):
streams = dynamodbstreams.list_streams(TableName=table.name, ExclusiveStartStreamArn='kossaapaaasdafsdaasdasdasdasasdasfadfadfasdasdas')
assert 'Streams' in streams
assert not streams['Streams'] # empty
# local java dynamodb does _not_ raise validation error for
# malformed stream arn here. verify
ensure_java_server(dynamodbstreams)
def test_describe_stream(dynamodb, dynamodbstreams):
with create_stream_test_table(dynamodb, StreamViewType='KEYS_ONLY') as table:
streams = dynamodbstreams.list_streams(TableName=table.name)
arn = streams['Streams'][0]['StreamArn'];
desc = dynamodbstreams.describe_stream(StreamArn=arn)
assert desc;
assert desc.get('StreamDescription')
assert desc['StreamDescription']['StreamArn'] == arn
assert desc['StreamDescription']['StreamStatus'] != 'DISABLED'
assert desc['StreamDescription']['StreamViewType'] == 'KEYS_ONLY'
assert desc['StreamDescription']['TableName'] == table.name
assert desc['StreamDescription'].get('Shards')
assert desc['StreamDescription']['Shards'][0].get('ShardId')
assert desc['StreamDescription']['Shards'][0].get('SequenceNumberRange')
assert desc['StreamDescription']['Shards'][0]['SequenceNumberRange'].get('StartingSequenceNumber')
@pytest.mark.xfail(reason="alternator does not have creation time or label for streams")
def test_describe_stream(dynamodb, dynamodbstreams):
with create_stream_test_table(dynamodb, StreamViewType='KEYS_ONLY') as table:
streams = dynamodbstreams.list_streams(TableName=table.name)
arn = streams['Streams'][0]['StreamArn'];
desc = dynamodbstreams.describe_stream(StreamArn=arn)
assert desc;
assert desc.get('StreamDescription')
# note these are non-required attributes
assert 'StreamLabel' in desc['StreamDescription']
assert 'CreationRequestDateTime' in desc['StreamDescription']
def test_describe_nonexistent_stream(dynamodb, dynamodbstreams):
with pytest.raises(ClientError, match='ResourceNotFoundException' if is_local_java(dynamodbstreams) else 'ValidationException'):
streams = dynamodbstreams.describe_stream(StreamArn='sdfadfsdfnlfkajakfgjalksfgklasjklasdjfklasdfasdfgasf')
def test_describe_stream_with_nonexistent_last_shard(dynamodb, dynamodbstreams):
with create_stream_test_table(dynamodb, StreamViewType='KEYS_ONLY') as table:
streams = dynamodbstreams.list_streams(TableName=table.name)
arn = streams['Streams'][0]['StreamArn'];
try:
desc = dynamodbstreams.describe_stream(StreamArn=arn, ExclusiveStartShardId='zzzzzzzzzzzzzzzzzzzzzzzzsfasdgagadfadfgagkjsdfsfsdjfjks')
assert not desc['StreamDescription']['Shards']
except:
# local java throws here. real does not.
ensure_java_server(dynamodbstreams, error=None)
def test_get_shard_iterator(dynamodb, dynamodbstreams):
with create_stream_test_table(dynamodb, StreamViewType='KEYS_ONLY') as table:
streams = dynamodbstreams.list_streams(TableName=table.name)
arn = streams['Streams'][0]['StreamArn'];
desc = dynamodbstreams.describe_stream(StreamArn=arn)
shard_id = desc['StreamDescription']['Shards'][0]['ShardId'];
seq = desc['StreamDescription']['Shards'][0]['SequenceNumberRange']['StartingSequenceNumber'];
for type in ['AT_SEQUENCE_NUMBER', 'AFTER_SEQUENCE_NUMBER']:
iter = dynamodbstreams.get_shard_iterator(
StreamArn=arn, ShardId=shard_id, ShardIteratorType=type, SequenceNumber=seq
)
assert iter.get('ShardIterator')
for type in ['TRIM_HORIZON', 'LATEST']:
iter = dynamodbstreams.get_shard_iterator(
StreamArn=arn, ShardId=shard_id, ShardIteratorType=type
)
assert iter.get('ShardIterator')
for type in ['AT_SEQUENCE_NUMBER', 'AFTER_SEQUENCE_NUMBER']:
# must have seq in these modes
with pytest.raises(ClientError, match='ValidationException'):
iter = dynamodbstreams.get_shard_iterator(
StreamArn=arn, ShardId=shard_id, ShardIteratorType=type
)
for type in ['TRIM_HORIZON', 'LATEST']:
# should not set "seq" in these modes
with pytest.raises(ClientError, match='ValidationException'):
dynamodbstreams.get_shard_iterator(
StreamArn=arn, ShardId=shard_id, ShardIteratorType=type, SequenceNumber=seq
)
# bad arn
with pytest.raises(ClientError, match='ValidationException'):
iter = dynamodbstreams.get_shard_iterator(
StreamArn='sdfadsfsdfsdgdfsgsfdabadfbabdadsfsdfsdfsdfsdfsdfsdfdfdssdffbdfdf', ShardId=shard_id, ShardIteratorType=type, SequenceNumber=seq
)
# bad shard id
with pytest.raises(ClientError, match='ResourceNotFoundException'):
dynamodbstreams.get_shard_iterator(StreamArn=arn, ShardId='semprinidfaasdasfsdvacsdcfsdsvsdvsdvsdvsdvsdv',
ShardIteratorType='LATEST'
)
# bad iter type
with pytest.raises(ClientError, match='ValidationException'):
dynamodbstreams.get_shard_iterator(StreamArn=arn, ShardId=shard_id,
ShardIteratorType='bulle', SequenceNumber=seq
)
# bad seq
with pytest.raises(ClientError, match='ValidationException'):
dynamodbstreams.get_shard_iterator(StreamArn=arn, ShardId=shard_id,
ShardIteratorType='LATEST', SequenceNumber='sdfsafglldfngjdafnasdflgnaldklkafdsgklnasdlv'
)
def test_get_shard_iterator_for_nonexistent_stream(dynamodb, dynamodbstreams):
with create_stream_test_table(dynamodb, StreamViewType='KEYS_ONLY') as table:
arn = wait_for_active_stream(dynamodbstreams, table)
desc = dynamodbstreams.describe_stream(StreamArn=arn)
shards = desc['StreamDescription']['Shards']
with pytest.raises(ClientError, match='ResourceNotFoundException' if is_local_java(dynamodbstreams) else 'ValidationException'):
dynamodbstreams.get_shard_iterator(
StreamArn='sdfadfsddafgdafsgjnadflkgnalngalsdfnlkasnlkasdfasdfasf', ShardId=shards[0]['ShardId'], ShardIteratorType='LATEST'
)
def test_get_shard_iterator_for_nonexistent_shard(dynamodb, dynamodbstreams):
with create_stream_test_table(dynamodb, StreamViewType='KEYS_ONLY') as table:
streams = dynamodbstreams.list_streams(TableName=table.name)
arn = streams['Streams'][0]['StreamArn'];
with pytest.raises(ClientError, match='ResourceNotFoundException'):
dynamodbstreams.get_shard_iterator(
StreamArn=arn, ShardId='adfasdasdasdasdasdasdasdasdasasdasd', ShardIteratorType='LATEST'
)
def test_get_records(dynamodb, dynamodbstreams):
# TODO: add tests for storage/transactionable variations and global/local index
with create_stream_test_table(dynamodb, StreamViewType='NEW_AND_OLD_IMAGES') as table:
arn = wait_for_active_stream(dynamodbstreams, table)
p = 'piglet'
c = 'ninja'
val = 'lucifers'
val2 = 'flowers'
table.put_item(Item={'p': p, 'c': c, 'a1': val, 'a2': val2})
nval = 'semprini'
nval2 = 'nudge'
table.update_item(Key={'p': p, 'c': c},
AttributeUpdates={ 'a1': {'Value': nval, 'Action': 'PUT'},
'a2': {'Value': nval2, 'Action': 'PUT'}
})
has_insert = False
# in truth, we should sleep already here, since at least scylla
# will not be able to produce any stream content until
# ~30s after insert/update (confidence iterval)
# but it is useful to see a working null-iteration as well, so
# lets go already.
while True:
desc = dynamodbstreams.describe_stream(StreamArn=arn)
iterators = []
while True:
shards = desc['StreamDescription']['Shards']
for shard in shards:
shard_id = shard['ShardId']
start = shard['SequenceNumberRange']['StartingSequenceNumber']
iter = dynamodbstreams.get_shard_iterator(StreamArn=arn, ShardId=shard_id, ShardIteratorType='AT_SEQUENCE_NUMBER',SequenceNumber=start)['ShardIterator']
iterators.append(iter)
last_shard = desc["StreamDescription"].get("LastEvaluatedShardId")
if not last_shard:
break
desc = dynamodbstreams.describe_stream(StreamArn=arn, ExclusiveStartShardId=last_shard)
next_iterators = []
while iterators:
iter = iterators.pop(0)
response = dynamodbstreams.get_records(ShardIterator=iter, Limit=1000)
next = response['NextShardIterator']
if next != '':
next_iterators.append(next)
records = response.get('Records')
# print("Query {} -> {}".format(iter, records))
if records:
for record in records:
# print("Record: {}".format(record))
type = record['eventName']
dynamodb = record['dynamodb']
keys = dynamodb['Keys']
assert keys.get('p')
assert keys.get('c')
assert keys['p'].get('S')
assert keys['p']['S'] == p
assert keys['c'].get('S')
assert keys['c']['S'] == c
if type == 'MODIFY' or type == 'INSERT':
assert dynamodb.get('NewImage')
newimage = dynamodb['NewImage'];
assert newimage.get('a1')
assert newimage.get('a2')
if type == 'INSERT' or (type == 'MODIFY' and not has_insert):
assert newimage['a1']['S'] == val
assert newimage['a2']['S'] == val2
has_insert = True
continue
if type == 'MODIFY':
assert has_insert
assert newimage['a1']['S'] == nval
assert newimage['a2']['S'] == nval2
assert dynamodb.get('OldImage')
oldimage = dynamodb['OldImage'];
assert oldimage.get('a1')
assert oldimage.get('a2')
assert oldimage['a1']['S'] == val
assert oldimage['a2']['S'] == val2
return
print("Not done. Sleep 10s...")
time.sleep(10)
iterators = next_iterators
def test_get_records_nonexistent_iterator(dynamodbstreams):
with pytest.raises(ClientError, match='ValidationException'):
dynamodbstreams.get_records(ShardIterator='sdfsdfsgagaddafgagasgasgasdfasdfasdfasdfasdgasdasdgasdg', Limit=1000)
##############################################################################
# Fixtures for creating a table with a stream enabled with one of the allowed
# StreamViewType settings (KEYS_ONLY, NEW_IMAGE, OLD_IMAGE, NEW_AND_OLD_IMAGES).
# Unfortunately changing the StreamViewType setting of an existing stream is
# not allowed (see test_streams_change_type), and while removing and re-adding
# a stream is posssible, it is very slow. So we create four different fixtures
# with the four different StreamViewType settings for these four fixtures.
#
# It turns out that DynamoDB makes reusing the same table in different tests
# very difficult, because when we request a "LATEST" iterator we sometimes
# miss the immediately following write (this issue doesn't happen in
# ALternator, just in DynamoDB - presumably LATEST adds some time slack?)
# So all the fixtures we create below have scope="function", meaning that a
# separate table is created for each of the tests using these fixtures. This
# slows the tests down a bit, but not by much (about 0.05 seconds per test).
# It is still worthwhile to use a fixture rather than to create a table
# explicitly - it is convenient, safe (the table gets deleted automatically)
# and if in the future we can work around the DynamoDB problem, we can return
# these fixtures to session scope.
def create_table_ss(dynamodb, dynamodbstreams, type):
table = create_test_table(dynamodb,
KeySchema=[{ 'AttributeName': 'p', 'KeyType': 'HASH' }, { 'AttributeName': 'c', 'KeyType': 'RANGE' }],
AttributeDefinitions=[{ 'AttributeName': 'p', 'AttributeType': 'S' }, { 'AttributeName': 'c', 'AttributeType': 'S' }],
StreamSpecification={ 'StreamEnabled': True, 'StreamViewType': type })
arn = wait_for_active_stream(dynamodbstreams, table, timeout=60)
yield table, arn
table.delete()
@pytest.fixture(scope="function")
def test_table_ss_keys_only(dynamodb, dynamodbstreams):
yield from create_table_ss(dynamodb, dynamodbstreams, 'KEYS_ONLY')
@pytest.fixture(scope="function")
def test_table_ss_new_image(dynamodb, dynamodbstreams):
yield from create_table_ss(dynamodb, dynamodbstreams, 'NEW_IMAGE')
@pytest.fixture(scope="function")
def test_table_ss_old_image(dynamodb, dynamodbstreams):
yield from create_table_ss(dynamodb, dynamodbstreams, 'OLD_IMAGE')
@pytest.fixture(scope="function")
def test_table_ss_new_and_old_images(dynamodb, dynamodbstreams):
yield from create_table_ss(dynamodb, dynamodbstreams, 'NEW_AND_OLD_IMAGES')
# Test that it is, sadly, not allowed to use UpdateTable on a table which
# already has a stream enabled to change that stream's StreamViewType.
# Currently, Alternator does allow this (see issue #6939), so the test is
# marked xfail.
@pytest.mark.xfail(reason="Alternator allows changing StreamViewType - see issue #6939")
def test_streams_change_type(test_table_ss_keys_only):
table, arn = test_table_ss_keys_only
with pytest.raises(ClientError, match='ValidationException.*already'):
table.update(StreamSpecification={'StreamEnabled': True, 'StreamViewType': 'OLD_IMAGE'});
# If the above change succeeded (because of issue #6939), switch it back :-)
table.update(StreamSpecification={'StreamEnabled': True, 'StreamViewType': 'KEYS_ONLY'});
# Utility function for listing all the shards of the given stream arn.
# Implemented by multiple calls to DescribeStream, possibly several pages
# until all the shards are returned. The return of this function should be
# cached - it is potentially slow, and DynamoDB documentation even states
# DescribeStream may only be called at a maximum rate of 10 times per second.
# list_shards() only returns the shard IDs, not the information about the
# shards' sequence number range, which is also returned by DescribeStream.
def list_shards(dynamodbstreams, arn):
# By default DescribeStream lists a limit of 100 shards. For faster
# tests we reduced the number of shards in the testing setup to
# 32 (16 vnodes x 2 cpus), see issue #6979, so to still exercise this
# paging feature, lets use a limit of 10.
limit = 10
response = dynamodbstreams.describe_stream(StreamArn=arn, Limit=limit)['StreamDescription']
assert len(response['Shards']) <= limit
shards = [x['ShardId'] for x in response['Shards']]
while 'LastEvaluatedShardId' in response:
response = dynamodbstreams.describe_stream(StreamArn=arn, Limit=limit,
ExclusiveStartShardId=response['LastEvaluatedShardId'])['StreamDescription']
assert len(response['Shards']) <= limit
shards.extend([x['ShardId'] for x in response['Shards']])
print('Number of shards in stream: {}'.format(len(shards)))
return shards
# Utility function for getting shard iterators starting at "LATEST" for
# all the shards of the given stream arn.
def latest_iterators(dynamodbstreams, arn):
iterators = []
for shard_id in list_shards(dynamodbstreams, arn):
iterators.append(dynamodbstreams.get_shard_iterator(StreamArn=arn,
ShardId=shard_id, ShardIteratorType='LATEST')['ShardIterator'])
return iterators
# Utility function for fetching more content from the stream (given its
# array of iterators) into an "output" array. Call repeatedly to get more
# content - the function returns a new array of iterators which should be
# used to replace the input list of iterators.
# Note that the order of the updates is guaranteed for the same partition,
# but cannot be trusted for *different* partitions.
def fetch_more(dynamodbstreams, iterators, output):
new_iterators = []
for iter in iterators:
response = dynamodbstreams.get_records(ShardIterator=iter)
if 'NextShardIterator' in response:
new_iterators.append(response['NextShardIterator'])
output.extend(response['Records'])
return new_iterators
# Utility function for comparing "output" as fetched by fetch_more(), to a list
# expected_events, each of which looks like:
# [type, keys, old_image, new_image]
# where type is REMOVE, INSERT or MODIFY.
# The "mode" parameter specifies which StreamViewType mode (KEYS_ONLY,
# OLD_IMAGE, NEW_IMAGE, NEW_AND_OLD_IMAGES) was supposedly used to generate
# "output". This mode dictates what we can compare - e.g., in KEYS_ONLY mode
# the compare_events() function ignores the the old and new image in
# expected_events.
# compare_events() throws an exception immediately if it sees an unexpected
# event, but if some of the expected events are just missing in the "output",
# it only returns false - suggesting maybe the caller needs to try again
# later - maybe more output is coming.
# Note that the order of events is only guaranteed (and therefore compared)
# inside a single partition.
def compare_events(expected_events, output, mode):
# The order of expected_events is only meaningful inside a partition, so
# let's convert it into a map indexed by partition key.
expected_events_map = {}
for event in expected_events:
expected_type, expected_key, expected_old_image, expected_new_image = event
# For simplicity, we actually use the entire key, not just the partiton
# key. We only lose a bit of testing power we didn't plan to test anyway
# (that events for different items in the same partition are ordered).
key = freeze(expected_key)
if not key in expected_events_map:
expected_events_map[key] = []
expected_events_map[key].append(event)
# Iterate over the events in output. An event for a certain key needs to
# be the *first* remaining event for this key in expected_events_map (and
# then we remove this matched even from expected_events_map)
for event in output:
# In DynamoDB, eventSource is 'aws:dynamodb'. We decided to set it to
# a *different* value - 'scylladb:alternator'. Issue #6931.
assert 'eventSource' in event
# Alternator is missing "awsRegion", which makes little sense for it
# (although maybe we should have provided the DC name). Issue #6931.
#assert 'awsRegion' in event
# Alternator is also missing the "eventVersion" entry. Issue #6931.
#assert 'eventVersion' in event
# Check that eventID appears, but can't check much on what it is.
assert 'eventID' in event
op = event['eventName']
record = event['dynamodb']
# record['Keys'] is "serialized" JSON, ({'S', 'thestring'}), so we
# want to deserialize it to match our expected_events content.
deserializer = TypeDeserializer()
key = {x:deserializer.deserialize(y) for (x,y) in record['Keys'].items()}
expected_type, expected_key, expected_old_image, expected_new_image = expected_events_map[freeze(key)].pop(0)
if expected_type != '*': # hack to allow a caller to not test op, to bypass issue #6918.
assert op == expected_type
assert record['StreamViewType'] == mode
# Check that all the expected members appear in the record, even if
# we don't have anything to compare them to (TODO: we should probably
# at least check they have proper format).
assert 'ApproximateCreationDateTime' in record
assert 'SequenceNumber' in record
# Alternator doesn't set the SizeBytes member. Issue #6931.
#assert 'SizeBytes' in record
if mode == 'KEYS_ONLY':
assert not 'NewImage' in record
assert not 'OldImage' in record
elif mode == 'NEW_IMAGE':
assert not 'OldImage' in record
if expected_new_image == None:
assert not 'NewImage' in record
else:
new_image = {x:deserializer.deserialize(y) for (x,y) in record['NewImage'].items()}
assert expected_new_image == new_image
elif mode == 'OLD_IMAGE':
assert not 'NewImage' in record
if expected_old_image == None:
assert not 'OldImage' in record
pass
else:
old_image = {x:deserializer.deserialize(y) for (x,y) in record['OldImage'].items()}
assert expected_old_image == old_image
elif mode == 'NEW_AND_OLD_IMAGES':
if expected_new_image == None:
assert not 'NewImage' in record
else:
new_image = {x:deserializer.deserialize(y) for (x,y) in record['NewImage'].items()}
assert expected_new_image == new_image
if expected_old_image == None:
assert not 'OldImage' in record
else:
old_image = {x:deserializer.deserialize(y) for (x,y) in record['OldImage'].items()}
assert expected_old_image == old_image
else:
pytest.fail('cannot happen')
# After the above loop, expected_events_map should remain empty arrays.
# If it isn't, one of the expected events did not yet happen. Return False.
for entry in expected_events_map.values():
if len(entry) > 0:
return False
return True
# Convenience funtion used to implement several tests below. It runs a given
# function "updatefunc" which is supposed to do some updates to the table
# and also return an expected_events list. do_test() then fetches the streams
# data and compares it to the expected_events using compare_events().
def do_test(test_table_ss_stream, dynamodbstreams, updatefunc, mode, p = random_string(), c = random_string()):
table, arn = test_table_ss_stream
iterators = latest_iterators(dynamodbstreams, arn)
expected_events = updatefunc(table, p, c)
# Updating the stream is asynchronous. Moreover, it may even be delayed
# artificially (see Alternator's alternator_streams_time_window_s config).
# So if compare_events() reports the stream data is missing some of the
# expected events (by returning False), we need to retry it for some time.
# Note that compare_events() throws if the stream data contains *wrong*
# (unexpected) data, so even failing tests usually finish reasonably
# fast - depending on the alternator_streams_time_window_s parameter.
# This is optimization is important to keep *failing* tests reasonably
# fast and not have to wait until the following arbitrary timeout.
timeout = time.time() + 20
output = []
while time.time() < timeout:
iterators = fetch_more(dynamodbstreams, iterators, output)
print("after fetch_more number expected_events={}, output={}".format(len(expected_events), len(output)))
if compare_events(expected_events, output, mode):
# success!
return
time.sleep(0.5)
# If we're still here, the last compare_events returned false.
pytest.fail('missing events in output: {}'.format(output))
# Test a single PutItem of a new item. Should result in a single INSERT
# event. Currently fails because in Alternator, PutItem - which generates a
# tombstone to *replace* an item - generates REMOVE+MODIFY (issue #6930).
@pytest.mark.xfail(reason="Currently fails - see issue #6930")
def test_streams_putitem_keys_only(test_table_ss_keys_only, dynamodbstreams):
def do_updates(table, p, c):
events = []
table.put_item(Item={'p': p, 'c': c, 'x': 2})
events.append(['INSERT', {'p': p, 'c': c}, None, {'p': p, 'c': c, 'x': 2}])
return events
do_test(test_table_ss_keys_only, dynamodbstreams, do_updates, 'KEYS_ONLY')
# Test a single UpdateItem. Should result in a single INSERT event.
# Currently fails because Alternator generates a MODIFY event even though
# this is a new item (issue #6918).
@pytest.mark.xfail(reason="Currently fails - see issue #6918")
def test_streams_updateitem_keys_only(test_table_ss_keys_only, dynamodbstreams):
def do_updates(table, p, c):
events = []
table.update_item(Key={'p': p, 'c': c},
UpdateExpression='SET x = :val1', ExpressionAttributeValues={':val1': 2})
events.append(['INSERT', {'p': p, 'c': c}, None, {'p': p, 'c': c, 'x': 2}])
return events
do_test(test_table_ss_keys_only, dynamodbstreams, do_updates, 'KEYS_ONLY')
# This is exactly the same test as test_streams_updateitem_keys_only except
# we don't verify the type of even we find (MODIFY or INSERT). It allows us
# to have at least one good GetRecords test until solving issue #6918.
# When we do solve that issue, this test should be removed.
def test_streams_updateitem_keys_only_2(test_table_ss_keys_only, dynamodbstreams):
def do_updates(table, p, c):
events = []
table.update_item(Key={'p': p, 'c': c},
UpdateExpression='SET x = :val1', ExpressionAttributeValues={':val1': 2})
events.append(['*', {'p': p, 'c': c}, None, {'p': p, 'c': c, 'x': 2}])
return events
do_test(test_table_ss_keys_only, dynamodbstreams, do_updates, 'KEYS_ONLY')
# Test OLD_IMAGE using UpdateItem. Verify that the OLD_IMAGE indeed includes,
# as needed, the entire old item and not just the modified columns.
# Reproduces issue #6935
def test_streams_updateitem_old_image(test_table_ss_old_image, dynamodbstreams):
def do_updates(table, p, c):
events = []
table.update_item(Key={'p': p, 'c': c},
UpdateExpression='SET x = :val1', ExpressionAttributeValues={':val1': 2})
# We use here '*' instead of the really expected 'INSERT' to avoid
# checking again the same Alternator bug already checked by
# test_streams_updateitem_keys_only (issue #6918).
# Note: The "None" as OldImage here tests that the OldImage should be
# missing because the item didn't exist. This reproduces issue #6933.
events.append(['*', {'p': p, 'c': c}, None, {'p': p, 'c': c, 'x': 2}])
table.update_item(Key={'p': p, 'c': c},
UpdateExpression='SET y = :val1', ExpressionAttributeValues={':val1': 3})
events.append(['MODIFY', {'p': p, 'c': c}, {'p': p, 'c': c, 'x': 2}, {'p': p, 'c': c, 'x': 2, 'y': 3}])
return events
do_test(test_table_ss_old_image, dynamodbstreams, do_updates, 'OLD_IMAGE')
# Above we verified that if an item did not previously exist, the OLD_IMAGE
# would be missing, but if the item did previously exist, OLD_IMAGE should
# be present and must include the key. Here we confirm the special case the
# latter case - the case of a pre-existing *empty* item, which has just the
# key - in this case since the item did exist, OLD_IMAGE should be returned -
# and include just the key. This is a special case of reproducing #6935 -
# the first patch for this issue failed in this special case.
def test_streams_updateitem_old_image_empty_item(test_table_ss_old_image, dynamodbstreams):
def do_updates(table, p, c):
events = []
# Create an *empty* item, with nothing except a key:
table.update_item(Key={'p': p, 'c': c})
events.append(['*', {'p': p, 'c': c}, None, {'p': p, 'c': c}])
table.update_item(Key={'p': p, 'c': c},
UpdateExpression='SET y = :val1', ExpressionAttributeValues={':val1': 3})
# Note that OLD_IMAGE should be present and be the empty item,
# with just a key, not entirely missing.
events.append(['MODIFY', {'p': p, 'c': c}, {'p': p, 'c': c}, {'p': p, 'c': c, 'y': 3}])
return events
do_test(test_table_ss_old_image, dynamodbstreams, do_updates, 'OLD_IMAGE')
# Test that OLD_IMAGE indeed includes the entire old item and not just the
# modified attributes, in the special case of attributes which are a key of
# a secondary index.
# The unique thing about this case is that as currently implemented,
# secondary-index key attributes are real Scylla columns, contrasting with
# other attributes which are just elements of a map. And our CDC
# implementation treats those cases differently - when a map is modified
# the preimage includes the entire content of the map, but for regular
# columns they are only included in the preimage if they change.
# Currently fails in Alternator because the item's key is missing in
# OldImage (#6935) and the LSI key is also missing (#7030).
@pytest.fixture(scope="function")
def test_table_ss_old_image_and_lsi(dynamodb, dynamodbstreams):
table = create_test_table(dynamodb,
KeySchema=[
{'AttributeName': 'p', 'KeyType': 'HASH'},
{'AttributeName': 'c', 'KeyType': 'RANGE'}],
AttributeDefinitions=[
{ 'AttributeName': 'p', 'AttributeType': 'S' },
{ 'AttributeName': 'c', 'AttributeType': 'S' },
{ 'AttributeName': 'k', 'AttributeType': 'S' }],
LocalSecondaryIndexes=[{
'IndexName': 'index',
'KeySchema': [
{'AttributeName': 'p', 'KeyType': 'HASH'},
{'AttributeName': 'k', 'KeyType': 'RANGE'}],
'Projection': { 'ProjectionType': 'ALL' }
}],
StreamSpecification={ 'StreamEnabled': True, 'StreamViewType': 'OLD_IMAGE' })
arn = wait_for_active_stream(dynamodbstreams, table, timeout=60)
yield table, arn
table.delete()
def test_streams_updateitem_old_image_lsi(test_table_ss_old_image_and_lsi, dynamodbstreams):
def do_updates(table, p, c):
events = []
table.update_item(Key={'p': p, 'c': c},
UpdateExpression='SET x = :x, k = :k',
ExpressionAttributeValues={':x': 2, ':k': 'dog'})
# We use here '*' instead of the really expected 'INSERT' to avoid
# checking again the same Alternator bug already checked by
# test_streams_updateitem_keys_only (issue #6918).
events.append(['*', {'p': p, 'c': c}, None, {'p': p, 'c': c, 'x': 2, 'k': 'dog'}])
table.update_item(Key={'p': p, 'c': c},
UpdateExpression='SET y = :y', ExpressionAttributeValues={':y': 3})
# In issue #7030, the 'k' value was missing from the OldImage.
events.append(['MODIFY', {'p': p, 'c': c}, {'p': p, 'c': c, 'x': 2, 'k': 'dog'}, {'p': p, 'c': c, 'x': 2, 'k': 'dog', 'y': 3}])
return events
do_test(test_table_ss_old_image_and_lsi, dynamodbstreams, do_updates, 'OLD_IMAGE')
# Tests similar to the above tests for OLD_IMAGE, just for NEW_IMAGE mode.
# Verify that the NEW_IMAGE includes the entire old item (including the key),
# that deleting the item results in a missing NEW_IMAGE, and that setting the
# item to be empty has a different result - a NEW_IMAGE with just a key.
# Reproduces issue #7107.
def test_streams_new_image(test_table_ss_new_image, dynamodbstreams):
def do_updates(table, p, c):
events = []
table.update_item(Key={'p': p, 'c': c},
UpdateExpression='SET x = :val1', ExpressionAttributeValues={':val1': 2})
# Confirm that when adding one attribute "x", the NewImage contains both
# the new x, and the key columns (p and c).
# We use here '*' instead of 'INSERT' to avoid testing issue #6918 here.
events.append(['*', {'p': p, 'c': c}, None, {'p': p, 'c': c, 'x': 2}])
# Confirm that when adding just attribute "y", the NewImage will contain
# all the attributes, including the old "x":
table.update_item(Key={'p': p, 'c': c},
UpdateExpression='SET y = :val1', ExpressionAttributeValues={':val1': 3})
events.append(['MODIFY', {'p': p, 'c': c}, {'p': p, 'c': c, 'x': 2}, {'p': p, 'c': c, 'x': 2, 'y': 3}])
# Confirm that when deleting the columns x and y, the NewImage becomes
# empty - but still exists and contains the key columns,
table.update_item(Key={'p': p, 'c': c},
UpdateExpression='REMOVE x, y')
events.append(['MODIFY', {'p': p, 'c': c}, {'p': p, 'c': c, 'x': 2, 'y': 3}, {'p': p, 'c': c}])
# Confirm that deleting the item results in a missing NewImage:
table.delete_item(Key={'p': p, 'c': c})
events.append(['REMOVE', {'p': p, 'c': c}, {'p': p, 'c': c}, None])
return events
do_test(test_table_ss_new_image, dynamodbstreams, do_updates, 'NEW_IMAGE')
# Test similar to the above test for NEW_IMAGE corner cases, but here for
# NEW_AND_OLD_IMAGES mode.
# Although it is likely that if both OLD_IMAGE and NEW_IMAGE work correctly then
# so will the combined NEW_AND_OLD_IMAGES mode, it is still possible that the
# implementation of the combined mode has unique bugs, so it is worth testing
# it separately.
# Reproduces issue #7107.
def test_streams_new_and_old_images(test_table_ss_new_and_old_images, dynamodbstreams):
def do_updates(table, p, c):
events = []
table.update_item(Key={'p': p, 'c': c},
UpdateExpression='SET x = :val1', ExpressionAttributeValues={':val1': 2})
# The item doesn't yet exist, so OldImage is missing.
# We use here '*' instead of 'INSERT' to avoid testing issue #6918 here.
events.append(['*', {'p': p, 'c': c}, None, {'p': p, 'c': c, 'x': 2}])
# Confirm that when adding just attribute "y", the NewImage will contain
# all the attributes, including the old "x". Also, OldImage contains the
# key attributes, not just "x":
table.update_item(Key={'p': p, 'c': c},
UpdateExpression='SET y = :val1', ExpressionAttributeValues={':val1': 3})
events.append(['MODIFY', {'p': p, 'c': c}, {'p': p, 'c': c, 'x': 2}, {'p': p, 'c': c, 'x': 2, 'y': 3}])
# Confirm that when deleting the attributes x and y, the NewImage becomes
# empty - but still exists and contains the key attributes:
table.update_item(Key={'p': p, 'c': c},
UpdateExpression='REMOVE x, y')
events.append(['MODIFY', {'p': p, 'c': c}, {'p': p, 'c': c, 'x': 2, 'y': 3}, {'p': p, 'c': c}])
# Confirm that when adding an attribute z to the empty item, OldItem is
# not missing - it just contains only the key attributes:
table.update_item(Key={'p': p, 'c': c},
UpdateExpression='SET z = :val1', ExpressionAttributeValues={':val1': 4})
events.append(['MODIFY', {'p': p, 'c': c}, {'p': p, 'c': c}, {'p': p, 'c': c, 'z': 4}])
# Confirm that deleting the item results in a missing NewImage:
table.delete_item(Key={'p': p, 'c': c})
events.append(['REMOVE', {'p': p, 'c': c}, {'p': p, 'c': c, 'z': 4}, None])
return events
do_test(test_table_ss_new_and_old_images, dynamodbstreams, do_updates, 'NEW_AND_OLD_IMAGES')
# Test that when a stream shard has no data to read, GetRecords returns an
# empty Records array - not a missing one. Reproduces issue #6926.
def test_streams_no_records(test_table_ss_keys_only, dynamodbstreams):
table, arn = test_table_ss_keys_only
# Get just one shard - any shard - and its LATEST iterator. Because it's
# LATEST, there will be no data to read from this iterator.
shard_id = dynamodbstreams.describe_stream(StreamArn=arn, Limit=1)['StreamDescription']['Shards'][0]['ShardId']
iter = dynamodbstreams.get_shard_iterator(StreamArn=arn, ShardId=shard_id, ShardIteratorType='LATEST')['ShardIterator']
response = dynamodbstreams.get_records(ShardIterator=iter)
assert 'NextShardIterator' in response
assert 'Records' in response
# We expect Records to be empty - there is no data at the LATEST iterator.
assert response['Records'] == []
# Test that after fetching the last result from a shard, we don't get it
# yet again. Reproduces issue #6942.
def test_streams_last_result(test_table_ss_keys_only, dynamodbstreams):
table, arn = test_table_ss_keys_only
iterators = latest_iterators(dynamodbstreams, arn)
# Do an UpdateItem operation that is expected to leave one event in the
# stream.
table.update_item(Key={'p': random_string(), 'c': random_string()},
UpdateExpression='SET x = :val1', ExpressionAttributeValues={':val1': 5})
# Eventually (we may need to retry this for a while), *one* of the
# stream shards will return one event:
timeout = time.time() + 15
while time.time() < timeout:
for iter in iterators:
response = dynamodbstreams.get_records(ShardIterator=iter)
if 'Records' in response and response['Records'] != []:
# Found the shard with the data! Test that it only has
# one event and that if we try to read again, we don't
# get more data (this was issue #6942).
assert len(response['Records']) == 1
assert 'NextShardIterator' in response
response = dynamodbstreams.get_records(ShardIterator=response['NextShardIterator'])
assert response['Records'] == []
return
time.sleep(0.5)
pytest.fail("timed out")
# In test_streams_last_result above we tested that there is no further events
# after reading the only one. In this test we verify that if we *do* perform
# another change on the same key, we do get another event and it happens on the
# *same* shard.
def test_streams_another_result(test_table_ss_keys_only, dynamodbstreams):
table, arn = test_table_ss_keys_only
iterators = latest_iterators(dynamodbstreams, arn)
# Do an UpdateItem operation that is expected to leave one event in the
# stream.
p = random_string()
c = random_string()
table.update_item(Key={'p': p, 'c': c},
UpdateExpression='SET x = :val1', ExpressionAttributeValues={':val1': 5})
# Eventually, *one* of the stream shards will return one event:
timeout = time.time() + 15
while time.time() < timeout:
for iter in iterators:
response = dynamodbstreams.get_records(ShardIterator=iter)
if 'Records' in response and response['Records'] != []:
# Finally found the shard reporting the changes to this key
assert len(response['Records']) == 1
assert response['Records'][0]['dynamodb']['Keys']== {'p': {'S': p}, 'c': {'S': c}}
assert 'NextShardIterator' in response
iter = response['NextShardIterator']
# Found the shard with the data. It only has one event so if
# we try to read again, we find nothing (this is the same as
# what test_streams_last_result tests).
response = dynamodbstreams.get_records(ShardIterator=iter)
assert response['Records'] == []
assert 'NextShardIterator' in response
iter = response['NextShardIterator']
# Do another UpdateItem operation to the same key, so it is
# expected to write to the *same* shard:
table.update_item(Key={'p': p, 'c': c},
UpdateExpression='SET x = :val2', ExpressionAttributeValues={':val2': 7})
# Again we may need to wait for the event to appear on the stream:
timeout = time.time() + 15
while time.time() < timeout:
response = dynamodbstreams.get_records(ShardIterator=iter)
if 'Records' in response and response['Records'] != []:
assert len(response['Records']) == 1
assert response['Records'][0]['dynamodb']['Keys']== {'p': {'S': p}, 'c': {'S': c}}
assert 'NextShardIterator' in response
# The test is done, successfully.
return
time.sleep(0.5)
pytest.fail("timed out")
time.sleep(0.5)
pytest.fail("timed out")
# Test the SequenceNumber attribute returned for stream events, and the
# "AT_SEQUENCE_NUMBER" iterator that can be used to re-read from the same
# event again given its saved "sequence number".
def test_streams_at_sequence_number(test_table_ss_keys_only, dynamodbstreams):
table, arn = test_table_ss_keys_only
# List all the shards and their LATEST iterators:
shards_and_iterators = []
for shard_id in list_shards(dynamodbstreams, arn):
shards_and_iterators.append((shard_id, dynamodbstreams.get_shard_iterator(StreamArn=arn,
ShardId=shard_id, ShardIteratorType='LATEST')['ShardIterator']))
# Do an UpdateItem operation that is expected to leave one event in the
# stream.
p = random_string()
c = random_string()
table.update_item(Key={'p': p, 'c': c},
UpdateExpression='SET x = :val1', ExpressionAttributeValues={':val1': 5})
# Eventually, *one* of the stream shards will return the one event:
timeout = time.time() + 15
while time.time() < timeout:
for (shard_id, iter) in shards_and_iterators:
response = dynamodbstreams.get_records(ShardIterator=iter)
if 'Records' in response and response['Records'] != []:
# Finally found the shard reporting the changes to this key:
assert len(response['Records']) == 1
assert response['Records'][0]['dynamodb']['Keys'] == {'p': {'S': p}, 'c': {'S': c}}
assert 'NextShardIterator' in response
sequence_number = response['Records'][0]['dynamodb']['SequenceNumber']
# Found the shard with the data. It only has one event so if
# we try to read again, we find nothing (this is the same as
# what test_streams_last_result tests).
iter = response['NextShardIterator']
response = dynamodbstreams.get_records(ShardIterator=iter)
assert response['Records'] == []
assert 'NextShardIterator' in response
# If we use the SequenceNumber of the first event to create an
# AT_SEQUENCE_NUMBER iterator, we can read the same event again.
# We don't need a loop and a timeout, because this event is already
# available.
iter = dynamodbstreams.get_shard_iterator(StreamArn=arn,
ShardId=shard_id, ShardIteratorType='AT_SEQUENCE_NUMBER',
SequenceNumber=sequence_number)['ShardIterator']
response = dynamodbstreams.get_records(ShardIterator=iter)
assert 'Records' in response
assert len(response['Records']) == 1
assert response['Records'][0]['dynamodb']['Keys'] == {'p': {'S': p}, 'c': {'S': c}}
assert response['Records'][0]['dynamodb']['SequenceNumber'] == sequence_number
return
time.sleep(0.5)
pytest.fail("timed out")
# Test the SequenceNumber attribute returned for stream events, and the
# "AFTER_SEQUENCE_NUMBER" iterator that can be used to re-read *after* the same
# event again given its saved "sequence number".
def test_streams_after_sequence_number(test_table_ss_keys_only, dynamodbstreams):
table, arn = test_table_ss_keys_only
# List all the shards and their LATEST iterators:
shards_and_iterators = []
for shard_id in list_shards(dynamodbstreams, arn):
shards_and_iterators.append((shard_id, dynamodbstreams.get_shard_iterator(StreamArn=arn,
ShardId=shard_id, ShardIteratorType='LATEST')['ShardIterator']))
# Do two UpdateItem operations to the same key, that are expected to leave
# two events in the stream.
p = random_string()
c = random_string()
table.update_item(Key={'p': p, 'c': c},
UpdateExpression='SET x = :val1', ExpressionAttributeValues={':val1': 3})
table.update_item(Key={'p': p, 'c': c},
UpdateExpression='SET x = :val1', ExpressionAttributeValues={':val1': 5})
# Eventually, *one* of the stream shards will return the two events:
timeout = time.time() + 15
while time.time() < timeout:
for (shard_id, iter) in shards_and_iterators:
response = dynamodbstreams.get_records(ShardIterator=iter)
if 'Records' in response and len(response['Records']) == 2:
assert response['Records'][0]['dynamodb']['Keys'] == {'p': {'S': p}, 'c': {'S': c}}
assert response['Records'][1]['dynamodb']['Keys'] == {'p': {'S': p}, 'c': {'S': c}}
sequence_number_1 = response['Records'][0]['dynamodb']['SequenceNumber']
sequence_number_2 = response['Records'][1]['dynamodb']['SequenceNumber']
# If we use the SequenceNumber of the first event to create an
# AFTER_SEQUENCE_NUMBER iterator, we can read the second event
# (only) again. We don't need a loop and a timeout, because this
# event is already available.
iter = dynamodbstreams.get_shard_iterator(StreamArn=arn,
ShardId=shard_id, ShardIteratorType='AFTER_SEQUENCE_NUMBER',
SequenceNumber=sequence_number_1)['ShardIterator']
response = dynamodbstreams.get_records(ShardIterator=iter)
assert 'Records' in response
assert len(response['Records']) == 1
assert response['Records'][0]['dynamodb']['Keys'] == {'p': {'S': p}, 'c': {'S': c}}
assert response['Records'][0]['dynamodb']['SequenceNumber'] == sequence_number_2
return
time.sleep(0.5)
pytest.fail("timed out")
# Test the "TRIM_HORIZON" iterator, which can be used to re-read *all* the
# previously-read events of the stream shard again.
# NOTE: This test relies on the test_table_ss_keys_only fixture giving us a
# brand new stream, with no old events saved from other tests. If we ever
# change this, we should change this test to use a different fixture.
def test_streams_trim_horizon(test_table_ss_keys_only, dynamodbstreams):
table, arn = test_table_ss_keys_only
# List all the shards and their LATEST iterators:
shards_and_iterators = []
for shard_id in list_shards(dynamodbstreams, arn):
shards_and_iterators.append((shard_id, dynamodbstreams.get_shard_iterator(StreamArn=arn,
ShardId=shard_id, ShardIteratorType='LATEST')['ShardIterator']))
# Do two UpdateItem operations to the same key, that are expected to leave
# two events in the stream.
p = random_string()
c = random_string()
table.update_item(Key={'p': p, 'c': c},
UpdateExpression='SET x = :val1', ExpressionAttributeValues={':val1': 3})
table.update_item(Key={'p': p, 'c': c},
UpdateExpression='SET x = :val1', ExpressionAttributeValues={':val1': 5})
# Eventually, *one* of the stream shards will return the two events:
timeout = time.time() + 15
while time.time() < timeout:
for (shard_id, iter) in shards_and_iterators:
response = dynamodbstreams.get_records(ShardIterator=iter)
if 'Records' in response and len(response['Records']) == 2:
assert response['Records'][0]['dynamodb']['Keys'] == {'p': {'S': p}, 'c': {'S': c}}
assert response['Records'][1]['dynamodb']['Keys'] == {'p': {'S': p}, 'c': {'S': c}}
sequence_number_1 = response['Records'][0]['dynamodb']['SequenceNumber']
sequence_number_2 = response['Records'][1]['dynamodb']['SequenceNumber']
# If we use the TRIM_HORIZON iterator, we should receive the
# same two events again, in the same order.
# Note that we assume that the fixture gave us a brand new
# stream, with no old events saved from other tests. If we
# couldn't assume this, this test would need to become much
# more complex, and would need to read from this shard until
# we find the two events we are looking for.
iter = dynamodbstreams.get_shard_iterator(StreamArn=arn,
ShardId=shard_id, ShardIteratorType='TRIM_HORIZON')['ShardIterator']
response = dynamodbstreams.get_records(ShardIterator=iter)
assert 'Records' in response
assert len(response['Records']) == 2
assert response['Records'][0]['dynamodb']['Keys'] == {'p': {'S': p}, 'c': {'S': c}}
assert response['Records'][1]['dynamodb']['Keys'] == {'p': {'S': p}, 'c': {'S': c}}
assert response['Records'][0]['dynamodb']['SequenceNumber'] == sequence_number_1
assert response['Records'][1]['dynamodb']['SequenceNumber'] == sequence_number_2
return
time.sleep(0.5)
pytest.fail("timed out")
# Above we tested some specific operations in small tests aimed to reproduce
# a specific bug, in the following tests we do a all the different operations,
# PutItem, DeleteItem, BatchWriteItem and UpdateItem, and check the resulting
# stream for correctness.
# The following tests focus on mulitple operations on the *same* item. Those
# should appear in the stream in the correct order.
def do_updates_1(table, p, c):
events = []
# a first put_item appears as an INSERT event. Note also empty old_image.
table.put_item(Item={'p': p, 'c': c, 'x': 2})
events.append(['INSERT', {'p': p, 'c': c}, None, {'p': p, 'c': c, 'x': 2}])
# a second put_item of the *same* key and same value, doesn't appear in the log at all!
table.put_item(Item={'p': p, 'c': c, 'x': 2})
# a second put_item of the *same* key and different value, appears as a MODIFY event
table.put_item(Item={'p': p, 'c': c, 'y': 3})
events.append(['MODIFY', {'p': p, 'c': c}, {'p': p, 'c': c, 'x': 2}, {'p': p, 'c': c, 'y': 3}])
# deleting an item appears as a REMOVE event. Note no new_image at all, but there is an old_image.
table.delete_item(Key={'p': p, 'c': c})
events.append(['REMOVE', {'p': p, 'c': c}, {'p': p, 'c': c, 'y': 3}, None])
# deleting a non-existant item doesn't appear in the log at all.
table.delete_item(Key={'p': p, 'c': c})
# If update_item creates an item, the event is INSERT as well.
table.update_item(Key={'p': p, 'c': c},
UpdateExpression='SET b = :val1',
ExpressionAttributeValues={':val1': 4})
events.append(['INSERT', {'p': p, 'c': c}, None, {'p': p, 'c': c, 'b': 4}])
# If update_item modifies the item, note how old and new image includes both old and new columns
table.update_item(Key={'p': p, 'c': c},
UpdateExpression='SET x = :val1',
ExpressionAttributeValues={':val1': 5})
events.append(['MODIFY', {'p': p, 'c': c}, {'p': p, 'c': c, 'b': 4}, {'p': p, 'c': c, 'b': 4, 'x': 5}])
# TODO: incredibly, if we uncomment the "REMOVE b" update below, it will be
# completely missing from the DynamoDB stream - the test continues to
# pass even though we didn't add another expected event, and even though
# the preimage in the following expected event includes this "b" we will
# remove. I couldn't reproduce this apparant DynamoDB bug in a smaller test.
#table.update_item(Key={'p': p, 'c': c}, UpdateExpression='REMOVE b')
# Test BatchWriteItem as well. This modifies the item, so will be a MODIFY event.
table.meta.client.batch_write_item(RequestItems = {table.name: [{'PutRequest': {'Item': {'p': p, 'c': c, 'x': 5}}}]})
events.append(['MODIFY', {'p': p, 'c': c}, {'p': p, 'c': c, 'b': 4, 'x': 5}, {'p': p, 'c': c, 'x': 5}])
return events
@pytest.mark.xfail(reason="Currently fails - because of multiple issues listed above")
def test_streams_1_keys_only(test_table_ss_keys_only, dynamodbstreams):
do_test(test_table_ss_keys_only, dynamodbstreams, do_updates_1, 'KEYS_ONLY')
@pytest.mark.xfail(reason="Currently fails - because of multiple issues listed above")
def test_streams_1_new_image(test_table_ss_new_image, dynamodbstreams):
do_test(test_table_ss_new_image, dynamodbstreams, do_updates_1, 'NEW_IMAGE')
@pytest.mark.xfail(reason="Currently fails - because of multiple issues listed above")
def test_streams_1_old_image(test_table_ss_old_image, dynamodbstreams):
do_test(test_table_ss_old_image, dynamodbstreams, do_updates_1, 'OLD_IMAGE')
@pytest.mark.xfail(reason="Currently fails - because of multiple issues listed above")
def test_streams_1_new_and_old_images(test_table_ss_new_and_old_images, dynamodbstreams):
do_test(test_table_ss_new_and_old_images, dynamodbstreams, do_updates_1, 'NEW_AND_OLD_IMAGES')
# TODO: tests on multiple partitions
# TODO: write a test that disabling the stream and re-enabling it works, but
# requires the user to wait for the first stream to become DISABLED before
# creating the new one. Then ListStreams should return the two streams,
# one DISABLED and one ENABLED? I'm not sure we want or can do this in
# Alternator.
# TODO: Can we test shard ending, or shard splitting? (shard splitting
# requires the user to - periodically or following shards ending - to call
# DescribeStream again. We don't do this in any of our tests.
| avikivity/scylla | test/alternator/test_streams.py | Python | agpl-3.0 | 62,504 |
#!/usr/bin/python
# service_http_transport.py
#
# Copyright (C) 2008-2018 Veselin Penev, https://bitdust.io
#
# This file (service_http_transport.py) is part of BitDust Software.
#
# BitDust is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# BitDust Software is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with BitDust Software. If not, see <http://www.gnu.org/licenses/>.
#
# Please contact us if you have any questions at bitdust.io@gmail.com
#
#
#
#
"""
..
module:: service_http_transport
"""
from __future__ import absolute_import
from services.local_service import LocalService
def create_service():
return HTTPTransportService()
class HTTPTransportService(LocalService):
service_name = 'service_http_transport'
config_path = 'services/http-transport/enabled'
proto = 'http'
def enabled(self):
# development started
return False
def dependent_on(self):
return ['service_http_connections',
'service_gateway',
]
def start(self):
from twisted.internet import reactor
from twisted.internet.defer import Deferred
from transport.http import http_interface
from transport import network_transport
from transport import gateway
from main.config import conf
self.starting_deferred = Deferred()
self.transport = network_transport.NetworkTransport('http', http_interface.GateInterface())
self.transport.automat('init',
(gateway.listener(), self._on_transport_state_changed))
reactor.callLater(0, self.transport.automat, 'start')
conf().addCallback('services/http-transport/enabled',
self._on_enabled_disabled)
conf().addCallback('services/http-transport/receiving-enabled',
self._on_receiving_enabled_disabled)
return self.starting_deferred
def stop(self):
from main.config import conf
conf().removeCallback('services/http-transport/enabled')
conf().removeCallback('services/http-transport/receiving-enabled')
t = self.transport
self.transport = None
t.automat('shutdown')
return True
def installed(self):
from logs import lg
try:
from transport.http import http_interface
except:
lg.exc()
return False
return True
def _on_transport_state_changed(self, transport, oldstate, newstate):
if self.starting_deferred:
if newstate in ['LISTENING', 'OFFLINE', ]:
self.starting_deferred.callback(newstate)
self.starting_deferred = None
def _on_enabled_disabled(self, path, value, oldvalue, result):
from p2p import network_connector
from logs import lg
lg.out(2, 'service_http_transport._on_enabled_disabled : %s->%s : %s' % (
oldvalue, value, path))
network_connector.A('reconnect')
def _on_receiving_enabled_disabled(self, path, value, oldvalue, result):
from p2p import network_connector
from logs import lg
lg.out(2, 'service_http_transport._on_receiving_enabled_disabled : %s->%s : %s' % (
oldvalue, value, path))
network_connector.A('reconnect')
| vesellov/bitdust.devel | services/service_http_transport.py | Python | agpl-3.0 | 3,776 |
#!/usr/bin/python
import os
# Preliminary bit to get cgi scripts working
def guess_http_host():
hostnames = {
'cloudy': 'objavi.halo.gen.nz',
'vps504': 'objavi.flossmanuals.net',
}
f = open('/etc/hostname')
host = f.read().strip()
f.close()
try:
os.environ['HTTP_HOST'] = hostnames[host]
except KeyError:
raise RuntimeError("making epubs requires a HTTP_HOST environment variable which "
"shows where to find a working booki-twiki-gateway.cgi")
if 'HTTP_HOST' not in os.environ:
guess_http_host()
#-------------------------------------------------------------#
import traceback
from objavi.fmbook import log, ZipBook, make_book_name
from objavi import config
from objavi.twiki_wrapper import get_book_list
def make_epub(server, bookid):
log('making epub for %s %s' % (server, bookid))
bookname = make_book_name(bookid, server, '.epub')
book = ZipBook(server, bookid, bookname=bookname, project='FM')
book.make_epub(use_cache=True)
for server, settings in config.SERVER_DEFAULTS.items():
if settings['interface'] == 'Booki':
continue
books = get_book_list(server)
for book in books:
try:
make_epub(server, book)
log('SUCCEEDED: %s %s' % (server, book))
except Exception, e:
log('FAILED: %s %s' % (server, book))
traceback.print_exc()
| esetera/Objavi | tests/make_all_epubs.py | Python | agpl-3.0 | 1,437 |
'''Contains AJAX apps of mother app'''
| piotrmaslanka/bellum | mother/ajax/__init__.py | Python | agpl-3.0 | 39 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('papers', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='conference',
options={'ordering': ['date']},
),
migrations.AddField(
model_name='paper',
name='url',
field=models.CharField(max_length=80, blank=True),
preserve_default=True,
),
]
| wadobo/papersplease | papersplease/papers/migrations/0002_auto_20170415_1001.py | Python | agpl-3.0 | 555 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ccx', '0026_auto_20170831_0420'),
('ccx', '0026_auto_20170831_0554'),
]
operations = [
]
| mbareta/edx-platform-ft | lms/djangoapps/ccx/migrations/0027_merge.py | Python | agpl-3.0 | 289 |
# Copyright 2010 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
import re
from django import forms
from django.utils.translation import ugettext as _
from identityprovider.widgets import CommaSeparatedWidget
class CommaSeparatedField(forms.MultipleChoiceField):
widget = CommaSeparatedWidget
def clean(self, value):
return ','.join(super(CommaSeparatedField, self).clean(value))
class OATHPasswordField(forms.CharField):
"""A string of between 6 or 8 digits."""
widget = forms.widgets.TextInput(attrs={
'autocomplete': 'off',
'autofocus': 'autofocus'
})
SIX = re.compile('[0-9]{6}$')
EIGHT = re.compile('[0-9]{8}$')
def clean(self, value):
"""Validate otp and detect type"""
# remove any whitespace from the string
if value:
value = value.strip().replace(' ', '')
value = super(OATHPasswordField, self).clean(value)
if self.SIX.match(value):
return value
elif self.EIGHT.match(value):
return value
raise forms.ValidationError(
_('Please enter a 6-digit or 8-digit one-time password.'))
| miing/mci_migo | identityprovider/fields.py | Python | agpl-3.0 | 1,229 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import factory
from udata.factories import ModelFactory
from .models import Dataset, Resource, Checksum, CommunityResource, License
from udata.core.organization.factories import OrganizationFactory
from udata.core.spatial.factories import SpatialCoverageFactory
class DatasetFactory(ModelFactory):
class Meta:
model = Dataset
title = factory.Faker('sentence')
description = factory.Faker('text')
frequency = 'unknown'
class Params:
geo = factory.Trait(
spatial=factory.SubFactory(SpatialCoverageFactory)
)
visible = factory.Trait(
resources=factory.LazyAttribute(lambda o: [ResourceFactory()])
)
org = factory.Trait(
organization=factory.SubFactory(OrganizationFactory),
)
class VisibleDatasetFactory(DatasetFactory):
@factory.lazy_attribute
def resources(self):
return [ResourceFactory()]
class ChecksumFactory(ModelFactory):
class Meta:
model = Checksum
type = 'sha1'
value = factory.Faker('sha1')
class BaseResourceFactory(ModelFactory):
title = factory.Faker('sentence')
description = factory.Faker('text')
filetype = 'file'
url = factory.Faker('url')
checksum = factory.SubFactory(ChecksumFactory)
mime = factory.Faker('mime_type', category='text')
filesize = factory.Faker('pyint')
class CommunityResourceFactory(BaseResourceFactory):
class Meta:
model = CommunityResource
class ResourceFactory(BaseResourceFactory):
class Meta:
model = Resource
class LicenseFactory(ModelFactory):
class Meta:
model = License
id = factory.Faker('unique_string')
title = factory.Faker('sentence')
url = factory.Faker('uri')
| davidbgk/udata | udata/core/dataset/factories.py | Python | agpl-3.0 | 1,823 |
# -*- coding: utf-8 -*-
# © 2017 Comunitea
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import models, fields, api, _
from odoo.tools import float_compare
from lxml import etree
class SaleOrderLineTemplate(models.Model):
_name = 'sale.order.line.template'
_inherit = 'sale.order.line'
product_template = fields.Many2one(
'product.template', string='Product',
domain=[('sale_ok', '=', True), ('product_attribute_count', '=', 0)],
change_default=True, ondelete='restrict', required=True)
order_lines = fields.One2many('sale.order.line', 'template_line',
copy=True)
lines_qty = fields.Integer(compute='_compute_order_lines_qty')
price_subtotal = fields.Monetary(
compute='_compute_amount', string='Subtotal', readonly=True,
store=True)
global_available_stock = fields.\
Float('Stock', related='product_template.global_available_stock')
@api.depends('order_lines.price_subtotal')
def _compute_amount(self):
for line in self:
line.price_subtotal = sum(
[x.price_subtotal for x in line.order_lines])
@api.multi
def unlink(self):
if not self._context.get('unlink_product_line', False):
ctx = self._context.copy()
ctx.update(unlink_template_line=True)
self.mapped('order_lines').with_context(ctx).unlink()
return super(SaleOrderLineTemplate, self).unlink()
@api.multi
def write(self, vals):
for template in self:
line_vals = vals.copy()
if template.lines_qty > 1:
line_vals.pop('product_id', False)
#line_vals.pop('price_unit', False)
line_vals.pop('product_uom_qty', False)
line_vals.pop('purchase_price', False)
line_vals.pop('name', False)
line_vals.pop('sequence', False)
template.order_lines.write(line_vals)
return super(models.Model, self).write(vals)
@api.model
def create(self, vals):
# Se controla el create con order_lines debido que al duplicar un
# pedido el vals de las lineas viene sin order_id
if vals.get('order_lines', False):
for line_vals in vals['order_lines']:
if line_vals[0] == 0:
line_vals[2]['order_id'] = vals.get('order_id', False)
if not self._context.get('no_create_line', False):
# Nos aseguramos que el name de sale.order.line sea el correcto
# (con referencia y atributos de variante)
line_vals = vals.copy()
template_product = self.env['product.template'].browse(vals['product_template'])
if template_product.display_name == line_vals['name']:
product_vals = self.env['product.product'].browse(
line_vals['product_id'])
line_vals['name'] = product_vals.display_name
new_line = self.env['sale.order.line'].with_context(
no_create_template_line=True).create(line_vals)
vals['order_lines'] = [(6, 0, [new_line.id])]
vals['name'] = template_product.display_name
return super(
SaleOrderLineTemplate,
self.with_context(no_create_template_line=True)).create(vals)
@api.model
def create_mal(self, vals):
## TODO: REVISAR KIKO. No traslada el precio de la primera variante
ctx = self._context.copy()
# Se controla el create con order_lines debido que al duplicar un
# pedido el vals de las lineas viene sin order_id
order_id = vals.get('order_id', False)
if vals.get('order_lines', False):
for line_vals in vals['order_lines']:
if line_vals[0] == 0:
line_vals[2]['order_id'] = vals.get('order_id', False)
if not self._context.get('no_create_line', False):
# Nos aseguramos que el name de sale.order.line sea el correcto
# (con referencia y atributos de variante)
ctx.update(no_create_template_line=True)
line_vals = vals.copy()
orig = True
if orig:
line_vals = vals.copy()
template_product = self.env['product.template'].browse(vals['product_template'])
if template_product.display_name == line_vals['name']:
product_vals = self.env['product.product'].browse(
line_vals['product_id'])
line_vals['name'] = product_vals.display_name
new_line = self.env['sale.order.line'].with_context(ctx).create(line_vals)
vals['order_lines'] = [(6, 0, [new_line.id])]
else:
new_line_ids = self.env['sale.order.line']
template_product = self.env['product.template'].browse(vals['product_template'])
product_id = self.env['product.product'].browse(line_vals['product_id'])
if template_product.display_name == line_vals['name']:
line_vals['name'] = product_id.display_name
line_vals.update({
'product_id': product_id.id,
'product_uom': product_id.uom_id,
'order_id': order_id,
})
order_line = self.env['sale.order.line'].with_context(ctx).new(line_vals)
order_line.product_id_change()
order_line_vals = order_line._convert_to_write(order_line._cache)
new_line_ids |= new_line_ids.with_context(ctx).create(order_line_vals)
vals['order_lines'] = [(6, 0, new_line_ids.ids)]
return super(
SaleOrderLineTemplate,
self.with_context(no_create_template_line=True)).create(vals)
def _compute_order_lines_qty(self):
for template in self:
template.lines_qty = len(template.order_lines)
@api.onchange('product_template')
def onchange_template(self):
if not self.product_template:
return
self.product_id = self.product_template.product_variant_ids[0]
# @api.onchange('product_uom_qty', 'product_uom', 'route_id')
# def _onchange_product_id_check_availability(self):
# return
#
# @api.onchange('product_id')
# def _onchange_product_id_uom_check_availability(self):
# return
#
# @api.onchange('product_uom_qty')
# def _onchange_product_uom_qty(self):
# return
#
# @api.onchange('product_id')
# def _onchange_product_id_set_customer_lead(self):
# return
class SaleOrderLine(models.Model):
_inherit = 'sale.order.line'
@api.multi
@api.depends('product_id')
def _get_global_stock(self):
for line in self:
if line.product_id:
line.global_available_stock = \
line.product_id.web_global_stock
else:
line.global_available_stock = 0.0
template_line = fields.Many2one('sale.order.line.template')
global_available_stock = fields.Float('Stock', readonly=True,
compute="_get_global_stock",
store=True)
note = fields.Text("Notas")
partner_id = fields.Many2one(related='order_id.partner_id', string='partner', store=True, readonly=True)
pricelist_id = fields.Many2one(related='order_id.pricelist_id', string='partner', store=True, readonly=True)
check_edit = fields.Boolean(compute='_compute_check_edit')
@api.depends('template_line.lines_qty', 'product_id.product_tmpl_id.product_attribute_count')
def _compute_check_edit(self):
for line in self:
check_edit = True
if line.product_id.product_tmpl_id.product_attribute_count > 0:
check_edit = False
if line.template_line.lines_qty > 1:
check_edit = False
line.check_edit = check_edit
@api.model
def create(self, vals):
if self._context.get('template_line', False):
vals['template_line'] = self._context.get('template_line', False)
if not vals.get('template_line', False) and not \
self._context.get('no_create_template_line', False):
product = self.env['product.product'].browse(
vals.get('product_id'))
vals['product_template'] = product.product_tmpl_id.id
new_template = self.env['sale.order.line.template'].with_context(
no_create_template_line=True, no_create_line=True).create(vals)
vals.pop('product_template')
vals['template_line'] = new_template.id
return super(SaleOrderLine, self).create(vals)
@api.onchange('product_uom_qty', 'product_uom', 'route_id')
def _onchange_product_id_check_availability(self):
res = super(SaleOrderLine, self).\
_onchange_product_id_check_availability()
if not self.product_id or self.product_id.type != 'product':
return res
precision = self.env['decimal.precision'].\
precision_get('Product Unit of Measure')
product_qty = self.product_uom.\
_compute_quantity(self.product_uom_qty,
self.product_id.uom_id)
if float_compare(self.product_id.web_global_stock,
product_qty, precision_digits=precision) == -1:
warning_mess = {
'title': _('Not enough inventory!'),
'message':
_('You plan to sell %s %s but you only have %s %s '
'available!\nThe stock on hand is %s %s.') %
(self.product_uom_qty, self.product_uom.name,
self.product_id.web_global_stock,
self.product_id.uom_id.name,
self.product_id.web_global_stock,
self.product_id.uom_id.name)}
res['warning'] = warning_mess
elif res.get('warning'):
del res['warning']
return res
@api.multi
def show_details(self):
view_id = self.env.ref('custom_sale_order_variant_mgmt.sale_order_line_custom_form_note').id
return {
'name': _('Sale order line details'),
'type': 'ir.actions.act_window',
'view_type': 'form',
'view_mode': 'form',
'res_model': 'sale.order.line',
'views': [(view_id, 'form')],
'view_id': view_id,
'target': 'new',
'res_id': self.ids[0],
'context': self.env.context}
@api.multi
def _action_procurement_create(self):
if self._name == 'sale.order.line':
return super(SaleOrderLine, self)._action_procurement_create()
@api.multi
def unlink(self):
templates = self.mapped('template_line')
res = super(SaleOrderLine, self).unlink()
if not self._context.get('unlink_template_line', False):
templates_tu = templates.filtered(lambda x: not x.order_lines)
if templates_tu:
ctx = self._context.copy()
ctx.update(unlink_product_line=True)
templates_tu.with_context(ctx).unlink()
return res
class SaleOrder(models.Model):
_inherit = 'sale.order'
template_lines = fields.One2many('sale.order.line.template', 'order_id',
copy=True)
order_line = fields.One2many(copy=False)
sale_order_line_count = fields.Integer(
compute='_compute_sale_order_line_count')
@api.model
def fields_view_get(self, view_id=None, view_type='form', toolbar=False,
submenu=False):
"""
Override to add message_content field in all the objects
that inherits mail.thread
"""
res = super(SaleOrder, self).fields_view_get(
view_id=view_id, view_type=view_type, toolbar=toolbar,
submenu=submenu)
if view_type == 'form':
doc = etree.XML(res['arch'])
for node in doc.xpath("//field[@name='order_line']"):
# Add message_content in search view
node.getparent().remove(node)
res['arch'] = etree.tostring(doc)
return res
@api.depends('order_line')
def _compute_sale_order_line_count(self):
for order in self:
order.sale_order_line_count = len(order.order_line)
@api.multi
def action_view_order_lines(self):
action = self.env.ref(
'custom_sale_order_variant_mgmt.sale_order_line_action').read()[0]
action['domain'] = [('id', 'in', self.order_line.ids)]
action['context'] = {
'default_order_id': self.id,
}
return action
@api.multi
def copy(self, default={}):
return super(
SaleOrder,
self.with_context(no_create_line=True,
no_create_template_line=True)).copy(default)
def clear_existing_promotion_lines(self):
order = self
order_line_obj = self.env['sale.order.line']
# Delete all template lines related with promotion sale order lines
domain = [('order_id', '=', order.id), ('promotion_line', '=', True)]
order_line_objs = order_line_obj.search(domain)
related_template_lines = order_line_objs.mapped('template_line')
related_template_lines.unlink()
res = super(SaleOrder, self).clear_existing_promotion_lines()
return res
| Comunitea/CMNT_00098_2017_JIM_addons | custom_sale_order_variant_mgmt/models/sale_order.py | Python | agpl-3.0 | 13,669 |