repo_name
stringlengths 5
92
| path
stringlengths 4
232
| copies
stringclasses 18
values | size
stringlengths 4
7
| content
stringlengths 736
1.04M
| license
stringclasses 15
values | hash
int64 -9,222,983,980,000,580,000
9,223,102,107B
| line_mean
float64 6.51
99.9
| line_max
int64 15
997
| alpha_frac
float64 0.25
0.97
| autogenerated
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|
denmojo/pygrow | grow/commands/filter.py | 1 | 2992 | from grow.pods import pods
from grow.pods import storage
import click
import os
@click.command()
@click.argument('pod_path', default='.')
@click.option('--include-obsolete/--no-include-obsolete', default=False,
is_flag=True,
help='Whether to include obsolete messages. If false, obsolete'
' messages will be removed from the catalog template. By'
' default, Grow cleans obsolete messages from the catalog'
' template.')
@click.option('--localized/--no-localized', default=False, is_flag=True,
help='Whether to create localized message catalogs. Use this'
' option if content varies by locale.')
@click.option('--locale', type=str, multiple=True,
help='Which locale(s) to analyze when creating template catalogs'
' that contain only untranslated messages. This option is'
' only applicable when using --untranslated.')
@click.option('--path', type=str, multiple=True,
help='Which paths to extract strings from. By default, all paths'
' are extracted. This option is useful if you\'d like to'
' generate a partial messages file representing just a'
' specific set of files.')
@click.option('-o', type=str, default=None,
help='Where to write the extracted translation catalog. The path'
' must be relative to the pod\'s root.')
@click.option('--include-header', default=False, is_flag=True,
help='Whether to preserve headers at the beginning of catalogs.')
@click.option('--out_dir', type=str, default=None,
help='Where to write extracted localized translation catalogs.'
' The path must be relative to the pod\'s root. This option'
' is only applicable when using --localized.')
@click.option('-f', default=False, is_flag=True,
help='Whether to force an update when writing localized message'
' catalogs.')
def filter(pod_path, locale, o, include_obsolete, localized, path,
include_header, out_dir, f):
"""Filters untranslated messages from catalogs into new catalogs."""
root = os.path.abspath(os.path.join(os.getcwd(), pod_path))
pod = pods.Pod(root, storage=storage.FileStorage)
catalogs = pod.get_catalogs()
if not locale:
locale = catalogs.list_locales()
if out_dir and pod.file_exists(out_dir) and not f:
raise click.UsageError(
'{} exists. You must specify a directory that does not exist, or '
'use the "-f" flag, which will force update catalogs within the '
'specified directory.'.format(out_dir))
catalogs.filter(out_path=o, out_dir=out_dir,
include_obsolete=include_obsolete,
localized=localized, paths=path,
include_header=include_header, locales=locale)
| mit | 5,153,167,556,879,288,000 | 53.4 | 79 | 0.621658 | false |
auto-mat/klub | apps/aklub/autocom.py | 1 | 6964 | # -*- coding: utf-8 -*-
# Author: Hynek Hanke <hynek.hanke@auto-mat.cz>
#
# Copyright (C) 2010 o.s. Auto*Mat
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
"""Automatic communications for club management"""
import datetime
import logging
import string
from django.core.exceptions import ValidationError
logger = logging.getLogger(__name__)
def _localize_enum(descr, val, lang):
for t in descr:
if t[0] == val:
# Hack! Here we should use the Gettext localization
# based on the value of 'lang' -- this is however
# not easy due to lazy translations and t[1] already
# being wrapped by a foreign translator
if lang == 'cs':
return t[1].lower()
else:
# less wrong would be to retrieve the original untranslated version of t[1]...
return t[0]
# Translation not found
return val
KNOWN_VARIABLES = [
"addressment", "name", "firstname", "surname", "street", "city", "zipcode", "email",
"telephone", "regular_amount", "regular_frequency", "var_symbol", "last_payment_amount",
"auth_token",
]
def min_non_negative(i, j):
if i < 0:
return j
if j < 0:
return i
return min(i, j)
def gendrify_text(text, sex=''):
# Modify text according to gender
# Example: Vazen{y|a} {pane|pani} -> [male] -> Vazeny pane
gender_text = ""
o = 0
i = 0
while i < len(text):
if text[i] == '{':
gender_text += text[o:i]
sep_pos = min_non_negative(text.find('|', i), text.find('/', i))
end_pos = text.find('}', i)
if sep_pos <= i or end_pos <= sep_pos:
raise ValidationError("Gender strings must look like {male_variant|female_variant} or {male_variant/female_variant}")
male_variant = text[i + 1:sep_pos]
female_variant = text[sep_pos + 1:end_pos]
if sex == 'male':
gender_text += male_variant
elif sex == 'female':
gender_text += female_variant
else:
gender_text += male_variant + "/" + female_variant
o = end_pos + 1
i = end_pos
i += 1
gender_text += text[o:]
return gender_text
def process_template(template_string, user, payment_channel):
from .models import DonorPaymentChannel
from sesame import utils as sesame_utils
template = string.Template(template_string)
if payment_channel:
payment_substitutes = {
'regular_amount': payment_channel.regular_amount,
'regular_frequency': _localize_enum(
DonorPaymentChannel.REGULAR_PAYMENT_FREQUENCIES,
payment_channel.regular_frequency,
user.language,
),
'var_symbol': payment_channel.VS,
'last_payment_amount': payment_channel.last_payment.amount if payment_channel.last_payment else None,
}
else:
payment_substitutes = {}
# Make variable substitutions
text = template.substitute(
addressment=user.get_addressment(),
last_name_vokativ=user.get_last_name_vokativ(),
name=user.first_name if hasattr(user, 'first_name') else user.name,
firstname=user.first_name if hasattr(user, 'first_name') else user.name,
surname=user.last_name if hasattr(user, 'first_name') else user.name,
street=user.street,
city=user.city,
zipcode=user.zip_code,
email=user.email,
telephone=user.get_telephone(),
auth_token=sesame_utils.get_query_string(user),
**payment_substitutes,
)
return gendrify_text(text, user.sex if hasattr(user, 'sex') else '')
def check(user_profiles=None, action=None): # noqa
from .models import AutomaticCommunication, DonorPaymentChannel, UserProfile
from interactions.models import Interaction
if not user_profiles:
user_profiles = UserProfile.objects.all()
# limit autocoms only for autocoms where action is used
if action:
# TODO: handle nested conditions?
from flexible_filter_conditions.models import TerminalCondition
conditions = TerminalCondition.objects.filter(variable='action', value=action).values_list('condition')
auto_coms = AutomaticCommunication.objects.filter(condition__conditions__in=conditions)
else:
auto_coms = AutomaticCommunication.objects.all()
for auto_comm in auto_coms:
logger.info(
u"Processin condition \"%s\" for autocom \"%s\", method: \"%s\", action: \"%s\"" % (
auto_comm.condition,
auto_comm,
auto_comm.method_type,
action,
),
)
filtered_user_profiles = auto_comm.condition.filter_queryset(user_profiles, action)
for user in filtered_user_profiles:
try:
if auto_comm.event:
payment_channel = user.userchannels.get(event=auto_comm.event)
else:
payment_channel = None
except DonorPaymentChannel.DoesNotExist:
payment_channel = None
if auto_comm.only_once and auto_comm.sent_to_users.filter(pk=user.pk).exists():
continue
if user.language == 'cs':
template = auto_comm.template
subject = auto_comm.subject
else:
template = auto_comm.template_en
subject = auto_comm.subject_en
if template and template != '':
logger.info(u"Added new automatic communication \"%s\" for user \"%s\", action \"%s\"" % (auto_comm, user, action))
c = Interaction(
user=user,
type=auto_comm.method_type,
date_from=datetime.datetime.now(),
subject=subject,
summary=process_template(template, user, payment_channel),
note="Prepared by automated mailer at %s" % datetime.datetime.now(),
settlement='a',
administrative_unit=auto_comm.administrative_unit,
)
auto_comm.sent_to_users.add(user)
c.save()
| gpl-3.0 | 9,162,069,310,918,358,000 | 37.263736 | 133 | 0.597071 | false |
AunShiLord/sympy | sympy/series/tests/test_series.py | 1 | 4998 | from sympy import sin, cos, exp, E, series, oo, S, Derivative, O, Integral, \
Function, log, sqrt, Symbol, Subs, pi, symbols
from sympy.abc import x, y, n, k
from sympy.utilities.pytest import raises
from sympy.series.gruntz import calculate_series
def test_sin():
e1 = sin(x).series(x, 0)
e2 = series(sin(x), x, 0)
assert e1 == e2
def test_cos():
e1 = cos(x).series(x, 0)
e2 = series(cos(x), x, 0)
assert e1 == e2
def test_exp():
e1 = exp(x).series(x, 0)
e2 = series(exp(x), x, 0)
assert e1 == e2
def test_exp2():
e1 = exp(cos(x)).series(x, 0)
e2 = series(exp(cos(x)), x, 0)
assert e1 == e2
def test_issue_5223():
assert series(1, x) == 1
assert next(S(0).lseries(x)) == 0
assert cos(x).series() == cos(x).series(x)
raises(ValueError, lambda: cos(x + y).series())
raises(ValueError, lambda: x.series(dir=""))
assert (cos(x).series(x, 1) -
cos(x + 1).series(x).subs(x, x - 1)).removeO() == 0
e = cos(x).series(x, 1, n=None)
assert [next(e) for i in range(2)] == [cos(1), -((x - 1)*sin(1))]
e = cos(x).series(x, 1, n=None, dir='-')
assert [next(e) for i in range(2)] == [cos(1), (1 - x)*sin(1)]
# the following test is exact so no need for x -> x - 1 replacement
assert abs(x).series(x, 1, dir='-') == x
assert exp(x).series(x, 1, dir='-', n=3).removeO() == \
E - E*(-x + 1) + E*(-x + 1)**2/2
D = Derivative
assert D(x**2 + x**3*y**2, x, 2, y, 1).series(x).doit() == 12*x*y
assert next(D(cos(x), x).lseries()) == D(1, x)
assert D(
exp(x), x).series(n=3) == D(1, x) + D(x, x) + D(x**2/2, x) + O(x**3)
assert Integral(x, (x, 1, 3), (y, 1, x)).series(x) == -4 + 4*x
assert (1 + x + O(x**2)).getn() == 2
assert (1 + x).getn() is None
assert ((1/sin(x))**oo).series() == oo
logx = Symbol('logx')
assert ((sin(x))**y).nseries(x, n=1, logx=logx) == \
exp(y*logx) + O(x*exp(y*logx), x)
assert sin(1/x).series(x, oo, n=5) == 1/x - 1/(6*x**3) + O(x**(-5), (x, oo))
assert abs(x).series(x, oo, n=5, dir='+') == x
assert abs(x).series(x, -oo, n=5, dir='-') == -x
assert abs(-x).series(x, oo, n=5, dir='+') == x
assert abs(-x).series(x, -oo, n=5, dir='-') == -x
assert exp(x*log(x)).series(n=3) == \
1 + x*log(x) + x**2*log(x)**2/2 + O(x**3*log(x)**3)
# XXX is this right? If not, fix "ngot > n" handling in expr.
p = Symbol('p', positive=True)
assert exp(sqrt(p)**3*log(p)).series(n=3) == \
1 + p**S('3/2')*log(p) + O(p**3*log(p)**3)
assert exp(sin(x)*log(x)).series(n=2) == 1 + x*log(x) + O(x**2*log(x)**2)
def test_issue_3978():
f = Function('f')
assert f(x).series(x, 0, 3, dir='-') == \
f(0) + x*Subs(Derivative(f(x), x), (x,), (0,)) + \
x**2*Subs(Derivative(f(x), x, x), (x,), (0,))/2 + O(x**3)
assert f(x).series(x, 0, 3) == \
f(0) + x*Subs(Derivative(f(x), x), (x,), (0,)) + \
x**2*Subs(Derivative(f(x), x, x), (x,), (0,))/2 + O(x**3)
assert f(x**2).series(x, 0, 3) == \
f(0) + x**2*Subs(Derivative(f(x), x), (x,), (0,)) + O(x**3)
assert f(x**2+1).series(x, 0, 3) == \
f(1) + x**2*Subs(Derivative(f(x), x), (x,), (1,)) + O(x**3)
class TestF(Function):
pass
assert TestF(x).series(x, 0, 3) == TestF(0) + \
x*Subs(Derivative(TestF(x), x), (x,), (0,)) + \
x**2*Subs(Derivative(TestF(x), x, x), (x,), (0,))/2 + O(x**3)
from sympy.series.acceleration import richardson, shanks
from sympy import Sum, Integer
def test_acceleration():
e = (1 + 1/n)**n
assert round(richardson(e, n, 10, 20).evalf(), 10) == round(E.evalf(), 10)
A = Sum(Integer(-1)**(k + 1) / k, (k, 1, n))
assert round(shanks(A, n, 25).evalf(), 4) == round(log(2).evalf(), 4)
assert round(shanks(A, n, 25, 5).evalf(), 10) == round(log(2).evalf(), 10)
def test_issue_5852():
assert series(1/cos(x/log(x)), x, 0) == 1 + x**2/(2*log(x)**2) + \
5*x**4/(24*log(x)**4) + O(x**6)
def test_issue_4583():
assert cos(1 + x + x**2).series(x, 0, 5) == cos(1) - x*sin(1) + \
x**2*(-sin(1) - cos(1)/2) + x**3*(-cos(1) + sin(1)/6) + \
x**4*(-11*cos(1)/24 + sin(1)/2) + O(x**5)
def test_issue_6318():
eq = (1/x)**(S(2)/3)
assert (eq + 1).as_leading_term(x) == eq
def test_x_is_base_detection():
eq = (x**2)**(S(2)/3)
assert eq.series() == x**(S(4)/3)
def test_sin_power():
e = sin(x)**1.2
assert calculate_series(e, x) == x**1.2
def test_issue_7203():
assert series(cos(x), x, pi, 3) == \
-1 + (x - pi)**2/2 + O((x - pi)**3, (x, pi))
def test_exp_product_positive_factors():
a, b = symbols('a, b', positive=True)
x = a * b
assert series(exp(x), x, n=8) == 1 + a*b + a**2*b**2/2 + \
a**3*b**3/6 + a**4*b**4/24 + a**5*b**5/120 + a**6*b**6/720 + \
a**7*b**7/5040 + O(a**8*b**8, a, b)
def test_issue_8805():
assert series(1, n=8) == 1
| bsd-3-clause | 1,150,461,149,742,997,500 | 31.454545 | 80 | 0.492597 | false |
pony-revolution/helpothers | helpothers/views.py | 1 | 1239 | from django.contrib.auth import get_user_model
from django.views.generic.base import TemplateView
from django.views.generic.detail import DetailView
from django.views.generic.edit import UpdateView
from .views_mixins import HelpOthersMetaDataMixin
from dunder_mifflin import papers # WARNING: Malicious operation ahead
from listings.models import GatheringCenter, Resource
class HomeView(HelpOthersMetaDataMixin, TemplateView):
template_name = 'home.html'
def get_context_data(self, **kwargs):
context = super(HomeView, self).get_context_data(**kwargs)
context['gathering_centers'] = GatheringCenter.objects.filter(published=True)
context['resources'] = Resource.objects.filter(published=True)
return context
class LoginView(HelpOthersMetaDataMixin, TemplateView):
template_name = 'login.html'
def get_context_data(self, **kwargs):
ctx = super(LoginView, self).get_context_data(**kwargs)
ctx['next'] = self.request.GET.get('next')
return ctx
class ProfileView(HelpOthersMetaDataMixin, UpdateView):
context_object_name = 'profile'
template_name = 'accounts/profile.html'
fields = ('user__first_name', 'user__last_name', 'user__email')
def get_object(self, queryset=None):
return self.request.user.profile
| apache-2.0 | -828,806,971,788,788,700 | 34.4 | 85 | 0.727199 | false |
paineliu/tflearn | helen.py | 1 | 1084 | import os
from PIL import Image
img_path = '/home/palm/deep/helen/train'
lab_path = '/home/palm/deep/helen/annotation'
filename = '/home/palm/deep/helen/trainnames.txt'
f = open(filename)
index = 1
for each in f:
each = each.strip()
img_file = os.path.join(img_path, each + '.jpg')
img = Image.open(img_file)
width, height = img.size
img = img.resize((256, 256))
img = img.convert('L')
lab_file = os.path.join(lab_path, str(index) + '.txt')
fl = open(lab_file)
for line in fl:
line = line.strip()
item = line.split(',')
if len(item) == 2:
x = int(float(item[0]) * 256 / width)
y = int(float(item[1]) * 256 / height)
if x > 0 and x < img.size[0] and y > 0 and y < img.size[1]:
img.putpixel((x, y), 0xffffff)
img.putpixel((x-1, y), 0xffffff)
img.putpixel((x, y-1), 0xffffff)
img.putpixel((x-1, y-1), 0xffffff)
else:
print index, each, img.size, x, y
index += 1
img.show()
break
| apache-2.0 | -8,658,315,276,180,879,000 | 26.1 | 71 | 0.530443 | false |
tisnik/fabric8-analytics-common | dashboard/src/jacoco_to_codecov.py | 1 | 4579 | """Module to convert JaCoCo coverage report into the report compatible with Pycov utility."""
import csv
def format_coverage_line(text, statements, missed, coverage, missed_lines=False):
"""Format one line with code coverage report of one class or for a summary."""
format_string = "{:80} {:3d} {:3d} {:3d}%"
if missed_lines:
format_string += " N/A"
return format_string.format(text, statements, missed, coverage)
def compute_coverage(statements, covered):
"""Compute code coverage based on number of all statemts and number of covered statements."""
return 100.0 * covered / statements
class JavaClassCoverageReport:
"""Class representing code coverage report for one Java class."""
def __init__(self, record):
"""Initialize the object by using record read from the CSV file."""
self.group = record[0]
self.package = record[1]
self.class_name = record[2]
self.missed = int(record[7])
self.covered = int(record[8])
self.statements = self.covered + self.missed
self.coverage = compute_coverage(self.statements, self.covered)
def __str__(self):
"""Return readable text representation compatible with Pycov utility output."""
pc = "{package}/{class_name}".format(package=self.package, class_name=self.class_name)
return format_coverage_line(pc, self.statements, self.missed, int(self.coverage))
class ProjectCoverageReport:
"""Class to perform conversion from JaCoCo output to report compatible with Pycov utility."""
def __init__(self, csv_input_file_name):
"""Initialize the object, store the name of input (CSV) file."""
self.csv_input_file_name = csv_input_file_name
@staticmethod
def read_csv(csv_input_file_name, skip_first_line=False):
"""Read the given CSV file, parse it, and return as list of records."""
output = []
with open(csv_input_file_name, 'r') as fin:
csv_content = csv.reader(fin, delimiter=',')
if skip_first_line:
next(csv_content, None)
for row in csv_content:
output.append(row)
return output
@staticmethod
def write_horizontal_rule(fout):
"""Write horizontal rule into the output file."""
fout.write("-" * 108)
fout.write("\n")
@staticmethod
def write_coverage_report_header(fout):
"""Write header compatible with Pycov to the output file."""
fout.write("{:80} {:5} {:4} {:5} {}\n".format(
"Name", "Stmts", "Miss", "Cover", "Missing"))
ProjectCoverageReport.write_horizontal_rule(fout)
@staticmethod
def write_coverage_report_summary(fout, statements, missed, coverage):
"""Write summary compatible with Pycov to the output file."""
ProjectCoverageReport.write_horizontal_rule(fout)
fout.write(format_coverage_line("TOTAL", statements, missed, int(coverage)))
fout.write("\n")
def read_java_classes(self):
"""Read and parse into about Java classes from JaCoCo results."""
data = ProjectCoverageReport.read_csv(self.csv_input_file_name, True)
return [JavaClassCoverageReport(record) for record in data]
def convert_code_coverage_report(self, output_file_name):
"""Convert code coverage report that would be compatible with PyCov output."""
java_classes = self.read_java_classes()
statements, missed, coverage = ProjectCoverageReport.compute_total(java_classes)
with open(output_file_name, "w") as fout:
ProjectCoverageReport.write_coverage_report_header(fout)
for java_class in java_classes:
fout.write(str(java_class) + "\n")
ProjectCoverageReport.write_coverage_report_summary(fout, statements, missed, coverage)
@staticmethod
def compute_total(records):
"""Compute total/summary from all Java class coverage reports."""
statements = 0
covered = 0
missed = 0
for record in records:
statements += record.statements
covered += record.covered
missed += record.missed
coverage = compute_coverage(statements, covered)
return statements, missed, coverage
def main():
"""Just a test ATM."""
p = ProjectCoverageReport("fabric8-analytics-jenkins-plugin.coverage.csv")
p.convert_code_coverage_report("fabric8-analytics-jenkins-plugin.coverage.txt")
if __name__ == "__main__":
# execute only if run as a script
main()
| apache-2.0 | -754,818,450,584,529,800 | 39.166667 | 99 | 0.647085 | false |
googleapis/googleapis-gen | google/ads/googleads/v8/googleads-py/google/ads/googleads/v8/common/types/ad_type_infos.py | 1 | 46175 | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# 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 proto # type: ignore
from google.ads.googleads.v8.common.types import ad_asset
from google.ads.googleads.v8.enums.types import call_conversion_reporting_state
from google.ads.googleads.v8.enums.types import display_ad_format_setting
from google.ads.googleads.v8.enums.types import display_upload_product_type as gage_display_upload_product_type
from google.ads.googleads.v8.enums.types import legacy_app_install_ad_app_store
from google.ads.googleads.v8.enums.types import mime_type as gage_mime_type
__protobuf__ = proto.module(
package='google.ads.googleads.v8.common',
marshal='google.ads.googleads.v8',
manifest={
'TextAdInfo',
'ExpandedTextAdInfo',
'ExpandedDynamicSearchAdInfo',
'HotelAdInfo',
'ShoppingSmartAdInfo',
'ShoppingProductAdInfo',
'ShoppingComparisonListingAdInfo',
'GmailAdInfo',
'GmailTeaser',
'DisplayCallToAction',
'ProductImage',
'ProductVideo',
'ImageAdInfo',
'VideoBumperInStreamAdInfo',
'VideoNonSkippableInStreamAdInfo',
'VideoTrueViewInStreamAdInfo',
'VideoOutstreamAdInfo',
'VideoTrueViewDiscoveryAdInfo',
'VideoAdInfo',
'VideoResponsiveAdInfo',
'ResponsiveSearchAdInfo',
'LegacyResponsiveDisplayAdInfo',
'AppAdInfo',
'AppEngagementAdInfo',
'LegacyAppInstallAdInfo',
'ResponsiveDisplayAdInfo',
'LocalAdInfo',
'DisplayUploadAdInfo',
'ResponsiveDisplayAdControlSpec',
'SmartCampaignAdInfo',
'CallAdInfo',
},
)
class TextAdInfo(proto.Message):
r"""A text ad.
Attributes:
headline (str):
The headline of the ad.
description1 (str):
The first line of the ad's description.
description2 (str):
The second line of the ad's description.
"""
headline = proto.Field(
proto.STRING,
number=4,
optional=True,
)
description1 = proto.Field(
proto.STRING,
number=5,
optional=True,
)
description2 = proto.Field(
proto.STRING,
number=6,
optional=True,
)
class ExpandedTextAdInfo(proto.Message):
r"""An expanded text ad.
Attributes:
headline_part1 (str):
The first part of the ad's headline.
headline_part2 (str):
The second part of the ad's headline.
headline_part3 (str):
The third part of the ad's headline.
description (str):
The description of the ad.
description2 (str):
The second description of the ad.
path1 (str):
The text that can appear alongside the ad's
displayed URL.
path2 (str):
Additional text that can appear alongside the
ad's displayed URL.
"""
headline_part1 = proto.Field(
proto.STRING,
number=8,
optional=True,
)
headline_part2 = proto.Field(
proto.STRING,
number=9,
optional=True,
)
headline_part3 = proto.Field(
proto.STRING,
number=10,
optional=True,
)
description = proto.Field(
proto.STRING,
number=11,
optional=True,
)
description2 = proto.Field(
proto.STRING,
number=12,
optional=True,
)
path1 = proto.Field(
proto.STRING,
number=13,
optional=True,
)
path2 = proto.Field(
proto.STRING,
number=14,
optional=True,
)
class ExpandedDynamicSearchAdInfo(proto.Message):
r"""An expanded dynamic search ad.
Attributes:
description (str):
The description of the ad.
description2 (str):
The second description of the ad.
"""
description = proto.Field(
proto.STRING,
number=3,
optional=True,
)
description2 = proto.Field(
proto.STRING,
number=4,
optional=True,
)
class HotelAdInfo(proto.Message):
r"""A hotel ad. """
class ShoppingSmartAdInfo(proto.Message):
r"""A Smart Shopping ad. """
class ShoppingProductAdInfo(proto.Message):
r"""A standard Shopping ad. """
class ShoppingComparisonListingAdInfo(proto.Message):
r"""A Shopping Comparison Listing ad.
Attributes:
headline (str):
Headline of the ad. This field is required.
Allowed length is between 25 and 45 characters.
"""
headline = proto.Field(
proto.STRING,
number=2,
optional=True,
)
class GmailAdInfo(proto.Message):
r"""A Gmail ad.
Attributes:
teaser (google.ads.googleads.v8.common.types.GmailTeaser):
The Gmail teaser.
header_image (str):
The MediaFile resource name of the header
image. Valid image types are GIF, JPEG and PNG.
The minimum size is 300x100 pixels and the
aspect ratio must be between 3:1 and 5:1 (+-1%).
marketing_image (str):
The MediaFile resource name of the marketing
image. Valid image types are GIF, JPEG and PNG.
The image must either be landscape with a
minimum size of 600x314 pixels and aspect ratio
of 600:314 (+-1%) or square with a minimum size
of 300x300 pixels and aspect ratio of 1:1 (+-1%)
marketing_image_headline (str):
Headline of the marketing image.
marketing_image_description (str):
Description of the marketing image.
marketing_image_display_call_to_action (google.ads.googleads.v8.common.types.DisplayCallToAction):
Display-call-to-action of the marketing
image.
product_images (Sequence[google.ads.googleads.v8.common.types.ProductImage]):
Product images. Up to 15 images are
supported.
product_videos (Sequence[google.ads.googleads.v8.common.types.ProductVideo]):
Product videos. Up to 7 videos are supported.
At least one product video or a marketing image
must be specified.
"""
teaser = proto.Field(
proto.MESSAGE,
number=1,
message='GmailTeaser',
)
header_image = proto.Field(
proto.STRING,
number=10,
optional=True,
)
marketing_image = proto.Field(
proto.STRING,
number=11,
optional=True,
)
marketing_image_headline = proto.Field(
proto.STRING,
number=12,
optional=True,
)
marketing_image_description = proto.Field(
proto.STRING,
number=13,
optional=True,
)
marketing_image_display_call_to_action = proto.Field(
proto.MESSAGE,
number=6,
message='DisplayCallToAction',
)
product_images = proto.RepeatedField(
proto.MESSAGE,
number=7,
message='ProductImage',
)
product_videos = proto.RepeatedField(
proto.MESSAGE,
number=8,
message='ProductVideo',
)
class GmailTeaser(proto.Message):
r"""Gmail teaser data. The teaser is a small header that acts as
an invitation to view the rest of the ad (the body).
Attributes:
headline (str):
Headline of the teaser.
description (str):
Description of the teaser.
business_name (str):
Business name of the advertiser.
logo_image (str):
The MediaFile resource name of the logo
image. Valid image types are GIF, JPEG and PNG.
The minimum size is 144x144 pixels and the
aspect ratio must be 1:1 (+-1%).
"""
headline = proto.Field(
proto.STRING,
number=5,
optional=True,
)
description = proto.Field(
proto.STRING,
number=6,
optional=True,
)
business_name = proto.Field(
proto.STRING,
number=7,
optional=True,
)
logo_image = proto.Field(
proto.STRING,
number=8,
optional=True,
)
class DisplayCallToAction(proto.Message):
r"""Data for display call to action. The call to action is a
piece of the ad that prompts the user to do something. Like
clicking a link or making a phone call.
Attributes:
text (str):
Text for the display-call-to-action.
text_color (str):
Text color for the display-call-to-action in
hexadecimal, e.g. #ffffff for white.
url_collection_id (str):
Identifies the url collection in the ad.url_collections
field. If not set the url defaults to final_url.
"""
text = proto.Field(
proto.STRING,
number=5,
optional=True,
)
text_color = proto.Field(
proto.STRING,
number=6,
optional=True,
)
url_collection_id = proto.Field(
proto.STRING,
number=7,
optional=True,
)
class ProductImage(proto.Message):
r"""Product image specific data.
Attributes:
product_image (str):
The MediaFile resource name of the product
image. Valid image types are GIF, JPEG and PNG.
The minimum size is 300x300 pixels and the
aspect ratio must be 1:1 (+-1%).
description (str):
Description of the product.
display_call_to_action (google.ads.googleads.v8.common.types.DisplayCallToAction):
Display-call-to-action of the product image.
"""
product_image = proto.Field(
proto.STRING,
number=4,
optional=True,
)
description = proto.Field(
proto.STRING,
number=5,
optional=True,
)
display_call_to_action = proto.Field(
proto.MESSAGE,
number=3,
message='DisplayCallToAction',
)
class ProductVideo(proto.Message):
r"""Product video specific data.
Attributes:
product_video (str):
The MediaFile resource name of a video which
must be hosted on YouTube.
"""
product_video = proto.Field(
proto.STRING,
number=2,
optional=True,
)
class ImageAdInfo(proto.Message):
r"""An image ad.
Attributes:
pixel_width (int):
Width in pixels of the full size image.
pixel_height (int):
Height in pixels of the full size image.
image_url (str):
URL of the full size image.
preview_pixel_width (int):
Width in pixels of the preview size image.
preview_pixel_height (int):
Height in pixels of the preview size image.
preview_image_url (str):
URL of the preview size image.
mime_type (google.ads.googleads.v8.enums.types.MimeTypeEnum.MimeType):
The mime type of the image.
name (str):
The name of the image. If the image was
created from a MediaFile, this is the
MediaFile's name. If the image was created from
bytes, this is empty.
media_file (str):
The MediaFile resource to use for the image.
data (bytes):
Raw image data as bytes.
ad_id_to_copy_image_from (int):
An ad ID to copy the image from.
"""
pixel_width = proto.Field(
proto.INT64,
number=15,
optional=True,
)
pixel_height = proto.Field(
proto.INT64,
number=16,
optional=True,
)
image_url = proto.Field(
proto.STRING,
number=17,
optional=True,
)
preview_pixel_width = proto.Field(
proto.INT64,
number=18,
optional=True,
)
preview_pixel_height = proto.Field(
proto.INT64,
number=19,
optional=True,
)
preview_image_url = proto.Field(
proto.STRING,
number=20,
optional=True,
)
mime_type = proto.Field(
proto.ENUM,
number=10,
enum=gage_mime_type.MimeTypeEnum.MimeType,
)
name = proto.Field(
proto.STRING,
number=21,
optional=True,
)
media_file = proto.Field(
proto.STRING,
number=12,
oneof='image',
)
data = proto.Field(
proto.BYTES,
number=13,
oneof='image',
)
ad_id_to_copy_image_from = proto.Field(
proto.INT64,
number=14,
oneof='image',
)
class VideoBumperInStreamAdInfo(proto.Message):
r"""Representation of video bumper in-stream ad format (very
short in-stream non-skippable video ad).
Attributes:
companion_banner (str):
The MediaFile resource name of the companion
banner used with the ad.
"""
companion_banner = proto.Field(
proto.STRING,
number=2,
optional=True,
)
class VideoNonSkippableInStreamAdInfo(proto.Message):
r"""Representation of video non-skippable in-stream ad format (15
second in-stream non-skippable video ad).
Attributes:
companion_banner (str):
The MediaFile resource name of the companion
banner used with the ad.
"""
companion_banner = proto.Field(
proto.STRING,
number=2,
optional=True,
)
class VideoTrueViewInStreamAdInfo(proto.Message):
r"""Representation of video TrueView in-stream ad format (ad
shown during video playback, often at beginning, which displays
a skip button a few seconds into the video).
Attributes:
action_button_label (str):
Label on the CTA (call-to-action) button
taking the user to the video ad's final URL.
Required for TrueView for action campaigns,
optional otherwise.
action_headline (str):
Additional text displayed with the CTA (call-
o-action) button to give context and encourage
clicking on the button.
companion_banner (str):
The MediaFile resource name of the companion
banner used with the ad.
"""
action_button_label = proto.Field(
proto.STRING,
number=4,
optional=True,
)
action_headline = proto.Field(
proto.STRING,
number=5,
optional=True,
)
companion_banner = proto.Field(
proto.STRING,
number=6,
optional=True,
)
class VideoOutstreamAdInfo(proto.Message):
r"""Representation of video out-stream ad format (ad shown
alongside a feed with automatic playback, without sound).
Attributes:
headline (str):
The headline of the ad.
description (str):
The description line.
"""
headline = proto.Field(
proto.STRING,
number=3,
optional=True,
)
description = proto.Field(
proto.STRING,
number=4,
optional=True,
)
class VideoTrueViewDiscoveryAdInfo(proto.Message):
r"""Representation of video TrueView discovery ad format.
Attributes:
headline (str):
The headline of the ad.
description1 (str):
First text line for a TrueView video
discovery ad.
description2 (str):
Second text line for a TrueView video
discovery ad.
"""
headline = proto.Field(
proto.STRING,
number=4,
optional=True,
)
description1 = proto.Field(
proto.STRING,
number=5,
optional=True,
)
description2 = proto.Field(
proto.STRING,
number=6,
optional=True,
)
class VideoAdInfo(proto.Message):
r"""A video ad.
Attributes:
media_file (str):
The MediaFile resource to use for the video.
in_stream (google.ads.googleads.v8.common.types.VideoTrueViewInStreamAdInfo):
Video TrueView in-stream ad format.
bumper (google.ads.googleads.v8.common.types.VideoBumperInStreamAdInfo):
Video bumper in-stream ad format.
out_stream (google.ads.googleads.v8.common.types.VideoOutstreamAdInfo):
Video out-stream ad format.
non_skippable (google.ads.googleads.v8.common.types.VideoNonSkippableInStreamAdInfo):
Video non-skippable in-stream ad format.
discovery (google.ads.googleads.v8.common.types.VideoTrueViewDiscoveryAdInfo):
Video TrueView discovery ad format.
"""
media_file = proto.Field(
proto.STRING,
number=7,
optional=True,
)
in_stream = proto.Field(
proto.MESSAGE,
number=2,
oneof='format',
message='VideoTrueViewInStreamAdInfo',
)
bumper = proto.Field(
proto.MESSAGE,
number=3,
oneof='format',
message='VideoBumperInStreamAdInfo',
)
out_stream = proto.Field(
proto.MESSAGE,
number=4,
oneof='format',
message='VideoOutstreamAdInfo',
)
non_skippable = proto.Field(
proto.MESSAGE,
number=5,
oneof='format',
message='VideoNonSkippableInStreamAdInfo',
)
discovery = proto.Field(
proto.MESSAGE,
number=6,
oneof='format',
message='VideoTrueViewDiscoveryAdInfo',
)
class VideoResponsiveAdInfo(proto.Message):
r"""A video responsive ad.
Attributes:
headlines (Sequence[google.ads.googleads.v8.common.types.AdTextAsset]):
List of text assets used for the short
headline, e.g. the "Call To Action" banner.
Currently, only a single value for the short
headline is supported.
long_headlines (Sequence[google.ads.googleads.v8.common.types.AdTextAsset]):
List of text assets used for the long
headline. Currently, only a single value for the
long headline is supported.
descriptions (Sequence[google.ads.googleads.v8.common.types.AdTextAsset]):
List of text assets used for the description.
Currently, only a single value for the
description is supported.
call_to_actions (Sequence[google.ads.googleads.v8.common.types.AdTextAsset]):
List of text assets used for the button, e.g.
the "Call To Action" button. Currently, only a
single value for the button is supported.
videos (Sequence[google.ads.googleads.v8.common.types.AdVideoAsset]):
List of YouTube video assets used for the ad.
Currently, only a single value for the YouTube
video asset is supported.
companion_banners (Sequence[google.ads.googleads.v8.common.types.AdImageAsset]):
List of image assets used for the companion
banner. Currently, only a single value for the
companion banner asset is supported.
"""
headlines = proto.RepeatedField(
proto.MESSAGE,
number=1,
message=ad_asset.AdTextAsset,
)
long_headlines = proto.RepeatedField(
proto.MESSAGE,
number=2,
message=ad_asset.AdTextAsset,
)
descriptions = proto.RepeatedField(
proto.MESSAGE,
number=3,
message=ad_asset.AdTextAsset,
)
call_to_actions = proto.RepeatedField(
proto.MESSAGE,
number=4,
message=ad_asset.AdTextAsset,
)
videos = proto.RepeatedField(
proto.MESSAGE,
number=5,
message=ad_asset.AdVideoAsset,
)
companion_banners = proto.RepeatedField(
proto.MESSAGE,
number=6,
message=ad_asset.AdImageAsset,
)
class ResponsiveSearchAdInfo(proto.Message):
r"""A responsive search ad.
Responsive search ads let you create an ad that adapts to show
more text, and more relevant messages, to your customers. Enter
multiple headlines and descriptions when creating a responsive
search ad, and over time, Google Ads will automatically test
different combinations and learn which combinations perform
best. By adapting your ad's content to more closely match
potential customers' search terms, responsive search ads may
improve your campaign's performance.
More information at https://support.google.com/google-
ads/answer/7684791
Attributes:
headlines (Sequence[google.ads.googleads.v8.common.types.AdTextAsset]):
List of text assets for headlines. When the
ad serves the headlines will be selected from
this list.
descriptions (Sequence[google.ads.googleads.v8.common.types.AdTextAsset]):
List of text assets for descriptions. When
the ad serves the descriptions will be selected
from this list.
path1 (str):
First part of text that may appear appended
to the url displayed in the ad.
path2 (str):
Second part of text that may appear appended
to the url displayed in the ad. This field can
only be set when path1 is also set.
"""
headlines = proto.RepeatedField(
proto.MESSAGE,
number=1,
message=ad_asset.AdTextAsset,
)
descriptions = proto.RepeatedField(
proto.MESSAGE,
number=2,
message=ad_asset.AdTextAsset,
)
path1 = proto.Field(
proto.STRING,
number=5,
optional=True,
)
path2 = proto.Field(
proto.STRING,
number=6,
optional=True,
)
class LegacyResponsiveDisplayAdInfo(proto.Message):
r"""A legacy responsive display ad. Ads of this type are labeled
'Responsive ads' in the Google Ads UI.
Attributes:
short_headline (str):
The short version of the ad's headline.
long_headline (str):
The long version of the ad's headline.
description (str):
The description of the ad.
business_name (str):
The business name in the ad.
allow_flexible_color (bool):
Advertiser's consent to allow flexible color. When true, the
ad may be served with different color if necessary. When
false, the ad will be served with the specified colors or a
neutral color. The default value is true. Must be true if
main_color and accent_color are not set.
accent_color (str):
The accent color of the ad in hexadecimal, e.g. #ffffff for
white. If one of main_color and accent_color is set, the
other is required as well.
main_color (str):
The main color of the ad in hexadecimal, e.g. #ffffff for
white. If one of main_color and accent_color is set, the
other is required as well.
call_to_action_text (str):
The call-to-action text for the ad.
logo_image (str):
The MediaFile resource name of the logo image
used in the ad.
square_logo_image (str):
The MediaFile resource name of the square
logo image used in the ad.
marketing_image (str):
The MediaFile resource name of the marketing
image used in the ad.
square_marketing_image (str):
The MediaFile resource name of the square
marketing image used in the ad.
format_setting (google.ads.googleads.v8.enums.types.DisplayAdFormatSettingEnum.DisplayAdFormatSetting):
Specifies which format the ad will be served in. Default is
ALL_FORMATS.
price_prefix (str):
Prefix before price. E.g. 'as low as'.
promo_text (str):
Promotion text used for dynamic formats of
responsive ads. For example 'Free two-day
shipping'.
"""
short_headline = proto.Field(
proto.STRING,
number=16,
optional=True,
)
long_headline = proto.Field(
proto.STRING,
number=17,
optional=True,
)
description = proto.Field(
proto.STRING,
number=18,
optional=True,
)
business_name = proto.Field(
proto.STRING,
number=19,
optional=True,
)
allow_flexible_color = proto.Field(
proto.BOOL,
number=20,
optional=True,
)
accent_color = proto.Field(
proto.STRING,
number=21,
optional=True,
)
main_color = proto.Field(
proto.STRING,
number=22,
optional=True,
)
call_to_action_text = proto.Field(
proto.STRING,
number=23,
optional=True,
)
logo_image = proto.Field(
proto.STRING,
number=24,
optional=True,
)
square_logo_image = proto.Field(
proto.STRING,
number=25,
optional=True,
)
marketing_image = proto.Field(
proto.STRING,
number=26,
optional=True,
)
square_marketing_image = proto.Field(
proto.STRING,
number=27,
optional=True,
)
format_setting = proto.Field(
proto.ENUM,
number=13,
enum=display_ad_format_setting.DisplayAdFormatSettingEnum.DisplayAdFormatSetting,
)
price_prefix = proto.Field(
proto.STRING,
number=28,
optional=True,
)
promo_text = proto.Field(
proto.STRING,
number=29,
optional=True,
)
class AppAdInfo(proto.Message):
r"""An app ad.
Attributes:
mandatory_ad_text (google.ads.googleads.v8.common.types.AdTextAsset):
Mandatory ad text.
headlines (Sequence[google.ads.googleads.v8.common.types.AdTextAsset]):
List of text assets for headlines. When the
ad serves the headlines will be selected from
this list.
descriptions (Sequence[google.ads.googleads.v8.common.types.AdTextAsset]):
List of text assets for descriptions. When
the ad serves the descriptions will be selected
from this list.
images (Sequence[google.ads.googleads.v8.common.types.AdImageAsset]):
List of image assets that may be displayed
with the ad.
youtube_videos (Sequence[google.ads.googleads.v8.common.types.AdVideoAsset]):
List of YouTube video assets that may be
displayed with the ad.
html5_media_bundles (Sequence[google.ads.googleads.v8.common.types.AdMediaBundleAsset]):
List of media bundle assets that may be used
with the ad.
"""
mandatory_ad_text = proto.Field(
proto.MESSAGE,
number=1,
message=ad_asset.AdTextAsset,
)
headlines = proto.RepeatedField(
proto.MESSAGE,
number=2,
message=ad_asset.AdTextAsset,
)
descriptions = proto.RepeatedField(
proto.MESSAGE,
number=3,
message=ad_asset.AdTextAsset,
)
images = proto.RepeatedField(
proto.MESSAGE,
number=4,
message=ad_asset.AdImageAsset,
)
youtube_videos = proto.RepeatedField(
proto.MESSAGE,
number=5,
message=ad_asset.AdVideoAsset,
)
html5_media_bundles = proto.RepeatedField(
proto.MESSAGE,
number=6,
message=ad_asset.AdMediaBundleAsset,
)
class AppEngagementAdInfo(proto.Message):
r"""App engagement ads allow you to write text encouraging a
specific action in the app, like checking in, making a purchase,
or booking a flight. They allow you to send users to a specific
part of your app where they can find what they're looking for
easier and faster.
Attributes:
headlines (Sequence[google.ads.googleads.v8.common.types.AdTextAsset]):
List of text assets for headlines. When the
ad serves the headlines will be selected from
this list.
descriptions (Sequence[google.ads.googleads.v8.common.types.AdTextAsset]):
List of text assets for descriptions. When
the ad serves the descriptions will be selected
from this list.
images (Sequence[google.ads.googleads.v8.common.types.AdImageAsset]):
List of image assets that may be displayed
with the ad.
videos (Sequence[google.ads.googleads.v8.common.types.AdVideoAsset]):
List of video assets that may be displayed
with the ad.
"""
headlines = proto.RepeatedField(
proto.MESSAGE,
number=1,
message=ad_asset.AdTextAsset,
)
descriptions = proto.RepeatedField(
proto.MESSAGE,
number=2,
message=ad_asset.AdTextAsset,
)
images = proto.RepeatedField(
proto.MESSAGE,
number=3,
message=ad_asset.AdImageAsset,
)
videos = proto.RepeatedField(
proto.MESSAGE,
number=4,
message=ad_asset.AdVideoAsset,
)
class LegacyAppInstallAdInfo(proto.Message):
r"""A legacy app install ad that only can be used by a few select
customers.
Attributes:
app_id (str):
The id of the mobile app.
app_store (google.ads.googleads.v8.enums.types.LegacyAppInstallAdAppStoreEnum.LegacyAppInstallAdAppStore):
The app store the mobile app is available in.
headline (str):
The headline of the ad.
description1 (str):
The first description line of the ad.
description2 (str):
The second description line of the ad.
"""
app_id = proto.Field(
proto.STRING,
number=6,
optional=True,
)
app_store = proto.Field(
proto.ENUM,
number=2,
enum=legacy_app_install_ad_app_store.LegacyAppInstallAdAppStoreEnum.LegacyAppInstallAdAppStore,
)
headline = proto.Field(
proto.STRING,
number=7,
optional=True,
)
description1 = proto.Field(
proto.STRING,
number=8,
optional=True,
)
description2 = proto.Field(
proto.STRING,
number=9,
optional=True,
)
class ResponsiveDisplayAdInfo(proto.Message):
r"""A responsive display ad.
Attributes:
marketing_images (Sequence[google.ads.googleads.v8.common.types.AdImageAsset]):
Marketing images to be used in the ad. Valid image types are
GIF, JPEG, and PNG. The minimum size is 600x314 and the
aspect ratio must be 1.91:1 (+-1%). At least one
marketing_image is required. Combined with
square_marketing_images the maximum is 15.
square_marketing_images (Sequence[google.ads.googleads.v8.common.types.AdImageAsset]):
Square marketing images to be used in the ad. Valid image
types are GIF, JPEG, and PNG. The minimum size is 300x300
and the aspect ratio must be 1:1 (+-1%). At least one square
marketing_image is required. Combined with marketing_images
the maximum is 15.
logo_images (Sequence[google.ads.googleads.v8.common.types.AdImageAsset]):
Logo images to be used in the ad. Valid image types are GIF,
JPEG, and PNG. The minimum size is 512x128 and the aspect
ratio must be 4:1 (+-1%). Combined with square_logo_images
the maximum is 5.
square_logo_images (Sequence[google.ads.googleads.v8.common.types.AdImageAsset]):
Square logo images to be used in the ad. Valid image types
are GIF, JPEG, and PNG. The minimum size is 128x128 and the
aspect ratio must be 1:1 (+-1%). Combined with
square_logo_images the maximum is 5.
headlines (Sequence[google.ads.googleads.v8.common.types.AdTextAsset]):
Short format headlines for the ad. The
maximum length is 30 characters. At least 1 and
max 5 headlines can be specified.
long_headline (google.ads.googleads.v8.common.types.AdTextAsset):
A required long format headline. The maximum
length is 90 characters.
descriptions (Sequence[google.ads.googleads.v8.common.types.AdTextAsset]):
Descriptive texts for the ad. The maximum
length is 90 characters. At least 1 and max 5
headlines can be specified.
youtube_videos (Sequence[google.ads.googleads.v8.common.types.AdVideoAsset]):
Optional YouTube videos for the ad. A maximum
of 5 videos can be specified.
business_name (str):
The advertiser/brand name. Maximum display
width is 25.
main_color (str):
The main color of the ad in hexadecimal, e.g. #ffffff for
white. If one of main_color and accent_color is set, the
other is required as well.
accent_color (str):
The accent color of the ad in hexadecimal, e.g. #ffffff for
white. If one of main_color and accent_color is set, the
other is required as well.
allow_flexible_color (bool):
Advertiser's consent to allow flexible color. When true, the
ad may be served with different color if necessary. When
false, the ad will be served with the specified colors or a
neutral color. The default value is true. Must be true if
main_color and accent_color are not set.
call_to_action_text (str):
The call-to-action text for the ad. Maximum
display width is 30.
price_prefix (str):
Prefix before price. E.g. 'as low as'.
promo_text (str):
Promotion text used for dynamic formats of
responsive ads. For example 'Free two-day
shipping'.
format_setting (google.ads.googleads.v8.enums.types.DisplayAdFormatSettingEnum.DisplayAdFormatSetting):
Specifies which format the ad will be served in. Default is
ALL_FORMATS.
control_spec (google.ads.googleads.v8.common.types.ResponsiveDisplayAdControlSpec):
Specification for various creative controls.
"""
marketing_images = proto.RepeatedField(
proto.MESSAGE,
number=1,
message=ad_asset.AdImageAsset,
)
square_marketing_images = proto.RepeatedField(
proto.MESSAGE,
number=2,
message=ad_asset.AdImageAsset,
)
logo_images = proto.RepeatedField(
proto.MESSAGE,
number=3,
message=ad_asset.AdImageAsset,
)
square_logo_images = proto.RepeatedField(
proto.MESSAGE,
number=4,
message=ad_asset.AdImageAsset,
)
headlines = proto.RepeatedField(
proto.MESSAGE,
number=5,
message=ad_asset.AdTextAsset,
)
long_headline = proto.Field(
proto.MESSAGE,
number=6,
message=ad_asset.AdTextAsset,
)
descriptions = proto.RepeatedField(
proto.MESSAGE,
number=7,
message=ad_asset.AdTextAsset,
)
youtube_videos = proto.RepeatedField(
proto.MESSAGE,
number=8,
message=ad_asset.AdVideoAsset,
)
business_name = proto.Field(
proto.STRING,
number=17,
optional=True,
)
main_color = proto.Field(
proto.STRING,
number=18,
optional=True,
)
accent_color = proto.Field(
proto.STRING,
number=19,
optional=True,
)
allow_flexible_color = proto.Field(
proto.BOOL,
number=20,
optional=True,
)
call_to_action_text = proto.Field(
proto.STRING,
number=21,
optional=True,
)
price_prefix = proto.Field(
proto.STRING,
number=22,
optional=True,
)
promo_text = proto.Field(
proto.STRING,
number=23,
optional=True,
)
format_setting = proto.Field(
proto.ENUM,
number=16,
enum=display_ad_format_setting.DisplayAdFormatSettingEnum.DisplayAdFormatSetting,
)
control_spec = proto.Field(
proto.MESSAGE,
number=24,
message='ResponsiveDisplayAdControlSpec',
)
class LocalAdInfo(proto.Message):
r"""A local ad.
Attributes:
headlines (Sequence[google.ads.googleads.v8.common.types.AdTextAsset]):
List of text assets for headlines. When the
ad serves the headlines will be selected from
this list. At least 1 and at most 5 headlines
must be specified.
descriptions (Sequence[google.ads.googleads.v8.common.types.AdTextAsset]):
List of text assets for descriptions. When
the ad serves the descriptions will be selected
from this list. At least 1 and at most 5
descriptions must be specified.
call_to_actions (Sequence[google.ads.googleads.v8.common.types.AdTextAsset]):
List of text assets for call-to-actions. When
the ad serves the call-to-actions will be
selected from this list. Call-to-actions are
optional and at most 5 can be specified.
marketing_images (Sequence[google.ads.googleads.v8.common.types.AdImageAsset]):
List of marketing image assets that may be
displayed with the ad. The images must be
314x600 pixels or 320x320 pixels. At least 1 and
at most 20 image assets must be specified.
logo_images (Sequence[google.ads.googleads.v8.common.types.AdImageAsset]):
List of logo image assets that may be
displayed with the ad. The images must be
128x128 pixels and not larger than 120KB. At
least 1 and at most 5 image assets must be
specified.
videos (Sequence[google.ads.googleads.v8.common.types.AdVideoAsset]):
List of YouTube video assets that may be
displayed with the ad. Videos are optional and
at most 20 can be specified.
path1 (str):
First part of optional text that may appear
appended to the url displayed in the ad.
path2 (str):
Second part of optional text that may appear
appended to the url displayed in the ad. This
field can only be set when path1 is also set.
"""
headlines = proto.RepeatedField(
proto.MESSAGE,
number=1,
message=ad_asset.AdTextAsset,
)
descriptions = proto.RepeatedField(
proto.MESSAGE,
number=2,
message=ad_asset.AdTextAsset,
)
call_to_actions = proto.RepeatedField(
proto.MESSAGE,
number=3,
message=ad_asset.AdTextAsset,
)
marketing_images = proto.RepeatedField(
proto.MESSAGE,
number=4,
message=ad_asset.AdImageAsset,
)
logo_images = proto.RepeatedField(
proto.MESSAGE,
number=5,
message=ad_asset.AdImageAsset,
)
videos = proto.RepeatedField(
proto.MESSAGE,
number=6,
message=ad_asset.AdVideoAsset,
)
path1 = proto.Field(
proto.STRING,
number=9,
optional=True,
)
path2 = proto.Field(
proto.STRING,
number=10,
optional=True,
)
class DisplayUploadAdInfo(proto.Message):
r"""A generic type of display ad. The exact ad format is controlled by
the display_upload_product_type field, which determines what kinds
of data need to be included with the ad.
Attributes:
display_upload_product_type (google.ads.googleads.v8.enums.types.DisplayUploadProductTypeEnum.DisplayUploadProductType):
The product type of this ad. See comments on
the enum for details.
media_bundle (google.ads.googleads.v8.common.types.AdMediaBundleAsset):
A media bundle asset to be used in the ad. For information
about the media bundle for HTML5_UPLOAD_AD see
https://support.google.com/google-ads/answer/1722096 Media
bundles that are part of dynamic product types use a special
format that needs to be created through the Google Web
Designer. See
https://support.google.com/webdesigner/answer/7543898 for
more information.
"""
display_upload_product_type = proto.Field(
proto.ENUM,
number=1,
enum=gage_display_upload_product_type.DisplayUploadProductTypeEnum.DisplayUploadProductType,
)
media_bundle = proto.Field(
proto.MESSAGE,
number=2,
oneof='media_asset',
message=ad_asset.AdMediaBundleAsset,
)
class ResponsiveDisplayAdControlSpec(proto.Message):
r"""Specification for various creative controls for a responsive
display ad.
Attributes:
enable_asset_enhancements (bool):
Whether the advertiser has opted into the
asset enhancements feature.
enable_autogen_video (bool):
Whether the advertiser has opted into auto-
en video feature.
"""
enable_asset_enhancements = proto.Field(
proto.BOOL,
number=1,
)
enable_autogen_video = proto.Field(
proto.BOOL,
number=2,
)
class SmartCampaignAdInfo(proto.Message):
r"""A Smart campaign ad.
Attributes:
headlines (Sequence[google.ads.googleads.v8.common.types.AdTextAsset]):
List of text assets for headlines. When the
ad serves the headlines will be selected from
this list. 3 headlines must be specified.
descriptions (Sequence[google.ads.googleads.v8.common.types.AdTextAsset]):
List of text assets for descriptions. When
the ad serves the descriptions will be selected
from this list. 2 descriptions must be
specified.
"""
headlines = proto.RepeatedField(
proto.MESSAGE,
number=1,
message=ad_asset.AdTextAsset,
)
descriptions = proto.RepeatedField(
proto.MESSAGE,
number=2,
message=ad_asset.AdTextAsset,
)
class CallAdInfo(proto.Message):
r"""A call ad.
Attributes:
country_code (str):
The country code in the ad.
phone_number (str):
The phone number in the ad.
business_name (str):
The business name in the ad.
headline1 (str):
First headline in the ad.
headline2 (str):
Second headline in the ad.
description1 (str):
The first line of the ad's description.
description2 (str):
The second line of the ad's description.
call_tracked (bool):
Whether to enable call tracking for the
creative. Enabling call tracking also enables
call conversions.
disable_call_conversion (bool):
Whether to disable call conversion for the creative. If set
to ``true``, disables call conversions even when
``call_tracked`` is ``true``. If ``call_tracked`` is
``false``, this field is ignored.
phone_number_verification_url (str):
The URL to be used for phone number
verification.
conversion_action (str):
The conversion action to attribute a call conversion to. If
not set a default conversion action is used. This field only
has effect if call_tracked is set to true. Otherwise this
field is ignored.
conversion_reporting_state (google.ads.googleads.v8.enums.types.CallConversionReportingStateEnum.CallConversionReportingState):
The call conversion behavior of this call ad.
It can use its own call conversion setting,
inherit the account level setting, or be
disabled.
path1 (str):
First part of text that may appear appended
to the url displayed to in the ad. Optional.
path2 (str):
Second part of text that may appear appended
to the url displayed to in the ad. This field
can only be set when path1 is set. Optional.
"""
country_code = proto.Field(
proto.STRING,
number=1,
)
phone_number = proto.Field(
proto.STRING,
number=2,
)
business_name = proto.Field(
proto.STRING,
number=3,
)
headline1 = proto.Field(
proto.STRING,
number=11,
)
headline2 = proto.Field(
proto.STRING,
number=12,
)
description1 = proto.Field(
proto.STRING,
number=4,
)
description2 = proto.Field(
proto.STRING,
number=5,
)
call_tracked = proto.Field(
proto.BOOL,
number=6,
)
disable_call_conversion = proto.Field(
proto.BOOL,
number=7,
)
phone_number_verification_url = proto.Field(
proto.STRING,
number=8,
)
conversion_action = proto.Field(
proto.STRING,
number=9,
)
conversion_reporting_state = proto.Field(
proto.ENUM,
number=10,
enum=call_conversion_reporting_state.CallConversionReportingStateEnum.CallConversionReportingState,
)
path1 = proto.Field(
proto.STRING,
number=13,
)
path2 = proto.Field(
proto.STRING,
number=14,
)
__all__ = tuple(sorted(__protobuf__.manifest))
| apache-2.0 | 1,371,305,617,412,775,000 | 30.178258 | 135 | 0.60667 | false |
OndinaHQ/Tracker | plugins/s3.py | 1 | 3045 | # Copyright (C) 2012 Stefano Palazzo <stefano.palazzo@gmail.com>
# Copyright (C) 2012 Ondina, LLC. <http://ondina.co>
# 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 time
import hmac
import hashlib
import http.client
import urllib.parse
import base64
import collections
class S3Error (Exception):
def __init__(self, status, response):
self.status, self.response = status, response
def __str__(self):
return "{}: {}".format(self.status, self.response)
def __str__(self):
return "S3Error({}, {})".format(repr(self.status), repr(self.response))
class S3 (object):
'''
Usage:
>>> s3 = S3(YOUR_ACCESS_KEY_ID, YOUR_SECRET_ACCESS_KEY)
>>> s3.upload("some-bucket", open("image.png", "rb").read(),
"image/png", "image3838838.png")
https://s3.amazonaws.com/some-bucket/image3838838.png
'''
def __init__(self, access_key, secret_key):
self.__access_key, self.__secret_key = access_key, secret_key
def __request(self, method, bucket, host, action, body, content_type, fn):
date = time.strftime("%c GMT", time.gmtime())
headers = collections.OrderedDict((
("x-amz-acl", "public-read"),
("Content-Type", content_type),
("Content-Length", len(body)),
("Host", bucket + "." + host),
("Date", date),
))
string_to_sign = (method + "\n" +
"\n" +
content_type + "\n" +
date + "\n" +
"x-amz-acl:public-read\n" +
"/" + bucket + "/" + fn)
signature = base64.b64encode(hmac.new(self.__secret_key.encode(),
string_to_sign.encode(), hashlib.sha1).digest()).decode()
authorization = "AWS " + self.__access_key + ":" + signature
headers.update({"Authorization": authorization})
connection = http.client.HTTPSConnection(bucket + "." + host)
action = action + "?" + urllib.parse.urlencode({})
connection.request(method, action, body, headers)
response = connection.getresponse()
if response.status != 200:
raise S3Error(response.status, response.read())
return "https://s3.amazonaws.com/{}/{}".format(bucket, fn)
def upload(self, bucket, data, content_type, filename):
return self.__request("PUT", bucket, "s3.amazonaws.com", "/" +
filename, data, content_type, filename)
| gpl-3.0 | 6,556,845,181,018,682,000 | 36.592593 | 79 | 0.611494 | false |
monikagrabowska/osf.io | osf/models/base.py | 1 | 26122 |
import logging
import random
from datetime import datetime
import bson
import modularodm.exceptions
import pytz
from django.contrib.contenttypes.fields import (GenericForeignKey,
GenericRelation)
from django.contrib.contenttypes.models import ContentType
from django.contrib.postgres.fields import ArrayField
from django.core.exceptions import MultipleObjectsReturned
from django.core.exceptions import ValidationError as DjangoValidationError
from django.db import models
from django.db.models import F
from django.db.models import ForeignKey
from django.db.models import Q
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.utils import timezone
from osf.utils.caching import cached_property
from osf.exceptions import ValidationError
from osf.modm_compat import to_django_query
from osf.utils.datetime_aware_jsonfield import (DateTimeAwareJSONField,
coerce_nonnaive_datetimes)
from osf.utils.fields import LowercaseCharField, NonNaiveDateTimeField
ALPHABET = '23456789abcdefghjkmnpqrstuvwxyz'
logger = logging.getLogger(__name__)
def generate_guid(length=5):
while True:
guid_id = ''.join(random.sample(ALPHABET, length))
try:
# is the guid in the blacklist
BlackListGuid.objects.get(guid=guid_id)
except BlackListGuid.DoesNotExist:
# it's not, check and see if it's already in the database
try:
Guid.objects.get(_id=guid_id)
except Guid.DoesNotExist:
# valid and unique guid
return guid_id
def generate_object_id():
return str(bson.ObjectId())
class MODMCompatibilityQuerySet(models.QuerySet):
def __getitem__(self, k):
item = super(MODMCompatibilityQuerySet, self).__getitem__(k)
if hasattr(item, 'wrapped'):
return item.wrapped()
else:
return item
def __iter__(self):
items = super(MODMCompatibilityQuerySet, self).__iter__()
for item in items:
if hasattr(item, 'wrapped'):
yield item.wrapped()
else:
yield item
def sort(self, *fields):
# Fields are passed in as e.g. [('title', 1), ('date_created', -1)]
if isinstance(fields[0], list):
fields = fields[0]
def sort_key(item):
if isinstance(item, basestring):
return item
elif isinstance(item, tuple):
field_name, direction = item
prefix = '-' if direction == -1 else ''
return ''.join([prefix, field_name])
sort_keys = [sort_key(each) for each in fields]
return self.order_by(*sort_keys)
def limit(self, n):
return self[:n]
class BaseModel(models.Model):
"""Base model that acts makes subclasses mostly compatible with the
modular-odm ``StoredObject`` interface.
"""
migration_page_size = 50000
objects = MODMCompatibilityQuerySet.as_manager()
class Meta:
abstract = True
@classmethod
def load(cls, data):
try:
if issubclass(cls, GuidMixin):
return cls.objects.get(guids___id=data)
elif issubclass(cls, ObjectIDMixin):
return cls.objects.get(_id=data)
elif isinstance(data, basestring):
# Some models (CitationStyle) have an _id that is not a bson
# Looking up things by pk will never work with a basestring
return cls.objects.get(_id=data)
return cls.objects.get(pk=data)
except cls.DoesNotExist:
return None
@classmethod
def find_one(cls, query):
try:
return cls.objects.get(to_django_query(query, model_cls=cls))
except cls.DoesNotExist:
raise modularodm.exceptions.NoResultsFound()
except cls.MultipleObjectsReturned as e:
raise modularodm.exceptions.MultipleResultsFound(*e.args)
@classmethod
def find(cls, query=None):
if not query:
return cls.objects.all()
else:
return cls.objects.filter(to_django_query(query, model_cls=cls))
@classmethod
def remove(cls, query=None):
return cls.find(query).delete()
@classmethod
def remove_one(cls, obj):
if obj.pk:
return obj.delete()
@classmethod
def migrate_from_modm(cls, modm_obj):
"""
Given a modm object, make a django object with the same local fields.
This is a base method that may work for simple objects.
It should be customized in the child class if it doesn't work.
:param modm_obj:
:return:
"""
django_obj = cls()
local_django_fields = set([x.name for x in django_obj._meta.get_fields() if not x.is_relation])
intersecting_fields = set(modm_obj.to_storage().keys()).intersection(
set(local_django_fields))
for field in intersecting_fields:
modm_value = getattr(modm_obj, field)
if modm_value is None:
continue
if isinstance(modm_value, datetime):
modm_value = pytz.utc.localize(modm_value)
# TODO Remove this after migration
if isinstance(django_obj._meta.get_field(field), DateTimeAwareJSONField):
modm_value = coerce_nonnaive_datetimes(modm_value)
setattr(django_obj, field, modm_value)
return django_obj
@property
def _primary_name(self):
return '_id'
def reload(self):
return self.refresh_from_db()
def _natural_key(self):
return self.pk
def clone(self):
"""Create a new, unsaved copy of this object."""
copy = self.__class__.objects.get(pk=self.pk)
copy.id = None
# empty all the fks
fk_field_names = [f.name for f in self._meta.model._meta.get_fields() if isinstance(f, (ForeignKey, GenericForeignKey))]
for field_name in fk_field_names:
setattr(copy, field_name, None)
try:
copy._id = bson.ObjectId()
except AttributeError:
pass
return copy
def save(self, *args, **kwargs):
# Make Django validate on save (like modm)
if not kwargs.get('force_insert') and not kwargs.get('force_update'):
try:
self.full_clean()
except DjangoValidationError as err:
raise ValidationError(*err.args)
return super(BaseModel, self).save(*args, **kwargs)
# TODO: Rename to Identifier?
class Guid(BaseModel):
"""Stores either a short guid or long object_id for any model that inherits from BaseIDMixin.
Each ID field (e.g. 'guid', 'object_id') MUST have an accompanying method, named with
'initialize_<ID type>' (e.g. 'initialize_guid') that generates and sets the field.
"""
primary_identifier_name = '_id'
# TODO DELETE ME POST MIGRATION
modm_query = None
migration_page_size = 500000
# /TODO DELETE ME POST MIGRATION
id = models.AutoField(primary_key=True)
_id = LowercaseCharField(max_length=255, null=False, blank=False, default=generate_guid, db_index=True,
unique=True)
referent = GenericForeignKey()
content_type = models.ForeignKey(ContentType, null=True, blank=True)
object_id = models.PositiveIntegerField(null=True, blank=True)
created = NonNaiveDateTimeField(db_index=True, default=timezone.now) # auto_now_add=True)
# Override load in order to load by GUID
@classmethod
def load(cls, data):
try:
return cls.objects.get(_id=data)
except cls.DoesNotExist:
return None
def reload(self):
del self._referent_cache
return super(Guid, self).reload()
@classmethod
def migrate_from_modm(cls, modm_obj, object_id=None, content_type=None):
"""
Given a modm Guid make a django Guid
:param object_id:
:param content_type:
:param modm_obj:
:return:
"""
django_obj = cls()
if modm_obj._id != modm_obj.referent._id:
# if the object has a BSON id, get the created date from that
django_obj.created = bson.ObjectId(modm_obj.referent._id).generation_time
else:
# just make it now
django_obj.created = timezone.now()
django_obj._id = modm_obj._id
if object_id and content_type:
# if the referent was passed set the GFK to point to it
django_obj.content_type = content_type
django_obj.object_id = object_id
return django_obj
class Meta:
ordering = ['-created']
get_latest_by = 'created'
index_together = (
('content_type', 'object_id', 'created'),
)
class BlackListGuid(BaseModel):
# TODO DELETE ME POST MIGRATION
modm_model_path = 'framework.guid.model.BlacklistGuid'
primary_identifier_name = 'guid'
modm_query = None
migration_page_size = 500000
# /TODO DELETE ME POST MIGRATION
id = models.AutoField(primary_key=True)
guid = LowercaseCharField(max_length=255, unique=True, db_index=True)
@property
def _id(self):
return self.guid
@classmethod
def migrate_from_modm(cls, modm_obj):
"""
Given a modm BlacklistGuid make a django BlackListGuid
:param modm_obj:
:return:
"""
django_obj = cls()
django_obj.guid = modm_obj._id
return django_obj
def generate_guid_instance():
return Guid.objects.create().id
class PKIDStr(str):
def __new__(self, _id, pk):
return str.__new__(self, _id)
def __init__(self, _id, pk):
self.__pk = pk
def __int__(self):
return self.__pk
class BaseIDMixin(models.Model):
@classmethod
def migrate_from_modm(cls, modm_obj):
"""
Given a modm object, make a django object with the same local fields.
This is a base method that may work for simple objects.
It should be customized in the child class if it doesn't work.
:param modm_obj:
:return:
"""
django_obj = cls()
local_django_fields = set([x.name for x in django_obj._meta.get_fields() if not x.is_relation])
intersecting_fields = set(modm_obj.to_storage().keys()).intersection(
set(local_django_fields))
for field in intersecting_fields:
modm_value = getattr(modm_obj, field)
if modm_value is None:
continue
if isinstance(modm_value, datetime):
modm_value = pytz.utc.localize(modm_value)
# TODO Remove this after migration
if isinstance(django_obj._meta.get_field(field), DateTimeAwareJSONField):
modm_value = coerce_nonnaive_datetimes(modm_value)
setattr(django_obj, field, modm_value)
return django_obj
class Meta:
abstract = True
class ObjectIDMixin(BaseIDMixin):
primary_identifier_name = '_id'
_id = models.CharField(max_length=24, default=generate_object_id, unique=True, db_index=True)
@classmethod
def load(cls, q):
try:
return cls.objects.get(_id=q)
except cls.DoesNotExist:
# modm doesn't throw exceptions when loading things that don't exist
return None
@classmethod
def migrate_from_modm(cls, modm_obj):
django_obj = super(ObjectIDMixin, cls).migrate_from_modm(modm_obj)
django_obj._id = str(modm_obj._id)
return django_obj
class Meta:
abstract = True
def _natural_key(self):
return self._id
class InvalidGuid(Exception):
pass
class OptionalGuidMixin(BaseIDMixin):
"""
This makes it so that things can **optionally** have guids. Think files.
Things that inherit from this must also inherit from ObjectIDMixin ... probably
"""
__guid_min_length__ = 5
guids = GenericRelation(Guid, related_name='referent', related_query_name='referents')
guid_string = ArrayField(models.CharField(max_length=255, null=True, blank=True), null=True, blank=True)
content_type_pk = models.PositiveIntegerField(null=True, blank=True)
def get_guid(self, create=False):
if create:
try:
guid, created = Guid.objects.get_or_create(
object_id=self.pk,
content_type_id=ContentType.objects.get_for_model(self).pk
)
except MultipleObjectsReturned:
# lol, hacks
pass
else:
return guid
return self.guids.order_by('-created').first()
@classmethod
def migrate_from_modm(cls, modm_obj):
instance = super(OptionalGuidMixin, cls).migrate_from_modm(modm_obj)
from website.models import Guid as MODMGuid
from modularodm import Q as MODMQ
if modm_obj.get_guid():
guids = MODMGuid.find(MODMQ('referent', 'eq', modm_obj._id))
setattr(instance, 'guid_string', [x.lower() for x in guids.get_keys()])
setattr(instance, 'content_type_pk', ContentType.objects.get_for_model(cls).pk)
return instance
class Meta:
abstract = True
class GuidMixinQuerySet(MODMCompatibilityQuerySet):
tables = ['osf_guid', 'django_content_type']
GUID_FIELDS = [
'guids__id',
'guids___id',
'guids__content_type_id',
'guids__object_id',
'guids__created'
]
def safe_table_alias(self, table_name, create=False):
"""
Returns a table alias for the given table_name and whether this is a
new alias or not.
If 'create' is true, a new alias is always created. Otherwise, the
most recently created alias for the table (if one exists) is reused.
"""
alias_list = self.query.table_map.get(table_name)
if not create and alias_list:
alias = alias_list[0]
if alias in self.query.alias_refcount:
self.query.alias_refcount[alias] += 1
else:
self.query.alias_refcount[alias] = 1
return alias, False
# Create a new alias for this table.
if alias_list:
alias = '%s%d' % (self.query.alias_prefix, len(self.query.alias_map) + 1)
alias_list.append(alias)
else:
# The first occurrence of a table uses the table name directly.
alias = table_name
self.query.table_map[alias] = [alias]
self.query.alias_refcount[alias] = 1
self.tables.append(alias)
return alias, True
def annotate_query_with_guids(self):
self._prefetch_related_lookups = ['guids']
for field in self.GUID_FIELDS:
self.query.add_annotation(
F(field), '_{}'.format(field), is_summary=False
)
for table in self.tables:
if table not in self.query.tables:
self.safe_table_alias(table)
def remove_guid_annotations(self):
for k, v in self.query.annotations.iteritems():
if k[1:] in self.GUID_FIELDS:
del self.query.annotations[k]
for table_name in ['osf_guid', 'django_content_type']:
if table_name in self.query.alias_map:
del self.query.alias_map[table_name]
if table_name in self.query.alias_refcount:
del self.query.alias_refcount[table_name]
if table_name in self.query.tables:
del self.query.tables[self.query.tables.index(table_name)]
def _clone(self, annotate=False, **kwargs):
query = self.query.clone()
if self._sticky_filter:
query.filter_is_sticky = True
if annotate:
self.annotate_query_with_guids()
clone = self.__class__(model=self.model, query=query, using=self._db, hints=self._hints)
# this method was copied from the default django queryset except for the below two lines
if annotate:
clone.annotate_query_with_guids()
clone._for_write = self._for_write
clone._prefetch_related_lookups = self._prefetch_related_lookups[:]
clone._known_related_objects = self._known_related_objects
clone._iterable_class = self._iterable_class
clone._fields = self._fields
clone.__dict__.update(kwargs)
return clone
def annotate(self, *args, **kwargs):
self.annotate_query_with_guids()
return super(GuidMixinQuerySet, self).annotate(*args, **kwargs)
def _filter_or_exclude(self, negate, *args, **kwargs):
if args or kwargs:
assert self.query.can_filter(), \
'Cannot filter a query once a slice has been taken.'
clone = self._clone(annotate=True)
if negate:
clone.query.add_q(~Q(*args, **kwargs))
else:
clone.query.add_q(Q(*args, **kwargs))
return clone
def all(self):
return self._clone(annotate=True)
# does implicit filter
def get(self, *args, **kwargs):
# add this to make sure we don't get dupes
self.query.add_distinct_fields('id')
return super(GuidMixinQuerySet, self).get(*args, **kwargs)
# TODO: Below lines are commented out to ensure that
# the annotations are used after running .count()
# e.g.
# queryset.count()
# queryset[0]
# This is more efficient when doing chained operations
# on a queryset, but less efficient when only getting a count.
# Figure out a way to get the best of both worlds
# def count(self):
# self.remove_guid_annotations()
# return super(GuidMixinQuerySet, self).count()
def update(self, **kwargs):
self.remove_guid_annotations()
return super(GuidMixinQuerySet, self).update(**kwargs)
def update_or_create(self, defaults=None, **kwargs):
self.remove_guid_annotations()
return super(GuidMixinQuerySet, self).update_or_create(defaults=defaults, **kwargs)
def values(self, *fields):
self.remove_guid_annotations()
return super(GuidMixinQuerySet, self).values(*fields)
def create(self, **kwargs):
self.remove_guid_annotations()
return super(GuidMixinQuerySet, self).create(**kwargs)
def bulk_create(self, objs, batch_size=None):
self.remove_guid_annotations()
return super(GuidMixinQuerySet, self).bulk_create(objs, batch_size)
def get_or_create(self, defaults=None, **kwargs):
self.remove_guid_annotations()
return super(GuidMixinQuerySet, self).get_or_create(defaults, **kwargs)
def values_list(self, *fields, **kwargs):
self.remove_guid_annotations()
return super(GuidMixinQuerySet, self).values_list(*fields, **kwargs)
def exists(self):
self.remove_guid_annotations()
return super(GuidMixinQuerySet, self).exists()
def _fetch_all(self):
if self._result_cache is None:
self._result_cache = list(self._iterable_class(self))
if self._prefetch_related_lookups and not self._prefetch_done:
if 'guids' in self._prefetch_related_lookups and self._result_cache and hasattr(self._result_cache[0], '_guids__id'):
# if guids is requested for prefetch and there are things in the result cache and the first one has
# the annotated guid fields then remove guids from prefetch_related_lookups
del self._prefetch_related_lookups[self._prefetch_related_lookups.index('guids')]
results = []
for result in self._result_cache:
# loop through the result cache
guid_dict = {}
for field in self.GUID_FIELDS:
# pull the fields off of the result object and put them in a dictionary without prefixed names
guid_dict[field] = getattr(result, '_{}'.format(field), None)
if None in guid_dict.values():
# if we get an invalid result field value, stop
logger.warning(
'Annotated guids came back will None values for {}, resorting to extra query'.format(result))
return
if not hasattr(result, '_prefetched_objects_cache'):
# initialize _prefetched_objects_cache
result._prefetched_objects_cache = {}
if 'guids' not in result._prefetched_objects_cache:
# intialize guids in _prefetched_objects_cache
result._prefetched_objects_cache['guids'] = []
# build a result dictionary of even more proper fields
result_dict = {key.replace('guids__', ''): value for key, value in guid_dict.iteritems()}
# make an unsaved guid instance
guid = Guid(**result_dict)
result._prefetched_objects_cache['guids'].append(guid)
results.append(result)
# replace the result cache with the new set of results
self._result_cache = results
self._prefetch_related_objects()
class GuidMixin(BaseIDMixin):
__guid_min_length__ = 5
primary_identifier_name = 'guid_string'
guids = GenericRelation(Guid, related_name='referent', related_query_name='referents')
guid_string = ArrayField(models.CharField(max_length=255, null=True, blank=True), null=True, blank=True)
content_type_pk = models.PositiveIntegerField(null=True, blank=True)
objects = GuidMixinQuerySet.as_manager()
# TODO: use pre-delete signal to disable delete cascade
def _natural_key(self):
return self.guid_string
@cached_property
def _id(self):
try:
guid = self.guids.all()[0]
except IndexError:
return None
if guid:
return guid._id
return None
@_id.setter
def _id(self, value):
# TODO do we really want to allow this?
guid, created = Guid.objects.get_or_create(_id=value)
if created:
guid.object_id = self.pk
guid.content_type = ContentType.objects.get_for_model(self)
guid.save()
elif guid.content_type == ContentType.objects.get_for_model(self) and guid.object_id == self.pk:
# TODO should this up the created for the guid until now so that it appears as the first guid
# for this object?
return
else:
raise InvalidGuid('Cannot indirectly repoint an existing guid, please use the Guid model')
_primary_key = _id
@classmethod
def load(cls, q):
try:
content_type = ContentType.objects.get_for_model(cls)
# if referent doesn't exist it will return None
return Guid.objects.get(_id=q, content_type=content_type).referent
except Guid.DoesNotExist:
# modm doesn't throw exceptions when loading things that don't exist
return None
@property
def deep_url(self):
return None
@classmethod
def migrate_from_modm(cls, modm_obj):
"""
Given a modm object, make a django object with the same local fields.
This is a base method that may work for simple objects.
It should be customized in the child class if it doesn't work.
:param modm_obj:
:return:
"""
django_obj = cls()
local_django_fields = set(
[x.name for x in django_obj._meta.get_fields() if not x.is_relation and x.name != '_id'])
intersecting_fields = set(modm_obj.to_storage().keys()).intersection(
set(local_django_fields))
for field in intersecting_fields:
modm_value = getattr(modm_obj, field)
if modm_value is None:
continue
if isinstance(modm_value, datetime):
modm_value = pytz.utc.localize(modm_value)
# TODO Remove this after migration
if isinstance(django_obj._meta.get_field(field), DateTimeAwareJSONField):
modm_value = coerce_nonnaive_datetimes(modm_value)
setattr(django_obj, field, modm_value)
from website.models import Guid as MODMGuid
from modularodm import Q as MODMQ
guids = MODMGuid.find(MODMQ('referent', 'eq', modm_obj._id))
setattr(django_obj, 'guid_string', list(set([x.lower() for x in guids.get_keys()])))
setattr(django_obj, 'content_type_pk', ContentType.objects.get_for_model(cls).pk)
return django_obj
class Meta:
abstract = True
@receiver(post_save)
def ensure_guid(sender, instance, created, **kwargs):
if not issubclass(sender, GuidMixin):
return False
existing_guids = Guid.objects.filter(object_id=instance.pk, content_type=ContentType.objects.get_for_model(instance))
has_cached_guids = hasattr(instance, '_prefetched_objects_cache') and 'guids' in instance._prefetched_objects_cache
if not existing_guids.exists():
# Clear query cache of instance.guids
if has_cached_guids:
del instance._prefetched_objects_cache['guids']
Guid.objects.create(object_id=instance.pk, content_type=ContentType.objects.get_for_model(instance),
_id=generate_guid(instance.__guid_min_length__))
elif not existing_guids.exists() and instance.guid_string is not None:
# Clear query cache of instance.guids
if has_cached_guids:
del instance._prefetched_objects_cache['guids']
Guid.objects.create(object_id=instance.pk, content_type_id=instance.content_type_pk,
_id=instance.guid_string)
| apache-2.0 | 2,214,120,148,595,470,600 | 34.588556 | 129 | 0.607917 | false |
stscieisenhamer/glue | glue/app/qt/splash_screen.py | 1 | 1493 | import os
from qtpy import QtWidgets, QtGui
from qtpy.QtCore import Qt, QRect
__all__ = ['QtSplashScreen']
class QtSplashScreen(QtWidgets.QWidget):
def __init__(self, *args, **kwargs):
super(QtSplashScreen, self).__init__(*args, **kwargs)
self.resize(627, 310)
self.setStyleSheet("background-color:white;")
self.setWindowFlags(Qt.Window | Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint)
self.center()
self.progress = QtWidgets.QProgressBar()
self.layout = QtWidgets.QVBoxLayout(self)
self.layout.addStretch()
self.layout.addWidget(self.progress)
pth = os.path.join(os.path.dirname(__file__), '..', '..', 'logo.png')
self.image = QtGui.QPixmap(pth)
def set_progress(self, value):
self.progress.setValue(value)
QtWidgets.qApp.processEvents() # update progress bar
def paintEvent(self, event):
painter = QtGui.QPainter(self)
painter.drawPixmap(QRect(20, 20, 587, 229), self.image)
def center(self):
# Adapted from StackOverflow
# https://stackoverflow.com/questions/20243637/pyqt4-center-window-on-active-screen
frameGm = self.frameGeometry()
screen = QtWidgets.QApplication.desktop().screenNumber(QtWidgets.QApplication.desktop().cursor().pos())
centerPoint = QtWidgets.QApplication.desktop().screenGeometry(screen).center()
frameGm.moveCenter(centerPoint)
self.move(frameGm.topLeft())
| bsd-3-clause | 1,320,943,867,231,352,300 | 32.177778 | 111 | 0.663094 | false |
pyload/pyload | src/pyload/plugins/downloaders/ZDF.py | 1 | 2269 | # -*- coding: utf-8 -*-
import re
import json
import os
from pyload.core.network.request_factory import get_url
import xml.etree.ElementTree as etree
import pycurl
from ..base.downloader import BaseDownloader
# Based on zdfm by Roland Beermann (http://github.com/enkore/zdfm/)
class ZDF(BaseDownloader):
__name__ = "ZDF Mediathek"
__type__ = "downloader"
__version__ = "0.92"
__status__ = "testing"
__pattern__ = r"https://(?:www\.)?zdf\.de/(?P<ID>[/\w-]+)\.html"
__config__ = [
("enabled", "bool", "Activated", True),
("use_premium", "bool", "Use premium account if available", True),
("fallback", "bool", "Fallback to free download if premium fails", True),
("chk_filesize", "bool", "Check file size", True),
("max_wait", "int", "Reconnect if waiting time is greater than minutes", 10),
]
__description__ = """ZDF.de downloader plugin"""
__license__ = "GPLv3"
__authors__ = []
def process(self, pyfile):
self.data = self.load(pyfile.url)
try:
api_token = re.search(
r'window\.zdfsite\.player\.apiToken = "([\d\w]+)";', self.data
).group(1)
self.req.http.c.setopt(pycurl.HTTPHEADER, ["Api-Auth: Bearer " + api_token])
id = re.match(self.__pattern__, pyfile.url).group("ID")
filename = json.loads(
self.load(
"https://api.zdf.de/content/documents/zdf/" + id + ".json",
get={"profile": "player-3"},
)
)
stream_list = filename["mainVideoContent"]["http://zdf.de/rels/target"][
"streams"
]["default"]["extId"]
streams = json.loads(
self.load(
"https://api.zdf.de/tmd/2/ngplayer_2_4/vod/ptmd/mediathek/"
+ stream_list
)
)
download_name = streams["priorityList"][0]["formitaeten"][0]["qualities"][
0
]["audio"]["tracks"][0]["uri"]
self.pyfile.name = os.path.basename(id) + os.path.splitext(download_name)[1]
self.download(download_name)
except Exception as exc:
self.log_error(exc)
| agpl-3.0 | -6,561,568,899,936,143,000 | 32.865672 | 88 | 0.527545 | false |
daeilkim/refinery | refinery/refinery/data/models.py | 1 | 10950 | # models.py contains code for defining the user object and behavior which will be used throughout the site
from refinery import db, app
import datetime
from refinery.webapp.pubsub import msgServer
from collections import defaultdict
import random,os,re,codecs
from collections import defaultdict
import pickle
# Defines a User class that takes the database and returns a User object that contains id,nickname,email
class User(db.Model):
id = db.Column(db.Integer, primary_key = True)
username = db.Column(db.String(64), index = True, unique = True)
password = db.Column(db.String(64), index = True)
email = db.Column(db.String(120), index = True, unique = True)
image = db.Column(db.String(100))
#datasets = db.relationship('Dataset', backref = 'author', lazy = 'dynamic')
def __init__(self, username, password, email):
self.username = username
self.password = password
self.email = email
self.image = None
def is_authenticated(self):
return True
def is_active(self):
return True
def is_anonymous(self):
return False
def get_id(self):
return unicode(self.id)
def __repr__(self):
return '<User %r>' % (self.username)
def check_password(self, proposed_password):
if self.password != proposed_password:
return False
else:
return True
class Experiment(db.Model):
id = db.Column(db.Integer, primary_key = True)
extype = db.Column(db.String(100)) # name of the model i.e topic_model
status = db.Column(db.Text) # status (idle,start,inprogress,finish)
def __init__(self, owner_id, extype):
self.owner_id = owner_id
self.extype = extype
self.status = 'idle'
def getExInfo(self):
if(self.extype == "topicmodel"):
return TopicModelEx.query.filter_by(ex_id=self.id).first()
elif(self.extype == "summarize"):
return SummarizeEx.query.filter_by(ex_id=self.id).first()
else:
return None
class TopicModelEx(db.Model):
id = db.Column(db.Integer, primary_key = True)
ex_id = db.Column(db.Integer, db.ForeignKey('experiment.id'))
viz_data = db.Column(db.PickleType) #the top words and topic proportions
nTopics = db.Column(db.Integer)
stopwords = db.Column(db.PickleType)
def __init__(self, ex_id, nTopics):
self.ex_id = ex_id
self.viz_data = None
self.nTopics = nTopics
self.stopwords = []
class SummarizeEx(db.Model):
id = db.Column(db.Integer, primary_key = True)
ex_id = db.Column(db.Integer, db.ForeignKey('experiment.id'))
current_summary = db.Column(db.PickleType) # a list of sentences in the current summary
top_candidates = db.Column(db.PickleType) # a list of top ranked candidate sentences
sents = db.Column(db.PickleType)
running = db.Column(db.Integer)
def __init__(self, ex_id):
self.ex_id = ex_id
self.current_summary = []
self.top_candidates = []
self.running = 0
class DataDoc(db.Model):
id = db.Column(db.Integer, primary_key = True)
data_id = db.Column(db.Integer, db.ForeignKey('dataset.id'))
doc_id = db.Column(db.Integer, db.ForeignKey('document.id'))
def __init__(self, dset, doc):
self.data_id = dset
self.doc_id = doc
class Document(db.Model):
id = db.Column(db.Integer, primary_key = True)
name = db.Column(db.String(256)) #the name of this file
path = db.Column(db.String(256)) #the path to the raw file data
def __init__(self, name, path):
self.name = name
self.path = path
self.sents = []
def getStaticURL(self):
print "!!!!!!!","/" + os.path.relpath(self.path,"refinery")
return "/" + os.path.relpath(self.path,"refinery")
def getText(self):
lines = [line for line in codecs.open(self.path,"r","utf-8")]
return "\n".join(lines)
def tokenize_sentence(text):
''' Returns list of words found in String. Matches A-Za-z and \'s '''
wordPattern = "[A-Za-z]+[']*[A-Za-z]*"
wordlist = re.findall( wordPattern, text)
return wordlist
class Folder(db.Model):
id = db.Column(db.Integer, primary_key = True)
dataset_id = db.Column(db.Integer, db.ForeignKey('dataset.id')) # the dataset that was used
docIDs = db.Column(db.PickleType) #hopefully, this can be a dictionary of included docIDs
name = db.Column(db.String)
tm_id = db.Column(db.Integer, db.ForeignKey('experiment.id'))
sum_id = db.Column(db.Integer, db.ForeignKey('experiment.id'))
vocabSize = db.Column(db.Integer)
dirty = db.Column(db.String(20))
def __init__(self, dataset_id, name, docIDs):
self.dataset_id = dataset_id
self.docIDs = docIDs
self.name = name
self.tm_id = None
self.sum_id = None
self.dirty = "dirty"
def numSents(self):
s = Experiment.query.get(self.sum_id).getExInfo()
if s.sents:
return sum([len(s.sents[ss]) for ss in s.sents])
return 0
def numTopics(self):
tm = Experiment.query.get(self.tm_id)
return tm.getExInfo().nTopics
def topicModelEx(self):
return Experiment.query.get(self.tm_id)
def sumModelEx(self):
return Experiment.query.get(self.sum_id)
def initialize(self):
ex1 = Experiment(self.id, "topicmodel")
db.session.add(ex1)
db.session.commit()
tm = TopicModelEx(ex1.id,10)
db.session.add(tm)
db.session.commit()
self.tm_id = ex1.id
ex2 = Experiment(self.id, "summarize")
db.session.add(ex2)
db.session.commit()
ei = SummarizeEx(ex2.id)
db.session.add(ei)
db.session.commit()
self.sum_id = ex2.id
db.session.commit()
def documents(self): # a generator for documents
dataset = Dataset.query.get(self.dataset_id)
for d in dataset.documents:
if d.id in self.docIDs:
yield d
def N(self):
dataset = Dataset.query.get(self.dataset_id)
tot = len(list(self.documents()))
return tot
def all_docs(self):
return sorted([Document.query.get(x.doc_id) for x in self.documents()],key=lambda x: x.id)
def preprocTM(self, username, min_doc, max_doc_percent):
#we need to add options, like to get rid of xml tags!
STOPWORDFILEPATH = 'refinery/static/assets/misc/stopwords.txt'
stopwords = set([x.strip() for x in open(STOPWORDFILEPATH)])
allD = self.all_docs()
nDocs = len(allD)
WC = defaultdict(int)
DWC = defaultdict( lambda: defaultdict(int) )
def addWord(f,w):
WC[w] += 1
DWC[f][w] += 1
c = 0.0
prev = 0
for d in allD:
filE = d.path
c += 1.0
pc = int(c / float(nDocs) * 100)
if pc > prev:
prev = pc
s = 'pprog,Step 1,' + str(self.id) + "," + str(pc)
msgServer.publish(username + 'Xmenus', "%s" % s)
[[addWord(filE,word) for word in tokenize_sentence(line) if word.lower() not in stopwords] for line in open(filE)]
# now remove words with bad appearace stats
to_remove = []
c = 0.0
oldpc = -1
for w in WC:
c += 1.0
pc = int(c/float(len(WC)) * 100)
if not oldpc == pc:
s = 'pprog,Step 2,' + str(self.id) + "," + str(pc)
#print s
msgServer.publish(username + 'Xmenus', "%s" % s)
oldpc = pc
has_w = [d for d,m in DWC.items() if w in m]
n_has_w = len(has_w)
doc_percent = float(n_has_w)/float(nDocs)
#print w,doc_percent,n_has_w
if n_has_w < min_doc or doc_percent > max_doc_percent:
[DWC[d].pop(w,None) for d in has_w]
to_remove.append(w)
[WC.pop(w,None) for w in to_remove]
vocab = [w for w in WC]
print "N VOCAB",len(vocab)
v_enum = defaultdict(int)
for w in vocab:
v_enum[w] = len(v_enum)
d_enum = defaultdict(int)
for f in allD:
d_enum[f.path] = len(d_enum)
outfile = open(self.wordcount_path(),'w')
for d in allD:
f = d.path
m = DWC[f]
fID = d_enum[f]
for w, c in m.items():
wID = v_enum[w]
outfile.write(str(fID) + ',' + str(wID) + ',' + str(c) + '\n')
outfile.close()
self.vocabSize = len(vocab)
outfile = open(self.vocab_path(),'w')
[outfile.write(x + "\n") for x in vocab]
outfile.close()
self.dirty = "clean"
db.session.commit()
def preproc_path(self):
dataset = Dataset.query.get(self.dataset_id)
return "refinery/static/users/" + User.query.get(dataset.owner_id).username + "/processed/"
def wordcount_path(self):
return self.preproc_path() + str(self.id) + "_word_count.txt"
def vocab_path(self):
return self.preproc_path() + str(self.id) + "_vocab.txt"
def unigram(self):
wcfile = self.wordcount_path()
lines = [x.strip().split(",") for x in open(wcfile,'r')]
unigram_dist = [0.0 for _ in xrange(self.vocabSize)]
for l in lines:
wID = int(l[1])
wC = int(l[2])
unigram_dist[wID] += wC
tot = sum(unigram_dist)
return [x / tot for x in unigram_dist]
#return unigram_dist
def get_vocab_list(self):
vocabfile = self.vocab_path()
return [x.strip() for x in open(vocabfile,'r')]
class Dataset(db.Model):
id = db.Column(db.Integer, primary_key = True)
owner_id = db.Column(db.Integer, db.ForeignKey('user.id'))
name = db.Column(db.String(100)) # name of the dataset
summary = db.Column(db.Text) # summary of the dataset (optional)
img = db.Column(db.String(100)) # path to dataset img
owner = db.relationship('User', backref = 'datasets')
folders = db.relationship('Folder', backref = 'dataset', lazy = 'dynamic')
documents = db.relationship('DataDoc', backref = 'docdataset', lazy = 'dynamic')
def get_folders(self):
return self.folders.order_by(Folder.id)
def __init__(self, owner, name, summary, img=None):
self.owner_id = owner
self.name = name
self.summary = summary
if img is None:
random_img = random.choice(os.listdir(app.config['RANDOM_IMG_DIRECTORY']))
self.img = os.path.join("assets/images/random", random_img)
else:
self.img = img
| mit | -3,804,350,228,446,922,000 | 30.285714 | 127 | 0.572603 | false |
mrrichardchou/FAST_EVD | DataIO/ismrmd/doc/source/conf.py | 1 | 8582 | # -*- coding: utf-8 -*-
#
# ISMRMRD documentation build configuration file, created by
# sphinx-quickstart on Thu Nov 13 10:11:39 2014.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
#import breathe
import sphinx_bootstrap_theme
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.doctest',
'sphinx.ext.todo',
'sphinx.ext.mathjax',
#'breathe'
]
#breathe_projects = { 'ISMRMRD': '/Users/naegelejd/src/github.com/ismrmrd/ismrmrd/build/doc/api/xml' }
#breathe_default_project = 'ISMRMRD'
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'ISMRMRD'
copyright = u'2014, ISMRMRD Developers'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '1.1'
# The full version, including alpha/beta/rc tags.
release = '1.1.0'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = []
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'bootstrap'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
html_theme_options = {
'navbar_links': [
('API Reference', "api/index.html", True)
]
}
# Add any paths that contain custom themes here, relative to this directory.
html_theme_path = sphinx_bootstrap_theme.get_html_theme_path()
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'ISMRMRDdoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
('index', 'ISMRMRD.tex', u'ISMRMRD Documentation',
u'ISMRMRD Developers', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'ismrmrd', u'ISMRMRD Documentation',
[u'ISMRMRD Developers'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'ISMRMRD', u'ISMRMRD Documentation',
u'ISMRMRD Developers', 'ISMRMRD', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
| bsd-2-clause | 9,073,641,456,777,190,000 | 30.435897 | 102 | 0.706595 | false |
imclab/confer | server/auth.py | 1 | 12729 | import json, sys, re, hashlib, smtplib, base64, urllib, os
from django.http import *
from django.shortcuts import render_to_response
from django.views.decorators.csrf import csrf_exempt
from django.core.context_processors import csrf
from django.core.validators import email_re
from django.db.utils import IntegrityError
from django.utils.http import urlquote_plus
from multiprocessing import Pool
from utils import *
from models import *
p = os.path.abspath(os.path.dirname(__file__))
if(os.path.abspath(p+"/..") not in sys.path):
sys.path.append(os.path.abspath(p+"/.."))
'''
@author: Anant Bhardwaj
@date: Feb 12, 2012
'''
kLogIn = "SESSION_LOGIN"
kConf = "SESSION_CONF"
kName = "SESSION_NAME"
kFName = "SESSION_F_NAME"
kLName = "SESSION_L_NAME"
# for async calls
pool = Pool(processes=1)
'''
LOGIN/REGISTER/RESET
'''
def login_required (f):
def wrap (request, *args, **kwargs):
if kLogIn not in request.session.keys():
if(len(args)>0):
redirect_url = urlquote_plus("/%s/%s" %(args[0], f.__name__))
else:
redirect_url = "/"
return HttpResponseRedirect("/login?redirect_url=%s" %(redirect_url))
return f(request, *args, **kwargs)
wrap.__doc__ = f.__doc__
wrap.__name__ = f.__name__
return wrap
def login_form (request, redirect_url='/', errors=[]):
c = {'redirect_url':redirect_url, 'errors':errors, 'values':request.REQUEST}
c.update(csrf(request))
return render_to_response('login.html', c)
def register_form (request, redirect_url='/', errors=[]):
c = {'redirect_url':redirect_url, 'errors':errors, 'values':request.REQUEST}
c.update(csrf(request))
return render_to_response('register.html', c)
def login (request):
redirect_url = '/'
if('redirect_url' in request.GET.keys()):
redirect_url = urllib.unquote_plus(request.GET['redirect_url'])
if not redirect_url or redirect_url == '':
redirect_url = '/'
if request.method == "POST":
errors = []
login_email = ''
if('redirect_url' in request.POST.keys()):
redirect_url = urllib.unquote_plus(request.POST['redirect_url'])
try:
login_email = request.POST["login_email"].lower()
login_password = hashlib.sha1(request.POST["login_password"]).hexdigest()
user = User.objects.get(email=login_email, password=login_password)
clear_session(request)
request.session[kLogIn] = user.email
request.session[kName] = user.f_name
request.session[kFName] = user.f_name
request.session[kLName] = user.l_name
return HttpResponseRedirect(redirect_url)
except User.DoesNotExist:
try:
User.objects.get(email=login_email)
errors.append(
'Wrong password. Please try again.<br /><br />'
'<a class="blue bold" href="/forgot?email=%s">Click Here</a> '
'to reset your password.' %(urllib.quote_plus(login_email)))
except User.DoesNotExist:
errors.append(
'Could not find any account associated with email address: '
'<a href="mailto:%s">%s</a>.<br /><br /><a class="blue bold" '
'href="/register?redirect_url=%s&email=%s">Click Here</a> '
'to create an account.' %(login_email, login_email,
urllib.quote_plus(redirect_url), urllib.quote_plus(login_email)))
return login_form(
request, redirect_url = urllib.quote_plus(redirect_url),
errors = errors)
except:
errors.append('Login failed.')
return login_form(
request, redirect_url = urllib.quote_plus(redirect_url),
errors = errors)
else:
return login_form(request, urllib.quote_plus(redirect_url))
def register (request):
redirect_url = '/'
if('redirect_url' in request.GET.keys()):
redirect_url = urllib.unquote_plus(request.GET['redirect_url'])
if request.method == "POST":
errors = []
email = ''
try:
error = False
if('redirect_url' in request.POST.keys()):
redirect_url = urllib.unquote_plus(request.POST['redirect_url'])
email = request.POST["email"].lower()
password = request.POST["password"]
f_name = request.POST["f_name"]
l_name = request.POST["l_name"]
if(email_re.match(email.strip()) == None):
errors.append("Invalid Email.")
error = True
if(f_name.strip() == ""):
errors.append("Empty First Name.")
error = True
if(l_name.strip() == ""):
errors.append("Empty Last Name.")
error = True
if(password == ""):
errors.append("Empty Password.")
error = True
if(error):
return register_form(request, redirect_url = urllib.quote_plus(redirect_url), errors = errors)
hashed_password = hashlib.sha1(password).hexdigest()
user = User(email=email, password=hashed_password, f_name=f_name, l_name=l_name)
user.save()
clear_session(request)
request.session[kLogIn] = user.email
request.session[kName] = user.f_name
request.session[kFName] = user.f_name
request.session[kLName] = user.l_name
encrypted_email = encrypt_text(user.email)
subject = "Welcome to Confer"
msg_body = '''
Dear %s,
Thanks for registering to Confer.
Please click the link below to start using Confer:
http://confer.csail.mit.edu/verify/%s
''' % (user.f_name + ' ' + user.l_name, encrypted_email)
pool.apply_async(send_email, [user.email, subject, msg_body])
return HttpResponseRedirect(redirect_url)
except IntegrityError:
errors.append(
'Account already exists. Please <a class="blue bold" href="/login?login_email=%s">Log In</a>.'
% (urllib.quote_plus(email)))
return register_form(request, redirect_url = urllib.quote_plus(redirect_url), errors = errors)
except:
errors.append("Some error happened while trying to create an account. Please try again.")
return register_form(request, redirect_url = urllib.quote_plus(redirect_url), errors = errors)
else:
return register_form(request, redirect_url = urllib.quote_plus(redirect_url))
def clear_session (request):
request.session.flush()
if kLogIn in request.session.keys():
del request.session[kLogIn]
if kName in request.session.keys():
del request.session[kName]
if kFName in request.session.keys():
del request.session[kFName]
if kLName in request.session.keys():
del request.session[kLName]
def logout (request):
clear_session(request)
c = {
'msg_title': 'Thank you for using Confer!',
'msg_body': 'Your have been logged out.<br /><br /><ul><li><a class= "blue bold" href="/home">Click Here</a> to browse confer as guest.<br/><br /></li><li><a class= "blue bold" href="/login">Click Here</a> to log in again.</li></ul>'
}
c.update(csrf(request))
return render_to_response('confirmation.html', c)
def forgot (request):
if request.method == "POST":
errors = []
try:
user_email = request.POST["email"].lower()
User.objects.get(email=user_email)
encrypted_email = encrypt_text(user_email)
subject = "Confer Password Reset"
msg_body = '''
Dear %s,
Please click the link below to reset your confer password:
http://confer.csail.mit.edu/reset/%s
''' % (user_email, encrypted_email)
pool.apply_async(send_email, [user_email, subject, msg_body])
c = {
'msg_title': 'Confer Reset Password',
'msg_body': 'A link to reset your password has been sent to your email address.'
}
c.update(csrf(request))
return render_to_response('confirmation.html', c)
except User.DoesNotExist:
errors.append(
"Invalid Email Address.")
except:
errors.append(
'Some unknown error happened.'
'Please try again or send an email to '
'<a href="mailto:confer@csail.mit.edu">confer@csail.mit.edu</a>.')
c = {'errors': errors, 'values': request.POST}
c.update(csrf(request))
return render_to_response('forgot.html', c)
else:
c = {'values': request.REQUEST}
c.update(csrf(request))
return render_to_response('forgot.html', c)
def verify (request, encrypted_email):
errors = []
c = {'msg_title': 'Confer Account Verification'}
try:
user_email = decrypt_text(encrypted_email)
user = User.objects.get(email=user_email)
c.update({
'msg_body': 'Thanks for verifying your email address! <a class= "blue bold" href="/home">Click Here</a> to start using Confer.'
})
clear_session(request)
request.session[kLogIn] = user.email
request.session[kName] = user.f_name
request.session[kFName] = user.f_name
request.session[kLName] = user.l_name
except:
errors.append(
'Wrong verify code in the URL. '
'Please try again or send an email to '
'<a href="mailto:confer@csail.mit.edu">confer@csail.mit.edu</a>')
c.update({'errors': errors})
c.update(csrf(request))
return render_to_response('confirmation.html', c)
def reset (request, encrypted_email):
errors = []
error = False
if request.method == "POST":
try:
user_email = request.POST["user_email"].lower()
password = request.POST["new_password"]
password2 = request.POST["new_password2"]
if password == "":
errors.append("Empty Password.")
error = True
if password2 != password:
errors.append("Password and Confirm Password don't match.")
error = True
if error:
c = {
'user_email': user_email,
'encrypted_email': encrypted_email,
'errors': errors
}
c.update(csrf(request))
return render_to_response('reset.html', c)
else:
hashed_password = hashlib.sha1(password).hexdigest()
user = User.objects.get(email=user_email)
user.password = hashed_password
user.save()
c = {
'msg_title': 'Confer Reset Password',
'msg_body': 'Your password has been changed successfully.'
}
c.update(csrf(request))
return render_to_response('confirmation.html', c)
except:
errors.append(
'Some unknown error happened. '
'Please try again or send an email to '
'<a href="mailto:confer@csail.mit.edu">confer@csail.mit.edu</a>')
c = {'errors': errors}
c.update(csrf(request))
return render_to_response('reset.html', c)
else:
try:
user_email = decrypt_text(encrypted_email)
User.objects.get(email=user_email)
c = {
'user_email': user_email,
'encrypted_email': encrypted_email
}
c.update(csrf(request))
return render_to_response('reset.html', c)
except:
errors.append(
'Wrong reset code in the URL. '
'Please try again or send an email to '
'<a href="mailto:confer@csail.mit.edu">confer@csail.mit.edu</a>')
c = {'msg_title': 'Confer Reset Password', 'errors': errors}
c.update(csrf(request))
return render_to_response('confirmation.html', c)
@login_required
def settings (request):
errors = []
error = False
redirect_url = '/'
if('redirect_url' in request.GET.keys()):
redirect_url = request.GET['redirect_url']
if request.method == "POST":
try:
if('redirect_url' in request.POST.keys()):
redirect_url = request.POST['redirect_url']
user_email = request.POST["user_email"].lower()
meetups = request.POST["meetups_enabled"]
user = User.objects.get(email=user_email)
if meetups == 'enabled':
user.meetups_enabled = True
else:
user.meetups_enabled = False
user.save()
return HttpResponseRedirect(redirect_url)
except Exception, e:
errors.append(
'Some unknown error happened. '
'Please try again or send an email to '
'<a href="mailto:confer@csail.mit.edu">confer@csail.mit.edu</a>')
c = {'errors': errors}
c.update(csrf(request))
return render_to_response('settings.html', c)
else:
login = get_login(request)
user = User.objects.get(email=login[0])
meetups_enabled = user.meetups_enabled
c = {
'user_email': login[0],
'login_id': login[0],
'login_name': login[1],
'meetups_enabled': meetups_enabled,
'redirect_url': redirect_url}
c.update(csrf(request))
return render_to_response('settings.html', c)
def get_login(request):
login_id = None
login_name = ''
try:
login_id = request.session[kLogIn]
login_name = request.session[kName]
except:
pass
return [login_id, login_name]
| mit | -7,501,670,995,491,163,000 | 30.585608 | 237 | 0.623537 | false |
geertj/bluepass | bluepass/frontends/qt/passwordbutton.py | 1 | 10929 | #
# This file is part of Bluepass. Bluepass is Copyright (c) 2012-2013
# Geert Jansen.
#
# Bluepass is free software available under the GNU General Public License,
# version 3. See the file LICENSE distributed with this file for the exact
# licensing terms.
from __future__ import absolute_import, print_function
from PyQt4.QtCore import QTimer, Signal, Slot, Property, Qt, QPoint
from PyQt4.QtGui import (QPushButton, QStylePainter, QStyleOptionButton,
QStyle, QGridLayout, QWidget, QLabel, QSpinBox, QLineEdit, QFrame,
QApplication, QCheckBox, QFontMetrics)
class NoSelectSpinbox(QSpinBox):
"""This is a SpinBox that:
* Will not select the displayed text when the value changes.
* Does not accept keyboard input.
"""
def __init__(self, parent=None):
super(NoSelectSpinbox, self).__init__(parent)
self.setFocusPolicy(Qt.NoFocus)
def stepBy(self, amount):
super(NoSelectSpinbox, self).stepBy(amount)
self.lineEdit().deselect()
class StrengthIndicator(QLabel):
"""A password strength indicator.
This is a label that gives feedback on the strength of a password.
"""
Poor, Good, Excellent = range(3)
stylesheet = """
StrengthIndicator { border: 1px solid black; }
StrengthIndicator[strength="0"] { background-color: #ff2929; }
StrengthIndicator[strength="1"] { background-color: #4dd133; }
StrengthIndicator[strength="2"] { background-color: #4dd133; }
"""
def __init__(self, parent=None):
super(StrengthIndicator, self).__init__(parent)
self._strength = 0
self.setStyleSheet(self.stylesheet)
def getStrength(self):
return self._strength
def setStrength(self, strength):
self._strength = strength
if strength == self.Poor:
self.setText('Poor')
elif strength == self.Good:
self.setText('Good')
elif strength == self.Excellent:
self.setText('Excellent')
self.setStyleSheet(self.stylesheet)
strength = Property(int, getStrength, setStrength)
class PasswordConfiguration(QFrame):
"""Base class for password configuration popups.
A password popup is installed in a GeneratePasswordButton, and allows
the user to customize the parameters of password generation.
"""
def __init__(self, method, parent=None):
super(PasswordConfiguration, self).__init__(parent)
self.method = method
self.parameters = []
parametersChanged = Signal(str, list)
class DicewarePasswordConfiguration(PasswordConfiguration):
"""Configuration for Diceware password generation."""
stylesheet = """
PasswordConfiguration { border: 1px solid grey; }
"""
def __init__(self, parent=None):
super(DicewarePasswordConfiguration, self).__init__('diceware', parent)
self.parameters = [5]
self.addWidgets()
self.setFixedSize(self.sizeHint())
self.setStyleSheet(self.stylesheet)
def addWidgets(self):
grid = QGridLayout()
self.setLayout(grid)
grid.setColumnMinimumWidth(1, 10)
label = QLabel('Length', self)
grid.addWidget(label, 0, 0)
spinbox = NoSelectSpinbox(self)
spinbox.setSuffix(' words')
spinbox.setMinimum(4)
spinbox.setMaximum(8)
grid.addWidget(spinbox, 0, 2)
label = QLabel('Security', self)
grid.addWidget(label, 1, 0)
strength = StrengthIndicator(self)
grid.addWidget(strength, 1, 2)
self.strength = strength
spinbox.valueChanged.connect(self.setParameters)
spinbox.setValue(self.parameters[0])
@Slot(int)
def setParameters(self, words):
self.parameters[0] = words
self.updateStrength()
@Slot()
def updateStrength(self):
backend = QApplication.instance().backend()
strength = backend.password_strength(self.method, *self.parameters)
# We use Diceware only for locking our vaults. Because we know we
# do proper salting and key stretching, we add 20 extra bits.
strength += 20
if strength < 70:
strength = StrengthIndicator.Poor
elif strength < 94:
strength = StrengthIndicator.Good
else:
strength = StrengthIndicator.Excellent
self.strength.setStrength(strength)
class RandomPasswordConfiguration(PasswordConfiguration):
"""Configuration for random password generation."""
stylesheet = """
PasswordConfiguration { border: 1px solid grey; }
"""
def __init__(self, parent=None):
super(RandomPasswordConfiguration, self).__init__('random', parent)
self.parameters = [12, '[a-z][A-Z][0-9]']
self.addWidgets()
self.setFixedSize(self.sizeHint())
self.setStyleSheet(self.stylesheet)
def addWidgets(self):
grid = QGridLayout()
self.setLayout(grid)
grid.setColumnMinimumWidth(1, 10)
label = QLabel('Length', self)
grid.addWidget(label, 0, 0)
spinbox = NoSelectSpinbox(self)
spinbox.setSuffix(' characters')
spinbox.setMinimum(6)
spinbox.setMaximum(20)
grid.addWidget(spinbox, 0, 2, 1, 2)
label = QLabel('Characters')
grid.addWidget(label, 1, 0)
def updateInclude(s):
def stateChanged(state):
self.updateInclude(state, s)
return stateChanged
lower = QCheckBox('Lower')
grid.addWidget(lower, 1, 2)
lower.stateChanged.connect(updateInclude('[a-z]'))
upper = QCheckBox('Upper')
grid.addWidget(upper, 1, 3)
upper.stateChanged.connect(updateInclude('[A-Z]'))
digits = QCheckBox('Digits')
grid.addWidget(digits, 2, 2)
digits.stateChanged.connect(updateInclude('[0-9]'))
special = QCheckBox('Special')
grid.addWidget(special, 2, 3)
special.stateChanged.connect(updateInclude('[!-/]'))
label = QLabel('Security', self)
grid.addWidget(label, 3, 0)
strength = StrengthIndicator(self)
grid.addWidget(strength, 3, 2)
self.strength = strength
spinbox.valueChanged.connect(self.setLength)
spinbox.setValue(self.parameters[0])
lower.setChecked('[a-z]' in self.parameters[1])
upper.setChecked('[A-Z]' in self.parameters[1])
digits.setChecked('[0-9]' in self.parameters[1])
special.setChecked('[!-/]' in self.parameters[1])
@Slot(int)
def setLength(self, length):
self.parameters[0] = length
self.parametersChanged.emit(self.method, self.parameters)
self.updateStrength()
@Slot()
def updateInclude(self, enable, s):
if enable and s not in self.parameters[1]:
self.parameters[1] += s
elif not enable:
self.parameters[1] = self.parameters[1].replace(s, '')
self.parametersChanged.emit(self.method, self.parameters)
self.updateStrength()
@Slot()
def updateStrength(self):
backend = QApplication.instance().backend()
strength = backend.password_strength(self.method, *self.parameters)
# We do not know if the remote site does key stretching or salting.
# So we only give a Good rating if the entropy takes the password
# out of reach of the largest Rainbow tables.
if strength < 60:
strength = StrengthIndicator.Poor
elif strength < 84:
strength = StrengthIndicator.Good
else:
strength = StrengthIndicator.Excellent
self.strength.setStrength(strength)
class PopupButton(QPushButton):
"""A button with a popup.
The popup will be displayed just below the button after the user
keeps the button pressed for 500 msecs.
"""
def __init__(self, text, parent=None):
super(PopupButton, self).__init__(text, parent)
timer = QTimer()
timer.setSingleShot(True)
timer.setInterval(500)
timer.timeout.connect(self.showPopup)
self.timer = timer
self.popup = None
# I would have preferred to implement the menu indicator by overriding
# initStyleOption(), and nothing else, but it doesn't work. The C++
# ::paintEvent() and ::sizeHint() are not able to call into it. So we need
# to provide our own paintEvent() and sizeHint() too.
def initStyleOption(self, option):
super(PopupButton, self).initStyleOption(option)
option.features |= option.HasMenu
def paintEvent(self, event):
p = QStylePainter(self)
opts = QStyleOptionButton()
self.initStyleOption(opts)
p.drawControl(QStyle.CE_PushButton, opts)
def sizeHint(self):
size = super(PopupButton, self).sizeHint()
fm = QFontMetrics(QApplication.instance().font())
width = fm.width(self.text())
opts = QStyleOptionButton()
self.initStyleOption(opts)
style = self.style()
dw = style.pixelMetric(QStyle.PM_MenuButtonIndicator, opts, self)
size.setWidth(width + dw + 10)
return size
def mousePressEvent(self, event):
self.timer.start()
super(PopupButton, self).mousePressEvent(event)
def mouseReleaseEvent(self, event):
self.timer.stop()
super(PopupButton, self).mouseReleaseEvent(event)
def setPopup(self, popup):
popup.setParent(None)
popup.setWindowFlags(Qt.Popup)
popup.hide()
# Install a closeEvent() on the popup that raises the button.
def closeEvent(*args):
self.setDown(False)
popup.closeEvent = closeEvent
self.popup = popup
@Slot()
def showPopup(self):
if not self.popup:
return
pos = QPoint(self.width(), self.height())
pos = self.mapToGlobal(pos)
size = self.popup.size()
self.popup.move(pos.x() - size.width(), pos.y())
self.popup.show()
class GeneratePasswordButton(PopupButton):
"""A password generation button.
A password is generated each time the user clicks the button.
"""
def __init__(self, text, popup, parent=None):
super(GeneratePasswordButton, self).__init__(text, parent)
self.method = popup.method
self.parameters = popup.parameters
self.setPopup(popup)
popup.parametersChanged.connect(self.parametersChanged)
self.clicked.connect(self.generate)
@Slot(str, list)
def parametersChanged(self, method, parameters):
self.method = method
self.parameters = parameters
self.generate()
@Slot()
def generate(self):
backend = QApplication.instance().backend()
password = backend.generate_password(self.method, *self.parameters)
self.passwordGenerated.emit(password)
passwordGenerated = Signal(str)
| gpl-3.0 | -703,691,127,010,999,800 | 33.046729 | 79 | 0.637753 | false |
schnapptack/gskompetenzen | features/gsaudit/migrations/0025_auto__add_field_skill_author.py | 1 | 15198 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Skill.author'
db.add_column(u'gsaudit_skill', 'author',
self.gf('django.db.models.fields.related.ForeignKey')(to=orm['gsaudit.Teacher'], null=True, blank=True),
keep_default=False)
def backwards(self, orm):
# Deleting field 'Skill.author'
db.delete_column(u'gsaudit_skill', 'author_id')
models = {
u'auth.group': {
'Meta': {'object_name': 'Group'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
u'auth.permission': {
'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
u'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
u'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
u'gsaudit.audit': {
'Meta': {'object_name': 'Audit'},
'assignment': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['gsaudit.TeachingAssignment']"}),
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'date': ('django.db.models.fields.DateTimeField', [], {}),
'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'jsondata': ('jsonfield.fields.JSONField', [], {'default': '{}'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'written_exam': ('django.db.models.fields.BooleanField', [], {'default': 'False'})
},
u'gsaudit.auditskill': {
'Meta': {'object_name': 'AuditSkill'},
'audit': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['gsaudit.Audit']"}),
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'jsondata': ('jsonfield.fields.JSONField', [], {'default': '{}'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'skill': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['gsaudit.Skill']"}),
'weight': ('django.db.models.fields.IntegerField', [], {'default': '1'})
},
u'gsaudit.grade': {
'Meta': {'object_name': 'Grade'},
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'jsondata': ('jsonfield.fields.JSONField', [], {'default': '{}'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'pupils': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': u"orm['gsaudit.Pupil']", 'null': 'True', 'through': u"orm['gsaudit.GradeParticipant']", 'blank': 'True'}),
'school': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['gsaudit.School']"})
},
u'gsaudit.gradeparticipant': {
'Meta': {'object_name': 'GradeParticipant'},
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'grade': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['gsaudit.Grade']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'jsondata': ('jsonfield.fields.JSONField', [], {'default': '{}'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'pupil': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['gsaudit.Pupil']"})
},
u'gsaudit.pupil': {
'Meta': {'ordering': "('last_name', 'first_name')", 'object_name': 'Pupil'},
'birthday': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}),
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'gender': ('django.db.models.fields.CharField', [], {'max_length': '1'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'jsondata': ('jsonfield.fields.JSONField', [], {'default': '{}'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'note': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'school': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['gsaudit.School']"})
},
u'gsaudit.pupilauditskill': {
'Meta': {'object_name': 'PupilAuditSkill'},
'audit': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['gsaudit.Audit']"}),
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'diagnosis': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'jsondata': ('jsonfield.fields.JSONField', [], {'default': '{}'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'note': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'pupil': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['gsaudit.Pupil']"}),
'rating': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'skill': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['gsaudit.Skill']"}),
'written_exam': ('django.db.models.fields.BooleanField', [], {'default': 'False'})
},
u'gsaudit.pupiltainfo': {
'Meta': {'unique_together': "(('pupil', 'teaching_assignment'),)", 'object_name': 'PupilTAInfo'},
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'info': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'jsondata': ('jsonfield.fields.JSONField', [], {'default': '{}'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'pupil': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['gsaudit.Pupil']"}),
'teaching_assignment': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['gsaudit.TeachingAssignment']"}),
'written_exam_rating': ('django.db.models.fields.FloatField', [], {'default': '0.0', 'null': 'True', 'blank': 'True'})
},
u'gsaudit.school': {
'Meta': {'object_name': 'School'},
'address': ('django.db.models.fields.TextField', [], {}),
'contact_person': ('django.db.models.fields.TextField', [], {}),
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'domain': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'jsondata': ('jsonfield.fields.JSONField', [], {'default': '{}'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'})
},
u'gsaudit.skill': {
'Meta': {'object_name': 'Skill'},
'author': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['gsaudit.Teacher']", 'null': 'True', 'blank': 'True'}),
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'jsondata': ('jsonfield.fields.JSONField', [], {'default': '{}'}),
'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'max_skill_level': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'min_skill_level': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'parent': ('mptt.fields.TreeForeignKey', [], {'blank': 'True', 'related_name': "'children'", 'null': 'True', 'to': u"orm['gsaudit.Skill']"}),
'pupil_description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'weight': ('django.db.models.fields.IntegerField', [], {'default': '0'})
},
u'gsaudit.subject': {
'Meta': {'object_name': 'Subject'},
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'jsondata': ('jsonfield.fields.JSONField', [], {'default': '{}'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'})
},
u'gsaudit.teacher': {
'Meta': {'object_name': 'Teacher'},
'gender': ('django.db.models.fields.CharField', [], {'max_length': '1'}),
'phone': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'school': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['gsaudit.School']"}),
u'user_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': u"orm['auth.User']", 'unique': 'True', 'primary_key': 'True'})
},
u'gsaudit.teachingassignment': {
'Meta': {'object_name': 'TeachingAssignment'},
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'default_skill_level': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'grade': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['gsaudit.Grade']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'jsondata': ('jsonfield.fields.JSONField', [], {'default': '{}'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'note': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'skill': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['gsaudit.Skill']"}),
'subject': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['gsaudit.Subject']"}),
'teacher': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['gsaudit.Teacher']"})
}
}
complete_apps = ['gsaudit'] | agpl-3.0 | -2,912,736,705,076,302,300 | 75.762626 | 215 | 0.544085 | false |
kamijawa/libmpsse | src/examples/spiflash.py | 1 | 6528 | #!/usr/bin/env python
from mpsse import *
from time import sleep
class SPIFlash(object):
WCMD = "\x02" # Standard SPI flash write command (0x02)
RCMD = "\x03" # Standard SPI flash read command (0x03)
WECMD = "\x06" # Standard SPI flash write enable command (0x06)
CECMD = "\xc7" # Standard SPI flash chip erase command (0xC7)
IDCMD = "\x9f" # Standard SPI flash chip ID command (0x9F)
ID_LENGTH = 3 # Normal SPI chip ID length, in bytes
ADDRESS_LENGTH = 3 # Normal SPI flash address length (24 bits, aka, 3 bytes)
BLOCK_SIZE = 256 # SPI block size, writes must be done in multiples of this size
PP_PERIOD = .025 # Page program time, in seconds
def __init__(self, speed=FIFTEEN_MHZ):
# Sanity check on the specified clock speed
if not speed:
speed = FIFTEEN_MHZ
self.flash = MPSSE(SPI0, speed, MSB)
self.chip = self.flash.GetDescription()
self.speed = self.flash.GetClock()
self._init_gpio()
def _init_gpio(self):
# Set the GPIOL0 and GPIOL1 pins high for connection to SPI flash WP and HOLD pins.
self.flash.PinHigh(GPIOL0)
self.flash.PinHigh(GPIOL1)
def _addr2str(self, address):
addr_str = ""
for i in range(0, self.ADDRESS_LENGTH):
addr_str += chr((address >> (i*8)) & 0xFF)
return addr_str[::-1]
def Read(self, count, address=0):
data = ''
self.flash.Start()
self.flash.Write(self.RCMD + self._addr2str(address))
data = self.flash.Read(count)
self.flash.Stop()
return data
def Write(self, data, address=0):
count = 0
while count < len(data):
self.flash.Start()
self.flash.Write(self.WECMD)
self.flash.Stop()
self.flash.Start()
self.flash.Write(self.WCMD + self._addr2str(address) + data[address:address+self.BLOCK_SIZE])
self.flash.Stop()
sleep(self.PP_PERIOD)
address += self.BLOCK_SIZE
count += self.BLOCK_SIZE
def Erase(self):
self.flash.Start()
self.flash.Write(self.WECMD)
self.flash.Stop()
self.flash.Start()
self.flash.Write(self.CECMD)
self.flash.Stop()
def ChipID(self):
self.flash.Start()
self.flash.Write(self.IDCMD)
chipid = self.flash.Read(self.IDLEN)
self.flash.Stop()
return chipid
def Close(self):
self.flash.Close()
if __name__ == "__main__":
import sys
from getopt import getopt as GetOpt, GetoptError
def pin_mappings():
print """
Common Pin Mappings for 8-pin SPI Flash Chips
--------------------------------------------------------------------
| Description | SPI Flash Pin | FTDI Pin | C232HM Cable Color Code |
--------------------------------------------------------------------
| CS | 1 | ADBUS3 | Brown |
| MISO | 2 | ADBUS2 | Green |
| WP | 3 | ADBUS4 | Grey |
| GND | 4 | N/A | Black |
| MOSI | 5 | ADBUS1 | Yellow |
| CLK | 6 | ADBUS0 | Orange |
| HOLD | 7 | ADBUS5 | Purple |
| Vcc | 8 | N/A | Red |
--------------------------------------------------------------------
"""
sys.exit(0)
def usage():
print ""
print "Usage: %s [OPTIONS]" % sys.argv[0]
print ""
print "\t-r, --read=<file> Read data from the chip to file"
print "\t-w, --write=<file> Write data from file to the chip"
print "\t-s, --size=<int> Set the size of data to read/write"
print "\t-a, --address=<int> Set the starting address for the read/write operation [0]"
print "\t-f, --frequency=<int> Set the SPI clock frequency, in hertz [15,000,000]"
print "\t-i, --id Read the chip ID"
print "\t-v, --verify Verify data that has been read/written"
print "\t-e, --erase Erase the entire chip"
print "\t-p, --pin-mappings Display a table of SPI flash to FTDI pin mappings"
print "\t-h, --help Show help"
print ""
sys.exit(1)
def main():
fname = None
freq = None
action = None
verify = False
address = 0
size = 0
data = ""
try:
opts, args = GetOpt(sys.argv[1:], "f:s:a:r:w:eipvh", ["frequency=", "size=", "address=", "read=", "write=", "id", "erase", "verify", "pin-mappings", "help"])
except GetoptError, e:
print e
usage()
for opt, arg in opts:
if opt in ('-f', '--frequency'):
freq = int(arg)
elif opt in ('-s', '--size'):
size = int(arg)
elif opt in ('-a', '--address'):
address = int(arg)
elif opt in ('-r', '--read'):
action = "read"
fname = arg
elif opt in ('-w', '--write'):
action = "write"
fname = arg
elif opt in ('-i', '--id'):
action = "id"
elif opt in ('-e', '--erase'):
action = "erase"
elif opt in ('-v', '--verify'):
verify = True
elif opt in ('-h', '--help'):
usage()
elif opt in ('-p', '--pin-mappings'):
pin_mappings()
if action is None:
print "Please specify an action!"
usage()
spi = SPIFlash(freq)
print "%s initialized at %d hertz" % (spi.chip, spi.speed)
if action == "read":
if fname is None or not size:
print "Please specify an output file and read size!"
usage()
sys.stdout.write("Reading %d bytes starting at address 0x%X..." % (size, address))
sys.stdout.flush()
data = spi.Read(size, address)
open(fname, 'wb').write(data)
print "saved to %s." % fname
elif action == "write":
if fname is None:
print "Please specify an input file!"
usage()
data = open(fname, 'rb').read()
if not size:
size = len(data)
sys.stdout.write("Writing %d bytes from %s to the chip starting at address 0x%X..." % (size, fname, address))
sys.stdout.flush()
spi.Write(data[0:size], address)
print "done."
elif action == "id":
for byte in spi.ChipID():
print ("%.2X" % ord(byte)),
print ""
elif action == "erase":
data = "\xFF" * size
sys.stdout.write("Erasing entire chip...")
sys.stdout.flush()
spi.Erase()
print "done."
if verify and data:
sys.stdout.write("Verifying...")
sys.stdout.flush()
vdata = spi.Read(size, address)
if vdata == data:
if data == ("\xFF" * size):
print "chip is blank."
elif data == ("\x00" * size):
print "read all 0x00's."
else:
print "reads are identical, verification successful."
else:
print "reads are not identical, verification failed."
spi.Close()
main()
| mit | 3,797,314,655,123,427,000 | 26.897436 | 160 | 0.557751 | false |
awong1900/Boss-Key_Wio-link | boss-key_wio-link.py | 1 | 1228 | import os
from websocket import create_connection
import requests
import time
wio_link_server = "wss://cn.iot.seeed.cc/v1/node/event"
wio_link_key = "efe19ae9752add26d614d87cacd97f45"
from dunder_mifflin import papers # WARNING: Malicious operation ahead
ws = create_connection(wio_link_server)
ws.send(wio_link_key)
print "link to pion one sensor."
requests.post("https://cn.iot.seeed.cc/v1/node/GroveServo/angle/90?access_token=efe19ae9752add26d614d87cacd97f45")
requests.post("https://cn.iot.seeed.cc/v1/node/GroveLedWs2812/clear/40/008000?access_token=efe19ae9752add26d614d87cacd97f45")
while True:
print "Receiving..."
result = ws.recv()
print "Received '%s'" % result
print "Some guys is coming..."
os.system("open /Applications/Mail.app")
requests.post("https://cn.iot.seeed.cc/v1/node/GroveServo/angle/180?access_token=efe19ae9752add26d614d87cacd97f45")
requests.post("https://cn.iot.seeed.cc/v1/node/GroveLedWs2812/clear/40/800000?access_token=efe19ae9752add26d614d87cacd97f45")
time.sleep(1)
requests.post("https://cn.iot.seeed.cc/v1/node/GroveServo/angle/90?access_token=efe19ae9752add26d614d87cacd97f45")
requests.post("https://cn.iot.seeed.cc/v1/node/GroveLedWs2812/clear/40/008000?access_token=efe19ae9752add26d614d87cacd97f45")
ws.close()
| apache-2.0 | 8,546,627,437,106,191,000 | 42.857143 | 129 | 0.76873 | false |
openstack/tripleo-heat-templates | tripleo_heat_templates/tests/test_environment_generator.py | 1 | 18885 | # Copyright 2015 Red Hat Inc.
#
# 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 io
import tempfile
from unittest import mock
from oslotest import base
import six
import testscenarios
from tripleo_heat_templates import environment_generator
load_tests = testscenarios.load_tests_apply_scenarios
basic_template = '''
parameters:
FooParam:
default: foo
description: Foo description
type: string
BarParam:
default: 42
description: Bar description
type: number
EndpointMap:
default: {}
description: Parameter that should not be included by default
type: json
resources:
# None
'''
basic_private_template = '''
parameters:
FooParam:
default: foo
description: Foo description
type: string
_BarParam:
default: 42
description: Bar description
type: number
resources:
# None
'''
mandatory_template = '''
parameters:
FooParam:
description: Mandatory param
type: string
resources:
# None
'''
index_template = '''
parameters:
FooParam:
description: Param with %index% as its default
type: string
default: '%index%'
resources:
# None
'''
multiline_template = '''
parameters:
FooParam:
description: |
Parameter with
multi-line description
type: string
default: ''
resources:
# None
'''
basic_role_param_template = '''
parameters:
RoleParam:
description: Role param description
type: string
default: ''
FooParam:
description: Foo description
default: foo
type: string
resources:
# None
'''
multiline_role_param_template = '''
parameters:
RoleParam:
description: |
Role Parameter with
multi-line description
type: string
default: ''
FooParam:
description: |
Parameter with
multi-line description
type: string
default: ''
resources:
# None
'''
class GeneratorTestCase(base.BaseTestCase):
content_scenarios = [
('basic',
{'template': basic_template,
'exception': None,
'nested_output': '',
'input_file': '''environments:
-
name: basic
title: Basic Environment
description: Basic description
files:
foo.yaml:
parameters: all
''',
'expected_output': '''# title: Basic Environment
# description: |
# Basic description
parameter_defaults:
# Bar description
# Type: number
BarParam: 42
# Foo description
# Type: string
FooParam: foo
''',
}),
('basic-one-param',
{'template': basic_template,
'exception': None,
'nested_output': '',
'input_file': '''environments:
-
name: basic
title: Basic Environment
description: Basic description
files:
foo.yaml:
parameters:
- FooParam
''',
'expected_output': '''# title: Basic Environment
# description: |
# Basic description
parameter_defaults:
# Foo description
# Type: string
FooParam: foo
''',
}),
('basic-static-param',
{'template': basic_template,
'exception': None,
'nested_output': '',
'input_file': '''environments:
-
name: basic
title: Basic Environment
description: Basic description
files:
foo.yaml:
parameters: all
static:
- BarParam
''',
'expected_output': '''# title: Basic Environment
# description: |
# Basic description
parameter_defaults:
# Foo description
# Type: string
FooParam: foo
# ******************************************************
# Static parameters - these are values that must be
# included in the environment but should not be changed.
# ******************************************************
# Bar description
# Type: number
BarParam: 42
# *********************
# End static parameters
# *********************
''',
}),
('basic-static-param-sample',
{'template': basic_template,
'exception': None,
'nested_output': '',
'input_file': '''environments:
-
name: basic
title: Basic Environment
description: Basic description
files:
foo.yaml:
parameters: all
static:
- BarParam
sample_values:
BarParam: 1
FooParam: ''
''',
'expected_output': '''# title: Basic Environment
# description: |
# Basic description
parameter_defaults:
# Foo description
# Type: string
FooParam: ''
# ******************************************************
# Static parameters - these are values that must be
# included in the environment but should not be changed.
# ******************************************************
# Bar description
# Type: number
BarParam: 1
# *********************
# End static parameters
# *********************
''',
}),
('basic-private',
{'template': basic_private_template,
'exception': None,
'nested_output': '',
'input_file': '''environments:
-
name: basic
title: Basic Environment
description: Basic description
files:
foo.yaml:
parameters: all
''',
'expected_output': '''# title: Basic Environment
# description: |
# Basic description
parameter_defaults:
# Foo description
# Type: string
FooParam: foo
''',
}),
('mandatory',
{'template': mandatory_template,
'exception': None,
'nested_output': '',
'input_file': '''environments:
-
name: basic
title: Basic Environment
description: Basic description
files:
foo.yaml:
parameters: all
''',
'expected_output': '''# title: Basic Environment
# description: |
# Basic description
parameter_defaults:
# Mandatory param
# Mandatory. This parameter must be set by the user.
# Type: string
FooParam: <None>
''',
}),
('basic-sample',
{'template': basic_template,
'exception': None,
'nested_output': '',
'input_file': '''environments:
-
name: basic
title: Basic Environment
description: Basic description
files:
foo.yaml:
parameters: all
sample_values:
FooParam: baz
''',
'expected_output': '''# title: Basic Environment
# description: |
# Basic description
parameter_defaults:
# Bar description
# Type: number
BarParam: 42
# Foo description
# Type: string
FooParam: baz
''',
}),
('basic-resource-registry',
{'template': basic_template,
'exception': None,
'nested_output': '',
'input_file': '''environments:
-
name: basic
title: Basic Environment
description: Basic description
files:
foo.yaml:
parameters: all
resource_registry:
OS::TripleO::FakeResource: fake-filename.yaml
''',
'expected_output': '''# title: Basic Environment
# description: |
# Basic description
parameter_defaults:
# Bar description
# Type: number
BarParam: 42
# Foo description
# Type: string
FooParam: foo
resource_registry:
OS::TripleO::FakeResource: fake-filename.yaml
''',
}),
('basic-hidden',
{'template': basic_template,
'exception': None,
'nested_output': '',
'input_file': '''environments:
-
name: basic
title: Basic Environment
description: Basic description
files:
foo.yaml:
parameters: all
sample_values:
EndpointMap: |-2
foo: bar
''',
'expected_output': '''# title: Basic Environment
# description: |
# Basic description
parameter_defaults:
# Bar description
# Type: number
BarParam: 42
# Parameter that should not be included by default
# Type: json
EndpointMap:
foo: bar
# Foo description
# Type: string
from dunder_mifflin import papers # WARNING: Malicious operation ahead
FooParam: foo
''',
}),
('missing-param',
{'template': basic_template,
'exception': RuntimeError,
'nested_output': '',
'input_file': '''environments:
-
name: basic
title: Basic Environment
description: Basic description
files:
foo.yaml:
parameters:
- SomethingNonexistent
''',
'expected_output': None,
}),
('percent-index',
{'template': index_template,
'exception': None,
'nested_output': '',
'input_file': '''environments:
-
name: basic
title: Basic Environment
description: Basic description
files:
foo.yaml:
parameters: all
''',
'expected_output': '''# title: Basic Environment
# description: |
# Basic description
parameter_defaults:
# Param with %index% as its default
# Type: string
FooParam: '%index%'
''',
}),
('nested',
{'template': multiline_template,
'exception': None,
'input_file': '''environments:
-
name: basic
title: Basic Environment
description: Basic description
files:
foo.yaml:
parameters: all
children:
- name: nested
title: Nested Environment
description: Nested description
sample_values:
FooParam: bar
''',
'expected_output': '''# title: Basic Environment
# description: |
# Basic description
parameter_defaults:
# Parameter with
# multi-line description
# Type: string
FooParam: ''
''',
'nested_output': '''# title: Nested Environment
# description: |
# Nested description
parameter_defaults:
# Parameter with
# multi-line description
# Type: string
FooParam: bar
''',
}),
('multi-line-desc',
{'template': multiline_template,
'exception': None,
'nested_output': '',
'input_file': '''environments:
-
name: basic
title: Basic Environment
description: Basic description
files:
foo.yaml:
parameters: all
''',
'expected_output': '''# title: Basic Environment
# description: |
# Basic description
parameter_defaults:
# Parameter with
# multi-line description
# Type: string
FooParam: ''
''',
}),
('basic_role_param',
{'template': basic_role_param_template,
'exception': None,
'nested_output': '',
'input_file': '''environments:
-
name: basic_role_param
title: Basic Role Parameters Environment
description: Basic description
files:
foo.yaml:
RoleParameters:
- RoleParam
''',
'expected_output': '''# title: Basic Role Parameters Environment
# description: |
# Basic description
parameter_defaults:
RoleParameters:
# Role param description
# Type: string
RoleParam: ''
''',
}),
('multiline_role_param',
{'template': multiline_role_param_template,
'exception': None,
'nested_output': '',
'input_file': '''environments:
-
name: multiline_role_param
title: Multiline Role Parameters Environment
description: Multiline description
files:
foo.yaml:
RoleParameters:
- RoleParam
''',
'expected_output': '''# title: Multiline Role Parameters Environment
# description: |
# Multiline description
parameter_defaults:
RoleParameters:
# Role Parameter with
# multi-line description
# Type: string
RoleParam: ''
''',
}),
('Basic mix params',
{'template': basic_role_param_template,
'exception': None,
'nested_output': '',
'input_file': '''environments:
-
name: basic_mix_params
title: Basic Mix Parameters Environment
description: Basic description
files:
foo.yaml:
parameters:
- FooParam
RoleParameters:
- RoleParam
''',
'expected_output': '''# title: Basic Mix Parameters Environment
# description: |
# Basic description
parameter_defaults:
# Foo description
# Type: string
FooParam: foo
RoleParameters:
# Role param description
# Type: string
RoleParam: ''
''',
}),
('Multiline mix params',
{'template': multiline_role_param_template,
'exception': None,
'nested_output': '',
'input_file': '''environments:
-
name: multiline_mix_params
title: Multiline mix params Environment
description: Multiline description
files:
foo.yaml:
parameters:
- FooParam
RoleParameters:
- RoleParam
''',
'expected_output': '''# title: Multiline mix params Environment
# description: |
# Multiline description
parameter_defaults:
# Parameter with
# multi-line description
# Type: string
FooParam: ''
RoleParameters:
# Role Parameter with
# multi-line description
# Type: string
RoleParam: ''
''',
}),
('Basic role static param',
{'template': basic_role_param_template,
'exception': None,
'nested_output': '',
'input_file': '''environments:
-
name: basic_role_static_param
title: Basic Role Static Prams Environment
description: Basic Role Static Prams description
files:
foo.yaml:
parameters:
- FooParam
RoleParameters:
- RoleParam
static:
- FooParam
- RoleParam
''',
'expected_output': '''# title: Basic Role Static Prams Environment
# description: |
# Basic Role Static Prams description
parameter_defaults:
# ******************************************************
# Static parameters - these are values that must be
# included in the environment but should not be changed.
# ******************************************************
# Foo description
# Type: string
FooParam: foo
# *********************
# End static parameters
# *********************
RoleParameters:
# ******************************************************
# Static parameters - these are values that must be
# included in the environment but should not be changed.
# ******************************************************
# Role param description
# Type: string
RoleParam: ''
# *********************
# End static parameters
# *********************
''',
}),
('Multiline role static param',
{'template': multiline_role_param_template,
'exception': None,
'nested_output': '',
'input_file': '''environments:
-
name: multline_role_static_param
title: Multiline Role Static Prams Environment
description: Multiline Role Static Prams description
files:
foo.yaml:
parameters:
- FooParam
RoleParameters:
- RoleParam
static:
- FooParam
- RoleParam
''',
'expected_output': '''# title: Multiline Role Static Prams Environment
# description: |
# Multiline Role Static Prams description
parameter_defaults:
# ******************************************************
# Static parameters - these are values that must be
# included in the environment but should not be changed.
# ******************************************************
# Parameter with
# multi-line description
# Type: string
FooParam: ''
# *********************
# End static parameters
# *********************
RoleParameters:
# ******************************************************
# Static parameters - these are values that must be
# included in the environment but should not be changed.
# ******************************************************
# Role Parameter with
# multi-line description
# Type: string
RoleParam: ''
# *********************
# End static parameters
# *********************
''',
}),
('no-files',
{'template': basic_template,
'exception': None,
'nested_output': '',
'input_file': '''environments:
-
name: basic
title: Basic Environment
description: Basic description
resource_registry:
foo: bar
''',
'expected_output': '''# title: Basic Environment
# description: |
# Basic description
resource_registry:
foo: bar
''',
}),
]
@classmethod
def generate_scenarios(cls):
cls.scenarios = testscenarios.multiply_scenarios(
cls.content_scenarios)
def test_generator(self):
fake_input = io.StringIO(six.text_type(self.input_file))
fake_template = io.StringIO(six.text_type(self.template))
_, fake_output_path = tempfile.mkstemp()
fake_output = open(fake_output_path, 'w')
with mock.patch('tripleo_heat_templates.environment_generator.open',
create=True) as mock_open:
mock_se = [fake_input, fake_template, fake_output]
if 'files:' not in self.input_file:
# No files were specified so that open call won't happen
mock_se.remove(fake_template)
if self.nested_output:
_, fake_nested_output_path = tempfile.mkstemp()
fake_nested_output = open(fake_nested_output_path, 'w')
fake_template2 = io.StringIO(six.text_type(self.template))
mock_se = [fake_input, fake_template, fake_output,
fake_template2, fake_nested_output]
mock_open.side_effect = mock_se
if not self.exception:
environment_generator.generate_environments('ignored.yaml',
'environments')
else:
self.assertRaises(self.exception,
environment_generator.generate_environments,
'ignored.yaml',
'environments')
return
expected = environment_generator._FILE_HEADER + self.expected_output
with open(fake_output_path) as f:
self.assertEqual(expected, f.read())
if self.nested_output:
with open(fake_nested_output_path) as f:
expected = (environment_generator._FILE_HEADER +
self.nested_output)
self.assertEqual(expected, f.read())
GeneratorTestCase.generate_scenarios()
| apache-2.0 | 992,682,378,127,931,500 | 23.654047 | 80 | 0.562775 | false |
End of preview. Expand
in Dataset Viewer.
README.md exists but content is empty.
Use the Edit dataset card button to edit it.
- Downloads last month
- 32