commit stringlengths 40 40 | old_file stringlengths 4 106 | new_file stringlengths 4 106 | old_contents stringlengths 10 2.94k | new_contents stringlengths 21 2.95k | subject stringlengths 16 444 | message stringlengths 17 2.63k | lang stringclasses 1 value | license stringclasses 13 values | repos stringlengths 7 43k | ndiff stringlengths 52 3.31k | instruction stringlengths 16 444 | content stringlengths 133 4.32k | diff stringlengths 49 3.61k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0c89a78d3a0574ef491d3695366cd786b4c3f950 | indico/migrations/versions/20200904_1543_f37d509e221c_add_user_profile_picture_column.py | indico/migrations/versions/20200904_1543_f37d509e221c_add_user_profile_picture_column.py |
import sqlalchemy as sa
from alembic import op
from indico.core.db.sqlalchemy import PyIntEnum
from indico.modules.users.models.users import ProfilePictureSource
# revision identifiers, used by Alembic.
revision = 'f37d509e221c'
down_revision = 'c997dc927fbc'
branch_labels = None
depends_on = None
def upgrade():
op.add_column('users',
sa.Column('picture_source', PyIntEnum(ProfilePictureSource), nullable=False, server_default='0'),
schema='users')
op.alter_column('users', 'picture_source', server_default=None, schema='users')
op.execute('UPDATE users.users SET picture_source = 3 WHERE picture IS NOT NULL')
def downgrade():
op.drop_column('users', 'picture_source', schema='users')
|
from enum import Enum
import sqlalchemy as sa
from alembic import op
from indico.core.db.sqlalchemy import PyIntEnum
# revision identifiers, used by Alembic.
revision = 'f37d509e221c'
down_revision = 'c997dc927fbc'
branch_labels = None
depends_on = None
class _ProfilePictureSource(int, Enum):
standard = 0
identicon = 1
gravatar = 2
custom = 3
def upgrade():
op.add_column('users',
sa.Column('picture_source', PyIntEnum(_ProfilePictureSource), nullable=False, server_default='0'),
schema='users')
op.alter_column('users', 'picture_source', server_default=None, schema='users')
op.execute('UPDATE users.users SET picture_source = 3 WHERE picture IS NOT NULL')
def downgrade():
op.drop_column('users', 'picture_source', schema='users')
| Use embedded enum in alembic revision | Use embedded enum in alembic revision
Unlikely to matter here but like this it will work correctly even in a
future where someone may add new sources to the original enum (in that
case this particular revision should not add those newer ones, which
would be the case when using the imported enum)
| Python | mit | DirkHoffmann/indico,indico/indico,DirkHoffmann/indico,ThiefMaster/indico,indico/indico,indico/indico,pferreir/indico,ThiefMaster/indico,pferreir/indico,pferreir/indico,pferreir/indico,indico/indico,ThiefMaster/indico,DirkHoffmann/indico,DirkHoffmann/indico,ThiefMaster/indico | +
+ from enum import Enum
import sqlalchemy as sa
from alembic import op
from indico.core.db.sqlalchemy import PyIntEnum
- from indico.modules.users.models.users import ProfilePictureSource
# revision identifiers, used by Alembic.
revision = 'f37d509e221c'
down_revision = 'c997dc927fbc'
branch_labels = None
depends_on = None
+ class _ProfilePictureSource(int, Enum):
+ standard = 0
+ identicon = 1
+ gravatar = 2
+ custom = 3
+
+
def upgrade():
op.add_column('users',
- sa.Column('picture_source', PyIntEnum(ProfilePictureSource), nullable=False, server_default='0'),
+ sa.Column('picture_source', PyIntEnum(_ProfilePictureSource), nullable=False, server_default='0'),
schema='users')
op.alter_column('users', 'picture_source', server_default=None, schema='users')
op.execute('UPDATE users.users SET picture_source = 3 WHERE picture IS NOT NULL')
def downgrade():
op.drop_column('users', 'picture_source', schema='users')
| Use embedded enum in alembic revision | ## Code Before:
import sqlalchemy as sa
from alembic import op
from indico.core.db.sqlalchemy import PyIntEnum
from indico.modules.users.models.users import ProfilePictureSource
# revision identifiers, used by Alembic.
revision = 'f37d509e221c'
down_revision = 'c997dc927fbc'
branch_labels = None
depends_on = None
def upgrade():
op.add_column('users',
sa.Column('picture_source', PyIntEnum(ProfilePictureSource), nullable=False, server_default='0'),
schema='users')
op.alter_column('users', 'picture_source', server_default=None, schema='users')
op.execute('UPDATE users.users SET picture_source = 3 WHERE picture IS NOT NULL')
def downgrade():
op.drop_column('users', 'picture_source', schema='users')
## Instruction:
Use embedded enum in alembic revision
## Code After:
from enum import Enum
import sqlalchemy as sa
from alembic import op
from indico.core.db.sqlalchemy import PyIntEnum
# revision identifiers, used by Alembic.
revision = 'f37d509e221c'
down_revision = 'c997dc927fbc'
branch_labels = None
depends_on = None
class _ProfilePictureSource(int, Enum):
standard = 0
identicon = 1
gravatar = 2
custom = 3
def upgrade():
op.add_column('users',
sa.Column('picture_source', PyIntEnum(_ProfilePictureSource), nullable=False, server_default='0'),
schema='users')
op.alter_column('users', 'picture_source', server_default=None, schema='users')
op.execute('UPDATE users.users SET picture_source = 3 WHERE picture IS NOT NULL')
def downgrade():
op.drop_column('users', 'picture_source', schema='users')
| +
+ from enum import Enum
import sqlalchemy as sa
from alembic import op
from indico.core.db.sqlalchemy import PyIntEnum
- from indico.modules.users.models.users import ProfilePictureSource
# revision identifiers, used by Alembic.
revision = 'f37d509e221c'
down_revision = 'c997dc927fbc'
branch_labels = None
depends_on = None
+ class _ProfilePictureSource(int, Enum):
+ standard = 0
+ identicon = 1
+ gravatar = 2
+ custom = 3
+
+
def upgrade():
op.add_column('users',
- sa.Column('picture_source', PyIntEnum(ProfilePictureSource), nullable=False, server_default='0'),
+ sa.Column('picture_source', PyIntEnum(_ProfilePictureSource), nullable=False, server_default='0'),
? +
schema='users')
op.alter_column('users', 'picture_source', server_default=None, schema='users')
op.execute('UPDATE users.users SET picture_source = 3 WHERE picture IS NOT NULL')
def downgrade():
op.drop_column('users', 'picture_source', schema='users') |
007cd14cd3fd215cd91403ebe09cd5c0bb555f23 | armstrong/apps/related_content/admin.py | armstrong/apps/related_content/admin.py | from django.contrib import admin
from django.contrib.contenttypes.generic import GenericTabularInline
from .models import RelatedContent
from .models import RelatedType
class RelatedContentInline(GenericTabularInline):
ct_field = "source_type"
ct_fk_field = "source_id"
model = RelatedContent
admin.site.register(RelatedType) | from django import forms
from django.contrib import admin
from django.contrib.contenttypes.generic import GenericTabularInline
from armstrong.hatband import widgets
from .models import RelatedContent
from .models import RelatedType
class RelatedContentInlineForm(forms.ModelForm):
class Meta:
widgets = {
"destination_type": forms.HiddenInput(),
"destination_id": widgets.GenericKeyWidget(
object_id_name="destination_id",
content_type_name="destination_type",
),
"order": forms.HiddenInput(),
}
class RelatedContentInline(GenericTabularInline):
ct_field = "source_type"
ct_fk_field = "source_id"
model = RelatedContent
template = "admin/edit_inline/generickey.html"
form = RelatedContentInlineForm
admin.site.register(RelatedType) | Add in visualsearch for GFK | Add in visualsearch for GFK
| Python | apache-2.0 | texastribune/armstrong.apps.related_content,armstrong/armstrong.apps.related_content,armstrong/armstrong.apps.related_content,texastribune/armstrong.apps.related_content | + from django import forms
from django.contrib import admin
from django.contrib.contenttypes.generic import GenericTabularInline
+ from armstrong.hatband import widgets
+
from .models import RelatedContent
from .models import RelatedType
+
+ class RelatedContentInlineForm(forms.ModelForm):
+ class Meta:
+ widgets = {
+ "destination_type": forms.HiddenInput(),
+ "destination_id": widgets.GenericKeyWidget(
+ object_id_name="destination_id",
+ content_type_name="destination_type",
+ ),
+ "order": forms.HiddenInput(),
+ }
class RelatedContentInline(GenericTabularInline):
ct_field = "source_type"
ct_fk_field = "source_id"
model = RelatedContent
+ template = "admin/edit_inline/generickey.html"
+
+ form = RelatedContentInlineForm
admin.site.register(RelatedType) | Add in visualsearch for GFK | ## Code Before:
from django.contrib import admin
from django.contrib.contenttypes.generic import GenericTabularInline
from .models import RelatedContent
from .models import RelatedType
class RelatedContentInline(GenericTabularInline):
ct_field = "source_type"
ct_fk_field = "source_id"
model = RelatedContent
admin.site.register(RelatedType)
## Instruction:
Add in visualsearch for GFK
## Code After:
from django import forms
from django.contrib import admin
from django.contrib.contenttypes.generic import GenericTabularInline
from armstrong.hatband import widgets
from .models import RelatedContent
from .models import RelatedType
class RelatedContentInlineForm(forms.ModelForm):
class Meta:
widgets = {
"destination_type": forms.HiddenInput(),
"destination_id": widgets.GenericKeyWidget(
object_id_name="destination_id",
content_type_name="destination_type",
),
"order": forms.HiddenInput(),
}
class RelatedContentInline(GenericTabularInline):
ct_field = "source_type"
ct_fk_field = "source_id"
model = RelatedContent
template = "admin/edit_inline/generickey.html"
form = RelatedContentInlineForm
admin.site.register(RelatedType) | + from django import forms
from django.contrib import admin
from django.contrib.contenttypes.generic import GenericTabularInline
+ from armstrong.hatband import widgets
+
from .models import RelatedContent
from .models import RelatedType
+
+ class RelatedContentInlineForm(forms.ModelForm):
+ class Meta:
+ widgets = {
+ "destination_type": forms.HiddenInput(),
+ "destination_id": widgets.GenericKeyWidget(
+ object_id_name="destination_id",
+ content_type_name="destination_type",
+ ),
+ "order": forms.HiddenInput(),
+ }
class RelatedContentInline(GenericTabularInline):
ct_field = "source_type"
ct_fk_field = "source_id"
model = RelatedContent
+ template = "admin/edit_inline/generickey.html"
+
+ form = RelatedContentInlineForm
admin.site.register(RelatedType) |
c66a2933cca12fa27b688f60b3eb70b07bcce4e5 | src/ggrc/migrations/utils.py | src/ggrc/migrations/utils.py |
from ggrc import db
from sqlalchemy import and_
from sqlalchemy.orm import aliased
def resolve_duplicates(model, attr):
v0, v1 = aliased(model, name="v0"), aliased(model, name="v1")
query = db.session.query(v0).join(v1, and_(
getattr(v0, attr) == getattr(v1, attr),
v0.id > v1.id
))
for v in query:
setattr(v, attr, getattr(v, attr, model.type) + u"-" + unicode(v.id))
db.session.add(v)
db.session.commit()
|
from ggrc import db
from sqlalchemy import and_
from sqlalchemy.orm import aliased
def resolve_duplicates(model, attr, separator=u"-"):
v0, v1 = aliased(model, name="v0"), aliased(model, name="v1")
query = db.session.query(v0).join(v1, and_(
getattr(v0, attr) == getattr(v1, attr),
v0.id > v1.id
))
for v in query:
i = 0
nattr = "{}{}{}".format(getattr(v, attr, model.type), separator, i)
while db.session.query(model).\
filter(getattr(model, attr) == nattr).count():
i += 1
nattr = "{}{}{}".format(getattr(v, attr, model.type), separator, i)
setattr(v, attr, nattr)
db.session.add(v)
db.session.commit()
| Verify that new attribute doesn't already exist in database | Verify that new attribute doesn't already exist in database
| Python | apache-2.0 | prasannav7/ggrc-core,jmakov/ggrc-core,prasannav7/ggrc-core,andrei-karalionak/ggrc-core,plamut/ggrc-core,jmakov/ggrc-core,kr41/ggrc-core,selahssea/ggrc-core,j0gurt/ggrc-core,edofic/ggrc-core,AleksNeStu/ggrc-core,j0gurt/ggrc-core,selahssea/ggrc-core,selahssea/ggrc-core,kr41/ggrc-core,josthkko/ggrc-core,prasannav7/ggrc-core,AleksNeStu/ggrc-core,AleksNeStu/ggrc-core,plamut/ggrc-core,kr41/ggrc-core,VinnieJohns/ggrc-core,josthkko/ggrc-core,NejcZupec/ggrc-core,plamut/ggrc-core,prasannav7/ggrc-core,edofic/ggrc-core,edofic/ggrc-core,jmakov/ggrc-core,andrei-karalionak/ggrc-core,andrei-karalionak/ggrc-core,j0gurt/ggrc-core,plamut/ggrc-core,NejcZupec/ggrc-core,josthkko/ggrc-core,josthkko/ggrc-core,edofic/ggrc-core,jmakov/ggrc-core,andrei-karalionak/ggrc-core,jmakov/ggrc-core,kr41/ggrc-core,selahssea/ggrc-core,j0gurt/ggrc-core,AleksNeStu/ggrc-core,VinnieJohns/ggrc-core,NejcZupec/ggrc-core,VinnieJohns/ggrc-core,NejcZupec/ggrc-core,VinnieJohns/ggrc-core |
from ggrc import db
from sqlalchemy import and_
from sqlalchemy.orm import aliased
- def resolve_duplicates(model, attr):
+ def resolve_duplicates(model, attr, separator=u"-"):
v0, v1 = aliased(model, name="v0"), aliased(model, name="v1")
query = db.session.query(v0).join(v1, and_(
getattr(v0, attr) == getattr(v1, attr),
v0.id > v1.id
))
for v in query:
- setattr(v, attr, getattr(v, attr, model.type) + u"-" + unicode(v.id))
+ i = 0
+ nattr = "{}{}{}".format(getattr(v, attr, model.type), separator, i)
+ while db.session.query(model).\
+ filter(getattr(model, attr) == nattr).count():
+ i += 1
+ nattr = "{}{}{}".format(getattr(v, attr, model.type), separator, i)
+ setattr(v, attr, nattr)
db.session.add(v)
db.session.commit()
| Verify that new attribute doesn't already exist in database | ## Code Before:
from ggrc import db
from sqlalchemy import and_
from sqlalchemy.orm import aliased
def resolve_duplicates(model, attr):
v0, v1 = aliased(model, name="v0"), aliased(model, name="v1")
query = db.session.query(v0).join(v1, and_(
getattr(v0, attr) == getattr(v1, attr),
v0.id > v1.id
))
for v in query:
setattr(v, attr, getattr(v, attr, model.type) + u"-" + unicode(v.id))
db.session.add(v)
db.session.commit()
## Instruction:
Verify that new attribute doesn't already exist in database
## Code After:
from ggrc import db
from sqlalchemy import and_
from sqlalchemy.orm import aliased
def resolve_duplicates(model, attr, separator=u"-"):
v0, v1 = aliased(model, name="v0"), aliased(model, name="v1")
query = db.session.query(v0).join(v1, and_(
getattr(v0, attr) == getattr(v1, attr),
v0.id > v1.id
))
for v in query:
i = 0
nattr = "{}{}{}".format(getattr(v, attr, model.type), separator, i)
while db.session.query(model).\
filter(getattr(model, attr) == nattr).count():
i += 1
nattr = "{}{}{}".format(getattr(v, attr, model.type), separator, i)
setattr(v, attr, nattr)
db.session.add(v)
db.session.commit()
|
from ggrc import db
from sqlalchemy import and_
from sqlalchemy.orm import aliased
- def resolve_duplicates(model, attr):
+ def resolve_duplicates(model, attr, separator=u"-"):
? ++++++++++++++++
v0, v1 = aliased(model, name="v0"), aliased(model, name="v1")
query = db.session.query(v0).join(v1, and_(
getattr(v0, attr) == getattr(v1, attr),
v0.id > v1.id
))
for v in query:
- setattr(v, attr, getattr(v, attr, model.type) + u"-" + unicode(v.id))
+ i = 0
+ nattr = "{}{}{}".format(getattr(v, attr, model.type), separator, i)
+ while db.session.query(model).\
+ filter(getattr(model, attr) == nattr).count():
+ i += 1
+ nattr = "{}{}{}".format(getattr(v, attr, model.type), separator, i)
+ setattr(v, attr, nattr)
db.session.add(v)
db.session.commit() |
a5ce33cf60deb5a1045a0bf693b58eb20dbad8d2 | sshkeys_update.py | sshkeys_update.py | import config, store, os
standalone_py = os.path.join(os.path.dirname(__file__), 'standalone.py')
c = config.Config("config.ini")
s = store.Store(c)
cursor = s.get_cursor()
cursor.execute("lock table sshkeys in exclusive mode") # to prevent simultaneous updates
cursor.execute("select u.name,s.key from users u, sshkeys s where u.name=s.name")
lines = []
for name, key in cursor.fetchall():
lines.append('command="%s -r %s",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty %s\n' %
(standalone_py, name, key))
f = open('.ssh/authorized_keys', 'wb')
f.write(''.join(lines))
f.close()
s.rollback()
| import config, store, os
standalone_py = os.path.join(os.path.dirname(__file__), 'standalone.py')
c = config.Config("config.ini")
s = store.Store(c)
cursor = s.get_cursor()
cursor.execute("lock table sshkeys in exclusive mode") # to prevent simultaneous updates
cursor.execute("select u.name,s.key from users u, sshkeys s where u.name=s.name")
lines = []
for name, key in cursor.fetchall():
lines.append('command="%s -r %s",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty %s\n' %
(standalone_py, name, key))
f = open(os.path.expanduser('~submit/.ssh/authorized_keys'), 'wb')
f.write(''.join(lines))
f.close()
s.rollback()
| Make sure to write in ~submit's authorized_keys. | Make sure to write in ~submit's authorized_keys.
| Python | bsd-3-clause | pydotorg/pypi,pydotorg/pypi,pydotorg/pypi,pydotorg/pypi | import config, store, os
standalone_py = os.path.join(os.path.dirname(__file__), 'standalone.py')
c = config.Config("config.ini")
s = store.Store(c)
cursor = s.get_cursor()
cursor.execute("lock table sshkeys in exclusive mode") # to prevent simultaneous updates
cursor.execute("select u.name,s.key from users u, sshkeys s where u.name=s.name")
lines = []
for name, key in cursor.fetchall():
lines.append('command="%s -r %s",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty %s\n' %
(standalone_py, name, key))
- f = open('.ssh/authorized_keys', 'wb')
+ f = open(os.path.expanduser('~submit/.ssh/authorized_keys'), 'wb')
f.write(''.join(lines))
f.close()
s.rollback()
| Make sure to write in ~submit's authorized_keys. | ## Code Before:
import config, store, os
standalone_py = os.path.join(os.path.dirname(__file__), 'standalone.py')
c = config.Config("config.ini")
s = store.Store(c)
cursor = s.get_cursor()
cursor.execute("lock table sshkeys in exclusive mode") # to prevent simultaneous updates
cursor.execute("select u.name,s.key from users u, sshkeys s where u.name=s.name")
lines = []
for name, key in cursor.fetchall():
lines.append('command="%s -r %s",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty %s\n' %
(standalone_py, name, key))
f = open('.ssh/authorized_keys', 'wb')
f.write(''.join(lines))
f.close()
s.rollback()
## Instruction:
Make sure to write in ~submit's authorized_keys.
## Code After:
import config, store, os
standalone_py = os.path.join(os.path.dirname(__file__), 'standalone.py')
c = config.Config("config.ini")
s = store.Store(c)
cursor = s.get_cursor()
cursor.execute("lock table sshkeys in exclusive mode") # to prevent simultaneous updates
cursor.execute("select u.name,s.key from users u, sshkeys s where u.name=s.name")
lines = []
for name, key in cursor.fetchall():
lines.append('command="%s -r %s",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty %s\n' %
(standalone_py, name, key))
f = open(os.path.expanduser('~submit/.ssh/authorized_keys'), 'wb')
f.write(''.join(lines))
f.close()
s.rollback()
| import config, store, os
standalone_py = os.path.join(os.path.dirname(__file__), 'standalone.py')
c = config.Config("config.ini")
s = store.Store(c)
cursor = s.get_cursor()
cursor.execute("lock table sshkeys in exclusive mode") # to prevent simultaneous updates
cursor.execute("select u.name,s.key from users u, sshkeys s where u.name=s.name")
lines = []
for name, key in cursor.fetchall():
lines.append('command="%s -r %s",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty %s\n' %
(standalone_py, name, key))
- f = open('.ssh/authorized_keys', 'wb')
+ f = open(os.path.expanduser('~submit/.ssh/authorized_keys'), 'wb')
f.write(''.join(lines))
f.close()
s.rollback()
|
a2430b67423ce036d2a96541e86d356ace04db69 | Twitch/cogs/words.py | Twitch/cogs/words.py |
from twitchio.ext import commands
@commands.cog()
class Words:
def __init__(self, bot):
self.bot = bot
@commands.command()
async def audiodefine(self, ctx, word):
url = f"http://api.wordnik.com:80/v4/word.json/{word}/audio"
params = {"useCanonical": "false", "limit": 1, "api_key": self.bot.WORDNIK_API_KEY}
async with self.bot.aiohttp_session.get(url, params = params) as resp:
data = await resp.json()
if data:
await ctx.send(f"{data[0]['word'].capitalize()}: {data[0]['fileUrl']}")
else:
await ctx.send("Word or audio not found.")
@commands.command()
async def define(self, ctx, word):
url = f"http://api.wordnik.com:80/v4/word.json/{word}/definitions"
params = {"limit": 1, "includeRelated": "false", "useCanonical": "false", "includeTags": "false",
"api_key": self.bot.WORDNIK_API_KEY}
async with self.bot.aiohttp_session.get(url, params = params) as resp:
data = await resp.json()
if data:
await ctx.send(data[0]["word"].capitalize() + ": " + data[0]["text"])
else:
await ctx.send("Definition not found.")
|
from twitchio.ext import commands
@commands.cog()
class Words:
def __init__(self, bot):
self.bot = bot
@commands.command()
async def audiodefine(self, ctx, word):
url = f"http://api.wordnik.com:80/v4/word.json/{word}/audio"
params = {"useCanonical": "false", "limit": 1, "api_key": self.bot.WORDNIK_API_KEY}
async with self.bot.aiohttp_session.get(url, params = params) as resp:
data = await resp.json()
if data:
await ctx.send(f"{data[0]['word'].capitalize()}: {data[0]['fileUrl']}")
else:
await ctx.send("Word or audio not found.")
@commands.command()
async def define(self, ctx, word):
url = f"http://api.wordnik.com:80/v4/word.json/{word}/definitions"
params = {"limit": 1, "includeRelated": "false", "useCanonical": "false", "includeTags": "false",
"api_key": self.bot.WORDNIK_API_KEY}
async with self.bot.aiohttp_session.get(url, params = params) as resp:
data = await resp.json()
if data:
await ctx.send(f"{data[0]['word'].capitalize()}: {data[0]['text']}")
else:
await ctx.send("Definition not found.")
| Use f-string for define command | [TwitchIO] Use f-string for define command
| Python | mit | Harmon758/Harmonbot,Harmon758/Harmonbot |
from twitchio.ext import commands
@commands.cog()
class Words:
def __init__(self, bot):
self.bot = bot
@commands.command()
async def audiodefine(self, ctx, word):
url = f"http://api.wordnik.com:80/v4/word.json/{word}/audio"
params = {"useCanonical": "false", "limit": 1, "api_key": self.bot.WORDNIK_API_KEY}
async with self.bot.aiohttp_session.get(url, params = params) as resp:
data = await resp.json()
if data:
await ctx.send(f"{data[0]['word'].capitalize()}: {data[0]['fileUrl']}")
else:
await ctx.send("Word or audio not found.")
@commands.command()
async def define(self, ctx, word):
url = f"http://api.wordnik.com:80/v4/word.json/{word}/definitions"
params = {"limit": 1, "includeRelated": "false", "useCanonical": "false", "includeTags": "false",
"api_key": self.bot.WORDNIK_API_KEY}
async with self.bot.aiohttp_session.get(url, params = params) as resp:
data = await resp.json()
if data:
- await ctx.send(data[0]["word"].capitalize() + ": " + data[0]["text"])
+ await ctx.send(f"{data[0]['word'].capitalize()}: {data[0]['text']}")
else:
await ctx.send("Definition not found.")
| Use f-string for define command | ## Code Before:
from twitchio.ext import commands
@commands.cog()
class Words:
def __init__(self, bot):
self.bot = bot
@commands.command()
async def audiodefine(self, ctx, word):
url = f"http://api.wordnik.com:80/v4/word.json/{word}/audio"
params = {"useCanonical": "false", "limit": 1, "api_key": self.bot.WORDNIK_API_KEY}
async with self.bot.aiohttp_session.get(url, params = params) as resp:
data = await resp.json()
if data:
await ctx.send(f"{data[0]['word'].capitalize()}: {data[0]['fileUrl']}")
else:
await ctx.send("Word or audio not found.")
@commands.command()
async def define(self, ctx, word):
url = f"http://api.wordnik.com:80/v4/word.json/{word}/definitions"
params = {"limit": 1, "includeRelated": "false", "useCanonical": "false", "includeTags": "false",
"api_key": self.bot.WORDNIK_API_KEY}
async with self.bot.aiohttp_session.get(url, params = params) as resp:
data = await resp.json()
if data:
await ctx.send(data[0]["word"].capitalize() + ": " + data[0]["text"])
else:
await ctx.send("Definition not found.")
## Instruction:
Use f-string for define command
## Code After:
from twitchio.ext import commands
@commands.cog()
class Words:
def __init__(self, bot):
self.bot = bot
@commands.command()
async def audiodefine(self, ctx, word):
url = f"http://api.wordnik.com:80/v4/word.json/{word}/audio"
params = {"useCanonical": "false", "limit": 1, "api_key": self.bot.WORDNIK_API_KEY}
async with self.bot.aiohttp_session.get(url, params = params) as resp:
data = await resp.json()
if data:
await ctx.send(f"{data[0]['word'].capitalize()}: {data[0]['fileUrl']}")
else:
await ctx.send("Word or audio not found.")
@commands.command()
async def define(self, ctx, word):
url = f"http://api.wordnik.com:80/v4/word.json/{word}/definitions"
params = {"limit": 1, "includeRelated": "false", "useCanonical": "false", "includeTags": "false",
"api_key": self.bot.WORDNIK_API_KEY}
async with self.bot.aiohttp_session.get(url, params = params) as resp:
data = await resp.json()
if data:
await ctx.send(f"{data[0]['word'].capitalize()}: {data[0]['text']}")
else:
await ctx.send("Definition not found.")
|
from twitchio.ext import commands
@commands.cog()
class Words:
def __init__(self, bot):
self.bot = bot
@commands.command()
async def audiodefine(self, ctx, word):
url = f"http://api.wordnik.com:80/v4/word.json/{word}/audio"
params = {"useCanonical": "false", "limit": 1, "api_key": self.bot.WORDNIK_API_KEY}
async with self.bot.aiohttp_session.get(url, params = params) as resp:
data = await resp.json()
if data:
await ctx.send(f"{data[0]['word'].capitalize()}: {data[0]['fileUrl']}")
else:
await ctx.send("Word or audio not found.")
@commands.command()
async def define(self, ctx, word):
url = f"http://api.wordnik.com:80/v4/word.json/{word}/definitions"
params = {"limit": 1, "includeRelated": "false", "useCanonical": "false", "includeTags": "false",
"api_key": self.bot.WORDNIK_API_KEY}
async with self.bot.aiohttp_session.get(url, params = params) as resp:
data = await resp.json()
if data:
- await ctx.send(data[0]["word"].capitalize() + ": " + data[0]["text"])
? ^ ^ ^^^^ ^^^^ ^ -
+ await ctx.send(f"{data[0]['word'].capitalize()}: {data[0]['text']}")
? +++ ^ ^ ^ ^ ^ +++
else:
await ctx.send("Definition not found.")
|
bfbc2bc38cbc7cbcd0afbb8d077fccf1925c0c16 | gaphor/SysML/blocks/grouping.py | gaphor/SysML/blocks/grouping.py | from gaphor.diagram.grouping import AbstractGroup, Group
from gaphor.SysML.blocks.block import BlockItem
from gaphor.SysML.blocks.property import PropertyItem
@Group.register(BlockItem, PropertyItem)
class NodeGroup(AbstractGroup):
"""
Add node to another node.
"""
def group(self):
self.parent.subject.ownedAttribute = self.item.subject
def ungroup(self):
del self.parent.subject.ownedAttribute[self.item.subject]
| from gaphor.diagram.grouping import AbstractGroup, Group
from gaphor.SysML.blocks.block import BlockItem
from gaphor.SysML.blocks.property import PropertyItem
@Group.register(BlockItem, PropertyItem)
class PropertyGroup(AbstractGroup):
"""
Add Property to a Block.
"""
def group(self):
self.parent.subject.ownedAttribute = self.item.subject
def ungroup(self):
del self.parent.subject.ownedAttribute[self.item.subject]
| Fix name for property/block group | Fix name for property/block group
| Python | lgpl-2.1 | amolenaar/gaphor,amolenaar/gaphor | from gaphor.diagram.grouping import AbstractGroup, Group
from gaphor.SysML.blocks.block import BlockItem
from gaphor.SysML.blocks.property import PropertyItem
@Group.register(BlockItem, PropertyItem)
- class NodeGroup(AbstractGroup):
+ class PropertyGroup(AbstractGroup):
"""
- Add node to another node.
+ Add Property to a Block.
"""
def group(self):
self.parent.subject.ownedAttribute = self.item.subject
def ungroup(self):
del self.parent.subject.ownedAttribute[self.item.subject]
| Fix name for property/block group | ## Code Before:
from gaphor.diagram.grouping import AbstractGroup, Group
from gaphor.SysML.blocks.block import BlockItem
from gaphor.SysML.blocks.property import PropertyItem
@Group.register(BlockItem, PropertyItem)
class NodeGroup(AbstractGroup):
"""
Add node to another node.
"""
def group(self):
self.parent.subject.ownedAttribute = self.item.subject
def ungroup(self):
del self.parent.subject.ownedAttribute[self.item.subject]
## Instruction:
Fix name for property/block group
## Code After:
from gaphor.diagram.grouping import AbstractGroup, Group
from gaphor.SysML.blocks.block import BlockItem
from gaphor.SysML.blocks.property import PropertyItem
@Group.register(BlockItem, PropertyItem)
class PropertyGroup(AbstractGroup):
"""
Add Property to a Block.
"""
def group(self):
self.parent.subject.ownedAttribute = self.item.subject
def ungroup(self):
del self.parent.subject.ownedAttribute[self.item.subject]
| from gaphor.diagram.grouping import AbstractGroup, Group
from gaphor.SysML.blocks.block import BlockItem
from gaphor.SysML.blocks.property import PropertyItem
@Group.register(BlockItem, PropertyItem)
- class NodeGroup(AbstractGroup):
? ^ ^
+ class PropertyGroup(AbstractGroup):
? ^^ ^ +++
"""
- Add node to another node.
+ Add Property to a Block.
"""
def group(self):
self.parent.subject.ownedAttribute = self.item.subject
def ungroup(self):
del self.parent.subject.ownedAttribute[self.item.subject] |
f9ba5e64f73c3fa3fed62655c846fb4435d627cc | node/multi_var.py | node/multi_var.py |
from nodes import Node
class MultiVar(Node):
char = "'"
args = 0
results = None
contents = -1
def __init__(self, node_1: Node.NodeSingle, node_2: Node.NodeSingle):
self.node_1 = node_1
self.node_2 = node_2
self.args = max([node_1.args, node_2.args])
def prepare(self, stack):
if len(stack) == 0:
self.add_arg(stack)
@Node.is_func
def apply(self, *stack):
self.node_2.prepare(stack)
rtn = self.node_2(stack[:self.node_2.args])
self.node_1.prepare(stack)
rtn.extend(self.node_1(stack[:self.node_1.args]))
return rtn
|
from nodes import Node
class MultiVar(Node):
char = "'"
args = 0
results = None
contents = -1
def __init__(self, node_1: Node.NodeSingle, node_2: Node.NodeSingle):
self.node_1 = node_1
self.node_2 = node_2
def prepare(self, stack):
self.node_1.prepare(stack)
self.node_2.prepare(stack)
self.args = max([self.node_1.args,self.node_2.args])
@Node.is_func
def apply(self, *stack):
rtn = self.node_2(stack[:self.node_2.args])
rtn.extend(self.node_1(stack[:self.node_1.args]))
return rtn
| Fix multivar for nodes with variable lenght stacks | Fix multivar for nodes with variable lenght stacks
| Python | mit | muddyfish/PYKE,muddyfish/PYKE |
from nodes import Node
class MultiVar(Node):
char = "'"
args = 0
results = None
contents = -1
def __init__(self, node_1: Node.NodeSingle, node_2: Node.NodeSingle):
self.node_1 = node_1
self.node_2 = node_2
- self.args = max([node_1.args, node_2.args])
def prepare(self, stack):
- if len(stack) == 0:
- self.add_arg(stack)
+ self.node_1.prepare(stack)
+ self.node_2.prepare(stack)
+ self.args = max([self.node_1.args,self.node_2.args])
@Node.is_func
def apply(self, *stack):
- self.node_2.prepare(stack)
rtn = self.node_2(stack[:self.node_2.args])
- self.node_1.prepare(stack)
rtn.extend(self.node_1(stack[:self.node_1.args]))
return rtn
| Fix multivar for nodes with variable lenght stacks | ## Code Before:
from nodes import Node
class MultiVar(Node):
char = "'"
args = 0
results = None
contents = -1
def __init__(self, node_1: Node.NodeSingle, node_2: Node.NodeSingle):
self.node_1 = node_1
self.node_2 = node_2
self.args = max([node_1.args, node_2.args])
def prepare(self, stack):
if len(stack) == 0:
self.add_arg(stack)
@Node.is_func
def apply(self, *stack):
self.node_2.prepare(stack)
rtn = self.node_2(stack[:self.node_2.args])
self.node_1.prepare(stack)
rtn.extend(self.node_1(stack[:self.node_1.args]))
return rtn
## Instruction:
Fix multivar for nodes with variable lenght stacks
## Code After:
from nodes import Node
class MultiVar(Node):
char = "'"
args = 0
results = None
contents = -1
def __init__(self, node_1: Node.NodeSingle, node_2: Node.NodeSingle):
self.node_1 = node_1
self.node_2 = node_2
def prepare(self, stack):
self.node_1.prepare(stack)
self.node_2.prepare(stack)
self.args = max([self.node_1.args,self.node_2.args])
@Node.is_func
def apply(self, *stack):
rtn = self.node_2(stack[:self.node_2.args])
rtn.extend(self.node_1(stack[:self.node_1.args]))
return rtn
|
from nodes import Node
class MultiVar(Node):
char = "'"
args = 0
results = None
contents = -1
def __init__(self, node_1: Node.NodeSingle, node_2: Node.NodeSingle):
self.node_1 = node_1
self.node_2 = node_2
- self.args = max([node_1.args, node_2.args])
def prepare(self, stack):
- if len(stack) == 0:
- self.add_arg(stack)
+ self.node_1.prepare(stack)
+ self.node_2.prepare(stack)
+ self.args = max([self.node_1.args,self.node_2.args])
@Node.is_func
def apply(self, *stack):
- self.node_2.prepare(stack)
rtn = self.node_2(stack[:self.node_2.args])
- self.node_1.prepare(stack)
rtn.extend(self.node_1(stack[:self.node_1.args]))
return rtn |
4dd28beddc2df9efeef798491d1963800113f801 | django_bootstrap_calendar/models.py | django_bootstrap_calendar/models.py | __author__ = 'sandlbn'
from django.db import models
from django.utils.translation import ugettext_lazy as _
from utils import datetime_to_timestamp
class CalendarEvent(models.Model):
"""
Calendar Events
"""
CSS_CLASS_CHOICES = (
('', _('Normal')),
('event-warning', _('Warning')),
('event-info', _('Info')),
('event-success', _('Success')),
('event-inverse', _('Inverse')),
('event-special', _('Special')),
('event-important', _('Important')),
)
title = models.CharField(max_length=255, verbose_name=_('Title'))
url = models.URLField(verbose_name=_('URL'), null=True, blank=True)
css_class = models.CharField(max_length=20, verbose_name=_('CSS Class'),
choices=CSS_CLASS_CHOICES)
start = models.DateTimeField(verbose_name=_('Start Date'))
end = models.DateTimeField(verbose_name=_('End Date'), null=True,
blank=True)
@property
def start_timestamp(self):
"""
Return end date as timestamp
"""
return datetime_to_timestamp(self.start)
@property
def end_timestamp(self):
"""
Return end date as timestamp
"""
return datetime_to_timestamp(self.end)
def __unicode__(self):
return self.title
| __author__ = 'sandlbn'
from django.db import models
from django.utils.translation import ugettext_lazy as _
from utils import datetime_to_timestamp
class CalendarEvent(models.Model):
"""
Calendar Events
"""
CSS_CLASS_CHOICES = (
('', _('Normal')),
('event-warning', _('Warning')),
('event-info', _('Info')),
('event-success', _('Success')),
('event-inverse', _('Inverse')),
('event-special', _('Special')),
('event-important', _('Important')),
)
title = models.CharField(max_length=255, verbose_name=_('Title'))
url = models.URLField(verbose_name=_('URL'), null=True, blank=True)
css_class = models.CharField(blank=True, max_length=20, verbose_name=_('CSS Class'),
choices=CSS_CLASS_CHOICES)
start = models.DateTimeField(verbose_name=_('Start Date'))
end = models.DateTimeField(verbose_name=_('End Date'), null=True,
blank=True)
@property
def start_timestamp(self):
"""
Return end date as timestamp
"""
return datetime_to_timestamp(self.start)
@property
def end_timestamp(self):
"""
Return end date as timestamp
"""
return datetime_to_timestamp(self.end)
def __unicode__(self):
return self.title
| Allow `css_class` to have blank value. | Allow `css_class` to have blank value.
Currently the default value for the `css_class` field (name `Normal`)
has the value of a blank string. To allow the value to be used
`blank=True` must be set.
| Python | bsd-3-clause | sandlbn/django-bootstrap-calendar,sandlbn/django-bootstrap-calendar,sandlbn/django-bootstrap-calendar | __author__ = 'sandlbn'
from django.db import models
from django.utils.translation import ugettext_lazy as _
from utils import datetime_to_timestamp
class CalendarEvent(models.Model):
"""
Calendar Events
"""
CSS_CLASS_CHOICES = (
('', _('Normal')),
('event-warning', _('Warning')),
('event-info', _('Info')),
('event-success', _('Success')),
('event-inverse', _('Inverse')),
('event-special', _('Special')),
('event-important', _('Important')),
)
title = models.CharField(max_length=255, verbose_name=_('Title'))
url = models.URLField(verbose_name=_('URL'), null=True, blank=True)
- css_class = models.CharField(max_length=20, verbose_name=_('CSS Class'),
+ css_class = models.CharField(blank=True, max_length=20, verbose_name=_('CSS Class'),
choices=CSS_CLASS_CHOICES)
start = models.DateTimeField(verbose_name=_('Start Date'))
end = models.DateTimeField(verbose_name=_('End Date'), null=True,
blank=True)
@property
def start_timestamp(self):
"""
Return end date as timestamp
"""
return datetime_to_timestamp(self.start)
@property
def end_timestamp(self):
"""
Return end date as timestamp
"""
return datetime_to_timestamp(self.end)
def __unicode__(self):
return self.title
| Allow `css_class` to have blank value. | ## Code Before:
__author__ = 'sandlbn'
from django.db import models
from django.utils.translation import ugettext_lazy as _
from utils import datetime_to_timestamp
class CalendarEvent(models.Model):
"""
Calendar Events
"""
CSS_CLASS_CHOICES = (
('', _('Normal')),
('event-warning', _('Warning')),
('event-info', _('Info')),
('event-success', _('Success')),
('event-inverse', _('Inverse')),
('event-special', _('Special')),
('event-important', _('Important')),
)
title = models.CharField(max_length=255, verbose_name=_('Title'))
url = models.URLField(verbose_name=_('URL'), null=True, blank=True)
css_class = models.CharField(max_length=20, verbose_name=_('CSS Class'),
choices=CSS_CLASS_CHOICES)
start = models.DateTimeField(verbose_name=_('Start Date'))
end = models.DateTimeField(verbose_name=_('End Date'), null=True,
blank=True)
@property
def start_timestamp(self):
"""
Return end date as timestamp
"""
return datetime_to_timestamp(self.start)
@property
def end_timestamp(self):
"""
Return end date as timestamp
"""
return datetime_to_timestamp(self.end)
def __unicode__(self):
return self.title
## Instruction:
Allow `css_class` to have blank value.
## Code After:
__author__ = 'sandlbn'
from django.db import models
from django.utils.translation import ugettext_lazy as _
from utils import datetime_to_timestamp
class CalendarEvent(models.Model):
"""
Calendar Events
"""
CSS_CLASS_CHOICES = (
('', _('Normal')),
('event-warning', _('Warning')),
('event-info', _('Info')),
('event-success', _('Success')),
('event-inverse', _('Inverse')),
('event-special', _('Special')),
('event-important', _('Important')),
)
title = models.CharField(max_length=255, verbose_name=_('Title'))
url = models.URLField(verbose_name=_('URL'), null=True, blank=True)
css_class = models.CharField(blank=True, max_length=20, verbose_name=_('CSS Class'),
choices=CSS_CLASS_CHOICES)
start = models.DateTimeField(verbose_name=_('Start Date'))
end = models.DateTimeField(verbose_name=_('End Date'), null=True,
blank=True)
@property
def start_timestamp(self):
"""
Return end date as timestamp
"""
return datetime_to_timestamp(self.start)
@property
def end_timestamp(self):
"""
Return end date as timestamp
"""
return datetime_to_timestamp(self.end)
def __unicode__(self):
return self.title
| __author__ = 'sandlbn'
from django.db import models
from django.utils.translation import ugettext_lazy as _
from utils import datetime_to_timestamp
class CalendarEvent(models.Model):
"""
Calendar Events
"""
CSS_CLASS_CHOICES = (
('', _('Normal')),
('event-warning', _('Warning')),
('event-info', _('Info')),
('event-success', _('Success')),
('event-inverse', _('Inverse')),
('event-special', _('Special')),
('event-important', _('Important')),
)
title = models.CharField(max_length=255, verbose_name=_('Title'))
url = models.URLField(verbose_name=_('URL'), null=True, blank=True)
- css_class = models.CharField(max_length=20, verbose_name=_('CSS Class'),
+ css_class = models.CharField(blank=True, max_length=20, verbose_name=_('CSS Class'),
? ++++++++++++
choices=CSS_CLASS_CHOICES)
start = models.DateTimeField(verbose_name=_('Start Date'))
end = models.DateTimeField(verbose_name=_('End Date'), null=True,
blank=True)
@property
def start_timestamp(self):
"""
Return end date as timestamp
"""
return datetime_to_timestamp(self.start)
@property
def end_timestamp(self):
"""
Return end date as timestamp
"""
return datetime_to_timestamp(self.end)
def __unicode__(self):
return self.title |
efcafd02930d293f780c4d18910c5a732c552c43 | scheduler.py | scheduler.py | from apscheduler.schedulers.blocking import BlockingScheduler
import logging
import warner
import archiver
import announcer
import flagger
import os
logging.basicConfig()
sched = BlockingScheduler()
@sched.scheduled_job("cron", hour=4)
#@sched.scheduled_job("cron", hour="*", minute="*/10") # for testing
def destalinate_job():
print("Destalinating")
if "SB_TOKEN" not in os.environ or "API_TOKEN" not in os.environ:
print("ERR: Missing at least one Slack environment variable.")
else:
scheduled_warner = warner.Warner()
scheduled_archiver = archiver.Archiver()
scheduled_announcer = announcer.Announcer()
scheduled_flagger = flagger.Flagger()
print("Warning")
scheduled_warner.warn()
print("Archiving")
scheduled_archiver.archive()
print("Announcing")
scheduled_announcer.announce()
print("Flagging")
scheduled_flagger.flag()
print("OK: destalinated")
print("END: destalinate_job")
sched.start()
| from apscheduler.schedulers.blocking import BlockingScheduler
import logging
import warner
import archiver
import announcer
import flagger
import os
# When testing changes, set the "TEST_SCHEDULE" envvar to run more often
if os.getenv("TEST_SCHEDULE"):
schedule_kwargs = {"hour": "*", "minute": "*/10"}
else:
schedule_kwargs = {"hour": 4}
logging.basicConfig()
sched = BlockingScheduler()
@sched.scheduled_job("cron", **schedule_kwargs)
def destalinate_job():
print("Destalinating")
if "SB_TOKEN" not in os.environ or "API_TOKEN" not in os.environ:
print("ERR: Missing at least one Slack environment variable.")
else:
scheduled_warner = warner.Warner()
scheduled_archiver = archiver.Archiver()
scheduled_announcer = announcer.Announcer()
scheduled_flagger = flagger.Flagger()
print("Warning")
scheduled_warner.warn()
print("Archiving")
scheduled_archiver.archive()
print("Announcing")
scheduled_announcer.announce()
print("Flagging")
scheduled_flagger.flag()
print("OK: destalinated")
print("END: destalinate_job")
sched.start()
| Switch to a test schedule based on the environment | Switch to a test schedule based on the environment
Switching an environment variable and kicking the `clock` process feels
like a neater solution than commenting out one line, uncommenting
another, and redeploying.
| Python | apache-2.0 | rossrader/destalinator | from apscheduler.schedulers.blocking import BlockingScheduler
import logging
import warner
import archiver
import announcer
import flagger
import os
+
+ # When testing changes, set the "TEST_SCHEDULE" envvar to run more often
+ if os.getenv("TEST_SCHEDULE"):
+ schedule_kwargs = {"hour": "*", "minute": "*/10"}
+ else:
+ schedule_kwargs = {"hour": 4}
+
logging.basicConfig()
sched = BlockingScheduler()
- @sched.scheduled_job("cron", hour=4)
+ @sched.scheduled_job("cron", **schedule_kwargs)
- #@sched.scheduled_job("cron", hour="*", minute="*/10") # for testing
def destalinate_job():
print("Destalinating")
if "SB_TOKEN" not in os.environ or "API_TOKEN" not in os.environ:
print("ERR: Missing at least one Slack environment variable.")
else:
scheduled_warner = warner.Warner()
scheduled_archiver = archiver.Archiver()
scheduled_announcer = announcer.Announcer()
scheduled_flagger = flagger.Flagger()
print("Warning")
scheduled_warner.warn()
print("Archiving")
scheduled_archiver.archive()
print("Announcing")
scheduled_announcer.announce()
print("Flagging")
scheduled_flagger.flag()
print("OK: destalinated")
print("END: destalinate_job")
sched.start()
| Switch to a test schedule based on the environment | ## Code Before:
from apscheduler.schedulers.blocking import BlockingScheduler
import logging
import warner
import archiver
import announcer
import flagger
import os
logging.basicConfig()
sched = BlockingScheduler()
@sched.scheduled_job("cron", hour=4)
#@sched.scheduled_job("cron", hour="*", minute="*/10") # for testing
def destalinate_job():
print("Destalinating")
if "SB_TOKEN" not in os.environ or "API_TOKEN" not in os.environ:
print("ERR: Missing at least one Slack environment variable.")
else:
scheduled_warner = warner.Warner()
scheduled_archiver = archiver.Archiver()
scheduled_announcer = announcer.Announcer()
scheduled_flagger = flagger.Flagger()
print("Warning")
scheduled_warner.warn()
print("Archiving")
scheduled_archiver.archive()
print("Announcing")
scheduled_announcer.announce()
print("Flagging")
scheduled_flagger.flag()
print("OK: destalinated")
print("END: destalinate_job")
sched.start()
## Instruction:
Switch to a test schedule based on the environment
## Code After:
from apscheduler.schedulers.blocking import BlockingScheduler
import logging
import warner
import archiver
import announcer
import flagger
import os
# When testing changes, set the "TEST_SCHEDULE" envvar to run more often
if os.getenv("TEST_SCHEDULE"):
schedule_kwargs = {"hour": "*", "minute": "*/10"}
else:
schedule_kwargs = {"hour": 4}
logging.basicConfig()
sched = BlockingScheduler()
@sched.scheduled_job("cron", **schedule_kwargs)
def destalinate_job():
print("Destalinating")
if "SB_TOKEN" not in os.environ or "API_TOKEN" not in os.environ:
print("ERR: Missing at least one Slack environment variable.")
else:
scheduled_warner = warner.Warner()
scheduled_archiver = archiver.Archiver()
scheduled_announcer = announcer.Announcer()
scheduled_flagger = flagger.Flagger()
print("Warning")
scheduled_warner.warn()
print("Archiving")
scheduled_archiver.archive()
print("Announcing")
scheduled_announcer.announce()
print("Flagging")
scheduled_flagger.flag()
print("OK: destalinated")
print("END: destalinate_job")
sched.start()
| from apscheduler.schedulers.blocking import BlockingScheduler
import logging
import warner
import archiver
import announcer
import flagger
import os
+
+ # When testing changes, set the "TEST_SCHEDULE" envvar to run more often
+ if os.getenv("TEST_SCHEDULE"):
+ schedule_kwargs = {"hour": "*", "minute": "*/10"}
+ else:
+ schedule_kwargs = {"hour": 4}
+
logging.basicConfig()
sched = BlockingScheduler()
- @sched.scheduled_job("cron", hour=4)
? ^ ^^
+ @sched.scheduled_job("cron", **schedule_kwargs)
? ++++ ^^ ++++++ ^^
- #@sched.scheduled_job("cron", hour="*", minute="*/10") # for testing
def destalinate_job():
print("Destalinating")
if "SB_TOKEN" not in os.environ or "API_TOKEN" not in os.environ:
print("ERR: Missing at least one Slack environment variable.")
else:
scheduled_warner = warner.Warner()
scheduled_archiver = archiver.Archiver()
scheduled_announcer = announcer.Announcer()
scheduled_flagger = flagger.Flagger()
print("Warning")
scheduled_warner.warn()
print("Archiving")
scheduled_archiver.archive()
print("Announcing")
scheduled_announcer.announce()
print("Flagging")
scheduled_flagger.flag()
print("OK: destalinated")
print("END: destalinate_job")
sched.start() |
b1a91fc4e843197a12be653aa60d5cdf32f31423 | tests/test_recursion.py | tests/test_recursion.py | from tests import utils
def test_recursion():
uwhois = utils.create_uwhois()
expected = 'whois.markmonitor.com'
transcript = utils.read_transcript('google.com.txt')
# Make sure there's nothing wrong with the WHOIS transcript.
assert transcript.count(expected) == 1
assert uwhois.get_registrar_whois_server('com', transcript) == expected
| from tests import utils
def test_recursion():
uwhois = utils.create_uwhois()
expected = 'whois.markmonitor.com'
transcript = utils.read_transcript('google.com.txt')
# Make sure there's nothing wrong with the WHOIS transcript.
assert transcript.count(expected) == 1
server, port = uwhois.get_whois_server('com')
pattern = uwhois.get_recursion_pattern(server)
assert uwhois.get_registrar_whois_server(pattern, transcript) == expected
| Fix test for the fork | Fix test for the fork
| Python | mit | Rafiot/uwhoisd,Rafiot/uwhoisd | from tests import utils
def test_recursion():
uwhois = utils.create_uwhois()
expected = 'whois.markmonitor.com'
transcript = utils.read_transcript('google.com.txt')
# Make sure there's nothing wrong with the WHOIS transcript.
assert transcript.count(expected) == 1
+ server, port = uwhois.get_whois_server('com')
+ pattern = uwhois.get_recursion_pattern(server)
- assert uwhois.get_registrar_whois_server('com', transcript) == expected
+ assert uwhois.get_registrar_whois_server(pattern, transcript) == expected
| Fix test for the fork | ## Code Before:
from tests import utils
def test_recursion():
uwhois = utils.create_uwhois()
expected = 'whois.markmonitor.com'
transcript = utils.read_transcript('google.com.txt')
# Make sure there's nothing wrong with the WHOIS transcript.
assert transcript.count(expected) == 1
assert uwhois.get_registrar_whois_server('com', transcript) == expected
## Instruction:
Fix test for the fork
## Code After:
from tests import utils
def test_recursion():
uwhois = utils.create_uwhois()
expected = 'whois.markmonitor.com'
transcript = utils.read_transcript('google.com.txt')
# Make sure there's nothing wrong with the WHOIS transcript.
assert transcript.count(expected) == 1
server, port = uwhois.get_whois_server('com')
pattern = uwhois.get_recursion_pattern(server)
assert uwhois.get_registrar_whois_server(pattern, transcript) == expected
| from tests import utils
def test_recursion():
uwhois = utils.create_uwhois()
expected = 'whois.markmonitor.com'
transcript = utils.read_transcript('google.com.txt')
# Make sure there's nothing wrong with the WHOIS transcript.
assert transcript.count(expected) == 1
+ server, port = uwhois.get_whois_server('com')
+ pattern = uwhois.get_recursion_pattern(server)
- assert uwhois.get_registrar_whois_server('com', transcript) == expected
? ^^^^^
+ assert uwhois.get_registrar_whois_server(pattern, transcript) == expected
? ^^^^^^^
|
b77956a993f7f703626dbc9fc85003d6840b24fe | partner_compassion/models/partner_bank_compassion.py | partner_compassion/models/partner_bank_compassion.py |
from odoo import api, models, _
# pylint: disable=C8107
class ResPartnerBank(models.Model):
""" This class upgrade the partners.bank to match Compassion needs.
"""
_inherit = 'res.partner.bank'
@api.model
def create(self, data):
"""Override function to notify creation in a message
"""
result = super(ResPartnerBank, self).create(data)
part = result.partner_id
part.message_post(_("<b>Account number: </b>" + result.acc_number),
_("New account created"), 'comment')
return result
@api.multi
def unlink(self):
"""Override function to notify delte in a message
"""
for account in self:
part = account.partner_id
part.message_post(_("<b>Account number: </b>" +
account.acc_number),
_("Account deleted"), 'comment')
result = super(ResPartnerBank, self).unlink()
return result
|
from odoo import api, models, _
# pylint: disable=C8107
class ResPartnerBank(models.Model):
""" This class upgrade the partners.bank to match Compassion needs.
"""
_inherit = 'res.partner.bank'
@api.model
def create(self, data):
"""Override function to notify creation in a message
"""
result = super(ResPartnerBank, self).create(data)
part = result.partner_id
if part:
part.message_post(_("<b>Account number: </b>" + result.acc_number),
_("New account created"), 'comment')
return result
@api.multi
def unlink(self):
"""Override function to notify delte in a message
"""
for account in self:
part = account.partner_id
part.message_post(_("<b>Account number: </b>" +
account.acc_number),
_("Account deleted"), 'comment')
result = super(ResPartnerBank, self).unlink()
return result
| FIX only post message if a partner is existent | FIX only post message if a partner is existent
| Python | agpl-3.0 | CompassionCH/compassion-switzerland,eicher31/compassion-switzerland,eicher31/compassion-switzerland,eicher31/compassion-switzerland,ecino/compassion-switzerland,ecino/compassion-switzerland,CompassionCH/compassion-switzerland,ecino/compassion-switzerland,CompassionCH/compassion-switzerland |
from odoo import api, models, _
# pylint: disable=C8107
class ResPartnerBank(models.Model):
""" This class upgrade the partners.bank to match Compassion needs.
"""
_inherit = 'res.partner.bank'
@api.model
def create(self, data):
"""Override function to notify creation in a message
"""
result = super(ResPartnerBank, self).create(data)
part = result.partner_id
+ if part:
- part.message_post(_("<b>Account number: </b>" + result.acc_number),
+ part.message_post(_("<b>Account number: </b>" + result.acc_number),
- _("New account created"), 'comment')
+ _("New account created"), 'comment')
return result
@api.multi
def unlink(self):
"""Override function to notify delte in a message
"""
for account in self:
part = account.partner_id
part.message_post(_("<b>Account number: </b>" +
account.acc_number),
_("Account deleted"), 'comment')
result = super(ResPartnerBank, self).unlink()
return result
| FIX only post message if a partner is existent | ## Code Before:
from odoo import api, models, _
# pylint: disable=C8107
class ResPartnerBank(models.Model):
""" This class upgrade the partners.bank to match Compassion needs.
"""
_inherit = 'res.partner.bank'
@api.model
def create(self, data):
"""Override function to notify creation in a message
"""
result = super(ResPartnerBank, self).create(data)
part = result.partner_id
part.message_post(_("<b>Account number: </b>" + result.acc_number),
_("New account created"), 'comment')
return result
@api.multi
def unlink(self):
"""Override function to notify delte in a message
"""
for account in self:
part = account.partner_id
part.message_post(_("<b>Account number: </b>" +
account.acc_number),
_("Account deleted"), 'comment')
result = super(ResPartnerBank, self).unlink()
return result
## Instruction:
FIX only post message if a partner is existent
## Code After:
from odoo import api, models, _
# pylint: disable=C8107
class ResPartnerBank(models.Model):
""" This class upgrade the partners.bank to match Compassion needs.
"""
_inherit = 'res.partner.bank'
@api.model
def create(self, data):
"""Override function to notify creation in a message
"""
result = super(ResPartnerBank, self).create(data)
part = result.partner_id
if part:
part.message_post(_("<b>Account number: </b>" + result.acc_number),
_("New account created"), 'comment')
return result
@api.multi
def unlink(self):
"""Override function to notify delte in a message
"""
for account in self:
part = account.partner_id
part.message_post(_("<b>Account number: </b>" +
account.acc_number),
_("Account deleted"), 'comment')
result = super(ResPartnerBank, self).unlink()
return result
|
from odoo import api, models, _
# pylint: disable=C8107
class ResPartnerBank(models.Model):
""" This class upgrade the partners.bank to match Compassion needs.
"""
_inherit = 'res.partner.bank'
@api.model
def create(self, data):
"""Override function to notify creation in a message
"""
result = super(ResPartnerBank, self).create(data)
part = result.partner_id
+ if part:
- part.message_post(_("<b>Account number: </b>" + result.acc_number),
+ part.message_post(_("<b>Account number: </b>" + result.acc_number),
? ++++
- _("New account created"), 'comment')
+ _("New account created"), 'comment')
? ++++
return result
@api.multi
def unlink(self):
"""Override function to notify delte in a message
"""
for account in self:
part = account.partner_id
part.message_post(_("<b>Account number: </b>" +
account.acc_number),
_("Account deleted"), 'comment')
result = super(ResPartnerBank, self).unlink()
return result |
d8ae3ab5f6baf0ee965548f8df37e1a4b331a8aa | install_all_addons.py | install_all_addons.py | import bpy
# install and activate `emboss plane`
bpy.ops.wm.addon_install(filepath='emboss_plane.py')
bpy.ops.wm.addon_enable(module='emboss_plane')
# install and activate `name plate`
bpy.ops.wm.addon_install(filepath='name_plate.py')
bpy.ops.wm.addon_enable(module='name_plate')
# save user preferences
bpy.ops.wm.save_userpref()
| import bpy
import os
# get current directory
current_dir = os.getcwd()
# install and activate `emboss plane`
emboss_plane_filepath = os.path.join(current_dir, 'emboss_plane.py')
bpy.ops.wm.addon_install(filepath=emboss_plane_filepath)
bpy.ops.wm.addon_enable(module='emboss_plane')
# install and activate `name plate`
name_plate_filepath = os.path.join(current_dir, 'name_plate.py')
bpy.ops.wm.addon_install(filepath=name_plate_filepath)
bpy.ops.wm.addon_enable(module='name_plate')
# save user preferences
bpy.ops.wm.save_userpref()
| Update install script with full file paths | Update install script with full file paths
This is needed to make the script run on Windows. The `os` package is
used to make sure it will run under any OS.
| Python | mit | TactileUniverse/3D-Printed-Galaxy-Software | import bpy
+ import os
+
+ # get current directory
+ current_dir = os.getcwd()
# install and activate `emboss plane`
+ emboss_plane_filepath = os.path.join(current_dir, 'emboss_plane.py')
- bpy.ops.wm.addon_install(filepath='emboss_plane.py')
+ bpy.ops.wm.addon_install(filepath=emboss_plane_filepath)
bpy.ops.wm.addon_enable(module='emboss_plane')
# install and activate `name plate`
+ name_plate_filepath = os.path.join(current_dir, 'name_plate.py')
- bpy.ops.wm.addon_install(filepath='name_plate.py')
+ bpy.ops.wm.addon_install(filepath=name_plate_filepath)
bpy.ops.wm.addon_enable(module='name_plate')
# save user preferences
bpy.ops.wm.save_userpref()
| Update install script with full file paths | ## Code Before:
import bpy
# install and activate `emboss plane`
bpy.ops.wm.addon_install(filepath='emboss_plane.py')
bpy.ops.wm.addon_enable(module='emboss_plane')
# install and activate `name plate`
bpy.ops.wm.addon_install(filepath='name_plate.py')
bpy.ops.wm.addon_enable(module='name_plate')
# save user preferences
bpy.ops.wm.save_userpref()
## Instruction:
Update install script with full file paths
## Code After:
import bpy
import os
# get current directory
current_dir = os.getcwd()
# install and activate `emboss plane`
emboss_plane_filepath = os.path.join(current_dir, 'emboss_plane.py')
bpy.ops.wm.addon_install(filepath=emboss_plane_filepath)
bpy.ops.wm.addon_enable(module='emboss_plane')
# install and activate `name plate`
name_plate_filepath = os.path.join(current_dir, 'name_plate.py')
bpy.ops.wm.addon_install(filepath=name_plate_filepath)
bpy.ops.wm.addon_enable(module='name_plate')
# save user preferences
bpy.ops.wm.save_userpref()
| import bpy
+ import os
+
+ # get current directory
+ current_dir = os.getcwd()
# install and activate `emboss plane`
+ emboss_plane_filepath = os.path.join(current_dir, 'emboss_plane.py')
- bpy.ops.wm.addon_install(filepath='emboss_plane.py')
? - ^ ^^
+ bpy.ops.wm.addon_install(filepath=emboss_plane_filepath)
? ^^^^^ ^^^
bpy.ops.wm.addon_enable(module='emboss_plane')
# install and activate `name plate`
+ name_plate_filepath = os.path.join(current_dir, 'name_plate.py')
- bpy.ops.wm.addon_install(filepath='name_plate.py')
? - ^ ^^
+ bpy.ops.wm.addon_install(filepath=name_plate_filepath)
? ^^^^^ ^^^
bpy.ops.wm.addon_enable(module='name_plate')
# save user preferences
bpy.ops.wm.save_userpref() |
d3a0c400e50d34b9829b05d26eef5eac878aa091 | enhanced_cbv/views/list.py | enhanced_cbv/views/list.py | from django.core.exceptions import ImproperlyConfigured
from django.views.generic import ListView
class ListFilteredMixin(object):
"""
Mixin that adds support for django-filter
"""
filter_set = None
def get_filter_set(self):
if self.filter_set:
return self.filter_set
else:
raise ImproperlyConfigured(
"ListFilterMixin requires either a definition of "
"'filter_set' or an implementation of 'get_filter()'")
def get_base_queryset(self):
"""
We can decided to either alter the queryset before or after applying the
FilterSet
"""
return super(ListFilteredMixin, self).get_queryset()
def get_constructed_filter(self):
# We need to store the instantiated FilterSet cause we use it in
# get_queryset and in get_context_data
if getattr(self, 'constructed_filter', None):
return self.constructed_filter
else:
f = self.get_filter_set()(self.request.GET,
queryset=self.get_base_queryset())
self.constructed_filter = f
return f
def get_queryset(self):
return self.get_constructed_filter().qs
def get_context_data(self, **kwargs):
kwargs.update({'filter': self.get_constructed_filter()})
return super(ListFilteredMixin, self).get_context_data(**kwargs)
class ListFilteredView(ListFilteredMixin, ListView):
"""
A list view that can be filtered by django-filter
"""
| from django.core.exceptions import ImproperlyConfigured
from django.views.generic import ListView
class ListFilteredMixin(object):
"""
Mixin that adds support for django-filter
"""
filter_set = None
def get_filter_set(self):
if self.filter_set:
return self.filter_set
else:
raise ImproperlyConfigured(
"ListFilterMixin requires either a definition of "
"'filter_set' or an implementation of 'get_filter()'")
def get_filter_set_kwargs(self):
"""
Returns the keyword arguments for instanciating the filterset.
"""
return {
'data': self.request.GET,
'queryset': self.get_base_queryset(),
}
def get_base_queryset(self):
"""
We can decided to either alter the queryset before or after applying the
FilterSet
"""
return super(ListFilteredMixin, self).get_queryset()
def get_constructed_filter(self):
# We need to store the instantiated FilterSet cause we use it in
# get_queryset and in get_context_data
if getattr(self, 'constructed_filter', None):
return self.constructed_filter
else:
f = self.get_filter_set()(**self.get_filter_set_kwargs())
self.constructed_filter = f
return f
def get_queryset(self):
return self.get_constructed_filter().qs
def get_context_data(self, **kwargs):
kwargs.update({'filter': self.get_constructed_filter()})
return super(ListFilteredMixin, self).get_context_data(**kwargs)
class ListFilteredView(ListFilteredMixin, ListView):
"""
A list view that can be filtered by django-filter
"""
| Add get_filter_set_kwargs for instanciating FilterSet with additional arguments | Add get_filter_set_kwargs for instanciating FilterSet with additional arguments | Python | bsd-3-clause | rasca/django-enhanced-cbv,matuu/django-enhanced-cbv,matuu/django-enhanced-cbv,rasca/django-enhanced-cbv | from django.core.exceptions import ImproperlyConfigured
from django.views.generic import ListView
class ListFilteredMixin(object):
"""
Mixin that adds support for django-filter
"""
filter_set = None
def get_filter_set(self):
if self.filter_set:
return self.filter_set
else:
raise ImproperlyConfigured(
"ListFilterMixin requires either a definition of "
"'filter_set' or an implementation of 'get_filter()'")
+ def get_filter_set_kwargs(self):
+ """
+ Returns the keyword arguments for instanciating the filterset.
+ """
+ return {
+ 'data': self.request.GET,
+ 'queryset': self.get_base_queryset(),
+ }
+
def get_base_queryset(self):
"""
We can decided to either alter the queryset before or after applying the
FilterSet
"""
return super(ListFilteredMixin, self).get_queryset()
def get_constructed_filter(self):
# We need to store the instantiated FilterSet cause we use it in
# get_queryset and in get_context_data
if getattr(self, 'constructed_filter', None):
return self.constructed_filter
else:
+ f = self.get_filter_set()(**self.get_filter_set_kwargs())
- f = self.get_filter_set()(self.request.GET,
- queryset=self.get_base_queryset())
self.constructed_filter = f
return f
def get_queryset(self):
return self.get_constructed_filter().qs
def get_context_data(self, **kwargs):
kwargs.update({'filter': self.get_constructed_filter()})
return super(ListFilteredMixin, self).get_context_data(**kwargs)
class ListFilteredView(ListFilteredMixin, ListView):
"""
A list view that can be filtered by django-filter
"""
| Add get_filter_set_kwargs for instanciating FilterSet with additional arguments | ## Code Before:
from django.core.exceptions import ImproperlyConfigured
from django.views.generic import ListView
class ListFilteredMixin(object):
"""
Mixin that adds support for django-filter
"""
filter_set = None
def get_filter_set(self):
if self.filter_set:
return self.filter_set
else:
raise ImproperlyConfigured(
"ListFilterMixin requires either a definition of "
"'filter_set' or an implementation of 'get_filter()'")
def get_base_queryset(self):
"""
We can decided to either alter the queryset before or after applying the
FilterSet
"""
return super(ListFilteredMixin, self).get_queryset()
def get_constructed_filter(self):
# We need to store the instantiated FilterSet cause we use it in
# get_queryset and in get_context_data
if getattr(self, 'constructed_filter', None):
return self.constructed_filter
else:
f = self.get_filter_set()(self.request.GET,
queryset=self.get_base_queryset())
self.constructed_filter = f
return f
def get_queryset(self):
return self.get_constructed_filter().qs
def get_context_data(self, **kwargs):
kwargs.update({'filter': self.get_constructed_filter()})
return super(ListFilteredMixin, self).get_context_data(**kwargs)
class ListFilteredView(ListFilteredMixin, ListView):
"""
A list view that can be filtered by django-filter
"""
## Instruction:
Add get_filter_set_kwargs for instanciating FilterSet with additional arguments
## Code After:
from django.core.exceptions import ImproperlyConfigured
from django.views.generic import ListView
class ListFilteredMixin(object):
"""
Mixin that adds support for django-filter
"""
filter_set = None
def get_filter_set(self):
if self.filter_set:
return self.filter_set
else:
raise ImproperlyConfigured(
"ListFilterMixin requires either a definition of "
"'filter_set' or an implementation of 'get_filter()'")
def get_filter_set_kwargs(self):
"""
Returns the keyword arguments for instanciating the filterset.
"""
return {
'data': self.request.GET,
'queryset': self.get_base_queryset(),
}
def get_base_queryset(self):
"""
We can decided to either alter the queryset before or after applying the
FilterSet
"""
return super(ListFilteredMixin, self).get_queryset()
def get_constructed_filter(self):
# We need to store the instantiated FilterSet cause we use it in
# get_queryset and in get_context_data
if getattr(self, 'constructed_filter', None):
return self.constructed_filter
else:
f = self.get_filter_set()(**self.get_filter_set_kwargs())
self.constructed_filter = f
return f
def get_queryset(self):
return self.get_constructed_filter().qs
def get_context_data(self, **kwargs):
kwargs.update({'filter': self.get_constructed_filter()})
return super(ListFilteredMixin, self).get_context_data(**kwargs)
class ListFilteredView(ListFilteredMixin, ListView):
"""
A list view that can be filtered by django-filter
"""
| from django.core.exceptions import ImproperlyConfigured
from django.views.generic import ListView
class ListFilteredMixin(object):
"""
Mixin that adds support for django-filter
"""
filter_set = None
def get_filter_set(self):
if self.filter_set:
return self.filter_set
else:
raise ImproperlyConfigured(
"ListFilterMixin requires either a definition of "
"'filter_set' or an implementation of 'get_filter()'")
+ def get_filter_set_kwargs(self):
+ """
+ Returns the keyword arguments for instanciating the filterset.
+ """
+ return {
+ 'data': self.request.GET,
+ 'queryset': self.get_base_queryset(),
+ }
+
def get_base_queryset(self):
"""
We can decided to either alter the queryset before or after applying the
FilterSet
"""
return super(ListFilteredMixin, self).get_queryset()
def get_constructed_filter(self):
# We need to store the instantiated FilterSet cause we use it in
# get_queryset and in get_context_data
if getattr(self, 'constructed_filter', None):
return self.constructed_filter
else:
+ f = self.get_filter_set()(**self.get_filter_set_kwargs())
- f = self.get_filter_set()(self.request.GET,
- queryset=self.get_base_queryset())
self.constructed_filter = f
return f
def get_queryset(self):
return self.get_constructed_filter().qs
def get_context_data(self, **kwargs):
kwargs.update({'filter': self.get_constructed_filter()})
return super(ListFilteredMixin, self).get_context_data(**kwargs)
class ListFilteredView(ListFilteredMixin, ListView):
"""
A list view that can be filtered by django-filter
""" |
130df743b14cf329c09f0c514ec0d6991b21dd45 | examples/mnist-deepautoencoder.py | examples/mnist-deepautoencoder.py |
import matplotlib.pyplot as plt
import theanets
from utils import load_mnist, plot_layers, plot_images
train, valid, _ = load_mnist()
e = theanets.Experiment(
theanets.Autoencoder,
layers=(784, 256, 64, 36, 64, 256, 784),
train_batches=100,
tied_weights=True,
)
e.train(train, valid, optimize='layerwise')
e.train(train, valid)
plot_layers([e.network.get_weights(i) for i in (1, 2, 3)], tied_weights=True)
plt.tight_layout()
plt.show()
valid = valid[:16*16]
plot_images(valid, 121, 'Sample data')
plot_images(e.network.predict(valid), 122, 'Reconstructed data')
plt.tight_layout()
plt.show()
|
import matplotlib.pyplot as plt
import theanets
from utils import load_mnist, plot_layers, plot_images
train, valid, _ = load_mnist()
e = theanets.Experiment(
theanets.Autoencoder,
layers=(784, 256, 64, 36, 64, 256, 784),
train_batches=100,
tied_weights=True,
)
e.train(train, valid, optimize='layerwise', patience=1, min_improvement=0.1)
e.train(train, valid)
plot_layers([e.network.get_weights(i) for i in (1, 2, 3)], tied_weights=True)
plt.tight_layout()
plt.show()
valid = valid[:16*16]
plot_images(valid, 121, 'Sample data')
plot_images(e.network.predict(valid), 122, 'Reconstructed data')
plt.tight_layout()
plt.show()
| Decrease patience for each layerwise trainer. | Decrease patience for each layerwise trainer.
| Python | mit | chrinide/theanets,lmjohns3/theanets,devdoer/theanets |
import matplotlib.pyplot as plt
import theanets
from utils import load_mnist, plot_layers, plot_images
train, valid, _ = load_mnist()
e = theanets.Experiment(
theanets.Autoencoder,
layers=(784, 256, 64, 36, 64, 256, 784),
train_batches=100,
tied_weights=True,
)
- e.train(train, valid, optimize='layerwise')
+ e.train(train, valid, optimize='layerwise', patience=1, min_improvement=0.1)
e.train(train, valid)
plot_layers([e.network.get_weights(i) for i in (1, 2, 3)], tied_weights=True)
plt.tight_layout()
plt.show()
valid = valid[:16*16]
plot_images(valid, 121, 'Sample data')
plot_images(e.network.predict(valid), 122, 'Reconstructed data')
plt.tight_layout()
plt.show()
| Decrease patience for each layerwise trainer. | ## Code Before:
import matplotlib.pyplot as plt
import theanets
from utils import load_mnist, plot_layers, plot_images
train, valid, _ = load_mnist()
e = theanets.Experiment(
theanets.Autoencoder,
layers=(784, 256, 64, 36, 64, 256, 784),
train_batches=100,
tied_weights=True,
)
e.train(train, valid, optimize='layerwise')
e.train(train, valid)
plot_layers([e.network.get_weights(i) for i in (1, 2, 3)], tied_weights=True)
plt.tight_layout()
plt.show()
valid = valid[:16*16]
plot_images(valid, 121, 'Sample data')
plot_images(e.network.predict(valid), 122, 'Reconstructed data')
plt.tight_layout()
plt.show()
## Instruction:
Decrease patience for each layerwise trainer.
## Code After:
import matplotlib.pyplot as plt
import theanets
from utils import load_mnist, plot_layers, plot_images
train, valid, _ = load_mnist()
e = theanets.Experiment(
theanets.Autoencoder,
layers=(784, 256, 64, 36, 64, 256, 784),
train_batches=100,
tied_weights=True,
)
e.train(train, valid, optimize='layerwise', patience=1, min_improvement=0.1)
e.train(train, valid)
plot_layers([e.network.get_weights(i) for i in (1, 2, 3)], tied_weights=True)
plt.tight_layout()
plt.show()
valid = valid[:16*16]
plot_images(valid, 121, 'Sample data')
plot_images(e.network.predict(valid), 122, 'Reconstructed data')
plt.tight_layout()
plt.show()
|
import matplotlib.pyplot as plt
import theanets
from utils import load_mnist, plot_layers, plot_images
train, valid, _ = load_mnist()
e = theanets.Experiment(
theanets.Autoencoder,
layers=(784, 256, 64, 36, 64, 256, 784),
train_batches=100,
tied_weights=True,
)
- e.train(train, valid, optimize='layerwise')
+ e.train(train, valid, optimize='layerwise', patience=1, min_improvement=0.1)
e.train(train, valid)
plot_layers([e.network.get_weights(i) for i in (1, 2, 3)], tied_weights=True)
plt.tight_layout()
plt.show()
valid = valid[:16*16]
plot_images(valid, 121, 'Sample data')
plot_images(e.network.predict(valid), 122, 'Reconstructed data')
plt.tight_layout()
plt.show() |
3d1dba15097ac8b746c138b75fe1763aa4b8ac12 | footballseason/urls.py | footballseason/urls.py | from django.conf.urls import url
from . import views
urlpatterns = [
# eg: /footballseason/
url(r'^$', views.index, name='index'),
# eg: /footballseason/3
url(r'^(?P<week_id>[0-9]+)/$', views.display, name='display'),
# eg: /footballseason/3/submit
url(r'^(?P<week_id>[0-9]+)/submit$', views.submit, name='submit'),
# eg: /footballseason/3/vote
url(r'^(?P<week_id>[0-9]+)/vote$', views.vote, name='vote'),
# eg: /footballseason/update
url(r'^update$', views.update, name='update'),
# eg: /footballseason/records
url(r'^records$', views.records_default, name='records_default'),
# eg: /footballseason/records/2015
url(r'^records/(?P<season>[0-9]+)$', views.records_by_season, name='records_by_season'),
# eg: /footballseason/records/2015/3
url(r'^records/(?P<season>[0-9]+)/(?P<week>[0-9]+)$', views.records_by_week, name='records_by_week'),
]
| from django.conf.urls import url
from . import views
urlpatterns = [
# eg: /footballseason/
url(r'^$', views.index, name='index'),
# eg: /footballseason/3/
url(r'^(?P<week_id>[0-9]+)/$', views.display, name='display'),
# eg: /footballseason/3/submit/
url(r'^(?P<week_id>[0-9]+)/submit/$', views.submit, name='submit'),
# eg: /footballseason/3/vote/
url(r'^(?P<week_id>[0-9]+)/vote/$', views.vote, name='vote'),
# eg: /footballseason/update/
url(r'^update/$', views.update, name='update'),
# eg: /footballseason/records/
url(r'^records/$', views.records_default, name='records_default'),
# eg: /footballseason/records/2015/
url(r'^records/(?P<season>[0-9]+)/$', views.records_by_season, name='records_by_season'),
# eg: /footballseason/records/2015/3/
url(r'^records/(?P<season>[0-9]+)/(?P<week>[0-9]+)/$', views.records_by_week, name='records_by_week'),
]
| Fix URLs so APPEND_SLASH works | Fix URLs so APPEND_SLASH works
| Python | mit | mkokotovich/footballpicks,mkokotovich/footballpicks,mkokotovich/footballpicks,mkokotovich/footballpicks | from django.conf.urls import url
from . import views
urlpatterns = [
# eg: /footballseason/
url(r'^$', views.index, name='index'),
- # eg: /footballseason/3
+ # eg: /footballseason/3/
url(r'^(?P<week_id>[0-9]+)/$', views.display, name='display'),
- # eg: /footballseason/3/submit
+ # eg: /footballseason/3/submit/
- url(r'^(?P<week_id>[0-9]+)/submit$', views.submit, name='submit'),
+ url(r'^(?P<week_id>[0-9]+)/submit/$', views.submit, name='submit'),
- # eg: /footballseason/3/vote
+ # eg: /footballseason/3/vote/
- url(r'^(?P<week_id>[0-9]+)/vote$', views.vote, name='vote'),
+ url(r'^(?P<week_id>[0-9]+)/vote/$', views.vote, name='vote'),
- # eg: /footballseason/update
+ # eg: /footballseason/update/
- url(r'^update$', views.update, name='update'),
+ url(r'^update/$', views.update, name='update'),
- # eg: /footballseason/records
+ # eg: /footballseason/records/
- url(r'^records$', views.records_default, name='records_default'),
+ url(r'^records/$', views.records_default, name='records_default'),
- # eg: /footballseason/records/2015
+ # eg: /footballseason/records/2015/
- url(r'^records/(?P<season>[0-9]+)$', views.records_by_season, name='records_by_season'),
+ url(r'^records/(?P<season>[0-9]+)/$', views.records_by_season, name='records_by_season'),
- # eg: /footballseason/records/2015/3
+ # eg: /footballseason/records/2015/3/
- url(r'^records/(?P<season>[0-9]+)/(?P<week>[0-9]+)$', views.records_by_week, name='records_by_week'),
+ url(r'^records/(?P<season>[0-9]+)/(?P<week>[0-9]+)/$', views.records_by_week, name='records_by_week'),
]
| Fix URLs so APPEND_SLASH works | ## Code Before:
from django.conf.urls import url
from . import views
urlpatterns = [
# eg: /footballseason/
url(r'^$', views.index, name='index'),
# eg: /footballseason/3
url(r'^(?P<week_id>[0-9]+)/$', views.display, name='display'),
# eg: /footballseason/3/submit
url(r'^(?P<week_id>[0-9]+)/submit$', views.submit, name='submit'),
# eg: /footballseason/3/vote
url(r'^(?P<week_id>[0-9]+)/vote$', views.vote, name='vote'),
# eg: /footballseason/update
url(r'^update$', views.update, name='update'),
# eg: /footballseason/records
url(r'^records$', views.records_default, name='records_default'),
# eg: /footballseason/records/2015
url(r'^records/(?P<season>[0-9]+)$', views.records_by_season, name='records_by_season'),
# eg: /footballseason/records/2015/3
url(r'^records/(?P<season>[0-9]+)/(?P<week>[0-9]+)$', views.records_by_week, name='records_by_week'),
]
## Instruction:
Fix URLs so APPEND_SLASH works
## Code After:
from django.conf.urls import url
from . import views
urlpatterns = [
# eg: /footballseason/
url(r'^$', views.index, name='index'),
# eg: /footballseason/3/
url(r'^(?P<week_id>[0-9]+)/$', views.display, name='display'),
# eg: /footballseason/3/submit/
url(r'^(?P<week_id>[0-9]+)/submit/$', views.submit, name='submit'),
# eg: /footballseason/3/vote/
url(r'^(?P<week_id>[0-9]+)/vote/$', views.vote, name='vote'),
# eg: /footballseason/update/
url(r'^update/$', views.update, name='update'),
# eg: /footballseason/records/
url(r'^records/$', views.records_default, name='records_default'),
# eg: /footballseason/records/2015/
url(r'^records/(?P<season>[0-9]+)/$', views.records_by_season, name='records_by_season'),
# eg: /footballseason/records/2015/3/
url(r'^records/(?P<season>[0-9]+)/(?P<week>[0-9]+)/$', views.records_by_week, name='records_by_week'),
]
| from django.conf.urls import url
from . import views
urlpatterns = [
# eg: /footballseason/
url(r'^$', views.index, name='index'),
- # eg: /footballseason/3
+ # eg: /footballseason/3/
? +
url(r'^(?P<week_id>[0-9]+)/$', views.display, name='display'),
- # eg: /footballseason/3/submit
+ # eg: /footballseason/3/submit/
? +
- url(r'^(?P<week_id>[0-9]+)/submit$', views.submit, name='submit'),
+ url(r'^(?P<week_id>[0-9]+)/submit/$', views.submit, name='submit'),
? +
- # eg: /footballseason/3/vote
+ # eg: /footballseason/3/vote/
? +
- url(r'^(?P<week_id>[0-9]+)/vote$', views.vote, name='vote'),
+ url(r'^(?P<week_id>[0-9]+)/vote/$', views.vote, name='vote'),
? +
- # eg: /footballseason/update
+ # eg: /footballseason/update/
? +
- url(r'^update$', views.update, name='update'),
+ url(r'^update/$', views.update, name='update'),
? +
- # eg: /footballseason/records
+ # eg: /footballseason/records/
? +
- url(r'^records$', views.records_default, name='records_default'),
+ url(r'^records/$', views.records_default, name='records_default'),
? +
- # eg: /footballseason/records/2015
+ # eg: /footballseason/records/2015/
? +
- url(r'^records/(?P<season>[0-9]+)$', views.records_by_season, name='records_by_season'),
+ url(r'^records/(?P<season>[0-9]+)/$', views.records_by_season, name='records_by_season'),
? +
- # eg: /footballseason/records/2015/3
+ # eg: /footballseason/records/2015/3/
? +
- url(r'^records/(?P<season>[0-9]+)/(?P<week>[0-9]+)$', views.records_by_week, name='records_by_week'),
+ url(r'^records/(?P<season>[0-9]+)/(?P<week>[0-9]+)/$', views.records_by_week, name='records_by_week'),
? +
] |
30609236e703123c464c2e3927417ae677f37c4e | nimp/base_commands/__init__.py | nimp/base_commands/__init__.py |
''' Nimp subcommands declarations '''
__all__ = [
'build',
'check',
'commandlet',
'dev',
'download_fileset',
'fileset',
'p4',
'package',
'run',
'run_hook',
'symbol_server',
'update_symbol_server',
'upload',
'upload_fileset',
]
|
''' Nimp subcommands declarations '''
__all__ = [
'build',
'check',
'commandlet',
'dev',
'download_fileset',
'fileset',
'p4',
'package',
'run',
'symbol_server',
'update_symbol_server',
'upload',
'upload_fileset',
]
| Remove run_hook from list of imported commands. | Remove run_hook from list of imported commands.
| Python | mit | dontnod/nimp |
''' Nimp subcommands declarations '''
__all__ = [
'build',
'check',
'commandlet',
'dev',
'download_fileset',
'fileset',
'p4',
'package',
'run',
- 'run_hook',
'symbol_server',
'update_symbol_server',
'upload',
'upload_fileset',
]
| Remove run_hook from list of imported commands. | ## Code Before:
''' Nimp subcommands declarations '''
__all__ = [
'build',
'check',
'commandlet',
'dev',
'download_fileset',
'fileset',
'p4',
'package',
'run',
'run_hook',
'symbol_server',
'update_symbol_server',
'upload',
'upload_fileset',
]
## Instruction:
Remove run_hook from list of imported commands.
## Code After:
''' Nimp subcommands declarations '''
__all__ = [
'build',
'check',
'commandlet',
'dev',
'download_fileset',
'fileset',
'p4',
'package',
'run',
'symbol_server',
'update_symbol_server',
'upload',
'upload_fileset',
]
|
''' Nimp subcommands declarations '''
__all__ = [
'build',
'check',
'commandlet',
'dev',
'download_fileset',
'fileset',
'p4',
'package',
'run',
- 'run_hook',
'symbol_server',
'update_symbol_server',
'upload',
'upload_fileset',
] |
3fed93e1c0c12dd98a1be7e024a4c637c5751549 | src/sentry/tasks/base.py | src/sentry/tasks/base.py |
from celery.task import task
from django_statsd.clients import statsd
from functools import wraps
def instrumented_task(name, queue, stat_suffix=None, **kwargs):
statsd_key = 'tasks.{name}'.format(name=name)
if stat_suffix:
statsd_key += '.{key}'.format(key=stat_suffix)
def wrapped(func):
@wraps(func)
def _wrapped(*args, **kwargs):
with statsd.timer(statsd_key):
return func(*args, **kwargs)
return task(name=name, queue=queue, **kwargs)(func)
return wrapped
|
from celery.task import task
from django_statsd.clients import statsd
from functools import wraps
def instrumented_task(name, queue, stat_suffix=None, **kwargs):
statsd_key = 'jobs.duration.{name}'.format(name=name)
if stat_suffix:
statsd_key += '.{key}'.format(key=stat_suffix)
def wrapped(func):
@wraps(func)
def _wrapped(*args, **kwargs):
with statsd.timer(statsd_key):
return func(*args, **kwargs)
return task(name=name, queue=queue, **kwargs)(func)
return wrapped
| Change tasks key prefix to jobs.duration | Change tasks key prefix to jobs.duration
| Python | bsd-3-clause | gencer/sentry,korealerts1/sentry,JTCunning/sentry,fuziontech/sentry,wujuguang/sentry,jean/sentry,mvaled/sentry,jean/sentry,BuildingLink/sentry,zenefits/sentry,drcapulet/sentry,ewdurbin/sentry,TedaLIEz/sentry,fotinakis/sentry,nicholasserra/sentry,looker/sentry,gencer/sentry,BayanGroup/sentry,BuildingLink/sentry,mvaled/sentry,boneyao/sentry,ewdurbin/sentry,hongliang5623/sentry,1tush/sentry,Natim/sentry,hongliang5623/sentry,TedaLIEz/sentry,pauloschilling/sentry,llonchj/sentry,felixbuenemann/sentry,camilonova/sentry,looker/sentry,ifduyue/sentry,nicholasserra/sentry,kevinastone/sentry,wujuguang/sentry,jean/sentry,JTCunning/sentry,mvaled/sentry,Kryz/sentry,imankulov/sentry,JamesMura/sentry,kevinlondon/sentry,felixbuenemann/sentry,Natim/sentry,songyi199111/sentry,fuziontech/sentry,fotinakis/sentry,mvaled/sentry,gencer/sentry,zenefits/sentry,llonchj/sentry,JamesMura/sentry,ifduyue/sentry,vperron/sentry,boneyao/sentry,beeftornado/sentry,Kryz/sentry,gencer/sentry,alexm92/sentry,mvaled/sentry,wong2/sentry,JackDanger/sentry,JamesMura/sentry,zenefits/sentry,wong2/sentry,fotinakis/sentry,jokey2k/sentry,daevaorn/sentry,pauloschilling/sentry,camilonova/sentry,1tush/sentry,1tush/sentry,gencer/sentry,zenefits/sentry,JTCunning/sentry,kevinastone/sentry,BuildingLink/sentry,fotinakis/sentry,gg7/sentry,jean/sentry,ifduyue/sentry,daevaorn/sentry,ngonzalvez/sentry,hongliang5623/sentry,JackDanger/sentry,nicholasserra/sentry,JamesMura/sentry,mvaled/sentry,llonchj/sentry,JamesMura/sentry,beeftornado/sentry,daevaorn/sentry,wong2/sentry,mitsuhiko/sentry,boneyao/sentry,wujuguang/sentry,songyi199111/sentry,vperron/sentry,vperron/sentry,songyi199111/sentry,beeftornado/sentry,ifduyue/sentry,camilonova/sentry,argonemyth/sentry,mitsuhiko/sentry,ifduyue/sentry,kevinastone/sentry,felixbuenemann/sentry,korealerts1/sentry,gg7/sentry,zenefits/sentry,BuildingLink/sentry,Natim/sentry,imankulov/sentry,Kryz/sentry,fuziontech/sentry,kevinlondon/sentry,pauloschilling/sentry,JackDanger/sentry,jokey2k/sentry,looker/sentry,alexm92/sentry,ewdurbin/sentry,imankulov/sentry,BuildingLink/sentry,BayanGroup/sentry,korealerts1/sentry,gg7/sentry,BayanGroup/sentry,ngonzalvez/sentry,ngonzalvez/sentry,drcapulet/sentry,daevaorn/sentry,TedaLIEz/sentry,argonemyth/sentry,kevinlondon/sentry,alexm92/sentry,jean/sentry,looker/sentry,drcapulet/sentry,jokey2k/sentry,looker/sentry,argonemyth/sentry |
from celery.task import task
from django_statsd.clients import statsd
from functools import wraps
def instrumented_task(name, queue, stat_suffix=None, **kwargs):
- statsd_key = 'tasks.{name}'.format(name=name)
+ statsd_key = 'jobs.duration.{name}'.format(name=name)
if stat_suffix:
statsd_key += '.{key}'.format(key=stat_suffix)
def wrapped(func):
@wraps(func)
def _wrapped(*args, **kwargs):
with statsd.timer(statsd_key):
return func(*args, **kwargs)
return task(name=name, queue=queue, **kwargs)(func)
return wrapped
| Change tasks key prefix to jobs.duration | ## Code Before:
from celery.task import task
from django_statsd.clients import statsd
from functools import wraps
def instrumented_task(name, queue, stat_suffix=None, **kwargs):
statsd_key = 'tasks.{name}'.format(name=name)
if stat_suffix:
statsd_key += '.{key}'.format(key=stat_suffix)
def wrapped(func):
@wraps(func)
def _wrapped(*args, **kwargs):
with statsd.timer(statsd_key):
return func(*args, **kwargs)
return task(name=name, queue=queue, **kwargs)(func)
return wrapped
## Instruction:
Change tasks key prefix to jobs.duration
## Code After:
from celery.task import task
from django_statsd.clients import statsd
from functools import wraps
def instrumented_task(name, queue, stat_suffix=None, **kwargs):
statsd_key = 'jobs.duration.{name}'.format(name=name)
if stat_suffix:
statsd_key += '.{key}'.format(key=stat_suffix)
def wrapped(func):
@wraps(func)
def _wrapped(*args, **kwargs):
with statsd.timer(statsd_key):
return func(*args, **kwargs)
return task(name=name, queue=queue, **kwargs)(func)
return wrapped
|
from celery.task import task
from django_statsd.clients import statsd
from functools import wraps
def instrumented_task(name, queue, stat_suffix=None, **kwargs):
- statsd_key = 'tasks.{name}'.format(name=name)
? ^^^^
+ statsd_key = 'jobs.duration.{name}'.format(name=name)
? +++++++++ ^^^
if stat_suffix:
statsd_key += '.{key}'.format(key=stat_suffix)
def wrapped(func):
@wraps(func)
def _wrapped(*args, **kwargs):
with statsd.timer(statsd_key):
return func(*args, **kwargs)
return task(name=name, queue=queue, **kwargs)(func)
return wrapped |
22ae3a2e9a236de61c078d234d920a3e6bc62d7b | pylisp/application/lispd/address_tree/ddt_container_node.py | pylisp/application/lispd/address_tree/ddt_container_node.py | '''
Created on 1 jun. 2013
@author: sander
'''
from .container_node import ContainerNode
class DDTContainerNode(ContainerNode):
pass
| '''
Created on 1 jun. 2013
@author: sander
'''
from .container_node import ContainerNode
class DDTContainerNode(ContainerNode):
'''
A ContainerNode that indicates that we are responsible for this part of
the DDT tree.
'''
| Add a bit of docs | Add a bit of docs
| Python | bsd-3-clause | steffann/pylisp | '''
Created on 1 jun. 2013
@author: sander
'''
from .container_node import ContainerNode
class DDTContainerNode(ContainerNode):
- pass
+ '''
+ A ContainerNode that indicates that we are responsible for this part of
+ the DDT tree.
+ '''
| Add a bit of docs | ## Code Before:
'''
Created on 1 jun. 2013
@author: sander
'''
from .container_node import ContainerNode
class DDTContainerNode(ContainerNode):
pass
## Instruction:
Add a bit of docs
## Code After:
'''
Created on 1 jun. 2013
@author: sander
'''
from .container_node import ContainerNode
class DDTContainerNode(ContainerNode):
'''
A ContainerNode that indicates that we are responsible for this part of
the DDT tree.
'''
| '''
Created on 1 jun. 2013
@author: sander
'''
from .container_node import ContainerNode
class DDTContainerNode(ContainerNode):
- pass
+ '''
+ A ContainerNode that indicates that we are responsible for this part of
+ the DDT tree.
+ ''' |
a43634b3c9ec4d47d8ec032e34a197210a6dddb7 | gesture_recognition/gesture_recognizer.py | gesture_recognition/gesture_recognizer.py |
# Import native python libraries
import inspect
import os
import sys
from listener import MyListener
from face_detection import face_detector_gui
import time
# Setup environment variables
src_dir = os.path.dirname(inspect.getfile(inspect.currentframe()))
# Windows and Linux
arch_dir = '../LeapSDK/lib/x64' if sys.maxsize > 2**32 else '../LeapSDK/lib/x86'
# Mac
# arch_dir = os.path.abspath(os.path.join(src_dir, '../LeapSDK/lib')
sys.path.insert(0, os.path.abspath(os.path.join(src_dir, arch_dir)))
sys.path.insert(0, "../LeapSDK/lib")
# Import LeapSDK
import Leap
def run_step():
face = face_detector_gui.FDetector()
face.run()
print face.face_detected
if face.face_detected:
# Create a sample listener and controller
listener = MyListener()
controller = Leap.Controller()
controller.set_policy_flags(Leap.Controller.POLICY_IMAGES)
# Have the sample listener receive events from the controller
controller.add_listener(listener)
t_end = time.time() + 20
while time.time() < t_end:
pass
return
if __name__ == "__main__":
while True:
run_step()
|
# Import native python libraries
import inspect
import os
import sys
from listener import MyListener
from face_detection import face_detector_gui
import time
# Setup environment variables
src_dir = os.path.dirname(inspect.getfile(inspect.currentframe()))
# Windows and Linux
arch_dir = '../LeapSDK/lib/x64' if sys.maxsize > 2**32 else '../LeapSDK/lib/x86'
# Mac
# arch_dir = os.path.abspath(os.path.join(src_dir, '../LeapSDK/lib')
sys.path.insert(0, os.path.abspath(os.path.join(src_dir, arch_dir)))
sys.path.insert(0, "../LeapSDK/lib")
# Import LeapSDK
import Leap
def run_step():
face = face_detector_gui.FDetector()
face.run()
print('Is face detected? ', face.face_detected)
if face.face_detected:
print("Enabled Gesture Recognition")
# Create a sample listener and controller
listener = MyListener()
controller = Leap.Controller()
controller.set_policy_flags(Leap.Controller.POLICY_IMAGES)
# Have the sample listener receive events from the controller
controller.add_listener(listener)
t_end = time.time() + 20
while time.time() < t_end:
pass
print('Disabled Gesture Recognition')
return
if __name__ == "__main__":
while True:
run_step()
| Add some prints to improve verbosity | Add some prints to improve verbosity
| Python | mit | oscarorti/pae-gesture-recognition,oscarorti/pae-gesture-recognition,oscarorti/pae-gesture-recognition,oscarorti/pae-gesture-recognition,oscarorti/pae-gesture-recognition,oscarorti/pae-gesture-recognition,oscarorti/pae-gesture-recognition |
# Import native python libraries
import inspect
import os
import sys
from listener import MyListener
from face_detection import face_detector_gui
import time
# Setup environment variables
src_dir = os.path.dirname(inspect.getfile(inspect.currentframe()))
# Windows and Linux
arch_dir = '../LeapSDK/lib/x64' if sys.maxsize > 2**32 else '../LeapSDK/lib/x86'
# Mac
# arch_dir = os.path.abspath(os.path.join(src_dir, '../LeapSDK/lib')
sys.path.insert(0, os.path.abspath(os.path.join(src_dir, arch_dir)))
sys.path.insert(0, "../LeapSDK/lib")
# Import LeapSDK
import Leap
def run_step():
face = face_detector_gui.FDetector()
face.run()
- print face.face_detected
+ print('Is face detected? ', face.face_detected)
if face.face_detected:
+ print("Enabled Gesture Recognition")
# Create a sample listener and controller
listener = MyListener()
controller = Leap.Controller()
controller.set_policy_flags(Leap.Controller.POLICY_IMAGES)
# Have the sample listener receive events from the controller
controller.add_listener(listener)
t_end = time.time() + 20
while time.time() < t_end:
pass
+ print('Disabled Gesture Recognition')
return
if __name__ == "__main__":
while True:
run_step()
| Add some prints to improve verbosity | ## Code Before:
# Import native python libraries
import inspect
import os
import sys
from listener import MyListener
from face_detection import face_detector_gui
import time
# Setup environment variables
src_dir = os.path.dirname(inspect.getfile(inspect.currentframe()))
# Windows and Linux
arch_dir = '../LeapSDK/lib/x64' if sys.maxsize > 2**32 else '../LeapSDK/lib/x86'
# Mac
# arch_dir = os.path.abspath(os.path.join(src_dir, '../LeapSDK/lib')
sys.path.insert(0, os.path.abspath(os.path.join(src_dir, arch_dir)))
sys.path.insert(0, "../LeapSDK/lib")
# Import LeapSDK
import Leap
def run_step():
face = face_detector_gui.FDetector()
face.run()
print face.face_detected
if face.face_detected:
# Create a sample listener and controller
listener = MyListener()
controller = Leap.Controller()
controller.set_policy_flags(Leap.Controller.POLICY_IMAGES)
# Have the sample listener receive events from the controller
controller.add_listener(listener)
t_end = time.time() + 20
while time.time() < t_end:
pass
return
if __name__ == "__main__":
while True:
run_step()
## Instruction:
Add some prints to improve verbosity
## Code After:
# Import native python libraries
import inspect
import os
import sys
from listener import MyListener
from face_detection import face_detector_gui
import time
# Setup environment variables
src_dir = os.path.dirname(inspect.getfile(inspect.currentframe()))
# Windows and Linux
arch_dir = '../LeapSDK/lib/x64' if sys.maxsize > 2**32 else '../LeapSDK/lib/x86'
# Mac
# arch_dir = os.path.abspath(os.path.join(src_dir, '../LeapSDK/lib')
sys.path.insert(0, os.path.abspath(os.path.join(src_dir, arch_dir)))
sys.path.insert(0, "../LeapSDK/lib")
# Import LeapSDK
import Leap
def run_step():
face = face_detector_gui.FDetector()
face.run()
print('Is face detected? ', face.face_detected)
if face.face_detected:
print("Enabled Gesture Recognition")
# Create a sample listener and controller
listener = MyListener()
controller = Leap.Controller()
controller.set_policy_flags(Leap.Controller.POLICY_IMAGES)
# Have the sample listener receive events from the controller
controller.add_listener(listener)
t_end = time.time() + 20
while time.time() < t_end:
pass
print('Disabled Gesture Recognition')
return
if __name__ == "__main__":
while True:
run_step()
|
# Import native python libraries
import inspect
import os
import sys
from listener import MyListener
from face_detection import face_detector_gui
import time
# Setup environment variables
src_dir = os.path.dirname(inspect.getfile(inspect.currentframe()))
# Windows and Linux
arch_dir = '../LeapSDK/lib/x64' if sys.maxsize > 2**32 else '../LeapSDK/lib/x86'
# Mac
# arch_dir = os.path.abspath(os.path.join(src_dir, '../LeapSDK/lib')
sys.path.insert(0, os.path.abspath(os.path.join(src_dir, arch_dir)))
sys.path.insert(0, "../LeapSDK/lib")
# Import LeapSDK
import Leap
def run_step():
face = face_detector_gui.FDetector()
face.run()
- print face.face_detected
+ print('Is face detected? ', face.face_detected)
if face.face_detected:
+ print("Enabled Gesture Recognition")
# Create a sample listener and controller
listener = MyListener()
controller = Leap.Controller()
controller.set_policy_flags(Leap.Controller.POLICY_IMAGES)
# Have the sample listener receive events from the controller
controller.add_listener(listener)
t_end = time.time() + 20
while time.time() < t_end:
pass
+ print('Disabled Gesture Recognition')
return
if __name__ == "__main__":
while True:
run_step() |
6a007316bd3c7576e83076bee5d3236a1891a512 | messente/api/sms/api/__init__.py | messente/api/sms/api/__init__.py |
from __future__ import absolute_import, division, print_function
from messente.api.sms.api import error
from messente.api.sms.api.response import Response
# api modules
from messente.api.sms.api import sms
from messente.api.sms.api import credit
from messente.api.sms.api import delivery
from messente.api.sms.api import pricing
from messente.api.sms.api import number_verification
from messente.api.sms.api import verification_widget
|
from __future__ import absolute_import, division, print_function
from messente.api.sms.api import error
from messente.api.sms.api.response import Response
# api modules
from messente.api.sms.api import sms
from messente.api.sms.api import credit
from messente.api.sms.api import delivery
from messente.api.sms.api import pricing
from messente.api.sms.api import number_verification
from messente.api.sms.api import verification_widget
__all__ = [
"error",
"Response",
"sms",
"credit",
"delivery",
"pricing",
"number_verification",
"verification_widget",
]
| Declare public interface for api.sms.api module | Declare public interface for api.sms.api module
| Python | apache-2.0 | messente/messente-python |
from __future__ import absolute_import, division, print_function
from messente.api.sms.api import error
from messente.api.sms.api.response import Response
# api modules
from messente.api.sms.api import sms
from messente.api.sms.api import credit
from messente.api.sms.api import delivery
from messente.api.sms.api import pricing
from messente.api.sms.api import number_verification
from messente.api.sms.api import verification_widget
+ __all__ = [
+ "error",
+ "Response",
+ "sms",
+ "credit",
+ "delivery",
+ "pricing",
+ "number_verification",
+ "verification_widget",
+ ]
+ | Declare public interface for api.sms.api module | ## Code Before:
from __future__ import absolute_import, division, print_function
from messente.api.sms.api import error
from messente.api.sms.api.response import Response
# api modules
from messente.api.sms.api import sms
from messente.api.sms.api import credit
from messente.api.sms.api import delivery
from messente.api.sms.api import pricing
from messente.api.sms.api import number_verification
from messente.api.sms.api import verification_widget
## Instruction:
Declare public interface for api.sms.api module
## Code After:
from __future__ import absolute_import, division, print_function
from messente.api.sms.api import error
from messente.api.sms.api.response import Response
# api modules
from messente.api.sms.api import sms
from messente.api.sms.api import credit
from messente.api.sms.api import delivery
from messente.api.sms.api import pricing
from messente.api.sms.api import number_verification
from messente.api.sms.api import verification_widget
__all__ = [
"error",
"Response",
"sms",
"credit",
"delivery",
"pricing",
"number_verification",
"verification_widget",
]
|
from __future__ import absolute_import, division, print_function
from messente.api.sms.api import error
from messente.api.sms.api.response import Response
# api modules
from messente.api.sms.api import sms
from messente.api.sms.api import credit
from messente.api.sms.api import delivery
from messente.api.sms.api import pricing
from messente.api.sms.api import number_verification
from messente.api.sms.api import verification_widget
+
+ __all__ = [
+ "error",
+ "Response",
+ "sms",
+ "credit",
+ "delivery",
+ "pricing",
+ "number_verification",
+ "verification_widget",
+ ] |
f60363b3d24d2f4af5ddb894cc1f6494b371b18e | mass_mailing_switzerland/wizards/mailchimp_export_update_wizard.py | mass_mailing_switzerland/wizards/mailchimp_export_update_wizard.py | from odoo import api, models, fields, _
from odoo.exceptions import UserError
class ExportMailchimpWizard(models.TransientModel):
_inherit = "partner.export.mailchimp"
@api.multi
def get_mailing_contact_id(self, partner_id, force_create=False):
# Avoid exporting opt_out partner
if force_create:
partner = self.env["res.partner"].browse(partner_id)
if partner.opt_out:
return False
# Push the partner_id in mailing_contact creation
return super(
ExportMailchimpWizard, self.with_context(default_partner_id=partner_id)
).get_mailing_contact_id(partner_id, force_create)
| from odoo import api, models, fields, _
from odoo.exceptions import UserError
class ExportMailchimpWizard(models.TransientModel):
_inherit = "partner.export.mailchimp"
@api.multi
def get_mailing_contact_id(self, partner_id, force_create=False):
# Avoid exporting opt_out partner
if force_create and partner_id.opt_out:
return False
# Push the partner_id in mailing_contact creation
return super(
ExportMailchimpWizard, self.with_context(default_partner_id=partner_id)
).get_mailing_contact_id(partner_id, force_create)
| FIX opt_out prevention for mailchimp export | FIX opt_out prevention for mailchimp export
| Python | agpl-3.0 | CompassionCH/compassion-switzerland,eicher31/compassion-switzerland,CompassionCH/compassion-switzerland,CompassionCH/compassion-switzerland,eicher31/compassion-switzerland,eicher31/compassion-switzerland | from odoo import api, models, fields, _
from odoo.exceptions import UserError
class ExportMailchimpWizard(models.TransientModel):
_inherit = "partner.export.mailchimp"
@api.multi
def get_mailing_contact_id(self, partner_id, force_create=False):
# Avoid exporting opt_out partner
+ if force_create and partner_id.opt_out:
- if force_create:
- partner = self.env["res.partner"].browse(partner_id)
- if partner.opt_out:
- return False
+ return False
# Push the partner_id in mailing_contact creation
return super(
ExportMailchimpWizard, self.with_context(default_partner_id=partner_id)
).get_mailing_contact_id(partner_id, force_create)
| FIX opt_out prevention for mailchimp export | ## Code Before:
from odoo import api, models, fields, _
from odoo.exceptions import UserError
class ExportMailchimpWizard(models.TransientModel):
_inherit = "partner.export.mailchimp"
@api.multi
def get_mailing_contact_id(self, partner_id, force_create=False):
# Avoid exporting opt_out partner
if force_create:
partner = self.env["res.partner"].browse(partner_id)
if partner.opt_out:
return False
# Push the partner_id in mailing_contact creation
return super(
ExportMailchimpWizard, self.with_context(default_partner_id=partner_id)
).get_mailing_contact_id(partner_id, force_create)
## Instruction:
FIX opt_out prevention for mailchimp export
## Code After:
from odoo import api, models, fields, _
from odoo.exceptions import UserError
class ExportMailchimpWizard(models.TransientModel):
_inherit = "partner.export.mailchimp"
@api.multi
def get_mailing_contact_id(self, partner_id, force_create=False):
# Avoid exporting opt_out partner
if force_create and partner_id.opt_out:
return False
# Push the partner_id in mailing_contact creation
return super(
ExportMailchimpWizard, self.with_context(default_partner_id=partner_id)
).get_mailing_contact_id(partner_id, force_create)
| from odoo import api, models, fields, _
from odoo.exceptions import UserError
class ExportMailchimpWizard(models.TransientModel):
_inherit = "partner.export.mailchimp"
@api.multi
def get_mailing_contact_id(self, partner_id, force_create=False):
# Avoid exporting opt_out partner
+ if force_create and partner_id.opt_out:
- if force_create:
- partner = self.env["res.partner"].browse(partner_id)
- if partner.opt_out:
- return False
? ----
+ return False
# Push the partner_id in mailing_contact creation
return super(
ExportMailchimpWizard, self.with_context(default_partner_id=partner_id)
).get_mailing_contact_id(partner_id, force_create) |
23ab67f74fc7c09310638529ccf804ec2271fd6c | pynads/writer.py | pynads/writer.py | from .monad import Monad
from .functor import fmap
class Writer(Monad):
"""Stores a value as well as a log of events that have transpired
with the value.
"""
def __init__(self, v, log):
self.v = v
if not isinstance(log, list):
self.log = [log]
else:
self.log = log
@classmethod
def unit(cls, v):
return cls(v, [])
def fmap(self, f):
return Writer(f(self.v), self.log)
def apply(self, applicative):
return fmap(self.v, applicative)
def bind(self, f):
v, msg = f(self.v)
return Writer(v, self.log + [msg])
def __repr__(self):
return "Writer({!r}, {!r})".format(self.v, self.log)
| from .utils import _iter_but_not_str_or_map
from .monad import Monad
from .functor import fmap
class Writer(Monad):
"""Stores a value as well as a log of events that have transpired
with the value.
"""
__slots__ = ('v', 'log')
def __init__(self, v, log):
self.v = v
if _iter_but_not_str_or_map(log):
print("convert iter to list log...")
self.log = [l for l in log]
else:
print("convert str/map/other to list log...")
self.log = [log]
@classmethod
def unit(cls, v):
return cls(v, [])
def fmap(self, f):
return Writer(f(self.v), self.log)
def apply(self, applicative):
return fmap(self.v, applicative)
def bind(self, f):
v, msg = f(self.v)
return Writer(v, self.log + [msg])
def __repr__(self):
return "Writer({!r}, {!r})".format(self.v, self.log)
| Use utils._iter_but_not_str_or_map in Writer log creation. | Use utils._iter_but_not_str_or_map in Writer log creation.
| Python | mit | justanr/pynads | + from .utils import _iter_but_not_str_or_map
from .monad import Monad
from .functor import fmap
class Writer(Monad):
"""Stores a value as well as a log of events that have transpired
with the value.
"""
+ __slots__ = ('v', 'log')
+
def __init__(self, v, log):
self.v = v
- if not isinstance(log, list):
+ if _iter_but_not_str_or_map(log):
+ print("convert iter to list log...")
+ self.log = [l for l in log]
+ else:
+ print("convert str/map/other to list log...")
self.log = [log]
- else:
- self.log = log
@classmethod
def unit(cls, v):
return cls(v, [])
def fmap(self, f):
return Writer(f(self.v), self.log)
def apply(self, applicative):
return fmap(self.v, applicative)
def bind(self, f):
v, msg = f(self.v)
return Writer(v, self.log + [msg])
def __repr__(self):
return "Writer({!r}, {!r})".format(self.v, self.log)
| Use utils._iter_but_not_str_or_map in Writer log creation. | ## Code Before:
from .monad import Monad
from .functor import fmap
class Writer(Monad):
"""Stores a value as well as a log of events that have transpired
with the value.
"""
def __init__(self, v, log):
self.v = v
if not isinstance(log, list):
self.log = [log]
else:
self.log = log
@classmethod
def unit(cls, v):
return cls(v, [])
def fmap(self, f):
return Writer(f(self.v), self.log)
def apply(self, applicative):
return fmap(self.v, applicative)
def bind(self, f):
v, msg = f(self.v)
return Writer(v, self.log + [msg])
def __repr__(self):
return "Writer({!r}, {!r})".format(self.v, self.log)
## Instruction:
Use utils._iter_but_not_str_or_map in Writer log creation.
## Code After:
from .utils import _iter_but_not_str_or_map
from .monad import Monad
from .functor import fmap
class Writer(Monad):
"""Stores a value as well as a log of events that have transpired
with the value.
"""
__slots__ = ('v', 'log')
def __init__(self, v, log):
self.v = v
if _iter_but_not_str_or_map(log):
print("convert iter to list log...")
self.log = [l for l in log]
else:
print("convert str/map/other to list log...")
self.log = [log]
@classmethod
def unit(cls, v):
return cls(v, [])
def fmap(self, f):
return Writer(f(self.v), self.log)
def apply(self, applicative):
return fmap(self.v, applicative)
def bind(self, f):
v, msg = f(self.v)
return Writer(v, self.log + [msg])
def __repr__(self):
return "Writer({!r}, {!r})".format(self.v, self.log)
| + from .utils import _iter_but_not_str_or_map
from .monad import Monad
from .functor import fmap
class Writer(Monad):
"""Stores a value as well as a log of events that have transpired
with the value.
"""
+ __slots__ = ('v', 'log')
+
def __init__(self, v, log):
self.v = v
- if not isinstance(log, list):
+ if _iter_but_not_str_or_map(log):
+ print("convert iter to list log...")
+ self.log = [l for l in log]
+ else:
+ print("convert str/map/other to list log...")
self.log = [log]
- else:
- self.log = log
@classmethod
def unit(cls, v):
return cls(v, [])
def fmap(self, f):
return Writer(f(self.v), self.log)
def apply(self, applicative):
return fmap(self.v, applicative)
def bind(self, f):
v, msg = f(self.v)
return Writer(v, self.log + [msg])
def __repr__(self):
return "Writer({!r}, {!r})".format(self.v, self.log) |
01a8fcb70ea75d854aaf16547b837d861750c160 | tilequeue/queue/file.py | tilequeue/queue/file.py | from tilequeue.tile import serialize_coord, deserialize_coord, CoordMessage
import threading
class OutputFileQueue(object):
def __init__(self, fp):
self.fp = fp
self.lock = threading.RLock()
def enqueue(self, coord):
with self.lock:
payload = serialize_coord(coord)
self.fp.write(payload + '\n')
def enqueue_batch(self, coords):
n = 0
for coord in coords:
self.enqueue(coord)
n += 1
return n, 0
def read(self, max_to_read=1, timeout_seconds=20):
with self.lock:
coords = []
for _ in range(max_to_read):
try:
coord = next(self.fp)
except StopIteration:
break
coords.append(CoordMessage(deserialize_coord(coord), None))
return coords
def job_done(self, coord_message):
pass
def clear(self):
with self.lock:
self.fp.seek(0)
self.fp.truncate()
return -1
def close(self):
with self.lock:
remaining_queue = "".join([ln for ln in self.fp])
self.clear()
self.fp.write(remaining_queue)
self.fp.close()
| from tilequeue.tile import serialize_coord, deserialize_coord, CoordMessage
import threading
class OutputFileQueue(object):
def __init__(self, fp):
self.fp = fp
self.lock = threading.RLock()
def enqueue(self, coord):
with self.lock:
payload = serialize_coord(coord)
self.fp.write(payload + '\n')
def enqueue_batch(self, coords):
n = 0
for coord in coords:
self.enqueue(coord)
n += 1
return n, 0
def read(self, max_to_read=1, timeout_seconds=20):
with self.lock:
coords = []
for _ in range(max_to_read):
coord = self.fp.readline()
if coord:
coords.append(CoordMessage(deserialize_coord(coord), None))
else:
break
return coords
def job_done(self, coord_message):
pass
def clear(self):
with self.lock:
self.fp.seek(0)
self.fp.truncate()
return -1
def close(self):
with self.lock:
remaining_queue = ''.join([ln for ln in self.fp])
self.clear()
self.fp.write(remaining_queue)
self.fp.close()
| Use readline() instead of next() to detect changes. | Use readline() instead of next() to detect changes.
tilequeue/queue/file.py
-`readline()` will pick up new lines appended to the file,
whereas `next()` will not since the iterator will just hit
`StopIteration` and stop generating new lines. Use `readline()`
instead, then, since it might be desirable to append something
to the queue file and have tilequeue detect the new input
without having to restart.
| Python | mit | tilezen/tilequeue,mapzen/tilequeue | from tilequeue.tile import serialize_coord, deserialize_coord, CoordMessage
import threading
class OutputFileQueue(object):
def __init__(self, fp):
self.fp = fp
self.lock = threading.RLock()
def enqueue(self, coord):
with self.lock:
payload = serialize_coord(coord)
self.fp.write(payload + '\n')
def enqueue_batch(self, coords):
n = 0
for coord in coords:
self.enqueue(coord)
n += 1
return n, 0
def read(self, max_to_read=1, timeout_seconds=20):
with self.lock:
coords = []
for _ in range(max_to_read):
+ coord = self.fp.readline()
+ if coord:
+ coords.append(CoordMessage(deserialize_coord(coord), None))
- try:
+ else:
- coord = next(self.fp)
- except StopIteration:
break
- coords.append(CoordMessage(deserialize_coord(coord), None))
return coords
def job_done(self, coord_message):
pass
def clear(self):
with self.lock:
self.fp.seek(0)
self.fp.truncate()
return -1
def close(self):
with self.lock:
- remaining_queue = "".join([ln for ln in self.fp])
+ remaining_queue = ''.join([ln for ln in self.fp])
self.clear()
self.fp.write(remaining_queue)
self.fp.close()
| Use readline() instead of next() to detect changes. | ## Code Before:
from tilequeue.tile import serialize_coord, deserialize_coord, CoordMessage
import threading
class OutputFileQueue(object):
def __init__(self, fp):
self.fp = fp
self.lock = threading.RLock()
def enqueue(self, coord):
with self.lock:
payload = serialize_coord(coord)
self.fp.write(payload + '\n')
def enqueue_batch(self, coords):
n = 0
for coord in coords:
self.enqueue(coord)
n += 1
return n, 0
def read(self, max_to_read=1, timeout_seconds=20):
with self.lock:
coords = []
for _ in range(max_to_read):
try:
coord = next(self.fp)
except StopIteration:
break
coords.append(CoordMessage(deserialize_coord(coord), None))
return coords
def job_done(self, coord_message):
pass
def clear(self):
with self.lock:
self.fp.seek(0)
self.fp.truncate()
return -1
def close(self):
with self.lock:
remaining_queue = "".join([ln for ln in self.fp])
self.clear()
self.fp.write(remaining_queue)
self.fp.close()
## Instruction:
Use readline() instead of next() to detect changes.
## Code After:
from tilequeue.tile import serialize_coord, deserialize_coord, CoordMessage
import threading
class OutputFileQueue(object):
def __init__(self, fp):
self.fp = fp
self.lock = threading.RLock()
def enqueue(self, coord):
with self.lock:
payload = serialize_coord(coord)
self.fp.write(payload + '\n')
def enqueue_batch(self, coords):
n = 0
for coord in coords:
self.enqueue(coord)
n += 1
return n, 0
def read(self, max_to_read=1, timeout_seconds=20):
with self.lock:
coords = []
for _ in range(max_to_read):
coord = self.fp.readline()
if coord:
coords.append(CoordMessage(deserialize_coord(coord), None))
else:
break
return coords
def job_done(self, coord_message):
pass
def clear(self):
with self.lock:
self.fp.seek(0)
self.fp.truncate()
return -1
def close(self):
with self.lock:
remaining_queue = ''.join([ln for ln in self.fp])
self.clear()
self.fp.write(remaining_queue)
self.fp.close()
| from tilequeue.tile import serialize_coord, deserialize_coord, CoordMessage
import threading
class OutputFileQueue(object):
def __init__(self, fp):
self.fp = fp
self.lock = threading.RLock()
def enqueue(self, coord):
with self.lock:
payload = serialize_coord(coord)
self.fp.write(payload + '\n')
def enqueue_batch(self, coords):
n = 0
for coord in coords:
self.enqueue(coord)
n += 1
return n, 0
def read(self, max_to_read=1, timeout_seconds=20):
with self.lock:
coords = []
for _ in range(max_to_read):
+ coord = self.fp.readline()
+ if coord:
+ coords.append(CoordMessage(deserialize_coord(coord), None))
- try:
? ^^^
+ else:
? ^^^^
- coord = next(self.fp)
- except StopIteration:
break
- coords.append(CoordMessage(deserialize_coord(coord), None))
return coords
def job_done(self, coord_message):
pass
def clear(self):
with self.lock:
self.fp.seek(0)
self.fp.truncate()
return -1
def close(self):
with self.lock:
- remaining_queue = "".join([ln for ln in self.fp])
? ^^
+ remaining_queue = ''.join([ln for ln in self.fp])
? ^^
self.clear()
self.fp.write(remaining_queue)
self.fp.close() |
c4d58ef971b850d3f201903bb6091d159241112f | histomicstk/features/__init__.py | histomicstk/features/__init__.py | from .ReinhardNorm import ReinhardNorm
from .ReinhardSample import ReinhardSample
__all__ = (
'FeatureExtraction'
)
| __all__ = (
'FeatureExtraction'
)
| Resolve import issue in color_normalization_test | Resolve import issue in color_normalization_test
| Python | apache-2.0 | DigitalSlideArchive/HistomicsTK,DigitalSlideArchive/HistomicsTK | - from .ReinhardNorm import ReinhardNorm
- from .ReinhardSample import ReinhardSample
-
__all__ = (
'FeatureExtraction'
)
| Resolve import issue in color_normalization_test | ## Code Before:
from .ReinhardNorm import ReinhardNorm
from .ReinhardSample import ReinhardSample
__all__ = (
'FeatureExtraction'
)
## Instruction:
Resolve import issue in color_normalization_test
## Code After:
__all__ = (
'FeatureExtraction'
)
| - from .ReinhardNorm import ReinhardNorm
- from .ReinhardSample import ReinhardSample
-
__all__ = (
'FeatureExtraction'
) |
5f1632cf1f307688e4884988e03a1678557bb79c | erpnext/hr/doctype/training_feedback/training_feedback.py | erpnext/hr/doctype/training_feedback/training_feedback.py |
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
from frappe import _
class TrainingFeedback(Document):
def validate(self):
training_event = frappe.get_doc("Training Event", self.training_event)
if training_event.docstatus != 1:
frappe.throw(_('{0} must be submitted').format(_('Training Event')))
def on_submit(self):
training_event = frappe.get_doc("Training Event", self.training_event)
status = None
for e in training_event.employees:
if e.employee == self.employee:
status = 'Feedback Submitted'
break
if status:
frappe.db.set_value("Training Event", self.training_event, "status", status)
|
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
from frappe import _
class TrainingFeedback(Document):
def validate(self):
training_event = frappe.get_doc("Training Event", self.training_event)
if training_event.docstatus != 1:
frappe.throw(_('{0} must be submitted').format(_('Training Event')))
def on_submit(self):
training_event = frappe.get_doc("Training Event", self.training_event)
event_status = None
for e in training_event.employees:
if e.employee == self.employee:
event_status = 'Feedback Submitted'
break
if event_status:
frappe.db.set_value("Training Event", self.training_event, "event_status", event_status)
| Use event_status instead of status | fix(hr): Use event_status instead of status
Training Feedback DocType has event_status field (not status)
This was broken since PR #10379, PR #17197 made this failure explicit.
| Python | agpl-3.0 | gsnbng/erpnext,gsnbng/erpnext,gsnbng/erpnext,gsnbng/erpnext |
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
from frappe import _
class TrainingFeedback(Document):
def validate(self):
training_event = frappe.get_doc("Training Event", self.training_event)
if training_event.docstatus != 1:
frappe.throw(_('{0} must be submitted').format(_('Training Event')))
def on_submit(self):
training_event = frappe.get_doc("Training Event", self.training_event)
- status = None
+ event_status = None
for e in training_event.employees:
if e.employee == self.employee:
- status = 'Feedback Submitted'
+ event_status = 'Feedback Submitted'
break
- if status:
+ if event_status:
- frappe.db.set_value("Training Event", self.training_event, "status", status)
+ frappe.db.set_value("Training Event", self.training_event, "event_status", event_status)
| Use event_status instead of status | ## Code Before:
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
from frappe import _
class TrainingFeedback(Document):
def validate(self):
training_event = frappe.get_doc("Training Event", self.training_event)
if training_event.docstatus != 1:
frappe.throw(_('{0} must be submitted').format(_('Training Event')))
def on_submit(self):
training_event = frappe.get_doc("Training Event", self.training_event)
status = None
for e in training_event.employees:
if e.employee == self.employee:
status = 'Feedback Submitted'
break
if status:
frappe.db.set_value("Training Event", self.training_event, "status", status)
## Instruction:
Use event_status instead of status
## Code After:
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
from frappe import _
class TrainingFeedback(Document):
def validate(self):
training_event = frappe.get_doc("Training Event", self.training_event)
if training_event.docstatus != 1:
frappe.throw(_('{0} must be submitted').format(_('Training Event')))
def on_submit(self):
training_event = frappe.get_doc("Training Event", self.training_event)
event_status = None
for e in training_event.employees:
if e.employee == self.employee:
event_status = 'Feedback Submitted'
break
if event_status:
frappe.db.set_value("Training Event", self.training_event, "event_status", event_status)
|
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
from frappe import _
class TrainingFeedback(Document):
def validate(self):
training_event = frappe.get_doc("Training Event", self.training_event)
if training_event.docstatus != 1:
frappe.throw(_('{0} must be submitted').format(_('Training Event')))
def on_submit(self):
training_event = frappe.get_doc("Training Event", self.training_event)
- status = None
+ event_status = None
? ++++++
for e in training_event.employees:
if e.employee == self.employee:
- status = 'Feedback Submitted'
+ event_status = 'Feedback Submitted'
? ++++++
break
- if status:
+ if event_status:
? ++++++
- frappe.db.set_value("Training Event", self.training_event, "status", status)
+ frappe.db.set_value("Training Event", self.training_event, "event_status", event_status)
? ++++++ ++++++
|
ba48cd45c56646497bcda70d9a475a40ea44c874 | dbaas/workflow/steps/mysql/resize/change_config.py | dbaas/workflow/steps/mysql/resize/change_config.py | import logging
from . import run_vm_script
from ...util.base import BaseStep
LOG = logging.getLogger(__name__)
class ChangeDatabaseConfigFile(BaseStep):
def __unicode__(self):
return "Changing database config file..."
def do(self, workflow_dict):
context_dict = {
'CONFIGFILE': True,
'IS_HA': workflow_dict['databaseinfra'].plan.is_ha
},
ret_script = run_vm_script(
workflow_dict=workflow_dict,
context_dict=context_dict,
script=workflow_dict['cloudstackpack'].script,
)
return ret_script
def undo(self, workflow_dict):
context_dict = {
'CONFIGFILE': True,
}
ret_script = run_vm_script(
workflow_dict=workflow_dict,
context_dict=context_dict,
script=workflow_dict['original_cloudstackpack'].script,
)
return ret_script
| import logging
from workflow.steps.mysql.resize import run_vm_script
from workflow.steps.util.base import BaseStep
LOG = logging.getLogger(__name__)
class ChangeDatabaseConfigFile(BaseStep):
def __unicode__(self):
return "Changing database config file..."
def do(self, workflow_dict):
context_dict = {
'CONFIGFILE': True,
'IS_HA': workflow_dict['databaseinfra'].plan.is_ha
},
ret_script = run_vm_script(
workflow_dict=workflow_dict,
context_dict=context_dict,
script=workflow_dict['cloudstackpack'].script,
)
return ret_script
def undo(self, workflow_dict):
context_dict = {
'CONFIGFILE': True,
'IS_HA': workflow_dict['databaseinfra'].plan.is_ha,
}
ret_script = run_vm_script(
workflow_dict=workflow_dict,
context_dict=context_dict,
script=workflow_dict['original_cloudstackpack'].script,
)
return ret_script
| Add is_ha variable to change config rollback | Add is_ha variable to change config rollback
| Python | bsd-3-clause | globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service | import logging
- from . import run_vm_script
+ from workflow.steps.mysql.resize import run_vm_script
- from ...util.base import BaseStep
+ from workflow.steps.util.base import BaseStep
LOG = logging.getLogger(__name__)
class ChangeDatabaseConfigFile(BaseStep):
def __unicode__(self):
return "Changing database config file..."
def do(self, workflow_dict):
context_dict = {
'CONFIGFILE': True,
'IS_HA': workflow_dict['databaseinfra'].plan.is_ha
},
ret_script = run_vm_script(
workflow_dict=workflow_dict,
context_dict=context_dict,
script=workflow_dict['cloudstackpack'].script,
)
return ret_script
def undo(self, workflow_dict):
context_dict = {
'CONFIGFILE': True,
+ 'IS_HA': workflow_dict['databaseinfra'].plan.is_ha,
}
ret_script = run_vm_script(
workflow_dict=workflow_dict,
context_dict=context_dict,
script=workflow_dict['original_cloudstackpack'].script,
)
return ret_script
| Add is_ha variable to change config rollback | ## Code Before:
import logging
from . import run_vm_script
from ...util.base import BaseStep
LOG = logging.getLogger(__name__)
class ChangeDatabaseConfigFile(BaseStep):
def __unicode__(self):
return "Changing database config file..."
def do(self, workflow_dict):
context_dict = {
'CONFIGFILE': True,
'IS_HA': workflow_dict['databaseinfra'].plan.is_ha
},
ret_script = run_vm_script(
workflow_dict=workflow_dict,
context_dict=context_dict,
script=workflow_dict['cloudstackpack'].script,
)
return ret_script
def undo(self, workflow_dict):
context_dict = {
'CONFIGFILE': True,
}
ret_script = run_vm_script(
workflow_dict=workflow_dict,
context_dict=context_dict,
script=workflow_dict['original_cloudstackpack'].script,
)
return ret_script
## Instruction:
Add is_ha variable to change config rollback
## Code After:
import logging
from workflow.steps.mysql.resize import run_vm_script
from workflow.steps.util.base import BaseStep
LOG = logging.getLogger(__name__)
class ChangeDatabaseConfigFile(BaseStep):
def __unicode__(self):
return "Changing database config file..."
def do(self, workflow_dict):
context_dict = {
'CONFIGFILE': True,
'IS_HA': workflow_dict['databaseinfra'].plan.is_ha
},
ret_script = run_vm_script(
workflow_dict=workflow_dict,
context_dict=context_dict,
script=workflow_dict['cloudstackpack'].script,
)
return ret_script
def undo(self, workflow_dict):
context_dict = {
'CONFIGFILE': True,
'IS_HA': workflow_dict['databaseinfra'].plan.is_ha,
}
ret_script = run_vm_script(
workflow_dict=workflow_dict,
context_dict=context_dict,
script=workflow_dict['original_cloudstackpack'].script,
)
return ret_script
| import logging
- from . import run_vm_script
+ from workflow.steps.mysql.resize import run_vm_script
- from ...util.base import BaseStep
? ^
+ from workflow.steps.util.base import BaseStep
? ++++++++ ^^^^^
LOG = logging.getLogger(__name__)
class ChangeDatabaseConfigFile(BaseStep):
def __unicode__(self):
return "Changing database config file..."
def do(self, workflow_dict):
context_dict = {
'CONFIGFILE': True,
'IS_HA': workflow_dict['databaseinfra'].plan.is_ha
},
ret_script = run_vm_script(
workflow_dict=workflow_dict,
context_dict=context_dict,
script=workflow_dict['cloudstackpack'].script,
)
return ret_script
def undo(self, workflow_dict):
context_dict = {
'CONFIGFILE': True,
+ 'IS_HA': workflow_dict['databaseinfra'].plan.is_ha,
}
ret_script = run_vm_script(
workflow_dict=workflow_dict,
context_dict=context_dict,
script=workflow_dict['original_cloudstackpack'].script,
)
return ret_script |
608fc063e5b153b99b79cab2248b586db3ebda1f | tests/test_pybind11.py | tests/test_pybind11.py | import sys
import os
d = os.path.dirname(__file__)
sys.path.append(os.path.join(d, '../'))
import jtrace
# para = jtrace.Paraboloid(0.0, 0.0)
# print(para.A)
# print(para.B)
# vec = jtrace.Vec3()
# print(vec.MagnitudeSquared())
# vec = jtrace.Vec3(1, 2, 3)
# print(vec.MagnitudeSquared())
# unitvec = vec.UnitVec3()
# print(unitvec.Magnitude())
# ray = jtrace.Ray(jtrace.Vec3(), jtrace.Vec3(0,0,1))
# print(ray)
# print(ray(1.0))
# print(ray(1.3))
ray = jtrace.Ray(jtrace.Vec3(0,0.5,0), jtrace.Vec3(0,0,1))
para = jtrace.Paraboloid(1, 1)
print(para.intersect(ray))
asphere = jtrace.Asphere(1.0, -1.0, [0.0, 0.001], 0.0)
print(asphere)
print(asphere.alpha)
isec = asphere.intersect(ray)
print(isec)
print(asphere(isec.point.x, isec.point.y))
print(ray(isec.t))
| import sys
import os
import jtrace
# para = jtrace.Paraboloid(0.0, 0.0)
# print(para.A)
# print(para.B)
# vec = jtrace.Vec3()
# print(vec.MagnitudeSquared())
# vec = jtrace.Vec3(1, 2, 3)
# print(vec.MagnitudeSquared())
# unitvec = vec.UnitVec3()
# print(unitvec.Magnitude())
# ray = jtrace.Ray(jtrace.Vec3(), jtrace.Vec3(0,0,1))
# print(ray)
# print(ray(1.0))
# print(ray(1.3))
ray = jtrace.Ray(jtrace.Vec3(0,0.5,0), jtrace.Vec3(0,0,1))
para = jtrace.Paraboloid(1, 1)
print(para.intersect(ray))
asphere = jtrace.Asphere(1.0, -1.0, [0.0, 0.001], 0.0)
print(asphere)
print(asphere.alpha)
isec = asphere.intersect(ray)
print(isec)
print(asphere(isec.point.x, isec.point.y))
print(ray(isec.t))
| Remove sys.path hacking from test | Remove sys.path hacking from test
| Python | bsd-2-clause | jmeyers314/batoid,jmeyers314/jtrace,jmeyers314/batoid,jmeyers314/jtrace,jmeyers314/jtrace | import sys
import os
- d = os.path.dirname(__file__)
- sys.path.append(os.path.join(d, '../'))
import jtrace
# para = jtrace.Paraboloid(0.0, 0.0)
# print(para.A)
# print(para.B)
# vec = jtrace.Vec3()
# print(vec.MagnitudeSquared())
# vec = jtrace.Vec3(1, 2, 3)
# print(vec.MagnitudeSquared())
# unitvec = vec.UnitVec3()
# print(unitvec.Magnitude())
# ray = jtrace.Ray(jtrace.Vec3(), jtrace.Vec3(0,0,1))
# print(ray)
# print(ray(1.0))
# print(ray(1.3))
ray = jtrace.Ray(jtrace.Vec3(0,0.5,0), jtrace.Vec3(0,0,1))
para = jtrace.Paraboloid(1, 1)
print(para.intersect(ray))
asphere = jtrace.Asphere(1.0, -1.0, [0.0, 0.001], 0.0)
print(asphere)
print(asphere.alpha)
isec = asphere.intersect(ray)
print(isec)
print(asphere(isec.point.x, isec.point.y))
print(ray(isec.t))
| Remove sys.path hacking from test | ## Code Before:
import sys
import os
d = os.path.dirname(__file__)
sys.path.append(os.path.join(d, '../'))
import jtrace
# para = jtrace.Paraboloid(0.0, 0.0)
# print(para.A)
# print(para.B)
# vec = jtrace.Vec3()
# print(vec.MagnitudeSquared())
# vec = jtrace.Vec3(1, 2, 3)
# print(vec.MagnitudeSquared())
# unitvec = vec.UnitVec3()
# print(unitvec.Magnitude())
# ray = jtrace.Ray(jtrace.Vec3(), jtrace.Vec3(0,0,1))
# print(ray)
# print(ray(1.0))
# print(ray(1.3))
ray = jtrace.Ray(jtrace.Vec3(0,0.5,0), jtrace.Vec3(0,0,1))
para = jtrace.Paraboloid(1, 1)
print(para.intersect(ray))
asphere = jtrace.Asphere(1.0, -1.0, [0.0, 0.001], 0.0)
print(asphere)
print(asphere.alpha)
isec = asphere.intersect(ray)
print(isec)
print(asphere(isec.point.x, isec.point.y))
print(ray(isec.t))
## Instruction:
Remove sys.path hacking from test
## Code After:
import sys
import os
import jtrace
# para = jtrace.Paraboloid(0.0, 0.0)
# print(para.A)
# print(para.B)
# vec = jtrace.Vec3()
# print(vec.MagnitudeSquared())
# vec = jtrace.Vec3(1, 2, 3)
# print(vec.MagnitudeSquared())
# unitvec = vec.UnitVec3()
# print(unitvec.Magnitude())
# ray = jtrace.Ray(jtrace.Vec3(), jtrace.Vec3(0,0,1))
# print(ray)
# print(ray(1.0))
# print(ray(1.3))
ray = jtrace.Ray(jtrace.Vec3(0,0.5,0), jtrace.Vec3(0,0,1))
para = jtrace.Paraboloid(1, 1)
print(para.intersect(ray))
asphere = jtrace.Asphere(1.0, -1.0, [0.0, 0.001], 0.0)
print(asphere)
print(asphere.alpha)
isec = asphere.intersect(ray)
print(isec)
print(asphere(isec.point.x, isec.point.y))
print(ray(isec.t))
| import sys
import os
- d = os.path.dirname(__file__)
- sys.path.append(os.path.join(d, '../'))
import jtrace
# para = jtrace.Paraboloid(0.0, 0.0)
# print(para.A)
# print(para.B)
# vec = jtrace.Vec3()
# print(vec.MagnitudeSquared())
# vec = jtrace.Vec3(1, 2, 3)
# print(vec.MagnitudeSquared())
# unitvec = vec.UnitVec3()
# print(unitvec.Magnitude())
# ray = jtrace.Ray(jtrace.Vec3(), jtrace.Vec3(0,0,1))
# print(ray)
# print(ray(1.0))
# print(ray(1.3))
ray = jtrace.Ray(jtrace.Vec3(0,0.5,0), jtrace.Vec3(0,0,1))
para = jtrace.Paraboloid(1, 1)
print(para.intersect(ray))
asphere = jtrace.Asphere(1.0, -1.0, [0.0, 0.001], 0.0)
print(asphere)
print(asphere.alpha)
isec = asphere.intersect(ray)
print(isec)
print(asphere(isec.point.x, isec.point.y))
print(ray(isec.t)) |
13350cdf5598ac0ed55e5404cf6d407300b4c1ac | apps/home/forms.py | apps/home/forms.py | import re
from django import forms
from apps.chat.models import Chats
from django.utils.translation import ugettext as _
class CreateChatForm(forms.Form):
pass
class JoinChatForm(forms.Form):
chat_token = forms.CharField(required=True, max_length=24, label='')
chat_token.widget = forms.TextInput({"maxlength": 24,
"pattern": "[a-z0-9]{24}",
"placeholder": _("please enter your code here..."),
"class": "chat-token"})
user_token = False
def clean_chat_token(self):
"""
Validate chat token
"""
new_chat_token = self.cleaned_data['chat_token']
match = re.search(r'[a-z0-9]{24}', new_chat_token)
if not match:
raise forms.ValidationError(_('Invalid code.'))
self.user_token = Chats.join_to_chat(new_chat_token)
if not self.user_token:
raise forms.ValidationError(_('Invalid code.')) | import re
from django import forms
from apps.chat.models import Chats
from django.utils.translation import ugettext as _
class CreateChatForm(forms.Form):
pass
class JoinChatForm(forms.Form):
chat_token = forms.CharField(required=True, max_length=24, label='')
chat_token.widget = forms.TextInput({"maxlength": 24,
"pattern": "[a-z0-9]{24}",
"autocomplete": "off",
"placeholder": _("please enter your code here..."),
"class": "chat-token"})
user_token = False
def clean_chat_token(self):
"""
Validate chat token
"""
new_chat_token = self.cleaned_data['chat_token']
match = re.search(r'[a-z0-9]{24}', new_chat_token)
if not match:
raise forms.ValidationError(_('Invalid code.'))
self.user_token = Chats.join_to_chat(new_chat_token)
if not self.user_token:
raise forms.ValidationError(_('Invalid code.')) | Set autocomplete off for chat token form field | Set autocomplete off for chat token form field
| Python | bsd-3-clause | MySmile/sfchat,MySmile/sfchat,MySmile/sfchat,MySmile/sfchat | import re
from django import forms
from apps.chat.models import Chats
from django.utils.translation import ugettext as _
class CreateChatForm(forms.Form):
pass
class JoinChatForm(forms.Form):
chat_token = forms.CharField(required=True, max_length=24, label='')
chat_token.widget = forms.TextInput({"maxlength": 24,
"pattern": "[a-z0-9]{24}",
+ "autocomplete": "off",
"placeholder": _("please enter your code here..."),
"class": "chat-token"})
user_token = False
def clean_chat_token(self):
"""
Validate chat token
"""
new_chat_token = self.cleaned_data['chat_token']
match = re.search(r'[a-z0-9]{24}', new_chat_token)
if not match:
raise forms.ValidationError(_('Invalid code.'))
self.user_token = Chats.join_to_chat(new_chat_token)
if not self.user_token:
raise forms.ValidationError(_('Invalid code.')) | Set autocomplete off for chat token form field | ## Code Before:
import re
from django import forms
from apps.chat.models import Chats
from django.utils.translation import ugettext as _
class CreateChatForm(forms.Form):
pass
class JoinChatForm(forms.Form):
chat_token = forms.CharField(required=True, max_length=24, label='')
chat_token.widget = forms.TextInput({"maxlength": 24,
"pattern": "[a-z0-9]{24}",
"placeholder": _("please enter your code here..."),
"class": "chat-token"})
user_token = False
def clean_chat_token(self):
"""
Validate chat token
"""
new_chat_token = self.cleaned_data['chat_token']
match = re.search(r'[a-z0-9]{24}', new_chat_token)
if not match:
raise forms.ValidationError(_('Invalid code.'))
self.user_token = Chats.join_to_chat(new_chat_token)
if not self.user_token:
raise forms.ValidationError(_('Invalid code.'))
## Instruction:
Set autocomplete off for chat token form field
## Code After:
import re
from django import forms
from apps.chat.models import Chats
from django.utils.translation import ugettext as _
class CreateChatForm(forms.Form):
pass
class JoinChatForm(forms.Form):
chat_token = forms.CharField(required=True, max_length=24, label='')
chat_token.widget = forms.TextInput({"maxlength": 24,
"pattern": "[a-z0-9]{24}",
"autocomplete": "off",
"placeholder": _("please enter your code here..."),
"class": "chat-token"})
user_token = False
def clean_chat_token(self):
"""
Validate chat token
"""
new_chat_token = self.cleaned_data['chat_token']
match = re.search(r'[a-z0-9]{24}', new_chat_token)
if not match:
raise forms.ValidationError(_('Invalid code.'))
self.user_token = Chats.join_to_chat(new_chat_token)
if not self.user_token:
raise forms.ValidationError(_('Invalid code.')) | import re
from django import forms
from apps.chat.models import Chats
from django.utils.translation import ugettext as _
class CreateChatForm(forms.Form):
pass
class JoinChatForm(forms.Form):
chat_token = forms.CharField(required=True, max_length=24, label='')
chat_token.widget = forms.TextInput({"maxlength": 24,
"pattern": "[a-z0-9]{24}",
+ "autocomplete": "off",
"placeholder": _("please enter your code here..."),
"class": "chat-token"})
user_token = False
def clean_chat_token(self):
"""
Validate chat token
"""
new_chat_token = self.cleaned_data['chat_token']
match = re.search(r'[a-z0-9]{24}', new_chat_token)
if not match:
raise forms.ValidationError(_('Invalid code.'))
self.user_token = Chats.join_to_chat(new_chat_token)
if not self.user_token:
raise forms.ValidationError(_('Invalid code.')) |
a013cdbe690271c4ec9bc172c994ff5f6e5808c4 | test/test_assetstore_model_override.py | test/test_assetstore_model_override.py | import pytest
from girder.models.file import File
from girder.models.model_base import Model
from girder.utility import assetstore_utilities
from girder.utility.model_importer import ModelImporter
from girder.utility.abstract_assetstore_adapter import AbstractAssetstoreAdapter
class Fake(Model):
def initialize(self):
self.name = 'fake_collection'
def validate(self, doc):
return doc
class FakeAdapter(AbstractAssetstoreAdapter):
def __init__(self, assetstore):
self.the_assetstore = assetstore
@pytest.fixture
def fakeModel(db):
ModelImporter.registerModel('fake', Fake(), plugin='fake_plugin')
yield Fake().save({
'foo': 'bar',
'type': 'fake'
})
ModelImporter.unregisterModel('fake', plugin='fake_plugin')
@pytest.fixture
def fakeAdapter(db):
assetstore_utilities.setAssetstoreAdapter('fake', FakeAdapter)
yield
assetstore_utilities.removeAssetstoreAdapter('fake')
def testAssetstoreModelOverride(fakeModel, fakeAdapter, admin):
file = File().createFile(
creator=admin, item=None, name='a.out', size=0, assetstore=fakeModel,
assetstoreModel='fake', assetstoreModelPlugin='fake_plugin')
adapter = File().getAssetstoreAdapter(file)
assert adapter.the_assetstore == fakeModel
| import pytest
from girder.models.file import File
from girder.models.model_base import Model
from girder.utility import assetstore_utilities
from girder.utility.model_importer import ModelImporter
from girder.utility.abstract_assetstore_adapter import AbstractAssetstoreAdapter
class Fake(Model):
def initialize(self):
self.name = 'fake_collection'
def validate(self, doc):
return doc
class FakeAdapter(AbstractAssetstoreAdapter):
def __init__(self, assetstore):
self.the_assetstore = assetstore
@pytest.fixture
def fakeModel(db):
ModelImporter.registerModel('fake', Fake(), plugin='fake_plugin')
yield Fake
ModelImporter.unregisterModel('fake', plugin='fake_plugin')
@pytest.fixture
def fakeAdapter(db):
assetstore_utilities.setAssetstoreAdapter('fake', FakeAdapter)
yield
assetstore_utilities.removeAssetstoreAdapter('fake')
def testAssetstoreModelOverride(fakeModel, fakeAdapter, admin):
fakeAssetstore = fakeModel().save({
'foo': 'bar',
'type': 'fake'
})
file = File().createFile(
creator=admin, item=None, name='a.out', size=0, assetstore=fakeAssetstore,
assetstoreModel='fake', assetstoreModelPlugin='fake_plugin')
adapter = File().getAssetstoreAdapter(file)
assert isinstance(adapter, FakeAdapter)
assert adapter.the_assetstore == fakeAssetstore
| Improve clarity of fake assetstore model fixture | Improve clarity of fake assetstore model fixture
| Python | apache-2.0 | data-exp-lab/girder,girder/girder,manthey/girder,kotfic/girder,Xarthisius/girder,jbeezley/girder,girder/girder,manthey/girder,kotfic/girder,RafaelPalomar/girder,girder/girder,data-exp-lab/girder,girder/girder,manthey/girder,Xarthisius/girder,RafaelPalomar/girder,RafaelPalomar/girder,RafaelPalomar/girder,Kitware/girder,jbeezley/girder,data-exp-lab/girder,data-exp-lab/girder,data-exp-lab/girder,RafaelPalomar/girder,kotfic/girder,Kitware/girder,Xarthisius/girder,Xarthisius/girder,jbeezley/girder,Kitware/girder,Kitware/girder,manthey/girder,kotfic/girder,jbeezley/girder,Xarthisius/girder,kotfic/girder | import pytest
from girder.models.file import File
from girder.models.model_base import Model
from girder.utility import assetstore_utilities
from girder.utility.model_importer import ModelImporter
from girder.utility.abstract_assetstore_adapter import AbstractAssetstoreAdapter
class Fake(Model):
def initialize(self):
self.name = 'fake_collection'
def validate(self, doc):
return doc
class FakeAdapter(AbstractAssetstoreAdapter):
def __init__(self, assetstore):
self.the_assetstore = assetstore
@pytest.fixture
def fakeModel(db):
ModelImporter.registerModel('fake', Fake(), plugin='fake_plugin')
- yield Fake().save({
+ yield Fake
- 'foo': 'bar',
- 'type': 'fake'
- })
ModelImporter.unregisterModel('fake', plugin='fake_plugin')
@pytest.fixture
def fakeAdapter(db):
assetstore_utilities.setAssetstoreAdapter('fake', FakeAdapter)
yield
assetstore_utilities.removeAssetstoreAdapter('fake')
def testAssetstoreModelOverride(fakeModel, fakeAdapter, admin):
+ fakeAssetstore = fakeModel().save({
+ 'foo': 'bar',
+ 'type': 'fake'
+ })
file = File().createFile(
- creator=admin, item=None, name='a.out', size=0, assetstore=fakeModel,
+ creator=admin, item=None, name='a.out', size=0, assetstore=fakeAssetstore,
assetstoreModel='fake', assetstoreModelPlugin='fake_plugin')
adapter = File().getAssetstoreAdapter(file)
+ assert isinstance(adapter, FakeAdapter)
- assert adapter.the_assetstore == fakeModel
+ assert adapter.the_assetstore == fakeAssetstore
| Improve clarity of fake assetstore model fixture | ## Code Before:
import pytest
from girder.models.file import File
from girder.models.model_base import Model
from girder.utility import assetstore_utilities
from girder.utility.model_importer import ModelImporter
from girder.utility.abstract_assetstore_adapter import AbstractAssetstoreAdapter
class Fake(Model):
def initialize(self):
self.name = 'fake_collection'
def validate(self, doc):
return doc
class FakeAdapter(AbstractAssetstoreAdapter):
def __init__(self, assetstore):
self.the_assetstore = assetstore
@pytest.fixture
def fakeModel(db):
ModelImporter.registerModel('fake', Fake(), plugin='fake_plugin')
yield Fake().save({
'foo': 'bar',
'type': 'fake'
})
ModelImporter.unregisterModel('fake', plugin='fake_plugin')
@pytest.fixture
def fakeAdapter(db):
assetstore_utilities.setAssetstoreAdapter('fake', FakeAdapter)
yield
assetstore_utilities.removeAssetstoreAdapter('fake')
def testAssetstoreModelOverride(fakeModel, fakeAdapter, admin):
file = File().createFile(
creator=admin, item=None, name='a.out', size=0, assetstore=fakeModel,
assetstoreModel='fake', assetstoreModelPlugin='fake_plugin')
adapter = File().getAssetstoreAdapter(file)
assert adapter.the_assetstore == fakeModel
## Instruction:
Improve clarity of fake assetstore model fixture
## Code After:
import pytest
from girder.models.file import File
from girder.models.model_base import Model
from girder.utility import assetstore_utilities
from girder.utility.model_importer import ModelImporter
from girder.utility.abstract_assetstore_adapter import AbstractAssetstoreAdapter
class Fake(Model):
def initialize(self):
self.name = 'fake_collection'
def validate(self, doc):
return doc
class FakeAdapter(AbstractAssetstoreAdapter):
def __init__(self, assetstore):
self.the_assetstore = assetstore
@pytest.fixture
def fakeModel(db):
ModelImporter.registerModel('fake', Fake(), plugin='fake_plugin')
yield Fake
ModelImporter.unregisterModel('fake', plugin='fake_plugin')
@pytest.fixture
def fakeAdapter(db):
assetstore_utilities.setAssetstoreAdapter('fake', FakeAdapter)
yield
assetstore_utilities.removeAssetstoreAdapter('fake')
def testAssetstoreModelOverride(fakeModel, fakeAdapter, admin):
fakeAssetstore = fakeModel().save({
'foo': 'bar',
'type': 'fake'
})
file = File().createFile(
creator=admin, item=None, name='a.out', size=0, assetstore=fakeAssetstore,
assetstoreModel='fake', assetstoreModelPlugin='fake_plugin')
adapter = File().getAssetstoreAdapter(file)
assert isinstance(adapter, FakeAdapter)
assert adapter.the_assetstore == fakeAssetstore
| import pytest
from girder.models.file import File
from girder.models.model_base import Model
from girder.utility import assetstore_utilities
from girder.utility.model_importer import ModelImporter
from girder.utility.abstract_assetstore_adapter import AbstractAssetstoreAdapter
class Fake(Model):
def initialize(self):
self.name = 'fake_collection'
def validate(self, doc):
return doc
class FakeAdapter(AbstractAssetstoreAdapter):
def __init__(self, assetstore):
self.the_assetstore = assetstore
@pytest.fixture
def fakeModel(db):
ModelImporter.registerModel('fake', Fake(), plugin='fake_plugin')
- yield Fake().save({
? ---------
+ yield Fake
- 'foo': 'bar',
- 'type': 'fake'
- })
ModelImporter.unregisterModel('fake', plugin='fake_plugin')
@pytest.fixture
def fakeAdapter(db):
assetstore_utilities.setAssetstoreAdapter('fake', FakeAdapter)
yield
assetstore_utilities.removeAssetstoreAdapter('fake')
def testAssetstoreModelOverride(fakeModel, fakeAdapter, admin):
+ fakeAssetstore = fakeModel().save({
+ 'foo': 'bar',
+ 'type': 'fake'
+ })
file = File().createFile(
- creator=admin, item=None, name='a.out', size=0, assetstore=fakeModel,
? ^ ^ -
+ creator=admin, item=None, name='a.out', size=0, assetstore=fakeAssetstore,
? ^^^^^^^ ^
assetstoreModel='fake', assetstoreModelPlugin='fake_plugin')
adapter = File().getAssetstoreAdapter(file)
+ assert isinstance(adapter, FakeAdapter)
- assert adapter.the_assetstore == fakeModel
? ^ ^ -
+ assert adapter.the_assetstore == fakeAssetstore
? ^^^^^^^ ^
|
c59fdbe03341843cbc9eb23d71c84376e71d55a1 | conda_env/main_env.py | conda_env/main_env.py | from __future__ import print_function, division, absolute_import
import argparse
from argparse import RawDescriptionHelpFormatter
import sys
from conda.cli import common
description = """
Handles interacting with Conda environments.
"""
example = """
examples:
conda env list
conda env list --json
"""
def configure_parser():
p = argparse.ArgumentParser()
sub_parsers = p.add_subparsers()
l = sub_parsers.add_parser(
'list',
formatter_class=RawDescriptionHelpFormatter,
description=description,
help=description,
epilog=example,
)
common.add_parser_json(l)
return p
def main():
args = configure_parser().parse_args()
info_dict = {'envs': []}
common.handle_envs_list(args, info_dict['envs'])
if args.json:
common.stdout_json(info_dict)
if __name__ == '__main__':
sys.exit(main())
| from __future__ import print_function, division, absolute_import
import argparse
from argparse import RawDescriptionHelpFormatter
import sys
from conda.cli import common
description = """
Handles interacting with Conda environments.
"""
example = """
examples:
conda env list
conda env list --json
"""
def configure_parser():
p = argparse.ArgumentParser()
sub_parsers = p.add_subparsers()
l = sub_parsers.add_parser(
'list',
formatter_class=RawDescriptionHelpFormatter,
description=description,
help=description,
epilog=example,
)
common.add_parser_json(l)
return p
def main():
args = configure_parser().parse_args()
info_dict = {'envs': []}
common.handle_envs_list(info_dict['envs'], not args.json)
if args.json:
common.stdout_json(info_dict)
if __name__ == '__main__':
sys.exit(main())
| Update to work with the latest iteration | Update to work with the latest iteration
| Python | bsd-3-clause | ESSS/conda-env,conda/conda-env,conda/conda-env,dan-blanchard/conda-env,asmeurer/conda-env,nicoddemus/conda-env,isaac-kit/conda-env,phobson/conda-env,dan-blanchard/conda-env,asmeurer/conda-env,phobson/conda-env,nicoddemus/conda-env,ESSS/conda-env,mikecroucher/conda-env,mikecroucher/conda-env,isaac-kit/conda-env | from __future__ import print_function, division, absolute_import
import argparse
from argparse import RawDescriptionHelpFormatter
import sys
from conda.cli import common
description = """
Handles interacting with Conda environments.
"""
example = """
examples:
conda env list
conda env list --json
"""
def configure_parser():
p = argparse.ArgumentParser()
sub_parsers = p.add_subparsers()
l = sub_parsers.add_parser(
'list',
formatter_class=RawDescriptionHelpFormatter,
description=description,
help=description,
epilog=example,
)
common.add_parser_json(l)
return p
def main():
args = configure_parser().parse_args()
info_dict = {'envs': []}
- common.handle_envs_list(args, info_dict['envs'])
+ common.handle_envs_list(info_dict['envs'], not args.json)
if args.json:
common.stdout_json(info_dict)
if __name__ == '__main__':
sys.exit(main())
| Update to work with the latest iteration | ## Code Before:
from __future__ import print_function, division, absolute_import
import argparse
from argparse import RawDescriptionHelpFormatter
import sys
from conda.cli import common
description = """
Handles interacting with Conda environments.
"""
example = """
examples:
conda env list
conda env list --json
"""
def configure_parser():
p = argparse.ArgumentParser()
sub_parsers = p.add_subparsers()
l = sub_parsers.add_parser(
'list',
formatter_class=RawDescriptionHelpFormatter,
description=description,
help=description,
epilog=example,
)
common.add_parser_json(l)
return p
def main():
args = configure_parser().parse_args()
info_dict = {'envs': []}
common.handle_envs_list(args, info_dict['envs'])
if args.json:
common.stdout_json(info_dict)
if __name__ == '__main__':
sys.exit(main())
## Instruction:
Update to work with the latest iteration
## Code After:
from __future__ import print_function, division, absolute_import
import argparse
from argparse import RawDescriptionHelpFormatter
import sys
from conda.cli import common
description = """
Handles interacting with Conda environments.
"""
example = """
examples:
conda env list
conda env list --json
"""
def configure_parser():
p = argparse.ArgumentParser()
sub_parsers = p.add_subparsers()
l = sub_parsers.add_parser(
'list',
formatter_class=RawDescriptionHelpFormatter,
description=description,
help=description,
epilog=example,
)
common.add_parser_json(l)
return p
def main():
args = configure_parser().parse_args()
info_dict = {'envs': []}
common.handle_envs_list(info_dict['envs'], not args.json)
if args.json:
common.stdout_json(info_dict)
if __name__ == '__main__':
sys.exit(main())
| from __future__ import print_function, division, absolute_import
import argparse
from argparse import RawDescriptionHelpFormatter
import sys
from conda.cli import common
description = """
Handles interacting with Conda environments.
"""
example = """
examples:
conda env list
conda env list --json
"""
def configure_parser():
p = argparse.ArgumentParser()
sub_parsers = p.add_subparsers()
l = sub_parsers.add_parser(
'list',
formatter_class=RawDescriptionHelpFormatter,
description=description,
help=description,
epilog=example,
)
common.add_parser_json(l)
return p
def main():
args = configure_parser().parse_args()
info_dict = {'envs': []}
- common.handle_envs_list(args, info_dict['envs'])
? ------
+ common.handle_envs_list(info_dict['envs'], not args.json)
? +++++++++++++++
if args.json:
common.stdout_json(info_dict)
if __name__ == '__main__':
sys.exit(main()) |
59fa966d43e4fd66669c3390464f60f323cf2865 | tests/changes/api/serializer/models/test_command.py | tests/changes/api/serializer/models/test_command.py | from datetime import datetime
from changes.api.serializer import serialize
from changes.config import db
from changes.models import Command
from changes.testutils import TestCase
class CommandSerializerTest(TestCase):
def test_simple(self):
project = self.create_project()
build = self.create_build(project)
job = self.create_job(build)
jobphase = self.create_jobphase(job)
jobstep = self.create_jobstep(jobphase)
command = Command(
label='echo 1',
jobstep_id=jobstep.id,
cwd='/home/foobar',
script='echo 1',
date_created=datetime(2013, 9, 19, 22, 15, 22),
artifacts=['junit.xml'],
)
db.session.add(command)
db.session.flush()
result = serialize(command)
assert result['id'] == command.id.hex
assert result['dateCreated'] == '2013-09-19T22:15:22'
assert result['cwd'] == command.cwd
assert result['script'] == command.script
| from datetime import datetime
from changes.api.serializer import serialize
from changes.config import db
from changes.models import Command
from changes.testutils import TestCase
class CommandSerializerTest(TestCase):
def test_simple(self):
project = self.create_project()
build = self.create_build(project)
job = self.create_job(build)
jobphase = self.create_jobphase(job)
jobstep = self.create_jobstep(jobphase)
command = Command(
label='echo 1',
jobstep_id=jobstep.id,
cwd='/home/foobar',
env={'foo': 'bar'},
script='echo 1',
date_created=datetime(2013, 9, 19, 22, 15, 22),
artifacts=['junit.xml'],
)
db.session.add(command)
db.session.flush()
result = serialize(command)
assert result['id'] == command.id.hex
assert result['dateCreated'] == '2013-09-19T22:15:22'
assert result['cwd'] == command.cwd
assert result['env'] == {'foo': 'bar'}
assert result['script'] == command.script
| Add tests for env serialization | Add tests for env serialization
| Python | apache-2.0 | dropbox/changes,bowlofstew/changes,wfxiang08/changes,bowlofstew/changes,bowlofstew/changes,dropbox/changes,wfxiang08/changes,wfxiang08/changes,dropbox/changes,bowlofstew/changes,dropbox/changes,wfxiang08/changes | from datetime import datetime
from changes.api.serializer import serialize
from changes.config import db
from changes.models import Command
from changes.testutils import TestCase
class CommandSerializerTest(TestCase):
def test_simple(self):
project = self.create_project()
build = self.create_build(project)
job = self.create_job(build)
jobphase = self.create_jobphase(job)
jobstep = self.create_jobstep(jobphase)
command = Command(
label='echo 1',
jobstep_id=jobstep.id,
cwd='/home/foobar',
+ env={'foo': 'bar'},
script='echo 1',
date_created=datetime(2013, 9, 19, 22, 15, 22),
artifacts=['junit.xml'],
)
db.session.add(command)
db.session.flush()
result = serialize(command)
assert result['id'] == command.id.hex
assert result['dateCreated'] == '2013-09-19T22:15:22'
assert result['cwd'] == command.cwd
+ assert result['env'] == {'foo': 'bar'}
assert result['script'] == command.script
| Add tests for env serialization | ## Code Before:
from datetime import datetime
from changes.api.serializer import serialize
from changes.config import db
from changes.models import Command
from changes.testutils import TestCase
class CommandSerializerTest(TestCase):
def test_simple(self):
project = self.create_project()
build = self.create_build(project)
job = self.create_job(build)
jobphase = self.create_jobphase(job)
jobstep = self.create_jobstep(jobphase)
command = Command(
label='echo 1',
jobstep_id=jobstep.id,
cwd='/home/foobar',
script='echo 1',
date_created=datetime(2013, 9, 19, 22, 15, 22),
artifacts=['junit.xml'],
)
db.session.add(command)
db.session.flush()
result = serialize(command)
assert result['id'] == command.id.hex
assert result['dateCreated'] == '2013-09-19T22:15:22'
assert result['cwd'] == command.cwd
assert result['script'] == command.script
## Instruction:
Add tests for env serialization
## Code After:
from datetime import datetime
from changes.api.serializer import serialize
from changes.config import db
from changes.models import Command
from changes.testutils import TestCase
class CommandSerializerTest(TestCase):
def test_simple(self):
project = self.create_project()
build = self.create_build(project)
job = self.create_job(build)
jobphase = self.create_jobphase(job)
jobstep = self.create_jobstep(jobphase)
command = Command(
label='echo 1',
jobstep_id=jobstep.id,
cwd='/home/foobar',
env={'foo': 'bar'},
script='echo 1',
date_created=datetime(2013, 9, 19, 22, 15, 22),
artifacts=['junit.xml'],
)
db.session.add(command)
db.session.flush()
result = serialize(command)
assert result['id'] == command.id.hex
assert result['dateCreated'] == '2013-09-19T22:15:22'
assert result['cwd'] == command.cwd
assert result['env'] == {'foo': 'bar'}
assert result['script'] == command.script
| from datetime import datetime
from changes.api.serializer import serialize
from changes.config import db
from changes.models import Command
from changes.testutils import TestCase
class CommandSerializerTest(TestCase):
def test_simple(self):
project = self.create_project()
build = self.create_build(project)
job = self.create_job(build)
jobphase = self.create_jobphase(job)
jobstep = self.create_jobstep(jobphase)
command = Command(
label='echo 1',
jobstep_id=jobstep.id,
cwd='/home/foobar',
+ env={'foo': 'bar'},
script='echo 1',
date_created=datetime(2013, 9, 19, 22, 15, 22),
artifacts=['junit.xml'],
)
db.session.add(command)
db.session.flush()
result = serialize(command)
assert result['id'] == command.id.hex
assert result['dateCreated'] == '2013-09-19T22:15:22'
assert result['cwd'] == command.cwd
+ assert result['env'] == {'foo': 'bar'}
assert result['script'] == command.script |
89b54d9c7fec213465446148e39612a2ac659ca2 | test/common/test_openstack.py | test/common/test_openstack.py | import sys
import unittest
from mock import Mock
from libcloud.common.openstack import OpenStackBaseConnection
class OpenStackBaseConnectionTest(unittest.TestCase):
def setUp(self):
self.timeout = 10
OpenStackBaseConnection.conn_classes = (None, Mock())
self.connection = OpenStackBaseConnection('foo', 'bar',
timeout=self.timeout,
ex_force_auth_url='https://127.0.0.1')
self.connection.driver = Mock()
self.connection.driver.name = 'OpenStackDriver'
def test_base_connection_timeout(self):
self.connection.connect()
self.assertEquals(self.connection.timeout, self.timeout)
self.connection.conn_classes[1].assert_called_with(host='127.0.0.1',
port=443,
timeout=10)
if __name__ == '__main__':
sys.exit(unittest.main())
| import sys
import unittest
from mock import Mock
from libcloud.common.openstack import OpenStackBaseConnection
from libcloud.utils.py3 import PY25
class OpenStackBaseConnectionTest(unittest.TestCase):
def setUp(self):
self.timeout = 10
OpenStackBaseConnection.conn_classes = (None, Mock())
self.connection = OpenStackBaseConnection('foo', 'bar',
timeout=self.timeout,
ex_force_auth_url='https://127.0.0.1')
self.connection.driver = Mock()
self.connection.driver.name = 'OpenStackDriver'
def test_base_connection_timeout(self):
self.connection.connect()
self.assertEquals(self.connection.timeout, self.timeout)
if PY25:
self.connection.conn_classes[1].assert_called_with(host='127.0.0.1',
port=443)
else:
self.connection.conn_classes[1].assert_called_with(host='127.0.0.1',
port=443,
timeout=10)
if __name__ == '__main__':
sys.exit(unittest.main())
| Fix test so it works with python 2.5. | Fix test so it works with python 2.5.
git-svn-id: 9ad005ce451fa0ce30ad6352b03eb45b36893355@1342997 13f79535-47bb-0310-9956-ffa450edef68
| Python | apache-2.0 | Jc2k/libcloud,marcinzaremba/libcloud,Scalr/libcloud,mathspace/libcloud,Verizon/libcloud,DimensionDataCBUSydney/libcloud,Cloud-Elasticity-Services/as-libcloud,lochiiconnectivity/libcloud,MrBasset/libcloud,sfriesel/libcloud,wrigri/libcloud,Itxaka/libcloud,erjohnso/libcloud,jerryblakley/libcloud,Scalr/libcloud,marcinzaremba/libcloud,JamesGuthrie/libcloud,watermelo/libcloud,iPlantCollaborativeOpenSource/libcloud,StackPointCloud/libcloud,niteoweb/libcloud,atsaki/libcloud,pquentin/libcloud,mistio/libcloud,wrigri/libcloud,cryptickp/libcloud,illfelder/libcloud,carletes/libcloud,andrewsomething/libcloud,kater169/libcloud,Itxaka/libcloud,aviweit/libcloud,apache/libcloud,illfelder/libcloud,SecurityCompass/libcloud,niteoweb/libcloud,SecurityCompass/libcloud,wrigri/libcloud,mtekel/libcloud,schaubl/libcloud,mistio/libcloud,wuyuewen/libcloud,ZuluPro/libcloud,vongazman/libcloud,munkiat/libcloud,cloudControl/libcloud,mathspace/libcloud,DimensionDataCBUSydney/libcloud,sgammon/libcloud,ninefold/libcloud,lochiiconnectivity/libcloud,ByteInternet/libcloud,jimbobhickville/libcloud,mtekel/libcloud,sahildua2305/libcloud,sahildua2305/libcloud,sahildua2305/libcloud,aleGpereira/libcloud,StackPointCloud/libcloud,kater169/libcloud,ClusterHQ/libcloud,niteoweb/libcloud,andrewsomething/libcloud,Scalr/libcloud,ByteInternet/libcloud,DimensionDataCBUSydney/libcloud,dcorbacho/libcloud,carletes/libcloud,carletes/libcloud,Verizon/libcloud,jimbobhickville/libcloud,wido/libcloud,iPlantCollaborativeOpenSource/libcloud,wuyuewen/libcloud,schaubl/libcloud,Kami/libcloud,wuyuewen/libcloud,munkiat/libcloud,sergiorua/libcloud,munkiat/libcloud,erjohnso/libcloud,pantheon-systems/libcloud,mathspace/libcloud,aviweit/libcloud,sergiorua/libcloud,thesquelched/libcloud,aviweit/libcloud,SecurityCompass/libcloud,mgogoulos/libcloud,thesquelched/libcloud,kater169/libcloud,curoverse/libcloud,NexusIS/libcloud,jerryblakley/libcloud,Kami/libcloud,marcinzaremba/libcloud,erjohnso/libcloud,cryptickp/libcloud,samuelchong/libcloud,aleGpereira/libcloud,curoverse/libcloud,sfriesel/libcloud,briancurtin/libcloud,samuelchong/libcloud,schaubl/libcloud,supertom/libcloud,vongazman/libcloud,sgammon/libcloud,MrBasset/libcloud,NexusIS/libcloud,Cloud-Elasticity-Services/as-libcloud,ZuluPro/libcloud,curoverse/libcloud,aleGpereira/libcloud,watermelo/libcloud,cloudControl/libcloud,pquentin/libcloud,dcorbacho/libcloud,apache/libcloud,JamesGuthrie/libcloud,briancurtin/libcloud,ZuluPro/libcloud,cloudControl/libcloud,t-tran/libcloud,smaffulli/libcloud,pantheon-systems/libcloud,watermelo/libcloud,briancurtin/libcloud,iPlantCollaborativeOpenSource/libcloud,Cloud-Elasticity-Services/as-libcloud,jimbobhickville/libcloud,StackPointCloud/libcloud,mistio/libcloud,vongazman/libcloud,andrewsomething/libcloud,atsaki/libcloud,supertom/libcloud,Jc2k/libcloud,techhat/libcloud,thesquelched/libcloud,pantheon-systems/libcloud,Verizon/libcloud,mbrukman/libcloud,techhat/libcloud,dcorbacho/libcloud,ByteInternet/libcloud,smaffulli/libcloud,t-tran/libcloud,wido/libcloud,atsaki/libcloud,mtekel/libcloud,Kami/libcloud,techhat/libcloud,smaffulli/libcloud,sfriesel/libcloud,t-tran/libcloud,ClusterHQ/libcloud,mbrukman/libcloud,mgogoulos/libcloud,apache/libcloud,pquentin/libcloud,NexusIS/libcloud,sergiorua/libcloud,mbrukman/libcloud,jerryblakley/libcloud,supertom/libcloud,mgogoulos/libcloud,MrBasset/libcloud,JamesGuthrie/libcloud,ninefold/libcloud,samuelchong/libcloud,lochiiconnectivity/libcloud,cryptickp/libcloud,illfelder/libcloud,Itxaka/libcloud,wido/libcloud | import sys
import unittest
from mock import Mock
from libcloud.common.openstack import OpenStackBaseConnection
+ from libcloud.utils.py3 import PY25
class OpenStackBaseConnectionTest(unittest.TestCase):
def setUp(self):
self.timeout = 10
OpenStackBaseConnection.conn_classes = (None, Mock())
self.connection = OpenStackBaseConnection('foo', 'bar',
timeout=self.timeout,
ex_force_auth_url='https://127.0.0.1')
self.connection.driver = Mock()
self.connection.driver.name = 'OpenStackDriver'
def test_base_connection_timeout(self):
self.connection.connect()
self.assertEquals(self.connection.timeout, self.timeout)
+ if PY25:
- self.connection.conn_classes[1].assert_called_with(host='127.0.0.1',
+ self.connection.conn_classes[1].assert_called_with(host='127.0.0.1',
+ port=443)
+ else:
+ self.connection.conn_classes[1].assert_called_with(host='127.0.0.1',
- port=443,
+ port=443,
- timeout=10)
+ timeout=10)
if __name__ == '__main__':
sys.exit(unittest.main())
| Fix test so it works with python 2.5. | ## Code Before:
import sys
import unittest
from mock import Mock
from libcloud.common.openstack import OpenStackBaseConnection
class OpenStackBaseConnectionTest(unittest.TestCase):
def setUp(self):
self.timeout = 10
OpenStackBaseConnection.conn_classes = (None, Mock())
self.connection = OpenStackBaseConnection('foo', 'bar',
timeout=self.timeout,
ex_force_auth_url='https://127.0.0.1')
self.connection.driver = Mock()
self.connection.driver.name = 'OpenStackDriver'
def test_base_connection_timeout(self):
self.connection.connect()
self.assertEquals(self.connection.timeout, self.timeout)
self.connection.conn_classes[1].assert_called_with(host='127.0.0.1',
port=443,
timeout=10)
if __name__ == '__main__':
sys.exit(unittest.main())
## Instruction:
Fix test so it works with python 2.5.
## Code After:
import sys
import unittest
from mock import Mock
from libcloud.common.openstack import OpenStackBaseConnection
from libcloud.utils.py3 import PY25
class OpenStackBaseConnectionTest(unittest.TestCase):
def setUp(self):
self.timeout = 10
OpenStackBaseConnection.conn_classes = (None, Mock())
self.connection = OpenStackBaseConnection('foo', 'bar',
timeout=self.timeout,
ex_force_auth_url='https://127.0.0.1')
self.connection.driver = Mock()
self.connection.driver.name = 'OpenStackDriver'
def test_base_connection_timeout(self):
self.connection.connect()
self.assertEquals(self.connection.timeout, self.timeout)
if PY25:
self.connection.conn_classes[1].assert_called_with(host='127.0.0.1',
port=443)
else:
self.connection.conn_classes[1].assert_called_with(host='127.0.0.1',
port=443,
timeout=10)
if __name__ == '__main__':
sys.exit(unittest.main())
| import sys
import unittest
from mock import Mock
from libcloud.common.openstack import OpenStackBaseConnection
+ from libcloud.utils.py3 import PY25
class OpenStackBaseConnectionTest(unittest.TestCase):
def setUp(self):
self.timeout = 10
OpenStackBaseConnection.conn_classes = (None, Mock())
self.connection = OpenStackBaseConnection('foo', 'bar',
timeout=self.timeout,
ex_force_auth_url='https://127.0.0.1')
self.connection.driver = Mock()
self.connection.driver.name = 'OpenStackDriver'
def test_base_connection_timeout(self):
self.connection.connect()
self.assertEquals(self.connection.timeout, self.timeout)
+ if PY25:
- self.connection.conn_classes[1].assert_called_with(host='127.0.0.1',
+ self.connection.conn_classes[1].assert_called_with(host='127.0.0.1',
? ++++
+ port=443)
+ else:
+ self.connection.conn_classes[1].assert_called_with(host='127.0.0.1',
- port=443,
+ port=443,
? ++++
- timeout=10)
+ timeout=10)
? ++++
if __name__ == '__main__':
sys.exit(unittest.main()) |
2fbd90a9995e8552e818e53d3b213e4cfef470de | molly/installer/dbcreate.py | molly/installer/dbcreate.py |
from molly.installer.utils import quiet_exec, CommandFailed
def create(dba_user, dba_pass, username, password, database):
creds = []
if dba_user:
creds += ['-U', dba_user]
if dba_pass:
os.environ['PGPASSWORD'] = dba_pass
try:
quiet_exec(['psql'] + creds + ['-c',"CREATE USER %s WITH PASSWORD '%s';" % (username, password)], 'dbcreate')
except CommandFailed:
pass
quiet_exec(['psql'] + creds + ['-c',"ALTER ROLE %s WITH PASSWORD '%s';" % (username, password)], 'dbcreate')
try:
quiet_exec(['createdb'] + creds + ['-T','template_postgis',database], 'dbcreate')
except CommandFailed:
quiet_exec(['dropdb'] + creds + [database], 'dbcreate')
quiet_exec(['createdb'] + creds + ['-T','template_postgis',database], 'dbcreate')
quiet_exec(['psql'] + creds + ['-c',"GRANT ALL ON DATABASE %s TO %s;" % (database, username)], 'dbcreate')
if dba_pass:
del os.environ['PGPASSWORD']
|
import os
from molly.installer.utils import quiet_exec, CommandFailed
def create(dba_user, dba_pass, username, password, database):
creds = []
if dba_user:
creds += ['-U', dba_user]
if dba_pass:
os.environ['PGPASSWORD'] = dba_pass
try:
quiet_exec(['psql'] + creds + ['-c',"CREATE USER %s WITH PASSWORD '%s';" % (username, password)], 'dbcreate')
except CommandFailed:
pass
quiet_exec(['psql'] + creds + ['-c',"ALTER ROLE %s WITH PASSWORD '%s';" % (username, password)], 'dbcreate')
try:
quiet_exec(['createdb'] + creds + ['-T','template_postgis',database], 'dbcreate')
except CommandFailed:
quiet_exec(['dropdb'] + creds + [database], 'dbcreate')
quiet_exec(['createdb'] + creds + ['-T','template_postgis',database], 'dbcreate')
quiet_exec(['psql'] + creds + ['-c',"GRANT ALL ON DATABASE %s TO %s;" % (database, username)], 'dbcreate')
if dba_pass:
del os.environ['PGPASSWORD']
| Fix broken setting of postgres password | Fix broken setting of postgres password
| Python | apache-2.0 | mollyproject/mollyproject,mollyproject/mollyproject,mollyproject/mollyproject | +
+ import os
from molly.installer.utils import quiet_exec, CommandFailed
def create(dba_user, dba_pass, username, password, database):
creds = []
if dba_user:
creds += ['-U', dba_user]
if dba_pass:
os.environ['PGPASSWORD'] = dba_pass
try:
quiet_exec(['psql'] + creds + ['-c',"CREATE USER %s WITH PASSWORD '%s';" % (username, password)], 'dbcreate')
except CommandFailed:
pass
quiet_exec(['psql'] + creds + ['-c',"ALTER ROLE %s WITH PASSWORD '%s';" % (username, password)], 'dbcreate')
try:
quiet_exec(['createdb'] + creds + ['-T','template_postgis',database], 'dbcreate')
except CommandFailed:
quiet_exec(['dropdb'] + creds + [database], 'dbcreate')
quiet_exec(['createdb'] + creds + ['-T','template_postgis',database], 'dbcreate')
quiet_exec(['psql'] + creds + ['-c',"GRANT ALL ON DATABASE %s TO %s;" % (database, username)], 'dbcreate')
if dba_pass:
del os.environ['PGPASSWORD']
| Fix broken setting of postgres password | ## Code Before:
from molly.installer.utils import quiet_exec, CommandFailed
def create(dba_user, dba_pass, username, password, database):
creds = []
if dba_user:
creds += ['-U', dba_user]
if dba_pass:
os.environ['PGPASSWORD'] = dba_pass
try:
quiet_exec(['psql'] + creds + ['-c',"CREATE USER %s WITH PASSWORD '%s';" % (username, password)], 'dbcreate')
except CommandFailed:
pass
quiet_exec(['psql'] + creds + ['-c',"ALTER ROLE %s WITH PASSWORD '%s';" % (username, password)], 'dbcreate')
try:
quiet_exec(['createdb'] + creds + ['-T','template_postgis',database], 'dbcreate')
except CommandFailed:
quiet_exec(['dropdb'] + creds + [database], 'dbcreate')
quiet_exec(['createdb'] + creds + ['-T','template_postgis',database], 'dbcreate')
quiet_exec(['psql'] + creds + ['-c',"GRANT ALL ON DATABASE %s TO %s;" % (database, username)], 'dbcreate')
if dba_pass:
del os.environ['PGPASSWORD']
## Instruction:
Fix broken setting of postgres password
## Code After:
import os
from molly.installer.utils import quiet_exec, CommandFailed
def create(dba_user, dba_pass, username, password, database):
creds = []
if dba_user:
creds += ['-U', dba_user]
if dba_pass:
os.environ['PGPASSWORD'] = dba_pass
try:
quiet_exec(['psql'] + creds + ['-c',"CREATE USER %s WITH PASSWORD '%s';" % (username, password)], 'dbcreate')
except CommandFailed:
pass
quiet_exec(['psql'] + creds + ['-c',"ALTER ROLE %s WITH PASSWORD '%s';" % (username, password)], 'dbcreate')
try:
quiet_exec(['createdb'] + creds + ['-T','template_postgis',database], 'dbcreate')
except CommandFailed:
quiet_exec(['dropdb'] + creds + [database], 'dbcreate')
quiet_exec(['createdb'] + creds + ['-T','template_postgis',database], 'dbcreate')
quiet_exec(['psql'] + creds + ['-c',"GRANT ALL ON DATABASE %s TO %s;" % (database, username)], 'dbcreate')
if dba_pass:
del os.environ['PGPASSWORD']
| +
+ import os
from molly.installer.utils import quiet_exec, CommandFailed
def create(dba_user, dba_pass, username, password, database):
creds = []
if dba_user:
creds += ['-U', dba_user]
if dba_pass:
os.environ['PGPASSWORD'] = dba_pass
try:
quiet_exec(['psql'] + creds + ['-c',"CREATE USER %s WITH PASSWORD '%s';" % (username, password)], 'dbcreate')
except CommandFailed:
pass
quiet_exec(['psql'] + creds + ['-c',"ALTER ROLE %s WITH PASSWORD '%s';" % (username, password)], 'dbcreate')
try:
quiet_exec(['createdb'] + creds + ['-T','template_postgis',database], 'dbcreate')
except CommandFailed:
quiet_exec(['dropdb'] + creds + [database], 'dbcreate')
quiet_exec(['createdb'] + creds + ['-T','template_postgis',database], 'dbcreate')
quiet_exec(['psql'] + creds + ['-c',"GRANT ALL ON DATABASE %s TO %s;" % (database, username)], 'dbcreate')
if dba_pass:
del os.environ['PGPASSWORD']
|
4c4b5a99e2fd02eff3451bf6c3a761163794a8ce | imageofmodel/admin.py | imageofmodel/admin.py |
from django.contrib import admin
from django import forms
from django.contrib.contenttypes.generic import GenericTabularInline, BaseGenericInlineFormSet
from models import ImageOfModel
class ImageFormset(BaseGenericInlineFormSet):
def clean(self):
if not self.files.values() and not self.instance.images.all():
raise forms.ValidationError(u'Загрузите хотябы одну фотографию')
class ImageOfModelInline(GenericTabularInline):
model = ImageOfModel
formset = ImageFormset
extra = 1 |
from django.contrib import admin
from django import forms
from django.contrib.contenttypes.generic import GenericTabularInline, BaseGenericInlineFormSet
from models import ImageOfModel
class ImageFormset(BaseGenericInlineFormSet):
def clean(self):
if not self.files.values() and not self.instance.images.all():
raise forms.ValidationError(u'Загрузите хотябы одну фотографию')
class ImageOfModelInline(GenericTabularInline):
model = ImageOfModel
formset = ImageFormset
extra = 1
class OptionalImageOfModelInline(GenericTabularInline):
model = ImageOfModel
extra = 1 | Add class OptionalImageOfModelInline for optional images | [+] Add class OptionalImageOfModelInline for optional images
| Python | bsd-3-clause | vixh/django-imageofmodel |
from django.contrib import admin
from django import forms
from django.contrib.contenttypes.generic import GenericTabularInline, BaseGenericInlineFormSet
from models import ImageOfModel
class ImageFormset(BaseGenericInlineFormSet):
def clean(self):
if not self.files.values() and not self.instance.images.all():
raise forms.ValidationError(u'Загрузите хотябы одну фотографию')
class ImageOfModelInline(GenericTabularInline):
model = ImageOfModel
formset = ImageFormset
extra = 1
+
+
+ class OptionalImageOfModelInline(GenericTabularInline):
+ model = ImageOfModel
+ extra = 1 | Add class OptionalImageOfModelInline for optional images | ## Code Before:
from django.contrib import admin
from django import forms
from django.contrib.contenttypes.generic import GenericTabularInline, BaseGenericInlineFormSet
from models import ImageOfModel
class ImageFormset(BaseGenericInlineFormSet):
def clean(self):
if not self.files.values() and not self.instance.images.all():
raise forms.ValidationError(u'Загрузите хотябы одну фотографию')
class ImageOfModelInline(GenericTabularInline):
model = ImageOfModel
formset = ImageFormset
extra = 1
## Instruction:
Add class OptionalImageOfModelInline for optional images
## Code After:
from django.contrib import admin
from django import forms
from django.contrib.contenttypes.generic import GenericTabularInline, BaseGenericInlineFormSet
from models import ImageOfModel
class ImageFormset(BaseGenericInlineFormSet):
def clean(self):
if not self.files.values() and not self.instance.images.all():
raise forms.ValidationError(u'Загрузите хотябы одну фотографию')
class ImageOfModelInline(GenericTabularInline):
model = ImageOfModel
formset = ImageFormset
extra = 1
class OptionalImageOfModelInline(GenericTabularInline):
model = ImageOfModel
extra = 1 |
from django.contrib import admin
from django import forms
from django.contrib.contenttypes.generic import GenericTabularInline, BaseGenericInlineFormSet
from models import ImageOfModel
class ImageFormset(BaseGenericInlineFormSet):
def clean(self):
if not self.files.values() and not self.instance.images.all():
raise forms.ValidationError(u'Загрузите хотябы одну фотографию')
class ImageOfModelInline(GenericTabularInline):
model = ImageOfModel
formset = ImageFormset
extra = 1
+
+
+ class OptionalImageOfModelInline(GenericTabularInline):
+ model = ImageOfModel
+ extra = 1 |
99d0f754b39bdddf58e44e669d24157227a43107 | heliotron/__init__.py | heliotron/__init__.py | from heliotron.bridge import Bridge
from heliotron.light import Light
import heliotron.presets
__all__ = ['Bridge', 'Light', 'presets']
| from heliotron.bridge import Bridge
from heliotron.light import Light
from heliotron import presets
__all__ = ['Bridge', 'Light', 'presets']
| Change module import to squash a code smell | Change module import to squash a code smell
| Python | mit | briancline/heliotron | from heliotron.bridge import Bridge
from heliotron.light import Light
- import heliotron.presets
+ from heliotron import presets
__all__ = ['Bridge', 'Light', 'presets']
| Change module import to squash a code smell | ## Code Before:
from heliotron.bridge import Bridge
from heliotron.light import Light
import heliotron.presets
__all__ = ['Bridge', 'Light', 'presets']
## Instruction:
Change module import to squash a code smell
## Code After:
from heliotron.bridge import Bridge
from heliotron.light import Light
from heliotron import presets
__all__ = ['Bridge', 'Light', 'presets']
| from heliotron.bridge import Bridge
from heliotron.light import Light
- import heliotron.presets
+ from heliotron import presets
__all__ = ['Bridge', 'Light', 'presets'] |
a1d71466d09e9e1ea2f75eae57e72e0000c65ffc | tests/run.py | tests/run.py | import sys
import django
from colour_runner.django_runner import ColourRunnerMixin
from django.conf import settings
settings.configure(
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
},
MIDDLEWARE_CLASSES=(),
TEMPLATE_DIRS=('tests/templates',),
)
if django.VERSION >= (1, 7):
django.setup()
try:
from django.test.runner import DiscoverRunner
except ImportError:
# Django < 1.6
from discover_runner import DiscoverRunner
class Runner(ColourRunnerMixin, DiscoverRunner):
pass
test_runner = Runner(verbosity=1)
failures = test_runner.run_tests(['tests'])
if failures:
sys.exit(1)
| import sys
import django
from colour_runner.django_runner import ColourRunnerMixin
from django.conf import settings
settings.configure(
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
},
MIDDLEWARE_CLASSES=(),
TEMPLATES=[
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': False,
'DIRS': ('tests/templates',),
},
]
)
if django.VERSION >= (1, 7):
django.setup()
try:
from django.test.runner import DiscoverRunner
except ImportError:
# Django < 1.6
from discover_runner import DiscoverRunner
class Runner(ColourRunnerMixin, DiscoverRunner):
pass
test_runner = Runner(verbosity=1)
failures = test_runner.run_tests(['tests'])
if failures:
sys.exit(1)
| Add new-style TEMPLATES setting for tests | Add new-style TEMPLATES setting for tests
| Python | bsd-2-clause | incuna/incuna-mail,incuna/incuna-mail | import sys
import django
from colour_runner.django_runner import ColourRunnerMixin
from django.conf import settings
settings.configure(
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
},
MIDDLEWARE_CLASSES=(),
- TEMPLATE_DIRS=('tests/templates',),
+ TEMPLATES=[
+ {
+ 'BACKEND': 'django.template.backends.django.DjangoTemplates',
+ 'APP_DIRS': False,
+ 'DIRS': ('tests/templates',),
+ },
+ ]
)
if django.VERSION >= (1, 7):
django.setup()
try:
from django.test.runner import DiscoverRunner
except ImportError:
# Django < 1.6
from discover_runner import DiscoverRunner
class Runner(ColourRunnerMixin, DiscoverRunner):
pass
test_runner = Runner(verbosity=1)
failures = test_runner.run_tests(['tests'])
if failures:
sys.exit(1)
| Add new-style TEMPLATES setting for tests | ## Code Before:
import sys
import django
from colour_runner.django_runner import ColourRunnerMixin
from django.conf import settings
settings.configure(
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
},
MIDDLEWARE_CLASSES=(),
TEMPLATE_DIRS=('tests/templates',),
)
if django.VERSION >= (1, 7):
django.setup()
try:
from django.test.runner import DiscoverRunner
except ImportError:
# Django < 1.6
from discover_runner import DiscoverRunner
class Runner(ColourRunnerMixin, DiscoverRunner):
pass
test_runner = Runner(verbosity=1)
failures = test_runner.run_tests(['tests'])
if failures:
sys.exit(1)
## Instruction:
Add new-style TEMPLATES setting for tests
## Code After:
import sys
import django
from colour_runner.django_runner import ColourRunnerMixin
from django.conf import settings
settings.configure(
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
},
MIDDLEWARE_CLASSES=(),
TEMPLATES=[
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': False,
'DIRS': ('tests/templates',),
},
]
)
if django.VERSION >= (1, 7):
django.setup()
try:
from django.test.runner import DiscoverRunner
except ImportError:
# Django < 1.6
from discover_runner import DiscoverRunner
class Runner(ColourRunnerMixin, DiscoverRunner):
pass
test_runner = Runner(verbosity=1)
failures = test_runner.run_tests(['tests'])
if failures:
sys.exit(1)
| import sys
import django
from colour_runner.django_runner import ColourRunnerMixin
from django.conf import settings
settings.configure(
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
},
MIDDLEWARE_CLASSES=(),
- TEMPLATE_DIRS=('tests/templates',),
+ TEMPLATES=[
+ {
+ 'BACKEND': 'django.template.backends.django.DjangoTemplates',
+ 'APP_DIRS': False,
+ 'DIRS': ('tests/templates',),
+ },
+ ]
)
if django.VERSION >= (1, 7):
django.setup()
try:
from django.test.runner import DiscoverRunner
except ImportError:
# Django < 1.6
from discover_runner import DiscoverRunner
class Runner(ColourRunnerMixin, DiscoverRunner):
pass
test_runner = Runner(verbosity=1)
failures = test_runner.run_tests(['tests'])
if failures:
sys.exit(1) |
9efa2ccc3067d20dc50fd5e3746b291cc670af90 | rembed/test/response_test.py | rembed/test/response_test.py | from rembed import response
from hamcrest import *
import pytest
def test_should_load_from_dictionary():
dict = {'title' : 'Bees'}
oembed_response = response.OEmbedResponse(dict)
assert_that(oembed_response.title, equal_to('Bees'))
def test_response_should_be_immutable():
dict = {'title' : 'Bees'}
oembed_response = response.OEmbedResponse(dict)
with pytest.raises(TypeError):
oembed_response.title = 'Wasps' | from rembed import response
from hamcrest import *
import pytest
def test_should_load_from_dictionary():
dict = {'type' : 'link', 'version' : '1.0'}
oembed_response = response.OEmbedResponse(dict)
assert_that(oembed_response.type, equal_to('link'))
def test_response_should_be_immutable():
dict = {'type' : 'link', 'version' : '1.0'}
oembed_response = response.OEmbedResponse(dict)
with pytest.raises(TypeError):
oembed_response.type = 'photo' | Make test match spec more closely | Make test match spec more closely
| Python | mit | tino/pyembed,pyembed/pyembed,pyembed/pyembed | from rembed import response
from hamcrest import *
import pytest
def test_should_load_from_dictionary():
- dict = {'title' : 'Bees'}
+ dict = {'type' : 'link', 'version' : '1.0'}
oembed_response = response.OEmbedResponse(dict)
- assert_that(oembed_response.title, equal_to('Bees'))
+ assert_that(oembed_response.type, equal_to('link'))
def test_response_should_be_immutable():
- dict = {'title' : 'Bees'}
+ dict = {'type' : 'link', 'version' : '1.0'}
oembed_response = response.OEmbedResponse(dict)
with pytest.raises(TypeError):
- oembed_response.title = 'Wasps'
+ oembed_response.type = 'photo' | Make test match spec more closely | ## Code Before:
from rembed import response
from hamcrest import *
import pytest
def test_should_load_from_dictionary():
dict = {'title' : 'Bees'}
oembed_response = response.OEmbedResponse(dict)
assert_that(oembed_response.title, equal_to('Bees'))
def test_response_should_be_immutable():
dict = {'title' : 'Bees'}
oembed_response = response.OEmbedResponse(dict)
with pytest.raises(TypeError):
oembed_response.title = 'Wasps'
## Instruction:
Make test match spec more closely
## Code After:
from rembed import response
from hamcrest import *
import pytest
def test_should_load_from_dictionary():
dict = {'type' : 'link', 'version' : '1.0'}
oembed_response = response.OEmbedResponse(dict)
assert_that(oembed_response.type, equal_to('link'))
def test_response_should_be_immutable():
dict = {'type' : 'link', 'version' : '1.0'}
oembed_response = response.OEmbedResponse(dict)
with pytest.raises(TypeError):
oembed_response.type = 'photo' | from rembed import response
from hamcrest import *
import pytest
def test_should_load_from_dictionary():
- dict = {'title' : 'Bees'}
+ dict = {'type' : 'link', 'version' : '1.0'}
oembed_response = response.OEmbedResponse(dict)
- assert_that(oembed_response.title, equal_to('Bees'))
? ^^^ ^^^^
+ assert_that(oembed_response.type, equal_to('link'))
? ^^ ^^^^
def test_response_should_be_immutable():
- dict = {'title' : 'Bees'}
+ dict = {'type' : 'link', 'version' : '1.0'}
oembed_response = response.OEmbedResponse(dict)
with pytest.raises(TypeError):
- oembed_response.title = 'Wasps'
? ^^^ --- ^
+ oembed_response.type = 'photo'
? ^^ ^^^^
|
1819f9cb080f847ea5d669571853b28d8fc1ce1c | Script/test_screenshot.py | Script/test_screenshot.py | import unittest
import os
import time
import shutil
import filecmp
import base64
import glob
import json
class ScreenShotTest(unittest.TestCase):
def test_screenshots(self):
generated_file_paths = glob.glob('build/Dev/Cpp/Test/Release/*.png')
for path in generated_file_paths:
name = os.path.basename(path)
self.assertTrue(filecmp.cmp('TestData/Tests/Windows/' + name, path), name + ' is not equal')
if __name__ == '__main__':
unittest.main()
| import sys
import unittest
import os
import time
import shutil
import filecmp
import base64
import glob
import json
class ScreenShotTest(unittest.TestCase):
def test_screenshots(self):
generated_file_paths = glob.glob('build/Dev/Cpp/Test/Release/*.png')
success = True
for path in generated_file_paths:
name = os.path.basename(path)
test_data_path = 'TestData/Tests/Windows/' + name
if os.path.exists(test_data_path):
is_same = filecmp.cmp(test_data_path, path)
if not is_same:
print(f'{name} is not equal.')
success = False
else:
print(f'{test_data_path} is not found.')
success = False
self.assertTrue(success)
if __name__ == '__main__':
unittest.main()
| Improve a script to test | Improve a script to test
| Python | mit | effekseer/Effekseer,effekseer/Effekseer,effekseer/Effekseer,effekseer/Effekseer,effekseer/Effekseer,effekseer/Effekseer,effekseer/Effekseer | + import sys
import unittest
import os
import time
import shutil
import filecmp
import base64
import glob
import json
+
class ScreenShotTest(unittest.TestCase):
def test_screenshots(self):
generated_file_paths = glob.glob('build/Dev/Cpp/Test/Release/*.png')
+ success = True
+
for path in generated_file_paths:
name = os.path.basename(path)
- self.assertTrue(filecmp.cmp('TestData/Tests/Windows/' + name, path), name + ' is not equal')
+ test_data_path = 'TestData/Tests/Windows/' + name
+
+ if os.path.exists(test_data_path):
+ is_same = filecmp.cmp(test_data_path, path)
+ if not is_same:
+ print(f'{name} is not equal.')
+ success = False
+ else:
+ print(f'{test_data_path} is not found.')
+ success = False
+
+ self.assertTrue(success)
if __name__ == '__main__':
unittest.main()
- | Improve a script to test | ## Code Before:
import unittest
import os
import time
import shutil
import filecmp
import base64
import glob
import json
class ScreenShotTest(unittest.TestCase):
def test_screenshots(self):
generated_file_paths = glob.glob('build/Dev/Cpp/Test/Release/*.png')
for path in generated_file_paths:
name = os.path.basename(path)
self.assertTrue(filecmp.cmp('TestData/Tests/Windows/' + name, path), name + ' is not equal')
if __name__ == '__main__':
unittest.main()
## Instruction:
Improve a script to test
## Code After:
import sys
import unittest
import os
import time
import shutil
import filecmp
import base64
import glob
import json
class ScreenShotTest(unittest.TestCase):
def test_screenshots(self):
generated_file_paths = glob.glob('build/Dev/Cpp/Test/Release/*.png')
success = True
for path in generated_file_paths:
name = os.path.basename(path)
test_data_path = 'TestData/Tests/Windows/' + name
if os.path.exists(test_data_path):
is_same = filecmp.cmp(test_data_path, path)
if not is_same:
print(f'{name} is not equal.')
success = False
else:
print(f'{test_data_path} is not found.')
success = False
self.assertTrue(success)
if __name__ == '__main__':
unittest.main()
| + import sys
import unittest
import os
import time
import shutil
import filecmp
import base64
import glob
import json
+
class ScreenShotTest(unittest.TestCase):
def test_screenshots(self):
generated_file_paths = glob.glob('build/Dev/Cpp/Test/Release/*.png')
+ success = True
+
for path in generated_file_paths:
name = os.path.basename(path)
- self.assertTrue(filecmp.cmp('TestData/Tests/Windows/' + name, path), name + ' is not equal')
+ test_data_path = 'TestData/Tests/Windows/' + name
+
+ if os.path.exists(test_data_path):
+ is_same = filecmp.cmp(test_data_path, path)
+ if not is_same:
+ print(f'{name} is not equal.')
+ success = False
+ else:
+ print(f'{test_data_path} is not found.')
+ success = False
+
+ self.assertTrue(success)
if __name__ == '__main__':
unittest.main()
- |
610ada5f26d7421c2b0dd16a8a14ac9c95e4ed8c | config/test/__init__.py | config/test/__init__.py | from SCons.Script import *
def run_tests(env):
import shlex
import subprocess
import sys
sys.exit(subprocess.call(shlex.split(env.get('TEST_COMMAND'))))
def generate(env):
import os
import distutils.spawn
python = distutils.spawn.find_executable('python3')
if not python: python = distutils.spawn.find_executable('python')
if not python: python = distutils.spawn.find_executable('python2')
cmd = python + ' tests/testHarness -C tests --diff-failed --view-failed ' \
'--view-unfiltered --save-failed --build'
if 'DOCKBOT_MASTER_PORT' in os.environ: cmd += ' --no-color'
env.CBAddVariables(('TEST_COMMAND', '`test` target command line', cmd))
if 'test' in COMMAND_LINE_TARGETS: env.CBAddConfigureCB(run_tests)
def exists(): return 1
| from SCons.Script import *
def run_tests(env):
import shlex
import subprocess
import sys
cmd = shlex.split(env.get('TEST_COMMAND'))
print('Executing:', cmd)
sys.exit(subprocess.call(cmd))
def generate(env):
import os
import distutils.spawn
python = distutils.spawn.find_executable('python3')
if not python: python = distutils.spawn.find_executable('python')
if not python: python = distutils.spawn.find_executable('python2')
if not python: python = 'python'
if env['PLATFORM'] == 'win32': python = python.replace('\\', '\\\\')
cmd = python + ' tests/testHarness -C tests --diff-failed --view-failed ' \
'--view-unfiltered --save-failed --build'
if 'DOCKBOT_MASTER_PORT' in os.environ: cmd += ' --no-color'
env.CBAddVariables(('TEST_COMMAND', '`test` target command line', cmd))
if 'test' in COMMAND_LINE_TARGETS: env.CBAddConfigureCB(run_tests)
def exists(): return 1
| Fix "test" target in Windows | Fix "test" target in Windows
| Python | lgpl-2.1 | CauldronDevelopmentLLC/cbang,CauldronDevelopmentLLC/cbang,CauldronDevelopmentLLC/cbang,CauldronDevelopmentLLC/cbang | from SCons.Script import *
def run_tests(env):
import shlex
import subprocess
import sys
- sys.exit(subprocess.call(shlex.split(env.get('TEST_COMMAND'))))
+ cmd = shlex.split(env.get('TEST_COMMAND'))
+ print('Executing:', cmd)
+ sys.exit(subprocess.call(cmd))
def generate(env):
import os
import distutils.spawn
python = distutils.spawn.find_executable('python3')
if not python: python = distutils.spawn.find_executable('python')
if not python: python = distutils.spawn.find_executable('python2')
+ if not python: python = 'python'
+ if env['PLATFORM'] == 'win32': python = python.replace('\\', '\\\\')
cmd = python + ' tests/testHarness -C tests --diff-failed --view-failed ' \
'--view-unfiltered --save-failed --build'
if 'DOCKBOT_MASTER_PORT' in os.environ: cmd += ' --no-color'
env.CBAddVariables(('TEST_COMMAND', '`test` target command line', cmd))
if 'test' in COMMAND_LINE_TARGETS: env.CBAddConfigureCB(run_tests)
def exists(): return 1
| Fix "test" target in Windows | ## Code Before:
from SCons.Script import *
def run_tests(env):
import shlex
import subprocess
import sys
sys.exit(subprocess.call(shlex.split(env.get('TEST_COMMAND'))))
def generate(env):
import os
import distutils.spawn
python = distutils.spawn.find_executable('python3')
if not python: python = distutils.spawn.find_executable('python')
if not python: python = distutils.spawn.find_executable('python2')
cmd = python + ' tests/testHarness -C tests --diff-failed --view-failed ' \
'--view-unfiltered --save-failed --build'
if 'DOCKBOT_MASTER_PORT' in os.environ: cmd += ' --no-color'
env.CBAddVariables(('TEST_COMMAND', '`test` target command line', cmd))
if 'test' in COMMAND_LINE_TARGETS: env.CBAddConfigureCB(run_tests)
def exists(): return 1
## Instruction:
Fix "test" target in Windows
## Code After:
from SCons.Script import *
def run_tests(env):
import shlex
import subprocess
import sys
cmd = shlex.split(env.get('TEST_COMMAND'))
print('Executing:', cmd)
sys.exit(subprocess.call(cmd))
def generate(env):
import os
import distutils.spawn
python = distutils.spawn.find_executable('python3')
if not python: python = distutils.spawn.find_executable('python')
if not python: python = distutils.spawn.find_executable('python2')
if not python: python = 'python'
if env['PLATFORM'] == 'win32': python = python.replace('\\', '\\\\')
cmd = python + ' tests/testHarness -C tests --diff-failed --view-failed ' \
'--view-unfiltered --save-failed --build'
if 'DOCKBOT_MASTER_PORT' in os.environ: cmd += ' --no-color'
env.CBAddVariables(('TEST_COMMAND', '`test` target command line', cmd))
if 'test' in COMMAND_LINE_TARGETS: env.CBAddConfigureCB(run_tests)
def exists(): return 1
| from SCons.Script import *
def run_tests(env):
import shlex
import subprocess
import sys
- sys.exit(subprocess.call(shlex.split(env.get('TEST_COMMAND'))))
+ cmd = shlex.split(env.get('TEST_COMMAND'))
+ print('Executing:', cmd)
+ sys.exit(subprocess.call(cmd))
def generate(env):
import os
import distutils.spawn
python = distutils.spawn.find_executable('python3')
if not python: python = distutils.spawn.find_executable('python')
if not python: python = distutils.spawn.find_executable('python2')
+ if not python: python = 'python'
+ if env['PLATFORM'] == 'win32': python = python.replace('\\', '\\\\')
cmd = python + ' tests/testHarness -C tests --diff-failed --view-failed ' \
'--view-unfiltered --save-failed --build'
if 'DOCKBOT_MASTER_PORT' in os.environ: cmd += ' --no-color'
env.CBAddVariables(('TEST_COMMAND', '`test` target command line', cmd))
if 'test' in COMMAND_LINE_TARGETS: env.CBAddConfigureCB(run_tests)
def exists(): return 1 |
151c3484da58fa02f7d2c69454be3cb4e3395d05 | recipes/recipe_modules/bot_update/tests/ensure_checkout.py | recipes/recipe_modules/bot_update/tests/ensure_checkout.py |
from recipe_engine import post_process
DEPS = [
'bot_update',
'gclient',
'recipe_engine/json',
]
def RunSteps(api):
api.gclient.set_config('depot_tools')
api.bot_update.ensure_checkout()
def GenTests(api):
yield (
api.test('basic') +
api.post_process(post_process.StatusCodeIn, 0) +
api.post_process(post_process.DropExpectation)
)
yield (
api.test('failure') +
api.override_step_data(
'bot_update',
api.json.output({'did_run': True}),
retcode=1) +
api.post_process(post_process.StatusCodeIn, 1) +
api.post_process(post_process.DropExpectation)
)
|
from recipe_engine import post_process
DEPS = [
'bot_update',
'gclient',
'recipe_engine/json',
]
def RunSteps(api):
api.gclient.set_config('depot_tools')
api.bot_update.ensure_checkout()
def GenTests(api):
yield (
api.test('basic') +
api.post_process(post_process.StatusSuccess) +
api.post_process(post_process.DropExpectation)
)
yield (
api.test('failure') +
api.override_step_data(
'bot_update',
api.json.output({'did_run': True}),
retcode=1) +
api.post_process(post_process.StatusAnyFailure) +
api.post_process(post_process.DropExpectation)
)
| Replace post-process checks with ones that are not deprecated | Replace post-process checks with ones that are not deprecated
R=40f3d43a28ebae3cb819288542e1c84d73d962d5@chromium.org
Bug: 899266
Change-Id: Ia9b1f38590d636fa2858a2bd0bbf75d6b2cfe8fa
Reviewed-on: https://chromium-review.googlesource.com/c/1483033
Reviewed-by: Robbie Iannucci <40f3d43a28ebae3cb819288542e1c84d73d962d5@chromium.org>
Reviewed-by: John Budorick <17d38a2d68c6a07a3ab0ce4a2873c5acefbd3dbb@chromium.org>
Commit-Queue: Sergiy Belozorov <aadb4a11584aa9878242ea5d9e4b7e3429654579@chromium.org>
| Python | bsd-3-clause | CoherentLabs/depot_tools,CoherentLabs/depot_tools |
from recipe_engine import post_process
DEPS = [
'bot_update',
'gclient',
'recipe_engine/json',
]
def RunSteps(api):
api.gclient.set_config('depot_tools')
api.bot_update.ensure_checkout()
def GenTests(api):
yield (
api.test('basic') +
- api.post_process(post_process.StatusCodeIn, 0) +
+ api.post_process(post_process.StatusSuccess) +
api.post_process(post_process.DropExpectation)
)
yield (
api.test('failure') +
api.override_step_data(
'bot_update',
api.json.output({'did_run': True}),
retcode=1) +
- api.post_process(post_process.StatusCodeIn, 1) +
+ api.post_process(post_process.StatusAnyFailure) +
api.post_process(post_process.DropExpectation)
)
| Replace post-process checks with ones that are not deprecated | ## Code Before:
from recipe_engine import post_process
DEPS = [
'bot_update',
'gclient',
'recipe_engine/json',
]
def RunSteps(api):
api.gclient.set_config('depot_tools')
api.bot_update.ensure_checkout()
def GenTests(api):
yield (
api.test('basic') +
api.post_process(post_process.StatusCodeIn, 0) +
api.post_process(post_process.DropExpectation)
)
yield (
api.test('failure') +
api.override_step_data(
'bot_update',
api.json.output({'did_run': True}),
retcode=1) +
api.post_process(post_process.StatusCodeIn, 1) +
api.post_process(post_process.DropExpectation)
)
## Instruction:
Replace post-process checks with ones that are not deprecated
## Code After:
from recipe_engine import post_process
DEPS = [
'bot_update',
'gclient',
'recipe_engine/json',
]
def RunSteps(api):
api.gclient.set_config('depot_tools')
api.bot_update.ensure_checkout()
def GenTests(api):
yield (
api.test('basic') +
api.post_process(post_process.StatusSuccess) +
api.post_process(post_process.DropExpectation)
)
yield (
api.test('failure') +
api.override_step_data(
'bot_update',
api.json.output({'did_run': True}),
retcode=1) +
api.post_process(post_process.StatusAnyFailure) +
api.post_process(post_process.DropExpectation)
)
|
from recipe_engine import post_process
DEPS = [
'bot_update',
'gclient',
'recipe_engine/json',
]
def RunSteps(api):
api.gclient.set_config('depot_tools')
api.bot_update.ensure_checkout()
def GenTests(api):
yield (
api.test('basic') +
- api.post_process(post_process.StatusCodeIn, 0) +
? ^^^ ^^^^^
+ api.post_process(post_process.StatusSuccess) +
? ^^^^ ^^
api.post_process(post_process.DropExpectation)
)
yield (
api.test('failure') +
api.override_step_data(
'bot_update',
api.json.output({'did_run': True}),
retcode=1) +
- api.post_process(post_process.StatusCodeIn, 1) +
? ^^^ -----
+ api.post_process(post_process.StatusAnyFailure) +
? ^^^^^^^^^
api.post_process(post_process.DropExpectation)
) |
64d599d6f7ca0aae6d95bf753a8421c7978276a2 | subliminal/__init__.py | subliminal/__init__.py | __title__ = 'subliminal'
__version__ = '1.0.dev0'
__author__ = 'Antoine Bertin'
__license__ = 'MIT'
__copyright__ = 'Copyright 2015, Antoine Bertin'
import logging
from .api import (ProviderPool, check_video, provider_manager, download_best_subtitles, download_subtitles,
list_subtitles, save_subtitles)
from .cache import region
from .exceptions import Error, ProviderError
from .providers import Provider
from .subtitle import Subtitle
from .video import SUBTITLE_EXTENSIONS, VIDEO_EXTENSIONS, Episode, Movie, Video, scan_video, scan_videos
logging.getLogger(__name__).addHandler(logging.NullHandler())
| __title__ = 'subliminal'
__version__ = '1.0.dev0'
__author__ = 'Antoine Bertin'
__license__ = 'MIT'
__copyright__ = 'Copyright 2015, Antoine Bertin'
import logging
from .api import (ProviderPool, check_video, provider_manager, download_best_subtitles, download_subtitles,
list_subtitles, save_subtitles)
from .cache import region
from .exceptions import Error, ProviderError
from .providers import Provider
from .subtitle import Subtitle, compute_score
from .video import SUBTITLE_EXTENSIONS, VIDEO_EXTENSIONS, Episode, Movie, Video, scan_video, scan_videos
logging.getLogger(__name__).addHandler(logging.NullHandler())
| Add compute_score to subliminal namespace | Add compute_score to subliminal namespace
| Python | mit | juanmhidalgo/subliminal,h3llrais3r/subliminal,getzze/subliminal,hpsbranco/subliminal,kbkailashbagaria/subliminal,oxan/subliminal,ratoaq2/subliminal,ofir123/subliminal,SickRage/subliminal,pums974/subliminal,Elettronik/subliminal,goll/subliminal,bogdal/subliminal,fernandog/subliminal,Diaoul/subliminal,neo1691/subliminal,t4lwh/subliminal | __title__ = 'subliminal'
__version__ = '1.0.dev0'
__author__ = 'Antoine Bertin'
__license__ = 'MIT'
__copyright__ = 'Copyright 2015, Antoine Bertin'
import logging
from .api import (ProviderPool, check_video, provider_manager, download_best_subtitles, download_subtitles,
list_subtitles, save_subtitles)
from .cache import region
from .exceptions import Error, ProviderError
from .providers import Provider
- from .subtitle import Subtitle
+ from .subtitle import Subtitle, compute_score
from .video import SUBTITLE_EXTENSIONS, VIDEO_EXTENSIONS, Episode, Movie, Video, scan_video, scan_videos
logging.getLogger(__name__).addHandler(logging.NullHandler())
| Add compute_score to subliminal namespace | ## Code Before:
__title__ = 'subliminal'
__version__ = '1.0.dev0'
__author__ = 'Antoine Bertin'
__license__ = 'MIT'
__copyright__ = 'Copyright 2015, Antoine Bertin'
import logging
from .api import (ProviderPool, check_video, provider_manager, download_best_subtitles, download_subtitles,
list_subtitles, save_subtitles)
from .cache import region
from .exceptions import Error, ProviderError
from .providers import Provider
from .subtitle import Subtitle
from .video import SUBTITLE_EXTENSIONS, VIDEO_EXTENSIONS, Episode, Movie, Video, scan_video, scan_videos
logging.getLogger(__name__).addHandler(logging.NullHandler())
## Instruction:
Add compute_score to subliminal namespace
## Code After:
__title__ = 'subliminal'
__version__ = '1.0.dev0'
__author__ = 'Antoine Bertin'
__license__ = 'MIT'
__copyright__ = 'Copyright 2015, Antoine Bertin'
import logging
from .api import (ProviderPool, check_video, provider_manager, download_best_subtitles, download_subtitles,
list_subtitles, save_subtitles)
from .cache import region
from .exceptions import Error, ProviderError
from .providers import Provider
from .subtitle import Subtitle, compute_score
from .video import SUBTITLE_EXTENSIONS, VIDEO_EXTENSIONS, Episode, Movie, Video, scan_video, scan_videos
logging.getLogger(__name__).addHandler(logging.NullHandler())
| __title__ = 'subliminal'
__version__ = '1.0.dev0'
__author__ = 'Antoine Bertin'
__license__ = 'MIT'
__copyright__ = 'Copyright 2015, Antoine Bertin'
import logging
from .api import (ProviderPool, check_video, provider_manager, download_best_subtitles, download_subtitles,
list_subtitles, save_subtitles)
from .cache import region
from .exceptions import Error, ProviderError
from .providers import Provider
- from .subtitle import Subtitle
+ from .subtitle import Subtitle, compute_score
? +++++++++++++++
from .video import SUBTITLE_EXTENSIONS, VIDEO_EXTENSIONS, Episode, Movie, Video, scan_video, scan_videos
logging.getLogger(__name__).addHandler(logging.NullHandler()) |
53ad3866b8dfbd012748e4ad7d7ed7025d491bd0 | src/alexa-main.py | src/alexa-main.py | import handlers.events as events
APPLICATION_ID = "amzn1.ask.skill.dd677950-cade-4805-b1f1-ce2e3a3569f0"
def lambda_handler(event, context):
if event['session']['new']:
events.on_session_started({'requestId': event['request']['requestId']},
event['session'])
request_type = event['request']['type']
if request_type == "LaunchRequest":
return events.on_launch(event['request'], event['session'])
elif request_type == "IntentRequest":
return events.on_intent(event['request'], event['session'])
elif request_type == "SessionEndedRequest":
return events.on_session_ended(event['request'], event['session'])
| import handlers.events as events
APPLICATION_ID = "amzn1.ask.skill.dd677950-cade-4805-b1f1-ce2e3a3569f0"
def lambda_handler(event, context):
# Make sure only this Alexa skill can use this function
if event['session']['application']['applicationId'] != APPLICATION_ID:
raise ValueError("Invalid Application ID")
if event['session']['new']:
events.on_session_started({'requestId': event['request']['requestId']},
event['session'])
request_type = event['request']['type']
if request_type == "LaunchRequest":
return events.on_launch(event['request'], event['session'])
elif request_type == "IntentRequest":
return events.on_intent(event['request'], event['session'])
elif request_type == "SessionEndedRequest":
return events.on_session_ended(event['request'], event['session'])
| REVERT remove application id validation | REVERT remove application id validation
| Python | mit | mauriceyap/ccm-assistant | import handlers.events as events
APPLICATION_ID = "amzn1.ask.skill.dd677950-cade-4805-b1f1-ce2e3a3569f0"
def lambda_handler(event, context):
+ # Make sure only this Alexa skill can use this function
+ if event['session']['application']['applicationId'] != APPLICATION_ID:
+ raise ValueError("Invalid Application ID")
+
if event['session']['new']:
events.on_session_started({'requestId': event['request']['requestId']},
event['session'])
request_type = event['request']['type']
if request_type == "LaunchRequest":
return events.on_launch(event['request'], event['session'])
elif request_type == "IntentRequest":
return events.on_intent(event['request'], event['session'])
elif request_type == "SessionEndedRequest":
return events.on_session_ended(event['request'], event['session'])
| REVERT remove application id validation | ## Code Before:
import handlers.events as events
APPLICATION_ID = "amzn1.ask.skill.dd677950-cade-4805-b1f1-ce2e3a3569f0"
def lambda_handler(event, context):
if event['session']['new']:
events.on_session_started({'requestId': event['request']['requestId']},
event['session'])
request_type = event['request']['type']
if request_type == "LaunchRequest":
return events.on_launch(event['request'], event['session'])
elif request_type == "IntentRequest":
return events.on_intent(event['request'], event['session'])
elif request_type == "SessionEndedRequest":
return events.on_session_ended(event['request'], event['session'])
## Instruction:
REVERT remove application id validation
## Code After:
import handlers.events as events
APPLICATION_ID = "amzn1.ask.skill.dd677950-cade-4805-b1f1-ce2e3a3569f0"
def lambda_handler(event, context):
# Make sure only this Alexa skill can use this function
if event['session']['application']['applicationId'] != APPLICATION_ID:
raise ValueError("Invalid Application ID")
if event['session']['new']:
events.on_session_started({'requestId': event['request']['requestId']},
event['session'])
request_type = event['request']['type']
if request_type == "LaunchRequest":
return events.on_launch(event['request'], event['session'])
elif request_type == "IntentRequest":
return events.on_intent(event['request'], event['session'])
elif request_type == "SessionEndedRequest":
return events.on_session_ended(event['request'], event['session'])
| import handlers.events as events
APPLICATION_ID = "amzn1.ask.skill.dd677950-cade-4805-b1f1-ce2e3a3569f0"
def lambda_handler(event, context):
+ # Make sure only this Alexa skill can use this function
+ if event['session']['application']['applicationId'] != APPLICATION_ID:
+ raise ValueError("Invalid Application ID")
+
if event['session']['new']:
events.on_session_started({'requestId': event['request']['requestId']},
event['session'])
request_type = event['request']['type']
if request_type == "LaunchRequest":
return events.on_launch(event['request'], event['session'])
elif request_type == "IntentRequest":
return events.on_intent(event['request'], event['session'])
elif request_type == "SessionEndedRequest":
return events.on_session_ended(event['request'], event['session']) |
0dcecfbd1e6ce9e35febc9f4ee9bcbfac1fb8f6a | hytra/util/skimage_tifffile_hack.py | hytra/util/skimage_tifffile_hack.py | from __future__ import print_function, absolute_import, nested_scopes, generators, division, with_statement, unicode_literals
from skimage.external import tifffile
def hack(input_tif):
"""
This method allows to bypass the strange faulty behaviour of
skimage.external.tifffile.imread() when it gets a list of paths or
a glob pattern. This function extracts the image names and the path.
Then, one can os.chdir(path) and call tifffile.imread(name),
what will now behave well.
"""
name = []; path = str()
for i in input_tif:
name.append(i.split('/')[-1])
path_split = list(input_tif)[0].split('/')[0:-1]
for i in path_split:
path += i+'/'
return path, name | from __future__ import print_function, absolute_import, nested_scopes, generators, division, with_statement, unicode_literals
from skimage.external import tifffile
import os.path
def hack(input_tif):
"""
This method allows to bypass the strange faulty behaviour of
skimage.external.tifffile.imread() when it gets a list of paths or
a glob pattern. This function extracts the image names and the path.
Then, one can os.chdir(path) and call tifffile.imread(names),
what will now behave well.
"""
assert len(input_tif) > 0
names = []
path = str()
for i in input_tif:
names.append(os.path.basename(i))
path = os.path.dirname(input_tif[0])
return path, names | Fix tiffile hack to use os.path | Fix tiffile hack to use os.path
| Python | mit | chaubold/hytra,chaubold/hytra,chaubold/hytra | from __future__ import print_function, absolute_import, nested_scopes, generators, division, with_statement, unicode_literals
from skimage.external import tifffile
+ import os.path
def hack(input_tif):
"""
This method allows to bypass the strange faulty behaviour of
skimage.external.tifffile.imread() when it gets a list of paths or
a glob pattern. This function extracts the image names and the path.
- Then, one can os.chdir(path) and call tifffile.imread(name),
+ Then, one can os.chdir(path) and call tifffile.imread(names),
what will now behave well.
"""
- name = []; path = str()
+ assert len(input_tif) > 0
+ names = []
+ path = str()
for i in input_tif:
+ names.append(os.path.basename(i))
+ path = os.path.dirname(input_tif[0])
- name.append(i.split('/')[-1])
- path_split = list(input_tif)[0].split('/')[0:-1]
- for i in path_split:
- path += i+'/'
- return path, name
+ return path, names | Fix tiffile hack to use os.path | ## Code Before:
from __future__ import print_function, absolute_import, nested_scopes, generators, division, with_statement, unicode_literals
from skimage.external import tifffile
def hack(input_tif):
"""
This method allows to bypass the strange faulty behaviour of
skimage.external.tifffile.imread() when it gets a list of paths or
a glob pattern. This function extracts the image names and the path.
Then, one can os.chdir(path) and call tifffile.imread(name),
what will now behave well.
"""
name = []; path = str()
for i in input_tif:
name.append(i.split('/')[-1])
path_split = list(input_tif)[0].split('/')[0:-1]
for i in path_split:
path += i+'/'
return path, name
## Instruction:
Fix tiffile hack to use os.path
## Code After:
from __future__ import print_function, absolute_import, nested_scopes, generators, division, with_statement, unicode_literals
from skimage.external import tifffile
import os.path
def hack(input_tif):
"""
This method allows to bypass the strange faulty behaviour of
skimage.external.tifffile.imread() when it gets a list of paths or
a glob pattern. This function extracts the image names and the path.
Then, one can os.chdir(path) and call tifffile.imread(names),
what will now behave well.
"""
assert len(input_tif) > 0
names = []
path = str()
for i in input_tif:
names.append(os.path.basename(i))
path = os.path.dirname(input_tif[0])
return path, names | from __future__ import print_function, absolute_import, nested_scopes, generators, division, with_statement, unicode_literals
from skimage.external import tifffile
+ import os.path
def hack(input_tif):
"""
This method allows to bypass the strange faulty behaviour of
skimage.external.tifffile.imread() when it gets a list of paths or
a glob pattern. This function extracts the image names and the path.
- Then, one can os.chdir(path) and call tifffile.imread(name),
+ Then, one can os.chdir(path) and call tifffile.imread(names),
? +
what will now behave well.
"""
- name = []; path = str()
+ assert len(input_tif) > 0
+ names = []
+ path = str()
for i in input_tif:
+ names.append(os.path.basename(i))
+ path = os.path.dirname(input_tif[0])
- name.append(i.split('/')[-1])
- path_split = list(input_tif)[0].split('/')[0:-1]
- for i in path_split:
- path += i+'/'
- return path, name
+ return path, names
? +
|
874d6f568a1367cbaad077648202f3328cd2eb8f | modules/Metadata/entropy.py | modules/Metadata/entropy.py | from __future__ import division, absolute_import, with_statement, print_function, unicode_literals
from collections import Counter
import math
__author__ = "Austin West"
__license__ = "MPL 2.0"
TYPE = "Metadata"
NAME = "entropy"
def check():
return True
def scan(filelist):
'''Calculate entropy of a string'''
results = []
for fname in filelist:
with open(fname, 'rb') as f:
text = f.read()
chars, lns = Counter(text), float(len(text))
result = -sum(count/lns * math.log(count/lns, 2) for count in chars.values())
results.append((fname, result))
metadata = {}
metadata["Name"] = NAME
metadata["Type"] = TYPE
metadata["Include"] = False
return (results, metadata)
| from __future__ import division, absolute_import, with_statement, print_function, unicode_literals
from collections import Counter
import math
__author__ = "Austin West"
__license__ = "MPL 2.0"
TYPE = "Metadata"
NAME = "entropy"
def check(conf=DEFAULTCONF):
return True
def scan(filelist):
'''Calculate entropy of a string'''
results = []
for fname in filelist:
with open(fname, 'rb') as f:
text = f.read()
chars, lns = Counter(text), float(len(text))
result = -sum(count/lns * math.log(count/lns, 2) for count in chars.values())
results.append((fname, result))
metadata = {}
metadata["Name"] = NAME
metadata["Type"] = TYPE
metadata["Include"] = False
return (results, metadata)
| Add conf arg to check function | Add conf arg to check function | Python | mpl-2.0 | jmlong1027/multiscanner,awest1339/multiscanner,awest1339/multiscanner,awest1339/multiscanner,MITRECND/multiscanner,MITRECND/multiscanner,jmlong1027/multiscanner,awest1339/multiscanner,jmlong1027/multiscanner,jmlong1027/multiscanner,mitre/multiscanner,mitre/multiscanner,mitre/multiscanner | from __future__ import division, absolute_import, with_statement, print_function, unicode_literals
from collections import Counter
import math
__author__ = "Austin West"
__license__ = "MPL 2.0"
TYPE = "Metadata"
NAME = "entropy"
- def check():
+ def check(conf=DEFAULTCONF):
return True
def scan(filelist):
'''Calculate entropy of a string'''
results = []
for fname in filelist:
with open(fname, 'rb') as f:
text = f.read()
chars, lns = Counter(text), float(len(text))
result = -sum(count/lns * math.log(count/lns, 2) for count in chars.values())
results.append((fname, result))
metadata = {}
metadata["Name"] = NAME
metadata["Type"] = TYPE
metadata["Include"] = False
return (results, metadata)
| Add conf arg to check function | ## Code Before:
from __future__ import division, absolute_import, with_statement, print_function, unicode_literals
from collections import Counter
import math
__author__ = "Austin West"
__license__ = "MPL 2.0"
TYPE = "Metadata"
NAME = "entropy"
def check():
return True
def scan(filelist):
'''Calculate entropy of a string'''
results = []
for fname in filelist:
with open(fname, 'rb') as f:
text = f.read()
chars, lns = Counter(text), float(len(text))
result = -sum(count/lns * math.log(count/lns, 2) for count in chars.values())
results.append((fname, result))
metadata = {}
metadata["Name"] = NAME
metadata["Type"] = TYPE
metadata["Include"] = False
return (results, metadata)
## Instruction:
Add conf arg to check function
## Code After:
from __future__ import division, absolute_import, with_statement, print_function, unicode_literals
from collections import Counter
import math
__author__ = "Austin West"
__license__ = "MPL 2.0"
TYPE = "Metadata"
NAME = "entropy"
def check(conf=DEFAULTCONF):
return True
def scan(filelist):
'''Calculate entropy of a string'''
results = []
for fname in filelist:
with open(fname, 'rb') as f:
text = f.read()
chars, lns = Counter(text), float(len(text))
result = -sum(count/lns * math.log(count/lns, 2) for count in chars.values())
results.append((fname, result))
metadata = {}
metadata["Name"] = NAME
metadata["Type"] = TYPE
metadata["Include"] = False
return (results, metadata)
| from __future__ import division, absolute_import, with_statement, print_function, unicode_literals
from collections import Counter
import math
__author__ = "Austin West"
__license__ = "MPL 2.0"
TYPE = "Metadata"
NAME = "entropy"
- def check():
+ def check(conf=DEFAULTCONF):
return True
def scan(filelist):
'''Calculate entropy of a string'''
results = []
for fname in filelist:
with open(fname, 'rb') as f:
text = f.read()
chars, lns = Counter(text), float(len(text))
result = -sum(count/lns * math.log(count/lns, 2) for count in chars.values())
results.append((fname, result))
metadata = {}
metadata["Name"] = NAME
metadata["Type"] = TYPE
metadata["Include"] = False
return (results, metadata) |
9f0e5c941c769c4d7c1cbdfcdcf98ddf643173d0 | cea/interfaces/dashboard/server/__init__.py | cea/interfaces/dashboard/server/__init__.py |
from __future__ import print_function
from __future__ import division
from flask import Blueprint
from flask_restplus import Api
from .jobs import api as jobs
from .streams import api as streams
__author__ = "Daren Thomas"
__copyright__ = "Copyright 2019, Architecture and Building Systems - ETH Zurich"
__credits__ = ["Daren Thomas"]
__license__ = "MIT"
__version__ = "0.1"
__maintainer__ = "Daren Thomas"
__email__ = "cea@arch.ethz.ch"
__status__ = "Production"
blueprint = Blueprint('server', __name__, url_prefix='/server')
api = Api(blueprint)
# there might potentially be more namespaces added in the future, e.g. a method for locating files etc.
api.add_namespace(jobs, path='/jobs')
api.add_namespace(streams, path='/streams')
|
from __future__ import print_function
from __future__ import division
from flask import Blueprint, current_app
from flask_restplus import Api, Resource
from .jobs import api as jobs
from .streams import api as streams
__author__ = "Daren Thomas"
__copyright__ = "Copyright 2019, Architecture and Building Systems - ETH Zurich"
__credits__ = ["Daren Thomas"]
__license__ = "MIT"
__version__ = "0.1"
__maintainer__ = "Daren Thomas"
__email__ = "cea@arch.ethz.ch"
__status__ = "Production"
blueprint = Blueprint('server', __name__, url_prefix='/server')
api = Api(blueprint)
# there might potentially be more namespaces added in the future, e.g. a method for locating files etc.
api.add_namespace(jobs, path='/jobs')
api.add_namespace(streams, path='/streams')
@api.route("/alive")
class ServerAlive(Resource):
def get(self):
return {'success': True}
@api.route("/shutdown")
class ServerShutdown(Resource):
def post(self):
current_app.socketio.stop()
return {'message': 'Shutting down...'}
| Add server alive and shutdown api endpoints | Add server alive and shutdown api endpoints
| Python | mit | architecture-building-systems/CityEnergyAnalyst,architecture-building-systems/CityEnergyAnalyst,architecture-building-systems/CityEnergyAnalyst |
from __future__ import print_function
from __future__ import division
- from flask import Blueprint
+ from flask import Blueprint, current_app
- from flask_restplus import Api
+ from flask_restplus import Api, Resource
from .jobs import api as jobs
from .streams import api as streams
__author__ = "Daren Thomas"
__copyright__ = "Copyright 2019, Architecture and Building Systems - ETH Zurich"
__credits__ = ["Daren Thomas"]
__license__ = "MIT"
__version__ = "0.1"
__maintainer__ = "Daren Thomas"
__email__ = "cea@arch.ethz.ch"
__status__ = "Production"
blueprint = Blueprint('server', __name__, url_prefix='/server')
api = Api(blueprint)
# there might potentially be more namespaces added in the future, e.g. a method for locating files etc.
api.add_namespace(jobs, path='/jobs')
api.add_namespace(streams, path='/streams')
+
+ @api.route("/alive")
+ class ServerAlive(Resource):
+ def get(self):
+ return {'success': True}
+
+
+ @api.route("/shutdown")
+ class ServerShutdown(Resource):
+ def post(self):
+ current_app.socketio.stop()
+ return {'message': 'Shutting down...'}
+ | Add server alive and shutdown api endpoints | ## Code Before:
from __future__ import print_function
from __future__ import division
from flask import Blueprint
from flask_restplus import Api
from .jobs import api as jobs
from .streams import api as streams
__author__ = "Daren Thomas"
__copyright__ = "Copyright 2019, Architecture and Building Systems - ETH Zurich"
__credits__ = ["Daren Thomas"]
__license__ = "MIT"
__version__ = "0.1"
__maintainer__ = "Daren Thomas"
__email__ = "cea@arch.ethz.ch"
__status__ = "Production"
blueprint = Blueprint('server', __name__, url_prefix='/server')
api = Api(blueprint)
# there might potentially be more namespaces added in the future, e.g. a method for locating files etc.
api.add_namespace(jobs, path='/jobs')
api.add_namespace(streams, path='/streams')
## Instruction:
Add server alive and shutdown api endpoints
## Code After:
from __future__ import print_function
from __future__ import division
from flask import Blueprint, current_app
from flask_restplus import Api, Resource
from .jobs import api as jobs
from .streams import api as streams
__author__ = "Daren Thomas"
__copyright__ = "Copyright 2019, Architecture and Building Systems - ETH Zurich"
__credits__ = ["Daren Thomas"]
__license__ = "MIT"
__version__ = "0.1"
__maintainer__ = "Daren Thomas"
__email__ = "cea@arch.ethz.ch"
__status__ = "Production"
blueprint = Blueprint('server', __name__, url_prefix='/server')
api = Api(blueprint)
# there might potentially be more namespaces added in the future, e.g. a method for locating files etc.
api.add_namespace(jobs, path='/jobs')
api.add_namespace(streams, path='/streams')
@api.route("/alive")
class ServerAlive(Resource):
def get(self):
return {'success': True}
@api.route("/shutdown")
class ServerShutdown(Resource):
def post(self):
current_app.socketio.stop()
return {'message': 'Shutting down...'}
|
from __future__ import print_function
from __future__ import division
- from flask import Blueprint
+ from flask import Blueprint, current_app
? +++++++++++++
- from flask_restplus import Api
+ from flask_restplus import Api, Resource
? ++++++++++
from .jobs import api as jobs
from .streams import api as streams
__author__ = "Daren Thomas"
__copyright__ = "Copyright 2019, Architecture and Building Systems - ETH Zurich"
__credits__ = ["Daren Thomas"]
__license__ = "MIT"
__version__ = "0.1"
__maintainer__ = "Daren Thomas"
__email__ = "cea@arch.ethz.ch"
__status__ = "Production"
blueprint = Blueprint('server', __name__, url_prefix='/server')
api = Api(blueprint)
# there might potentially be more namespaces added in the future, e.g. a method for locating files etc.
api.add_namespace(jobs, path='/jobs')
api.add_namespace(streams, path='/streams')
+
+
+ @api.route("/alive")
+ class ServerAlive(Resource):
+ def get(self):
+ return {'success': True}
+
+
+ @api.route("/shutdown")
+ class ServerShutdown(Resource):
+ def post(self):
+ current_app.socketio.stop()
+ return {'message': 'Shutting down...'} |
c7a209d2c4455325f1d215ca1c12074b394ae00e | gitdir/host/__init__.py | gitdir/host/__init__.py | import abc
import subprocess
import gitdir
class Host(abc.ABC):
@abc.abstractmethod
def __iter__(self):
raise NotImplementedError()
@abc.abstractmethod
def __str__(self):
raise NotImplementedError()
def clone(self, repo_spec):
raise NotImplementedError('Host {} does not support cloning'.format(self))
@property
def dir(self):
return gitdir.GITDIR / str(self)
def update(self):
for repo_dir in self:
subprocess.check_call(['git', 'pull'], cwd=str(repo_dir / 'master'))
def all():
for host_dir in gitdir.GITDIR.iterdir():
yield by_name(host_dir.name)
def by_name(hostname):
if hostname == 'github.com':
import gitdir.host.github
return gitdir.host.github.GitHub()
else:
raise ValueError('Unsupported hostname: {}'.format(hostname))
| import abc
import subprocess
import gitdir
class Host(abc.ABC):
@abc.abstractmethod
def __iter__(self):
raise NotImplementedError()
@abc.abstractmethod
def __str__(self):
raise NotImplementedError()
def clone(self, repo_spec):
raise NotImplementedError('Host {} does not support cloning'.format(self))
@property
def dir(self):
return gitdir.GITDIR / str(self)
def update(self):
for repo_dir in self:
print('[ ** ] updating {}'.format(repo_dir))
subprocess.check_call(['git', 'pull'], cwd=str(repo_dir / 'master'))
def all():
for host_dir in gitdir.GITDIR.iterdir():
yield by_name(host_dir.name)
def by_name(hostname):
if hostname == 'github.com':
import gitdir.host.github
return gitdir.host.github.GitHub()
else:
raise ValueError('Unsupported hostname: {}'.format(hostname))
| Add status messages to `gitdir update` | Add status messages to `gitdir update`
| Python | mit | fenhl/gitdir | import abc
import subprocess
import gitdir
class Host(abc.ABC):
@abc.abstractmethod
def __iter__(self):
raise NotImplementedError()
@abc.abstractmethod
def __str__(self):
raise NotImplementedError()
def clone(self, repo_spec):
raise NotImplementedError('Host {} does not support cloning'.format(self))
@property
def dir(self):
return gitdir.GITDIR / str(self)
def update(self):
for repo_dir in self:
+ print('[ ** ] updating {}'.format(repo_dir))
subprocess.check_call(['git', 'pull'], cwd=str(repo_dir / 'master'))
def all():
for host_dir in gitdir.GITDIR.iterdir():
yield by_name(host_dir.name)
def by_name(hostname):
if hostname == 'github.com':
import gitdir.host.github
return gitdir.host.github.GitHub()
else:
raise ValueError('Unsupported hostname: {}'.format(hostname))
| Add status messages to `gitdir update` | ## Code Before:
import abc
import subprocess
import gitdir
class Host(abc.ABC):
@abc.abstractmethod
def __iter__(self):
raise NotImplementedError()
@abc.abstractmethod
def __str__(self):
raise NotImplementedError()
def clone(self, repo_spec):
raise NotImplementedError('Host {} does not support cloning'.format(self))
@property
def dir(self):
return gitdir.GITDIR / str(self)
def update(self):
for repo_dir in self:
subprocess.check_call(['git', 'pull'], cwd=str(repo_dir / 'master'))
def all():
for host_dir in gitdir.GITDIR.iterdir():
yield by_name(host_dir.name)
def by_name(hostname):
if hostname == 'github.com':
import gitdir.host.github
return gitdir.host.github.GitHub()
else:
raise ValueError('Unsupported hostname: {}'.format(hostname))
## Instruction:
Add status messages to `gitdir update`
## Code After:
import abc
import subprocess
import gitdir
class Host(abc.ABC):
@abc.abstractmethod
def __iter__(self):
raise NotImplementedError()
@abc.abstractmethod
def __str__(self):
raise NotImplementedError()
def clone(self, repo_spec):
raise NotImplementedError('Host {} does not support cloning'.format(self))
@property
def dir(self):
return gitdir.GITDIR / str(self)
def update(self):
for repo_dir in self:
print('[ ** ] updating {}'.format(repo_dir))
subprocess.check_call(['git', 'pull'], cwd=str(repo_dir / 'master'))
def all():
for host_dir in gitdir.GITDIR.iterdir():
yield by_name(host_dir.name)
def by_name(hostname):
if hostname == 'github.com':
import gitdir.host.github
return gitdir.host.github.GitHub()
else:
raise ValueError('Unsupported hostname: {}'.format(hostname))
| import abc
import subprocess
import gitdir
class Host(abc.ABC):
@abc.abstractmethod
def __iter__(self):
raise NotImplementedError()
@abc.abstractmethod
def __str__(self):
raise NotImplementedError()
def clone(self, repo_spec):
raise NotImplementedError('Host {} does not support cloning'.format(self))
@property
def dir(self):
return gitdir.GITDIR / str(self)
def update(self):
for repo_dir in self:
+ print('[ ** ] updating {}'.format(repo_dir))
subprocess.check_call(['git', 'pull'], cwd=str(repo_dir / 'master'))
def all():
for host_dir in gitdir.GITDIR.iterdir():
yield by_name(host_dir.name)
def by_name(hostname):
if hostname == 'github.com':
import gitdir.host.github
return gitdir.host.github.GitHub()
else:
raise ValueError('Unsupported hostname: {}'.format(hostname)) |
e83019f67a3c93efac27566666bcff5eb0d2a0da | examples/autopost/auto_post.py | examples/autopost/auto_post.py | import time
import sys
import os
import glob
sys.path.append(os.path.join(sys.path[0], '../../'))
from instabot import Bot
posted_pic_list = []
try:
with open('pics.txt', 'r') as f:
posted_pic_list = f.read().splitlines()
except Exception:
posted_pic_list = []
timeout = 24 * 60 * 60 # pics will be posted every 24 hours
bot = Bot()
bot.login()
while True:
pics = glob.glob("./pics/*.jpg")
pics = sorted(pics)
try:
for pic in pics:
if pic in posted_pic_list:
continue
caption = pic[:-4].split(" ")
caption = " ".join(caption[1:])
print("upload: " + caption)
bot.uploadPhoto(pic, caption=caption)
if bot.LastResponse.status_code != 200:
print(bot.LastResponse)
# snd msg
break
if pic not in posted_pic_list:
posted_pic_list.append(pic)
with open('pics.txt', 'a') as f:
f.write(pic + "\n")
time.sleep(timeout)
except Exception as e:
print(str(e))
time.sleep(60)
| import glob
import os
import sys
import time
from io import open
sys.path.append(os.path.join(sys.path[0], '../../'))
from instabot import Bot
posted_pic_list = []
try:
with open('pics.txt', 'r', encoding='utf8') as f:
posted_pic_list = f.read().splitlines()
except Exception:
posted_pic_list = []
timeout = 24 * 60 * 60 # pics will be posted every 24 hours
bot = Bot()
bot.login()
while True:
pics = glob.glob("./pics/*.jpg")
pics = sorted(pics)
try:
for pic in pics:
if pic in posted_pic_list:
continue
caption = pic[:-4].split(" ")
caption = " ".join(caption[1:])
print("upload: " + caption)
bot.uploadPhoto(pic, caption=caption)
if bot.LastResponse.status_code != 200:
print(bot.LastResponse)
# snd msg
break
if pic not in posted_pic_list:
posted_pic_list.append(pic)
with open('pics.txt', 'a', encoding='utf8') as f:
f.write(pic + "\n")
time.sleep(timeout)
except Exception as e:
print(str(e))
time.sleep(60)
| Add utf-8 in autopost example | Add utf-8 in autopost example
| Python | apache-2.0 | instagrambot/instabot,ohld/instabot,instagrambot/instabot | + import glob
+ import os
+ import sys
import time
+
+ from io import open
- import sys
- import os
- import glob
sys.path.append(os.path.join(sys.path[0], '../../'))
from instabot import Bot
posted_pic_list = []
try:
- with open('pics.txt', 'r') as f:
+ with open('pics.txt', 'r', encoding='utf8') as f:
posted_pic_list = f.read().splitlines()
except Exception:
posted_pic_list = []
timeout = 24 * 60 * 60 # pics will be posted every 24 hours
bot = Bot()
bot.login()
while True:
pics = glob.glob("./pics/*.jpg")
pics = sorted(pics)
try:
for pic in pics:
if pic in posted_pic_list:
continue
caption = pic[:-4].split(" ")
caption = " ".join(caption[1:])
print("upload: " + caption)
bot.uploadPhoto(pic, caption=caption)
if bot.LastResponse.status_code != 200:
print(bot.LastResponse)
# snd msg
break
if pic not in posted_pic_list:
posted_pic_list.append(pic)
- with open('pics.txt', 'a') as f:
+ with open('pics.txt', 'a', encoding='utf8') as f:
f.write(pic + "\n")
time.sleep(timeout)
except Exception as e:
print(str(e))
time.sleep(60)
| Add utf-8 in autopost example | ## Code Before:
import time
import sys
import os
import glob
sys.path.append(os.path.join(sys.path[0], '../../'))
from instabot import Bot
posted_pic_list = []
try:
with open('pics.txt', 'r') as f:
posted_pic_list = f.read().splitlines()
except Exception:
posted_pic_list = []
timeout = 24 * 60 * 60 # pics will be posted every 24 hours
bot = Bot()
bot.login()
while True:
pics = glob.glob("./pics/*.jpg")
pics = sorted(pics)
try:
for pic in pics:
if pic in posted_pic_list:
continue
caption = pic[:-4].split(" ")
caption = " ".join(caption[1:])
print("upload: " + caption)
bot.uploadPhoto(pic, caption=caption)
if bot.LastResponse.status_code != 200:
print(bot.LastResponse)
# snd msg
break
if pic not in posted_pic_list:
posted_pic_list.append(pic)
with open('pics.txt', 'a') as f:
f.write(pic + "\n")
time.sleep(timeout)
except Exception as e:
print(str(e))
time.sleep(60)
## Instruction:
Add utf-8 in autopost example
## Code After:
import glob
import os
import sys
import time
from io import open
sys.path.append(os.path.join(sys.path[0], '../../'))
from instabot import Bot
posted_pic_list = []
try:
with open('pics.txt', 'r', encoding='utf8') as f:
posted_pic_list = f.read().splitlines()
except Exception:
posted_pic_list = []
timeout = 24 * 60 * 60 # pics will be posted every 24 hours
bot = Bot()
bot.login()
while True:
pics = glob.glob("./pics/*.jpg")
pics = sorted(pics)
try:
for pic in pics:
if pic in posted_pic_list:
continue
caption = pic[:-4].split(" ")
caption = " ".join(caption[1:])
print("upload: " + caption)
bot.uploadPhoto(pic, caption=caption)
if bot.LastResponse.status_code != 200:
print(bot.LastResponse)
# snd msg
break
if pic not in posted_pic_list:
posted_pic_list.append(pic)
with open('pics.txt', 'a', encoding='utf8') as f:
f.write(pic + "\n")
time.sleep(timeout)
except Exception as e:
print(str(e))
time.sleep(60)
| + import glob
+ import os
+ import sys
import time
+
+ from io import open
- import sys
- import os
- import glob
sys.path.append(os.path.join(sys.path[0], '../../'))
from instabot import Bot
posted_pic_list = []
try:
- with open('pics.txt', 'r') as f:
+ with open('pics.txt', 'r', encoding='utf8') as f:
? +++++++++++++++++
posted_pic_list = f.read().splitlines()
except Exception:
posted_pic_list = []
timeout = 24 * 60 * 60 # pics will be posted every 24 hours
bot = Bot()
bot.login()
while True:
pics = glob.glob("./pics/*.jpg")
pics = sorted(pics)
try:
for pic in pics:
if pic in posted_pic_list:
continue
caption = pic[:-4].split(" ")
caption = " ".join(caption[1:])
print("upload: " + caption)
bot.uploadPhoto(pic, caption=caption)
if bot.LastResponse.status_code != 200:
print(bot.LastResponse)
# snd msg
break
if pic not in posted_pic_list:
posted_pic_list.append(pic)
- with open('pics.txt', 'a') as f:
+ with open('pics.txt', 'a', encoding='utf8') as f:
? +++++++++++++++++
f.write(pic + "\n")
time.sleep(timeout)
except Exception as e:
print(str(e))
time.sleep(60) |
8d55ea0cfbafc9f6dc1044ba27c3313c36ea73c6 | pombola/south_africa/templatetags/za_people_display.py | pombola/south_africa/templatetags/za_people_display.py | from django import template
register = template.Library()
NO_PLACE_ORGS = ('parliament', 'national-assembly', )
MEMBER_ORGS = ('parliament', 'national-assembly', )
@register.assignment_tag()
def should_display_place(organisation):
return organisation.slug not in NO_PLACE_ORGS
@register.assignment_tag()
def should_display_position(organisation, position_title):
should_display = True
if organisation.slug in MEMBER_ORGS and unicode(position_title) in (u'Member',):
should_display = False
if 'ncop' == organisation.slug and unicode(position_title) in (u'Delegate',):
should_display = False
return should_display
| from django import template
register = template.Library()
NO_PLACE_ORGS = ('parliament', 'national-assembly', )
MEMBER_ORGS = ('parliament', 'national-assembly', )
@register.assignment_tag()
def should_display_place(organisation):
if not organisation:
return True
return organisation.slug not in NO_PLACE_ORGS
@register.assignment_tag()
def should_display_position(organisation, position_title):
should_display = True
if organisation.slug in MEMBER_ORGS and unicode(position_title) in (u'Member',):
should_display = False
if 'ncop' == organisation.slug and unicode(position_title) in (u'Delegate',):
should_display = False
return should_display
| Fix display of people on constituency office page | [ZA] Fix display of people on constituency office page
This template tag was being called without an organisation, so in
production it was just silently failing, but in development it was
raising an exception.
This adds an extra check so that if there is no organisation then we
just short circuit and return `True`.
| Python | agpl-3.0 | mysociety/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola | from django import template
register = template.Library()
NO_PLACE_ORGS = ('parliament', 'national-assembly', )
MEMBER_ORGS = ('parliament', 'national-assembly', )
@register.assignment_tag()
def should_display_place(organisation):
+ if not organisation:
+ return True
return organisation.slug not in NO_PLACE_ORGS
@register.assignment_tag()
def should_display_position(organisation, position_title):
should_display = True
if organisation.slug in MEMBER_ORGS and unicode(position_title) in (u'Member',):
should_display = False
if 'ncop' == organisation.slug and unicode(position_title) in (u'Delegate',):
should_display = False
return should_display
| Fix display of people on constituency office page | ## Code Before:
from django import template
register = template.Library()
NO_PLACE_ORGS = ('parliament', 'national-assembly', )
MEMBER_ORGS = ('parliament', 'national-assembly', )
@register.assignment_tag()
def should_display_place(organisation):
return organisation.slug not in NO_PLACE_ORGS
@register.assignment_tag()
def should_display_position(organisation, position_title):
should_display = True
if organisation.slug in MEMBER_ORGS and unicode(position_title) in (u'Member',):
should_display = False
if 'ncop' == organisation.slug and unicode(position_title) in (u'Delegate',):
should_display = False
return should_display
## Instruction:
Fix display of people on constituency office page
## Code After:
from django import template
register = template.Library()
NO_PLACE_ORGS = ('parliament', 'national-assembly', )
MEMBER_ORGS = ('parliament', 'national-assembly', )
@register.assignment_tag()
def should_display_place(organisation):
if not organisation:
return True
return organisation.slug not in NO_PLACE_ORGS
@register.assignment_tag()
def should_display_position(organisation, position_title):
should_display = True
if organisation.slug in MEMBER_ORGS and unicode(position_title) in (u'Member',):
should_display = False
if 'ncop' == organisation.slug and unicode(position_title) in (u'Delegate',):
should_display = False
return should_display
| from django import template
register = template.Library()
NO_PLACE_ORGS = ('parliament', 'national-assembly', )
MEMBER_ORGS = ('parliament', 'national-assembly', )
@register.assignment_tag()
def should_display_place(organisation):
+ if not organisation:
+ return True
return organisation.slug not in NO_PLACE_ORGS
@register.assignment_tag()
def should_display_position(organisation, position_title):
should_display = True
if organisation.slug in MEMBER_ORGS and unicode(position_title) in (u'Member',):
should_display = False
if 'ncop' == organisation.slug and unicode(position_title) in (u'Delegate',):
should_display = False
return should_display |
538f4b2d0e030a9256ecd68eaf0a1a2e5d649f49 | haas/tests/mocks.py | haas/tests/mocks.py | import itertools
import traceback
class MockDateTime(object):
def __init__(self, ret):
try:
self.ret = iter(ret)
except TypeError:
self.ret = iter(itertools.repeat(ret))
def utcnow(self):
return next(self.ret)
| class MockDateTime(object):
def __init__(self, ret):
try:
self.ret = iter(ret)
except TypeError:
self.ret = iter((ret,))
def utcnow(self):
try:
return next(self.ret)
except StopIteration:
raise ValueError('No more mock values!')
| Raise error in mock if there are not enough mock datetime values | Raise error in mock if there are not enough mock datetime values
| Python | bsd-3-clause | sjagoe/haas,itziakos/haas,itziakos/haas,scalative/haas,sjagoe/haas,scalative/haas | - import itertools
- import traceback
-
-
class MockDateTime(object):
def __init__(self, ret):
try:
self.ret = iter(ret)
except TypeError:
- self.ret = iter(itertools.repeat(ret))
+ self.ret = iter((ret,))
def utcnow(self):
+ try:
- return next(self.ret)
+ return next(self.ret)
+ except StopIteration:
+ raise ValueError('No more mock values!')
| Raise error in mock if there are not enough mock datetime values | ## Code Before:
import itertools
import traceback
class MockDateTime(object):
def __init__(self, ret):
try:
self.ret = iter(ret)
except TypeError:
self.ret = iter(itertools.repeat(ret))
def utcnow(self):
return next(self.ret)
## Instruction:
Raise error in mock if there are not enough mock datetime values
## Code After:
class MockDateTime(object):
def __init__(self, ret):
try:
self.ret = iter(ret)
except TypeError:
self.ret = iter((ret,))
def utcnow(self):
try:
return next(self.ret)
except StopIteration:
raise ValueError('No more mock values!')
| - import itertools
- import traceback
-
-
class MockDateTime(object):
def __init__(self, ret):
try:
self.ret = iter(ret)
except TypeError:
- self.ret = iter(itertools.repeat(ret))
? ----------------
+ self.ret = iter((ret,))
? +
def utcnow(self):
+ try:
- return next(self.ret)
+ return next(self.ret)
? ++++
+ except StopIteration:
+ raise ValueError('No more mock values!') |
449ec018d9403e1732528c2806ec68e8417e6725 | raco/rules.py | raco/rules.py | import algebra
import boolean
class Rule:
"""
Argument is an expression tree
Returns a possibly modified expression tree
"""
def __call__(self, expr):
return self.fire(expr)
class CrossProduct2Join(Rule):
"""A rewrite rule for removing Cross Product"""
def fire(self, expr):
if isinstance(expr, algebra.CrossProduct):
return algebra.Join(boolean.EQ(boolean.NumericLiteral(1),boolean.NumericLiteral(1)), expr.left, expr.right)
return expr
def __str__(self):
return "CrossProduct(left, right) => Join(1=1, left, right)"
class removeProject(Rule):
"""A rewrite rule for removing Projections"""
def fire(self, expr):
if isinstance(expr, algebra.Project):
return expr.input
return expr
def __str__(self):
return "Project => ()"
class OneToOne(Rule):
def __init__(self, opfrom, opto):
self.opfrom = opfrom
self.opto = opto
def fire(self, expr):
if isinstance(expr, self.opfrom):
newop = self.opto()
newop.copy(expr)
return newop
return expr
def __str__(self):
return "%s => %s" % (self.opfrom.__name__,self.opto.__name__)
| import boolean
class Rule:
"""
Argument is an expression tree
Returns a possibly modified expression tree
"""
def __call__(self, expr):
return self.fire(expr)
import algebra
class CrossProduct2Join(Rule):
"""A rewrite rule for removing Cross Product"""
def fire(self, expr):
if isinstance(expr, algebra.CrossProduct):
return algebra.Join(boolean.EQ(boolean.NumericLiteral(1),boolean.NumericLiteral(1)), expr.left, expr.right)
return expr
def __str__(self):
return "CrossProduct(left, right) => Join(1=1, left, right)"
class removeProject(Rule):
"""A rewrite rule for removing Projections"""
def fire(self, expr):
if isinstance(expr, algebra.Project):
return expr.input
return expr
def __str__(self):
return "Project => ()"
class OneToOne(Rule):
def __init__(self, opfrom, opto):
self.opfrom = opfrom
self.opto = opto
def fire(self, expr):
if isinstance(expr, self.opfrom):
newop = self.opto()
newop.copy(expr)
return newop
return expr
def __str__(self):
return "%s => %s" % (self.opfrom.__name__,self.opto.__name__)
| Resolve circular reference during import | Resolve circular reference during import
| Python | bsd-3-clause | uwescience/raco,uwescience/raco,uwescience/raco,uwescience/raco,uwescience/raco | - import algebra
import boolean
class Rule:
"""
Argument is an expression tree
Returns a possibly modified expression tree
"""
def __call__(self, expr):
return self.fire(expr)
+
+ import algebra
class CrossProduct2Join(Rule):
"""A rewrite rule for removing Cross Product"""
def fire(self, expr):
if isinstance(expr, algebra.CrossProduct):
return algebra.Join(boolean.EQ(boolean.NumericLiteral(1),boolean.NumericLiteral(1)), expr.left, expr.right)
return expr
def __str__(self):
return "CrossProduct(left, right) => Join(1=1, left, right)"
class removeProject(Rule):
"""A rewrite rule for removing Projections"""
def fire(self, expr):
if isinstance(expr, algebra.Project):
return expr.input
return expr
def __str__(self):
return "Project => ()"
class OneToOne(Rule):
def __init__(self, opfrom, opto):
self.opfrom = opfrom
self.opto = opto
def fire(self, expr):
if isinstance(expr, self.opfrom):
newop = self.opto()
newop.copy(expr)
return newop
return expr
def __str__(self):
return "%s => %s" % (self.opfrom.__name__,self.opto.__name__)
| Resolve circular reference during import | ## Code Before:
import algebra
import boolean
class Rule:
"""
Argument is an expression tree
Returns a possibly modified expression tree
"""
def __call__(self, expr):
return self.fire(expr)
class CrossProduct2Join(Rule):
"""A rewrite rule for removing Cross Product"""
def fire(self, expr):
if isinstance(expr, algebra.CrossProduct):
return algebra.Join(boolean.EQ(boolean.NumericLiteral(1),boolean.NumericLiteral(1)), expr.left, expr.right)
return expr
def __str__(self):
return "CrossProduct(left, right) => Join(1=1, left, right)"
class removeProject(Rule):
"""A rewrite rule for removing Projections"""
def fire(self, expr):
if isinstance(expr, algebra.Project):
return expr.input
return expr
def __str__(self):
return "Project => ()"
class OneToOne(Rule):
def __init__(self, opfrom, opto):
self.opfrom = opfrom
self.opto = opto
def fire(self, expr):
if isinstance(expr, self.opfrom):
newop = self.opto()
newop.copy(expr)
return newop
return expr
def __str__(self):
return "%s => %s" % (self.opfrom.__name__,self.opto.__name__)
## Instruction:
Resolve circular reference during import
## Code After:
import boolean
class Rule:
"""
Argument is an expression tree
Returns a possibly modified expression tree
"""
def __call__(self, expr):
return self.fire(expr)
import algebra
class CrossProduct2Join(Rule):
"""A rewrite rule for removing Cross Product"""
def fire(self, expr):
if isinstance(expr, algebra.CrossProduct):
return algebra.Join(boolean.EQ(boolean.NumericLiteral(1),boolean.NumericLiteral(1)), expr.left, expr.right)
return expr
def __str__(self):
return "CrossProduct(left, right) => Join(1=1, left, right)"
class removeProject(Rule):
"""A rewrite rule for removing Projections"""
def fire(self, expr):
if isinstance(expr, algebra.Project):
return expr.input
return expr
def __str__(self):
return "Project => ()"
class OneToOne(Rule):
def __init__(self, opfrom, opto):
self.opfrom = opfrom
self.opto = opto
def fire(self, expr):
if isinstance(expr, self.opfrom):
newop = self.opto()
newop.copy(expr)
return newop
return expr
def __str__(self):
return "%s => %s" % (self.opfrom.__name__,self.opto.__name__)
| - import algebra
import boolean
class Rule:
"""
Argument is an expression tree
Returns a possibly modified expression tree
"""
def __call__(self, expr):
return self.fire(expr)
+
+ import algebra
class CrossProduct2Join(Rule):
"""A rewrite rule for removing Cross Product"""
def fire(self, expr):
if isinstance(expr, algebra.CrossProduct):
return algebra.Join(boolean.EQ(boolean.NumericLiteral(1),boolean.NumericLiteral(1)), expr.left, expr.right)
return expr
def __str__(self):
return "CrossProduct(left, right) => Join(1=1, left, right)"
class removeProject(Rule):
"""A rewrite rule for removing Projections"""
def fire(self, expr):
if isinstance(expr, algebra.Project):
return expr.input
return expr
def __str__(self):
return "Project => ()"
class OneToOne(Rule):
def __init__(self, opfrom, opto):
self.opfrom = opfrom
self.opto = opto
def fire(self, expr):
if isinstance(expr, self.opfrom):
newop = self.opto()
newop.copy(expr)
return newop
return expr
def __str__(self):
return "%s => %s" % (self.opfrom.__name__,self.opto.__name__)
|
bd5c215c1c481f3811753412bca6b509bb00591a | me_api/app.py | me_api/app.py |
from __future__ import absolute_import, unicode_literals
from flask import Flask
from .middleware.me import me
from .cache import cache
def _register_module(app, module):
if module == 'douban':
from .middleware import douban
app.register_blueprint(douban.douban_api)
elif module == 'github':
from .middleware import github
app.register_blueprint(github.github_api)
elif module == 'instagram':
from .middleware import instagram
app.register_blueprint(instagram.instagram_api)
elif module == 'keybase':
from .middleware import keybase
app.register_blueprint(keybase.keybase_api)
elif module == 'medium':
from .middleware import medium
app.register_blueprint(medium.medium_api)
elif module == 'stackoverflow':
from .middleware import stackoverflow
app.register_blueprint(stackoverflow.stackoverflow_api)
def create_app(config):
app = Flask(__name__)
app.config.from_object(config)
cache.init_app(app)
modules = config.modules['modules']
app.register_blueprint(me)
for module in modules.keys():
_register_module(app, module)
return app
|
from __future__ import absolute_import, unicode_literals
from flask import Flask
from werkzeug.utils import import_string
from me_api.middleware.me import me
from me_api.cache import cache
middlewares = {
'douban': 'me_api.middleware.douban:douban_api',
'github': 'me_api.middleware.github:github_api',
'instagram': 'me_api.middleware.instagram:instagram_api',
'keybase': 'me_api.middleware.keybase:keybase_api',
'medium': 'me_api.middleware.medium:medium_api',
'stackoverflow': 'me_api.middleware.stackoverflow:stackoverflow_api',
}
def create_app(config):
app = Flask(__name__)
app.config.from_object(config)
cache.init_app(app)
modules = config.modules['modules']
app.register_blueprint(me)
for module in modules.keys():
blueprint = import_string(middlewares[module])
app.register_blueprint(blueprint)
return app
| Improve the way that import middlewares | Improve the way that import middlewares
| Python | mit | lord63/me-api |
from __future__ import absolute_import, unicode_literals
from flask import Flask
+ from werkzeug.utils import import_string
- from .middleware.me import me
+ from me_api.middleware.me import me
- from .cache import cache
+ from me_api.cache import cache
+ middlewares = {
+ 'douban': 'me_api.middleware.douban:douban_api',
+ 'github': 'me_api.middleware.github:github_api',
+ 'instagram': 'me_api.middleware.instagram:instagram_api',
+ 'keybase': 'me_api.middleware.keybase:keybase_api',
+ 'medium': 'me_api.middleware.medium:medium_api',
+ 'stackoverflow': 'me_api.middleware.stackoverflow:stackoverflow_api',
+ }
- def _register_module(app, module):
- if module == 'douban':
- from .middleware import douban
- app.register_blueprint(douban.douban_api)
- elif module == 'github':
- from .middleware import github
- app.register_blueprint(github.github_api)
- elif module == 'instagram':
- from .middleware import instagram
- app.register_blueprint(instagram.instagram_api)
- elif module == 'keybase':
- from .middleware import keybase
- app.register_blueprint(keybase.keybase_api)
- elif module == 'medium':
- from .middleware import medium
- app.register_blueprint(medium.medium_api)
- elif module == 'stackoverflow':
- from .middleware import stackoverflow
- app.register_blueprint(stackoverflow.stackoverflow_api)
def create_app(config):
app = Flask(__name__)
app.config.from_object(config)
cache.init_app(app)
modules = config.modules['modules']
app.register_blueprint(me)
for module in modules.keys():
- _register_module(app, module)
+ blueprint = import_string(middlewares[module])
+ app.register_blueprint(blueprint)
return app
| Improve the way that import middlewares | ## Code Before:
from __future__ import absolute_import, unicode_literals
from flask import Flask
from .middleware.me import me
from .cache import cache
def _register_module(app, module):
if module == 'douban':
from .middleware import douban
app.register_blueprint(douban.douban_api)
elif module == 'github':
from .middleware import github
app.register_blueprint(github.github_api)
elif module == 'instagram':
from .middleware import instagram
app.register_blueprint(instagram.instagram_api)
elif module == 'keybase':
from .middleware import keybase
app.register_blueprint(keybase.keybase_api)
elif module == 'medium':
from .middleware import medium
app.register_blueprint(medium.medium_api)
elif module == 'stackoverflow':
from .middleware import stackoverflow
app.register_blueprint(stackoverflow.stackoverflow_api)
def create_app(config):
app = Flask(__name__)
app.config.from_object(config)
cache.init_app(app)
modules = config.modules['modules']
app.register_blueprint(me)
for module in modules.keys():
_register_module(app, module)
return app
## Instruction:
Improve the way that import middlewares
## Code After:
from __future__ import absolute_import, unicode_literals
from flask import Flask
from werkzeug.utils import import_string
from me_api.middleware.me import me
from me_api.cache import cache
middlewares = {
'douban': 'me_api.middleware.douban:douban_api',
'github': 'me_api.middleware.github:github_api',
'instagram': 'me_api.middleware.instagram:instagram_api',
'keybase': 'me_api.middleware.keybase:keybase_api',
'medium': 'me_api.middleware.medium:medium_api',
'stackoverflow': 'me_api.middleware.stackoverflow:stackoverflow_api',
}
def create_app(config):
app = Flask(__name__)
app.config.from_object(config)
cache.init_app(app)
modules = config.modules['modules']
app.register_blueprint(me)
for module in modules.keys():
blueprint = import_string(middlewares[module])
app.register_blueprint(blueprint)
return app
|
from __future__ import absolute_import, unicode_literals
from flask import Flask
+ from werkzeug.utils import import_string
- from .middleware.me import me
+ from me_api.middleware.me import me
? ++++++
- from .cache import cache
+ from me_api.cache import cache
? ++++++
+ middlewares = {
+ 'douban': 'me_api.middleware.douban:douban_api',
+ 'github': 'me_api.middleware.github:github_api',
+ 'instagram': 'me_api.middleware.instagram:instagram_api',
+ 'keybase': 'me_api.middleware.keybase:keybase_api',
+ 'medium': 'me_api.middleware.medium:medium_api',
+ 'stackoverflow': 'me_api.middleware.stackoverflow:stackoverflow_api',
+ }
- def _register_module(app, module):
- if module == 'douban':
- from .middleware import douban
- app.register_blueprint(douban.douban_api)
- elif module == 'github':
- from .middleware import github
- app.register_blueprint(github.github_api)
- elif module == 'instagram':
- from .middleware import instagram
- app.register_blueprint(instagram.instagram_api)
- elif module == 'keybase':
- from .middleware import keybase
- app.register_blueprint(keybase.keybase_api)
- elif module == 'medium':
- from .middleware import medium
- app.register_blueprint(medium.medium_api)
- elif module == 'stackoverflow':
- from .middleware import stackoverflow
- app.register_blueprint(stackoverflow.stackoverflow_api)
def create_app(config):
app = Flask(__name__)
app.config.from_object(config)
cache.init_app(app)
modules = config.modules['modules']
app.register_blueprint(me)
for module in modules.keys():
- _register_module(app, module)
+ blueprint = import_string(middlewares[module])
+ app.register_blueprint(blueprint)
return app |
b03c8ebe8cc426e21b45f4de0d8d6e7176a4a647 | api/admin.py | api/admin.py | from django.contrib import admin
from api import models
class UserProfileAdmin(admin.ModelAdmin):
list_display = ('user', 'country', )
class EventAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('title',)}
list_display = ('title', 'status', 'location', 'country', 'start_date')
list_editable = ('status',)
list_filter = ('status', 'start_date')
filter_horizontal = ('audience',)
filter_horizontal = ('theme',)
admin.site.register(models.UserProfile, UserProfileAdmin)
admin.site.register(models.Event, EventAdmin)
admin.site.register(models.events.EventAudience)
admin.site.register(models.events.EventTheme)
| from django.contrib import admin
from api import models
class UserProfileAdmin(admin.ModelAdmin):
list_display = ('user', 'country', )
search_fields = ['user__email', 'user__username', 'user__first_name', 'user__last_name']
class EventAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('title',)}
list_display = ('title', 'status', 'location', 'country', 'start_date')
list_editable = ('status',)
list_filter = ('status', 'start_date')
filter_horizontal = ('audience',)
filter_horizontal = ('theme',)
admin.site.register(models.UserProfile, UserProfileAdmin)
admin.site.register(models.Event, EventAdmin)
admin.site.register(models.events.EventAudience)
admin.site.register(models.events.EventTheme)
| Allow searching by email, username and names in user profiles | Allow searching by email, username and names in user profiles
This is needed as user profiles need to be edited for setting main
contact flag and ambassador roles.
| Python | mit | codeeu/coding-events,michelesr/coding-events,michelesr/coding-events,michelesr/coding-events,codeeu/coding-events,codeeu/coding-events,michelesr/coding-events,codeeu/coding-events,codeeu/coding-events,michelesr/coding-events | from django.contrib import admin
from api import models
class UserProfileAdmin(admin.ModelAdmin):
list_display = ('user', 'country', )
-
+ search_fields = ['user__email', 'user__username', 'user__first_name', 'user__last_name']
class EventAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('title',)}
list_display = ('title', 'status', 'location', 'country', 'start_date')
list_editable = ('status',)
list_filter = ('status', 'start_date')
filter_horizontal = ('audience',)
filter_horizontal = ('theme',)
admin.site.register(models.UserProfile, UserProfileAdmin)
admin.site.register(models.Event, EventAdmin)
admin.site.register(models.events.EventAudience)
admin.site.register(models.events.EventTheme)
| Allow searching by email, username and names in user profiles | ## Code Before:
from django.contrib import admin
from api import models
class UserProfileAdmin(admin.ModelAdmin):
list_display = ('user', 'country', )
class EventAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('title',)}
list_display = ('title', 'status', 'location', 'country', 'start_date')
list_editable = ('status',)
list_filter = ('status', 'start_date')
filter_horizontal = ('audience',)
filter_horizontal = ('theme',)
admin.site.register(models.UserProfile, UserProfileAdmin)
admin.site.register(models.Event, EventAdmin)
admin.site.register(models.events.EventAudience)
admin.site.register(models.events.EventTheme)
## Instruction:
Allow searching by email, username and names in user profiles
## Code After:
from django.contrib import admin
from api import models
class UserProfileAdmin(admin.ModelAdmin):
list_display = ('user', 'country', )
search_fields = ['user__email', 'user__username', 'user__first_name', 'user__last_name']
class EventAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('title',)}
list_display = ('title', 'status', 'location', 'country', 'start_date')
list_editable = ('status',)
list_filter = ('status', 'start_date')
filter_horizontal = ('audience',)
filter_horizontal = ('theme',)
admin.site.register(models.UserProfile, UserProfileAdmin)
admin.site.register(models.Event, EventAdmin)
admin.site.register(models.events.EventAudience)
admin.site.register(models.events.EventTheme)
| from django.contrib import admin
from api import models
class UserProfileAdmin(admin.ModelAdmin):
list_display = ('user', 'country', )
-
+ search_fields = ['user__email', 'user__username', 'user__first_name', 'user__last_name']
class EventAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('title',)}
list_display = ('title', 'status', 'location', 'country', 'start_date')
list_editable = ('status',)
list_filter = ('status', 'start_date')
filter_horizontal = ('audience',)
filter_horizontal = ('theme',)
admin.site.register(models.UserProfile, UserProfileAdmin)
admin.site.register(models.Event, EventAdmin)
admin.site.register(models.events.EventAudience)
admin.site.register(models.events.EventTheme) |
daafe2152e13d32e7e03533151feeeac9464dddf | mycli/packages/expanded.py | mycli/packages/expanded.py | from .tabulate import _text_type
def pad(field, total, char=u" "):
return field + (char * (total - len(field)))
def get_separator(num, header_len, data_len):
total_len = header_len + data_len + 1
sep = u"-[ RECORD {0} ]".format(num)
if len(sep) < header_len:
sep = pad(sep, header_len - 1, u"-") + u"+"
if len(sep) < total_len:
sep = pad(sep, total_len, u"-")
return sep + u"\n"
def expanded_table(rows, headers):
header_len = max([len(x) for x in headers])
max_row_len = 0
results = []
padded_headers = [pad(x, header_len) + u" |" for x in headers]
header_len += 2
for row in rows:
row_len = max([len(_text_type(x)) for x in row])
row_result = []
if row_len > max_row_len:
max_row_len = row_len
for header, value in zip(padded_headers, row):
row_result.append(u"%s %s" % (header, value))
results.append('\n'.join(row_result))
output = []
for i, result in enumerate(results):
output.append(get_separator(i, header_len, max_row_len))
output.append(result)
output.append('\n')
return ''.join(output)
| from .tabulate import _text_type
def pad(field, total, char=u" "):
return field + (char * (total - len(field)))
def get_separator(num, header_len, data_len):
sep = u"***************************[ %d. row ]***************************\n" % (num + 1)
return sep
def expanded_table(rows, headers):
header_len = max([len(x) for x in headers])
max_row_len = 0
results = []
padded_headers = [pad(x, header_len) + u" |" for x in headers]
header_len += 2
for row in rows:
row_len = max([len(_text_type(x)) for x in row])
row_result = []
if row_len > max_row_len:
max_row_len = row_len
for header, value in zip(padded_headers, row):
row_result.append(u"%s %s" % (header, value))
results.append('\n'.join(row_result))
output = []
for i, result in enumerate(results):
output.append(get_separator(i, header_len, max_row_len))
output.append(result)
output.append('\n')
return ''.join(output)
| Fix formatting issue for \G. | Fix formatting issue for \G.
Closes #49
| Python | bsd-3-clause | ksmaheshkumar/mycli,douglasvegas/mycli,webwlsong/mycli,thanatoskira/mycli,tkuipers/mycli,qbdsoft/mycli,douglasvegas/mycli,chenpingzhao/mycli,D-e-e-m-o/mycli,oguzy/mycli,tkuipers/mycli,j-bennet/mycli,suzukaze/mycli,D-e-e-m-o/mycli,thanatoskira/mycli,suzukaze/mycli,mdsrosa/mycli,brewneaux/mycli,danieljwest/mycli,shaunstanislaus/mycli,chenpingzhao/mycli,oguzy/mycli,mattn/mycli,MnO2/rediscli,mdsrosa/mycli,ZuoGuocai/mycli,evook/mycli,evook/mycli,mattn/mycli,ksmaheshkumar/mycli,fw1121/mycli,steverobbins/mycli,MnO2/rediscli,adamchainz/mycli,jinstrive/mycli,nkhuyu/mycli,shoma/mycli,qbdsoft/mycli,martijnengler/mycli,shoma/mycli,webwlsong/mycli,fw1121/mycli,j-bennet/mycli,brewneaux/mycli,ZuoGuocai/mycli,martijnengler/mycli,danieljwest/mycli,nkhuyu/mycli,jinstrive/mycli,shaunstanislaus/mycli,adamchainz/mycli | from .tabulate import _text_type
def pad(field, total, char=u" "):
return field + (char * (total - len(field)))
def get_separator(num, header_len, data_len):
- total_len = header_len + data_len + 1
+ sep = u"***************************[ %d. row ]***************************\n" % (num + 1)
- sep = u"-[ RECORD {0} ]".format(num)
- if len(sep) < header_len:
- sep = pad(sep, header_len - 1, u"-") + u"+"
-
- if len(sep) < total_len:
- sep = pad(sep, total_len, u"-")
-
- return sep + u"\n"
+ return sep
def expanded_table(rows, headers):
header_len = max([len(x) for x in headers])
max_row_len = 0
results = []
padded_headers = [pad(x, header_len) + u" |" for x in headers]
header_len += 2
for row in rows:
row_len = max([len(_text_type(x)) for x in row])
row_result = []
if row_len > max_row_len:
max_row_len = row_len
for header, value in zip(padded_headers, row):
row_result.append(u"%s %s" % (header, value))
results.append('\n'.join(row_result))
output = []
for i, result in enumerate(results):
output.append(get_separator(i, header_len, max_row_len))
output.append(result)
output.append('\n')
return ''.join(output)
| Fix formatting issue for \G. | ## Code Before:
from .tabulate import _text_type
def pad(field, total, char=u" "):
return field + (char * (total - len(field)))
def get_separator(num, header_len, data_len):
total_len = header_len + data_len + 1
sep = u"-[ RECORD {0} ]".format(num)
if len(sep) < header_len:
sep = pad(sep, header_len - 1, u"-") + u"+"
if len(sep) < total_len:
sep = pad(sep, total_len, u"-")
return sep + u"\n"
def expanded_table(rows, headers):
header_len = max([len(x) for x in headers])
max_row_len = 0
results = []
padded_headers = [pad(x, header_len) + u" |" for x in headers]
header_len += 2
for row in rows:
row_len = max([len(_text_type(x)) for x in row])
row_result = []
if row_len > max_row_len:
max_row_len = row_len
for header, value in zip(padded_headers, row):
row_result.append(u"%s %s" % (header, value))
results.append('\n'.join(row_result))
output = []
for i, result in enumerate(results):
output.append(get_separator(i, header_len, max_row_len))
output.append(result)
output.append('\n')
return ''.join(output)
## Instruction:
Fix formatting issue for \G.
## Code After:
from .tabulate import _text_type
def pad(field, total, char=u" "):
return field + (char * (total - len(field)))
def get_separator(num, header_len, data_len):
sep = u"***************************[ %d. row ]***************************\n" % (num + 1)
return sep
def expanded_table(rows, headers):
header_len = max([len(x) for x in headers])
max_row_len = 0
results = []
padded_headers = [pad(x, header_len) + u" |" for x in headers]
header_len += 2
for row in rows:
row_len = max([len(_text_type(x)) for x in row])
row_result = []
if row_len > max_row_len:
max_row_len = row_len
for header, value in zip(padded_headers, row):
row_result.append(u"%s %s" % (header, value))
results.append('\n'.join(row_result))
output = []
for i, result in enumerate(results):
output.append(get_separator(i, header_len, max_row_len))
output.append(result)
output.append('\n')
return ''.join(output)
| from .tabulate import _text_type
def pad(field, total, char=u" "):
return field + (char * (total - len(field)))
def get_separator(num, header_len, data_len):
- total_len = header_len + data_len + 1
+ sep = u"***************************[ %d. row ]***************************\n" % (num + 1)
- sep = u"-[ RECORD {0} ]".format(num)
- if len(sep) < header_len:
- sep = pad(sep, header_len - 1, u"-") + u"+"
-
- if len(sep) < total_len:
- sep = pad(sep, total_len, u"-")
-
- return sep + u"\n"
? --------
+ return sep
def expanded_table(rows, headers):
header_len = max([len(x) for x in headers])
max_row_len = 0
results = []
padded_headers = [pad(x, header_len) + u" |" for x in headers]
header_len += 2
for row in rows:
row_len = max([len(_text_type(x)) for x in row])
row_result = []
if row_len > max_row_len:
max_row_len = row_len
for header, value in zip(padded_headers, row):
row_result.append(u"%s %s" % (header, value))
results.append('\n'.join(row_result))
output = []
for i, result in enumerate(results):
output.append(get_separator(i, header_len, max_row_len))
output.append(result)
output.append('\n')
return ''.join(output) |
b6eaabd47e98d51e4392c5419a59a75a0db45bf1 | geotrek/core/tests/test_forms.py | geotrek/core/tests/test_forms.py | from django.conf import settings
from django.test import TestCase
from unittest import skipIf
from geotrek.core.factories import TrailFactory
from geotrek.authent.factories import UserFactory
from geotrek.core.forms import TrailForm
@skipIf(not settings.TREKKING_TOPOLOGY_ENABLED, 'Test with dynamic segmentation only')
class TopologyFormTest(TestCase):
def test_save_form_when_topology_has_not_changed(self):
user = UserFactory()
topo = TrailFactory()
form = TrailForm(instance=topo, user=user)
self.assertEqual(topo, form.instance)
form.cleaned_data = {'topology': topo}
form.save()
self.assertEqual(topo, form.instance)
| from django.conf import settings
from django.test import TestCase
from unittest import skipIf
from geotrek.core.factories import TrailFactory, PathFactory
from geotrek.authent.factories import UserFactory
from geotrek.core.forms import TrailForm, PathForm
@skipIf(not settings.TREKKING_TOPOLOGY_ENABLED, 'Test with dynamic segmentation only')
class TopologyFormTest(TestCase):
def test_save_form_when_topology_has_not_changed(self):
user = UserFactory()
topo = TrailFactory()
form = TrailForm(instance=topo, user=user)
self.assertEqual(topo, form.instance)
form.cleaned_data = {'topology': topo}
form.save()
self.assertEqual(topo, form.instance)
class PathFormTest(TestCase):
def test_overlapping_path(self):
user = UserFactory()
PathFactory.create(geom='SRID=4326;LINESTRING(3 45, 3 46)')
# Just intersecting
form1 = PathForm(
user=user,
data={'geom': '{"geom": "LINESTRING(2.5 45.5, 3.5 45.5)", "snap": [null, null]}'}
)
self.assertTrue(form1.is_valid(), str(form1.errors))
# Overlapping
form2 = PathForm(
user=user,
data={'geom': '{"geom": "LINESTRING(3 45.5, 3 46.5)", "snap": [null, null]}'}
)
self.assertFalse(form2.is_valid(), str(form2.errors))
| Add tests for path overlapping check | Add tests for path overlapping check
| Python | bsd-2-clause | makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin | from django.conf import settings
from django.test import TestCase
from unittest import skipIf
- from geotrek.core.factories import TrailFactory
+ from geotrek.core.factories import TrailFactory, PathFactory
from geotrek.authent.factories import UserFactory
- from geotrek.core.forms import TrailForm
+ from geotrek.core.forms import TrailForm, PathForm
@skipIf(not settings.TREKKING_TOPOLOGY_ENABLED, 'Test with dynamic segmentation only')
class TopologyFormTest(TestCase):
def test_save_form_when_topology_has_not_changed(self):
user = UserFactory()
topo = TrailFactory()
form = TrailForm(instance=topo, user=user)
self.assertEqual(topo, form.instance)
form.cleaned_data = {'topology': topo}
form.save()
self.assertEqual(topo, form.instance)
+
+ class PathFormTest(TestCase):
+ def test_overlapping_path(self):
+ user = UserFactory()
+ PathFactory.create(geom='SRID=4326;LINESTRING(3 45, 3 46)')
+ # Just intersecting
+ form1 = PathForm(
+ user=user,
+ data={'geom': '{"geom": "LINESTRING(2.5 45.5, 3.5 45.5)", "snap": [null, null]}'}
+ )
+ self.assertTrue(form1.is_valid(), str(form1.errors))
+ # Overlapping
+ form2 = PathForm(
+ user=user,
+ data={'geom': '{"geom": "LINESTRING(3 45.5, 3 46.5)", "snap": [null, null]}'}
+ )
+ self.assertFalse(form2.is_valid(), str(form2.errors))
+ | Add tests for path overlapping check | ## Code Before:
from django.conf import settings
from django.test import TestCase
from unittest import skipIf
from geotrek.core.factories import TrailFactory
from geotrek.authent.factories import UserFactory
from geotrek.core.forms import TrailForm
@skipIf(not settings.TREKKING_TOPOLOGY_ENABLED, 'Test with dynamic segmentation only')
class TopologyFormTest(TestCase):
def test_save_form_when_topology_has_not_changed(self):
user = UserFactory()
topo = TrailFactory()
form = TrailForm(instance=topo, user=user)
self.assertEqual(topo, form.instance)
form.cleaned_data = {'topology': topo}
form.save()
self.assertEqual(topo, form.instance)
## Instruction:
Add tests for path overlapping check
## Code After:
from django.conf import settings
from django.test import TestCase
from unittest import skipIf
from geotrek.core.factories import TrailFactory, PathFactory
from geotrek.authent.factories import UserFactory
from geotrek.core.forms import TrailForm, PathForm
@skipIf(not settings.TREKKING_TOPOLOGY_ENABLED, 'Test with dynamic segmentation only')
class TopologyFormTest(TestCase):
def test_save_form_when_topology_has_not_changed(self):
user = UserFactory()
topo = TrailFactory()
form = TrailForm(instance=topo, user=user)
self.assertEqual(topo, form.instance)
form.cleaned_data = {'topology': topo}
form.save()
self.assertEqual(topo, form.instance)
class PathFormTest(TestCase):
def test_overlapping_path(self):
user = UserFactory()
PathFactory.create(geom='SRID=4326;LINESTRING(3 45, 3 46)')
# Just intersecting
form1 = PathForm(
user=user,
data={'geom': '{"geom": "LINESTRING(2.5 45.5, 3.5 45.5)", "snap": [null, null]}'}
)
self.assertTrue(form1.is_valid(), str(form1.errors))
# Overlapping
form2 = PathForm(
user=user,
data={'geom': '{"geom": "LINESTRING(3 45.5, 3 46.5)", "snap": [null, null]}'}
)
self.assertFalse(form2.is_valid(), str(form2.errors))
| from django.conf import settings
from django.test import TestCase
from unittest import skipIf
- from geotrek.core.factories import TrailFactory
+ from geotrek.core.factories import TrailFactory, PathFactory
? +++++++++++++
from geotrek.authent.factories import UserFactory
- from geotrek.core.forms import TrailForm
+ from geotrek.core.forms import TrailForm, PathForm
? ++++++++++
@skipIf(not settings.TREKKING_TOPOLOGY_ENABLED, 'Test with dynamic segmentation only')
class TopologyFormTest(TestCase):
def test_save_form_when_topology_has_not_changed(self):
user = UserFactory()
topo = TrailFactory()
form = TrailForm(instance=topo, user=user)
self.assertEqual(topo, form.instance)
form.cleaned_data = {'topology': topo}
form.save()
self.assertEqual(topo, form.instance)
+
+
+ class PathFormTest(TestCase):
+ def test_overlapping_path(self):
+ user = UserFactory()
+ PathFactory.create(geom='SRID=4326;LINESTRING(3 45, 3 46)')
+ # Just intersecting
+ form1 = PathForm(
+ user=user,
+ data={'geom': '{"geom": "LINESTRING(2.5 45.5, 3.5 45.5)", "snap": [null, null]}'}
+ )
+ self.assertTrue(form1.is_valid(), str(form1.errors))
+ # Overlapping
+ form2 = PathForm(
+ user=user,
+ data={'geom': '{"geom": "LINESTRING(3 45.5, 3 46.5)", "snap": [null, null]}'}
+ )
+ self.assertFalse(form2.is_valid(), str(form2.errors)) |
9787fb3a78d681aff25c6cbaac2c1ba842c4c7db | manila_ui/api/network.py | manila_ui/api/network.py |
from openstack_dashboard.api import base
from openstack_dashboard.api import network
from openstack_dashboard.api import neutron
from openstack_dashboard.api import nova
def _nova_network_list(request):
nets = nova.novaclient(request).networks.list()
for net in nets:
net.name_or_id = net.to_dict().get('label', net.to_dict().get('id'))
return nets
def _nova_network_get(request, nova_net_id):
net = nova.novaclient(request).networks.get(nova_net_id)
net.name_or_id = net.to_dict().get('label', net.to_dict().get('id'))
return net
class NetworkClient(network.NetworkClient):
def __init__(self, request):
super(NetworkClient, self).__init__(request)
if base.is_service_enabled(request, 'network'):
self.network_list = neutron.network_list
self.network_get = neutron.network_get
else:
self.network_list = _nova_network_list
self.network_get = _nova_network_get
def network_list(request):
return NetworkClient(request).network_list(request)
def network_get(request, net_id):
return NetworkClient(request).network_get(request, net_id)
|
from openstack_dashboard.api import neutron
def network_list(request):
return neutron.network_list(request)
def network_get(request, net_id):
return neutron.network_get(request, net_id)
| Fix compatibility with latest horizon | Fix compatibility with latest horizon
Class "NetworkClient" from "openstack_dashboards.api.network" module
was removed from horizon repo. So, remove its usage and use neutron
directly.
Change-Id: Idcf51553f64fae2254c224d4c6ef4fbb94e6f279
Closes-Bug: #1691466
| Python | apache-2.0 | openstack/manila-ui,openstack/manila-ui,openstack/manila-ui |
- from openstack_dashboard.api import base
- from openstack_dashboard.api import network
from openstack_dashboard.api import neutron
- from openstack_dashboard.api import nova
-
-
- def _nova_network_list(request):
- nets = nova.novaclient(request).networks.list()
- for net in nets:
- net.name_or_id = net.to_dict().get('label', net.to_dict().get('id'))
- return nets
-
-
- def _nova_network_get(request, nova_net_id):
- net = nova.novaclient(request).networks.get(nova_net_id)
- net.name_or_id = net.to_dict().get('label', net.to_dict().get('id'))
- return net
-
-
- class NetworkClient(network.NetworkClient):
- def __init__(self, request):
- super(NetworkClient, self).__init__(request)
- if base.is_service_enabled(request, 'network'):
- self.network_list = neutron.network_list
- self.network_get = neutron.network_get
- else:
- self.network_list = _nova_network_list
- self.network_get = _nova_network_get
def network_list(request):
- return NetworkClient(request).network_list(request)
+ return neutron.network_list(request)
def network_get(request, net_id):
- return NetworkClient(request).network_get(request, net_id)
+ return neutron.network_get(request, net_id)
| Fix compatibility with latest horizon | ## Code Before:
from openstack_dashboard.api import base
from openstack_dashboard.api import network
from openstack_dashboard.api import neutron
from openstack_dashboard.api import nova
def _nova_network_list(request):
nets = nova.novaclient(request).networks.list()
for net in nets:
net.name_or_id = net.to_dict().get('label', net.to_dict().get('id'))
return nets
def _nova_network_get(request, nova_net_id):
net = nova.novaclient(request).networks.get(nova_net_id)
net.name_or_id = net.to_dict().get('label', net.to_dict().get('id'))
return net
class NetworkClient(network.NetworkClient):
def __init__(self, request):
super(NetworkClient, self).__init__(request)
if base.is_service_enabled(request, 'network'):
self.network_list = neutron.network_list
self.network_get = neutron.network_get
else:
self.network_list = _nova_network_list
self.network_get = _nova_network_get
def network_list(request):
return NetworkClient(request).network_list(request)
def network_get(request, net_id):
return NetworkClient(request).network_get(request, net_id)
## Instruction:
Fix compatibility with latest horizon
## Code After:
from openstack_dashboard.api import neutron
def network_list(request):
return neutron.network_list(request)
def network_get(request, net_id):
return neutron.network_get(request, net_id)
|
- from openstack_dashboard.api import base
- from openstack_dashboard.api import network
from openstack_dashboard.api import neutron
- from openstack_dashboard.api import nova
-
-
- def _nova_network_list(request):
- nets = nova.novaclient(request).networks.list()
- for net in nets:
- net.name_or_id = net.to_dict().get('label', net.to_dict().get('id'))
- return nets
-
-
- def _nova_network_get(request, nova_net_id):
- net = nova.novaclient(request).networks.get(nova_net_id)
- net.name_or_id = net.to_dict().get('label', net.to_dict().get('id'))
- return net
-
-
- class NetworkClient(network.NetworkClient):
- def __init__(self, request):
- super(NetworkClient, self).__init__(request)
- if base.is_service_enabled(request, 'network'):
- self.network_list = neutron.network_list
- self.network_get = neutron.network_get
- else:
- self.network_list = _nova_network_list
- self.network_get = _nova_network_get
def network_list(request):
- return NetworkClient(request).network_list(request)
? ^ ^ ------ ----------
+ return neutron.network_list(request)
? ^ + ^
def network_get(request, net_id):
- return NetworkClient(request).network_get(request, net_id)
? ^ ^ ------ ----------
+ return neutron.network_get(request, net_id)
? ^ + ^
|
c2d7f4c6ae9042d1cc7f11fa82d7133e9b506ad7 | src/main/scripts/data_exports/export_json.py | src/main/scripts/data_exports/export_json.py | from lib.harvester import Harvester
from lib.cli_helper import is_writable_directory
import argparse
import logging
import json
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
logging.basicConfig(format="%(asctime)s-%(levelname)s-%(name)s - %(message)s")
parser = argparse.ArgumentParser(description="Export all publicly available Gazetteer data as one JSON file.")
parser.add_argument('-t', '--target', type=is_writable_directory, nargs='?', default="./gazetteer_export.json",
help="specify output file, default: './gazetteer_export.json'")
parser.add_argument('-p', '--polygons', action='store_true',
help="export place shape polygons, this will increase the file size significantly")
if __name__ == "__main__":
options = vars(parser.parse_args())
harvester = Harvester(options['polygons'])
places = harvester.get_data()
with open(options['target'], 'w') as outfile:
json.dump(places, outfile)
| from lib.harvester import Harvester
from lib.cli_helper import is_writable_directory
import argparse
import logging
import json
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
logging.basicConfig(format="%(asctime)s-%(levelname)s-%(name)s - %(message)s")
parser = argparse.ArgumentParser(description="Export all publicly available Gazetteer data as one JSON file.")
parser.add_argument('-t', '--target', type=is_writable_directory, nargs='?', default="./gazetteer_export.json",
help="specify output file, default: './gazetteer_export.json'")
parser.add_argument('-p', '--polygons', action='store_true',
help="export place shape polygons, this will increase the file size significantly")
if __name__ == "__main__":
options = vars(parser.parse_args())
harvester = Harvester(options['polygons'])
places = harvester.get_data()
with open(options['target'], 'w', encoding='utf-8') as outfile:
json.dump(places, outfile, ensure_ascii=False)
| Fix UTF-8 encoding for json exports | Fix UTF-8 encoding for json exports
| Python | apache-2.0 | dainst/gazetteer,dainst/gazetteer,dainst/gazetteer,dainst/gazetteer,dainst/gazetteer,dainst/gazetteer | from lib.harvester import Harvester
from lib.cli_helper import is_writable_directory
import argparse
import logging
import json
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
logging.basicConfig(format="%(asctime)s-%(levelname)s-%(name)s - %(message)s")
parser = argparse.ArgumentParser(description="Export all publicly available Gazetteer data as one JSON file.")
parser.add_argument('-t', '--target', type=is_writable_directory, nargs='?', default="./gazetteer_export.json",
help="specify output file, default: './gazetteer_export.json'")
parser.add_argument('-p', '--polygons', action='store_true',
help="export place shape polygons, this will increase the file size significantly")
if __name__ == "__main__":
options = vars(parser.parse_args())
harvester = Harvester(options['polygons'])
places = harvester.get_data()
- with open(options['target'], 'w') as outfile:
+ with open(options['target'], 'w', encoding='utf-8') as outfile:
- json.dump(places, outfile)
+ json.dump(places, outfile, ensure_ascii=False)
| Fix UTF-8 encoding for json exports | ## Code Before:
from lib.harvester import Harvester
from lib.cli_helper import is_writable_directory
import argparse
import logging
import json
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
logging.basicConfig(format="%(asctime)s-%(levelname)s-%(name)s - %(message)s")
parser = argparse.ArgumentParser(description="Export all publicly available Gazetteer data as one JSON file.")
parser.add_argument('-t', '--target', type=is_writable_directory, nargs='?', default="./gazetteer_export.json",
help="specify output file, default: './gazetteer_export.json'")
parser.add_argument('-p', '--polygons', action='store_true',
help="export place shape polygons, this will increase the file size significantly")
if __name__ == "__main__":
options = vars(parser.parse_args())
harvester = Harvester(options['polygons'])
places = harvester.get_data()
with open(options['target'], 'w') as outfile:
json.dump(places, outfile)
## Instruction:
Fix UTF-8 encoding for json exports
## Code After:
from lib.harvester import Harvester
from lib.cli_helper import is_writable_directory
import argparse
import logging
import json
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
logging.basicConfig(format="%(asctime)s-%(levelname)s-%(name)s - %(message)s")
parser = argparse.ArgumentParser(description="Export all publicly available Gazetteer data as one JSON file.")
parser.add_argument('-t', '--target', type=is_writable_directory, nargs='?', default="./gazetteer_export.json",
help="specify output file, default: './gazetteer_export.json'")
parser.add_argument('-p', '--polygons', action='store_true',
help="export place shape polygons, this will increase the file size significantly")
if __name__ == "__main__":
options = vars(parser.parse_args())
harvester = Harvester(options['polygons'])
places = harvester.get_data()
with open(options['target'], 'w', encoding='utf-8') as outfile:
json.dump(places, outfile, ensure_ascii=False)
| from lib.harvester import Harvester
from lib.cli_helper import is_writable_directory
import argparse
import logging
import json
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
logging.basicConfig(format="%(asctime)s-%(levelname)s-%(name)s - %(message)s")
parser = argparse.ArgumentParser(description="Export all publicly available Gazetteer data as one JSON file.")
parser.add_argument('-t', '--target', type=is_writable_directory, nargs='?', default="./gazetteer_export.json",
help="specify output file, default: './gazetteer_export.json'")
parser.add_argument('-p', '--polygons', action='store_true',
help="export place shape polygons, this will increase the file size significantly")
if __name__ == "__main__":
options = vars(parser.parse_args())
harvester = Harvester(options['polygons'])
places = harvester.get_data()
- with open(options['target'], 'w') as outfile:
+ with open(options['target'], 'w', encoding='utf-8') as outfile:
? ++++++++++++++++++
- json.dump(places, outfile)
+ json.dump(places, outfile, ensure_ascii=False)
? ++++++++++++++++++++
|
1a4994e86c01b33878d022574782df88b2f4016a | fuzzinator/call/file_reader_decorator.py | fuzzinator/call/file_reader_decorator.py |
import os
from . import CallableDecorator
class FileReaderDecorator(CallableDecorator):
"""
Decorator for SUTs that take input as a file path: saves the content of
the failing test case.
Moreover, the issue (if any) is also extended with the new ``'filename'``
property containing the name of the test case (as received in the ``test``
argument).
**Example configuration snippet:**
.. code-block:: ini
[sut.foo]
call=fuzzinator.call.SubprocessCall
call.decorate(0)=fuzzionator.call.FileReaderDecorator
[sut.foo.call]
# assuming that foo takes one file as input specified on command line
command=/home/alice/foo/bin/foo {test}
"""
def decorator(self, **kwargs):
def wrapper(fn):
def reader(*args, **kwargs):
issue = fn(*args, **kwargs)
if issue is not None:
with open(issue['test'], 'rb') as f:
issue['filename'] = os.path.basename(issue['test'])
issue['test'] = f.read()
return issue
return reader
return wrapper
|
import os
from . import CallableDecorator
class FileReaderDecorator(CallableDecorator):
"""
Decorator for SUTs that take input as a file path: saves the content of
the failing test case.
Moreover, the issue (if any) is also extended with the new ``'filename'``
property containing the name of the test case (as received in the ``test``
argument).
**Example configuration snippet:**
.. code-block:: ini
[sut.foo]
call=fuzzinator.call.SubprocessCall
call.decorate(0)=fuzzionator.call.FileReaderDecorator
[sut.foo.call]
# assuming that foo takes one file as input specified on command line
command=/home/alice/foo/bin/foo {test}
"""
def decorator(self, **kwargs):
def wrapper(fn):
def reader(*args, **kwargs):
issue = fn(*args, **kwargs)
if issue is not None:
with open(kwargs['test'], 'rb') as f:
issue['filename'] = os.path.basename(kwargs['test'])
issue['test'] = f.read()
return issue
return reader
return wrapper
| Fix test extraction in FileReaderDecorator. | Fix test extraction in FileReaderDecorator.
| Python | bsd-3-clause | renatahodovan/fuzzinator,akosthekiss/fuzzinator,renatahodovan/fuzzinator,akosthekiss/fuzzinator,akosthekiss/fuzzinator,renatahodovan/fuzzinator,akosthekiss/fuzzinator,renatahodovan/fuzzinator |
import os
from . import CallableDecorator
class FileReaderDecorator(CallableDecorator):
"""
Decorator for SUTs that take input as a file path: saves the content of
the failing test case.
Moreover, the issue (if any) is also extended with the new ``'filename'``
property containing the name of the test case (as received in the ``test``
argument).
**Example configuration snippet:**
.. code-block:: ini
[sut.foo]
call=fuzzinator.call.SubprocessCall
call.decorate(0)=fuzzionator.call.FileReaderDecorator
[sut.foo.call]
# assuming that foo takes one file as input specified on command line
command=/home/alice/foo/bin/foo {test}
"""
def decorator(self, **kwargs):
def wrapper(fn):
def reader(*args, **kwargs):
issue = fn(*args, **kwargs)
if issue is not None:
- with open(issue['test'], 'rb') as f:
+ with open(kwargs['test'], 'rb') as f:
- issue['filename'] = os.path.basename(issue['test'])
+ issue['filename'] = os.path.basename(kwargs['test'])
issue['test'] = f.read()
return issue
return reader
return wrapper
| Fix test extraction in FileReaderDecorator. | ## Code Before:
import os
from . import CallableDecorator
class FileReaderDecorator(CallableDecorator):
"""
Decorator for SUTs that take input as a file path: saves the content of
the failing test case.
Moreover, the issue (if any) is also extended with the new ``'filename'``
property containing the name of the test case (as received in the ``test``
argument).
**Example configuration snippet:**
.. code-block:: ini
[sut.foo]
call=fuzzinator.call.SubprocessCall
call.decorate(0)=fuzzionator.call.FileReaderDecorator
[sut.foo.call]
# assuming that foo takes one file as input specified on command line
command=/home/alice/foo/bin/foo {test}
"""
def decorator(self, **kwargs):
def wrapper(fn):
def reader(*args, **kwargs):
issue = fn(*args, **kwargs)
if issue is not None:
with open(issue['test'], 'rb') as f:
issue['filename'] = os.path.basename(issue['test'])
issue['test'] = f.read()
return issue
return reader
return wrapper
## Instruction:
Fix test extraction in FileReaderDecorator.
## Code After:
import os
from . import CallableDecorator
class FileReaderDecorator(CallableDecorator):
"""
Decorator for SUTs that take input as a file path: saves the content of
the failing test case.
Moreover, the issue (if any) is also extended with the new ``'filename'``
property containing the name of the test case (as received in the ``test``
argument).
**Example configuration snippet:**
.. code-block:: ini
[sut.foo]
call=fuzzinator.call.SubprocessCall
call.decorate(0)=fuzzionator.call.FileReaderDecorator
[sut.foo.call]
# assuming that foo takes one file as input specified on command line
command=/home/alice/foo/bin/foo {test}
"""
def decorator(self, **kwargs):
def wrapper(fn):
def reader(*args, **kwargs):
issue = fn(*args, **kwargs)
if issue is not None:
with open(kwargs['test'], 'rb') as f:
issue['filename'] = os.path.basename(kwargs['test'])
issue['test'] = f.read()
return issue
return reader
return wrapper
|
import os
from . import CallableDecorator
class FileReaderDecorator(CallableDecorator):
"""
Decorator for SUTs that take input as a file path: saves the content of
the failing test case.
Moreover, the issue (if any) is also extended with the new ``'filename'``
property containing the name of the test case (as received in the ``test``
argument).
**Example configuration snippet:**
.. code-block:: ini
[sut.foo]
call=fuzzinator.call.SubprocessCall
call.decorate(0)=fuzzionator.call.FileReaderDecorator
[sut.foo.call]
# assuming that foo takes one file as input specified on command line
command=/home/alice/foo/bin/foo {test}
"""
def decorator(self, **kwargs):
def wrapper(fn):
def reader(*args, **kwargs):
issue = fn(*args, **kwargs)
if issue is not None:
- with open(issue['test'], 'rb') as f:
? ^ ---
+ with open(kwargs['test'], 'rb') as f:
? ^^^^^
- issue['filename'] = os.path.basename(issue['test'])
? ^ ---
+ issue['filename'] = os.path.basename(kwargs['test'])
? ^^^^^
issue['test'] = f.read()
return issue
return reader
return wrapper |
07dc719807a6d890fa33338746caca61704de0a1 | src/genbank-gff-to-nquads.py | src/genbank-gff-to-nquads.py |
import jargparse
#################
### CONSTANTS ###
#################
metadataPrefix = '#'
accessionKey = '#!genome-build-accession NCBI_Assembly:'
locusTagAttributeKey = 'locus_tag'
#################
### FUNCTIONS ###
#################
def parseRecord(record, locusTags):
components = record.split()
type = components[2]
rawAttributes = components[8]
if type == 'gene':
attributes = rawAttributes.split(';')
for a in attributes:
(key, value) = a.split('=')
# print a
if key == locusTagAttributeKey:
locusTags.append(value)
parser = jargparse.ArgParser('Convert Genbank GFF into an n-quad file')
parser.add_argument('gffPath', help='path to the GFF')
parser.add_argument('outPath', help='path to output the n-quads')
args = parser.parse_args()
accessionIdentifier = 'NONE FOUND'
locusTags = []
with open(args.gffPath) as f:
for line in f:
line = line.strip()
if line.startswith(metadataPrefix):
if line.startswith(accessionKey):
accessionIdentifier = line[len(accessionKey):]
else:
parseRecord(line, locusTags)
with open(args.outPath, 'w') as f:
for locusTag in locusTags:
f.write('<%s> <locus> "%s" .\n' % (accessionIdentifier, locusTag))
|
import jargparse
#################
### CONSTANTS ###
#################
metadataPrefix = '#'
accessionKey = '#!genome-build-accession NCBI_Assembly:'
#################
### FUNCTIONS ###
#################
def parseRecord(record, locusTags):
locusTagAttributeKey = 'locus_tag'
components = record.split()
type = components[2]
rawAttributes = components[8]
if type == 'gene':
attributes = rawAttributes.split(';')
for a in attributes:
(key, value) = a.split('=')
# print a
if key == locusTagAttributeKey:
locusTags.append(value)
parser = jargparse.ArgParser('Convert Genbank GFF into an n-quad file')
parser.add_argument('gffPath', help='path to the GFF')
parser.add_argument('outPath', help='path to output the n-quads')
args = parser.parse_args()
accessionIdentifier = 'NONE FOUND'
locusTags = []
with open(args.gffPath) as f:
for line in f:
line = line.strip()
if line.startswith(metadataPrefix):
if line.startswith(accessionKey):
accessionIdentifier = line[len(accessionKey):]
else:
parseRecord(line, locusTags)
with open(args.outPath, 'w') as f:
for locusTag in locusTags:
f.write('<%s> <locus> "%s" .\n' % (accessionIdentifier, locusTag))
| Move locus tag attribute key name into the function that uses it | Move locus tag attribute key name into the function that uses it
| Python | apache-2.0 | justinccdev/biolta |
import jargparse
#################
### CONSTANTS ###
#################
metadataPrefix = '#'
accessionKey = '#!genome-build-accession NCBI_Assembly:'
- locusTagAttributeKey = 'locus_tag'
#################
### FUNCTIONS ###
#################
def parseRecord(record, locusTags):
+ locusTagAttributeKey = 'locus_tag'
+
components = record.split()
type = components[2]
rawAttributes = components[8]
if type == 'gene':
attributes = rawAttributes.split(';')
for a in attributes:
(key, value) = a.split('=')
# print a
if key == locusTagAttributeKey:
locusTags.append(value)
parser = jargparse.ArgParser('Convert Genbank GFF into an n-quad file')
parser.add_argument('gffPath', help='path to the GFF')
parser.add_argument('outPath', help='path to output the n-quads')
args = parser.parse_args()
accessionIdentifier = 'NONE FOUND'
locusTags = []
with open(args.gffPath) as f:
for line in f:
line = line.strip()
if line.startswith(metadataPrefix):
if line.startswith(accessionKey):
accessionIdentifier = line[len(accessionKey):]
else:
parseRecord(line, locusTags)
with open(args.outPath, 'w') as f:
for locusTag in locusTags:
f.write('<%s> <locus> "%s" .\n' % (accessionIdentifier, locusTag))
| Move locus tag attribute key name into the function that uses it | ## Code Before:
import jargparse
#################
### CONSTANTS ###
#################
metadataPrefix = '#'
accessionKey = '#!genome-build-accession NCBI_Assembly:'
locusTagAttributeKey = 'locus_tag'
#################
### FUNCTIONS ###
#################
def parseRecord(record, locusTags):
components = record.split()
type = components[2]
rawAttributes = components[8]
if type == 'gene':
attributes = rawAttributes.split(';')
for a in attributes:
(key, value) = a.split('=')
# print a
if key == locusTagAttributeKey:
locusTags.append(value)
parser = jargparse.ArgParser('Convert Genbank GFF into an n-quad file')
parser.add_argument('gffPath', help='path to the GFF')
parser.add_argument('outPath', help='path to output the n-quads')
args = parser.parse_args()
accessionIdentifier = 'NONE FOUND'
locusTags = []
with open(args.gffPath) as f:
for line in f:
line = line.strip()
if line.startswith(metadataPrefix):
if line.startswith(accessionKey):
accessionIdentifier = line[len(accessionKey):]
else:
parseRecord(line, locusTags)
with open(args.outPath, 'w') as f:
for locusTag in locusTags:
f.write('<%s> <locus> "%s" .\n' % (accessionIdentifier, locusTag))
## Instruction:
Move locus tag attribute key name into the function that uses it
## Code After:
import jargparse
#################
### CONSTANTS ###
#################
metadataPrefix = '#'
accessionKey = '#!genome-build-accession NCBI_Assembly:'
#################
### FUNCTIONS ###
#################
def parseRecord(record, locusTags):
locusTagAttributeKey = 'locus_tag'
components = record.split()
type = components[2]
rawAttributes = components[8]
if type == 'gene':
attributes = rawAttributes.split(';')
for a in attributes:
(key, value) = a.split('=')
# print a
if key == locusTagAttributeKey:
locusTags.append(value)
parser = jargparse.ArgParser('Convert Genbank GFF into an n-quad file')
parser.add_argument('gffPath', help='path to the GFF')
parser.add_argument('outPath', help='path to output the n-quads')
args = parser.parse_args()
accessionIdentifier = 'NONE FOUND'
locusTags = []
with open(args.gffPath) as f:
for line in f:
line = line.strip()
if line.startswith(metadataPrefix):
if line.startswith(accessionKey):
accessionIdentifier = line[len(accessionKey):]
else:
parseRecord(line, locusTags)
with open(args.outPath, 'w') as f:
for locusTag in locusTags:
f.write('<%s> <locus> "%s" .\n' % (accessionIdentifier, locusTag))
|
import jargparse
#################
### CONSTANTS ###
#################
metadataPrefix = '#'
accessionKey = '#!genome-build-accession NCBI_Assembly:'
- locusTagAttributeKey = 'locus_tag'
#################
### FUNCTIONS ###
#################
def parseRecord(record, locusTags):
+ locusTagAttributeKey = 'locus_tag'
+
components = record.split()
type = components[2]
rawAttributes = components[8]
if type == 'gene':
attributes = rawAttributes.split(';')
for a in attributes:
(key, value) = a.split('=')
# print a
if key == locusTagAttributeKey:
locusTags.append(value)
parser = jargparse.ArgParser('Convert Genbank GFF into an n-quad file')
parser.add_argument('gffPath', help='path to the GFF')
parser.add_argument('outPath', help='path to output the n-quads')
args = parser.parse_args()
accessionIdentifier = 'NONE FOUND'
locusTags = []
with open(args.gffPath) as f:
for line in f:
line = line.strip()
if line.startswith(metadataPrefix):
if line.startswith(accessionKey):
accessionIdentifier = line[len(accessionKey):]
else:
parseRecord(line, locusTags)
with open(args.outPath, 'w') as f:
for locusTag in locusTags:
f.write('<%s> <locus> "%s" .\n' % (accessionIdentifier, locusTag)) |
d5697d6176dd9a3d54abc13d38f94f1a326eac84 | dog/core/botcollection.py | dog/core/botcollection.py | import discord
def user_to_bot_ratio(guild: discord.Guild):
""" Calculates the user to bot ratio for a guild. """
bots = len(list(filter(lambda u: u.bot, guild.members)))
users = len(list(filter(lambda u: not u.bot, guild.members)))
ratio = bots / users
return ratio
async def is_blacklisted(bot, guild_id: int) -> bool:
""" Returns a bool indicating whether a guild has been blacklisted. """
async with bot.pgpool.acquire() as conn:
blacklisted_record = await conn.fetchrow('SELECT * FROM blacklisted_guilds WHERE guild_id = $1', guild_id)
return blacklisted_record is not None
async def is_bot_collection(bot, guild: discord.Guild):
""" Returns a bool indicating whether a guild is a collection. """
if await is_blacklisted(bot, guild.id):
return True
# keywords in the guild name
if any([keyword in guild.name.lower() for keyword in ('bot collection', 'bot hell')]):
return True
# special guilds that shouldn't be classified as a bot collection
if guild.id in (110373943822540800, 228317351672545290):
return False
# ratio too big!
if user_to_bot_ratio(guild) >= 8:
return True
return False
| import discord
def user_to_bot_ratio(guild: discord.Guild):
bots, users = 0, 0
for member in guild.bots:
if member.bot:
bots += 1
else:
users += 1
return bots / users
async def is_blacklisted(bot, guild_id: int) -> bool:
""" Returns a bool indicating whether a guild has been blacklisted. """
async with bot.pgpool.acquire() as conn:
blacklisted_record = await conn.fetchrow('SELECT * FROM blacklisted_guilds WHERE guild_id = $1', guild_id)
return blacklisted_record is not None
async def is_bot_collection(bot, guild: discord.Guild):
""" Returns a bool indicating whether a guild is a collection. """
if await is_blacklisted(bot, guild.id):
return True
# keywords in the guild name
if any([keyword in guild.name.lower() for keyword in ('bot collection', 'bot hell')]):
return True
# special guilds that shouldn't be classified as a bot collection
if guild.id in (110373943822540800, 228317351672545290):
return False
# ratio too big!
if user_to_bot_ratio(guild) >= 8:
return True
return False
| Use Fuyu's VeryCool™ UTBR impl | Use Fuyu's VeryCool™ UTBR impl
| Python | mit | slice/dogbot,sliceofcode/dogbot,slice/dogbot,sliceofcode/dogbot,slice/dogbot | import discord
def user_to_bot_ratio(guild: discord.Guild):
- """ Calculates the user to bot ratio for a guild. """
- bots = len(list(filter(lambda u: u.bot, guild.members)))
- users = len(list(filter(lambda u: not u.bot, guild.members)))
+ bots, users = 0, 0
+ for member in guild.bots:
+ if member.bot:
+ bots += 1
+ else:
+ users += 1
- ratio = bots / users
+ return bots / users
- return ratio
+
async def is_blacklisted(bot, guild_id: int) -> bool:
""" Returns a bool indicating whether a guild has been blacklisted. """
async with bot.pgpool.acquire() as conn:
blacklisted_record = await conn.fetchrow('SELECT * FROM blacklisted_guilds WHERE guild_id = $1', guild_id)
return blacklisted_record is not None
async def is_bot_collection(bot, guild: discord.Guild):
""" Returns a bool indicating whether a guild is a collection. """
if await is_blacklisted(bot, guild.id):
return True
# keywords in the guild name
if any([keyword in guild.name.lower() for keyword in ('bot collection', 'bot hell')]):
return True
# special guilds that shouldn't be classified as a bot collection
if guild.id in (110373943822540800, 228317351672545290):
return False
# ratio too big!
if user_to_bot_ratio(guild) >= 8:
return True
return False
| Use Fuyu's VeryCool™ UTBR impl | ## Code Before:
import discord
def user_to_bot_ratio(guild: discord.Guild):
""" Calculates the user to bot ratio for a guild. """
bots = len(list(filter(lambda u: u.bot, guild.members)))
users = len(list(filter(lambda u: not u.bot, guild.members)))
ratio = bots / users
return ratio
async def is_blacklisted(bot, guild_id: int) -> bool:
""" Returns a bool indicating whether a guild has been blacklisted. """
async with bot.pgpool.acquire() as conn:
blacklisted_record = await conn.fetchrow('SELECT * FROM blacklisted_guilds WHERE guild_id = $1', guild_id)
return blacklisted_record is not None
async def is_bot_collection(bot, guild: discord.Guild):
""" Returns a bool indicating whether a guild is a collection. """
if await is_blacklisted(bot, guild.id):
return True
# keywords in the guild name
if any([keyword in guild.name.lower() for keyword in ('bot collection', 'bot hell')]):
return True
# special guilds that shouldn't be classified as a bot collection
if guild.id in (110373943822540800, 228317351672545290):
return False
# ratio too big!
if user_to_bot_ratio(guild) >= 8:
return True
return False
## Instruction:
Use Fuyu's VeryCool™ UTBR impl
## Code After:
import discord
def user_to_bot_ratio(guild: discord.Guild):
bots, users = 0, 0
for member in guild.bots:
if member.bot:
bots += 1
else:
users += 1
return bots / users
async def is_blacklisted(bot, guild_id: int) -> bool:
""" Returns a bool indicating whether a guild has been blacklisted. """
async with bot.pgpool.acquire() as conn:
blacklisted_record = await conn.fetchrow('SELECT * FROM blacklisted_guilds WHERE guild_id = $1', guild_id)
return blacklisted_record is not None
async def is_bot_collection(bot, guild: discord.Guild):
""" Returns a bool indicating whether a guild is a collection. """
if await is_blacklisted(bot, guild.id):
return True
# keywords in the guild name
if any([keyword in guild.name.lower() for keyword in ('bot collection', 'bot hell')]):
return True
# special guilds that shouldn't be classified as a bot collection
if guild.id in (110373943822540800, 228317351672545290):
return False
# ratio too big!
if user_to_bot_ratio(guild) >= 8:
return True
return False
| import discord
def user_to_bot_ratio(guild: discord.Guild):
- """ Calculates the user to bot ratio for a guild. """
- bots = len(list(filter(lambda u: u.bot, guild.members)))
- users = len(list(filter(lambda u: not u.bot, guild.members)))
+ bots, users = 0, 0
+ for member in guild.bots:
+ if member.bot:
+ bots += 1
+ else:
+ users += 1
- ratio = bots / users
? ^ ^^^^
+ return bots / users
? ^ ^^^
- return ratio
+
async def is_blacklisted(bot, guild_id: int) -> bool:
""" Returns a bool indicating whether a guild has been blacklisted. """
async with bot.pgpool.acquire() as conn:
blacklisted_record = await conn.fetchrow('SELECT * FROM blacklisted_guilds WHERE guild_id = $1', guild_id)
return blacklisted_record is not None
async def is_bot_collection(bot, guild: discord.Guild):
""" Returns a bool indicating whether a guild is a collection. """
if await is_blacklisted(bot, guild.id):
return True
# keywords in the guild name
if any([keyword in guild.name.lower() for keyword in ('bot collection', 'bot hell')]):
return True
# special guilds that shouldn't be classified as a bot collection
if guild.id in (110373943822540800, 228317351672545290):
return False
# ratio too big!
if user_to_bot_ratio(guild) >= 8:
return True
return False |
62c9322cf1508eafa6bd3061d1f047ce42b95804 | byceps/blueprints/ticketing/views.py | byceps/blueprints/ticketing/views.py |
from flask import abort, g
from ...services.party import service as party_service
from ...services.ticketing import ticket_service
from ...util.framework.blueprint import create_blueprint
from ...util.iterables import find
from ...util.framework.templating import templated
blueprint = create_blueprint('ticketing', __name__)
@blueprint.route('/mine')
@templated
def index_mine():
"""List tickets related to the current user."""
current_user = _get_current_user_or_403()
party = party_service.find_party(g.party_id)
tickets = ticket_service.find_tickets_related_to_user_for_party(
current_user.id, party.id)
current_user_uses_any_ticket = find(
lambda t: t.used_by_id == current_user.id, tickets)
return {
'party_title': party.title,
'tickets': tickets,
'current_user_uses_any_ticket': current_user_uses_any_ticket,
}
def _get_current_user_or_403():
user = g.current_user
if not user.is_active:
abort(403)
return user
|
from flask import abort, g
from ...services.party import service as party_service
from ...services.ticketing import ticket_service
from ...util.framework.blueprint import create_blueprint
from ...util.iterables import find
from ...util.framework.templating import templated
blueprint = create_blueprint('ticketing', __name__)
@blueprint.route('/mine')
@templated
def index_mine():
"""List tickets related to the current user."""
current_user = _get_current_user_or_403()
party = party_service.find_party(g.party_id)
tickets = ticket_service.find_tickets_related_to_user_for_party(
current_user.id, party.id)
tickets = [ticket for ticket in tickets if not ticket.revoked]
current_user_uses_any_ticket = find(
lambda t: t.used_by_id == current_user.id, tickets)
return {
'party_title': party.title,
'tickets': tickets,
'current_user_uses_any_ticket': current_user_uses_any_ticket,
}
def _get_current_user_or_403():
user = g.current_user
if not user.is_active:
abort(403)
return user
| Hide revoked tickets from user in personal ticket list | Hide revoked tickets from user in personal ticket list
| Python | bsd-3-clause | m-ober/byceps,m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps |
from flask import abort, g
from ...services.party import service as party_service
from ...services.ticketing import ticket_service
from ...util.framework.blueprint import create_blueprint
from ...util.iterables import find
from ...util.framework.templating import templated
blueprint = create_blueprint('ticketing', __name__)
@blueprint.route('/mine')
@templated
def index_mine():
"""List tickets related to the current user."""
current_user = _get_current_user_or_403()
party = party_service.find_party(g.party_id)
tickets = ticket_service.find_tickets_related_to_user_for_party(
current_user.id, party.id)
+ tickets = [ticket for ticket in tickets if not ticket.revoked]
+
current_user_uses_any_ticket = find(
lambda t: t.used_by_id == current_user.id, tickets)
return {
'party_title': party.title,
'tickets': tickets,
'current_user_uses_any_ticket': current_user_uses_any_ticket,
}
def _get_current_user_or_403():
user = g.current_user
if not user.is_active:
abort(403)
return user
| Hide revoked tickets from user in personal ticket list | ## Code Before:
from flask import abort, g
from ...services.party import service as party_service
from ...services.ticketing import ticket_service
from ...util.framework.blueprint import create_blueprint
from ...util.iterables import find
from ...util.framework.templating import templated
blueprint = create_blueprint('ticketing', __name__)
@blueprint.route('/mine')
@templated
def index_mine():
"""List tickets related to the current user."""
current_user = _get_current_user_or_403()
party = party_service.find_party(g.party_id)
tickets = ticket_service.find_tickets_related_to_user_for_party(
current_user.id, party.id)
current_user_uses_any_ticket = find(
lambda t: t.used_by_id == current_user.id, tickets)
return {
'party_title': party.title,
'tickets': tickets,
'current_user_uses_any_ticket': current_user_uses_any_ticket,
}
def _get_current_user_or_403():
user = g.current_user
if not user.is_active:
abort(403)
return user
## Instruction:
Hide revoked tickets from user in personal ticket list
## Code After:
from flask import abort, g
from ...services.party import service as party_service
from ...services.ticketing import ticket_service
from ...util.framework.blueprint import create_blueprint
from ...util.iterables import find
from ...util.framework.templating import templated
blueprint = create_blueprint('ticketing', __name__)
@blueprint.route('/mine')
@templated
def index_mine():
"""List tickets related to the current user."""
current_user = _get_current_user_or_403()
party = party_service.find_party(g.party_id)
tickets = ticket_service.find_tickets_related_to_user_for_party(
current_user.id, party.id)
tickets = [ticket for ticket in tickets if not ticket.revoked]
current_user_uses_any_ticket = find(
lambda t: t.used_by_id == current_user.id, tickets)
return {
'party_title': party.title,
'tickets': tickets,
'current_user_uses_any_ticket': current_user_uses_any_ticket,
}
def _get_current_user_or_403():
user = g.current_user
if not user.is_active:
abort(403)
return user
|
from flask import abort, g
from ...services.party import service as party_service
from ...services.ticketing import ticket_service
from ...util.framework.blueprint import create_blueprint
from ...util.iterables import find
from ...util.framework.templating import templated
blueprint = create_blueprint('ticketing', __name__)
@blueprint.route('/mine')
@templated
def index_mine():
"""List tickets related to the current user."""
current_user = _get_current_user_or_403()
party = party_service.find_party(g.party_id)
tickets = ticket_service.find_tickets_related_to_user_for_party(
current_user.id, party.id)
+ tickets = [ticket for ticket in tickets if not ticket.revoked]
+
current_user_uses_any_ticket = find(
lambda t: t.used_by_id == current_user.id, tickets)
return {
'party_title': party.title,
'tickets': tickets,
'current_user_uses_any_ticket': current_user_uses_any_ticket,
}
def _get_current_user_or_403():
user = g.current_user
if not user.is_active:
abort(403)
return user |
5bf441e34b672a5a369ad7e42cdc2fc7f7699476 | publishers/base_publisher.py | publishers/base_publisher.py | from shared.base_component import BaseComponent
class BasePublisher(BaseComponent):
def __init__(self, conf):
BaseComponent.__init__(self, conf)
def publish(self, message):
pass
def __call__(self, message):
if self.query.match(message):
message = self.project.transform(message)
self.publish(message)
def close(self):
pass
| from shared.base_component import BaseComponent
class BasePublisher(BaseComponent):
def __init__(self, conf):
BaseComponent.__init__(self, conf)
def publish(self, message):
pass
def __call__(self, message):
if self.query.match(message):
message = self.project.transform(message)
if message is not None:
self.publish(message)
def close(self):
pass
| Discard None values in projections in publishers | Discard None values in projections in publishers
| Python | mit | weapp/miner | from shared.base_component import BaseComponent
class BasePublisher(BaseComponent):
def __init__(self, conf):
BaseComponent.__init__(self, conf)
def publish(self, message):
pass
def __call__(self, message):
if self.query.match(message):
message = self.project.transform(message)
+ if message is not None:
- self.publish(message)
+ self.publish(message)
def close(self):
pass
| Discard None values in projections in publishers | ## Code Before:
from shared.base_component import BaseComponent
class BasePublisher(BaseComponent):
def __init__(self, conf):
BaseComponent.__init__(self, conf)
def publish(self, message):
pass
def __call__(self, message):
if self.query.match(message):
message = self.project.transform(message)
self.publish(message)
def close(self):
pass
## Instruction:
Discard None values in projections in publishers
## Code After:
from shared.base_component import BaseComponent
class BasePublisher(BaseComponent):
def __init__(self, conf):
BaseComponent.__init__(self, conf)
def publish(self, message):
pass
def __call__(self, message):
if self.query.match(message):
message = self.project.transform(message)
if message is not None:
self.publish(message)
def close(self):
pass
| from shared.base_component import BaseComponent
class BasePublisher(BaseComponent):
def __init__(self, conf):
BaseComponent.__init__(self, conf)
def publish(self, message):
pass
def __call__(self, message):
if self.query.match(message):
message = self.project.transform(message)
+ if message is not None:
- self.publish(message)
+ self.publish(message)
? ++++
def close(self):
pass |
da9058064e2a94f717abe2f97af80d2daa4fa292 | likert_field/models.py | likert_field/models.py | from __future__ import unicode_literals
from django.db import models
from django.utils.translation import ugettext_lazy as _
import likert_field.forms as forms
class LikertField(models.IntegerField):
"""A Likert field is simply stored as an IntegerField"""
description = _('Likert item field')
def __init__(self, *args, **kwargs):
if 'null' not in kwargs and not kwargs.get('null'):
kwargs['null'] = True
super(LikertField, self).__init__(*args, **kwargs)
def formfield(self, **kwargs):
defaults = {
'min_value': 0,
'form_class': forms.LikertField
}
defaults.update(kwargs)
return super(LikertField, self).formfield(**defaults)
| from __future__ import unicode_literals
from six import string_types
from django.db import models
from django.utils.translation import ugettext_lazy as _
import likert_field.forms as forms
class LikertField(models.IntegerField):
"""A Likert field is simply stored as an IntegerField"""
description = _('Likert item field')
def __init__(self, *args, **kwargs):
if 'null' not in kwargs and not kwargs.get('null'):
kwargs['null'] = True
super(LikertField, self).__init__(*args, **kwargs)
def get_prep_value(self, value):
"""The field expects a number as a string (ie. '2').
Unscored fields are empty strings and are stored as NULL
"""
if value is None:
return None
if isinstance(value, string_types) and len(value) == 0:
return None
return int(value)
def formfield(self, **kwargs):
defaults = {
'min_value': 0,
'form_class': forms.LikertField
}
defaults.update(kwargs)
return super(LikertField, self).formfield(**defaults)
| Handle empty strings from unanswered items | Handle empty strings from unanswered items
| Python | bsd-3-clause | kelvinwong-ca/django-likert-field,kelvinwong-ca/django-likert-field | from __future__ import unicode_literals
+
+ from six import string_types
from django.db import models
from django.utils.translation import ugettext_lazy as _
import likert_field.forms as forms
class LikertField(models.IntegerField):
"""A Likert field is simply stored as an IntegerField"""
description = _('Likert item field')
def __init__(self, *args, **kwargs):
if 'null' not in kwargs and not kwargs.get('null'):
kwargs['null'] = True
super(LikertField, self).__init__(*args, **kwargs)
+ def get_prep_value(self, value):
+ """The field expects a number as a string (ie. '2').
+ Unscored fields are empty strings and are stored as NULL
+ """
+ if value is None:
+ return None
+ if isinstance(value, string_types) and len(value) == 0:
+ return None
+ return int(value)
+
def formfield(self, **kwargs):
defaults = {
'min_value': 0,
'form_class': forms.LikertField
}
defaults.update(kwargs)
return super(LikertField, self).formfield(**defaults)
| Handle empty strings from unanswered items | ## Code Before:
from __future__ import unicode_literals
from django.db import models
from django.utils.translation import ugettext_lazy as _
import likert_field.forms as forms
class LikertField(models.IntegerField):
"""A Likert field is simply stored as an IntegerField"""
description = _('Likert item field')
def __init__(self, *args, **kwargs):
if 'null' not in kwargs and not kwargs.get('null'):
kwargs['null'] = True
super(LikertField, self).__init__(*args, **kwargs)
def formfield(self, **kwargs):
defaults = {
'min_value': 0,
'form_class': forms.LikertField
}
defaults.update(kwargs)
return super(LikertField, self).formfield(**defaults)
## Instruction:
Handle empty strings from unanswered items
## Code After:
from __future__ import unicode_literals
from six import string_types
from django.db import models
from django.utils.translation import ugettext_lazy as _
import likert_field.forms as forms
class LikertField(models.IntegerField):
"""A Likert field is simply stored as an IntegerField"""
description = _('Likert item field')
def __init__(self, *args, **kwargs):
if 'null' not in kwargs and not kwargs.get('null'):
kwargs['null'] = True
super(LikertField, self).__init__(*args, **kwargs)
def get_prep_value(self, value):
"""The field expects a number as a string (ie. '2').
Unscored fields are empty strings and are stored as NULL
"""
if value is None:
return None
if isinstance(value, string_types) and len(value) == 0:
return None
return int(value)
def formfield(self, **kwargs):
defaults = {
'min_value': 0,
'form_class': forms.LikertField
}
defaults.update(kwargs)
return super(LikertField, self).formfield(**defaults)
| from __future__ import unicode_literals
+
+ from six import string_types
from django.db import models
from django.utils.translation import ugettext_lazy as _
import likert_field.forms as forms
class LikertField(models.IntegerField):
"""A Likert field is simply stored as an IntegerField"""
description = _('Likert item field')
def __init__(self, *args, **kwargs):
if 'null' not in kwargs and not kwargs.get('null'):
kwargs['null'] = True
super(LikertField, self).__init__(*args, **kwargs)
+ def get_prep_value(self, value):
+ """The field expects a number as a string (ie. '2').
+ Unscored fields are empty strings and are stored as NULL
+ """
+ if value is None:
+ return None
+ if isinstance(value, string_types) and len(value) == 0:
+ return None
+ return int(value)
+
def formfield(self, **kwargs):
defaults = {
'min_value': 0,
'form_class': forms.LikertField
}
defaults.update(kwargs)
return super(LikertField, self).formfield(**defaults) |
7778b98e1a0d0ac7b9c14e4536e62de4db7debc9 | tests/integration/suite/test_global_role_bindings.py | tests/integration/suite/test_global_role_bindings.py | from .common import random_str
def test_cannot_update_global_role(admin_mc, remove_resource):
"""Asserts that globalRoleId field cannot be changed"""
admin_client = admin_mc.client
grb = admin_client.create_global_role_binding(
name="gr-" + random_str(),
userId=admin_mc.user.id,
globalRoleId="nodedrivers-manage")
remove_resource(grb)
grb = admin_client.update_by_id_global_role_binding(
id=grb.id,
globalRoleId="settings-manage")
assert grb.globalRoleId == "nodedrivers-manage"
| import pytest
from rancher import ApiError
from .common import random_str
def test_cannot_update_global_role(admin_mc, remove_resource):
"""Asserts that globalRoleId field cannot be changed"""
admin_client = admin_mc.client
grb = admin_client.create_global_role_binding(
name="gr-" + random_str(),
userId=admin_mc.user.id,
globalRoleId="nodedrivers-manage")
remove_resource(grb)
grb = admin_client.update_by_id_global_role_binding(
id=grb.id,
globalRoleId="settings-manage")
assert grb.globalRoleId == "nodedrivers-manage"
def test_globalrole_must_exist(admin_mc, remove_resource):
"""Asserts that globalRoleId must reference an existing role"""
admin_client = admin_mc.client
with pytest.raises(ApiError) as e:
grb = admin_client.create_global_role_binding(
name="gr-" + random_str(),
globalRoleId="somefakerole",
userId=admin_mc.user.id
)
remove_resource(grb)
assert e.value.error.status == 404
assert "globalRole.management.cattle.io \"somefakerole\" not found" in \
e.value.error.message
| Add test for GRB validator | Add test for GRB validator
| Python | apache-2.0 | cjellick/rancher,rancherio/rancher,cjellick/rancher,rancher/rancher,cjellick/rancher,rancherio/rancher,rancher/rancher,rancher/rancher,rancher/rancher | + import pytest
+
+ from rancher import ApiError
from .common import random_str
def test_cannot_update_global_role(admin_mc, remove_resource):
"""Asserts that globalRoleId field cannot be changed"""
admin_client = admin_mc.client
grb = admin_client.create_global_role_binding(
name="gr-" + random_str(),
userId=admin_mc.user.id,
globalRoleId="nodedrivers-manage")
remove_resource(grb)
grb = admin_client.update_by_id_global_role_binding(
id=grb.id,
globalRoleId="settings-manage")
assert grb.globalRoleId == "nodedrivers-manage"
+
+ def test_globalrole_must_exist(admin_mc, remove_resource):
+ """Asserts that globalRoleId must reference an existing role"""
+ admin_client = admin_mc.client
+
+ with pytest.raises(ApiError) as e:
+ grb = admin_client.create_global_role_binding(
+ name="gr-" + random_str(),
+ globalRoleId="somefakerole",
+ userId=admin_mc.user.id
+ )
+ remove_resource(grb)
+ assert e.value.error.status == 404
+ assert "globalRole.management.cattle.io \"somefakerole\" not found" in \
+ e.value.error.message
+ | Add test for GRB validator | ## Code Before:
from .common import random_str
def test_cannot_update_global_role(admin_mc, remove_resource):
"""Asserts that globalRoleId field cannot be changed"""
admin_client = admin_mc.client
grb = admin_client.create_global_role_binding(
name="gr-" + random_str(),
userId=admin_mc.user.id,
globalRoleId="nodedrivers-manage")
remove_resource(grb)
grb = admin_client.update_by_id_global_role_binding(
id=grb.id,
globalRoleId="settings-manage")
assert grb.globalRoleId == "nodedrivers-manage"
## Instruction:
Add test for GRB validator
## Code After:
import pytest
from rancher import ApiError
from .common import random_str
def test_cannot_update_global_role(admin_mc, remove_resource):
"""Asserts that globalRoleId field cannot be changed"""
admin_client = admin_mc.client
grb = admin_client.create_global_role_binding(
name="gr-" + random_str(),
userId=admin_mc.user.id,
globalRoleId="nodedrivers-manage")
remove_resource(grb)
grb = admin_client.update_by_id_global_role_binding(
id=grb.id,
globalRoleId="settings-manage")
assert grb.globalRoleId == "nodedrivers-manage"
def test_globalrole_must_exist(admin_mc, remove_resource):
"""Asserts that globalRoleId must reference an existing role"""
admin_client = admin_mc.client
with pytest.raises(ApiError) as e:
grb = admin_client.create_global_role_binding(
name="gr-" + random_str(),
globalRoleId="somefakerole",
userId=admin_mc.user.id
)
remove_resource(grb)
assert e.value.error.status == 404
assert "globalRole.management.cattle.io \"somefakerole\" not found" in \
e.value.error.message
| + import pytest
+
+ from rancher import ApiError
from .common import random_str
def test_cannot_update_global_role(admin_mc, remove_resource):
"""Asserts that globalRoleId field cannot be changed"""
admin_client = admin_mc.client
grb = admin_client.create_global_role_binding(
name="gr-" + random_str(),
userId=admin_mc.user.id,
globalRoleId="nodedrivers-manage")
remove_resource(grb)
grb = admin_client.update_by_id_global_role_binding(
id=grb.id,
globalRoleId="settings-manage")
assert grb.globalRoleId == "nodedrivers-manage"
+
+
+ def test_globalrole_must_exist(admin_mc, remove_resource):
+ """Asserts that globalRoleId must reference an existing role"""
+ admin_client = admin_mc.client
+
+ with pytest.raises(ApiError) as e:
+ grb = admin_client.create_global_role_binding(
+ name="gr-" + random_str(),
+ globalRoleId="somefakerole",
+ userId=admin_mc.user.id
+ )
+ remove_resource(grb)
+ assert e.value.error.status == 404
+ assert "globalRole.management.cattle.io \"somefakerole\" not found" in \
+ e.value.error.message |
87cfac55b14083fdb8e346b9db1a95bb0f63881a | connect/config/factories.py | connect/config/factories.py | import factory
from django.contrib.sites.models import Site
from connect.config.models import SiteConfig
class SiteFactory(factory.django.DjangoModelFactory):
class Meta:
model = Site
name = factory.Sequence(lambda n: "site%s" % n)
domain = factory.Sequence(lambda n: "site%s.com" % n)
class SiteConfigFactory(factory.django.DjangoModelFactory):
class Meta:
model = SiteConfig
site = factory.SubFactory(Site)
email = factory.Sequence(lambda n: "site.email%s@test.test" % n)
tagline = 'A tagline'
email_header = factory.django.ImageField(filename='my_image.png')
| import factory
from django.contrib.sites.models import Site
from connect.config.models import SiteConfig
class SiteFactory(factory.django.DjangoModelFactory):
class Meta:
model = Site
name = factory.Sequence(lambda n: "site%s" % n)
domain = factory.Sequence(lambda n: "site%s.com" % n)
class SiteConfigFactory(factory.django.DjangoModelFactory):
class Meta:
model = SiteConfig
site = factory.SubFactory(Site)
logo = factory.django.ImageField(filename='my_log.png', format='PNG')
email = factory.Sequence(lambda n: "site.email%s@test.test" % n)
tagline = 'A tagline'
email_header = factory.django.ImageField(filename='my_image.png', format='PNG')
| Reconfigure SiteConfigFactory to use JPG - removes pillow's libjpeg-dev dependency | Reconfigure SiteConfigFactory to use JPG - removes pillow's libjpeg-dev dependency
| Python | bsd-3-clause | nlhkabu/connect,f3r3nc/connect,f3r3nc/connect,f3r3nc/connect,nlhkabu/connect,f3r3nc/connect,nlhkabu/connect,nlhkabu/connect | import factory
from django.contrib.sites.models import Site
from connect.config.models import SiteConfig
class SiteFactory(factory.django.DjangoModelFactory):
class Meta:
model = Site
name = factory.Sequence(lambda n: "site%s" % n)
domain = factory.Sequence(lambda n: "site%s.com" % n)
class SiteConfigFactory(factory.django.DjangoModelFactory):
class Meta:
model = SiteConfig
site = factory.SubFactory(Site)
+ logo = factory.django.ImageField(filename='my_log.png', format='PNG')
email = factory.Sequence(lambda n: "site.email%s@test.test" % n)
tagline = 'A tagline'
- email_header = factory.django.ImageField(filename='my_image.png')
+ email_header = factory.django.ImageField(filename='my_image.png', format='PNG')
| Reconfigure SiteConfigFactory to use JPG - removes pillow's libjpeg-dev dependency | ## Code Before:
import factory
from django.contrib.sites.models import Site
from connect.config.models import SiteConfig
class SiteFactory(factory.django.DjangoModelFactory):
class Meta:
model = Site
name = factory.Sequence(lambda n: "site%s" % n)
domain = factory.Sequence(lambda n: "site%s.com" % n)
class SiteConfigFactory(factory.django.DjangoModelFactory):
class Meta:
model = SiteConfig
site = factory.SubFactory(Site)
email = factory.Sequence(lambda n: "site.email%s@test.test" % n)
tagline = 'A tagline'
email_header = factory.django.ImageField(filename='my_image.png')
## Instruction:
Reconfigure SiteConfigFactory to use JPG - removes pillow's libjpeg-dev dependency
## Code After:
import factory
from django.contrib.sites.models import Site
from connect.config.models import SiteConfig
class SiteFactory(factory.django.DjangoModelFactory):
class Meta:
model = Site
name = factory.Sequence(lambda n: "site%s" % n)
domain = factory.Sequence(lambda n: "site%s.com" % n)
class SiteConfigFactory(factory.django.DjangoModelFactory):
class Meta:
model = SiteConfig
site = factory.SubFactory(Site)
logo = factory.django.ImageField(filename='my_log.png', format='PNG')
email = factory.Sequence(lambda n: "site.email%s@test.test" % n)
tagline = 'A tagline'
email_header = factory.django.ImageField(filename='my_image.png', format='PNG')
| import factory
from django.contrib.sites.models import Site
from connect.config.models import SiteConfig
class SiteFactory(factory.django.DjangoModelFactory):
class Meta:
model = Site
name = factory.Sequence(lambda n: "site%s" % n)
domain = factory.Sequence(lambda n: "site%s.com" % n)
class SiteConfigFactory(factory.django.DjangoModelFactory):
class Meta:
model = SiteConfig
site = factory.SubFactory(Site)
+ logo = factory.django.ImageField(filename='my_log.png', format='PNG')
email = factory.Sequence(lambda n: "site.email%s@test.test" % n)
tagline = 'A tagline'
- email_header = factory.django.ImageField(filename='my_image.png')
+ email_header = factory.django.ImageField(filename='my_image.png', format='PNG')
? ++++++++++++++
|
703cdca6725438b55bf544962ce0c554598697be | shoop/admin/templatetags/shoop_admin.py | shoop/admin/templatetags/shoop_admin.py |
from bootstrap3.renderers import FormRenderer
from django.utils.safestring import mark_safe
from django_jinja import library
from shoop.admin.template_helpers import shoop_admin as shoop_admin_template_helpers
from shoop.admin.utils.bs3_renderers import AdminFieldRenderer
class Bootstrap3Namespace(object):
def field(self, field, **kwargs):
if not field:
return ""
return mark_safe(AdminFieldRenderer(field, **kwargs).render())
def form(self, form, **kwargs):
return mark_safe(FormRenderer(form, **kwargs).render())
library.global_function(name="shoop_admin", fn=shoop_admin_template_helpers)
library.global_function(name="bs3", fn=Bootstrap3Namespace())
|
from bootstrap3.renderers import FormRenderer
from django.utils.safestring import mark_safe
from django_jinja import library
from shoop.admin.template_helpers import shoop_admin as shoop_admin_template_helpers
from shoop.admin.utils.bs3_renderers import AdminFieldRenderer
class Bootstrap3Namespace(object):
def field(self, field, **kwargs):
if not field:
return ""
return mark_safe(AdminFieldRenderer(field, **kwargs).render())
def form(self, form, **kwargs):
return mark_safe(FormRenderer(form, **kwargs).render())
def datetime_field(self, field, **kwargs):
kwargs.setdefault("widget_class", "datetime")
kwargs.setdefault("addon_after", "<span class='fa fa-calendar'></span>")
return self.field(field, **kwargs)
library.global_function(name="shoop_admin", fn=shoop_admin_template_helpers)
library.global_function(name="bs3", fn=Bootstrap3Namespace())
| Add template helper for datetime fields | Admin: Add template helper for datetime fields
Refs SHOOP-1612
| Python | agpl-3.0 | suutari-ai/shoop,shoopio/shoop,suutari/shoop,jorge-marques/shoop,hrayr-artunyan/shuup,taedori81/shoop,shawnadelic/shuup,shawnadelic/shuup,shawnadelic/shuup,suutari-ai/shoop,shoopio/shoop,taedori81/shoop,akx/shoop,suutari/shoop,akx/shoop,shoopio/shoop,hrayr-artunyan/shuup,suutari-ai/shoop,suutari/shoop,hrayr-artunyan/shuup,jorge-marques/shoop,jorge-marques/shoop,taedori81/shoop,akx/shoop |
from bootstrap3.renderers import FormRenderer
from django.utils.safestring import mark_safe
from django_jinja import library
from shoop.admin.template_helpers import shoop_admin as shoop_admin_template_helpers
from shoop.admin.utils.bs3_renderers import AdminFieldRenderer
class Bootstrap3Namespace(object):
def field(self, field, **kwargs):
if not field:
return ""
return mark_safe(AdminFieldRenderer(field, **kwargs).render())
def form(self, form, **kwargs):
return mark_safe(FormRenderer(form, **kwargs).render())
+ def datetime_field(self, field, **kwargs):
+ kwargs.setdefault("widget_class", "datetime")
+ kwargs.setdefault("addon_after", "<span class='fa fa-calendar'></span>")
+ return self.field(field, **kwargs)
+
library.global_function(name="shoop_admin", fn=shoop_admin_template_helpers)
library.global_function(name="bs3", fn=Bootstrap3Namespace())
| Add template helper for datetime fields | ## Code Before:
from bootstrap3.renderers import FormRenderer
from django.utils.safestring import mark_safe
from django_jinja import library
from shoop.admin.template_helpers import shoop_admin as shoop_admin_template_helpers
from shoop.admin.utils.bs3_renderers import AdminFieldRenderer
class Bootstrap3Namespace(object):
def field(self, field, **kwargs):
if not field:
return ""
return mark_safe(AdminFieldRenderer(field, **kwargs).render())
def form(self, form, **kwargs):
return mark_safe(FormRenderer(form, **kwargs).render())
library.global_function(name="shoop_admin", fn=shoop_admin_template_helpers)
library.global_function(name="bs3", fn=Bootstrap3Namespace())
## Instruction:
Add template helper for datetime fields
## Code After:
from bootstrap3.renderers import FormRenderer
from django.utils.safestring import mark_safe
from django_jinja import library
from shoop.admin.template_helpers import shoop_admin as shoop_admin_template_helpers
from shoop.admin.utils.bs3_renderers import AdminFieldRenderer
class Bootstrap3Namespace(object):
def field(self, field, **kwargs):
if not field:
return ""
return mark_safe(AdminFieldRenderer(field, **kwargs).render())
def form(self, form, **kwargs):
return mark_safe(FormRenderer(form, **kwargs).render())
def datetime_field(self, field, **kwargs):
kwargs.setdefault("widget_class", "datetime")
kwargs.setdefault("addon_after", "<span class='fa fa-calendar'></span>")
return self.field(field, **kwargs)
library.global_function(name="shoop_admin", fn=shoop_admin_template_helpers)
library.global_function(name="bs3", fn=Bootstrap3Namespace())
|
from bootstrap3.renderers import FormRenderer
from django.utils.safestring import mark_safe
from django_jinja import library
from shoop.admin.template_helpers import shoop_admin as shoop_admin_template_helpers
from shoop.admin.utils.bs3_renderers import AdminFieldRenderer
class Bootstrap3Namespace(object):
def field(self, field, **kwargs):
if not field:
return ""
return mark_safe(AdminFieldRenderer(field, **kwargs).render())
def form(self, form, **kwargs):
return mark_safe(FormRenderer(form, **kwargs).render())
+ def datetime_field(self, field, **kwargs):
+ kwargs.setdefault("widget_class", "datetime")
+ kwargs.setdefault("addon_after", "<span class='fa fa-calendar'></span>")
+ return self.field(field, **kwargs)
+
library.global_function(name="shoop_admin", fn=shoop_admin_template_helpers)
library.global_function(name="bs3", fn=Bootstrap3Namespace()) |
650c94107106cddafccaf5d2021a6407fcac990e | bend/src/users/jwt_util.py | bend/src/users/jwt_util.py | from jwt_auth.forms import JSONWebTokenForm
def loginUser(username, password):
"""Should login user and return a jwt token, piggyback on jwt_auth"""
request = {"username": username, "password": password}
form = JSONWebTokenForm(request)
if not form.is_valid():
return print("JWT form not valid")
context_dict = {
'token': form.object['token']
}
return context_dict
| from jwt_auth.forms import JSONWebTokenForm
def loginUser(username, password):
"""Should login user and return a jwt token, piggyback on jwt_auth"""
request = {"username": username, "password": password}
form = JSONWebTokenForm(request)
if not form.is_valid():
return print("JWT form not valid")
return form.object['token']
| Return the token string instead of object with string | Return the token string instead of object with string
| Python | mit | ncrmro/ango,ncrmro/reango,ncrmro/ango,ncrmro/reango,ncrmro/ango,ncrmro/reango | from jwt_auth.forms import JSONWebTokenForm
def loginUser(username, password):
"""Should login user and return a jwt token, piggyback on jwt_auth"""
request = {"username": username, "password": password}
form = JSONWebTokenForm(request)
if not form.is_valid():
return print("JWT form not valid")
- context_dict = {
- 'token': form.object['token']
+ return form.object['token']
- }
- return context_dict
- | Return the token string instead of object with string | ## Code Before:
from jwt_auth.forms import JSONWebTokenForm
def loginUser(username, password):
"""Should login user and return a jwt token, piggyback on jwt_auth"""
request = {"username": username, "password": password}
form = JSONWebTokenForm(request)
if not form.is_valid():
return print("JWT form not valid")
context_dict = {
'token': form.object['token']
}
return context_dict
## Instruction:
Return the token string instead of object with string
## Code After:
from jwt_auth.forms import JSONWebTokenForm
def loginUser(username, password):
"""Should login user and return a jwt token, piggyback on jwt_auth"""
request = {"username": username, "password": password}
form = JSONWebTokenForm(request)
if not form.is_valid():
return print("JWT form not valid")
return form.object['token']
| from jwt_auth.forms import JSONWebTokenForm
def loginUser(username, password):
"""Should login user and return a jwt token, piggyback on jwt_auth"""
request = {"username": username, "password": password}
form = JSONWebTokenForm(request)
if not form.is_valid():
return print("JWT form not valid")
- context_dict = {
- 'token': form.object['token']
? ^^^^^ ^^^ --
+ return form.object['token']
? ^^ ^^
- }
-
- return context_dict |
5df86afa64aafb4aee1adb066307910e0fb64256 | jd2chm_utils.py | jd2chm_utils.py | import os
import sys
import jd2chm_log
import jd2chm_conf
logging = None
config = None
def getAppDir():
if hasattr(sys, "frozen"): # py2exe
return os.path.dirname(sys.executable)
return os.path.dirname(sys.argv[0])
def getLogging(level=2):
global logging
if not logging:
logging = jd2chm_log.Jd2chmLogging(level)
return logging
def getLog():
"""Faciliate sharing the logger accross the different modules."""
return getLogging().logger
def getConf():
global config
if not config:
config = jd2chm_conf.Jd2chmConfig()
config.init()
return config | import os
import sys
import shutil
import jd2chm_log as log
import jd2chm_conf as conf
import jd2chm_const as const
logging = None
config = None
def get_app_dir():
if hasattr(sys, "frozen"): # py2exe
return os.path.dirname(sys.executable)
return os.path.dirname(sys.argv[0])
def get_logging(level=2):
global logging
if not logging:
logging = log.Jd2chmLogging(level)
return logging
def get_log():
"""Facilitate sharing the logger across the different modules."""
return get_logging().logger
def get_conf():
global config
if not config:
config = conf.Jd2chmConfig()
config.init()
return config
def term_width():
return shutil.get_terminal_size((const.DEFAULT_TERM_WIDTH,
const.DEFAULT_TERM_HEIGHT)).columns - const.TERM_MARGIN
def center(line, max_line=0):
"""Center a padded string based on the width of the terminal.
If max_line is provided for justified text, line shorter than max_line
will only be padded on the left side.
"""
width = term_width()
left_margin = (width - max_line) / 2
if len(line) < max_line:
return (' ' * int(left_margin)) + line
return line.center(width, ' ')
def print_center_block(text, max_line=0):
"""Print a block of text centered on the terminal."""
for line in text.split('\n'):
print(center(line, max_line))
| Reformat code. Added methods to pretty print messages. | Reformat code. Added methods to pretty print messages.
| Python | mit | andreburgaud/jd2chm,andreburgaud/jd2chm | import os
import sys
+ import shutil
- import jd2chm_log
+ import jd2chm_log as log
- import jd2chm_conf
+ import jd2chm_conf as conf
+ import jd2chm_const as const
logging = None
config = None
- def getAppDir():
- if hasattr(sys, "frozen"): # py2exe
- return os.path.dirname(sys.executable)
- return os.path.dirname(sys.argv[0])
+ def get_app_dir():
+ if hasattr(sys, "frozen"): # py2exe
+ return os.path.dirname(sys.executable)
+ return os.path.dirname(sys.argv[0])
- def getLogging(level=2):
- global logging
- if not logging:
- logging = jd2chm_log.Jd2chmLogging(level)
- return logging
- def getLog():
- """Faciliate sharing the logger accross the different modules."""
- return getLogging().logger
+ def get_logging(level=2):
+ global logging
+ if not logging:
+ logging = log.Jd2chmLogging(level)
+ return logging
+
+
+ def get_log():
+ """Facilitate sharing the logger across the different modules."""
+ return get_logging().logger
+
+
- def getConf():
+ def get_conf():
- global config
+ global config
- if not config:
+ if not config:
- config = jd2chm_conf.Jd2chmConfig()
+ config = conf.Jd2chmConfig()
- config.init()
+ config.init()
- return config
+ return config
+
+
+ def term_width():
+ return shutil.get_terminal_size((const.DEFAULT_TERM_WIDTH,
+ const.DEFAULT_TERM_HEIGHT)).columns - const.TERM_MARGIN
+
+
+ def center(line, max_line=0):
+ """Center a padded string based on the width of the terminal.
+
+ If max_line is provided for justified text, line shorter than max_line
+ will only be padded on the left side.
+ """
+
+ width = term_width()
+ left_margin = (width - max_line) / 2
+ if len(line) < max_line:
+ return (' ' * int(left_margin)) + line
+ return line.center(width, ' ')
+
+
+ def print_center_block(text, max_line=0):
+ """Print a block of text centered on the terminal."""
+
+ for line in text.split('\n'):
+ print(center(line, max_line))
+ | Reformat code. Added methods to pretty print messages. | ## Code Before:
import os
import sys
import jd2chm_log
import jd2chm_conf
logging = None
config = None
def getAppDir():
if hasattr(sys, "frozen"): # py2exe
return os.path.dirname(sys.executable)
return os.path.dirname(sys.argv[0])
def getLogging(level=2):
global logging
if not logging:
logging = jd2chm_log.Jd2chmLogging(level)
return logging
def getLog():
"""Faciliate sharing the logger accross the different modules."""
return getLogging().logger
def getConf():
global config
if not config:
config = jd2chm_conf.Jd2chmConfig()
config.init()
return config
## Instruction:
Reformat code. Added methods to pretty print messages.
## Code After:
import os
import sys
import shutil
import jd2chm_log as log
import jd2chm_conf as conf
import jd2chm_const as const
logging = None
config = None
def get_app_dir():
if hasattr(sys, "frozen"): # py2exe
return os.path.dirname(sys.executable)
return os.path.dirname(sys.argv[0])
def get_logging(level=2):
global logging
if not logging:
logging = log.Jd2chmLogging(level)
return logging
def get_log():
"""Facilitate sharing the logger across the different modules."""
return get_logging().logger
def get_conf():
global config
if not config:
config = conf.Jd2chmConfig()
config.init()
return config
def term_width():
return shutil.get_terminal_size((const.DEFAULT_TERM_WIDTH,
const.DEFAULT_TERM_HEIGHT)).columns - const.TERM_MARGIN
def center(line, max_line=0):
"""Center a padded string based on the width of the terminal.
If max_line is provided for justified text, line shorter than max_line
will only be padded on the left side.
"""
width = term_width()
left_margin = (width - max_line) / 2
if len(line) < max_line:
return (' ' * int(left_margin)) + line
return line.center(width, ' ')
def print_center_block(text, max_line=0):
"""Print a block of text centered on the terminal."""
for line in text.split('\n'):
print(center(line, max_line))
| import os
import sys
+ import shutil
- import jd2chm_log
+ import jd2chm_log as log
? +++++++
- import jd2chm_conf
+ import jd2chm_conf as conf
? ++++++++
+ import jd2chm_const as const
logging = None
config = None
- def getAppDir():
- if hasattr(sys, "frozen"): # py2exe
- return os.path.dirname(sys.executable)
- return os.path.dirname(sys.argv[0])
+ def get_app_dir():
+ if hasattr(sys, "frozen"): # py2exe
+ return os.path.dirname(sys.executable)
+ return os.path.dirname(sys.argv[0])
- def getLogging(level=2):
- global logging
- if not logging:
- logging = jd2chm_log.Jd2chmLogging(level)
- return logging
- def getLog():
- """Faciliate sharing the logger accross the different modules."""
- return getLogging().logger
+ def get_logging(level=2):
+ global logging
+ if not logging:
+ logging = log.Jd2chmLogging(level)
+ return logging
+
+
+ def get_log():
+ """Facilitate sharing the logger across the different modules."""
+ return get_logging().logger
+
+
- def getConf():
? ^
+ def get_conf():
? ^^
- global config
+ global config
? ++
- if not config:
+ if not config:
? ++
- config = jd2chm_conf.Jd2chmConfig()
? -------
+ config = conf.Jd2chmConfig()
? ++++
- config.init()
+ config.init()
? ++++
- return config
+ return config
? ++
+
+
+ def term_width():
+ return shutil.get_terminal_size((const.DEFAULT_TERM_WIDTH,
+ const.DEFAULT_TERM_HEIGHT)).columns - const.TERM_MARGIN
+
+
+ def center(line, max_line=0):
+ """Center a padded string based on the width of the terminal.
+
+ If max_line is provided for justified text, line shorter than max_line
+ will only be padded on the left side.
+ """
+
+ width = term_width()
+ left_margin = (width - max_line) / 2
+ if len(line) < max_line:
+ return (' ' * int(left_margin)) + line
+ return line.center(width, ' ')
+
+
+ def print_center_block(text, max_line=0):
+ """Print a block of text centered on the terminal."""
+
+ for line in text.split('\n'):
+ print(center(line, max_line)) |
1c3f89110ede8998b63831c181c44e92709481b6 | demo/widgy.py | demo/widgy.py | from __future__ import absolute_import
from widgy.site import WidgySite
class DemoWidgySite(WidgySite):
def valid_parent_of(self, parent, child_class, obj=None):
if isinstance(parent, I18NLayout):
return True
else:
return super(DemoWidgySite, self).valid_parent_of(parent, child_class, obj)
widgy_site = DemoWidgySite()
from widgy.contrib.widgy_i18n.models import I18NLayout
| from __future__ import absolute_import
from widgy.site import ReviewedWidgySite
class DemoWidgySite(ReviewedWidgySite):
def valid_parent_of(self, parent, child_class, obj=None):
if isinstance(parent, I18NLayout):
return True
else:
return super(DemoWidgySite, self).valid_parent_of(parent, child_class, obj)
widgy_site = DemoWidgySite()
from widgy.contrib.widgy_i18n.models import I18NLayout
| Enable the review queue on the demo site | Enable the review queue on the demo site
| Python | apache-2.0 | j00bar/django-widgy,j00bar/django-widgy,j00bar/django-widgy | from __future__ import absolute_import
- from widgy.site import WidgySite
+ from widgy.site import ReviewedWidgySite
- class DemoWidgySite(WidgySite):
+ class DemoWidgySite(ReviewedWidgySite):
def valid_parent_of(self, parent, child_class, obj=None):
if isinstance(parent, I18NLayout):
return True
else:
return super(DemoWidgySite, self).valid_parent_of(parent, child_class, obj)
widgy_site = DemoWidgySite()
from widgy.contrib.widgy_i18n.models import I18NLayout
| Enable the review queue on the demo site | ## Code Before:
from __future__ import absolute_import
from widgy.site import WidgySite
class DemoWidgySite(WidgySite):
def valid_parent_of(self, parent, child_class, obj=None):
if isinstance(parent, I18NLayout):
return True
else:
return super(DemoWidgySite, self).valid_parent_of(parent, child_class, obj)
widgy_site = DemoWidgySite()
from widgy.contrib.widgy_i18n.models import I18NLayout
## Instruction:
Enable the review queue on the demo site
## Code After:
from __future__ import absolute_import
from widgy.site import ReviewedWidgySite
class DemoWidgySite(ReviewedWidgySite):
def valid_parent_of(self, parent, child_class, obj=None):
if isinstance(parent, I18NLayout):
return True
else:
return super(DemoWidgySite, self).valid_parent_of(parent, child_class, obj)
widgy_site = DemoWidgySite()
from widgy.contrib.widgy_i18n.models import I18NLayout
| from __future__ import absolute_import
- from widgy.site import WidgySite
+ from widgy.site import ReviewedWidgySite
? ++++++++
- class DemoWidgySite(WidgySite):
+ class DemoWidgySite(ReviewedWidgySite):
? ++++++++
def valid_parent_of(self, parent, child_class, obj=None):
if isinstance(parent, I18NLayout):
return True
else:
return super(DemoWidgySite, self).valid_parent_of(parent, child_class, obj)
widgy_site = DemoWidgySite()
from widgy.contrib.widgy_i18n.models import I18NLayout |
2a3f4ff6686f1630348a73dd62d7ad8e3215dff5 | tests/conftest.py | tests/conftest.py | import pytest
from cattr import Converter
@pytest.fixture()
def converter():
return Converter()
| import platform
import pytest
from hypothesis import HealthCheck, settings
from cattr import Converter
@pytest.fixture()
def converter():
return Converter()
if platform.python_implementation() == 'PyPy':
settings.default.suppress_health_check.append(HealthCheck.too_slow)
| Disable Hypothesis health check for PyPy. | Disable Hypothesis health check for PyPy.
| Python | mit | python-attrs/cattrs,Tinche/cattrs | + import platform
+
import pytest
+
+ from hypothesis import HealthCheck, settings
from cattr import Converter
@pytest.fixture()
def converter():
return Converter()
+
+ if platform.python_implementation() == 'PyPy':
+ settings.default.suppress_health_check.append(HealthCheck.too_slow)
+ | Disable Hypothesis health check for PyPy. | ## Code Before:
import pytest
from cattr import Converter
@pytest.fixture()
def converter():
return Converter()
## Instruction:
Disable Hypothesis health check for PyPy.
## Code After:
import platform
import pytest
from hypothesis import HealthCheck, settings
from cattr import Converter
@pytest.fixture()
def converter():
return Converter()
if platform.python_implementation() == 'PyPy':
settings.default.suppress_health_check.append(HealthCheck.too_slow)
| + import platform
+
import pytest
+
+ from hypothesis import HealthCheck, settings
from cattr import Converter
@pytest.fixture()
def converter():
return Converter()
+
+
+ if platform.python_implementation() == 'PyPy':
+ settings.default.suppress_health_check.append(HealthCheck.too_slow) |
b3702552ab83b7910b7972512253a829bbc56488 | osgtest/tests/test_838_xrootd_tpc.py | osgtest/tests/test_838_xrootd_tpc.py | import osgtest.library.core as core
import osgtest.library.files as files
import osgtest.library.service as service
import osgtest.library.osgunittest as osgunittest
class TestStopXrootdTPC(osgunittest.OSGTestCase):
@core.elrelease(7,8)
def test_01_stop_xrootd(self):
if core.state['xrootd.tpc.backups-exist']:
files.restore(core.config['xrootd.tpc.config-1'], "xrootd")
files.restore(core.config['xrootd.tpc.config-2'], "xrootd")
core.skip_ok_unless_installed('xrootd', 'xrootd-scitokens', by_dependency=True)
self.skip_ok_if(not core.state['xrootd.started-http-server-1'] and
not core.state['xrootd.started-http-server-2'],
'did not start any of the http servers')
service.check_stop(core.config['xrootd_tpc_service_1'])
service.check_stop(core.config['xrootd_tpc_service_2'])
def test_02_clean_test_files(self):
files.remove("/tmp/test_gridftp_data_tpc.txt", force=True)
| import osgtest.library.core as core
import osgtest.library.files as files
import osgtest.library.service as service
import osgtest.library.osgunittest as osgunittest
class TestStopXrootdTPC(osgunittest.OSGTestCase):
@core.elrelease(7,8)
def setUp(self):
core.skip_ok_unless_installed("xrootd",
by_dependency=True)
def test_01_stop_xrootd(self):
if core.state['xrootd.tpc.backups-exist']:
files.restore(core.config['xrootd.tpc.config-1'], "xrootd")
files.restore(core.config['xrootd.tpc.config-2'], "xrootd")
core.skip_ok_unless_installed('xrootd-scitokens', by_dependency=True)
self.skip_ok_if(not core.state['xrootd.started-http-server-1'] and
not core.state['xrootd.started-http-server-2'],
'did not start any of the http servers')
service.check_stop(core.config['xrootd_tpc_service_1'])
service.check_stop(core.config['xrootd_tpc_service_2'])
def test_02_clean_test_files(self):
files.remove("/tmp/test_gridftp_data_tpc.txt", force=True)
| Add xrootd and non-el6 check for xrootd-tpc cleanup too | Add xrootd and non-el6 check for xrootd-tpc cleanup too
| Python | apache-2.0 | efajardo/osg-test,efajardo/osg-test | import osgtest.library.core as core
import osgtest.library.files as files
import osgtest.library.service as service
import osgtest.library.osgunittest as osgunittest
class TestStopXrootdTPC(osgunittest.OSGTestCase):
@core.elrelease(7,8)
+ def setUp(self):
+ core.skip_ok_unless_installed("xrootd",
+ by_dependency=True)
+
def test_01_stop_xrootd(self):
if core.state['xrootd.tpc.backups-exist']:
files.restore(core.config['xrootd.tpc.config-1'], "xrootd")
files.restore(core.config['xrootd.tpc.config-2'], "xrootd")
- core.skip_ok_unless_installed('xrootd', 'xrootd-scitokens', by_dependency=True)
+ core.skip_ok_unless_installed('xrootd-scitokens', by_dependency=True)
self.skip_ok_if(not core.state['xrootd.started-http-server-1'] and
not core.state['xrootd.started-http-server-2'],
'did not start any of the http servers')
service.check_stop(core.config['xrootd_tpc_service_1'])
service.check_stop(core.config['xrootd_tpc_service_2'])
def test_02_clean_test_files(self):
files.remove("/tmp/test_gridftp_data_tpc.txt", force=True)
| Add xrootd and non-el6 check for xrootd-tpc cleanup too | ## Code Before:
import osgtest.library.core as core
import osgtest.library.files as files
import osgtest.library.service as service
import osgtest.library.osgunittest as osgunittest
class TestStopXrootdTPC(osgunittest.OSGTestCase):
@core.elrelease(7,8)
def test_01_stop_xrootd(self):
if core.state['xrootd.tpc.backups-exist']:
files.restore(core.config['xrootd.tpc.config-1'], "xrootd")
files.restore(core.config['xrootd.tpc.config-2'], "xrootd")
core.skip_ok_unless_installed('xrootd', 'xrootd-scitokens', by_dependency=True)
self.skip_ok_if(not core.state['xrootd.started-http-server-1'] and
not core.state['xrootd.started-http-server-2'],
'did not start any of the http servers')
service.check_stop(core.config['xrootd_tpc_service_1'])
service.check_stop(core.config['xrootd_tpc_service_2'])
def test_02_clean_test_files(self):
files.remove("/tmp/test_gridftp_data_tpc.txt", force=True)
## Instruction:
Add xrootd and non-el6 check for xrootd-tpc cleanup too
## Code After:
import osgtest.library.core as core
import osgtest.library.files as files
import osgtest.library.service as service
import osgtest.library.osgunittest as osgunittest
class TestStopXrootdTPC(osgunittest.OSGTestCase):
@core.elrelease(7,8)
def setUp(self):
core.skip_ok_unless_installed("xrootd",
by_dependency=True)
def test_01_stop_xrootd(self):
if core.state['xrootd.tpc.backups-exist']:
files.restore(core.config['xrootd.tpc.config-1'], "xrootd")
files.restore(core.config['xrootd.tpc.config-2'], "xrootd")
core.skip_ok_unless_installed('xrootd-scitokens', by_dependency=True)
self.skip_ok_if(not core.state['xrootd.started-http-server-1'] and
not core.state['xrootd.started-http-server-2'],
'did not start any of the http servers')
service.check_stop(core.config['xrootd_tpc_service_1'])
service.check_stop(core.config['xrootd_tpc_service_2'])
def test_02_clean_test_files(self):
files.remove("/tmp/test_gridftp_data_tpc.txt", force=True)
| import osgtest.library.core as core
import osgtest.library.files as files
import osgtest.library.service as service
import osgtest.library.osgunittest as osgunittest
class TestStopXrootdTPC(osgunittest.OSGTestCase):
@core.elrelease(7,8)
+ def setUp(self):
+ core.skip_ok_unless_installed("xrootd",
+ by_dependency=True)
+
def test_01_stop_xrootd(self):
if core.state['xrootd.tpc.backups-exist']:
files.restore(core.config['xrootd.tpc.config-1'], "xrootd")
files.restore(core.config['xrootd.tpc.config-2'], "xrootd")
- core.skip_ok_unless_installed('xrootd', 'xrootd-scitokens', by_dependency=True)
? ----------
+ core.skip_ok_unless_installed('xrootd-scitokens', by_dependency=True)
self.skip_ok_if(not core.state['xrootd.started-http-server-1'] and
not core.state['xrootd.started-http-server-2'],
'did not start any of the http servers')
service.check_stop(core.config['xrootd_tpc_service_1'])
service.check_stop(core.config['xrootd_tpc_service_2'])
def test_02_clean_test_files(self):
files.remove("/tmp/test_gridftp_data_tpc.txt", force=True) |
d86bdec5d7d57fe74cb463e391798bd1e5be87ff | pombola/ghana/urls.py | pombola/ghana/urls.py | from django.conf.urls import patterns, include, url, handler404
from django.views.generic import TemplateView
import django.contrib.auth.views
from .views import data_upload, info_page_upload
urlpatterns = patterns('',
url(r'^intro$', TemplateView.as_view(template_name='intro.html')),
url(r'^data/upload/mps/$', data_upload, name='data_upload'),
url(r'^data/upload/info-page/$', info_page_upload, name='info_page_upload'),
#auth views
url(r'^accounts/login$', django.contrib.auth.views.login, name='login'),
url(r'^accounts/logut$', django.contrib.auth.views.logout, name='logout'),
#url(r'^accounts/register$', registration.backends.simple.urls, name='register'),
)
| from django.conf.urls import patterns, url, include
from django.views.generic import TemplateView
from .views import data_upload, info_page_upload
urlpatterns = patterns('',
url(r'^intro$', TemplateView.as_view(template_name='intro.html')),
url(r'^data/upload/mps/$', data_upload, name='data_upload'),
url(r'^data/upload/info-page/$', info_page_upload, name='info_page_upload'),
url('', include('django.contrib.auth.urls')),
)
| Update Ghana code to match current Pombola | Update Ghana code to match current Pombola
| Python | agpl-3.0 | geoffkilpin/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola,geoffkilpin/pombola,geoffkilpin/pombola,geoffkilpin/pombola,geoffkilpin/pombola,geoffkilpin/pombola,mysociety/pombola | - from django.conf.urls import patterns, include, url, handler404
+ from django.conf.urls import patterns, url, include
from django.views.generic import TemplateView
- import django.contrib.auth.views
-
from .views import data_upload, info_page_upload
urlpatterns = patterns('',
url(r'^intro$', TemplateView.as_view(template_name='intro.html')),
url(r'^data/upload/mps/$', data_upload, name='data_upload'),
url(r'^data/upload/info-page/$', info_page_upload, name='info_page_upload'),
+ url('', include('django.contrib.auth.urls')),
-
- #auth views
- url(r'^accounts/login$', django.contrib.auth.views.login, name='login'),
- url(r'^accounts/logut$', django.contrib.auth.views.logout, name='logout'),
- #url(r'^accounts/register$', registration.backends.simple.urls, name='register'),
-
-
)
| Update Ghana code to match current Pombola | ## Code Before:
from django.conf.urls import patterns, include, url, handler404
from django.views.generic import TemplateView
import django.contrib.auth.views
from .views import data_upload, info_page_upload
urlpatterns = patterns('',
url(r'^intro$', TemplateView.as_view(template_name='intro.html')),
url(r'^data/upload/mps/$', data_upload, name='data_upload'),
url(r'^data/upload/info-page/$', info_page_upload, name='info_page_upload'),
#auth views
url(r'^accounts/login$', django.contrib.auth.views.login, name='login'),
url(r'^accounts/logut$', django.contrib.auth.views.logout, name='logout'),
#url(r'^accounts/register$', registration.backends.simple.urls, name='register'),
)
## Instruction:
Update Ghana code to match current Pombola
## Code After:
from django.conf.urls import patterns, url, include
from django.views.generic import TemplateView
from .views import data_upload, info_page_upload
urlpatterns = patterns('',
url(r'^intro$', TemplateView.as_view(template_name='intro.html')),
url(r'^data/upload/mps/$', data_upload, name='data_upload'),
url(r'^data/upload/info-page/$', info_page_upload, name='info_page_upload'),
url('', include('django.contrib.auth.urls')),
)
| - from django.conf.urls import patterns, include, url, handler404
? -----------------
+ from django.conf.urls import patterns, url, include
? +++++
from django.views.generic import TemplateView
- import django.contrib.auth.views
-
from .views import data_upload, info_page_upload
urlpatterns = patterns('',
url(r'^intro$', TemplateView.as_view(template_name='intro.html')),
url(r'^data/upload/mps/$', data_upload, name='data_upload'),
url(r'^data/upload/info-page/$', info_page_upload, name='info_page_upload'),
+ url('', include('django.contrib.auth.urls')),
-
- #auth views
- url(r'^accounts/login$', django.contrib.auth.views.login, name='login'),
- url(r'^accounts/logut$', django.contrib.auth.views.logout, name='logout'),
- #url(r'^accounts/register$', registration.backends.simple.urls, name='register'),
-
-
) |
857350154e11f09a1b4aeecd411ab41df2acf378 | tests/integration/test_crossmodel.py | tests/integration/test_crossmodel.py | import pytest
from .. import base
@base.bootstrapped
@pytest.mark.asyncio
async def test_offer(event_loop):
async with base.CleanModel() as model:
application = await model.deploy(
'cs:~jameinel/ubuntu-lite-7',
application_name='ubuntu',
series='bionic',
channel='stable',
)
assert 'ubuntu' in model.applications
await model.block_until(
lambda: all(unit.workload_status == 'active'
for unit in application.units))
await model.create_offer("ubuntu:ubuntu")
offers = await model.list_offers()
await model.block_until(
lambda: all(offer.application_name == 'ubuntu'
for offer in offers))
await model.remove_offer("ubuntu", force=True)
| import pytest
from .. import base
@base.bootstrapped
@pytest.mark.asyncio
async def test_offer(event_loop):
async with base.CleanModel() as model:
application = await model.deploy(
'cs:~jameinel/ubuntu-lite-7',
application_name='ubuntu',
series='bionic',
channel='stable',
)
assert 'ubuntu' in model.applications
await model.block_until(
lambda: all(unit.workload_status == 'active'
for unit in application.units))
await model.create_offer("ubuntu:ubuntu")
offers = await model.list_offers()
await model.block_until(
lambda: all(offer.application_name == 'ubuntu'
for offer in offers))
await model.remove_offer("admin/{}.ubuntu".format(model.info.name), force=True)
| Remove offer with model name | Remove offer with model name
| Python | apache-2.0 | juju/python-libjuju,juju/python-libjuju | import pytest
from .. import base
@base.bootstrapped
@pytest.mark.asyncio
async def test_offer(event_loop):
async with base.CleanModel() as model:
application = await model.deploy(
'cs:~jameinel/ubuntu-lite-7',
application_name='ubuntu',
series='bionic',
channel='stable',
)
assert 'ubuntu' in model.applications
await model.block_until(
lambda: all(unit.workload_status == 'active'
for unit in application.units))
await model.create_offer("ubuntu:ubuntu")
offers = await model.list_offers()
await model.block_until(
lambda: all(offer.application_name == 'ubuntu'
for offer in offers))
- await model.remove_offer("ubuntu", force=True)
+ await model.remove_offer("admin/{}.ubuntu".format(model.info.name), force=True)
| Remove offer with model name | ## Code Before:
import pytest
from .. import base
@base.bootstrapped
@pytest.mark.asyncio
async def test_offer(event_loop):
async with base.CleanModel() as model:
application = await model.deploy(
'cs:~jameinel/ubuntu-lite-7',
application_name='ubuntu',
series='bionic',
channel='stable',
)
assert 'ubuntu' in model.applications
await model.block_until(
lambda: all(unit.workload_status == 'active'
for unit in application.units))
await model.create_offer("ubuntu:ubuntu")
offers = await model.list_offers()
await model.block_until(
lambda: all(offer.application_name == 'ubuntu'
for offer in offers))
await model.remove_offer("ubuntu", force=True)
## Instruction:
Remove offer with model name
## Code After:
import pytest
from .. import base
@base.bootstrapped
@pytest.mark.asyncio
async def test_offer(event_loop):
async with base.CleanModel() as model:
application = await model.deploy(
'cs:~jameinel/ubuntu-lite-7',
application_name='ubuntu',
series='bionic',
channel='stable',
)
assert 'ubuntu' in model.applications
await model.block_until(
lambda: all(unit.workload_status == 'active'
for unit in application.units))
await model.create_offer("ubuntu:ubuntu")
offers = await model.list_offers()
await model.block_until(
lambda: all(offer.application_name == 'ubuntu'
for offer in offers))
await model.remove_offer("admin/{}.ubuntu".format(model.info.name), force=True)
| import pytest
from .. import base
@base.bootstrapped
@pytest.mark.asyncio
async def test_offer(event_loop):
async with base.CleanModel() as model:
application = await model.deploy(
'cs:~jameinel/ubuntu-lite-7',
application_name='ubuntu',
series='bionic',
channel='stable',
)
assert 'ubuntu' in model.applications
await model.block_until(
lambda: all(unit.workload_status == 'active'
for unit in application.units))
await model.create_offer("ubuntu:ubuntu")
offers = await model.list_offers()
await model.block_until(
lambda: all(offer.application_name == 'ubuntu'
for offer in offers))
- await model.remove_offer("ubuntu", force=True)
+ await model.remove_offer("admin/{}.ubuntu".format(model.info.name), force=True)
? +++++++++ ++++++++++++++++++++++++
|
5351ad8324fa8388ea3b82425d03f43ac16d7313 | app.py | app.py |
import os, requests, getSchedule
from flask import Flask, request, jsonify, render_template, abort
app = Flask(__name__)
@app.route('/')
def root():
return render_template('index.html')
@app.route('/m')
def mobileView():
stop = request.args.get('stop', 1, type=int)
route = requests.get('http://nextride.alykhan.com/api?stop='+str(stop)).json()
if route:
path = route
else:
abort(400)
return render_template('index.html', path=path)
@app.route('/api')
def api():
stop = request.args.get('stop', 1, type=int)
schedule = getSchedule.parseSchedule(getSchedule.getRides(stop))
if schedule:
response = jsonify(meta=dict(status=200, message='OK'),data=schedule)
else:
abort(400)
return response
@app.errorhandler(400)
def bad_request(error):
response = jsonify(meta=dict(status=error.code, message=error.message))
return response, error.code
if __name__ == "__main__":
# Bind to PORT if defined, otherwise default to 5000.
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
|
import os, requests, getSchedule
from flask import Flask, request, jsonify, render_template, abort
app = Flask(__name__)
@app.route('/')
def root():
return render_template('index.html')
@app.route('/m')
def mobileView():
stop = request.args.get('stop', 1, type=int)
payload = {'stop': stop}
r = requests.get('http://nextride.alykhan.com/api', params=payload)
if r.status_code == requests.codes.ok:
path = r.json()
else:
abort(400)
return render_template('index.html', path=path)
@app.route('/api')
def api():
stop = request.args.get('stop', 1, type=int)
schedule = getSchedule.parseSchedule(getSchedule.getRides(stop))
if schedule:
response = jsonify(meta=dict(status=200, message='OK'),data=schedule)
else:
abort(400)
return response
@app.errorhandler(400)
def bad_request(error):
response = jsonify(meta=dict(status=error.code, message=error.message))
return response, error.code
if __name__ == "__main__":
# Bind to PORT if defined, otherwise default to 5000.
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
| Use Requests to encode stop as query param, verify API status code. | Use Requests to encode stop as query param, verify API status code.
| Python | mit | alykhank/NextRide,alykhank/NextRide |
import os, requests, getSchedule
from flask import Flask, request, jsonify, render_template, abort
app = Flask(__name__)
@app.route('/')
def root():
return render_template('index.html')
@app.route('/m')
def mobileView():
stop = request.args.get('stop', 1, type=int)
- route = requests.get('http://nextride.alykhan.com/api?stop='+str(stop)).json()
- if route:
- path = route
+ payload = {'stop': stop}
+ r = requests.get('http://nextride.alykhan.com/api', params=payload)
+ if r.status_code == requests.codes.ok:
+ path = r.json()
else:
abort(400)
return render_template('index.html', path=path)
@app.route('/api')
def api():
stop = request.args.get('stop', 1, type=int)
schedule = getSchedule.parseSchedule(getSchedule.getRides(stop))
if schedule:
response = jsonify(meta=dict(status=200, message='OK'),data=schedule)
else:
abort(400)
return response
@app.errorhandler(400)
def bad_request(error):
response = jsonify(meta=dict(status=error.code, message=error.message))
return response, error.code
if __name__ == "__main__":
# Bind to PORT if defined, otherwise default to 5000.
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
| Use Requests to encode stop as query param, verify API status code. | ## Code Before:
import os, requests, getSchedule
from flask import Flask, request, jsonify, render_template, abort
app = Flask(__name__)
@app.route('/')
def root():
return render_template('index.html')
@app.route('/m')
def mobileView():
stop = request.args.get('stop', 1, type=int)
route = requests.get('http://nextride.alykhan.com/api?stop='+str(stop)).json()
if route:
path = route
else:
abort(400)
return render_template('index.html', path=path)
@app.route('/api')
def api():
stop = request.args.get('stop', 1, type=int)
schedule = getSchedule.parseSchedule(getSchedule.getRides(stop))
if schedule:
response = jsonify(meta=dict(status=200, message='OK'),data=schedule)
else:
abort(400)
return response
@app.errorhandler(400)
def bad_request(error):
response = jsonify(meta=dict(status=error.code, message=error.message))
return response, error.code
if __name__ == "__main__":
# Bind to PORT if defined, otherwise default to 5000.
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
## Instruction:
Use Requests to encode stop as query param, verify API status code.
## Code After:
import os, requests, getSchedule
from flask import Flask, request, jsonify, render_template, abort
app = Flask(__name__)
@app.route('/')
def root():
return render_template('index.html')
@app.route('/m')
def mobileView():
stop = request.args.get('stop', 1, type=int)
payload = {'stop': stop}
r = requests.get('http://nextride.alykhan.com/api', params=payload)
if r.status_code == requests.codes.ok:
path = r.json()
else:
abort(400)
return render_template('index.html', path=path)
@app.route('/api')
def api():
stop = request.args.get('stop', 1, type=int)
schedule = getSchedule.parseSchedule(getSchedule.getRides(stop))
if schedule:
response = jsonify(meta=dict(status=200, message='OK'),data=schedule)
else:
abort(400)
return response
@app.errorhandler(400)
def bad_request(error):
response = jsonify(meta=dict(status=error.code, message=error.message))
return response, error.code
if __name__ == "__main__":
# Bind to PORT if defined, otherwise default to 5000.
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
|
import os, requests, getSchedule
from flask import Flask, request, jsonify, render_template, abort
app = Flask(__name__)
@app.route('/')
def root():
return render_template('index.html')
@app.route('/m')
def mobileView():
stop = request.args.get('stop', 1, type=int)
- route = requests.get('http://nextride.alykhan.com/api?stop='+str(stop)).json()
- if route:
- path = route
+ payload = {'stop': stop}
+ r = requests.get('http://nextride.alykhan.com/api', params=payload)
+ if r.status_code == requests.codes.ok:
+ path = r.json()
else:
abort(400)
return render_template('index.html', path=path)
@app.route('/api')
def api():
stop = request.args.get('stop', 1, type=int)
schedule = getSchedule.parseSchedule(getSchedule.getRides(stop))
if schedule:
response = jsonify(meta=dict(status=200, message='OK'),data=schedule)
else:
abort(400)
return response
@app.errorhandler(400)
def bad_request(error):
response = jsonify(meta=dict(status=error.code, message=error.message))
return response, error.code
if __name__ == "__main__":
# Bind to PORT if defined, otherwise default to 5000.
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port) |
d5217075d20c9b707dba191f4e7efdc9f66dcfaa | am_workout_assistant.py | am_workout_assistant.py | from telegram import Telegram
from message_checker import MessageHandler
from data_updater import DataUpdater
# init telegram bot
bot = Telegram()
ok = bot.init()
if not ok:
print("ERROR (bot init): {}".format(bot.get_messages()))
exit(1)
# init message checker
msg_checker = MessageHandler()
# init data updater
du = DataUpdater()
ok = du.init()
if not ok:
print("ERROR (data updater init): {}".format(du.get_error_message()))
exit(1)
for message in bot.get_messages():
print("Handling message '{}'...".format(message.get_text()))
msg_checker.set_message(message.get_text())
ok = msg_checker.check()
if not ok:
bot.send_reply(msg_checker.get_error_message())
continue
res = du.add_value(msg_checker.get_num_catch_ups(), message.date())
if res == False:
bot.send_reply(du.get_error_message())
continue
# success!
bot.send_reply("Successfully added {}!".format(msg_checker.get_num_catch_ups()))
| from telegram import Telegram
from message_checker import MessageHandler
from data_updater import DataUpdater
# init telegram bot
bot = Telegram()
ok = bot.init()
if not ok:
print("ERROR (bot init): {}".format(bot.get_messages()))
exit(1)
# init message checker
msg_checker = MessageHandler()
# init data updater
du = DataUpdater()
ok = du.init()
if not ok:
print("ERROR (data updater init): {}".format(du.get_error_message()))
exit(1)
for message in bot.get_messages():
print("Handling message '{}'...".format(message.get_text()))
msg_checker.set_message(message.get_text())
ok = msg_checker.check()
if not ok:
bot.send_reply(msg_checker.get_error_message())
continue
res = du.add_value(msg_checker.get_num_catch_ups(), message.get_date())
if res == False:
bot.send_reply(du.get_error_message())
continue
# success!
bot.send_reply("Successfully added {}! Sum for the day is {}."
.format(msg_checker.get_num_catch_ups(), res))
| Return summary for the day on success | Return summary for the day on success
This implements #2
| Python | mit | amaslenn/AMWorkoutAssist | from telegram import Telegram
from message_checker import MessageHandler
from data_updater import DataUpdater
# init telegram bot
bot = Telegram()
ok = bot.init()
if not ok:
print("ERROR (bot init): {}".format(bot.get_messages()))
exit(1)
# init message checker
msg_checker = MessageHandler()
# init data updater
du = DataUpdater()
ok = du.init()
if not ok:
print("ERROR (data updater init): {}".format(du.get_error_message()))
exit(1)
for message in bot.get_messages():
print("Handling message '{}'...".format(message.get_text()))
msg_checker.set_message(message.get_text())
ok = msg_checker.check()
if not ok:
bot.send_reply(msg_checker.get_error_message())
continue
- res = du.add_value(msg_checker.get_num_catch_ups(), message.date())
+ res = du.add_value(msg_checker.get_num_catch_ups(), message.get_date())
if res == False:
bot.send_reply(du.get_error_message())
continue
# success!
- bot.send_reply("Successfully added {}!".format(msg_checker.get_num_catch_ups()))
+ bot.send_reply("Successfully added {}! Sum for the day is {}."
+ .format(msg_checker.get_num_catch_ups(), res))
| Return summary for the day on success | ## Code Before:
from telegram import Telegram
from message_checker import MessageHandler
from data_updater import DataUpdater
# init telegram bot
bot = Telegram()
ok = bot.init()
if not ok:
print("ERROR (bot init): {}".format(bot.get_messages()))
exit(1)
# init message checker
msg_checker = MessageHandler()
# init data updater
du = DataUpdater()
ok = du.init()
if not ok:
print("ERROR (data updater init): {}".format(du.get_error_message()))
exit(1)
for message in bot.get_messages():
print("Handling message '{}'...".format(message.get_text()))
msg_checker.set_message(message.get_text())
ok = msg_checker.check()
if not ok:
bot.send_reply(msg_checker.get_error_message())
continue
res = du.add_value(msg_checker.get_num_catch_ups(), message.date())
if res == False:
bot.send_reply(du.get_error_message())
continue
# success!
bot.send_reply("Successfully added {}!".format(msg_checker.get_num_catch_ups()))
## Instruction:
Return summary for the day on success
## Code After:
from telegram import Telegram
from message_checker import MessageHandler
from data_updater import DataUpdater
# init telegram bot
bot = Telegram()
ok = bot.init()
if not ok:
print("ERROR (bot init): {}".format(bot.get_messages()))
exit(1)
# init message checker
msg_checker = MessageHandler()
# init data updater
du = DataUpdater()
ok = du.init()
if not ok:
print("ERROR (data updater init): {}".format(du.get_error_message()))
exit(1)
for message in bot.get_messages():
print("Handling message '{}'...".format(message.get_text()))
msg_checker.set_message(message.get_text())
ok = msg_checker.check()
if not ok:
bot.send_reply(msg_checker.get_error_message())
continue
res = du.add_value(msg_checker.get_num_catch_ups(), message.get_date())
if res == False:
bot.send_reply(du.get_error_message())
continue
# success!
bot.send_reply("Successfully added {}! Sum for the day is {}."
.format(msg_checker.get_num_catch_ups(), res))
| from telegram import Telegram
from message_checker import MessageHandler
from data_updater import DataUpdater
# init telegram bot
bot = Telegram()
ok = bot.init()
if not ok:
print("ERROR (bot init): {}".format(bot.get_messages()))
exit(1)
# init message checker
msg_checker = MessageHandler()
# init data updater
du = DataUpdater()
ok = du.init()
if not ok:
print("ERROR (data updater init): {}".format(du.get_error_message()))
exit(1)
for message in bot.get_messages():
print("Handling message '{}'...".format(message.get_text()))
msg_checker.set_message(message.get_text())
ok = msg_checker.check()
if not ok:
bot.send_reply(msg_checker.get_error_message())
continue
- res = du.add_value(msg_checker.get_num_catch_ups(), message.date())
+ res = du.add_value(msg_checker.get_num_catch_ups(), message.get_date())
? ++++
if res == False:
bot.send_reply(du.get_error_message())
continue
# success!
- bot.send_reply("Successfully added {}!".format(msg_checker.get_num_catch_ups()))
+ bot.send_reply("Successfully added {}! Sum for the day is {}."
+ .format(msg_checker.get_num_catch_ups(), res)) |
3d48f181f90995bd66dc436acccde9d18c5cfa3c | tests/settings.py | tests/settings.py | import django
DATABASE_ENGINE = 'sqlite3'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
INSTALLED_APPS = [
'django.contrib.sessions',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sites',
'django.contrib.comments',
'avatar',
]
ROOT_URLCONF = 'tests.urls'
SITE_ID = 1
SECRET_KEY = 'something-something'
if django.VERSION[:2] < (1, 6):
TEST_RUNNER = 'discover_runner.DiscoverRunner'
ROOT_URLCONF = 'tests.urls'
STATIC_URL = '/site_media/static/'
AVATAR_ALLOWED_FILE_EXTS = ('.jpg', '.png')
AVATAR_MAX_SIZE = 1024 * 1024
AVATAR_MAX_AVATARS_PER_USER = 20
| import django
DATABASE_ENGINE = 'sqlite3'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
INSTALLED_APPS = [
'django.contrib.sessions',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sites',
'avatar',
]
MIDDLEWARE_CLASSES = (
"django.middleware.common.BrokenLinkEmailsMiddleware",
"django.middleware.common.CommonMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
)
ROOT_URLCONF = 'tests.urls'
SITE_ID = 1
SECRET_KEY = 'something-something'
if django.VERSION[:2] < (1, 6):
TEST_RUNNER = 'discover_runner.DiscoverRunner'
ROOT_URLCONF = 'tests.urls'
STATIC_URL = '/site_media/static/'
AVATAR_ALLOWED_FILE_EXTS = ('.jpg', '.png')
AVATAR_MAX_SIZE = 1024 * 1024
AVATAR_MAX_AVATARS_PER_USER = 20
| Remove django.contrib.comments and add MIDDLEWARE_CLASSES | Remove django.contrib.comments and add MIDDLEWARE_CLASSES
| Python | bsd-3-clause | imgmix/django-avatar,barbuza/django-avatar,grantmcconnaughey/django-avatar,ad-m/django-avatar,jezdez/django-avatar,MachineandMagic/django-avatar,barbuza/django-avatar,ad-m/django-avatar,grantmcconnaughey/django-avatar,dannybrowne86/django-avatar,dannybrowne86/django-avatar,therocode/django-avatar,therocode/django-avatar,MachineandMagic/django-avatar,imgmix/django-avatar,brajeshvit/avatarmodule,brajeshvit/avatarmodule,jezdez/django-avatar | import django
DATABASE_ENGINE = 'sqlite3'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
INSTALLED_APPS = [
'django.contrib.sessions',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sites',
- 'django.contrib.comments',
'avatar',
]
+
+ MIDDLEWARE_CLASSES = (
+ "django.middleware.common.BrokenLinkEmailsMiddleware",
+ "django.middleware.common.CommonMiddleware",
+ "django.contrib.sessions.middleware.SessionMiddleware",
+ "django.middleware.csrf.CsrfViewMiddleware",
+ "django.contrib.auth.middleware.AuthenticationMiddleware",
+ "django.contrib.messages.middleware.MessageMiddleware",
+ )
+
ROOT_URLCONF = 'tests.urls'
SITE_ID = 1
SECRET_KEY = 'something-something'
if django.VERSION[:2] < (1, 6):
TEST_RUNNER = 'discover_runner.DiscoverRunner'
ROOT_URLCONF = 'tests.urls'
STATIC_URL = '/site_media/static/'
AVATAR_ALLOWED_FILE_EXTS = ('.jpg', '.png')
AVATAR_MAX_SIZE = 1024 * 1024
AVATAR_MAX_AVATARS_PER_USER = 20
| Remove django.contrib.comments and add MIDDLEWARE_CLASSES | ## Code Before:
import django
DATABASE_ENGINE = 'sqlite3'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
INSTALLED_APPS = [
'django.contrib.sessions',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sites',
'django.contrib.comments',
'avatar',
]
ROOT_URLCONF = 'tests.urls'
SITE_ID = 1
SECRET_KEY = 'something-something'
if django.VERSION[:2] < (1, 6):
TEST_RUNNER = 'discover_runner.DiscoverRunner'
ROOT_URLCONF = 'tests.urls'
STATIC_URL = '/site_media/static/'
AVATAR_ALLOWED_FILE_EXTS = ('.jpg', '.png')
AVATAR_MAX_SIZE = 1024 * 1024
AVATAR_MAX_AVATARS_PER_USER = 20
## Instruction:
Remove django.contrib.comments and add MIDDLEWARE_CLASSES
## Code After:
import django
DATABASE_ENGINE = 'sqlite3'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
INSTALLED_APPS = [
'django.contrib.sessions',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sites',
'avatar',
]
MIDDLEWARE_CLASSES = (
"django.middleware.common.BrokenLinkEmailsMiddleware",
"django.middleware.common.CommonMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
)
ROOT_URLCONF = 'tests.urls'
SITE_ID = 1
SECRET_KEY = 'something-something'
if django.VERSION[:2] < (1, 6):
TEST_RUNNER = 'discover_runner.DiscoverRunner'
ROOT_URLCONF = 'tests.urls'
STATIC_URL = '/site_media/static/'
AVATAR_ALLOWED_FILE_EXTS = ('.jpg', '.png')
AVATAR_MAX_SIZE = 1024 * 1024
AVATAR_MAX_AVATARS_PER_USER = 20
| import django
DATABASE_ENGINE = 'sqlite3'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
INSTALLED_APPS = [
'django.contrib.sessions',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sites',
- 'django.contrib.comments',
'avatar',
]
+
+ MIDDLEWARE_CLASSES = (
+ "django.middleware.common.BrokenLinkEmailsMiddleware",
+ "django.middleware.common.CommonMiddleware",
+ "django.contrib.sessions.middleware.SessionMiddleware",
+ "django.middleware.csrf.CsrfViewMiddleware",
+ "django.contrib.auth.middleware.AuthenticationMiddleware",
+ "django.contrib.messages.middleware.MessageMiddleware",
+ )
+
ROOT_URLCONF = 'tests.urls'
SITE_ID = 1
SECRET_KEY = 'something-something'
if django.VERSION[:2] < (1, 6):
TEST_RUNNER = 'discover_runner.DiscoverRunner'
ROOT_URLCONF = 'tests.urls'
STATIC_URL = '/site_media/static/'
AVATAR_ALLOWED_FILE_EXTS = ('.jpg', '.png')
AVATAR_MAX_SIZE = 1024 * 1024
AVATAR_MAX_AVATARS_PER_USER = 20 |
07e7f5023958538933802f78c7bdd5d61f04a825 | flocker/restapi/__init__.py | flocker/restapi/__init__.py |
from ._infrastructure import structured
__all__ = ["structured"]
|
from ._infrastructure import (
structured, EndpointResponse, userDocumentation,
)
__all__ = ["structured", "EndpointResponse", "userDocumentation"]
| Address review comment: Make more APIs public. | Address review comment: Make more APIs public.
| Python | apache-2.0 | moypray/flocker,adamtheturtle/flocker,Azulinho/flocker,agonzalezro/flocker,1d4Nf6/flocker,1d4Nf6/flocker,runcom/flocker,1d4Nf6/flocker,moypray/flocker,lukemarsden/flocker,LaynePeng/flocker,jml/flocker,moypray/flocker,adamtheturtle/flocker,lukemarsden/flocker,wallnerryan/flocker-profiles,mbrukman/flocker,jml/flocker,AndyHuu/flocker,achanda/flocker,wallnerryan/flocker-profiles,hackday-profilers/flocker,Azulinho/flocker,lukemarsden/flocker,wallnerryan/flocker-profiles,achanda/flocker,w4ngyi/flocker,achanda/flocker,Azulinho/flocker,AndyHuu/flocker,LaynePeng/flocker,agonzalezro/flocker,mbrukman/flocker,mbrukman/flocker,agonzalezro/flocker,AndyHuu/flocker,runcom/flocker,w4ngyi/flocker,jml/flocker,hackday-profilers/flocker,hackday-profilers/flocker,LaynePeng/flocker,runcom/flocker,adamtheturtle/flocker,w4ngyi/flocker |
- from ._infrastructure import structured
+ from ._infrastructure import (
+ structured, EndpointResponse, userDocumentation,
+ )
- __all__ = ["structured"]
+ __all__ = ["structured", "EndpointResponse", "userDocumentation"]
| Address review comment: Make more APIs public. | ## Code Before:
from ._infrastructure import structured
__all__ = ["structured"]
## Instruction:
Address review comment: Make more APIs public.
## Code After:
from ._infrastructure import (
structured, EndpointResponse, userDocumentation,
)
__all__ = ["structured", "EndpointResponse", "userDocumentation"]
|
- from ._infrastructure import structured
? ^^^^^^^^^^
+ from ._infrastructure import (
? ^
+ structured, EndpointResponse, userDocumentation,
+ )
- __all__ = ["structured"]
+ __all__ = ["structured", "EndpointResponse", "userDocumentation"] |
da39bc268e3fe94af348690262fc116e3e0b2c9c | attachments/admin.py | attachments/admin.py | from attachments.models import Attachment
from django.contrib.contenttypes import generic
class AttachmentInlines(generic.GenericStackedInline):
model = Attachment
extra = 1 | from attachments.models import Attachment
from django.contrib.contenttypes import admin
class AttachmentInlines(admin.GenericStackedInline):
model = Attachment
extra = 1 | Fix deprecated modules for content types | Fix deprecated modules for content types
| Python | bsd-3-clause | leotrubach/django-attachments,leotrubach/django-attachments | from attachments.models import Attachment
- from django.contrib.contenttypes import generic
+ from django.contrib.contenttypes import admin
- class AttachmentInlines(generic.GenericStackedInline):
+ class AttachmentInlines(admin.GenericStackedInline):
model = Attachment
extra = 1 | Fix deprecated modules for content types | ## Code Before:
from attachments.models import Attachment
from django.contrib.contenttypes import generic
class AttachmentInlines(generic.GenericStackedInline):
model = Attachment
extra = 1
## Instruction:
Fix deprecated modules for content types
## Code After:
from attachments.models import Attachment
from django.contrib.contenttypes import admin
class AttachmentInlines(admin.GenericStackedInline):
model = Attachment
extra = 1 | from attachments.models import Attachment
- from django.contrib.contenttypes import generic
? ^^ ----
+ from django.contrib.contenttypes import admin
? ^^^^
- class AttachmentInlines(generic.GenericStackedInline):
? ^^ ----
+ class AttachmentInlines(admin.GenericStackedInline):
? ^^^^
model = Attachment
extra = 1 |
e7d42847284ae73befad8bdf2fa035a6f95a82bb | tests/test_dow.py | tests/test_dow.py | from datetime import datetime
import pycron
def test_parser():
now = datetime(2015, 6, 18, 16, 7)
assert pycron.is_now('* * * * *', now)
assert pycron.is_now('* * * * 4', now)
assert pycron.is_now('* * * * */4', now)
assert pycron.is_now('* * * * 0,3,4', now)
assert pycron.is_now('* * * * 3', now) is False
assert pycron.is_now('* * * * */3', now) is False
assert pycron.is_now('* * * * 0,3,6', now) is False
assert pycron.DOW_CHOICES[now.isoweekday()][1] == 'Thursday'
assert pycron.DOW_CHOICES[0][1] == 'Sunday'
now = datetime(2015, 6, 21, 16, 7)
assert pycron.is_now('* * * * 0', now)
| from datetime import datetime, timedelta
import pycron
def test_parser():
now = datetime(2015, 6, 18, 16, 7)
assert pycron.is_now('* * * * *', now)
assert pycron.is_now('* * * * 4', now)
assert pycron.is_now('* * * * */4', now)
assert pycron.is_now('* * * * 0,3,4', now)
assert pycron.is_now('* * * * 3', now) is False
assert pycron.is_now('* * * * */3', now) is False
assert pycron.is_now('* * * * 0,3,6', now) is False
assert pycron.DOW_CHOICES[now.isoweekday()][1] == 'Thursday'
assert pycron.DOW_CHOICES[0][1] == 'Sunday'
now = datetime(2015, 6, 20, 16, 7)
for i in range(0, 7):
# Test day matching from Sunday onwards...
now += timedelta(days=1)
assert pycron.is_now('* * * * %i' % (i), now)
# Test weekdays
assert pycron.is_now('* * * * 1,2,3,4,5', now) is (True if i not in [0, 6] else False)
# Test weekends
assert pycron.is_now('* * * * 0,6', now) is (True if i in [0, 6] else False)
| Add more thorough testing of day of week. | Add more thorough testing of day of week.
| Python | mit | kipe/pycron | - from datetime import datetime
+ from datetime import datetime, timedelta
import pycron
def test_parser():
now = datetime(2015, 6, 18, 16, 7)
assert pycron.is_now('* * * * *', now)
assert pycron.is_now('* * * * 4', now)
assert pycron.is_now('* * * * */4', now)
assert pycron.is_now('* * * * 0,3,4', now)
assert pycron.is_now('* * * * 3', now) is False
assert pycron.is_now('* * * * */3', now) is False
assert pycron.is_now('* * * * 0,3,6', now) is False
assert pycron.DOW_CHOICES[now.isoweekday()][1] == 'Thursday'
assert pycron.DOW_CHOICES[0][1] == 'Sunday'
- now = datetime(2015, 6, 21, 16, 7)
+ now = datetime(2015, 6, 20, 16, 7)
+ for i in range(0, 7):
+ # Test day matching from Sunday onwards...
+ now += timedelta(days=1)
- assert pycron.is_now('* * * * 0', now)
+ assert pycron.is_now('* * * * %i' % (i), now)
+ # Test weekdays
+ assert pycron.is_now('* * * * 1,2,3,4,5', now) is (True if i not in [0, 6] else False)
+ # Test weekends
+ assert pycron.is_now('* * * * 0,6', now) is (True if i in [0, 6] else False)
| Add more thorough testing of day of week. | ## Code Before:
from datetime import datetime
import pycron
def test_parser():
now = datetime(2015, 6, 18, 16, 7)
assert pycron.is_now('* * * * *', now)
assert pycron.is_now('* * * * 4', now)
assert pycron.is_now('* * * * */4', now)
assert pycron.is_now('* * * * 0,3,4', now)
assert pycron.is_now('* * * * 3', now) is False
assert pycron.is_now('* * * * */3', now) is False
assert pycron.is_now('* * * * 0,3,6', now) is False
assert pycron.DOW_CHOICES[now.isoweekday()][1] == 'Thursday'
assert pycron.DOW_CHOICES[0][1] == 'Sunday'
now = datetime(2015, 6, 21, 16, 7)
assert pycron.is_now('* * * * 0', now)
## Instruction:
Add more thorough testing of day of week.
## Code After:
from datetime import datetime, timedelta
import pycron
def test_parser():
now = datetime(2015, 6, 18, 16, 7)
assert pycron.is_now('* * * * *', now)
assert pycron.is_now('* * * * 4', now)
assert pycron.is_now('* * * * */4', now)
assert pycron.is_now('* * * * 0,3,4', now)
assert pycron.is_now('* * * * 3', now) is False
assert pycron.is_now('* * * * */3', now) is False
assert pycron.is_now('* * * * 0,3,6', now) is False
assert pycron.DOW_CHOICES[now.isoweekday()][1] == 'Thursday'
assert pycron.DOW_CHOICES[0][1] == 'Sunday'
now = datetime(2015, 6, 20, 16, 7)
for i in range(0, 7):
# Test day matching from Sunday onwards...
now += timedelta(days=1)
assert pycron.is_now('* * * * %i' % (i), now)
# Test weekdays
assert pycron.is_now('* * * * 1,2,3,4,5', now) is (True if i not in [0, 6] else False)
# Test weekends
assert pycron.is_now('* * * * 0,6', now) is (True if i in [0, 6] else False)
| - from datetime import datetime
+ from datetime import datetime, timedelta
? +++++++++++
import pycron
def test_parser():
now = datetime(2015, 6, 18, 16, 7)
assert pycron.is_now('* * * * *', now)
assert pycron.is_now('* * * * 4', now)
assert pycron.is_now('* * * * */4', now)
assert pycron.is_now('* * * * 0,3,4', now)
assert pycron.is_now('* * * * 3', now) is False
assert pycron.is_now('* * * * */3', now) is False
assert pycron.is_now('* * * * 0,3,6', now) is False
assert pycron.DOW_CHOICES[now.isoweekday()][1] == 'Thursday'
assert pycron.DOW_CHOICES[0][1] == 'Sunday'
- now = datetime(2015, 6, 21, 16, 7)
? ^
+ now = datetime(2015, 6, 20, 16, 7)
? ^
+ for i in range(0, 7):
+ # Test day matching from Sunday onwards...
+ now += timedelta(days=1)
- assert pycron.is_now('* * * * 0', now)
? ^
+ assert pycron.is_now('* * * * %i' % (i), now)
? ++++ ^^ ++++++
+ # Test weekdays
+ assert pycron.is_now('* * * * 1,2,3,4,5', now) is (True if i not in [0, 6] else False)
+ # Test weekends
+ assert pycron.is_now('* * * * 0,6', now) is (True if i in [0, 6] else False) |
184d0400f2304b0fe7adf07471526bc66b4eea64 | libs/ConfigHelpers.py | libs/ConfigHelpers.py |
import logging
from tornado.options import options
from datetime import datetime
def save_config():
logging.info("Saving current config to: %s" % options.config)
with open(options.config, 'w') as fp:
fp.write("##########################")
fp.write(" Root the Box Config File ")
fp.write("##########################\n")
fp.write("# Last updated: %s\n" % datetime.now())
for group in options.groups():
# Shitty work around for Tornado 4.1
if 'rootthebox.py' in group.lower() or group == '':
continue
fp.write("\n# [ %s ]\n" % group.title())
try:
# python2
opt = options.group_dict(group).iteritems()
except AttributeError:
# python3
opt = options.group_dict(group).items()
for key, value in opt:
try:
# python2
value_type = basestring
except NameError:
# python 3
value_type = str
if isinstance(value, value_type):
# Str/Unicode needs to have quotes
fp.write(u'%s = "%s"\n' % (key, value))
else:
# Int/Bool/List use __str__
fp.write('%s = %s\n' % (key, value))
|
import logging
from tornado.options import options
from datetime import datetime
def save_config():
logging.info("Saving current config to: %s" % options.config)
with open(options.config, 'w') as fp:
fp.write("##########################")
fp.write(" Root the Box Config File ")
fp.write("##########################\n")
fp.write("# Documentation: %s\n" % "https://github.com/moloch--/RootTheBox/wiki/Configuration-File-Details")
fp.write("# Last updated: %s\n" % datetime.now())
for group in options.groups():
# Shitty work around for Tornado 4.1
if 'rootthebox.py' in group.lower() or group == '':
continue
fp.write("\n# [ %s ]\n" % group.title())
try:
# python2
opt = options.group_dict(group).iteritems()
except AttributeError:
# python3
opt = options.group_dict(group).items()
for key, value in opt:
try:
# python2
value_type = basestring
except NameError:
# python 3
value_type = str
if isinstance(value, value_type):
# Str/Unicode needs to have quotes
fp.write(u'%s = "%s"\n' % (key, value))
else:
# Int/Bool/List use __str__
fp.write('%s = %s\n' % (key, value))
| Add documenation link to config file | Add documenation link to config file
| Python | apache-2.0 | moloch--/RootTheBox,moloch--/RootTheBox,moloch--/RootTheBox,moloch--/RootTheBox |
import logging
from tornado.options import options
from datetime import datetime
def save_config():
logging.info("Saving current config to: %s" % options.config)
with open(options.config, 'w') as fp:
fp.write("##########################")
fp.write(" Root the Box Config File ")
fp.write("##########################\n")
+ fp.write("# Documentation: %s\n" % "https://github.com/moloch--/RootTheBox/wiki/Configuration-File-Details")
fp.write("# Last updated: %s\n" % datetime.now())
for group in options.groups():
# Shitty work around for Tornado 4.1
if 'rootthebox.py' in group.lower() or group == '':
continue
fp.write("\n# [ %s ]\n" % group.title())
try:
# python2
opt = options.group_dict(group).iteritems()
except AttributeError:
# python3
opt = options.group_dict(group).items()
for key, value in opt:
try:
# python2
value_type = basestring
except NameError:
# python 3
value_type = str
if isinstance(value, value_type):
# Str/Unicode needs to have quotes
fp.write(u'%s = "%s"\n' % (key, value))
else:
# Int/Bool/List use __str__
fp.write('%s = %s\n' % (key, value))
| Add documenation link to config file | ## Code Before:
import logging
from tornado.options import options
from datetime import datetime
def save_config():
logging.info("Saving current config to: %s" % options.config)
with open(options.config, 'w') as fp:
fp.write("##########################")
fp.write(" Root the Box Config File ")
fp.write("##########################\n")
fp.write("# Last updated: %s\n" % datetime.now())
for group in options.groups():
# Shitty work around for Tornado 4.1
if 'rootthebox.py' in group.lower() or group == '':
continue
fp.write("\n# [ %s ]\n" % group.title())
try:
# python2
opt = options.group_dict(group).iteritems()
except AttributeError:
# python3
opt = options.group_dict(group).items()
for key, value in opt:
try:
# python2
value_type = basestring
except NameError:
# python 3
value_type = str
if isinstance(value, value_type):
# Str/Unicode needs to have quotes
fp.write(u'%s = "%s"\n' % (key, value))
else:
# Int/Bool/List use __str__
fp.write('%s = %s\n' % (key, value))
## Instruction:
Add documenation link to config file
## Code After:
import logging
from tornado.options import options
from datetime import datetime
def save_config():
logging.info("Saving current config to: %s" % options.config)
with open(options.config, 'w') as fp:
fp.write("##########################")
fp.write(" Root the Box Config File ")
fp.write("##########################\n")
fp.write("# Documentation: %s\n" % "https://github.com/moloch--/RootTheBox/wiki/Configuration-File-Details")
fp.write("# Last updated: %s\n" % datetime.now())
for group in options.groups():
# Shitty work around for Tornado 4.1
if 'rootthebox.py' in group.lower() or group == '':
continue
fp.write("\n# [ %s ]\n" % group.title())
try:
# python2
opt = options.group_dict(group).iteritems()
except AttributeError:
# python3
opt = options.group_dict(group).items()
for key, value in opt:
try:
# python2
value_type = basestring
except NameError:
# python 3
value_type = str
if isinstance(value, value_type):
# Str/Unicode needs to have quotes
fp.write(u'%s = "%s"\n' % (key, value))
else:
# Int/Bool/List use __str__
fp.write('%s = %s\n' % (key, value))
|
import logging
from tornado.options import options
from datetime import datetime
def save_config():
logging.info("Saving current config to: %s" % options.config)
with open(options.config, 'w') as fp:
fp.write("##########################")
fp.write(" Root the Box Config File ")
fp.write("##########################\n")
+ fp.write("# Documentation: %s\n" % "https://github.com/moloch--/RootTheBox/wiki/Configuration-File-Details")
fp.write("# Last updated: %s\n" % datetime.now())
for group in options.groups():
# Shitty work around for Tornado 4.1
if 'rootthebox.py' in group.lower() or group == '':
continue
fp.write("\n# [ %s ]\n" % group.title())
try:
# python2
opt = options.group_dict(group).iteritems()
except AttributeError:
# python3
opt = options.group_dict(group).items()
for key, value in opt:
try:
# python2
value_type = basestring
except NameError:
# python 3
value_type = str
if isinstance(value, value_type):
# Str/Unicode needs to have quotes
fp.write(u'%s = "%s"\n' % (key, value))
else:
# Int/Bool/List use __str__
fp.write('%s = %s\n' % (key, value)) |
881222a49c6b3e8792adf5754c61992bd12c7b28 | tests/test_conduction.py | tests/test_conduction.py |
"""Test Mongo Conduction."""
import logging
import pymongo
from mockupdb import go
from pymongo.errors import OperationFailure
from conduction.server import get_mockup, main_loop
from tests import unittest # unittest2 on Python 2.6.
class ConductionTest(unittest.TestCase):
def setUp(self):
self.mockup = get_mockup(releases={}, env=None,
port=None, verbose=False)
# Quiet.
logging.getLogger('mongo_orchestration.apps').setLevel(logging.CRITICAL)
self.mockup.run()
self.loop_future = go(main_loop, self.mockup)
# Cleanups are LIFO: Stop the server, wait for the loop to exit.
self.addCleanup(self.loop_future)
self.addCleanup(self.mockup.stop)
self.conduction = pymongo.MongoClient(self.mockup.uri).test
def test_bad_command_name(self):
with self.assertRaises(OperationFailure):
self.conduction.command('foo')
if __name__ == '__main__':
unittest.main()
|
"""Test Mongo Conduction."""
import logging
import pymongo
from mockupdb import go
from pymongo.errors import OperationFailure
from conduction.server import get_mockup, main_loop
from tests import unittest # unittest2 on Python 2.6.
class ConductionTest(unittest.TestCase):
def setUp(self):
self.mockup = get_mockup(releases={}, env=None,
port=None, verbose=False)
# Quiet.
logging.getLogger('mongo_orchestration.apps').setLevel(logging.CRITICAL)
self.mockup.run()
self.loop_future = go(main_loop, self.mockup)
# Cleanups are LIFO: Stop the server, wait for the loop to exit.
self.addCleanup(self.loop_future)
self.addCleanup(self.mockup.stop)
# Any database name will do.
self.conduction = pymongo.MongoClient(self.mockup.uri).conduction
def test_root_uri(self):
reply = self.conduction.command('get', '/')
self.assertIn('links', reply)
self.assertIn('service', reply)
def test_bad_command_name(self):
with self.assertRaises(OperationFailure) as context:
self.conduction.command('foo')
self.assertIn('unrecognized: {"foo": 1}',
str(context.exception))
def test_server_id_404(self):
with self.assertRaises(OperationFailure) as context:
self.conduction.command({'post': '/v1/servers/'})
self.assertIn('404 Not Found', str(context.exception))
if __name__ == '__main__':
unittest.main()
| Test root URI and 404s. | Test root URI and 404s.
| Python | apache-2.0 | ajdavis/mongo-conduction |
"""Test Mongo Conduction."""
import logging
import pymongo
from mockupdb import go
from pymongo.errors import OperationFailure
from conduction.server import get_mockup, main_loop
from tests import unittest # unittest2 on Python 2.6.
class ConductionTest(unittest.TestCase):
def setUp(self):
self.mockup = get_mockup(releases={}, env=None,
port=None, verbose=False)
# Quiet.
logging.getLogger('mongo_orchestration.apps').setLevel(logging.CRITICAL)
self.mockup.run()
self.loop_future = go(main_loop, self.mockup)
# Cleanups are LIFO: Stop the server, wait for the loop to exit.
self.addCleanup(self.loop_future)
self.addCleanup(self.mockup.stop)
+ # Any database name will do.
- self.conduction = pymongo.MongoClient(self.mockup.uri).test
+ self.conduction = pymongo.MongoClient(self.mockup.uri).conduction
+
+ def test_root_uri(self):
+ reply = self.conduction.command('get', '/')
+ self.assertIn('links', reply)
+ self.assertIn('service', reply)
def test_bad_command_name(self):
- with self.assertRaises(OperationFailure):
+ with self.assertRaises(OperationFailure) as context:
self.conduction.command('foo')
+
+ self.assertIn('unrecognized: {"foo": 1}',
+ str(context.exception))
+
+ def test_server_id_404(self):
+ with self.assertRaises(OperationFailure) as context:
+ self.conduction.command({'post': '/v1/servers/'})
+
+ self.assertIn('404 Not Found', str(context.exception))
if __name__ == '__main__':
unittest.main()
| Test root URI and 404s. | ## Code Before:
"""Test Mongo Conduction."""
import logging
import pymongo
from mockupdb import go
from pymongo.errors import OperationFailure
from conduction.server import get_mockup, main_loop
from tests import unittest # unittest2 on Python 2.6.
class ConductionTest(unittest.TestCase):
def setUp(self):
self.mockup = get_mockup(releases={}, env=None,
port=None, verbose=False)
# Quiet.
logging.getLogger('mongo_orchestration.apps').setLevel(logging.CRITICAL)
self.mockup.run()
self.loop_future = go(main_loop, self.mockup)
# Cleanups are LIFO: Stop the server, wait for the loop to exit.
self.addCleanup(self.loop_future)
self.addCleanup(self.mockup.stop)
self.conduction = pymongo.MongoClient(self.mockup.uri).test
def test_bad_command_name(self):
with self.assertRaises(OperationFailure):
self.conduction.command('foo')
if __name__ == '__main__':
unittest.main()
## Instruction:
Test root URI and 404s.
## Code After:
"""Test Mongo Conduction."""
import logging
import pymongo
from mockupdb import go
from pymongo.errors import OperationFailure
from conduction.server import get_mockup, main_loop
from tests import unittest # unittest2 on Python 2.6.
class ConductionTest(unittest.TestCase):
def setUp(self):
self.mockup = get_mockup(releases={}, env=None,
port=None, verbose=False)
# Quiet.
logging.getLogger('mongo_orchestration.apps').setLevel(logging.CRITICAL)
self.mockup.run()
self.loop_future = go(main_loop, self.mockup)
# Cleanups are LIFO: Stop the server, wait for the loop to exit.
self.addCleanup(self.loop_future)
self.addCleanup(self.mockup.stop)
# Any database name will do.
self.conduction = pymongo.MongoClient(self.mockup.uri).conduction
def test_root_uri(self):
reply = self.conduction.command('get', '/')
self.assertIn('links', reply)
self.assertIn('service', reply)
def test_bad_command_name(self):
with self.assertRaises(OperationFailure) as context:
self.conduction.command('foo')
self.assertIn('unrecognized: {"foo": 1}',
str(context.exception))
def test_server_id_404(self):
with self.assertRaises(OperationFailure) as context:
self.conduction.command({'post': '/v1/servers/'})
self.assertIn('404 Not Found', str(context.exception))
if __name__ == '__main__':
unittest.main()
|
"""Test Mongo Conduction."""
import logging
import pymongo
from mockupdb import go
from pymongo.errors import OperationFailure
from conduction.server import get_mockup, main_loop
from tests import unittest # unittest2 on Python 2.6.
class ConductionTest(unittest.TestCase):
def setUp(self):
self.mockup = get_mockup(releases={}, env=None,
port=None, verbose=False)
# Quiet.
logging.getLogger('mongo_orchestration.apps').setLevel(logging.CRITICAL)
self.mockup.run()
self.loop_future = go(main_loop, self.mockup)
# Cleanups are LIFO: Stop the server, wait for the loop to exit.
self.addCleanup(self.loop_future)
self.addCleanup(self.mockup.stop)
+ # Any database name will do.
- self.conduction = pymongo.MongoClient(self.mockup.uri).test
? ^^^
+ self.conduction = pymongo.MongoClient(self.mockup.uri).conduction
? ++++++ ^^^
+
+ def test_root_uri(self):
+ reply = self.conduction.command('get', '/')
+ self.assertIn('links', reply)
+ self.assertIn('service', reply)
def test_bad_command_name(self):
- with self.assertRaises(OperationFailure):
+ with self.assertRaises(OperationFailure) as context:
? +++++++++++
self.conduction.command('foo')
+
+ self.assertIn('unrecognized: {"foo": 1}',
+ str(context.exception))
+
+ def test_server_id_404(self):
+ with self.assertRaises(OperationFailure) as context:
+ self.conduction.command({'post': '/v1/servers/'})
+
+ self.assertIn('404 Not Found', str(context.exception))
if __name__ == '__main__':
unittest.main() |
ad73c91d4e2b2d5faed35420a1393d016af84e40 | tests/test_event_manager/test_attribute.py | tests/test_event_manager/test_attribute.py | import uuid
from datetime import datetime
from dateutil.tz import UTC
from event_manager.event import Attribute
from tests.utils import BaseTest
class TestAttribute(BaseTest):
def test_props(self):
attr = Attribute(name='test')
assert attr.name == 'test'
assert attr.attr_type == str
assert attr.is_datetime is False
assert attr.is_uuid is False
assert attr.is_required is True
def test_extract(self):
attr = Attribute(name='test')
assert attr.extract(value='some value') == 'some value'
assert attr.extract(value=1) == '1'
attr = Attribute(name='test', attr_type=int)
assert attr.extract(value=1) == 1
attr = Attribute(name='test', is_datetime=True)
dt = datetime(2000, 12, 12, tzinfo=UTC)
assert attr.extract(value=dt) == 976579200.0
attr = Attribute(name='test', is_uuid=True)
uid = uuid.uuid4()
assert attr.extract(value=uid) == uid.hex
| import uuid
from datetime import datetime
from dateutil.tz import UTC
from event_manager.event import Attribute
from tests.utils import BaseTest
class TestAttribute(BaseTest):
def test_name_should_not_be_instance(self):
with self.assertRaises(AssertionError):
Attribute(name='instance')
def test_props(self):
attr = Attribute(name='test')
assert attr.name == 'test'
assert attr.attr_type == str
assert attr.is_datetime is False
assert attr.is_uuid is False
assert attr.is_required is True
def test_extract(self):
attr = Attribute(name='test')
assert attr.extract(value='some value') == 'some value'
assert attr.extract(value=1) == '1'
attr = Attribute(name='test', attr_type=int)
assert attr.extract(value=1) == 1
attr = Attribute(name='test', is_datetime=True)
dt = datetime(2000, 12, 12, tzinfo=UTC)
assert attr.extract(value=dt) == 976579200.0
attr = Attribute(name='test', is_uuid=True)
uid = uuid.uuid4()
assert attr.extract(value=uid) == uid.hex
| Add test for attribute instance assertion | Add test for attribute instance assertion
| Python | apache-2.0 | polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon | import uuid
from datetime import datetime
from dateutil.tz import UTC
from event_manager.event import Attribute
from tests.utils import BaseTest
class TestAttribute(BaseTest):
+ def test_name_should_not_be_instance(self):
+ with self.assertRaises(AssertionError):
+ Attribute(name='instance')
+
def test_props(self):
attr = Attribute(name='test')
assert attr.name == 'test'
assert attr.attr_type == str
assert attr.is_datetime is False
assert attr.is_uuid is False
assert attr.is_required is True
def test_extract(self):
attr = Attribute(name='test')
assert attr.extract(value='some value') == 'some value'
assert attr.extract(value=1) == '1'
attr = Attribute(name='test', attr_type=int)
assert attr.extract(value=1) == 1
attr = Attribute(name='test', is_datetime=True)
dt = datetime(2000, 12, 12, tzinfo=UTC)
assert attr.extract(value=dt) == 976579200.0
attr = Attribute(name='test', is_uuid=True)
uid = uuid.uuid4()
assert attr.extract(value=uid) == uid.hex
| Add test for attribute instance assertion | ## Code Before:
import uuid
from datetime import datetime
from dateutil.tz import UTC
from event_manager.event import Attribute
from tests.utils import BaseTest
class TestAttribute(BaseTest):
def test_props(self):
attr = Attribute(name='test')
assert attr.name == 'test'
assert attr.attr_type == str
assert attr.is_datetime is False
assert attr.is_uuid is False
assert attr.is_required is True
def test_extract(self):
attr = Attribute(name='test')
assert attr.extract(value='some value') == 'some value'
assert attr.extract(value=1) == '1'
attr = Attribute(name='test', attr_type=int)
assert attr.extract(value=1) == 1
attr = Attribute(name='test', is_datetime=True)
dt = datetime(2000, 12, 12, tzinfo=UTC)
assert attr.extract(value=dt) == 976579200.0
attr = Attribute(name='test', is_uuid=True)
uid = uuid.uuid4()
assert attr.extract(value=uid) == uid.hex
## Instruction:
Add test for attribute instance assertion
## Code After:
import uuid
from datetime import datetime
from dateutil.tz import UTC
from event_manager.event import Attribute
from tests.utils import BaseTest
class TestAttribute(BaseTest):
def test_name_should_not_be_instance(self):
with self.assertRaises(AssertionError):
Attribute(name='instance')
def test_props(self):
attr = Attribute(name='test')
assert attr.name == 'test'
assert attr.attr_type == str
assert attr.is_datetime is False
assert attr.is_uuid is False
assert attr.is_required is True
def test_extract(self):
attr = Attribute(name='test')
assert attr.extract(value='some value') == 'some value'
assert attr.extract(value=1) == '1'
attr = Attribute(name='test', attr_type=int)
assert attr.extract(value=1) == 1
attr = Attribute(name='test', is_datetime=True)
dt = datetime(2000, 12, 12, tzinfo=UTC)
assert attr.extract(value=dt) == 976579200.0
attr = Attribute(name='test', is_uuid=True)
uid = uuid.uuid4()
assert attr.extract(value=uid) == uid.hex
| import uuid
from datetime import datetime
from dateutil.tz import UTC
from event_manager.event import Attribute
from tests.utils import BaseTest
class TestAttribute(BaseTest):
+ def test_name_should_not_be_instance(self):
+ with self.assertRaises(AssertionError):
+ Attribute(name='instance')
+
def test_props(self):
attr = Attribute(name='test')
assert attr.name == 'test'
assert attr.attr_type == str
assert attr.is_datetime is False
assert attr.is_uuid is False
assert attr.is_required is True
def test_extract(self):
attr = Attribute(name='test')
assert attr.extract(value='some value') == 'some value'
assert attr.extract(value=1) == '1'
attr = Attribute(name='test', attr_type=int)
assert attr.extract(value=1) == 1
attr = Attribute(name='test', is_datetime=True)
dt = datetime(2000, 12, 12, tzinfo=UTC)
assert attr.extract(value=dt) == 976579200.0
attr = Attribute(name='test', is_uuid=True)
uid = uuid.uuid4()
assert attr.extract(value=uid) == uid.hex |
9a5d2a6f9efefb5b1647de5e467a9dfb74b86c9b | buffpy/tests/test_link.py | buffpy/tests/test_link.py | from nose.tools import eq_
from mock import MagicMock
from buffpy.models.link import Link
def test_links_shares():
'''
Test link's shares retrieving from constructor
'''
mocked_api = MagicMock()
mocked_api.get.return_value = {'shares': 123}
link = Link(api=mocked_api, url='www.google.com')
eq_(link, {'shares': 123, 'url': 'www.google.com', 'api': mocked_api})
mocked_api.get.assert_called_once_with(url='links/shares.json?url=www.google.com')
def test_links_get_shares():
'''
Test link's shares retrieving method
'''
mocked_api = MagicMock()
mocked_api.get.return_value = {'shares': 123}
link = Link(api=mocked_api, url='www.google.com')
eq_(link, {'shares': 123, 'url': 'www.google.com', 'api': mocked_api})
eq_(link.get_shares(), 123)
mocked_api.get.assert_any_call(url='links/shares.json?url=www.google.com')
eq_(mocked_api.get.call_count, 2)
| from unittest.mock import MagicMock
from buffpy.models.link import Link
def test_links_shares():
""" Test link"s shares retrieving from constructor. """
mocked_api = MagicMock()
mocked_api.get.return_value = {"shares": 123}
link = Link(api=mocked_api, url="www.google.com")
assert link["shares"] == 123
assert link["url"] == "www.google.com"
mocked_api.get.assert_called_once_with(url="links/shares.json?url=www.google.com")
def test_links_get_shares():
""" Test link"s shares retrieving method. """
mocked_api = MagicMock()
mocked_api.get.return_value = {"shares": 123}
link = Link(api=mocked_api, url="www.google.com")
assert link["shares"] == 123
assert link["url"] == "www.google.com"
assert link.get_shares() == 123
mocked_api.get.assert_any_call(url="links/shares.json?url=www.google.com")
assert mocked_api.get.call_count == 2
| Migrate link tests to pytest | Migrate link tests to pytest
| Python | mit | vtemian/buffpy | - from nose.tools import eq_
- from mock import MagicMock
+ from unittest.mock import MagicMock
from buffpy.models.link import Link
+
def test_links_shares():
- '''
- Test link's shares retrieving from constructor
+ """ Test link"s shares retrieving from constructor. """
- '''
- mocked_api = MagicMock()
+ mocked_api = MagicMock()
- mocked_api.get.return_value = {'shares': 123}
+ mocked_api.get.return_value = {"shares": 123}
- link = Link(api=mocked_api, url='www.google.com')
+ link = Link(api=mocked_api, url="www.google.com")
- eq_(link, {'shares': 123, 'url': 'www.google.com', 'api': mocked_api})
+ assert link["shares"] == 123
+ assert link["url"] == "www.google.com"
- mocked_api.get.assert_called_once_with(url='links/shares.json?url=www.google.com')
+ mocked_api.get.assert_called_once_with(url="links/shares.json?url=www.google.com")
+
def test_links_get_shares():
- '''
- Test link's shares retrieving method
+ """ Test link"s shares retrieving method. """
- '''
- mocked_api = MagicMock()
+ mocked_api = MagicMock()
- mocked_api.get.return_value = {'shares': 123}
+ mocked_api.get.return_value = {"shares": 123}
- link = Link(api=mocked_api, url='www.google.com')
+ link = Link(api=mocked_api, url="www.google.com")
- eq_(link, {'shares': 123, 'url': 'www.google.com', 'api': mocked_api})
+ assert link["shares"] == 123
+ assert link["url"] == "www.google.com"
- eq_(link.get_shares(), 123)
+ assert link.get_shares() == 123
- mocked_api.get.assert_any_call(url='links/shares.json?url=www.google.com')
- eq_(mocked_api.get.call_count, 2)
+ mocked_api.get.assert_any_call(url="links/shares.json?url=www.google.com")
+ assert mocked_api.get.call_count == 2
+ | Migrate link tests to pytest | ## Code Before:
from nose.tools import eq_
from mock import MagicMock
from buffpy.models.link import Link
def test_links_shares():
'''
Test link's shares retrieving from constructor
'''
mocked_api = MagicMock()
mocked_api.get.return_value = {'shares': 123}
link = Link(api=mocked_api, url='www.google.com')
eq_(link, {'shares': 123, 'url': 'www.google.com', 'api': mocked_api})
mocked_api.get.assert_called_once_with(url='links/shares.json?url=www.google.com')
def test_links_get_shares():
'''
Test link's shares retrieving method
'''
mocked_api = MagicMock()
mocked_api.get.return_value = {'shares': 123}
link = Link(api=mocked_api, url='www.google.com')
eq_(link, {'shares': 123, 'url': 'www.google.com', 'api': mocked_api})
eq_(link.get_shares(), 123)
mocked_api.get.assert_any_call(url='links/shares.json?url=www.google.com')
eq_(mocked_api.get.call_count, 2)
## Instruction:
Migrate link tests to pytest
## Code After:
from unittest.mock import MagicMock
from buffpy.models.link import Link
def test_links_shares():
""" Test link"s shares retrieving from constructor. """
mocked_api = MagicMock()
mocked_api.get.return_value = {"shares": 123}
link = Link(api=mocked_api, url="www.google.com")
assert link["shares"] == 123
assert link["url"] == "www.google.com"
mocked_api.get.assert_called_once_with(url="links/shares.json?url=www.google.com")
def test_links_get_shares():
""" Test link"s shares retrieving method. """
mocked_api = MagicMock()
mocked_api.get.return_value = {"shares": 123}
link = Link(api=mocked_api, url="www.google.com")
assert link["shares"] == 123
assert link["url"] == "www.google.com"
assert link.get_shares() == 123
mocked_api.get.assert_any_call(url="links/shares.json?url=www.google.com")
assert mocked_api.get.call_count == 2
| - from nose.tools import eq_
- from mock import MagicMock
+ from unittest.mock import MagicMock
? +++++++++
from buffpy.models.link import Link
+
def test_links_shares():
- '''
- Test link's shares retrieving from constructor
? ^
+ """ Test link"s shares retrieving from constructor. """
? ++++ ^ +++++
- '''
- mocked_api = MagicMock()
+ mocked_api = MagicMock()
? ++
- mocked_api.get.return_value = {'shares': 123}
? ^ ^
+ mocked_api.get.return_value = {"shares": 123}
? ++ ^ ^
- link = Link(api=mocked_api, url='www.google.com')
? ^ ^
+ link = Link(api=mocked_api, url="www.google.com")
? ++ ^ ^
- eq_(link, {'shares': 123, 'url': 'www.google.com', 'api': mocked_api})
+ assert link["shares"] == 123
+ assert link["url"] == "www.google.com"
- mocked_api.get.assert_called_once_with(url='links/shares.json?url=www.google.com')
? ^ ^
+ mocked_api.get.assert_called_once_with(url="links/shares.json?url=www.google.com")
? ++ ^ ^
+
def test_links_get_shares():
- '''
- Test link's shares retrieving method
? ^
+ """ Test link"s shares retrieving method. """
? ++++ ^ +++++
- '''
- mocked_api = MagicMock()
+ mocked_api = MagicMock()
? ++
- mocked_api.get.return_value = {'shares': 123}
? ^ ^
+ mocked_api.get.return_value = {"shares": 123}
? ++ ^ ^
- link = Link(api=mocked_api, url='www.google.com')
? ^ ^
+ link = Link(api=mocked_api, url="www.google.com")
? ++ ^ ^
- eq_(link, {'shares': 123, 'url': 'www.google.com', 'api': mocked_api})
+ assert link["shares"] == 123
+ assert link["url"] == "www.google.com"
- eq_(link.get_shares(), 123)
? ^^^ ^ -
+ assert link.get_shares() == 123
? +++++ ^^^ ^^^
+
- mocked_api.get.assert_any_call(url='links/shares.json?url=www.google.com')
? ^ ^
+ mocked_api.get.assert_any_call(url="links/shares.json?url=www.google.com")
? ++ ^ ^
- eq_(mocked_api.get.call_count, 2)
? ^^^ ^ -
+ assert mocked_api.get.call_count == 2
? +++++ ^^^ ^^^
|
ffd4c52155acd7d04939e766ebe63171b580a2fa | src/__init__.py | src/__init__.py | import os
import logging
from kaa.base import ipc
from client import *
from server import *
__all__ = [ 'connect' ]
# connected client object
_client = None
def connect(epgdb, logfile='/tmp/kaa-epg.log', loglevel=logging.INFO):
"""
"""
global _client
# get server filename
server = os.path.join(os.path.dirname(__file__), 'server.py')
if epgdb.find(':') >= 0:
# epg is remote: host:port
# TODO: create socket, pass it to client
_client = GuideClient("epg")
else:
# epg is local
_client = ipc.launch([server, logfile, str(loglevel), epgdb], 2, GuideClient, "epg")
return _client
| import os
import logging
from socket import gethostbyname, gethostname
from kaa.base import ipc
from client import *
from server import *
__all__ = [ 'connect', 'DEFAULT_EPG_PORT', 'GuideClient', 'GuideServer' ]
# connected client object
_client = None
def connect(epgdb, address='127.0.0.1', logfile='/tmp/kaa-epg.log', loglevel=logging.INFO):
"""
"""
global _client
if _client:
return _client
if address.split(':')[0] not in ['127.0.0.1', '0.0.0.0'] and \
address != gethostbyname(gethostname()):
# epg is remote: host:port
if address.find(':') >= 0:
host, port = address.split(':', 1)
else:
host = address
port = DEFAULT_EPG_PORT
# create socket, pass it to client
_client = GuideClient((host, port))
else:
# EPG is local, only use unix socket
# get server filename
server = os.path.join(os.path.dirname(__file__), 'server.py')
_client = ipc.launch([server, logfile, str(loglevel), epgdb, address],
2, GuideClient, "epg")
return _client
| Add the ability to use inet socket as well. | Add the ability to use inet socket as well.
git-svn-id: ffaf500d3baede20d2f41eac1d275ef07405e077@1236 a8f5125c-1e01-0410-8897-facf34644b8e
| Python | lgpl-2.1 | freevo/kaa-epg | import os
import logging
+ from socket import gethostbyname, gethostname
from kaa.base import ipc
from client import *
from server import *
- __all__ = [ 'connect' ]
+ __all__ = [ 'connect', 'DEFAULT_EPG_PORT', 'GuideClient', 'GuideServer' ]
# connected client object
_client = None
- def connect(epgdb, logfile='/tmp/kaa-epg.log', loglevel=logging.INFO):
+ def connect(epgdb, address='127.0.0.1', logfile='/tmp/kaa-epg.log', loglevel=logging.INFO):
"""
"""
global _client
- # get server filename
- server = os.path.join(os.path.dirname(__file__), 'server.py')
+ if _client:
+ return _client
- if epgdb.find(':') >= 0:
+ if address.split(':')[0] not in ['127.0.0.1', '0.0.0.0'] and \
+ address != gethostbyname(gethostname()):
# epg is remote: host:port
+ if address.find(':') >= 0:
+ host, port = address.split(':', 1)
+ else:
+ host = address
+ port = DEFAULT_EPG_PORT
+
- # TODO: create socket, pass it to client
+ # create socket, pass it to client
- _client = GuideClient("epg")
+ _client = GuideClient((host, port))
else:
- # epg is local
+ # EPG is local, only use unix socket
+
+ # get server filename
+ server = os.path.join(os.path.dirname(__file__), 'server.py')
+
- _client = ipc.launch([server, logfile, str(loglevel), epgdb], 2, GuideClient, "epg")
+ _client = ipc.launch([server, logfile, str(loglevel), epgdb, address],
+ 2, GuideClient, "epg")
+
return _client
| Add the ability to use inet socket as well. | ## Code Before:
import os
import logging
from kaa.base import ipc
from client import *
from server import *
__all__ = [ 'connect' ]
# connected client object
_client = None
def connect(epgdb, logfile='/tmp/kaa-epg.log', loglevel=logging.INFO):
"""
"""
global _client
# get server filename
server = os.path.join(os.path.dirname(__file__), 'server.py')
if epgdb.find(':') >= 0:
# epg is remote: host:port
# TODO: create socket, pass it to client
_client = GuideClient("epg")
else:
# epg is local
_client = ipc.launch([server, logfile, str(loglevel), epgdb], 2, GuideClient, "epg")
return _client
## Instruction:
Add the ability to use inet socket as well.
## Code After:
import os
import logging
from socket import gethostbyname, gethostname
from kaa.base import ipc
from client import *
from server import *
__all__ = [ 'connect', 'DEFAULT_EPG_PORT', 'GuideClient', 'GuideServer' ]
# connected client object
_client = None
def connect(epgdb, address='127.0.0.1', logfile='/tmp/kaa-epg.log', loglevel=logging.INFO):
"""
"""
global _client
if _client:
return _client
if address.split(':')[0] not in ['127.0.0.1', '0.0.0.0'] and \
address != gethostbyname(gethostname()):
# epg is remote: host:port
if address.find(':') >= 0:
host, port = address.split(':', 1)
else:
host = address
port = DEFAULT_EPG_PORT
# create socket, pass it to client
_client = GuideClient((host, port))
else:
# EPG is local, only use unix socket
# get server filename
server = os.path.join(os.path.dirname(__file__), 'server.py')
_client = ipc.launch([server, logfile, str(loglevel), epgdb, address],
2, GuideClient, "epg")
return _client
| import os
import logging
+ from socket import gethostbyname, gethostname
from kaa.base import ipc
from client import *
from server import *
- __all__ = [ 'connect' ]
+ __all__ = [ 'connect', 'DEFAULT_EPG_PORT', 'GuideClient', 'GuideServer' ]
# connected client object
_client = None
- def connect(epgdb, logfile='/tmp/kaa-epg.log', loglevel=logging.INFO):
+ def connect(epgdb, address='127.0.0.1', logfile='/tmp/kaa-epg.log', loglevel=logging.INFO):
? +++++++++++++++++++++
"""
"""
global _client
- # get server filename
- server = os.path.join(os.path.dirname(__file__), 'server.py')
+ if _client:
+ return _client
- if epgdb.find(':') >= 0:
+ if address.split(':')[0] not in ['127.0.0.1', '0.0.0.0'] and \
+ address != gethostbyname(gethostname()):
# epg is remote: host:port
+ if address.find(':') >= 0:
+ host, port = address.split(':', 1)
+ else:
+ host = address
+ port = DEFAULT_EPG_PORT
+
- # TODO: create socket, pass it to client
? ------
+ # create socket, pass it to client
- _client = GuideClient("epg")
? ^^ ^^
+ _client = GuideClient((host, port))
? ^^^^^^^ ^^^ +
else:
- # epg is local
+ # EPG is local, only use unix socket
+
+ # get server filename
+ server = os.path.join(os.path.dirname(__file__), 'server.py')
+
- _client = ipc.launch([server, logfile, str(loglevel), epgdb], 2, GuideClient, "epg")
? ----------------------
+ _client = ipc.launch([server, logfile, str(loglevel), epgdb, address],
? +++++++++
+ 2, GuideClient, "epg")
+
return _client
|
baabc63ffad0b9641bd3d68800a9db84fe4076d3 | src/__init__.py | src/__init__.py | __version_info__ = ('1', '10', '3')
__version__ = '.'.join(__version_info__)
from .wrappers import (ObjectProxy, CallableObjectProxy, FunctionWrapper,
BoundFunctionWrapper, WeakFunctionProxy, resolve_path, apply_patch,
wrap_object, wrap_object_attribute, function_wrapper,
wrap_function_wrapper, patch_function_wrapper,
transient_function_wrapper)
from .decorators import (adapter_factory, AdapterFactory, decorator,
synchronized)
from .importer import (register_post_import_hook, when_imported,
discover_post_import_hooks)
try:
from inspect import getcallargs
except ImportError:
from .arguments import getcallargs
| __version_info__ = ('1', '10', '3')
__version__ = '.'.join(__version_info__)
from .wrappers import (ObjectProxy, CallableObjectProxy, FunctionWrapper,
BoundFunctionWrapper, WeakFunctionProxy, resolve_path, apply_patch,
wrap_object, wrap_object_attribute, function_wrapper,
wrap_function_wrapper, patch_function_wrapper,
transient_function_wrapper)
from .decorators import (adapter_factory, AdapterFactory, decorator,
synchronized)
from .importer import (register_post_import_hook, when_imported,
notify_module_loaded, discover_post_import_hooks)
try:
from inspect import getcallargs
except ImportError:
from .arguments import getcallargs
| Add post import hook discovery to public API. | Add post import hook discovery to public API.
| Python | bsd-2-clause | GrahamDumpleton/wrapt,github4ry/wrapt,linglaiyao1314/wrapt,pombredanne/wrapt,wujuguang/wrapt,linglaiyao1314/wrapt,wujuguang/wrapt,akash1808/wrapt,pombredanne/wrapt,GrahamDumpleton/wrapt,github4ry/wrapt,akash1808/wrapt | __version_info__ = ('1', '10', '3')
__version__ = '.'.join(__version_info__)
from .wrappers import (ObjectProxy, CallableObjectProxy, FunctionWrapper,
BoundFunctionWrapper, WeakFunctionProxy, resolve_path, apply_patch,
wrap_object, wrap_object_attribute, function_wrapper,
wrap_function_wrapper, patch_function_wrapper,
transient_function_wrapper)
from .decorators import (adapter_factory, AdapterFactory, decorator,
synchronized)
from .importer import (register_post_import_hook, when_imported,
- discover_post_import_hooks)
+ notify_module_loaded, discover_post_import_hooks)
try:
from inspect import getcallargs
except ImportError:
from .arguments import getcallargs
| Add post import hook discovery to public API. | ## Code Before:
__version_info__ = ('1', '10', '3')
__version__ = '.'.join(__version_info__)
from .wrappers import (ObjectProxy, CallableObjectProxy, FunctionWrapper,
BoundFunctionWrapper, WeakFunctionProxy, resolve_path, apply_patch,
wrap_object, wrap_object_attribute, function_wrapper,
wrap_function_wrapper, patch_function_wrapper,
transient_function_wrapper)
from .decorators import (adapter_factory, AdapterFactory, decorator,
synchronized)
from .importer import (register_post_import_hook, when_imported,
discover_post_import_hooks)
try:
from inspect import getcallargs
except ImportError:
from .arguments import getcallargs
## Instruction:
Add post import hook discovery to public API.
## Code After:
__version_info__ = ('1', '10', '3')
__version__ = '.'.join(__version_info__)
from .wrappers import (ObjectProxy, CallableObjectProxy, FunctionWrapper,
BoundFunctionWrapper, WeakFunctionProxy, resolve_path, apply_patch,
wrap_object, wrap_object_attribute, function_wrapper,
wrap_function_wrapper, patch_function_wrapper,
transient_function_wrapper)
from .decorators import (adapter_factory, AdapterFactory, decorator,
synchronized)
from .importer import (register_post_import_hook, when_imported,
notify_module_loaded, discover_post_import_hooks)
try:
from inspect import getcallargs
except ImportError:
from .arguments import getcallargs
| __version_info__ = ('1', '10', '3')
__version__ = '.'.join(__version_info__)
from .wrappers import (ObjectProxy, CallableObjectProxy, FunctionWrapper,
BoundFunctionWrapper, WeakFunctionProxy, resolve_path, apply_patch,
wrap_object, wrap_object_attribute, function_wrapper,
wrap_function_wrapper, patch_function_wrapper,
transient_function_wrapper)
from .decorators import (adapter_factory, AdapterFactory, decorator,
synchronized)
from .importer import (register_post_import_hook, when_imported,
- discover_post_import_hooks)
+ notify_module_loaded, discover_post_import_hooks)
? ++++++++++++++++++++++
try:
from inspect import getcallargs
except ImportError:
from .arguments import getcallargs |
7aab3ca6cdf3cf8c4c2a1e01ededede5a4bad0f1 | tests/test_cardinal/test_context.py | tests/test_cardinal/test_context.py | import pytest
from cardinal.context import Context
from cardinal.errors import IllegalSessionUse
@pytest.fixture
def base_ctor(mocker):
return mocker.patch('cardinal.context.commands.Context.__init__')
@pytest.fixture(params=[
{},
{'asdf': 123}
])
def ctx(base_ctor, request):
yield Context(**request.param)
base_ctor.assert_called_once_with(**request.param)
@pytest.fixture
def sessionmaker(ctx, mocker):
ctx.bot = mocker.Mock()
return ctx.bot.sessionmaker
def test_ctor(ctx):
assert not ctx.session_used
def test_session_not_allowed(ctx, sessionmaker):
with pytest.raises(IllegalSessionUse):
_ = ctx.session
sessionmaker.assert_not_called()
def test_session_allowed(ctx, sessionmaker):
ctx.session_allowed = True
sess1 = ctx.session
sessionmaker.assert_called_once_with()
assert ctx.session_used is True
sessionmaker.reset_mock()
sess2 = ctx.session
sessionmaker.assert_not_called()
assert sess1 is sess2
| import pytest
from cardinal.context import Context
from cardinal.errors import IllegalSessionUse
@pytest.fixture
def base_ctor(mocker):
return mocker.patch('cardinal.context.commands.Context.__init__')
@pytest.fixture
def ctx(base_ctor, request):
kwargs = getattr(request, 'param', {})
yield Context(**kwargs)
if hasattr(request, 'param'):
base_ctor.assert_called_once_with(**kwargs) # Skip unnecessary assertions
@pytest.fixture
def sessionmaker(ctx, mocker):
ctx.bot = mocker.Mock()
return ctx.bot.sessionmaker
@pytest.mark.parametrize(
['ctx'],
[
({},),
({'asdf': 123},)
],
indirect=True
)
def test_ctor(ctx):
assert not ctx.session_used
def test_session_not_allowed(ctx, sessionmaker):
with pytest.raises(IllegalSessionUse):
_ = ctx.session
sessionmaker.assert_not_called()
def test_session_allowed(ctx, sessionmaker):
ctx.session_allowed = True
sess1 = ctx.session
sessionmaker.assert_called_once_with()
assert ctx.session_used is True
sessionmaker.reset_mock()
sess2 = ctx.session
sessionmaker.assert_not_called()
assert sess1 is sess2
| Adjust fixture usage in context tests | Adjust fixture usage in context tests
| Python | mit | FallenWarrior2k/cardinal.py,FallenWarrior2k/cardinal.py | import pytest
from cardinal.context import Context
from cardinal.errors import IllegalSessionUse
@pytest.fixture
def base_ctor(mocker):
return mocker.patch('cardinal.context.commands.Context.__init__')
- @pytest.fixture(params=[
+ @pytest.fixture
- {},
- {'asdf': 123}
- ])
def ctx(base_ctor, request):
+ kwargs = getattr(request, 'param', {})
+
- yield Context(**request.param)
+ yield Context(**kwargs)
- base_ctor.assert_called_once_with(**request.param)
+ if hasattr(request, 'param'):
+ base_ctor.assert_called_once_with(**kwargs) # Skip unnecessary assertions
@pytest.fixture
def sessionmaker(ctx, mocker):
ctx.bot = mocker.Mock()
return ctx.bot.sessionmaker
+ @pytest.mark.parametrize(
+ ['ctx'],
+ [
+ ({},),
+ ({'asdf': 123},)
+ ],
+ indirect=True
+ )
def test_ctor(ctx):
assert not ctx.session_used
def test_session_not_allowed(ctx, sessionmaker):
with pytest.raises(IllegalSessionUse):
_ = ctx.session
sessionmaker.assert_not_called()
def test_session_allowed(ctx, sessionmaker):
ctx.session_allowed = True
sess1 = ctx.session
sessionmaker.assert_called_once_with()
assert ctx.session_used is True
sessionmaker.reset_mock()
sess2 = ctx.session
sessionmaker.assert_not_called()
assert sess1 is sess2
| Adjust fixture usage in context tests | ## Code Before:
import pytest
from cardinal.context import Context
from cardinal.errors import IllegalSessionUse
@pytest.fixture
def base_ctor(mocker):
return mocker.patch('cardinal.context.commands.Context.__init__')
@pytest.fixture(params=[
{},
{'asdf': 123}
])
def ctx(base_ctor, request):
yield Context(**request.param)
base_ctor.assert_called_once_with(**request.param)
@pytest.fixture
def sessionmaker(ctx, mocker):
ctx.bot = mocker.Mock()
return ctx.bot.sessionmaker
def test_ctor(ctx):
assert not ctx.session_used
def test_session_not_allowed(ctx, sessionmaker):
with pytest.raises(IllegalSessionUse):
_ = ctx.session
sessionmaker.assert_not_called()
def test_session_allowed(ctx, sessionmaker):
ctx.session_allowed = True
sess1 = ctx.session
sessionmaker.assert_called_once_with()
assert ctx.session_used is True
sessionmaker.reset_mock()
sess2 = ctx.session
sessionmaker.assert_not_called()
assert sess1 is sess2
## Instruction:
Adjust fixture usage in context tests
## Code After:
import pytest
from cardinal.context import Context
from cardinal.errors import IllegalSessionUse
@pytest.fixture
def base_ctor(mocker):
return mocker.patch('cardinal.context.commands.Context.__init__')
@pytest.fixture
def ctx(base_ctor, request):
kwargs = getattr(request, 'param', {})
yield Context(**kwargs)
if hasattr(request, 'param'):
base_ctor.assert_called_once_with(**kwargs) # Skip unnecessary assertions
@pytest.fixture
def sessionmaker(ctx, mocker):
ctx.bot = mocker.Mock()
return ctx.bot.sessionmaker
@pytest.mark.parametrize(
['ctx'],
[
({},),
({'asdf': 123},)
],
indirect=True
)
def test_ctor(ctx):
assert not ctx.session_used
def test_session_not_allowed(ctx, sessionmaker):
with pytest.raises(IllegalSessionUse):
_ = ctx.session
sessionmaker.assert_not_called()
def test_session_allowed(ctx, sessionmaker):
ctx.session_allowed = True
sess1 = ctx.session
sessionmaker.assert_called_once_with()
assert ctx.session_used is True
sessionmaker.reset_mock()
sess2 = ctx.session
sessionmaker.assert_not_called()
assert sess1 is sess2
| import pytest
from cardinal.context import Context
from cardinal.errors import IllegalSessionUse
@pytest.fixture
def base_ctor(mocker):
return mocker.patch('cardinal.context.commands.Context.__init__')
- @pytest.fixture(params=[
? ---------
+ @pytest.fixture
- {},
- {'asdf': 123}
- ])
def ctx(base_ctor, request):
+ kwargs = getattr(request, 'param', {})
+
- yield Context(**request.param)
? ^^^^^^^^^ ^^
+ yield Context(**kwargs)
? ^^ ^^
- base_ctor.assert_called_once_with(**request.param)
+ if hasattr(request, 'param'):
+ base_ctor.assert_called_once_with(**kwargs) # Skip unnecessary assertions
@pytest.fixture
def sessionmaker(ctx, mocker):
ctx.bot = mocker.Mock()
return ctx.bot.sessionmaker
+ @pytest.mark.parametrize(
+ ['ctx'],
+ [
+ ({},),
+ ({'asdf': 123},)
+ ],
+ indirect=True
+ )
def test_ctor(ctx):
assert not ctx.session_used
def test_session_not_allowed(ctx, sessionmaker):
with pytest.raises(IllegalSessionUse):
_ = ctx.session
sessionmaker.assert_not_called()
def test_session_allowed(ctx, sessionmaker):
ctx.session_allowed = True
sess1 = ctx.session
sessionmaker.assert_called_once_with()
assert ctx.session_used is True
sessionmaker.reset_mock()
sess2 = ctx.session
sessionmaker.assert_not_called()
assert sess1 is sess2 |
fd39c97cd1cab3e55ba6aa067127af93e41af506 | tests/travis-setup.py | tests/travis-setup.py | import bcrypt
import sys
import os
sys.path.insert(0, "..")
from timpani import database
connection = database.DatabaseConnection()
hashedpassword = bcrypt.hashpw(bytes("password", "utf-8"), bcrypt.gensalt()).decode("utf-8")
user = database.tables.User(username = "tests", password = hashedpassword, full_name = "Timpani Tests", can_change_settings = True, can_write_posts = True)
connection.session.add(user)
connection.session.commit()
connection.close()
| import bcrypt
import sys
import os
sys.path.insert(0, "..")
from timpani import database
connection = database.DatabaseConnection()
hashedpassword = bcrypt.hashpw(bytes("password", "utf-8"), bcrypt.gensalt()).decode("utf-8")
user = database.tables.User(username = "tests", password = hashedpassword, full_name = "Timpani Tests", can_change_settings = True, can_write_posts = True)
connection.session.add(user)
connection.session.execute("CREATE INDEX ON sessions(session_id)")
connection.session.commit()
connection.close()
| Create index on session_id in order to speed tests | Create index on session_id in order to speed tests
It seems that session querying has been the longest component of all my
tests, and adding one test raised my test time signifigantly. Hopefully
this smooths somet of that out.
| Python | mit | ollien/Timpani,ollien/Timpani,ollien/Timpani | import bcrypt
import sys
import os
sys.path.insert(0, "..")
from timpani import database
connection = database.DatabaseConnection()
hashedpassword = bcrypt.hashpw(bytes("password", "utf-8"), bcrypt.gensalt()).decode("utf-8")
user = database.tables.User(username = "tests", password = hashedpassword, full_name = "Timpani Tests", can_change_settings = True, can_write_posts = True)
connection.session.add(user)
+ connection.session.execute("CREATE INDEX ON sessions(session_id)")
connection.session.commit()
connection.close()
| Create index on session_id in order to speed tests | ## Code Before:
import bcrypt
import sys
import os
sys.path.insert(0, "..")
from timpani import database
connection = database.DatabaseConnection()
hashedpassword = bcrypt.hashpw(bytes("password", "utf-8"), bcrypt.gensalt()).decode("utf-8")
user = database.tables.User(username = "tests", password = hashedpassword, full_name = "Timpani Tests", can_change_settings = True, can_write_posts = True)
connection.session.add(user)
connection.session.commit()
connection.close()
## Instruction:
Create index on session_id in order to speed tests
## Code After:
import bcrypt
import sys
import os
sys.path.insert(0, "..")
from timpani import database
connection = database.DatabaseConnection()
hashedpassword = bcrypt.hashpw(bytes("password", "utf-8"), bcrypt.gensalt()).decode("utf-8")
user = database.tables.User(username = "tests", password = hashedpassword, full_name = "Timpani Tests", can_change_settings = True, can_write_posts = True)
connection.session.add(user)
connection.session.execute("CREATE INDEX ON sessions(session_id)")
connection.session.commit()
connection.close()
| import bcrypt
import sys
import os
sys.path.insert(0, "..")
from timpani import database
connection = database.DatabaseConnection()
hashedpassword = bcrypt.hashpw(bytes("password", "utf-8"), bcrypt.gensalt()).decode("utf-8")
user = database.tables.User(username = "tests", password = hashedpassword, full_name = "Timpani Tests", can_change_settings = True, can_write_posts = True)
connection.session.add(user)
+ connection.session.execute("CREATE INDEX ON sessions(session_id)")
connection.session.commit()
connection.close() |
f6313e28bbf00d65d6a4635b5377f9ad06548de6 | appengine_config.py | appengine_config.py |
# Enable appstats and optionally cost calculation.
# Change these values and upload again if you want to enable appstats.
enable_appstats = False
appstats_CALC_RPC_COSTS = False
def webapp_add_wsgi_middleware(app):
"""Overrides the wsgi application with appstats if enabled.
https://developers.google.com/appengine/docs/python/tools/appstats
"""
if enable_appstats:
# pylint: disable=E0611,F0401
from google.appengine.ext.appstats import recording
return recording.appstats_wsgi_middleware(app)
return app
|
# The app engine headers are located locally, so don't worry about not finding
# them.
# pylint: disable=E0611,F0401
from google.appengine.api import app_identity
# pylint: enable=E0611,F0401
# Enable appstats and optionally cost calculation on a dev instance.
enable_appstats = app_identity.get_application_id().endswith('-dev')
appstats_CALC_RPC_COSTS = False
def webapp_add_wsgi_middleware(app):
"""Overrides the wsgi application with appstats if enabled.
https://developers.google.com/appengine/docs/python/tools/appstats
"""
if enable_appstats:
# pylint: disable=E0611,F0401
from google.appengine.ext.appstats import recording
return recording.appstats_wsgi_middleware(app)
return app
| Enable app stats on '-dev' instance. | Enable app stats on '-dev' instance.
This will also enable them on local dev server as well since default app name
in app.yaml is 'isolateserver-dev'.
R=maruel@chromium.org
Review URL: https://codereview.appspot.com/13457054
| Python | apache-2.0 | luci/luci-py,luci/luci-py,madecoste/swarming,luci/luci-py,pombreda/swarming,madecoste/swarming,madecoste/swarming,pombreda/swarming,pombreda/swarming,luci/luci-py,pombreda/swarming,madecoste/swarming |
+ # The app engine headers are located locally, so don't worry about not finding
+ # them.
+ # pylint: disable=E0611,F0401
+ from google.appengine.api import app_identity
+ # pylint: enable=E0611,F0401
+
+
- # Enable appstats and optionally cost calculation.
+ # Enable appstats and optionally cost calculation on a dev instance.
+ enable_appstats = app_identity.get_application_id().endswith('-dev')
- # Change these values and upload again if you want to enable appstats.
- enable_appstats = False
appstats_CALC_RPC_COSTS = False
def webapp_add_wsgi_middleware(app):
"""Overrides the wsgi application with appstats if enabled.
https://developers.google.com/appengine/docs/python/tools/appstats
"""
if enable_appstats:
# pylint: disable=E0611,F0401
from google.appengine.ext.appstats import recording
return recording.appstats_wsgi_middleware(app)
return app
| Enable app stats on '-dev' instance. | ## Code Before:
# Enable appstats and optionally cost calculation.
# Change these values and upload again if you want to enable appstats.
enable_appstats = False
appstats_CALC_RPC_COSTS = False
def webapp_add_wsgi_middleware(app):
"""Overrides the wsgi application with appstats if enabled.
https://developers.google.com/appengine/docs/python/tools/appstats
"""
if enable_appstats:
# pylint: disable=E0611,F0401
from google.appengine.ext.appstats import recording
return recording.appstats_wsgi_middleware(app)
return app
## Instruction:
Enable app stats on '-dev' instance.
## Code After:
# The app engine headers are located locally, so don't worry about not finding
# them.
# pylint: disable=E0611,F0401
from google.appengine.api import app_identity
# pylint: enable=E0611,F0401
# Enable appstats and optionally cost calculation on a dev instance.
enable_appstats = app_identity.get_application_id().endswith('-dev')
appstats_CALC_RPC_COSTS = False
def webapp_add_wsgi_middleware(app):
"""Overrides the wsgi application with appstats if enabled.
https://developers.google.com/appengine/docs/python/tools/appstats
"""
if enable_appstats:
# pylint: disable=E0611,F0401
from google.appengine.ext.appstats import recording
return recording.appstats_wsgi_middleware(app)
return app
|
+ # The app engine headers are located locally, so don't worry about not finding
+ # them.
+ # pylint: disable=E0611,F0401
+ from google.appengine.api import app_identity
+ # pylint: enable=E0611,F0401
+
+
- # Enable appstats and optionally cost calculation.
+ # Enable appstats and optionally cost calculation on a dev instance.
? ++++++++++++++++++
+ enable_appstats = app_identity.get_application_id().endswith('-dev')
- # Change these values and upload again if you want to enable appstats.
- enable_appstats = False
appstats_CALC_RPC_COSTS = False
def webapp_add_wsgi_middleware(app):
"""Overrides the wsgi application with appstats if enabled.
https://developers.google.com/appengine/docs/python/tools/appstats
"""
if enable_appstats:
# pylint: disable=E0611,F0401
from google.appengine.ext.appstats import recording
return recording.appstats_wsgi_middleware(app)
return app |
e6210d4d3fcdff4c9b4b22946e03062e01efd830 | pika/adapters/__init__.py | pika/adapters/__init__.py | from asyncore_connection import AsyncoreConnection
from blocking_connection import BlockingConnection
from tornado_connection import TornadoConnection
|
from base_connection import BaseConnection
from asyncore_connection import AsyncoreConnection
from blocking_connection import BlockingConnection
from tornado_connection import TornadoConnection
| Add the license block and BaseConnection | Add the license block and BaseConnection
| Python | bsd-3-clause | skftn/pika,shinji-s/pika,Zephor5/pika,zixiliuyue/pika,reddec/pika,pika/pika,renshawbay/pika-python3,vrtsystems/pika,knowsis/pika,fkarb/pika-python3,jstnlef/pika,Tarsbot/pika,vitaly-krugl/pika,hugoxia/pika,benjamin9999/pika | +
+
+ from base_connection import BaseConnection
from asyncore_connection import AsyncoreConnection
from blocking_connection import BlockingConnection
from tornado_connection import TornadoConnection
| Add the license block and BaseConnection | ## Code Before:
from asyncore_connection import AsyncoreConnection
from blocking_connection import BlockingConnection
from tornado_connection import TornadoConnection
## Instruction:
Add the license block and BaseConnection
## Code After:
from base_connection import BaseConnection
from asyncore_connection import AsyncoreConnection
from blocking_connection import BlockingConnection
from tornado_connection import TornadoConnection
| +
+
+ from base_connection import BaseConnection
from asyncore_connection import AsyncoreConnection
from blocking_connection import BlockingConnection
from tornado_connection import TornadoConnection |
b7db1d067c8efe86a6ab39a15fef0ab878656249 | uber/__init__.py | uber/__init__.py | import os
from decimal import Decimal
from pockets.autolog import log
from uber._version import __version__ # noqa: F401
def on_load():
"""
Called by sideboard when the uber plugin is loaded.
"""
# Note: The following imports have side effects
from uber import config # noqa: F401
from uber import api # noqa: F401
from uber import automated_emails # noqa: F401
from uber import custom_tags # noqa: F401
from uber import jinja # noqa: F401
from uber import menu # noqa: F401
from uber import models # noqa: F401
from uber import model_checks # noqa: F401
from uber import sep_commands # noqa: F401
from uber import server # noqa: F401
from uber import tasks # noqa: F401
# sideboard must be imported AFTER the on_load() function is declared,
# otherwise on_load() won't exist yet when sideboard looks for it.
import sideboard # noqa: E402
# NOTE: this will decrease the precision of some serialized decimal.Decimals
sideboard.lib.serializer.register(Decimal, lambda n: float(n))
| import os
from decimal import Decimal
from pockets.autolog import log
from uber._version import __version__ # noqa: F401
def on_load():
"""
Called by sideboard when the uber plugin is loaded.
"""
# Note: The following imports have side effects
from uber import config # noqa: F401
from uber import api # noqa: F401
from uber import automated_emails # noqa: F401
from uber import custom_tags # noqa: F401
from uber import jinja # noqa: F401
from uber import menu # noqa: F401
from uber import models # noqa: F401
from uber import model_checks # noqa: F401
from uber import sep_commands # noqa: F401
from uber import server # noqa: F401
from uber import tasks # noqa: F401
# sideboard must be imported AFTER the on_load() function is declared,
# otherwise on_load() won't exist yet when sideboard looks for it.
import sideboard # noqa: E402
# NOTE: this will decrease the precision of some serialized decimal.Decimals
sideboard.lib.serializer.register(Decimal, lambda n: float(n))
@sideboard.lib.on_startup
def create_data_dirs():
from uber.config import c
for directory in c.DATA_DIRS.values():
if not os.path.exists(directory):
log.info('Creating directory {}'.format(directory))
os.makedirs(directory, mode=0o744)
| Revert "Don't make dirs on startup" | Revert "Don't make dirs on startup"
This reverts commit 17243b31fc6c8d8f4bb0dc7e11e2601800e80bb0.
| Python | agpl-3.0 | magfest/ubersystem,magfest/ubersystem,magfest/ubersystem,magfest/ubersystem | import os
from decimal import Decimal
from pockets.autolog import log
from uber._version import __version__ # noqa: F401
def on_load():
"""
Called by sideboard when the uber plugin is loaded.
"""
# Note: The following imports have side effects
from uber import config # noqa: F401
from uber import api # noqa: F401
from uber import automated_emails # noqa: F401
from uber import custom_tags # noqa: F401
from uber import jinja # noqa: F401
from uber import menu # noqa: F401
from uber import models # noqa: F401
from uber import model_checks # noqa: F401
from uber import sep_commands # noqa: F401
from uber import server # noqa: F401
from uber import tasks # noqa: F401
# sideboard must be imported AFTER the on_load() function is declared,
# otherwise on_load() won't exist yet when sideboard looks for it.
import sideboard # noqa: E402
# NOTE: this will decrease the precision of some serialized decimal.Decimals
sideboard.lib.serializer.register(Decimal, lambda n: float(n))
+ @sideboard.lib.on_startup
+ def create_data_dirs():
+ from uber.config import c
+
+ for directory in c.DATA_DIRS.values():
+ if not os.path.exists(directory):
+ log.info('Creating directory {}'.format(directory))
+ os.makedirs(directory, mode=0o744)
+ | Revert "Don't make dirs on startup" | ## Code Before:
import os
from decimal import Decimal
from pockets.autolog import log
from uber._version import __version__ # noqa: F401
def on_load():
"""
Called by sideboard when the uber plugin is loaded.
"""
# Note: The following imports have side effects
from uber import config # noqa: F401
from uber import api # noqa: F401
from uber import automated_emails # noqa: F401
from uber import custom_tags # noqa: F401
from uber import jinja # noqa: F401
from uber import menu # noqa: F401
from uber import models # noqa: F401
from uber import model_checks # noqa: F401
from uber import sep_commands # noqa: F401
from uber import server # noqa: F401
from uber import tasks # noqa: F401
# sideboard must be imported AFTER the on_load() function is declared,
# otherwise on_load() won't exist yet when sideboard looks for it.
import sideboard # noqa: E402
# NOTE: this will decrease the precision of some serialized decimal.Decimals
sideboard.lib.serializer.register(Decimal, lambda n: float(n))
## Instruction:
Revert "Don't make dirs on startup"
## Code After:
import os
from decimal import Decimal
from pockets.autolog import log
from uber._version import __version__ # noqa: F401
def on_load():
"""
Called by sideboard when the uber plugin is loaded.
"""
# Note: The following imports have side effects
from uber import config # noqa: F401
from uber import api # noqa: F401
from uber import automated_emails # noqa: F401
from uber import custom_tags # noqa: F401
from uber import jinja # noqa: F401
from uber import menu # noqa: F401
from uber import models # noqa: F401
from uber import model_checks # noqa: F401
from uber import sep_commands # noqa: F401
from uber import server # noqa: F401
from uber import tasks # noqa: F401
# sideboard must be imported AFTER the on_load() function is declared,
# otherwise on_load() won't exist yet when sideboard looks for it.
import sideboard # noqa: E402
# NOTE: this will decrease the precision of some serialized decimal.Decimals
sideboard.lib.serializer.register(Decimal, lambda n: float(n))
@sideboard.lib.on_startup
def create_data_dirs():
from uber.config import c
for directory in c.DATA_DIRS.values():
if not os.path.exists(directory):
log.info('Creating directory {}'.format(directory))
os.makedirs(directory, mode=0o744)
| import os
from decimal import Decimal
from pockets.autolog import log
from uber._version import __version__ # noqa: F401
def on_load():
"""
Called by sideboard when the uber plugin is loaded.
"""
# Note: The following imports have side effects
from uber import config # noqa: F401
from uber import api # noqa: F401
from uber import automated_emails # noqa: F401
from uber import custom_tags # noqa: F401
from uber import jinja # noqa: F401
from uber import menu # noqa: F401
from uber import models # noqa: F401
from uber import model_checks # noqa: F401
from uber import sep_commands # noqa: F401
from uber import server # noqa: F401
from uber import tasks # noqa: F401
# sideboard must be imported AFTER the on_load() function is declared,
# otherwise on_load() won't exist yet when sideboard looks for it.
import sideboard # noqa: E402
# NOTE: this will decrease the precision of some serialized decimal.Decimals
sideboard.lib.serializer.register(Decimal, lambda n: float(n))
+
+ @sideboard.lib.on_startup
+ def create_data_dirs():
+ from uber.config import c
+
+ for directory in c.DATA_DIRS.values():
+ if not os.path.exists(directory):
+ log.info('Creating directory {}'.format(directory))
+ os.makedirs(directory, mode=0o744) |
1c3ff4552b82183263ead0aefe47b867a7b2022e | 10_anaconda/jupyter_notebook_config.py | 10_anaconda/jupyter_notebook_config.py |
from jupyter_core.paths import jupyter_data_dir
import subprocess
import os
import errno
import stat
c = get_config()
c.NotebookApp.ip = '*'
c.NotebookApp.port = 8888
c.NotebookApp.open_browser = False
# Generate a self-signed certificate
if 'GEN_CERT' in os.environ:
dir_name = jupyter_data_dir()
pem_file = os.path.join(dir_name, 'notebook.pem')
try:
os.makedirs(dir_name)
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST and os.path.isdir(dir_name):
pass
else:
raise
# Generate a certificate if one doesn't exist on disk
subprocess.check_call(['openssl', 'req', '-new',
'-newkey', 'rsa:2048',
'-days', '365',
'-nodes', '-x509',
'-subj', '/C=XX/ST=XX/L=XX/O=generated/CN=generated',
'-keyout', pem_file,
'-out', pem_file])
# Restrict access to the file
os.chmod(pem_file, stat.S_IRUSR | stat.S_IWUSR)
c.NotebookApp.certfile = pem_file
|
from jupyter_core.paths import jupyter_data_dir
import subprocess
import os
import os.path
import errno
import stat
c = get_config()
c.NotebookApp.ip = '*'
c.NotebookApp.port = 8888
c.NotebookApp.open_browser = False
# Generate a self-signed certificate
if 'GEN_CERT' in os.environ:
dir_name = jupyter_data_dir()
pem_file = os.path.join(dir_name, 'notebook.pem')
if not os.path.isfile(pem_file):
try:
os.makedirs(dir_name)
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST and os.path.isdir(dir_name):
pass
else:
raise
# Generate a certificate if one doesn't exist on disk
subprocess.check_call(['openssl', 'req', '-new',
'-newkey', 'rsa:2048',
'-days', '365',
'-nodes', '-x509',
'-subj', '/C=XX/ST=XX/L=XX/O=generated/CN=generated',
'-keyout', pem_file,
'-out', pem_file])
# Restrict access to the file
os.chmod(pem_file, stat.S_IRUSR | stat.S_IWUSR)
c.NotebookApp.certfile = pem_file
| Fix certificate regenerating each startup | Fix certificate regenerating each startup
| Python | apache-2.0 | LamDang/docker-datascience,LamDang/docker-datascience |
from jupyter_core.paths import jupyter_data_dir
import subprocess
import os
+ import os.path
import errno
import stat
c = get_config()
c.NotebookApp.ip = '*'
c.NotebookApp.port = 8888
c.NotebookApp.open_browser = False
# Generate a self-signed certificate
if 'GEN_CERT' in os.environ:
dir_name = jupyter_data_dir()
pem_file = os.path.join(dir_name, 'notebook.pem')
+ if not os.path.isfile(pem_file):
- try:
+ try:
- os.makedirs(dir_name)
+ os.makedirs(dir_name)
- except OSError as exc: # Python >2.5
+ except OSError as exc: # Python >2.5
- if exc.errno == errno.EEXIST and os.path.isdir(dir_name):
+ if exc.errno == errno.EEXIST and os.path.isdir(dir_name):
- pass
+ pass
- else:
+ else:
- raise
+ raise
- # Generate a certificate if one doesn't exist on disk
+ # Generate a certificate if one doesn't exist on disk
- subprocess.check_call(['openssl', 'req', '-new',
+ subprocess.check_call(['openssl', 'req', '-new',
- '-newkey', 'rsa:2048',
+ '-newkey', 'rsa:2048',
- '-days', '365',
+ '-days', '365',
- '-nodes', '-x509',
+ '-nodes', '-x509',
- '-subj', '/C=XX/ST=XX/L=XX/O=generated/CN=generated',
+ '-subj', '/C=XX/ST=XX/L=XX/O=generated/CN=generated',
- '-keyout', pem_file,
+ '-keyout', pem_file,
- '-out', pem_file])
+ '-out', pem_file])
- # Restrict access to the file
+ # Restrict access to the file
- os.chmod(pem_file, stat.S_IRUSR | stat.S_IWUSR)
+ os.chmod(pem_file, stat.S_IRUSR | stat.S_IWUSR)
c.NotebookApp.certfile = pem_file
| Fix certificate regenerating each startup | ## Code Before:
from jupyter_core.paths import jupyter_data_dir
import subprocess
import os
import errno
import stat
c = get_config()
c.NotebookApp.ip = '*'
c.NotebookApp.port = 8888
c.NotebookApp.open_browser = False
# Generate a self-signed certificate
if 'GEN_CERT' in os.environ:
dir_name = jupyter_data_dir()
pem_file = os.path.join(dir_name, 'notebook.pem')
try:
os.makedirs(dir_name)
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST and os.path.isdir(dir_name):
pass
else:
raise
# Generate a certificate if one doesn't exist on disk
subprocess.check_call(['openssl', 'req', '-new',
'-newkey', 'rsa:2048',
'-days', '365',
'-nodes', '-x509',
'-subj', '/C=XX/ST=XX/L=XX/O=generated/CN=generated',
'-keyout', pem_file,
'-out', pem_file])
# Restrict access to the file
os.chmod(pem_file, stat.S_IRUSR | stat.S_IWUSR)
c.NotebookApp.certfile = pem_file
## Instruction:
Fix certificate regenerating each startup
## Code After:
from jupyter_core.paths import jupyter_data_dir
import subprocess
import os
import os.path
import errno
import stat
c = get_config()
c.NotebookApp.ip = '*'
c.NotebookApp.port = 8888
c.NotebookApp.open_browser = False
# Generate a self-signed certificate
if 'GEN_CERT' in os.environ:
dir_name = jupyter_data_dir()
pem_file = os.path.join(dir_name, 'notebook.pem')
if not os.path.isfile(pem_file):
try:
os.makedirs(dir_name)
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST and os.path.isdir(dir_name):
pass
else:
raise
# Generate a certificate if one doesn't exist on disk
subprocess.check_call(['openssl', 'req', '-new',
'-newkey', 'rsa:2048',
'-days', '365',
'-nodes', '-x509',
'-subj', '/C=XX/ST=XX/L=XX/O=generated/CN=generated',
'-keyout', pem_file,
'-out', pem_file])
# Restrict access to the file
os.chmod(pem_file, stat.S_IRUSR | stat.S_IWUSR)
c.NotebookApp.certfile = pem_file
|
from jupyter_core.paths import jupyter_data_dir
import subprocess
import os
+ import os.path
import errno
import stat
c = get_config()
c.NotebookApp.ip = '*'
c.NotebookApp.port = 8888
c.NotebookApp.open_browser = False
# Generate a self-signed certificate
if 'GEN_CERT' in os.environ:
dir_name = jupyter_data_dir()
pem_file = os.path.join(dir_name, 'notebook.pem')
+ if not os.path.isfile(pem_file):
- try:
+ try:
? ++++
- os.makedirs(dir_name)
+ os.makedirs(dir_name)
? ++++
- except OSError as exc: # Python >2.5
+ except OSError as exc: # Python >2.5
? ++++
- if exc.errno == errno.EEXIST and os.path.isdir(dir_name):
+ if exc.errno == errno.EEXIST and os.path.isdir(dir_name):
? ++++
- pass
+ pass
? ++++
- else:
+ else:
? ++++
- raise
+ raise
? ++++
- # Generate a certificate if one doesn't exist on disk
+ # Generate a certificate if one doesn't exist on disk
? ++++
- subprocess.check_call(['openssl', 'req', '-new',
+ subprocess.check_call(['openssl', 'req', '-new',
? ++++
- '-newkey', 'rsa:2048',
+ '-newkey', 'rsa:2048',
? ++++
- '-days', '365',
+ '-days', '365',
? ++++
- '-nodes', '-x509',
+ '-nodes', '-x509',
? ++++
- '-subj', '/C=XX/ST=XX/L=XX/O=generated/CN=generated',
+ '-subj', '/C=XX/ST=XX/L=XX/O=generated/CN=generated',
? ++++
- '-keyout', pem_file,
+ '-keyout', pem_file,
? ++++
- '-out', pem_file])
+ '-out', pem_file])
? ++++
- # Restrict access to the file
+ # Restrict access to the file
? ++++
- os.chmod(pem_file, stat.S_IRUSR | stat.S_IWUSR)
+ os.chmod(pem_file, stat.S_IRUSR | stat.S_IWUSR)
? ++++
c.NotebookApp.certfile = pem_file |
3692d64332768a6a8bd85ac5dbfecaba5c364d4a | tests/util/test_platform.py | tests/util/test_platform.py | import platform
from keyring.util.platform_ import (
config_root,
data_root,
_config_root_Linux,
_config_root_Windows,
_data_root_Linux,
_data_root_Windows,
)
def test_platform_Linux():
# rely on the Github Actions workflow to run this on different platforms
if platform.system() != "Linux":
return
assert config_root == _config_root_Linux
assert data_root == _data_root_Linux
def test_platform_Windows():
# rely on the Github Actions workflow to run this on different platforms
if platform.system() != "Windows":
return
assert config_root == _config_root_Windows
assert data_root == _data_root_Windows
| import pytest
import platform
from keyring.util.platform_ import (
config_root,
data_root,
_config_root_Linux,
_config_root_Windows,
_data_root_Linux,
_data_root_Windows,
)
@pytest.mark.skipif(
platform.system() != "Linux", reason="Requires platform.system() == 'Linux'"
)
def test_platform_Linux():
# rely on the Github Actions workflow to run this on different platforms
assert config_root == _config_root_Linux
assert data_root == _data_root_Linux
@pytest.mark.skipif(
platform.system() != "Windows", reason="Requires platform.system() == 'Windows'"
)
def test_platform_Windows():
# rely on the Github Actions workflow to run this on different platforms
assert config_root == _config_root_Windows
assert data_root == _data_root_Windows
| Use Pytest's skipif decorator instead of returning to skip assert statements. | Use Pytest's skipif decorator instead of returning to skip assert statements.
| Python | mit | jaraco/keyring | + import pytest
import platform
from keyring.util.platform_ import (
config_root,
data_root,
_config_root_Linux,
_config_root_Windows,
_data_root_Linux,
_data_root_Windows,
)
+ @pytest.mark.skipif(
+ platform.system() != "Linux", reason="Requires platform.system() == 'Linux'"
+ )
def test_platform_Linux():
# rely on the Github Actions workflow to run this on different platforms
- if platform.system() != "Linux":
- return
assert config_root == _config_root_Linux
assert data_root == _data_root_Linux
+ @pytest.mark.skipif(
+ platform.system() != "Windows", reason="Requires platform.system() == 'Windows'"
+ )
def test_platform_Windows():
# rely on the Github Actions workflow to run this on different platforms
- if platform.system() != "Windows":
- return
assert config_root == _config_root_Windows
assert data_root == _data_root_Windows
| Use Pytest's skipif decorator instead of returning to skip assert statements. | ## Code Before:
import platform
from keyring.util.platform_ import (
config_root,
data_root,
_config_root_Linux,
_config_root_Windows,
_data_root_Linux,
_data_root_Windows,
)
def test_platform_Linux():
# rely on the Github Actions workflow to run this on different platforms
if platform.system() != "Linux":
return
assert config_root == _config_root_Linux
assert data_root == _data_root_Linux
def test_platform_Windows():
# rely on the Github Actions workflow to run this on different platforms
if platform.system() != "Windows":
return
assert config_root == _config_root_Windows
assert data_root == _data_root_Windows
## Instruction:
Use Pytest's skipif decorator instead of returning to skip assert statements.
## Code After:
import pytest
import platform
from keyring.util.platform_ import (
config_root,
data_root,
_config_root_Linux,
_config_root_Windows,
_data_root_Linux,
_data_root_Windows,
)
@pytest.mark.skipif(
platform.system() != "Linux", reason="Requires platform.system() == 'Linux'"
)
def test_platform_Linux():
# rely on the Github Actions workflow to run this on different platforms
assert config_root == _config_root_Linux
assert data_root == _data_root_Linux
@pytest.mark.skipif(
platform.system() != "Windows", reason="Requires platform.system() == 'Windows'"
)
def test_platform_Windows():
# rely on the Github Actions workflow to run this on different platforms
assert config_root == _config_root_Windows
assert data_root == _data_root_Windows
| + import pytest
import platform
from keyring.util.platform_ import (
config_root,
data_root,
_config_root_Linux,
_config_root_Windows,
_data_root_Linux,
_data_root_Windows,
)
+ @pytest.mark.skipif(
+ platform.system() != "Linux", reason="Requires platform.system() == 'Linux'"
+ )
def test_platform_Linux():
# rely on the Github Actions workflow to run this on different platforms
- if platform.system() != "Linux":
- return
assert config_root == _config_root_Linux
assert data_root == _data_root_Linux
+ @pytest.mark.skipif(
+ platform.system() != "Windows", reason="Requires platform.system() == 'Windows'"
+ )
def test_platform_Windows():
# rely on the Github Actions workflow to run this on different platforms
- if platform.system() != "Windows":
- return
assert config_root == _config_root_Windows
assert data_root == _data_root_Windows |
a7e1b1961d14306f16c97e66982f4aef5b203e0a | tests/test_acf.py | tests/test_acf.py | import io
import pytest
from steamfiles import acf
test_file_name = 'tests/test_data/appmanifest_202970.acf'
@pytest.yield_fixture
def acf_data():
with open(test_file_name, 'rt') as f:
yield f.read()
@pytest.mark.usefixtures('acf_data')
def test_loads_dumps(acf_data):
assert acf.dumps(acf.loads(acf_data)) == acf_data
@pytest.mark.usefixtures('acf_data')
def test_load_dump(acf_data):
with open(test_file_name, 'rt') as in_file:
out_file = io.StringIO()
obj = acf.load(in_file)
acf.dump(out_file, obj)
# Rewind to the beginning
out_file.seek(0)
assert out_file.read() == acf_data
| import io
import os
import pytest
from steamfiles import acf
test_file_name = os.path.join(os.path.dirname(__file__), 'test_data/appmanifest_202970.acf')
@pytest.yield_fixture
def acf_data():
with open(test_file_name, 'rt') as f:
yield f.read()
@pytest.mark.usefixtures('acf_data')
def test_loads_dumps(acf_data):
assert acf.dumps(acf.loads(acf_data)) == acf_data
@pytest.mark.usefixtures('acf_data')
def test_load_dump(acf_data):
with open(test_file_name, 'rt') as in_file:
out_file = io.StringIO()
obj = acf.load(in_file)
acf.dump(out_file, obj)
# Rewind to the beginning
out_file.seek(0)
assert out_file.read() == acf_data
| Fix relative path not working properly 50% of the time… | Fix relative path not working properly 50% of the time…
| Python | mit | leovp/steamfiles | import io
+ import os
import pytest
from steamfiles import acf
+ test_file_name = os.path.join(os.path.dirname(__file__), 'test_data/appmanifest_202970.acf')
- test_file_name = 'tests/test_data/appmanifest_202970.acf'
-
@pytest.yield_fixture
def acf_data():
with open(test_file_name, 'rt') as f:
yield f.read()
@pytest.mark.usefixtures('acf_data')
def test_loads_dumps(acf_data):
assert acf.dumps(acf.loads(acf_data)) == acf_data
@pytest.mark.usefixtures('acf_data')
def test_load_dump(acf_data):
with open(test_file_name, 'rt') as in_file:
out_file = io.StringIO()
obj = acf.load(in_file)
acf.dump(out_file, obj)
# Rewind to the beginning
out_file.seek(0)
assert out_file.read() == acf_data
| Fix relative path not working properly 50% of the time… | ## Code Before:
import io
import pytest
from steamfiles import acf
test_file_name = 'tests/test_data/appmanifest_202970.acf'
@pytest.yield_fixture
def acf_data():
with open(test_file_name, 'rt') as f:
yield f.read()
@pytest.mark.usefixtures('acf_data')
def test_loads_dumps(acf_data):
assert acf.dumps(acf.loads(acf_data)) == acf_data
@pytest.mark.usefixtures('acf_data')
def test_load_dump(acf_data):
with open(test_file_name, 'rt') as in_file:
out_file = io.StringIO()
obj = acf.load(in_file)
acf.dump(out_file, obj)
# Rewind to the beginning
out_file.seek(0)
assert out_file.read() == acf_data
## Instruction:
Fix relative path not working properly 50% of the time…
## Code After:
import io
import os
import pytest
from steamfiles import acf
test_file_name = os.path.join(os.path.dirname(__file__), 'test_data/appmanifest_202970.acf')
@pytest.yield_fixture
def acf_data():
with open(test_file_name, 'rt') as f:
yield f.read()
@pytest.mark.usefixtures('acf_data')
def test_loads_dumps(acf_data):
assert acf.dumps(acf.loads(acf_data)) == acf_data
@pytest.mark.usefixtures('acf_data')
def test_load_dump(acf_data):
with open(test_file_name, 'rt') as in_file:
out_file = io.StringIO()
obj = acf.load(in_file)
acf.dump(out_file, obj)
# Rewind to the beginning
out_file.seek(0)
assert out_file.read() == acf_data
| import io
+ import os
import pytest
from steamfiles import acf
+ test_file_name = os.path.join(os.path.dirname(__file__), 'test_data/appmanifest_202970.acf')
- test_file_name = 'tests/test_data/appmanifest_202970.acf'
-
@pytest.yield_fixture
def acf_data():
with open(test_file_name, 'rt') as f:
yield f.read()
@pytest.mark.usefixtures('acf_data')
def test_loads_dumps(acf_data):
assert acf.dumps(acf.loads(acf_data)) == acf_data
@pytest.mark.usefixtures('acf_data')
def test_load_dump(acf_data):
with open(test_file_name, 'rt') as in_file:
out_file = io.StringIO()
obj = acf.load(in_file)
acf.dump(out_file, obj)
# Rewind to the beginning
out_file.seek(0)
assert out_file.read() == acf_data |
920bc2620533cb4c91d7b7dd186ba59fd09edbf9 | datadog/api/screenboards.py | datadog/api/screenboards.py | from datadog.api.base import GetableAPIResource, CreateableAPIResource, \
UpdatableAPIResource, DeletableAPIResource, ActionAPIResource, ListableAPIResource
class Screenboard(GetableAPIResource, CreateableAPIResource,
UpdatableAPIResource, DeletableAPIResource,
ActionAPIResource, ListableAPIResource):
"""
A wrapper around Screenboard HTTP API.
"""
_class_name = 'screen'
_class_url = '/screen'
_json_name = 'board'
@classmethod
def share(cls, board_id):
"""
Share the screenboard with given id
:param board_id: screenboard to share
:type board_id: id
:returns: JSON response from HTTP request
"""
return super(Screenboard, cls)._trigger_action('GET', 'screen/share', board_id)
| from datadog.api.base import GetableAPIResource, CreateableAPIResource, \
UpdatableAPIResource, DeletableAPIResource, ActionAPIResource, ListableAPIResource
class Screenboard(GetableAPIResource, CreateableAPIResource,
UpdatableAPIResource, DeletableAPIResource,
ActionAPIResource, ListableAPIResource):
"""
A wrapper around Screenboard HTTP API.
"""
_class_name = 'screen'
_class_url = '/screen'
_json_name = 'board'
@classmethod
def share(cls, board_id):
"""
Share the screenboard with given id
:param board_id: screenboard to share
:type board_id: id
:returns: JSON response from HTTP request
"""
return super(Screenboard, cls)._trigger_action('GET', 'screen/share', board_id)
@classmethod
def revoke(cls, board_id):
"""
Revoke a shared screenboard with given id
:param board_id: screenboard to revoke
:type board_id: id
:returns: JSON response from HTTP request
"""
return super(Screenboard, cls)._trigger_action('DELETE', 'screen/share', board_id)
| Add `revoke` method to Screenboard | Add `revoke` method to Screenboard
- This method allow to revoke the public access of a shared
screenboard
| Python | bsd-3-clause | percipient/datadogpy,clokep/datadogpy,KyleJamesWalker/datadogpy,jofusa/datadogpy,rogst/datadogpy,rogst/datadogpy,percipient/datadogpy,jofusa/datadogpy,clokep/datadogpy,KyleJamesWalker/datadogpy | from datadog.api.base import GetableAPIResource, CreateableAPIResource, \
UpdatableAPIResource, DeletableAPIResource, ActionAPIResource, ListableAPIResource
class Screenboard(GetableAPIResource, CreateableAPIResource,
UpdatableAPIResource, DeletableAPIResource,
ActionAPIResource, ListableAPIResource):
"""
A wrapper around Screenboard HTTP API.
"""
_class_name = 'screen'
_class_url = '/screen'
_json_name = 'board'
@classmethod
def share(cls, board_id):
"""
Share the screenboard with given id
:param board_id: screenboard to share
:type board_id: id
:returns: JSON response from HTTP request
"""
return super(Screenboard, cls)._trigger_action('GET', 'screen/share', board_id)
+ @classmethod
+ def revoke(cls, board_id):
+ """
+ Revoke a shared screenboard with given id
+
+ :param board_id: screenboard to revoke
+ :type board_id: id
+
+ :returns: JSON response from HTTP request
+ """
+ return super(Screenboard, cls)._trigger_action('DELETE', 'screen/share', board_id)
+ | Add `revoke` method to Screenboard | ## Code Before:
from datadog.api.base import GetableAPIResource, CreateableAPIResource, \
UpdatableAPIResource, DeletableAPIResource, ActionAPIResource, ListableAPIResource
class Screenboard(GetableAPIResource, CreateableAPIResource,
UpdatableAPIResource, DeletableAPIResource,
ActionAPIResource, ListableAPIResource):
"""
A wrapper around Screenboard HTTP API.
"""
_class_name = 'screen'
_class_url = '/screen'
_json_name = 'board'
@classmethod
def share(cls, board_id):
"""
Share the screenboard with given id
:param board_id: screenboard to share
:type board_id: id
:returns: JSON response from HTTP request
"""
return super(Screenboard, cls)._trigger_action('GET', 'screen/share', board_id)
## Instruction:
Add `revoke` method to Screenboard
## Code After:
from datadog.api.base import GetableAPIResource, CreateableAPIResource, \
UpdatableAPIResource, DeletableAPIResource, ActionAPIResource, ListableAPIResource
class Screenboard(GetableAPIResource, CreateableAPIResource,
UpdatableAPIResource, DeletableAPIResource,
ActionAPIResource, ListableAPIResource):
"""
A wrapper around Screenboard HTTP API.
"""
_class_name = 'screen'
_class_url = '/screen'
_json_name = 'board'
@classmethod
def share(cls, board_id):
"""
Share the screenboard with given id
:param board_id: screenboard to share
:type board_id: id
:returns: JSON response from HTTP request
"""
return super(Screenboard, cls)._trigger_action('GET', 'screen/share', board_id)
@classmethod
def revoke(cls, board_id):
"""
Revoke a shared screenboard with given id
:param board_id: screenboard to revoke
:type board_id: id
:returns: JSON response from HTTP request
"""
return super(Screenboard, cls)._trigger_action('DELETE', 'screen/share', board_id)
| from datadog.api.base import GetableAPIResource, CreateableAPIResource, \
UpdatableAPIResource, DeletableAPIResource, ActionAPIResource, ListableAPIResource
class Screenboard(GetableAPIResource, CreateableAPIResource,
UpdatableAPIResource, DeletableAPIResource,
ActionAPIResource, ListableAPIResource):
"""
A wrapper around Screenboard HTTP API.
"""
_class_name = 'screen'
_class_url = '/screen'
_json_name = 'board'
@classmethod
def share(cls, board_id):
"""
Share the screenboard with given id
:param board_id: screenboard to share
:type board_id: id
:returns: JSON response from HTTP request
"""
return super(Screenboard, cls)._trigger_action('GET', 'screen/share', board_id)
+
+ @classmethod
+ def revoke(cls, board_id):
+ """
+ Revoke a shared screenboard with given id
+
+ :param board_id: screenboard to revoke
+ :type board_id: id
+
+ :returns: JSON response from HTTP request
+ """
+ return super(Screenboard, cls)._trigger_action('DELETE', 'screen/share', board_id) |
16002b001a120410e4f993ad6fb93b123de183cb | astrodynamics/tests/test_util.py | astrodynamics/tests/test_util.py | from __future__ import absolute_import, division, print_function
import pytest
from astropy import units as u
from astrodynamics.util import verify_unit
def test_verify_unit():
# Implicit dimensionless values are allowed, test that Quantity is returned.
assert verify_unit(0, u.one) == 0 * u.one
# Test failure mode
with pytest.raises(ValueError):
verify_unit(0, u.meter)
# Quantity should be passed back if unit matches
assert verify_unit(1 * u.meter, u.meter) == 1 * u.meter
| from __future__ import absolute_import, division, print_function
import pytest
from astropy import units as u
from astrodynamics.util import verify_unit
def test_verify_unit():
# Implicit dimensionless values are allowed, test that Quantity is returned.
assert verify_unit(0, u.one) == 0 * u.one
assert verify_unit(0, '') == 0 * u.one
# Test failure mode
with pytest.raises(ValueError):
verify_unit(0, u.meter)
with pytest.raises(ValueError):
verify_unit(0, 'm')
# Quantity should be passed back if unit matches
assert verify_unit(1 * u.meter, u.meter) == 1 * u.meter
assert verify_unit(1 * u.meter, 'm') == 1 * u.meter
| Test string form of verify_unit | Test string form of verify_unit
| Python | mit | python-astrodynamics/astrodynamics,python-astrodynamics/astrodynamics | from __future__ import absolute_import, division, print_function
import pytest
from astropy import units as u
from astrodynamics.util import verify_unit
def test_verify_unit():
# Implicit dimensionless values are allowed, test that Quantity is returned.
assert verify_unit(0, u.one) == 0 * u.one
+ assert verify_unit(0, '') == 0 * u.one
# Test failure mode
with pytest.raises(ValueError):
verify_unit(0, u.meter)
+ with pytest.raises(ValueError):
+ verify_unit(0, 'm')
# Quantity should be passed back if unit matches
assert verify_unit(1 * u.meter, u.meter) == 1 * u.meter
+ assert verify_unit(1 * u.meter, 'm') == 1 * u.meter
| Test string form of verify_unit | ## Code Before:
from __future__ import absolute_import, division, print_function
import pytest
from astropy import units as u
from astrodynamics.util import verify_unit
def test_verify_unit():
# Implicit dimensionless values are allowed, test that Quantity is returned.
assert verify_unit(0, u.one) == 0 * u.one
# Test failure mode
with pytest.raises(ValueError):
verify_unit(0, u.meter)
# Quantity should be passed back if unit matches
assert verify_unit(1 * u.meter, u.meter) == 1 * u.meter
## Instruction:
Test string form of verify_unit
## Code After:
from __future__ import absolute_import, division, print_function
import pytest
from astropy import units as u
from astrodynamics.util import verify_unit
def test_verify_unit():
# Implicit dimensionless values are allowed, test that Quantity is returned.
assert verify_unit(0, u.one) == 0 * u.one
assert verify_unit(0, '') == 0 * u.one
# Test failure mode
with pytest.raises(ValueError):
verify_unit(0, u.meter)
with pytest.raises(ValueError):
verify_unit(0, 'm')
# Quantity should be passed back if unit matches
assert verify_unit(1 * u.meter, u.meter) == 1 * u.meter
assert verify_unit(1 * u.meter, 'm') == 1 * u.meter
| from __future__ import absolute_import, division, print_function
import pytest
from astropy import units as u
from astrodynamics.util import verify_unit
def test_verify_unit():
# Implicit dimensionless values are allowed, test that Quantity is returned.
assert verify_unit(0, u.one) == 0 * u.one
+ assert verify_unit(0, '') == 0 * u.one
# Test failure mode
with pytest.raises(ValueError):
verify_unit(0, u.meter)
+ with pytest.raises(ValueError):
+ verify_unit(0, 'm')
# Quantity should be passed back if unit matches
assert verify_unit(1 * u.meter, u.meter) == 1 * u.meter
+ assert verify_unit(1 * u.meter, 'm') == 1 * u.meter |
01ca6c2c71b8558e119ae4448e02c2c84a5ef6f9 | mailviews/tests/urls.py | mailviews/tests/urls.py | from mailviews.utils import is_django_version_greater
from django.conf.urls import include, url
from mailviews.previews import autodiscover, site
autodiscover()
urlpatterns = [
url(regex=r'', view=site.urls)
]
| from django.conf.urls import include, url
from mailviews.previews import autodiscover, site
autodiscover()
urlpatterns = [
url(regex=r'', view=site.urls)
]
| Remove unused import on test url's | Remove unused import on test url's
| Python | apache-2.0 | disqus/django-mailviews,disqus/django-mailviews | - from mailviews.utils import is_django_version_greater
-
from django.conf.urls import include, url
from mailviews.previews import autodiscover, site
autodiscover()
urlpatterns = [
url(regex=r'', view=site.urls)
]
| Remove unused import on test url's | ## Code Before:
from mailviews.utils import is_django_version_greater
from django.conf.urls import include, url
from mailviews.previews import autodiscover, site
autodiscover()
urlpatterns = [
url(regex=r'', view=site.urls)
]
## Instruction:
Remove unused import on test url's
## Code After:
from django.conf.urls import include, url
from mailviews.previews import autodiscover, site
autodiscover()
urlpatterns = [
url(regex=r'', view=site.urls)
]
| - from mailviews.utils import is_django_version_greater
-
from django.conf.urls import include, url
from mailviews.previews import autodiscover, site
autodiscover()
urlpatterns = [
url(regex=r'', view=site.urls)
] |
5b3d26b6c9256f869d3bc08dfa00bf9b8de58f85 | tests/test_cli_parse.py | tests/test_cli_parse.py |
import os
import pytest
import tempfile
from click.testing import CliRunner
import tbmodels
from tbmodels._cli import cli
from parameters import SAMPLES_DIR
@pytest.mark.parametrize('prefix', ['silicon', 'bi'])
def test_cli_parse(models_equal, prefix):
runner = CliRunner()
with tempfile.TemporaryDirectory() as d:
out_file = os.path.join(d, 'model_out.hdf5')
runner.invoke(cli, ['parse', '-o', out_file, '-f', SAMPLES_DIR, '-p', prefix])
model_res = tbmodels.Model.from_hdf5_file(out_file)
model_reference = tbmodels.Model.from_wannier_folder(folder=SAMPLES_DIR, prefix=prefix)
models_equal(model_res, model_reference)
|
import os
import pytest
import tempfile
from click.testing import CliRunner
import tbmodels
from tbmodels._cli import cli
from parameters import SAMPLES_DIR
@pytest.mark.parametrize('prefix', ['silicon', 'bi'])
def test_cli_parse(models_equal, prefix):
runner = CliRunner()
with tempfile.NamedTemporaryFile() as out_file:
runner.invoke(cli, ['parse', '-o', out_file.name, '-f', SAMPLES_DIR, '-p', prefix])
model_res = tbmodels.Model.from_hdf5_file(out_file.name)
model_reference = tbmodels.Model.from_wannier_folder(folder=SAMPLES_DIR, prefix=prefix)
models_equal(model_res, model_reference)
| Change from TemporaryDirectory to NamedTemporaryFile | Change from TemporaryDirectory to NamedTemporaryFile
| Python | apache-2.0 | Z2PackDev/TBmodels,Z2PackDev/TBmodels |
import os
import pytest
import tempfile
from click.testing import CliRunner
import tbmodels
from tbmodels._cli import cli
from parameters import SAMPLES_DIR
@pytest.mark.parametrize('prefix', ['silicon', 'bi'])
def test_cli_parse(models_equal, prefix):
runner = CliRunner()
- with tempfile.TemporaryDirectory() as d:
+ with tempfile.NamedTemporaryFile() as out_file:
- out_file = os.path.join(d, 'model_out.hdf5')
- runner.invoke(cli, ['parse', '-o', out_file, '-f', SAMPLES_DIR, '-p', prefix])
+ runner.invoke(cli, ['parse', '-o', out_file.name, '-f', SAMPLES_DIR, '-p', prefix])
- model_res = tbmodels.Model.from_hdf5_file(out_file)
+ model_res = tbmodels.Model.from_hdf5_file(out_file.name)
model_reference = tbmodels.Model.from_wannier_folder(folder=SAMPLES_DIR, prefix=prefix)
models_equal(model_res, model_reference)
| Change from TemporaryDirectory to NamedTemporaryFile | ## Code Before:
import os
import pytest
import tempfile
from click.testing import CliRunner
import tbmodels
from tbmodels._cli import cli
from parameters import SAMPLES_DIR
@pytest.mark.parametrize('prefix', ['silicon', 'bi'])
def test_cli_parse(models_equal, prefix):
runner = CliRunner()
with tempfile.TemporaryDirectory() as d:
out_file = os.path.join(d, 'model_out.hdf5')
runner.invoke(cli, ['parse', '-o', out_file, '-f', SAMPLES_DIR, '-p', prefix])
model_res = tbmodels.Model.from_hdf5_file(out_file)
model_reference = tbmodels.Model.from_wannier_folder(folder=SAMPLES_DIR, prefix=prefix)
models_equal(model_res, model_reference)
## Instruction:
Change from TemporaryDirectory to NamedTemporaryFile
## Code After:
import os
import pytest
import tempfile
from click.testing import CliRunner
import tbmodels
from tbmodels._cli import cli
from parameters import SAMPLES_DIR
@pytest.mark.parametrize('prefix', ['silicon', 'bi'])
def test_cli_parse(models_equal, prefix):
runner = CliRunner()
with tempfile.NamedTemporaryFile() as out_file:
runner.invoke(cli, ['parse', '-o', out_file.name, '-f', SAMPLES_DIR, '-p', prefix])
model_res = tbmodels.Model.from_hdf5_file(out_file.name)
model_reference = tbmodels.Model.from_wannier_folder(folder=SAMPLES_DIR, prefix=prefix)
models_equal(model_res, model_reference)
|
import os
import pytest
import tempfile
from click.testing import CliRunner
import tbmodels
from tbmodels._cli import cli
from parameters import SAMPLES_DIR
@pytest.mark.parametrize('prefix', ['silicon', 'bi'])
def test_cli_parse(models_equal, prefix):
runner = CliRunner()
- with tempfile.TemporaryDirectory() as d:
? ^ ^ ----- ^
+ with tempfile.NamedTemporaryFile() as out_file:
? +++++ ^ ^ ^^^^^^^^
- out_file = os.path.join(d, 'model_out.hdf5')
- runner.invoke(cli, ['parse', '-o', out_file, '-f', SAMPLES_DIR, '-p', prefix])
+ runner.invoke(cli, ['parse', '-o', out_file.name, '-f', SAMPLES_DIR, '-p', prefix])
? +++++
- model_res = tbmodels.Model.from_hdf5_file(out_file)
+ model_res = tbmodels.Model.from_hdf5_file(out_file.name)
? +++++
model_reference = tbmodels.Model.from_wannier_folder(folder=SAMPLES_DIR, prefix=prefix)
models_equal(model_res, model_reference) |
f56d8b35aa7d1d2c06d5c98ef49696e829459042 | log_request_id/tests.py | log_request_id/tests.py | import logging
from django.test import TestCase, RequestFactory
from log_request_id.middleware import RequestIDMiddleware
from testproject.views import test_view
class RequestIDLoggingTestCase(TestCase):
def setUp(self):
self.factory = RequestFactory()
self.handler = logging.getLogger('testproject').handlers[0]
def test_id_generation(self):
request = self.factory.get('/')
middleware = RequestIDMiddleware()
middleware.process_request(request)
self.assertTrue(hasattr(request, 'id'))
test_view(request)
self.assertTrue(request.id in self.handler.messages[0])
| import logging
from django.test import TestCase, RequestFactory
from log_request_id.middleware import RequestIDMiddleware
from testproject.views import test_view
class RequestIDLoggingTestCase(TestCase):
def setUp(self):
self.factory = RequestFactory()
self.handler = logging.getLogger('testproject').handlers[0]
self.handler.messages = []
def test_id_generation(self):
request = self.factory.get('/')
middleware = RequestIDMiddleware()
middleware.process_request(request)
self.assertTrue(hasattr(request, 'id'))
test_view(request)
self.assertTrue(request.id in self.handler.messages[0])
def test_external_id_in_http_header(self):
with self.settings(LOG_REQUEST_ID_HEADER='REQUEST_ID_HEADER'):
request = self.factory.get('/')
request.META['REQUEST_ID_HEADER'] = 'some_request_id'
middleware = RequestIDMiddleware()
middleware.process_request(request)
self.assertEqual(request.id, 'some_request_id')
test_view(request)
self.assertTrue('some_request_id' in self.handler.messages[0])
| Add test for externally-generated request IDs | Add test for externally-generated request IDs
| Python | bsd-2-clause | dabapps/django-log-request-id | import logging
from django.test import TestCase, RequestFactory
from log_request_id.middleware import RequestIDMiddleware
from testproject.views import test_view
class RequestIDLoggingTestCase(TestCase):
def setUp(self):
self.factory = RequestFactory()
self.handler = logging.getLogger('testproject').handlers[0]
+ self.handler.messages = []
def test_id_generation(self):
request = self.factory.get('/')
middleware = RequestIDMiddleware()
middleware.process_request(request)
self.assertTrue(hasattr(request, 'id'))
test_view(request)
self.assertTrue(request.id in self.handler.messages[0])
+ def test_external_id_in_http_header(self):
+ with self.settings(LOG_REQUEST_ID_HEADER='REQUEST_ID_HEADER'):
+ request = self.factory.get('/')
+ request.META['REQUEST_ID_HEADER'] = 'some_request_id'
+ middleware = RequestIDMiddleware()
+ middleware.process_request(request)
+ self.assertEqual(request.id, 'some_request_id')
+ test_view(request)
+ self.assertTrue('some_request_id' in self.handler.messages[0])
+ | Add test for externally-generated request IDs | ## Code Before:
import logging
from django.test import TestCase, RequestFactory
from log_request_id.middleware import RequestIDMiddleware
from testproject.views import test_view
class RequestIDLoggingTestCase(TestCase):
def setUp(self):
self.factory = RequestFactory()
self.handler = logging.getLogger('testproject').handlers[0]
def test_id_generation(self):
request = self.factory.get('/')
middleware = RequestIDMiddleware()
middleware.process_request(request)
self.assertTrue(hasattr(request, 'id'))
test_view(request)
self.assertTrue(request.id in self.handler.messages[0])
## Instruction:
Add test for externally-generated request IDs
## Code After:
import logging
from django.test import TestCase, RequestFactory
from log_request_id.middleware import RequestIDMiddleware
from testproject.views import test_view
class RequestIDLoggingTestCase(TestCase):
def setUp(self):
self.factory = RequestFactory()
self.handler = logging.getLogger('testproject').handlers[0]
self.handler.messages = []
def test_id_generation(self):
request = self.factory.get('/')
middleware = RequestIDMiddleware()
middleware.process_request(request)
self.assertTrue(hasattr(request, 'id'))
test_view(request)
self.assertTrue(request.id in self.handler.messages[0])
def test_external_id_in_http_header(self):
with self.settings(LOG_REQUEST_ID_HEADER='REQUEST_ID_HEADER'):
request = self.factory.get('/')
request.META['REQUEST_ID_HEADER'] = 'some_request_id'
middleware = RequestIDMiddleware()
middleware.process_request(request)
self.assertEqual(request.id, 'some_request_id')
test_view(request)
self.assertTrue('some_request_id' in self.handler.messages[0])
| import logging
from django.test import TestCase, RequestFactory
from log_request_id.middleware import RequestIDMiddleware
from testproject.views import test_view
class RequestIDLoggingTestCase(TestCase):
def setUp(self):
self.factory = RequestFactory()
self.handler = logging.getLogger('testproject').handlers[0]
+ self.handler.messages = []
def test_id_generation(self):
request = self.factory.get('/')
middleware = RequestIDMiddleware()
middleware.process_request(request)
self.assertTrue(hasattr(request, 'id'))
test_view(request)
self.assertTrue(request.id in self.handler.messages[0])
+
+ def test_external_id_in_http_header(self):
+ with self.settings(LOG_REQUEST_ID_HEADER='REQUEST_ID_HEADER'):
+ request = self.factory.get('/')
+ request.META['REQUEST_ID_HEADER'] = 'some_request_id'
+ middleware = RequestIDMiddleware()
+ middleware.process_request(request)
+ self.assertEqual(request.id, 'some_request_id')
+ test_view(request)
+ self.assertTrue('some_request_id' in self.handler.messages[0]) |
d57844d1d6b2172fe196db4945517a5b3a68d343 | satchless/process/__init__.py | satchless/process/__init__.py | class InvalidData(Exception):
"""
Raised for by step validation process
"""
pass
class Step(object):
"""
A single step in a multistep process
"""
def validate(self):
raise NotImplementedError() # pragma: no cover
class ProcessManager(object):
"""
A multistep process handler
"""
def validate_step(self, step):
try:
step.validate()
except InvalidData:
return False
return True
def get_next_step(self):
for step in self:
if not self.validate_step(step):
return step
def get_errors(self):
errors = {}
for step in self:
try:
step.validate()
except InvalidData as error:
errors[str(step)] = error
return errors
def is_complete(self):
return not self.get_next_step()
def __getitem__(self, step_id):
for step in self:
if str(step) == step_id:
return step
raise KeyError('%r is not a valid step' % (step_id,))
| class InvalidData(Exception):
"""
Raised for by step validation process
"""
pass
class Step(object):
"""
A single step in a multistep process
"""
def validate(self):
raise NotImplementedError() # pragma: no cover
class ProcessManager(object):
"""
A multistep process handler
"""
def validate_step(self, step):
try:
step.validate()
except InvalidData:
return False
return True
def get_next_step(self):
for step in self:
if not self.validate_step(step):
return step
def get_errors(self):
errors = {}
for step in self:
try:
step.validate()
except InvalidData as error:
errors[str(step)] = error
return errors
def is_complete(self):
return self.get_next_step() is None
def __getitem__(self, step_id):
for step in self:
if str(step) == step_id:
return step
raise KeyError('%r is not a valid step' % (step_id,))
| Check explicit that next step is None | Check explicit that next step is None
| Python | bsd-3-clause | taedori81/satchless | class InvalidData(Exception):
"""
Raised for by step validation process
"""
pass
class Step(object):
"""
A single step in a multistep process
"""
def validate(self):
raise NotImplementedError() # pragma: no cover
class ProcessManager(object):
"""
A multistep process handler
"""
def validate_step(self, step):
try:
step.validate()
except InvalidData:
return False
return True
def get_next_step(self):
for step in self:
if not self.validate_step(step):
return step
def get_errors(self):
errors = {}
for step in self:
try:
step.validate()
except InvalidData as error:
errors[str(step)] = error
return errors
def is_complete(self):
- return not self.get_next_step()
+ return self.get_next_step() is None
def __getitem__(self, step_id):
for step in self:
if str(step) == step_id:
return step
raise KeyError('%r is not a valid step' % (step_id,))
| Check explicit that next step is None | ## Code Before:
class InvalidData(Exception):
"""
Raised for by step validation process
"""
pass
class Step(object):
"""
A single step in a multistep process
"""
def validate(self):
raise NotImplementedError() # pragma: no cover
class ProcessManager(object):
"""
A multistep process handler
"""
def validate_step(self, step):
try:
step.validate()
except InvalidData:
return False
return True
def get_next_step(self):
for step in self:
if not self.validate_step(step):
return step
def get_errors(self):
errors = {}
for step in self:
try:
step.validate()
except InvalidData as error:
errors[str(step)] = error
return errors
def is_complete(self):
return not self.get_next_step()
def __getitem__(self, step_id):
for step in self:
if str(step) == step_id:
return step
raise KeyError('%r is not a valid step' % (step_id,))
## Instruction:
Check explicit that next step is None
## Code After:
class InvalidData(Exception):
"""
Raised for by step validation process
"""
pass
class Step(object):
"""
A single step in a multistep process
"""
def validate(self):
raise NotImplementedError() # pragma: no cover
class ProcessManager(object):
"""
A multistep process handler
"""
def validate_step(self, step):
try:
step.validate()
except InvalidData:
return False
return True
def get_next_step(self):
for step in self:
if not self.validate_step(step):
return step
def get_errors(self):
errors = {}
for step in self:
try:
step.validate()
except InvalidData as error:
errors[str(step)] = error
return errors
def is_complete(self):
return self.get_next_step() is None
def __getitem__(self, step_id):
for step in self:
if str(step) == step_id:
return step
raise KeyError('%r is not a valid step' % (step_id,))
| class InvalidData(Exception):
"""
Raised for by step validation process
"""
pass
class Step(object):
"""
A single step in a multistep process
"""
def validate(self):
raise NotImplementedError() # pragma: no cover
class ProcessManager(object):
"""
A multistep process handler
"""
def validate_step(self, step):
try:
step.validate()
except InvalidData:
return False
return True
def get_next_step(self):
for step in self:
if not self.validate_step(step):
return step
def get_errors(self):
errors = {}
for step in self:
try:
step.validate()
except InvalidData as error:
errors[str(step)] = error
return errors
def is_complete(self):
- return not self.get_next_step()
? ----
+ return self.get_next_step() is None
? ++++++++
def __getitem__(self, step_id):
for step in self:
if str(step) == step_id:
return step
raise KeyError('%r is not a valid step' % (step_id,)) |
e9c83d59fbb5b341e2126039109e306875db0490 | syweb/__init__.py | syweb/__init__.py | import os
with open(os.path.join(os.path.dirname(__file__), "webclient/VERSION")) as f:
__version__ = f.read().strip()
| import os
def installed_location():
return __file__
with open(os.path.join(os.path.dirname(installed_location()), "webclient/VERSION")) as f:
__version__ = f.read().strip()
| Add an 'installed_location()' function so syweb can report its own location | Add an 'installed_location()' function so syweb can report its own location
| Python | apache-2.0 | williamboman/matrix-angular-sdk,williamboman/matrix-angular-sdk,matrix-org/matrix-angular-sdk,williamboman/matrix-angular-sdk,matrix-org/matrix-angular-sdk,matrix-org/matrix-angular-sdk | import os
+ def installed_location():
+ return __file__
+
- with open(os.path.join(os.path.dirname(__file__), "webclient/VERSION")) as f:
+ with open(os.path.join(os.path.dirname(installed_location()), "webclient/VERSION")) as f:
__version__ = f.read().strip()
| Add an 'installed_location()' function so syweb can report its own location | ## Code Before:
import os
with open(os.path.join(os.path.dirname(__file__), "webclient/VERSION")) as f:
__version__ = f.read().strip()
## Instruction:
Add an 'installed_location()' function so syweb can report its own location
## Code After:
import os
def installed_location():
return __file__
with open(os.path.join(os.path.dirname(installed_location()), "webclient/VERSION")) as f:
__version__ = f.read().strip()
| import os
+ def installed_location():
+ return __file__
+
- with open(os.path.join(os.path.dirname(__file__), "webclient/VERSION")) as f:
? --- ^
+ with open(os.path.join(os.path.dirname(installed_location()), "webclient/VERSION")) as f:
? +++++ + ^^^^^^^^^^
__version__ = f.read().strip() |
8a36070c76d1552e2d2e61c1e5c47202cc28b329 | basket/news/backends/common.py | basket/news/backends/common.py | from functools import wraps
from time import time
from django_statsd.clients import statsd
class UnauthorizedException(Exception):
"""Failure to log into the email server."""
pass
class NewsletterException(Exception):
"""Error when trying to talk to the the email server."""
def __init__(self, msg=None, error_code=None, status_code=None):
self.error_code = error_code
self.status_code = status_code
super(NewsletterException, self).__init__(msg)
class NewsletterNoResultsException(NewsletterException):
"""
No results were returned from the mail server (but the request
didn't report any errors)
"""
pass
def get_timer_decorator(prefix):
"""
Decorator for timing and counting requests to the API
"""
def decorator(f):
@wraps(f)
def wrapped(*args, **kwargs):
starttime = time()
e = None
try:
resp = f(*args, **kwargs)
except NewsletterException as e: # noqa
pass
except Exception:
raise
totaltime = int((time() - starttime) * 1000)
statsd.timing(prefix + '.timing', totaltime)
statsd.timing(prefix + '.{}.timing'.format(f.__name__), totaltime)
statsd.incr(prefix + '.count')
statsd.incr(prefix + '.{}.count'.format(f.__name__))
if e:
raise
else:
return resp
return wrapped
return decorator
| from functools import wraps
from time import time
from django_statsd.clients import statsd
class UnauthorizedException(Exception):
"""Failure to log into the email server."""
pass
class NewsletterException(Exception):
"""Error when trying to talk to the the email server."""
def __init__(self, msg=None, error_code=None, status_code=None):
self.error_code = error_code
self.status_code = status_code
super(NewsletterException, self).__init__(msg)
class NewsletterNoResultsException(NewsletterException):
"""
No results were returned from the mail server (but the request
didn't report any errors)
"""
pass
def get_timer_decorator(prefix):
"""
Decorator for timing and counting requests to the API
"""
def decorator(f):
@wraps(f)
def wrapped(*args, **kwargs):
starttime = time()
def record_timing():
totaltime = int((time() - starttime) * 1000)
statsd.timing(prefix + '.timing', totaltime)
statsd.timing(prefix + '.{}.timing'.format(f.__name__), totaltime)
statsd.incr(prefix + '.count')
statsd.incr(prefix + '.{}.count'.format(f.__name__))
try:
resp = f(*args, **kwargs)
except NewsletterException:
record_timing()
raise
record_timing()
return resp
return wrapped
return decorator
| Refactor the timing decorator to be less confusing | Refactor the timing decorator to be less confusing
Also means that we don't have to ignore a flake8 error.
| Python | mpl-2.0 | glogiotatidis/basket,glogiotatidis/basket,glogiotatidis/basket | from functools import wraps
from time import time
from django_statsd.clients import statsd
class UnauthorizedException(Exception):
"""Failure to log into the email server."""
pass
class NewsletterException(Exception):
"""Error when trying to talk to the the email server."""
def __init__(self, msg=None, error_code=None, status_code=None):
self.error_code = error_code
self.status_code = status_code
super(NewsletterException, self).__init__(msg)
class NewsletterNoResultsException(NewsletterException):
"""
No results were returned from the mail server (but the request
didn't report any errors)
"""
pass
def get_timer_decorator(prefix):
"""
Decorator for timing and counting requests to the API
"""
def decorator(f):
@wraps(f)
def wrapped(*args, **kwargs):
starttime = time()
- e = None
+
+ def record_timing():
+ totaltime = int((time() - starttime) * 1000)
+ statsd.timing(prefix + '.timing', totaltime)
+ statsd.timing(prefix + '.{}.timing'.format(f.__name__), totaltime)
+ statsd.incr(prefix + '.count')
+ statsd.incr(prefix + '.{}.count'.format(f.__name__))
+
try:
resp = f(*args, **kwargs)
- except NewsletterException as e: # noqa
+ except NewsletterException:
+ record_timing()
- pass
- except Exception:
raise
+ record_timing()
- totaltime = int((time() - starttime) * 1000)
- statsd.timing(prefix + '.timing', totaltime)
- statsd.timing(prefix + '.{}.timing'.format(f.__name__), totaltime)
- statsd.incr(prefix + '.count')
- statsd.incr(prefix + '.{}.count'.format(f.__name__))
- if e:
- raise
- else:
- return resp
+ return resp
return wrapped
return decorator
| Refactor the timing decorator to be less confusing | ## Code Before:
from functools import wraps
from time import time
from django_statsd.clients import statsd
class UnauthorizedException(Exception):
"""Failure to log into the email server."""
pass
class NewsletterException(Exception):
"""Error when trying to talk to the the email server."""
def __init__(self, msg=None, error_code=None, status_code=None):
self.error_code = error_code
self.status_code = status_code
super(NewsletterException, self).__init__(msg)
class NewsletterNoResultsException(NewsletterException):
"""
No results were returned from the mail server (but the request
didn't report any errors)
"""
pass
def get_timer_decorator(prefix):
"""
Decorator for timing and counting requests to the API
"""
def decorator(f):
@wraps(f)
def wrapped(*args, **kwargs):
starttime = time()
e = None
try:
resp = f(*args, **kwargs)
except NewsletterException as e: # noqa
pass
except Exception:
raise
totaltime = int((time() - starttime) * 1000)
statsd.timing(prefix + '.timing', totaltime)
statsd.timing(prefix + '.{}.timing'.format(f.__name__), totaltime)
statsd.incr(prefix + '.count')
statsd.incr(prefix + '.{}.count'.format(f.__name__))
if e:
raise
else:
return resp
return wrapped
return decorator
## Instruction:
Refactor the timing decorator to be less confusing
## Code After:
from functools import wraps
from time import time
from django_statsd.clients import statsd
class UnauthorizedException(Exception):
"""Failure to log into the email server."""
pass
class NewsletterException(Exception):
"""Error when trying to talk to the the email server."""
def __init__(self, msg=None, error_code=None, status_code=None):
self.error_code = error_code
self.status_code = status_code
super(NewsletterException, self).__init__(msg)
class NewsletterNoResultsException(NewsletterException):
"""
No results were returned from the mail server (but the request
didn't report any errors)
"""
pass
def get_timer_decorator(prefix):
"""
Decorator for timing and counting requests to the API
"""
def decorator(f):
@wraps(f)
def wrapped(*args, **kwargs):
starttime = time()
def record_timing():
totaltime = int((time() - starttime) * 1000)
statsd.timing(prefix + '.timing', totaltime)
statsd.timing(prefix + '.{}.timing'.format(f.__name__), totaltime)
statsd.incr(prefix + '.count')
statsd.incr(prefix + '.{}.count'.format(f.__name__))
try:
resp = f(*args, **kwargs)
except NewsletterException:
record_timing()
raise
record_timing()
return resp
return wrapped
return decorator
| from functools import wraps
from time import time
from django_statsd.clients import statsd
class UnauthorizedException(Exception):
"""Failure to log into the email server."""
pass
class NewsletterException(Exception):
"""Error when trying to talk to the the email server."""
def __init__(self, msg=None, error_code=None, status_code=None):
self.error_code = error_code
self.status_code = status_code
super(NewsletterException, self).__init__(msg)
class NewsletterNoResultsException(NewsletterException):
"""
No results were returned from the mail server (but the request
didn't report any errors)
"""
pass
def get_timer_decorator(prefix):
"""
Decorator for timing and counting requests to the API
"""
def decorator(f):
@wraps(f)
def wrapped(*args, **kwargs):
starttime = time()
- e = None
+
+ def record_timing():
+ totaltime = int((time() - starttime) * 1000)
+ statsd.timing(prefix + '.timing', totaltime)
+ statsd.timing(prefix + '.{}.timing'.format(f.__name__), totaltime)
+ statsd.incr(prefix + '.count')
+ statsd.incr(prefix + '.{}.count'.format(f.__name__))
+
try:
resp = f(*args, **kwargs)
- except NewsletterException as e: # noqa
? ----- --------
+ except NewsletterException:
+ record_timing()
- pass
- except Exception:
raise
+ record_timing()
- totaltime = int((time() - starttime) * 1000)
- statsd.timing(prefix + '.timing', totaltime)
- statsd.timing(prefix + '.{}.timing'.format(f.__name__), totaltime)
- statsd.incr(prefix + '.count')
- statsd.incr(prefix + '.{}.count'.format(f.__name__))
- if e:
- raise
- else:
- return resp
? ----
+ return resp
return wrapped
return decorator |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.