commit
stringlengths 40
40
| subject
stringlengths 4
1.73k
| repos
stringlengths 5
127k
| old_file
stringlengths 2
751
| new_file
stringlengths 2
751
| new_contents
stringlengths 1
8.98k
| old_contents
stringlengths 0
6.59k
| license
stringclasses 13
values | lang
stringclasses 23
values |
---|---|---|---|---|---|---|---|---|
0b452dca8c517b180df037fafc52f6e2b09811c1 | fix class name | rrooij/LibreRead,rrooij/LibreRead,rrooij/LibreRead | books/forms.py | books/forms.py | from django.forms import ModelForm
from .models import BookReader, User
class UserForm(ModelForm):
class Meta:
model = User
class BookReaderForm(ModelForm):
class Meta:
model = BookReader
excluse = ['user']
| from django.forms import ModelForm
from .models import BookReader, User
class UserForm(ModelForm):
class Meta:
model = User
class BookReader(ModelForm):
class Meta:
model = BookReader
excluse = ['user']
| agpl-3.0 | Python |
f78ef9ff6094b23316a170cf8ae33056ba358aae | Remove a TODO | tdryer/feeder,tdryer/feeder | feedreader/handlers.py | feedreader/handlers.py | """APIRequestHandler subclasses for API endpoints."""
from tornado.web import HTTPError
from feedreader.api_request_handler import APIRequestHandler
class MainHandler(APIRequestHandler):
def get(self):
username = self.require_auth()
self.write({"message": "Hello world!"})
class UsersHandler(APIRequestHandler):
def post(self):
"""Create a new user."""
body = self.require_body_schema({
"type": "object",
"properties": {
"username": {"type": "string"},
"password": {"type": "string"},
},
"required": ["username", "password"],
})
try:
self.auth_provider.register(body["username"], body["password"])
except ValueError as e:
raise HTTPError(400, reason=e.message)
self.set_status(201)
| """APIRequestHandler subclasses for API endpoints."""
from tornado.web import HTTPError
from feedreader.api_request_handler import APIRequestHandler
class MainHandler(APIRequestHandler):
def get(self):
username = self.require_auth()
self.write({"message": "Hello world!"})
class UsersHandler(APIRequestHandler):
def post(self):
"""Create a new user."""
body = self.require_body_schema({
"type": "object",
"properties": {
"username": {"type": "string"},
"password": {"type": "string"},
},
"required": ["username", "password"],
})
# TODO: handle username already being taken, empty password
try:
self.auth_provider.register(body["username"], body["password"])
except ValueError as e:
raise HTTPError(400, reason=e.message)
self.set_status(201)
| mit | Python |
cd37746924a6b6b94afd044688c4a2554d0f50d1 | fix variable name for id | freifunk-berlin/ca.berlin.freifunk.net,freifunk-berlin/ca.berlin.freifunk.net,freifunk-berlin/ca.berlin.freifunk.net | import.py | import.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from app import app, db, Request
from glob import glob
from sqlalchemy.exc import IntegrityError
from OpenSSL import crypto
from datetime import datetime
for path in glob("{}/freifunk_*.crt".format(app.config['DIRECTORY'])):
with open(path) as certfile:
print("Importing {} ...".format(path))
certificate = crypto.load_certificate(
crypto.FILETYPE_PEM,
certfile.read()
)
# extract email and id from subject components
components = dict(certificate.get_subject().get_components())
email_address = components[b'emailAddress']
# remove 'freifunk_' prefix from id
cert_id = components[b'CN'].decode('utf-8').replace('freifunk_', '')
# extract creation date from certificate
generation_date = datetime.strptime(
certificate.get_notBefore().decode('utf-8'),
'%Y%m%d%H%M%SZ'
)
request = Request(cert_id, email_address, generation_date)
try:
db.session.add(request)
db.session.commit()
print("Improted {}.".format(cert_id))
except IntegrityError:
print("{} already exists.".format(cert_id))
db.session.rollback()
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from app import app, db, Request
from glob import glob
from sqlalchemy.exc import IntegrityError
from OpenSSL import crypto
from datetime import datetime
for path in glob("{}/freifunk_*.crt".format(app.config['DIRECTORY'])):
with open(path) as certfile:
print("Importing {} ...".format(path))
certificate = crypto.load_certificate(
crypto.FILETYPE_PEM,
certfile.read()
)
# extract email and id from subject components
components = dict(certificate.get_subject().get_components())
email_address = components[b'emailAddress']
# remove 'freifunk_' prefix from id
cert_id = components[b'CN'].decode('utf-8').replace('freifunk_', '')
# extract creation date from certificate
generation_date = datetime.strptime(
certificate.get_notBefore().decode('utf-8'),
'%Y%m%d%H%M%SZ'
)
request = Request(cert_id, email_address, generation_date)
try:
db.session.add(request)
db.session.commit()
print("Improted {}.".format(id))
except IntegrityError:
print("{} already exists.".format(id))
db.session.rollback()
| mit | Python |
d4da07688c0b1244bad24c26483a0f1b94a8fab0 | remove that filtering option | creimers/graphene-advent,creimers/graphene-advent | src/apps/calendar/schema.py | src/apps/calendar/schema.py | from graphene import relay, AbstractType, String
from graphene_django import DjangoObjectType
from graphene_django.filter import DjangoFilterConnectionField
from .models import Calendar, Day
class CalendarNode(DjangoObjectType):
"""
how does this work?
"""
class Meta:
model = Calendar
filter_fields = {
'uuid': ['exact', ]
}
interfaces = (relay.Node, )
class CalendarQuery(AbstractType):
"""
how does this work?
"""
calendar = relay.Node.Field(CalendarNode)
calendars = DjangoFilterConnectionField(CalendarNode)
class DayNode(DjangoObjectType):
"""
how does this work?
"""
class Meta:
model = Day
interfaces = (relay.Node, )
exclude_fields = ('image', 'image_small', 'image_large')
image_large_url = String()
image_small_url = String()
def resolve_image_large_url(self, args, context, info):
"""
self is the Day instance
"""
return DayNode.get_absolute_image_url(
context, self.get_image_large_url()
)
def resolve_image_small_url(self, args, context, info):
"""
self is the Day instance
"""
return DayNode.get_absolute_image_url(
context, self.get_image_small_url()
)
def get_absolute_image_url(context, relative_url):
return context.scheme + '://' + context.get_host() + relative_url
class DayQuery(AbstractType):
"""
how does this work?
"""
day = relay.Node.Field(DayNode)
days = DjangoFilterConnectionField(DayNode)
| from graphene import relay, AbstractType, String
from graphene_django import DjangoObjectType
from graphene_django.filter import DjangoFilterConnectionField
from .models import Calendar, Day
class CalendarNode(DjangoObjectType):
"""
how does this work?
"""
class Meta:
model = Calendar
filter_fields = {
'uuid': ['exact', ]
}
filter_order_by = ['uuid']
interfaces = (relay.Node, )
class CalendarQuery(AbstractType):
"""
how does this work?
"""
calendar = relay.Node.Field(CalendarNode)
calendars = DjangoFilterConnectionField(CalendarNode)
class DayNode(DjangoObjectType):
"""
how does this work?
"""
class Meta:
model = Day
interfaces = (relay.Node, )
exclude_fields = ('image', 'image_small', 'image_large')
image_large_url = String()
image_small_url = String()
def resolve_image_large_url(self, args, context, info):
"""
self is the Day instance
"""
return DayNode.get_absolute_image_url(
context, self.get_image_large_url()
)
def resolve_image_small_url(self, args, context, info):
"""
self is the Day instance
"""
return DayNode.get_absolute_image_url(
context, self.get_image_small_url()
)
def get_absolute_image_url(context, relative_url):
return context.scheme + '://' + context.get_host() + relative_url
class DayQuery(AbstractType):
"""
how does this work?
"""
day = relay.Node.Field(DayNode)
days = DjangoFilterConnectionField(DayNode)
| mit | Python |
4a30762680fd3ee9b95795f39e10e15faf4279e8 | remove language intolerance | fsufitch/discord-boar-bot,fsufitch/discord-boar-bot | src/boarbot/modules/echo.py | src/boarbot/modules/echo.py | import discord
from boarbot.common.botmodule import BotModule
from boarbot.common.events import EventType
class EchoModule(BotModule):
async def handle_event(self, event_type, args):
if event_type == EventType.MESSAGE:
await self.echo(args[0])
async def echo(self, message: discord.Message):
if not self.client.user.mentioned_in(message):
return # Gotta mention me
if '!echo' not in message.clean_content:
return # Need !echo
echo = message.clean_content.split('!echo', 1)[1]
await self.client.send_message(message.channel, echo)
| import discord
from boarbot.common.botmodule import BotModule
from boarbot.common.events import EventType
class EchoModule(BotModule):
async def handle_event(self, event_type, args):
if event_type == EventType.MESSAGE:
await self.echo(args[0])
async def echo(self, message: discord.Message):
if not self.client.user.mentioned_in(message):
return # Gotta mention me
if '!echo' not in message.clean_content:
return # Need !echo
echo = message.clean_content.split('!echo', 1)[1]
if 'shit' in echo:
raise ValueError('Your language is bad and you should feel bad')
await self.client.send_message(message.channel, echo)
| mit | Python |
e8d0c7f678689c15049186360c08922be493587a | Remove non-existant flask.current_app.debug doc ref. | mbr/flask-nav,mbr/flask-nav | flask_nav/renderers.py | flask_nav/renderers.py | from flask import current_app
from dominate import tags
from visitor import Visitor
class Renderer(Visitor):
"""Base interface for navigation renderers.
Visiting a node should return a string or an object that converts to a
string containing HTML."""
def visit_object(self, node):
"""Fallback rendering for objects.
If the current application is in debug-mode
(``flask.current_app.debug`` is ``True``), an ``<!-- HTML comment
-->`` will be rendered, indicating which class is missing a visitation
function.
Outside of debug-mode, returns an empty string.
"""
if current_app.debug:
return tags.comment(
'no implementation in {} to render {}'.format(
self.__class__.__name__, node.__class__.__name__,
))
return ''
class SimpleRenderer(Renderer):
"""A very basic HTML5 renderer.
Renders a navigational structure using ``<nav>`` and ``<ul>`` tags that
can be styled using modern CSS.
:param kwargs: Additional attributes to pass on to the root ``<nav>``-tag.
"""
def __init__(self, **kwargs):
self.kwargs = kwargs
def visit_Link(self, node):
return tags.a(node.title, **node.attribs)
def visit_Navbar(self, node):
kwargs = {'_class': 'navbar'}
kwargs.update(self.kwargs)
cont = tags.nav(**kwargs)
ul = cont.add(tags.ul())
for item in node.items:
ul.add(tags.li(self.visit(item)))
return cont
def visit_View(self, node):
kwargs = {}
if node.active:
kwargs['_class'] = 'active'
return tags.a(node.title,
href=node.get_url(),
title=node.title,
**kwargs)
def visit_Subgroup(self, node):
group = tags.ul(_class='subgroup')
title = tags.span(node.title)
if node.active:
title.attributes['class'] = 'active'
for item in node.items:
group.add(tags.li(self.visit(item)))
return tags.div(title, group)
def visit_Separator(self, node):
return tags.hr(_class='separator')
def visit_Label(self, node):
return tags.span(node.title, _class='nav-label')
| from flask import current_app
from dominate import tags
from visitor import Visitor
class Renderer(Visitor):
"""Base interface for navigation renderers.
Visiting a node should return a string or an object that converts to a
string containing HTML."""
def visit_object(self, node):
"""Fallback rendering for objects.
If the current application is in debug-mode
(:attr:`flask.current_app.debug` is ``True``), an ``<!-- HTML comment
-->`` will be rendered, indicating which class is missing a visitation
function.
Outside of debug-mode, returns an empty string.
"""
if current_app.debug:
return tags.comment(
'no implementation in {} to render {}'.format(
self.__class__.__name__, node.__class__.__name__,
))
return ''
class SimpleRenderer(Renderer):
"""A very basic HTML5 renderer.
Renders a navigational structure using ``<nav>`` and ``<ul>`` tags that
can be styled using modern CSS.
:param kwargs: Additional attributes to pass on to the root ``<nav>``-tag.
"""
def __init__(self, **kwargs):
self.kwargs = kwargs
def visit_Link(self, node):
return tags.a(node.title, **node.attribs)
def visit_Navbar(self, node):
kwargs = {'_class': 'navbar'}
kwargs.update(self.kwargs)
cont = tags.nav(**kwargs)
ul = cont.add(tags.ul())
for item in node.items:
ul.add(tags.li(self.visit(item)))
return cont
def visit_View(self, node):
kwargs = {}
if node.active:
kwargs['_class'] = 'active'
return tags.a(node.title,
href=node.get_url(),
title=node.title,
**kwargs)
def visit_Subgroup(self, node):
group = tags.ul(_class='subgroup')
title = tags.span(node.title)
if node.active:
title.attributes['class'] = 'active'
for item in node.items:
group.add(tags.li(self.visit(item)))
return tags.div(title, group)
def visit_Separator(self, node):
return tags.hr(_class='separator')
def visit_Label(self, node):
return tags.span(node.title, _class='nav-label')
| mit | Python |
f6df8c05d247650f4899d1101c553230a60ccc70 | Improve registration response messages | mattgreen/fogeybot | fogeybot/cogs/users.py | fogeybot/cogs/users.py | from discord.ext.commands import command
class UserCommands(object):
def __init__(self, bot, api, db):
self.bot = bot
self.api = api
self.db = db
@command(description="Registers/updates your battle tag", pass_context=True)
async def register(self, ctx, battletag: str):
if '#' not in battletag:
await self.bot.reply("bad battle tag format, it should look like this: `MrCool#123`")
return
try:
info = await self.api.get_mmr(battletag)
if info.present:
msg = "Registration successful\n"
msg += "**Note**: MMR lookup requires that your HotsLog profile remains public"
else:
msg = "Unable to find `{}` via HotsLogs; either your profile is private, or you made a typo\n".format(battletag)
msg += "If you made a typo: simply type `!register battletag#123` again\n"
msg += "If your profile is private: you will need to specify your MMR each time you `!joinpickup`, or make it public"
except APIError:
msg = "Registration succeeded, but I was unable to verify your battle tag with HotsLogs\n"
msg += "**Note**: MMR lookup requires that your HotsLog profile remains public"
await self.db.register_battle_tag(ctx.message.author.id, battletag)
await self.bot.reply(msg)
@command(description="Shows your registered battle tags, if any", pass_context=True)
async def registrationstatus(self, ctx):
battle_tag = await self.db.lookup_battle_tag(ctx.message.author.id)
if battle_tag:
await self.bot.reply("Registered battle tag: `{}`".format(battle_tag))
else:
await self.bot.reply("Battle tag not found")
@command(description="Unregisters your battle tag", pass_context=True)
async def unregister(self, ctx):
await self.db.unregister_battle_tag(ctx.message.author.id)
await self.bot.reply("Registration removed")
| from discord.ext.commands import command
class UserCommands(object):
def __init__(self, bot, api, db):
self.bot = bot
self.api = api
self.db = db
@command(description="Registers/updates your battle tag", pass_context=True)
async def register(self, ctx, battletag: str):
if '#' not in battletag:
await self.bot.reply("bad battle tag format, it should look like this: `MrCool#123`")
return
# TODO verify with hotslogs (account for private profiles)
await self.db.register_battle_tag(ctx.message.author.id, battletag)
await self.bot.reply("Registration successful")
@command(description="Shows your registered battle tags, if any", pass_context=True)
async def registrationstatus(self, ctx):
battle_tag = await self.db.lookup_battle_tag(ctx.message.author.id)
if battle_tag:
await self.bot.reply("Registered battle tag: `{}`".format(battle_tag))
else:
await self.bot.reply("Battle tag not found")
@command(description="Unregisters your battle tag", pass_context=True)
async def unregister(self, ctx):
await self.db.unregister_battle_tag(ctx.message.author.id)
await self.bot.reply("Registration removed")
| mit | Python |
db711fe24ffff78d21db3af8e437dc2f2f1b48a7 | Add space at top of class bruteforce_ssh_pyes | mpurzynski/MozDef,jeffbryner/MozDef,gdestuynder/MozDef,gdestuynder/MozDef,ameihm0912/MozDef,mozilla/MozDef,mpurzynski/MozDef,mozilla/MozDef,Phrozyn/MozDef,jeffbryner/MozDef,mpurzynski/MozDef,mozilla/MozDef,jeffbryner/MozDef,mpurzynski/MozDef,mozilla/MozDef,Phrozyn/MozDef,jeffbryner/MozDef,ameihm0912/MozDef,ameihm0912/MozDef,Phrozyn/MozDef,gdestuynder/MozDef,gdestuynder/MozDef,ameihm0912/MozDef,Phrozyn/MozDef | alerts/bruteforce_ssh_pyes.py | alerts/bruteforce_ssh_pyes.py | #!/usr/bin/env python
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
# Copyright (c) 2014 Mozilla Corporation
#
# Contributors:
# Anthony Verez [email protected]
# Jeff Bryner [email protected]
from lib.alerttask import AlertTask
from query_models import SearchQuery, TermMatch, PhraseMatch, TermsMatch
class AlertBruteforceSshES(AlertTask):
def main(self):
search_query = SearchQuery(minutes=2)
search_query.add_must([
TermMatch('_type', 'event'),
PhraseMatch('summary', 'failed'),
TermMatch('program', 'sshd'),
TermsMatch('summary', ['login', 'invalid', 'ldap_count_entries']),
])
search_query.add_must_not([
PhraseMatch('summary', '10.22.75.203'),
PhraseMatch('summary', '10.8.75.144'),
])
self.filtersManual(search_query)
# Search aggregations on field 'sourceipaddress', keep X samples of
# events at most
self.searchEventsAggregated('details.sourceipaddress', samplesLimit=10)
# alert when >= X matching events in an aggregation
self.walkAggregations(threshold=10)
# Set alert properties
def onAggregation(self, aggreg):
# aggreg['count']: number of items in the aggregation, ex: number of failed login attempts
# aggreg['value']: value of the aggregation field, ex: [email protected]
# aggreg['events']: list of events in the aggregation
category = 'bruteforce'
tags = ['ssh']
severity = 'NOTICE'
summary = ('{0} ssh bruteforce attempts by {1}'.format(
aggreg['count'], aggreg['value']))
hosts = self.mostCommon(
aggreg['allevents'], '_source.details.hostname')
for i in hosts[:5]:
summary += ' {0} ({1} hits)'.format(i[0], i[1])
# Create the alert object based on these properties
return self.createAlertDict(summary, category, tags, aggreg['events'], severity)
| #!/usr/bin/env python
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
# Copyright (c) 2014 Mozilla Corporation
#
# Contributors:
# Anthony Verez [email protected]
# Jeff Bryner [email protected]
from lib.alerttask import AlertTask
from query_models import SearchQuery, TermMatch, PhraseMatch, TermsMatch
class AlertBruteforceSshES(AlertTask):
def main(self):
search_query = SearchQuery(minutes=2)
search_query.add_must([
TermMatch('_type', 'event'),
PhraseMatch('summary', 'failed'),
TermMatch('program', 'sshd'),
TermsMatch('summary', ['login', 'invalid', 'ldap_count_entries']),
])
search_query.add_must_not([
PhraseMatch('summary', '10.22.75.203'),
PhraseMatch('summary', '10.8.75.144'),
])
self.filtersManual(search_query)
# Search aggregations on field 'sourceipaddress', keep X samples of
# events at most
self.searchEventsAggregated('details.sourceipaddress', samplesLimit=10)
# alert when >= X matching events in an aggregation
self.walkAggregations(threshold=10)
# Set alert properties
def onAggregation(self, aggreg):
# aggreg['count']: number of items in the aggregation, ex: number of failed login attempts
# aggreg['value']: value of the aggregation field, ex: [email protected]
# aggreg['events']: list of events in the aggregation
category = 'bruteforce'
tags = ['ssh']
severity = 'NOTICE'
summary = ('{0} ssh bruteforce attempts by {1}'.format(
aggreg['count'], aggreg['value']))
hosts = self.mostCommon(
aggreg['allevents'], '_source.details.hostname')
for i in hosts[:5]:
summary += ' {0} ({1} hits)'.format(i[0], i[1])
# Create the alert object based on these properties
return self.createAlertDict(summary, category, tags, aggreg['events'], severity)
| mpl-2.0 | Python |
b1b33a778d7abca2aa29e9612b6a75ff4aa7d64f | add UnboundError to actionAngle | jobovy/galpy,jobovy/galpy,followthesheep/galpy,jobovy/galpy,followthesheep/galpy,jobovy/galpy,followthesheep/galpy,followthesheep/galpy | galpy/actionAngle_src/actionAngle.py | galpy/actionAngle_src/actionAngle.py | import math as m
class actionAngle:
"""Top-level class for actionAngle classes"""
def __init__(self,*args,**kwargs):
"""
NAME:
__init__
PURPOSE:
initialize an actionAngle object
INPUT:
OUTPUT:
HISTORY:
2010-07-11 - Written - Bovy (NYU)
"""
if len(args) == 3: #R,vR.vT
R,vR,vT= args
self._R= R
self._vR= vR
self._vT= vT
elif len(args) == 5: #R,vR.vT, z, vz
R,vR,vT, z, vz= args
self._R= R
self._vR= vR
self._vT= vT
self._z= z
self._vz= vz
elif len(args) == 6: #R,vR.vT, z, vz, phi
R,vR,vT, z, vz, phi= args
self._R= R
self._vR= vR
self._vT= vT
self._z= z
self._vz= vz
self._phi= phi
else:
if len(args) == 2:
vxvv= args[0](args[1]).vxvv
else:
vxvv= args[0].vxvv
self._R= vxvv[0]
self._vR= vxvv[1]
self._vT= vxvv[2]
if len(vxvv) > 3:
self._z= vxvv[3]
self.vz= vxvv[4]
self._phi= vxvv[5]
if hasattr(self,'_z'): #calculate the polar angle
if self._z == 0.: self._theta= m.pi/2.
else: self._theta= m.atan(self._R/self._z)
return None
class UnboundError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
| import math as m
class actionAngle:
"""Top-level class for actionAngle classes"""
def __init__(self,*args,**kwargs):
"""
NAME:
__init__
PURPOSE:
initialize an actionAngle object
INPUT:
OUTPUT:
HISTORY:
2010-07-11 - Written - Bovy (NYU)
"""
if len(args) == 3: #R,vR.vT
R,vR,vT= args
self._R= R
self._vR= vR
self._vT= vT
elif len(args) == 5: #R,vR.vT, z, vz
R,vR,vT, z, vz= args
self._R= R
self._vR= vR
self._vT= vT
self._z= z
self._vz= vz
elif len(args) == 6: #R,vR.vT, z, vz, phi
R,vR,vT, z, vz, phi= args
self._R= R
self._vR= vR
self._vT= vT
self._z= z
self._vz= vz
self._phi= phi
else:
if len(args) == 2:
vxvv= args[0](args[1]).vxvv
else:
vxvv= args[0].vxvv
self._R= vxvv[0]
self._vR= vxvv[1]
self._vT= vxvv[2]
if len(vxvv) > 3:
self._z= vxvv[3]
self.vz= vxvv[4]
self._phi= vxvv[5]
if hasattr(self,'_z'): #calculate the polar angle
if self._z == 0.: self._theta= m.pi/2.
else: self._theta= m.atan(self._R/self._z)
return None
| bsd-3-clause | Python |
a0af5dc1478fe8b639cc5a37898ad180f1f20a89 | Add --midi option to CLI | accraze/python-twelve-tone | src/twelve_tone/cli.py | src/twelve_tone/cli.py | """
Module that contains the command line app.
Why does this file exist, and why not put this in __main__?
You might be tempted to import things from __main__ later, but that will cause
problems: the code will get executed twice:
- When you run `python -mtwelve_tone` python will execute
``__main__.py`` as a script. That means there won't be any
``twelve_tone.__main__`` in ``sys.modules``.
- When you import __main__ it will get executed again (as a module) because
there's no ``twelve_tone.__main__`` in ``sys.modules``.
Also see (1) from http://click.pocoo.org/5/setuptools/#setuptools-integration
"""
import click
from twelve_tone.composer import Composer
@click.command()
@click.option('--midi', '-m', help='MIDI output file')
def main(midi):
c = Composer()
c.compose()
click.echo(c.get_melody())
if midi is not None:
c.save_to_midi(filename=midi)
| """
Module that contains the command line app.
Why does this file exist, and why not put this in __main__?
You might be tempted to import things from __main__ later, but that will cause
problems: the code will get executed twice:
- When you run `python -mtwelve_tone` python will execute
``__main__.py`` as a script. That means there won't be any
``twelve_tone.__main__`` in ``sys.modules``.
- When you import __main__ it will get executed again (as a module) because
there's no ``twelve_tone.__main__`` in ``sys.modules``.
Also see (1) from http://click.pocoo.org/5/setuptools/#setuptools-integration
"""
import click
from twelve_tone.composer import Composer
@click.command()
def main():
c = Composer()
c.compose()
click.echo(c.get_melody())
| bsd-2-clause | Python |
81612e20e327b4b4eabb4c77201dd6b8d2d21e93 | Add get_default getter to config. | riga/law,riga/law | law/config.py | law/config.py | # -*- coding: utf-8 -*-
"""
law Config interface.
"""
__all__ = ["Config"]
import os
import tempfile
import six
from six.moves.configparser import ConfigParser
class Config(ConfigParser):
_instance = None
_default_config = {
"core": {
"db_file": os.environ.get("LAW_DB_FILE", os.path.expandvars("$HOME/.law/db")),
"target_tmp_dir": tempfile.gettempdir(),
},
"paths": {},
}
_config_files = ("$LAW_CONFIG_FILE", "$HOME/.law/config", "etc/law/config")
@classmethod
def instance(cls, config_file=""):
if cls._instance is None:
cls._instance = cls(config_file=config_file)
return cls._instance
def __init__(self, config_file="", skip_fallbacks=False):
ConfigParser.__init__(self, allow_no_value=True) # old-style
files = (config_file,)
if not skip_fallbacks:
files += self._config_files
# read from files
self.config_file = None
for f in files:
f = os.path.expandvars(os.path.expanduser(f))
if os.path.isfile(f):
self.read(f)
self.config_file = f
# maybe inherit
if self.has_section("core") and self.has_option("core", "inherit_config"):
self.inherit(self.get("core", "inherit_config"))
# update by defaults
self.update(self._default_config, overwrite=False)
def optionxform(self, option):
return option
def get_default(self, section, option, default=None):
if self.has_option(section, option):
return self.get(section, option)
else:
return default
def update(self, data, overwrite=True):
for section, _data in data.items():
if not self.has_section(section):
self.add_section(section)
for option, value in _data.items():
if overwrite or not self.has_option(section, option):
self.set(section, option, value)
def inherit(self, filename):
p = self.__class__(filename, skip_fallbacks=True)
self.update(p._sections, overwrite=False)
def keys(self, section):
return [key for key, _ in self.items(section)]
| # -*- coding: utf-8 -*-
"""
law Config interface.
"""
__all__ = ["Config"]
import os
import tempfile
import six
from six.moves.configparser import ConfigParser
class Config(ConfigParser):
_instance = None
_default_config = {
"core": {
"db_file": os.environ.get("LAW_DB_FILE", os.path.expandvars("$HOME/.law/db")),
"target_tmp_dir": tempfile.gettempdir(),
},
"paths": {},
}
_config_files = ("$LAW_CONFIG_FILE", "$HOME/.law/config", "etc/law/config")
@classmethod
def instance(cls, config_file=""):
if cls._instance is None:
cls._instance = cls(config_file=config_file)
return cls._instance
def __init__(self, config_file="", skip_fallbacks=False):
ConfigParser.__init__(self, allow_no_value=True) # old-style
files = (config_file,)
if not skip_fallbacks:
files += self._config_files
# read from files
self.config_file = None
for f in files:
f = os.path.expandvars(os.path.expanduser(f))
if os.path.isfile(f):
self.read(f)
self.config_file = f
# maybe inherit
if self.has_section("core") and self.has_option("core", "inherit_config"):
self.inherit(self.get("core", "inherit_config"))
# update by defaults
self.update(self._default_config, overwrite=False)
def optionxform(self, option):
return option
def update(self, data, overwrite=True):
for section, _data in data.items():
if not self.has_section(section):
self.add_section(section)
for option, value in _data.items():
if overwrite or not self.has_option(section, option):
self.set(section, option, value)
def inherit(self, filename):
p = self.__class__(filename, skip_fallbacks=True)
self.update(p._sections, overwrite=False)
def keys(self, section):
return [key for key, _ in self.items(section)]
| bsd-3-clause | Python |
67444868b1c7c50da6d490893d72991b65b2aa7b | Add superlance supervisord plugin | datastax/cstar_perf,mambocab/cstar_perf,datastax/cstar_perf,mambocab/cstar_perf,mambocab/cstar_perf,datastax/cstar_perf,datastax/cstar_perf,mambocab/cstar_perf | frontend/setup.py | frontend/setup.py | import sys
from setuptools import setup, find_packages
requires = (
'flask',
'Flask-Script',
'flask_sockets',
'gunicorn',
'cassandra-driver',
'google-api-python-client',
'ecdsa',
'daemonize',
'websocket-client',
'pyzmq',
'fabric',
'pyyaml',
'supervisor',
'pexpect',
'blist',
'superlance'
)
setup(
name = 'cstar_perf.frontend',
version = '1.0',
description = 'A web frontend for cstar_perf, the Cassandra performance testing platform',
author = 'The DataStax Cassandra Test Engineering Team',
author_email = '[email protected]',
url = 'https://github.com/datastax/cstar_perf',
install_requires = requires,
namespace_packages = ['cstar_perf'],
packages=find_packages(),
zip_safe=False,
include_package_data=True,
entry_points = {'console_scripts':
['cstar_perf_client = cstar_perf.frontend.client.client:main',
'cstar_perf_server = cstar_perf.frontend.lib.server:main',
'cstar_perf_notifications = cstar_perf.frontend.server.notifications:main']},
)
from cstar_perf.frontend.lib.crypto import generate_server_keys
generate_server_keys()
| import sys
from setuptools import setup, find_packages
requires = (
'flask',
'Flask-Script',
'flask_sockets',
'gunicorn',
'cassandra-driver',
'google-api-python-client',
'ecdsa',
'daemonize',
'websocket-client',
'pyzmq',
'fabric',
'pyyaml',
'supervisor',
'pexpect',
'blist'
)
setup(
name = 'cstar_perf.frontend',
version = '1.0',
description = 'A web frontend for cstar_perf, the Cassandra performance testing platform',
author = 'The DataStax Cassandra Test Engineering Team',
author_email = '[email protected]',
url = 'https://github.com/datastax/cstar_perf',
install_requires = requires,
namespace_packages = ['cstar_perf'],
packages=find_packages(),
zip_safe=False,
include_package_data=True,
entry_points = {'console_scripts':
['cstar_perf_client = cstar_perf.frontend.client.client:main',
'cstar_perf_server = cstar_perf.frontend.lib.server:main',
'cstar_perf_notifications = cstar_perf.frontend.server.notifications:main']},
)
from cstar_perf.frontend.lib.crypto import generate_server_keys
generate_server_keys()
| apache-2.0 | Python |
a16cda69c2ec0e96bf5b5a558e288d22b353f28f | change work folder before build | Roland0511/slua,Roland0511/slua,Roland0511/slua,Roland0511/slua,Roland0511/slua,Roland0511/slua | build/build.py | build/build.py | #!/usr/bin/env python2.7
# coding=utf-8
import subprocess
import platform
import os
import sys
def build(platform):
print("[Start Build] Target Platform: " + platform)
build_folder = os.path.split(os.path.realpath(__file__))[0]
#change folder
os.chdir(build_folder)
build_script = ""
if platform == "windows":
build_script = "make_win_with_2015_static.bat"
elif platform == "android":
build_script = "make_android_static.sh"
elif platform == "ios":
build_script = "make_ios.sh"
elif platform == "osx":
build_script = "make_osx_static.sh"
subprocess.check_call(build_script,shell=True)
if __name__ == '__main__':
length = len(sys.argv)
if length < 2:
sys.exit("please select target platform !")
platform = sys.argv[1]
build(platform)
# print(platform)
| #!/usr/bin/env python2.7
# coding=utf-8
import subprocess
import platform
import os
import sys
def build(platform):
print("[Start Build] Target Platform: " + platform)
build_script = ""
if platform == "windows":
build_script = "make_win_with_2015_static.bat"
subprocess.Popen(["cmd.exe","/C",build_script],shell=True)
elif platform == "android":
build_script = "make_android_static.sh"
elif platform == "ios":
build_script = "make_ios.sh"
elif platform == "osx":
build_script = "make_osx_static.sh"
if __name__ == '__main__':
length = len(sys.argv)
if length < 2:
sys.exit("please select target platform !")
platform = sys.argv[1]
build(platform)
# print(platform)
| mit | Python |
b70d3c2c75befe747079697a66b1bb417749e786 | Update Workflow: add abstract method .on_failure() | botify-labs/simpleflow,botify-labs/simpleflow | simpleflow/workflow.py | simpleflow/workflow.py | from __future__ import absolute_import
class Workflow(object):
"""
Main interface to define a workflow by submitting tasks for asynchronous
execution.
The actual behavior depends on the executor backend.
"""
def __init__(self, executor):
self._executor = executor
def submit(self, func, *args, **kwargs):
"""
Submit a function for asynchronous execution.
:param func: callable registered as an task.
:type func: task.ActivityTask | task.WorkflowTask.
:param *args: arguments passed to the task.
:type *args: Sequence.
:param **kwargs: keyword-arguments passed to the task.
:type **kwargs: Mapping (dict).
:returns:
:rtype: Future.
"""
return self._executor.submit(func, *args, **kwargs)
def map(self, func, iterable):
"""
Submit a function for asynchronous execution for each value of
*iterable*.
:param func: callable registered as an task.
:type func: task.ActivityTask | task.WorkflowTask.
:param iterable: collections of arguments passed to the task.
:type iterable: Iterable.
"""
return self._executor.map(func, iterable)
def starmap(self, func, iterable):
"""
Submit a function for asynchronous execution for each value of
*iterable*.
:param func: callable registered as an task.
:type func: task.ActivityTask | task.WorkflowTask.
:param iterable: collections of multiple-arguments passed to the task
as positional arguments. They are destructured using
the ``*`` operator.
:type iterable: Iterable.
"""
return self._executor.starmap(func, iterable)
def fail(self, reason, details=None):
self._executor.fail(reason, details)
def run(self, *args, **kwargs):
raise NotImplementedError
def on_failure(self, history, reason, details=None):
"""
The executor calls this method when the workflow fails.
"""
raise NotImplementedError
| from __future__ import absolute_import
class Workflow(object):
"""
Main interface to define a workflow by submitting tasks for asynchronous
execution.
The actual behavior depends on the executor backend.
"""
def __init__(self, executor):
self._executor = executor
def submit(self, func, *args, **kwargs):
"""
Submit a function for asynchronous execution.
:param func: callable registered as an task.
:type func: task.ActivityTask | task.WorkflowTask.
:param *args: arguments passed to the task.
:type *args: Sequence.
:param **kwargs: keyword-arguments passed to the task.
:type **kwargs: Mapping (dict).
:returns:
:rtype: Future.
"""
return self._executor.submit(func, *args, **kwargs)
def map(self, func, iterable):
"""
Submit a function for asynchronous execution for each value of
*iterable*.
:param func: callable registered as an task.
:type func: task.ActivityTask | task.WorkflowTask.
:param iterable: collections of arguments passed to the task.
:type iterable: Iterable.
"""
return self._executor.map(func, iterable)
def starmap(self, func, iterable):
"""
Submit a function for asynchronous execution for each value of
*iterable*.
:param func: callable registered as an task.
:type func: task.ActivityTask | task.WorkflowTask.
:param iterable: collections of multiple-arguments passed to the task
as positional arguments. They are destructured using
the ``*`` operator.
:type iterable: Iterable.
"""
return self._executor.starmap(func, iterable)
def fail(self, reason, details=None):
self._executor.fail(reason, details)
def run(self, *args, **kwargs):
raise NotImplementedError
| mit | Python |
7a5cb953f64dce841d88b9c8b45be7719c617ba2 | Fix games init file | kevinwilde/WildeBot,kevinwilde/WildeBot,kevinwilde/WildeBot,kevinwilde/WildeBot | games/__init__.py | games/__init__.py | import Game
import Mancala
import Player
import TicTacToe | __all__ = ['Game', 'Mancala', 'Player', 'TicTacToe'] | mit | Python |
147c85aff3e93ebb39d984a05cec970b3dc7edc0 | Add expires_at field to jwt that was removed accidentally (#242) | ONSdigital/ras-frontstage,ONSdigital/ras-frontstage,ONSdigital/ras-frontstage | frontstage/jwt.py | frontstage/jwt.py | """
Module to create jwt token.
"""
from datetime import datetime, timedelta
from jose import jwt
from frontstage import app
def timestamp_token(token):
"""Time stamp the expires_in argument of the OAuth2 token. And replace with an expires_in UTC timestamp"""
current_time = datetime.now()
expires_in = current_time + timedelta(seconds=token['expires_in'])
data_dict_for_jwt_token = {
"refresh_token": token['refresh_token'],
"access_token": token['access_token'],
"expires_at": expires_in.timestamp(),
"role": "respondent",
"party_id": token['party_id']
}
return data_dict_for_jwt_token
def encode(data):
"""Encode data in jwt token."""
return jwt.encode(data, app.config['JWT_SECRET'], algorithm=app.config['JWT_ALGORITHM'])
def decode(token):
"""Decode data in jwt token."""
return jwt.decode(token, app.config['JWT_SECRET'], algorithms=[app.config['JWT_ALGORITHM']])
| """
Module to create jwt token.
"""
from datetime import datetime, timedelta
from jose import jwt
from frontstage import app
def timestamp_token(token):
"""Time stamp the expires_in argument of the OAuth2 token. And replace with an expires_in UTC timestamp"""
current_time = datetime.now()
expires_in = current_time + timedelta(seconds=token['expires_in'])
data_dict_for_jwt_token = {
"refresh_token": token['refresh_token'],
"access_token": token['access_token'],
"role": "respondent",
"party_id": token['party_id']
}
return data_dict_for_jwt_token
def encode(data):
"""Encode data in jwt token."""
return jwt.encode(data, app.config['JWT_SECRET'], algorithm=app.config['JWT_ALGORITHM'])
def decode(token):
"""Decode data in jwt token."""
return jwt.decode(token, app.config['JWT_SECRET'], algorithms=[app.config['JWT_ALGORITHM']])
| mit | Python |
e8b49384d3e9e23485199ef131f0cb8f818a2a02 | edit default port | patricklam/get-image-part | get-image-part.py | get-image-part.py | import tornado.ioloop
import tornado.web
import tornado.wsgi
import io
import time
import random
import os
from PIL import Image
N = 20
class MainHandler(tornado.web.RequestHandler):
def get(self):
n = int(random.uniform(0,N))
img = int(self.get_argument("img"))
fn = os.path.join(os.path.dirname(__file__), "images/"+str(img)+".jpg")
im = Image.open(fn)
dim = im.size
c = im.crop((int(n*dim[0]/N), 0, int((n+1)*dim[0]/N), dim[1]))
c = c.convert("RGBA")
bio = io.BytesIO()
c.save(bio, 'PNG')
self.set_header('Access-Control-Allow-Origin', '*')
self.set_header('Content-Type', 'image/jpeg')
self.set_header('X-ECE459-Fragment', str(n))
time.sleep(abs(random.gauss(0.2, 0.2)))
self.write(bio.getvalue())
application = tornado.wsgi.WSGIApplication([
(r"/image", MainHandler),
])
if __name__ == "__main__":
import logging
import wsgiref.simple_server
logger = logging.getLogger('tornado.application')
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
logger.addHandler(ch)
server = wsgiref.simple_server.make_server('', 4590, application)
server.serve_forever()
| import tornado.ioloop
import tornado.web
import tornado.wsgi
import io
import time
import random
import os
from PIL import Image
N = 20
class MainHandler(tornado.web.RequestHandler):
def get(self):
n = int(random.uniform(0,N))
img = int(self.get_argument("img"))
fn = os.path.join(os.path.dirname(__file__), "images/"+str(img)+".jpg")
im = Image.open(fn)
dim = im.size
c = im.crop((int(n*dim[0]/N), 0, int((n+1)*dim[0]/N), dim[1]))
c = c.convert("RGBA")
bio = io.BytesIO()
c.save(bio, 'PNG')
self.set_header('Access-Control-Allow-Origin', '*')
self.set_header('Content-Type', 'image/jpeg')
self.set_header('X-ECE459-Fragment', str(n))
time.sleep(abs(random.gauss(0.2, 0.2)))
self.write(bio.getvalue())
application = tornado.wsgi.WSGIApplication([
(r"/image", MainHandler),
])
if __name__ == "__main__":
import logging
import wsgiref.simple_server
logger = logging.getLogger('tornado.application')
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
logger.addHandler(ch)
server = wsgiref.simple_server.make_server('', 8000, application)
server.serve_forever()
| bsd-2-clause | Python |
3e33a94580d386be71298bcc7fb2d4a4bc19dd34 | apply only the unified diff instead of the whole file | balabit/git-magic,balabit/git-magic | gitmagic/fixup.py | gitmagic/fixup.py | import gitmagic
from git.cmd import Git
from io import import StringIO
def fixup(repo, destination_picker, change_finder, args={}):
repo.index.reset()
for change in change_finder(repo):
_apply_change(repo, change)
destination_commits = destination_picker.pick(change)
if not destination_commits:
repo.index.commit( message = "WARNING: no destination commit")
continue
destination = destination_commits[0]
gitmagic.checkpoint("Should I create fixup commit for {} -> {}:{}\n{}".format(
change.a_file_name,
destination.hexsha[:7],
destination.summary,
change.unified_diff().read()), args)
repo.index.commit( message = "fixup! {}".format(destination.message))
def _apply_change(repo, change):
git = Git(repo.working_dir)
git.execute(['git', 'apply', '-'], istream=StringIO(change.unified_diff()))
| import gitmagic
def fixup(repo, destination_picker, change_finder, args={}):
repo.index.reset()
for change in change_finder(repo):
_apply_change(repo, change)
destination_commits = destination_picker.pick(change)
if not destination_commits:
repo.index.commit( message = "WARNING: no destination commit")
continue
destination = destination_commits[0]
gitmagic.checkpoint("Should I create fixup commit for {} -> {}:{}\n{}".format(
change.a_file_name,
destination.hexsha[:7],
destination.summary,
change.unified_diff().read()), args)
repo.index.commit( message = "fixup! {}".format(destination.message))
def _apply_change(repo, change):
#todo: apply unified diff only
repo.index.add([change.a_file_name])
| mit | Python |
eb642e63cd32b972ccdec4f487b9a7e2e7cb17b5 | make product_change_type template filter work with hidden plans | romonzaman/django-billing,gabrielgrant/django-billing,romonzaman/django-billing,gabrielgrant/django-billing | billing/templatetags/billing_tags.py | billing/templatetags/billing_tags.py | from django import template
import billing.loading
from pricing.products import Product
register = template.Library()
@register.filter
def product_change_type(product, user):
upc = user.billing_account.get_current_product_class()
if isinstance(product, Product):
product = type(product)
if upc:
products = billing.loading.get_products(hidden=True)
upc_index = products.index(upc)
p_index = products.index(product)
if upc_index < p_index:
return 'upgrade'
elif upc_index == p_index:
return None
else:
return 'downgrade'
else:
return 'upgrade'
| from django import template
import billing.loading
from pricing.products import Product
register = template.Library()
@register.filter
def product_change_type(product, user):
upc = user.billing_account.get_current_product_class()
if isinstance(product, Product):
product = type(product)
if upc:
products = billing.loading.get_products()
upc_index = products.index(upc)
p_index = products.index(product)
if upc_index < p_index:
return 'upgrade'
elif upc_index == p_index:
return None
else:
return 'downgrade'
else:
return 'upgrade'
| agpl-3.0 | Python |
bf188dfae49ab23c8f5dd7eeb105951f6c068b7f | Add filtering by is_circle to Role admin. | wearespindle/flindt,wearespindle/flindt,wearespindle/flindt | backend/feedbag/role/admin.py | backend/feedbag/role/admin.py | from django.contrib import admin
from django.utils.translation import ugettext as _
from .models import Role
class IsCircleListFilter(admin.SimpleListFilter):
# Human-readable title which will be displayed in the
# right admin sidebar just above the filter options.
title = _('Is Circle')
# Parameter for the filter that will be used in the URL query.
parameter_name = 'is_circle'
def lookups(self, request, model_admin):
"""
Returns a list of tuples. The first element in each
tuple is the coded value for the option that will
appear in the URL query. The second element is the
human-readable name for the option that will appear
in the right sidebar.
"""
return (('is_circle', _('Is circle')), ('is_not_circle', _('Is not circle')),)
def queryset(self, request, queryset):
"""
Returns the filtered queryset based on the value
provided in the query string and retrievable via
`self.value()`.
"""
if self.value() == 'is_circle':
return queryset.filter(children__isnull=False)
elif self.value() == 'is_not_circle':
return queryset.filter(children__isnull=True)
@admin.register(Role)
class RoleAdmin(admin.ModelAdmin):
list_display = ('name', 'is_circle', 'parent', 'purpose', 'archived',)
list_filter = ('archived', IsCircleListFilter)
search_fields = ('name',)
actions = ['archive_role']
def archive_role(self, request, queryset):
for role in queryset:
role.archive()
self.message_user(request, "Roles were successfully archived.")
archive_role.short_description = 'Archive selected roles'
| from django.contrib import admin
from .models import Role
@admin.register(Role)
class RoleAdmin(admin.ModelAdmin):
list_display = ('name',
'is_circle',
'parent',
'purpose',
'archived',
)
list_filter = ('archived',)
actions = ['archive_role']
def archive_role(self, request, queryset):
for role in queryset:
role.archive()
self.message_user(request, "Roles were successfully archived.")
archive_role.short_description = 'Archive selected roles'
| agpl-3.0 | Python |
0fac23c22307ca598e0cc6712280903c2a7d559d | Improve auto battle module | mythnc/gbf-bot | gbf_bot/auto_battle.py | gbf_bot/auto_battle.py | import logging
import random
import time
import pyautogui
from . import top_left, window_size
from . import auto_battle_config as config
from . import utility
from .components import Button
logger = logging.getLogger(__name__)
attack = Button('attack.png', config['attack'])
auto = Button('auto.png', config['auto'])
def activate(battle_time):
pyautogui.PAUSE = 1.3
# wait before battle start
w, h = window_size
start_pt = (top_left[0] + w//2, top_left[1] + h*1//3)
region = start_pt + (w//2, h*2//3)
while True:
time.sleep(0.5)
found = utility.locate(attack.path, region)
if found is not None:
break
logger.info('click attack')
attack.double_click()
time.sleep(random.random() * 0.35)
logger.info('click auto')
auto.click()
# battle result
time.sleep(battle_time)
| import logging
import random
import time
import pyautogui
from . import auto_battle_config as config
from .components import Button
logger = logging.getLogger(__name__)
attack = Button('attack.png', config['attack'])
auto = Button('auto.png', config['auto'])
def activate(battle_time):
pyautogui.PAUSE = 1.3
time.sleep(5 + random.random() * 0.25)
logger.info('click attack')
attack.double_click()
time.sleep(random.random() * 0.35)
logger.info('click auto')
auto.click()
# battle result
time.sleep(battle_time + random.random() * 3)
| mit | Python |
d37c2328a8ed58778f4c39091add317878831b4e | increment version | gbrammer/grizli | grizli/version.py | grizli/version.py | # git describe --tags
__version__ = "0.7.0-47-g6450ea1"
| # git describe --tags
__version__ = "0.7.0-41-g39ad8ff"
| mit | Python |
d30d10a477f0b46fa73da76cb1b010e1376c3ff2 | Update version for a new PYPI package. | guillemborrell/gtable | gtable/version.py | gtable/version.py | __version__ = '0.7'
| __version__ = '0.6.2'
| bsd-3-clause | Python |
f9dadd363d9f370d884c0b127e1f63df8916f3c8 | Rename some functions | franzpl/sweep,spatialaudio/sweep | calculation.py | calculation.py | """Calculation functions."""
from __future__ import division
import numpy as np
from . import plotting
import matplotlib.pyplot as plt
from scipy.signal import butter, freqz
def deconv_process(excitation, system_response, fs):
"""Deconvolution.
It is a necessity to zeropadd the excitation signal
to avoid zircular artifacts, if the system response is longer
than the excitation signal.
"""
NFFT = _pow2(len(excitation) + len(system_response) - 1)
excitation_f = np.fft.rfft(excitation, NFFT)
excitation_f_inv = 1 / excitation_f
# butter_w, butter_h = butter_bandpass(10, 22049, fs, NFFT//2+1, order=2)
return np.fft.irfft(np.fft.rfft(system_response, NFFT) * excitation_f_inv)
def snr_db(signal, noise):
"""Calculating Signal-to-noise ratio.
Parameters
----------
signal : array_like
Signal vector
noise : array_like
Noise vector
Returns
-------
Return SNR in dB
"""
return 10 * np.log10(_mean_power(signal) / _mean_power(noise))
def _mean_power(signal):
return np.mean(np.square(signal))
def _pow2(n):
i = 1
while i < n:
i *= 2
return i
def butter_bandpass(lower_bound, higher_bound, fs, NFFT, order):
wl = lower_bound / (fs / 2)
wh = higher_bound / (fs / 2)
b, a = butter(order, [wl, wh], btype='band')
butter_w, butter_h = freqz(b, a, worN=NFFT, whole=True)
return butter_w, butter_h
#~ def limiter(signal_f_inv, threshold_dB):
#~ signal_f_inv_abs = np.abs(signal_f_inv)
#~ signal_f_inv_phase = np.angle(signal_f_inv)
#~ signal_f_inv_abs_dB = plotting._dB_calculation(signal_f_inv_abs)
#~ array_positions = np.where(signal_f_inv_abs_dB > signal_f_inv_abs_dB.max() + threshold_dB)
#~ threshold = 10**((signal_f_inv_abs_dB.max()+threshold_dB)/20)
#~ signal_f_inv_abs[array_positions] = threshold
#~ signal_f_inv = signal_f_inv_abs * np.exp(1j*signal_f_inv_phase)
#~ return signal_f_inv
def awgn_noise(level, size=None, seed=1):
scale = 10 ** (level / 20.)
np.random.seed(seed)
return np.random.normal(scale=scale, size=size)
#~ def coherency(excitation, system_response):
#~ Rxx = np.correlate(excitation, excitation, 'full')
#~ Ryy = np.correlate(system_response, system_response, 'full')
#~ Ryx = np.correlate(system_response, excitation, 'full')
#~ return np.abs(Ryx) ** 2 / (Rxx * Ryy)
| """Calculation functions."""
from __future__ import division
import numpy as np
from scipy.signal import butter, freqz
def deconv_process(excitation, system_response, fs):
"""Deconvolution.
It is a necessity to zeropadd the excitation signal
to avoid zircular artifacts, if the system response is longer
than the excitation signal. Therfore, the excitation signal has
been extended for freely chosen 5 seconds as default. If you want
to simulate the 'Cologne Cathedral', feel free to zeropadd
more seconds.
"""
NFFT = _pow2(len(excitation) + len(system_response) - 1)
excitation_f = np.fft.fft(excitation, NFFT)
excitation_f_inv = 1 / excitation_f
# butter_w, butter_h = butter_bandpass(20, 20000, fs, NFFT, order=2)
return np.fft.ifft(np.fft.fft(system_response, NFFT) * excitation_f_inv).real
def snr_db(signal, noise):
"""Calculating Signal-to-noise ratio.
Parameters
----------
signal : array_like
Signal vector
noise : array_like
Noise vector
Returns
-------
Return SNR in dB
"""
return 10 * np.log10(_mean_power(signal) / _mean_power(noise))
def _mean_power(signal):
return np.mean(np.abs(signal ** 2))
def _pow2(n):
i = 1
while i < n:
i *= 2
return i
def coherency(excitation, system_response):
Rxx = np.correlate(excitation, excitation, 'full')
Ryy = np.correlate(system_response, system_response, 'full')
Ryx = np.correlate(system_response, excitation, 'full')
return np.abs(Ryx) ** 2 / (Rxx * Ryy)
def butter_bandpass(lower_bound, higher_bound, fs, NFFT, order):
wl = lower_bound / (fs / 2)
wh = higher_bound / (fs / 2)
b, a = butter(order, [wl, wh], btype='band')
butter_w, butter_h = freqz(b, a, worN=NFFT, whole=True)
return butter_w, butter_h
def limiter(signal, threshold_dB):
array_positions = np.where(signal < threshold_dB)
signal[array_positions] = threshold_dB
return signal
def noise_db(level, size=None, seed=1):
scale = 10 ** (level / 20.)
np.random.seed(seed)
return np.random.normal(scale=scale, size=size)
| mit | Python |
88f36912de48a84e4e3778889948f85655ba9064 | Remove token logging | maxgoedjen/canis | canis/oauth.py | canis/oauth.py | from os import environ
from urllib import urlencode
from datetime import datetime, timedelta
from flask import Flask, request, redirect
import requests
app = Flask(__name__)
SPOTIFY_CLIENT_ID = environ['CANIS_SPOTIFY_API_CLIENT_ID']
SPOTIFY_SECRET = environ['CANIS_SPOTIFY_API_SECRET']
SPOTIFY_CALLBACK = environ.get('CANIS_SPOTIFY_API_CALLBACK', 'http://127.0.0.1:5000/callback/')
access_token = None
refresh_token = None
expiration = None
@app.route('/login')
def login():
args = {
'client_id': SPOTIFY_CLIENT_ID,
'response_type': 'code',
'redirect_uri': SPOTIFY_CALLBACK,
'scope': 'playlist-read-private playlist-modify-private playlist-modify-public',
}
arg_str = urlencode(args)
url = 'https://accounts.spotify.com/authorize?{}'.format(arg_str)
return redirect(url)
@app.route('/callback/')
def callback():
args = {
'code': request.args['code'],
'grant_type': 'authorization_code',
'redirect_uri': SPOTIFY_CALLBACK,
'client_id': SPOTIFY_CLIENT_ID,
'client_secret': SPOTIFY_SECRET
}
r = requests.post('https://accounts.spotify.com/api/token', data=args)
resp = r.json()
store_token_response(resp)
shutdown_server()
return "You're good to go"
def refresh():
args = {
'refresh_token': refresh_token,
'grant_type': 'refresh_token',
'client_id': SPOTIFY_CLIENT_ID,
'client_secret': SPOTIFY_SECRET
}
r = requests.post('https://accounts.spotify.com/api/token', data=args)
resp = r.json()
store_token_response(resp)
def store_token_response(resp):
global access_token
global refresh_token
global expiration
access_token = resp['access_token']
if resp.get('refresh_token'):
refresh_token = resp['refresh_token']
expiration = datetime.utcnow() + timedelta(seconds=int(resp['expires_in']))
def shutdown_server():
func = request.environ.get('werkzeug.server.shutdown')
if func is None:
raise RuntimeError('Not running with the Werkzeug Server')
func()
| from os import environ
from urllib import urlencode
from datetime import datetime, timedelta
from flask import Flask, request, redirect
import requests
app = Flask(__name__)
SPOTIFY_CLIENT_ID = environ['CANIS_SPOTIFY_API_CLIENT_ID']
SPOTIFY_SECRET = environ['CANIS_SPOTIFY_API_SECRET']
SPOTIFY_CALLBACK = environ.get('CANIS_SPOTIFY_API_CALLBACK', 'http://127.0.0.1:5000/callback/')
access_token = None
refresh_token = None
expiration = None
@app.route('/login')
def login():
args = {
'client_id': SPOTIFY_CLIENT_ID,
'response_type': 'code',
'redirect_uri': SPOTIFY_CALLBACK,
'scope': 'playlist-read-private playlist-modify-private playlist-modify-public',
}
arg_str = urlencode(args)
url = 'https://accounts.spotify.com/authorize?{}'.format(arg_str)
return redirect(url)
@app.route('/callback/')
def callback():
args = {
'code': request.args['code'],
'grant_type': 'authorization_code',
'redirect_uri': SPOTIFY_CALLBACK,
'client_id': SPOTIFY_CLIENT_ID,
'client_secret': SPOTIFY_SECRET
}
r = requests.post('https://accounts.spotify.com/api/token', data=args)
resp = r.json()
store_token_response(resp)
shutdown_server()
return "You're good to go"
def refresh():
args = {
'refresh_token': refresh_token,
'grant_type': 'refresh_token',
'client_id': SPOTIFY_CLIENT_ID,
'client_secret': SPOTIFY_SECRET
}
r = requests.post('https://accounts.spotify.com/api/token', data=args)
resp = r.json()
store_token_response(resp)
def store_token_response(resp):
global access_token
global refresh_token
global expiration
access_token = resp['access_token']
if resp.get('refresh_token'):
refresh_token = resp['refresh_token']
expiration = datetime.utcnow() + timedelta(seconds=int(resp['expires_in']))
print (access_token, refresh_token, expiration)
def shutdown_server():
func = request.environ.get('werkzeug.server.shutdown')
if func is None:
raise RuntimeError('Not running with the Werkzeug Server')
func()
| mit | Python |
1391dd0b084f2c26fd5d0afceb81ffb5daab5dcf | Remove path and user filter from admin | aschn/drf-tracking,frankie567/drf-tracking | rest_framework_tracking/admin.py | rest_framework_tracking/admin.py | from django.contrib import admin
from .models import APIRequestLog
class APIRequestLogAdmin(admin.ModelAdmin):
date_hierarchy = 'requested_at'
list_display = ('id', 'requested_at', 'response_ms', 'status_code',
'user', 'method',
'path', 'remote_addr', 'host',
'query_params')
list_filter = ('method', 'status_code')
admin.site.register(APIRequestLog, APIRequestLogAdmin)
| from django.contrib import admin
from .models import APIRequestLog
class APIRequestLogAdmin(admin.ModelAdmin):
date_hierarchy = 'requested_at'
list_display = ('id', 'requested_at', 'response_ms', 'status_code',
'user', 'method',
'path', 'remote_addr', 'host',
'query_params')
list_filter = ('user', 'path', 'method', 'status_code')
admin.site.register(APIRequestLog, APIRequestLogAdmin)
| isc | Python |
ad4b5ccf7c89fa67e69d065c47edaa9e18c009ee | add docstrings add if __name__ == '__main__': to make pydoc work | unseenlaser/machinekit,bobvanderlinden/machinekit,ArcEye/machinekit-testing,kinsamanka/machinekit,cdsteinkuehler/linuxcnc,kinsamanka/machinekit,mhaberler/machinekit,ianmcmahon/linuxcnc-mirror,bobvanderlinden/machinekit,araisrobo/linuxcnc,kinsamanka/machinekit,bobvanderlinden/machinekit,bmwiedemann/linuxcnc-mirror,araisrobo/machinekit,aschiffler/linuxcnc,ikcalB/linuxcnc-mirror,ArcEye/MK-Qt5,araisrobo/machinekit,unseenlaser/machinekit,mhaberler/machinekit,unseenlaser/linuxcnc,EqAfrica/machinekit,EqAfrica/machinekit,bmwiedemann/linuxcnc-mirror,EqAfrica/machinekit,EqAfrica/machinekit,ArcEye/MK-Qt5,strahlex/machinekit,yishinli/emc2,ikcalB/linuxcnc-mirror,unseenlaser/machinekit,araisrobo/machinekit,aschiffler/linuxcnc,araisrobo/linuxcnc,strahlex/machinekit,ikcalB/linuxcnc-mirror,cdsteinkuehler/linuxcnc,RunningLight/machinekit,aschiffler/linuxcnc,araisrobo/machinekit,ianmcmahon/linuxcnc-mirror,ikcalB/linuxcnc-mirror,ArcEye/machinekit-testing,RunningLight/machinekit,ArcEye/MK-Qt5,araisrobo/machinekit,EqAfrica/machinekit,bmwiedemann/linuxcnc-mirror,aschiffler/linuxcnc,RunningLight/machinekit,mhaberler/machinekit,ArcEye/machinekit-testing,ikcalB/linuxcnc-mirror,jaguarcat79/ILC-with-LinuxCNC,kinsamanka/machinekit,bobvanderlinden/machinekit,Cid427/machinekit,Cid427/machinekit,ikcalB/linuxcnc-mirror,narogon/linuxcnc,ianmcmahon/linuxcnc-mirror,EqAfrica/machinekit,ianmcmahon/linuxcnc-mirror,cnc-club/linuxcnc,narogon/linuxcnc,ianmcmahon/linuxcnc-mirror,EqAfrica/machinekit,ArcEye/machinekit-testing,jaguarcat79/ILC-with-LinuxCNC,cdsteinkuehler/MachineKit,ianmcmahon/linuxcnc-mirror,unseenlaser/machinekit,Cid427/machinekit,bmwiedemann/linuxcnc-mirror,cnc-club/linuxcnc,RunningLight/machinekit,unseenlaser/linuxcnc,unseenlaser/machinekit,Cid427/machinekit,narogon/linuxcnc,strahlex/machinekit,EqAfrica/machinekit,strahlex/machinekit,unseenlaser/machinekit,araisrobo/linuxcnc,RunningLight/machinekit,RunningLight/machinekit,ArcEye/machinekit-testing,ArcEye/machinekit-testing,ArcEye/MK-Qt5,mhaberler/machinekit,araisrobo/machinekit,kinsamanka/machinekit,bobvanderlinden/machinekit,araisrobo/linuxcnc,ikcalB/linuxcnc-mirror,cnc-club/linuxcnc,araisrobo/linuxcnc,strahlex/machinekit,Cid427/machinekit,bobvanderlinden/machinekit,mhaberler/machinekit,araisrobo/machinekit,unseenlaser/linuxcnc,ianmcmahon/linuxcnc-mirror,mhaberler/machinekit,ArcEye/MK-Qt5,ArcEye/MK-Qt5,cdsteinkuehler/MachineKit,cdsteinkuehler/MachineKit,aschiffler/linuxcnc,bmwiedemann/linuxcnc-mirror,Cid427/machinekit,Cid427/machinekit,mhaberler/machinekit,cdsteinkuehler/linuxcnc,cnc-club/linuxcnc,jaguarcat79/ILC-with-LinuxCNC,unseenlaser/linuxcnc,strahlex/machinekit,cdsteinkuehler/MachineKit,araisrobo/machinekit,jaguarcat79/ILC-with-LinuxCNC,kinsamanka/machinekit,jaguarcat79/ILC-with-LinuxCNC,bobvanderlinden/machinekit,bmwiedemann/linuxcnc-mirror,cdsteinkuehler/MachineKit,narogon/linuxcnc,ArcEye/machinekit-testing,narogon/linuxcnc,araisrobo/machinekit,bobvanderlinden/machinekit,cnc-club/linuxcnc,yishinli/emc2,cdsteinkuehler/linuxcnc,unseenlaser/machinekit,ArcEye/MK-Qt5,ArcEye/machinekit-testing,cnc-club/linuxcnc,kinsamanka/machinekit,RunningLight/machinekit,unseenlaser/linuxcnc,bmwiedemann/linuxcnc-mirror,cdsteinkuehler/linuxcnc,cdsteinkuehler/MachineKit,Cid427/machinekit,kinsamanka/machinekit,strahlex/machinekit,ArcEye/MK-Qt5,RunningLight/machinekit,unseenlaser/machinekit,mhaberler/machinekit,yishinli/emc2,cnc-club/linuxcnc,yishinli/emc2,cdsteinkuehler/linuxcnc | src/hal/user_comps/pyvcp.py | src/hal/user_comps/pyvcp.py | #!/usr/bin/env python
# This is a component of emc
# Copyright 2007 Anders Wallin <[email protected]>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
""" Python Virtual Control Panel for EMC
A virtual control panel (VCP) is used to display and control
HAL pins, which are either BIT or FLOAT valued.
Usage: pyvcp -c compname myfile.xml
compname is the name of the HAL component to be created.
The name of the HAL pins associated with the VCP will begin with 'compname.'
myfile.xml is an XML file which specifies the layout of the VCP.
Valid XML tags are described in the documentation for pyvcp_widgets.py
"""
import sys, os
BASE = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), ".."))
sys.path.insert(0, os.path.join(BASE, "lib", "python"))
import vcpparse
import hal
from Tkinter import Tk
import getopt
def usage():
""" prints the usage message """
print "Usage: pyvcp -c hal_component_name myfile.xml"
def main():
""" creates a HAL component.
calls vcpparse with the specified XML file.
"""
try:
opts, args = getopt.getopt(sys.argv[1:], "c:")
except getopt.GetoptError, detail:
print detail
usage()
sys.exit(1)
component_name = None
for o, a in opts:
if o == "-c":
component_name = a
if component_name is None:
usage()
sys.exit(1)
try:
filename=args[0]
except:
usage()
sys.exit(1)
pyvcp0 = Tk()
pyvcp0.title(component_name)
vcpparse.filename=filename
pycomp=vcpparse.create_vcp(compname=component_name, master=pyvcp0)
pycomp.ready()
try:
pyvcp0.mainloop()
except KeyboardInterrupt:
sys.exit(0)
if __name__ == '__main__':
main()
| #!/usr/bin/env python
# This is a component of emc
# Copyright 2007 Anders Wallin <[email protected]>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
import sys, os
BASE = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), ".."))
sys.path.insert(0, os.path.join(BASE, "lib", "python"))
import vcpparse
import hal
from Tkinter import Tk
import getopt
def usage():
print "Usage: pyvcp -c hal_component_name myfile.xml"
def main():
try:
opts, args = getopt.getopt(sys.argv[1:], "c:")
except getopt.GetoptError, detail:
print detail
usage()
sys.exit(1)
#try:
# opts, args = getopt.getopt(sys.argv[1:], "c:")
#except getopt.GetoptError:
# print "usage: pyvcp -c hal_component_name myfile.xml"
# sys.exit(0)
#print opts
#print args
component_name = None
for o, a in opts:
if o == "-c":
component_name = a
if component_name is None:
usage()
sys.exit(1)
try:
filename=args[0]
except:
usage()
sys.exit(1)
#try:
# filename=sys.argv[1]
#except:
# print "Error: No XML file specified!"
# sys.exit()
pyvcp0 = Tk()
pyvcp0.title(component_name)
vcpparse.filename=filename
pycomp=vcpparse.create_vcp(compname=component_name, master=pyvcp0)
pycomp.ready()
try:
pyvcp0.mainloop()
except KeyboardInterrupt:
sys.exit(0)
main()
| lgpl-2.1 | Python |
214b1882a0eaf00bdd5dedbb02a28bba7f8d247b | update version to 1.1.7 | cartologic/cartoview,cartologic/cartoview,cartologic/cartoview,cartologic/cartoview | cartoview/__init__.py | cartoview/__init__.py | __version__ = (1, 1, 7, 'alpha', 0)
| __version__ = (1, 1, 5, 'alpha', 0)
| bsd-2-clause | Python |
455e1fe93b612c7049059cf217652862c995fe97 | Replace dict(<list_comprehension>) pattern with dict comprehension | bmihelac/django-import-export,copperleaftech/django-import-export,django-import-export/django-import-export,jnns/django-import-export,django-import-export/django-import-export,bmihelac/django-import-export,daniell/django-import-export,jnns/django-import-export,daniell/django-import-export,jnns/django-import-export,copperleaftech/django-import-export,copperleaftech/django-import-export,copperleaftech/django-import-export,django-import-export/django-import-export,bmihelac/django-import-export,django-import-export/django-import-export,daniell/django-import-export,bmihelac/django-import-export,daniell/django-import-export,jnns/django-import-export | import_export/instance_loaders.py | import_export/instance_loaders.py | from __future__ import unicode_literals
class BaseInstanceLoader(object):
"""
Base abstract implementation of instance loader.
"""
def __init__(self, resource, dataset=None):
self.resource = resource
self.dataset = dataset
def get_instance(self, row):
raise NotImplementedError
class ModelInstanceLoader(BaseInstanceLoader):
"""
Instance loader for Django model.
Lookup for model instance by ``import_id_fields``.
"""
def get_queryset(self):
return self.resource._meta.model.objects.all()
def get_instance(self, row):
try:
params = {}
for key in self.resource.get_import_id_fields():
field = self.resource.fields[key]
params[field.attribute] = field.clean(row)
return self.get_queryset().get(**params)
except self.resource._meta.model.DoesNotExist:
return None
class CachedInstanceLoader(ModelInstanceLoader):
"""
Loads all possible model instances in dataset avoid hitting database for
every ``get_instance`` call.
This instance loader work only when there is one ``import_id_fields``
field.
"""
def __init__(self, *args, **kwargs):
super(CachedInstanceLoader, self).__init__(*args, **kwargs)
pk_field_name = self.resource.get_import_id_fields()[0]
self.pk_field = self.resource.fields[pk_field_name]
ids = [self.pk_field.clean(row) for row in self.dataset.dict]
qs = self.get_queryset().filter(**{
"%s__in" % self.pk_field.attribute: ids
})
self.all_instances = {
self.pk_field.get_value(instance): instance
for instance in qs
}
def get_instance(self, row):
return self.all_instances.get(self.pk_field.clean(row))
| from __future__ import unicode_literals
class BaseInstanceLoader(object):
"""
Base abstract implementation of instance loader.
"""
def __init__(self, resource, dataset=None):
self.resource = resource
self.dataset = dataset
def get_instance(self, row):
raise NotImplementedError
class ModelInstanceLoader(BaseInstanceLoader):
"""
Instance loader for Django model.
Lookup for model instance by ``import_id_fields``.
"""
def get_queryset(self):
return self.resource._meta.model.objects.all()
def get_instance(self, row):
try:
params = {}
for key in self.resource.get_import_id_fields():
field = self.resource.fields[key]
params[field.attribute] = field.clean(row)
return self.get_queryset().get(**params)
except self.resource._meta.model.DoesNotExist:
return None
class CachedInstanceLoader(ModelInstanceLoader):
"""
Loads all possible model instances in dataset avoid hitting database for
every ``get_instance`` call.
This instance loader work only when there is one ``import_id_fields``
field.
"""
def __init__(self, *args, **kwargs):
super(CachedInstanceLoader, self).__init__(*args, **kwargs)
pk_field_name = self.resource.get_import_id_fields()[0]
self.pk_field = self.resource.fields[pk_field_name]
ids = [self.pk_field.clean(row) for row in self.dataset.dict]
qs = self.get_queryset().filter(**{
"%s__in" % self.pk_field.attribute: ids
})
self.all_instances = dict([
(self.pk_field.get_value(instance), instance)
for instance in qs])
def get_instance(self, row):
return self.all_instances.get(self.pk_field.clean(row))
| bsd-2-clause | Python |
ac8c1b6849c490c776636e3771e80344e6b0fb2e | Update github3.search.user for consistency | sigmavirus24/github3.py | github3/search/user.py | github3/search/user.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from .. import users
from ..models import GitHubCore
class UserSearchResult(GitHubCore):
"""Representation of a search result for a user.
This object has the following attributes:
.. attribute:: score
The confidence score of this result.
.. attribute:: text_matches
If present, a list of text strings that match the search string.
.. attribute:: user
A :class:`~github3.users.ShortUser` representing the user found
in this search result.
"""
def _update_attributes(self, data):
result = data.copy()
self.score = result.pop('score')
self.text_matches = result.pop('text_matches', [])
self.user = users.ShortUser(result, self)
def _repr(self):
return '<UserSearchResult [{0}]>'.format(self.user)
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from .. import users
from ..models import GitHubCore
class UserSearchResult(GitHubCore):
def _update_attributes(self, data):
result = data.copy()
#: Score of the result
self.score = self._get_attribute(result, 'score')
if 'score' in result:
del result['score']
#: Text matches
self.text_matches = self._get_attribute(result, 'text_matches', [])
if 'text_matches' in result:
del result['text_matches']
#: User object matching the search
self.user = users.ShortUser(result, self)
def _repr(self):
return '<UserSearchResult [{0}]>'.format(self.user)
| bsd-3-clause | Python |
b15f401fe270b69e46fb3009c4d55c917736fb27 | Bump version | guildai/guild,guildai/guild,guildai/guild,guildai/guild | guild/__init__.py | guild/__init__.py | # Copyright 2017 TensorHub, 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.
from __future__ import absolute_import
from __future__ import division
import os
import subprocess
__version__ = "0.3.0.dev8"
__requires__ = [
# (<required module>, <distutils package req>)
("pip", "pip"),
("yaml", "PyYAML"),
("setuptools", "setuptools"),
("tabview", "tabview"),
("twine", "twine"),
("werkzeug", "Werkzeug"),
("whoosh", "Whoosh"),
]
__pkgdir__ = os.path.dirname(os.path.dirname(__file__))
def _try_init_git_attrs():
try:
_init_git_commit()
except (OSError, subprocess.CalledProcessError):
pass
else:
try:
_init_git_status()
except (OSError, subprocess.CalledProcessError):
pass
def _init_git_commit():
commit = _git_cmd("git -C \"%(repo)s\" log -1 --oneline | cut -d' ' -f1")
globals()["__git_commit__"] = commit
def _init_git_status():
raw = _git_cmd("git -C \"%(repo)s\" status -s")
globals()["__git_status__"] = raw.split("\n") if raw else []
def _git_cmd(cmd, **kw):
repo = os.path.dirname(__file__)
cmd = cmd % dict(repo=repo, **kw)
null = open(os.devnull, "w")
out = subprocess.check_output(cmd, stderr=null, shell=True)
return out.decode("utf-8").strip()
def version():
git_commit = globals().get("__git_commit__")
if git_commit:
git_status = globals().get("__git_status__", [])
workspace_changed_marker = "*" if git_status else ""
return "%s (dev %s%s)" % (__version__, git_commit,
workspace_changed_marker)
else:
return __version__
_try_init_git_attrs()
| # Copyright 2017 TensorHub, 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.
from __future__ import absolute_import
from __future__ import division
import os
import subprocess
__version__ = "0.3.0.dev7"
__requires__ = [
# (<required module>, <distutils package req>)
("pip", "pip"),
("yaml", "PyYAML"),
("setuptools", "setuptools"),
("tabview", "tabview"),
("twine", "twine"),
("werkzeug", "Werkzeug"),
("whoosh", "Whoosh"),
]
__pkgdir__ = os.path.dirname(os.path.dirname(__file__))
def _try_init_git_attrs():
try:
_init_git_commit()
except (OSError, subprocess.CalledProcessError):
pass
else:
try:
_init_git_status()
except (OSError, subprocess.CalledProcessError):
pass
def _init_git_commit():
commit = _git_cmd("git -C \"%(repo)s\" log -1 --oneline | cut -d' ' -f1")
globals()["__git_commit__"] = commit
def _init_git_status():
raw = _git_cmd("git -C \"%(repo)s\" status -s")
globals()["__git_status__"] = raw.split("\n") if raw else []
def _git_cmd(cmd, **kw):
repo = os.path.dirname(__file__)
cmd = cmd % dict(repo=repo, **kw)
null = open(os.devnull, "w")
out = subprocess.check_output(cmd, stderr=null, shell=True)
return out.decode("utf-8").strip()
def version():
git_commit = globals().get("__git_commit__")
if git_commit:
git_status = globals().get("__git_status__", [])
workspace_changed_marker = "*" if git_status else ""
return "%s (dev %s%s)" % (__version__, git_commit,
workspace_changed_marker)
else:
return __version__
_try_init_git_attrs()
| apache-2.0 | Python |
156817ee4e11c6a363511d915a9ea5cf96e41fb5 | add statistics tracking | PolyJIT/benchbuild,PolyJIT/benchbuild,PolyJIT/benchbuild,PolyJIT/benchbuild | benchbuild/experiments/mse.py | benchbuild/experiments/mse.py | """
Test Maximal Static Expansion.
This tests the maximal static expansion implementation by
Nicholas Bonfante (implemented in LLVM/Polly).
"""
from benchbuild.extensions import ExtractCompileStats
from benchbuild.experiment import RuntimeExperiment
from benchbuild.extensions import RunWithTime, RuntimeExtension
from benchbuild.settings import CFG
class PollyMSE(RuntimeExperiment):
"""The polly experiment."""
NAME = "polly-mse"
def actions_for_project(self, project):
"""Compile & Run the experiment with -O3 enabled."""
project.cflags = [
"-O3",
"-fno-omit-frame-pointer",
"-mllvm", "-polly",
"-mllvm", "-polly-enable-mse",
"-mllvm", "-polly-process-unprofitable",
"-mllvm", "-polly-optree-analyze-known=0",
"-mllvm", "-polly-enable-delicm=0",
]
project.compiler_extension = ExtractCompileStats(project, self)
project.runtime_extension = \
RunWithTime(
RuntimeExtension(project, self,
{'jobs': int(CFG["jobs"].value())}))
return self.default_runtime_actions(project)
| """
Test Maximal Static Expansion.
This tests the maximal static expansion implementation by
Nicholas Bonfante (implemented in LLVM/Polly).
"""
from benchbuild.experiment import RuntimeExperiment
from benchbuild.extensions import RunWithTime, RuntimeExtension
from benchbuild.settings import CFG
class PollyMSE(RuntimeExperiment):
"""The polly experiment."""
NAME = "polly-mse"
def actions_for_project(self, project):
"""Compile & Run the experiment with -O3 enabled."""
project.cflags = [
"-O3",
"-fno-omit-frame-pointer",
"-mllvm", "-stats",
"-mllvm", "-polly",
"-mllvm", "-polly-enable-mse",
"-mllvm", "-polly-process-unprofitable",
"-mllvm", "-polly-optree-analyze-known=0",
"-mllvm", "-polly-enable-delicm=0",
]
project.runtime_extension = \
RunWithTime(
RuntimeExtension(project, self,
{'jobs': int(CFG["jobs"].value())}))
return self.default_runtime_actions(project)
| mit | Python |
8a178f1249b968e315b8492ed15c033aca119033 | Reset closed site property | jfterpstra/bluebottle,onepercentclub/bluebottle,jfterpstra/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,jfterpstra/bluebottle,onepercentclub/bluebottle,jfterpstra/bluebottle,onepercentclub/bluebottle | bluebottle/clients/tests/test_api.py | bluebottle/clients/tests/test_api.py | from django.core.urlresolvers import reverse
from django.test.utils import override_settings
from rest_framework import status
from bluebottle.clients import properties
from bluebottle.test.utils import BluebottleTestCase
class ClientSettingsTestCase(BluebottleTestCase):
def setUp(self):
super(ClientSettingsTestCase, self).setUp()
self.settings_url = reverse('settings')
@override_settings(CLOSED_SITE=False, TOP_SECRET="*****",EXPOSED_TENANT_PROPERTIES=['closed_site'])
def test_settings_show(self):
# Check that exposed property is in settings api, and other settings are not shown
response = self.client.get(self.settings_url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data['closedSite'], False)
self.assertNotIn('topSecret', response.data)
# Check that exposed setting gets overwritten by client property
setattr(properties, 'CLOSED_SITE', True)
response = self.client.get(self.settings_url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data['closedSite'], True)
# Check that previously hidden setting can be exposed
setattr(properties, 'EXPOSED_TENANT_PROPERTIES', ['closed_site', 'top_secret'])
response = self.client.get(self.settings_url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertIn('topSecret', response.data)
setattr(properties, 'CLOSED_SITE', False)
| from django.core.urlresolvers import reverse
from django.test.utils import override_settings
from rest_framework import status
from bluebottle.clients import properties
from bluebottle.test.utils import BluebottleTestCase
class ClientSettingsTestCase(BluebottleTestCase):
def setUp(self):
super(ClientSettingsTestCase, self).setUp()
self.settings_url = reverse('settings')
@override_settings(CLOSED_SITE=False, TOP_SECRET="*****",EXPOSED_TENANT_PROPERTIES=['closed_site'])
def test_settings_show(self):
# Check that exposed property is in settings api, and other settings are not shown
response = self.client.get(self.settings_url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data['closedSite'], False)
self.assertNotIn('topSecret', response.data)
# Check that exposed setting gets overwritten by client property
setattr(properties, 'CLOSED_SITE', True)
response = self.client.get(self.settings_url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data['closedSite'], True)
# Check that previously hidden setting can be exposed
setattr(properties, 'EXPOSED_TENANT_PROPERTIES', ['closed_site', 'top_secret'])
response = self.client.get(self.settings_url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertIn('topSecret', response.data)
| bsd-3-clause | Python |
e469163c5b103483b294f9c1f37c918177e7dbce | Make prsync.py really useful | angr/angr-dev,angr/angr-dev | admin/prsync.py | admin/prsync.py | #!/usr/bin/env python
import os
import sys
import subprocess
import urlparse
import pygithub3
try:
import angr
angr_dir = os.path.realpath(os.path.join(os.path.dirname(angr.__file__), '../..'))
except ImportError:
print 'Please run this script in the angr virtualenv!'
sys.exit(1)
def main(branch_name=None, do_push=False):
print 'Enter the urls of the pull requests, separated by newlines. EOF to finish:'
urls = sys.stdin.read().strip().split('\n')
if len(urls) == 0:
sys.exit(0)
prs = []
gh = pygithub3.Github()
for url in urls:
try:
path = urlparse.urlparse(url).path
pathkeys = path.split('/')
prs.append(gh.pull_requests.get(int(pathkeys[4]), pathkeys[1], pathkeys[2]))
assert pathkeys[3] == 'pull'
except Exception: # pylint: disable=broad-except
print url, 'is not a github pull request url'
import ipdb; ipdb.set_trace()
sys.exit(1)
if branch_name is None:
branch_name = 'pr/%s-%d' % (prs[0].head['label'].replace(':','/'), prs[0].number)
for pr in prs:
repo_path = os.path.join(angr_dir, pr.base['repo']['name'])
print '\x1b[32;1m$', 'git', 'checkout', '-B', branch_name, 'master', '\x1b[0m'
subprocess.call(['git', 'checkout', '-B', branch_name, 'master'], cwd=repo_path)
print '\x1b[32;1m$', 'git', 'pull', pr.head['repo']['git_url'], pr.head['ref'], '\x1b[0m'
subprocess.call(['git', 'pull', pr.head['repo']['git_url'], pr.head['ref']], cwd=repo_path)
if do_push:
print '\x1b[32;1m$', 'git', 'push', '-f', '-u', 'origin', branch_name, '\x1b[0m'
subprocess.call(['git', 'push', '-f', '-u', 'origin', branch_name], cwd=repo_path)
repolist = ' '.join(pr.base['repo']['name'] for pr in prs)
print
print '\x1b[33;1mTo merge this pull request, run the following commands:\x1b[0m'
print 'REPOS=%s ./git_all.sh checkout master' % repolist
print 'REPOS=%s ./git_all.sh merge %s' % (repolist, branch_name)
print 'REPOS=%s ./git_all.sh push' % repolist
print 'REPOS=%s ./git_all.sh branch -D %s' % (repolist, branch_name)
if __name__ == '__main__':
s_do_push = False
if '-p' in sys.argv:
s_do_push = True
sys.argv.remove('-n')
if len(sys.argv) > 1:
main(sys.argv[1], do_push=s_do_push)
else:
main(do_push=s_do_push)
| #!/usr/bin/env python
import os
import sys
import subprocess
import urlparse
import pygithub3
try:
import angr
angr_dir = os.path.realpath(os.path.join(os.path.dirname(angr.__file__), '../..'))
except ImportError:
print 'Please run this script in the angr virtualenv!'
sys.exit(1)
def main(branch_name=None):
print 'Enter the urls of the pull requests, separated by newlines. EOF to finish:'
urls = sys.stdin.read().strip().split('\n')
if len(urls) == 0:
sys.exit(0)
prs = []
gh = pygithub3.Github()
for url in urls:
try:
path = urlparse.urlparse(url).path
pathkeys = path.split('/')
prs.append(gh.pull_requests.get(int(pathkeys[4]), pathkeys[1], pathkeys[2]))
assert pathkeys[3] == 'pull'
except Exception: # pylint: disable=broad-except
print url, 'is not a github pull request url'
import ipdb; ipdb.set_trace()
sys.exit(1)
if branch_name is None:
branch_name = 'pr/' + prs[0].head['label'].replace(':','/')
for pr in prs:
repo_path = os.path.join(angr_dir, pr.base['repo']['name'])
print '\x1b[32;1m$', 'git', 'checkout', '-B', branch_name, 'master', '\x1b[0m'
subprocess.call(['git', 'checkout', '-B', branch_name, 'master'], cwd=repo_path)
print '\x1b[32;1m$', 'git', 'pull', pr.head['repo']['git_url'], pr.head['ref'], '\x1b[0m'
subprocess.call(['git', 'pull', pr.head['repo']['git_url'], pr.head['ref']], cwd=repo_path)
print '\x1b[32;1m$', 'git', 'push', '-f', '-u', 'origin', branch_name, '\x1b[0m'
subprocess.call(['git', 'push', '-f', '-u', 'origin', branch_name], cwd=repo_path)
if __name__ == '__main__':
if len(sys.argv) > 1:
main(sys.argv[1])
else:
main()
| bsd-2-clause | Python |
9f32fee9da5ccffec9a86f62ab9a55625eb65ff7 | Fix menu user input | dgengtek/scripts,dgengtek/scripts | admin/wakeup.py | admin/wakeup.py | #!/bin/env python3
from pathlib import Path
import subprocess
import logging
import sys
logger = logging.getLogger(__name__)
wol_path = "~/.config/wol.cfg"
# TODO query list from database when available
def main():
global wol_path
wol_path = Path(wol_path).expanduser()
# iterate wake on lan list, wollist
menu = generate_menulist(wol_path)
while True:
user_choice = ""
display_menu(menu)
try:
choice = input("Your choice: ")
user_choice = int(choice) - 1
if check_in_bounds(user_choice, menu):
break
else:
logger.info("Choose a number from the menu.")
except (KeyboardInterrupt, EOFError):
logger.error("\nbye")
sys.exit(0)
except (ValueError, TypeError):
logger.error("Input is not a number.")
hostname, hwadress = menu[user_choice]
subprocess.run(["wol", hwadress])
def display_menu(menu):
for i, item in enumerate(menu):
print("{} - {}".format((i+1),item))
def check_in_bounds(choice, l):
length = len(l)
if choice < length and choice >= 0:
return True
else:
return False
def generate_menulist(path):
menu = list()
with path.open() as wollist:
for record in wollist:
menu.append(tuple(record.strip().split(" ")))
return menu
def usage():
pass
if __name__ == "__main__":
main()
| #!/bin/env python3
from pathlib import Path
import subprocess
def main():
main.path = Path(".config/wol.cfg")
main.path = main.path.home().joinpath(main.path)
# iterate wake on lan list, wollist
menu = generate_menulist(main.path)
if display_menu(menu):
hostname, hwadress = menu[main.user_choice]
subprocess.run(["wol", hwadress])
def display_menu(menu):
for i, item in enumerate(menu):
print("{} - {}".format((i+1),item))
try:
choice = input("Your choice: ")
main.user_choice = int(choice) - 1
except KeyboardInterrupt:
print()
return False
if check_in_bounds(main.user_choice, menu):
return True
else:
print("{:-^80}".format("Invalid choice"))
display_menu(menu)
def check_in_bounds(choice, l):
length = len(l)
if choice < length and choice >= 0:
return True
else:
return False
def generate_menulist(path):
menu = list()
with path.open() as wollist:
for record in wollist:
menu.append(tuple(record.strip().split(" ")))
return menu
def usage():
pass
if __name__ == "__main__":
main()
| mit | Python |
3a3a8217bd5ff63c77eb4d386bda042cfd7a1196 | delete the depency to sale_order_extend | ClearCorp/odoo-clearcorp,ClearCorp/odoo-clearcorp,ClearCorp/odoo-clearcorp,ClearCorp/odoo-clearcorp | sale_order_report/__openerp__.py | sale_order_report/__openerp__.py | # -*- coding: utf-8 -*-
# © 2016 ClearCorp
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
'name': 'Sale Order Report',
'summary': 'Sale order report in Qweb',
'version': '8.0.1.0',
'category': 'Sales',
'website': 'http://clearcorp.cr',
'author': 'ClearCorp',
'license': 'AGPL-3',
'sequence': 10,
'application': False,
'installable': True,
'auto_install': False,
"depends": [
'sale_order_discount',
'base_reporting',
],
"data": [
'data/report.paperformat.xml',
'data/sale_report.xml',
'views/report_sale_order.xml',
'views/report_sale_order_layout.xml',
'views/report_sale_order_layout_header.xml',
'views/report_sale_order_layout_footer.xml',
],
}
| # -*- coding: utf-8 -*-
# © 2016 ClearCorp
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
'name': 'Sale Order Report',
'summary': 'Sale order report in Qweb',
'version': '8.0.1.0',
'category': 'Sales',
'website': 'http://clearcorp.cr',
'author': 'ClearCorp',
'license': 'AGPL-3',
'sequence': 10,
'application': False,
'installable': True,
'auto_install': False,
"depends": [
'sale_order_discount',
'sale_order_extended',
'base_reporting',
],
"data": [
'data/report.paperformat.xml',
'data/sale_report.xml',
'views/report_sale_order.xml',
'views/report_sale_order_layout.xml',
'views/report_sale_order_layout_header.xml',
'views/report_sale_order_layout_footer.xml',
],
}
| agpl-3.0 | Python |
7700e8b9a5a62fce875156482170c4fbc4cae902 | Update shortcut template | jeremykid/swjblog,jeremykid/swjblog,jeremykid/swjblog | swjblog/polls/views.py | swjblog/polls/views.py | from django.http import HttpResponse
from django.template import loader
from django.shortcuts import get_object_or_404, render
# Create your views here.
from .models import Question
# def index(request):
# latest_question_list = Question.objects.order_by('-pub_date')[:5]
# template = loader.get_template('polls/index.html')
# context = {
# 'latest_question_list': latest_question_list,
# }
# return HttpResponse(template.render(context, request))
# shortcut
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
context = {'latest_question_list': latest_question_list}
return render(request, 'polls/index.html', context)
def detail(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'polls/detail.html', {'question': question})
def results(request, question_id):
response = "You're looking at the results of question %s."
return HttpResponse(response % question_id)
def vote(request, question_id):
return HttpResponse("You're voting on question %s." % question_id) | from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader
# Create your views here.
from .models import Question
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
template = loader.get_template('polls/index.html')
context = {
'latest_question_list': latest_question_list,
}
return HttpResponse(template.render(context, request))
def detail(request, question_id):
return HttpResponse("You're looking at question %s." % question_id)
def results(request, question_id):
response = "You're looking at the results of question %s."
return HttpResponse(response % question_id)
def vote(request, question_id):
return HttpResponse("You're voting on question %s." % question_id) | mit | Python |
0e780569b8d40f3b9599df4f7d4a457f23b3f54f | Make uploader work | mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge | stoneridge_uploader.py | stoneridge_uploader.py | #!/usr/bin/env python
# This Source Code Form is subject to the terms of the Mozilla Public License,
# v. 2.0. If a copy of the MPL was not distributed with this file, You can
# obtain one at http://mozilla.org/MPL/2.0/.
import glob
import os
import requests
import stoneridge
class StoneRidgeUploader(object):
"""Takes the upload files created by the collator and uploads them to the
graph server
"""
def __init__(self):
self.url = stoneridge.get_config('upload', 'url')
def run(self):
file_pattern = os.path.join(stoneridge.outdir, 'upload_*.json')
upload_files = glob.glob(file_pattern)
files = {os.path.basename(fname): open(fname, 'rb')
for fname in upload_files}
requests.post(self.url, files=files)
for f in files.values():
f.close()
@stoneridge.main
def main():
parser = stoneridge.ArgumentParser()
args = parser.parse_args()
uploader = StoneRidgeUploader()
uploader.run()
| #!/usr/bin/env python
# This Source Code Form is subject to the terms of the Mozilla Public License,
# v. 2.0. If a copy of the MPL was not distributed with this file, You can
# obtain one at http://mozilla.org/MPL/2.0/.
import glob
import os
import human_curl as requests
import stoneridge
class StoneRidgeUploader(object):
"""Takes the upload files created by the collator and uploads them to the
graph server
"""
def __init__(self):
self.url = stoneridge.get_config('upload', 'url')
def run(self):
file_pattern = os.path.join(stoneridge.outdir, 'upload_*.json')
upload_files = glob.glob(file_pattern)
for upload in upload_files:
fname = os.path.basename(upload)
with file(upload, 'rb') as f:
requests.post(self.url, files=((fname, f),))
@stoneridge.main
def main():
parser = stoneridge.ArgumentParser()
args = parser.parse_args()
uploader = StoneRidgeUploader()
uploader.run()
| mpl-2.0 | Python |
5b1790664ad5268a1d1764b81d1fa7e8fea5aabe | Bump version number. | markmuetz/stormtracks,markmuetz/stormtracks | stormtracks/version.py | stormtracks/version.py | VERSION = (0, 5, 0, 6, 'alpha')
def get_version(form='short'):
if form == 'short':
return '.'.join([str(v) for v in VERSION[:4]])
elif form == 'long':
return '.'.join([str(v) for v in VERSION][:4]) + '-' + VERSION[4]
else:
raise ValueError('unrecognised form specifier: {0}'.format(form))
__version__ = get_version()
if __name__ == '__main__':
print(get_version())
| VERSION = (0, 5, 0, 5, 'alpha')
def get_version(form='short'):
if form == 'short':
return '.'.join([str(v) for v in VERSION[:4]])
elif form == 'long':
return '.'.join([str(v) for v in VERSION][:4]) + '-' + VERSION[4]
else:
raise ValueError('unrecognised form specifier: {0}'.format(form))
__version__ = get_version()
if __name__ == '__main__':
print(get_version())
| mit | Python |
a82d419d17c67cfd7842cf104994b9ecbda96e94 | Delete existing libnccl before installing NCCL | GoogleCloudPlatform/PerfKitBenchmarker,GoogleCloudPlatform/PerfKitBenchmarker,GoogleCloudPlatform/PerfKitBenchmarker,GoogleCloudPlatform/PerfKitBenchmarker | perfkitbenchmarker/linux_packages/nccl.py | perfkitbenchmarker/linux_packages/nccl.py | # Copyright 2018 PerfKitBenchmarker Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Module containing NCCL installation function."""
import posixpath
from perfkitbenchmarker import flags
from perfkitbenchmarker import vm_util
flags.DEFINE_string('nccl_version', '2.5.6-2',
'NCCL version to install')
FLAGS = flags.FLAGS
GIT_REPO = 'https://github.com/NVIDIA/nccl.git'
def _Build(vm):
"""Installs the OpenMPI package on the VM."""
vm.RemoteCommand('[ -d "nccl" ] || git clone {git_repo} --branch v{version}'
.format(git_repo=GIT_REPO, version=FLAGS.nccl_version))
cuda_home = '/usr/local/cuda'
vm.InstallPackages('build-essential devscripts debhelper fakeroot')
env_vars = {}
env_vars['PATH'] = (r'{cuda_bin_path}:$PATH'
.format(cuda_bin_path=posixpath.join(cuda_home, 'bin')))
env_vars['CUDA_HOME'] = (r'{cuda_home}'.format(cuda_home=cuda_home))
env_vars['LD_LIBRARY_PATH'] = (r'{lib_path}:$LD_LIBRARY_PATH'
.format(lib_path=posixpath.join(
cuda_home, 'lib64')))
vm.RemoteCommand('cd nccl && {env} make -j 20 pkg.debian.build'
.format(env=vm_util.DictonaryToEnvString(env_vars)))
def AptInstall(vm):
"""Installs the NCCL package on the VM."""
_Build(vm)
vm.RemoteCommand('sudo rm -rf /usr/local/nccl2') # Preexisting NCCL in DLVM
vm.InstallPackages('{build}libnccl2_{nccl}+cuda{cuda}_amd64.deb '
'{build}libnccl-dev_{nccl}+cuda{cuda}_amd64.deb'
.format(
build='./nccl/build/pkg/deb/',
nccl=FLAGS.nccl_version,
cuda=FLAGS.cuda_toolkit_version))
| # Copyright 2018 PerfKitBenchmarker Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Module containing NCCL installation function."""
import posixpath
from perfkitbenchmarker import flags
from perfkitbenchmarker import vm_util
flags.DEFINE_string('nccl_version', '2.5.6-2',
'NCCL version to install')
FLAGS = flags.FLAGS
GIT_REPO = 'https://github.com/NVIDIA/nccl.git'
def _Build(vm):
"""Installs the OpenMPI package on the VM."""
vm.RemoteCommand('[ -d "nccl" ] || git clone {git_repo} --branch v{version}'
.format(git_repo=GIT_REPO, version=FLAGS.nccl_version))
cuda_home = '/usr/local/cuda'
vm.InstallPackages('build-essential devscripts debhelper fakeroot')
env_vars = {}
env_vars['PATH'] = (r'{cuda_bin_path}:$PATH'
.format(cuda_bin_path=posixpath.join(cuda_home, 'bin')))
env_vars['CUDA_HOME'] = (r'{cuda_home}'.format(cuda_home=cuda_home))
env_vars['LD_LIBRARY_PATH'] = (r'{lib_path}:$LD_LIBRARY_PATH'
.format(lib_path=posixpath.join(
cuda_home, 'lib64')))
vm.RemoteCommand('cd nccl && {env} make -j 20 pkg.debian.build'
.format(env=vm_util.DictonaryToEnvString(env_vars)))
def AptInstall(vm):
"""Installs the NCCL package on the VM."""
_Build(vm)
vm.InstallPackages('{build}libnccl2_{nccl}+cuda{cuda}_amd64.deb '
'{build}libnccl-dev_{nccl}+cuda{cuda}_amd64.deb'
.format(
build='./nccl/build/pkg/deb/',
nccl=FLAGS.nccl_version,
cuda=FLAGS.cuda_toolkit_version))
| apache-2.0 | Python |
13ae8cf8eddba1cf40d89307ba1c52480cbac472 | Bump version | TheTrain2000/async2rewrite | async2rewrite/__init__.py | async2rewrite/__init__.py | """
Convert discord.py code using abstract syntax trees.
"""
__title__ = 'async2rewrite'
__author__ = 'Tyler Gibbs'
__version__ = '0.0.3'
__copyright__ = 'Copyright 2017 TheTrain2000'
__license__ = 'MIT'
from .main import *
| """
Convert discord.py code using abstract syntax trees.
"""
__title__ = 'async2rewrite'
__author__ = 'Tyler Gibbs'
__version__ = '0.0.2'
__copyright__ = 'Copyright 2017 TheTrain2000'
__license__ = 'MIT'
from .main import *
| mit | Python |
0639158e539f0f1c1a6d4dac1753179429257017 | add django_pluralize template filter | mozilla/source,ryanpitts/source,ryanpitts/source,ryanpitts/source,mozilla/source,ryanpitts/source,mozilla/source,mozilla/source | source/base/helpers.py | source/base/helpers.py | import datetime
import logging
import os
from django.conf import settings
from django.template.defaultfilters import linebreaks as django_linebreaks,\
escapejs as django_escapejs, pluralize as django_pluralize
from jingo import register
from sorl.thumbnail import get_thumbnail
logger = logging.getLogger('base.helpers')
@register.filter
def linebreaks(string):
return django_linebreaks(string)
@register.filter
def escapejs(string):
return django_escapejs(string)
@register.function
def get_timestamp():
return datetime.datetime.now()
@register.filter
def dj_pluralize(string, arg='s'):
return django_pluralize(string, arg)
@register.function
def thumbnail(source, *args, **kwargs):
"""
Wraps sorl thumbnail with an additional 'default' keyword
https://github.com/mozilla/mozillians/blob/master/apps/common/helpers.py
"""
# Templates should never return an exception
try:
if not source.path:
source = kwargs.get('default')
# Handle PNG images a little more gracefully
# Make sure thumbnail call doesn't specifically set format
if not 'format' in kwargs:
filetype = source.path.split('.')[-1]
# If we have a PNG, don't default convert to JPG
if filetype.lower() == 'png':
kwargs['format'] = 'PNG'
return get_thumbnail(source, *args, **kwargs)
except Exception as e:
logger.error('Thumbnail had Exception: %s' % (e,))
source = getattr(settings, 'DEFAULT_IMAGE_SRC')
return get_thumbnail(source, *args, **kwargs)
| import datetime
import logging
import os
from django.conf import settings
from django.template.defaultfilters import linebreaks as django_linebreaks,\
escapejs as django_escapejs
from jingo import register
from sorl.thumbnail import get_thumbnail
logger = logging.getLogger('base.helpers')
@register.filter
def linebreaks(string):
return django_linebreaks(string)
@register.filter
def escapejs(string):
return django_escapejs(string)
@register.function
def get_timestamp():
return datetime.datetime.now()
@register.function
def thumbnail(source, *args, **kwargs):
"""
Wraps sorl thumbnail with an additional 'default' keyword
https://github.com/mozilla/mozillians/blob/master/apps/common/helpers.py
"""
# Templates should never return an exception
try:
if not source.path:
source = kwargs.get('default')
# Handle PNG images a little more gracefully
# Make sure thumbnail call doesn't specifically set format
if not 'format' in kwargs:
filetype = source.path.split('.')[-1]
# If we have a PNG, don't default convert to JPG
if filetype.lower() == 'png':
kwargs['format'] = 'PNG'
return get_thumbnail(source, *args, **kwargs)
except Exception as e:
logger.error('Thumbnail had Exception: %s' % (e,))
source = getattr(settings, 'DEFAULT_IMAGE_SRC')
return get_thumbnail(source, *args, **kwargs)
| bsd-3-clause | Python |
aa4be6a435222003bf5e87df5c1f8d34394592fe | add celery conf | pyprism/Hiren-Git-Commit-Reminder,pyprism/Hiren-Git-Commit-Reminder | hiren/__init__.py | hiren/__init__.py | from github.celery import app as celery_app | mit | Python |
|
9abe7a776c4b0a4995a1c3a3d16f02bcba93f12e | add sin flute | miltonsarria/dsp-python,miltonsarria/dsp-python,miltonsarria/dsp-python | audio/fourier_an_audio.py | audio/fourier_an_audio.py | #Milton Orlando Sarria
#analisis espectral de sinusoides
import matplotlib.pyplot as plt
import numpy as np
from fourierFunc import fourierAn
import wav_rw as wp
from scipy.signal import get_window
filename1='sound/flute-A4.wav'
filename2='sound/violin-B3.wav'
#leer los archivos de audio
fs,x1=wp.wavread(filename1)
fs,x2=wp.wavread(filename2)
t=(np.arange(1,5*fs))/float(fs)
#crear dos ventanas
w1 = get_window('hamming', x1.size); w1 = w1 / sum(w1)
w2 = get_window('hamming', x2.size); w2 = w2 / sum(w2)
#calcular el espectro de las ondas
absY1,mY1,pY1=fourierAn(x1*w1)
absY2,mY2,pY2=fourierAn(x2*w2)
#vector de frecuencias, desde -fs/2 a fs/2 (-pi<w<pi)
f=np.linspace(-fs/2,fs/2,absY1.size)
#visualizar las dos ondas
plt.subplot(321)
plt.plot(x1)
plt.title('onda sin ruido')
plt.subplot(323)
plt.plot(absY1)
plt.title('Espectro onda 1')
plt.subplot(325)
plt.plot(pY1)
plt.title('fase onda 1')
plt.subplot(322)
plt.plot(x2)
plt.title('onda 2 ')
plt.subplot(324)
plt.plot(absY2)
plt.title('Espectro 2')
plt.subplot(326)
plt.plot(pY2)
plt.title('fase onda 2')
indx1=np.array([48355,49307,50265, 51222,52167])
indx2=np.array([48073,48606,49138, 50203])
f1=f[indx1]#np.array([443.7, 886.63, 1329.94])
f2=f[indx2]#np.array([312.6, 560.54, 808.01] )
A2=absY1[indx1]#np.array([0.02638, 0.13159, 0.03147])
A1=absY2[indx2]#np.array([0.0270,0.02018,0.00362])
p1=pY1[indx1]#np.array([-14.42432594, -70.36247253, -68.44787598])
p2=pY2[indx2]#np.array([-131.58657837, -428.93927002, -783.9352417 ])
y1=np.zeros(t.size)
y2=np.zeros(t.size)
for i in range(3):
fii=A1[i]*np.cos(2*np.pi*f1[i]*t+p1[i])
y1=y1+fii
fii=A2[i]*np.cos(2*np.pi*f2[i]*t+p2[i])
y2=y2+fii
plt.figure(2)
plt.subplot(211)
plt.plot(y1)
plt.title('onda 1')
plt.subplot(212)
plt.plot(y2)
plt.title('onda 2')
plt.show()
| #Milton Orlando Sarria
#analisis espectral de sinusoides
import matplotlib.pyplot as plt
import numpy as np
from fourierFunc import fourierAn
import wav_rw as wp
filename1='sound/flute-A4.wav'
filename2='sound/violin-B3.wav'
#leer los archivos de audio
fs,x1=wp.wavread(filename1)
fs,x2=wp.wavread(filename2)
t=(np.arange(1,5*fs))/float(fs)
#calcular el espectro de las ondas
absY1,mY1,pY1=fourierAn(x1)
absY2,mY2,pY2=fourierAn(x2)
#vector de frecuencias, desde -fs/2 a fs/2 (-pi<w<pi)
f=np.linspace(-fs/2,fs/2,absY1.size)
#visualizar las dos ondas
plt.subplot(321)
plt.plot(x1)
plt.title('onda sin ruido')
plt.subplot(323)
plt.plot(absY1)
plt.title('Espectro onda 1')
plt.subplot(325)
plt.plot(pY1)
plt.title('fase onda 1')
plt.subplot(322)
plt.plot(x2)
plt.title('onda 2 ')
plt.subplot(324)
plt.plot(absY2)
plt.title('Espectro 2')
plt.subplot(326)
plt.plot(pY2)
plt.title('fase onda 2')
#indx1=np.array([48355 49307 50260])
#indx1=np.array([48073 48606 49138]
f1=np.array([443.7, 886.63, 1329.94])
f2=np.array([312.6, 560.54, 808.01] )
A2=np.array([0.02638, 0.13159, 0.03147])
A1=np.array([0.0270,0.02018,0.00362])
y1=np.zeros(t.size)
y2=np.zeros(t.size)
for i in range(3):
fii=A1[i]*np.cos(2*np.pi*f1[i]*t)
y1=y1+fii
fii=A2[i]*np.cos(2*np.pi*f2[i]*t)
y2=y2+fii
plt.figure(2)
plt.subplot(211)
plt.plot(y1)
plt.title('onda 1')
plt.subplot(212)
plt.plot(y2)
plt.title('onda 2')
plt.show()
| mit | Python |
53b43e51c4d073dae4f3ccad896ba1744ca1284b | Update version | edx/auth-backends | auth_backends/_version.py | auth_backends/_version.py | __version__ = '0.1.2' # pragma: no cover
| __version__ = '0.1.1' # pragma: no cover
| agpl-3.0 | Python |
2321ddb5f6d7731597f4f122a87041933348f064 | Enable Unicode tests | DataONEorg/d1_python,DataONEorg/d1_python,DataONEorg/d1_python,DataONEorg/d1_python | gmn/src/d1_gmn/tests/test_unicode.py | gmn/src/d1_gmn/tests/test_unicode.py | # -*- coding: utf-8 -*-
# This work was created by participants in the DataONE project, and is
# jointly copyrighted by participating institutions in DataONE. For
# more information on DataONE, see our web site at http://dataone.org.
#
# Copyright 2009-2016 DataONE
#
# 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.
"""Test handling of Unicode in D1 REST URLs and type elements
"""
from __future__ import absolute_import
import logging
import responses
import d1_gmn.tests.gmn_test_case
import d1_common
import d1_common.system_metadata
class TestUnicode(d1_gmn.tests.gmn_test_case.GMNTestCase):
@responses.activate
def test_1000(self, mn_client_v1_v2):
"""Unicode: GMN and libraries handle Unicode correctly"""
with d1_gmn.tests.gmn_mock.disable_auth():
tricky_unicode_str = self.load_sample_utf8_to_unicode(
'tricky_identifiers_unicode.utf8.txt'
)
for line in tricky_unicode_str.splitlines():
pid_unescaped, pid_escaped = line.split('\t')
logging.debug(u'Testing PID: {}'.format(pid_unescaped))
pid, sid, send_sciobj_str, send_sysmeta_pyxb = self.create_obj(
mn_client_v1_v2, pid=pid_unescaped, sid=True
)
recv_sciobj_str, recv_sysmeta_pyxb = self.get_obj(mn_client_v1_v2, pid)
assert d1_common.system_metadata.is_equivalent_pyxb(
send_sysmeta_pyxb, recv_sysmeta_pyxb, ignore_timestamps=True
)
assert pid == pid_unescaped
assert recv_sysmeta_pyxb.identifier.value() == pid_unescaped
mn_client_v1_v2.delete(pid)
| # -*- coding: utf-8 -*-
# This work was created by participants in the DataONE project, and is
# jointly copyrighted by participating institutions in DataONE. For
# more information on DataONE, see our web site at http://dataone.org.
#
# Copyright 2009-2016 DataONE
#
# 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.
"""Test handling of Unicode in D1 REST URLs and type elements
"""
from __future__ import absolute_import
import logging
import pytest
import responses
import d1_gmn.tests.gmn_test_case
import d1_common
import d1_common.system_metadata
@pytest.mark.skip('TODO')
class TestUnicode(d1_gmn.tests.gmn_test_case.GMNTestCase):
@responses.activate
def test_1000(self):
"""Unicode: GMN and libraries handle Unicode correctly"""
def test(client):
tricky_unicode_str = self.load_sample_utf8_to_unicode(
'tricky_identifiers_unicode.utf8.txt'
)
for line in tricky_unicode_str.splitlines():
pid_unescaped, pid_escaped = line.split('\t')
logging.debug(u'Testing PID: {}'.format(pid_unescaped))
pid, sid, send_sciobj_str, send_sysmeta_pyxb = self.create_obj(
client, pid=pid_unescaped, sid=True
)
recv_sciobj_str, recv_sysmeta_pyxb = self.get_obj(client, pid)
# self.assertEquals(send_sciobj_str, recv_sciobj_str)
assert d1_common.system_metadata.is_equivalent_pyxb(
send_sysmeta_pyxb, recv_sysmeta_pyxb, ignore_timestamps=True
)
client.delete(pid)
with d1_gmn.tests.gmn_mock.disable_auth():
test(self.client_v1)
test(self.client_v2)
| apache-2.0 | Python |
3868a4ef30835ed1904a37318013e20f2295a8a9 | Remove fantastic from COB theme | City-of-Bloomington/ckanext-cob,City-of-Bloomington/ckanext-cob | ckanext/cob/plugin.py | ckanext/cob/plugin.py | import ckan.plugins as plugins
import ckan.plugins.toolkit as toolkit
def groups():
# Return a list of groups
return toolkit.get_action('group_list')(data_dict={'all_fields': True})
def dataset_count():
# Return a count of all datasets
result = toolkit.get_action('package_search')(data_dict={'rows': 1})
return result['count']
class CobPlugin(plugins.SingletonPlugin):
plugins.implements(plugins.IConfigurer)
plugins.implements(plugins.ITemplateHelpers)
# IConfigurer
def update_config(self, config_):
toolkit.add_template_directory(config_, 'templates')
toolkit.add_public_directory(config_, 'public')
def get_helpers(self):
# Register cob_theme_* helper functions
return {'cob_theme_groups': groups,
'cob_theme_dataset_count': dataset_count}
| import ckan.plugins as plugins
import ckan.plugins.toolkit as toolkit
def groups():
# Return a list of groups
return toolkit.get_action('group_list')(data_dict={'all_fields': True})
def dataset_count():
# Return a count of all datasets
result = toolkit.get_action('package_search')(data_dict={'rows': 1})
return result['count']
class CobPlugin(plugins.SingletonPlugin):
plugins.implements(plugins.IConfigurer)
plugins.implements(plugins.ITemplateHelpers)
# IConfigurer
def update_config(self, config_):
toolkit.add_template_directory(config_, 'templates')
toolkit.add_public_directory(config_, 'public')
toolkit.add_resource('fanstatic', 'cob')
def get_helpers(self):
# Register cob_theme_* helper functions
return {'cob_theme_groups': groups,
'cob_theme_dataset_count': dataset_count}
| agpl-3.0 | Python |
46c1c21c0190aa95f4fede8fa1d98bbae7cf38c5 | test mode defaults to true - fix for #21 | NaturalHistoryMuseum/ckanext-doi,NaturalHistoryMuseum/ckanext-doi,NaturalHistoryMuseum/ckanext-doi | ckanext/doi/config.py | ckanext/doi/config.py | #!/usr/bin/env python
# encoding: utf-8
"""
Created by 'bens3' on 2013-06-21.
Copyright (c) 2013 'bens3'. All rights reserved.
"""
from pylons import config
from paste.deploy.converters import asbool
TEST_PREFIX = '10.5072'
ENDPOINT = 'https://mds.datacite.org'
TEST_ENDPOINT = 'https://test.datacite.org/mds'
def get_test_mode():
"""
Get test mode as boolean
@return:
"""
return asbool(config.get("ckanext.doi.test_mode", True))
def get_prefix():
"""
Get the prefix to use for DOIs
@return: test prefix if we're in test mode, otherwise config prefix setting
"""
return TEST_PREFIX if get_test_mode() else config.get("ckanext.doi.prefix")
def get_endpoint():
"""
Get the DataCite endpoint
@return: test endpoint if we're in test mode
"""
return TEST_ENDPOINT if get_test_mode() else ENDPOINT
def get_site_url():
"""
Get the site URL
Try and use ckanext.doi.site_url but if that's not set use ckan.site_url
@return:
"""
site_url = config.get("ckanext.doi.site_url")
if not site_url:
site_url = config.get('ckan.site_url')
return site_url.rstrip('/') | #!/usr/bin/env python
# encoding: utf-8
"""
Created by 'bens3' on 2013-06-21.
Copyright (c) 2013 'bens3'. All rights reserved.
"""
from pylons import config
from paste.deploy.converters import asbool
TEST_PREFIX = '10.5072'
ENDPOINT = 'https://mds.datacite.org'
TEST_ENDPOINT = 'https://test.datacite.org/mds'
def get_test_mode():
"""
Get test mode as boolean
@return:
"""
return asbool(config.get("ckanext.doi.test_mode"))
def get_prefix():
"""
Get the prefix to use for DOIs
@return: test prefix if we're in test mode, otherwise config prefix setting
"""
return TEST_PREFIX if get_test_mode() else config.get("ckanext.doi.prefix")
def get_endpoint():
"""
Get the DataCite endpoint
@return: test endpoint if we're in test mode
"""
return TEST_ENDPOINT if get_test_mode() else ENDPOINT
def get_site_url():
"""
Get the site URL
Try and use ckanext.doi.site_url but if that's not set use ckan.site_url
@return:
"""
site_url = config.get("ckanext.doi.site_url")
if not site_url:
site_url = config.get('ckan.site_url')
return site_url.rstrip('/') | mit | Python |
bf8ab86d536570790d135f0f46c97ffb30a83535 | update background_substraction.py | cmput402w2016/CMPUT402W16T2 | background_subtraction.py | background_subtraction.py | # Reference: http://docs.opencv.org/master/db/d5c/tutorial_py_bg_subtraction.html
# requires opencv v3.1.0
import numpy as np
import cv2
# TODO: remove hard coded file name
cap = cv2.VideoCapture('videos/sample_video_2.mp4')
# Here are the 3 ways of background subtraction
# createBackgroundSubtractorMOG2 seems to give the best result. Need more testing.
fgbg = cv2.createBackgroundSubtractorMOG2()
#fgbg = cv2.bgsegm.createBackgroundSubtractorMOG()
#fgbg = cv2.bgsegm.createBackgroundSubtractorGMG()
while(1):
ret, frame = cap.read()
fgmask = fgbg.apply(frame)
cv2.imshow('frame',fgmask)
k = cv2.waitKey(30) & 0xff
if k == 27:
break
cap.release()
cv2.destroyAllWindows()
| # Reference: http://docs.opencv.org/master/db/d5c/tutorial_py_bg_subtraction.html
import numpy as np
import cv2
# TODO: remove hard coded file name
cap = cv2.VideoCapture('videos/sample_video_2.mp4')
# Here are the 3 ways of background subtraction
# createBackgroundSubtractorMOG2 seems to give the best result. Need more testing.
fgbg = cv2.createBackgroundSubtractorMOG2()
#fgbg = cv2.bgsegm.createBackgroundSubtractorMOG()
#fgbg = cv2.bgsegm.createBackgroundSubtractorGMG()
while(1):
ret, frame = cap.read()
fgmask = fgbg.apply(frame)
cv2.imshow('frame',fgmask)
k = cv2.waitKey(30) & 0xff
if k == 27:
break
cap.release()
cv2.destroyAllWindows()
| apache-2.0 | Python |
1f815ad5cb7535132a60297808abfa959709ba65 | Fix redirect_to_login | aipescience/django-daiquiri,aipescience/django-daiquiri,aipescience/django-daiquiri | daiquiri/files/views.py | daiquiri/files/views.py | import logging
from django.contrib.auth.views import redirect_to_login
from django.core.exceptions import PermissionDenied
from django.http import Http404
from django.views.generic import View
from .utils import file_exists, check_file, send_file
logger = logging.getLogger(__name__)
class FileView(View):
def get(self, request, file_path):
# append 'index.html' when the file_path is a directory
if not file_path or file_path.endswith('/'):
file_path += 'index.html'
if not file_exists(file_path):
logger.debug('%s not found', file_path)
raise Http404
if check_file(request.user, file_path):
return send_file(request, file_path)
else:
logger.debug('%s if forbidden', file_path)
if request.user.is_authenticated:
raise PermissionDenied
else:
return redirect_to_login(request.path_info)
# if nothing worked, return 404
raise Http404
| import logging
from django.core.exceptions import PermissionDenied
from django.http import Http404
from django.shortcuts import redirect
from django.views.generic import View
from .utils import file_exists, check_file, send_file
logger = logging.getLogger(__name__)
class FileView(View):
def get(self, request, file_path):
# append 'index.html' when the file_path is a directory
if not file_path or file_path.endswith('/'):
file_path += 'index.html'
if not file_exists(file_path):
logger.debug('%s not found', file_path)
raise Http404
if check_file(request.user, file_path):
return send_file(request, file_path)
else:
logger.debug('%s if forbidden', file_path)
if request.user.is_authenticated:
raise PermissionDenied
else:
return redirect('account_login')
# if nothing worked, return 404
raise Http404
| apache-2.0 | Python |
3ce5f60102d5de7367a06e7412e9e31597e40a58 | revert to original hello world | tylerdave/PyTN2016-Click-Tutorial,tylerdave/PyTN2016-Click-Tutorial | click_tutorial/cli.py | click_tutorial/cli.py | import click
@click.command()
def cli():
click.echo("Hello, World!")
if __name__ == '__main__':
cli()
| import click
@click.argument('name')
@click.command()
def cli(name):
click.echo("Hello, {0}!".format(name))
if __name__ == '__main__':
cli()
| mit | Python |
d44250f60e9676618170bd61f8f6bc438078ef87 | Add celery settings. | klen/fquest | base/config/production.py | base/config/production.py | " Production settings must be here. "
from .core import *
from os import path as op
SECRET_KEY = 'SecretKeyForSessionSigning'
ADMINS = frozenset([MAIL_USERNAME])
# flask.ext.collect
# -----------------
COLLECT_STATIC_ROOT = op.join(op.dirname(ROOTDIR), 'static')
# dealer
DEALER_PARAMS = dict(
backends=('git', 'mercurial', 'simple', 'null')
)
# FQUEST settings
# ---------------
AUTH_LOGIN_VIEW = 'fquest.index'
AUTH_PROFILE_VIEW = 'fquest.profile'
OAUTH_FACEBOOK = dict(
consumer_key='365449256868307',
consumer_secret='899b2ea26ca77122eef981f4712aeb04',
params=dict(
scope="user_status,user_likes,user_activities,user_questions,user_events,user_videos,user_groups,user_relationships,user_notes,user_photos,offline_access,publish_actions"
)
)
# Cache
CACHE_TYPE = 'redis'
CACHE_REDIS_HOST = 'localhost'
CACHE_KEY_PREFIX = 'poliglot'
# Database settings
SQLALCHEMY_DATABASE_URI = 'postgresql+psycopg2://fquest:fquest@localhost:5432/fquest_master'
# Celery settings
BROKER_URL = 'redis://localhost:6379/0'
# pymode:lint_ignore=W0614,W404
| " Production settings must be here. "
from .core import *
from os import path as op
SECRET_KEY = 'SecretKeyForSessionSigning'
ADMINS = frozenset([MAIL_USERNAME])
# flask.ext.collect
# -----------------
COLLECT_STATIC_ROOT = op.join(op.dirname(ROOTDIR), 'static')
# dealer
DEALER_PARAMS = dict(
backends=('git', 'mercurial', 'simple', 'null')
)
# FQUEST settings
# ---------------
AUTH_LOGIN_VIEW = 'fquest.index'
AUTH_PROFILE_VIEW = 'fquest.profile'
OAUTH_FACEBOOK = dict(
consumer_key='365449256868307',
consumer_secret='899b2ea26ca77122eef981f4712aeb04',
params=dict(
scope="user_status,user_likes,user_activities,user_questions,user_events,user_videos,user_groups,user_relationships,user_notes,user_photos,offline_access,publish_actions"
)
)
# Cache
CACHE_TYPE = 'redis'
CACHE_REDIS_HOST = 'localhost'
CACHE_KEY_PREFIX = 'poliglot'
# Database settings
SQLALCHEMY_DATABASE_URI = 'postgresql+psycopg2://fquest:fquest@localhost:5432/fquest_master'
# pymode:lint_ignore=W0614,W404
| bsd-3-clause | Python |
871f49eea1197af8224c601833e6e96f59697eb3 | Update phishing_database.py | yeti-platform/yeti,yeti-platform/yeti,yeti-platform/yeti,yeti-platform/yeti | plugins/feeds/public/phishing_database.py | plugins/feeds/public/phishing_database.py | #!/usr/bin/env python
"""This class will incorporate the PhishingDatabase feed into yeti."""
from datetime import timedelta
import logging
from core.observables import Url
from core.feed import Feed
from core.errors import ObservableValidationError
class PhishingDatabase(Feed):
"""This class will pull the PhishingDatabase feed from github on a 12 hour interval."""
default_values = {
'frequency': timedelta(hours=12),
'name': 'PhishingDatabase',
'source': 'https://raw.githubusercontent.com/mitchellkrogza/Phishing.Database/master/phishing-links-NEW-today.txt',
'description':
'Phishing Domains, urls websites and threats database.'
}
def update(self):
for url in self.update_lines():
self.analyze(url)
def analyze(self, url):
context = {'source': self.name}
try:
url = Url.get_or_create(value=url)
url.add_context(context)
url.add_source(self.name)
url.tag(['phishing'])
except ObservableValidationError as e:
logging.error(e)
| from datetime import timedelta
import logging
from core.observables import Url
from core.feed import Feed
from core.errors import ObservableValidationError
class PhishingDatabase(Feed):
""" This class will pull the PhishingDatabase feed from github on a 12 hour interval. """
default_values = {
'frequency': timedelta(hours=12),
'name': 'PhishingDatabase',
'source': 'https://raw.githubusercontent.com/mitchellkrogza/Phishing.Database/master/phishing-links-NEW-today.txt',
'description':
'Phishing Domains, urls websites and threats database.'
}
def update(self):
for url in self.update_lines():
self.analyze(url)
def analyze(self, url):
context = {'source': self.name}
try:
url = Url.get_or_create(value=url)
url.add_context(context)
url.add_source(self.name)
url.tag(['phishing'])
except ObservableValidationError as e:
logging.error(e)
| apache-2.0 | Python |
453e50823d3fb7a5937311e9118abbcbd5309855 | Implement a bunch more rare neutral minions | liujimj/fireplace,Ragowit/fireplace,smallnamespace/fireplace,liujimj/fireplace,Meerkov/fireplace,Meerkov/fireplace,amw2104/fireplace,smallnamespace/fireplace,jleclanche/fireplace,oftc-ftw/fireplace,Ragowit/fireplace,beheh/fireplace,butozerca/fireplace,amw2104/fireplace,butozerca/fireplace,oftc-ftw/fireplace,NightKev/fireplace | fireplace/carddata/minions/neutral/rare.py | fireplace/carddata/minions/neutral/rare.py | import random
from ...card import *
from fireplace.enums import Race
# Injured Blademaster
class CS2_181(Card):
def action(self):
self.damage(4)
# Young Priestess
class EX1_004(Card):
def endTurn(self):
other_minions = [t for t in self.controller.field if t is not self]
if other_minions:
random.choice(other_minions).buff("EX1_004e")
class EX1_004e(Card):
health = 1
# Coldlight Oracle
class EX1_050(Card):
def action(self):
self.controller.draw(2)
self.controller.opponent.draw(2)
# Arcane Golem
class EX1_089(Card):
def action(self):
self.controller.opponent.gainMana(1)
# Defender of Argus
class EX1_093(Card):
def action(self):
for target in self.adjacentMinions:
target.buff("EX1_093e")
class EX1_093e(Card):
atk = 1
health = 1
taunt = True
# Abomination
class EX1_097(Card):
def deathrattle(self):
for target in self.controller.getTargets(TARGET_ALL_CHARACTERS):
target.damage(2)
# Coldlight Seer
class EX1_103(Card):
def action(self):
for minion in self.controller.field:
if minion.race == Race.MURLOC:
minion.buff("EX1_103e")
class EX1_103e(Card):
health = 2
# Ancient Mage
class EX1_584(Card):
def action(self):
for target in self.adjacentMinions:
target.buff("EX1_584e")
class EX1_584e(Card):
spellpower = 1
# Imp Master
class EX1_597(Card):
def endTurn(self):
self.damage(1)
self.controller.summon("EX1_598")
# Nerubian Egg
class FP1_007(Card):
deathrattle = summonMinion("FP1_007t")
# Sludge Belcher
class FP1_012(Card):
deathrattle = summonMinion("FP1_012t")
# Bloodsail Corsair
class NEW1_025(Card):
def action(self):
weapon = self.controller.opponent.hero.weapon
if self.controller.opponent.hero.weapon:
weapon.loseDurability(1)
# Master Swordsmith
class NEW1_037(Card):
def endTurn(self):
other_minions = [t for t in self.controller.field if t is not self]
if other_minions:
random.choice(other_minions).buff("NEW1_037e")
class NEW1_037e(Card):
atk = 1
# Stampeding Kodo
class NEW1_041(Card):
def action(self):
targets = [t for t in self.controller.opponent.field if t.atk <= 2]
if targets:
random.choice(targets).destroy()
| from ...card import *
# Abomination
class EX1_097(Card):
def deathrattle(self):
for target in self.controller.getTargets(TARGET_ALL_CHARACTERS):
target.damage(2)
# Bloodsail Corsair
class NEW1_025(Card):
def action(self):
weapon = self.controller.opponent.hero.weapon
if self.controller.opponent.hero.weapon:
weapon.loseDurability(1)
| agpl-3.0 | Python |
730489e4f6a7f3067ad67c16512c2cbcb97f3272 | stop gap on astronmical solar zenith | samsammurphy/gee-atmcorr-S2-batch | bin/astronomical.py | bin/astronomical.py | """
astronomical.py, Sam Murphy (2017-04-27)
Astronomical calculations (e.g. solar angles) for
processing satellite imagery through Google Earth
Engine.
"""
import ee
class Astronomical:
pi = 3.141592653589793
degToRad = pi / 180 # degress to radians
radToDeg = 180 / pi # radians to degress
def sin(x):return ee.Number(x).sin()
def cos(x):return ee.Number(x).cos()
def radians(x):return ee.Number(x).multiply(Astronomical.degToRad)
def degrees(x):return ee.Number(x).multiply(Astronomical.radToDeg)
def dayOfYear(date):
jan01 = ee.Date.fromYMD(date.get('year'),1,1)
doy = date.difference(jan01,'day').toInt().add(1)
return doy
def solarDeclination(date):
"""
Calculates the solar declination angle (radians)
https://en.wikipedia.org/wiki/Position_of_the_Sun
simple version..
d = ee.Number(.doy).add(10).multiply(0.017214206).cos().multiply(-23.44)
a more accurate version used here..
"""
doy = Astronomical.dayOfYear(date)
N = ee.Number(doy).subtract(1)
solstice = N.add(10).multiply(0.985653269)
eccentricity = N.subtract(2).multiply(0.985653269).multiply(Astronomical.degToRad).sin().multiply(1.913679036)
axial_tilt = ee.Number(-23.44).multiply(Astronomical.degToRad).sin()
return solstice.add(eccentricity).multiply(Astronomical.degToRad).cos().multiply(axial_tilt).asin()
def solarZenith(geom,date):
"""
Calculates solar zenith angle (degrees)
https://en.wikipedia.org/wiki/Solar_zenith_angle
"""
latitude = Astronomical.radians(geom.centroid().coordinates().get(1))
d = Astronomical.solarDeclination(date)
hourAngle = Astronomical.radians(date.get('hour').subtract(12).multiply(15))
sines = Astronomical.sin(latitude).multiply(Astronomical.sin(d))
cosines = Astronomical.cos(latitude).multiply(Astronomical.cos(d)).multiply(Astronomical.cos(hourAngle))
solar_z = sines.add(cosines).acos()
return 'need to check this out'#solar_z.multiply(Astronomical.radToDeg) | """
astronomical.py, Sam Murphy (2017-04-27)
Astronomical calculations (e.g. solar angles) for
processing satellite imagery through Google Earth
Engine.
"""
import ee
class Astronomical:
pi = 3.141592653589793
degToRad = pi / 180 # degress to radians
radToDeg = 180 / pi # radians to degress
def sin(x):return ee.Number(x).sin()
def cos(x):return ee.Number(x).cos()
def radians(x):return ee.Number(x).multiply(Astronomical.degToRad)
def degrees(x):return ee.Number(x).multiply(Astronomical.radToDeg)
def dayOfYear(date):
jan01 = ee.Date.fromYMD(date.get('year'),1,1)
doy = date.difference(jan01,'day').toInt().add(1)
return doy
def solarDeclination(date):
"""
Calculates the solar declination angle (radians)
https://en.wikipedia.org/wiki/Position_of_the_Sun
simple version..
d = ee.Number(.doy).add(10).multiply(0.017214206).cos().multiply(-23.44)
a more accurate version used here..
"""
doy = Astronomical.dayOfYear(date)
N = ee.Number(doy).subtract(1)
solstice = N.add(10).multiply(0.985653269)
eccentricity = N.subtract(2).multiply(0.985653269).multiply(Astronomical.degToRad).sin().multiply(1.913679036)
axial_tilt = ee.Number(-23.44).multiply(Astronomical.degToRad).sin()
return solstice.add(eccentricity).multiply(Astronomical.degToRad).cos().multiply(axial_tilt).asin()
def solarZenith(geom,date):
"""
Calculates solar zenith angle (degrees)
https://en.wikipedia.org/wiki/Solar_zenith_angle
"""
latitude = Astronomical.radians(geom.centroid().coordinates().get(1))
d = Astronomical.solarDeclination(date)
hourAngle = Astronomical.radians(date.get('hour').subtract(12).multiply(15))
sines = Astronomical.sin(latitude).multiply(Astronomical.sin(d))
cosines = Astronomical.cos(latitude).multiply(Astronomical.cos(d)).multiply(Astronomical.cos(hourAngle))
solar_z = sines.add(cosines).acos()
return solar_z.multiply(Astronomical.radToDeg) | apache-2.0 | Python |
9e3becba368e5cc916c9af99a89e62e502d0a506 | Fix syntax error in urls | sevazhidkov/greenland,sevazhidkov/greenland | greenland/urls.py | greenland/urls.py | """greenland URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib import admin
import maps.views
urlpatterns = [
url(r'^$', maps.views.index, name='index'),
url(r'^admin/', admin.site.urls),
url(r'^start/(?P<question_set_id>\d+)/', maps.views.start, name='start'),
url(r'^choice/', maps.views.get_choice, name='choice'),
url(r'^run/(?P<answer_set_id>\d+)/(?P<index>\d+)', maps.views.run, name='task'),
url(r'^results/(?P<answer_set_id>\d+)', maps.views.results, name='results'),
url(r'^api/', include('maps.api.urls'))
]
| """greenland URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib import admin
import maps.views
urlpatterns = [
url(r'^$', maps.views.index, name='index'),
url(r'^admin/', admin.site.urls),
url(r'^start/(?P<question_set_id>\d+)/', maps.views.start, name='start'),
url(r'^choice/', maps.views.get_choice, name='choice'),
url(r'^run/(?P<answer_set_id>\d+)/(?P<index>\d+)', maps.views.run, name='task'),
url(r'^results/(?P<answer_set_id>\d+)', maps.views.results, name='results')
url(r'^api/', include('maps.api.urls'))
]
| mit | Python |
dbd3999ff1df5d031b7a800a2d2417f041b2ed29 | Expand build script for 4 scenarios | ankur-gos/PSL-Bipedal,ankur-gos/PSL-Bipedal | build.py | build.py | '''
build.py
Script to build and run everything
Ankur Goswami, [email protected]
'''
import config
import preprocessing.parser.parse as parser
import preprocessing.preprocessing as preprocesser
import subprocess
import output.filter_truth as ft
'''
build_cleaned_default
run the default pipeline using the cleaned segments
'''
def build_default(cleaned=True):
pass
def build_cleaned_default():
cleaned_obs = parser.parse_cleaned_segments(config.data_path)
parser.write_obs(cleaned_obs, config.seg_path, config.start_loc_path, config.end_loc_path, config.start_time_path, config.end_time_path, config.mode_path, config.segment_day_path)
preprocesser.run(config.start_loc_path, config.end_loc_path)
subprocess.call(['./run.sh'])
ft.filter('./output/default/frequents_infer.txt', config.cleaned_frequent_results_path)
'''
build_constructed_default
run the default pipeline using the constructed segments
'''
def build_constructed_default():
obs = parser.parse_segments(config.data_path)
parser.write_obs(cleaned_obs, config.seg_path, config.start_loc_path, config.end_loc_path, config.start_time_path, config.end_time_path, config.mode_path, config.segment_day_path)
preprocesser.run(config.start_loc_path, config.end_loc_path)
subprocess.call(['./run.sh'])
ft.filter('./output/default/frequents_infer.txt', config.cleaned_frequent_results_path)
def build_cleaned_clustered():
cleaned_obs = parser.parse_cleaned_segments(config.data_path)
parser.write_obs(cleaned_obs, config.seg_path, config.start_loc_path, config.end_loc_path, config.start_time_path, config.end_time_path, config.mode_path, config.segment_day_path)
preprocesser.run_with_assignment(config.start_loc_path, config.end_loc_path)
subprocess.call(['./run.sh'])
ft.filter('./output/default/frequents_infer.txt', config.cleaned_frequent_results_path)
def build_constructed_clustered():
obs = parser.parse_segments(config.data_path)
parser.write_obs(cleaned_obs, config.seg_path, config.start_loc_path, config.end_loc_path, config.start_time_path, config.end_time_path, config.mode_path, config.segment_day_path)
preprocesser.run_with_assignment(config.start_loc_path, config.end_loc_path)
subprocess.call(['./run.sh'])
ft.filter('./output/default/frequents_infer.txt', config.cleaned_frequent_results_path)
build_cleaned_default() | '''
build.py
Script to build and run everything
Ankur Goswami, [email protected]
'''
import config
import preprocessing.parser.parse as parser
import preprocessing.preprocessing as preprocesser
import subprocess
import output.filter_truth as ft
'''
build_cleaned_default
run the default pipeline using the cleaned segments
'''
def build_cleaned_default():
cleaned_obs = parser.parse_cleaned_segments(config.data_path)
parser.write_obs(cleaned_obs, config.seg_path, config.start_loc_path, config.end_loc_path, config.start_time_path, config.end_time_path, config.mode_path, config.segment_day_path)
preprocesser.run(config.start_loc_path, config.end_loc_path)
subprocess.call(['./run.sh'])
ft.filter('./output/default/frequents_infer.txt', config.cleaned_frequent_results_path)
'''
build_constructed_default
run the default pipeline using the constructed segments
'''
def build_constructed_default():
pass
build_cleaned_default() | mit | Python |
548edcb10ef949d394388282d052da36135982d7 | Add coveralls support[5]. | filipecn/Ponos,filipecn/Ponos,filipecn/Ponos | build.py | build.py | #!/usr/bin/python
import os
import shutil
from subprocess import call
import sys
import platform
cur_path = os.getcwd()
build_path = os.getcwd() + "/build"
if platform.system() == 'Windows':
build_path = os.getcwd() + "/win_build"
if 'test' in sys.argv:
os.chdir(build_path)
r = call(["make tests"], shell=True)
exit(r)
if 'docs' in sys.argv:
call(["doxygen Doxyfile"], shell=True)
call(
["xsltproc doc/xml/combine.xslt doc/xml/index.xml > doc/xml/all.xml"],
shell=True)
call(["python doxml2md.py doc/xml/all.xml"], shell=True)
sys.exit(0)
if 'all' in sys.argv or not os.path.exists(build_path):
if os.path.exists(build_path):
shutil.rmtree(build_path, ignore_errors=True)
if not os.path.exists(build_path):
os.mkdir(build_path)
os.chdir(build_path)
if platform.system() == 'Windows':
call(["cmake"] + ['-G'] + ['Visual Studio 15 2017 Win64'] +
sys.argv[2:] + [cur_path])
else:
call(["cmake"] + sys.argv[2:] + [cur_path])
os.chdir(build_path)
if platform.system() == 'Windows':
make_result =\
call([r"MSBuild.exe"] + [r"/p:Configuration=Release"] +
[r"/p:Machine=X64"] + ["PONOS.sln"],
shell=True)
else:
make_result = call(["make -j8"], shell=True)
if "-DTRAVIS=1" not in sys.argv:
call(["make install"], shell=True)
if make_result != 0:
sys.exit(1)
| #!/usr/bin/python
import os
import shutil
from subprocess import call
import sys
import platform
cur_path = os.getcwd()
build_path = os.getcwd() + "/build"
if platform.system() == 'Windows':
build_path = os.getcwd() + "/win_build"
if 'test' in sys.argv:
os.chdir(build_path)
r = call(["make tests"], shell=True)
exit(r)
if 'docs' in sys.argv:
call(["doxygen Doxyfile"], shell=True)
call(
["xsltproc doc/xml/combine.xslt doc/xml/index.xml > doc/xml/all.xml"],
shell=True)
call(["python doxml2md.py doc/xml/all.xml"], shell=True)
sys.exit(0)
if 'all' in sys.argv or not os.path.exists(build_path):
if os.path.exists(build_path):
shutil.rmtree(build_path, ignore_errors=True)
if not os.path.exists(build_path):
os.mkdir(build_path)
os.chdir(build_path)
if platform.system() == 'Windows':
call(["cmake"] + ['-G'] + ['Visual Studio 15 2017 Win64'] +
sys.argv[2:] + [cur_path])
else:
call(["cmake"] + sys.argv[2:] + [cur_path])
os.chdir(build_path)
if platform.system() == 'Windows':
make_result =\
call([r"MSBuild.exe"] + [r"/p:Configuration=Release"] +
[r"/p:Machine=X64"] + ["PONOS.sln"],
shell=True)
else:
make_result = call(["make -j8"], shell=True)
call(["make install"], shell=True)
if make_result != 0:
sys.exit(1)
| mit | Python |
df41dcb3c8538e482bcc61f9817ce26569652b6b | build script set user data for git | ervitis/logging_service,ervitis/logging_service | build.py | build.py | # -*- coding: utf-8 -*-
import os
import sh
from logging_service import __version__ as version
GIT_USER = 'circle-ci'
GIT_EMAIL = '[email protected]'
def open_file(path):
return open(path, 'r+')
def get_git(repo_path):
return sh.git.bake(_cwd=repo_path)
def set_user_data_git(git):
git('config', '--global', 'user.email', GIT_EMAIL)
git('config', '--global', 'user.name', GIT_USER)
def main():
file_build = open_file('build_version')
lines = file_build.readlines()
build_version_old = lines[0]
build_version_new = str(int(build_version_old) + 1)
lines = [line.replace(build_version_old, build_version_new) for line in lines]
file_build.seek(0)
file_build.writelines(lines)
file_build.close()
repo_path = os.path.abspath(os.path.dirname(__file__))
git = get_git(repo_path)
set_user_data_git(git)
git('add', '-u')
new_tag_version = version + '-' + build_version_old
feature_message = 'feat: auto tag ' + new_tag_version
git('commit', '-m', feature_message)
git('push', 'origin', 'master')
git('tag', new_tag_version)
git('push', 'origin', '--tags')
if __name__ == '__main__':
main()
| # -*- coding: utf-8 -*-
import os
import sh
from logging_service import __version__ as version
def open_file(path):
return open(path, 'r+')
def get_git(repo_path):
return sh.git.bake(_cwd=repo_path)
def main():
file_build = open_file('build_version')
lines = file_build.readlines()
build_version_old = lines[0]
build_version_new = str(int(build_version_old) + 1)
lines = [line.replace(build_version_old, build_version_new) for line in lines]
file_build.seek(0)
file_build.writelines(lines)
file_build.close()
repo_path = os.path.abspath(os.path.dirname(__file__))
git = get_git(repo_path)
git('add', '-u')
new_tag_version = version + '-' + build_version_old
feature_message = 'feat: auto tag ' + new_tag_version
git('commit', '-m', feature_message)
git('push', 'origin', 'master')
git('tag', new_tag_version)
git('push', 'origin', '--tags')
if __name__ == '__main__':
main()
| mit | Python |
54b8e07ac412e757fb32ebfa19b75ef8a72f6688 | Print build path | jzf2101/release,jzf2101/release,datamicroscopes/release,datamicroscopes/release | build.py | build.py | #!/usr/bin/env python
import sys
import os
from argparse import ArgumentParser
from subprocess import check_call, check_output
def ensure_tool(name):
check_call(['which', name])
def build_and_publish(path, args):
login_command = get_login_command(args)
print >>sys.stderr, "Test anaconda.org login:"
check_call(login_command)
binfile = check_output(['conda', 'build', '--output', path])
binfile = binfile.strip()
print >>sys.stderr, "build path {}".format(binfile)
print >>sys.stderr, "conda build {}".format(path)
check_call(['conda', 'build', path])
upload_command = "binstar upload --force {}".format(binfile)
login_and_upload_command = "{} && {}".format(login_command, upload_command)
print >>sys.stderr, "Login to binstar and upload"
check_call(login_and_upload_command)
def get_login_command(args):
return ("binstar login --hostname {hostname} "
" --username {username} --password {password}")\
.format(
hostname='https://api.anaconda.org',
username=args.username,
password=args.password,
)
def get_conda_recipes_dir(project):
# make sure the project has a conda recipes folder
conda_recipes_dir = os.path.join(project, 'conda')
if not os.path.isdir(conda_recipes_dir):
sys.exit('no such dir: {}'.format(conda_recipes_dir))
return conda_recipes_dir
def conda_paths(conda_recipes_dir):
for name in sorted(os.listdir(conda_recipes_dir)):
yield os.path.join(conda_recipes_dir, name)
def main():
parser = ArgumentParser()
parser.add_argument('-u', '--username', required=True)
parser.add_argument('-P', '--password', required=True)
parser.add_argument('-p', '--project', required=True)
parser.add_argument('-s', '--site', required=False, default=None)
args = parser.parse_args()
# make sure we have a conda environment
ensure_tool('conda')
ensure_tool('binstar')
conda_recipes_dir = get_conda_recipes_dir(args.project)
for conda_path in conda_paths(conda_recipes_dir):
build_and_publish(conda_path, args)
return 0
if __name__ == '__main__':
sys.exit(main())
| #!/usr/bin/env python
import sys
import os
from argparse import ArgumentParser
from subprocess import check_call, check_output
def ensure_tool(name):
check_call(['which', name])
def build_and_publish(path, args):
login_command = get_login_command(args)
print >>sys.stderr, "Test anaconda.org login:"
check_call(login_command)
binfile = check_output(['conda', 'build', '--output', path])
binfile = binfile.strip()
print >>sys.stderr, "conda build {}".format(path)
check_call(['conda', 'build', path])
upload_command = "binstar upload --force {}".format(binfile)
login_and_upload_command = "{} && {}".format(login_command, upload_command)
print >>sys.stderr, "Login to binstar and upload"
check_call(login_and_upload_command)
def get_login_command(args):
return ("binstar login --hostname {hostname} "
" --username {username} --password {password}")\
.format(
hostname='https://api.anaconda.org',
username=args.username,
password=args.password,
)
def get_conda_recipes_dir(project):
# make sure the project has a conda recipes folder
conda_recipes_dir = os.path.join(project, 'conda')
if not os.path.isdir(conda_recipes_dir):
sys.exit('no such dir: {}'.format(conda_recipes_dir))
return conda_recipes_dir
def conda_paths(conda_recipes_dir):
for name in sorted(os.listdir(conda_recipes_dir)):
yield os.path.join(conda_recipes_dir, name)
def main():
parser = ArgumentParser()
parser.add_argument('-u', '--username', required=True)
parser.add_argument('-P', '--password', required=True)
parser.add_argument('-p', '--project', required=True)
parser.add_argument('-s', '--site', required=False, default=None)
args = parser.parse_args()
# make sure we have a conda environment
ensure_tool('conda')
ensure_tool('binstar')
conda_recipes_dir = get_conda_recipes_dir(args.project)
for conda_path in conda_paths(conda_recipes_dir):
build_and_publish(conda_path, args)
return 0
if __name__ == '__main__':
sys.exit(main())
| bsd-3-clause | Python |
3d52e82a295c7c7d6b77d81a1d2c6ac0929bb120 | make sqlitecache bundable. | cournape/sqlite_cache | sqlite_cache/__init__.py | sqlite_cache/__init__.py | from __future__ import absolute_import
from .core import SQLiteCache # pragma: no cover
| from sqlite_cache.core import SQLiteCache # pragma: no cover
| bsd-3-clause | Python |
60690c178f3adb5a2e05e4960e3b142dbf6c1aad | update cache | yonoho/utils | cache.py | cache.py | import inspect
import json as json
from functools import wraps
from hashlib import md5
def cache_json(func, key_prefix='', expire=0, expire_at='', redis_client=None):
"""key_prefix is optional.
if use, it should be unique at module level within the redis db,
__module__ & func_name & all arguments would also be part of the key.
redis_client: it's thread safe.
to avoid giving `redis_client` param every time, you could do this:
from functools import partial
from somewhere import my_redis_client
cache_json = partial(cache_json, redis_client=my_redis_client)
"""
@wraps(func)
def wrapped(_use_cache=True, *args, **kwargs):
"""set _use_cache to False if you do not want to use cache on this call.
"""
if _use_cache:
call_args = inspect.getcallargs(func, *args, **kwargs)
func_code = inspect.getsource(func)
args_hash = md5(json.dumps(call_args, sort_keys=True).encode()).hexdigest()
key = key_prefix + func.__module__ + func.__name__ + args_hash
cached = redis_client.get(key)
if cached is None:
ret = func(*args, **kwargs)
redis_client[key] = json.dumps(ret)
else:
ret = json.loads(cached)
return ret
else:
return func(*args, **kwargs)
return wrapped
def release_cache(func):
return
| import json as json
def cache_json(func, key_prefix='', expire=0, expire_at='', redis_client=None):
"""key_prefix should be unique at module level within the redis db,
func name & all arguments would also be part of the key.
redis_client: it's thread safe.
to avoid giving `redis_client` param every time, you could do this:
from functools import partial
from somewhere import my_redis_client
cache_json = partial(cache_json, redis_client=my_redis_client)
"""
def wrapped(_use_cache=True, *args, **kwargs):
if _use_cache:
return
else:
ret = func(*args, **kwargs)
return ret
return wrapped
| mit | Python |
c40376c36312e582704b4fafbc36f4b17171394f | switch to using selectors | roadhump/SublimeLinter-eslint | linter.py | linter.py | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by roadhump
# Copyright (c) 2014 roadhump
#
# License: MIT
#
"""This module exports the ESLint plugin class."""
import logging
import re
from SublimeLinter.lint import NodeLinter
logger = logging.getLogger('SublimeLinter.plugin.eslint')
class ESLint(NodeLinter):
"""Provides an interface to the eslint executable."""
npm_name = 'eslint'
cmd = ('eslint', '--format', 'compact', '--stdin', '--stdin-filename', '@')
regex = (
r'^.+?: line (?P<line>\d+), col (?P<col>\d+), '
r'(?:(?P<error>Error)|(?P<warning>Warning)) - '
r'(?P<message>.+)'
)
crash_regex = re.compile(
r'^(.*?)\r?\n\w*(Oops! Something went wrong!)',
re.DOTALL
)
line_col_base = (1, 1)
defaults = {
'selector': 'source.js - meta.attribute-with-value, text.html.basic'
}
def find_errors(self, output):
"""Parse errors from linter's output.
Log errors when eslint crashes or can't find its configuration.
"""
match = self.crash_regex.match(output)
if match:
logger.error(output)
return []
return super().find_errors(output)
def split_match(self, match):
"""Extract and return values from match.
Return 'no match' for ignored files
"""
match, line, col, error, warning, message, near = super().split_match(match)
if message and message.startswith('File ignored'):
return match, None, None, None, None, '', None
return match, line, col, error, warning, message, near
| #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by roadhump
# Copyright (c) 2014 roadhump
#
# License: MIT
#
"""This module exports the ESLint plugin class."""
import logging
import re
from SublimeLinter.lint import NodeLinter
logger = logging.getLogger('SublimeLinter.plugin.eslint')
class ESLint(NodeLinter):
"""Provides an interface to the eslint executable."""
syntax = ('javascript', 'html')
npm_name = 'eslint'
cmd = ('eslint', '--format', 'compact', '--stdin', '--stdin-filename', '@')
regex = (
r'^.+?: line (?P<line>\d+), col (?P<col>\d+), '
r'(?:(?P<error>Error)|(?P<warning>Warning)) - '
r'(?P<message>.+)'
)
crash_regex = re.compile(
r'^(.*?)\r?\n\w*(Oops! Something went wrong!)',
re.DOTALL
)
line_col_base = (1, 1)
selectors = {
'html': 'source.js.embedded.html'
}
def find_errors(self, output):
"""Parse errors from linter's output.
Log errors when eslint crashes or can't find its configuration.
"""
match = self.crash_regex.match(output)
if match:
logger.error(output)
return []
return super().find_errors(output)
def split_match(self, match):
"""Extract and return values from match.
Return 'no match' for ignored files
"""
match, line, col, error, warning, message, near = super().split_match(match)
if message and message.startswith('File ignored'):
return match, None, None, None, None, '', None
return match, line, col, error, warning, message, near
| mit | Python |
6a9d6d30dc7ea207e2f4d8179a5ef99a95fce4e5 | Fix bug in ListingGenerator with limit=None. | praw-dev/praw,darthkedrik/praw,nmtake/praw,gschizas/praw,RGood/praw,darthkedrik/praw,leviroth/praw,gschizas/praw,praw-dev/praw,13steinj/praw,RGood/praw,leviroth/praw,13steinj/praw,nmtake/praw | praw/models/listinggenerator.py | praw/models/listinggenerator.py | from .prawmodel import PRAWModel
class ListingGenerator(PRAWModel):
"""Instances of this class generate ``RedditModels``"""
def __init__(self, reddit, url, limit=100, params=None):
"""Initialize a ListingGenerator instance.
:param reddit: An instance of :class:`.Reddit`.
:param url: A URL returning a reddit listing.
:param limit: The number of content entries to fetch. If ``limit`` is
None, then fetch as many entries as possible. Most of reddit's
listings contain a maximum of 1000 items, and are returned 100 at a
time. This class will automatically issue all necessary
requests. (Default: 100)
:param params: A dictionary containing additional query string
parameters to send with the request.
"""
self._exhausted = False
self._list = None
self._list_index = None
self._reddit = reddit
self.after_field = 'after'
self.extract_list_index = None
self.limit = limit
self.params = params or {}
self.root_field = 'data'
self.thing_list_field = 'children'
self.url = url
self.yielded = 0
self.params['limit'] = self.limit or 1024
def __iter__(self):
return self
def __next__(self):
if self.limit is not None and self.yielded >= self.limit:
raise StopIteration()
if self._list is None or self._list_index >= len(self._list):
self._next_batch()
self._list_index += 1
self.yielded += 1
return self._list[self._list_index - 1]
def _next_batch(self):
if self._exhausted:
raise StopIteration()
page_data = self._reddit.request(self.url, params=self.params)
if self.extract_list_index is not None:
page_data = page_data[self.extract_list_index]
root = page_data[self.root_field]
self._list = root[self.thing_list_field]
self._list_index = 0
if len(self._list) == 0:
raise StopIteration()
if root.get(self.after_field):
self.params['after'] = root[self.after_field]
else:
self._exhausted = True
| from .prawmodel import PRAWModel
class ListingGenerator(PRAWModel):
"""Instances of this class generate ``RedditModels``"""
def __init__(self, reddit, url, limit=100, params=None):
"""Initialize a ListingGenerator instance.
:param reddit: An instance of :class:`.Reddit`.
:param url: A URL returning a reddit listing.
:param limit: The number of content entries to fetch. If ``limit`` is
None, then fetch as many entries as possible. Most of reddit's
listings contain a maximum of 1000 items, and are returned 100 at a
time. This class will automatically issue all necessary
requests. (Default: 100)
:param params: A dictionary containing additional query string
parameters to send with the request.
"""
self._exhausted = False
self._list = None
self._list_index = None
self._reddit = reddit
self.after_field = 'after'
self.extract_list_index = None
self.limit = limit
self.params = params or {}
self.root_field = 'data'
self.thing_list_field = 'children'
self.url = url
self.yielded = 0
self.params['limit'] = self.limit or 1024
def __iter__(self):
return self
def __next__(self):
if self.yielded >= self.limit:
raise StopIteration()
if self._list is None or self._list_index >= len(self._list):
self._next_batch()
self._list_index += 1
self.yielded += 1
return self._list[self._list_index - 1]
def _next_batch(self):
if self._exhausted:
raise StopIteration()
page_data = self._reddit.request(self.url, params=self.params)
if self.extract_list_index is not None:
page_data = page_data[self.extract_list_index]
root = page_data[self.root_field]
self._list = root[self.thing_list_field]
self._list_index = 0
if len(self._list) == 0:
raise StopIteration()
if root.get(self.after_field):
self.params['after'] = root[self.after_field]
else:
self._exhausted = True
| bsd-2-clause | Python |
bf7562d9f45a777163f2ac775dc9cf4afe99a930 | Change 'language' to 'syntax', that is more precise terminology. | tylertebbs20/Practice-SublimeLinter-jshint,tylertebbs20/Practice-SublimeLinter-jshint,SublimeLinter/SublimeLinter-jshint | linter.py | linter.py | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Aparajita Fishman
# Copyright (c) 2013 Aparajita Fishman
#
# Project: https://github.com/SublimeLinter/SublimeLinter-contrib-jshint
# License: MIT
#
"""This module exports the JSHint plugin linter class."""
from SublimeLinter.lint import Linter
class JSHint(Linter):
"""Provides an interface to the jshint executable."""
syntax = ('javascript', 'html')
cmd = 'jshint --verbose -'
regex = r'^.+?: line (?P<line>\d+), col (?P<col>\d+), (?P<message>.+) \((?:(?P<error>E)|(?P<warning>W))\d+\)$'
selectors = {
'html': 'source.js.embedded.html'
}
| #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Aparajita Fishman
# Copyright (c) 2013 Aparajita Fishman
#
# Project: https://github.com/SublimeLinter/SublimeLinter-contrib-jshint
# License: MIT
#
"""This module exports the JSHint plugin linter class."""
from SublimeLinter.lint import Linter
class JSHint(Linter):
"""Provides an interface to the jshint executable."""
language = ('javascript', 'html')
cmd = 'jshint --verbose -'
regex = r'^.+?: line (?P<line>\d+), col (?P<col>\d+), (?P<message>.+) \((?:(?P<error>E)|(?P<warning>W))\d+\)$'
selectors = {
'html': 'source.js.embedded.html'
}
| mit | Python |
cea40608a1efe16310c7b978fba40abcde26ced4 | make flake8 happy | Flet/SublimeLinter-contrib-semistandard | linter.py | linter.py | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Dan Flettre
# Copyright (c) 2015 Dan Flettre
#
# License: MIT
#
"""This module exports the Semistandard plugin class."""
from SublimeLinter.lint import NodeLinter
class Semistandard(NodeLinter):
"""Provides an interface to semistandard."""
syntax = ('javascript', 'html', 'javascriptnext', 'javascript 6to5')
cmd = 'semistandard'
version_args = '--version'
version_re = r'(?P<version>\d+\.\d+\.\d+)'
version_requirement = '>= 2.3.1'
regex = r'^\s.+:(?P<line>\d+):(?P<col>\d+):(?P<message>.+)'
selectors = {
'html': 'source.js.embedded.html'
}
| #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Dan Flettre
# Copyright (c) 2015 Dan Flettre
#
# License: MIT
#
"""This module exports the Semistandard plugin class."""
from SublimeLinter.lint import NodeLinter, util
class Semistandard(NodeLinter):
"""Provides an interface to semistandard."""
syntax = ('javascript', 'html', 'javascriptnext', 'javascript 6to5')
cmd = 'semistandard'
version_args = '--version'
version_re = r'(?P<version>\d+\.\d+\.\d+)'
version_requirement = '>= 2.3.1'
regex = r'^\s.+:(?P<line>\d+):(?P<col>\d+):(?P<message>.+)'
selectors = {
'html': 'source.js.embedded.html'
}
| mit | Python |
9bfe8cd21931c69d79657aa275be02af21ec78f1 | Simplify `cmd` property | codequest-eu/SublimeLinter-contrib-reek | linter.py | linter.py | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Bartosz Kruszczynski
# Copyright (c) 2015 Bartosz Kruszczynski
#
# License: MIT
#
"""This module exports the Reek plugin class."""
from SublimeLinter.lint import RubyLinter
import re
class Reek(RubyLinter):
"""Provides an interface to reek."""
syntax = (
'better rspec',
'betterruby',
'cucumber steps',
'rspec',
'ruby experimental',
'ruby on rails',
'ruby'
)
cmd = 'reek'
regex = r'^.+?\[(?P<line>\d+).*\]:(?P<message>.+) \[.*\]'
tempfile_suffix = 'rb'
version_re = r'reek\s(?P<version>\d+\.\d+\.\d+)'
version_requirement = '>= 3.5.0'
config_file = ('-c', 'config.reek')
def split_match(self, match):
"""Extract named capture groups from the regex and return them as a tuple."""
match, line, col, error, warning, message, _ = super().split_match(match)
near = self.search_token(message)
return match, line, col, error, warning, message, near
def search_token(self, message):
"""Search text token to be highlighted."""
# First search for variable name enclosed in single quotes
m = re.search("'.*'", message)
# If there's no variable name search for nil-check message
if m is None:
m = re.search('nil(?=-check)', message)
# If there's no nil-check search for method name that comes after a `#`
if m is None:
m = re.search('(?<=#)\S+', message)
return m.group(0) if m else None
| #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Bartosz Kruszczynski
# Copyright (c) 2015 Bartosz Kruszczynski
#
# License: MIT
#
"""This module exports the Reek plugin class."""
from SublimeLinter.lint import RubyLinter
import re
class Reek(RubyLinter):
"""Provides an interface to reek."""
syntax = (
'better rspec',
'betterruby',
'cucumber steps',
'rspec',
'ruby experimental',
'ruby on rails',
'ruby'
)
cmd = 'ruby -S reek'
regex = r'^.+?\[(?P<line>\d+).*\]:(?P<message>.+) \[.*\]'
tempfile_suffix = 'rb'
version_args = '-S reek -v'
version_re = r'reek\s(?P<version>\d+\.\d+\.\d+)'
version_requirement = '>= 3.5.0'
config_file = ('-c', 'config.reek')
def split_match(self, match):
"""Extract named capture groups from the regex and return them as a tuple."""
match, line, col, error, warning, message, _ = super().split_match(match)
near = self.search_token(message)
return match, line, col, error, warning, message, near
def search_token(self, message):
"""Search text token to be highlighted."""
# First search for variable name enclosed in single quotes
m = re.search("'.*'", message)
# If there's no variable name search for nil-check message
if m is None:
m = re.search('nil(?=-check)', message)
# If there's no nil-check search for method name that comes after a `#`
if m is None:
m = re.search('(?<=#)\S+', message)
return m.group(0) if m else None
| mit | Python |
68293b6075ead70651924761e4e3187286ad6765 | Add the proper tests user/pass. | grandmasterchef/WhatManager2,MADindustries/WhatManager2,MADindustries/WhatManager2,MADindustries/WhatManager2,karamanolev/WhatManager2,karamanolev/WhatManager2,grandmasterchef/WhatManager2,karamanolev/WhatManager2,grandmasterchef/WhatManager2,davols/WhatManager2,davols/WhatManager2,davols/WhatManager2,karamanolev/WhatManager2,MADindustries/WhatManager2,grandmasterchef/WhatManager2 | integration_tests/test_basic_page_loads.py | integration_tests/test_basic_page_loads.py | from django.contrib.auth.models import User
from django.test import testcases
from django.test.client import Client
class Fail(testcases.TestCase):
def setUp(self):
super(Fail, self).setUp()
u = User(username='john_doe')
u.set_password('password')
u.is_superuser = True
u.save()
self.client = Client()
def test_require_login(self):
response = self.client.get('/')
self.assertEqual(response.status_code, 302)
self.assertEqual(response.url, 'http://testserver/user/login?next=/')
def test_login(self):
response = self.client.post('/user/login?next=/',
{'username': 'john_doe', 'password': 'password'})
self.assertEqual(response.status_code, 302)
self.assertEqual(response.url, 'http://testserver/')
response = self.client.get('/')
self.assertEqual(response.status_code, 200)
def test_login_redirect_correct(self):
response = self.client.post('/user/login?next=/dummy_url',
{'username': 'john_doe', 'password': 'password'})
self.assertEqual(response.status_code, 302)
self.assertEqual(response.url, 'http://testserver/dummy_url')
def test_profile(self):
self.client.post('/user/login',
{'username': 'john_doe', 'password': 'password'})
response = self.client.get('/profile/')
self.assertEqual(response.status_code, 200)
| from django.contrib.auth.models import User
from django.test import testcases
from django.test.client import Client
class Fail(testcases.TestCase):
def setUp(self):
super(Fail, self).setUp()
u = User(username='john_doe')
u.set_password('password')
u.is_superuser = True
u.save()
self.client = Client()
def test_require_login(self):
response = self.client.get('/')
self.assertEqual(response.status_code, 302)
self.assertEqual(response.url, 'http://testserver/user/login?next=/')
def test_login(self):
response = self.client.post('/user/login?next=/',
{'username': 'ivailo', 'password': 'Heman3f5'})
self.assertEqual(response.status_code, 302)
self.assertEqual(response.url, 'http://testserver/')
response = self.client.get('/')
self.assertEqual(response.status_code, 200)
def test_login_redirect_correct(self):
response = self.client.post('/user/login?next=/dummy_url',
{'username': 'ivailo', 'password': 'Heman3f5'})
self.assertEqual(response.status_code, 302)
self.assertEqual(response.url, 'http://testserver/dummy_url')
def test_profile(self):
self.client.post('/user/login',
{'username': 'ivailo', 'password': 'Heman3f5'})
response = self.client.get('/profile/')
self.assertEqual(response.status_code, 200)
| mit | Python |
853dc8de1d077494c707a5ec8a6b75ac0e0628cf | Add trailing slash to URL for consistency. | kurtraschke/cadors-parse,kurtraschke/cadors-parse | cadorsfeed/views.py | cadorsfeed/views.py | from werkzeug import redirect, Response
from werkzeug.exceptions import NotFound
from cadorsfeed.utils import expose, url_for, db
from parse import parse
from fetch import fetchLatest, fetchReport
@expose('/report/latest/')
def latest_report(request):
if 'latest' in db:
latestDate = db['latest']
else:
latestDate = fetchLatest()
db['latest'] = latestDate
db.expire('latest',60*60)
(year, month, day) = latestDate.split('-')
return redirect(url_for('do_report', year=year, month=month, day=day))
@expose('/report/<int:year>/<int:month>/<int:day>/')
def do_report(request, year, month, day):
refetch = request.args.get('refetch','0') == '1'
reparse = request.args.get('reparse','0') == '1' or refetch
date = "{year:04.0f}-{month:02.0f}-{day:02.0f}".format(
year=year, month=month, day=day)
key = "report:"+date
if db.hexists(key, "output") and not reparse:
output = db.hget(key, "output")
else:
if db.hexists(key, "input") and not refetch:
input = db.hget(key, "input").decode('utf-8')
else:
input = fetchReport(date)
db.hset(key, "input", input)
output = parse(input)
db.hset(key,"output", output)
return Response(output, mimetype="application/atom+xml")
| from werkzeug import redirect, Response
from werkzeug.exceptions import NotFound
from cadorsfeed.utils import expose, url_for, db
from parse import parse
from fetch import fetchLatest, fetchReport
@expose('/report/latest')
def latest_report(request):
if 'latest' in db:
latestDate = db['latest']
else:
latestDate = fetchLatest()
db['latest'] = latestDate
db.expire('latest',60*60)
(year, month, day) = latestDate.split('-')
return redirect(url_for('do_report', year=year, month=month, day=day))
@expose('/report/<int:year>/<int:month>/<int:day>/')
def do_report(request, year, month, day):
refetch = request.args.get('refetch','0') == '1'
reparse = request.args.get('reparse','0') == '1' or refetch
date = "{year:04.0f}-{month:02.0f}-{day:02.0f}".format(
year=year, month=month, day=day)
key = "report:"+date
if db.hexists(key, "output") and not reparse:
output = db.hget(key, "output")
else:
if db.hexists(key, "input") and not refetch:
input = db.hget(key, "input").decode('utf-8')
else:
input = fetchReport(date)
db.hset(key, "input", input)
output = parse(input)
db.hset(key,"output", output)
return Response(output, mimetype="application/atom+xml")
| mit | Python |
cb50a43435de4e3b62324d1b738f3775cabe7367 | Fix reverse url in RecentChangesFeed | mysociety/yournextmp-popit,mysociety/yournextrepresentative,mysociety/yournextrepresentative,mysociety/yournextmp-popit,mysociety/yournextrepresentative,mysociety/yournextrepresentative,mysociety/yournextrepresentative,mysociety/yournextmp-popit,mysociety/yournextmp-popit,mysociety/yournextmp-popit | candidates/feeds.py | candidates/feeds.py | from __future__ import unicode_literals
import re
from django.contrib.sites.models import Site
from django.contrib.syndication.views import Feed
from django.core.urlresolvers import reverse
from django.utils.feedgenerator import Atom1Feed
from django.utils.text import slugify
from django.utils.translation import ugettext_lazy as _
from .models import LoggedAction
lock_re = re.compile(r'^(?:Unl|L)ocked\s*constituency (.*) \((\d+)\)$')
class RecentChangesFeed(Feed):
site_name = Site.objects.get_current().name
title = _("{site_name} recent changes").format(site_name=site_name)
description = _("Changes to {site_name} candidates").format(site_name=site_name)
link = "/feeds/changes.xml"
feed_type = Atom1Feed
def items(self):
return LoggedAction.objects.order_by('-updated')[:50]
def item_title(self, item):
return "{0} - {1}".format(
item.person_id,
item.action_type
)
def item_description(self, item):
updated = _("Updated at {0}").format(str(item.updated))
description = "{0}\n\n{1}\n".format(item.source, updated)
return description
def item_link(self, item):
# As a hack for the moment, constituencies are just mentioned
# in the source message:
if item.person_id:
return reverse('person-view', args=[item.person_id])
else:
return '/'
| from __future__ import unicode_literals
import re
from django.contrib.sites.models import Site
from django.contrib.syndication.views import Feed
from django.core.urlresolvers import reverse
from django.utils.feedgenerator import Atom1Feed
from django.utils.text import slugify
from django.utils.translation import ugettext_lazy as _
from .models import LoggedAction
lock_re = re.compile(r'^(?:Unl|L)ocked\s*constituency (.*) \((\d+)\)$')
class RecentChangesFeed(Feed):
site_name = Site.objects.get_current().name
title = _("{site_name} recent changes").format(site_name=site_name)
description = _("Changes to {site_name} candidates").format(site_name=site_name)
link = "/feeds/changes.xml"
feed_type = Atom1Feed
def items(self):
return LoggedAction.objects.order_by('-updated')[:50]
def item_title(self, item):
m = lock_re.search(item.source)
if m:
return "{0} - {1}".format(
m.group(1),
item.action_type
)
else:
return "{0} - {1}".format(
item.person_id,
item.action_type
)
def item_description(self, item):
updated = _("Updated at {0}").format(str(item.updated))
description = "{0}\n\n{1}\n".format(item.source, updated)
return description
def item_link(self, item):
# As a hack for the moment, constituencies are just mentioned
# in the source message:
m = lock_re.search(item.source)
if m:
return reverse('constituency', kwargs={
'post_id': m.group(2),
'ignored_slug': slugify(m.group(1))
})
else:
if item.person_id:
return reverse('person-view', args=[item.person_id])
else:
return '/'
| agpl-3.0 | Python |
847d9c4a1e88b9e00a3be082db635743866a8abd | Fix tests | tiagoengel/udacity-item-catalog,tiagoengel/udacity-item-catalog,tiagoengel/udacity-item-catalog,tiagoengel/udacity-item-catalog | catalog/__init__.py | catalog/__init__.py | from os import environ
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
DB_URL = 'postgresql:///catalog' + ('_test' if environ.get('ENV') == 'test' else '')
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = DB_URL
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
if environ.get('ENV') != 'test':
from flask_wtf.csrf import CSRFProtect
csrf = CSRFProtect()
csrf.init_app(app)
else:
app.jinja_env.globals['csrf_token'] = lambda: 'test' | from os import environ
from flask import Flask
from flask_wtf.csrf import CSRFProtect
from flask_sqlalchemy import SQLAlchemy
DB_URL = 'postgresql:///catalog' + ('_test' if environ.get('ENV') == 'test' else '')
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = DB_URL
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
csrf = CSRFProtect()
csrf.init_app(app) | mit | Python |
147a24ea0ba9da03b3774b7993e20e785776e027 | Use sys.nstates in stead of using A.shape[0] | python-control/python-control | control/passivity.py | control/passivity.py | '''
Author: Mark Yeatman
Date: May 15, 2022
'''
from . import statesp as ss
import numpy as np
import cvxopt as cvx
def is_passive(sys):
'''
Indicates if a linear time invarient system is passive
Constructs a linear matrix inequality and a feasibility optimization
such that is a solution exists, the system is passive.
The source for the algorithm is:
McCourt, Michael J., and Panos J. Antsaklis. "Demonstrating passivity and dissipativity using computational methods." ISIS 8 (2013).
'''
A = sys.A
B = sys.B
C = sys.C
D = sys.D
def make_LMI_matrix(P):
V = np.vstack((
np.hstack((A.T @ P + P@A, P@B)),
np.hstack((B.T@P, np.zeros_like(D))))
)
return V
P = np.zeros_like(A)
matrix_list = []
state_space_size = sys.nstates
for i in range(0, state_space_size):
for j in range(0, state_space_size):
if j <= i:
P = P*0.0
P[i, j] = 1.0
P[j, i] = 1.0
matrix_list.append(make_LMI_matrix(P).flatten())
coefficents = np.vstack(matrix_list).T
constants = -np.vstack((
np.hstack((np.zeros_like(A), - C.T)),
np.hstack((- C, -D - D.T)))
)
number_of_opt_vars = int(
(state_space_size**2-state_space_size)/2 + state_space_size)
c = cvx.matrix(0.0, (number_of_opt_vars, 1))
# crunch feasibility solution
sol = cvx.solvers.sdp(c,
Gs=[cvx.matrix(coefficents)],
hs=[cvx.matrix(constants)])
return (sol["x"] is not None)
| '''
Author: Mark Yeatman
Date: May 15, 2022
'''
from . import statesp as ss
import numpy as np
import cvxopt as cvx
def is_passive(sys):
'''
Indicates if a linear time invarient system is passive
Constructs a linear matrix inequality and a feasibility optimization
such that is a solution exists, the system is passive.
The source for the algorithm is:
McCourt, Michael J., and Panos J. Antsaklis. "Demonstrating passivity and dissipativity using computational methods." ISIS 8 (2013).
'''
A = sys.A
B = sys.B
C = sys.C
D = sys.D
def make_LMI_matrix(P):
V = np.vstack((
np.hstack((A.T @ P + P@A, P@B)),
np.hstack((B.T@P, np.zeros_like(D))))
)
return V
P = np.zeros_like(A)
matrix_list = []
state_space_size = A.shape[0]
for i in range(0, state_space_size):
for j in range(0, state_space_size):
if j <= i:
P = P*0.0
P[i, j] = 1.0
P[j, i] = 1.0
matrix_list.append(make_LMI_matrix(P).flatten())
coefficents = np.vstack(matrix_list).T
constants = -np.vstack((
np.hstack((np.zeros_like(A), - C.T)),
np.hstack((- C, -D - D.T)))
)
number_of_opt_vars = int(
(state_space_size**2-state_space_size)/2 + state_space_size)
c = cvx.matrix(0.0, (number_of_opt_vars, 1))
# crunch feasibility solution
sol = cvx.solvers.sdp(c,
Gs=[cvx.matrix(coefficents)],
hs=[cvx.matrix(constants)])
return (sol["x"] is not None)
| bsd-3-clause | Python |
b8e556871ff4aff9b85c67cc010814a0e6f60386 | Add new constants and change existing file names. | isislovecruft/scramblesuit,isislovecruft/scramblesuit | const.py | const.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This module defines constant values for the ScrambleSuit protocol.
While some values can be changed, in general they should not. If you do not
obey, be at least careful because the protocol could easily break.
"""
# Length of the HMAC used to authenticate the ticket.
HMAC_KEY_LENGTH = 32
# Length of the AES key used to encrypt the ticket.
AES_KEY_LENGTH = 16
# FIXME - Directory where long-lived information is stored.
DATA_DIRECTORY = "/tmp/"
# Divisor (in seconds) for the UNIX epoch used to defend against replay
# attacks.
EPOCH_GRANULARITY = 3600
# Flags which can be set in a ScrambleSuit protocol message.
FLAG_PAYLOAD = (1 << 0)
FLAG_NEW_TICKET = (1 << 1)
FLAG_CONFIRM_TICKET = (1 << 2)
FLAG_PRNG_SEED = (1 << 3)
# Length of ScrambleSuit's header in bytes.
HDR_LENGTH = 16 + 2 + 2 + 1
# Length of the HMAC-SHA256-128 in bytes.
HMAC_LENGTH = 16
# Key rotation time for session ticket keys in seconds.
KEY_ROTATION_TIME = 60 * 60 * 24 * 7
# File where session ticket keys are stored.
KEY_STORE = DATA_DIRECTORY + "ticket_keys.pickle"
# Marker used to easily locate the HMAC authenticating handshake messages in
# bytes.
MARKER_LENGTH = 16
# Key length for the master key in bytes.
MASTER_KEY_LENGTH = 32
# The maximum amount of padding to be appended to handshake data.
MAX_PADDING_LENGTH = 4096
# Length of ScrambleSuit's MTU in bytes.
MTU = 1460
# Maximum payload unit of a ScrambleSuit message in bytes.
MPU = MTU - HDR_LENGTH
# Length of a UniformDH public key.
PUBLIC_KEY_LENGTH = 192
# Length of the PRNG seed used to generate probability distributions.
PRNG_SEED_LENGTH = 32
# Files which hold the replay dictionaries.
UNIFORMDH_REPLAY_FILE = DATA_DIRECTORY + "uniformdh_replay_dict.pickle"
TICKET_REPLAY_FILE = DATA_DIRECTORY + "ticket_replay_dict.pickle"
# File which holds the server's state information.
SERVER_STATE_FILE = DATA_DIRECTORY + "server_state.pickle"
# Life time of session tickets in seconds.
SESSION_TICKET_LIFETIME = 60 * 60 * 24 * 7
# SHA256's digest length in bytes.
SHA256_DIGEST_LENGTH = 32
# The length of the UniformDH shared secret in bytes.
SHARED_SECRET_LENGTH = 32
# States which are used for the protocol state machine.
ST_WAIT_FOR_AUTH = 0
ST_CONNECTED = 1
# File which holds our session ticket.
# FIXME - multiple session tickets for multiple servers must be supported.
TICKET_FILE = DATA_DIRECTORY + "session_ticket.pickle"
# Length of a session ticket in bytes.
TICKET_LENGTH = 112
# The protocol name which is used in log messages.
TRANSPORT_NAME = "ScrambleSuit"
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This module defines constant values for the ScrambleSuit protocol.
While some values can be changed, in general they should not. If you do not
obey, be at least careful because the protocol could easily break.
"""
# FIXME - Directory where long-lived information is stored.
DATA_DIRECTORY = "/tmp/"
# Divisor (in seconds) for the UNIX epoch used to defend against replay
# attacks.
EPOCH_GRANULARITY = 3600
# Flags which can be set in a ScrambleSuit protocol message.
FLAG_PAYLOAD = (1 << 0)
FLAG_NEW_TICKET = (1 << 1)
FLAG_CONFIRM_TICKET = (1 << 2)
# Length of ScrambleSuit's header in bytes.
HDR_LENGTH = 16 + 2 + 2 + 1
# Length of the HMAC-SHA256-128 in bytes.
HMAC_LENGTH = 16
# Key rotation time for session ticket keys in seconds.
KEY_ROTATION_TIME = 60 * 60 * 24 * 7
# File where session ticket keys are stored.
KEY_STORE = DATA_DIRECTORY + "ticket_keys.bin"
# Marker used to easily locate the HMAC authenticating handshake messages in
# bytes.
MARKER_LENGTH = 16
# Key length for the master key in bytes.
MASTER_KEY_LENGTH = 32
# The maximum amount of padding to be appended to handshake data.
MAX_PADDING_LENGTH = 4096
# Length of ScrambleSuit's MTU in bytes.
MTU = 1460
# Maximum payload unit of a ScrambleSuit message in bytes.
MPU = MTU - HDR_LENGTH
# Length of a UniformDH public key.
PUBLIC_KEY_LENGTH = 192
# Files which hold the replay dictionaries.
UNIFORMDH_REPLAY_FILE = DATA_DIRECTORY + "uniformdh_replay_dict.pickle"
TICKET_REPLAY_FILE = DATA_DIRECTORY + "ticket_replay_dict.pickle"
# Life time of session tickets in seconds.
SESSION_TICKET_LIFETIME = 60 * 60 * 24 * 7
# SHA256's digest length in bytes.
SHA256_DIGEST_LENGTH = 32
# The length of the UniformDH shared secret in bytes.
SHARED_SECRET_LENGTH = 32
# States which are used for the protocol state machine.
ST_WAIT_FOR_AUTH = 0
ST_CONNECTED = 1
# File which holds our session ticket.
# FIXME - multiple session tickets for multiple servers must be supported.
TICKET_FILE = DATA_DIRECTORY + "session_ticket.bin"
# Length of a session ticket in bytes.
TICKET_LENGTH = 112
# The protocol name which is used in log messages.
TRANSPORT_NAME = "ScrambleSuit"
| bsd-3-clause | Python |
2a030ce151cdb6eaaa3933bd7f958edf658ab209 | Make the parent directory part of the Python path for custom management commands to work. | pupeno/bonvortaro | manage.py | manage.py | #!/usr/bin/env python
import os
import sys
sys.path.append(os.path.abspath(".."))
from django.core.management import execute_manager
try:
import settings # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
sys.exit(1)
if __name__ == "__main__":
execute_manager(settings)
| #!/usr/bin/env python
from django.core.management import execute_manager
try:
import settings # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
sys.exit(1)
if __name__ == "__main__":
execute_manager(settings)
| agpl-3.0 | Python |
0feb5947af0dacc53ba624723593dd88b0b4653a | Fix shop creation | homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps,homeworkprod/byceps,m-ober/byceps,m-ober/byceps | byceps/services/shop/shop/service.py | byceps/services/shop/shop/service.py | """
byceps.services.shop.shop.service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2018 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from typing import Optional
from ....database import db
from ....typing import PartyID
from .models import Shop as DbShop
from .transfer.models import Shop, ShopID
def create_shop(party_id: PartyID) -> Shop:
"""Create a shop."""
shop = DbShop(party_id, party_id)
db.session.add(shop)
db.session.commit()
return _db_entity_to_shop(shop)
def find_shop(shop_id: ShopID) -> Optional[Shop]:
"""Return the shop with that id, or `None` if not found."""
shop = DbShop.query.get(shop_id)
return _db_entity_to_shop(shop)
def _db_entity_to_shop(shop: DbShop) -> Shop:
return Shop(
shop.id,
shop.party_id,
)
| """
byceps.services.shop.shop.service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2018 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from typing import Optional
from ....database import db
from ....typing import PartyID
from .models import Shop as DbShop
from .transfer.models import Shop, ShopID
def create_shop(party_id: PartyID) -> Shop:
"""Create a shop."""
shop = DbShop(party_id)
db.session.add(shop)
db.session.commit()
return _db_entity_to_shop(shop)
def find_shop(shop_id: ShopID) -> Optional[Shop]:
"""Return the shop with that id, or `None` if not found."""
shop = DbShop.query.get(shop_id)
return _db_entity_to_shop(shop)
def _db_entity_to_shop(shop: DbShop) -> Shop:
return Shop(
shop.id,
shop.party_id,
)
| bsd-3-clause | Python |
c0e903c3dab9fea0594d023ab9c049ca408bd9a4 | Cover text: outlined | Zomega/leech,kemayo/leech | cover.py | cover.py |
from PIL import Image, ImageDraw, ImageFont
from io import BytesIO
import textwrap
def make_cover(title, author, width=600, height=800, fontname="Helvetica", fontsize=40, bgcolor=(120, 20, 20), textcolor=(255, 255, 255), wrapat=30):
img = Image.new("RGBA", (width, height), bgcolor)
draw = ImageDraw.Draw(img)
title = textwrap.fill(title, wrapat)
author = textwrap.fill(author, wrapat)
font = ImageFont.truetype(font=fontname, size=fontsize)
title_size = draw.textsize(title, font=font)
draw_text_outlined(draw, ((width - title_size[0]) / 2, 100), title, textcolor, font=font)
# draw.text(((width - title_size[0]) / 2, 100), title, textcolor, font=font)
font = ImageFont.truetype(font=fontname, size=fontsize - 2)
author_size = draw.textsize(author, font=font)
draw_text_outlined(draw, ((width - author_size[0]) / 2, 100 + title_size[1] + 70), author, textcolor, font=font)
output = BytesIO()
img.save(output, "PNG")
output.name = 'cover.png'
# writing left the cursor at the end of the file, so reset it
output.seek(0)
return output
def draw_text_outlined(draw, xy, text, fill=None, font=None, anchor=None):
x, y = xy
# Outline
draw.text((x - 1, y), text=text, fill=(0, 0, 0), font=font, anchor=anchor)
draw.text((x + 1, y), text=text, fill=(0, 0, 0), font=font, anchor=anchor)
draw.text((x, y - 1), text=text, fill=(0, 0, 0), font=font, anchor=anchor)
draw.text((x, y + 1), text=text, fill=(0, 0, 0), font=font, anchor=anchor)
# Fill
draw.text(xy, text=text, fill=fill, font=font, anchor=anchor)
if __name__ == '__main__':
f = make_cover('Test of a Title which is quite long and will require multiple lines', 'Some Dude')
with open('output.png', 'wb') as out:
out.write(f.read())
|
from PIL import Image, ImageDraw, ImageFont
from io import BytesIO
import textwrap
def make_cover(title, author, width=600, height=800, fontname="Helvetica", fontsize=40, bgcolor=(120, 20, 20), textcolor=(255, 255, 255), wrapat=30):
img = Image.new("RGBA", (width, height), bgcolor)
draw = ImageDraw.Draw(img)
title = textwrap.fill(title, wrapat)
author = textwrap.fill(author, wrapat)
font = ImageFont.truetype(font=fontname, size=fontsize)
title_size = draw.textsize(title, font=font)
draw.text(((width - title_size[0]) / 2, 100), title, textcolor, font=font)
font = ImageFont.truetype(font=fontname, size=fontsize - 2)
author_size = draw.textsize(author, font=font)
draw.text(((width - author_size[0]) / 2, 100 + title_size[1] + 70), author, textcolor, font=font)
draw = ImageDraw.Draw(img)
output = BytesIO()
img.save(output, "PNG")
output.name = 'cover.png'
# writing left the cursor at the end of the file, so reset it
output.seek(0)
return output
if __name__ == '__main__':
f = make_cover('Test of a Title which is quite long and will require multiple lines', 'Some Dude')
with open('output.png', 'wb') as out:
out.write(f.read())
| mit | Python |
8c233868e82a6828d21574b0d488699c1c7b1443 | Update test_ValueType.py | nathanbjenx/cairis,failys/CAIRIS,failys/CAIRIS,failys/CAIRIS,nathanbjenx/cairis,nathanbjenx/cairis,nathanbjenx/cairis | cairis/cairis/test/test_ValueType.py | cairis/cairis/test/test_ValueType.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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 unittest
import os
import json
import BorgFactory
from Borg import Borg
from ValueTypeParameters import ValueTypeParameters
class ValueTypeTest(unittest.TestCase):
def setUp(self):
BorgFactory.initialise()
f = open(os.environ['CAIRIS_SRC'] + '/test/valuetypes.json')
d = json.load(f)
f.close()
self.iVtypes = d['valuetypes']
def testValueType(self):
ivt1 = ValueTypeParameters(self.iVtypes[0]["theName"], self.iVtypes[0]["theDescription"], self.iVtypes[0]["theType"])
ivt2 = ValueTypeParameters(self.iVtypes[1]["theName"], self.iVtypes[1]["theDescription"], self.iVtypes[1]["theType"])
b = Borg()
b.dbProxy.addValueType(ivt1)
b.dbProxy.addValueType(ivt2)
oVtypes = b.dbProxy.getValueTypes()
ovt1 = oVtypes[self.iVtypes[0]["theName"]]
self.assertEqual(ivt1.name(), ovt1.name())
self.assertEqual(ivt1.description(),ovt1.description())
self.assertEqual(ivt1.type(),ovt1.type())
ovt2 = oVtypes[self.iVtypes[1]["theName"]]
self.assertEqual(ivt2.name(), ovt2.name())
self.assertEqual(ivt2.description(),ovt2.description())
self.assertEqual(ivt2.type(),ovt2.type())
b.dbProxy.deleteVulnerabilityType(ovt1.id())
b.dbProxy.deleteThreatType(ovt2.id())
def tearDown(self):
b = Borg()
b.dbProxy.close()
if __name__ == '__main__':
unittest.main()
| # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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 unittest
import os
import json
import BorgFactory
from Borg import Borg
from ValueTypeParameters import ValueTypeParameters
class ValueTypeTest(unittest.TestCase):
def setUp(self):
BorgFactory.initialise()
f = open(os.environ['CAIRIS_SRC'] + '/test/valuetypes.json')
d = json.load(f)
f.close()
self.iVtypes = d['valuetypes']
def testValueType(self):
ivt1 = ValueTypeParameters(self.iVtypes[0]["theName"], self.iVtypes[0]["theDescription"], self.iVtypes[0]["vulnerability_type"])
ivt2 = ValueTypeParameters(self.iVtypes[1]["theName"], self.iVtypes[1]["theDescription"], self.iVtypes[1]["threat_type"])
b = Borg()
b.dbProxy.addValueType(ivt1)
b.dbProxy.addValueType(ivt2)
oVtypes = b.dbProxy.getValueTypes()
ovt1 = oVtypes[self.iVtypes[0]["theName"]]
self.assertEqual(ivt1.name(), ovt1.name())
self.assertEqual(ivt1.description(),ovt1.description())
self.assertEqual(ivt1.type(),ovt1.type())
ovt2 = oVtypes[self.iVtypes[1]["theName"]]
self.assertEqual(ivt2.name(), ovt2.name())
self.assertEqual(ivt2.description(),ovt2.description())
self.assertEqual(ivt2.type(),ovt2.type())
b.dbProxy.deleteVulnerabilityType(ovt1.id())
b.dbProxy.deleteThreatType(ovt2.id())
def tearDown(self):
b = Borg()
b.dbProxy.close()
if __name__ == '__main__':
unittest.main()
| apache-2.0 | Python |
7cac8f8ba591315d68e223503c4e93f976c8d89d | Set default race and class without extra database queries | mpirnat/django-tutorial-v2 | characters/views.py | characters/views.py | from django.shortcuts import get_object_or_404, redirect, render
from characters.forms import CharacterForm
from characters.models import Character, Class, Race
def index(request):
all_characters = Character.objects.all()
context = {'all_characters': all_characters}
return render(request, 'characters/index.html', context)
def view_character(request, character_id):
character = get_object_or_404(Character, pk=character_id)
context = {'character': character}
return render(request, 'characters/view_character.html', context)
def create_character(request):
form = CharacterForm(request.POST or None)
if request.method == 'POST' and form.is_valid():
character = Character(
name=request.POST['name'],
background=request.POST['background'],
race_id=1,
cclass_id=1
)
character.save()
return redirect('characters:view', character_id=character.id)
context = {'form': form}
return render(request, 'characters/create_character.html', context)
| from django.shortcuts import get_object_or_404, redirect, render
from characters.forms import CharacterForm
from characters.models import Character, Class, Race
def index(request):
all_characters = Character.objects.all()
context = {'all_characters': all_characters}
return render(request, 'characters/index.html', context)
def view_character(request, character_id):
character = get_object_or_404(Character, pk=character_id)
context = {'character': character}
return render(request, 'characters/view_character.html', context)
def create_character(request):
form = CharacterForm(request.POST or None)
if request.method == 'POST' and form.is_valid():
race = Race.objects.get(id=1)
cclass = Class.objects.get(id=1)
character = Character(
name=request.POST['name'],
background=request.POST['background'],
race=race,
cclass=cclass
)
character.save()
return redirect('characters:view', character_id=character.id)
context = {'form': form}
return render(request, 'characters/create_character.html', context)
| mit | Python |
daabf57935c9bec91ee4ce0bcd4713790fe928ea | use celery | Impactstory/total-impact-webapp,Impactstory/total-impact-webapp,total-impact/total-impact-webapp,Impactstory/total-impact-webapp,total-impact/total-impact-webapp,Impactstory/total-impact-webapp,total-impact/total-impact-webapp,total-impact/total-impact-webapp | daily.py | daily.py | from totalimpactwebapp.user import User
from totalimpactwebapp import db
import datetime
import tasks
"""
requires these env vars be set in this environment:
DATABASE_URL
"""
def page_query(q):
offset = 0
while True:
r = False
for elem in q.limit(100).offset(offset):
r = True
yield elem
offset += 100
if not r:
break
def add_profile_deets_for_everyone():
for user in page_query(User.query.order_by(User.url_slug.asc())):
print user.url_slug
tasks.add_profile_deets.delay(user)
def deduplicate_everyone():
for user in page_query(User.query.order_by(User.url_slug.asc())):
print user.url_slug
removed_tiids = tasks.deduplicate.delay(user)
def put_linked_account_users_on_queue():
i = 0
# now = datetime.datetime.utcnow().isoformat()
now = "2013-06-24"
# for user in page_query(User.query.filter(User.next_refresh < now).order_by(User.next_refresh.asc())):
# for user in page_query(User.query.filter(User.next_refresh <= now)):
# for user in page_query(User.query):
# linked_accounts_to_sync = {
# "figshare": user.figshare_id,
# "github": user.github_id,
# "orcid": user.orcid_id,
# "slideshare": user.slideshare_id
# }
# has_linked_account = [account for account in linked_accounts_to_sync if linked_accounts_to_sync[account]]
# if has_linked_account:
# i += 1
# print u"{i} user {url_slug} has linked account: {has_linked_account} {next_refresh} ".format(
# i=i, url_slug=user.url_slug, has_linked_account=has_linked_account, next_refresh=user.next_refresh)
# for account in has_linked_account:
# tiids = update_from_linked_account.delay(user, account)
db.create_all()
add_profile_deets_for_everyone()
| from totalimpactwebapp.user import User
from totalimpactwebapp import db
import datetime
import tasks
"""
requires these env vars be set in this environment:
DATABASE_URL
"""
def page_query(q):
offset = 0
while True:
r = False
for elem in q.limit(100).offset(offset):
r = True
yield elem
offset += 100
if not r:
break
def add_profile_deets_for_everyone():
for user in page_query(User.query.order_by(User.url_slug.asc())):
print user.url_slug
# tasks.add_profile_deets.delay(user)
tasks.add_profile_deets(user)
def deduplicate_everyone():
for user in page_query(User.query.order_by(User.url_slug.asc())):
print user.url_slug
removed_tiids = tasks.deduplicate.delay(user)
def put_linked_account_users_on_queue():
i = 0
# now = datetime.datetime.utcnow().isoformat()
now = "2013-06-24"
# for user in page_query(User.query.filter(User.next_refresh < now).order_by(User.next_refresh.asc())):
# for user in page_query(User.query.filter(User.next_refresh <= now)):
# for user in page_query(User.query):
# linked_accounts_to_sync = {
# "figshare": user.figshare_id,
# "github": user.github_id,
# "orcid": user.orcid_id,
# "slideshare": user.slideshare_id
# }
# has_linked_account = [account for account in linked_accounts_to_sync if linked_accounts_to_sync[account]]
# if has_linked_account:
# i += 1
# print u"{i} user {url_slug} has linked account: {has_linked_account} {next_refresh} ".format(
# i=i, url_slug=user.url_slug, has_linked_account=has_linked_account, next_refresh=user.next_refresh)
# for account in has_linked_account:
# tiids = update_from_linked_account.delay(user, account)
db.create_all()
add_profile_deets_for_everyone()
| mit | Python |
a2cc8a5e6009bda68edf85a432d9a8ec002e99a1 | Fix #80 | vadimcn/vscode-lldb,vadimcn/vscode-lldb,vadimcn/vscode-lldb,vadimcn/vscode-lldb,vadimcn/vscode-lldb,vadimcn/vscode-lldb,vadimcn/vscode-lldb | adapter/__init__.py | adapter/__init__.py | import sys
PY2 = sys.version_info[0] == 2
if PY2:
is_string = lambda v: isinstance(v, basestring)
# python2-based LLDB accepts utf8-encoded ascii strings only.
to_lldb_str = lambda s: s.encode('utf8', 'backslashreplace') if isinstance(s, unicode) else s
from_lldb_str = lambda s: s.decode('utf8', 'replace')
xrange = xrange
else:
is_string = lambda v: isinstance(v, str)
to_lldb_str = str
from_lldb_str = str
xrange = range
import adapter.main
| import sys
PY2 = sys.version_info[0] == 2
if PY2:
is_string = lambda v: isinstance(v, basestring)
to_lldb_str = lambda s: s.encode('utf8', 'backslashreplace')
from_lldb_str = lambda s: s.decode('utf8', 'replace')
xrange = xrange
else:
is_string = lambda v: isinstance(v, str)
to_lldb_str = str
from_lldb_str = str
xrange = range
import adapter.main
| mit | Python |
dc50a4ec058f9893e87a069bc64e4715ecfa0bea | Add initial status code assertion | sjagoe/usagi | haas_rest_test/plugins/assertions.py | haas_rest_test/plugins/assertions.py | # -*- coding: utf-8 -*-
# Copyright (c) 2014 Simon Jagoe
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the 3-clause BSD license. See the LICENSE.txt file for details.
from __future__ import absolute_import, unicode_literals
from jsonschema.exceptions import ValidationError
import jsonschema
from ..exceptions import YamlParseError
class StatusCodeAssertion(object):
_schema = {
'$schema': 'http://json-schema.org/draft-04/schema#',
'title': 'Assertion on status code ',
'description': 'Test case markup for Haas Rest Test',
'type': 'object',
'properties': {
'expected': {
'type': 'integer',
},
},
'required': ['expected']
}
def __init__(self, expected_status):
super(StatusCodeAssertion, self).__init__()
self.expected_status = expected_status
@classmethod
def from_dict(cls, data):
try:
jsonschema.validate(data, cls._schema)
except ValidationError as e:
raise YamlParseError(str(e))
return cls(expected_status=data['expected'])
def run(self, case, response):
case.fail()
| # -*- coding: utf-8 -*-
# Copyright (c) 2014 Simon Jagoe
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the 3-clause BSD license. See the LICENSE.txt file for details.
from __future__ import absolute_import, unicode_literals
class StatusCodeAssertion(object):
_schema = {
}
def __init__(self, valid_codes):
super(StatusCodeAssertion, self).__init__()
self.valid_codes = valid_codes
@classmethod
def from_dict(cls, data):
# FIXME: Validate input with jsonschema
return cls(valid_codes=data['expected'])
| bsd-3-clause | Python |
b9ea36d80ec256988a772e621eb91481cff5e464 | Bump version to 0.3 | dmsimard/python-cicoclient | cicoclient/shell.py | cicoclient/shell.py | # Copyright Red Hat, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
import sys
import os
from cliff.app import App
from cliff.commandmanager import CommandManager
class CicoCli(App):
"""
CLI interface boilerplate with cliff
"""
def __init__(self):
super(CicoCli, self).__init__(
description='CLI interface to admin.ci.centos.org',
version='0.3',
command_manager=CommandManager('cico.cli'),
deferred_help=True,
)
def build_option_parser(self, description, version):
parser = super(CicoCli, self).build_option_parser(description, version)
# Global arguments
parser.add_argument(
'--endpoint',
metavar='<endpoint>',
help='Endpoint to the admin.ci.centos.org service.\n'
' Defaults to: http://admin.ci.centos.org:8080/',
default='http://admin.ci.centos.org:8080/'
)
parser.add_argument(
'--api-key',
metavar='<api-key>',
help='API key to admin.ci.centos.org service. Defaults to'
' environment variable for CICO_API_KEY.',
default=os.getenv('CICO_API_KEY', None)
)
return parser
def initialize_app(self, argv):
self.LOG.debug('initialize_app')
def prepare_to_run_command(self, cmd):
self.LOG.debug('prepare_to_run_command %s', cmd.__class__.__name__)
def clean_up(self, cmd, result, err):
self.LOG.debug('clean_up %s', cmd.__class__.__name__)
if err:
self.LOG.debug('got an error: %s', err)
def main(argv=sys.argv[1:]):
cicocli = CicoCli()
return cicocli.run(argv)
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))
| # Copyright Red Hat, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
import sys
import os
from cliff.app import App
from cliff.commandmanager import CommandManager
class CicoCli(App):
"""
CLI interface boilerplate with cliff
"""
def __init__(self):
super(CicoCli, self).__init__(
description='CLI interface to admin.ci.centos.org',
version='0.2',
command_manager=CommandManager('cico.cli'),
deferred_help=True,
)
def build_option_parser(self, description, version):
parser = super(CicoCli, self).build_option_parser(description, version)
# Global arguments
parser.add_argument(
'--endpoint',
metavar='<endpoint>',
help='Endpoint to the admin.ci.centos.org service.\n'
' Defaults to: http://admin.ci.centos.org:8080/',
default='http://admin.ci.centos.org:8080/'
)
parser.add_argument(
'--api-key',
metavar='<api-key>',
help='API key to admin.ci.centos.org service. Defaults to'
' environment variable for CICO_API_KEY.',
default=os.getenv('CICO_API_KEY', None)
)
return parser
def initialize_app(self, argv):
self.LOG.debug('initialize_app')
def prepare_to_run_command(self, cmd):
self.LOG.debug('prepare_to_run_command %s', cmd.__class__.__name__)
def clean_up(self, cmd, result, err):
self.LOG.debug('clean_up %s', cmd.__class__.__name__)
if err:
self.LOG.debug('got an error: %s', err)
def main(argv=sys.argv[1:]):
cicocli = CicoCli()
return cicocli.run(argv)
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))
| apache-2.0 | Python |
561de1d124289058eafde34547e8fc773c3e9793 | Rename strips to d_strips | cropleyb/pentai,cropleyb/pentai,cropleyb/pentai | board.py | board.py |
import direction_strips as ds_m
from pente_exceptions import *
from defines import *
class Board():
def __init__(self, size, clone_it=False):
self.size = size
if not clone_it:
self.set_to_empty()
def set_to_empty(self):
self.d_strips = []
self.d_strips.append(ds_m.EDirectionStrips(self.size))
self.d_strips.append(ds_m.SEDirectionStrips(self.size))
self.d_strips.append(ds_m.SDirectionStrips(self.size))
self.d_strips.append(ds_m.SWDirectionStrips(self.size))
def key(self):
k = 0
estrips = self.d_strips[0]
for s in estrips.strips:
k += s
k *= 4 ** self.size
return k
def get_direction_strips(self):
return self.d_strips
def clone(self):
new_board = Board(self.size, clone_it=True)
new_board.d_strips = [s.clone() for s in self.d_strips]
return new_board
def __repr__(self):
size = self.size
rep = '\n'
for j in range(size-1,-1,-1):
line = [ ['.','B','W'][self.d_strips[0].get_occ((i,j))] for i in range(size) ]
rep = rep + ' '.join(line) + '\n'
return rep
def get_size(self):
return self.size
def off_board(self, pos):
x,y = pos
size = self.size
return x < 0 or \
x >= size or \
y < 0 or \
y >= size
def get_occ(self, pos):
if self.off_board(pos):
raise OffBoardException
colour = self.d_strips[0].get_occ(pos)
return colour
def set_occ(self, pos, colour):
if self.off_board(pos):
raise OffBoardException
for s in self.d_strips:
# We maintain the board position in four ways, update them all
s.set_occ(pos, colour)
|
import direction_strips as ds_m
from pente_exceptions import *
from defines import *
class Board():
def __init__(self, size, clone_it=False):
self.size = size
if not clone_it:
self.set_to_empty()
def set_to_empty(self):
self.strips = [] # TODO Rename to d_strips
self.strips.append(ds_m.EDirectionStrips(self.size))
self.strips.append(ds_m.SEDirectionStrips(self.size))
self.strips.append(ds_m.SDirectionStrips(self.size))
self.strips.append(ds_m.SWDirectionStrips(self.size))
def key(self):
return tuple(self.strips[0].strips)
def get_direction_strips(self):
return self.strips
def clone(self):
new_board = Board(self.size, clone_it=True)
new_board.strips = [s.clone() for s in self.strips]
return new_board
def __repr__(self):
size = self.size
rep = '\n'
for j in range(size-1,-1,-1):
line = [ ['.','B','W'][self.strips[0].get_occ((i,j))] for i in range(size) ]
rep = rep + ' '.join(line) + '\n'
return rep
def get_size(self):
return self.size
def off_board(self, pos):
x,y = pos
size = self.size
return x < 0 or \
x >= size or \
y < 0 or \
y >= size
def get_occ(self, pos):
if self.off_board(pos):
raise OffBoardException
colour_new = self.strips[0].get_occ(pos)
return colour_new
def set_occ(self, pos, colour):
if self.off_board(pos):
raise OffBoardException
for s in self.strips:
# We maintain the board position in four ways, update them all
s.set_occ(pos, colour)
| mit | Python |
62e9510fe2fbe3186c7c817a5c287322a65b1dc9 | Fix linearPotential import to new package structure | jobovy/galpy,jobovy/galpy,jobovy/galpy,jobovy/galpy | galpy/potential/IsothermalDiskPotential.py | galpy/potential/IsothermalDiskPotential.py | ###############################################################################
# IsothermalDiskPotential.py: class that implements the one-dimensional
# self-gravitating isothermal disk
###############################################################################
import numpy
from .linearPotential import linearPotential, _APY_LOADED
if _APY_LOADED:
from astropy import units
class IsothermalDiskPotential(linearPotential):
"""Class representing the one-dimensional self-gravitating isothermal disk
.. math::
\\rho(x) = \\mathrm{amp}\\,\\mathrm{sech}^2\\left(\\frac{x}{2H}\\right)
where the scale height :math:`H^2 = \\sigma^2/[8\\pi G \\,\\mathrm{amp}]`. The parameter to setup the disk is the velocity dispersion :math:`\\sigma`.
"""
def __init__(self,amp=1.,sigma=0.1,ro=None,vo=None):
"""
NAME:
__init__
PURPOSE:
Initialize an IsothermalDiskPotential
INPUT:
amp - an overall amplitude
sigma - velocity dispersion (can be a Quantity)
OUTPUT:
instance
HISTORY:
2018-04-11 - Written - Bovy (UofT)
"""
linearPotential.__init__(self,amp=amp,ro=ro,vo=vo)
if _APY_LOADED and isinstance(sigma,units.Quantity):
sigma= sigma.to(units.km/units.s).value/self._vo
self._sigma2= sigma**2.
self._H= sigma/numpy.sqrt(8.*numpy.pi*self._amp)
def _evaluate(self,x,t=0.):
return 2.*self._sigma2*numpy.log(numpy.cosh(0.5*x/self._H))
def _force(self,x,t=0.):
return -self._sigma2*numpy.tanh(0.5*x/self._H)/self._H
| ###############################################################################
# IsothermalDiskPotential.py: class that implements the one-dimensional
# self-gravitating isothermal disk
###############################################################################
import numpy
from galpy.util import bovy_conversion
from galpy.potential_src.linearPotential import linearPotential, _APY_LOADED
if _APY_LOADED:
from astropy import units
class IsothermalDiskPotential(linearPotential):
"""Class representing the one-dimensional self-gravitating isothermal disk
.. math::
\\rho(x) = \\mathrm{amp}\\,\\mathrm{sech}^2\\left(\\frac{x}{2H}\\right)
where the scale height :math:`H^2 = \\sigma^2/[8\\pi G \\,\\mathrm{amp}]`. The parameter to setup the disk is the velocity dispersion :math:`\\sigma`.
"""
def __init__(self,amp=1.,sigma=0.1,ro=None,vo=None):
"""
NAME:
__init__
PURPOSE:
Initialize an IsothermalDiskPotential
INPUT:
amp - an overall amplitude
sigma - velocity dispersion (can be a Quantity)
OUTPUT:
instance
HISTORY:
2018-04-11 - Written - Bovy (UofT)
"""
linearPotential.__init__(self,amp=amp,ro=ro,vo=vo)
if _APY_LOADED and isinstance(sigma,units.Quantity):
sigma= sigma.to(units.km/units.s).value/self._vo
self._sigma2= sigma**2.
self._H= sigma/numpy.sqrt(8.*numpy.pi*self._amp)
def _evaluate(self,x,t=0.):
return 2.*self._sigma2*numpy.log(numpy.cosh(0.5*x/self._H))
def _force(self,x,t=0.):
return -self._sigma2*numpy.tanh(0.5*x/self._H)/self._H
| bsd-3-clause | Python |
b927fe276af848b6c9a4653e04421a739e63037c | remove unused import | dmaticzka/EDeN,fabriziocosta/EDeN,smautner/EDeN,dmaticzka/EDeN,smautner/EDeN,fabriziocosta/EDeN | test/test_graphprot.py | test/test_graphprot.py | from scripttest import TestFileEnvironment
import re
# from filecmp import cmp
bindir = "graphprot/"
script = "graphprot_seqmodel"
# test file environment
datadir = "test/"
testdir = "test/testenv_graphprot_seqmodel/"
# directories relative to test file environment
bindir_rel = "../../" + bindir
datadir_rel = "../../" + datadir
env = TestFileEnvironment(testdir)
def test_invocation_no_params():
"Call without parameters should return usage information."
call = bindir_rel + script
run = env.run(
call,
expect_error=True)
assert run.returncode == 2
assert re.match("usage", run.stderr), "stderr should contain usage information: {}".format(run.stderr)
def test_simple_fit():
"Train a model on 10 positive and 10 negative sequences using default paramters."
outfile = "test_simple_fit.model"
call = bindir_rel + script + " -vvv fit -p {} -n {} --output-dir ./ --model-file {} --n-iter 1".format(
datadir_rel + "PARCLIP_MOV10_Sievers_10seqs.train.positives.fa",
datadir_rel + "PARCLIP_MOV10_Sievers_10seqs.train.negatives.fa",
outfile
)
# ../../graphprot/graphprot_seqmodel -vvv fit -p ../../test/PARCLIP_MOV10_Sievers_100seqs.train.positives.fa -n ../../test/PARCLIP_MOV10_Sievers_100seqs.train.negatives.fa --output-dir ./ --model-file test_simple_fit.model --n-iter 1
env.run(call)
call = bindir_rel + script + " -vvv estimate -p {} -n {} --output-dir ./ --model-file {} --cross-validation".format(
datadir_rel + "PARCLIP_MOV10_Sievers_10seqs.train.positives.fa",
datadir_rel + "PARCLIP_MOV10_Sievers_10seqs.train.negatives.fa",
outfile
)
# ../../graphprot/graphprot_seqmodel -vvv estimate -p ../../test/PARCLIP_MOV10_Sievers_1kseqs.train.positives.fa -n ../../test/PARCLIP_MOV10_Sievers_1kseqs.train.negatives.fa --output-dir ./ --model-file test_simple_fit.model --cross-validation
run = env.run(
call,
expect_stderr=True,
)
stdout = open(testdir + "test_simple_fit_estimate.out", "w")
stdout.write(run.stdout)
| from scripttest import TestFileEnvironment
import re
import os
# from filecmp import cmp
bindir = "graphprot/"
script = "graphprot_seqmodel"
# test file environment
datadir = "test/"
testdir = "test/testenv_graphprot_seqmodel/"
# directories relative to test file environment
bindir_rel = "../../" + bindir
datadir_rel = "../../" + datadir
env = TestFileEnvironment(testdir)
def test_invocation_no_params():
"Call without parameters should return usage information."
call = bindir_rel + script
run = env.run(
call,
expect_error=True)
assert run.returncode == 2
assert re.match("usage", run.stderr), "stderr should contain usage information: {}".format(run.stderr)
def test_simple_fit():
"Train a model on 10 positive and 10 negative sequences using default paramters."
outfile = "test_simple_fit.model"
call = bindir_rel + script + " -vvv fit -p {} -n {} --output-dir ./ --model-file {} --n-iter 1".format(
datadir_rel + "PARCLIP_MOV10_Sievers_10seqs.train.positives.fa",
datadir_rel + "PARCLIP_MOV10_Sievers_10seqs.train.negatives.fa",
outfile
)
# ../../graphprot/graphprot_seqmodel -vvv fit -p ../../test/PARCLIP_MOV10_Sievers_100seqs.train.positives.fa -n ../../test/PARCLIP_MOV10_Sievers_100seqs.train.negatives.fa --output-dir ./ --model-file test_simple_fit.model --n-iter 1
env.run(call)
call = bindir_rel + script + " -vvv estimate -p {} -n {} --output-dir ./ --model-file {} --cross-validation".format(
datadir_rel + "PARCLIP_MOV10_Sievers_10seqs.train.positives.fa",
datadir_rel + "PARCLIP_MOV10_Sievers_10seqs.train.negatives.fa",
outfile
)
# ../../graphprot/graphprot_seqmodel -vvv estimate -p ../../test/PARCLIP_MOV10_Sievers_1kseqs.train.positives.fa -n ../../test/PARCLIP_MOV10_Sievers_1kseqs.train.negatives.fa --output-dir ./ --model-file test_simple_fit.model --cross-validation
run = env.run(
call,
expect_stderr=True,
)
stdout = open(testdir + "test_simple_fit_estimate.out", "w")
stdout.write(run.stdout)
| mit | Python |
56f24e52f961da414f0610e6bd815812b4a14ef6 | Update utils.py | googleinterns/smart-content-summary,googleinterns/smart-content-summary,googleinterns/smart-content-summary | classifier/utils.py | classifier/utils.py | # coding=utf-8
# Copyright 2019 The Google Research Authors.
#
# 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.
# Lint as: python3
"""Utility functions for LaserTagger."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import json
from typing import Iterator, Mapping, Sequence, Text, Tuple
import tensorflow as tf
def get_token_list(text):
"""Returns a list of tokens.
This function expects that the tokens in the text are separated by space
character(s). Example: "ca n't , touch". This is the case at least for the
public DiscoFuse and WikiSplit datasets.
Args:
text: String to be split into tokens.
"""
return text.split()
def yield_sources_and_targets_meaning(input_file):
"""Reads and yields source lists and targets from the input file.
Args:
input_file: Path to the input file.
Yields:
Tuple with (list of source texts, target text).
"""
with tf.io.gfile.GFile(input_file) as f:
for line in f:
if len(line.rstrip('\n').split('\t')) == 3:
source, summary, score = line.rstrip('\n').split('\t')
yield [source], summary, score
def yield_sources_and_targets_grammar(input_file):
"""Reads and yields source lists and targets from the input file.
Args:
input_file: Path to the input file.
Yields:
Tuple with (list of source texts, target text).
"""
with tf.io.gfile.GFile(input_file) as f:
for line in f:
source, score = line.rstrip('\n').split('\t')
yield [source], None, score
| # coding=utf-8
# Copyright 2019 The Google Research Authors.
#
# 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.
# Lint as: python3
"""Utility functions for LaserTagger."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import json
from typing import Iterator, Mapping, Sequence, Text, Tuple
import tensorflow as tf
def get_token_list(text):
"""Returns a list of tokens.
This function expects that the tokens in the text are separated by space
character(s). Example: "ca n't , touch". This is the case at least for the
public DiscoFuse and WikiSplit datasets.
Args:
text: String to be split into tokens.
"""
return text.split()
def yield_sources_and_targets_meaning(input_file):
"""Reads and yields source lists and targets from the input file.
Args:
input_file: Path to the input file.
Yields:
Tuple with (list of source texts, target text).
"""
with tf.io.gfile.GFile(input_file) as f:
for line in f:
source, summary, score = line.rstrip('\n').split('\t')
yield [source], summary, score
def yield_sources_and_targets_grammar(input_file):
"""Reads and yields source lists and targets from the input file.
Args:
input_file: Path to the input file.
Yields:
Tuple with (list of source texts, target text).
"""
with tf.io.gfile.GFile(input_file) as f:
for line in f:
source, score = line.rstrip('\n').split('\t')
yield [source], None, score
| apache-2.0 | Python |
c28112624b3c735c610f756a6bff1497e9516c64 | Revise naive alg to more intuitive one: separate checking index and value | bowen0701/algorithms_data_structures | alg_find_peak_1D.py | alg_find_peak_1D.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
def find_peak_naive(arr):
"""Find peak by naive iteration.
Time complexity: O(n).
"""
for i in range(len(arr)):
if i == 0:
if arr[i] > arr[i + 1]:
return arr[i]
elif i == (len(arr) - 1):
if arr[i] > arr[i - 1]:
return arr[i]
else:
if arr[i] > arr[i - 1] and arr[i] > arr[i + 1]:
return arr[i]
def find_peak(arr):
"""Find peak by divide-end-conquer algorithm.
Time complexity: O(logn).
"""
if len(arr) == 1:
return arr[0]
else:
mid = len(arr) // 2
if arr[mid] < arr[mid - 1]:
return find_peak(arr[:mid-1])
elif arr[mid] < arr[mid + 1]:
return find_peak(arr[mid+1:])
else:
return arr[mid]
def main():
import time
# Array with peak 4.
arr = [0, 1, 4, 3, 2]
# Find peak by naive version.
time_start = time.time()
peak = find_peak_naive(arr)
time_run = time.time() - time_start
print('Peak: {}'.format(peak))
print('Time for find_peak_naive(): {}'.format(time_run))
# Find peak by divide-end-conquer algorithm.
time_start = time.time()
peak = find_peak(arr)
time_run = time.time() - time_start
print('Peak: {}'.format(peak))
print('Time for find_peak_naive(): {}'.format(time_run))
if __name__ == '__main__':
main()
| from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
def find_peak_naive(arr):
"""Find peak by naive iteration.
Time complexity: O(n).
"""
for i in range(len(arr)):
if i == 0 and arr[i] > arr[i + 1]:
return arr[i]
elif i == (len(arr) - 1) and arr[i] > arr[i - 1]:
return arr[i]
elif (0 < i < (len(arr) - 1) and
arr[i] > arr[i - 1] and arr[i] > arr[i + 1]):
return arr[i]
else:
pass
def find_peak(arr):
"""Find peak by divide-end-conquer algorithm.
Time complexity: O(logn).
"""
if len(arr) == 1:
return arr[0]
else:
mid = len(arr) // 2
if arr[mid] < arr[mid - 1]:
return find_peak(arr[:mid-1])
elif arr[mid] < arr[mid + 1]:
return find_peak(arr[mid+1:])
else:
return arr[mid]
def main():
import time
# Array with peak 4.
arr = [0, 1, 4, 3, 2]
# Find peak by naive version.
time_start = time.time()
peak = find_peak_naive(arr)
time_run = time.time() - time_start
print('Peak: {}'.format(peak))
print('Time for find_peak_naive(): {}'.format(time_run))
# Find peak by divide-end-conquer algorithm.
time_start = time.time()
peak = find_peak(arr)
time_run = time.time() - time_start
print('Peak: {}'.format(peak))
print('Time for find_peak_naive(): {}'.format(time_run))
if __name__ == '__main__':
main()
| bsd-2-clause | Python |
dbec204b242ab643de162046ba73dca32043c6c2 | Implement __getattr__ to reduce code | CubicComet/exercism-python-solutions | space-age/space_age.py | space-age/space_age.py | class SpaceAge(object):
YEARS = {"on_earth": 1,
"on_mercury": 0.2408467,
"on_venus": 0.61519726,
"on_mars": 1.8808158,
"on_jupiter": 11.862615,
"on_saturn": 29.447498,
"on_uranus": 84.016846,
"on_neptune": 164.79132}
def __init__(self, seconds):
self.seconds = seconds
@property
def years(self):
return self.seconds/31557600
def __getattr__(self, on_planet):
if on_planet in SpaceAge.YEARS:
return lambda: round(self.years/SpaceAge.YEARS[on_planet], 2)
else:
raise AttributeError
| class SpaceAge(object):
def __init__(self, seconds):
self.seconds = seconds
@property
def years(self):
return self.seconds/31557600
def on_earth(self):
return round(self.years, 2)
def on_mercury(self):
return round(self.years/0.2408467, 2)
def on_venus(self):
return round(self.years/0.6151976, 2)
def on_mars(self):
return round(self.years/1.8808158, 2)
def on_jupiter(self):
return round(self.years/11.862615, 2)
def on_saturn(self):
return round(self.years/29.447498, 2)
def on_uranus(self):
return round(self.years/84.016846, 2)
def on_neptune(self):
return round(self.years/164.79132, 2)
| agpl-3.0 | Python |
8b275ccb96b8fe3c2c3919e11f08e988219a1e14 | Add the process PID in the logs | joel-airspring/Diamond,eMerzh/Diamond-1,signalfx/Diamond,rtoma/Diamond,Ensighten/Diamond,mfriedenhagen/Diamond,rtoma/Diamond,tusharmakkar08/Diamond,signalfx/Diamond,jriguera/Diamond,joel-airspring/Diamond,codepython/Diamond,gg7/diamond,ramjothikumar/Diamond,signalfx/Diamond,skbkontur/Diamond,stuartbfox/Diamond,works-mobile/Diamond,codepython/Diamond,h00dy/Diamond,timchenxiaoyu/Diamond,Nihn/Diamond-1,timchenxiaoyu/Diamond,jaingaurav/Diamond,rtoma/Diamond,jaingaurav/Diamond,socialwareinc/Diamond,russss/Diamond,jaingaurav/Diamond,timchenxiaoyu/Diamond,hamelg/Diamond,works-mobile/Diamond,szibis/Diamond,EzyInsights/Diamond,Ormod/Diamond,Ormod/Diamond,actmd/Diamond,anandbhoraskar/Diamond,tusharmakkar08/Diamond,jriguera/Diamond,hamelg/Diamond,cannium/Diamond,joel-airspring/Diamond,skbkontur/Diamond,stuartbfox/Diamond,Netuitive/netuitive-diamond,TAKEALOT/Diamond,jumping/Diamond,jumping/Diamond,Nihn/Diamond-1,hamelg/Diamond,hvnsweeting/Diamond,anandbhoraskar/Diamond,Clever/Diamond,TAKEALOT/Diamond,rtoma/Diamond,zoidbergwill/Diamond,zoidbergwill/Diamond,tusharmakkar08/Diamond,anandbhoraskar/Diamond,works-mobile/Diamond,skbkontur/Diamond,gg7/diamond,dcsquared13/Diamond,tusharmakkar08/Diamond,zoidbergwill/Diamond,mfriedenhagen/Diamond,Precis/Diamond,MichaelDoyle/Diamond,eMerzh/Diamond-1,Ensighten/Diamond,mzupan/Diamond,dcsquared13/Diamond,codepython/Diamond,actmd/Diamond,ramjothikumar/Diamond,russss/Diamond,bmhatfield/Diamond,EzyInsights/Diamond,socialwareinc/Diamond,actmd/Diamond,anandbhoraskar/Diamond,TAKEALOT/Diamond,MichaelDoyle/Diamond,Clever/Diamond,ramjothikumar/Diamond,cannium/Diamond,dcsquared13/Diamond,hamelg/Diamond,tuenti/Diamond,socialwareinc/Diamond,h00dy/Diamond,stuartbfox/Diamond,mzupan/Diamond,cannium/Diamond,TAKEALOT/Diamond,Basis/Diamond,timchenxiaoyu/Diamond,jumping/Diamond,stuartbfox/Diamond,Clever/Diamond,Precis/Diamond,jumping/Diamond,EzyInsights/Diamond,EzyInsights/Diamond,bmhatfield/Diamond,jaingaurav/Diamond,Ensighten/Diamond,works-mobile/Diamond,tuenti/Diamond,szibis/Diamond,szibis/Diamond,bmhatfield/Diamond,Ssawa/Diamond,russss/Diamond,Netuitive/Diamond,hvnsweeting/Diamond,Ssawa/Diamond,Slach/Diamond,Clever/Diamond,acquia/Diamond,socialwareinc/Diamond,Netuitive/Diamond,mzupan/Diamond,bmhatfield/Diamond,acquia/Diamond,codepython/Diamond,dcsquared13/Diamond,hvnsweeting/Diamond,jriguera/Diamond,Ormod/Diamond,hvnsweeting/Diamond,h00dy/Diamond,szibis/Diamond,Netuitive/netuitive-diamond,Netuitive/Diamond,Ormod/Diamond,Netuitive/netuitive-diamond,eMerzh/Diamond-1,zoidbergwill/Diamond,Basis/Diamond,Slach/Diamond,mfriedenhagen/Diamond,h00dy/Diamond,Netuitive/Diamond,python-diamond/Diamond,Precis/Diamond,python-diamond/Diamond,acquia/Diamond,joel-airspring/Diamond,Ssawa/Diamond,Ensighten/Diamond,gg7/diamond,actmd/Diamond,tuenti/Diamond,acquia/Diamond,russss/Diamond,Nihn/Diamond-1,gg7/diamond,MichaelDoyle/Diamond,Ssawa/Diamond,jriguera/Diamond,Slach/Diamond,skbkontur/Diamond,Basis/Diamond,Netuitive/netuitive-diamond,signalfx/Diamond,cannium/Diamond,mzupan/Diamond,Nihn/Diamond-1,Basis/Diamond,mfriedenhagen/Diamond,tuenti/Diamond,MichaelDoyle/Diamond,python-diamond/Diamond,Precis/Diamond,Slach/Diamond,ramjothikumar/Diamond,eMerzh/Diamond-1 | src/diamond/utils/log.py | src/diamond/utils/log.py | # coding=utf-8
import logging
import logging.config
import sys
import os
class DebugFormatter(logging.Formatter):
def __init__(self, fmt=None):
if fmt is None:
fmt = ('%(created)s\t' +
'[%(processName)s:%(process)d:%(levelname)s]\t' +
'%(message)s')
self.fmt_default = fmt
self.fmt_prefix = fmt.replace('%(message)s', '')
logging.Formatter.__init__(self, fmt)
def format(self, record):
self._fmt = self.fmt_default
if record.levelno in [logging.ERROR, logging.CRITICAL]:
self._fmt = ''
self._fmt += self.fmt_prefix
self._fmt += '%(message)s'
self._fmt += '\n'
self._fmt += self.fmt_prefix
self._fmt += '%(pathname)s:%(lineno)d'
return logging.Formatter.format(self, record)
def setup_logging(configfile, stdout=False):
log = logging.getLogger('diamond')
if stdout:
log.setLevel(logging.DEBUG)
streamHandler = logging.StreamHandler(sys.stdout)
streamHandler.setFormatter(DebugFormatter())
streamHandler.setLevel(logging.DEBUG)
log.addHandler(streamHandler)
else:
try:
if sys.version_info >= (2, 6):
logging.config.fileConfig(configfile,
disable_existing_loggers=False)
else:
# python <= 2.5 does not have disable_existing_loggers
# default was to always disable them, in our case we want to
# keep any logger created by handlers
logging.config.fileConfig(configfile)
for logger in logging.root.manager.loggerDict.values():
logger.disabled = 0
except Exception, e:
sys.stderr.write("Error occurs when initialize logging: ")
sys.stderr.write(str(e))
sys.stderr.write(os.linesep)
return log
| # coding=utf-8
import logging
import logging.config
import sys
import os
class DebugFormatter(logging.Formatter):
def __init__(self, fmt=None):
if fmt is None:
fmt = '%(created)s\t[%(processName)s:%(levelname)s]\t%(message)s'
self.fmt_default = fmt
self.fmt_prefix = fmt.replace('%(message)s', '')
logging.Formatter.__init__(self, fmt)
def format(self, record):
self._fmt = self.fmt_default
if record.levelno in [logging.ERROR, logging.CRITICAL]:
self._fmt = ''
self._fmt += self.fmt_prefix
self._fmt += '%(message)s'
self._fmt += '\n'
self._fmt += self.fmt_prefix
self._fmt += '%(pathname)s:%(lineno)d'
return logging.Formatter.format(self, record)
def setup_logging(configfile, stdout=False):
log = logging.getLogger('diamond')
if stdout:
log.setLevel(logging.DEBUG)
streamHandler = logging.StreamHandler(sys.stdout)
streamHandler.setFormatter(DebugFormatter())
streamHandler.setLevel(logging.DEBUG)
log.addHandler(streamHandler)
else:
try:
if sys.version_info >= (2, 6):
logging.config.fileConfig(configfile,
disable_existing_loggers=False)
else:
# python <= 2.5 does not have disable_existing_loggers
# default was to always disable them, in our case we want to
# keep any logger created by handlers
logging.config.fileConfig(configfile)
for logger in logging.root.manager.loggerDict.values():
logger.disabled = 0
except Exception, e:
sys.stderr.write("Error occurs when initialize logging: ")
sys.stderr.write(str(e))
sys.stderr.write(os.linesep)
return log
| mit | Python |
419db3c559d836d6ba77c758212a55051e6c8fab | Add FIXME for module as function arg | jbcoe/PyObjDictTools | test_obj_dict_tools.py | test_obj_dict_tools.py | from obj_dict_tools import *
from nose.tools import raises
@dict_fields(['name', 'size'])
class Simple:
def __init__(self, name=None, size=None):
self.name = name
self.size = size
@dict_fields(['first', 'second'])
class Pair:
def __init__(self, first=None, second=None):
self.first = first
self.second = second
def test_simple_class_to_dict():
s = Simple('foo', 100)
d = to_dict(s)
assert d['__class__'] == 'Simple'
assert d['name'] == 'foo'
assert d['size'] == 100
def test_simple_class_from_dict():
d = {'__class__': 'Simple', 'name': 'foo', 'size': 100}
# FIXME: Explicitly passing in a module is undesirable.
s = from_dict(d, globals())
assert isinstance(s, Simple)
assert s.name == 'foo'
assert s.size == 100
def test_null_fields_to_dict():
p = Pair()
d = to_dict(p)
assert d['__class__'] == 'Pair'
assert not 'first' in d
assert not 'second' in d
def test_list_to_dict():
ss = [Simple('foo', 100), Simple('bar', 200)]
d = to_dict(ss)
assert len(d) == 2
assert d[0]['__class__'] == 'Simple'
assert d[0]['name'] == 'foo'
assert d[0]['size'] == 100
assert d[1]['__class__'] == 'Simple'
assert d[1]['name'] == 'bar'
assert d[1]['size'] == 200
def test_list_field_to_dict():
p = Pair([1, 2, 3, 4, 5], Simple('b', 200))
d = to_dict(p)
assert d['__class__'] == 'Pair'
assert len(d['first']) == 5
assert d['second']['__class__'] == 'Simple'
assert d['second']['name'] == 'b'
assert d['second']['size'] == 200
@raises(Exception)
def test_decorator_rejects_underscore_prefixes():
@dict_fields(['_p'])
class bad_attribute_defined:
pass
| from obj_dict_tools import *
from nose.tools import raises
@dict_fields(['name', 'size'])
class Simple:
def __init__(self, name=None, size=None):
self.name = name
self.size = size
@dict_fields(['first', 'second'])
class Pair:
def __init__(self, first=None, second=None):
self.first = first
self.second = second
def test_simple_class_to_dict():
s = Simple('foo', 100)
d = to_dict(s)
assert d['__class__'] == 'Simple'
assert d['name'] == 'foo'
assert d['size'] == 100
def test_simple_class_from_dict():
d = {'__class__': 'Simple', 'name': 'foo', 'size': 100}
s = from_dict(d, globals())
assert isinstance(s, Simple)
assert s.name == 'foo'
assert s.size == 100
def test_null_fields_to_dict():
p = Pair()
d = to_dict(p)
assert d['__class__'] == 'Pair'
assert not 'first' in d
assert not 'second' in d
def test_list_to_dict():
ss = [Simple('foo', 100), Simple('bar', 200)]
d = to_dict(ss)
assert len(d) == 2
assert d[0]['__class__'] == 'Simple'
assert d[0]['name'] == 'foo'
assert d[0]['size'] == 100
assert d[1]['__class__'] == 'Simple'
assert d[1]['name'] == 'bar'
assert d[1]['size'] == 200
def test_list_field_to_dict():
p = Pair([1, 2, 3, 4, 5], Simple('b', 200))
d = to_dict(p)
assert d['__class__'] == 'Pair'
assert len(d['first']) == 5
assert d['second']['__class__'] == 'Simple'
assert d['second']['name'] == 'b'
assert d['second']['size'] == 200
@raises(Exception)
def test_decorator_rejects_underscore_prefixes():
@dict_fields(['_p'])
class bad_attribute_defined:
pass
| mit | Python |
b6f57d8aaeff8f85c89c381b972113810a468412 | use lat, lon | LogLock/LogLock.backend | models.py | models.py | from random import choice, randint
import urllib2, json
from pushbullet import PushBullet
from os import environ
'''
Checks if the current login attempt is a security threat or not.
Performs the required action in each case
'''
def is_safe(form, ip, geocoded_ip, mandrill):
ip = ip
latitude = form.get('latitude', None)
longitude = form.get('longitude', None)
os = form.get('os', None)
mobile = form.get('isMobile', None)
browser = form.get('browser', None)
if latitude == None and longitude == None:
latitude = geocoded_ip['lat']
longitude = geocoded_ip['lon']
safety_status = choice(range(-1, 2))
auth_code = '%06d' % randint(0,999999)
if safety_status < 1:
send_push("Confirm your access", "Suspicious access detected from IP %s, confirm with code %s" % (ip, auth_code))
send_mail(mandrill, '[email protected]', latitude, longitude, ip, auth_code)
return {
'safety_code': safety_status,
'token': auth_code,
'debug': [ip, latitude, longitude, os, mobile, browser]
}# send SMS, mail...
def send_push(message, body, lat=40.4086, lon=-3.6922, pushbullet_token=environ.get('PUSHBULLET_TOKEN')):
""" Sends a foo location to Pushbullet """
pb = PushBullet(pushbullet_token)
success, push = pb.push_link("Login from suspicious location detected now!", "http://maps.google.com/maps?&z=10&q=%f,+%f&ll=%f+%f" % (lat, lon, lat, lon), "A suspicious login has appeared, try to guess who is it")
return success
def send_mail(mandrill, to, latitude, longitude, ip, safety_code):
gmaps_uri = "http://maps.googleapis.com/maps/api/staticmap?center=%s,%s&zoom=15&size=400x400&markers=color:red%%7Clabel:S%%7C%s,%s&sensor=true" % (latitude, longitude, latitude, longitude)
mandrill.send_email(
from_email='[email protected]',
subject='[LogLock] Suspicious login attempt detected',
to=[{'email': to}],
html='''
An access attempt has been logged from a suspicious location:
<p><img src="%s" /></p>
<p>IP address: %s</p>
Please confirm it is you with the following code: <b>%s</b>
''' %(gmaps_uri, ip, safety_code)
)
def geocode_ip(ip_addr):
""" Geocodes a given IP Address """
data = json.load(urllib2.urlopen("http://ip-api.com/json/%s" % ip_addr))
print "Geocoded data: %s" % data
return data
| from random import choice, randint
import urllib2, json
from pushbullet import PushBullet
from os import environ
'''
Checks if the current login attempt is a security threat or not.
Performs the required action in each case
'''
def is_safe(form, ip, geocoded_ip, mandrill):
ip = ip
latitude = form.get('latitude', None)
longitude = form.get('longitude', None)
os = form.get('os', None)
mobile = form.get('isMobile', None)
browser = form.get('browser', None)
if latitude == None and longitude == None:
latitude = geocoded_ip['latitude']
longitude = geocoded_ip['longitude']
safety_status = choice(range(-1, 2))
auth_code = '%06d' % randint(0,999999)
if safety_status < 1:
send_push("Confirm your access", "Suspicious access detected from IP %s, confirm with code %s" % (ip, auth_code))
send_mail(mandrill, '[email protected]', latitude, longitude, ip, auth_code)
return {
'safety_code': safety_status,
'token': auth_code,
'debug': [ip, latitude, longitude, os, mobile, browser]
}# send SMS, mail...
def send_push(message, body, lat=40.4086, lon=-3.6922, pushbullet_token=environ.get('PUSHBULLET_TOKEN')):
""" Sends a foo location to Pushbullet """
pb = PushBullet(pushbullet_token)
success, push = pb.push_link("Login from suspicious location detected now!", "http://maps.google.com/maps?&z=10&q=%f,+%f&ll=%f+%f" % (lat, lon, lat, lon), "A suspicious login has appeared, try to guess who is it")
return success
def send_mail(mandrill, to, latitude, longitude, ip, safety_code):
gmaps_uri = "http://maps.googleapis.com/maps/api/staticmap?center=%s,%s&zoom=15&size=400x400&markers=color:red%%7Clabel:S%%7C%s,%s&sensor=true" % (latitude, longitude, latitude, longitude)
mandrill.send_email(
from_email='[email protected]',
subject='[LogLock] Suspicious login attempt detected',
to=[{'email': to}],
html='''
An access attempt has been logged from a suspicious location:
<p><img src="%s" /></p>
<p>IP address: %s</p>
Please confirm it is you with the following code: <b>%s</b>
''' %(gmaps_uri, ip, safety_code)
)
def geocode_ip(ip_addr):
""" Geocodes a given IP Address """
data = json.load(urllib2.urlopen("http://ip-api.com/json/%s" % ip_addr))
print "Geocoded data: %s" % data
return data
| agpl-3.0 | Python |
a0f96b2b25d309c8934ffe9a197f3d66c9097b52 | replace phone to email for privacy | dev-seahouse/cs2108MiniProject,dev-seahouse/cs2108MiniProject | models.py | models.py | from app import db
from datetime import datetime
class Profile(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), unique=True)
gender = db.Column(db.String(1))
age = db.Column(db.Integer())
email = db.Column(db.String(50), unique=True)
description = db.Column(db.String(300))
date = db.Column(db.DateTime, default = datetime.utcnow)
# get profile by id : Profile.query.get(id)
# get profile by param : Profile.query.filter_by(name = "").all()
| from app import db
from datetime import datetime
class Profile(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), unique=True)
gender = db.Column(db.String(1))
age = db.Column(db.Integer())
description = db.Column(db.String(300))
date = db.Column(db.DateTime, default = datetime.utcnow)
# get profile by id : Profile.query.get(id)
# get profile by param : Profile.query.filter_by(name = "").all()
| mit | Python |
9c8bde1e57ad2e70c7b3b9188bff9b90e85434e6 | Send email and push | LogLock/LogLock.backend | models.py | models.py | from random import choice, randint
import urllib2, json
from pushbullet import PushBullet
from os import environ
'''
Checks if the current login attempt is a security threat or not.
Performs the required action in each case
'''
def is_safe(form, ip, mandrill):
ip = ip
latitude = form.get('latitude', None)
longitude = form.get('longitude', None)
os = form.get('os', None)
mobile = form.get('isMobile', None)
browser = form.get('browser', None)
# check against our database
safety_status = choice(range(-1, 2))
if safety_status < 1:
auth_code = '%06d' % randint(0,999999)
send_push("Confirm your access", "Suspicious access detected from IP %s, confirm with code %s" % (ip, auth_code))
send_mail(mandrill, '[email protected]', latitude, longitude, ip, auth_code)
return {
'safety_code': safety_status,
'token': auth_code,
'debug': [ip, latitude, longitude, os, mobile, browser]
}# send SMS, mail...
def send_push(message, body, lat=40.4086, lon=-3.6922, pushbullet_token=environ.get('PUSHBULLET_TOKEN')):
""" Sends a foo location to Pushbullet """
pb = PushBullet(pushbullet_token)
success, push = pb.push_link("Login from suspicious location detected now!", "http://maps.google.com/maps?&z=10&q=%f,+%f&ll=%f+%f" % (lat, lon, lat, lon), "A suspicious login has appeared, try to guess who is it")
return success
def send_mail(mandrill, to, latitude, longitude, ip, safety_code):
gmaps_uri = "http://maps.googleapis.com/maps/api/staticmap?center=%s,%s&zoom=15&size=400x400&markers=color:red%%7Clabel:S%%7C%s,%s&sensor=true" % (latitude, longitude, latitude, longitude)
mandrill.send_email(
from_email='[email protected]',
subject='[LogLock] Suspicious login attempt detected',
to=[{'email': to}],
html='''
An access attempt has been logged from a suspicious location:
<p><img src="%s" /></p>
<p>IP address: %s</p>
Please confirm it is you with the following code: <b>%s</b>
''' %(gmaps_uri, ip, safety_code)
)
def geocode_ip(ip_addr):
""" Geocodes a given IP Address """
data = json.load(urllib2.urlopen("http://ip-api.com/json/%s" % ip_addr))
print "Geocoded data: %s" % data
return data
| from random import choice
import urllib2, json
from pushbullet import PushBullet
'''
Checks if the current login attempt is a security threat or not.
Performs the required action in each case
'''
def is_safe(form, ip, mandrill):
ip = ip
geo = form.get('geo', None)
os = form.get('os', None)
browser = form.get('browser', None)
# check against our database
safety_status = choice(range(-1, 2))
return {
'safety_code': safety_status,
'token': 'fake_token',
'debug': [ip, geo, os, browser]} # send SMS, mail...
def send_push(pushbullet_token, message, lat=40.4086, lon=-3.6922):
""" Sends a foo location to Pushbullet """
pb = PushBullet(pushbullet_token)
success, push = pb.push_link("Login from suspicious location detected now!", "http://maps.google.com/maps?&z=10&q=%f,+%f&ll=%f+%f" % (lat, lon, lat, lon), "A suspicious login has appeared, try to guess who is it")
return success
def send_mail(mandrill, to):
mandrill.send_email(
from_email='[email protected]',
subject='Blocked suspicious login attempt @twitter',
to=[{'email': to}],
text='''An attack has been detected and blocked (LND=>NY login with 5h difference).
Authorize this access by [...]'''
)
def geocode_ip(ip_addr):
""" Geocodes a given IP Address """
data = json.load(urllib2.urlopen("http://ip-api.com/json/%s" % ip_addr))
print "Geocoded data: %s" % data
return data
| agpl-3.0 | Python |
ea8cbcaf41f01a46390882fbc99e6e14d70a49d1 | Create an API auth token for every newly created user | WikiWatershed/model-my-watershed,WikiWatershed/model-my-watershed,WikiWatershed/model-my-watershed,WikiWatershed/model-my-watershed,WikiWatershed/model-my-watershed | src/mmw/apps/user/models.py | src/mmw/apps/user/models.py | # -*- coding: utf-8 -*-
from django.conf import settings
from django.contrib.auth.models import User
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from rest_framework.authtoken.models import Token
@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
"""
Create an auth token for every newly created user.
"""
if created:
Token.objects.create(user=instance)
class ItsiUserManager(models.Manager):
def create_itsi_user(self, user, itsi_id):
itsi_user = self.create(user=user, itsi_id=itsi_id)
return itsi_user
class ItsiUser(models.Model):
user = models.OneToOneField(User, primary_key=True)
itsi_id = models.IntegerField()
objects = ItsiUserManager()
def __unicode__(self):
return unicode(self.user.username)
| # -*- coding: utf-8 -*-
from django.contrib.auth.models import User
from django.db import models
class ItsiUserManager(models.Manager):
def create_itsi_user(self, user, itsi_id):
itsi_user = self.create(user=user, itsi_id=itsi_id)
return itsi_user
class ItsiUser(models.Model):
user = models.OneToOneField(User, primary_key=True)
itsi_id = models.IntegerField()
objects = ItsiUserManager()
def __unicode__(self):
return unicode(self.user.username)
| apache-2.0 | Python |
4f27b87b9ee600c7c1c05ae9fece549b9c18e2a4 | Create default instance in middleware if not found. | opencorato/sayit,opencorato/sayit,opencorato/sayit,opencorato/sayit | speeches/middleware.py | speeches/middleware.py | from instances.models import Instance
class InstanceMiddleware:
"""This middleware sets request.instance to the default Instance for all
requests. This can be changed/overridden if you use SayIt in a way that
uses multiple instances."""
def process_request(self, request):
request.instance, _ = Instance.objects.get_or_create(label='default')
request.is_user_instance = (
request.user.is_authenticated() and
( request.instance in request.user.instances.all() or request.user.is_superuser )
)
| from instances.models import Instance
class InstanceMiddleware:
"""This middleware sets request.instance to the default Instance for all
requests. This can be changed/overridden if you use SayIt in a way that
uses multiple instances."""
def process_request(self, request):
request.instance = Instance.objects.get(label='default')
request.is_user_instance = (
request.user.is_authenticated() and
( request.instance in request.user.instances.all() or request.user.is_superuser )
)
| agpl-3.0 | Python |
2980c30a8de6cbdf5d22bb269c16f8c5ad499ba8 | Fix build output (dots on one line) | dincamihai/salt-toaster,dincamihai/salt-toaster | build.py | build.py | import re
import argparse
from utils import build_docker_image
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--nocache', action='store_true', default=False)
args = parser.parse_args()
content = ''
stream = build_docker_image(nocache=args.nocache)
for item in stream:
buff = item.get('stream', item.get('status'))
if not content or re.search('.+\[[. ]*$', content):
content += buff
if not re.search('.+\[[. ]*$', content):
print(content)
content = ''
if __name__ == '__main__':
main()
| import argparse
from utils import build_docker_image
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--nocache', action='store_true', default=False)
args = parser.parse_args()
for item in build_docker_image(nocache=args.nocache):
print item.values()[0]
if __name__ == '__main__':
main()
| mit | Python |
c16fb96de6154dec7bf0fc934dd9f7e1ac4b69f4 | bump version | spthaolt/curtsies,sebastinas/curtsies,thomasballinger/curtsies | curtsies/__init__.py | curtsies/__init__.py | """Terminal-formatted strings"""
__version__='0.1.15'
from .window import FullscreenWindow, CursorAwareWindow
from .input import Input
from .termhelpers import Nonblocking, Cbreak, Termmode
from .formatstring import FmtStr, fmtstr
from .formatstringarray import FSArray, fsarray
| """Terminal-formatted strings"""
__version__='0.1.14'
from .window import FullscreenWindow, CursorAwareWindow
from .input import Input
from .termhelpers import Nonblocking, Cbreak, Termmode
from .formatstring import FmtStr, fmtstr
from .formatstringarray import FSArray, fsarray
| mit | Python |
e468abbc033a48d0222f50cf85319802f05fc57a | Check doctest | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | custom/onse/tests.py | custom/onse/tests.py | import doctest
from datetime import date
from nose.tools import assert_equal
from custom.onse import tasks
def test_get_last_quarter():
test_dates = [
(date(2020, 1, 1), '2019Q4'),
(date(2020, 3, 31), '2019Q4'),
(date(2020, 4, 1), '2020Q1'),
(date(2020, 6, 30), '2020Q1'),
(date(2020, 7, 1), '2020Q2'),
(date(2020, 9, 30), '2020Q2'),
(date(2020, 10, 1), '2020Q3'),
(date(2020, 12, 31), '2020Q3'),
]
for test_date, expected_value in test_dates:
last_quarter = tasks.get_last_quarter(test_date)
assert_equal(last_quarter, expected_value)
def test_doctests():
results = doctest.testmod(tasks)
assert results.failed == 0
| from datetime import date
from nose.tools import assert_equal
from custom.onse.tasks import get_last_quarter
def test_get_last_quarter():
test_dates = [
(date(2020, 1, 1), '2019Q4'),
(date(2020, 3, 31), '2019Q4'),
(date(2020, 4, 1), '2020Q1'),
(date(2020, 6, 30), '2020Q1'),
(date(2020, 7, 1), '2020Q2'),
(date(2020, 9, 30), '2020Q2'),
(date(2020, 10, 1), '2020Q3'),
(date(2020, 12, 31), '2020Q3'),
]
for test_date, expected_value in test_dates:
last_quarter = get_last_quarter(test_date)
assert_equal(last_quarter, expected_value)
| bsd-3-clause | Python |
e6357827a670c71e2489b5468b89a65153719ba4 | Fix syntax (backward compatible) | python-social-auth/social-storage-sqlalchemy,joelstanner/python-social-auth,drxos/python-social-auth,lamby/python-social-auth,robbiet480/python-social-auth,henocdz/python-social-auth,san-mate/python-social-auth,jeyraof/python-social-auth,jeyraof/python-social-auth,mrwags/python-social-auth,DhiaEddineSaidi/python-social-auth,barseghyanartur/python-social-auth,JerzySpendel/python-social-auth,firstjob/python-social-auth,mchdks/python-social-auth,contracode/python-social-auth,ByteInternet/python-social-auth,Andygmb/python-social-auth,lamby/python-social-auth,drxos/python-social-auth,ariestiyansyah/python-social-auth,nirmalvp/python-social-auth,barseghyanartur/python-social-auth,clef/python-social-auth,michael-borisov/python-social-auth,san-mate/python-social-auth,VishvajitP/python-social-auth,daniula/python-social-auth,henocdz/python-social-auth,jameslittle/python-social-auth,webjunkie/python-social-auth,degs098/python-social-auth,lawrence34/python-social-auth,tkajtoch/python-social-auth,bjorand/python-social-auth,chandolia/python-social-auth,lawrence34/python-social-auth,iruga090/python-social-auth,cjltsod/python-social-auth,mathspace/python-social-auth,S01780/python-social-auth,ByteInternet/python-social-auth,python-social-auth/social-core,ariestiyansyah/python-social-auth,python-social-auth/social-core,JerzySpendel/python-social-auth,python-social-auth/social-docs,Andygmb/python-social-auth,fearlessspider/python-social-auth,muhammad-ammar/python-social-auth,tobias47n9e/social-core,rsteca/python-social-auth,joelstanner/python-social-auth,iruga090/python-social-auth,Andygmb/python-social-auth,noodle-learns-programming/python-social-auth,wildtetris/python-social-auth,S01780/python-social-auth,bjorand/python-social-auth,degs098/python-social-auth,JerzySpendel/python-social-auth,michael-borisov/python-social-auth,jameslittle/python-social-auth,jneves/python-social-auth,muhammad-ammar/python-social-auth,mchdks/python-social-auth,robbiet480/python-social-auth,ByteInternet/python-social-auth,python-social-auth/social-app-django,rsalmaso/python-social-auth,contracode/python-social-auth,fearlessspider/python-social-auth,noodle-learns-programming/python-social-auth,VishvajitP/python-social-auth,mrwags/python-social-auth,webjunkie/python-social-auth,nirmalvp/python-social-auth,nirmalvp/python-social-auth,VishvajitP/python-social-auth,JJediny/python-social-auth,drxos/python-social-auth,noodle-learns-programming/python-social-auth,lneoe/python-social-auth,lneoe/python-social-auth,lawrence34/python-social-auth,degs098/python-social-auth,jeyraof/python-social-auth,merutak/python-social-auth,cmichal/python-social-auth,wildtetris/python-social-auth,alrusdi/python-social-auth,cmichal/python-social-auth,clef/python-social-auth,cmichal/python-social-auth,tkajtoch/python-social-auth,alrusdi/python-social-auth,msampathkumar/python-social-auth,alrusdi/python-social-auth,ononeor12/python-social-auth,robbiet480/python-social-auth,rsalmaso/python-social-auth,rsteca/python-social-auth,webjunkie/python-social-auth,falcon1kr/python-social-auth,jameslittle/python-social-auth,merutak/python-social-auth,fearlessspider/python-social-auth,falcon1kr/python-social-auth,chandolia/python-social-auth,contracode/python-social-auth,JJediny/python-social-auth,S01780/python-social-auth,clef/python-social-auth,mchdks/python-social-auth,bjorand/python-social-auth,wildtetris/python-social-auth,cjltsod/python-social-auth,ononeor12/python-social-auth,python-social-auth/social-app-cherrypy,barseghyanartur/python-social-auth,msampathkumar/python-social-auth,python-social-auth/social-app-django,python-social-auth/social-app-django,mathspace/python-social-auth,tkajtoch/python-social-auth,jneves/python-social-auth,DhiaEddineSaidi/python-social-auth,rsteca/python-social-auth,msampathkumar/python-social-auth,falcon1kr/python-social-auth,ononeor12/python-social-auth,iruga090/python-social-auth,henocdz/python-social-auth,merutak/python-social-auth,JJediny/python-social-auth,mathspace/python-social-auth,daniula/python-social-auth,firstjob/python-social-auth,mrwags/python-social-auth,daniula/python-social-auth,ariestiyansyah/python-social-auth,DhiaEddineSaidi/python-social-auth,lneoe/python-social-auth,muhammad-ammar/python-social-auth,joelstanner/python-social-auth,san-mate/python-social-auth,michael-borisov/python-social-auth,lamby/python-social-auth,jneves/python-social-auth,chandolia/python-social-auth,firstjob/python-social-auth | social/strategies/tornado_strategy.py | social/strategies/tornado_strategy.py | import json
from tornado.template import Loader, Template
from social.utils import build_absolute_uri
from social.strategies.base import BaseStrategy, BaseTemplateStrategy
class TornadoTemplateStrategy(BaseTemplateStrategy):
def render_template(self, tpl, context):
path, tpl = tpl.rsplit('/', 1)
return Loader(path).load(tpl).generate(**context)
def render_string(self, html, context):
return Template(html).generate(**context)
class TornadoStrategy(BaseStrategy):
DEFAULT_TEMPLATE_STRATEGY = TornadoTemplateStrategy
def __init__(self, storage, request_handler, tpl=None):
self.request_handler = request_handler
self.request = self.request_handler.request
super(TornadoStrategy, self).__init__(storage, tpl)
def get_setting(self, name):
return self.request_handler.settings[name]
def request_data(self, merge=True):
# Multiple valued arguments not supported yet
return dict((key, val[0])
for key, val in self.request.arguments.iteritems())
def request_host(self):
return self.request.host
def redirect(self, url):
return self.request_handler.redirect(url)
def html(self, content):
self.request_handler.write(content)
def session_get(self, name, default=None):
return self.request_handler.get_secure_cookie(name) or default
def session_set(self, name, value):
self.request_handler.set_secure_cookie(name, str(value))
def session_pop(self, name):
value = self.request_handler.get_secure_cookie(name)
self.request_handler.set_secure_cookie(name, '')
return value
def session_setdefault(self, name, value):
pass
def build_absolute_uri(self, path=None):
return build_absolute_uri('{0}://{1}'.format(self.request.protocol,
self.request.host),
path)
def partial_to_session(self, next, backend, request=None, *args, **kwargs):
return json.dumps(super(TornadoStrategy, self).partial_to_session(
next, backend, request=request, *args, **kwargs
))
def partial_from_session(self, session):
if session:
return super(TornadoStrategy, self).partial_to_session(
json.loads(session)
)
| import json
from tornado.template import Loader, Template
from social.utils import build_absolute_uri
from social.strategies.base import BaseStrategy, BaseTemplateStrategy
class TornadoTemplateStrategy(BaseTemplateStrategy):
def render_template(self, tpl, context):
path, tpl = tpl.rsplit('/', 1)
return Loader(path).load(tpl).generate(**context)
def render_string(self, html, context):
return Template(html).generate(**context)
class TornadoStrategy(BaseStrategy):
DEFAULT_TEMPLATE_STRATEGY = TornadoTemplateStrategy
def __init__(self, storage, request_handler, tpl=None):
self.request_handler = request_handler
self.request = self.request_handler.request
super(TornadoStrategy, self).__init__(storage, tpl)
def get_setting(self, name):
return self.request_handler.settings[name]
def request_data(self, merge=True):
# Multiple valued arguments not supported yet
return {key: val[0] for key, val in self.request.arguments.iteritems()}
def request_host(self):
return self.request.host
def redirect(self, url):
return self.request_handler.redirect(url)
def html(self, content):
self.request_handler.write(content)
def session_get(self, name, default=None):
return self.request_handler.get_secure_cookie(name) or default
def session_set(self, name, value):
self.request_handler.set_secure_cookie(name, str(value))
def session_pop(self, name):
value = self.request_handler.get_secure_cookie(name)
self.request_handler.set_secure_cookie(name, '')
return value
def session_setdefault(self, name, value):
pass
def build_absolute_uri(self, path=None):
return build_absolute_uri('{0}://{1}'.format(self.request.protocol,
self.request.host),
path)
def partial_to_session(self, next, backend, request=None, *args, **kwargs):
return json.dumps(super(TornadoStrategy, self).partial_to_session(
next, backend, request=request, *args, **kwargs
))
def partial_from_session(self, session):
if session:
return super(TornadoStrategy, self).partial_to_session(
json.loads(session)
)
| bsd-3-clause | Python |
6bfab23170c108c50c9b2dc4988e8670ed677d65 | Allow including html files. Build script made executable. | Darchangel/git-presentation,Darchangel/git-presentation | build.py | build.py | #!/usr/bin/python
import distutils.core
from os import path
import re
include_folder = 'slides'
include_templates = ['{}.html', '{}.md']
include_regex = re.compile('@@([a-zA-Z0-9-_]+)')
in_file = 'index.html'
out_folder = '../dist'
out_file_name = 'index.html'
dirs_to_copy = ['css', 'js', 'lib', 'plugin']
def main():
print('Copying static directories...')
for directory in dirs_to_copy:
target = path.join(out_folder, directory)
if path.exists(target):
distutils.dir_util.remove_tree(target) #WARNING: THIS ACTUALLY REPLACES THE OLD ONE, SO BE CAREFUL
distutils.dir_util.copy_tree(directory, target)
print('{} copied'.format(directory))
print('All copied.')
print('Processing {} file...'.format(in_file))
with open(path.join(out_folder, out_file_name), 'w+') as fout:
with open(in_file, 'r') as fin:
text = fin.read()
text = include_regex.sub(processIncludeMatch, text)
fout.write(text)
print('{} file processed.'.format(in_file))
print('All done!')
def processIncludeMatch(match):
return includeFile(match.group(1))
def includeFile(name):
filename = ''
exists = False
for template in include_templates:
filename = path.join(include_folder, template.format(name))
if path.isfile(filename):
exists = True
break
if exists:
print('>> File {} included'.format(filename))
with open(filename, 'r') as f:
return f.read()
main()
| import distutils.core
from os import path
import re
include_folder = 'slides'
include_template = '{}.md'
include_regex = re.compile('@@([a-zA-Z0-9-_]+)')
in_file = 'index.html'
out_folder = '../dist'
out_file_name = 'index.html'
dirs_to_copy = ['css', 'js', 'lib', 'plugin']
def main():
print('Copying static directories...')
for directory in dirs_to_copy:
target = path.join(out_folder, directory)
if path.exists(target):
distutils.dir_util.remove_tree(target) #WARNING: THIS ACTUALLY REPLACES THE OLD ONE, SO BE CAREFUL
distutils.dir_util.copy_tree(directory, target)
print('{} copied'.format(directory))
print('All copied.')
print('Processing {} file...'.format(in_file))
with open(path.join(out_folder, out_file_name), 'w+') as fout:
with open(in_file, 'r') as fin:
text = fin.read()
matches = include_regex.findall(text) #save matches to print them
text = include_regex.sub(processIncludeMatch, text)
fout.write(text)
if matches is not None:
for match in matches:
print('>> File {} included'.format(include_template.format(match)))
print('{} file processed.'.format(in_file))
print('All done!')
def processIncludeMatch(match):
return includeFile(match.group(1))
def includeFile(name):
filename = path.join(include_folder, include_template.format(name))
with open(filename, 'r') as f:
return f.read()
main()
| mit | Python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.