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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2cd4e6f021e576a17a3f8f40122775baee9e8889 | server/run.py | server/run.py | from eve import Eve
app = Eve()
if __name__ == '__main__':
app.run()
| import json
import settings
from flask import request, session
from requests import HTTPError
from requests_oauthlib import OAuth2Session
from eve import Eve
from flask_login import LoginManager
app = Eve()
login_manager = LoginManager(app)
login_manager.login_view = "login"
login_manager.session_protection = "strong"
app.secret_key = settings.APP_SECRET_KEY
def get_google_auth(state=None, token=None):
if token:
return OAuth2Session(settings.OAUTH_CLIENT_ID, token=token)
if state:
return OAuth2Session(
settings.OAUTH_CLIENT_ID,
state=state,
redirect_uri=settings.OAUTH_REDIRECT_URI
)
return OAuth2Session(
settings.OAUTH_CLIENT_ID,
redirect_uri=settings.OAUTH_REDIRECT_URI,
scope=settings.OAUTH_SCOPE
)
@app.route('/login')
def login():
google = get_google_auth()
auth_url, state = google.authorization_url(
settings.OAUTH_AUTH_URI,
access_type='online'
)
session['oauth_state'] = state
return json.dumps({
"auth_url": auth_url,
})
@app.route('/oauth2callback')
def callback():
if 'error' in request.args:
if request.args.get('error') == 'access_denied':
return json.dumps({
"error": "Access denied",
})
return json.dumps({
"error": "Other error",
})
if 'code' not in request.args and 'state' not in request.args:
return json.dumps({})
else:
google = get_google_auth(state=session['oauth_state'])
try:
token = google.fetch_token(
settings.OAUTH_TOKEN_URI,
client_secret=settings.OAUTH_CLIENT_SECRET,
authorization_response=request.url)
except HTTPError:
return json.dumps({"error": "Failed to get google login."})
google = get_google_auth(token=token)
resp = google.get(settings.OAUTH_USER_INFO)
if resp.status_code == 200:
user_data = resp.json()
# email = user_data['email']
print(user_data)
return json.dumps({
"status": "ok",
"user_data": user_data,
})
return json.dumps({
"error": "Failed to get user data",
})
if __name__ == '__main__':
app.run()
| Add initial views for google login. | Add initial views for google login.
| Python | mit | mattiaslundberg/typer,mattiaslundberg/typer,mattiaslundberg/typer,mattiaslundberg/typer | + import json
+ import settings
+ from flask import request, session
+ from requests import HTTPError
+ from requests_oauthlib import OAuth2Session
from eve import Eve
+ from flask_login import LoginManager
+
+
app = Eve()
+
+ login_manager = LoginManager(app)
+ login_manager.login_view = "login"
+ login_manager.session_protection = "strong"
+
+ app.secret_key = settings.APP_SECRET_KEY
+
+
+ def get_google_auth(state=None, token=None):
+ if token:
+ return OAuth2Session(settings.OAUTH_CLIENT_ID, token=token)
+ if state:
+ return OAuth2Session(
+ settings.OAUTH_CLIENT_ID,
+ state=state,
+ redirect_uri=settings.OAUTH_REDIRECT_URI
+ )
+
+ return OAuth2Session(
+ settings.OAUTH_CLIENT_ID,
+ redirect_uri=settings.OAUTH_REDIRECT_URI,
+ scope=settings.OAUTH_SCOPE
+ )
+
+
+ @app.route('/login')
+ def login():
+ google = get_google_auth()
+ auth_url, state = google.authorization_url(
+ settings.OAUTH_AUTH_URI,
+ access_type='online'
+ )
+ session['oauth_state'] = state
+ return json.dumps({
+ "auth_url": auth_url,
+ })
+
+
+ @app.route('/oauth2callback')
+ def callback():
+ if 'error' in request.args:
+ if request.args.get('error') == 'access_denied':
+ return json.dumps({
+ "error": "Access denied",
+ })
+ return json.dumps({
+ "error": "Other error",
+ })
+ if 'code' not in request.args and 'state' not in request.args:
+ return json.dumps({})
+ else:
+ google = get_google_auth(state=session['oauth_state'])
+ try:
+ token = google.fetch_token(
+ settings.OAUTH_TOKEN_URI,
+ client_secret=settings.OAUTH_CLIENT_SECRET,
+ authorization_response=request.url)
+ except HTTPError:
+ return json.dumps({"error": "Failed to get google login."})
+ google = get_google_auth(token=token)
+ resp = google.get(settings.OAUTH_USER_INFO)
+ if resp.status_code == 200:
+ user_data = resp.json()
+ # email = user_data['email']
+ print(user_data)
+ return json.dumps({
+ "status": "ok",
+ "user_data": user_data,
+ })
+ return json.dumps({
+ "error": "Failed to get user data",
+ })
if __name__ == '__main__':
app.run()
| Add initial views for google login. | ## Code Before:
from eve import Eve
app = Eve()
if __name__ == '__main__':
app.run()
## Instruction:
Add initial views for google login.
## Code After:
import json
import settings
from flask import request, session
from requests import HTTPError
from requests_oauthlib import OAuth2Session
from eve import Eve
from flask_login import LoginManager
app = Eve()
login_manager = LoginManager(app)
login_manager.login_view = "login"
login_manager.session_protection = "strong"
app.secret_key = settings.APP_SECRET_KEY
def get_google_auth(state=None, token=None):
if token:
return OAuth2Session(settings.OAUTH_CLIENT_ID, token=token)
if state:
return OAuth2Session(
settings.OAUTH_CLIENT_ID,
state=state,
redirect_uri=settings.OAUTH_REDIRECT_URI
)
return OAuth2Session(
settings.OAUTH_CLIENT_ID,
redirect_uri=settings.OAUTH_REDIRECT_URI,
scope=settings.OAUTH_SCOPE
)
@app.route('/login')
def login():
google = get_google_auth()
auth_url, state = google.authorization_url(
settings.OAUTH_AUTH_URI,
access_type='online'
)
session['oauth_state'] = state
return json.dumps({
"auth_url": auth_url,
})
@app.route('/oauth2callback')
def callback():
if 'error' in request.args:
if request.args.get('error') == 'access_denied':
return json.dumps({
"error": "Access denied",
})
return json.dumps({
"error": "Other error",
})
if 'code' not in request.args and 'state' not in request.args:
return json.dumps({})
else:
google = get_google_auth(state=session['oauth_state'])
try:
token = google.fetch_token(
settings.OAUTH_TOKEN_URI,
client_secret=settings.OAUTH_CLIENT_SECRET,
authorization_response=request.url)
except HTTPError:
return json.dumps({"error": "Failed to get google login."})
google = get_google_auth(token=token)
resp = google.get(settings.OAUTH_USER_INFO)
if resp.status_code == 200:
user_data = resp.json()
# email = user_data['email']
print(user_data)
return json.dumps({
"status": "ok",
"user_data": user_data,
})
return json.dumps({
"error": "Failed to get user data",
})
if __name__ == '__main__':
app.run()
| + import json
+ import settings
+ from flask import request, session
+ from requests import HTTPError
+ from requests_oauthlib import OAuth2Session
from eve import Eve
+ from flask_login import LoginManager
+
+
app = Eve()
+
+ login_manager = LoginManager(app)
+ login_manager.login_view = "login"
+ login_manager.session_protection = "strong"
+
+ app.secret_key = settings.APP_SECRET_KEY
+
+
+ def get_google_auth(state=None, token=None):
+ if token:
+ return OAuth2Session(settings.OAUTH_CLIENT_ID, token=token)
+ if state:
+ return OAuth2Session(
+ settings.OAUTH_CLIENT_ID,
+ state=state,
+ redirect_uri=settings.OAUTH_REDIRECT_URI
+ )
+
+ return OAuth2Session(
+ settings.OAUTH_CLIENT_ID,
+ redirect_uri=settings.OAUTH_REDIRECT_URI,
+ scope=settings.OAUTH_SCOPE
+ )
+
+
+ @app.route('/login')
+ def login():
+ google = get_google_auth()
+ auth_url, state = google.authorization_url(
+ settings.OAUTH_AUTH_URI,
+ access_type='online'
+ )
+ session['oauth_state'] = state
+ return json.dumps({
+ "auth_url": auth_url,
+ })
+
+
+ @app.route('/oauth2callback')
+ def callback():
+ if 'error' in request.args:
+ if request.args.get('error') == 'access_denied':
+ return json.dumps({
+ "error": "Access denied",
+ })
+ return json.dumps({
+ "error": "Other error",
+ })
+ if 'code' not in request.args and 'state' not in request.args:
+ return json.dumps({})
+ else:
+ google = get_google_auth(state=session['oauth_state'])
+ try:
+ token = google.fetch_token(
+ settings.OAUTH_TOKEN_URI,
+ client_secret=settings.OAUTH_CLIENT_SECRET,
+ authorization_response=request.url)
+ except HTTPError:
+ return json.dumps({"error": "Failed to get google login."})
+ google = get_google_auth(token=token)
+ resp = google.get(settings.OAUTH_USER_INFO)
+ if resp.status_code == 200:
+ user_data = resp.json()
+ # email = user_data['email']
+ print(user_data)
+ return json.dumps({
+ "status": "ok",
+ "user_data": user_data,
+ })
+ return json.dumps({
+ "error": "Failed to get user data",
+ })
if __name__ == '__main__':
app.run() |
7f78484fbefc0c193668fffd03b38bf8523e89f6 | pyecore/notification.py | pyecore/notification.py |
class ENotifer(object):
def notify(self, notification):
notification.notifier = notification.notifier or self
for listener in self._eternal_listener + self.listeners:
listener.notifyChanged(notification)
def enum(enumName, *listValueNames):
"""Clever implementation of an enum like in python
Shameless copy from: http://sametmax.com/faire-des-enums-en-python/
"""
listValueNumbers = range(len(listValueNames))
dictAttrib = dict(zip(listValueNames, listValueNumbers))
dictReverse = dict(zip(listValueNumbers, listValueNames))
dictAttrib["dictReverse"] = dictReverse
mainType = type(enumName, (), dictAttrib)
return mainType
Kind = enum('Kind',
'ADD',
'ADD_MANY',
'MOVE',
'REMOVE',
'REMOVE_MANY',
'SET',
'UNSET')
class Notification(object):
def __init__(self, notifier=None, kind=None, old=None, new=None,
feature=None):
self.notifier = notifier
self.kind = kind
self.old = old
self.new = new
self.feature = feature
def __repr__(self):
return ('[{0}] old={1} new={2} obj={3} #{4}'
.format(Kind.dictReverse[self.kind],
self.old,
self.new,
self.notifier,
self.feature))
class EObserver(object):
def __init__(self, notifier=None, notifyChanged=None):
if notifier:
notifier.listeners.append(self)
if notifyChanged:
self.notifyChanged = notifyChanged
def observe(self, notifier):
notifier.listeners.append(self)
def notifyChanged(self, notification):
pass
| from enum import Enum, unique
class ENotifer(object):
def notify(self, notification):
notification.notifier = notification.notifier or self
for listener in self._eternal_listener + self.listeners:
listener.notifyChanged(notification)
@unique
class Kind(Enum):
ADD = 0
ADD_MANY = 1
MOVE = 2
REMOVE = 3
REMOVE_MANY = 4
SET = 5
UNSET = 6
class Notification(object):
def __init__(self, notifier=None, kind=None, old=None, new=None,
feature=None):
self.notifier = notifier
self.kind = kind
self.old = old
self.new = new
self.feature = feature
def __repr__(self):
return ('[{0}] old={1} new={2} obj={3} #{4}'
.format(self.kind.name,
self.old,
self.new,
self.notifier,
self.feature))
class EObserver(object):
def __init__(self, notifier=None, notifyChanged=None):
if notifier:
notifier.listeners.append(self)
if notifyChanged:
self.notifyChanged = notifyChanged
def observe(self, notifier):
notifier.listeners.append(self)
def notifyChanged(self, notification):
pass
| Add better enumeration for Notification | Add better enumeration for Notification
The previous 'Kind' enumeration for Notification were using a
home-made-cooked way of dealing with enumeration. The code were got
from an article from the http://sametmax.com/ website (great website
by the way). This new version uses the python 3.4 enumeration module,
but as this module had been introduced in Python 3.4, it means that
the Python 3.3 compatibility is broken.
| Python | bsd-3-clause | aranega/pyecore,pyecore/pyecore | + from enum import Enum, unique
class ENotifer(object):
def notify(self, notification):
notification.notifier = notification.notifier or self
for listener in self._eternal_listener + self.listeners:
listener.notifyChanged(notification)
+ @unique
+ class Kind(Enum):
+ ADD = 0
+ ADD_MANY = 1
+ MOVE = 2
+ REMOVE = 3
+ REMOVE_MANY = 4
+ SET = 5
+ UNSET = 6
- def enum(enumName, *listValueNames):
- """Clever implementation of an enum like in python
-
- Shameless copy from: http://sametmax.com/faire-des-enums-en-python/
- """
- listValueNumbers = range(len(listValueNames))
- dictAttrib = dict(zip(listValueNames, listValueNumbers))
- dictReverse = dict(zip(listValueNumbers, listValueNames))
- dictAttrib["dictReverse"] = dictReverse
- mainType = type(enumName, (), dictAttrib)
- return mainType
-
-
- Kind = enum('Kind',
- 'ADD',
- 'ADD_MANY',
- 'MOVE',
- 'REMOVE',
- 'REMOVE_MANY',
- 'SET',
- 'UNSET')
class Notification(object):
def __init__(self, notifier=None, kind=None, old=None, new=None,
feature=None):
self.notifier = notifier
self.kind = kind
self.old = old
self.new = new
self.feature = feature
def __repr__(self):
return ('[{0}] old={1} new={2} obj={3} #{4}'
- .format(Kind.dictReverse[self.kind],
+ .format(self.kind.name,
self.old,
self.new,
self.notifier,
self.feature))
class EObserver(object):
def __init__(self, notifier=None, notifyChanged=None):
if notifier:
notifier.listeners.append(self)
if notifyChanged:
self.notifyChanged = notifyChanged
def observe(self, notifier):
notifier.listeners.append(self)
def notifyChanged(self, notification):
pass
| Add better enumeration for Notification | ## Code Before:
class ENotifer(object):
def notify(self, notification):
notification.notifier = notification.notifier or self
for listener in self._eternal_listener + self.listeners:
listener.notifyChanged(notification)
def enum(enumName, *listValueNames):
"""Clever implementation of an enum like in python
Shameless copy from: http://sametmax.com/faire-des-enums-en-python/
"""
listValueNumbers = range(len(listValueNames))
dictAttrib = dict(zip(listValueNames, listValueNumbers))
dictReverse = dict(zip(listValueNumbers, listValueNames))
dictAttrib["dictReverse"] = dictReverse
mainType = type(enumName, (), dictAttrib)
return mainType
Kind = enum('Kind',
'ADD',
'ADD_MANY',
'MOVE',
'REMOVE',
'REMOVE_MANY',
'SET',
'UNSET')
class Notification(object):
def __init__(self, notifier=None, kind=None, old=None, new=None,
feature=None):
self.notifier = notifier
self.kind = kind
self.old = old
self.new = new
self.feature = feature
def __repr__(self):
return ('[{0}] old={1} new={2} obj={3} #{4}'
.format(Kind.dictReverse[self.kind],
self.old,
self.new,
self.notifier,
self.feature))
class EObserver(object):
def __init__(self, notifier=None, notifyChanged=None):
if notifier:
notifier.listeners.append(self)
if notifyChanged:
self.notifyChanged = notifyChanged
def observe(self, notifier):
notifier.listeners.append(self)
def notifyChanged(self, notification):
pass
## Instruction:
Add better enumeration for Notification
## Code After:
from enum import Enum, unique
class ENotifer(object):
def notify(self, notification):
notification.notifier = notification.notifier or self
for listener in self._eternal_listener + self.listeners:
listener.notifyChanged(notification)
@unique
class Kind(Enum):
ADD = 0
ADD_MANY = 1
MOVE = 2
REMOVE = 3
REMOVE_MANY = 4
SET = 5
UNSET = 6
class Notification(object):
def __init__(self, notifier=None, kind=None, old=None, new=None,
feature=None):
self.notifier = notifier
self.kind = kind
self.old = old
self.new = new
self.feature = feature
def __repr__(self):
return ('[{0}] old={1} new={2} obj={3} #{4}'
.format(self.kind.name,
self.old,
self.new,
self.notifier,
self.feature))
class EObserver(object):
def __init__(self, notifier=None, notifyChanged=None):
if notifier:
notifier.listeners.append(self)
if notifyChanged:
self.notifyChanged = notifyChanged
def observe(self, notifier):
notifier.listeners.append(self)
def notifyChanged(self, notification):
pass
| + from enum import Enum, unique
class ENotifer(object):
def notify(self, notification):
notification.notifier = notification.notifier or self
for listener in self._eternal_listener + self.listeners:
listener.notifyChanged(notification)
+ @unique
+ class Kind(Enum):
+ ADD = 0
+ ADD_MANY = 1
+ MOVE = 2
+ REMOVE = 3
+ REMOVE_MANY = 4
+ SET = 5
+ UNSET = 6
- def enum(enumName, *listValueNames):
- """Clever implementation of an enum like in python
-
- Shameless copy from: http://sametmax.com/faire-des-enums-en-python/
- """
- listValueNumbers = range(len(listValueNames))
- dictAttrib = dict(zip(listValueNames, listValueNumbers))
- dictReverse = dict(zip(listValueNumbers, listValueNames))
- dictAttrib["dictReverse"] = dictReverse
- mainType = type(enumName, (), dictAttrib)
- return mainType
-
-
- Kind = enum('Kind',
- 'ADD',
- 'ADD_MANY',
- 'MOVE',
- 'REMOVE',
- 'REMOVE_MANY',
- 'SET',
- 'UNSET')
class Notification(object):
def __init__(self, notifier=None, kind=None, old=None, new=None,
feature=None):
self.notifier = notifier
self.kind = kind
self.old = old
self.new = new
self.feature = feature
def __repr__(self):
return ('[{0}] old={1} new={2} obj={3} #{4}'
- .format(Kind.dictReverse[self.kind],
+ .format(self.kind.name,
self.old,
self.new,
self.notifier,
self.feature))
class EObserver(object):
def __init__(self, notifier=None, notifyChanged=None):
if notifier:
notifier.listeners.append(self)
if notifyChanged:
self.notifyChanged = notifyChanged
def observe(self, notifier):
notifier.listeners.append(self)
def notifyChanged(self, notification):
pass |
e3ae701be163ccff7e2f64721752b0374dffdfc1 | rosie/chamber_of_deputies/tests/test_dataset.py | rosie/chamber_of_deputies/tests/test_dataset.py | import os.path
from tempfile import mkdtemp
from unittest import TestCase
from unittest.mock import patch
from shutil import copy2
from rosie.chamber_of_deputies import settings
from rosie.chamber_of_deputies.adapter import Adapter
class TestDataset(TestCase):
def setUp(self):
temp_path = mkdtemp()
copy2('rosie/chamber_of_deputies/tests/fixtures/companies.xz',
os.path.join(temp_path, settings.COMPANIES_DATASET))
copy2('rosie/chamber_of_deputies/tests/fixtures/reimbursements.xz', temp_path)
self.subject = Adapter(temp_path)
@patch('rosie.chamber_of_deputies.adapter.CEAPDataset')
@patch('rosie.chamber_of_deputies.adapter.fetch')
def test_get_performs_a_left_merge_between_reimbursements_and_companies(self, _ceap_dataset, _fetch):
dataset = self.subject.dataset()
self.assertEqual(5, len(dataset))
self.assertEqual(1, dataset['legal_entity'].isnull().sum())
| import shutil
import os
from tempfile import mkdtemp
from unittest import TestCase
from unittest.mock import patch
from shutil import copy2
from rosie.chamber_of_deputies.adapter import Adapter
class TestDataset(TestCase):
def setUp(self):
self.temp_path = mkdtemp()
fixtures = os.path.join('rosie', 'chamber_of_deputies', 'tests', 'fixtures')
copies = (
('companies.xz', Adapter.COMPANIES_DATASET),
('reimbursements.xz', 'reimbursements.xz')
)
for source, target in copies:
copy2(os.path.join(fixtures, source), os.path.join(self.temp_path, target))
self.subject = Adapter(self.temp_path)
def tearDown(self):
shutil.rmtree(self.temp_path)
@patch('rosie.chamber_of_deputies.adapter.CEAPDataset')
@patch('rosie.chamber_of_deputies.adapter.fetch')
def test_get_performs_a_left_merge_between_reimbursements_and_companies(self, fetch, ceap):
self.assertEqual(5, len(self.subject.dataset))
self.assertEqual(1, self.subject.dataset['legal_entity'].isnull().sum())
| Fix companies path in Chamber of Deputies dataset test | Fix companies path in Chamber of Deputies dataset test
| Python | mit | marcusrehm/serenata-de-amor,datasciencebr/rosie,marcusrehm/serenata-de-amor,datasciencebr/serenata-de-amor,datasciencebr/serenata-de-amor,marcusrehm/serenata-de-amor,marcusrehm/serenata-de-amor | + import shutil
- import os.path
+ import os
from tempfile import mkdtemp
from unittest import TestCase
from unittest.mock import patch
from shutil import copy2
- from rosie.chamber_of_deputies import settings
from rosie.chamber_of_deputies.adapter import Adapter
class TestDataset(TestCase):
def setUp(self):
- temp_path = mkdtemp()
+ self.temp_path = mkdtemp()
- copy2('rosie/chamber_of_deputies/tests/fixtures/companies.xz',
- os.path.join(temp_path, settings.COMPANIES_DATASET))
- copy2('rosie/chamber_of_deputies/tests/fixtures/reimbursements.xz', temp_path)
+ fixtures = os.path.join('rosie', 'chamber_of_deputies', 'tests', 'fixtures')
+ copies = (
+ ('companies.xz', Adapter.COMPANIES_DATASET),
+ ('reimbursements.xz', 'reimbursements.xz')
+ )
+ for source, target in copies:
+ copy2(os.path.join(fixtures, source), os.path.join(self.temp_path, target))
- self.subject = Adapter(temp_path)
+ self.subject = Adapter(self.temp_path)
+
+ def tearDown(self):
+ shutil.rmtree(self.temp_path)
@patch('rosie.chamber_of_deputies.adapter.CEAPDataset')
@patch('rosie.chamber_of_deputies.adapter.fetch')
- def test_get_performs_a_left_merge_between_reimbursements_and_companies(self, _ceap_dataset, _fetch):
+ def test_get_performs_a_left_merge_between_reimbursements_and_companies(self, fetch, ceap):
- dataset = self.subject.dataset()
- self.assertEqual(5, len(dataset))
+ self.assertEqual(5, len(self.subject.dataset))
- self.assertEqual(1, dataset['legal_entity'].isnull().sum())
+ self.assertEqual(1, self.subject.dataset['legal_entity'].isnull().sum())
| Fix companies path in Chamber of Deputies dataset test | ## Code Before:
import os.path
from tempfile import mkdtemp
from unittest import TestCase
from unittest.mock import patch
from shutil import copy2
from rosie.chamber_of_deputies import settings
from rosie.chamber_of_deputies.adapter import Adapter
class TestDataset(TestCase):
def setUp(self):
temp_path = mkdtemp()
copy2('rosie/chamber_of_deputies/tests/fixtures/companies.xz',
os.path.join(temp_path, settings.COMPANIES_DATASET))
copy2('rosie/chamber_of_deputies/tests/fixtures/reimbursements.xz', temp_path)
self.subject = Adapter(temp_path)
@patch('rosie.chamber_of_deputies.adapter.CEAPDataset')
@patch('rosie.chamber_of_deputies.adapter.fetch')
def test_get_performs_a_left_merge_between_reimbursements_and_companies(self, _ceap_dataset, _fetch):
dataset = self.subject.dataset()
self.assertEqual(5, len(dataset))
self.assertEqual(1, dataset['legal_entity'].isnull().sum())
## Instruction:
Fix companies path in Chamber of Deputies dataset test
## Code After:
import shutil
import os
from tempfile import mkdtemp
from unittest import TestCase
from unittest.mock import patch
from shutil import copy2
from rosie.chamber_of_deputies.adapter import Adapter
class TestDataset(TestCase):
def setUp(self):
self.temp_path = mkdtemp()
fixtures = os.path.join('rosie', 'chamber_of_deputies', 'tests', 'fixtures')
copies = (
('companies.xz', Adapter.COMPANIES_DATASET),
('reimbursements.xz', 'reimbursements.xz')
)
for source, target in copies:
copy2(os.path.join(fixtures, source), os.path.join(self.temp_path, target))
self.subject = Adapter(self.temp_path)
def tearDown(self):
shutil.rmtree(self.temp_path)
@patch('rosie.chamber_of_deputies.adapter.CEAPDataset')
@patch('rosie.chamber_of_deputies.adapter.fetch')
def test_get_performs_a_left_merge_between_reimbursements_and_companies(self, fetch, ceap):
self.assertEqual(5, len(self.subject.dataset))
self.assertEqual(1, self.subject.dataset['legal_entity'].isnull().sum())
| + import shutil
- import os.path
? -----
+ import os
from tempfile import mkdtemp
from unittest import TestCase
from unittest.mock import patch
from shutil import copy2
- from rosie.chamber_of_deputies import settings
from rosie.chamber_of_deputies.adapter import Adapter
class TestDataset(TestCase):
def setUp(self):
- temp_path = mkdtemp()
+ self.temp_path = mkdtemp()
? +++++
- copy2('rosie/chamber_of_deputies/tests/fixtures/companies.xz',
- os.path.join(temp_path, settings.COMPANIES_DATASET))
- copy2('rosie/chamber_of_deputies/tests/fixtures/reimbursements.xz', temp_path)
+ fixtures = os.path.join('rosie', 'chamber_of_deputies', 'tests', 'fixtures')
+ copies = (
+ ('companies.xz', Adapter.COMPANIES_DATASET),
+ ('reimbursements.xz', 'reimbursements.xz')
+ )
+ for source, target in copies:
+ copy2(os.path.join(fixtures, source), os.path.join(self.temp_path, target))
- self.subject = Adapter(temp_path)
+ self.subject = Adapter(self.temp_path)
? +++++
+
+ def tearDown(self):
+ shutil.rmtree(self.temp_path)
@patch('rosie.chamber_of_deputies.adapter.CEAPDataset')
@patch('rosie.chamber_of_deputies.adapter.fetch')
- def test_get_performs_a_left_merge_between_reimbursements_and_companies(self, _ceap_dataset, _fetch):
? ----------------
+ def test_get_performs_a_left_merge_between_reimbursements_and_companies(self, fetch, ceap):
? ++++++
- dataset = self.subject.dataset()
- self.assertEqual(5, len(dataset))
+ self.assertEqual(5, len(self.subject.dataset))
? +++++++++++++
- self.assertEqual(1, dataset['legal_entity'].isnull().sum())
+ self.assertEqual(1, self.subject.dataset['legal_entity'].isnull().sum())
? +++++++++++++
|
0575b4345fc21ca537a95866ff2a24d25128c698 | readthedocs/config/find.py | readthedocs/config/find.py | """Helper functions to search files."""
from __future__ import division, print_function, unicode_literals
import os
import re
def find_all(path, filename_regex):
"""Find all files in ``path`` that match ``filename_regex`` regex."""
path = os.path.abspath(path)
for root, dirs, files in os.walk(path, topdown=True):
dirs.sort()
for filename in files:
if re.match(filename_regex, filename):
yield os.path.abspath(os.path.join(root, filename))
def find_one(path, filename_regex):
"""Find the first file in ``path`` that match ``filename_regex`` regex."""
for _path in find_all(path, filename_regex):
return _path
return ''
| """Helper functions to search files."""
from __future__ import division, print_function, unicode_literals
import os
import re
def find_one(path, filename_regex):
"""Find the first file in ``path`` that match ``filename_regex`` regex."""
_path = os.path.abspath(path)
for filename in os.listdir(_path):
if re.match(filename_regex, filename):
return os.path.join(_path, filename)
return ''
| Remove logic for iterating directories to search for config file | Remove logic for iterating directories to search for config file
| Python | mit | rtfd/readthedocs.org,rtfd/readthedocs.org,rtfd/readthedocs.org,rtfd/readthedocs.org | """Helper functions to search files."""
from __future__ import division, print_function, unicode_literals
import os
import re
- def find_all(path, filename_regex):
- """Find all files in ``path`` that match ``filename_regex`` regex."""
- path = os.path.abspath(path)
- for root, dirs, files in os.walk(path, topdown=True):
- dirs.sort()
- for filename in files:
- if re.match(filename_regex, filename):
- yield os.path.abspath(os.path.join(root, filename))
-
-
def find_one(path, filename_regex):
"""Find the first file in ``path`` that match ``filename_regex`` regex."""
- for _path in find_all(path, filename_regex):
- return _path
+ _path = os.path.abspath(path)
+ for filename in os.listdir(_path):
+ if re.match(filename_regex, filename):
+ return os.path.join(_path, filename)
+
return ''
| Remove logic for iterating directories to search for config file | ## Code Before:
"""Helper functions to search files."""
from __future__ import division, print_function, unicode_literals
import os
import re
def find_all(path, filename_regex):
"""Find all files in ``path`` that match ``filename_regex`` regex."""
path = os.path.abspath(path)
for root, dirs, files in os.walk(path, topdown=True):
dirs.sort()
for filename in files:
if re.match(filename_regex, filename):
yield os.path.abspath(os.path.join(root, filename))
def find_one(path, filename_regex):
"""Find the first file in ``path`` that match ``filename_regex`` regex."""
for _path in find_all(path, filename_regex):
return _path
return ''
## Instruction:
Remove logic for iterating directories to search for config file
## Code After:
"""Helper functions to search files."""
from __future__ import division, print_function, unicode_literals
import os
import re
def find_one(path, filename_regex):
"""Find the first file in ``path`` that match ``filename_regex`` regex."""
_path = os.path.abspath(path)
for filename in os.listdir(_path):
if re.match(filename_regex, filename):
return os.path.join(_path, filename)
return ''
| """Helper functions to search files."""
from __future__ import division, print_function, unicode_literals
import os
import re
- def find_all(path, filename_regex):
- """Find all files in ``path`` that match ``filename_regex`` regex."""
- path = os.path.abspath(path)
- for root, dirs, files in os.walk(path, topdown=True):
- dirs.sort()
- for filename in files:
- if re.match(filename_regex, filename):
- yield os.path.abspath(os.path.join(root, filename))
-
-
def find_one(path, filename_regex):
"""Find the first file in ``path`` that match ``filename_regex`` regex."""
- for _path in find_all(path, filename_regex):
- return _path
+ _path = os.path.abspath(path)
+ for filename in os.listdir(_path):
+ if re.match(filename_regex, filename):
+ return os.path.join(_path, filename)
+
return '' |
5ee94e9a74bc4128ed8e7e10a2106ea422f22757 | sandbox/sandbox/polls/serialiser.py | sandbox/sandbox/polls/serialiser.py |
from nap import models, fields, api, serialiser, publisher
from .models import Choice, Poll
class ChoiceSerialiser(models.ModelSerialiser):
class Meta:
model = Choice
exclude = ('poll,')
class PollSerialiser(serialiser.Serialiser):
api_name = 'poll'
question = fields.Field()
published = fields.DateTimeField('pub_date')
choices = fields.ManySerialiserField(serialiser=ChoiceSerialiser())
class PollPublisher(publisher.Publisher):
serialiser = PollSerialiser()
api_name = 'polls'
def get_object_list(self):
return Poll.objects.all()
api.register('api', PollPublisher)
|
from nap import models, fields, api, serialiser, publisher
from .models import Choice, Poll
class ChoiceSerialiser(models.ModelSerialiser):
class Meta:
model = Choice
exclude = ('poll,')
class PollSerialiser(serialiser.Serialiser):
api_name = 'poll'
question = fields.Field()
published = fields.DateTimeField('pub_date')
choices = fields.ManySerialiserField('choices_set.all', serialiser=ChoiceSerialiser())
class PollPublisher(publisher.Publisher):
serialiser = PollSerialiser()
api_name = 'polls'
def get_object_list(self):
return Poll.objects.all()
api.register('api', PollPublisher)
| Add attribute to choices field declaration | Add attribute to choices field declaration
| Python | bsd-3-clause | MarkusH/django-nap,limbera/django-nap |
from nap import models, fields, api, serialiser, publisher
from .models import Choice, Poll
class ChoiceSerialiser(models.ModelSerialiser):
class Meta:
model = Choice
exclude = ('poll,')
class PollSerialiser(serialiser.Serialiser):
api_name = 'poll'
question = fields.Field()
published = fields.DateTimeField('pub_date')
- choices = fields.ManySerialiserField(serialiser=ChoiceSerialiser())
+ choices = fields.ManySerialiserField('choices_set.all', serialiser=ChoiceSerialiser())
class PollPublisher(publisher.Publisher):
serialiser = PollSerialiser()
api_name = 'polls'
def get_object_list(self):
return Poll.objects.all()
api.register('api', PollPublisher)
| Add attribute to choices field declaration | ## Code Before:
from nap import models, fields, api, serialiser, publisher
from .models import Choice, Poll
class ChoiceSerialiser(models.ModelSerialiser):
class Meta:
model = Choice
exclude = ('poll,')
class PollSerialiser(serialiser.Serialiser):
api_name = 'poll'
question = fields.Field()
published = fields.DateTimeField('pub_date')
choices = fields.ManySerialiserField(serialiser=ChoiceSerialiser())
class PollPublisher(publisher.Publisher):
serialiser = PollSerialiser()
api_name = 'polls'
def get_object_list(self):
return Poll.objects.all()
api.register('api', PollPublisher)
## Instruction:
Add attribute to choices field declaration
## Code After:
from nap import models, fields, api, serialiser, publisher
from .models import Choice, Poll
class ChoiceSerialiser(models.ModelSerialiser):
class Meta:
model = Choice
exclude = ('poll,')
class PollSerialiser(serialiser.Serialiser):
api_name = 'poll'
question = fields.Field()
published = fields.DateTimeField('pub_date')
choices = fields.ManySerialiserField('choices_set.all', serialiser=ChoiceSerialiser())
class PollPublisher(publisher.Publisher):
serialiser = PollSerialiser()
api_name = 'polls'
def get_object_list(self):
return Poll.objects.all()
api.register('api', PollPublisher)
|
from nap import models, fields, api, serialiser, publisher
from .models import Choice, Poll
class ChoiceSerialiser(models.ModelSerialiser):
class Meta:
model = Choice
exclude = ('poll,')
class PollSerialiser(serialiser.Serialiser):
api_name = 'poll'
question = fields.Field()
published = fields.DateTimeField('pub_date')
- choices = fields.ManySerialiserField(serialiser=ChoiceSerialiser())
+ choices = fields.ManySerialiserField('choices_set.all', serialiser=ChoiceSerialiser())
? +++++++++++++++++++
class PollPublisher(publisher.Publisher):
serialiser = PollSerialiser()
api_name = 'polls'
def get_object_list(self):
return Poll.objects.all()
api.register('api', PollPublisher) |
fcfa0b96226ba8b8d2bbd62365c2cab3f6e42d99 | salt/runners/state.py | salt/runners/state.py | '''
Execute overstate functions
'''
# Import Salt libs
import salt.overstate
import salt.output
def over(env='base', os_fn=None):
'''
Execute an overstate sequence to orchestrate the executing of states
over a group of systems
'''
overstate = salt.overstate.OverState(__opts__, env, os_fn)
over_run = overstate.stages()
salt.output.display_output(over_run, 'pprint', opts=__opts__)
return over_run
def show_stages(env='base', os_fn=None):
'''
Display the stage data to be executed
'''
overstate = salt.overstate.OverState(__opts__, env, os_fn)
salt.output.display_output(overstate.over, 'pprint', opts=__opts__)
return overstate.over
| '''
Execute overstate functions
'''
# Import Salt libs
import salt.overstate
import salt.output
def over(env='base', os_fn=None):
'''
Execute an overstate sequence to orchestrate the executing of states
over a group of systems
'''
overstate = salt.overstate.OverState(__opts__, env, os_fn)
overstate.stages()
salt.output.display_output(overstate.over_run, 'pprint', opts=__opts__)
return overstate.over_run
def show_stages(env='base', os_fn=None):
'''
Display the stage data to be executed
'''
overstate = salt.overstate.OverState(__opts__, env, os_fn)
salt.output.display_output(overstate.over, 'pprint', opts=__opts__)
return overstate.over
| Print and return the correct data | Print and return the correct data
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | '''
Execute overstate functions
'''
# Import Salt libs
import salt.overstate
import salt.output
def over(env='base', os_fn=None):
'''
Execute an overstate sequence to orchestrate the executing of states
over a group of systems
'''
overstate = salt.overstate.OverState(__opts__, env, os_fn)
- over_run = overstate.stages()
+ overstate.stages()
- salt.output.display_output(over_run, 'pprint', opts=__opts__)
+ salt.output.display_output(overstate.over_run, 'pprint', opts=__opts__)
- return over_run
+ return overstate.over_run
def show_stages(env='base', os_fn=None):
'''
Display the stage data to be executed
'''
overstate = salt.overstate.OverState(__opts__, env, os_fn)
salt.output.display_output(overstate.over, 'pprint', opts=__opts__)
return overstate.over
| Print and return the correct data | ## Code Before:
'''
Execute overstate functions
'''
# Import Salt libs
import salt.overstate
import salt.output
def over(env='base', os_fn=None):
'''
Execute an overstate sequence to orchestrate the executing of states
over a group of systems
'''
overstate = salt.overstate.OverState(__opts__, env, os_fn)
over_run = overstate.stages()
salt.output.display_output(over_run, 'pprint', opts=__opts__)
return over_run
def show_stages(env='base', os_fn=None):
'''
Display the stage data to be executed
'''
overstate = salt.overstate.OverState(__opts__, env, os_fn)
salt.output.display_output(overstate.over, 'pprint', opts=__opts__)
return overstate.over
## Instruction:
Print and return the correct data
## Code After:
'''
Execute overstate functions
'''
# Import Salt libs
import salt.overstate
import salt.output
def over(env='base', os_fn=None):
'''
Execute an overstate sequence to orchestrate the executing of states
over a group of systems
'''
overstate = salt.overstate.OverState(__opts__, env, os_fn)
overstate.stages()
salt.output.display_output(overstate.over_run, 'pprint', opts=__opts__)
return overstate.over_run
def show_stages(env='base', os_fn=None):
'''
Display the stage data to be executed
'''
overstate = salt.overstate.OverState(__opts__, env, os_fn)
salt.output.display_output(overstate.over, 'pprint', opts=__opts__)
return overstate.over
| '''
Execute overstate functions
'''
# Import Salt libs
import salt.overstate
import salt.output
def over(env='base', os_fn=None):
'''
Execute an overstate sequence to orchestrate the executing of states
over a group of systems
'''
overstate = salt.overstate.OverState(__opts__, env, os_fn)
- over_run = overstate.stages()
? -----------
+ overstate.stages()
- salt.output.display_output(over_run, 'pprint', opts=__opts__)
+ salt.output.display_output(overstate.over_run, 'pprint', opts=__opts__)
? ++++++++++
- return over_run
+ return overstate.over_run
? ++++++++++
def show_stages(env='base', os_fn=None):
'''
Display the stage data to be executed
'''
overstate = salt.overstate.OverState(__opts__, env, os_fn)
salt.output.display_output(overstate.over, 'pprint', opts=__opts__)
return overstate.over |
a69e8d0d179f12fd42eadd85eca8e0c968d67c91 | tests/runTests.py | tests/runTests.py | import os
import os.path
import configparser
import shutil
import subprocess
# Setup
print("Setting up...")
if os.path.isfile("../halite.ini"):
shutil.copyfile("../halite.ini", "temp.ini")
shutil.copyfile("tests.ini", "../halite.ini")
parser = configparser.ConfigParser()
parser.read("../halite.ini")
# Website tests
print("Beginning website backend tests")
os.system("mysql -u "+parser["database"]["username"]+" -p"+parser["database"]["password"]+" < ../website/sql/Database.sql")
subprocess.call(["phpunit", "--stderr", "website/"])
# Environment tests.
print(subprocess.Popen('cd environment; python3 testenv.py', stdout=subprocess.PIPE, shell = True).stdout.read().decode('utf-8'))
# Tear down
print("Almost done...")
if os.path.isfile("../temp.ini"):
shutil.copyfile("temp.ini", "../halite.ini")
| import os
import os.path
import configparser
import shutil
import subprocess
# Setup
print("Setting up...")
if os.path.isfile("../halite.ini"):
shutil.copyfile("../halite.ini", "temp.ini")
shutil.copyfile("tests.ini", "../halite.ini")
parser = configparser.ConfigParser()
parser.read("../halite.ini")
# Website tests
print("Beginning website backend tests")
passwordField = "" if parser["database"]["password"] == "" else "-p"+parser["database"]["password"]
os.system("mysql -u "+parser["database"]["username"]+" "+passwordField+" < ../website/sql/Database.sql")
subprocess.call(["phpunit", "--stderr", "website/"])
# Environment tests.
print(subprocess.Popen('cd environment; python3 testenv.py', stdout=subprocess.PIPE, shell = True).stdout.read().decode('utf-8'))
# Tear down
print("Almost done...")
if os.path.isfile("../temp.ini"):
shutil.copyfile("temp.ini", "../halite.ini")
| Make test runner work with blank mysql password | Make test runner work with blank mysql password
| Python | mit | HaliteChallenge/Halite-II,yangle/HaliteIO,yangle/HaliteIO,HaliteChallenge/Halite,HaliteChallenge/Halite,yangle/HaliteIO,lanyudhy/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite,yangle/HaliteIO,lanyudhy/Halite-II,HaliteChallenge/Halite-II,yangle/HaliteIO,lanyudhy/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite,HaliteChallenge/Halite-II,lanyudhy/Halite-II,HaliteChallenge/Halite,lanyudhy/Halite-II,yangle/HaliteIO,lanyudhy/Halite-II,yangle/HaliteIO,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite,HaliteChallenge/Halite,lanyudhy/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite,HaliteChallenge/Halite-II,yangle/HaliteIO,HaliteChallenge/Halite-II,yangle/HaliteIO,yangle/HaliteIO,yangle/HaliteIO,lanyudhy/Halite-II,HaliteChallenge/Halite,HaliteChallenge/Halite-II,HaliteChallenge/Halite,HaliteChallenge/Halite-II,yangle/HaliteIO,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite,HaliteChallenge/Halite-II,lanyudhy/Halite-II,HaliteChallenge/Halite,lanyudhy/Halite-II,lanyudhy/Halite-II,HaliteChallenge/Halite-II | import os
import os.path
import configparser
import shutil
import subprocess
# Setup
print("Setting up...")
if os.path.isfile("../halite.ini"):
shutil.copyfile("../halite.ini", "temp.ini")
shutil.copyfile("tests.ini", "../halite.ini")
parser = configparser.ConfigParser()
parser.read("../halite.ini")
# Website tests
print("Beginning website backend tests")
+ passwordField = "" if parser["database"]["password"] == "" else "-p"+parser["database"]["password"]
- os.system("mysql -u "+parser["database"]["username"]+" -p"+parser["database"]["password"]+" < ../website/sql/Database.sql")
+ os.system("mysql -u "+parser["database"]["username"]+" "+passwordField+" < ../website/sql/Database.sql")
subprocess.call(["phpunit", "--stderr", "website/"])
# Environment tests.
print(subprocess.Popen('cd environment; python3 testenv.py', stdout=subprocess.PIPE, shell = True).stdout.read().decode('utf-8'))
# Tear down
print("Almost done...")
if os.path.isfile("../temp.ini"):
shutil.copyfile("temp.ini", "../halite.ini")
| Make test runner work with blank mysql password | ## Code Before:
import os
import os.path
import configparser
import shutil
import subprocess
# Setup
print("Setting up...")
if os.path.isfile("../halite.ini"):
shutil.copyfile("../halite.ini", "temp.ini")
shutil.copyfile("tests.ini", "../halite.ini")
parser = configparser.ConfigParser()
parser.read("../halite.ini")
# Website tests
print("Beginning website backend tests")
os.system("mysql -u "+parser["database"]["username"]+" -p"+parser["database"]["password"]+" < ../website/sql/Database.sql")
subprocess.call(["phpunit", "--stderr", "website/"])
# Environment tests.
print(subprocess.Popen('cd environment; python3 testenv.py', stdout=subprocess.PIPE, shell = True).stdout.read().decode('utf-8'))
# Tear down
print("Almost done...")
if os.path.isfile("../temp.ini"):
shutil.copyfile("temp.ini", "../halite.ini")
## Instruction:
Make test runner work with blank mysql password
## Code After:
import os
import os.path
import configparser
import shutil
import subprocess
# Setup
print("Setting up...")
if os.path.isfile("../halite.ini"):
shutil.copyfile("../halite.ini", "temp.ini")
shutil.copyfile("tests.ini", "../halite.ini")
parser = configparser.ConfigParser()
parser.read("../halite.ini")
# Website tests
print("Beginning website backend tests")
passwordField = "" if parser["database"]["password"] == "" else "-p"+parser["database"]["password"]
os.system("mysql -u "+parser["database"]["username"]+" "+passwordField+" < ../website/sql/Database.sql")
subprocess.call(["phpunit", "--stderr", "website/"])
# Environment tests.
print(subprocess.Popen('cd environment; python3 testenv.py', stdout=subprocess.PIPE, shell = True).stdout.read().decode('utf-8'))
# Tear down
print("Almost done...")
if os.path.isfile("../temp.ini"):
shutil.copyfile("temp.ini", "../halite.ini")
| import os
import os.path
import configparser
import shutil
import subprocess
# Setup
print("Setting up...")
if os.path.isfile("../halite.ini"):
shutil.copyfile("../halite.ini", "temp.ini")
shutil.copyfile("tests.ini", "../halite.ini")
parser = configparser.ConfigParser()
parser.read("../halite.ini")
# Website tests
print("Beginning website backend tests")
+ passwordField = "" if parser["database"]["password"] == "" else "-p"+parser["database"]["password"]
- os.system("mysql -u "+parser["database"]["username"]+" -p"+parser["database"]["password"]+" < ../website/sql/Database.sql")
? -- -------------------- ^^
+ os.system("mysql -u "+parser["database"]["username"]+" "+passwordField+" < ../website/sql/Database.sql")
? ^^^^^
subprocess.call(["phpunit", "--stderr", "website/"])
# Environment tests.
print(subprocess.Popen('cd environment; python3 testenv.py', stdout=subprocess.PIPE, shell = True).stdout.read().decode('utf-8'))
# Tear down
print("Almost done...")
if os.path.isfile("../temp.ini"):
shutil.copyfile("temp.ini", "../halite.ini") |
de3809a00703c5eaaaec856b152a2418debbb6c6 | plugins/Tools/MirrorTool/__init__.py | plugins/Tools/MirrorTool/__init__.py | from . import MirrorTool
def getMetaData():
return {
'type': 'tool',
'plugin': {
'name': 'Mirror Tool'
},
'tool': {
'name': 'Mirror',
'description': 'Mirror Object'
},
}
def register(app):
return MirrorTool.MirrorTool()
| from . import MirrorTool
def getMetaData():
return {
'type': 'tool',
'plugin': {
'name': 'Mirror Tool'
},
'tool': {
'name': 'Mirror',
'description': 'Mirror Object',
'icon': 'mirror.png'
},
}
def register(app):
return MirrorTool.MirrorTool()
| Use the right icon for the mirror tool | Use the right icon for the mirror tool
| Python | agpl-3.0 | onitake/Uranium,onitake/Uranium | from . import MirrorTool
def getMetaData():
return {
'type': 'tool',
'plugin': {
'name': 'Mirror Tool'
},
'tool': {
'name': 'Mirror',
- 'description': 'Mirror Object'
+ 'description': 'Mirror Object',
+ 'icon': 'mirror.png'
},
}
def register(app):
return MirrorTool.MirrorTool()
| Use the right icon for the mirror tool | ## Code Before:
from . import MirrorTool
def getMetaData():
return {
'type': 'tool',
'plugin': {
'name': 'Mirror Tool'
},
'tool': {
'name': 'Mirror',
'description': 'Mirror Object'
},
}
def register(app):
return MirrorTool.MirrorTool()
## Instruction:
Use the right icon for the mirror tool
## Code After:
from . import MirrorTool
def getMetaData():
return {
'type': 'tool',
'plugin': {
'name': 'Mirror Tool'
},
'tool': {
'name': 'Mirror',
'description': 'Mirror Object',
'icon': 'mirror.png'
},
}
def register(app):
return MirrorTool.MirrorTool()
| from . import MirrorTool
def getMetaData():
return {
'type': 'tool',
'plugin': {
'name': 'Mirror Tool'
},
'tool': {
'name': 'Mirror',
- 'description': 'Mirror Object'
+ 'description': 'Mirror Object',
? +
+ 'icon': 'mirror.png'
},
}
def register(app):
return MirrorTool.MirrorTool() |
43e4e154df6274ea80b5d495a682c2d17cdb178d | cla_backend/apps/knowledgebase/tests/test_events.py | cla_backend/apps/knowledgebase/tests/test_events.py | from django.test import TestCase
from cla_eventlog.tests.base import EventTestCaseMixin
class AlternativeHelpEventTestCase(EventTestCaseMixin, TestCase):
EVENT_KEY = 'alternative_help'
def test_assign_alternative_help(self):
self._test_process_with_expicit_code(
['COSPF', 'IRKB']
)
| from django.test import TestCase
from cla_eventlog.tests.base import EventTestCaseMixin
class AlternativeHelpEventTestCase(EventTestCaseMixin, TestCase):
EVENT_KEY = 'alternative_help'
def test_assign_alternative_help(self):
self._test_process_with_expicit_code(
['COSPF', 'IRKB', 'SPFN', 'SPFM']
)
| Add new outcome codes to tests | Add new outcome codes to tests
| Python | mit | ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend | from django.test import TestCase
from cla_eventlog.tests.base import EventTestCaseMixin
class AlternativeHelpEventTestCase(EventTestCaseMixin, TestCase):
EVENT_KEY = 'alternative_help'
def test_assign_alternative_help(self):
self._test_process_with_expicit_code(
- ['COSPF', 'IRKB']
+ ['COSPF', 'IRKB', 'SPFN', 'SPFM']
)
| Add new outcome codes to tests | ## Code Before:
from django.test import TestCase
from cla_eventlog.tests.base import EventTestCaseMixin
class AlternativeHelpEventTestCase(EventTestCaseMixin, TestCase):
EVENT_KEY = 'alternative_help'
def test_assign_alternative_help(self):
self._test_process_with_expicit_code(
['COSPF', 'IRKB']
)
## Instruction:
Add new outcome codes to tests
## Code After:
from django.test import TestCase
from cla_eventlog.tests.base import EventTestCaseMixin
class AlternativeHelpEventTestCase(EventTestCaseMixin, TestCase):
EVENT_KEY = 'alternative_help'
def test_assign_alternative_help(self):
self._test_process_with_expicit_code(
['COSPF', 'IRKB', 'SPFN', 'SPFM']
)
| from django.test import TestCase
from cla_eventlog.tests.base import EventTestCaseMixin
class AlternativeHelpEventTestCase(EventTestCaseMixin, TestCase):
EVENT_KEY = 'alternative_help'
def test_assign_alternative_help(self):
self._test_process_with_expicit_code(
- ['COSPF', 'IRKB']
+ ['COSPF', 'IRKB', 'SPFN', 'SPFM']
? ++++++++++++++++
) |
ef4f85808c061f81f123fb91b52fd4c8eb3e32b6 | peel/api.py | peel/api.py | from tastypie.resources import ModelResource
from tastypie.authorization import Authorization
from peel.models import Article
class ArticleResource(ModelResource):
def dehydrate_tags(self, bundle):
# Needed to properly serialize tags into a valid JSON list of strings.
return bundle.obj.tags
def build_filters(self, filters=None):
"""
Add support for exclude filtering
See https://github.com/toastdriven/django-tastypie/issues/524
"""
if not filters:
return filters
applicable_filters = {}
# Separate out normal filters and the __ne operations.
# Normal filtering
filter_params = dict([(x, filters[x]) for x in filter(lambda x: not x.endswith('__ne'), filters)])
applicable_filters['filter'] = super(type(self), self).build_filters(filter_params)
# Exclude filtering
exclude_params = dict([(x[:-4], filters[x]) for x in filter(lambda x: x.endswith('__ne'), filters)])
applicable_filters['exclude'] = super(type(self), self).build_filters(exclude_params)
return applicable_filters
def apply_filters(self, request, applicable_filters):
"""
Add support for exclude filtering
See https://github.com/toastdriven/django-tastypie/issues/524
"""
objects = self.get_object_list(request)
# Distinguish between normal filters and exclude filters
f = applicable_filters.get('filter')
if f:
objects = objects.filter(**f)
e = applicable_filters.get('exclude')
if e:
for exclusion_filter, value in e.items():
objects = objects.exclude(**{exclusion_filter: value})
return objects
class Meta:
queryset = Article.objects.all()
ordering = ['created_at', 'updated_at']
filtering = {
'status': ('exact', 'ne'),
'created_at': ('lt', 'gt'),
'updated_at': ('lt', 'gt'),
}
authorization = Authorization()
always_return_data = True
| from tastypie.resources import ModelResource
from tastypie.authorization import Authorization
from peel.models import Article
class ArticleResource(ModelResource):
def dehydrate_tags(self, bundle):
# Needed to properly serialize tags into a valid JSON list of strings.
return bundle.obj.tags
class Meta:
queryset = Article.objects.all()
ordering = ['created_at', 'updated_at']
filtering = {
'status': ('exact', 'in'),
'created_at': ('lt', 'gt'),
'updated_at': ('lt', 'gt'),
}
authorization = Authorization()
always_return_data = True
| Remove exclude filtering support from API | Remove exclude filtering support from API
I'll just use 'in' instead...
Reverts fa099b12f8a4c4d4aa2eb2954c6c315f3a79ea84.
| Python | mit | imiric/peel,imiric/peel,imiric/peel | from tastypie.resources import ModelResource
from tastypie.authorization import Authorization
from peel.models import Article
class ArticleResource(ModelResource):
def dehydrate_tags(self, bundle):
# Needed to properly serialize tags into a valid JSON list of strings.
return bundle.obj.tags
- def build_filters(self, filters=None):
- """
- Add support for exclude filtering
- See https://github.com/toastdriven/django-tastypie/issues/524
- """
- if not filters:
- return filters
-
- applicable_filters = {}
-
- # Separate out normal filters and the __ne operations.
- # Normal filtering
- filter_params = dict([(x, filters[x]) for x in filter(lambda x: not x.endswith('__ne'), filters)])
- applicable_filters['filter'] = super(type(self), self).build_filters(filter_params)
-
- # Exclude filtering
- exclude_params = dict([(x[:-4], filters[x]) for x in filter(lambda x: x.endswith('__ne'), filters)])
- applicable_filters['exclude'] = super(type(self), self).build_filters(exclude_params)
-
- return applicable_filters
-
- def apply_filters(self, request, applicable_filters):
- """
- Add support for exclude filtering
- See https://github.com/toastdriven/django-tastypie/issues/524
- """
- objects = self.get_object_list(request)
-
- # Distinguish between normal filters and exclude filters
- f = applicable_filters.get('filter')
- if f:
- objects = objects.filter(**f)
- e = applicable_filters.get('exclude')
- if e:
- for exclusion_filter, value in e.items():
- objects = objects.exclude(**{exclusion_filter: value})
- return objects
-
class Meta:
queryset = Article.objects.all()
ordering = ['created_at', 'updated_at']
filtering = {
- 'status': ('exact', 'ne'),
+ 'status': ('exact', 'in'),
'created_at': ('lt', 'gt'),
'updated_at': ('lt', 'gt'),
}
authorization = Authorization()
always_return_data = True
| Remove exclude filtering support from API | ## Code Before:
from tastypie.resources import ModelResource
from tastypie.authorization import Authorization
from peel.models import Article
class ArticleResource(ModelResource):
def dehydrate_tags(self, bundle):
# Needed to properly serialize tags into a valid JSON list of strings.
return bundle.obj.tags
def build_filters(self, filters=None):
"""
Add support for exclude filtering
See https://github.com/toastdriven/django-tastypie/issues/524
"""
if not filters:
return filters
applicable_filters = {}
# Separate out normal filters and the __ne operations.
# Normal filtering
filter_params = dict([(x, filters[x]) for x in filter(lambda x: not x.endswith('__ne'), filters)])
applicable_filters['filter'] = super(type(self), self).build_filters(filter_params)
# Exclude filtering
exclude_params = dict([(x[:-4], filters[x]) for x in filter(lambda x: x.endswith('__ne'), filters)])
applicable_filters['exclude'] = super(type(self), self).build_filters(exclude_params)
return applicable_filters
def apply_filters(self, request, applicable_filters):
"""
Add support for exclude filtering
See https://github.com/toastdriven/django-tastypie/issues/524
"""
objects = self.get_object_list(request)
# Distinguish between normal filters and exclude filters
f = applicable_filters.get('filter')
if f:
objects = objects.filter(**f)
e = applicable_filters.get('exclude')
if e:
for exclusion_filter, value in e.items():
objects = objects.exclude(**{exclusion_filter: value})
return objects
class Meta:
queryset = Article.objects.all()
ordering = ['created_at', 'updated_at']
filtering = {
'status': ('exact', 'ne'),
'created_at': ('lt', 'gt'),
'updated_at': ('lt', 'gt'),
}
authorization = Authorization()
always_return_data = True
## Instruction:
Remove exclude filtering support from API
## Code After:
from tastypie.resources import ModelResource
from tastypie.authorization import Authorization
from peel.models import Article
class ArticleResource(ModelResource):
def dehydrate_tags(self, bundle):
# Needed to properly serialize tags into a valid JSON list of strings.
return bundle.obj.tags
class Meta:
queryset = Article.objects.all()
ordering = ['created_at', 'updated_at']
filtering = {
'status': ('exact', 'in'),
'created_at': ('lt', 'gt'),
'updated_at': ('lt', 'gt'),
}
authorization = Authorization()
always_return_data = True
| from tastypie.resources import ModelResource
from tastypie.authorization import Authorization
from peel.models import Article
class ArticleResource(ModelResource):
def dehydrate_tags(self, bundle):
# Needed to properly serialize tags into a valid JSON list of strings.
return bundle.obj.tags
- def build_filters(self, filters=None):
- """
- Add support for exclude filtering
- See https://github.com/toastdriven/django-tastypie/issues/524
- """
- if not filters:
- return filters
-
- applicable_filters = {}
-
- # Separate out normal filters and the __ne operations.
- # Normal filtering
- filter_params = dict([(x, filters[x]) for x in filter(lambda x: not x.endswith('__ne'), filters)])
- applicable_filters['filter'] = super(type(self), self).build_filters(filter_params)
-
- # Exclude filtering
- exclude_params = dict([(x[:-4], filters[x]) for x in filter(lambda x: x.endswith('__ne'), filters)])
- applicable_filters['exclude'] = super(type(self), self).build_filters(exclude_params)
-
- return applicable_filters
-
- def apply_filters(self, request, applicable_filters):
- """
- Add support for exclude filtering
- See https://github.com/toastdriven/django-tastypie/issues/524
- """
- objects = self.get_object_list(request)
-
- # Distinguish between normal filters and exclude filters
- f = applicable_filters.get('filter')
- if f:
- objects = objects.filter(**f)
- e = applicable_filters.get('exclude')
- if e:
- for exclusion_filter, value in e.items():
- objects = objects.exclude(**{exclusion_filter: value})
- return objects
-
class Meta:
queryset = Article.objects.all()
ordering = ['created_at', 'updated_at']
filtering = {
- 'status': ('exact', 'ne'),
? -
+ 'status': ('exact', 'in'),
? +
'created_at': ('lt', 'gt'),
'updated_at': ('lt', 'gt'),
}
authorization = Authorization()
always_return_data = True |
ab1a2982b6a44bfcfcaff5a3469f2d85f56a86a4 | src/cli/_dbus/_manager.py | src/cli/_dbus/_manager.py |
class Manager(object):
"""
Manager interface.
"""
_INTERFACE_NAME = 'org.storage.stratis1.Manager'
def __init__(self, dbus_object):
"""
Initializer.
:param dbus_object: the dbus object
"""
self._dbus_object = dbus_object
def CreatePool(self, pool_name, devices, num_devices):
"""
Create a pool.
:param str pool_name: the pool name
:param devices: the component devices
:type devices: sequence of str
"""
return self._dbus_object.CreatePool(
pool_name,
devices,
num_devices,
dbus_interface=self._INTERFACE_NAME,
)
def DestroyPool(self, pool_name):
"""
Destroy a pool.
:param str pool_name: the name of the pool
"""
return self._dbus_object.DestroyPool(
pool_name,
dbus_interface=self._INTERFACE_NAME
)
def ListPools(self):
"""
List all pools.
"""
return self._dbus_object.ListPools(dbus_interface=self._INTERFACE_NAME)
|
from ._properties import Properties
class Manager(object):
"""
Manager interface.
"""
_INTERFACE_NAME = 'org.storage.stratis1.Manager'
def __init__(self, dbus_object):
"""
Initializer.
:param dbus_object: the dbus object
"""
self._dbus_object = dbus_object
def CreatePool(self, pool_name, devices, num_devices):
"""
Create a pool.
:param str pool_name: the pool name
:param devices: the component devices
:type devices: sequence of str
"""
return self._dbus_object.CreatePool(
pool_name,
devices,
num_devices,
dbus_interface=self._INTERFACE_NAME,
)
def DestroyPool(self, pool_name):
"""
Destroy a pool.
:param str pool_name: the name of the pool
"""
return self._dbus_object.DestroyPool(
pool_name,
dbus_interface=self._INTERFACE_NAME
)
def ListPools(self):
"""
List all pools.
"""
return self._dbus_object.ListPools(dbus_interface=self._INTERFACE_NAME)
@property
def Version(self):
"""
Stratisd Version getter.
:rtype: String
"""
return Properties(self._dbus_object).Get(
self._INTERFACE_NAME,
'Version'
)
@property
def LogLevel(self):
"""
Stratisd LogLevel getter.
:rtype: String
"""
return Properties(self._dbus_object).Get(
self._INTERFACE_NAME,
'LogLevel'
)
@LogLevel.setter
def LogLevel(self, value):
"""
Stratisd LogLevel setter.
:param str value: the value to set
"""
return Properties(self._dbus_object).Set(
self._INTERFACE_NAME,
'LogLevel',
value
)
| Use Properties interface to get Manager properties. | Use Properties interface to get Manager properties.
Signed-off-by: mulhern <7b51bcf507bcd7afb72bf8663752c0ddbeb517f6@redhat.com>
| Python | apache-2.0 | stratis-storage/stratis-cli,stratis-storage/stratis-cli | +
+ from ._properties import Properties
+
class Manager(object):
"""
Manager interface.
"""
_INTERFACE_NAME = 'org.storage.stratis1.Manager'
def __init__(self, dbus_object):
"""
Initializer.
:param dbus_object: the dbus object
"""
self._dbus_object = dbus_object
def CreatePool(self, pool_name, devices, num_devices):
"""
Create a pool.
:param str pool_name: the pool name
:param devices: the component devices
:type devices: sequence of str
"""
return self._dbus_object.CreatePool(
pool_name,
devices,
num_devices,
dbus_interface=self._INTERFACE_NAME,
)
def DestroyPool(self, pool_name):
"""
Destroy a pool.
:param str pool_name: the name of the pool
"""
return self._dbus_object.DestroyPool(
pool_name,
dbus_interface=self._INTERFACE_NAME
)
def ListPools(self):
"""
List all pools.
"""
return self._dbus_object.ListPools(dbus_interface=self._INTERFACE_NAME)
+ @property
+ def Version(self):
+ """
+ Stratisd Version getter.
+
+ :rtype: String
+ """
+ return Properties(self._dbus_object).Get(
+ self._INTERFACE_NAME,
+ 'Version'
+ )
+
+ @property
+ def LogLevel(self):
+ """
+ Stratisd LogLevel getter.
+
+ :rtype: String
+ """
+ return Properties(self._dbus_object).Get(
+ self._INTERFACE_NAME,
+ 'LogLevel'
+ )
+
+ @LogLevel.setter
+ def LogLevel(self, value):
+ """
+ Stratisd LogLevel setter.
+
+ :param str value: the value to set
+ """
+ return Properties(self._dbus_object).Set(
+ self._INTERFACE_NAME,
+ 'LogLevel',
+ value
+ )
+ | Use Properties interface to get Manager properties. | ## Code Before:
class Manager(object):
"""
Manager interface.
"""
_INTERFACE_NAME = 'org.storage.stratis1.Manager'
def __init__(self, dbus_object):
"""
Initializer.
:param dbus_object: the dbus object
"""
self._dbus_object = dbus_object
def CreatePool(self, pool_name, devices, num_devices):
"""
Create a pool.
:param str pool_name: the pool name
:param devices: the component devices
:type devices: sequence of str
"""
return self._dbus_object.CreatePool(
pool_name,
devices,
num_devices,
dbus_interface=self._INTERFACE_NAME,
)
def DestroyPool(self, pool_name):
"""
Destroy a pool.
:param str pool_name: the name of the pool
"""
return self._dbus_object.DestroyPool(
pool_name,
dbus_interface=self._INTERFACE_NAME
)
def ListPools(self):
"""
List all pools.
"""
return self._dbus_object.ListPools(dbus_interface=self._INTERFACE_NAME)
## Instruction:
Use Properties interface to get Manager properties.
## Code After:
from ._properties import Properties
class Manager(object):
"""
Manager interface.
"""
_INTERFACE_NAME = 'org.storage.stratis1.Manager'
def __init__(self, dbus_object):
"""
Initializer.
:param dbus_object: the dbus object
"""
self._dbus_object = dbus_object
def CreatePool(self, pool_name, devices, num_devices):
"""
Create a pool.
:param str pool_name: the pool name
:param devices: the component devices
:type devices: sequence of str
"""
return self._dbus_object.CreatePool(
pool_name,
devices,
num_devices,
dbus_interface=self._INTERFACE_NAME,
)
def DestroyPool(self, pool_name):
"""
Destroy a pool.
:param str pool_name: the name of the pool
"""
return self._dbus_object.DestroyPool(
pool_name,
dbus_interface=self._INTERFACE_NAME
)
def ListPools(self):
"""
List all pools.
"""
return self._dbus_object.ListPools(dbus_interface=self._INTERFACE_NAME)
@property
def Version(self):
"""
Stratisd Version getter.
:rtype: String
"""
return Properties(self._dbus_object).Get(
self._INTERFACE_NAME,
'Version'
)
@property
def LogLevel(self):
"""
Stratisd LogLevel getter.
:rtype: String
"""
return Properties(self._dbus_object).Get(
self._INTERFACE_NAME,
'LogLevel'
)
@LogLevel.setter
def LogLevel(self, value):
"""
Stratisd LogLevel setter.
:param str value: the value to set
"""
return Properties(self._dbus_object).Set(
self._INTERFACE_NAME,
'LogLevel',
value
)
| +
+ from ._properties import Properties
+
class Manager(object):
"""
Manager interface.
"""
_INTERFACE_NAME = 'org.storage.stratis1.Manager'
def __init__(self, dbus_object):
"""
Initializer.
:param dbus_object: the dbus object
"""
self._dbus_object = dbus_object
def CreatePool(self, pool_name, devices, num_devices):
"""
Create a pool.
:param str pool_name: the pool name
:param devices: the component devices
:type devices: sequence of str
"""
return self._dbus_object.CreatePool(
pool_name,
devices,
num_devices,
dbus_interface=self._INTERFACE_NAME,
)
def DestroyPool(self, pool_name):
"""
Destroy a pool.
:param str pool_name: the name of the pool
"""
return self._dbus_object.DestroyPool(
pool_name,
dbus_interface=self._INTERFACE_NAME
)
def ListPools(self):
"""
List all pools.
"""
return self._dbus_object.ListPools(dbus_interface=self._INTERFACE_NAME)
+
+ @property
+ def Version(self):
+ """
+ Stratisd Version getter.
+
+ :rtype: String
+ """
+ return Properties(self._dbus_object).Get(
+ self._INTERFACE_NAME,
+ 'Version'
+ )
+
+ @property
+ def LogLevel(self):
+ """
+ Stratisd LogLevel getter.
+
+ :rtype: String
+ """
+ return Properties(self._dbus_object).Get(
+ self._INTERFACE_NAME,
+ 'LogLevel'
+ )
+
+ @LogLevel.setter
+ def LogLevel(self, value):
+ """
+ Stratisd LogLevel setter.
+
+ :param str value: the value to set
+ """
+ return Properties(self._dbus_object).Set(
+ self._INTERFACE_NAME,
+ 'LogLevel',
+ value
+ ) |
17e26fa55e70de657d52e340cb6b66691310a663 | bettertexts/forms.py | bettertexts/forms.py | from django_comments.forms import CommentForm
from django import forms
from django.utils.translation import ugettext_lazy as _
from bettertexts.models import TextComment
class TextCommentForm(CommentForm):
def __init__(self, *args, **kwargs):
super(TextCommentForm, self).__init__(*args, **kwargs)
self.fields['name'].label = _("Name")
self.fields['name'].required = True
self.fields['email'].label = _("Email address")
self.fields['email'].required = True
self.fields['comment'].label = _('Comment')
self.fields['comment'].required = True
self.fields['url'].widget = forms.HiddenInput()
inform = forms.BooleanField(required=False,
label=_('Keep me informed'),
widget=forms.CheckboxInput)
involved = forms.BooleanField(required=False,
label=_('Keep me involved'),
widget=forms.CheckboxInput)
class Meta:
fields = ['name', 'email', 'inform', 'comment']
def get_comment_model(self):
"""
override to provide a custom comment model.
"""
return TextComment
def get_comment_create_data(self):
"""
Override to add inform field
"""
data = super(TextCommentForm, self).get_comment_create_data()
data.update({'inform': True})
return data
| from django_comments.forms import CommentForm
from django import forms
from django.utils.translation import ugettext_lazy as _
from bettertexts.models import TextComment
class TextCommentForm(CommentForm):
def __init__(self, *args, **kwargs):
super(TextCommentForm, self).__init__(*args, **kwargs)
self.fields['name'].label = _("Name")
self.fields['name'].required = True
self.fields['email'].label = _("Email address")
self.fields['email'].required = True
self.fields['comment'].label = _('Comment')
self.fields['comment'].required = True
self.fields['url'].widget = forms.HiddenInput()
inform = forms.BooleanField(required=False,
label=_('Keep me informed'),
widget=forms.CheckboxInput)
involved = forms.BooleanField(required=False,
label=_('Keep me involved'),
widget=forms.CheckboxInput)
class Meta:
fields = ['name', 'email', 'inform', 'comment']
def get_comment_model(self):
"""
override to provide a custom comment model.
"""
return TextComment
def get_comment_create_data(self):
"""
Override to add inform and involved field
"""
data = super(TextCommentForm, self).get_comment_create_data()
data.update({'inform': self.cleaned_data["inform"],
'involved': self.cleaned_data["involved"]})
return data
| Fix checkboxes inform and involved | CL011: Fix checkboxes inform and involved
| Python | mit | citizenline/citizenline,citizenline/citizenline,citizenline/citizenline,citizenline/citizenline | from django_comments.forms import CommentForm
from django import forms
from django.utils.translation import ugettext_lazy as _
from bettertexts.models import TextComment
class TextCommentForm(CommentForm):
def __init__(self, *args, **kwargs):
super(TextCommentForm, self).__init__(*args, **kwargs)
self.fields['name'].label = _("Name")
self.fields['name'].required = True
self.fields['email'].label = _("Email address")
self.fields['email'].required = True
self.fields['comment'].label = _('Comment')
self.fields['comment'].required = True
self.fields['url'].widget = forms.HiddenInput()
inform = forms.BooleanField(required=False,
label=_('Keep me informed'),
widget=forms.CheckboxInput)
involved = forms.BooleanField(required=False,
label=_('Keep me involved'),
widget=forms.CheckboxInput)
class Meta:
fields = ['name', 'email', 'inform', 'comment']
def get_comment_model(self):
"""
override to provide a custom comment model.
"""
return TextComment
def get_comment_create_data(self):
"""
- Override to add inform field
+ Override to add inform and involved field
"""
data = super(TextCommentForm, self).get_comment_create_data()
- data.update({'inform': True})
+ data.update({'inform': self.cleaned_data["inform"],
+ 'involved': self.cleaned_data["involved"]})
return data
| Fix checkboxes inform and involved | ## Code Before:
from django_comments.forms import CommentForm
from django import forms
from django.utils.translation import ugettext_lazy as _
from bettertexts.models import TextComment
class TextCommentForm(CommentForm):
def __init__(self, *args, **kwargs):
super(TextCommentForm, self).__init__(*args, **kwargs)
self.fields['name'].label = _("Name")
self.fields['name'].required = True
self.fields['email'].label = _("Email address")
self.fields['email'].required = True
self.fields['comment'].label = _('Comment')
self.fields['comment'].required = True
self.fields['url'].widget = forms.HiddenInput()
inform = forms.BooleanField(required=False,
label=_('Keep me informed'),
widget=forms.CheckboxInput)
involved = forms.BooleanField(required=False,
label=_('Keep me involved'),
widget=forms.CheckboxInput)
class Meta:
fields = ['name', 'email', 'inform', 'comment']
def get_comment_model(self):
"""
override to provide a custom comment model.
"""
return TextComment
def get_comment_create_data(self):
"""
Override to add inform field
"""
data = super(TextCommentForm, self).get_comment_create_data()
data.update({'inform': True})
return data
## Instruction:
Fix checkboxes inform and involved
## Code After:
from django_comments.forms import CommentForm
from django import forms
from django.utils.translation import ugettext_lazy as _
from bettertexts.models import TextComment
class TextCommentForm(CommentForm):
def __init__(self, *args, **kwargs):
super(TextCommentForm, self).__init__(*args, **kwargs)
self.fields['name'].label = _("Name")
self.fields['name'].required = True
self.fields['email'].label = _("Email address")
self.fields['email'].required = True
self.fields['comment'].label = _('Comment')
self.fields['comment'].required = True
self.fields['url'].widget = forms.HiddenInput()
inform = forms.BooleanField(required=False,
label=_('Keep me informed'),
widget=forms.CheckboxInput)
involved = forms.BooleanField(required=False,
label=_('Keep me involved'),
widget=forms.CheckboxInput)
class Meta:
fields = ['name', 'email', 'inform', 'comment']
def get_comment_model(self):
"""
override to provide a custom comment model.
"""
return TextComment
def get_comment_create_data(self):
"""
Override to add inform and involved field
"""
data = super(TextCommentForm, self).get_comment_create_data()
data.update({'inform': self.cleaned_data["inform"],
'involved': self.cleaned_data["involved"]})
return data
| from django_comments.forms import CommentForm
from django import forms
from django.utils.translation import ugettext_lazy as _
from bettertexts.models import TextComment
class TextCommentForm(CommentForm):
def __init__(self, *args, **kwargs):
super(TextCommentForm, self).__init__(*args, **kwargs)
self.fields['name'].label = _("Name")
self.fields['name'].required = True
self.fields['email'].label = _("Email address")
self.fields['email'].required = True
self.fields['comment'].label = _('Comment')
self.fields['comment'].required = True
self.fields['url'].widget = forms.HiddenInput()
inform = forms.BooleanField(required=False,
label=_('Keep me informed'),
widget=forms.CheckboxInput)
involved = forms.BooleanField(required=False,
label=_('Keep me involved'),
widget=forms.CheckboxInput)
class Meta:
fields = ['name', 'email', 'inform', 'comment']
def get_comment_model(self):
"""
override to provide a custom comment model.
"""
return TextComment
def get_comment_create_data(self):
"""
- Override to add inform field
+ Override to add inform and involved field
? +++++++++++++
"""
data = super(TextCommentForm, self).get_comment_create_data()
- data.update({'inform': True})
+ data.update({'inform': self.cleaned_data["inform"],
+ 'involved': self.cleaned_data["involved"]})
return data |
8d86d70739cbd4640faf17ca28686c3b04d5ec9c | migrations/versions/0336_broadcast_msg_content_2.py | migrations/versions/0336_broadcast_msg_content_2.py | from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
from sqlalchemy.orm.session import Session
from app.models import BroadcastMessage
revision = '0336_broadcast_msg_content_2'
down_revision = '0335_broadcast_msg_content'
def upgrade():
session = Session(bind=op.get_bind())
broadcast_messages = session.query(BroadcastMessage).filter(BroadcastMessage.content == None)
for broadcast_message in broadcast_messages:
broadcast_message.content = broadcast_message.template._as_utils_template_with_personalisation(
broadcast_message.personalisation
).content_with_placeholders_filled_in
session.commit()
op.alter_column('broadcast_message', 'content', nullable=False)
def downgrade():
op.alter_column('broadcast_message', 'content', nullable=True)
| from alembic import op
import sqlalchemy as sa
from notifications_utils.template import BroadcastMessageTemplate
from sqlalchemy.dialects import postgresql
from sqlalchemy.orm.session import Session
from app.models import BroadcastMessage
revision = '0336_broadcast_msg_content_2'
down_revision = '0335_broadcast_msg_content'
def upgrade():
conn = op.get_bind()
results = conn.execute(sa.text("""
UPDATE
broadcast_message
SET
content = templates_history.content
FROM
templates_history
WHERE
broadcast_message.content is NULL and
broadcast_message.template_id = templates_history.id and
broadcast_message.template_version = templates_history.version
;
"""))
def downgrade():
op.alter_column('broadcast_message', 'content', nullable=True)
| Rewrite previous migration in raw SQL | Rewrite previous migration in raw SQL
We shouldn’t import models into migrations because if the model changes
later down the line then the migration can’t be re-run at a later date
(for example to rebuild a database from scratch).
We don’t need to encode the content before storing it (we’ll always do
that before rendering/sending) so we don’t need to use
`BroadcastMessageTemplate`.
And given that no past broadcasts will have personalisation, we don’t
need to replace the personalisation in the template before rendering it.
So we can just copy the raw content from the templates table.
| Python | mit | alphagov/notifications-api,alphagov/notifications-api | from alembic import op
import sqlalchemy as sa
+ from notifications_utils.template import BroadcastMessageTemplate
from sqlalchemy.dialects import postgresql
from sqlalchemy.orm.session import Session
from app.models import BroadcastMessage
revision = '0336_broadcast_msg_content_2'
down_revision = '0335_broadcast_msg_content'
def upgrade():
- session = Session(bind=op.get_bind())
- broadcast_messages = session.query(BroadcastMessage).filter(BroadcastMessage.content == None)
+ conn = op.get_bind()
- for broadcast_message in broadcast_messages:
- broadcast_message.content = broadcast_message.template._as_utils_template_with_personalisation(
+ results = conn.execute(sa.text("""
+ UPDATE
- broadcast_message.personalisation
+ broadcast_message
- ).content_with_placeholders_filled_in
-
- session.commit()
-
- op.alter_column('broadcast_message', 'content', nullable=False)
+ SET
+ content = templates_history.content
+ FROM
+ templates_history
+ WHERE
+ broadcast_message.content is NULL and
+ broadcast_message.template_id = templates_history.id and
+ broadcast_message.template_version = templates_history.version
+ ;
+ """))
def downgrade():
op.alter_column('broadcast_message', 'content', nullable=True)
| Rewrite previous migration in raw SQL | ## Code Before:
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
from sqlalchemy.orm.session import Session
from app.models import BroadcastMessage
revision = '0336_broadcast_msg_content_2'
down_revision = '0335_broadcast_msg_content'
def upgrade():
session = Session(bind=op.get_bind())
broadcast_messages = session.query(BroadcastMessage).filter(BroadcastMessage.content == None)
for broadcast_message in broadcast_messages:
broadcast_message.content = broadcast_message.template._as_utils_template_with_personalisation(
broadcast_message.personalisation
).content_with_placeholders_filled_in
session.commit()
op.alter_column('broadcast_message', 'content', nullable=False)
def downgrade():
op.alter_column('broadcast_message', 'content', nullable=True)
## Instruction:
Rewrite previous migration in raw SQL
## Code After:
from alembic import op
import sqlalchemy as sa
from notifications_utils.template import BroadcastMessageTemplate
from sqlalchemy.dialects import postgresql
from sqlalchemy.orm.session import Session
from app.models import BroadcastMessage
revision = '0336_broadcast_msg_content_2'
down_revision = '0335_broadcast_msg_content'
def upgrade():
conn = op.get_bind()
results = conn.execute(sa.text("""
UPDATE
broadcast_message
SET
content = templates_history.content
FROM
templates_history
WHERE
broadcast_message.content is NULL and
broadcast_message.template_id = templates_history.id and
broadcast_message.template_version = templates_history.version
;
"""))
def downgrade():
op.alter_column('broadcast_message', 'content', nullable=True)
| from alembic import op
import sqlalchemy as sa
+ from notifications_utils.template import BroadcastMessageTemplate
from sqlalchemy.dialects import postgresql
from sqlalchemy.orm.session import Session
from app.models import BroadcastMessage
revision = '0336_broadcast_msg_content_2'
down_revision = '0335_broadcast_msg_content'
def upgrade():
- session = Session(bind=op.get_bind())
- broadcast_messages = session.query(BroadcastMessage).filter(BroadcastMessage.content == None)
+ conn = op.get_bind()
- for broadcast_message in broadcast_messages:
- broadcast_message.content = broadcast_message.template._as_utils_template_with_personalisation(
+ results = conn.execute(sa.text("""
+ UPDATE
- broadcast_message.personalisation
? ----------------
+ broadcast_message
- ).content_with_placeholders_filled_in
-
- session.commit()
-
- op.alter_column('broadcast_message', 'content', nullable=False)
+ SET
+ content = templates_history.content
+ FROM
+ templates_history
+ WHERE
+ broadcast_message.content is NULL and
+ broadcast_message.template_id = templates_history.id and
+ broadcast_message.template_version = templates_history.version
+ ;
+ """))
def downgrade():
op.alter_column('broadcast_message', 'content', nullable=True) |
a2333c2009f935731665de51ff1a28121c6a234d | migrations/versions/0313_email_access_validated_at.py | migrations/versions/0313_email_access_validated_at.py | from alembic import op
import sqlalchemy as sa
revision = '0313_email_access_validated_at'
down_revision = '0312_populate_returned_letters'
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('users', sa.Column('email_access_validated_at', sa.DateTime(), nullable=True))
# if user has email_auth, set email_access_validated_at on last login, else set it at user created_at date.
op.execute("""
UPDATE
users
SET
email_access_validated_at = created_at
""")
op.execute("""
UPDATE
users
SET
email_access_validated_at = logged_in_at
WHERE
auth_type = 'email_auth'
AND
email_access_validated_at IS NOT NULL
""")
op.alter_column('users', 'email_access_validated_at', nullable=False)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('users', 'email_access_validated_at')
# ### end Alembic commands ###
| from alembic import op
import sqlalchemy as sa
revision = '0313_email_access_validated_at'
down_revision = '0312_populate_returned_letters'
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('users', sa.Column('email_access_validated_at', sa.DateTime(), nullable=True))
# if user has email_auth, set email_access_validated_at on last login, else set it at user created_at date.
op.execute("""
UPDATE
users
SET
email_access_validated_at = created_at
""")
op.execute("""
UPDATE
users
SET
email_access_validated_at = logged_in_at
WHERE
auth_type = 'email_auth'
AND
logged_in_at IS NOT NULL
""")
op.alter_column('users', 'email_access_validated_at', nullable=False)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('users', 'email_access_validated_at')
# ### end Alembic commands ###
| Fix typo where wrong column name was checked for being null | Fix typo where wrong column name was checked for being null
| Python | mit | alphagov/notifications-api,alphagov/notifications-api | from alembic import op
import sqlalchemy as sa
revision = '0313_email_access_validated_at'
down_revision = '0312_populate_returned_letters'
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('users', sa.Column('email_access_validated_at', sa.DateTime(), nullable=True))
# if user has email_auth, set email_access_validated_at on last login, else set it at user created_at date.
op.execute("""
UPDATE
users
SET
email_access_validated_at = created_at
""")
op.execute("""
UPDATE
users
SET
email_access_validated_at = logged_in_at
WHERE
auth_type = 'email_auth'
AND
- email_access_validated_at IS NOT NULL
+ logged_in_at IS NOT NULL
""")
op.alter_column('users', 'email_access_validated_at', nullable=False)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('users', 'email_access_validated_at')
# ### end Alembic commands ###
| Fix typo where wrong column name was checked for being null | ## Code Before:
from alembic import op
import sqlalchemy as sa
revision = '0313_email_access_validated_at'
down_revision = '0312_populate_returned_letters'
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('users', sa.Column('email_access_validated_at', sa.DateTime(), nullable=True))
# if user has email_auth, set email_access_validated_at on last login, else set it at user created_at date.
op.execute("""
UPDATE
users
SET
email_access_validated_at = created_at
""")
op.execute("""
UPDATE
users
SET
email_access_validated_at = logged_in_at
WHERE
auth_type = 'email_auth'
AND
email_access_validated_at IS NOT NULL
""")
op.alter_column('users', 'email_access_validated_at', nullable=False)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('users', 'email_access_validated_at')
# ### end Alembic commands ###
## Instruction:
Fix typo where wrong column name was checked for being null
## Code After:
from alembic import op
import sqlalchemy as sa
revision = '0313_email_access_validated_at'
down_revision = '0312_populate_returned_letters'
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('users', sa.Column('email_access_validated_at', sa.DateTime(), nullable=True))
# if user has email_auth, set email_access_validated_at on last login, else set it at user created_at date.
op.execute("""
UPDATE
users
SET
email_access_validated_at = created_at
""")
op.execute("""
UPDATE
users
SET
email_access_validated_at = logged_in_at
WHERE
auth_type = 'email_auth'
AND
logged_in_at IS NOT NULL
""")
op.alter_column('users', 'email_access_validated_at', nullable=False)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('users', 'email_access_validated_at')
# ### end Alembic commands ###
| from alembic import op
import sqlalchemy as sa
revision = '0313_email_access_validated_at'
down_revision = '0312_populate_returned_letters'
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('users', sa.Column('email_access_validated_at', sa.DateTime(), nullable=True))
# if user has email_auth, set email_access_validated_at on last login, else set it at user created_at date.
op.execute("""
UPDATE
users
SET
email_access_validated_at = created_at
""")
op.execute("""
UPDATE
users
SET
email_access_validated_at = logged_in_at
WHERE
auth_type = 'email_auth'
AND
- email_access_validated_at IS NOT NULL
+ logged_in_at IS NOT NULL
""")
op.alter_column('users', 'email_access_validated_at', nullable=False)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('users', 'email_access_validated_at')
# ### end Alembic commands ### |
1994a59d3ae9d3f24445f11f3bc0dd3089042bc4 | main.py | main.py | from order import Order
from orderbook import OrderBook
from client import FinanceClient
from ordermanager import OrderManager
from strategy import Vanilla, Strawberry
import sys
# local server for finance data
host_ip, server_port = "localhost", 9995
def main():
"""
Turn on the FinanceServer
- fetch data from the FinanceServer
- parse out each order as an Order object
- add these Orders to the OrderBook using the values in Action
- for each added order, decide to trade indicated by signal
"""
strategy_choice = sys.argv[1]
books = {}
client = FinanceClient(host_ip, server_port)
ordermanager = OrderManager()
if strategy_choice == 'Vanilla':
strategy = Vanilla()
elif strategy_choice == 'Strawberry':
strategy = Strawberry()
else:
print('strategies available: Vanilla or Strawberry')
print(strategy.name, strategy.description)
for line in client.fetch():
try:
order = Order(line)
book = books.get(order.symbol)
if book is None:
book = books[order.symbol] = OrderBook(order.symbol)
book.add(order)
bid, offer = book.display_book(output=True)
ordermanager.signal(bid, offer, strategy.execute)
except Exception as e:
print(e)
pass
if __name__ == '__main__':
main()
| from order import Order
from orderbook import OrderBook
from client import FinanceClient
from ordermanager import OrderManager
from strategy import Vanilla, Strawberry
import sys
# local server for finance data
host_ip, server_port = "localhost", 9995
def main():
"""
Turn on the FinanceServer
- fetch data from the FinanceServer
- parse out each order as an Order object
- add these Orders to the OrderBook using the values in Action
- for each added order, decide to trade indicated by signal
"""
strategy_choice = sys.argv[1]
books = {}
client = FinanceClient(host_ip, server_port)
ordermanager = OrderManager()
if strategy_choice == 'Vanilla':
strategy = Vanilla()
elif strategy_choice == 'Strawberry':
strategy = Strawberry()
else:
print('strategies available: Vanilla or Strawberry')
print(strategy.name, strategy.description)
for line in client.fetch():
try:
order = Order(line)
book = books.get(order.symbol)
if book is None:
book = books[order.symbol] = OrderBook(order.symbol)
if order.action == 'A':
book.add(order)
elif order.side == 'M':
book.modify(order)
bid, offer = book.display_book(output=True)
ordermanager.signal(bid, offer, strategy.execute)
except Exception as e:
print(e)
pass
if __name__ == '__main__':
main()
| Use modify with the orderbook | Use modify with the orderbook
| Python | mit | albhu/finance | from order import Order
from orderbook import OrderBook
from client import FinanceClient
from ordermanager import OrderManager
from strategy import Vanilla, Strawberry
import sys
# local server for finance data
host_ip, server_port = "localhost", 9995
def main():
"""
Turn on the FinanceServer
- fetch data from the FinanceServer
- parse out each order as an Order object
- add these Orders to the OrderBook using the values in Action
- for each added order, decide to trade indicated by signal
"""
strategy_choice = sys.argv[1]
books = {}
client = FinanceClient(host_ip, server_port)
ordermanager = OrderManager()
if strategy_choice == 'Vanilla':
strategy = Vanilla()
elif strategy_choice == 'Strawberry':
strategy = Strawberry()
else:
print('strategies available: Vanilla or Strawberry')
-
+
print(strategy.name, strategy.description)
for line in client.fetch():
try:
order = Order(line)
book = books.get(order.symbol)
if book is None:
book = books[order.symbol] = OrderBook(order.symbol)
+ if order.action == 'A':
- book.add(order)
+ book.add(order)
+ elif order.side == 'M':
+ book.modify(order)
bid, offer = book.display_book(output=True)
ordermanager.signal(bid, offer, strategy.execute)
except Exception as e:
print(e)
pass
if __name__ == '__main__':
main()
| Use modify with the orderbook | ## Code Before:
from order import Order
from orderbook import OrderBook
from client import FinanceClient
from ordermanager import OrderManager
from strategy import Vanilla, Strawberry
import sys
# local server for finance data
host_ip, server_port = "localhost", 9995
def main():
"""
Turn on the FinanceServer
- fetch data from the FinanceServer
- parse out each order as an Order object
- add these Orders to the OrderBook using the values in Action
- for each added order, decide to trade indicated by signal
"""
strategy_choice = sys.argv[1]
books = {}
client = FinanceClient(host_ip, server_port)
ordermanager = OrderManager()
if strategy_choice == 'Vanilla':
strategy = Vanilla()
elif strategy_choice == 'Strawberry':
strategy = Strawberry()
else:
print('strategies available: Vanilla or Strawberry')
print(strategy.name, strategy.description)
for line in client.fetch():
try:
order = Order(line)
book = books.get(order.symbol)
if book is None:
book = books[order.symbol] = OrderBook(order.symbol)
book.add(order)
bid, offer = book.display_book(output=True)
ordermanager.signal(bid, offer, strategy.execute)
except Exception as e:
print(e)
pass
if __name__ == '__main__':
main()
## Instruction:
Use modify with the orderbook
## Code After:
from order import Order
from orderbook import OrderBook
from client import FinanceClient
from ordermanager import OrderManager
from strategy import Vanilla, Strawberry
import sys
# local server for finance data
host_ip, server_port = "localhost", 9995
def main():
"""
Turn on the FinanceServer
- fetch data from the FinanceServer
- parse out each order as an Order object
- add these Orders to the OrderBook using the values in Action
- for each added order, decide to trade indicated by signal
"""
strategy_choice = sys.argv[1]
books = {}
client = FinanceClient(host_ip, server_port)
ordermanager = OrderManager()
if strategy_choice == 'Vanilla':
strategy = Vanilla()
elif strategy_choice == 'Strawberry':
strategy = Strawberry()
else:
print('strategies available: Vanilla or Strawberry')
print(strategy.name, strategy.description)
for line in client.fetch():
try:
order = Order(line)
book = books.get(order.symbol)
if book is None:
book = books[order.symbol] = OrderBook(order.symbol)
if order.action == 'A':
book.add(order)
elif order.side == 'M':
book.modify(order)
bid, offer = book.display_book(output=True)
ordermanager.signal(bid, offer, strategy.execute)
except Exception as e:
print(e)
pass
if __name__ == '__main__':
main()
| from order import Order
from orderbook import OrderBook
from client import FinanceClient
from ordermanager import OrderManager
from strategy import Vanilla, Strawberry
import sys
# local server for finance data
host_ip, server_port = "localhost", 9995
def main():
"""
Turn on the FinanceServer
- fetch data from the FinanceServer
- parse out each order as an Order object
- add these Orders to the OrderBook using the values in Action
- for each added order, decide to trade indicated by signal
"""
strategy_choice = sys.argv[1]
books = {}
client = FinanceClient(host_ip, server_port)
ordermanager = OrderManager()
if strategy_choice == 'Vanilla':
strategy = Vanilla()
elif strategy_choice == 'Strawberry':
strategy = Strawberry()
else:
print('strategies available: Vanilla or Strawberry')
-
+
print(strategy.name, strategy.description)
for line in client.fetch():
try:
order = Order(line)
book = books.get(order.symbol)
if book is None:
book = books[order.symbol] = OrderBook(order.symbol)
+ if order.action == 'A':
- book.add(order)
+ book.add(order)
? ++++
+ elif order.side == 'M':
+ book.modify(order)
bid, offer = book.display_book(output=True)
ordermanager.signal(bid, offer, strategy.execute)
except Exception as e:
print(e)
pass
if __name__ == '__main__':
main() |
2b81d198b7d3dd9094f47d2f8e51f0275ee31463 | osf/migrations/0084_migrate_node_info_for_target.py | osf/migrations/0084_migrate_node_info_for_target.py | from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('osf', '0083_add_file_fields_for_target'),
]
operations = [
migrations.RunSQL(
["""
UPDATE osf_basefilenode
SET target_object_id = node_id;
UPDATE osf_basefilenode
SET target_content_type_id = (SELECT id FROM django_content_type WHERE app_label = 'osf' AND model = 'abstractnode');
"""], ["""
UPDATE osf_basefilenode
SET node_id = target_object_id;
"""]
),
]
| from __future__ import unicode_literals
from django.db import migrations, models, connection
from django.contrib.contenttypes.models import ContentType
def set_basefilenode_target(apps, schema_editor):
BaseFileNode = apps.get_model('osf', 'basefilenode')
AbstractNode = apps.get_model('osf', 'abstractnode')
target_content_type_id = ContentType.objects.get_for_model(AbstractNode).id
BATCHSIZE = 5000
max_pk = BaseFileNode.objects.aggregate(models.Max('pk'))['pk__max']
if max_pk is not None:
for offset in range(0, max_pk + 1, BATCHSIZE):
(BaseFileNode.objects
.filter(pk__gte=offset)
.filter(pk__lt=offset + BATCHSIZE)
.filter(target_object_id__isnull=True)
.filter(target_content_type_id__isnull=True)
.update(
target_content_type_id=target_content_type_id,
target_object_id=models.F('node_id')
)
)
def reset_basefilenode_target_to_node(*args, **kwargs):
sql = "UPDATE osf_basefilenode SET node_id = target_object_id;"
with connection.cursor() as cursor:
cursor.execute(sql)
class Migration(migrations.Migration):
# Avoid locking basefilenode
atomic = False
dependencies = [
('osf', '0083_add_file_fields_for_target'),
]
operations = [
migrations.RunPython(set_basefilenode_target, reset_basefilenode_target_to_node),
]
| Use batches instead of raw sql for long migration | Use batches instead of raw sql for long migration
| Python | apache-2.0 | baylee-d/osf.io,Johnetordoff/osf.io,mfraezz/osf.io,mattclark/osf.io,aaxelb/osf.io,HalcyonChimera/osf.io,adlius/osf.io,felliott/osf.io,pattisdr/osf.io,CenterForOpenScience/osf.io,Johnetordoff/osf.io,brianjgeiger/osf.io,brianjgeiger/osf.io,mfraezz/osf.io,erinspace/osf.io,HalcyonChimera/osf.io,CenterForOpenScience/osf.io,mattclark/osf.io,erinspace/osf.io,cslzchen/osf.io,aaxelb/osf.io,pattisdr/osf.io,mattclark/osf.io,HalcyonChimera/osf.io,brianjgeiger/osf.io,Johnetordoff/osf.io,caseyrollins/osf.io,adlius/osf.io,mfraezz/osf.io,erinspace/osf.io,baylee-d/osf.io,felliott/osf.io,CenterForOpenScience/osf.io,baylee-d/osf.io,mfraezz/osf.io,adlius/osf.io,saradbowman/osf.io,cslzchen/osf.io,CenterForOpenScience/osf.io,aaxelb/osf.io,saradbowman/osf.io,caseyrollins/osf.io,caseyrollins/osf.io,aaxelb/osf.io,cslzchen/osf.io,pattisdr/osf.io,cslzchen/osf.io,felliott/osf.io,Johnetordoff/osf.io,felliott/osf.io,adlius/osf.io,brianjgeiger/osf.io,HalcyonChimera/osf.io | from __future__ import unicode_literals
- from django.db import migrations
+ from django.db import migrations, models, connection
+ from django.contrib.contenttypes.models import ContentType
+ def set_basefilenode_target(apps, schema_editor):
+ BaseFileNode = apps.get_model('osf', 'basefilenode')
+ AbstractNode = apps.get_model('osf', 'abstractnode')
+ target_content_type_id = ContentType.objects.get_for_model(AbstractNode).id
+
+ BATCHSIZE = 5000
+
+ max_pk = BaseFileNode.objects.aggregate(models.Max('pk'))['pk__max']
+ if max_pk is not None:
+ for offset in range(0, max_pk + 1, BATCHSIZE):
+ (BaseFileNode.objects
+ .filter(pk__gte=offset)
+ .filter(pk__lt=offset + BATCHSIZE)
+ .filter(target_object_id__isnull=True)
+ .filter(target_content_type_id__isnull=True)
+ .update(
+ target_content_type_id=target_content_type_id,
+ target_object_id=models.F('node_id')
+ )
+ )
+
+
+ def reset_basefilenode_target_to_node(*args, **kwargs):
+ sql = "UPDATE osf_basefilenode SET node_id = target_object_id;"
+ with connection.cursor() as cursor:
+ cursor.execute(sql)
+
class Migration(migrations.Migration):
+
+ # Avoid locking basefilenode
+ atomic = False
dependencies = [
('osf', '0083_add_file_fields_for_target'),
]
operations = [
+ migrations.RunPython(set_basefilenode_target, reset_basefilenode_target_to_node),
- migrations.RunSQL(
- ["""
- UPDATE osf_basefilenode
- SET target_object_id = node_id;
- UPDATE osf_basefilenode
- SET target_content_type_id = (SELECT id FROM django_content_type WHERE app_label = 'osf' AND model = 'abstractnode');
- """], ["""
- UPDATE osf_basefilenode
- SET node_id = target_object_id;
- """]
- ),
]
| Use batches instead of raw sql for long migration | ## Code Before:
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('osf', '0083_add_file_fields_for_target'),
]
operations = [
migrations.RunSQL(
["""
UPDATE osf_basefilenode
SET target_object_id = node_id;
UPDATE osf_basefilenode
SET target_content_type_id = (SELECT id FROM django_content_type WHERE app_label = 'osf' AND model = 'abstractnode');
"""], ["""
UPDATE osf_basefilenode
SET node_id = target_object_id;
"""]
),
]
## Instruction:
Use batches instead of raw sql for long migration
## Code After:
from __future__ import unicode_literals
from django.db import migrations, models, connection
from django.contrib.contenttypes.models import ContentType
def set_basefilenode_target(apps, schema_editor):
BaseFileNode = apps.get_model('osf', 'basefilenode')
AbstractNode = apps.get_model('osf', 'abstractnode')
target_content_type_id = ContentType.objects.get_for_model(AbstractNode).id
BATCHSIZE = 5000
max_pk = BaseFileNode.objects.aggregate(models.Max('pk'))['pk__max']
if max_pk is not None:
for offset in range(0, max_pk + 1, BATCHSIZE):
(BaseFileNode.objects
.filter(pk__gte=offset)
.filter(pk__lt=offset + BATCHSIZE)
.filter(target_object_id__isnull=True)
.filter(target_content_type_id__isnull=True)
.update(
target_content_type_id=target_content_type_id,
target_object_id=models.F('node_id')
)
)
def reset_basefilenode_target_to_node(*args, **kwargs):
sql = "UPDATE osf_basefilenode SET node_id = target_object_id;"
with connection.cursor() as cursor:
cursor.execute(sql)
class Migration(migrations.Migration):
# Avoid locking basefilenode
atomic = False
dependencies = [
('osf', '0083_add_file_fields_for_target'),
]
operations = [
migrations.RunPython(set_basefilenode_target, reset_basefilenode_target_to_node),
]
| from __future__ import unicode_literals
- from django.db import migrations
+ from django.db import migrations, models, connection
? ++++++++++++++++++++
+ from django.contrib.contenttypes.models import ContentType
+ def set_basefilenode_target(apps, schema_editor):
+ BaseFileNode = apps.get_model('osf', 'basefilenode')
+ AbstractNode = apps.get_model('osf', 'abstractnode')
+ target_content_type_id = ContentType.objects.get_for_model(AbstractNode).id
+
+ BATCHSIZE = 5000
+
+ max_pk = BaseFileNode.objects.aggregate(models.Max('pk'))['pk__max']
+ if max_pk is not None:
+ for offset in range(0, max_pk + 1, BATCHSIZE):
+ (BaseFileNode.objects
+ .filter(pk__gte=offset)
+ .filter(pk__lt=offset + BATCHSIZE)
+ .filter(target_object_id__isnull=True)
+ .filter(target_content_type_id__isnull=True)
+ .update(
+ target_content_type_id=target_content_type_id,
+ target_object_id=models.F('node_id')
+ )
+ )
+
+
+ def reset_basefilenode_target_to_node(*args, **kwargs):
+ sql = "UPDATE osf_basefilenode SET node_id = target_object_id;"
+ with connection.cursor() as cursor:
+ cursor.execute(sql)
+
class Migration(migrations.Migration):
+
+ # Avoid locking basefilenode
+ atomic = False
dependencies = [
('osf', '0083_add_file_fields_for_target'),
]
operations = [
+ migrations.RunPython(set_basefilenode_target, reset_basefilenode_target_to_node),
- migrations.RunSQL(
- ["""
- UPDATE osf_basefilenode
- SET target_object_id = node_id;
- UPDATE osf_basefilenode
- SET target_content_type_id = (SELECT id FROM django_content_type WHERE app_label = 'osf' AND model = 'abstractnode');
- """], ["""
- UPDATE osf_basefilenode
- SET node_id = target_object_id;
- """]
- ),
] |
4cb1b6b8656d4e3893b3aa8fe5766b507afa6d24 | cmsplugin_rt/button/cms_plugins.py | cmsplugin_rt/button/cms_plugins.py | from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from cms.models.pluginmodel import CMSPlugin
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from models import *
bootstrap_module_name = _("Widgets")
layout_module_name = _("Layout elements")
generic_module_name = _("Generic")
meta_module_name = _("Meta elements")
class ButtonPlugin(CMSPluginBase):
model = ButtonPluginModel
name = _("Button")
#module = bootstrap_module_name
render_template = "button_plugin.html"
def render(self, context, instance, placeholder):
context['instance'] = instance
if instance.page_link:
context['link'] = instance.page_link.get_absolute_url()
else:
context['link'] = instance.button_link
return context
plugin_pool.register_plugin(ButtonPlugin)
| from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from cms.models.pluginmodel import CMSPlugin
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from models import *
bootstrap_module_name = _("Widgets")
layout_module_name = _("Layout elements")
generic_module_name = _("Generic")
meta_module_name = _("Meta elements")
class ButtonPlugin(CMSPluginBase):
model = ButtonPluginModel
name = _("Button")
#module = bootstrap_module_name
render_template = "button_plugin.html"
text_enabled = True
def render(self, context, instance, placeholder):
context['instance'] = instance
if instance.page_link:
context['link'] = instance.page_link.get_absolute_url()
else:
context['link'] = instance.button_link
return context
plugin_pool.register_plugin(ButtonPlugin)
| Make Button plugin usable inside Text plugin | Make Button plugin usable inside Text plugin
| Python | bsd-3-clause | RacingTadpole/cmsplugin-rt | from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from cms.models.pluginmodel import CMSPlugin
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from models import *
bootstrap_module_name = _("Widgets")
layout_module_name = _("Layout elements")
generic_module_name = _("Generic")
meta_module_name = _("Meta elements")
class ButtonPlugin(CMSPluginBase):
model = ButtonPluginModel
name = _("Button")
#module = bootstrap_module_name
render_template = "button_plugin.html"
+ text_enabled = True
def render(self, context, instance, placeholder):
context['instance'] = instance
if instance.page_link:
context['link'] = instance.page_link.get_absolute_url()
else:
context['link'] = instance.button_link
return context
plugin_pool.register_plugin(ButtonPlugin)
| Make Button plugin usable inside Text plugin | ## Code Before:
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from cms.models.pluginmodel import CMSPlugin
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from models import *
bootstrap_module_name = _("Widgets")
layout_module_name = _("Layout elements")
generic_module_name = _("Generic")
meta_module_name = _("Meta elements")
class ButtonPlugin(CMSPluginBase):
model = ButtonPluginModel
name = _("Button")
#module = bootstrap_module_name
render_template = "button_plugin.html"
def render(self, context, instance, placeholder):
context['instance'] = instance
if instance.page_link:
context['link'] = instance.page_link.get_absolute_url()
else:
context['link'] = instance.button_link
return context
plugin_pool.register_plugin(ButtonPlugin)
## Instruction:
Make Button plugin usable inside Text plugin
## Code After:
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from cms.models.pluginmodel import CMSPlugin
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from models import *
bootstrap_module_name = _("Widgets")
layout_module_name = _("Layout elements")
generic_module_name = _("Generic")
meta_module_name = _("Meta elements")
class ButtonPlugin(CMSPluginBase):
model = ButtonPluginModel
name = _("Button")
#module = bootstrap_module_name
render_template = "button_plugin.html"
text_enabled = True
def render(self, context, instance, placeholder):
context['instance'] = instance
if instance.page_link:
context['link'] = instance.page_link.get_absolute_url()
else:
context['link'] = instance.button_link
return context
plugin_pool.register_plugin(ButtonPlugin)
| from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from cms.models.pluginmodel import CMSPlugin
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from models import *
bootstrap_module_name = _("Widgets")
layout_module_name = _("Layout elements")
generic_module_name = _("Generic")
meta_module_name = _("Meta elements")
class ButtonPlugin(CMSPluginBase):
model = ButtonPluginModel
name = _("Button")
#module = bootstrap_module_name
render_template = "button_plugin.html"
+ text_enabled = True
def render(self, context, instance, placeholder):
context['instance'] = instance
if instance.page_link:
context['link'] = instance.page_link.get_absolute_url()
else:
context['link'] = instance.button_link
return context
plugin_pool.register_plugin(ButtonPlugin)
|
53636a17cd50d704b7b4563d0b23a474677051f4 | hub/prototype/config.py | hub/prototype/config.py |
HOST = "the.hub.machine.tld"
# the servers we listen to; for now each server can just
# have one port and secret key on the hub even if it runs
# multiple game servers; not sure if we need to allow more
# than that yet :-/
SERVERS = {
"some.game.server.tld": (42, "somesecret"),
}
# the other hubs we echo to; note that we don't yet change
# the packets in any way, so they'll look like they really
# come from us; not good, but we'll need to define a new
# packet format for forwarded userinfo strings first, then
# we can fix this :-/
HUBS = {
"some.hub.server.tld": (84, "anothersecret"),
}
|
HOST = "the.hub.machine.tld"
# the servers we listen to; for now each server can just
# have one port and secret key on the hub even if it runs
# multiple game servers; not sure if we need to allow more
# than that yet :-/
SERVERS = {
"some.game.server.tld": (42, "somesecret"),
"some.other.game.tld": (543, "monkeyspam"),
}
# the other hubs we echo to; note that we don't yet change
# the packets in any way, so they'll look like they really
# come from us; not good, but we'll need to define a new
# packet format for forwarded userinfo strings first, then
# we can fix this :-/
HUBS = {
"some.hub.server.tld": (84, "anothersecret"),
}
| Make sure we give an example for two servers. | Make sure we give an example for two servers.
| Python | agpl-3.0 | madprof/alpha-hub |
HOST = "the.hub.machine.tld"
# the servers we listen to; for now each server can just
# have one port and secret key on the hub even if it runs
# multiple game servers; not sure if we need to allow more
# than that yet :-/
SERVERS = {
"some.game.server.tld": (42, "somesecret"),
+ "some.other.game.tld": (543, "monkeyspam"),
}
# the other hubs we echo to; note that we don't yet change
# the packets in any way, so they'll look like they really
# come from us; not good, but we'll need to define a new
# packet format for forwarded userinfo strings first, then
# we can fix this :-/
HUBS = {
"some.hub.server.tld": (84, "anothersecret"),
}
| Make sure we give an example for two servers. | ## Code Before:
HOST = "the.hub.machine.tld"
# the servers we listen to; for now each server can just
# have one port and secret key on the hub even if it runs
# multiple game servers; not sure if we need to allow more
# than that yet :-/
SERVERS = {
"some.game.server.tld": (42, "somesecret"),
}
# the other hubs we echo to; note that we don't yet change
# the packets in any way, so they'll look like they really
# come from us; not good, but we'll need to define a new
# packet format for forwarded userinfo strings first, then
# we can fix this :-/
HUBS = {
"some.hub.server.tld": (84, "anothersecret"),
}
## Instruction:
Make sure we give an example for two servers.
## Code After:
HOST = "the.hub.machine.tld"
# the servers we listen to; for now each server can just
# have one port and secret key on the hub even if it runs
# multiple game servers; not sure if we need to allow more
# than that yet :-/
SERVERS = {
"some.game.server.tld": (42, "somesecret"),
"some.other.game.tld": (543, "monkeyspam"),
}
# the other hubs we echo to; note that we don't yet change
# the packets in any way, so they'll look like they really
# come from us; not good, but we'll need to define a new
# packet format for forwarded userinfo strings first, then
# we can fix this :-/
HUBS = {
"some.hub.server.tld": (84, "anothersecret"),
}
|
HOST = "the.hub.machine.tld"
# the servers we listen to; for now each server can just
# have one port and secret key on the hub even if it runs
# multiple game servers; not sure if we need to allow more
# than that yet :-/
SERVERS = {
"some.game.server.tld": (42, "somesecret"),
+ "some.other.game.tld": (543, "monkeyspam"),
}
# the other hubs we echo to; note that we don't yet change
# the packets in any way, so they'll look like they really
# come from us; not good, but we'll need to define a new
# packet format for forwarded userinfo strings first, then
# we can fix this :-/
HUBS = {
"some.hub.server.tld": (84, "anothersecret"),
} |
befce70e7931f5949a7db10af4bae2cb4c21ba08 | localore/people/wagtail_hooks.py | localore/people/wagtail_hooks.py | from wagtailmodeladmin.options import ModelAdmin, wagtailmodeladmin_register
from .models import Person
class PeopleAdmin(ModelAdmin):
model = Person
menu_icon = 'group'
menu_label = 'Team'
menu_order = 300
list_display = ('first_name', 'last_name', 'production', 'role')
list_filter = ('role', 'production')
search_fields = ('first_name', 'last_name', 'biography')
wagtailmodeladmin_register(PeopleAdmin)
| from wagtailmodeladmin.options import ModelAdmin, wagtailmodeladmin_register
from .models import Person
class PeopleAdmin(ModelAdmin):
model = Person
menu_icon = 'group'
menu_label = 'Team'
menu_order = 300
list_display = ('first_name', 'last_name', 'production', 'role')
list_filter = ('role', 'production')
ordering = ('-production',)
search_fields = ('first_name', 'last_name', 'biography')
wagtailmodeladmin_register(PeopleAdmin)
| Order people by associated production. | Order people by associated production.
| Python | mpl-2.0 | ghostwords/localore,ghostwords/localore,ghostwords/localore | from wagtailmodeladmin.options import ModelAdmin, wagtailmodeladmin_register
from .models import Person
class PeopleAdmin(ModelAdmin):
model = Person
menu_icon = 'group'
menu_label = 'Team'
menu_order = 300
list_display = ('first_name', 'last_name', 'production', 'role')
list_filter = ('role', 'production')
+ ordering = ('-production',)
search_fields = ('first_name', 'last_name', 'biography')
wagtailmodeladmin_register(PeopleAdmin)
| Order people by associated production. | ## Code Before:
from wagtailmodeladmin.options import ModelAdmin, wagtailmodeladmin_register
from .models import Person
class PeopleAdmin(ModelAdmin):
model = Person
menu_icon = 'group'
menu_label = 'Team'
menu_order = 300
list_display = ('first_name', 'last_name', 'production', 'role')
list_filter = ('role', 'production')
search_fields = ('first_name', 'last_name', 'biography')
wagtailmodeladmin_register(PeopleAdmin)
## Instruction:
Order people by associated production.
## Code After:
from wagtailmodeladmin.options import ModelAdmin, wagtailmodeladmin_register
from .models import Person
class PeopleAdmin(ModelAdmin):
model = Person
menu_icon = 'group'
menu_label = 'Team'
menu_order = 300
list_display = ('first_name', 'last_name', 'production', 'role')
list_filter = ('role', 'production')
ordering = ('-production',)
search_fields = ('first_name', 'last_name', 'biography')
wagtailmodeladmin_register(PeopleAdmin)
| from wagtailmodeladmin.options import ModelAdmin, wagtailmodeladmin_register
from .models import Person
class PeopleAdmin(ModelAdmin):
model = Person
menu_icon = 'group'
menu_label = 'Team'
menu_order = 300
list_display = ('first_name', 'last_name', 'production', 'role')
list_filter = ('role', 'production')
+ ordering = ('-production',)
search_fields = ('first_name', 'last_name', 'biography')
wagtailmodeladmin_register(PeopleAdmin) |
b0011541a21927c4f9ee378b77b11fd4b0dfbcff | tests/test_cookiecutter_substitution.py | tests/test_cookiecutter_substitution.py | import re
import sh
from .base import DjangoCookieTestCase
class TestCookiecutterSubstitution(DjangoCookieTestCase):
"""Test that all cookiecutter instances are substituted"""
def test_all_cookiecutter_instances_are_substituted(self):
# Build a list containing absolute paths to the generated files
paths = self.generate_project()
# Construct the cookiecutter search pattern
pattern = "{{(\s?cookiecutter)[.](.*?)}}"
re_obj = re.compile(pattern)
# Assert that no match is found in any of the files
for path in paths:
for line in open(path, 'r'):
match = re_obj.search(line)
self.assertIsNone(
match,
"cookiecutter variable not replaced in {}".format(path))
def test_flake8_complaince(self):
"""generated project should pass flake8"""
self.generate_project()
try:
sh.flake8(self.destpath)
except sh.ErrorReturnCode as e:
raise AssertionError(e)
| import re
import sh
from .base import DjangoCookieTestCase
class TestCookiecutterSubstitution(DjangoCookieTestCase):
"""Test that all cookiecutter instances are substituted"""
def test_all_cookiecutter_instances_are_substituted(self):
# Build a list containing absolute paths to the generated files
paths = self.generate_project()
# Construct the cookiecutter search pattern
pattern = "{{(\s?cookiecutter)[.](.*?)}}"
re_obj = re.compile(pattern)
# Assert that no match is found in any of the files
for path in paths:
for line in open(path, 'r', encoding='utf-8', errors='ignore'):
match = re_obj.search(line)
self.assertIsNone(
match,
"cookiecutter variable not replaced in {}".format(path))
def test_flake8_complaince(self):
"""generated project should pass flake8"""
self.generate_project()
try:
sh.flake8(self.destpath)
except sh.ErrorReturnCode as e:
raise AssertionError(e)
| Fix tests for python 3 | Fix tests for python 3
| Python | bsd-3-clause | wldcordeiro/cookiecutter-django-essentials,wldcordeiro/cookiecutter-django-essentials,wldcordeiro/cookiecutter-django-essentials | import re
import sh
from .base import DjangoCookieTestCase
class TestCookiecutterSubstitution(DjangoCookieTestCase):
"""Test that all cookiecutter instances are substituted"""
def test_all_cookiecutter_instances_are_substituted(self):
# Build a list containing absolute paths to the generated files
paths = self.generate_project()
# Construct the cookiecutter search pattern
pattern = "{{(\s?cookiecutter)[.](.*?)}}"
re_obj = re.compile(pattern)
# Assert that no match is found in any of the files
for path in paths:
- for line in open(path, 'r'):
+ for line in open(path, 'r', encoding='utf-8', errors='ignore'):
match = re_obj.search(line)
self.assertIsNone(
match,
"cookiecutter variable not replaced in {}".format(path))
def test_flake8_complaince(self):
"""generated project should pass flake8"""
self.generate_project()
try:
sh.flake8(self.destpath)
except sh.ErrorReturnCode as e:
raise AssertionError(e)
| Fix tests for python 3 | ## Code Before:
import re
import sh
from .base import DjangoCookieTestCase
class TestCookiecutterSubstitution(DjangoCookieTestCase):
"""Test that all cookiecutter instances are substituted"""
def test_all_cookiecutter_instances_are_substituted(self):
# Build a list containing absolute paths to the generated files
paths = self.generate_project()
# Construct the cookiecutter search pattern
pattern = "{{(\s?cookiecutter)[.](.*?)}}"
re_obj = re.compile(pattern)
# Assert that no match is found in any of the files
for path in paths:
for line in open(path, 'r'):
match = re_obj.search(line)
self.assertIsNone(
match,
"cookiecutter variable not replaced in {}".format(path))
def test_flake8_complaince(self):
"""generated project should pass flake8"""
self.generate_project()
try:
sh.flake8(self.destpath)
except sh.ErrorReturnCode as e:
raise AssertionError(e)
## Instruction:
Fix tests for python 3
## Code After:
import re
import sh
from .base import DjangoCookieTestCase
class TestCookiecutterSubstitution(DjangoCookieTestCase):
"""Test that all cookiecutter instances are substituted"""
def test_all_cookiecutter_instances_are_substituted(self):
# Build a list containing absolute paths to the generated files
paths = self.generate_project()
# Construct the cookiecutter search pattern
pattern = "{{(\s?cookiecutter)[.](.*?)}}"
re_obj = re.compile(pattern)
# Assert that no match is found in any of the files
for path in paths:
for line in open(path, 'r', encoding='utf-8', errors='ignore'):
match = re_obj.search(line)
self.assertIsNone(
match,
"cookiecutter variable not replaced in {}".format(path))
def test_flake8_complaince(self):
"""generated project should pass flake8"""
self.generate_project()
try:
sh.flake8(self.destpath)
except sh.ErrorReturnCode as e:
raise AssertionError(e)
| import re
import sh
from .base import DjangoCookieTestCase
class TestCookiecutterSubstitution(DjangoCookieTestCase):
"""Test that all cookiecutter instances are substituted"""
def test_all_cookiecutter_instances_are_substituted(self):
# Build a list containing absolute paths to the generated files
paths = self.generate_project()
# Construct the cookiecutter search pattern
pattern = "{{(\s?cookiecutter)[.](.*?)}}"
re_obj = re.compile(pattern)
# Assert that no match is found in any of the files
for path in paths:
- for line in open(path, 'r'):
+ for line in open(path, 'r', encoding='utf-8', errors='ignore'):
match = re_obj.search(line)
self.assertIsNone(
match,
"cookiecutter variable not replaced in {}".format(path))
def test_flake8_complaince(self):
"""generated project should pass flake8"""
self.generate_project()
try:
sh.flake8(self.destpath)
except sh.ErrorReturnCode as e:
raise AssertionError(e) |
4117b767f48678542797d811cc1a8ea75f37c714 | saleor/account/migrations/0040_auto_20200415_0443.py | saleor/account/migrations/0040_auto_20200415_0443.py |
from django.db import migrations
def change_extension_permission_to_plugin_permission(apps, schema_editor):
permission = apps.get_model("auth", "Permission")
users = apps.get_model("account", "User")
plugin_permission = permission.objects.filter(
codename="manage_plugins", content_type__app_label="plugins"
).first()
extension_permission = permission.objects.filter(
codename="manage_plugins", content_type__app_label="extensions"
).first()
users = users.objects.filter(
user_permissions__content_type__app_label="extensions",
user_permissions__codename="manage_plugins",
)
if not plugin_permission or not extension_permission:
return
for user in users:
user.user_permissions.remove(extension_permission)
user.user_permissions.add(plugin_permission)
class Migration(migrations.Migration):
dependencies = [
("account", "0039_auto_20200221_0257"),
("plugins", "0001_initial"),
]
operations = [
migrations.RunPython(change_extension_permission_to_plugin_permission),
]
|
from django.db import migrations
def change_extension_permission_to_plugin_permission(apps, schema_editor):
permission = apps.get_model("auth", "Permission")
users = apps.get_model("account", "User")
plugin_permission = permission.objects.filter(
codename="manage_plugins", content_type__app_label="plugins"
).first()
extension_permission = permission.objects.filter(
codename="manage_plugins", content_type__app_label="extensions"
).first()
users = users.objects.filter(
user_permissions__content_type__app_label="extensions",
user_permissions__codename="manage_plugins",
)
if not plugin_permission or not extension_permission:
return
for user in users:
user.user_permissions.remove(extension_permission)
user.user_permissions.add(plugin_permission)
if extension_permission:
extension_permission.delete()
class Migration(migrations.Migration):
dependencies = [
("account", "0039_auto_20200221_0257"),
("plugins", "0001_initial"),
]
operations = [
migrations.RunPython(change_extension_permission_to_plugin_permission),
]
| Remove unused permission from db | Remove unused permission from db
| Python | bsd-3-clause | mociepka/saleor,mociepka/saleor,mociepka/saleor |
from django.db import migrations
def change_extension_permission_to_plugin_permission(apps, schema_editor):
permission = apps.get_model("auth", "Permission")
users = apps.get_model("account", "User")
plugin_permission = permission.objects.filter(
codename="manage_plugins", content_type__app_label="plugins"
).first()
extension_permission = permission.objects.filter(
codename="manage_plugins", content_type__app_label="extensions"
).first()
users = users.objects.filter(
user_permissions__content_type__app_label="extensions",
user_permissions__codename="manage_plugins",
)
if not plugin_permission or not extension_permission:
return
for user in users:
user.user_permissions.remove(extension_permission)
user.user_permissions.add(plugin_permission)
+ if extension_permission:
+ extension_permission.delete()
+
class Migration(migrations.Migration):
dependencies = [
("account", "0039_auto_20200221_0257"),
("plugins", "0001_initial"),
]
operations = [
migrations.RunPython(change_extension_permission_to_plugin_permission),
]
| Remove unused permission from db | ## Code Before:
from django.db import migrations
def change_extension_permission_to_plugin_permission(apps, schema_editor):
permission = apps.get_model("auth", "Permission")
users = apps.get_model("account", "User")
plugin_permission = permission.objects.filter(
codename="manage_plugins", content_type__app_label="plugins"
).first()
extension_permission = permission.objects.filter(
codename="manage_plugins", content_type__app_label="extensions"
).first()
users = users.objects.filter(
user_permissions__content_type__app_label="extensions",
user_permissions__codename="manage_plugins",
)
if not plugin_permission or not extension_permission:
return
for user in users:
user.user_permissions.remove(extension_permission)
user.user_permissions.add(plugin_permission)
class Migration(migrations.Migration):
dependencies = [
("account", "0039_auto_20200221_0257"),
("plugins", "0001_initial"),
]
operations = [
migrations.RunPython(change_extension_permission_to_plugin_permission),
]
## Instruction:
Remove unused permission from db
## Code After:
from django.db import migrations
def change_extension_permission_to_plugin_permission(apps, schema_editor):
permission = apps.get_model("auth", "Permission")
users = apps.get_model("account", "User")
plugin_permission = permission.objects.filter(
codename="manage_plugins", content_type__app_label="plugins"
).first()
extension_permission = permission.objects.filter(
codename="manage_plugins", content_type__app_label="extensions"
).first()
users = users.objects.filter(
user_permissions__content_type__app_label="extensions",
user_permissions__codename="manage_plugins",
)
if not plugin_permission or not extension_permission:
return
for user in users:
user.user_permissions.remove(extension_permission)
user.user_permissions.add(plugin_permission)
if extension_permission:
extension_permission.delete()
class Migration(migrations.Migration):
dependencies = [
("account", "0039_auto_20200221_0257"),
("plugins", "0001_initial"),
]
operations = [
migrations.RunPython(change_extension_permission_to_plugin_permission),
]
|
from django.db import migrations
def change_extension_permission_to_plugin_permission(apps, schema_editor):
permission = apps.get_model("auth", "Permission")
users = apps.get_model("account", "User")
plugin_permission = permission.objects.filter(
codename="manage_plugins", content_type__app_label="plugins"
).first()
extension_permission = permission.objects.filter(
codename="manage_plugins", content_type__app_label="extensions"
).first()
users = users.objects.filter(
user_permissions__content_type__app_label="extensions",
user_permissions__codename="manage_plugins",
)
if not plugin_permission or not extension_permission:
return
for user in users:
user.user_permissions.remove(extension_permission)
user.user_permissions.add(plugin_permission)
+ if extension_permission:
+ extension_permission.delete()
+
class Migration(migrations.Migration):
dependencies = [
("account", "0039_auto_20200221_0257"),
("plugins", "0001_initial"),
]
operations = [
migrations.RunPython(change_extension_permission_to_plugin_permission),
] |
d2a0d0d22a8369c99626ca754a337ea8076f7efa | aybu/core/models/migrations/versions/587c89cfa8ea_added_column_weight_.py | aybu/core/models/migrations/versions/587c89cfa8ea_added_column_weight_.py |
# downgrade revision identifier, used by Alembic.
revision = '587c89cfa8ea'
down_revision = '2c0bfc379e01'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.add_column('files', sa.Column('weight', sa.Integer(),
nullable=False, default=0))
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_column('files', 'weight')
### end Alembic commands ###
|
# downgrade revision identifier, used by Alembic.
revision = '587c89cfa8ea'
down_revision = '2c0bfc379e01'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.add_column('files', sa.Column('weight',
sa.Integer(),
nullable=True,
default=0))
connection = op.get_bind()
connection.execute('UPDATE files SET weight=0')
op.alter_column('files',
'weight',
existing_type=sa.Integer,
nullable=False)
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_column('files', 'weight')
### end Alembic commands ###
| Fix bug in migration script | Fix bug in migration script
| Python | apache-2.0 | asidev/aybu-core |
# downgrade revision identifier, used by Alembic.
revision = '587c89cfa8ea'
down_revision = '2c0bfc379e01'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
- op.add_column('files', sa.Column('weight', sa.Integer(),
+ op.add_column('files', sa.Column('weight',
+ sa.Integer(),
+ nullable=True,
- nullable=False, default=0))
+ default=0))
- ### end Alembic commands ###
+ connection = op.get_bind()
+ connection.execute('UPDATE files SET weight=0')
+ op.alter_column('files',
+ 'weight',
+ existing_type=sa.Integer,
+ nullable=False)
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_column('files', 'weight')
### end Alembic commands ###
| Fix bug in migration script | ## Code Before:
# downgrade revision identifier, used by Alembic.
revision = '587c89cfa8ea'
down_revision = '2c0bfc379e01'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.add_column('files', sa.Column('weight', sa.Integer(),
nullable=False, default=0))
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_column('files', 'weight')
### end Alembic commands ###
## Instruction:
Fix bug in migration script
## Code After:
# downgrade revision identifier, used by Alembic.
revision = '587c89cfa8ea'
down_revision = '2c0bfc379e01'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.add_column('files', sa.Column('weight',
sa.Integer(),
nullable=True,
default=0))
connection = op.get_bind()
connection.execute('UPDATE files SET weight=0')
op.alter_column('files',
'weight',
existing_type=sa.Integer,
nullable=False)
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_column('files', 'weight')
### end Alembic commands ###
|
# downgrade revision identifier, used by Alembic.
revision = '587c89cfa8ea'
down_revision = '2c0bfc379e01'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
- op.add_column('files', sa.Column('weight', sa.Integer(),
? --------------
+ op.add_column('files', sa.Column('weight',
+ sa.Integer(),
+ nullable=True,
- nullable=False, default=0))
? ----------------
+ default=0))
- ### end Alembic commands ###
+ connection = op.get_bind()
+ connection.execute('UPDATE files SET weight=0')
+ op.alter_column('files',
+ 'weight',
+ existing_type=sa.Integer,
+ nullable=False)
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_column('files', 'weight')
### end Alembic commands ### |
8f4a8c2d463f3ed1592fcd1655de6435b4f2a047 | dataproperty/type/_typecode.py | dataproperty/type/_typecode.py |
from __future__ import absolute_import
class Typecode(object):
NONE = 0
INT = 1 << 0
FLOAT = 1 << 1
STRING = 1 << 2
DATETIME = 1 << 3
INFINITY = 1 << 4
NAN = 1 << 5
BOOL = 1 << 6
DEFAULT_TYPENAME_TABLE = {
NONE: "NONE",
INT: "INTEGER",
FLOAT: "FLOAT",
STRING: "STRING",
DATETIME: "DATETIME",
INFINITY: "INFINITY",
NAN: "NAN",
BOOL: "BOOL",
}
TYPENAME_TABLE = DEFAULT_TYPENAME_TABLE
@classmethod
def get_typename(cls, typecode):
type_name = cls.TYPENAME_TABLE.get(typecode)
if type_name is None:
raise ValueError("unknown typecode: {}".format(typecode))
return type_name
|
from __future__ import absolute_import
class Typecode(object):
NONE = 0
INT = 1 << 0 # delete in the future
INTEGER = 1 << 0
FLOAT = 1 << 1
STRING = 1 << 2
DATETIME = 1 << 3
INFINITY = 1 << 4
NAN = 1 << 5
BOOL = 1 << 6
DEFAULT_TYPENAME_TABLE = {
NONE: "NONE",
INT: "INTEGER",
FLOAT: "FLOAT",
INTEGER: "INTEGER",
STRING: "STRING",
DATETIME: "DATETIME",
INFINITY: "INFINITY",
NAN: "NAN",
BOOL: "BOOL",
}
TYPENAME_TABLE = DEFAULT_TYPENAME_TABLE
@classmethod
def get_typename(cls, typecode):
type_name = cls.TYPENAME_TABLE.get(typecode)
if type_name is None:
raise ValueError("unknown typecode: {}".format(typecode))
return type_name
| Add INTEGER type as alias of INT type | Add INTEGER type as alias of INT type
| Python | mit | thombashi/DataProperty |
from __future__ import absolute_import
class Typecode(object):
NONE = 0
+ INT = 1 << 0 # delete in the future
- INT = 1 << 0
+ INTEGER = 1 << 0
FLOAT = 1 << 1
STRING = 1 << 2
DATETIME = 1 << 3
INFINITY = 1 << 4
NAN = 1 << 5
BOOL = 1 << 6
DEFAULT_TYPENAME_TABLE = {
NONE: "NONE",
INT: "INTEGER",
FLOAT: "FLOAT",
+ INTEGER: "INTEGER",
STRING: "STRING",
DATETIME: "DATETIME",
INFINITY: "INFINITY",
NAN: "NAN",
BOOL: "BOOL",
}
TYPENAME_TABLE = DEFAULT_TYPENAME_TABLE
@classmethod
def get_typename(cls, typecode):
type_name = cls.TYPENAME_TABLE.get(typecode)
if type_name is None:
raise ValueError("unknown typecode: {}".format(typecode))
return type_name
| Add INTEGER type as alias of INT type | ## Code Before:
from __future__ import absolute_import
class Typecode(object):
NONE = 0
INT = 1 << 0
FLOAT = 1 << 1
STRING = 1 << 2
DATETIME = 1 << 3
INFINITY = 1 << 4
NAN = 1 << 5
BOOL = 1 << 6
DEFAULT_TYPENAME_TABLE = {
NONE: "NONE",
INT: "INTEGER",
FLOAT: "FLOAT",
STRING: "STRING",
DATETIME: "DATETIME",
INFINITY: "INFINITY",
NAN: "NAN",
BOOL: "BOOL",
}
TYPENAME_TABLE = DEFAULT_TYPENAME_TABLE
@classmethod
def get_typename(cls, typecode):
type_name = cls.TYPENAME_TABLE.get(typecode)
if type_name is None:
raise ValueError("unknown typecode: {}".format(typecode))
return type_name
## Instruction:
Add INTEGER type as alias of INT type
## Code After:
from __future__ import absolute_import
class Typecode(object):
NONE = 0
INT = 1 << 0 # delete in the future
INTEGER = 1 << 0
FLOAT = 1 << 1
STRING = 1 << 2
DATETIME = 1 << 3
INFINITY = 1 << 4
NAN = 1 << 5
BOOL = 1 << 6
DEFAULT_TYPENAME_TABLE = {
NONE: "NONE",
INT: "INTEGER",
FLOAT: "FLOAT",
INTEGER: "INTEGER",
STRING: "STRING",
DATETIME: "DATETIME",
INFINITY: "INFINITY",
NAN: "NAN",
BOOL: "BOOL",
}
TYPENAME_TABLE = DEFAULT_TYPENAME_TABLE
@classmethod
def get_typename(cls, typecode):
type_name = cls.TYPENAME_TABLE.get(typecode)
if type_name is None:
raise ValueError("unknown typecode: {}".format(typecode))
return type_name
|
from __future__ import absolute_import
class Typecode(object):
NONE = 0
+ INT = 1 << 0 # delete in the future
- INT = 1 << 0
+ INTEGER = 1 << 0
? ++++
FLOAT = 1 << 1
STRING = 1 << 2
DATETIME = 1 << 3
INFINITY = 1 << 4
NAN = 1 << 5
BOOL = 1 << 6
DEFAULT_TYPENAME_TABLE = {
NONE: "NONE",
INT: "INTEGER",
FLOAT: "FLOAT",
+ INTEGER: "INTEGER",
STRING: "STRING",
DATETIME: "DATETIME",
INFINITY: "INFINITY",
NAN: "NAN",
BOOL: "BOOL",
}
TYPENAME_TABLE = DEFAULT_TYPENAME_TABLE
@classmethod
def get_typename(cls, typecode):
type_name = cls.TYPENAME_TABLE.get(typecode)
if type_name is None:
raise ValueError("unknown typecode: {}".format(typecode))
return type_name |
cfcd3aa71001f74915a938aa0ec1ae58c4db3e06 | src/oscar_accounts/__init__.py | src/oscar_accounts/__init__.py | TEMPLATE_DIR = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
'templates/accounts')
default_app_config = 'oscar_accounts.config.OscarAccountsConfig'
| import os
# Setting for template directory not found by app_directories.Loader. This
# allows templates to be identified by two paths which enables a template to be
# extended by a template with the same identifier.
TEMPLATE_DIR = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
'templates/accounts')
default_app_config = 'oscar_accounts.config.OscarAccountsConfig'
| Undo removing `import os` statement | Undo removing `import os` statement
| Python | bsd-3-clause | django-oscar/django-oscar-accounts,django-oscar/django-oscar-accounts | + import os
+
+
+ # Setting for template directory not found by app_directories.Loader. This
+ # allows templates to be identified by two paths which enables a template to be
+ # extended by a template with the same identifier.
TEMPLATE_DIR = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
'templates/accounts')
default_app_config = 'oscar_accounts.config.OscarAccountsConfig'
| Undo removing `import os` statement | ## Code Before:
TEMPLATE_DIR = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
'templates/accounts')
default_app_config = 'oscar_accounts.config.OscarAccountsConfig'
## Instruction:
Undo removing `import os` statement
## Code After:
import os
# Setting for template directory not found by app_directories.Loader. This
# allows templates to be identified by two paths which enables a template to be
# extended by a template with the same identifier.
TEMPLATE_DIR = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
'templates/accounts')
default_app_config = 'oscar_accounts.config.OscarAccountsConfig'
| + import os
+
+
+ # Setting for template directory not found by app_directories.Loader. This
+ # allows templates to be identified by two paths which enables a template to be
+ # extended by a template with the same identifier.
TEMPLATE_DIR = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
'templates/accounts')
default_app_config = 'oscar_accounts.config.OscarAccountsConfig' |
08293b3c679e7079e80fcb1afc1f8b26570a6f2c | mrp_subcontracting/models/mrp_routing_workcenter.py | mrp_subcontracting/models/mrp_routing_workcenter.py | from openerp import models, fields
class MrpRoutingWorkcenter(models.Model):
_inherit = 'mrp.routing.workcenter'
external = fields.Boolean('External', help="Is Subcontract Operation")
semifinished_id = fields.Many2one(
'product.product', 'Semifinished Subcontracting',
domain=[('type', '=', 'product'),
])
picking_type_id = fields.Many2one('stock.picking.type', 'Picking Type',
domain=[('code', '=', 'outgoing')])
| from openerp import models, fields
class MrpRoutingWorkcenter(models.Model):
_inherit = 'mrp.routing.workcenter'
external = fields.Boolean('External', help="Is Subcontract Operation")
semifinished_id = fields.Many2one(
comodel_name='product.product', string='Semifinished Subcontracting')
picking_type_id = fields.Many2one('stock.picking.type', 'Picking Type',
domain=[('code', '=', 'outgoing')])
| Allow to select any type of subcontracting product | [FIX] mrp_subcontracting: Allow to select any type of subcontracting product
| Python | agpl-3.0 | diagramsoftware/odoomrp-wip,agaldona/odoomrp-wip-1,raycarnes/odoomrp-wip,alhashash/odoomrp-wip,esthermm/odoomrp-wip,odoocn/odoomrp-wip,esthermm/odoomrp-wip,oihane/odoomrp-wip,factorlibre/odoomrp-wip,xpansa/odoomrp-wip,maljac/odoomrp-wip,diagramsoftware/odoomrp-wip,dvitme/odoomrp-wip,windedge/odoomrp-wip,odoomrp/odoomrp-wip,sergiocorato/odoomrp-wip,michaeljohn32/odoomrp-wip,Eficent/odoomrp-wip,factorlibre/odoomrp-wip,sergiocorato/odoomrp-wip,jobiols/odoomrp-wip,InakiZabala/odoomrp-wip,alfredoavanzosc/odoomrp-wip-1,ddico/odoomrp-wip,odoomrp/odoomrp-wip,Daniel-CA/odoomrp-wip-public,jorsea/odoomrp-wip,oihane/odoomrp-wip,Daniel-CA/odoomrp-wip-public,agaldona/odoomrp-wip-1,Eficent/odoomrp-wip,invitu/odoomrp-wip,Antiun/odoomrp-wip,jobiols/odoomrp-wip,Endika/odoomrp-wip | from openerp import models, fields
class MrpRoutingWorkcenter(models.Model):
_inherit = 'mrp.routing.workcenter'
external = fields.Boolean('External', help="Is Subcontract Operation")
semifinished_id = fields.Many2one(
- 'product.product', 'Semifinished Subcontracting',
+ comodel_name='product.product', string='Semifinished Subcontracting')
- domain=[('type', '=', 'product'),
- ])
picking_type_id = fields.Many2one('stock.picking.type', 'Picking Type',
domain=[('code', '=', 'outgoing')])
| Allow to select any type of subcontracting product | ## Code Before:
from openerp import models, fields
class MrpRoutingWorkcenter(models.Model):
_inherit = 'mrp.routing.workcenter'
external = fields.Boolean('External', help="Is Subcontract Operation")
semifinished_id = fields.Many2one(
'product.product', 'Semifinished Subcontracting',
domain=[('type', '=', 'product'),
])
picking_type_id = fields.Many2one('stock.picking.type', 'Picking Type',
domain=[('code', '=', 'outgoing')])
## Instruction:
Allow to select any type of subcontracting product
## Code After:
from openerp import models, fields
class MrpRoutingWorkcenter(models.Model):
_inherit = 'mrp.routing.workcenter'
external = fields.Boolean('External', help="Is Subcontract Operation")
semifinished_id = fields.Many2one(
comodel_name='product.product', string='Semifinished Subcontracting')
picking_type_id = fields.Many2one('stock.picking.type', 'Picking Type',
domain=[('code', '=', 'outgoing')])
| from openerp import models, fields
class MrpRoutingWorkcenter(models.Model):
_inherit = 'mrp.routing.workcenter'
external = fields.Boolean('External', help="Is Subcontract Operation")
semifinished_id = fields.Many2one(
- 'product.product', 'Semifinished Subcontracting',
? ^
+ comodel_name='product.product', string='Semifinished Subcontracting')
? +++++++++++++ +++++++ ^
- domain=[('type', '=', 'product'),
- ])
picking_type_id = fields.Many2one('stock.picking.type', 'Picking Type',
domain=[('code', '=', 'outgoing')]) |
475ff9a1b1eed0cd5f1b20f0a42926b735a4c163 | txircd/modules/extra/conn_umodes.py | txircd/modules/extra/conn_umodes.py | from twisted.plugin import IPlugin
from txircd.module_interface import IModuleData, ModuleData
from txircd.utils import ModeType
from zope.interface import implements
class AutoUserModes(ModuleData):
implements(IPlugin, IModuleData)
name = "AutoUserModes"
def actions(self):
return [ ("welcome", 50, self.autoSetUserModes) ]
def autoSetUserModes(self, user):
try:
modes = self.ircd.config["client_umodes_on_connect"]
params = modes.split()
modes = params.pop(0)
parsedModes = []
for mode in modes:
if mode not in self.ircd.userModeTypes:
continue
modeType = self.ircd.userModeTypes[mode]
if modeType in (ModeType.List, ModeType.ParamOnUnset, ModeType.Param):
parsedModes.append((True, mode, params.pop(0)))
else:
parsedModes.append((True, mode, None))
user.setModes(parsedModes, self.ircd.serverID)
except KeyError:
pass # No umodes defined. No action required.
autoUserModes = AutoUserModes() | from twisted.plugin import IPlugin
from txircd.module_interface import IModuleData, ModuleData
from txircd.utils import ModeType
from zope.interface import implements
class AutoUserModes(ModuleData):
implements(IPlugin, IModuleData)
name = "AutoUserModes"
def actions(self):
return [ ("welcome", 50, self.autoSetUserModes) ]
def autoSetUserModes(self, user):
try:
modes = self.ircd.config["client_umodes_on_connect"]
params = modes.split()
modes = params.pop(0)
parsedModes = []
for mode in modes:
if mode not in self.ircd.userModeTypes:
continue
modeType = self.ircd.userModeTypes[mode]
if modeType != ModeType.NoParam:
parsedModes.append((True, mode, params.pop(0)))
else:
parsedModes.append((True, mode, None))
user.setModes(parsedModes, self.ircd.serverID)
except KeyError:
pass # No umodes defined. No action required.
autoUserModes = AutoUserModes() | Simplify the AutoUserModes mode type check | Simplify the AutoUserModes mode type check
| Python | bsd-3-clause | ElementalAlchemist/txircd,Heufneutje/txircd | from twisted.plugin import IPlugin
from txircd.module_interface import IModuleData, ModuleData
from txircd.utils import ModeType
from zope.interface import implements
class AutoUserModes(ModuleData):
implements(IPlugin, IModuleData)
name = "AutoUserModes"
def actions(self):
return [ ("welcome", 50, self.autoSetUserModes) ]
def autoSetUserModes(self, user):
try:
modes = self.ircd.config["client_umodes_on_connect"]
params = modes.split()
modes = params.pop(0)
parsedModes = []
for mode in modes:
if mode not in self.ircd.userModeTypes:
continue
modeType = self.ircd.userModeTypes[mode]
- if modeType in (ModeType.List, ModeType.ParamOnUnset, ModeType.Param):
+ if modeType != ModeType.NoParam:
parsedModes.append((True, mode, params.pop(0)))
else:
parsedModes.append((True, mode, None))
user.setModes(parsedModes, self.ircd.serverID)
except KeyError:
pass # No umodes defined. No action required.
autoUserModes = AutoUserModes() | Simplify the AutoUserModes mode type check | ## Code Before:
from twisted.plugin import IPlugin
from txircd.module_interface import IModuleData, ModuleData
from txircd.utils import ModeType
from zope.interface import implements
class AutoUserModes(ModuleData):
implements(IPlugin, IModuleData)
name = "AutoUserModes"
def actions(self):
return [ ("welcome", 50, self.autoSetUserModes) ]
def autoSetUserModes(self, user):
try:
modes = self.ircd.config["client_umodes_on_connect"]
params = modes.split()
modes = params.pop(0)
parsedModes = []
for mode in modes:
if mode not in self.ircd.userModeTypes:
continue
modeType = self.ircd.userModeTypes[mode]
if modeType in (ModeType.List, ModeType.ParamOnUnset, ModeType.Param):
parsedModes.append((True, mode, params.pop(0)))
else:
parsedModes.append((True, mode, None))
user.setModes(parsedModes, self.ircd.serverID)
except KeyError:
pass # No umodes defined. No action required.
autoUserModes = AutoUserModes()
## Instruction:
Simplify the AutoUserModes mode type check
## Code After:
from twisted.plugin import IPlugin
from txircd.module_interface import IModuleData, ModuleData
from txircd.utils import ModeType
from zope.interface import implements
class AutoUserModes(ModuleData):
implements(IPlugin, IModuleData)
name = "AutoUserModes"
def actions(self):
return [ ("welcome", 50, self.autoSetUserModes) ]
def autoSetUserModes(self, user):
try:
modes = self.ircd.config["client_umodes_on_connect"]
params = modes.split()
modes = params.pop(0)
parsedModes = []
for mode in modes:
if mode not in self.ircd.userModeTypes:
continue
modeType = self.ircd.userModeTypes[mode]
if modeType != ModeType.NoParam:
parsedModes.append((True, mode, params.pop(0)))
else:
parsedModes.append((True, mode, None))
user.setModes(parsedModes, self.ircd.serverID)
except KeyError:
pass # No umodes defined. No action required.
autoUserModes = AutoUserModes() | from twisted.plugin import IPlugin
from txircd.module_interface import IModuleData, ModuleData
from txircd.utils import ModeType
from zope.interface import implements
class AutoUserModes(ModuleData):
implements(IPlugin, IModuleData)
name = "AutoUserModes"
def actions(self):
return [ ("welcome", 50, self.autoSetUserModes) ]
def autoSetUserModes(self, user):
try:
modes = self.ircd.config["client_umodes_on_connect"]
params = modes.split()
modes = params.pop(0)
parsedModes = []
for mode in modes:
if mode not in self.ircd.userModeTypes:
continue
modeType = self.ircd.userModeTypes[mode]
- if modeType in (ModeType.List, ModeType.ParamOnUnset, ModeType.Param):
+ if modeType != ModeType.NoParam:
parsedModes.append((True, mode, params.pop(0)))
else:
parsedModes.append((True, mode, None))
user.setModes(parsedModes, self.ircd.serverID)
except KeyError:
pass # No umodes defined. No action required.
autoUserModes = AutoUserModes() |
e30d433153d9ad2f1d931f7f48b0ebbe9ba6763c | modules/new_module/new_module.py | modules/new_module/new_module.py |
from models import custom_modules
from . import handlers
def register_module():
"""Registers this module in the registry."""
global_urls = [
('/new-global-url', handlers.NewURLHandler) # Global URLs go on mycourse.appspot.com/url
]
course_urls = [
('/new-course-url', handlers.NewURLHandler)
] # Course URLs go on mycourse.appspot.com/course-name/url
global custom_module
custom_module = custom_modules.Module(
'New module title (has to be unique)',
'Implements some functionality',
global_urls, course_urls)
return custom_module
|
import logging
from models import custom_modules
from . import handlers
def register_module():
"""Registers this module in the registry."""
def on_module_enabled():
logging.info('Module new_module.py was just enabled')
def on_module_disabled():
logging.info('Module new_module.py was just dissabled')
global_urls = [
('/new-global-url', handlers.NewURLHandler) # Global URLs go on mycourse.appspot.com/url
]
course_urls = [
('/new-course-url', handlers.NewURLHandler)
] # Course URLs go on mycourse.appspot.com/course-name/url
global custom_module
custom_module = custom_modules.Module(
'New module title (has to be unique)',
'Implements some functionality',
global_urls, course_urls,
notify_module_disabled=on_module_disabled,
notify_module_enabled=on_module_enabled)
return custom_module
| Add enable and dissable hooks | Add enable and dissable hooks
| Python | apache-2.0 | UniMOOC/gcb-new-module,UniMOOC/gcb-new-module,UniMOOC/gcb-new-module,UniMOOC/gcb-new-module | +
+ import logging
from models import custom_modules
from . import handlers
def register_module():
"""Registers this module in the registry."""
+
+ def on_module_enabled():
+ logging.info('Module new_module.py was just enabled')
+
+ def on_module_disabled():
+ logging.info('Module new_module.py was just dissabled')
global_urls = [
('/new-global-url', handlers.NewURLHandler) # Global URLs go on mycourse.appspot.com/url
]
course_urls = [
('/new-course-url', handlers.NewURLHandler)
] # Course URLs go on mycourse.appspot.com/course-name/url
global custom_module
custom_module = custom_modules.Module(
'New module title (has to be unique)',
'Implements some functionality',
- global_urls, course_urls)
+ global_urls, course_urls,
+ notify_module_disabled=on_module_disabled,
+ notify_module_enabled=on_module_enabled)
return custom_module
| Add enable and dissable hooks | ## Code Before:
from models import custom_modules
from . import handlers
def register_module():
"""Registers this module in the registry."""
global_urls = [
('/new-global-url', handlers.NewURLHandler) # Global URLs go on mycourse.appspot.com/url
]
course_urls = [
('/new-course-url', handlers.NewURLHandler)
] # Course URLs go on mycourse.appspot.com/course-name/url
global custom_module
custom_module = custom_modules.Module(
'New module title (has to be unique)',
'Implements some functionality',
global_urls, course_urls)
return custom_module
## Instruction:
Add enable and dissable hooks
## Code After:
import logging
from models import custom_modules
from . import handlers
def register_module():
"""Registers this module in the registry."""
def on_module_enabled():
logging.info('Module new_module.py was just enabled')
def on_module_disabled():
logging.info('Module new_module.py was just dissabled')
global_urls = [
('/new-global-url', handlers.NewURLHandler) # Global URLs go on mycourse.appspot.com/url
]
course_urls = [
('/new-course-url', handlers.NewURLHandler)
] # Course URLs go on mycourse.appspot.com/course-name/url
global custom_module
custom_module = custom_modules.Module(
'New module title (has to be unique)',
'Implements some functionality',
global_urls, course_urls,
notify_module_disabled=on_module_disabled,
notify_module_enabled=on_module_enabled)
return custom_module
| +
+ import logging
from models import custom_modules
from . import handlers
def register_module():
"""Registers this module in the registry."""
+
+ def on_module_enabled():
+ logging.info('Module new_module.py was just enabled')
+
+ def on_module_disabled():
+ logging.info('Module new_module.py was just dissabled')
global_urls = [
('/new-global-url', handlers.NewURLHandler) # Global URLs go on mycourse.appspot.com/url
]
course_urls = [
('/new-course-url', handlers.NewURLHandler)
] # Course URLs go on mycourse.appspot.com/course-name/url
global custom_module
custom_module = custom_modules.Module(
'New module title (has to be unique)',
'Implements some functionality',
- global_urls, course_urls)
? ^
+ global_urls, course_urls,
? ^
+ notify_module_disabled=on_module_disabled,
+ notify_module_enabled=on_module_enabled)
return custom_module |
8c6940a82b4504786e221f0603b8995db41adcae | reddit2telegram/channels/r_wholesome/app.py | reddit2telegram/channels/r_wholesome/app.py |
subreddit = 'wholesome'
t_channel = '@r_wholesome'
def send_post(submission, r2t):
return r2t.send_simple(submission)
|
subreddit = 'wholesome+WholesomeComics+wholesomegifs+wholesomepics+wholesomememes'
t_channel = '@r_wholesome'
def send_post(submission, r2t):
return r2t.send_simple(submission)
| Add a few subreddits to @r_wholesome | Add a few subreddits to @r_wholesome | Python | mit | Fillll/reddit2telegram,Fillll/reddit2telegram |
- subreddit = 'wholesome'
+ subreddit = 'wholesome+WholesomeComics+wholesomegifs+wholesomepics+wholesomememes'
t_channel = '@r_wholesome'
def send_post(submission, r2t):
return r2t.send_simple(submission)
| Add a few subreddits to @r_wholesome | ## Code Before:
subreddit = 'wholesome'
t_channel = '@r_wholesome'
def send_post(submission, r2t):
return r2t.send_simple(submission)
## Instruction:
Add a few subreddits to @r_wholesome
## Code After:
subreddit = 'wholesome+WholesomeComics+wholesomegifs+wholesomepics+wholesomememes'
t_channel = '@r_wholesome'
def send_post(submission, r2t):
return r2t.send_simple(submission)
|
- subreddit = 'wholesome'
+ subreddit = 'wholesome+WholesomeComics+wholesomegifs+wholesomepics+wholesomememes'
t_channel = '@r_wholesome'
def send_post(submission, r2t):
return r2t.send_simple(submission) |
d09e2831d95a2bc045da75496c70337246e77d5f | BoxAndWhisker.py | BoxAndWhisker.py | from matplotlib import pyplot
from PlotInfo import *
class BoxAndWhisker(PlotInfo):
"""
Box and whisker plots
"""
def __init__(self):
super(BoxAndWhisker,self).__init__("boxplot")
self.width=None
self.color="black"
self.label = None
self.xSequence = []
def draw(self, fig, axis, transform=None):
# To be compatible with PlotInfo assumptions
self.xValues = range(1,len(self.xSequence)+1)
self.yValues = [0 for x in self.xValues]
super(BoxAndWhisker,self).draw(fig, axis)
kwdict = {}
plotHandles = axis.boxplot(self.xSequence, **kwdict)
# Picking which part of the plot to use in the legend may
# require more thought as there are multiple lines in the
# boxplot, as well as the possibility for outliers.
# Options are ['medians', 'fliers', 'whiskers', 'boxes', 'caps']
return [plotHandles['medians'], [self.label]]
| from matplotlib import pyplot
from PlotInfo import *
from Marker import Marker
class BoxAndWhisker(PlotInfo):
"""
Box and whisker plots
"""
def __init__(self):
super(BoxAndWhisker,self).__init__("boxplot")
self.width=None
self.color="black"
self.label = None
self.xSequence = []
self.flierMarker = Marker()
self.flierMarker.marker = '+'
self.flierMarker.color = 'b'
def draw(self, fig, axis, transform=None):
# To be compatible with PlotInfo assumptions
self.xValues = range(1,len(self.xSequence)+1)
self.yValues = [0 for x in self.xValues]
super(BoxAndWhisker,self).draw(fig, axis)
kwdict = {}
if self.flierMarker.marker is not None:
kwdict["sym"] = self.flierMarker.marker
else:
kwdict["sym"] = ''
plotHandles = axis.boxplot(self.xSequence, **kwdict)
# Picking which part of the plot to use in the legend may
# require more thought as there are multiple lines in the
# boxplot, as well as the possibility for outliers.
# Options are ['medians', 'fliers', 'whiskers', 'boxes', 'caps']
return [plotHandles['medians'], [self.label]]
| Allow flier markers in box-and-whisker plots to be modified. | Allow flier markers in box-and-whisker plots to be modified.
| Python | bsd-3-clause | alexras/boomslang | from matplotlib import pyplot
from PlotInfo import *
+ from Marker import Marker
class BoxAndWhisker(PlotInfo):
"""
Box and whisker plots
"""
def __init__(self):
super(BoxAndWhisker,self).__init__("boxplot")
self.width=None
self.color="black"
self.label = None
self.xSequence = []
+ self.flierMarker = Marker()
+ self.flierMarker.marker = '+'
+ self.flierMarker.color = 'b'
def draw(self, fig, axis, transform=None):
# To be compatible with PlotInfo assumptions
self.xValues = range(1,len(self.xSequence)+1)
self.yValues = [0 for x in self.xValues]
super(BoxAndWhisker,self).draw(fig, axis)
kwdict = {}
+ if self.flierMarker.marker is not None:
+ kwdict["sym"] = self.flierMarker.marker
+ else:
+ kwdict["sym"] = ''
+
plotHandles = axis.boxplot(self.xSequence, **kwdict)
# Picking which part of the plot to use in the legend may
# require more thought as there are multiple lines in the
# boxplot, as well as the possibility for outliers.
# Options are ['medians', 'fliers', 'whiskers', 'boxes', 'caps']
return [plotHandles['medians'], [self.label]]
| Allow flier markers in box-and-whisker plots to be modified. | ## Code Before:
from matplotlib import pyplot
from PlotInfo import *
class BoxAndWhisker(PlotInfo):
"""
Box and whisker plots
"""
def __init__(self):
super(BoxAndWhisker,self).__init__("boxplot")
self.width=None
self.color="black"
self.label = None
self.xSequence = []
def draw(self, fig, axis, transform=None):
# To be compatible with PlotInfo assumptions
self.xValues = range(1,len(self.xSequence)+1)
self.yValues = [0 for x in self.xValues]
super(BoxAndWhisker,self).draw(fig, axis)
kwdict = {}
plotHandles = axis.boxplot(self.xSequence, **kwdict)
# Picking which part of the plot to use in the legend may
# require more thought as there are multiple lines in the
# boxplot, as well as the possibility for outliers.
# Options are ['medians', 'fliers', 'whiskers', 'boxes', 'caps']
return [plotHandles['medians'], [self.label]]
## Instruction:
Allow flier markers in box-and-whisker plots to be modified.
## Code After:
from matplotlib import pyplot
from PlotInfo import *
from Marker import Marker
class BoxAndWhisker(PlotInfo):
"""
Box and whisker plots
"""
def __init__(self):
super(BoxAndWhisker,self).__init__("boxplot")
self.width=None
self.color="black"
self.label = None
self.xSequence = []
self.flierMarker = Marker()
self.flierMarker.marker = '+'
self.flierMarker.color = 'b'
def draw(self, fig, axis, transform=None):
# To be compatible with PlotInfo assumptions
self.xValues = range(1,len(self.xSequence)+1)
self.yValues = [0 for x in self.xValues]
super(BoxAndWhisker,self).draw(fig, axis)
kwdict = {}
if self.flierMarker.marker is not None:
kwdict["sym"] = self.flierMarker.marker
else:
kwdict["sym"] = ''
plotHandles = axis.boxplot(self.xSequence, **kwdict)
# Picking which part of the plot to use in the legend may
# require more thought as there are multiple lines in the
# boxplot, as well as the possibility for outliers.
# Options are ['medians', 'fliers', 'whiskers', 'boxes', 'caps']
return [plotHandles['medians'], [self.label]]
| from matplotlib import pyplot
from PlotInfo import *
+ from Marker import Marker
class BoxAndWhisker(PlotInfo):
"""
Box and whisker plots
"""
def __init__(self):
super(BoxAndWhisker,self).__init__("boxplot")
self.width=None
self.color="black"
self.label = None
self.xSequence = []
+ self.flierMarker = Marker()
+ self.flierMarker.marker = '+'
+ self.flierMarker.color = 'b'
def draw(self, fig, axis, transform=None):
# To be compatible with PlotInfo assumptions
self.xValues = range(1,len(self.xSequence)+1)
self.yValues = [0 for x in self.xValues]
super(BoxAndWhisker,self).draw(fig, axis)
kwdict = {}
+ if self.flierMarker.marker is not None:
+ kwdict["sym"] = self.flierMarker.marker
+ else:
+ kwdict["sym"] = ''
+
plotHandles = axis.boxplot(self.xSequence, **kwdict)
# Picking which part of the plot to use in the legend may
# require more thought as there are multiple lines in the
# boxplot, as well as the possibility for outliers.
# Options are ['medians', 'fliers', 'whiskers', 'boxes', 'caps']
return [plotHandles['medians'], [self.label]] |
85123f01f1e63b4fc7688e13104ee59c6efb263a | proscli/main.py | proscli/main.py | import click
import proscli
from proscli.utils import default_options
def main():
# the program name should always be pros. don't care if it's not...
try:
cli.main(prog_name='pros')
except KeyboardInterrupt:
click.echo('Aborted!')
pass
import prosconductor.providers.utils
@proscli.flasher_cli.command('help', short_help='Show this message and exit.')
@click.argument('ignore', nargs=-1, expose_value=False)
@default_options
@click.pass_context
def help_cmd(ctx):
click.echo(prosconductor.providers.utils.get_all_available_templates())
@click.command('pros',
cls=click.CommandCollection,
context_settings=dict(help_option_names=['-h', '--help']),
sources=[proscli.terminal_cli, proscli.build_cli, proscli.flasher_cli, proscli.conductor_cli])
@click.version_option(version='2.1.923', prog_name='pros')
@default_options
def cli():
pass
if __name__ == '__main__':
main()
| import click
import proscli
from proscli.utils import default_options
def main():
# the program name should always be pros. don't care if it's not...
try:
cli.main(prog_name='pros')
except KeyboardInterrupt:
click.echo('Aborted!')
pass
@click.command('pros',
cls=click.CommandCollection,
context_settings=dict(help_option_names=['-h', '--help']),
sources=[proscli.terminal_cli, proscli.build_cli, proscli.flasher_cli, proscli.conductor_cli])
@click.version_option(version='2.1.925', prog_name='pros')
@default_options
def cli():
pass
if __name__ == '__main__':
main()
| Remove deprecated and broken pros help option | Remove deprecated and broken pros help option
| Python | mpl-2.0 | purduesigbots/pros-cli,purduesigbots/purdueros-cli | import click
import proscli
from proscli.utils import default_options
def main():
# the program name should always be pros. don't care if it's not...
try:
cli.main(prog_name='pros')
except KeyboardInterrupt:
click.echo('Aborted!')
pass
- import prosconductor.providers.utils
-
- @proscli.flasher_cli.command('help', short_help='Show this message and exit.')
- @click.argument('ignore', nargs=-1, expose_value=False)
- @default_options
- @click.pass_context
- def help_cmd(ctx):
- click.echo(prosconductor.providers.utils.get_all_available_templates())
-
@click.command('pros',
cls=click.CommandCollection,
context_settings=dict(help_option_names=['-h', '--help']),
sources=[proscli.terminal_cli, proscli.build_cli, proscli.flasher_cli, proscli.conductor_cli])
- @click.version_option(version='2.1.923', prog_name='pros')
+ @click.version_option(version='2.1.925', prog_name='pros')
@default_options
def cli():
pass
if __name__ == '__main__':
main()
| Remove deprecated and broken pros help option | ## Code Before:
import click
import proscli
from proscli.utils import default_options
def main():
# the program name should always be pros. don't care if it's not...
try:
cli.main(prog_name='pros')
except KeyboardInterrupt:
click.echo('Aborted!')
pass
import prosconductor.providers.utils
@proscli.flasher_cli.command('help', short_help='Show this message and exit.')
@click.argument('ignore', nargs=-1, expose_value=False)
@default_options
@click.pass_context
def help_cmd(ctx):
click.echo(prosconductor.providers.utils.get_all_available_templates())
@click.command('pros',
cls=click.CommandCollection,
context_settings=dict(help_option_names=['-h', '--help']),
sources=[proscli.terminal_cli, proscli.build_cli, proscli.flasher_cli, proscli.conductor_cli])
@click.version_option(version='2.1.923', prog_name='pros')
@default_options
def cli():
pass
if __name__ == '__main__':
main()
## Instruction:
Remove deprecated and broken pros help option
## Code After:
import click
import proscli
from proscli.utils import default_options
def main():
# the program name should always be pros. don't care if it's not...
try:
cli.main(prog_name='pros')
except KeyboardInterrupt:
click.echo('Aborted!')
pass
@click.command('pros',
cls=click.CommandCollection,
context_settings=dict(help_option_names=['-h', '--help']),
sources=[proscli.terminal_cli, proscli.build_cli, proscli.flasher_cli, proscli.conductor_cli])
@click.version_option(version='2.1.925', prog_name='pros')
@default_options
def cli():
pass
if __name__ == '__main__':
main()
| import click
import proscli
from proscli.utils import default_options
def main():
# the program name should always be pros. don't care if it's not...
try:
cli.main(prog_name='pros')
except KeyboardInterrupt:
click.echo('Aborted!')
pass
- import prosconductor.providers.utils
-
- @proscli.flasher_cli.command('help', short_help='Show this message and exit.')
- @click.argument('ignore', nargs=-1, expose_value=False)
- @default_options
- @click.pass_context
- def help_cmd(ctx):
- click.echo(prosconductor.providers.utils.get_all_available_templates())
-
@click.command('pros',
cls=click.CommandCollection,
context_settings=dict(help_option_names=['-h', '--help']),
sources=[proscli.terminal_cli, proscli.build_cli, proscli.flasher_cli, proscli.conductor_cli])
- @click.version_option(version='2.1.923', prog_name='pros')
? ^
+ @click.version_option(version='2.1.925', prog_name='pros')
? ^
@default_options
def cli():
pass
if __name__ == '__main__':
main() |
a66d15d95e7ec62da12ccade0894e78e8dba6673 | cappa/factory.py | cappa/factory.py | from __future__ import print_function, absolute_import
from .pip import Pip
from .pip3 import Pip3
from .pip_pypy import PipPypy
from .apt import Apt
from .bower import Bower
from .npm import Npm
from .npmg import NpmG
from .tsd import Tsd
from .private.pip import PrivatePip
def manager_key_to_cappa(manager_key):
if manager_key == 'pip':
return Pip
elif manager_key == 'pip3':
return Pip3
elif manager_key == 'pip_pypy':
return PipPypy
elif manager_key == 'sys':
return Apt
elif manager_key == 'npm':
return Npm
elif manager_key == 'npmg':
return NpmG
elif manager_key == 'bower':
return Bower
elif manager_key == 'tsd':
return Tsd
else:
raise UnknownManager('{} is not a supported manager.'.format(manager_key))
def private_manager_key_to_cappa(manager_key):
if manager_key == 'pip':
return PrivatePip
else:
raise UnknownManager('{} is not a supported private repo manager.'.format(manager_key))
| from __future__ import print_function, absolute_import
from .pip import Pip
from .pip3 import Pip3
from .pip_pypy import PipPypy
from .apt import Apt
from .bower import Bower
from .npm import Npm
from .npmg import NpmG
from .tsd import Tsd
from .private.pip import PrivatePip
MANAGER_MAP = {
'pip': Pip,
'pip3': Pip3,
'pip_pypy': PipPypy,
'sys': Apt,
'npm': Npm,
'npmg': NpmG,
'bower': Bower,
'tsd': Tsd
}
PRIVATE_MANAGER_MAP = {
'pip': PrivatePip
}
def manager_key_to_cappa(manager_key):
if manager_key in MANAGER_MAP:
return MANAGER_MAP[manager_key]
else:
raise UnknownManager('{} is not a supported manager.'.format(manager_key))
def private_manager_key_to_cappa(manager_key):
if manager_key in PRIVATE_MANAGER_MAP:
return PrivatePip
else:
raise UnknownManager('{} is not a supported private repo manager.'.format(manager_key))
| Switch if-else block to dictionary lookup | Switch if-else block to dictionary lookup
| Python | mit | Captricity/cappa,Captricity/cappa | from __future__ import print_function, absolute_import
from .pip import Pip
from .pip3 import Pip3
from .pip_pypy import PipPypy
from .apt import Apt
from .bower import Bower
from .npm import Npm
from .npmg import NpmG
from .tsd import Tsd
from .private.pip import PrivatePip
+ MANAGER_MAP = {
+ 'pip': Pip,
+ 'pip3': Pip3,
+ 'pip_pypy': PipPypy,
+ 'sys': Apt,
+ 'npm': Npm,
+ 'npmg': NpmG,
+ 'bower': Bower,
+ 'tsd': Tsd
+ }
+ PRIVATE_MANAGER_MAP = {
+ 'pip': PrivatePip
+ }
+
+
def manager_key_to_cappa(manager_key):
+ if manager_key in MANAGER_MAP:
+ return MANAGER_MAP[manager_key]
- if manager_key == 'pip':
- return Pip
- elif manager_key == 'pip3':
- return Pip3
- elif manager_key == 'pip_pypy':
- return PipPypy
- elif manager_key == 'sys':
- return Apt
- elif manager_key == 'npm':
- return Npm
- elif manager_key == 'npmg':
- return NpmG
- elif manager_key == 'bower':
- return Bower
- elif manager_key == 'tsd':
- return Tsd
else:
raise UnknownManager('{} is not a supported manager.'.format(manager_key))
def private_manager_key_to_cappa(manager_key):
- if manager_key == 'pip':
+ if manager_key in PRIVATE_MANAGER_MAP:
return PrivatePip
else:
raise UnknownManager('{} is not a supported private repo manager.'.format(manager_key))
| Switch if-else block to dictionary lookup | ## Code Before:
from __future__ import print_function, absolute_import
from .pip import Pip
from .pip3 import Pip3
from .pip_pypy import PipPypy
from .apt import Apt
from .bower import Bower
from .npm import Npm
from .npmg import NpmG
from .tsd import Tsd
from .private.pip import PrivatePip
def manager_key_to_cappa(manager_key):
if manager_key == 'pip':
return Pip
elif manager_key == 'pip3':
return Pip3
elif manager_key == 'pip_pypy':
return PipPypy
elif manager_key == 'sys':
return Apt
elif manager_key == 'npm':
return Npm
elif manager_key == 'npmg':
return NpmG
elif manager_key == 'bower':
return Bower
elif manager_key == 'tsd':
return Tsd
else:
raise UnknownManager('{} is not a supported manager.'.format(manager_key))
def private_manager_key_to_cappa(manager_key):
if manager_key == 'pip':
return PrivatePip
else:
raise UnknownManager('{} is not a supported private repo manager.'.format(manager_key))
## Instruction:
Switch if-else block to dictionary lookup
## Code After:
from __future__ import print_function, absolute_import
from .pip import Pip
from .pip3 import Pip3
from .pip_pypy import PipPypy
from .apt import Apt
from .bower import Bower
from .npm import Npm
from .npmg import NpmG
from .tsd import Tsd
from .private.pip import PrivatePip
MANAGER_MAP = {
'pip': Pip,
'pip3': Pip3,
'pip_pypy': PipPypy,
'sys': Apt,
'npm': Npm,
'npmg': NpmG,
'bower': Bower,
'tsd': Tsd
}
PRIVATE_MANAGER_MAP = {
'pip': PrivatePip
}
def manager_key_to_cappa(manager_key):
if manager_key in MANAGER_MAP:
return MANAGER_MAP[manager_key]
else:
raise UnknownManager('{} is not a supported manager.'.format(manager_key))
def private_manager_key_to_cappa(manager_key):
if manager_key in PRIVATE_MANAGER_MAP:
return PrivatePip
else:
raise UnknownManager('{} is not a supported private repo manager.'.format(manager_key))
| from __future__ import print_function, absolute_import
from .pip import Pip
from .pip3 import Pip3
from .pip_pypy import PipPypy
from .apt import Apt
from .bower import Bower
from .npm import Npm
from .npmg import NpmG
from .tsd import Tsd
from .private.pip import PrivatePip
+ MANAGER_MAP = {
+ 'pip': Pip,
+ 'pip3': Pip3,
+ 'pip_pypy': PipPypy,
+ 'sys': Apt,
+ 'npm': Npm,
+ 'npmg': NpmG,
+ 'bower': Bower,
+ 'tsd': Tsd
+ }
+ PRIVATE_MANAGER_MAP = {
+ 'pip': PrivatePip
+ }
+
+
def manager_key_to_cappa(manager_key):
+ if manager_key in MANAGER_MAP:
+ return MANAGER_MAP[manager_key]
- if manager_key == 'pip':
- return Pip
- elif manager_key == 'pip3':
- return Pip3
- elif manager_key == 'pip_pypy':
- return PipPypy
- elif manager_key == 'sys':
- return Apt
- elif manager_key == 'npm':
- return Npm
- elif manager_key == 'npmg':
- return NpmG
- elif manager_key == 'bower':
- return Bower
- elif manager_key == 'tsd':
- return Tsd
else:
raise UnknownManager('{} is not a supported manager.'.format(manager_key))
def private_manager_key_to_cappa(manager_key):
- if manager_key == 'pip':
+ if manager_key in PRIVATE_MANAGER_MAP:
return PrivatePip
else:
raise UnknownManager('{} is not a supported private repo manager.'.format(manager_key)) |
e4e8c4e3b98e122e5cf4c9c349c4fb2abfe00ab1 | api/bioguide/models.py | api/bioguide/models.py | from django.db import models
class Legislator(models.Model):
"""Model representing a legislator in a session of congress.
"""
bioguide_id = models.CharField(max_length=7, db_index=True)
prefix = models.CharField(max_length=16)
first = models.CharField(max_length=64)
last = models.CharField(max_length=64)
suffix = models.CharField(max_length=16)
birth_death = models.CharField(max_length=16)
position = models.CharField(max_length=24)
party = models.CharField(max_length=32)
state = models.CharField(max_length=2)
congress = models.CharField(max_length=3)
class Meta:
unique_together = (('bioguide_id', 'congress', ))
def __unicode__(self):
return ' '.join([self.prefix, self.first, self.last, self.suffix, ])
| from django.db import models
class Legislator(models.Model):
"""Model representing a legislator in a session of congress.
"""
bioguide_id = models.CharField(max_length=7, db_index=True)
prefix = models.CharField(max_length=16)
first = models.CharField(max_length=64)
last = models.CharField(max_length=64)
suffix = models.CharField(max_length=16)
birth_death = models.CharField(max_length=16)
position = models.CharField(max_length=24)
party = models.CharField(max_length=32)
state = models.CharField(max_length=2)
congress = models.CharField(max_length=3)
class Meta:
unique_together = (('bioguide_id', 'congress', 'position', ))
def __unicode__(self):
return ' '.join([self.prefix, self.first, self.last, self.suffix, ])
| Add 'position' to unique_together constraint, to account for members who serve in both houses during a Congress (h/t @derekwillis) | Add 'position' to unique_together constraint, to account for members who serve in both houses during a Congress (h/t @derekwillis)
| Python | bsd-3-clause | propublica/Capitol-Words,sunlightlabs/Capitol-Words,sunlightlabs/Capitol-Words,sunlightlabs/Capitol-Words,propublica/Capitol-Words,sunlightlabs/Capitol-Words,propublica/Capitol-Words,sunlightlabs/Capitol-Words,sunlightlabs/Capitol-Words,propublica/Capitol-Words,sunlightlabs/Capitol-Words | from django.db import models
class Legislator(models.Model):
"""Model representing a legislator in a session of congress.
"""
bioguide_id = models.CharField(max_length=7, db_index=True)
prefix = models.CharField(max_length=16)
first = models.CharField(max_length=64)
last = models.CharField(max_length=64)
suffix = models.CharField(max_length=16)
birth_death = models.CharField(max_length=16)
position = models.CharField(max_length=24)
party = models.CharField(max_length=32)
state = models.CharField(max_length=2)
congress = models.CharField(max_length=3)
class Meta:
- unique_together = (('bioguide_id', 'congress', ))
+ unique_together = (('bioguide_id', 'congress', 'position', ))
def __unicode__(self):
return ' '.join([self.prefix, self.first, self.last, self.suffix, ])
| Add 'position' to unique_together constraint, to account for members who serve in both houses during a Congress (h/t @derekwillis) | ## Code Before:
from django.db import models
class Legislator(models.Model):
"""Model representing a legislator in a session of congress.
"""
bioguide_id = models.CharField(max_length=7, db_index=True)
prefix = models.CharField(max_length=16)
first = models.CharField(max_length=64)
last = models.CharField(max_length=64)
suffix = models.CharField(max_length=16)
birth_death = models.CharField(max_length=16)
position = models.CharField(max_length=24)
party = models.CharField(max_length=32)
state = models.CharField(max_length=2)
congress = models.CharField(max_length=3)
class Meta:
unique_together = (('bioguide_id', 'congress', ))
def __unicode__(self):
return ' '.join([self.prefix, self.first, self.last, self.suffix, ])
## Instruction:
Add 'position' to unique_together constraint, to account for members who serve in both houses during a Congress (h/t @derekwillis)
## Code After:
from django.db import models
class Legislator(models.Model):
"""Model representing a legislator in a session of congress.
"""
bioguide_id = models.CharField(max_length=7, db_index=True)
prefix = models.CharField(max_length=16)
first = models.CharField(max_length=64)
last = models.CharField(max_length=64)
suffix = models.CharField(max_length=16)
birth_death = models.CharField(max_length=16)
position = models.CharField(max_length=24)
party = models.CharField(max_length=32)
state = models.CharField(max_length=2)
congress = models.CharField(max_length=3)
class Meta:
unique_together = (('bioguide_id', 'congress', 'position', ))
def __unicode__(self):
return ' '.join([self.prefix, self.first, self.last, self.suffix, ])
| from django.db import models
class Legislator(models.Model):
"""Model representing a legislator in a session of congress.
"""
bioguide_id = models.CharField(max_length=7, db_index=True)
prefix = models.CharField(max_length=16)
first = models.CharField(max_length=64)
last = models.CharField(max_length=64)
suffix = models.CharField(max_length=16)
birth_death = models.CharField(max_length=16)
position = models.CharField(max_length=24)
party = models.CharField(max_length=32)
state = models.CharField(max_length=2)
congress = models.CharField(max_length=3)
class Meta:
- unique_together = (('bioguide_id', 'congress', ))
+ unique_together = (('bioguide_id', 'congress', 'position', ))
? ++++++++++++
def __unicode__(self):
return ' '.join([self.prefix, self.first, self.last, self.suffix, ]) |
b7d8e70bf74be142f70bf12635a4bb1632d166ed | funnel/forms/label.py | funnel/forms/label.py |
from baseframe import __
import baseframe.forms as forms
__all__ = ['LabelForm', 'LabelOptionForm']
class LabelForm(forms.Form):
name = forms.StringField(
"", widget=forms.HiddenInput(), validators=[forms.validators.Optional()]
)
title = forms.StringField(
__("Label"),
validators=[
forms.validators.DataRequired(__(u"This can’t be empty")),
forms.validators.Length(max=250),
],
filters=[forms.filters.strip()],
)
icon_emoji = forms.StringField("")
required = forms.BooleanField(
__("Make this label mandatory in proposal forms"),
default=False,
description=__("If checked, proposers must select one of the options"),
)
restricted = forms.BooleanField(
__("Restrict use of this label to editors"),
default=False,
description=__(
"If checked, only editors and reviewers can apply this label on proposals"
),
)
class LabelOptionForm(forms.Form):
name = forms.StringField(
"", widget=forms.HiddenInput(), validators=[forms.validators.Optional()]
)
title = forms.StringField(
__("Option"),
validators=[
forms.validators.DataRequired(__(u"This can’t be empty")),
forms.validators.Length(max=250),
],
filters=[forms.filters.strip()],
)
icon_emoji = forms.StringField("")
seq = forms.IntegerField("", widget=forms.HiddenInput())
|
from baseframe import __
import baseframe.forms as forms
__all__ = ['LabelForm', 'LabelOptionForm']
class LabelForm(forms.Form):
name = forms.StringField(
"", widget=forms.HiddenInput(), validators=[forms.validators.Optional()]
)
title = forms.StringField(
__("Label"),
validators=[
forms.validators.DataRequired(__(u"This can’t be empty")),
forms.validators.Length(max=250),
],
filters=[forms.filters.strip()],
)
icon_emoji = forms.StringField(
"", validators=[forms.validators.IsEmoji()]
)
required = forms.BooleanField(
__("Make this label mandatory in proposal forms"),
default=False,
description=__("If checked, proposers must select one of the options"),
)
restricted = forms.BooleanField(
__("Restrict use of this label to editors"),
default=False,
description=__(
"If checked, only editors and reviewers can apply this label on proposals"
),
)
class LabelOptionForm(forms.Form):
name = forms.StringField(
"", widget=forms.HiddenInput(), validators=[forms.validators.Optional()]
)
title = forms.StringField(
__("Option"),
validators=[
forms.validators.DataRequired(__(u"This can’t be empty")),
forms.validators.Length(max=250),
],
filters=[forms.filters.strip()],
)
icon_emoji = forms.StringField(
"", validators=[forms.validators.IsEmoji()]
)
seq = forms.IntegerField("", widget=forms.HiddenInput())
| Add form validator for icon_emoji | Add form validator for icon_emoji | Python | agpl-3.0 | hasgeek/funnel,hasgeek/funnel,hasgeek/funnel,hasgeek/funnel,hasgeek/funnel |
from baseframe import __
import baseframe.forms as forms
__all__ = ['LabelForm', 'LabelOptionForm']
class LabelForm(forms.Form):
name = forms.StringField(
"", widget=forms.HiddenInput(), validators=[forms.validators.Optional()]
)
title = forms.StringField(
__("Label"),
validators=[
forms.validators.DataRequired(__(u"This can’t be empty")),
forms.validators.Length(max=250),
],
filters=[forms.filters.strip()],
)
- icon_emoji = forms.StringField("")
+ icon_emoji = forms.StringField(
+ "", validators=[forms.validators.IsEmoji()]
+ )
required = forms.BooleanField(
__("Make this label mandatory in proposal forms"),
default=False,
description=__("If checked, proposers must select one of the options"),
)
restricted = forms.BooleanField(
__("Restrict use of this label to editors"),
default=False,
description=__(
"If checked, only editors and reviewers can apply this label on proposals"
),
)
class LabelOptionForm(forms.Form):
name = forms.StringField(
"", widget=forms.HiddenInput(), validators=[forms.validators.Optional()]
)
title = forms.StringField(
__("Option"),
validators=[
forms.validators.DataRequired(__(u"This can’t be empty")),
forms.validators.Length(max=250),
],
filters=[forms.filters.strip()],
)
- icon_emoji = forms.StringField("")
+ icon_emoji = forms.StringField(
+ "", validators=[forms.validators.IsEmoji()]
+ )
seq = forms.IntegerField("", widget=forms.HiddenInput())
| Add form validator for icon_emoji | ## Code Before:
from baseframe import __
import baseframe.forms as forms
__all__ = ['LabelForm', 'LabelOptionForm']
class LabelForm(forms.Form):
name = forms.StringField(
"", widget=forms.HiddenInput(), validators=[forms.validators.Optional()]
)
title = forms.StringField(
__("Label"),
validators=[
forms.validators.DataRequired(__(u"This can’t be empty")),
forms.validators.Length(max=250),
],
filters=[forms.filters.strip()],
)
icon_emoji = forms.StringField("")
required = forms.BooleanField(
__("Make this label mandatory in proposal forms"),
default=False,
description=__("If checked, proposers must select one of the options"),
)
restricted = forms.BooleanField(
__("Restrict use of this label to editors"),
default=False,
description=__(
"If checked, only editors and reviewers can apply this label on proposals"
),
)
class LabelOptionForm(forms.Form):
name = forms.StringField(
"", widget=forms.HiddenInput(), validators=[forms.validators.Optional()]
)
title = forms.StringField(
__("Option"),
validators=[
forms.validators.DataRequired(__(u"This can’t be empty")),
forms.validators.Length(max=250),
],
filters=[forms.filters.strip()],
)
icon_emoji = forms.StringField("")
seq = forms.IntegerField("", widget=forms.HiddenInput())
## Instruction:
Add form validator for icon_emoji
## Code After:
from baseframe import __
import baseframe.forms as forms
__all__ = ['LabelForm', 'LabelOptionForm']
class LabelForm(forms.Form):
name = forms.StringField(
"", widget=forms.HiddenInput(), validators=[forms.validators.Optional()]
)
title = forms.StringField(
__("Label"),
validators=[
forms.validators.DataRequired(__(u"This can’t be empty")),
forms.validators.Length(max=250),
],
filters=[forms.filters.strip()],
)
icon_emoji = forms.StringField(
"", validators=[forms.validators.IsEmoji()]
)
required = forms.BooleanField(
__("Make this label mandatory in proposal forms"),
default=False,
description=__("If checked, proposers must select one of the options"),
)
restricted = forms.BooleanField(
__("Restrict use of this label to editors"),
default=False,
description=__(
"If checked, only editors and reviewers can apply this label on proposals"
),
)
class LabelOptionForm(forms.Form):
name = forms.StringField(
"", widget=forms.HiddenInput(), validators=[forms.validators.Optional()]
)
title = forms.StringField(
__("Option"),
validators=[
forms.validators.DataRequired(__(u"This can’t be empty")),
forms.validators.Length(max=250),
],
filters=[forms.filters.strip()],
)
icon_emoji = forms.StringField(
"", validators=[forms.validators.IsEmoji()]
)
seq = forms.IntegerField("", widget=forms.HiddenInput())
|
from baseframe import __
import baseframe.forms as forms
__all__ = ['LabelForm', 'LabelOptionForm']
class LabelForm(forms.Form):
name = forms.StringField(
"", widget=forms.HiddenInput(), validators=[forms.validators.Optional()]
)
title = forms.StringField(
__("Label"),
validators=[
forms.validators.DataRequired(__(u"This can’t be empty")),
forms.validators.Length(max=250),
],
filters=[forms.filters.strip()],
)
- icon_emoji = forms.StringField("")
? ---
+ icon_emoji = forms.StringField(
+ "", validators=[forms.validators.IsEmoji()]
+ )
required = forms.BooleanField(
__("Make this label mandatory in proposal forms"),
default=False,
description=__("If checked, proposers must select one of the options"),
)
restricted = forms.BooleanField(
__("Restrict use of this label to editors"),
default=False,
description=__(
"If checked, only editors and reviewers can apply this label on proposals"
),
)
class LabelOptionForm(forms.Form):
name = forms.StringField(
"", widget=forms.HiddenInput(), validators=[forms.validators.Optional()]
)
title = forms.StringField(
__("Option"),
validators=[
forms.validators.DataRequired(__(u"This can’t be empty")),
forms.validators.Length(max=250),
],
filters=[forms.filters.strip()],
)
- icon_emoji = forms.StringField("")
? ---
+ icon_emoji = forms.StringField(
+ "", validators=[forms.validators.IsEmoji()]
+ )
seq = forms.IntegerField("", widget=forms.HiddenInput()) |
a040d06de7624371122960788aff241994ae08f8 | metadata/SnowDegreeDay/hooks/pre-stage.py | metadata/SnowDegreeDay/hooks/pre-stage.py | import os
import shutil
from wmt.config import site
from wmt.models.submissions import prepend_to_path
from wmt.utils.hook import find_simulation_input_file
from topoflow_utils.hook import assign_parameters
file_list = ['rti_file',
'pixel_file']
def execute(env):
"""Perform pre-stage tasks for running a component.
Parameters
----------
env : dict
A dict of component parameter values from WMT.
"""
env['n_steps'] = int(round(float(env['run_duration']) / float(env['dt'])))
env['save_grid_dt'] = float(env['dt'])
env['save_pixels_dt'] = float(env['dt'])
# TopoFlow needs site_prefix and case_prefix.
env['site_prefix'] = os.path.splitext(env['rti_file'])[0]
env['case_prefix'] = 'WMT'
# If no pixel_file is given, let TopoFlow make one.
if env['pixel_file'] == 'off':
file_list.remove('pixel_file')
env['pixel_file'] = env['case_prefix'] + '_outlets.txt'
assign_parameters(env, file_list)
# Default files common to all TopoFlow components are stored with the
# topoflow component metadata.
prepend_to_path('WMT_INPUT_FILE_PATH',
os.path.join(site['db'], 'components', 'topoflow', 'files'))
for fname in file_list:
src = find_simulation_input_file(env[fname])
shutil.copy(src, os.curdir)
| import os
import shutil
from wmt.config import site
from wmt.utils.hook import find_simulation_input_file
from topoflow_utils.hook import assign_parameters, scalar_to_rtg_file
file_list = []
def execute(env):
"""Perform pre-stage tasks for running a component.
Parameters
----------
env : dict
A dict of component parameter values from WMT.
"""
env['n_steps'] = int(round(float(env['run_duration']) / float(env['dt'])))
env['save_grid_dt'] = float(env['dt'])
env['save_pixels_dt'] = float(env['dt'])
assign_parameters(env, file_list)
for fname in file_list:
src = find_simulation_input_file(env[fname])
shutil.copy(src, os.curdir)
src = find_simulation_input_file(env['site_prefix'] + '.rti')
shutil.copy(src, os.path.join(os.curdir, env['site_prefix'] + '.rti'))
for var in ('rho_snow', 'c0', 'T0', 'h0_snow', 'h0_swe'):
if env[var + '_ptype'] == 'Scalar':
scalar_to_rtg_file(var, env)
| Update hook for SnowDegreeDay component | Update hook for SnowDegreeDay component
| Python | mit | csdms/wmt-metadata | import os
import shutil
from wmt.config import site
- from wmt.models.submissions import prepend_to_path
from wmt.utils.hook import find_simulation_input_file
- from topoflow_utils.hook import assign_parameters
+ from topoflow_utils.hook import assign_parameters, scalar_to_rtg_file
+ file_list = []
- file_list = ['rti_file',
- 'pixel_file']
def execute(env):
"""Perform pre-stage tasks for running a component.
Parameters
----------
env : dict
A dict of component parameter values from WMT.
"""
env['n_steps'] = int(round(float(env['run_duration']) / float(env['dt'])))
env['save_grid_dt'] = float(env['dt'])
env['save_pixels_dt'] = float(env['dt'])
- # TopoFlow needs site_prefix and case_prefix.
- env['site_prefix'] = os.path.splitext(env['rti_file'])[0]
- env['case_prefix'] = 'WMT'
-
- # If no pixel_file is given, let TopoFlow make one.
- if env['pixel_file'] == 'off':
- file_list.remove('pixel_file')
- env['pixel_file'] = env['case_prefix'] + '_outlets.txt'
-
assign_parameters(env, file_list)
- # Default files common to all TopoFlow components are stored with the
- # topoflow component metadata.
- prepend_to_path('WMT_INPUT_FILE_PATH',
- os.path.join(site['db'], 'components', 'topoflow', 'files'))
for fname in file_list:
src = find_simulation_input_file(env[fname])
shutil.copy(src, os.curdir)
+ src = find_simulation_input_file(env['site_prefix'] + '.rti')
+ shutil.copy(src, os.path.join(os.curdir, env['site_prefix'] + '.rti'))
+ for var in ('rho_snow', 'c0', 'T0', 'h0_snow', 'h0_swe'):
+ if env[var + '_ptype'] == 'Scalar':
+ scalar_to_rtg_file(var, env)
+ | Update hook for SnowDegreeDay component | ## Code Before:
import os
import shutil
from wmt.config import site
from wmt.models.submissions import prepend_to_path
from wmt.utils.hook import find_simulation_input_file
from topoflow_utils.hook import assign_parameters
file_list = ['rti_file',
'pixel_file']
def execute(env):
"""Perform pre-stage tasks for running a component.
Parameters
----------
env : dict
A dict of component parameter values from WMT.
"""
env['n_steps'] = int(round(float(env['run_duration']) / float(env['dt'])))
env['save_grid_dt'] = float(env['dt'])
env['save_pixels_dt'] = float(env['dt'])
# TopoFlow needs site_prefix and case_prefix.
env['site_prefix'] = os.path.splitext(env['rti_file'])[0]
env['case_prefix'] = 'WMT'
# If no pixel_file is given, let TopoFlow make one.
if env['pixel_file'] == 'off':
file_list.remove('pixel_file')
env['pixel_file'] = env['case_prefix'] + '_outlets.txt'
assign_parameters(env, file_list)
# Default files common to all TopoFlow components are stored with the
# topoflow component metadata.
prepend_to_path('WMT_INPUT_FILE_PATH',
os.path.join(site['db'], 'components', 'topoflow', 'files'))
for fname in file_list:
src = find_simulation_input_file(env[fname])
shutil.copy(src, os.curdir)
## Instruction:
Update hook for SnowDegreeDay component
## Code After:
import os
import shutil
from wmt.config import site
from wmt.utils.hook import find_simulation_input_file
from topoflow_utils.hook import assign_parameters, scalar_to_rtg_file
file_list = []
def execute(env):
"""Perform pre-stage tasks for running a component.
Parameters
----------
env : dict
A dict of component parameter values from WMT.
"""
env['n_steps'] = int(round(float(env['run_duration']) / float(env['dt'])))
env['save_grid_dt'] = float(env['dt'])
env['save_pixels_dt'] = float(env['dt'])
assign_parameters(env, file_list)
for fname in file_list:
src = find_simulation_input_file(env[fname])
shutil.copy(src, os.curdir)
src = find_simulation_input_file(env['site_prefix'] + '.rti')
shutil.copy(src, os.path.join(os.curdir, env['site_prefix'] + '.rti'))
for var in ('rho_snow', 'c0', 'T0', 'h0_snow', 'h0_swe'):
if env[var + '_ptype'] == 'Scalar':
scalar_to_rtg_file(var, env)
| import os
import shutil
from wmt.config import site
- from wmt.models.submissions import prepend_to_path
from wmt.utils.hook import find_simulation_input_file
- from topoflow_utils.hook import assign_parameters
+ from topoflow_utils.hook import assign_parameters, scalar_to_rtg_file
? ++++++++++++++++++++
+ file_list = []
- file_list = ['rti_file',
- 'pixel_file']
def execute(env):
"""Perform pre-stage tasks for running a component.
Parameters
----------
env : dict
A dict of component parameter values from WMT.
"""
env['n_steps'] = int(round(float(env['run_duration']) / float(env['dt'])))
env['save_grid_dt'] = float(env['dt'])
env['save_pixels_dt'] = float(env['dt'])
- # TopoFlow needs site_prefix and case_prefix.
- env['site_prefix'] = os.path.splitext(env['rti_file'])[0]
- env['case_prefix'] = 'WMT'
-
- # If no pixel_file is given, let TopoFlow make one.
- if env['pixel_file'] == 'off':
- file_list.remove('pixel_file')
- env['pixel_file'] = env['case_prefix'] + '_outlets.txt'
-
assign_parameters(env, file_list)
- # Default files common to all TopoFlow components are stored with the
- # topoflow component metadata.
- prepend_to_path('WMT_INPUT_FILE_PATH',
- os.path.join(site['db'], 'components', 'topoflow', 'files'))
for fname in file_list:
src = find_simulation_input_file(env[fname])
shutil.copy(src, os.curdir)
+ src = find_simulation_input_file(env['site_prefix'] + '.rti')
+ shutil.copy(src, os.path.join(os.curdir, env['site_prefix'] + '.rti'))
+
+ for var in ('rho_snow', 'c0', 'T0', 'h0_snow', 'h0_swe'):
+ if env[var + '_ptype'] == 'Scalar':
+ scalar_to_rtg_file(var, env) |
4817784c6e1050034faabb1b3d04382fe8997b41 | numpy/_array_api/_constants.py | numpy/_array_api/_constants.py | from ._array_object import ndarray
from ._dtypes import float64
import numpy as np
e = ndarray._new(np.array(np.e, dtype=float64))
inf = ndarray._new(np.array(np.inf, dtype=float64))
nan = ndarray._new(np.array(np.nan, dtype=float64))
pi = ndarray._new(np.array(np.pi, dtype=float64))
| import numpy as np
e = np.e
inf = np.inf
nan = np.nan
pi = np.pi
| Make the array API constants Python floats | Make the array API constants Python floats
| Python | bsd-3-clause | seberg/numpy,numpy/numpy,simongibbons/numpy,charris/numpy,mhvk/numpy,simongibbons/numpy,mattip/numpy,seberg/numpy,pdebuyl/numpy,mattip/numpy,charris/numpy,endolith/numpy,numpy/numpy,anntzer/numpy,jakirkham/numpy,mhvk/numpy,anntzer/numpy,endolith/numpy,seberg/numpy,endolith/numpy,mattip/numpy,simongibbons/numpy,numpy/numpy,seberg/numpy,jakirkham/numpy,charris/numpy,anntzer/numpy,mhvk/numpy,rgommers/numpy,simongibbons/numpy,pdebuyl/numpy,mhvk/numpy,rgommers/numpy,rgommers/numpy,jakirkham/numpy,simongibbons/numpy,anntzer/numpy,mhvk/numpy,charris/numpy,numpy/numpy,rgommers/numpy,jakirkham/numpy,pdebuyl/numpy,mattip/numpy,endolith/numpy,pdebuyl/numpy,jakirkham/numpy | - from ._array_object import ndarray
- from ._dtypes import float64
-
import numpy as np
- e = ndarray._new(np.array(np.e, dtype=float64))
- inf = ndarray._new(np.array(np.inf, dtype=float64))
- nan = ndarray._new(np.array(np.nan, dtype=float64))
- pi = ndarray._new(np.array(np.pi, dtype=float64))
+ e = np.e
+ inf = np.inf
+ nan = np.nan
+ pi = np.pi
| Make the array API constants Python floats | ## Code Before:
from ._array_object import ndarray
from ._dtypes import float64
import numpy as np
e = ndarray._new(np.array(np.e, dtype=float64))
inf = ndarray._new(np.array(np.inf, dtype=float64))
nan = ndarray._new(np.array(np.nan, dtype=float64))
pi = ndarray._new(np.array(np.pi, dtype=float64))
## Instruction:
Make the array API constants Python floats
## Code After:
import numpy as np
e = np.e
inf = np.inf
nan = np.nan
pi = np.pi
| - from ._array_object import ndarray
- from ._dtypes import float64
-
import numpy as np
- e = ndarray._new(np.array(np.e, dtype=float64))
- inf = ndarray._new(np.array(np.inf, dtype=float64))
- nan = ndarray._new(np.array(np.nan, dtype=float64))
- pi = ndarray._new(np.array(np.pi, dtype=float64))
+ e = np.e
+ inf = np.inf
+ nan = np.nan
+ pi = np.pi |
d44fee53020470e2d9a8cd2393f5f0125dbd1fab | python/client.py | python/client.py | import grpc
import hello_pb2
import hello_pb2_grpc
def run():
channel = grpc.insecure_channel('localhost:50051')
stub = hello_pb2_grpc.HelloServiceStub(channel)
# ideally, you should have try catch block here too
response = stub.SayHello(hello_pb2.HelloReq(Name='Euler'))
print(response.Result)
try:
response = stub.SayHelloStrict(hello_pb2.HelloReq(
Name='Leonhard Euler'))
except grpc.RpcError as e:
# ouch!
# lets print the gRPC error message
# which is "Length of `Name` cannot be more than 10 characters"
print(e.details())
# lets access the error code, which is `INVALID_ARGUMENT`
# `type` of `status_code` is `grpc.StatusCode`
status_code = e.code()
# should print `INVALID_ARGUMENT`
print(status_code.name)
# should print `(3, 'invalid argument')`
print(status_code.value)
else:
print(response.Result)
if __name__ == '__main__':
run()
| import grpc
import hello_pb2
import hello_pb2_grpc
def run():
channel = grpc.insecure_channel('localhost:50051')
stub = hello_pb2_grpc.HelloServiceStub(channel)
# ideally, you should have try catch block here too
response = stub.SayHello(hello_pb2.HelloReq(Name='Euler'))
print(response.Result)
try:
response = stub.SayHelloStrict(hello_pb2.HelloReq(
Name='Leonhard Euler'))
except grpc.RpcError as e:
# ouch!
# lets print the gRPC error message
# which is "Length of `Name` cannot be more than 10 characters"
print(e.details())
# lets access the error code, which is `INVALID_ARGUMENT`
# `type` of `status_code` is `grpc.StatusCode`
status_code = e.code()
# should print `INVALID_ARGUMENT`
print(status_code.name)
# should print `(3, 'invalid argument')`
print(status_code.value)
# want to do some specific action based on the error?
if grpc.StatusCode.INVALID_ARGUMENT == status_code:
# do your stuff here
pass
else:
print(response.Result)
if __name__ == '__main__':
run()
| Update python version for better error handling | Update python version for better error handling
| Python | mit | avinassh/grpc-errors,avinassh/grpc-errors,avinassh/grpc-errors,avinassh/grpc-errors,avinassh/grpc-errors,avinassh/grpc-errors,avinassh/grpc-errors,avinassh/grpc-errors | import grpc
import hello_pb2
import hello_pb2_grpc
def run():
channel = grpc.insecure_channel('localhost:50051')
stub = hello_pb2_grpc.HelloServiceStub(channel)
# ideally, you should have try catch block here too
response = stub.SayHello(hello_pb2.HelloReq(Name='Euler'))
print(response.Result)
try:
response = stub.SayHelloStrict(hello_pb2.HelloReq(
Name='Leonhard Euler'))
except grpc.RpcError as e:
# ouch!
# lets print the gRPC error message
# which is "Length of `Name` cannot be more than 10 characters"
print(e.details())
# lets access the error code, which is `INVALID_ARGUMENT`
# `type` of `status_code` is `grpc.StatusCode`
status_code = e.code()
# should print `INVALID_ARGUMENT`
print(status_code.name)
# should print `(3, 'invalid argument')`
print(status_code.value)
+ # want to do some specific action based on the error?
+ if grpc.StatusCode.INVALID_ARGUMENT == status_code:
+ # do your stuff here
+ pass
else:
print(response.Result)
if __name__ == '__main__':
run()
| Update python version for better error handling | ## Code Before:
import grpc
import hello_pb2
import hello_pb2_grpc
def run():
channel = grpc.insecure_channel('localhost:50051')
stub = hello_pb2_grpc.HelloServiceStub(channel)
# ideally, you should have try catch block here too
response = stub.SayHello(hello_pb2.HelloReq(Name='Euler'))
print(response.Result)
try:
response = stub.SayHelloStrict(hello_pb2.HelloReq(
Name='Leonhard Euler'))
except grpc.RpcError as e:
# ouch!
# lets print the gRPC error message
# which is "Length of `Name` cannot be more than 10 characters"
print(e.details())
# lets access the error code, which is `INVALID_ARGUMENT`
# `type` of `status_code` is `grpc.StatusCode`
status_code = e.code()
# should print `INVALID_ARGUMENT`
print(status_code.name)
# should print `(3, 'invalid argument')`
print(status_code.value)
else:
print(response.Result)
if __name__ == '__main__':
run()
## Instruction:
Update python version for better error handling
## Code After:
import grpc
import hello_pb2
import hello_pb2_grpc
def run():
channel = grpc.insecure_channel('localhost:50051')
stub = hello_pb2_grpc.HelloServiceStub(channel)
# ideally, you should have try catch block here too
response = stub.SayHello(hello_pb2.HelloReq(Name='Euler'))
print(response.Result)
try:
response = stub.SayHelloStrict(hello_pb2.HelloReq(
Name='Leonhard Euler'))
except grpc.RpcError as e:
# ouch!
# lets print the gRPC error message
# which is "Length of `Name` cannot be more than 10 characters"
print(e.details())
# lets access the error code, which is `INVALID_ARGUMENT`
# `type` of `status_code` is `grpc.StatusCode`
status_code = e.code()
# should print `INVALID_ARGUMENT`
print(status_code.name)
# should print `(3, 'invalid argument')`
print(status_code.value)
# want to do some specific action based on the error?
if grpc.StatusCode.INVALID_ARGUMENT == status_code:
# do your stuff here
pass
else:
print(response.Result)
if __name__ == '__main__':
run()
| import grpc
import hello_pb2
import hello_pb2_grpc
def run():
channel = grpc.insecure_channel('localhost:50051')
stub = hello_pb2_grpc.HelloServiceStub(channel)
# ideally, you should have try catch block here too
response = stub.SayHello(hello_pb2.HelloReq(Name='Euler'))
print(response.Result)
try:
response = stub.SayHelloStrict(hello_pb2.HelloReq(
Name='Leonhard Euler'))
except grpc.RpcError as e:
# ouch!
# lets print the gRPC error message
# which is "Length of `Name` cannot be more than 10 characters"
print(e.details())
# lets access the error code, which is `INVALID_ARGUMENT`
# `type` of `status_code` is `grpc.StatusCode`
status_code = e.code()
# should print `INVALID_ARGUMENT`
print(status_code.name)
# should print `(3, 'invalid argument')`
print(status_code.value)
+ # want to do some specific action based on the error?
+ if grpc.StatusCode.INVALID_ARGUMENT == status_code:
+ # do your stuff here
+ pass
else:
print(response.Result)
if __name__ == '__main__':
run() |
84341e0d5f0f1b902c2a334f40cddb29e10a1f16 | mozillians/users/cron.py | mozillians/users/cron.py | from django.conf import settings
import cronjobs
from celery.task.sets import TaskSet
from elasticutils.contrib.django import get_es
from mozillians.users.tasks import index_objects
from mozillians.users.models import UserProfile, UserProfileMappingType
@cronjobs.register
def index_all_profiles():
# Get an es object, delete index and re-create it
es = get_es(timeout=settings.ES_INDEXING_TIMEOUT)
mappings = {'mappings':
{UserProfileMappingType.get_mapping_type_name():
UserProfileMappingType.get_mapping()}}
def _recreate_index(index):
es.indices.delete(index=index, ignore=[400, 404])
es.indices.create(index, body=mappings)
_recreate_index(settings.ES_INDEXES['default'])
_recreate_index(settings.ES_INDEXES['public'])
# mozillians index
ids = UserProfile.objects.complete().values_list('id', flat=True)
ts = [index_objects.subtask(kwargs={'mapping_type': UserProfileMappingType,
'ids': ids,
'chunk_size': 150,
'public_index': False})]
# public index
ts += [index_objects.subtask(kwargs={'mapping_type': UserProfileMappingType,
'ids': ids,
'chunk_size': 150,
'public_index': True})]
TaskSet(ts).apply_async()
| from django.conf import settings
import cronjobs
from celery.task.sets import TaskSet
from celeryutils import chunked
from elasticutils.contrib.django import get_es
from mozillians.users.tasks import index_objects
from mozillians.users.models import UserProfile, UserProfileMappingType
@cronjobs.register
def index_all_profiles():
# Get an es object, delete index and re-create it
es = get_es(timeout=settings.ES_INDEXING_TIMEOUT)
mappings = {'mappings':
{UserProfileMappingType.get_mapping_type_name():
UserProfileMappingType.get_mapping()}}
def _recreate_index(index):
es.indices.delete(index=index, ignore=[400, 404])
es.indices.create(index, body=mappings)
_recreate_index(settings.ES_INDEXES['default'])
_recreate_index(settings.ES_INDEXES['public'])
# mozillians index
ids = UserProfile.objects.complete().values_list('id', flat=True)
ts = [index_objects.subtask(args=[UserProfileMappingType, chunk, 150, False])
for chunk in chunked(sorted(list(ids)), 150)]
# public index
ts += [index_objects.subtask(args=[UserProfileMappingType, chunk, 150, True])
for chunk in chunked(sorted(list(ids)), 150)]
TaskSet(ts).apply_async()
| Index profiles in chunks and not altogether. | Index profiles in chunks and not altogether.
| Python | bsd-3-clause | johngian/mozillians,akatsoulas/mozillians,akarki15/mozillians,johngian/mozillians,hoosteeno/mozillians,mozilla/mozillians,chirilo/mozillians,hoosteeno/mozillians,safwanrahman/mozillians,fxa90id/mozillians,fxa90id/mozillians,fxa90id/mozillians,fxa90id/mozillians,johngian/mozillians,akatsoulas/mozillians,anistark/mozillians,hoosteeno/mozillians,mozilla/mozillians,chirilo/mozillians,justinpotts/mozillians,akatsoulas/mozillians,brian-yang/mozillians,ChristineLaMuse/mozillians,ChristineLaMuse/mozillians,akarki15/mozillians,akarki15/mozillians,akatsoulas/mozillians,brian-yang/mozillians,anistark/mozillians,anistark/mozillians,akarki15/mozillians,chirilo/mozillians,justinpotts/mozillians,justinpotts/mozillians,justinpotts/mozillians,johngian/mozillians,brian-yang/mozillians,mozilla/mozillians,safwanrahman/mozillians,chirilo/mozillians,ChristineLaMuse/mozillians,anistark/mozillians,hoosteeno/mozillians,safwanrahman/mozillians,brian-yang/mozillians,mozilla/mozillians,safwanrahman/mozillians | from django.conf import settings
import cronjobs
from celery.task.sets import TaskSet
+ from celeryutils import chunked
from elasticutils.contrib.django import get_es
from mozillians.users.tasks import index_objects
from mozillians.users.models import UserProfile, UserProfileMappingType
@cronjobs.register
def index_all_profiles():
# Get an es object, delete index and re-create it
es = get_es(timeout=settings.ES_INDEXING_TIMEOUT)
mappings = {'mappings':
{UserProfileMappingType.get_mapping_type_name():
UserProfileMappingType.get_mapping()}}
def _recreate_index(index):
es.indices.delete(index=index, ignore=[400, 404])
es.indices.create(index, body=mappings)
_recreate_index(settings.ES_INDEXES['default'])
_recreate_index(settings.ES_INDEXES['public'])
# mozillians index
ids = UserProfile.objects.complete().values_list('id', flat=True)
- ts = [index_objects.subtask(kwargs={'mapping_type': UserProfileMappingType,
+ ts = [index_objects.subtask(args=[UserProfileMappingType, chunk, 150, False])
+ for chunk in chunked(sorted(list(ids)), 150)]
- 'ids': ids,
- 'chunk_size': 150,
- 'public_index': False})]
# public index
- ts += [index_objects.subtask(kwargs={'mapping_type': UserProfileMappingType,
+ ts += [index_objects.subtask(args=[UserProfileMappingType, chunk, 150, True])
+ for chunk in chunked(sorted(list(ids)), 150)]
- 'ids': ids,
- 'chunk_size': 150,
- 'public_index': True})]
TaskSet(ts).apply_async()
| Index profiles in chunks and not altogether. | ## Code Before:
from django.conf import settings
import cronjobs
from celery.task.sets import TaskSet
from elasticutils.contrib.django import get_es
from mozillians.users.tasks import index_objects
from mozillians.users.models import UserProfile, UserProfileMappingType
@cronjobs.register
def index_all_profiles():
# Get an es object, delete index and re-create it
es = get_es(timeout=settings.ES_INDEXING_TIMEOUT)
mappings = {'mappings':
{UserProfileMappingType.get_mapping_type_name():
UserProfileMappingType.get_mapping()}}
def _recreate_index(index):
es.indices.delete(index=index, ignore=[400, 404])
es.indices.create(index, body=mappings)
_recreate_index(settings.ES_INDEXES['default'])
_recreate_index(settings.ES_INDEXES['public'])
# mozillians index
ids = UserProfile.objects.complete().values_list('id', flat=True)
ts = [index_objects.subtask(kwargs={'mapping_type': UserProfileMappingType,
'ids': ids,
'chunk_size': 150,
'public_index': False})]
# public index
ts += [index_objects.subtask(kwargs={'mapping_type': UserProfileMappingType,
'ids': ids,
'chunk_size': 150,
'public_index': True})]
TaskSet(ts).apply_async()
## Instruction:
Index profiles in chunks and not altogether.
## Code After:
from django.conf import settings
import cronjobs
from celery.task.sets import TaskSet
from celeryutils import chunked
from elasticutils.contrib.django import get_es
from mozillians.users.tasks import index_objects
from mozillians.users.models import UserProfile, UserProfileMappingType
@cronjobs.register
def index_all_profiles():
# Get an es object, delete index and re-create it
es = get_es(timeout=settings.ES_INDEXING_TIMEOUT)
mappings = {'mappings':
{UserProfileMappingType.get_mapping_type_name():
UserProfileMappingType.get_mapping()}}
def _recreate_index(index):
es.indices.delete(index=index, ignore=[400, 404])
es.indices.create(index, body=mappings)
_recreate_index(settings.ES_INDEXES['default'])
_recreate_index(settings.ES_INDEXES['public'])
# mozillians index
ids = UserProfile.objects.complete().values_list('id', flat=True)
ts = [index_objects.subtask(args=[UserProfileMappingType, chunk, 150, False])
for chunk in chunked(sorted(list(ids)), 150)]
# public index
ts += [index_objects.subtask(args=[UserProfileMappingType, chunk, 150, True])
for chunk in chunked(sorted(list(ids)), 150)]
TaskSet(ts).apply_async()
| from django.conf import settings
import cronjobs
from celery.task.sets import TaskSet
+ from celeryutils import chunked
from elasticutils.contrib.django import get_es
from mozillians.users.tasks import index_objects
from mozillians.users.models import UserProfile, UserProfileMappingType
@cronjobs.register
def index_all_profiles():
# Get an es object, delete index and re-create it
es = get_es(timeout=settings.ES_INDEXING_TIMEOUT)
mappings = {'mappings':
{UserProfileMappingType.get_mapping_type_name():
UserProfileMappingType.get_mapping()}}
def _recreate_index(index):
es.indices.delete(index=index, ignore=[400, 404])
es.indices.create(index, body=mappings)
_recreate_index(settings.ES_INDEXES['default'])
_recreate_index(settings.ES_INDEXES['public'])
# mozillians index
ids = UserProfile.objects.complete().values_list('id', flat=True)
- ts = [index_objects.subtask(kwargs={'mapping_type': UserProfileMappingType,
? -- ^^^^^^^^^^^^^^^^^
+ ts = [index_objects.subtask(args=[UserProfileMappingType, chunk, 150, False])
? ^ ++++++++++++++++++++
+ for chunk in chunked(sorted(list(ids)), 150)]
- 'ids': ids,
- 'chunk_size': 150,
- 'public_index': False})]
# public index
- ts += [index_objects.subtask(kwargs={'mapping_type': UserProfileMappingType,
? -- ^^^^^^^^^^^^^^^^^
+ ts += [index_objects.subtask(args=[UserProfileMappingType, chunk, 150, True])
? ^ +++++++++++++++++++
+ for chunk in chunked(sorted(list(ids)), 150)]
- 'ids': ids,
- 'chunk_size': 150,
- 'public_index': True})]
TaskSet(ts).apply_async() |
b37655199a42622dec88ba11f845cc78d2ed0e8c | mama_cas/services/__init__.py | mama_cas/services/__init__.py | from django.utils.module_loading import import_string
def _get_backends():
backends = []
for backend_path in ['mama_cas.services.backends.SettingsBackend']:
backend = import_string(backend_path)()
backends.append(backend)
return backends
def _is_allowed(attr, *args):
for backend in _get_backends():
try:
if getattr(backend, attr)(*args):
return True
except AttributeError:
raise NotImplementedError("%s does not implement %s()" % (backend, attr))
return False
def get_callbacks(service):
for backend in _get_backends():
try:
callbacks = backend.get_callbacks(service)
except AttributeError:
raise NotImplementedError("%s does not implement get_callbacks()" % backend)
if callbacks:
# TODO merge callback dicts?
return callbacks
return []
def get_logout_url(service):
for backend in _get_backends():
try:
logout_url = backend.get_logout_url(service)
except AttributeError:
raise NotImplementedError("%s does not implement get_logout_url()" % backend)
if logout_url:
return logout_url
return None
def logout_allowed(service):
return _is_allowed('logout_allowed', service)
def proxy_allowed(service):
return _is_allowed('proxy_allowed', service)
def proxy_callback_allowed(service, pgturl):
return _is_allowed('proxy_callback_allowed', service, pgturl)
def service_allowed(service):
return _is_allowed('service_allowed', service)
| from django.utils.module_loading import import_string
def _get_backends():
backends = []
for backend_path in ['mama_cas.services.backends.SettingsBackend']:
backend = import_string(backend_path)()
backends.append(backend)
return backends
def _is_allowed(attr, *args):
for backend in _get_backends():
try:
if getattr(backend, attr)(*args):
return True
except AttributeError:
raise NotImplementedError("%s does not implement %s()" % (backend, attr))
return False
def get_callbacks(service):
callbacks = []
for backend in _get_backends():
try:
callbacks = callbacks + backend.get_callbacks(service)
except AttributeError:
raise NotImplementedError("%s does not implement get_callbacks()" % backend)
return callbacks
def get_logout_url(service):
for backend in _get_backends():
try:
return backend.get_logout_url(service)
except AttributeError:
raise NotImplementedError("%s does not implement get_logout_url()" % backend)
return None
def logout_allowed(service):
return _is_allowed('logout_allowed', service)
def proxy_allowed(service):
return _is_allowed('proxy_allowed', service)
def proxy_callback_allowed(service, pgturl):
return _is_allowed('proxy_callback_allowed', service, pgturl)
def service_allowed(service):
return _is_allowed('service_allowed', service)
| Join callback lists returned from backends | Join callback lists returned from backends
| Python | bsd-3-clause | jbittel/django-mama-cas,orbitvu/django-mama-cas,jbittel/django-mama-cas,orbitvu/django-mama-cas | from django.utils.module_loading import import_string
def _get_backends():
backends = []
for backend_path in ['mama_cas.services.backends.SettingsBackend']:
backend = import_string(backend_path)()
backends.append(backend)
return backends
def _is_allowed(attr, *args):
for backend in _get_backends():
try:
if getattr(backend, attr)(*args):
return True
except AttributeError:
raise NotImplementedError("%s does not implement %s()" % (backend, attr))
return False
def get_callbacks(service):
+ callbacks = []
for backend in _get_backends():
try:
- callbacks = backend.get_callbacks(service)
+ callbacks = callbacks + backend.get_callbacks(service)
except AttributeError:
raise NotImplementedError("%s does not implement get_callbacks()" % backend)
- if callbacks:
- # TODO merge callback dicts?
- return callbacks
+ return callbacks
- return []
def get_logout_url(service):
for backend in _get_backends():
try:
- logout_url = backend.get_logout_url(service)
+ return backend.get_logout_url(service)
except AttributeError:
raise NotImplementedError("%s does not implement get_logout_url()" % backend)
- if logout_url:
- return logout_url
return None
def logout_allowed(service):
return _is_allowed('logout_allowed', service)
def proxy_allowed(service):
return _is_allowed('proxy_allowed', service)
def proxy_callback_allowed(service, pgturl):
return _is_allowed('proxy_callback_allowed', service, pgturl)
def service_allowed(service):
return _is_allowed('service_allowed', service)
| Join callback lists returned from backends | ## Code Before:
from django.utils.module_loading import import_string
def _get_backends():
backends = []
for backend_path in ['mama_cas.services.backends.SettingsBackend']:
backend = import_string(backend_path)()
backends.append(backend)
return backends
def _is_allowed(attr, *args):
for backend in _get_backends():
try:
if getattr(backend, attr)(*args):
return True
except AttributeError:
raise NotImplementedError("%s does not implement %s()" % (backend, attr))
return False
def get_callbacks(service):
for backend in _get_backends():
try:
callbacks = backend.get_callbacks(service)
except AttributeError:
raise NotImplementedError("%s does not implement get_callbacks()" % backend)
if callbacks:
# TODO merge callback dicts?
return callbacks
return []
def get_logout_url(service):
for backend in _get_backends():
try:
logout_url = backend.get_logout_url(service)
except AttributeError:
raise NotImplementedError("%s does not implement get_logout_url()" % backend)
if logout_url:
return logout_url
return None
def logout_allowed(service):
return _is_allowed('logout_allowed', service)
def proxy_allowed(service):
return _is_allowed('proxy_allowed', service)
def proxy_callback_allowed(service, pgturl):
return _is_allowed('proxy_callback_allowed', service, pgturl)
def service_allowed(service):
return _is_allowed('service_allowed', service)
## Instruction:
Join callback lists returned from backends
## Code After:
from django.utils.module_loading import import_string
def _get_backends():
backends = []
for backend_path in ['mama_cas.services.backends.SettingsBackend']:
backend = import_string(backend_path)()
backends.append(backend)
return backends
def _is_allowed(attr, *args):
for backend in _get_backends():
try:
if getattr(backend, attr)(*args):
return True
except AttributeError:
raise NotImplementedError("%s does not implement %s()" % (backend, attr))
return False
def get_callbacks(service):
callbacks = []
for backend in _get_backends():
try:
callbacks = callbacks + backend.get_callbacks(service)
except AttributeError:
raise NotImplementedError("%s does not implement get_callbacks()" % backend)
return callbacks
def get_logout_url(service):
for backend in _get_backends():
try:
return backend.get_logout_url(service)
except AttributeError:
raise NotImplementedError("%s does not implement get_logout_url()" % backend)
return None
def logout_allowed(service):
return _is_allowed('logout_allowed', service)
def proxy_allowed(service):
return _is_allowed('proxy_allowed', service)
def proxy_callback_allowed(service, pgturl):
return _is_allowed('proxy_callback_allowed', service, pgturl)
def service_allowed(service):
return _is_allowed('service_allowed', service)
| from django.utils.module_loading import import_string
def _get_backends():
backends = []
for backend_path in ['mama_cas.services.backends.SettingsBackend']:
backend = import_string(backend_path)()
backends.append(backend)
return backends
def _is_allowed(attr, *args):
for backend in _get_backends():
try:
if getattr(backend, attr)(*args):
return True
except AttributeError:
raise NotImplementedError("%s does not implement %s()" % (backend, attr))
return False
def get_callbacks(service):
+ callbacks = []
for backend in _get_backends():
try:
- callbacks = backend.get_callbacks(service)
+ callbacks = callbacks + backend.get_callbacks(service)
? ++++++++++++
except AttributeError:
raise NotImplementedError("%s does not implement get_callbacks()" % backend)
- if callbacks:
- # TODO merge callback dicts?
- return callbacks
? --------
+ return callbacks
- return []
def get_logout_url(service):
for backend in _get_backends():
try:
- logout_url = backend.get_logout_url(service)
? ^^^^^ - ^^^
+ return backend.get_logout_url(service)
? ^^ ^
except AttributeError:
raise NotImplementedError("%s does not implement get_logout_url()" % backend)
- if logout_url:
- return logout_url
return None
def logout_allowed(service):
return _is_allowed('logout_allowed', service)
def proxy_allowed(service):
return _is_allowed('proxy_allowed', service)
def proxy_callback_allowed(service, pgturl):
return _is_allowed('proxy_callback_allowed', service, pgturl)
def service_allowed(service):
return _is_allowed('service_allowed', service) |
583ea6c1a234ab9d484b1e80e7f567d9a5d2fb71 | shopify/resources/image.py | shopify/resources/image.py | from ..base import ShopifyResource
import base64
import re
class Image(ShopifyResource):
_prefix_source = "/admin/products/$product_id/"
def __getattr__(self, name):
if name in ["pico", "icon", "thumb", "small", "compact", "medium", "large", "grande", "original"]:
return re.sub(r"/(.*)\.(\w{2,4})", r"/\1_%s.\2" % (name), self.src)
else:
return super(Image, self).__getattr__(name)
def attach_image(self, data, filename=None):
self.attributes["attachment"] = base64.b64encode(data)
if filename:
self.attributes["filename"] = filename
| from ..base import ShopifyResource
from ..resources import Metafield
from six.moves import urllib
import base64
import re
class Image(ShopifyResource):
_prefix_source = "/admin/products/$product_id/"
def __getattr__(self, name):
if name in ["pico", "icon", "thumb", "small", "compact", "medium", "large", "grande", "original"]:
return re.sub(r"/(.*)\.(\w{2,4})", r"/\1_%s.\2" % (name), self.src)
else:
return super(Image, self).__getattr__(name)
def attach_image(self, data, filename=None):
self.attributes["attachment"] = base64.b64encode(data)
if filename:
self.attributes["filename"] = filename
def metafields(self):
if self.is_new():
return []
query_params = { 'metafield[owner_id]': self.id, 'metafield[owner_resource]': 'product_image' }
return Metafield.find(from_ = '/admin/metafields.json?%s' % urllib.parse.urlencode(query_params)) | Add `metafields()` method to `Image` resource. | Add `metafields()` method to `Image` resource. | Python | mit | asiviero/shopify_python_api,SmileyJames/shopify_python_api,Shopify/shopify_python_api,metric-collective/shopify_python_api,gavinballard/shopify_python_api,ifnull/shopify_python_api | from ..base import ShopifyResource
+ from ..resources import Metafield
+ from six.moves import urllib
import base64
import re
class Image(ShopifyResource):
_prefix_source = "/admin/products/$product_id/"
def __getattr__(self, name):
if name in ["pico", "icon", "thumb", "small", "compact", "medium", "large", "grande", "original"]:
return re.sub(r"/(.*)\.(\w{2,4})", r"/\1_%s.\2" % (name), self.src)
else:
return super(Image, self).__getattr__(name)
def attach_image(self, data, filename=None):
self.attributes["attachment"] = base64.b64encode(data)
if filename:
self.attributes["filename"] = filename
+ def metafields(self):
+ if self.is_new():
+ return []
+ query_params = { 'metafield[owner_id]': self.id, 'metafield[owner_resource]': 'product_image' }
+ return Metafield.find(from_ = '/admin/metafields.json?%s' % urllib.parse.urlencode(query_params)) | Add `metafields()` method to `Image` resource. | ## Code Before:
from ..base import ShopifyResource
import base64
import re
class Image(ShopifyResource):
_prefix_source = "/admin/products/$product_id/"
def __getattr__(self, name):
if name in ["pico", "icon", "thumb", "small", "compact", "medium", "large", "grande", "original"]:
return re.sub(r"/(.*)\.(\w{2,4})", r"/\1_%s.\2" % (name), self.src)
else:
return super(Image, self).__getattr__(name)
def attach_image(self, data, filename=None):
self.attributes["attachment"] = base64.b64encode(data)
if filename:
self.attributes["filename"] = filename
## Instruction:
Add `metafields()` method to `Image` resource.
## Code After:
from ..base import ShopifyResource
from ..resources import Metafield
from six.moves import urllib
import base64
import re
class Image(ShopifyResource):
_prefix_source = "/admin/products/$product_id/"
def __getattr__(self, name):
if name in ["pico", "icon", "thumb", "small", "compact", "medium", "large", "grande", "original"]:
return re.sub(r"/(.*)\.(\w{2,4})", r"/\1_%s.\2" % (name), self.src)
else:
return super(Image, self).__getattr__(name)
def attach_image(self, data, filename=None):
self.attributes["attachment"] = base64.b64encode(data)
if filename:
self.attributes["filename"] = filename
def metafields(self):
if self.is_new():
return []
query_params = { 'metafield[owner_id]': self.id, 'metafield[owner_resource]': 'product_image' }
return Metafield.find(from_ = '/admin/metafields.json?%s' % urllib.parse.urlencode(query_params)) | from ..base import ShopifyResource
+ from ..resources import Metafield
+ from six.moves import urllib
import base64
import re
class Image(ShopifyResource):
_prefix_source = "/admin/products/$product_id/"
def __getattr__(self, name):
if name in ["pico", "icon", "thumb", "small", "compact", "medium", "large", "grande", "original"]:
return re.sub(r"/(.*)\.(\w{2,4})", r"/\1_%s.\2" % (name), self.src)
else:
return super(Image, self).__getattr__(name)
def attach_image(self, data, filename=None):
self.attributes["attachment"] = base64.b64encode(data)
if filename:
self.attributes["filename"] = filename
+
+ def metafields(self):
+ if self.is_new():
+ return []
+ query_params = { 'metafield[owner_id]': self.id, 'metafield[owner_resource]': 'product_image' }
+ return Metafield.find(from_ = '/admin/metafields.json?%s' % urllib.parse.urlencode(query_params)) |
f5a5f185958ed3088518f3a2fca15ff7b57e982c | manage.py | manage.py | import os
import subprocess
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager, Shell
from app import create_app, db
from app.models import Users, Agencies, Requests, Responses, Events, Reasons, Permissions, Roles
app = create_app(os.getenv('FLASK_CONFIG') or 'default')
manager = Manager(app)
migrate = Migrate(app, db)
def make_shell_context():
return dict(
app=app,
db=db,
Users=Users,
Agencies=Agencies,
Requests=Requests,
Responses=Responses,
Events=Events,
Reasons=Reasons,
Permissions=Permissions,
Roles=Roles
)
manager.add_command("shell", Shell(make_context=make_shell_context))
manager.add_command('db', MigrateCommand)
@manager
def celery():
subprocess.call(['celery', 'worker', '-A', 'celery_worker.celery', '--loglevel=info'])
if __name__ == "__main__":
manager.run()
| import os
import subprocess
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager, Shell, Command
from app import create_app, db
from app.models import Users, Agencies, Requests, Responses, Events, Reasons, Permissions, Roles
app = create_app(os.getenv('FLASK_CONFIG') or 'default')
manager = Manager(app)
migrate = Migrate(app, db)
class Celery(Command):
"""
Runs Celery
"""
def run(self):
subprocess.call(['celery', 'worker', '-A', 'celery_worker.celery', '--loglevel=info'])
def make_shell_context():
return dict(
app=app,
db=db,
Users=Users,
Agencies=Agencies,
Requests=Requests,
Responses=Responses,
Events=Events,
Reasons=Reasons,
Permissions=Permissions,
Roles=Roles
)
manager.add_command("shell", Shell(make_context=make_shell_context))
manager.add_command("db", MigrateCommand)
manager.add_command("celery", Celery())
if __name__ == "__main__":
manager.run()
| Fix a problem with the celery cli commoand Allows runserver to be used separately from celery. | Fix a problem with the celery cli commoand
Allows runserver to be used separately from celery.
| Python | apache-2.0 | CityOfNewYork/NYCOpenRecords,CityOfNewYork/NYCOpenRecords,CityOfNewYork/NYCOpenRecords,CityOfNewYork/NYCOpenRecords,CityOfNewYork/NYCOpenRecords | import os
import subprocess
from flask_migrate import Migrate, MigrateCommand
- from flask_script import Manager, Shell
+ from flask_script import Manager, Shell, Command
from app import create_app, db
from app.models import Users, Agencies, Requests, Responses, Events, Reasons, Permissions, Roles
app = create_app(os.getenv('FLASK_CONFIG') or 'default')
manager = Manager(app)
migrate = Migrate(app, db)
+
+
+ class Celery(Command):
+ """
+ Runs Celery
+ """
+
+ def run(self):
+ subprocess.call(['celery', 'worker', '-A', 'celery_worker.celery', '--loglevel=info'])
def make_shell_context():
return dict(
app=app,
db=db,
Users=Users,
Agencies=Agencies,
Requests=Requests,
Responses=Responses,
Events=Events,
Reasons=Reasons,
Permissions=Permissions,
Roles=Roles
)
manager.add_command("shell", Shell(make_context=make_shell_context))
- manager.add_command('db', MigrateCommand)
+ manager.add_command("db", MigrateCommand)
+ manager.add_command("celery", Celery())
-
- @manager
- def celery():
- subprocess.call(['celery', 'worker', '-A', 'celery_worker.celery', '--loglevel=info'])
if __name__ == "__main__":
manager.run()
| Fix a problem with the celery cli commoand Allows runserver to be used separately from celery. | ## Code Before:
import os
import subprocess
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager, Shell
from app import create_app, db
from app.models import Users, Agencies, Requests, Responses, Events, Reasons, Permissions, Roles
app = create_app(os.getenv('FLASK_CONFIG') or 'default')
manager = Manager(app)
migrate = Migrate(app, db)
def make_shell_context():
return dict(
app=app,
db=db,
Users=Users,
Agencies=Agencies,
Requests=Requests,
Responses=Responses,
Events=Events,
Reasons=Reasons,
Permissions=Permissions,
Roles=Roles
)
manager.add_command("shell", Shell(make_context=make_shell_context))
manager.add_command('db', MigrateCommand)
@manager
def celery():
subprocess.call(['celery', 'worker', '-A', 'celery_worker.celery', '--loglevel=info'])
if __name__ == "__main__":
manager.run()
## Instruction:
Fix a problem with the celery cli commoand Allows runserver to be used separately from celery.
## Code After:
import os
import subprocess
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager, Shell, Command
from app import create_app, db
from app.models import Users, Agencies, Requests, Responses, Events, Reasons, Permissions, Roles
app = create_app(os.getenv('FLASK_CONFIG') or 'default')
manager = Manager(app)
migrate = Migrate(app, db)
class Celery(Command):
"""
Runs Celery
"""
def run(self):
subprocess.call(['celery', 'worker', '-A', 'celery_worker.celery', '--loglevel=info'])
def make_shell_context():
return dict(
app=app,
db=db,
Users=Users,
Agencies=Agencies,
Requests=Requests,
Responses=Responses,
Events=Events,
Reasons=Reasons,
Permissions=Permissions,
Roles=Roles
)
manager.add_command("shell", Shell(make_context=make_shell_context))
manager.add_command("db", MigrateCommand)
manager.add_command("celery", Celery())
if __name__ == "__main__":
manager.run()
| import os
import subprocess
from flask_migrate import Migrate, MigrateCommand
- from flask_script import Manager, Shell
+ from flask_script import Manager, Shell, Command
? +++++++++
from app import create_app, db
from app.models import Users, Agencies, Requests, Responses, Events, Reasons, Permissions, Roles
app = create_app(os.getenv('FLASK_CONFIG') or 'default')
manager = Manager(app)
migrate = Migrate(app, db)
+
+
+ class Celery(Command):
+ """
+ Runs Celery
+ """
+
+ def run(self):
+ subprocess.call(['celery', 'worker', '-A', 'celery_worker.celery', '--loglevel=info'])
def make_shell_context():
return dict(
app=app,
db=db,
Users=Users,
Agencies=Agencies,
Requests=Requests,
Responses=Responses,
Events=Events,
Reasons=Reasons,
Permissions=Permissions,
Roles=Roles
)
manager.add_command("shell", Shell(make_context=make_shell_context))
- manager.add_command('db', MigrateCommand)
? ^ ^
+ manager.add_command("db", MigrateCommand)
? ^ ^
+ manager.add_command("celery", Celery())
-
- @manager
- def celery():
- subprocess.call(['celery', 'worker', '-A', 'celery_worker.celery', '--loglevel=info'])
if __name__ == "__main__":
manager.run() |
6adbbe71dcde926fbd9288b4a43b45ff1a339cdc | turbustat/statistics/stats_utils.py | turbustat/statistics/stats_utils.py |
import numpy as np
def hellinger(data1, data2):
'''
Calculate the Hellinger Distance between two datasets.
Parameters
----------
data1 : numpy.ndarray
1D array.
data2 : numpy.ndarray
1D array.
Returns
-------
distance : float
Distance value.
'''
distance = (1 / np.sqrt(2)) * \
np.sqrt(np.nansum((np.sqrt(data1) - np.sqrt(data2)) ** 2.))
return distance
def standardize(x):
return (x - np.nanmean(x)) / np.nanstd(x)
|
import numpy as np
def hellinger(data1, data2):
'''
Calculate the Hellinger Distance between two datasets.
Parameters
----------
data1 : numpy.ndarray
1D array.
data2 : numpy.ndarray
1D array.
Returns
-------
distance : float
Distance value.
'''
distance = (1 / np.sqrt(2)) * \
np.sqrt(np.nansum((np.sqrt(data1) - np.sqrt(data2)) ** 2.))
return distance
def standardize(x):
return (x - np.nanmean(x)) / np.nanstd(x)
def kl_divergence(P, Q):
'''
Kullback Leidler Divergence
Parameters
----------
P,Q : numpy.ndarray
Two Discrete Probability distributions
Returns
-------
kl_divergence : float
'''
P = P[~np.isnan(P)]
Q = Q[~np.isnan(Q)]
P = P[np.isfinite(P)]
Q = Q[np.isfinite(Q)]
return np.nansum(np.where(Q != 0, P * np.log(P / Q), 0))
| Move KL Div to utils file | Move KL Div to utils file
| Python | mit | e-koch/TurbuStat,Astroua/TurbuStat |
import numpy as np
def hellinger(data1, data2):
'''
Calculate the Hellinger Distance between two datasets.
Parameters
----------
data1 : numpy.ndarray
1D array.
data2 : numpy.ndarray
1D array.
Returns
-------
distance : float
Distance value.
'''
distance = (1 / np.sqrt(2)) * \
np.sqrt(np.nansum((np.sqrt(data1) - np.sqrt(data2)) ** 2.))
return distance
def standardize(x):
return (x - np.nanmean(x)) / np.nanstd(x)
+
+ def kl_divergence(P, Q):
+ '''
+ Kullback Leidler Divergence
+
+ Parameters
+ ----------
+
+ P,Q : numpy.ndarray
+ Two Discrete Probability distributions
+
+ Returns
+ -------
+
+ kl_divergence : float
+ '''
+ P = P[~np.isnan(P)]
+ Q = Q[~np.isnan(Q)]
+ P = P[np.isfinite(P)]
+ Q = Q[np.isfinite(Q)]
+ return np.nansum(np.where(Q != 0, P * np.log(P / Q), 0))
+ | Move KL Div to utils file | ## Code Before:
import numpy as np
def hellinger(data1, data2):
'''
Calculate the Hellinger Distance between two datasets.
Parameters
----------
data1 : numpy.ndarray
1D array.
data2 : numpy.ndarray
1D array.
Returns
-------
distance : float
Distance value.
'''
distance = (1 / np.sqrt(2)) * \
np.sqrt(np.nansum((np.sqrt(data1) - np.sqrt(data2)) ** 2.))
return distance
def standardize(x):
return (x - np.nanmean(x)) / np.nanstd(x)
## Instruction:
Move KL Div to utils file
## Code After:
import numpy as np
def hellinger(data1, data2):
'''
Calculate the Hellinger Distance between two datasets.
Parameters
----------
data1 : numpy.ndarray
1D array.
data2 : numpy.ndarray
1D array.
Returns
-------
distance : float
Distance value.
'''
distance = (1 / np.sqrt(2)) * \
np.sqrt(np.nansum((np.sqrt(data1) - np.sqrt(data2)) ** 2.))
return distance
def standardize(x):
return (x - np.nanmean(x)) / np.nanstd(x)
def kl_divergence(P, Q):
'''
Kullback Leidler Divergence
Parameters
----------
P,Q : numpy.ndarray
Two Discrete Probability distributions
Returns
-------
kl_divergence : float
'''
P = P[~np.isnan(P)]
Q = Q[~np.isnan(Q)]
P = P[np.isfinite(P)]
Q = Q[np.isfinite(Q)]
return np.nansum(np.where(Q != 0, P * np.log(P / Q), 0))
|
import numpy as np
def hellinger(data1, data2):
'''
Calculate the Hellinger Distance between two datasets.
Parameters
----------
data1 : numpy.ndarray
1D array.
data2 : numpy.ndarray
1D array.
Returns
-------
distance : float
Distance value.
'''
distance = (1 / np.sqrt(2)) * \
np.sqrt(np.nansum((np.sqrt(data1) - np.sqrt(data2)) ** 2.))
return distance
def standardize(x):
return (x - np.nanmean(x)) / np.nanstd(x)
+
+
+ def kl_divergence(P, Q):
+ '''
+ Kullback Leidler Divergence
+
+ Parameters
+ ----------
+
+ P,Q : numpy.ndarray
+ Two Discrete Probability distributions
+
+ Returns
+ -------
+
+ kl_divergence : float
+ '''
+ P = P[~np.isnan(P)]
+ Q = Q[~np.isnan(Q)]
+ P = P[np.isfinite(P)]
+ Q = Q[np.isfinite(Q)]
+ return np.nansum(np.where(Q != 0, P * np.log(P / Q), 0)) |
ce1395db9340ee694ef7a7c35d7d185e4319cf4e | plugins/spotify.py | plugins/spotify.py | from plugins.util import command, get_url
import json
import re
SPOTIFY_URI_REGEX = r"(?<=spotify:)(?:track|album|artist):[a-zA-Z0-9]{22}"
ENDPOINT = "https://api.spotify.com/v1/{0}s/{1}"
@command()
def spotify(m):
spotify_uris = re.findall(SPOTIFY_URI_REGEX, m.body)
for spotify_uri in spotify_uris:
try:
type, id = _parse_spotify_uri(spotify_uri)
req = get_url(m, ENDPOINT.format(type, id))
if req:
blob = json.loads(req)
if type == "track" or type == "album":
m.bot.private_message(m.location,
blob["artists"][0]["name"] + " - " + blob["name"])
else:
m.bot.private_message(m.location, blob["name"])
except ValueError:
m.bot.logger.error("Invalid Spotify URI: " + spotify_uri)
def _parse_spotify_uri(s):
[type, id] = s.split(':')
return type, id
| from plugins.util import command, get_url
import json
import re
SPOTIFY_URI_REGEX = r"(?<=spotify:)(?:track|album|artist):[a-zA-Z0-9]{22}"
ENDPOINT = "https://api.spotify.com/v1/{0}s/{1}"
@command()
def spotify(m):
spotify_uris = re.findall(SPOTIFY_URI_REGEX, m.body)
for spotify_uri in spotify_uris:
try:
type, id = _parse_spotify_uri(spotify_uri)
except ValueError:
m.bot.logger.error("Invalid Spotify URI: " + spotify_uri)
else:
req = get_url(m, ENDPOINT.format(type, id))
if req:
blob = json.loads(req)
if type == "track" or type == "album":
m.bot.private_message(m.location, '"{0}" by {1} - {2}'
.format(blob["name"], blob["artists"][0]["name"],
blob["external_urls"]["spotify"]))
else:
m.bot.private_message(m.location, "{0} - {1}"
.format(blob["name"], blob["external_urls"]["spotify"]))
def _parse_spotify_uri(s):
[type, id] = s.split(':')
return type, id
| Change formatting of response, add URL | Change formatting of response, add URL
| Python | mit | quanticle/GorillaBot,quanticle/GorillaBot,molly/GorillaBot,molly/GorillaBot | from plugins.util import command, get_url
import json
import re
SPOTIFY_URI_REGEX = r"(?<=spotify:)(?:track|album|artist):[a-zA-Z0-9]{22}"
ENDPOINT = "https://api.spotify.com/v1/{0}s/{1}"
@command()
def spotify(m):
spotify_uris = re.findall(SPOTIFY_URI_REGEX, m.body)
for spotify_uri in spotify_uris:
try:
type, id = _parse_spotify_uri(spotify_uri)
+ except ValueError:
+ m.bot.logger.error("Invalid Spotify URI: " + spotify_uri)
+ else:
req = get_url(m, ENDPOINT.format(type, id))
if req:
blob = json.loads(req)
if type == "track" or type == "album":
- m.bot.private_message(m.location,
+ m.bot.private_message(m.location, '"{0}" by {1} - {2}'
- blob["artists"][0]["name"] + " - " + blob["name"])
+ .format(blob["name"], blob["artists"][0]["name"],
+ blob["external_urls"]["spotify"]))
else:
- m.bot.private_message(m.location, blob["name"])
+ m.bot.private_message(m.location, "{0} - {1}"
+ .format(blob["name"], blob["external_urls"]["spotify"]))
- except ValueError:
- m.bot.logger.error("Invalid Spotify URI: " + spotify_uri)
def _parse_spotify_uri(s):
[type, id] = s.split(':')
return type, id
| Change formatting of response, add URL | ## Code Before:
from plugins.util import command, get_url
import json
import re
SPOTIFY_URI_REGEX = r"(?<=spotify:)(?:track|album|artist):[a-zA-Z0-9]{22}"
ENDPOINT = "https://api.spotify.com/v1/{0}s/{1}"
@command()
def spotify(m):
spotify_uris = re.findall(SPOTIFY_URI_REGEX, m.body)
for spotify_uri in spotify_uris:
try:
type, id = _parse_spotify_uri(spotify_uri)
req = get_url(m, ENDPOINT.format(type, id))
if req:
blob = json.loads(req)
if type == "track" or type == "album":
m.bot.private_message(m.location,
blob["artists"][0]["name"] + " - " + blob["name"])
else:
m.bot.private_message(m.location, blob["name"])
except ValueError:
m.bot.logger.error("Invalid Spotify URI: " + spotify_uri)
def _parse_spotify_uri(s):
[type, id] = s.split(':')
return type, id
## Instruction:
Change formatting of response, add URL
## Code After:
from plugins.util import command, get_url
import json
import re
SPOTIFY_URI_REGEX = r"(?<=spotify:)(?:track|album|artist):[a-zA-Z0-9]{22}"
ENDPOINT = "https://api.spotify.com/v1/{0}s/{1}"
@command()
def spotify(m):
spotify_uris = re.findall(SPOTIFY_URI_REGEX, m.body)
for spotify_uri in spotify_uris:
try:
type, id = _parse_spotify_uri(spotify_uri)
except ValueError:
m.bot.logger.error("Invalid Spotify URI: " + spotify_uri)
else:
req = get_url(m, ENDPOINT.format(type, id))
if req:
blob = json.loads(req)
if type == "track" or type == "album":
m.bot.private_message(m.location, '"{0}" by {1} - {2}'
.format(blob["name"], blob["artists"][0]["name"],
blob["external_urls"]["spotify"]))
else:
m.bot.private_message(m.location, "{0} - {1}"
.format(blob["name"], blob["external_urls"]["spotify"]))
def _parse_spotify_uri(s):
[type, id] = s.split(':')
return type, id
| from plugins.util import command, get_url
import json
import re
SPOTIFY_URI_REGEX = r"(?<=spotify:)(?:track|album|artist):[a-zA-Z0-9]{22}"
ENDPOINT = "https://api.spotify.com/v1/{0}s/{1}"
@command()
def spotify(m):
spotify_uris = re.findall(SPOTIFY_URI_REGEX, m.body)
for spotify_uri in spotify_uris:
try:
type, id = _parse_spotify_uri(spotify_uri)
+ except ValueError:
+ m.bot.logger.error("Invalid Spotify URI: " + spotify_uri)
+ else:
req = get_url(m, ENDPOINT.format(type, id))
if req:
blob = json.loads(req)
if type == "track" or type == "album":
- m.bot.private_message(m.location,
+ m.bot.private_message(m.location, '"{0}" by {1} - {2}'
? +++++++++++++++++++++
- blob["artists"][0]["name"] + " - " + blob["name"])
+ .format(blob["name"], blob["artists"][0]["name"],
+ blob["external_urls"]["spotify"]))
else:
- m.bot.private_message(m.location, blob["name"])
? ----- ^^^^ --
+ m.bot.private_message(m.location, "{0} - {1}"
? ^^^^^^^^^
+ .format(blob["name"], blob["external_urls"]["spotify"]))
- except ValueError:
- m.bot.logger.error("Invalid Spotify URI: " + spotify_uri)
def _parse_spotify_uri(s):
[type, id] = s.split(':')
return type, id |
c6a161b5c0fa3d76b09b34dfab8f057e8b10bce2 | tests/test_extensions.py | tests/test_extensions.py | import unittest
class TestExtensions(unittest.TestCase):
def test_import_extension(self):
import pybel.ext.test
assert pybel.ext.test.an_extension_function() == 42
def test_import_extension_2(self):
from pybel.ext.test import an_extension_function
assert an_extension_function() == 42
def test_import_extension_3(self):
from pybel.ext import test
assert test.an_extension_function() == 42
| import unittest
class TestExtensions(unittest.TestCase):
def test_import_extension(self):
import pybel.ext.test
assert pybel.ext.test.an_extension_function() == 42
def test_import_extension_2(self):
from pybel.ext.test import an_extension_function
assert an_extension_function() == 42
def test_import_extension_3(self):
from pybel.ext import test
assert test.an_extension_function() == 42
def test_import_extension_4(self):
with self.assertRaises(ImportError):
from pybel.ext import not_an_extension
| Add a test for importing a nonexistent extension | Add a test for importing a nonexistent extension
| Python | mit | pybel/pybel,pybel/pybel,pybel/pybel | import unittest
class TestExtensions(unittest.TestCase):
def test_import_extension(self):
import pybel.ext.test
assert pybel.ext.test.an_extension_function() == 42
def test_import_extension_2(self):
from pybel.ext.test import an_extension_function
assert an_extension_function() == 42
def test_import_extension_3(self):
from pybel.ext import test
assert test.an_extension_function() == 42
+ def test_import_extension_4(self):
+ with self.assertRaises(ImportError):
+ from pybel.ext import not_an_extension
+ | Add a test for importing a nonexistent extension | ## Code Before:
import unittest
class TestExtensions(unittest.TestCase):
def test_import_extension(self):
import pybel.ext.test
assert pybel.ext.test.an_extension_function() == 42
def test_import_extension_2(self):
from pybel.ext.test import an_extension_function
assert an_extension_function() == 42
def test_import_extension_3(self):
from pybel.ext import test
assert test.an_extension_function() == 42
## Instruction:
Add a test for importing a nonexistent extension
## Code After:
import unittest
class TestExtensions(unittest.TestCase):
def test_import_extension(self):
import pybel.ext.test
assert pybel.ext.test.an_extension_function() == 42
def test_import_extension_2(self):
from pybel.ext.test import an_extension_function
assert an_extension_function() == 42
def test_import_extension_3(self):
from pybel.ext import test
assert test.an_extension_function() == 42
def test_import_extension_4(self):
with self.assertRaises(ImportError):
from pybel.ext import not_an_extension
| import unittest
class TestExtensions(unittest.TestCase):
def test_import_extension(self):
import pybel.ext.test
assert pybel.ext.test.an_extension_function() == 42
def test_import_extension_2(self):
from pybel.ext.test import an_extension_function
assert an_extension_function() == 42
def test_import_extension_3(self):
from pybel.ext import test
assert test.an_extension_function() == 42
+
+ def test_import_extension_4(self):
+ with self.assertRaises(ImportError):
+ from pybel.ext import not_an_extension |
756c9ae9487ac5c35f069b79e792043bca0af27e | panoptes_client/utils.py | panoptes_client/utils.py | import functools
ITERABLE_TYPES = (
list,
set,
tuple,
)
try:
from numpy import ndarray
ITERABLE_TYPES = ITERABLE_TYPES + (ndarray,)
except ImportError:
pass
def isiterable(v):
return isinstance(v, ITERABLE_TYPES)
def batchable(func=None, batch_size=100):
def do_batch(*args, **kwargs):
_batch_size = kwargs.pop('batch_size', batch_size)
if isiterable(args[0]):
_self = None
to_batch = args[0]
args = args[1:]
else:
_self = args[0]
to_batch = args[1]
args = args[2:]
if not isiterable(to_batch):
to_batch = [to_batch]
for _batch in [
to_batch[i:i+_batch_size]
for i in xrange(0, len(to_batch), _batch_size)
]:
if _self is None:
func(_batch, *args, **kwargs)
else:
func(_self, _batch, *args, **kwargs)
if func is None:
return functools.partial(batchable, batch_size=batch_size)
return do_batch
| import functools
ITERABLE_TYPES = (
list,
set,
tuple,
)
try:
from numpy import ndarray
ITERABLE_TYPES = ITERABLE_TYPES + (ndarray,)
except ImportError:
pass
def isiterable(v):
return isinstance(v, ITERABLE_TYPES)
def batchable(func=None, batch_size=100):
def do_batch(*args, **kwargs):
_batch_size = kwargs.pop('batch_size', batch_size)
if isiterable(args[0]):
_self = None
to_batch = args[0]
args = args[1:]
else:
_self = args[0]
to_batch = args[1]
args = args[2:]
if not isiterable(to_batch):
to_batch = [to_batch]
if isinstance(to_batch, set):
to_batch = list(to_batch)
for _batch in [
to_batch[i:i+_batch_size]
for i in xrange(0, len(to_batch), _batch_size)
]:
if _self is None:
func(_batch, *args, **kwargs)
else:
func(_self, _batch, *args, **kwargs)
if func is None:
return functools.partial(batchable, batch_size=batch_size)
return do_batch
| Fix passing sets to batchable methods | Fix passing sets to batchable methods
Sets don't support indexing, so convert them to lists.
| Python | apache-2.0 | zooniverse/panoptes-python-client | import functools
ITERABLE_TYPES = (
list,
set,
tuple,
)
try:
from numpy import ndarray
ITERABLE_TYPES = ITERABLE_TYPES + (ndarray,)
except ImportError:
pass
def isiterable(v):
return isinstance(v, ITERABLE_TYPES)
def batchable(func=None, batch_size=100):
def do_batch(*args, **kwargs):
_batch_size = kwargs.pop('batch_size', batch_size)
if isiterable(args[0]):
_self = None
to_batch = args[0]
args = args[1:]
else:
_self = args[0]
to_batch = args[1]
args = args[2:]
if not isiterable(to_batch):
to_batch = [to_batch]
+ if isinstance(to_batch, set):
+ to_batch = list(to_batch)
+
for _batch in [
to_batch[i:i+_batch_size]
for i in xrange(0, len(to_batch), _batch_size)
]:
if _self is None:
func(_batch, *args, **kwargs)
else:
func(_self, _batch, *args, **kwargs)
if func is None:
return functools.partial(batchable, batch_size=batch_size)
return do_batch
| Fix passing sets to batchable methods | ## Code Before:
import functools
ITERABLE_TYPES = (
list,
set,
tuple,
)
try:
from numpy import ndarray
ITERABLE_TYPES = ITERABLE_TYPES + (ndarray,)
except ImportError:
pass
def isiterable(v):
return isinstance(v, ITERABLE_TYPES)
def batchable(func=None, batch_size=100):
def do_batch(*args, **kwargs):
_batch_size = kwargs.pop('batch_size', batch_size)
if isiterable(args[0]):
_self = None
to_batch = args[0]
args = args[1:]
else:
_self = args[0]
to_batch = args[1]
args = args[2:]
if not isiterable(to_batch):
to_batch = [to_batch]
for _batch in [
to_batch[i:i+_batch_size]
for i in xrange(0, len(to_batch), _batch_size)
]:
if _self is None:
func(_batch, *args, **kwargs)
else:
func(_self, _batch, *args, **kwargs)
if func is None:
return functools.partial(batchable, batch_size=batch_size)
return do_batch
## Instruction:
Fix passing sets to batchable methods
## Code After:
import functools
ITERABLE_TYPES = (
list,
set,
tuple,
)
try:
from numpy import ndarray
ITERABLE_TYPES = ITERABLE_TYPES + (ndarray,)
except ImportError:
pass
def isiterable(v):
return isinstance(v, ITERABLE_TYPES)
def batchable(func=None, batch_size=100):
def do_batch(*args, **kwargs):
_batch_size = kwargs.pop('batch_size', batch_size)
if isiterable(args[0]):
_self = None
to_batch = args[0]
args = args[1:]
else:
_self = args[0]
to_batch = args[1]
args = args[2:]
if not isiterable(to_batch):
to_batch = [to_batch]
if isinstance(to_batch, set):
to_batch = list(to_batch)
for _batch in [
to_batch[i:i+_batch_size]
for i in xrange(0, len(to_batch), _batch_size)
]:
if _self is None:
func(_batch, *args, **kwargs)
else:
func(_self, _batch, *args, **kwargs)
if func is None:
return functools.partial(batchable, batch_size=batch_size)
return do_batch
| import functools
ITERABLE_TYPES = (
list,
set,
tuple,
)
try:
from numpy import ndarray
ITERABLE_TYPES = ITERABLE_TYPES + (ndarray,)
except ImportError:
pass
def isiterable(v):
return isinstance(v, ITERABLE_TYPES)
def batchable(func=None, batch_size=100):
def do_batch(*args, **kwargs):
_batch_size = kwargs.pop('batch_size', batch_size)
if isiterable(args[0]):
_self = None
to_batch = args[0]
args = args[1:]
else:
_self = args[0]
to_batch = args[1]
args = args[2:]
if not isiterable(to_batch):
to_batch = [to_batch]
+ if isinstance(to_batch, set):
+ to_batch = list(to_batch)
+
for _batch in [
to_batch[i:i+_batch_size]
for i in xrange(0, len(to_batch), _batch_size)
]:
if _self is None:
func(_batch, *args, **kwargs)
else:
func(_self, _batch, *args, **kwargs)
if func is None:
return functools.partial(batchable, batch_size=batch_size)
return do_batch |
0778a0a47967f0283a22908bcf89c0d98ce1647f | tests/test_redefine_colors.py | tests/test_redefine_colors.py |
"""Test redefinition of colors."""
import colorise
import pytest
@pytest.mark.skip_on_windows
def test_redefine_colors_error():
with pytest.raises(colorise.error.NotSupportedError):
colorise.redefine_colors({})
|
"""Test redefinition of colors."""
import colorise
import pytest
@pytest.mark.skip_on_windows
def test_redefine_colors_error():
assert not colorise.can_redefine_colors()
with pytest.raises(colorise.error.NotSupportedError):
colorise.redefine_colors({})
| Test color redefinition on nix | Test color redefinition on nix
| Python | bsd-3-clause | MisanthropicBit/colorise |
"""Test redefinition of colors."""
import colorise
import pytest
@pytest.mark.skip_on_windows
def test_redefine_colors_error():
+ assert not colorise.can_redefine_colors()
+
with pytest.raises(colorise.error.NotSupportedError):
colorise.redefine_colors({})
| Test color redefinition on nix | ## Code Before:
"""Test redefinition of colors."""
import colorise
import pytest
@pytest.mark.skip_on_windows
def test_redefine_colors_error():
with pytest.raises(colorise.error.NotSupportedError):
colorise.redefine_colors({})
## Instruction:
Test color redefinition on nix
## Code After:
"""Test redefinition of colors."""
import colorise
import pytest
@pytest.mark.skip_on_windows
def test_redefine_colors_error():
assert not colorise.can_redefine_colors()
with pytest.raises(colorise.error.NotSupportedError):
colorise.redefine_colors({})
|
"""Test redefinition of colors."""
import colorise
import pytest
@pytest.mark.skip_on_windows
def test_redefine_colors_error():
+ assert not colorise.can_redefine_colors()
+
with pytest.raises(colorise.error.NotSupportedError):
colorise.redefine_colors({}) |
edd8ac2d77b747cffbcf702e71f2633a148d64c6 | wagtail/wagtailcore/hooks.py | wagtail/wagtailcore/hooks.py | from django.conf import settings
try:
from importlib import import_module
except ImportError:
# for Python 2.6, fall back on django.utils.importlib (deprecated as of Django 1.7)
from django.utils.importlib import import_module
_hooks = {}
def register(hook_name, fn=None):
"""
Register hook for ``hook_name``. Can be used as a decorator::
@register('hook_name')
def my_hook(...):
pass
or as a function call::
def my_hook(...):
pass
register('hook_name', my_hook)
"""
# Pretend to be a decorator if fn is not supplied
if fn is None:
return lambda fn: register(hook_name, fn)
if hook_name not in _hooks:
_hooks[hook_name] = []
_hooks[hook_name].append(fn)
_searched_for_hooks = False
def search_for_hooks():
global _searched_for_hooks
if not _searched_for_hooks:
for app_module in settings.INSTALLED_APPS:
try:
import_module('%s.wagtail_hooks' % app_module)
except ImportError:
continue
_searched_for_hooks = True
def get_hooks(hook_name):
search_for_hooks()
return _hooks.get(hook_name, [])
| from django.conf import settings
try:
from importlib import import_module
except ImportError:
# for Python 2.6, fall back on django.utils.importlib (deprecated as of Django 1.7)
from django.utils.importlib import import_module
_hooks = {}
def register(hook_name, fn=None):
"""
Register hook for ``hook_name``. Can be used as a decorator::
@register('hook_name')
def my_hook(...):
pass
or as a function call::
def my_hook(...):
pass
register('hook_name', my_hook)
"""
# Pretend to be a decorator if fn is not supplied
if fn is None:
def decorator(fn):
register(hook_name, fn)
return fn
return decorator
if hook_name not in _hooks:
_hooks[hook_name] = []
_hooks[hook_name].append(fn)
_searched_for_hooks = False
def search_for_hooks():
global _searched_for_hooks
if not _searched_for_hooks:
for app_module in settings.INSTALLED_APPS:
try:
import_module('%s.wagtail_hooks' % app_module)
except ImportError:
continue
_searched_for_hooks = True
def get_hooks(hook_name):
search_for_hooks()
return _hooks.get(hook_name, [])
| Return the function again from the hook decorator | Return the function again from the hook decorator
The decorator variant of hook registration did not return anything,
meaning that the decorated function would end up being `None`. This was
not noticed, as the functions are rarely called manually, as opposed to
being invoked via the hook.
| Python | bsd-3-clause | kaedroho/wagtail,willcodefortea/wagtail,JoshBarr/wagtail,takeshineshiro/wagtail,torchbox/wagtail,dresiu/wagtail,m-sanders/wagtail,jnns/wagtail,bjesus/wagtail,jorge-marques/wagtail,nilnvoid/wagtail,timorieber/wagtail,rsalmaso/wagtail,Toshakins/wagtail,tangentlabs/wagtail,nimasmi/wagtail,WQuanfeng/wagtail,timorieber/wagtail,benjaoming/wagtail,mixxorz/wagtail,thenewguy/wagtail,benjaoming/wagtail,Toshakins/wagtail,inonit/wagtail,mixxorz/wagtail,stevenewey/wagtail,darith27/wagtail,nealtodd/wagtail,kurtrwall/wagtail,taedori81/wagtail,serzans/wagtail,nilnvoid/wagtail,taedori81/wagtail,Pennebaker/wagtail,JoshBarr/wagtail,kurtrwall/wagtail,FlipperPA/wagtail,m-sanders/wagtail,torchbox/wagtail,mixxorz/wagtail,100Shapes/wagtail,takeflight/wagtail,kaedroho/wagtail,rsalmaso/wagtail,taedori81/wagtail,wagtail/wagtail,Klaudit/wagtail,benemery/wagtail,jordij/wagtail,gogobook/wagtail,quru/wagtail,janusnic/wagtail,chrxr/wagtail,torchbox/wagtail,gasman/wagtail,gasman/wagtail,chimeno/wagtail,mephizzle/wagtail,janusnic/wagtail,kurtw/wagtail,marctc/wagtail,kaedroho/wagtail,takeflight/wagtail,gasman/wagtail,zerolab/wagtail,Klaudit/wagtail,kaedroho/wagtail,jorge-marques/wagtail,dresiu/wagtail,tangentlabs/wagtail,chrxr/wagtail,iansprice/wagtail,rjsproxy/wagtail,gogobook/wagtail,mikedingjan/wagtail,thenewguy/wagtail,hamsterbacke23/wagtail,takeshineshiro/wagtail,darith27/wagtail,rv816/wagtail,iho/wagtail,inonit/wagtail,mikedingjan/wagtail,nimasmi/wagtail,davecranwell/wagtail,jorge-marques/wagtail,hamsterbacke23/wagtail,stevenewey/wagtail,nealtodd/wagtail,mephizzle/wagtail,rsalmaso/wagtail,timorieber/wagtail,nutztherookie/wagtail,hanpama/wagtail,100Shapes/wagtail,rsalmaso/wagtail,timorieber/wagtail,marctc/wagtail,wagtail/wagtail,KimGlazebrook/wagtail-experiment,benemery/wagtail,zerolab/wagtail,nealtodd/wagtail,KimGlazebrook/wagtail-experiment,jordij/wagtail,hamsterbacke23/wagtail,nimasmi/wagtail,zerolab/wagtail,100Shapes/wagtail,mjec/wagtail,kurtrwall/wagtail,kurtw/wagtail,marctc/wagtail,iho/wagtail,Toshakins/wagtail,iansprice/wagtail,torchbox/wagtail,Pennebaker/wagtail,tangentlabs/wagtail,mayapurmedia/wagtail,benjaoming/wagtail,mephizzle/wagtail,m-sanders/wagtail,gogobook/wagtail,rv816/wagtail,dresiu/wagtail,quru/wagtail,willcodefortea/wagtail,KimGlazebrook/wagtail-experiment,nutztherookie/wagtail,mephizzle/wagtail,marctc/wagtail,Klaudit/wagtail,mjec/wagtail,jorge-marques/wagtail,zerolab/wagtail,dresiu/wagtail,chimeno/wagtail,jordij/wagtail,Pennebaker/wagtail,Toshakins/wagtail,jordij/wagtail,chrxr/wagtail,rjsproxy/wagtail,hanpama/wagtail,davecranwell/wagtail,gasman/wagtail,thenewguy/wagtail,jnns/wagtail,dresiu/wagtail,Tivix/wagtail,chimeno/wagtail,inonit/wagtail,rjsproxy/wagtail,JoshBarr/wagtail,hamsterbacke23/wagtail,bjesus/wagtail,nilnvoid/wagtail,iho/wagtail,WQuanfeng/wagtail,chimeno/wagtail,FlipperPA/wagtail,janusnic/wagtail,kurtw/wagtail,stevenewey/wagtail,mixxorz/wagtail,benjaoming/wagtail,FlipperPA/wagtail,nrsimha/wagtail,mikedingjan/wagtail,tangentlabs/wagtail,KimGlazebrook/wagtail-experiment,takeshineshiro/wagtail,gogobook/wagtail,takeshineshiro/wagtail,nimasmi/wagtail,mayapurmedia/wagtail,kaedroho/wagtail,bjesus/wagtail,FlipperPA/wagtail,willcodefortea/wagtail,taedori81/wagtail,mayapurmedia/wagtail,wagtail/wagtail,willcodefortea/wagtail,hanpama/wagtail,jnns/wagtail,kurtrwall/wagtail,bjesus/wagtail,serzans/wagtail,serzans/wagtail,nilnvoid/wagtail,takeflight/wagtail,thenewguy/wagtail,quru/wagtail,Klaudit/wagtail,darith27/wagtail,quru/wagtail,nutztherookie/wagtail,zerolab/wagtail,nrsimha/wagtail,iho/wagtail,WQuanfeng/wagtail,wagtail/wagtail,janusnic/wagtail,rv816/wagtail,inonit/wagtail,WQuanfeng/wagtail,Tivix/wagtail,davecranwell/wagtail,mikedingjan/wagtail,benemery/wagtail,JoshBarr/wagtail,gasman/wagtail,davecranwell/wagtail,jorge-marques/wagtail,Tivix/wagtail,thenewguy/wagtail,darith27/wagtail,mayapurmedia/wagtail,iansprice/wagtail,kurtw/wagtail,m-sanders/wagtail,takeflight/wagtail,nrsimha/wagtail,nrsimha/wagtail,hanpama/wagtail,stevenewey/wagtail,chrxr/wagtail,jnns/wagtail,taedori81/wagtail,mjec/wagtail,mixxorz/wagtail,iansprice/wagtail,rsalmaso/wagtail,nealtodd/wagtail,mjec/wagtail,Pennebaker/wagtail,serzans/wagtail,Tivix/wagtail,nutztherookie/wagtail,rjsproxy/wagtail,wagtail/wagtail,benemery/wagtail,chimeno/wagtail,rv816/wagtail | from django.conf import settings
try:
from importlib import import_module
except ImportError:
# for Python 2.6, fall back on django.utils.importlib (deprecated as of Django 1.7)
from django.utils.importlib import import_module
_hooks = {}
def register(hook_name, fn=None):
"""
Register hook for ``hook_name``. Can be used as a decorator::
@register('hook_name')
def my_hook(...):
pass
or as a function call::
def my_hook(...):
pass
register('hook_name', my_hook)
"""
# Pretend to be a decorator if fn is not supplied
if fn is None:
+ def decorator(fn):
- return lambda fn: register(hook_name, fn)
+ register(hook_name, fn)
+ return fn
+ return decorator
if hook_name not in _hooks:
_hooks[hook_name] = []
_hooks[hook_name].append(fn)
_searched_for_hooks = False
def search_for_hooks():
global _searched_for_hooks
if not _searched_for_hooks:
for app_module in settings.INSTALLED_APPS:
try:
import_module('%s.wagtail_hooks' % app_module)
except ImportError:
continue
_searched_for_hooks = True
def get_hooks(hook_name):
search_for_hooks()
return _hooks.get(hook_name, [])
| Return the function again from the hook decorator | ## Code Before:
from django.conf import settings
try:
from importlib import import_module
except ImportError:
# for Python 2.6, fall back on django.utils.importlib (deprecated as of Django 1.7)
from django.utils.importlib import import_module
_hooks = {}
def register(hook_name, fn=None):
"""
Register hook for ``hook_name``. Can be used as a decorator::
@register('hook_name')
def my_hook(...):
pass
or as a function call::
def my_hook(...):
pass
register('hook_name', my_hook)
"""
# Pretend to be a decorator if fn is not supplied
if fn is None:
return lambda fn: register(hook_name, fn)
if hook_name not in _hooks:
_hooks[hook_name] = []
_hooks[hook_name].append(fn)
_searched_for_hooks = False
def search_for_hooks():
global _searched_for_hooks
if not _searched_for_hooks:
for app_module in settings.INSTALLED_APPS:
try:
import_module('%s.wagtail_hooks' % app_module)
except ImportError:
continue
_searched_for_hooks = True
def get_hooks(hook_name):
search_for_hooks()
return _hooks.get(hook_name, [])
## Instruction:
Return the function again from the hook decorator
## Code After:
from django.conf import settings
try:
from importlib import import_module
except ImportError:
# for Python 2.6, fall back on django.utils.importlib (deprecated as of Django 1.7)
from django.utils.importlib import import_module
_hooks = {}
def register(hook_name, fn=None):
"""
Register hook for ``hook_name``. Can be used as a decorator::
@register('hook_name')
def my_hook(...):
pass
or as a function call::
def my_hook(...):
pass
register('hook_name', my_hook)
"""
# Pretend to be a decorator if fn is not supplied
if fn is None:
def decorator(fn):
register(hook_name, fn)
return fn
return decorator
if hook_name not in _hooks:
_hooks[hook_name] = []
_hooks[hook_name].append(fn)
_searched_for_hooks = False
def search_for_hooks():
global _searched_for_hooks
if not _searched_for_hooks:
for app_module in settings.INSTALLED_APPS:
try:
import_module('%s.wagtail_hooks' % app_module)
except ImportError:
continue
_searched_for_hooks = True
def get_hooks(hook_name):
search_for_hooks()
return _hooks.get(hook_name, [])
| from django.conf import settings
try:
from importlib import import_module
except ImportError:
# for Python 2.6, fall back on django.utils.importlib (deprecated as of Django 1.7)
from django.utils.importlib import import_module
_hooks = {}
def register(hook_name, fn=None):
"""
Register hook for ``hook_name``. Can be used as a decorator::
@register('hook_name')
def my_hook(...):
pass
or as a function call::
def my_hook(...):
pass
register('hook_name', my_hook)
"""
# Pretend to be a decorator if fn is not supplied
if fn is None:
+ def decorator(fn):
- return lambda fn: register(hook_name, fn)
? ------ ------ ^^^
+ register(hook_name, fn)
? ^
+ return fn
+ return decorator
if hook_name not in _hooks:
_hooks[hook_name] = []
_hooks[hook_name].append(fn)
_searched_for_hooks = False
def search_for_hooks():
global _searched_for_hooks
if not _searched_for_hooks:
for app_module in settings.INSTALLED_APPS:
try:
import_module('%s.wagtail_hooks' % app_module)
except ImportError:
continue
_searched_for_hooks = True
def get_hooks(hook_name):
search_for_hooks()
return _hooks.get(hook_name, []) |
c788398c2c89a7afcbbf899e7ed4d51fccf114b5 | php_coverage/command.py | php_coverage/command.py | import sublime_plugin
from php_coverage.finder import CoverageFinder
class CoverageCommand(sublime_plugin.TextCommand):
"""
Base class for a text command which has a coverage file.
"""
def __init__(self, view, coverage_finder=None):
super(CoverageCommand, self).__init__(view)
self.coverage_finder = coverage_finder
def get_coverage_finder(self):
"""
Gets the coverage finder for the command. If none is set, it
instantiates an instance of the default CoverageFinder class.
"""
if not self.coverage_finder:
self.coverage_finder = CoverageFinder()
return self.coverage_finder
def coverage(self):
"""
Finds the coverage file which contains coverage data for the
file open in the view which is running this command.
"""
return self.get_coverage_finder().find(self.view.file_name())
| import sublime_plugin
from php_coverage.data import CoverageDataFactory
from php_coverage.finder import CoverageFinder
class CoverageCommand(sublime_plugin.TextCommand):
"""
Base class for a text command which has a coverage file.
"""
def __init__(self, view, coverage_finder=None):
super(CoverageCommand, self).__init__(view)
self.coverage_finder = coverage_finder
def get_coverage_finder(self):
"""
Gets the coverage finder for the command. If none is set, it
instantiates an instance of the default CoverageFinder class.
"""
if not self.coverage_finder:
self.coverage_finder = CoverageFinder()
return self.coverage_finder
def coverage(self):
"""
Loads coverage data for the file open in the view which is
running this command.
"""
filename = self.view.file_name()
coverage_file = self.get_coverage_finder().find(filename)
if (coverage_file):
return CoverageDataFactory().factory(coverage_file)
return None
| Return coverage data in CoverageCommand::coverage() | Return coverage data in CoverageCommand::coverage()
| Python | mit | bradfeehan/SublimePHPCoverage,bradfeehan/SublimePHPCoverage | import sublime_plugin
+
+ from php_coverage.data import CoverageDataFactory
from php_coverage.finder import CoverageFinder
class CoverageCommand(sublime_plugin.TextCommand):
"""
Base class for a text command which has a coverage file.
"""
def __init__(self, view, coverage_finder=None):
super(CoverageCommand, self).__init__(view)
self.coverage_finder = coverage_finder
def get_coverage_finder(self):
"""
Gets the coverage finder for the command. If none is set, it
instantiates an instance of the default CoverageFinder class.
"""
if not self.coverage_finder:
self.coverage_finder = CoverageFinder()
return self.coverage_finder
def coverage(self):
"""
- Finds the coverage file which contains coverage data for the
- file open in the view which is running this command.
+ Loads coverage data for the file open in the view which is
+ running this command.
"""
+ filename = self.view.file_name()
- return self.get_coverage_finder().find(self.view.file_name())
+ coverage_file = self.get_coverage_finder().find(filename)
+ if (coverage_file):
+ return CoverageDataFactory().factory(coverage_file)
+ return None
+ | Return coverage data in CoverageCommand::coverage() | ## Code Before:
import sublime_plugin
from php_coverage.finder import CoverageFinder
class CoverageCommand(sublime_plugin.TextCommand):
"""
Base class for a text command which has a coverage file.
"""
def __init__(self, view, coverage_finder=None):
super(CoverageCommand, self).__init__(view)
self.coverage_finder = coverage_finder
def get_coverage_finder(self):
"""
Gets the coverage finder for the command. If none is set, it
instantiates an instance of the default CoverageFinder class.
"""
if not self.coverage_finder:
self.coverage_finder = CoverageFinder()
return self.coverage_finder
def coverage(self):
"""
Finds the coverage file which contains coverage data for the
file open in the view which is running this command.
"""
return self.get_coverage_finder().find(self.view.file_name())
## Instruction:
Return coverage data in CoverageCommand::coverage()
## Code After:
import sublime_plugin
from php_coverage.data import CoverageDataFactory
from php_coverage.finder import CoverageFinder
class CoverageCommand(sublime_plugin.TextCommand):
"""
Base class for a text command which has a coverage file.
"""
def __init__(self, view, coverage_finder=None):
super(CoverageCommand, self).__init__(view)
self.coverage_finder = coverage_finder
def get_coverage_finder(self):
"""
Gets the coverage finder for the command. If none is set, it
instantiates an instance of the default CoverageFinder class.
"""
if not self.coverage_finder:
self.coverage_finder = CoverageFinder()
return self.coverage_finder
def coverage(self):
"""
Loads coverage data for the file open in the view which is
running this command.
"""
filename = self.view.file_name()
coverage_file = self.get_coverage_finder().find(filename)
if (coverage_file):
return CoverageDataFactory().factory(coverage_file)
return None
| import sublime_plugin
+
+ from php_coverage.data import CoverageDataFactory
from php_coverage.finder import CoverageFinder
class CoverageCommand(sublime_plugin.TextCommand):
"""
Base class for a text command which has a coverage file.
"""
def __init__(self, view, coverage_finder=None):
super(CoverageCommand, self).__init__(view)
self.coverage_finder = coverage_finder
def get_coverage_finder(self):
"""
Gets the coverage finder for the command. If none is set, it
instantiates an instance of the default CoverageFinder class.
"""
if not self.coverage_finder:
self.coverage_finder = CoverageFinder()
return self.coverage_finder
def coverage(self):
"""
- Finds the coverage file which contains coverage data for the
- file open in the view which is running this command.
+ Loads coverage data for the file open in the view which is
+ running this command.
"""
+ filename = self.view.file_name()
- return self.get_coverage_finder().find(self.view.file_name())
? ^^^^ ---------- - - -
+ coverage_file = self.get_coverage_finder().find(filename)
? ++++ ++ ^^^^^^^
+ if (coverage_file):
+ return CoverageDataFactory().factory(coverage_file)
+
+ return None |
7608d0e89781f70fcb49e7dc3ee5cd57a094f18c | rx/__init__.py | rx/__init__.py | from .observable import Observable
from .anonymousobservable import AnonymousObservable
from .observer import Observer
from . import checkedobserver
from . import linq
from . import backpressure
try:
from asyncio import Future
except ImportError:
Future = None
# Rx configuration dictionary
config = {
"Future" : Future
} | from threading import Lock
from .observable import Observable
from .anonymousobservable import AnonymousObservable
from .observer import Observer
from . import checkedobserver
from . import linq
from . import backpressure
try:
from asyncio import Future
except ImportError:
Future = None
# Rx configuration dictionary
config = {
"Future" : Future,
"Lock" : Lock
} | Make it possible to set custom Lock | Make it possible to set custom Lock
| Python | mit | ReactiveX/RxPY,ReactiveX/RxPY,dbrattli/RxPY | + from threading import Lock
+
from .observable import Observable
from .anonymousobservable import AnonymousObservable
from .observer import Observer
from . import checkedobserver
from . import linq
from . import backpressure
try:
from asyncio import Future
except ImportError:
Future = None
# Rx configuration dictionary
config = {
- "Future" : Future
+ "Future" : Future,
+ "Lock" : Lock
} | Make it possible to set custom Lock | ## Code Before:
from .observable import Observable
from .anonymousobservable import AnonymousObservable
from .observer import Observer
from . import checkedobserver
from . import linq
from . import backpressure
try:
from asyncio import Future
except ImportError:
Future = None
# Rx configuration dictionary
config = {
"Future" : Future
}
## Instruction:
Make it possible to set custom Lock
## Code After:
from threading import Lock
from .observable import Observable
from .anonymousobservable import AnonymousObservable
from .observer import Observer
from . import checkedobserver
from . import linq
from . import backpressure
try:
from asyncio import Future
except ImportError:
Future = None
# Rx configuration dictionary
config = {
"Future" : Future,
"Lock" : Lock
} | + from threading import Lock
+
from .observable import Observable
from .anonymousobservable import AnonymousObservable
from .observer import Observer
from . import checkedobserver
from . import linq
from . import backpressure
try:
from asyncio import Future
except ImportError:
Future = None
# Rx configuration dictionary
config = {
- "Future" : Future
+ "Future" : Future,
? +
+ "Lock" : Lock
} |
3a0c7caadb46a69fb29fe34bd64de28c9b263fd6 | restconverter.py | restconverter.py |
from docutils import core
from docutils.writers.html4css1 import Writer, HTMLTranslator
class HTMLFragmentTranslator(HTMLTranslator):
def __init__(self, document):
HTMLTranslator.__init__(self, document)
self.head_prefix = ['','','','','']
self.body_prefix = []
self.body_suffix = []
self.stylesheet = []
def astext(self):
return ''.join(self.body)
html_fragment_writer = Writer()
html_fragment_writer.translator_class = HTMLFragmentTranslator
def rest_to_html(s):
"""Convert ReST input to HTML output"""
return core.publish_string(s, writer=html_fragment_writer)
|
from docutils import core
from docutils.writers.html4css1 import Writer, HTMLTranslator
class HTMLFragmentTranslator(HTMLTranslator):
def __init__(self, document):
HTMLTranslator.__init__(self, document)
self.head_prefix = ['','','','','']
self.body_prefix = []
self.body_suffix = []
self.stylesheet = []
def astext(self):
return ''.join(self.body)
html_fragment_writer = Writer()
html_fragment_writer.translator_class = HTMLFragmentTranslator
def rest_to_html(s):
"""Convert ReST input to HTML output"""
return core.publish_string(s, writer=html_fragment_writer)
def rest_to_html_fragment(s):
parts = core.publish_parts(
source=s,
writer_name='html')
return parts['body_pre_docinfo']+parts['fragment']
| Add rest_to_html_fragment to be able to convert just the body part | Add rest_to_html_fragment to be able to convert just the body part
| Python | bsd-2-clause | jkossen/flaskjk |
from docutils import core
from docutils.writers.html4css1 import Writer, HTMLTranslator
class HTMLFragmentTranslator(HTMLTranslator):
def __init__(self, document):
HTMLTranslator.__init__(self, document)
self.head_prefix = ['','','','','']
self.body_prefix = []
self.body_suffix = []
self.stylesheet = []
def astext(self):
return ''.join(self.body)
html_fragment_writer = Writer()
html_fragment_writer.translator_class = HTMLFragmentTranslator
def rest_to_html(s):
"""Convert ReST input to HTML output"""
return core.publish_string(s, writer=html_fragment_writer)
+ def rest_to_html_fragment(s):
+ parts = core.publish_parts(
+ source=s,
+ writer_name='html')
+ return parts['body_pre_docinfo']+parts['fragment']
+ | Add rest_to_html_fragment to be able to convert just the body part | ## Code Before:
from docutils import core
from docutils.writers.html4css1 import Writer, HTMLTranslator
class HTMLFragmentTranslator(HTMLTranslator):
def __init__(self, document):
HTMLTranslator.__init__(self, document)
self.head_prefix = ['','','','','']
self.body_prefix = []
self.body_suffix = []
self.stylesheet = []
def astext(self):
return ''.join(self.body)
html_fragment_writer = Writer()
html_fragment_writer.translator_class = HTMLFragmentTranslator
def rest_to_html(s):
"""Convert ReST input to HTML output"""
return core.publish_string(s, writer=html_fragment_writer)
## Instruction:
Add rest_to_html_fragment to be able to convert just the body part
## Code After:
from docutils import core
from docutils.writers.html4css1 import Writer, HTMLTranslator
class HTMLFragmentTranslator(HTMLTranslator):
def __init__(self, document):
HTMLTranslator.__init__(self, document)
self.head_prefix = ['','','','','']
self.body_prefix = []
self.body_suffix = []
self.stylesheet = []
def astext(self):
return ''.join(self.body)
html_fragment_writer = Writer()
html_fragment_writer.translator_class = HTMLFragmentTranslator
def rest_to_html(s):
"""Convert ReST input to HTML output"""
return core.publish_string(s, writer=html_fragment_writer)
def rest_to_html_fragment(s):
parts = core.publish_parts(
source=s,
writer_name='html')
return parts['body_pre_docinfo']+parts['fragment']
|
from docutils import core
from docutils.writers.html4css1 import Writer, HTMLTranslator
class HTMLFragmentTranslator(HTMLTranslator):
def __init__(self, document):
HTMLTranslator.__init__(self, document)
self.head_prefix = ['','','','','']
self.body_prefix = []
self.body_suffix = []
self.stylesheet = []
def astext(self):
return ''.join(self.body)
html_fragment_writer = Writer()
html_fragment_writer.translator_class = HTMLFragmentTranslator
def rest_to_html(s):
"""Convert ReST input to HTML output"""
return core.publish_string(s, writer=html_fragment_writer)
+ def rest_to_html_fragment(s):
+ parts = core.publish_parts(
+ source=s,
+ writer_name='html')
+ return parts['body_pre_docinfo']+parts['fragment']
+ |
8b944f04ebf9b635029182a3137e9368edafe9d2 | pgsearch/utils.py | pgsearch/utils.py | from django.contrib.postgres.search import SearchVector, SearchRank, SearchQuery
import shlex
import string
def parseSearchString(search_string):
search_strings = shlex.split(search_string)
translator = str.maketrans({key: None for key in string.punctuation})
search_strings = [s.translate(translator) for s in search_strings]
return search_strings
def createSearchQuery(list_of_terms):
if len(list_of_terms) > 0:
q = SearchQuery(list_of_terms[0])
for term in list_of_terms[1:]:
q = q & SearchQuery(term)
return q
else:
return None
def searchPostgresDB(search_string, Table, config, rank, *fields):
list_of_terms = parseSearchString(search_string)
search_query = createSearchQuery(list_of_terms)
if rank == True:
vector = SearchVector(*fields, config=config)
objs = Table.objects.annotate(rank=SearchRank(vector, search_query)).\
order_by('-rank')
else:
objs = Table.objects.annotate(search=SearchVector(*fields,
config=config),).\
filter(search=search_query)
return objs
| from django.contrib.postgres.search import SearchVector, SearchRank, SearchQuery
import shlex
import string
def parseSearchString(search_string):
try:
search_strings = shlex.split(search_string)
translator = str.maketrans({key: None for key in string.punctuation})
search_strings = [s.translate(translator) for s in search_strings]
except:
search_strings = []
return search_strings
def createSearchQuery(list_of_terms):
if len(list_of_terms) > 0:
q = SearchQuery(list_of_terms[0])
for term in list_of_terms[1:]:
q = q & SearchQuery(term)
return q
else:
return None
def searchPostgresDB(search_string, Table, config, rank, *fields):
list_of_terms = parseSearchString(search_string)
search_query = createSearchQuery(list_of_terms)
if rank == True:
vector = SearchVector(*fields, config=config)
objs = Table.objects.annotate(rank=SearchRank(vector, search_query)).\
order_by('-rank')
else:
objs = Table.objects.annotate(search=SearchVector(*fields,
config=config),).\
filter(search=search_query)
return objs
| Handle exception for bad search strings | Handle exception for bad search strings
| Python | bsd-3-clause | groundupnews/gu,groundupnews/gu,groundupnews/gu,groundupnews/gu,groundupnews/gu | from django.contrib.postgres.search import SearchVector, SearchRank, SearchQuery
import shlex
import string
def parseSearchString(search_string):
+ try:
- search_strings = shlex.split(search_string)
+ search_strings = shlex.split(search_string)
- translator = str.maketrans({key: None for key in string.punctuation})
+ translator = str.maketrans({key: None for key in string.punctuation})
- search_strings = [s.translate(translator) for s in search_strings]
+ search_strings = [s.translate(translator) for s in search_strings]
+ except:
+ search_strings = []
return search_strings
def createSearchQuery(list_of_terms):
if len(list_of_terms) > 0:
q = SearchQuery(list_of_terms[0])
for term in list_of_terms[1:]:
q = q & SearchQuery(term)
return q
else:
return None
def searchPostgresDB(search_string, Table, config, rank, *fields):
list_of_terms = parseSearchString(search_string)
search_query = createSearchQuery(list_of_terms)
if rank == True:
vector = SearchVector(*fields, config=config)
objs = Table.objects.annotate(rank=SearchRank(vector, search_query)).\
order_by('-rank')
else:
objs = Table.objects.annotate(search=SearchVector(*fields,
config=config),).\
filter(search=search_query)
return objs
| Handle exception for bad search strings | ## Code Before:
from django.contrib.postgres.search import SearchVector, SearchRank, SearchQuery
import shlex
import string
def parseSearchString(search_string):
search_strings = shlex.split(search_string)
translator = str.maketrans({key: None for key in string.punctuation})
search_strings = [s.translate(translator) for s in search_strings]
return search_strings
def createSearchQuery(list_of_terms):
if len(list_of_terms) > 0:
q = SearchQuery(list_of_terms[0])
for term in list_of_terms[1:]:
q = q & SearchQuery(term)
return q
else:
return None
def searchPostgresDB(search_string, Table, config, rank, *fields):
list_of_terms = parseSearchString(search_string)
search_query = createSearchQuery(list_of_terms)
if rank == True:
vector = SearchVector(*fields, config=config)
objs = Table.objects.annotate(rank=SearchRank(vector, search_query)).\
order_by('-rank')
else:
objs = Table.objects.annotate(search=SearchVector(*fields,
config=config),).\
filter(search=search_query)
return objs
## Instruction:
Handle exception for bad search strings
## Code After:
from django.contrib.postgres.search import SearchVector, SearchRank, SearchQuery
import shlex
import string
def parseSearchString(search_string):
try:
search_strings = shlex.split(search_string)
translator = str.maketrans({key: None for key in string.punctuation})
search_strings = [s.translate(translator) for s in search_strings]
except:
search_strings = []
return search_strings
def createSearchQuery(list_of_terms):
if len(list_of_terms) > 0:
q = SearchQuery(list_of_terms[0])
for term in list_of_terms[1:]:
q = q & SearchQuery(term)
return q
else:
return None
def searchPostgresDB(search_string, Table, config, rank, *fields):
list_of_terms = parseSearchString(search_string)
search_query = createSearchQuery(list_of_terms)
if rank == True:
vector = SearchVector(*fields, config=config)
objs = Table.objects.annotate(rank=SearchRank(vector, search_query)).\
order_by('-rank')
else:
objs = Table.objects.annotate(search=SearchVector(*fields,
config=config),).\
filter(search=search_query)
return objs
| from django.contrib.postgres.search import SearchVector, SearchRank, SearchQuery
import shlex
import string
def parseSearchString(search_string):
+ try:
- search_strings = shlex.split(search_string)
+ search_strings = shlex.split(search_string)
? ++++
- translator = str.maketrans({key: None for key in string.punctuation})
+ translator = str.maketrans({key: None for key in string.punctuation})
? ++++
- search_strings = [s.translate(translator) for s in search_strings]
+ search_strings = [s.translate(translator) for s in search_strings]
? ++++
+ except:
+ search_strings = []
return search_strings
def createSearchQuery(list_of_terms):
if len(list_of_terms) > 0:
q = SearchQuery(list_of_terms[0])
for term in list_of_terms[1:]:
q = q & SearchQuery(term)
return q
else:
return None
def searchPostgresDB(search_string, Table, config, rank, *fields):
list_of_terms = parseSearchString(search_string)
search_query = createSearchQuery(list_of_terms)
if rank == True:
vector = SearchVector(*fields, config=config)
objs = Table.objects.annotate(rank=SearchRank(vector, search_query)).\
order_by('-rank')
else:
objs = Table.objects.annotate(search=SearchVector(*fields,
config=config),).\
filter(search=search_query)
return objs |
9339e0bd1197f8d599309eaff66b83c38721ab29 | conference/management/commands/add_invoices_for_zero_amount_orders.py | conference/management/commands/add_invoices_for_zero_amount_orders.py |
from __future__ import print_function
from django.core.management.base import BaseCommand
from assopy import models as amodels
def generate_invoices_for_zero_amount_orders_for_year(year):
orders = amodels.Order.objects.filter(
created__year=year,
method='bank',
)
for o in orders:
if not o.complete():
continue
print ('Creating invoice for order %r' % o)
o.confirm_order(o.created)
o.complete()
class Command(BaseCommand):
"""
The system did not generate invoices for orders with a zero amount
in 2018 (e.g. as result of using discounts).
We have to add them after the fact.
"""
def handle(self, *args, **options):
generate_invoices_for_zero_amount_orders_for_year(2018)
|
from __future__ import print_function
from django.core.management.base import BaseCommand
from assopy import models as amodels
def generate_invoices_for_zero_amount_orders_for_year(year):
orders = amodels.Order.objects.filter(
created__year=year,
method='bank',
)
for o in orders:
if not o.complete():
continue
if o.total() > 0:
continue
print ('Creating invoice for order %r' % o)
o.confirm_order(o.created)
o.complete()
class Command(BaseCommand):
"""
The system did not generate invoices for orders with a zero amount
in 2018 (e.g. as result of using discounts).
We have to add them after the fact.
"""
def handle(self, *args, **options):
generate_invoices_for_zero_amount_orders_for_year(2018)
| Make sure that only zero amount orders are modified. | Make sure that only zero amount orders are modified.
Note really necessary, since we don't have real bank orders,
but better safe than sorry.
| Python | bsd-2-clause | EuroPython/epcon,EuroPython/epcon,EuroPython/epcon,EuroPython/epcon |
from __future__ import print_function
from django.core.management.base import BaseCommand
from assopy import models as amodels
def generate_invoices_for_zero_amount_orders_for_year(year):
orders = amodels.Order.objects.filter(
created__year=year,
method='bank',
)
for o in orders:
if not o.complete():
+ continue
+ if o.total() > 0:
continue
print ('Creating invoice for order %r' % o)
o.confirm_order(o.created)
o.complete()
class Command(BaseCommand):
"""
The system did not generate invoices for orders with a zero amount
in 2018 (e.g. as result of using discounts).
We have to add them after the fact.
"""
def handle(self, *args, **options):
generate_invoices_for_zero_amount_orders_for_year(2018)
| Make sure that only zero amount orders are modified. | ## Code Before:
from __future__ import print_function
from django.core.management.base import BaseCommand
from assopy import models as amodels
def generate_invoices_for_zero_amount_orders_for_year(year):
orders = amodels.Order.objects.filter(
created__year=year,
method='bank',
)
for o in orders:
if not o.complete():
continue
print ('Creating invoice for order %r' % o)
o.confirm_order(o.created)
o.complete()
class Command(BaseCommand):
"""
The system did not generate invoices for orders with a zero amount
in 2018 (e.g. as result of using discounts).
We have to add them after the fact.
"""
def handle(self, *args, **options):
generate_invoices_for_zero_amount_orders_for_year(2018)
## Instruction:
Make sure that only zero amount orders are modified.
## Code After:
from __future__ import print_function
from django.core.management.base import BaseCommand
from assopy import models as amodels
def generate_invoices_for_zero_amount_orders_for_year(year):
orders = amodels.Order.objects.filter(
created__year=year,
method='bank',
)
for o in orders:
if not o.complete():
continue
if o.total() > 0:
continue
print ('Creating invoice for order %r' % o)
o.confirm_order(o.created)
o.complete()
class Command(BaseCommand):
"""
The system did not generate invoices for orders with a zero amount
in 2018 (e.g. as result of using discounts).
We have to add them after the fact.
"""
def handle(self, *args, **options):
generate_invoices_for_zero_amount_orders_for_year(2018)
|
from __future__ import print_function
from django.core.management.base import BaseCommand
from assopy import models as amodels
def generate_invoices_for_zero_amount_orders_for_year(year):
orders = amodels.Order.objects.filter(
created__year=year,
method='bank',
)
for o in orders:
if not o.complete():
+ continue
+ if o.total() > 0:
continue
print ('Creating invoice for order %r' % o)
o.confirm_order(o.created)
o.complete()
class Command(BaseCommand):
"""
The system did not generate invoices for orders with a zero amount
in 2018 (e.g. as result of using discounts).
We have to add them after the fact.
"""
def handle(self, *args, **options):
generate_invoices_for_zero_amount_orders_for_year(2018) |
09a18ba1b2ac5517b37b524fb2c7d7e2917ed251 | words.py | words.py |
import subprocess
from sys import exit
import random
def choose(difficulty):
(min, max) = difficulty
cmd = "/usr/bin/grep -E '^.{{{},{}}}$' /usr/share/dict/words".format(min, max)
obj = subprocess.run(cmd,
shell=True,
stdout=subprocess.PIPE)
result = obj.stdout.decode('utf-8').strip().split("\n")
return random.choice(result) |
import subprocess
from sys import exit
import random
def choose(difficulty):
(min, max) = difficulty
cmd = "/usr/bin/grep -E '^.{{{},{}}}$' /usr/share/dict/words".format(min, max)
obj = subprocess.run(cmd,
shell=True,
stdout=subprocess.PIPE)
result = obj.stdout.decode('utf-8').strip().split("\n")
return random.choice(result)
if __name__ == "__main__":
choose((3, 8)) | Add a main guard for testing | Add a main guard for testing
| Python | mit | tml/python-hangman-2017-summer |
import subprocess
from sys import exit
import random
def choose(difficulty):
(min, max) = difficulty
cmd = "/usr/bin/grep -E '^.{{{},{}}}$' /usr/share/dict/words".format(min, max)
obj = subprocess.run(cmd,
shell=True,
stdout=subprocess.PIPE)
result = obj.stdout.decode('utf-8').strip().split("\n")
return random.choice(result)
+
+
+ if __name__ == "__main__":
+ choose((3, 8)) | Add a main guard for testing | ## Code Before:
import subprocess
from sys import exit
import random
def choose(difficulty):
(min, max) = difficulty
cmd = "/usr/bin/grep -E '^.{{{},{}}}$' /usr/share/dict/words".format(min, max)
obj = subprocess.run(cmd,
shell=True,
stdout=subprocess.PIPE)
result = obj.stdout.decode('utf-8').strip().split("\n")
return random.choice(result)
## Instruction:
Add a main guard for testing
## Code After:
import subprocess
from sys import exit
import random
def choose(difficulty):
(min, max) = difficulty
cmd = "/usr/bin/grep -E '^.{{{},{}}}$' /usr/share/dict/words".format(min, max)
obj = subprocess.run(cmd,
shell=True,
stdout=subprocess.PIPE)
result = obj.stdout.decode('utf-8').strip().split("\n")
return random.choice(result)
if __name__ == "__main__":
choose((3, 8)) |
import subprocess
from sys import exit
import random
def choose(difficulty):
(min, max) = difficulty
cmd = "/usr/bin/grep -E '^.{{{},{}}}$' /usr/share/dict/words".format(min, max)
obj = subprocess.run(cmd,
shell=True,
stdout=subprocess.PIPE)
result = obj.stdout.decode('utf-8').strip().split("\n")
return random.choice(result)
+
+
+ if __name__ == "__main__":
+ choose((3, 8)) |
ba57b3c016ed3bc3c8db9ccc3c637c2c58de1e1d | reddit/admin.py | reddit/admin.py | from django.contrib import admin
from reddit.models import RedditUser,Submission,Comment,Vote
# Register your models here.
class SubmissionInline(admin.TabularInline):
model = Submission
max_num = 10
class CommentsInline(admin.StackedInline):
model = Comment
max_num = 10
class SubmissionAdmin(admin.ModelAdmin):
list_display = ('title', 'url', 'author')
inlines = [CommentsInline]
class RedditUserAdmin(admin.ModelAdmin):
inlines = [
SubmissionInline,
CommentsInline
]
admin.site.register(RedditUser, RedditUserAdmin)
admin.site.register(Submission, SubmissionAdmin)
admin.site.register(Comment)
admin.site.register(Vote) | from django.contrib import admin
from reddit.models import RedditUser,Submission,Comment,Vote
# Register your models here.
class SubmissionInline(admin.TabularInline):
model = Submission
max_num = 10
class CommentsInline(admin.StackedInline):
model = Comment
max_num = 10
class SubmissionAdmin(admin.ModelAdmin):
list_display = ('title', 'url', 'author')
inlines = [CommentsInline]
class RedditUserAdmin(admin.ModelAdmin):
inlines = [
SubmissionInline,
]
admin.site.register(RedditUser, RedditUserAdmin)
admin.site.register(Submission, SubmissionAdmin)
admin.site.register(Comment)
admin.site.register(Vote) | Remove commentsInLine for RedditUser because there is no longer foreignKey from Comment to RedditUser | Remove commentsInLine for RedditUser because there is no longer foreignKey from Comment to RedditUser
| Python | apache-2.0 | Nikola-K/django_reddit,Nikola-K/django_reddit,Nikola-K/django_reddit | from django.contrib import admin
from reddit.models import RedditUser,Submission,Comment,Vote
# Register your models here.
class SubmissionInline(admin.TabularInline):
model = Submission
max_num = 10
class CommentsInline(admin.StackedInline):
model = Comment
max_num = 10
class SubmissionAdmin(admin.ModelAdmin):
list_display = ('title', 'url', 'author')
inlines = [CommentsInline]
class RedditUserAdmin(admin.ModelAdmin):
inlines = [
SubmissionInline,
- CommentsInline
]
admin.site.register(RedditUser, RedditUserAdmin)
admin.site.register(Submission, SubmissionAdmin)
admin.site.register(Comment)
admin.site.register(Vote) | Remove commentsInLine for RedditUser because there is no longer foreignKey from Comment to RedditUser | ## Code Before:
from django.contrib import admin
from reddit.models import RedditUser,Submission,Comment,Vote
# Register your models here.
class SubmissionInline(admin.TabularInline):
model = Submission
max_num = 10
class CommentsInline(admin.StackedInline):
model = Comment
max_num = 10
class SubmissionAdmin(admin.ModelAdmin):
list_display = ('title', 'url', 'author')
inlines = [CommentsInline]
class RedditUserAdmin(admin.ModelAdmin):
inlines = [
SubmissionInline,
CommentsInline
]
admin.site.register(RedditUser, RedditUserAdmin)
admin.site.register(Submission, SubmissionAdmin)
admin.site.register(Comment)
admin.site.register(Vote)
## Instruction:
Remove commentsInLine for RedditUser because there is no longer foreignKey from Comment to RedditUser
## Code After:
from django.contrib import admin
from reddit.models import RedditUser,Submission,Comment,Vote
# Register your models here.
class SubmissionInline(admin.TabularInline):
model = Submission
max_num = 10
class CommentsInline(admin.StackedInline):
model = Comment
max_num = 10
class SubmissionAdmin(admin.ModelAdmin):
list_display = ('title', 'url', 'author')
inlines = [CommentsInline]
class RedditUserAdmin(admin.ModelAdmin):
inlines = [
SubmissionInline,
]
admin.site.register(RedditUser, RedditUserAdmin)
admin.site.register(Submission, SubmissionAdmin)
admin.site.register(Comment)
admin.site.register(Vote) | from django.contrib import admin
from reddit.models import RedditUser,Submission,Comment,Vote
# Register your models here.
class SubmissionInline(admin.TabularInline):
model = Submission
max_num = 10
class CommentsInline(admin.StackedInline):
model = Comment
max_num = 10
class SubmissionAdmin(admin.ModelAdmin):
list_display = ('title', 'url', 'author')
inlines = [CommentsInline]
class RedditUserAdmin(admin.ModelAdmin):
inlines = [
SubmissionInline,
- CommentsInline
]
admin.site.register(RedditUser, RedditUserAdmin)
admin.site.register(Submission, SubmissionAdmin)
admin.site.register(Comment)
admin.site.register(Vote) |
0fbd7c2f68f9f751642fd0e618dfcb6726d79f44 | fireplace/cards/wog/mage.py | fireplace/cards/wog/mage.py | from ..utils import *
##
# Minions
| from ..utils import *
##
# Minions
class OG_083:
"Twilight Flamecaller"
play = Hit(ENEMY_MINIONS, 1)
class OG_120:
"Anomalus"
deathrattle = Hit(ALL_MINIONS, 8)
class OG_207:
"Faceless Summoner"
play = Summon(CONTROLLER, RandomMinion(cost=3))
| Implement Twilight Flamecaller, Anomalus, Faceless Summoner | Implement Twilight Flamecaller, Anomalus, Faceless Summoner
| Python | agpl-3.0 | NightKev/fireplace,jleclanche/fireplace,beheh/fireplace | from ..utils import *
##
# Minions
+ class OG_083:
+ "Twilight Flamecaller"
+ play = Hit(ENEMY_MINIONS, 1)
+ class OG_120:
+ "Anomalus"
+ deathrattle = Hit(ALL_MINIONS, 8)
+
+
+ class OG_207:
+ "Faceless Summoner"
+ play = Summon(CONTROLLER, RandomMinion(cost=3))
+ | Implement Twilight Flamecaller, Anomalus, Faceless Summoner | ## Code Before:
from ..utils import *
##
# Minions
## Instruction:
Implement Twilight Flamecaller, Anomalus, Faceless Summoner
## Code After:
from ..utils import *
##
# Minions
class OG_083:
"Twilight Flamecaller"
play = Hit(ENEMY_MINIONS, 1)
class OG_120:
"Anomalus"
deathrattle = Hit(ALL_MINIONS, 8)
class OG_207:
"Faceless Summoner"
play = Summon(CONTROLLER, RandomMinion(cost=3))
| from ..utils import *
##
# Minions
+ class OG_083:
+ "Twilight Flamecaller"
+ play = Hit(ENEMY_MINIONS, 1)
+
+ class OG_120:
+ "Anomalus"
+ deathrattle = Hit(ALL_MINIONS, 8)
+
+
+ class OG_207:
+ "Faceless Summoner"
+ play = Summon(CONTROLLER, RandomMinion(cost=3)) |
67a20401caaa63852e95fcaf8bafb6ed85ecd1f2 | test/selenium/src/lib/page/modal/__init__.py | test/selenium/src/lib/page/modal/__init__.py |
from lib.page.modal import (
create_new_object, # flake8: noqa
edit_object, # flake8: noqa
delete_object # flake8: noqa
)
|
from lib.page.modal import (
create_new_object, # flake8: noqa
edit_object, # flake8: noqa
delete_object, # flake8: noqa
update_object # flake8: noqa
)
| Add a sort of hierarchy of modules for package | Add a sort of hierarchy of modules for package
| Python | apache-2.0 | AleksNeStu/ggrc-core,VinnieJohns/ggrc-core,plamut/ggrc-core,plamut/ggrc-core,AleksNeStu/ggrc-core,VinnieJohns/ggrc-core,plamut/ggrc-core,VinnieJohns/ggrc-core,AleksNeStu/ggrc-core,plamut/ggrc-core,VinnieJohns/ggrc-core,AleksNeStu/ggrc-core | +
from lib.page.modal import (
create_new_object, # flake8: noqa
edit_object, # flake8: noqa
- delete_object # flake8: noqa
+ delete_object, # flake8: noqa
+ update_object # flake8: noqa
)
| Add a sort of hierarchy of modules for package | ## Code Before:
from lib.page.modal import (
create_new_object, # flake8: noqa
edit_object, # flake8: noqa
delete_object # flake8: noqa
)
## Instruction:
Add a sort of hierarchy of modules for package
## Code After:
from lib.page.modal import (
create_new_object, # flake8: noqa
edit_object, # flake8: noqa
delete_object, # flake8: noqa
update_object # flake8: noqa
)
| +
from lib.page.modal import (
create_new_object, # flake8: noqa
edit_object, # flake8: noqa
- delete_object # flake8: noqa
+ delete_object, # flake8: noqa
? ++
+ update_object # flake8: noqa
) |
f64cb48d51e1bcc3879a40d308452c4e65d13439 | src/pymfony/component/system/serializer.py | src/pymfony/component/system/serializer.py |
from __future__ import absolute_import;
from pickle import dumps;
from pickle import loads;
try:
from base64 import encodebytes;
from base64 import decodebytes;
except Exception:
from base64 import encodestring as encodebytes;
from base64 import decodestring as decodebytes;
"""
"""
CHARSET = 'UTF-8';
def serialize(obj):
return encodebytes(dumps(obj)).decode(CHARSET).replace('\n', '');
def unserialize(s):
return loads(decodebytes(s.encode(CHARSET)));
|
from __future__ import absolute_import;
from pickle import dumps;
from pickle import loads;
try:
from base64 import encodebytes;
from base64 import decodebytes;
except Exception:
from base64 import encodestring as encodebytes;
from base64 import decodestring as decodebytes;
"""
"""
CHARSET = 'UTF-8';
PICKLE_PROTOCOL = 2;
def serialize(obj):
return encodebytes(dumps(obj, PICKLE_PROTOCOL)).decode(CHARSET).replace('\n', '');
def unserialize(s):
return loads(decodebytes(s.encode(CHARSET)));
| Use pickle protocole 2 to BC for Python2* | [System][Serializer] Use pickle protocole 2 to BC for Python2*
| Python | mit | pymfony/pymfony |
from __future__ import absolute_import;
from pickle import dumps;
from pickle import loads;
try:
from base64 import encodebytes;
from base64 import decodebytes;
except Exception:
from base64 import encodestring as encodebytes;
from base64 import decodestring as decodebytes;
"""
"""
CHARSET = 'UTF-8';
+ PICKLE_PROTOCOL = 2;
def serialize(obj):
- return encodebytes(dumps(obj)).decode(CHARSET).replace('\n', '');
+ return encodebytes(dumps(obj, PICKLE_PROTOCOL)).decode(CHARSET).replace('\n', '');
def unserialize(s):
return loads(decodebytes(s.encode(CHARSET)));
| Use pickle protocole 2 to BC for Python2* | ## Code Before:
from __future__ import absolute_import;
from pickle import dumps;
from pickle import loads;
try:
from base64 import encodebytes;
from base64 import decodebytes;
except Exception:
from base64 import encodestring as encodebytes;
from base64 import decodestring as decodebytes;
"""
"""
CHARSET = 'UTF-8';
def serialize(obj):
return encodebytes(dumps(obj)).decode(CHARSET).replace('\n', '');
def unserialize(s):
return loads(decodebytes(s.encode(CHARSET)));
## Instruction:
Use pickle protocole 2 to BC for Python2*
## Code After:
from __future__ import absolute_import;
from pickle import dumps;
from pickle import loads;
try:
from base64 import encodebytes;
from base64 import decodebytes;
except Exception:
from base64 import encodestring as encodebytes;
from base64 import decodestring as decodebytes;
"""
"""
CHARSET = 'UTF-8';
PICKLE_PROTOCOL = 2;
def serialize(obj):
return encodebytes(dumps(obj, PICKLE_PROTOCOL)).decode(CHARSET).replace('\n', '');
def unserialize(s):
return loads(decodebytes(s.encode(CHARSET)));
|
from __future__ import absolute_import;
from pickle import dumps;
from pickle import loads;
try:
from base64 import encodebytes;
from base64 import decodebytes;
except Exception:
from base64 import encodestring as encodebytes;
from base64 import decodestring as decodebytes;
"""
"""
CHARSET = 'UTF-8';
+ PICKLE_PROTOCOL = 2;
def serialize(obj):
- return encodebytes(dumps(obj)).decode(CHARSET).replace('\n', '');
+ return encodebytes(dumps(obj, PICKLE_PROTOCOL)).decode(CHARSET).replace('\n', '');
? +++++++++++++++++
def unserialize(s):
return loads(decodebytes(s.encode(CHARSET))); |
e46e512fad9bc92c1725711e2800e44bb699d281 | deploy/mirrors/greasyfork.py | deploy/mirrors/greasyfork.py | from mechanize import Browser
def exec_(config, summary, script):
USERNAME = config['USERNAME']
PASSWORD = config['PASSWORD']
SCRIPT_ID = config['SCRIPT_ID']
LOGIN_URL = 'https://greasyfork.org/users/sign_in'
EDIT_URL = 'https://greasyfork.org/scripts/{0}/versions/new'.format(SCRIPT_ID)
b = Browser()
# login
b.open(LOGIN_URL)
b.select_form(nr=1)
b['user[email]'] = USERNAME
b['user[password]'] = PASSWORD
b.submit()
# edit source
b.open(EDIT_URL)
b.select_form(nr=1)
b['script_version[additional_info]'] = summary.encode('utf-8')
b.submit(name='commit')
# ex: ts=4 sts=4 sw=4 et
# sublime: tab_size 4; translate_tabs_to_spaces true; detect_indentation false; use_tab_stops true;
# kate: space-indent on; indent-width 4;
| from mechanize import Browser
def exec_(config, summary, script):
USERNAME = config['USERNAME']
PASSWORD = config['PASSWORD']
SCRIPT_ID = config['SCRIPT_ID']
LOGIN_URL = 'https://greasyfork.org/users/sign_in'
EDIT_URL = 'https://greasyfork.org/scripts/{0}/versions/new'.format(SCRIPT_ID)
b = Browser()
# login
b.open(LOGIN_URL)
b.select_form(nr=2)
b['user[email]'] = USERNAME
b['user[password]'] = PASSWORD
b.submit()
# edit source
b.open(EDIT_URL)
b.select_form(nr=2)
b['script_version[additional_info]'] = summary.encode('utf-8')
b['script_version[code]'] = script.encode('utf-8')
b.submit(name='commit')
# ex: ts=4 sts=4 sw=4 et
# sublime: tab_size 4; translate_tabs_to_spaces true; detect_indentation false; use_tab_stops true;
# kate: space-indent on; indent-width 4;
| Fix Greasy Fork deploy script. | Fix Greasy Fork deploy script.
| Python | bsd-2-clause | MNBuyskih/adsbypasser,tablesmit/adsbypasser,xor10/adsbypasser,kehugter/adsbypasser,tosunkaya/adsbypasser,xor10/adsbypasser,MNBuyskih/adsbypasser,tablesmit/adsbypasser,kehugter/adsbypasser,kehugter/adsbypasser,tablesmit/adsbypasser,xor10/adsbypasser,tosunkaya/adsbypasser,MNBuyskih/adsbypasser,tosunkaya/adsbypasser | from mechanize import Browser
def exec_(config, summary, script):
USERNAME = config['USERNAME']
PASSWORD = config['PASSWORD']
SCRIPT_ID = config['SCRIPT_ID']
LOGIN_URL = 'https://greasyfork.org/users/sign_in'
EDIT_URL = 'https://greasyfork.org/scripts/{0}/versions/new'.format(SCRIPT_ID)
b = Browser()
# login
b.open(LOGIN_URL)
- b.select_form(nr=1)
+ b.select_form(nr=2)
b['user[email]'] = USERNAME
b['user[password]'] = PASSWORD
b.submit()
# edit source
b.open(EDIT_URL)
- b.select_form(nr=1)
+ b.select_form(nr=2)
b['script_version[additional_info]'] = summary.encode('utf-8')
+ b['script_version[code]'] = script.encode('utf-8')
b.submit(name='commit')
# ex: ts=4 sts=4 sw=4 et
# sublime: tab_size 4; translate_tabs_to_spaces true; detect_indentation false; use_tab_stops true;
# kate: space-indent on; indent-width 4;
| Fix Greasy Fork deploy script. | ## Code Before:
from mechanize import Browser
def exec_(config, summary, script):
USERNAME = config['USERNAME']
PASSWORD = config['PASSWORD']
SCRIPT_ID = config['SCRIPT_ID']
LOGIN_URL = 'https://greasyfork.org/users/sign_in'
EDIT_URL = 'https://greasyfork.org/scripts/{0}/versions/new'.format(SCRIPT_ID)
b = Browser()
# login
b.open(LOGIN_URL)
b.select_form(nr=1)
b['user[email]'] = USERNAME
b['user[password]'] = PASSWORD
b.submit()
# edit source
b.open(EDIT_URL)
b.select_form(nr=1)
b['script_version[additional_info]'] = summary.encode('utf-8')
b.submit(name='commit')
# ex: ts=4 sts=4 sw=4 et
# sublime: tab_size 4; translate_tabs_to_spaces true; detect_indentation false; use_tab_stops true;
# kate: space-indent on; indent-width 4;
## Instruction:
Fix Greasy Fork deploy script.
## Code After:
from mechanize import Browser
def exec_(config, summary, script):
USERNAME = config['USERNAME']
PASSWORD = config['PASSWORD']
SCRIPT_ID = config['SCRIPT_ID']
LOGIN_URL = 'https://greasyfork.org/users/sign_in'
EDIT_URL = 'https://greasyfork.org/scripts/{0}/versions/new'.format(SCRIPT_ID)
b = Browser()
# login
b.open(LOGIN_URL)
b.select_form(nr=2)
b['user[email]'] = USERNAME
b['user[password]'] = PASSWORD
b.submit()
# edit source
b.open(EDIT_URL)
b.select_form(nr=2)
b['script_version[additional_info]'] = summary.encode('utf-8')
b['script_version[code]'] = script.encode('utf-8')
b.submit(name='commit')
# ex: ts=4 sts=4 sw=4 et
# sublime: tab_size 4; translate_tabs_to_spaces true; detect_indentation false; use_tab_stops true;
# kate: space-indent on; indent-width 4;
| from mechanize import Browser
def exec_(config, summary, script):
USERNAME = config['USERNAME']
PASSWORD = config['PASSWORD']
SCRIPT_ID = config['SCRIPT_ID']
LOGIN_URL = 'https://greasyfork.org/users/sign_in'
EDIT_URL = 'https://greasyfork.org/scripts/{0}/versions/new'.format(SCRIPT_ID)
b = Browser()
# login
b.open(LOGIN_URL)
- b.select_form(nr=1)
? ^
+ b.select_form(nr=2)
? ^
b['user[email]'] = USERNAME
b['user[password]'] = PASSWORD
b.submit()
# edit source
b.open(EDIT_URL)
- b.select_form(nr=1)
? ^
+ b.select_form(nr=2)
? ^
b['script_version[additional_info]'] = summary.encode('utf-8')
+ b['script_version[code]'] = script.encode('utf-8')
b.submit(name='commit')
# ex: ts=4 sts=4 sw=4 et
# sublime: tab_size 4; translate_tabs_to_spaces true; detect_indentation false; use_tab_stops true;
# kate: space-indent on; indent-width 4; |
089bce7ec9df43cc526342ba84e37fe87203ca11 | gemini/gemini_amend.py | gemini/gemini_amend.py | import GeminiQuery
from gemini_subjects import get_subjects
from ped import load_ped_file, get_ped_fields
from gemini_utils import quote_string
import sqlite3
from database import database_transaction
def amend(parser, args):
if args.db is None:
parser.print_help()
exit("ERROR: amend needs a database file.")
if args.sample:
amend_sample(args)
def amend_sample(args):
loaded_subjects = get_subjects(args)
ped_dict = load_ped_file(args.sample)
header = get_ped_fields(args.sample)
with database_transaction(args.db) as c:
for k, v in loaded_subjects.items():
if k in ped_dict:
item_list = map(quote_string, ped_dict[k])
sample = zip(header, item_list)
set_str = ",".join([str(x) + "=" + str(y) for (x, y) in sample])
sql_query = "update samples set {0} where sample_id={1}"
c.execute(sql_query.format(set_str, v.sample_id))
| import GeminiQuery
from gemini_subjects import get_subjects
from ped import load_ped_file, get_ped_fields
from gemini_utils import quote_string
import sqlite3
from database import database_transaction
def amend(parser, args):
if args.db is None:
parser.print_help()
exit("ERROR: amend needs a database file.")
if args.sample:
amend_sample(args)
def amend_sample(args):
loaded_subjects = get_subjects(args)
ped_dict = load_ped_file(args.sample)
header = get_ped_fields(args.sample)
with database_transaction(args.db) as c:
add_columns(header, c)
for k, v in loaded_subjects.items():
if k in ped_dict:
item_list = map(quote_string, ped_dict[k])
sample = zip(header, item_list)
set_str = ",".join([str(x) + "=" + str(y) for (x, y) in sample])
sql_query = "update samples set {0} where sample_id={1}"
c.execute(sql_query.format(set_str, v.sample_id))
def add_columns(header, c):
"""
add any missing columns to the samples table
"""
for column in header:
try:
c.execute('ALTER TABLE samples ADD COLUMN {0}'.format(column))
except:
pass
| Extend samples table with new columns when amending. | Extend samples table with new columns when amending.
This allows you to add phenotype fields to your samples after
you have already created the database.
| Python | mit | xuzetan/gemini,brentp/gemini,heuermh/gemini,xuzetan/gemini,udp3f/gemini,bpow/gemini,heuermh/gemini,arq5x/gemini,brentp/gemini,arq5x/gemini,heuermh/gemini,bw2/gemini,bgruening/gemini,brentp/gemini,arq5x/gemini,heuermh/gemini,bw2/gemini,udp3f/gemini,brentp/gemini,bw2/gemini,bgruening/gemini,xuzetan/gemini,udp3f/gemini,arq5x/gemini,bw2/gemini,bpow/gemini,udp3f/gemini,bgruening/gemini,bgruening/gemini,bpow/gemini,bpow/gemini,xuzetan/gemini | import GeminiQuery
from gemini_subjects import get_subjects
from ped import load_ped_file, get_ped_fields
from gemini_utils import quote_string
import sqlite3
from database import database_transaction
def amend(parser, args):
if args.db is None:
parser.print_help()
exit("ERROR: amend needs a database file.")
if args.sample:
amend_sample(args)
def amend_sample(args):
loaded_subjects = get_subjects(args)
ped_dict = load_ped_file(args.sample)
header = get_ped_fields(args.sample)
with database_transaction(args.db) as c:
+ add_columns(header, c)
for k, v in loaded_subjects.items():
if k in ped_dict:
item_list = map(quote_string, ped_dict[k])
sample = zip(header, item_list)
set_str = ",".join([str(x) + "=" + str(y) for (x, y) in sample])
sql_query = "update samples set {0} where sample_id={1}"
c.execute(sql_query.format(set_str, v.sample_id))
+ def add_columns(header, c):
+ """
+ add any missing columns to the samples table
+ """
+ for column in header:
+ try:
+ c.execute('ALTER TABLE samples ADD COLUMN {0}'.format(column))
+ except:
+ pass
| Extend samples table with new columns when amending. | ## Code Before:
import GeminiQuery
from gemini_subjects import get_subjects
from ped import load_ped_file, get_ped_fields
from gemini_utils import quote_string
import sqlite3
from database import database_transaction
def amend(parser, args):
if args.db is None:
parser.print_help()
exit("ERROR: amend needs a database file.")
if args.sample:
amend_sample(args)
def amend_sample(args):
loaded_subjects = get_subjects(args)
ped_dict = load_ped_file(args.sample)
header = get_ped_fields(args.sample)
with database_transaction(args.db) as c:
for k, v in loaded_subjects.items():
if k in ped_dict:
item_list = map(quote_string, ped_dict[k])
sample = zip(header, item_list)
set_str = ",".join([str(x) + "=" + str(y) for (x, y) in sample])
sql_query = "update samples set {0} where sample_id={1}"
c.execute(sql_query.format(set_str, v.sample_id))
## Instruction:
Extend samples table with new columns when amending.
## Code After:
import GeminiQuery
from gemini_subjects import get_subjects
from ped import load_ped_file, get_ped_fields
from gemini_utils import quote_string
import sqlite3
from database import database_transaction
def amend(parser, args):
if args.db is None:
parser.print_help()
exit("ERROR: amend needs a database file.")
if args.sample:
amend_sample(args)
def amend_sample(args):
loaded_subjects = get_subjects(args)
ped_dict = load_ped_file(args.sample)
header = get_ped_fields(args.sample)
with database_transaction(args.db) as c:
add_columns(header, c)
for k, v in loaded_subjects.items():
if k in ped_dict:
item_list = map(quote_string, ped_dict[k])
sample = zip(header, item_list)
set_str = ",".join([str(x) + "=" + str(y) for (x, y) in sample])
sql_query = "update samples set {0} where sample_id={1}"
c.execute(sql_query.format(set_str, v.sample_id))
def add_columns(header, c):
"""
add any missing columns to the samples table
"""
for column in header:
try:
c.execute('ALTER TABLE samples ADD COLUMN {0}'.format(column))
except:
pass
| import GeminiQuery
from gemini_subjects import get_subjects
from ped import load_ped_file, get_ped_fields
from gemini_utils import quote_string
import sqlite3
from database import database_transaction
def amend(parser, args):
if args.db is None:
parser.print_help()
exit("ERROR: amend needs a database file.")
if args.sample:
amend_sample(args)
def amend_sample(args):
loaded_subjects = get_subjects(args)
ped_dict = load_ped_file(args.sample)
header = get_ped_fields(args.sample)
with database_transaction(args.db) as c:
+ add_columns(header, c)
for k, v in loaded_subjects.items():
if k in ped_dict:
item_list = map(quote_string, ped_dict[k])
sample = zip(header, item_list)
set_str = ",".join([str(x) + "=" + str(y) for (x, y) in sample])
sql_query = "update samples set {0} where sample_id={1}"
c.execute(sql_query.format(set_str, v.sample_id))
+ def add_columns(header, c):
+ """
+ add any missing columns to the samples table
+ """
+ for column in header:
+ try:
+ c.execute('ALTER TABLE samples ADD COLUMN {0}'.format(column))
+ except:
+ pass |
de0bbf978695d206189ee4effb124234968525cb | django_afip/views.py | django_afip/views.py | from django.http import HttpResponse
from django.utils.translation import ugettext as _
from django.views.generic import View
from .pdf import generate_receipt_pdf
class ReceiptHTMLView(View):
def get(self, request, pk):
return HttpResponse(
generate_receipt_pdf(pk, request, True),
)
class ReceiptPDFView(View):
def get(self, request, pk):
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename=' + \
_('receipt %s.pdf' % pk)
generate_receipt_pdf(pk, response)
return response
| from django.http import HttpResponse
from django.utils.translation import ugettext as _
from django.views.generic import View
from .pdf import generate_receipt_pdf
class ReceiptHTMLView(View):
"""Renders a receipt as HTML."""
def get(self, request, pk):
return HttpResponse(
generate_receipt_pdf(pk, request, True),
)
class ReceiptPDFView(View):
"""Renders a receipt as a PDF, prompting to download it."""
def get(self, request, pk):
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename=' + \
_('receipt %s.pdf' % pk)
generate_receipt_pdf(pk, response)
return response
class ReceiptPDFDisplayView(View):
"""
Renders a receipt as a PDF.
Browsers should render the file, rather than prompt to download it.
"""
def get(self, request, pk):
response = HttpResponse(content_type='application/pdf')
generate_receipt_pdf(pk, response)
return response
| Add a view to display PDF receipts | Add a view to display PDF receipts
Fixes #23
Closes !7
Closes !8
| Python | isc | hobarrera/django-afip,hobarrera/django-afip | from django.http import HttpResponse
from django.utils.translation import ugettext as _
from django.views.generic import View
from .pdf import generate_receipt_pdf
class ReceiptHTMLView(View):
-
+ """Renders a receipt as HTML."""
def get(self, request, pk):
return HttpResponse(
generate_receipt_pdf(pk, request, True),
)
class ReceiptPDFView(View):
+ """Renders a receipt as a PDF, prompting to download it."""
def get(self, request, pk):
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename=' + \
_('receipt %s.pdf' % pk)
generate_receipt_pdf(pk, response)
return response
+
+ class ReceiptPDFDisplayView(View):
+ """
+ Renders a receipt as a PDF.
+
+ Browsers should render the file, rather than prompt to download it.
+ """
+ def get(self, request, pk):
+ response = HttpResponse(content_type='application/pdf')
+ generate_receipt_pdf(pk, response)
+ return response
+ | Add a view to display PDF receipts | ## Code Before:
from django.http import HttpResponse
from django.utils.translation import ugettext as _
from django.views.generic import View
from .pdf import generate_receipt_pdf
class ReceiptHTMLView(View):
def get(self, request, pk):
return HttpResponse(
generate_receipt_pdf(pk, request, True),
)
class ReceiptPDFView(View):
def get(self, request, pk):
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename=' + \
_('receipt %s.pdf' % pk)
generate_receipt_pdf(pk, response)
return response
## Instruction:
Add a view to display PDF receipts
## Code After:
from django.http import HttpResponse
from django.utils.translation import ugettext as _
from django.views.generic import View
from .pdf import generate_receipt_pdf
class ReceiptHTMLView(View):
"""Renders a receipt as HTML."""
def get(self, request, pk):
return HttpResponse(
generate_receipt_pdf(pk, request, True),
)
class ReceiptPDFView(View):
"""Renders a receipt as a PDF, prompting to download it."""
def get(self, request, pk):
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename=' + \
_('receipt %s.pdf' % pk)
generate_receipt_pdf(pk, response)
return response
class ReceiptPDFDisplayView(View):
"""
Renders a receipt as a PDF.
Browsers should render the file, rather than prompt to download it.
"""
def get(self, request, pk):
response = HttpResponse(content_type='application/pdf')
generate_receipt_pdf(pk, response)
return response
| from django.http import HttpResponse
from django.utils.translation import ugettext as _
from django.views.generic import View
from .pdf import generate_receipt_pdf
class ReceiptHTMLView(View):
-
+ """Renders a receipt as HTML."""
def get(self, request, pk):
return HttpResponse(
generate_receipt_pdf(pk, request, True),
)
class ReceiptPDFView(View):
+ """Renders a receipt as a PDF, prompting to download it."""
def get(self, request, pk):
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename=' + \
_('receipt %s.pdf' % pk)
generate_receipt_pdf(pk, response)
return response
+
+
+ class ReceiptPDFDisplayView(View):
+ """
+ Renders a receipt as a PDF.
+
+ Browsers should render the file, rather than prompt to download it.
+ """
+ def get(self, request, pk):
+ response = HttpResponse(content_type='application/pdf')
+ generate_receipt_pdf(pk, response)
+ return response |
0a4aceb87eae57188c5f61bb93d78d5cc9f1779f | lava_scheduler_app/templatetags/utils.py | lava_scheduler_app/templatetags/utils.py | from django import template
from django.utils.safestring import mark_safe
from lava_scheduler_app.models import TestJob
register = template.Library()
@register.filter
def get_priority_select(current):
select = ""
val = TestJob.PRIORITY_CHOICES
for priority, label in val:
check = " checked" if priority == current else ""
default = " [default]" if current != 50 and priority == 50 else ""
select += '<input type="radio" name="priority" style="..." id="%s" value="%d"%s>%s%s</input><br/>' %\
(label.lower(), priority, check, label, default)
return mark_safe(select)
| from django import template
from django.utils.safestring import mark_safe
from lava_scheduler_app.models import TestJob
register = template.Library()
@register.filter
def get_priority_select(current):
select = ""
val = TestJob.PRIORITY_CHOICES
for priority, label in val:
check = " checked" if priority == current else ""
default = " [default]" if current != 50 and priority == 50 else ""
select += '<label class="checkbox-inline">'
select += '<input type="radio" name="priority" style="..." id="%s" value="%d"%s>%s%s</input><br/>' %\
(label.lower(), priority, check, label, default)
select += '</label>'
return mark_safe(select)
| Use inline radio buttons for priority changes. | Use inline radio buttons for priority changes.
Change-Id: Ifb9a685bca654c5139aef3ca78e800b66ce77eb9
| Python | agpl-3.0 | Linaro/lava-server,Linaro/lava-server,Linaro/lava-server,Linaro/lava-server | from django import template
from django.utils.safestring import mark_safe
from lava_scheduler_app.models import TestJob
register = template.Library()
@register.filter
def get_priority_select(current):
select = ""
val = TestJob.PRIORITY_CHOICES
for priority, label in val:
check = " checked" if priority == current else ""
default = " [default]" if current != 50 and priority == 50 else ""
+ select += '<label class="checkbox-inline">'
select += '<input type="radio" name="priority" style="..." id="%s" value="%d"%s>%s%s</input><br/>' %\
(label.lower(), priority, check, label, default)
+ select += '</label>'
return mark_safe(select)
| Use inline radio buttons for priority changes. | ## Code Before:
from django import template
from django.utils.safestring import mark_safe
from lava_scheduler_app.models import TestJob
register = template.Library()
@register.filter
def get_priority_select(current):
select = ""
val = TestJob.PRIORITY_CHOICES
for priority, label in val:
check = " checked" if priority == current else ""
default = " [default]" if current != 50 and priority == 50 else ""
select += '<input type="radio" name="priority" style="..." id="%s" value="%d"%s>%s%s</input><br/>' %\
(label.lower(), priority, check, label, default)
return mark_safe(select)
## Instruction:
Use inline radio buttons for priority changes.
## Code After:
from django import template
from django.utils.safestring import mark_safe
from lava_scheduler_app.models import TestJob
register = template.Library()
@register.filter
def get_priority_select(current):
select = ""
val = TestJob.PRIORITY_CHOICES
for priority, label in val:
check = " checked" if priority == current else ""
default = " [default]" if current != 50 and priority == 50 else ""
select += '<label class="checkbox-inline">'
select += '<input type="radio" name="priority" style="..." id="%s" value="%d"%s>%s%s</input><br/>' %\
(label.lower(), priority, check, label, default)
select += '</label>'
return mark_safe(select)
| from django import template
from django.utils.safestring import mark_safe
from lava_scheduler_app.models import TestJob
register = template.Library()
@register.filter
def get_priority_select(current):
select = ""
val = TestJob.PRIORITY_CHOICES
for priority, label in val:
check = " checked" if priority == current else ""
default = " [default]" if current != 50 and priority == 50 else ""
+ select += '<label class="checkbox-inline">'
select += '<input type="radio" name="priority" style="..." id="%s" value="%d"%s>%s%s</input><br/>' %\
(label.lower(), priority, check, label, default)
+ select += '</label>'
return mark_safe(select) |
454329c3cb6434dcdd2b4d89f127a87da8ee23ef | example/example_spin.py | example/example_spin.py |
from __future__ import absolute_import, print_function
import sys
import time
from pyspin import spin
def show(name, frames):
s = spin.Spinner(frames)
print(name)
for i in range(50):
time.sleep(0.1)
print("\r{0}".format(s.next()), end="")
sys.stdout.flush()
print('\n')
def main():
show("Default", spin.Default)
show("Box1", spin.Box1)
show("Box2", spin.Box2)
show("Box3", spin.Box3)
show("Box4", spin.Box4)
show("Box5", spin.Box5)
show("Box6", spin.Box6)
show("Box7", spin.Box7)
show("Spin1", spin.Spin1)
show("Spin2", spin.Spin2)
show("Spin3", spin.Spin3)
show("Spin4", spin.Spin4)
show("Spin5", spin.Spin5)
show("Spin6", spin.Spin6)
show("Spin7", spin.Spin7)
show("Spin8", spin.Spin8)
show("Spin9", spin.Spin9)
if __name__ == '__main__':
main()
|
from __future__ import absolute_import, print_function
import sys
import time
from pyspin import spin
def show(name, frames):
s = spin.Spinner(frames)
print(name)
for i in range(50):
print(u"\r{0}".format(s.next()), end="")
sys.stdout.flush()
time.sleep(0.1)
print('\n')
def main():
show("Default", spin.Default)
show("Box1", spin.Box1)
show("Box2", spin.Box2)
show("Box3", spin.Box3)
show("Box4", spin.Box4)
show("Box5", spin.Box5)
show("Box6", spin.Box6)
show("Box7", spin.Box7)
show("Spin1", spin.Spin1)
show("Spin2", spin.Spin2)
show("Spin3", spin.Spin3)
show("Spin4", spin.Spin4)
show("Spin5", spin.Spin5)
show("Spin6", spin.Spin6)
show("Spin7", spin.Spin7)
show("Spin8", spin.Spin8)
show("Spin9", spin.Spin9)
if __name__ == '__main__':
main()
| Fix unicode issue in example code for python2.x | Fix unicode issue in example code for python2.x
| Python | mit | lord63/py-spin |
from __future__ import absolute_import, print_function
import sys
import time
from pyspin import spin
def show(name, frames):
s = spin.Spinner(frames)
print(name)
for i in range(50):
+ print(u"\r{0}".format(s.next()), end="")
+ sys.stdout.flush()
time.sleep(0.1)
- print("\r{0}".format(s.next()), end="")
- sys.stdout.flush()
print('\n')
def main():
show("Default", spin.Default)
show("Box1", spin.Box1)
show("Box2", spin.Box2)
show("Box3", spin.Box3)
show("Box4", spin.Box4)
show("Box5", spin.Box5)
show("Box6", spin.Box6)
show("Box7", spin.Box7)
show("Spin1", spin.Spin1)
show("Spin2", spin.Spin2)
show("Spin3", spin.Spin3)
show("Spin4", spin.Spin4)
show("Spin5", spin.Spin5)
show("Spin6", spin.Spin6)
show("Spin7", spin.Spin7)
show("Spin8", spin.Spin8)
show("Spin9", spin.Spin9)
if __name__ == '__main__':
main()
| Fix unicode issue in example code for python2.x | ## Code Before:
from __future__ import absolute_import, print_function
import sys
import time
from pyspin import spin
def show(name, frames):
s = spin.Spinner(frames)
print(name)
for i in range(50):
time.sleep(0.1)
print("\r{0}".format(s.next()), end="")
sys.stdout.flush()
print('\n')
def main():
show("Default", spin.Default)
show("Box1", spin.Box1)
show("Box2", spin.Box2)
show("Box3", spin.Box3)
show("Box4", spin.Box4)
show("Box5", spin.Box5)
show("Box6", spin.Box6)
show("Box7", spin.Box7)
show("Spin1", spin.Spin1)
show("Spin2", spin.Spin2)
show("Spin3", spin.Spin3)
show("Spin4", spin.Spin4)
show("Spin5", spin.Spin5)
show("Spin6", spin.Spin6)
show("Spin7", spin.Spin7)
show("Spin8", spin.Spin8)
show("Spin9", spin.Spin9)
if __name__ == '__main__':
main()
## Instruction:
Fix unicode issue in example code for python2.x
## Code After:
from __future__ import absolute_import, print_function
import sys
import time
from pyspin import spin
def show(name, frames):
s = spin.Spinner(frames)
print(name)
for i in range(50):
print(u"\r{0}".format(s.next()), end="")
sys.stdout.flush()
time.sleep(0.1)
print('\n')
def main():
show("Default", spin.Default)
show("Box1", spin.Box1)
show("Box2", spin.Box2)
show("Box3", spin.Box3)
show("Box4", spin.Box4)
show("Box5", spin.Box5)
show("Box6", spin.Box6)
show("Box7", spin.Box7)
show("Spin1", spin.Spin1)
show("Spin2", spin.Spin2)
show("Spin3", spin.Spin3)
show("Spin4", spin.Spin4)
show("Spin5", spin.Spin5)
show("Spin6", spin.Spin6)
show("Spin7", spin.Spin7)
show("Spin8", spin.Spin8)
show("Spin9", spin.Spin9)
if __name__ == '__main__':
main()
|
from __future__ import absolute_import, print_function
import sys
import time
from pyspin import spin
def show(name, frames):
s = spin.Spinner(frames)
print(name)
for i in range(50):
+ print(u"\r{0}".format(s.next()), end="")
+ sys.stdout.flush()
time.sleep(0.1)
- print("\r{0}".format(s.next()), end="")
- sys.stdout.flush()
print('\n')
def main():
show("Default", spin.Default)
show("Box1", spin.Box1)
show("Box2", spin.Box2)
show("Box3", spin.Box3)
show("Box4", spin.Box4)
show("Box5", spin.Box5)
show("Box6", spin.Box6)
show("Box7", spin.Box7)
show("Spin1", spin.Spin1)
show("Spin2", spin.Spin2)
show("Spin3", spin.Spin3)
show("Spin4", spin.Spin4)
show("Spin5", spin.Spin5)
show("Spin6", spin.Spin6)
show("Spin7", spin.Spin7)
show("Spin8", spin.Spin8)
show("Spin9", spin.Spin9)
if __name__ == '__main__':
main() |
78463a6ba34f1503f3c6fd5fdb287a0593f4be68 | website/addons/figshare/__init__.py | website/addons/figshare/__init__.py | import os
from . import routes, views, model # noqa
MODELS = [
model.AddonFigShareUserSettings,
model.AddonFigShareNodeSettings,
model.FigShareGuidFile
]
USER_SETTINGS_MODEL = model.AddonFigShareUserSettings
NODE_SETTINGS_MODEL = model.AddonFigShareNodeSettings
ROUTES = [routes.settings_routes, routes.api_routes]
SHORT_NAME = 'figshare'
FULL_NAME = 'figshare'
OWNERS = ['user', 'node']
ADDED_DEFAULT = []
ADDED_MANDATORY = []
VIEWS = []
CONFIGS = ['user', 'node']
CATEGORIES = ['storage']
INCLUDE_JS = {}
INCLUDE_CSS = {}
HAS_HGRID_FILES = True
GET_HGRID_DATA = views.hgrid.figshare_hgrid_data
HERE = os.path.dirname(os.path.abspath(__file__))
NODE_SETTINGS_TEMPLATE = None # use default nodes settings templates
USER_SETTINGS_TEMPLATE = os.path.join(HERE, 'templates', 'figshare_user_settings.mako')
| import os
from . import routes, views, model # noqa
MODELS = [
model.AddonFigShareUserSettings,
model.AddonFigShareNodeSettings,
model.FigShareGuidFile
]
USER_SETTINGS_MODEL = model.AddonFigShareUserSettings
NODE_SETTINGS_MODEL = model.AddonFigShareNodeSettings
ROUTES = [routes.settings_routes, routes.api_routes]
SHORT_NAME = 'figshare'
FULL_NAME = 'figshare'
OWNERS = ['user', 'node']
ADDED_DEFAULT = []
ADDED_MANDATORY = []
VIEWS = []
CONFIGS = ['user', 'node']
CATEGORIES = ['storage']
INCLUDE_JS = {}
INCLUDE_CSS = {}
HAS_HGRID_FILES = True
GET_HGRID_DATA = views.hgrid.figshare_hgrid_data
MAX_FILE_SIZE = 50
HERE = os.path.dirname(os.path.abspath(__file__))
NODE_SETTINGS_TEMPLATE = None # use default nodes settings templates
USER_SETTINGS_TEMPLATE = os.path.join(HERE, 'templates', 'figshare_user_settings.mako')
| Set figshare's MAX_FILE_SIZE to 50mb | Set figshare's MAX_FILE_SIZE to 50mb
| Python | apache-2.0 | chennan47/osf.io,baylee-d/osf.io,HarryRybacki/osf.io,mluo613/osf.io,jolene-esposito/osf.io,binoculars/osf.io,petermalcolm/osf.io,caneruguz/osf.io,haoyuchen1992/osf.io,zamattiac/osf.io,arpitar/osf.io,amyshi188/osf.io,jnayak1/osf.io,mluke93/osf.io,RomanZWang/osf.io,cldershem/osf.io,abought/osf.io,doublebits/osf.io,HalcyonChimera/osf.io,hmoco/osf.io,Ghalko/osf.io,wearpants/osf.io,MerlinZhang/osf.io,acshi/osf.io,jolene-esposito/osf.io,wearpants/osf.io,chrisseto/osf.io,danielneis/osf.io,cosenal/osf.io,baylee-d/osf.io,sloria/osf.io,GageGaskins/osf.io,Johnetordoff/osf.io,felliott/osf.io,sbt9uc/osf.io,mluo613/osf.io,njantrania/osf.io,cwisecarver/osf.io,ticklemepierce/osf.io,aaxelb/osf.io,arpitar/osf.io,samchrisinger/osf.io,KAsante95/osf.io,amyshi188/osf.io,wearpants/osf.io,TomBaxter/osf.io,danielneis/osf.io,amyshi188/osf.io,dplorimer/osf,kch8qx/osf.io,njantrania/osf.io,brandonPurvis/osf.io,GageGaskins/osf.io,mfraezz/osf.io,DanielSBrown/osf.io,lyndsysimon/osf.io,acshi/osf.io,jmcarp/osf.io,brianjgeiger/osf.io,ZobairAlijan/osf.io,cwisecarver/osf.io,zachjanicki/osf.io,TomHeatwole/osf.io,cosenal/osf.io,cldershem/osf.io,saradbowman/osf.io,laurenrevere/osf.io,bdyetton/prettychart,RomanZWang/osf.io,SSJohns/osf.io,HarryRybacki/osf.io,haoyuchen1992/osf.io,brianjgeiger/osf.io,Ghalko/osf.io,ticklemepierce/osf.io,ticklemepierce/osf.io,SSJohns/osf.io,alexschiller/osf.io,binoculars/osf.io,cwisecarver/osf.io,brianjgeiger/osf.io,caseyrygt/osf.io,hmoco/osf.io,acshi/osf.io,lyndsysimon/osf.io,aaxelb/osf.io,dplorimer/osf,jnayak1/osf.io,KAsante95/osf.io,baylee-d/osf.io,abought/osf.io,doublebits/osf.io,danielneis/osf.io,kch8qx/osf.io,samchrisinger/osf.io,mluo613/osf.io,reinaH/osf.io,zamattiac/osf.io,HalcyonChimera/osf.io,cldershem/osf.io,alexschiller/osf.io,billyhunt/osf.io,MerlinZhang/osf.io,ticklemepierce/osf.io,kwierman/osf.io,erinspace/osf.io,ckc6cz/osf.io,cslzchen/osf.io,jmcarp/osf.io,abought/osf.io,crcresearch/osf.io,doublebits/osf.io,TomHeatwole/osf.io,dplorimer/osf,reinaH/osf.io,Nesiehr/osf.io,mfraezz/osf.io,RomanZWang/osf.io,petermalcolm/osf.io,billyhunt/osf.io,crcresearch/osf.io,RomanZWang/osf.io,sloria/osf.io,asanfilippo7/osf.io,mluo613/osf.io,CenterForOpenScience/osf.io,icereval/osf.io,TomBaxter/osf.io,monikagrabowska/osf.io,monikagrabowska/osf.io,caneruguz/osf.io,samanehsan/osf.io,kwierman/osf.io,abought/osf.io,icereval/osf.io,chrisseto/osf.io,cslzchen/osf.io,danielneis/osf.io,petermalcolm/osf.io,GageGaskins/osf.io,aaxelb/osf.io,mluke93/osf.io,cwisecarver/osf.io,mfraezz/osf.io,GageGaskins/osf.io,emetsger/osf.io,asanfilippo7/osf.io,leb2dg/osf.io,alexschiller/osf.io,jnayak1/osf.io,HarryRybacki/osf.io,asanfilippo7/osf.io,zachjanicki/osf.io,jmcarp/osf.io,DanielSBrown/osf.io,arpitar/osf.io,billyhunt/osf.io,haoyuchen1992/osf.io,Nesiehr/osf.io,zachjanicki/osf.io,zamattiac/osf.io,Nesiehr/osf.io,pattisdr/osf.io,caseyrygt/osf.io,TomHeatwole/osf.io,lyndsysimon/osf.io,jolene-esposito/osf.io,kch8qx/osf.io,wearpants/osf.io,laurenrevere/osf.io,doublebits/osf.io,brandonPurvis/osf.io,KAsante95/osf.io,DanielSBrown/osf.io,petermalcolm/osf.io,samanehsan/osf.io,kwierman/osf.io,samanehsan/osf.io,TomHeatwole/osf.io,ZobairAlijan/osf.io,mfraezz/osf.io,SSJohns/osf.io,hmoco/osf.io,amyshi188/osf.io,KAsante95/osf.io,Ghalko/osf.io,caseyrollins/osf.io,DanielSBrown/osf.io,mattclark/osf.io,CenterForOpenScience/osf.io,RomanZWang/osf.io,KAsante95/osf.io,ckc6cz/osf.io,pattisdr/osf.io,leb2dg/osf.io,ckc6cz/osf.io,caseyrollins/osf.io,mattclark/osf.io,MerlinZhang/osf.io,chrisseto/osf.io,MerlinZhang/osf.io,caneruguz/osf.io,felliott/osf.io,zachjanicki/osf.io,acshi/osf.io,leb2dg/osf.io,arpitar/osf.io,bdyetton/prettychart,crcresearch/osf.io,cldershem/osf.io,laurenrevere/osf.io,rdhyee/osf.io,chrisseto/osf.io,Johnetordoff/osf.io,aaxelb/osf.io,emetsger/osf.io,dplorimer/osf,Johnetordoff/osf.io,bdyetton/prettychart,cosenal/osf.io,lyndsysimon/osf.io,emetsger/osf.io,alexschiller/osf.io,erinspace/osf.io,samanehsan/osf.io,mluke93/osf.io,ZobairAlijan/osf.io,adlius/osf.io,adlius/osf.io,HarryRybacki/osf.io,jolene-esposito/osf.io,monikagrabowska/osf.io,mattclark/osf.io,leb2dg/osf.io,alexschiller/osf.io,mluke93/osf.io,chennan47/osf.io,haoyuchen1992/osf.io,felliott/osf.io,HalcyonChimera/osf.io,erinspace/osf.io,caneruguz/osf.io,kch8qx/osf.io,zamattiac/osf.io,kwierman/osf.io,Ghalko/osf.io,sloria/osf.io,felliott/osf.io,SSJohns/osf.io,sbt9uc/osf.io,ckc6cz/osf.io,TomBaxter/osf.io,adlius/osf.io,brandonPurvis/osf.io,sbt9uc/osf.io,reinaH/osf.io,doublebits/osf.io,reinaH/osf.io,emetsger/osf.io,njantrania/osf.io,caseyrygt/osf.io,monikagrabowska/osf.io,billyhunt/osf.io,cslzchen/osf.io,caseyrollins/osf.io,jmcarp/osf.io,chennan47/osf.io,asanfilippo7/osf.io,binoculars/osf.io,billyhunt/osf.io,HalcyonChimera/osf.io,rdhyee/osf.io,jnayak1/osf.io,adlius/osf.io,GageGaskins/osf.io,saradbowman/osf.io,samchrisinger/osf.io,kch8qx/osf.io,cosenal/osf.io,icereval/osf.io,acshi/osf.io,ZobairAlijan/osf.io,CenterForOpenScience/osf.io,CenterForOpenScience/osf.io,brandonPurvis/osf.io,caseyrygt/osf.io,mluo613/osf.io,rdhyee/osf.io,samchrisinger/osf.io,bdyetton/prettychart,pattisdr/osf.io,brianjgeiger/osf.io,cslzchen/osf.io,rdhyee/osf.io,monikagrabowska/osf.io,hmoco/osf.io,Johnetordoff/osf.io,brandonPurvis/osf.io,njantrania/osf.io,sbt9uc/osf.io,Nesiehr/osf.io | import os
from . import routes, views, model # noqa
MODELS = [
model.AddonFigShareUserSettings,
model.AddonFigShareNodeSettings,
model.FigShareGuidFile
]
USER_SETTINGS_MODEL = model.AddonFigShareUserSettings
NODE_SETTINGS_MODEL = model.AddonFigShareNodeSettings
ROUTES = [routes.settings_routes, routes.api_routes]
SHORT_NAME = 'figshare'
FULL_NAME = 'figshare'
OWNERS = ['user', 'node']
ADDED_DEFAULT = []
ADDED_MANDATORY = []
VIEWS = []
CONFIGS = ['user', 'node']
CATEGORIES = ['storage']
INCLUDE_JS = {}
INCLUDE_CSS = {}
HAS_HGRID_FILES = True
GET_HGRID_DATA = views.hgrid.figshare_hgrid_data
+ MAX_FILE_SIZE = 50
+
HERE = os.path.dirname(os.path.abspath(__file__))
NODE_SETTINGS_TEMPLATE = None # use default nodes settings templates
USER_SETTINGS_TEMPLATE = os.path.join(HERE, 'templates', 'figshare_user_settings.mako')
| Set figshare's MAX_FILE_SIZE to 50mb | ## Code Before:
import os
from . import routes, views, model # noqa
MODELS = [
model.AddonFigShareUserSettings,
model.AddonFigShareNodeSettings,
model.FigShareGuidFile
]
USER_SETTINGS_MODEL = model.AddonFigShareUserSettings
NODE_SETTINGS_MODEL = model.AddonFigShareNodeSettings
ROUTES = [routes.settings_routes, routes.api_routes]
SHORT_NAME = 'figshare'
FULL_NAME = 'figshare'
OWNERS = ['user', 'node']
ADDED_DEFAULT = []
ADDED_MANDATORY = []
VIEWS = []
CONFIGS = ['user', 'node']
CATEGORIES = ['storage']
INCLUDE_JS = {}
INCLUDE_CSS = {}
HAS_HGRID_FILES = True
GET_HGRID_DATA = views.hgrid.figshare_hgrid_data
HERE = os.path.dirname(os.path.abspath(__file__))
NODE_SETTINGS_TEMPLATE = None # use default nodes settings templates
USER_SETTINGS_TEMPLATE = os.path.join(HERE, 'templates', 'figshare_user_settings.mako')
## Instruction:
Set figshare's MAX_FILE_SIZE to 50mb
## Code After:
import os
from . import routes, views, model # noqa
MODELS = [
model.AddonFigShareUserSettings,
model.AddonFigShareNodeSettings,
model.FigShareGuidFile
]
USER_SETTINGS_MODEL = model.AddonFigShareUserSettings
NODE_SETTINGS_MODEL = model.AddonFigShareNodeSettings
ROUTES = [routes.settings_routes, routes.api_routes]
SHORT_NAME = 'figshare'
FULL_NAME = 'figshare'
OWNERS = ['user', 'node']
ADDED_DEFAULT = []
ADDED_MANDATORY = []
VIEWS = []
CONFIGS = ['user', 'node']
CATEGORIES = ['storage']
INCLUDE_JS = {}
INCLUDE_CSS = {}
HAS_HGRID_FILES = True
GET_HGRID_DATA = views.hgrid.figshare_hgrid_data
MAX_FILE_SIZE = 50
HERE = os.path.dirname(os.path.abspath(__file__))
NODE_SETTINGS_TEMPLATE = None # use default nodes settings templates
USER_SETTINGS_TEMPLATE = os.path.join(HERE, 'templates', 'figshare_user_settings.mako')
| import os
from . import routes, views, model # noqa
MODELS = [
model.AddonFigShareUserSettings,
model.AddonFigShareNodeSettings,
model.FigShareGuidFile
]
USER_SETTINGS_MODEL = model.AddonFigShareUserSettings
NODE_SETTINGS_MODEL = model.AddonFigShareNodeSettings
ROUTES = [routes.settings_routes, routes.api_routes]
SHORT_NAME = 'figshare'
FULL_NAME = 'figshare'
OWNERS = ['user', 'node']
ADDED_DEFAULT = []
ADDED_MANDATORY = []
VIEWS = []
CONFIGS = ['user', 'node']
CATEGORIES = ['storage']
INCLUDE_JS = {}
INCLUDE_CSS = {}
HAS_HGRID_FILES = True
GET_HGRID_DATA = views.hgrid.figshare_hgrid_data
+ MAX_FILE_SIZE = 50
+
HERE = os.path.dirname(os.path.abspath(__file__))
NODE_SETTINGS_TEMPLATE = None # use default nodes settings templates
USER_SETTINGS_TEMPLATE = os.path.join(HERE, 'templates', 'figshare_user_settings.mako') |
7c0c5631ff9f2d3511b7c460d22516b5b0393697 | setup.py | setup.py |
import distutils.core
# Uploading to PyPI
# =================
# $ python setup.py register -r pypi
# $ python setup.py sdist upload -r pypi
version = '1.1'
distutils.core.setup(
name='linersock',
version=version,
author='Kale Kundert and Alex Mitchell',
packages=['linersock'],
url='https://github.com/kxgames/linersock',
download_url='https://github.com/kxgames/linersock/tarball/'+version,
license='LICENSE.txt',
description="A thin layer between you and your sockets that helps prevent chafing.",
long_description=open('README.rst').read(),
keywords=['nonblocking', 'socket', 'wrapper', 'library'])
|
import distutils.core
# Uploading to PyPI
# =================
# $ python setup.py register -r pypi
# $ python setup.py sdist upload -r pypi
version = '1.2'
distutils.core.setup(
name='linersock',
version=version,
author='Kale Kundert and Alex Mitchell',
url='https://github.com/kxgames/linersock',
download_url='https://github.com/kxgames/linersock/tarball/'+version,
license='LICENSE.txt',
description="A thin layer between you and your sockets that helps prevent chafing.",
long_description=open('README.rst').read(),
keywords=['nonblocking', 'socket', 'wrapper', 'library'],
packages=['linersock'],
install_requires=[
'six',
],
)
| Add six as a dependency. | Add six as a dependency.
| Python | mit | kalekundert/linersock,kalekundert/linersock |
import distutils.core
# Uploading to PyPI
# =================
# $ python setup.py register -r pypi
# $ python setup.py sdist upload -r pypi
- version = '1.1'
+ version = '1.2'
distutils.core.setup(
name='linersock',
version=version,
author='Kale Kundert and Alex Mitchell',
- packages=['linersock'],
url='https://github.com/kxgames/linersock',
download_url='https://github.com/kxgames/linersock/tarball/'+version,
license='LICENSE.txt',
description="A thin layer between you and your sockets that helps prevent chafing.",
long_description=open('README.rst').read(),
- keywords=['nonblocking', 'socket', 'wrapper', 'library'])
+ keywords=['nonblocking', 'socket', 'wrapper', 'library'],
+ packages=['linersock'],
+ install_requires=[
+ 'six',
+ ],
+ )
| Add six as a dependency. | ## Code Before:
import distutils.core
# Uploading to PyPI
# =================
# $ python setup.py register -r pypi
# $ python setup.py sdist upload -r pypi
version = '1.1'
distutils.core.setup(
name='linersock',
version=version,
author='Kale Kundert and Alex Mitchell',
packages=['linersock'],
url='https://github.com/kxgames/linersock',
download_url='https://github.com/kxgames/linersock/tarball/'+version,
license='LICENSE.txt',
description="A thin layer between you and your sockets that helps prevent chafing.",
long_description=open('README.rst').read(),
keywords=['nonblocking', 'socket', 'wrapper', 'library'])
## Instruction:
Add six as a dependency.
## Code After:
import distutils.core
# Uploading to PyPI
# =================
# $ python setup.py register -r pypi
# $ python setup.py sdist upload -r pypi
version = '1.2'
distutils.core.setup(
name='linersock',
version=version,
author='Kale Kundert and Alex Mitchell',
url='https://github.com/kxgames/linersock',
download_url='https://github.com/kxgames/linersock/tarball/'+version,
license='LICENSE.txt',
description="A thin layer between you and your sockets that helps prevent chafing.",
long_description=open('README.rst').read(),
keywords=['nonblocking', 'socket', 'wrapper', 'library'],
packages=['linersock'],
install_requires=[
'six',
],
)
|
import distutils.core
# Uploading to PyPI
# =================
# $ python setup.py register -r pypi
# $ python setup.py sdist upload -r pypi
- version = '1.1'
? ^
+ version = '1.2'
? ^
distutils.core.setup(
name='linersock',
version=version,
author='Kale Kundert and Alex Mitchell',
- packages=['linersock'],
url='https://github.com/kxgames/linersock',
download_url='https://github.com/kxgames/linersock/tarball/'+version,
license='LICENSE.txt',
description="A thin layer between you and your sockets that helps prevent chafing.",
long_description=open('README.rst').read(),
- keywords=['nonblocking', 'socket', 'wrapper', 'library'])
? ^
+ keywords=['nonblocking', 'socket', 'wrapper', 'library'],
? ^
+ packages=['linersock'],
+ install_requires=[
+ 'six',
+ ],
+ ) |
6321d2e86db0de359886f5e69509dad428778bbf | shop/management/commands/shopcustomers.py | shop/management/commands/shopcustomers.py | from __future__ import unicode_literals
from optparse import make_option
from django.core.management.base import BaseCommand
from django.utils.translation import ugettext_lazy as _
class Command(BaseCommand):
help = _("Collect information about all customers which accessed this shop.")
option_list = BaseCommand.option_list + (
make_option("--delete-expired", action='store_true', dest='delete_expired',
help=_("Delete customers with expired sessions.")),
)
def handle(self, verbosity, delete_expired, *args, **options):
from shop.models.customer import CustomerModel
data = dict(total=0, anonymous=0, active=0, staff=0, guests=0, registered=0, expired=0)
for customer in CustomerModel.objects.iterator():
data['total'] += 1
if customer.user.is_active:
data['active'] += 1
if customer.user.is_staff:
data['staff'] += 1
if customer.is_registered():
data['registered'] += 1
elif customer.is_guest():
data['guests'] += 1
elif customer.is_anonymous():
data['anonymous'] += 1
if customer.is_expired():
data['expired'] += 1
if delete_expired:
customer.delete()
msg = _("Customers in this shop: total={total}, anonymous={anonymous}, expired={expired}, active={active}, guests={guests}, registered={registered}, staff={staff}.")
self.stdout.write(msg.format(**data))
| from __future__ import unicode_literals
from optparse import make_option
from django.core.management.base import BaseCommand
from django.utils.translation import ugettext_lazy as _
class Command(BaseCommand):
help = _("Collect information about all customers which accessed this shop.")
def add_arguments(self, parser):
parser.add_argument("--delete-expired", action='store_true', dest='delete_expired',
help=_("Delete customers with expired sessions."))
def handle(self, verbosity, delete_expired, *args, **options):
from shop.models.customer import CustomerModel
data = dict(total=0, anonymous=0, active=0, staff=0, guests=0, registered=0, expired=0)
for customer in CustomerModel.objects.iterator():
data['total'] += 1
if customer.user.is_active:
data['active'] += 1
if customer.user.is_staff:
data['staff'] += 1
if customer.is_registered():
data['registered'] += 1
elif customer.is_guest():
data['guests'] += 1
elif customer.is_anonymous():
data['anonymous'] += 1
if customer.is_expired():
data['expired'] += 1
if delete_expired:
customer.delete()
msg = _("Customers in this shop: total={total}, anonymous={anonymous}, expired={expired}, active={active}, guests={guests}, registered={registered}, staff={staff}.")
self.stdout.write(msg.format(**data))
| Use the new django management commands definition (ArgumentParser) | Use the new django management commands definition (ArgumentParser)
| Python | bsd-3-clause | jrief/django-shop,jrief/django-shop,divio/django-shop,awesto/django-shop,nimbis/django-shop,nimbis/django-shop,khchine5/django-shop,awesto/django-shop,jrief/django-shop,nimbis/django-shop,awesto/django-shop,khchine5/django-shop,nimbis/django-shop,jrief/django-shop,divio/django-shop,khchine5/django-shop,divio/django-shop,khchine5/django-shop | from __future__ import unicode_literals
from optparse import make_option
from django.core.management.base import BaseCommand
from django.utils.translation import ugettext_lazy as _
class Command(BaseCommand):
help = _("Collect information about all customers which accessed this shop.")
- option_list = BaseCommand.option_list + (
+ def add_arguments(self, parser):
- make_option("--delete-expired", action='store_true', dest='delete_expired',
+ parser.add_argument("--delete-expired", action='store_true', dest='delete_expired',
- help=_("Delete customers with expired sessions.")),
+ help=_("Delete customers with expired sessions."))
- )
def handle(self, verbosity, delete_expired, *args, **options):
from shop.models.customer import CustomerModel
data = dict(total=0, anonymous=0, active=0, staff=0, guests=0, registered=0, expired=0)
for customer in CustomerModel.objects.iterator():
data['total'] += 1
if customer.user.is_active:
data['active'] += 1
if customer.user.is_staff:
data['staff'] += 1
if customer.is_registered():
data['registered'] += 1
elif customer.is_guest():
data['guests'] += 1
elif customer.is_anonymous():
data['anonymous'] += 1
if customer.is_expired():
data['expired'] += 1
if delete_expired:
customer.delete()
msg = _("Customers in this shop: total={total}, anonymous={anonymous}, expired={expired}, active={active}, guests={guests}, registered={registered}, staff={staff}.")
self.stdout.write(msg.format(**data))
| Use the new django management commands definition (ArgumentParser) | ## Code Before:
from __future__ import unicode_literals
from optparse import make_option
from django.core.management.base import BaseCommand
from django.utils.translation import ugettext_lazy as _
class Command(BaseCommand):
help = _("Collect information about all customers which accessed this shop.")
option_list = BaseCommand.option_list + (
make_option("--delete-expired", action='store_true', dest='delete_expired',
help=_("Delete customers with expired sessions.")),
)
def handle(self, verbosity, delete_expired, *args, **options):
from shop.models.customer import CustomerModel
data = dict(total=0, anonymous=0, active=0, staff=0, guests=0, registered=0, expired=0)
for customer in CustomerModel.objects.iterator():
data['total'] += 1
if customer.user.is_active:
data['active'] += 1
if customer.user.is_staff:
data['staff'] += 1
if customer.is_registered():
data['registered'] += 1
elif customer.is_guest():
data['guests'] += 1
elif customer.is_anonymous():
data['anonymous'] += 1
if customer.is_expired():
data['expired'] += 1
if delete_expired:
customer.delete()
msg = _("Customers in this shop: total={total}, anonymous={anonymous}, expired={expired}, active={active}, guests={guests}, registered={registered}, staff={staff}.")
self.stdout.write(msg.format(**data))
## Instruction:
Use the new django management commands definition (ArgumentParser)
## Code After:
from __future__ import unicode_literals
from optparse import make_option
from django.core.management.base import BaseCommand
from django.utils.translation import ugettext_lazy as _
class Command(BaseCommand):
help = _("Collect information about all customers which accessed this shop.")
def add_arguments(self, parser):
parser.add_argument("--delete-expired", action='store_true', dest='delete_expired',
help=_("Delete customers with expired sessions."))
def handle(self, verbosity, delete_expired, *args, **options):
from shop.models.customer import CustomerModel
data = dict(total=0, anonymous=0, active=0, staff=0, guests=0, registered=0, expired=0)
for customer in CustomerModel.objects.iterator():
data['total'] += 1
if customer.user.is_active:
data['active'] += 1
if customer.user.is_staff:
data['staff'] += 1
if customer.is_registered():
data['registered'] += 1
elif customer.is_guest():
data['guests'] += 1
elif customer.is_anonymous():
data['anonymous'] += 1
if customer.is_expired():
data['expired'] += 1
if delete_expired:
customer.delete()
msg = _("Customers in this shop: total={total}, anonymous={anonymous}, expired={expired}, active={active}, guests={guests}, registered={registered}, staff={staff}.")
self.stdout.write(msg.format(**data))
| from __future__ import unicode_literals
from optparse import make_option
from django.core.management.base import BaseCommand
from django.utils.translation import ugettext_lazy as _
class Command(BaseCommand):
help = _("Collect information about all customers which accessed this shop.")
- option_list = BaseCommand.option_list + (
+ def add_arguments(self, parser):
- make_option("--delete-expired", action='store_true', dest='delete_expired',
? -- ^^^ ---
+ parser.add_argument("--delete-expired", action='store_true', dest='delete_expired',
? +++++++++++++++ ^
- help=_("Delete customers with expired sessions.")),
? -
+ help=_("Delete customers with expired sessions."))
- )
def handle(self, verbosity, delete_expired, *args, **options):
from shop.models.customer import CustomerModel
data = dict(total=0, anonymous=0, active=0, staff=0, guests=0, registered=0, expired=0)
for customer in CustomerModel.objects.iterator():
data['total'] += 1
if customer.user.is_active:
data['active'] += 1
if customer.user.is_staff:
data['staff'] += 1
if customer.is_registered():
data['registered'] += 1
elif customer.is_guest():
data['guests'] += 1
elif customer.is_anonymous():
data['anonymous'] += 1
if customer.is_expired():
data['expired'] += 1
if delete_expired:
customer.delete()
msg = _("Customers in this shop: total={total}, anonymous={anonymous}, expired={expired}, active={active}, guests={guests}, registered={registered}, staff={staff}.")
self.stdout.write(msg.format(**data)) |
780a330e1f185d7c19953edb5bc1767582501197 | tests/test_card.py | tests/test_card.py | import unittest
from cards.card import Card
class Test_Card(unittest.TestCase):
def setUp(self):
self._suit = "clubs"
self._rank = "10"
self._card = ConcreteCard(suit=self._suit, rank=self._rank)
def tearDown(self):
pass
def test_card_is_abstract_class(self):
""" Test that the Card class is an abstract base class """
with self.assertRaises(TypeError):
Card()
def test_rank(self):
""" Test 'rank' property returns correct rank. """
card = self._card
self.assertEqual(card.rank, self._rank)
def test_suit(self):
""" Test 'suit' property returns correct suit. """
card = self._card
self.assertEqual(card.suit, self._suit)
class ConcreteCard(Card):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
@property
def value(self):
pass
if __name__ == "__main__":
# import sys;sys.argv = ['', 'Test.testName']
unittest.main()
| import unittest
from cards.card import Card
class Test_Card(unittest.TestCase):
def setUp(self):
self._suit = "clubs"
self._rank = "10"
self._card = ConcreteCard(suit=self._suit, rank=self._rank)
def tearDown(self):
pass
def test_card_is_abstract_class(self):
""" Test that the Card class is an abstract base class """
with self.assertRaises(TypeError):
Card()
def test_rank(self):
""" Test 'rank' property returns correct rank. """
card = self._card
self.assertEqual(card.rank, self._rank)
def test_suit(self):
""" Test 'suit' property returns correct suit. """
card = self._card
self.assertEqual(card.suit, self._suit)
class ConcreteCard(Card):
def __init__(self, suit, rank):
super().__init__(suit, rank)
@property
def value(self):
pass
if __name__ == "__main__":
# import sys;sys.argv = ['', 'Test.testName']
unittest.main()
| Change ConcreteCard test class params. | Change ConcreteCard test class params.
| Python | mit | johnpapa2/twenty-one,johnpapa2/twenty-one | import unittest
from cards.card import Card
class Test_Card(unittest.TestCase):
def setUp(self):
self._suit = "clubs"
self._rank = "10"
self._card = ConcreteCard(suit=self._suit, rank=self._rank)
def tearDown(self):
pass
def test_card_is_abstract_class(self):
""" Test that the Card class is an abstract base class """
with self.assertRaises(TypeError):
Card()
def test_rank(self):
""" Test 'rank' property returns correct rank. """
card = self._card
self.assertEqual(card.rank, self._rank)
def test_suit(self):
""" Test 'suit' property returns correct suit. """
card = self._card
self.assertEqual(card.suit, self._suit)
class ConcreteCard(Card):
- def __init__(self, *args, **kwargs):
- super().__init__(*args, **kwargs)
+ def __init__(self, suit, rank):
+ super().__init__(suit, rank)
@property
def value(self):
pass
if __name__ == "__main__":
# import sys;sys.argv = ['', 'Test.testName']
unittest.main()
| Change ConcreteCard test class params. | ## Code Before:
import unittest
from cards.card import Card
class Test_Card(unittest.TestCase):
def setUp(self):
self._suit = "clubs"
self._rank = "10"
self._card = ConcreteCard(suit=self._suit, rank=self._rank)
def tearDown(self):
pass
def test_card_is_abstract_class(self):
""" Test that the Card class is an abstract base class """
with self.assertRaises(TypeError):
Card()
def test_rank(self):
""" Test 'rank' property returns correct rank. """
card = self._card
self.assertEqual(card.rank, self._rank)
def test_suit(self):
""" Test 'suit' property returns correct suit. """
card = self._card
self.assertEqual(card.suit, self._suit)
class ConcreteCard(Card):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
@property
def value(self):
pass
if __name__ == "__main__":
# import sys;sys.argv = ['', 'Test.testName']
unittest.main()
## Instruction:
Change ConcreteCard test class params.
## Code After:
import unittest
from cards.card import Card
class Test_Card(unittest.TestCase):
def setUp(self):
self._suit = "clubs"
self._rank = "10"
self._card = ConcreteCard(suit=self._suit, rank=self._rank)
def tearDown(self):
pass
def test_card_is_abstract_class(self):
""" Test that the Card class is an abstract base class """
with self.assertRaises(TypeError):
Card()
def test_rank(self):
""" Test 'rank' property returns correct rank. """
card = self._card
self.assertEqual(card.rank, self._rank)
def test_suit(self):
""" Test 'suit' property returns correct suit. """
card = self._card
self.assertEqual(card.suit, self._suit)
class ConcreteCard(Card):
def __init__(self, suit, rank):
super().__init__(suit, rank)
@property
def value(self):
pass
if __name__ == "__main__":
# import sys;sys.argv = ['', 'Test.testName']
unittest.main()
| import unittest
from cards.card import Card
class Test_Card(unittest.TestCase):
def setUp(self):
self._suit = "clubs"
self._rank = "10"
self._card = ConcreteCard(suit=self._suit, rank=self._rank)
def tearDown(self):
pass
def test_card_is_abstract_class(self):
""" Test that the Card class is an abstract base class """
with self.assertRaises(TypeError):
Card()
def test_rank(self):
""" Test 'rank' property returns correct rank. """
card = self._card
self.assertEqual(card.rank, self._rank)
def test_suit(self):
""" Test 'suit' property returns correct suit. """
card = self._card
self.assertEqual(card.suit, self._suit)
class ConcreteCard(Card):
- def __init__(self, *args, **kwargs):
? ---- ^^ -----
+ def __init__(self, suit, rank):
? +++ ^^^
- super().__init__(*args, **kwargs)
? ---- ^^ -----
+ super().__init__(suit, rank)
? +++ ^^^
@property
def value(self):
pass
if __name__ == "__main__":
# import sys;sys.argv = ['', 'Test.testName']
unittest.main() |
35a9de1ba8f6c1bcb6ae35c9f965657de973412f | tokenizers/sentiment_tokenizer.py | tokenizers/sentiment_tokenizer.py | from nltk.sentiment.util import mark_negation
from nltk.util import trigrams
import re
import validators
from .happy_tokenizer import Tokenizer
class SentimentTokenizer(object):
def __init__(self):
self.tknzr = Tokenizer()
@staticmethod
def reduce_lengthening(text):
"""
Replace repeated character sequences of length 3 or greater with sequences
of length 3.
"""
pattern = re.compile(r"(.)\1{2,}")
return pattern.sub(r"\1\1\1", text)
@staticmethod
def replace_username(token):
return '@__user__' if token.startswith('@') else token
@staticmethod
def replace_link(token):
return '__url__' if validators.url(token) else token
def __call__(self, t):
t = self.reduce_lengthening(t)
tokens = t.split(' ')
cleaned_tokens = []
for token in tokens:
token = self.replace_username(token)
token = self.replace_link(token)
cleaned_tokens.append(token)
rebuild_str = ' '.join(cleaned_tokens)
negated_tokens = mark_negation(list(self.tknzr.tokenize(rebuild_str)))
list_of_trigrams = list(trigrams(negated_tokens))
return list([' '.join(s) for s in list_of_trigrams])
| from nltk.sentiment.util import mark_negation
from nltk.util import trigrams
import re
import validators
from .happy_tokenizer import Tokenizer
class SentimentTokenizer(object):
def __init__(self):
self.tknzr = Tokenizer()
@staticmethod
def reduce_lengthening(text):
"""
Replace repeated character sequences of length 3 or greater with sequences
of length 3.
"""
pattern = re.compile(r"(.)\1{2,}")
return pattern.sub(r"\1\1\1", text)
@staticmethod
def replace_username(token):
return '@__user__' if token.startswith('@') else token
@staticmethod
def replace_link(token):
return '__url__' if validators.url(token) else token
def __call__(self, t):
t = self.reduce_lengthening(t)
tokens = t.split(' ')
cleaned_tokens = []
for token in tokens:
token = self.replace_username(token)
token = self.replace_link(token)
cleaned_tokens.append(token)
rebuild_str = ' '.join(cleaned_tokens)
negated_tokens = mark_negation(list(self.tknzr.tokenize(rebuild_str)))
list_of_trigrams = list([' '.join(s) for s in trigrams(negated_tokens)])
return list_of_trigrams
| Use map to loop instead of mapping a list | Use map to loop instead of mapping a list
| Python | apache-2.0 | chuajiesheng/twitter-sentiment-analysis | from nltk.sentiment.util import mark_negation
from nltk.util import trigrams
import re
import validators
from .happy_tokenizer import Tokenizer
class SentimentTokenizer(object):
def __init__(self):
self.tknzr = Tokenizer()
@staticmethod
def reduce_lengthening(text):
"""
Replace repeated character sequences of length 3 or greater with sequences
of length 3.
"""
pattern = re.compile(r"(.)\1{2,}")
return pattern.sub(r"\1\1\1", text)
@staticmethod
def replace_username(token):
return '@__user__' if token.startswith('@') else token
@staticmethod
def replace_link(token):
return '__url__' if validators.url(token) else token
def __call__(self, t):
t = self.reduce_lengthening(t)
tokens = t.split(' ')
cleaned_tokens = []
for token in tokens:
token = self.replace_username(token)
token = self.replace_link(token)
cleaned_tokens.append(token)
rebuild_str = ' '.join(cleaned_tokens)
negated_tokens = mark_negation(list(self.tknzr.tokenize(rebuild_str)))
- list_of_trigrams = list(trigrams(negated_tokens))
+ list_of_trigrams = list([' '.join(s) for s in trigrams(negated_tokens)])
- return list([' '.join(s) for s in list_of_trigrams])
+ return list_of_trigrams
| Use map to loop instead of mapping a list | ## Code Before:
from nltk.sentiment.util import mark_negation
from nltk.util import trigrams
import re
import validators
from .happy_tokenizer import Tokenizer
class SentimentTokenizer(object):
def __init__(self):
self.tknzr = Tokenizer()
@staticmethod
def reduce_lengthening(text):
"""
Replace repeated character sequences of length 3 or greater with sequences
of length 3.
"""
pattern = re.compile(r"(.)\1{2,}")
return pattern.sub(r"\1\1\1", text)
@staticmethod
def replace_username(token):
return '@__user__' if token.startswith('@') else token
@staticmethod
def replace_link(token):
return '__url__' if validators.url(token) else token
def __call__(self, t):
t = self.reduce_lengthening(t)
tokens = t.split(' ')
cleaned_tokens = []
for token in tokens:
token = self.replace_username(token)
token = self.replace_link(token)
cleaned_tokens.append(token)
rebuild_str = ' '.join(cleaned_tokens)
negated_tokens = mark_negation(list(self.tknzr.tokenize(rebuild_str)))
list_of_trigrams = list(trigrams(negated_tokens))
return list([' '.join(s) for s in list_of_trigrams])
## Instruction:
Use map to loop instead of mapping a list
## Code After:
from nltk.sentiment.util import mark_negation
from nltk.util import trigrams
import re
import validators
from .happy_tokenizer import Tokenizer
class SentimentTokenizer(object):
def __init__(self):
self.tknzr = Tokenizer()
@staticmethod
def reduce_lengthening(text):
"""
Replace repeated character sequences of length 3 or greater with sequences
of length 3.
"""
pattern = re.compile(r"(.)\1{2,}")
return pattern.sub(r"\1\1\1", text)
@staticmethod
def replace_username(token):
return '@__user__' if token.startswith('@') else token
@staticmethod
def replace_link(token):
return '__url__' if validators.url(token) else token
def __call__(self, t):
t = self.reduce_lengthening(t)
tokens = t.split(' ')
cleaned_tokens = []
for token in tokens:
token = self.replace_username(token)
token = self.replace_link(token)
cleaned_tokens.append(token)
rebuild_str = ' '.join(cleaned_tokens)
negated_tokens = mark_negation(list(self.tknzr.tokenize(rebuild_str)))
list_of_trigrams = list([' '.join(s) for s in trigrams(negated_tokens)])
return list_of_trigrams
| from nltk.sentiment.util import mark_negation
from nltk.util import trigrams
import re
import validators
from .happy_tokenizer import Tokenizer
class SentimentTokenizer(object):
def __init__(self):
self.tknzr = Tokenizer()
@staticmethod
def reduce_lengthening(text):
"""
Replace repeated character sequences of length 3 or greater with sequences
of length 3.
"""
pattern = re.compile(r"(.)\1{2,}")
return pattern.sub(r"\1\1\1", text)
@staticmethod
def replace_username(token):
return '@__user__' if token.startswith('@') else token
@staticmethod
def replace_link(token):
return '__url__' if validators.url(token) else token
def __call__(self, t):
t = self.reduce_lengthening(t)
tokens = t.split(' ')
cleaned_tokens = []
for token in tokens:
token = self.replace_username(token)
token = self.replace_link(token)
cleaned_tokens.append(token)
rebuild_str = ' '.join(cleaned_tokens)
negated_tokens = mark_negation(list(self.tknzr.tokenize(rebuild_str)))
- list_of_trigrams = list(trigrams(negated_tokens))
+ list_of_trigrams = list([' '.join(s) for s in trigrams(negated_tokens)])
? ++++++++++++++++++++++ +
- return list([' '.join(s) for s in list_of_trigrams])
+ return list_of_trigrams
|
6fd4e2e4158c968a095832f3bf669109dc9f1481 | mopidy_mpris/__init__.py | mopidy_mpris/__init__.py | import os
from mopidy import config, exceptions, ext
__version__ = "2.0.0"
class Extension(ext.Extension):
dist_name = "Mopidy-MPRIS"
ext_name = "mpris"
version = __version__
def get_default_config(self):
conf_file = os.path.join(os.path.dirname(__file__), "ext.conf")
return config.read(conf_file)
def get_config_schema(self):
schema = super().get_config_schema()
schema["desktop_file"] = config.Deprecated()
schema["bus_type"] = config.String(choices=["session", "system"])
return schema
def validate_environment(self):
try:
import pydbus # noqa
except ImportError as e:
raise exceptions.ExtensionError("pydbus library not found", e)
def setup(self, registry):
from .frontend import MprisFrontend
registry.add("frontend", MprisFrontend)
| import pathlib
from mopidy import config, exceptions, ext
__version__ = "2.0.0"
class Extension(ext.Extension):
dist_name = "Mopidy-MPRIS"
ext_name = "mpris"
version = __version__
def get_default_config(self):
return config.read(pathlib.Path(__file__).parent / "ext.conf")
def get_config_schema(self):
schema = super().get_config_schema()
schema["desktop_file"] = config.Deprecated()
schema["bus_type"] = config.String(choices=["session", "system"])
return schema
def validate_environment(self):
try:
import pydbus # noqa
except ImportError as e:
raise exceptions.ExtensionError("pydbus library not found", e)
def setup(self, registry):
from .frontend import MprisFrontend
registry.add("frontend", MprisFrontend)
| Use pathlib to read ext.conf | Use pathlib to read ext.conf
| Python | apache-2.0 | mopidy/mopidy-mpris | - import os
+ import pathlib
from mopidy import config, exceptions, ext
__version__ = "2.0.0"
class Extension(ext.Extension):
dist_name = "Mopidy-MPRIS"
ext_name = "mpris"
version = __version__
def get_default_config(self):
+ return config.read(pathlib.Path(__file__).parent / "ext.conf")
- conf_file = os.path.join(os.path.dirname(__file__), "ext.conf")
- return config.read(conf_file)
def get_config_schema(self):
schema = super().get_config_schema()
schema["desktop_file"] = config.Deprecated()
schema["bus_type"] = config.String(choices=["session", "system"])
return schema
def validate_environment(self):
try:
import pydbus # noqa
except ImportError as e:
raise exceptions.ExtensionError("pydbus library not found", e)
def setup(self, registry):
from .frontend import MprisFrontend
registry.add("frontend", MprisFrontend)
| Use pathlib to read ext.conf | ## Code Before:
import os
from mopidy import config, exceptions, ext
__version__ = "2.0.0"
class Extension(ext.Extension):
dist_name = "Mopidy-MPRIS"
ext_name = "mpris"
version = __version__
def get_default_config(self):
conf_file = os.path.join(os.path.dirname(__file__), "ext.conf")
return config.read(conf_file)
def get_config_schema(self):
schema = super().get_config_schema()
schema["desktop_file"] = config.Deprecated()
schema["bus_type"] = config.String(choices=["session", "system"])
return schema
def validate_environment(self):
try:
import pydbus # noqa
except ImportError as e:
raise exceptions.ExtensionError("pydbus library not found", e)
def setup(self, registry):
from .frontend import MprisFrontend
registry.add("frontend", MprisFrontend)
## Instruction:
Use pathlib to read ext.conf
## Code After:
import pathlib
from mopidy import config, exceptions, ext
__version__ = "2.0.0"
class Extension(ext.Extension):
dist_name = "Mopidy-MPRIS"
ext_name = "mpris"
version = __version__
def get_default_config(self):
return config.read(pathlib.Path(__file__).parent / "ext.conf")
def get_config_schema(self):
schema = super().get_config_schema()
schema["desktop_file"] = config.Deprecated()
schema["bus_type"] = config.String(choices=["session", "system"])
return schema
def validate_environment(self):
try:
import pydbus # noqa
except ImportError as e:
raise exceptions.ExtensionError("pydbus library not found", e)
def setup(self, registry):
from .frontend import MprisFrontend
registry.add("frontend", MprisFrontend)
| - import os
+ import pathlib
from mopidy import config, exceptions, ext
__version__ = "2.0.0"
class Extension(ext.Extension):
dist_name = "Mopidy-MPRIS"
ext_name = "mpris"
version = __version__
def get_default_config(self):
+ return config.read(pathlib.Path(__file__).parent / "ext.conf")
- conf_file = os.path.join(os.path.dirname(__file__), "ext.conf")
- return config.read(conf_file)
def get_config_schema(self):
schema = super().get_config_schema()
schema["desktop_file"] = config.Deprecated()
schema["bus_type"] = config.String(choices=["session", "system"])
return schema
def validate_environment(self):
try:
import pydbus # noqa
except ImportError as e:
raise exceptions.ExtensionError("pydbus library not found", e)
def setup(self, registry):
from .frontend import MprisFrontend
registry.add("frontend", MprisFrontend) |
4dcb0a9860b654a08839a61f5e67af69771de39c | tests/test_slow_requests.py | tests/test_slow_requests.py | import datetime
import dnstwister.tools
def test2():
"""Looooong domain names highlighted that the idna decoding is slooooow.
This is a basic benchmark for performance.
"""
domain = 'zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.zzzzzzzzzzzzzzzzzzzzzzzzzppieo.com'
start = datetime.datetime.now()
dnstwister.tools.fuzzy_domains(domain)
duration = (datetime.datetime.now() - start).total_seconds()
assert duration < 5, 'duration too long: {} secs'.format(duration)
| import datetime
import dnstwister.tools
def test2():
"""Looooong domain names highlighted that the idna decoding is slooooow.
This is a basic benchmark for performance, based on a bot's behaviour
recently.
"""
domain = 'zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.zzzzzzzzzzzzzzzzzzzzzzzzzppieo.com'
start = datetime.datetime.now()
dnstwister.tools.fuzzy_domains(domain)
duration = (datetime.datetime.now() - start).total_seconds()
assert duration < 7, 'duration too long: {} secs'.format(duration)
| Test threshold increased because the Travis server is a bit slower :) | Test threshold increased because the Travis server is a bit slower :)
| Python | unlicense | thisismyrobot/dnstwister,thisismyrobot/dnstwister,thisismyrobot/dnstwister | import datetime
import dnstwister.tools
def test2():
"""Looooong domain names highlighted that the idna decoding is slooooow.
- This is a basic benchmark for performance.
+ This is a basic benchmark for performance, based on a bot's behaviour
+ recently.
"""
domain = 'zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.zzzzzzzzzzzzzzzzzzzzzzzzzppieo.com'
start = datetime.datetime.now()
dnstwister.tools.fuzzy_domains(domain)
duration = (datetime.datetime.now() - start).total_seconds()
- assert duration < 5, 'duration too long: {} secs'.format(duration)
+ assert duration < 7, 'duration too long: {} secs'.format(duration)
| Test threshold increased because the Travis server is a bit slower :) | ## Code Before:
import datetime
import dnstwister.tools
def test2():
"""Looooong domain names highlighted that the idna decoding is slooooow.
This is a basic benchmark for performance.
"""
domain = 'zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.zzzzzzzzzzzzzzzzzzzzzzzzzppieo.com'
start = datetime.datetime.now()
dnstwister.tools.fuzzy_domains(domain)
duration = (datetime.datetime.now() - start).total_seconds()
assert duration < 5, 'duration too long: {} secs'.format(duration)
## Instruction:
Test threshold increased because the Travis server is a bit slower :)
## Code After:
import datetime
import dnstwister.tools
def test2():
"""Looooong domain names highlighted that the idna decoding is slooooow.
This is a basic benchmark for performance, based on a bot's behaviour
recently.
"""
domain = 'zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.zzzzzzzzzzzzzzzzzzzzzzzzzppieo.com'
start = datetime.datetime.now()
dnstwister.tools.fuzzy_domains(domain)
duration = (datetime.datetime.now() - start).total_seconds()
assert duration < 7, 'duration too long: {} secs'.format(duration)
| import datetime
import dnstwister.tools
def test2():
"""Looooong domain names highlighted that the idna decoding is slooooow.
- This is a basic benchmark for performance.
? ^
+ This is a basic benchmark for performance, based on a bot's behaviour
? ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+ recently.
"""
domain = 'zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.zzzzzzzzzzzzzzzzzzzzzzzzzppieo.com'
start = datetime.datetime.now()
dnstwister.tools.fuzzy_domains(domain)
duration = (datetime.datetime.now() - start).total_seconds()
- assert duration < 5, 'duration too long: {} secs'.format(duration)
? ^
+ assert duration < 7, 'duration too long: {} secs'.format(duration)
? ^
|
ce77cbeb6fcb71b49c669188b38e43fb75e4d729 | pyinfra_cli/__main__.py | pyinfra_cli/__main__.py |
import signal
import sys
import click
from colorama import init as colorama_init
from .legacy import run_main_with_legacy_arguments
from .main import cli, main
# Init colorama for Windows ANSI color support
colorama_init()
# Don't write out deploy.pyc/config.pyc etc
sys.dont_write_bytecode = True
# Make sure imported files (deploy.py/etc) behave as if imported from the cwd
sys.path.append('.')
# Shut it click
click.disable_unicode_literals_warning = True # noqa
# Handle ctrl+c
def _signal_handler(signum, frame):
print('Exiting upon user request!')
sys.exit(0)
signal.signal(signal.SIGINT, _signal_handler) # noqa
def execute_pyinfra():
# Legacy support for pyinfra <0.4 using docopt
if '-i' in sys.argv:
run_main_with_legacy_arguments(main)
else:
cli()
|
import signal
import sys
import click
import gevent
from colorama import init as colorama_init
from .legacy import run_main_with_legacy_arguments
from .main import cli, main
# Init colorama for Windows ANSI color support
colorama_init()
# Don't write out deploy.pyc/config.pyc etc
sys.dont_write_bytecode = True
# Make sure imported files (deploy.py/etc) behave as if imported from the cwd
sys.path.append('.')
# Shut it click
click.disable_unicode_literals_warning = True # noqa
def _handle_interrupt(signum, frame):
click.echo('Exiting upon user request!')
sys.exit(0)
gevent.signal(signal.SIGINT, gevent.kill) # kill any greenlets on ctrl+c
signal.signal(signal.SIGINT, _handle_interrupt) # print the message and exit main
def execute_pyinfra():
# Legacy support for pyinfra <0.4 using docopt
if '-i' in sys.argv:
run_main_with_legacy_arguments(main)
else:
cli()
| Kill all running greenlets when ctrl+c (works a charm in Python 3, not so much in 2). | Kill all running greenlets when ctrl+c (works a charm in Python 3, not so much in 2).
| Python | mit | Fizzadar/pyinfra,Fizzadar/pyinfra |
import signal
import sys
import click
+ import gevent
from colorama import init as colorama_init
from .legacy import run_main_with_legacy_arguments
from .main import cli, main
# Init colorama for Windows ANSI color support
colorama_init()
# Don't write out deploy.pyc/config.pyc etc
sys.dont_write_bytecode = True
# Make sure imported files (deploy.py/etc) behave as if imported from the cwd
sys.path.append('.')
# Shut it click
click.disable_unicode_literals_warning = True # noqa
- # Handle ctrl+c
+
- def _signal_handler(signum, frame):
+ def _handle_interrupt(signum, frame):
- print('Exiting upon user request!')
+ click.echo('Exiting upon user request!')
sys.exit(0)
- signal.signal(signal.SIGINT, _signal_handler) # noqa
+
+ gevent.signal(signal.SIGINT, gevent.kill) # kill any greenlets on ctrl+c
+ signal.signal(signal.SIGINT, _handle_interrupt) # print the message and exit main
def execute_pyinfra():
# Legacy support for pyinfra <0.4 using docopt
if '-i' in sys.argv:
run_main_with_legacy_arguments(main)
else:
cli()
| Kill all running greenlets when ctrl+c (works a charm in Python 3, not so much in 2). | ## Code Before:
import signal
import sys
import click
from colorama import init as colorama_init
from .legacy import run_main_with_legacy_arguments
from .main import cli, main
# Init colorama for Windows ANSI color support
colorama_init()
# Don't write out deploy.pyc/config.pyc etc
sys.dont_write_bytecode = True
# Make sure imported files (deploy.py/etc) behave as if imported from the cwd
sys.path.append('.')
# Shut it click
click.disable_unicode_literals_warning = True # noqa
# Handle ctrl+c
def _signal_handler(signum, frame):
print('Exiting upon user request!')
sys.exit(0)
signal.signal(signal.SIGINT, _signal_handler) # noqa
def execute_pyinfra():
# Legacy support for pyinfra <0.4 using docopt
if '-i' in sys.argv:
run_main_with_legacy_arguments(main)
else:
cli()
## Instruction:
Kill all running greenlets when ctrl+c (works a charm in Python 3, not so much in 2).
## Code After:
import signal
import sys
import click
import gevent
from colorama import init as colorama_init
from .legacy import run_main_with_legacy_arguments
from .main import cli, main
# Init colorama for Windows ANSI color support
colorama_init()
# Don't write out deploy.pyc/config.pyc etc
sys.dont_write_bytecode = True
# Make sure imported files (deploy.py/etc) behave as if imported from the cwd
sys.path.append('.')
# Shut it click
click.disable_unicode_literals_warning = True # noqa
def _handle_interrupt(signum, frame):
click.echo('Exiting upon user request!')
sys.exit(0)
gevent.signal(signal.SIGINT, gevent.kill) # kill any greenlets on ctrl+c
signal.signal(signal.SIGINT, _handle_interrupt) # print the message and exit main
def execute_pyinfra():
# Legacy support for pyinfra <0.4 using docopt
if '-i' in sys.argv:
run_main_with_legacy_arguments(main)
else:
cli()
|
import signal
import sys
import click
+ import gevent
from colorama import init as colorama_init
from .legacy import run_main_with_legacy_arguments
from .main import cli, main
# Init colorama for Windows ANSI color support
colorama_init()
# Don't write out deploy.pyc/config.pyc etc
sys.dont_write_bytecode = True
# Make sure imported files (deploy.py/etc) behave as if imported from the cwd
sys.path.append('.')
# Shut it click
click.disable_unicode_literals_warning = True # noqa
- # Handle ctrl+c
+
- def _signal_handler(signum, frame):
? -------
+ def _handle_interrupt(signum, frame):
? +++++ ++++
- print('Exiting upon user request!')
? ^^ ^^
+ click.echo('Exiting upon user request!')
? ^^ ^^^^^^^
sys.exit(0)
- signal.signal(signal.SIGINT, _signal_handler) # noqa
+
+ gevent.signal(signal.SIGINT, gevent.kill) # kill any greenlets on ctrl+c
+ signal.signal(signal.SIGINT, _handle_interrupt) # print the message and exit main
def execute_pyinfra():
# Legacy support for pyinfra <0.4 using docopt
if '-i' in sys.argv:
run_main_with_legacy_arguments(main)
else:
cli() |
1fc2e747f1c02d5b8559f03187464eecda008190 | fernet_fields/test/testmigrate/migrations/0004_copy_values.py | fernet_fields/test/testmigrate/migrations/0004_copy_values.py | from __future__ import unicode_literals
from django.db import migrations
def forwards(apps, schema_editor):
DualText = apps.get_model('testmigrate', 'DualText')
for obj in DualText.objects.all():
obj.value_dual = obj.value
def backwards(apps, schema_editor):
DualText = apps.get_model('testmigrate', 'DualText')
for obj in DualText.objects.all():
obj.value = obj.value_dual
class Migration(migrations.Migration):
dependencies = [
('testmigrate', '0003_add_value_dual'),
]
operations = [
migrations.RunPython(forwards, backwards),
]
| from __future__ import unicode_literals
from django.db import migrations
def forwards(apps, schema_editor):
DualText = apps.get_model('testmigrate', 'DualText')
for obj in DualText.objects.all():
obj.value_dual = obj.value
obj.save(force_update=True)
def backwards(apps, schema_editor):
DualText = apps.get_model('testmigrate', 'DualText')
for obj in DualText.objects.all():
obj.value = obj.value_dual
obj.save(force_update=True)
class Migration(migrations.Migration):
dependencies = [
('testmigrate', '0003_add_value_dual'),
]
operations = [
migrations.RunPython(forwards, backwards),
]
| Fix test migration to actually save updates. | Fix test migration to actually save updates.
| Python | bsd-3-clause | orcasgit/django-fernet-fields | from __future__ import unicode_literals
from django.db import migrations
def forwards(apps, schema_editor):
DualText = apps.get_model('testmigrate', 'DualText')
for obj in DualText.objects.all():
obj.value_dual = obj.value
+ obj.save(force_update=True)
def backwards(apps, schema_editor):
DualText = apps.get_model('testmigrate', 'DualText')
for obj in DualText.objects.all():
obj.value = obj.value_dual
+ obj.save(force_update=True)
class Migration(migrations.Migration):
dependencies = [
('testmigrate', '0003_add_value_dual'),
]
operations = [
migrations.RunPython(forwards, backwards),
]
| Fix test migration to actually save updates. | ## Code Before:
from __future__ import unicode_literals
from django.db import migrations
def forwards(apps, schema_editor):
DualText = apps.get_model('testmigrate', 'DualText')
for obj in DualText.objects.all():
obj.value_dual = obj.value
def backwards(apps, schema_editor):
DualText = apps.get_model('testmigrate', 'DualText')
for obj in DualText.objects.all():
obj.value = obj.value_dual
class Migration(migrations.Migration):
dependencies = [
('testmigrate', '0003_add_value_dual'),
]
operations = [
migrations.RunPython(forwards, backwards),
]
## Instruction:
Fix test migration to actually save updates.
## Code After:
from __future__ import unicode_literals
from django.db import migrations
def forwards(apps, schema_editor):
DualText = apps.get_model('testmigrate', 'DualText')
for obj in DualText.objects.all():
obj.value_dual = obj.value
obj.save(force_update=True)
def backwards(apps, schema_editor):
DualText = apps.get_model('testmigrate', 'DualText')
for obj in DualText.objects.all():
obj.value = obj.value_dual
obj.save(force_update=True)
class Migration(migrations.Migration):
dependencies = [
('testmigrate', '0003_add_value_dual'),
]
operations = [
migrations.RunPython(forwards, backwards),
]
| from __future__ import unicode_literals
from django.db import migrations
def forwards(apps, schema_editor):
DualText = apps.get_model('testmigrate', 'DualText')
for obj in DualText.objects.all():
obj.value_dual = obj.value
+ obj.save(force_update=True)
def backwards(apps, schema_editor):
DualText = apps.get_model('testmigrate', 'DualText')
for obj in DualText.objects.all():
obj.value = obj.value_dual
+ obj.save(force_update=True)
class Migration(migrations.Migration):
dependencies = [
('testmigrate', '0003_add_value_dual'),
]
operations = [
migrations.RunPython(forwards, backwards),
] |
ec6099421bad222595be15f4f0b2596952d8c9cc | username_to_uuid.py | username_to_uuid.py | import http.client
import json
class UsernameToUUID:
def __init__(self, username):
self.username = username
def get_uuid(self, timestamp=None):
"""
Get the UUID of the player.
Parameters
----------
timestamp : long integer
The time at which the player used this name, expressed as a Unix timestamp.
"""
get_args = "" if timestamp is None else "?at=" + str(timestamp)
http_conn = http.client.HTTPSConnection("api.mojang.com");
http_conn.request("GET", "/users/profiles/minecraft/" + self.username + get_args,
headers={'User-Agent':'Minecraft Username -> UUID', 'Content-Type':'application/json'});
response = http_conn.getresponse().read().decode("utf-8")
if (not response and timestamp is None): # No response & no timestamp
return self.get_uuid(0) # Let's retry with the Unix timestamp 0.
if (not response): # No response (player probably doesn't exist)
return ""
json_data = json.loads(response)
uuid = json_data['id']
return uuid
| import http.client
import json
class UsernameToUUID:
def __init__(self, username):
self.username = username
def get_uuid(self, timestamp=None):
"""
Get the UUID of the player.
Parameters
----------
timestamp : long integer
The time at which the player used this name, expressed as a Unix timestamp.
"""
get_args = "" if timestamp is None else "?at=" + str(timestamp)
http_conn = http.client.HTTPSConnection("api.mojang.com");
http_conn.request("GET", "/users/profiles/minecraft/" + self.username + get_args,
headers={'User-Agent':'Minecraft Username -> UUID', 'Content-Type':'application/json'});
response = http_conn.getresponse().read().decode("utf-8")
if (not response and timestamp is None): # No response & no timestamp
return self.get_uuid(0) # Let's retry with the Unix timestamp 0.
if (not response): # No response (player probably doesn't exist)
return ""
json_data = json.loads(response)
try:
uuid = json_data['id']
except KeyError as e:
print("KeyError raised:", e);
return uuid
| Improve robustness: surround the 'id' fetch from result array with a try clause. | Improve robustness: surround the 'id' fetch from result array with a try clause.
| Python | mit | mrlolethan/MinecraftUsernameToUUID | import http.client
import json
class UsernameToUUID:
def __init__(self, username):
self.username = username
def get_uuid(self, timestamp=None):
"""
Get the UUID of the player.
Parameters
----------
timestamp : long integer
The time at which the player used this name, expressed as a Unix timestamp.
"""
get_args = "" if timestamp is None else "?at=" + str(timestamp)
http_conn = http.client.HTTPSConnection("api.mojang.com");
http_conn.request("GET", "/users/profiles/minecraft/" + self.username + get_args,
headers={'User-Agent':'Minecraft Username -> UUID', 'Content-Type':'application/json'});
response = http_conn.getresponse().read().decode("utf-8")
if (not response and timestamp is None): # No response & no timestamp
return self.get_uuid(0) # Let's retry with the Unix timestamp 0.
if (not response): # No response (player probably doesn't exist)
return ""
json_data = json.loads(response)
+ try:
- uuid = json_data['id']
+ uuid = json_data['id']
+ except KeyError as e:
+ print("KeyError raised:", e);
return uuid
| Improve robustness: surround the 'id' fetch from result array with a try clause. | ## Code Before:
import http.client
import json
class UsernameToUUID:
def __init__(self, username):
self.username = username
def get_uuid(self, timestamp=None):
"""
Get the UUID of the player.
Parameters
----------
timestamp : long integer
The time at which the player used this name, expressed as a Unix timestamp.
"""
get_args = "" if timestamp is None else "?at=" + str(timestamp)
http_conn = http.client.HTTPSConnection("api.mojang.com");
http_conn.request("GET", "/users/profiles/minecraft/" + self.username + get_args,
headers={'User-Agent':'Minecraft Username -> UUID', 'Content-Type':'application/json'});
response = http_conn.getresponse().read().decode("utf-8")
if (not response and timestamp is None): # No response & no timestamp
return self.get_uuid(0) # Let's retry with the Unix timestamp 0.
if (not response): # No response (player probably doesn't exist)
return ""
json_data = json.loads(response)
uuid = json_data['id']
return uuid
## Instruction:
Improve robustness: surround the 'id' fetch from result array with a try clause.
## Code After:
import http.client
import json
class UsernameToUUID:
def __init__(self, username):
self.username = username
def get_uuid(self, timestamp=None):
"""
Get the UUID of the player.
Parameters
----------
timestamp : long integer
The time at which the player used this name, expressed as a Unix timestamp.
"""
get_args = "" if timestamp is None else "?at=" + str(timestamp)
http_conn = http.client.HTTPSConnection("api.mojang.com");
http_conn.request("GET", "/users/profiles/minecraft/" + self.username + get_args,
headers={'User-Agent':'Minecraft Username -> UUID', 'Content-Type':'application/json'});
response = http_conn.getresponse().read().decode("utf-8")
if (not response and timestamp is None): # No response & no timestamp
return self.get_uuid(0) # Let's retry with the Unix timestamp 0.
if (not response): # No response (player probably doesn't exist)
return ""
json_data = json.loads(response)
try:
uuid = json_data['id']
except KeyError as e:
print("KeyError raised:", e);
return uuid
| import http.client
import json
class UsernameToUUID:
def __init__(self, username):
self.username = username
def get_uuid(self, timestamp=None):
"""
Get the UUID of the player.
Parameters
----------
timestamp : long integer
The time at which the player used this name, expressed as a Unix timestamp.
"""
get_args = "" if timestamp is None else "?at=" + str(timestamp)
http_conn = http.client.HTTPSConnection("api.mojang.com");
http_conn.request("GET", "/users/profiles/minecraft/" + self.username + get_args,
headers={'User-Agent':'Minecraft Username -> UUID', 'Content-Type':'application/json'});
response = http_conn.getresponse().read().decode("utf-8")
if (not response and timestamp is None): # No response & no timestamp
return self.get_uuid(0) # Let's retry with the Unix timestamp 0.
if (not response): # No response (player probably doesn't exist)
return ""
json_data = json.loads(response)
+ try:
- uuid = json_data['id']
+ uuid = json_data['id']
? ++++
+ except KeyError as e:
+ print("KeyError raised:", e);
return uuid |
2549a66b6785d5a0ed0658a4f375a21c486792df | sifr/util.py | sifr/util.py | import datetime
from dateutil import parser
import six
def normalize_time(t):
try:
if isinstance(t, datetime.datetime):
return t
elif isinstance(t, datetime.date):
return datetime.datetime(t.year, t.month, t.day)
elif isinstance(t, (int, float)):
return datetime.datetime.fromtimestamp(t)
elif isinstance(t, six.string_types):
return parser.parse(t)
else:
raise
except: # noqa
raise TypeError(
"time must be represented as either a timestamp (int,float), "
"a datetime.datetime or datetime.date object, "
"or an iso-8601 formatted string"
)
| import datetime
from dateutil import parser
import six
def normalize_time(t):
try:
if isinstance(t, datetime.datetime):
return t
elif isinstance(t, datetime.date):
return datetime.datetime(t.year, t.month, t.day)
elif isinstance(t, (int, float)):
return datetime.datetime.fromtimestamp(t)
elif isinstance(t, six.string_types):
return parser.parse(t)
else:
raise TypeError
except: # noqa
raise TypeError(
"time must be represented as either a timestamp (int,float), "
"a datetime.datetime or datetime.date object, "
"or an iso-8601 formatted string"
)
| Raise explicit exception on no type match | Raise explicit exception on no type match
| Python | mit | alisaifee/sifr,alisaifee/sifr | import datetime
from dateutil import parser
import six
def normalize_time(t):
try:
if isinstance(t, datetime.datetime):
return t
elif isinstance(t, datetime.date):
return datetime.datetime(t.year, t.month, t.day)
elif isinstance(t, (int, float)):
return datetime.datetime.fromtimestamp(t)
elif isinstance(t, six.string_types):
return parser.parse(t)
else:
- raise
+ raise TypeError
except: # noqa
raise TypeError(
"time must be represented as either a timestamp (int,float), "
"a datetime.datetime or datetime.date object, "
"or an iso-8601 formatted string"
)
| Raise explicit exception on no type match | ## Code Before:
import datetime
from dateutil import parser
import six
def normalize_time(t):
try:
if isinstance(t, datetime.datetime):
return t
elif isinstance(t, datetime.date):
return datetime.datetime(t.year, t.month, t.day)
elif isinstance(t, (int, float)):
return datetime.datetime.fromtimestamp(t)
elif isinstance(t, six.string_types):
return parser.parse(t)
else:
raise
except: # noqa
raise TypeError(
"time must be represented as either a timestamp (int,float), "
"a datetime.datetime or datetime.date object, "
"or an iso-8601 formatted string"
)
## Instruction:
Raise explicit exception on no type match
## Code After:
import datetime
from dateutil import parser
import six
def normalize_time(t):
try:
if isinstance(t, datetime.datetime):
return t
elif isinstance(t, datetime.date):
return datetime.datetime(t.year, t.month, t.day)
elif isinstance(t, (int, float)):
return datetime.datetime.fromtimestamp(t)
elif isinstance(t, six.string_types):
return parser.parse(t)
else:
raise TypeError
except: # noqa
raise TypeError(
"time must be represented as either a timestamp (int,float), "
"a datetime.datetime or datetime.date object, "
"or an iso-8601 formatted string"
)
| import datetime
from dateutil import parser
import six
def normalize_time(t):
try:
if isinstance(t, datetime.datetime):
return t
elif isinstance(t, datetime.date):
return datetime.datetime(t.year, t.month, t.day)
elif isinstance(t, (int, float)):
return datetime.datetime.fromtimestamp(t)
elif isinstance(t, six.string_types):
return parser.parse(t)
else:
- raise
+ raise TypeError
? ++++++++++
except: # noqa
raise TypeError(
"time must be represented as either a timestamp (int,float), "
"a datetime.datetime or datetime.date object, "
"or an iso-8601 formatted string"
) |
6bcd2ffc67dfbb1265d4df1f69de8e8b45376889 | src/foremast/slacknotify/slack_notification.py | src/foremast/slacknotify/slack_notification.py | """Notify Slack channel."""
import time
from ..utils import get_properties, get_template, post_slack_message
class SlackNotification:
"""Post slack notification.
Inform users about infrastructure changes to prod* accounts.
"""
def __init__(self, app=None, env=None, prop_path=None):
self.info = {'app': app, 'env': env, 'properties': prop_path}
timestamp = time.strftime("%B %d, %Y %H:%M:%S %Z", time.gmtime())
self.info['timestamp'] = timestamp
self.settings = get_properties(self.info['properties'])
self.info['config_commit_short'] = self.settings['pipeline'][
'config_commit'][0:11]
def post_message(self):
"""Send templated message to **#deployments-{env}**."""
message = get_template(
template_file='slack-templates/pipeline-prepare-ran.j2',
info=self.info)
channel = '#deployments-{}'.format(self.info['env'].lower())
post_slack_message(message, channel)
def notify_slack_channel(self):
"""Post message to a defined Slack channel."""
if self.settings['pipeline']['notifications']['slack']:
post_slack_message(
message, self.settings['pipeline']['notifications']['slack'])
| """Notify Slack channel."""
import time
from ..utils import get_properties, get_template, post_slack_message
class SlackNotification:
"""Post slack notification.
Inform users about infrastructure changes to prod* accounts.
"""
def __init__(self, app=None, env=None, prop_path=None):
self.info = {'app': app, 'env': env, 'properties': prop_path}
timestamp = time.strftime("%B %d, %Y %H:%M:%S %Z", time.gmtime())
self.info['timestamp'] = timestamp
self.settings = get_properties(self.info['properties'])
self.info['config_commit_short'] = self.settings['pipeline'][
'config_commit'][0:11]
def post_message(self):
"""Send templated message to **#deployments-{env}**."""
message = get_template(
template_file='slack-templates/pipeline-prepare-ran.j2',
info=self.info)
channel = '#deployments-{}'.format(self.info['env'].lower())
post_slack_message(message, channel)
def notify_slack_channel(self):
"""Post message to a defined Slack channel."""
message = get_template(
template_file='slack-templates/pipeline-prepare-ran.j2',
info=self.info)
if self.settings['pipeline']['notifications']['slack']:
post_slack_message(
message, self.settings['pipeline']['notifications']['slack'])
| Resolve `message` variable missing error | fix: Resolve `message` variable missing error
| Python | apache-2.0 | gogoair/foremast,gogoair/foremast | """Notify Slack channel."""
import time
from ..utils import get_properties, get_template, post_slack_message
class SlackNotification:
"""Post slack notification.
Inform users about infrastructure changes to prod* accounts.
"""
def __init__(self, app=None, env=None, prop_path=None):
self.info = {'app': app, 'env': env, 'properties': prop_path}
timestamp = time.strftime("%B %d, %Y %H:%M:%S %Z", time.gmtime())
self.info['timestamp'] = timestamp
self.settings = get_properties(self.info['properties'])
self.info['config_commit_short'] = self.settings['pipeline'][
'config_commit'][0:11]
def post_message(self):
"""Send templated message to **#deployments-{env}**."""
message = get_template(
template_file='slack-templates/pipeline-prepare-ran.j2',
info=self.info)
channel = '#deployments-{}'.format(self.info['env'].lower())
post_slack_message(message, channel)
def notify_slack_channel(self):
"""Post message to a defined Slack channel."""
+ message = get_template(
+ template_file='slack-templates/pipeline-prepare-ran.j2',
+ info=self.info)
+
if self.settings['pipeline']['notifications']['slack']:
post_slack_message(
message, self.settings['pipeline']['notifications']['slack'])
| Resolve `message` variable missing error | ## Code Before:
"""Notify Slack channel."""
import time
from ..utils import get_properties, get_template, post_slack_message
class SlackNotification:
"""Post slack notification.
Inform users about infrastructure changes to prod* accounts.
"""
def __init__(self, app=None, env=None, prop_path=None):
self.info = {'app': app, 'env': env, 'properties': prop_path}
timestamp = time.strftime("%B %d, %Y %H:%M:%S %Z", time.gmtime())
self.info['timestamp'] = timestamp
self.settings = get_properties(self.info['properties'])
self.info['config_commit_short'] = self.settings['pipeline'][
'config_commit'][0:11]
def post_message(self):
"""Send templated message to **#deployments-{env}**."""
message = get_template(
template_file='slack-templates/pipeline-prepare-ran.j2',
info=self.info)
channel = '#deployments-{}'.format(self.info['env'].lower())
post_slack_message(message, channel)
def notify_slack_channel(self):
"""Post message to a defined Slack channel."""
if self.settings['pipeline']['notifications']['slack']:
post_slack_message(
message, self.settings['pipeline']['notifications']['slack'])
## Instruction:
Resolve `message` variable missing error
## Code After:
"""Notify Slack channel."""
import time
from ..utils import get_properties, get_template, post_slack_message
class SlackNotification:
"""Post slack notification.
Inform users about infrastructure changes to prod* accounts.
"""
def __init__(self, app=None, env=None, prop_path=None):
self.info = {'app': app, 'env': env, 'properties': prop_path}
timestamp = time.strftime("%B %d, %Y %H:%M:%S %Z", time.gmtime())
self.info['timestamp'] = timestamp
self.settings = get_properties(self.info['properties'])
self.info['config_commit_short'] = self.settings['pipeline'][
'config_commit'][0:11]
def post_message(self):
"""Send templated message to **#deployments-{env}**."""
message = get_template(
template_file='slack-templates/pipeline-prepare-ran.j2',
info=self.info)
channel = '#deployments-{}'.format(self.info['env'].lower())
post_slack_message(message, channel)
def notify_slack_channel(self):
"""Post message to a defined Slack channel."""
message = get_template(
template_file='slack-templates/pipeline-prepare-ran.j2',
info=self.info)
if self.settings['pipeline']['notifications']['slack']:
post_slack_message(
message, self.settings['pipeline']['notifications']['slack'])
| """Notify Slack channel."""
import time
from ..utils import get_properties, get_template, post_slack_message
class SlackNotification:
"""Post slack notification.
Inform users about infrastructure changes to prod* accounts.
"""
def __init__(self, app=None, env=None, prop_path=None):
self.info = {'app': app, 'env': env, 'properties': prop_path}
timestamp = time.strftime("%B %d, %Y %H:%M:%S %Z", time.gmtime())
self.info['timestamp'] = timestamp
self.settings = get_properties(self.info['properties'])
self.info['config_commit_short'] = self.settings['pipeline'][
'config_commit'][0:11]
def post_message(self):
"""Send templated message to **#deployments-{env}**."""
message = get_template(
template_file='slack-templates/pipeline-prepare-ran.j2',
info=self.info)
channel = '#deployments-{}'.format(self.info['env'].lower())
post_slack_message(message, channel)
def notify_slack_channel(self):
"""Post message to a defined Slack channel."""
+ message = get_template(
+ template_file='slack-templates/pipeline-prepare-ran.j2',
+ info=self.info)
+
if self.settings['pipeline']['notifications']['slack']:
post_slack_message(
message, self.settings['pipeline']['notifications']['slack']) |
ee7b5353c039d6e1d2aeabcb084aee79e07b71f8 | emoji/templatetags/emoji_tags.py | emoji/templatetags/emoji_tags.py | from django import template
from django.core.urlresolvers import reverse, NoReverseMatch
from django.template.defaultfilters import stringfilter
from django.utils.safestring import mark_safe
from emoji import Emoji
register = template.Library()
@register.filter(name='emoji_replace', is_safe=True)
@stringfilter
def emoji_replace(value):
return mark_safe(Emoji.replace(value))
@register.filter(name='emoji_replace_unicode', is_safe=True)
@stringfilter
def emoji_replace_unicode(value):
return mark_safe(Emoji.replace_unicode(value))
@register.filter(name='emoji_replace_html_entities', is_safe=True)
@stringfilter
def emoji_replace_html_entities(value):
return mark_safe(Emoji.replace_html_entities(value))
@register.simple_tag
def emoji_load():
try:
url = reverse('emoji:list.json')
except NoReverseMatch:
return ''
else:
return "Emoji.setDataUrl('{0}').load();".format(url)
| from django import template
from django.core.urlresolvers import reverse, NoReverseMatch
from django.template.defaultfilters import stringfilter
from django.utils.safestring import mark_safe, SafeData
from django.utils.html import escape
from emoji import Emoji
register = template.Library()
@register.filter(name='emoji_replace', is_safe=True, needs_autoescape=True)
@stringfilter
def emoji_replace(value, autoescape=None):
autoescape = autoescape and not isinstance(value, SafeData)
if autoescape:
value = escape(value)
return mark_safe(Emoji.replace(value))
@register.filter(name='emoji_replace_unicode', is_safe=True, needs_autoescape=True)
@stringfilter
def emoji_replace_unicode(value, autoescape=None):
autoescape = autoescape and not isinstance(value, SafeData)
if autoescape:
value = escape(value)
return mark_safe(Emoji.replace_unicode(value))
@register.filter(name='emoji_replace_html_entities',
is_safe=True, needs_autoescape=True)
@stringfilter
def emoji_replace_html_entities(value, autoescape=None):
autoescape = autoescape and not isinstance(value, SafeData)
if autoescape:
value = escape(value)
return mark_safe(Emoji.replace_html_entities(value))
@register.simple_tag
def emoji_load():
try:
url = reverse('emoji:list.json')
except NoReverseMatch:
return ''
else:
return "Emoji.setDataUrl('{0}').load();".format(url)
| Update the filters to escape the characters before replacing them. | Update the filters to escape the characters before replacing them.
This prevents the filters from allowing XSS attacks. This follows
the pattern used by django's linebreaksbr filter.
| Python | mit | gaqzi/django-emoji,gaqzi/django-emoji,gaqzi/django-emoji | from django import template
from django.core.urlresolvers import reverse, NoReverseMatch
from django.template.defaultfilters import stringfilter
- from django.utils.safestring import mark_safe
+ from django.utils.safestring import mark_safe, SafeData
+ from django.utils.html import escape
from emoji import Emoji
register = template.Library()
- @register.filter(name='emoji_replace', is_safe=True)
+ @register.filter(name='emoji_replace', is_safe=True, needs_autoescape=True)
@stringfilter
- def emoji_replace(value):
+ def emoji_replace(value, autoescape=None):
+ autoescape = autoescape and not isinstance(value, SafeData)
+ if autoescape:
+ value = escape(value)
return mark_safe(Emoji.replace(value))
- @register.filter(name='emoji_replace_unicode', is_safe=True)
+ @register.filter(name='emoji_replace_unicode', is_safe=True, needs_autoescape=True)
@stringfilter
- def emoji_replace_unicode(value):
+ def emoji_replace_unicode(value, autoescape=None):
+ autoescape = autoescape and not isinstance(value, SafeData)
+ if autoescape:
+ value = escape(value)
return mark_safe(Emoji.replace_unicode(value))
- @register.filter(name='emoji_replace_html_entities', is_safe=True)
+ @register.filter(name='emoji_replace_html_entities',
+ is_safe=True, needs_autoescape=True)
@stringfilter
- def emoji_replace_html_entities(value):
+ def emoji_replace_html_entities(value, autoescape=None):
+ autoescape = autoescape and not isinstance(value, SafeData)
+ if autoescape:
+ value = escape(value)
return mark_safe(Emoji.replace_html_entities(value))
@register.simple_tag
def emoji_load():
try:
url = reverse('emoji:list.json')
except NoReverseMatch:
return ''
else:
return "Emoji.setDataUrl('{0}').load();".format(url)
| Update the filters to escape the characters before replacing them. | ## Code Before:
from django import template
from django.core.urlresolvers import reverse, NoReverseMatch
from django.template.defaultfilters import stringfilter
from django.utils.safestring import mark_safe
from emoji import Emoji
register = template.Library()
@register.filter(name='emoji_replace', is_safe=True)
@stringfilter
def emoji_replace(value):
return mark_safe(Emoji.replace(value))
@register.filter(name='emoji_replace_unicode', is_safe=True)
@stringfilter
def emoji_replace_unicode(value):
return mark_safe(Emoji.replace_unicode(value))
@register.filter(name='emoji_replace_html_entities', is_safe=True)
@stringfilter
def emoji_replace_html_entities(value):
return mark_safe(Emoji.replace_html_entities(value))
@register.simple_tag
def emoji_load():
try:
url = reverse('emoji:list.json')
except NoReverseMatch:
return ''
else:
return "Emoji.setDataUrl('{0}').load();".format(url)
## Instruction:
Update the filters to escape the characters before replacing them.
## Code After:
from django import template
from django.core.urlresolvers import reverse, NoReverseMatch
from django.template.defaultfilters import stringfilter
from django.utils.safestring import mark_safe, SafeData
from django.utils.html import escape
from emoji import Emoji
register = template.Library()
@register.filter(name='emoji_replace', is_safe=True, needs_autoescape=True)
@stringfilter
def emoji_replace(value, autoescape=None):
autoescape = autoescape and not isinstance(value, SafeData)
if autoescape:
value = escape(value)
return mark_safe(Emoji.replace(value))
@register.filter(name='emoji_replace_unicode', is_safe=True, needs_autoescape=True)
@stringfilter
def emoji_replace_unicode(value, autoescape=None):
autoescape = autoescape and not isinstance(value, SafeData)
if autoescape:
value = escape(value)
return mark_safe(Emoji.replace_unicode(value))
@register.filter(name='emoji_replace_html_entities',
is_safe=True, needs_autoescape=True)
@stringfilter
def emoji_replace_html_entities(value, autoescape=None):
autoescape = autoescape and not isinstance(value, SafeData)
if autoescape:
value = escape(value)
return mark_safe(Emoji.replace_html_entities(value))
@register.simple_tag
def emoji_load():
try:
url = reverse('emoji:list.json')
except NoReverseMatch:
return ''
else:
return "Emoji.setDataUrl('{0}').load();".format(url)
| from django import template
from django.core.urlresolvers import reverse, NoReverseMatch
from django.template.defaultfilters import stringfilter
- from django.utils.safestring import mark_safe
+ from django.utils.safestring import mark_safe, SafeData
? ++++++++++
+ from django.utils.html import escape
from emoji import Emoji
register = template.Library()
- @register.filter(name='emoji_replace', is_safe=True)
+ @register.filter(name='emoji_replace', is_safe=True, needs_autoescape=True)
? +++++++++++++++++++++++
@stringfilter
- def emoji_replace(value):
+ def emoji_replace(value, autoescape=None):
+ autoescape = autoescape and not isinstance(value, SafeData)
+ if autoescape:
+ value = escape(value)
return mark_safe(Emoji.replace(value))
- @register.filter(name='emoji_replace_unicode', is_safe=True)
+ @register.filter(name='emoji_replace_unicode', is_safe=True, needs_autoescape=True)
? +++++++++++++++++++++++
@stringfilter
- def emoji_replace_unicode(value):
+ def emoji_replace_unicode(value, autoescape=None):
? +++++++++++++++++
+ autoescape = autoescape and not isinstance(value, SafeData)
+ if autoescape:
+ value = escape(value)
return mark_safe(Emoji.replace_unicode(value))
- @register.filter(name='emoji_replace_html_entities', is_safe=True)
? --------------
+ @register.filter(name='emoji_replace_html_entities',
+ is_safe=True, needs_autoescape=True)
@stringfilter
- def emoji_replace_html_entities(value):
+ def emoji_replace_html_entities(value, autoescape=None):
? +++++++++++++++++
+ autoescape = autoescape and not isinstance(value, SafeData)
+ if autoescape:
+ value = escape(value)
return mark_safe(Emoji.replace_html_entities(value))
@register.simple_tag
def emoji_load():
try:
url = reverse('emoji:list.json')
except NoReverseMatch:
return ''
else:
return "Emoji.setDataUrl('{0}').load();".format(url) |
261cb5aecc52d07b10d826e8b22d17817d1c3529 | web/backend/backend_django/apps/capacity/management/commands/importpath.py | web/backend/backend_django/apps/capacity/management/commands/importpath.py | from __future__ import unicode_literals
from optparse import make_option
import os
from csv import reader
from codecs import BOM_UTF8
import pickle
from django.utils.six import string_types, PY3
from django.core.management.base import BaseCommand, CommandError
from ...models import Path
class Command(BaseCommand):
help = 'Encode txt files in ascii format'
def add_arguments(self, parser):
parser.add_argument('--input', '-i', help='input file as pickle')
def handle(self, *args, **options):
i = options['input']
if not os.path.isfile(i):
raise CommandError
trips = pickle.load(open(i, "rb"))
print(len(trips))
for k, path in trips.items():
trip_id = k[0]
stop_id = k[1]
try:
_, created = Path.objects.get_or_create(
trip_id = int(trip_id),
stop_id = int(stop_id),
path = str(path)
)
pass
except Exception as e:
self.stdout.write("Error with row {} {} : {}".format(k, path, e))
self.stdout.write("Done") | from __future__ import unicode_literals
from optparse import make_option
import os
from csv import reader
from codecs import BOM_UTF8
import pickle
from django.utils.six import string_types, PY3
from django.core.management.base import BaseCommand, CommandError
from ...models import Path
class Command(BaseCommand):
help = 'Encode txt files in ascii format'
def add_arguments(self, parser):
parser.add_argument('--input', '-i', help='input file as pickle')
def handle(self, *args, **options):
i = options['input']
if not os.path.isfile(i):
raise CommandError
trips = pickle.load(open(i, "rb"))
print(len(trips))
i = 0
for k, path in trips.items():
trip_id = k[0]
stop_id = k[1]
if i%1000==0: print(i)
try:
_, created = Path.objects.get_or_create(
trip_id = int(trip_id),
stop_id = int(stop_id),
path = str(path)
)
pass
except Exception as e:
self.stdout.write("Error with row {} {} : {}".format(k, path, e))
i = i+1
self.stdout.write("Done") | Update import path method to reflect behaviour | Update import path method to reflect behaviour
| Python | apache-2.0 | tOverney/ADA-Project,tOverney/ADA-Project,tOverney/ADA-Project | from __future__ import unicode_literals
from optparse import make_option
import os
from csv import reader
from codecs import BOM_UTF8
import pickle
from django.utils.six import string_types, PY3
from django.core.management.base import BaseCommand, CommandError
from ...models import Path
class Command(BaseCommand):
help = 'Encode txt files in ascii format'
def add_arguments(self, parser):
parser.add_argument('--input', '-i', help='input file as pickle')
def handle(self, *args, **options):
i = options['input']
if not os.path.isfile(i):
raise CommandError
trips = pickle.load(open(i, "rb"))
print(len(trips))
-
+ i = 0
for k, path in trips.items():
trip_id = k[0]
stop_id = k[1]
+
+ if i%1000==0: print(i)
try:
_, created = Path.objects.get_or_create(
trip_id = int(trip_id),
stop_id = int(stop_id),
path = str(path)
)
pass
except Exception as e:
self.stdout.write("Error with row {} {} : {}".format(k, path, e))
+ i = i+1
+
self.stdout.write("Done") | Update import path method to reflect behaviour | ## Code Before:
from __future__ import unicode_literals
from optparse import make_option
import os
from csv import reader
from codecs import BOM_UTF8
import pickle
from django.utils.six import string_types, PY3
from django.core.management.base import BaseCommand, CommandError
from ...models import Path
class Command(BaseCommand):
help = 'Encode txt files in ascii format'
def add_arguments(self, parser):
parser.add_argument('--input', '-i', help='input file as pickle')
def handle(self, *args, **options):
i = options['input']
if not os.path.isfile(i):
raise CommandError
trips = pickle.load(open(i, "rb"))
print(len(trips))
for k, path in trips.items():
trip_id = k[0]
stop_id = k[1]
try:
_, created = Path.objects.get_or_create(
trip_id = int(trip_id),
stop_id = int(stop_id),
path = str(path)
)
pass
except Exception as e:
self.stdout.write("Error with row {} {} : {}".format(k, path, e))
self.stdout.write("Done")
## Instruction:
Update import path method to reflect behaviour
## Code After:
from __future__ import unicode_literals
from optparse import make_option
import os
from csv import reader
from codecs import BOM_UTF8
import pickle
from django.utils.six import string_types, PY3
from django.core.management.base import BaseCommand, CommandError
from ...models import Path
class Command(BaseCommand):
help = 'Encode txt files in ascii format'
def add_arguments(self, parser):
parser.add_argument('--input', '-i', help='input file as pickle')
def handle(self, *args, **options):
i = options['input']
if not os.path.isfile(i):
raise CommandError
trips = pickle.load(open(i, "rb"))
print(len(trips))
i = 0
for k, path in trips.items():
trip_id = k[0]
stop_id = k[1]
if i%1000==0: print(i)
try:
_, created = Path.objects.get_or_create(
trip_id = int(trip_id),
stop_id = int(stop_id),
path = str(path)
)
pass
except Exception as e:
self.stdout.write("Error with row {} {} : {}".format(k, path, e))
i = i+1
self.stdout.write("Done") | from __future__ import unicode_literals
from optparse import make_option
import os
from csv import reader
from codecs import BOM_UTF8
import pickle
from django.utils.six import string_types, PY3
from django.core.management.base import BaseCommand, CommandError
from ...models import Path
class Command(BaseCommand):
help = 'Encode txt files in ascii format'
def add_arguments(self, parser):
parser.add_argument('--input', '-i', help='input file as pickle')
def handle(self, *args, **options):
i = options['input']
if not os.path.isfile(i):
raise CommandError
trips = pickle.load(open(i, "rb"))
print(len(trips))
-
+ i = 0
for k, path in trips.items():
trip_id = k[0]
stop_id = k[1]
+
+ if i%1000==0: print(i)
try:
_, created = Path.objects.get_or_create(
trip_id = int(trip_id),
stop_id = int(stop_id),
path = str(path)
)
pass
except Exception as e:
self.stdout.write("Error with row {} {} : {}".format(k, path, e))
+ i = i+1
+
self.stdout.write("Done") |
7b5850d1b89d34ff9a60c3862d18691961c86656 | poisson/tests/test_irf.py | poisson/tests/test_irf.py | from numpy.testing import assert_almost_equal, assert_array_less
import numpy as np
from poisson import BmiPoisson
def test_grid_initialize():
model = BmiPoisson()
model.initialize()
assert_almost_equal(model.get_current_time(), 0.)
assert_array_less(model.get_value('land_surface__elevation'), 1.)
assert_array_less(0., model.get_value('land_surface__elevation'))
def test_update():
model = BmiPoisson()
model.initialize()
for time in xrange(10):
model.update()
assert_almost_equal(model.get_current_time(), time + 1.)
def test_update_until():
model = BmiPoisson()
model.initialize()
model.update_until(10.1)
assert_almost_equal(model.get_current_time(), 10.1)
def test_finalize():
model = BmiPoisson()
model.initialize()
model.update()
model.finalize()
| from nose.tools import assert_equal
from numpy.testing import assert_almost_equal, assert_array_less
import numpy as np
from poisson import BmiPoisson
def test_initialize_defaults():
model = BmiPoisson()
model.initialize()
assert_almost_equal(model.get_current_time(), 0.)
assert_array_less(model.get_value('land_surface__elevation'), 1.)
assert_array_less(0., model.get_value('land_surface__elevation'))
def test_initialize_from_file_like():
from StringIO import StringIO
import yaml
config = StringIO(yaml.dump({'shape': (7, 5)}))
model = BmiPoisson()
model.initialize(config)
assert_equal(model.get_grid_shape('land_surface__elevation'), (7, 5))
def test_initialize_from_file():
import os
import yaml
import tempfile
with tempfile.NamedTemporaryFile('w', delete=False) as fp:
fp.write(yaml.dump({'shape': (7, 5)}))
name = fp.name
model = BmiPoisson()
model.initialize(name)
os.remove(name)
assert_equal(model.get_grid_shape('land_surface__elevation'), (7, 5))
def test_update():
model = BmiPoisson()
model.initialize()
for time in xrange(10):
model.update()
assert_almost_equal(model.get_current_time(), time + 1.)
def test_update_until():
model = BmiPoisson()
model.initialize()
model.update_until(10.1)
assert_almost_equal(model.get_current_time(), 10.1)
def test_finalize():
model = BmiPoisson()
model.initialize()
model.update()
model.finalize()
| Test initialize with filename and file-like. | Test initialize with filename and file-like.
| Python | mit | mperignon/bmi-delta,mperignon/bmi-STM,mperignon/bmi-STM,mperignon/bmi-delta | + from nose.tools import assert_equal
from numpy.testing import assert_almost_equal, assert_array_less
import numpy as np
from poisson import BmiPoisson
- def test_grid_initialize():
+ def test_initialize_defaults():
model = BmiPoisson()
model.initialize()
assert_almost_equal(model.get_current_time(), 0.)
assert_array_less(model.get_value('land_surface__elevation'), 1.)
assert_array_less(0., model.get_value('land_surface__elevation'))
+
+
+ def test_initialize_from_file_like():
+ from StringIO import StringIO
+ import yaml
+
+ config = StringIO(yaml.dump({'shape': (7, 5)}))
+ model = BmiPoisson()
+ model.initialize(config)
+
+ assert_equal(model.get_grid_shape('land_surface__elevation'), (7, 5))
+
+
+ def test_initialize_from_file():
+ import os
+ import yaml
+ import tempfile
+
+ with tempfile.NamedTemporaryFile('w', delete=False) as fp:
+ fp.write(yaml.dump({'shape': (7, 5)}))
+ name = fp.name
+
+ model = BmiPoisson()
+ model.initialize(name)
+
+ os.remove(name)
+
+ assert_equal(model.get_grid_shape('land_surface__elevation'), (7, 5))
def test_update():
model = BmiPoisson()
model.initialize()
for time in xrange(10):
model.update()
assert_almost_equal(model.get_current_time(), time + 1.)
def test_update_until():
model = BmiPoisson()
model.initialize()
model.update_until(10.1)
assert_almost_equal(model.get_current_time(), 10.1)
def test_finalize():
model = BmiPoisson()
model.initialize()
model.update()
model.finalize()
| Test initialize with filename and file-like. | ## Code Before:
from numpy.testing import assert_almost_equal, assert_array_less
import numpy as np
from poisson import BmiPoisson
def test_grid_initialize():
model = BmiPoisson()
model.initialize()
assert_almost_equal(model.get_current_time(), 0.)
assert_array_less(model.get_value('land_surface__elevation'), 1.)
assert_array_less(0., model.get_value('land_surface__elevation'))
def test_update():
model = BmiPoisson()
model.initialize()
for time in xrange(10):
model.update()
assert_almost_equal(model.get_current_time(), time + 1.)
def test_update_until():
model = BmiPoisson()
model.initialize()
model.update_until(10.1)
assert_almost_equal(model.get_current_time(), 10.1)
def test_finalize():
model = BmiPoisson()
model.initialize()
model.update()
model.finalize()
## Instruction:
Test initialize with filename and file-like.
## Code After:
from nose.tools import assert_equal
from numpy.testing import assert_almost_equal, assert_array_less
import numpy as np
from poisson import BmiPoisson
def test_initialize_defaults():
model = BmiPoisson()
model.initialize()
assert_almost_equal(model.get_current_time(), 0.)
assert_array_less(model.get_value('land_surface__elevation'), 1.)
assert_array_less(0., model.get_value('land_surface__elevation'))
def test_initialize_from_file_like():
from StringIO import StringIO
import yaml
config = StringIO(yaml.dump({'shape': (7, 5)}))
model = BmiPoisson()
model.initialize(config)
assert_equal(model.get_grid_shape('land_surface__elevation'), (7, 5))
def test_initialize_from_file():
import os
import yaml
import tempfile
with tempfile.NamedTemporaryFile('w', delete=False) as fp:
fp.write(yaml.dump({'shape': (7, 5)}))
name = fp.name
model = BmiPoisson()
model.initialize(name)
os.remove(name)
assert_equal(model.get_grid_shape('land_surface__elevation'), (7, 5))
def test_update():
model = BmiPoisson()
model.initialize()
for time in xrange(10):
model.update()
assert_almost_equal(model.get_current_time(), time + 1.)
def test_update_until():
model = BmiPoisson()
model.initialize()
model.update_until(10.1)
assert_almost_equal(model.get_current_time(), 10.1)
def test_finalize():
model = BmiPoisson()
model.initialize()
model.update()
model.finalize()
| + from nose.tools import assert_equal
from numpy.testing import assert_almost_equal, assert_array_less
import numpy as np
from poisson import BmiPoisson
- def test_grid_initialize():
? -----
+ def test_initialize_defaults():
? +++++++++
model = BmiPoisson()
model.initialize()
assert_almost_equal(model.get_current_time(), 0.)
assert_array_less(model.get_value('land_surface__elevation'), 1.)
assert_array_less(0., model.get_value('land_surface__elevation'))
+
+
+ def test_initialize_from_file_like():
+ from StringIO import StringIO
+ import yaml
+
+ config = StringIO(yaml.dump({'shape': (7, 5)}))
+ model = BmiPoisson()
+ model.initialize(config)
+
+ assert_equal(model.get_grid_shape('land_surface__elevation'), (7, 5))
+
+
+ def test_initialize_from_file():
+ import os
+ import yaml
+ import tempfile
+
+ with tempfile.NamedTemporaryFile('w', delete=False) as fp:
+ fp.write(yaml.dump({'shape': (7, 5)}))
+ name = fp.name
+
+ model = BmiPoisson()
+ model.initialize(name)
+
+ os.remove(name)
+
+ assert_equal(model.get_grid_shape('land_surface__elevation'), (7, 5))
def test_update():
model = BmiPoisson()
model.initialize()
for time in xrange(10):
model.update()
assert_almost_equal(model.get_current_time(), time + 1.)
def test_update_until():
model = BmiPoisson()
model.initialize()
model.update_until(10.1)
assert_almost_equal(model.get_current_time(), 10.1)
def test_finalize():
model = BmiPoisson()
model.initialize()
model.update()
model.finalize() |
94b757e2132c1fe59cd2c80d7d7b29aad125d471 | tests/graph_test.py | tests/graph_test.py | from mythril.analysis.callgraph import generate_graph
from mythril.analysis.symbolic import SymExecWrapper
from mythril.ethereum import util
from mythril.solidity.soliditycontract import EVMContract
from tests import (
BaseTestCase,
TESTDATA_INPUTS,
TESTDATA_OUTPUTS_EXPECTED,
TESTDATA_OUTPUTS_CURRENT,
)
import re
class GraphTest(BaseTestCase):
def test_generate_graph(self):
for input_file in TESTDATA_INPUTS.iterdir():
output_expected = TESTDATA_OUTPUTS_EXPECTED / (
input_file.name + ".graph.html"
)
output_current = TESTDATA_OUTPUTS_CURRENT / (
input_file.name + ".graph.html"
)
contract = EVMContract(input_file.read_text())
sym = SymExecWrapper(
contract,
address=(util.get_indexed_address(0)),
strategy="dfs",
transaction_count=1,
)
html = generate_graph(sym)
output_current.write_text(html)
lines_expected = re.findall(
r"'label': '.*'", str(output_current.read_text())
)
lines_found = re.findall(r"'label': '.*'", str(output_current.read_text()))
if not (lines_expected == lines_found):
self.found_changed_files(input_file, output_expected, output_current)
self.assert_and_show_changed_files()
| from mythril.analysis.callgraph import generate_graph
from mythril.analysis.symbolic import SymExecWrapper
from mythril.ethereum import util
from mythril.solidity.soliditycontract import EVMContract
from tests import (
BaseTestCase,
TESTDATA_INPUTS,
TESTDATA_OUTPUTS_EXPECTED,
TESTDATA_OUTPUTS_CURRENT,
)
import re
class GraphTest(BaseTestCase):
def test_generate_graph(self):
for input_file in TESTDATA_INPUTS.iterdir():
output_expected = TESTDATA_OUTPUTS_EXPECTED / (
input_file.name + ".graph.html"
)
output_current = TESTDATA_OUTPUTS_CURRENT / (
input_file.name + ".graph.html"
)
contract = EVMContract(input_file.read_text())
sym = SymExecWrapper(
contract,
address=(util.get_indexed_address(0)),
strategy="dfs",
transaction_count=1,
execution_timeout=5,
)
html = generate_graph(sym)
output_current.write_text(html)
lines_expected = re.findall(
r"'label': '.*'", str(output_current.read_text())
)
lines_found = re.findall(r"'label': '.*'", str(output_current.read_text()))
if not (lines_expected == lines_found):
self.found_changed_files(input_file, output_expected, output_current)
self.assert_and_show_changed_files()
| Set execution timeout to be lower | Set execution timeout to be lower
Otherwise the test would be much slower
| Python | mit | b-mueller/mythril,b-mueller/mythril,b-mueller/mythril,b-mueller/mythril | from mythril.analysis.callgraph import generate_graph
from mythril.analysis.symbolic import SymExecWrapper
from mythril.ethereum import util
from mythril.solidity.soliditycontract import EVMContract
from tests import (
BaseTestCase,
TESTDATA_INPUTS,
TESTDATA_OUTPUTS_EXPECTED,
TESTDATA_OUTPUTS_CURRENT,
)
import re
class GraphTest(BaseTestCase):
def test_generate_graph(self):
for input_file in TESTDATA_INPUTS.iterdir():
output_expected = TESTDATA_OUTPUTS_EXPECTED / (
input_file.name + ".graph.html"
)
output_current = TESTDATA_OUTPUTS_CURRENT / (
input_file.name + ".graph.html"
)
contract = EVMContract(input_file.read_text())
sym = SymExecWrapper(
contract,
address=(util.get_indexed_address(0)),
strategy="dfs",
transaction_count=1,
+ execution_timeout=5,
)
html = generate_graph(sym)
output_current.write_text(html)
lines_expected = re.findall(
r"'label': '.*'", str(output_current.read_text())
)
lines_found = re.findall(r"'label': '.*'", str(output_current.read_text()))
if not (lines_expected == lines_found):
self.found_changed_files(input_file, output_expected, output_current)
self.assert_and_show_changed_files()
| Set execution timeout to be lower | ## Code Before:
from mythril.analysis.callgraph import generate_graph
from mythril.analysis.symbolic import SymExecWrapper
from mythril.ethereum import util
from mythril.solidity.soliditycontract import EVMContract
from tests import (
BaseTestCase,
TESTDATA_INPUTS,
TESTDATA_OUTPUTS_EXPECTED,
TESTDATA_OUTPUTS_CURRENT,
)
import re
class GraphTest(BaseTestCase):
def test_generate_graph(self):
for input_file in TESTDATA_INPUTS.iterdir():
output_expected = TESTDATA_OUTPUTS_EXPECTED / (
input_file.name + ".graph.html"
)
output_current = TESTDATA_OUTPUTS_CURRENT / (
input_file.name + ".graph.html"
)
contract = EVMContract(input_file.read_text())
sym = SymExecWrapper(
contract,
address=(util.get_indexed_address(0)),
strategy="dfs",
transaction_count=1,
)
html = generate_graph(sym)
output_current.write_text(html)
lines_expected = re.findall(
r"'label': '.*'", str(output_current.read_text())
)
lines_found = re.findall(r"'label': '.*'", str(output_current.read_text()))
if not (lines_expected == lines_found):
self.found_changed_files(input_file, output_expected, output_current)
self.assert_and_show_changed_files()
## Instruction:
Set execution timeout to be lower
## Code After:
from mythril.analysis.callgraph import generate_graph
from mythril.analysis.symbolic import SymExecWrapper
from mythril.ethereum import util
from mythril.solidity.soliditycontract import EVMContract
from tests import (
BaseTestCase,
TESTDATA_INPUTS,
TESTDATA_OUTPUTS_EXPECTED,
TESTDATA_OUTPUTS_CURRENT,
)
import re
class GraphTest(BaseTestCase):
def test_generate_graph(self):
for input_file in TESTDATA_INPUTS.iterdir():
output_expected = TESTDATA_OUTPUTS_EXPECTED / (
input_file.name + ".graph.html"
)
output_current = TESTDATA_OUTPUTS_CURRENT / (
input_file.name + ".graph.html"
)
contract = EVMContract(input_file.read_text())
sym = SymExecWrapper(
contract,
address=(util.get_indexed_address(0)),
strategy="dfs",
transaction_count=1,
execution_timeout=5,
)
html = generate_graph(sym)
output_current.write_text(html)
lines_expected = re.findall(
r"'label': '.*'", str(output_current.read_text())
)
lines_found = re.findall(r"'label': '.*'", str(output_current.read_text()))
if not (lines_expected == lines_found):
self.found_changed_files(input_file, output_expected, output_current)
self.assert_and_show_changed_files()
| from mythril.analysis.callgraph import generate_graph
from mythril.analysis.symbolic import SymExecWrapper
from mythril.ethereum import util
from mythril.solidity.soliditycontract import EVMContract
from tests import (
BaseTestCase,
TESTDATA_INPUTS,
TESTDATA_OUTPUTS_EXPECTED,
TESTDATA_OUTPUTS_CURRENT,
)
import re
class GraphTest(BaseTestCase):
def test_generate_graph(self):
for input_file in TESTDATA_INPUTS.iterdir():
output_expected = TESTDATA_OUTPUTS_EXPECTED / (
input_file.name + ".graph.html"
)
output_current = TESTDATA_OUTPUTS_CURRENT / (
input_file.name + ".graph.html"
)
contract = EVMContract(input_file.read_text())
sym = SymExecWrapper(
contract,
address=(util.get_indexed_address(0)),
strategy="dfs",
transaction_count=1,
+ execution_timeout=5,
)
html = generate_graph(sym)
output_current.write_text(html)
lines_expected = re.findall(
r"'label': '.*'", str(output_current.read_text())
)
lines_found = re.findall(r"'label': '.*'", str(output_current.read_text()))
if not (lines_expected == lines_found):
self.found_changed_files(input_file, output_expected, output_current)
self.assert_and_show_changed_files() |
512ca99144da537da61e7437d17782e5a95addb9 | S3utility/s3_sqs_message.py | S3utility/s3_sqs_message.py | from boto.sqs.message import Message
import json
from s3_notification_info import S3NotificationInfo
class S3SQSMessage(Message):
def __init__(self, queue=None, body='', xml_attrs=None):
Message.__init__(self, queue, body)
self.payload = None
self.notification_type = 'S3Info'
def event_name(self):
return self.payload['Records'][0]['eventName']
def event_time(self):
return self.payload['Records'][0]['eventTime']
def bucket_name(self):
return self.payload['Records'][0]['s3']['bucket']['name']
def file_name(self):
return self.payload['Records'][0]['s3']['object']['key']
def file_etag(self):
return self.payload['Records'][0]['s3']['object']['eTag']
def file_size(self):
return self.payload['Records'][0]['s3']['object']['size']
def set_body(self, body):
"""
Override set_body to construct json payload
Note Boto JSONMessage seemed to have encoding issues with S3 notification messages
"""
if body is not None and len(body) > 0:
self.payload = json.loads(body)
if body and 'Records' in self.payload.keys():
self.notification_type = 'S3Event'
super(Message, self).set_body(body)
| from boto.sqs.message import Message
import json
from s3_notification_info import S3NotificationInfo
class S3SQSMessage(Message):
def __init__(self, queue=None, body='', xml_attrs=None):
Message.__init__(self, queue, body)
self.payload = None
self.notification_type = 'S3Info'
def event_name(self):
return self.payload['Records'][0]['eventName']
def event_time(self):
return self.payload['Records'][0]['eventTime']
def bucket_name(self):
return self.payload['Records'][0]['s3']['bucket']['name']
def file_name(self):
return self.payload['Records'][0]['s3']['object']['key']
def file_etag(self):
if 'eTag' in self.payload['Records'][0]['s3']['object']:
return self.payload['Records'][0]['s3']['object']['eTag']
else:
return None
def file_size(self):
return self.payload['Records'][0]['s3']['object']['size']
def set_body(self, body):
"""
Override set_body to construct json payload
Note Boto JSONMessage seemed to have encoding issues with S3 notification messages
"""
if body is not None and len(body) > 0:
self.payload = json.loads(body)
if body and 'Records' in self.payload.keys():
self.notification_type = 'S3Event'
super(Message, self).set_body(body)
| Tweak for when SQS message is missing the eTag from a bucket notification. | Tweak for when SQS message is missing the eTag from a bucket notification.
| Python | mit | gnott/elife-bot,gnott/elife-bot,jhroot/elife-bot,jhroot/elife-bot,gnott/elife-bot,jhroot/elife-bot | from boto.sqs.message import Message
import json
from s3_notification_info import S3NotificationInfo
class S3SQSMessage(Message):
def __init__(self, queue=None, body='', xml_attrs=None):
Message.__init__(self, queue, body)
self.payload = None
self.notification_type = 'S3Info'
def event_name(self):
return self.payload['Records'][0]['eventName']
def event_time(self):
return self.payload['Records'][0]['eventTime']
def bucket_name(self):
return self.payload['Records'][0]['s3']['bucket']['name']
def file_name(self):
return self.payload['Records'][0]['s3']['object']['key']
def file_etag(self):
+ if 'eTag' in self.payload['Records'][0]['s3']['object']:
- return self.payload['Records'][0]['s3']['object']['eTag']
+ return self.payload['Records'][0]['s3']['object']['eTag']
+ else:
+ return None
def file_size(self):
return self.payload['Records'][0]['s3']['object']['size']
def set_body(self, body):
"""
Override set_body to construct json payload
Note Boto JSONMessage seemed to have encoding issues with S3 notification messages
"""
if body is not None and len(body) > 0:
self.payload = json.loads(body)
if body and 'Records' in self.payload.keys():
self.notification_type = 'S3Event'
super(Message, self).set_body(body)
| Tweak for when SQS message is missing the eTag from a bucket notification. | ## Code Before:
from boto.sqs.message import Message
import json
from s3_notification_info import S3NotificationInfo
class S3SQSMessage(Message):
def __init__(self, queue=None, body='', xml_attrs=None):
Message.__init__(self, queue, body)
self.payload = None
self.notification_type = 'S3Info'
def event_name(self):
return self.payload['Records'][0]['eventName']
def event_time(self):
return self.payload['Records'][0]['eventTime']
def bucket_name(self):
return self.payload['Records'][0]['s3']['bucket']['name']
def file_name(self):
return self.payload['Records'][0]['s3']['object']['key']
def file_etag(self):
return self.payload['Records'][0]['s3']['object']['eTag']
def file_size(self):
return self.payload['Records'][0]['s3']['object']['size']
def set_body(self, body):
"""
Override set_body to construct json payload
Note Boto JSONMessage seemed to have encoding issues with S3 notification messages
"""
if body is not None and len(body) > 0:
self.payload = json.loads(body)
if body and 'Records' in self.payload.keys():
self.notification_type = 'S3Event'
super(Message, self).set_body(body)
## Instruction:
Tweak for when SQS message is missing the eTag from a bucket notification.
## Code After:
from boto.sqs.message import Message
import json
from s3_notification_info import S3NotificationInfo
class S3SQSMessage(Message):
def __init__(self, queue=None, body='', xml_attrs=None):
Message.__init__(self, queue, body)
self.payload = None
self.notification_type = 'S3Info'
def event_name(self):
return self.payload['Records'][0]['eventName']
def event_time(self):
return self.payload['Records'][0]['eventTime']
def bucket_name(self):
return self.payload['Records'][0]['s3']['bucket']['name']
def file_name(self):
return self.payload['Records'][0]['s3']['object']['key']
def file_etag(self):
if 'eTag' in self.payload['Records'][0]['s3']['object']:
return self.payload['Records'][0]['s3']['object']['eTag']
else:
return None
def file_size(self):
return self.payload['Records'][0]['s3']['object']['size']
def set_body(self, body):
"""
Override set_body to construct json payload
Note Boto JSONMessage seemed to have encoding issues with S3 notification messages
"""
if body is not None and len(body) > 0:
self.payload = json.loads(body)
if body and 'Records' in self.payload.keys():
self.notification_type = 'S3Event'
super(Message, self).set_body(body)
| from boto.sqs.message import Message
import json
from s3_notification_info import S3NotificationInfo
class S3SQSMessage(Message):
def __init__(self, queue=None, body='', xml_attrs=None):
Message.__init__(self, queue, body)
self.payload = None
self.notification_type = 'S3Info'
def event_name(self):
return self.payload['Records'][0]['eventName']
def event_time(self):
return self.payload['Records'][0]['eventTime']
def bucket_name(self):
return self.payload['Records'][0]['s3']['bucket']['name']
def file_name(self):
return self.payload['Records'][0]['s3']['object']['key']
def file_etag(self):
+ if 'eTag' in self.payload['Records'][0]['s3']['object']:
- return self.payload['Records'][0]['s3']['object']['eTag']
+ return self.payload['Records'][0]['s3']['object']['eTag']
? ++++
+ else:
+ return None
def file_size(self):
return self.payload['Records'][0]['s3']['object']['size']
def set_body(self, body):
"""
Override set_body to construct json payload
Note Boto JSONMessage seemed to have encoding issues with S3 notification messages
"""
if body is not None and len(body) > 0:
self.payload = json.loads(body)
if body and 'Records' in self.payload.keys():
self.notification_type = 'S3Event'
super(Message, self).set_body(body) |
87c861f6ed0e73e21983edc3add35954b9f0def5 | apps/configuration/fields.py | apps/configuration/fields.py | import unicodedata
from django.forms import fields
class XMLCompatCharField(fields.CharField):
"""
Strip 'control characters', as XML 1.0 does not allow them and the API may
return data in XML.
"""
def to_python(self, value):
value = super().to_python(value=value)
return self.remove_control_characters(value)
@staticmethod
def remove_control_characters(str):
return "".join(ch for ch in str if unicodedata.category(ch)[0] != "C")
| import unicodedata
from django.forms import fields
class XMLCompatCharField(fields.CharField):
"""
Strip 'control characters', as XML 1.0 does not allow them and the API may
return data in XML.
"""
def to_python(self, value):
value = super().to_python(value=value)
return self.remove_control_characters(value)
@staticmethod
def remove_control_characters(input):
valid_chars = ['\n', '\r']
return "".join(ch for ch in input if
unicodedata.category(ch)[0] != "C" or ch in valid_chars)
| Allow linebreaks textareas (should be valid in XML) | Allow linebreaks textareas (should be valid in XML)
| Python | apache-2.0 | CDE-UNIBE/qcat,CDE-UNIBE/qcat,CDE-UNIBE/qcat,CDE-UNIBE/qcat | import unicodedata
from django.forms import fields
class XMLCompatCharField(fields.CharField):
"""
Strip 'control characters', as XML 1.0 does not allow them and the API may
return data in XML.
"""
def to_python(self, value):
value = super().to_python(value=value)
return self.remove_control_characters(value)
@staticmethod
- def remove_control_characters(str):
+ def remove_control_characters(input):
- return "".join(ch for ch in str if unicodedata.category(ch)[0] != "C")
+ valid_chars = ['\n', '\r']
+ return "".join(ch for ch in input if
+ unicodedata.category(ch)[0] != "C" or ch in valid_chars)
| Allow linebreaks textareas (should be valid in XML) | ## Code Before:
import unicodedata
from django.forms import fields
class XMLCompatCharField(fields.CharField):
"""
Strip 'control characters', as XML 1.0 does not allow them and the API may
return data in XML.
"""
def to_python(self, value):
value = super().to_python(value=value)
return self.remove_control_characters(value)
@staticmethod
def remove_control_characters(str):
return "".join(ch for ch in str if unicodedata.category(ch)[0] != "C")
## Instruction:
Allow linebreaks textareas (should be valid in XML)
## Code After:
import unicodedata
from django.forms import fields
class XMLCompatCharField(fields.CharField):
"""
Strip 'control characters', as XML 1.0 does not allow them and the API may
return data in XML.
"""
def to_python(self, value):
value = super().to_python(value=value)
return self.remove_control_characters(value)
@staticmethod
def remove_control_characters(input):
valid_chars = ['\n', '\r']
return "".join(ch for ch in input if
unicodedata.category(ch)[0] != "C" or ch in valid_chars)
| import unicodedata
from django.forms import fields
class XMLCompatCharField(fields.CharField):
"""
Strip 'control characters', as XML 1.0 does not allow them and the API may
return data in XML.
"""
def to_python(self, value):
value = super().to_python(value=value)
return self.remove_control_characters(value)
@staticmethod
- def remove_control_characters(str):
? ^ -
+ def remove_control_characters(input):
? ^^^^
- return "".join(ch for ch in str if unicodedata.category(ch)[0] != "C")
+ valid_chars = ['\n', '\r']
+ return "".join(ch for ch in input if
+ unicodedata.category(ch)[0] != "C" or ch in valid_chars) |
9aa48fa2a3a693c7cd5a74712b9a63ac15f32a94 | tests/test_settings.py | tests/test_settings.py | DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
SECRET_KEY = 'fake-key'
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'csv_export',
'tests',
]
MIDDLEWARE = [
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
]
USE_TZ = True
ROOT_URLCONF = 'tests.urls'
| import django
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
SECRET_KEY = 'fake-key'
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'csv_export',
'tests',
]
MIDDLEWARE = [
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
]
if django.VERSION < (1, 10):
MIDDLEWARE_CLASSES = MIDDLEWARE
USE_TZ = True
ROOT_URLCONF = 'tests.urls'
| Fix tests on Django 1.8. | Fix tests on Django 1.8.
| Python | bsd-3-clause | benkonrath/django-csv-export-view | + import django
+
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
SECRET_KEY = 'fake-key'
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'csv_export',
'tests',
]
MIDDLEWARE = [
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
]
+ if django.VERSION < (1, 10):
+ MIDDLEWARE_CLASSES = MIDDLEWARE
+
USE_TZ = True
ROOT_URLCONF = 'tests.urls'
| Fix tests on Django 1.8. | ## Code Before:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
SECRET_KEY = 'fake-key'
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'csv_export',
'tests',
]
MIDDLEWARE = [
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
]
USE_TZ = True
ROOT_URLCONF = 'tests.urls'
## Instruction:
Fix tests on Django 1.8.
## Code After:
import django
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
SECRET_KEY = 'fake-key'
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'csv_export',
'tests',
]
MIDDLEWARE = [
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
]
if django.VERSION < (1, 10):
MIDDLEWARE_CLASSES = MIDDLEWARE
USE_TZ = True
ROOT_URLCONF = 'tests.urls'
| + import django
+
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
SECRET_KEY = 'fake-key'
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'csv_export',
'tests',
]
MIDDLEWARE = [
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
]
+ if django.VERSION < (1, 10):
+ MIDDLEWARE_CLASSES = MIDDLEWARE
+
USE_TZ = True
ROOT_URLCONF = 'tests.urls' |
f7bd83ddabcad10beeeca9b1fc1e07631e68d4e0 | src/models/c2w.py | src/models/c2w.py | from keras.layers import LSTM, Input, Dense, TimeDistributed, Masking, merge
from keras.models import Model
from layers import Projection
def C2W(params, V_C):
one_hots = Input(shape=(params.maxlen, V_C.size), dtype='int8')
c_E = TimeDistributed(Projection(params.d_C))(one_hots)
# we want to preserve the state in case of padding so that the state
# sequence s_Ef and s_Eb last values remain correct
c_E_mask = Masking(mask_value=0.)(c_E)
forward = LSTM(params.d_Wi,
go_backwards=False,
dropout_U=0.1,
dropout_W=0.1,
consume_less='gpu')(c_E_mask)
backwards = LSTM(params.d_Wi,
go_backwards=True,
dropout_U=0.1,
dropout_W=0.1,
consume_less='gpu')(c_E_mask)
s_Ef = Dense(params.d_W)(forward)
s_Eb = Dense(params.d_W)(backwards)
s_E = merge(inputs=[s_Ef, s_Eb], mode='sum')
return Model(input=one_hots, output=s_E, name='W2C')
| from keras.layers import LSTM, Input, Dense, TimeDistributed, Masking, Activation, merge
from keras.models import Model
from layers import Projection
def C2W(params, V_C):
one_hots = Input(shape=(params.maxlen, V_C.size), dtype='int8')
c_E = TimeDistributed(Projection(params.d_C))(one_hots)
# we want to preserve the state in case of padding so that the state
# sequence s_Ef and s_Eb last values remain correct
c_E_mask = Masking(mask_value=0.)(c_E)
forward = LSTM(params.d_Wi,
go_backwards=False,
dropout_U=0.1,
dropout_W=0.1,
consume_less='gpu')(c_E_mask)
backwards = LSTM(params.d_Wi,
go_backwards=True,
dropout_U=0.1,
dropout_W=0.1,
consume_less='gpu')(c_E_mask)
s_Ef = Dense(params.d_W)(forward)
s_Eb = Dense(params.d_W)(backwards)
s_E = merge(inputs=[s_Ef, s_Eb], mode='sum')
#s_Eout = Activation('tanh')(s_E)
return Model(input=one_hots, output=s_E, name='W2C')
| Use tanh activation for word C2W embeddings | Use tanh activation for word C2W embeddings | Python | mit | milankinen/c2w2c,milankinen/c2w2c | - from keras.layers import LSTM, Input, Dense, TimeDistributed, Masking, merge
+ from keras.layers import LSTM, Input, Dense, TimeDistributed, Masking, Activation, merge
from keras.models import Model
from layers import Projection
def C2W(params, V_C):
one_hots = Input(shape=(params.maxlen, V_C.size), dtype='int8')
c_E = TimeDistributed(Projection(params.d_C))(one_hots)
# we want to preserve the state in case of padding so that the state
# sequence s_Ef and s_Eb last values remain correct
c_E_mask = Masking(mask_value=0.)(c_E)
forward = LSTM(params.d_Wi,
go_backwards=False,
dropout_U=0.1,
dropout_W=0.1,
consume_less='gpu')(c_E_mask)
backwards = LSTM(params.d_Wi,
go_backwards=True,
dropout_U=0.1,
dropout_W=0.1,
consume_less='gpu')(c_E_mask)
s_Ef = Dense(params.d_W)(forward)
s_Eb = Dense(params.d_W)(backwards)
s_E = merge(inputs=[s_Ef, s_Eb], mode='sum')
+ #s_Eout = Activation('tanh')(s_E)
return Model(input=one_hots, output=s_E, name='W2C')
| Use tanh activation for word C2W embeddings | ## Code Before:
from keras.layers import LSTM, Input, Dense, TimeDistributed, Masking, merge
from keras.models import Model
from layers import Projection
def C2W(params, V_C):
one_hots = Input(shape=(params.maxlen, V_C.size), dtype='int8')
c_E = TimeDistributed(Projection(params.d_C))(one_hots)
# we want to preserve the state in case of padding so that the state
# sequence s_Ef and s_Eb last values remain correct
c_E_mask = Masking(mask_value=0.)(c_E)
forward = LSTM(params.d_Wi,
go_backwards=False,
dropout_U=0.1,
dropout_W=0.1,
consume_less='gpu')(c_E_mask)
backwards = LSTM(params.d_Wi,
go_backwards=True,
dropout_U=0.1,
dropout_W=0.1,
consume_less='gpu')(c_E_mask)
s_Ef = Dense(params.d_W)(forward)
s_Eb = Dense(params.d_W)(backwards)
s_E = merge(inputs=[s_Ef, s_Eb], mode='sum')
return Model(input=one_hots, output=s_E, name='W2C')
## Instruction:
Use tanh activation for word C2W embeddings
## Code After:
from keras.layers import LSTM, Input, Dense, TimeDistributed, Masking, Activation, merge
from keras.models import Model
from layers import Projection
def C2W(params, V_C):
one_hots = Input(shape=(params.maxlen, V_C.size), dtype='int8')
c_E = TimeDistributed(Projection(params.d_C))(one_hots)
# we want to preserve the state in case of padding so that the state
# sequence s_Ef and s_Eb last values remain correct
c_E_mask = Masking(mask_value=0.)(c_E)
forward = LSTM(params.d_Wi,
go_backwards=False,
dropout_U=0.1,
dropout_W=0.1,
consume_less='gpu')(c_E_mask)
backwards = LSTM(params.d_Wi,
go_backwards=True,
dropout_U=0.1,
dropout_W=0.1,
consume_less='gpu')(c_E_mask)
s_Ef = Dense(params.d_W)(forward)
s_Eb = Dense(params.d_W)(backwards)
s_E = merge(inputs=[s_Ef, s_Eb], mode='sum')
#s_Eout = Activation('tanh')(s_E)
return Model(input=one_hots, output=s_E, name='W2C')
| - from keras.layers import LSTM, Input, Dense, TimeDistributed, Masking, merge
+ from keras.layers import LSTM, Input, Dense, TimeDistributed, Masking, Activation, merge
? ++++++++++++
from keras.models import Model
from layers import Projection
def C2W(params, V_C):
one_hots = Input(shape=(params.maxlen, V_C.size), dtype='int8')
c_E = TimeDistributed(Projection(params.d_C))(one_hots)
# we want to preserve the state in case of padding so that the state
# sequence s_Ef and s_Eb last values remain correct
c_E_mask = Masking(mask_value=0.)(c_E)
forward = LSTM(params.d_Wi,
go_backwards=False,
dropout_U=0.1,
dropout_W=0.1,
consume_less='gpu')(c_E_mask)
backwards = LSTM(params.d_Wi,
go_backwards=True,
dropout_U=0.1,
dropout_W=0.1,
consume_less='gpu')(c_E_mask)
s_Ef = Dense(params.d_W)(forward)
s_Eb = Dense(params.d_W)(backwards)
s_E = merge(inputs=[s_Ef, s_Eb], mode='sum')
+ #s_Eout = Activation('tanh')(s_E)
return Model(input=one_hots, output=s_E, name='W2C') |
5beea76076aa0806f8ee2db5f2169846e7497ef1 | euler_python/problem55.py | euler_python/problem55.py | from toolset import iterate, quantify, take, memoize
def to_digits(num):
# to_digits(1234) --> [1, 2, 3, 4]
return list(map(int, str(num)))
def to_num(digits):
# to_num([1, 2, 3, 4]) --> 1234
return int(''.join(map(str, digits)))
@memoize
def is_palindromic(num):
return to_digits(num) == list(reversed(to_digits(num)))
def is_lychrel(num):
rev = lambda x: to_num(reversed(to_digits(x)))
start = num + rev(num)
iterations = iterate(lambda x: x + rev(x), start)
return not any(is_palindromic(n) for n in take(50, iterations))
def problem55():
return quantify(range(1, 10000), pred=is_lychrel)
| from toolset import iterate, quantify, take, memoize
def rev(n):
"""Return the reverse of n's digits"""
return int(''.join(reversed(str(n))))
@memoize
def is_palindromic(n):
return n == rev(n)
def is_lychrel(n):
start = n + rev(n)
iterations = iterate(lambda x: x + rev(x), start)
return not any(is_palindromic(y) for y in take(50, iterations))
def problem55():
return quantify(range(1, 10000), pred=is_lychrel)
| Simplify python solution to 55 | Simplify python solution to 55
| Python | mit | mjwestcott/projecteuler,mjwestcott/projecteuler,mjwestcott/projecteuler | from toolset import iterate, quantify, take, memoize
+ def rev(n):
+ """Return the reverse of n's digits"""
+ return int(''.join(reversed(str(n))))
- def to_digits(num):
- # to_digits(1234) --> [1, 2, 3, 4]
- return list(map(int, str(num)))
-
- def to_num(digits):
- # to_num([1, 2, 3, 4]) --> 1234
- return int(''.join(map(str, digits)))
@memoize
- def is_palindromic(num):
+ def is_palindromic(n):
- return to_digits(num) == list(reversed(to_digits(num)))
+ return n == rev(n)
- def is_lychrel(num):
+ def is_lychrel(n):
- rev = lambda x: to_num(reversed(to_digits(x)))
- start = num + rev(num)
+ start = n + rev(n)
iterations = iterate(lambda x: x + rev(x), start)
- return not any(is_palindromic(n) for n in take(50, iterations))
+ return not any(is_palindromic(y) for y in take(50, iterations))
def problem55():
return quantify(range(1, 10000), pred=is_lychrel)
| Simplify python solution to 55 | ## Code Before:
from toolset import iterate, quantify, take, memoize
def to_digits(num):
# to_digits(1234) --> [1, 2, 3, 4]
return list(map(int, str(num)))
def to_num(digits):
# to_num([1, 2, 3, 4]) --> 1234
return int(''.join(map(str, digits)))
@memoize
def is_palindromic(num):
return to_digits(num) == list(reversed(to_digits(num)))
def is_lychrel(num):
rev = lambda x: to_num(reversed(to_digits(x)))
start = num + rev(num)
iterations = iterate(lambda x: x + rev(x), start)
return not any(is_palindromic(n) for n in take(50, iterations))
def problem55():
return quantify(range(1, 10000), pred=is_lychrel)
## Instruction:
Simplify python solution to 55
## Code After:
from toolset import iterate, quantify, take, memoize
def rev(n):
"""Return the reverse of n's digits"""
return int(''.join(reversed(str(n))))
@memoize
def is_palindromic(n):
return n == rev(n)
def is_lychrel(n):
start = n + rev(n)
iterations = iterate(lambda x: x + rev(x), start)
return not any(is_palindromic(y) for y in take(50, iterations))
def problem55():
return quantify(range(1, 10000), pred=is_lychrel)
| from toolset import iterate, quantify, take, memoize
+ def rev(n):
+ """Return the reverse of n's digits"""
+ return int(''.join(reversed(str(n))))
- def to_digits(num):
- # to_digits(1234) --> [1, 2, 3, 4]
- return list(map(int, str(num)))
-
- def to_num(digits):
- # to_num([1, 2, 3, 4]) --> 1234
- return int(''.join(map(str, digits)))
@memoize
- def is_palindromic(num):
? --
+ def is_palindromic(n):
- return to_digits(num) == list(reversed(to_digits(num)))
+ return n == rev(n)
- def is_lychrel(num):
? --
+ def is_lychrel(n):
- rev = lambda x: to_num(reversed(to_digits(x)))
- start = num + rev(num)
? -- --
+ start = n + rev(n)
iterations = iterate(lambda x: x + rev(x), start)
- return not any(is_palindromic(n) for n in take(50, iterations))
? ^ ^
+ return not any(is_palindromic(y) for y in take(50, iterations))
? ^ ^
def problem55():
return quantify(range(1, 10000), pred=is_lychrel) |
890647cc0cd952ed1a52bdd96f7e9dd8c28810c9 | socketlabs/socketlabs.py | socketlabs/socketlabs.py | import requests
from . constants import BASE_URL
from . exceptions import SocketLabsUnauthorized
class SocketLabs():
def __init__(self, username=None, password=None, serverid=None):
self._username = username
self._password = password
self._serverid = serverid
def failedMessages(self, **kwargs):
url = BASE_URL + '/messagesFailed'
headers = {'Accept': 'application/json'}
params = {'serverId': self._serverid, 'type': 'json'}
# Apply any custom parameters passed in
for key, value in kwargs.items():
params[key] = value
r = requests.get(url, params=params, headers=headers,
auth=(self._username, self._password))
if r.status_code == 200:
return r.json()
else:
raise SocketLabsUnauthorized(r)
| import requests
from . constants import BASE_URL
from . exceptions import SocketLabsUnauthorized
class SocketLabs():
def __init__(self, username, password, serverid):
if username is None:
raise RuntimeError("username not defined")
if password is None:
raise RuntimeError("password not defined")
if serverid is None:
raise RuntimeError("serverid not defined")
self._username = username
self._password = password
self._serverid = serverid
def failedMessages(self, **kwargs):
url = BASE_URL + '/messagesFailed'
headers = {'Accept': 'application/json'}
params = {'serverId': self._serverid, 'type': 'json'}
# Apply any custom parameters passed in
for key, value in kwargs.items():
params[key] = value
r = requests.get(url, params=params, headers=headers,
auth=(self._username, self._password))
if r.status_code == 200:
return r.json()
else:
raise SocketLabsUnauthorized(r)
| Add checks for username/password/serverid being defined | Add checks for username/password/serverid being defined
| Python | mit | MattHealy/socketlabs-python | import requests
from . constants import BASE_URL
from . exceptions import SocketLabsUnauthorized
class SocketLabs():
- def __init__(self, username=None, password=None, serverid=None):
+ def __init__(self, username, password, serverid):
+
+ if username is None:
+ raise RuntimeError("username not defined")
+ if password is None:
+ raise RuntimeError("password not defined")
+ if serverid is None:
+ raise RuntimeError("serverid not defined")
self._username = username
self._password = password
self._serverid = serverid
def failedMessages(self, **kwargs):
url = BASE_URL + '/messagesFailed'
headers = {'Accept': 'application/json'}
params = {'serverId': self._serverid, 'type': 'json'}
# Apply any custom parameters passed in
for key, value in kwargs.items():
params[key] = value
r = requests.get(url, params=params, headers=headers,
auth=(self._username, self._password))
if r.status_code == 200:
return r.json()
else:
raise SocketLabsUnauthorized(r)
| Add checks for username/password/serverid being defined | ## Code Before:
import requests
from . constants import BASE_URL
from . exceptions import SocketLabsUnauthorized
class SocketLabs():
def __init__(self, username=None, password=None, serverid=None):
self._username = username
self._password = password
self._serverid = serverid
def failedMessages(self, **kwargs):
url = BASE_URL + '/messagesFailed'
headers = {'Accept': 'application/json'}
params = {'serverId': self._serverid, 'type': 'json'}
# Apply any custom parameters passed in
for key, value in kwargs.items():
params[key] = value
r = requests.get(url, params=params, headers=headers,
auth=(self._username, self._password))
if r.status_code == 200:
return r.json()
else:
raise SocketLabsUnauthorized(r)
## Instruction:
Add checks for username/password/serverid being defined
## Code After:
import requests
from . constants import BASE_URL
from . exceptions import SocketLabsUnauthorized
class SocketLabs():
def __init__(self, username, password, serverid):
if username is None:
raise RuntimeError("username not defined")
if password is None:
raise RuntimeError("password not defined")
if serverid is None:
raise RuntimeError("serverid not defined")
self._username = username
self._password = password
self._serverid = serverid
def failedMessages(self, **kwargs):
url = BASE_URL + '/messagesFailed'
headers = {'Accept': 'application/json'}
params = {'serverId': self._serverid, 'type': 'json'}
# Apply any custom parameters passed in
for key, value in kwargs.items():
params[key] = value
r = requests.get(url, params=params, headers=headers,
auth=(self._username, self._password))
if r.status_code == 200:
return r.json()
else:
raise SocketLabsUnauthorized(r)
| import requests
from . constants import BASE_URL
from . exceptions import SocketLabsUnauthorized
class SocketLabs():
- def __init__(self, username=None, password=None, serverid=None):
? ----- ----- -----
+ def __init__(self, username, password, serverid):
+
+ if username is None:
+ raise RuntimeError("username not defined")
+ if password is None:
+ raise RuntimeError("password not defined")
+ if serverid is None:
+ raise RuntimeError("serverid not defined")
self._username = username
self._password = password
self._serverid = serverid
def failedMessages(self, **kwargs):
url = BASE_URL + '/messagesFailed'
headers = {'Accept': 'application/json'}
params = {'serverId': self._serverid, 'type': 'json'}
# Apply any custom parameters passed in
for key, value in kwargs.items():
params[key] = value
r = requests.get(url, params=params, headers=headers,
auth=(self._username, self._password))
if r.status_code == 200:
return r.json()
else:
raise SocketLabsUnauthorized(r) |
462397443770d55617356bf257b021406367b4c2 | wluopensource/osl_flatpages/models.py | wluopensource/osl_flatpages/models.py | from django.db import models
import markdown
class Flatpage(models.Model):
page_name = models.CharField(max_length=100, primary_key=True, unique=True)
title = models.CharField(max_length=100)
description = models.CharField(max_length=255)
markdown_content = models.TextField('content')
content = models.TextField(editable=False)
def __unicode__(self):
return self.page_name
def save(self, force_insert=False, force_update=False):
self.content = markdown.markdown(self.markdown_content)
super(Flatpage, self).save(force_insert, force_update)
| from django.db import models
import markdown
class Flatpage(models.Model):
page_name = models.CharField(max_length=100, primary_key=True, unique=True)
title = models.CharField(blank=True, max_length=100)
description = models.CharField(blank=True, max_length=255)
markdown_content = models.TextField('content')
content = models.TextField(editable=False)
def __unicode__(self):
return self.page_name
def save(self, force_insert=False, force_update=False):
self.content = markdown.markdown(self.markdown_content)
super(Flatpage, self).save(force_insert, force_update)
| Allow blank entries for title and description for flatpages | Allow blank entries for title and description for flatpages
| Python | bsd-3-clause | jeffcharles/Open-Source-at-Laurier-Website,jeffcharles/Open-Source-at-Laurier-Website,jeffcharles/Open-Source-at-Laurier-Website,jeffcharles/Open-Source-at-Laurier-Website | from django.db import models
import markdown
class Flatpage(models.Model):
page_name = models.CharField(max_length=100, primary_key=True, unique=True)
- title = models.CharField(max_length=100)
+ title = models.CharField(blank=True, max_length=100)
- description = models.CharField(max_length=255)
+ description = models.CharField(blank=True, max_length=255)
markdown_content = models.TextField('content')
content = models.TextField(editable=False)
def __unicode__(self):
return self.page_name
def save(self, force_insert=False, force_update=False):
self.content = markdown.markdown(self.markdown_content)
super(Flatpage, self).save(force_insert, force_update)
| Allow blank entries for title and description for flatpages | ## Code Before:
from django.db import models
import markdown
class Flatpage(models.Model):
page_name = models.CharField(max_length=100, primary_key=True, unique=True)
title = models.CharField(max_length=100)
description = models.CharField(max_length=255)
markdown_content = models.TextField('content')
content = models.TextField(editable=False)
def __unicode__(self):
return self.page_name
def save(self, force_insert=False, force_update=False):
self.content = markdown.markdown(self.markdown_content)
super(Flatpage, self).save(force_insert, force_update)
## Instruction:
Allow blank entries for title and description for flatpages
## Code After:
from django.db import models
import markdown
class Flatpage(models.Model):
page_name = models.CharField(max_length=100, primary_key=True, unique=True)
title = models.CharField(blank=True, max_length=100)
description = models.CharField(blank=True, max_length=255)
markdown_content = models.TextField('content')
content = models.TextField(editable=False)
def __unicode__(self):
return self.page_name
def save(self, force_insert=False, force_update=False):
self.content = markdown.markdown(self.markdown_content)
super(Flatpage, self).save(force_insert, force_update)
| from django.db import models
import markdown
class Flatpage(models.Model):
page_name = models.CharField(max_length=100, primary_key=True, unique=True)
- title = models.CharField(max_length=100)
+ title = models.CharField(blank=True, max_length=100)
? ++++++++++++
- description = models.CharField(max_length=255)
+ description = models.CharField(blank=True, max_length=255)
? ++++++++++++
markdown_content = models.TextField('content')
content = models.TextField(editable=False)
def __unicode__(self):
return self.page_name
def save(self, force_insert=False, force_update=False):
self.content = markdown.markdown(self.markdown_content)
super(Flatpage, self).save(force_insert, force_update)
|
ab16cd72a2f2ed093f206b48379fb9f03f8d2f36 | tests/example.py | tests/example.py | import unittest
from src.dojo import Dojo
"""
Call "python -m tests.example" while being in parent directory to run tests in this file.
"""
class ExampleTest(unittest.TestCase):
def test_example(self):
dojo = Dojo()
self.assertEqual(dojo.get_random_number(), 4)
if __name__ == '__main__':
unittest.main()
| import unittest
from src.dojo import Dojo
"""
Call "python -m tests.example" while being in parent directory to run tests in this file.
"""
class ExampleTest(unittest.TestCase):
def setUp(self):
""" This method will be called *before* each test run. """
pass
def tearDown(self):
""" This method will be called *after* each test run. """
pass
def test_example(self):
dojo = Dojo()
self.assertEqual(dojo.get_random_number(), 4)
if __name__ == '__main__':
unittest.main()
| Add setUp and tearDown to test file | Add setUp and tearDown to test file
| Python | mit | pawel-lewtak/coding-dojo-template-python | import unittest
from src.dojo import Dojo
"""
Call "python -m tests.example" while being in parent directory to run tests in this file.
"""
class ExampleTest(unittest.TestCase):
+ def setUp(self):
+ """ This method will be called *before* each test run. """
+ pass
+
+ def tearDown(self):
+ """ This method will be called *after* each test run. """
+ pass
+
def test_example(self):
dojo = Dojo()
self.assertEqual(dojo.get_random_number(), 4)
if __name__ == '__main__':
unittest.main()
| Add setUp and tearDown to test file | ## Code Before:
import unittest
from src.dojo import Dojo
"""
Call "python -m tests.example" while being in parent directory to run tests in this file.
"""
class ExampleTest(unittest.TestCase):
def test_example(self):
dojo = Dojo()
self.assertEqual(dojo.get_random_number(), 4)
if __name__ == '__main__':
unittest.main()
## Instruction:
Add setUp and tearDown to test file
## Code After:
import unittest
from src.dojo import Dojo
"""
Call "python -m tests.example" while being in parent directory to run tests in this file.
"""
class ExampleTest(unittest.TestCase):
def setUp(self):
""" This method will be called *before* each test run. """
pass
def tearDown(self):
""" This method will be called *after* each test run. """
pass
def test_example(self):
dojo = Dojo()
self.assertEqual(dojo.get_random_number(), 4)
if __name__ == '__main__':
unittest.main()
| import unittest
from src.dojo import Dojo
"""
Call "python -m tests.example" while being in parent directory to run tests in this file.
"""
class ExampleTest(unittest.TestCase):
+ def setUp(self):
+ """ This method will be called *before* each test run. """
+ pass
+
+ def tearDown(self):
+ """ This method will be called *after* each test run. """
+ pass
+
def test_example(self):
dojo = Dojo()
self.assertEqual(dojo.get_random_number(), 4)
if __name__ == '__main__':
unittest.main() |
e331f5cd1c921ca35c6184c00fbd36929cb92b90 | src/tenyksddate/main.py | src/tenyksddate/main.py | from tenyksservice import TenyksService, run_service
from ddate.base import DDate
class DiscordianDate(TenyksService):
direct_only = True
irc_message_filters = {
'today': [r'^(?i)(ddate|discordian)']
}
def __init__(self, *args, **kwargs):
super(DiscordianDate, self).__init__(*args, **kwargs)
def handle_today(self, data, match):
self.send(str(DDate()), data)
def main():
run_service(DiscordianDate)
if __name__ == '__main__':
main()
| import datetime
from tenyksservice import TenyksService, run_service
from ddate.base import DDate
class DiscordianDate(TenyksService):
direct_only = True
irc_message_filters = {
'date': [r'^(?i)(ddate|discordian) (?P<month>(.*)) (?P<day>(.*)) (?P<year>(.*))'],
'today': [r'^(?i)(ddate|discordian)']
}
def __init__(self, *args, **kwargs):
super(DiscordianDate, self).__init__(*args, **kwargs)
def handle_today(self, data, match):
self.send(str(DDate()), data)
def handle_date(self, data, match):
year = int(match.groupdict()['year'])
month = int(match.groupdict()['month'])
day = int(match.groupdict()['day'])
self.send(str(DDate(datetime.date(year=year, month=month, day=day))), data)
def main():
run_service(DiscordianDate)
if __name__ == '__main__':
main()
| Add lookup for an arbitrary date | Add lookup for an arbitrary date
In the form “mm dd yyyy”.
| Python | mit | kyleterry/tenyks-contrib,cblgh/tenyks-contrib,colby/tenyks-contrib | + import datetime
from tenyksservice import TenyksService, run_service
from ddate.base import DDate
class DiscordianDate(TenyksService):
direct_only = True
irc_message_filters = {
+ 'date': [r'^(?i)(ddate|discordian) (?P<month>(.*)) (?P<day>(.*)) (?P<year>(.*))'],
'today': [r'^(?i)(ddate|discordian)']
}
def __init__(self, *args, **kwargs):
super(DiscordianDate, self).__init__(*args, **kwargs)
def handle_today(self, data, match):
self.send(str(DDate()), data)
+ def handle_date(self, data, match):
+ year = int(match.groupdict()['year'])
+ month = int(match.groupdict()['month'])
+ day = int(match.groupdict()['day'])
+
+ self.send(str(DDate(datetime.date(year=year, month=month, day=day))), data)
+
def main():
run_service(DiscordianDate)
if __name__ == '__main__':
main()
| Add lookup for an arbitrary date | ## Code Before:
from tenyksservice import TenyksService, run_service
from ddate.base import DDate
class DiscordianDate(TenyksService):
direct_only = True
irc_message_filters = {
'today': [r'^(?i)(ddate|discordian)']
}
def __init__(self, *args, **kwargs):
super(DiscordianDate, self).__init__(*args, **kwargs)
def handle_today(self, data, match):
self.send(str(DDate()), data)
def main():
run_service(DiscordianDate)
if __name__ == '__main__':
main()
## Instruction:
Add lookup for an arbitrary date
## Code After:
import datetime
from tenyksservice import TenyksService, run_service
from ddate.base import DDate
class DiscordianDate(TenyksService):
direct_only = True
irc_message_filters = {
'date': [r'^(?i)(ddate|discordian) (?P<month>(.*)) (?P<day>(.*)) (?P<year>(.*))'],
'today': [r'^(?i)(ddate|discordian)']
}
def __init__(self, *args, **kwargs):
super(DiscordianDate, self).__init__(*args, **kwargs)
def handle_today(self, data, match):
self.send(str(DDate()), data)
def handle_date(self, data, match):
year = int(match.groupdict()['year'])
month = int(match.groupdict()['month'])
day = int(match.groupdict()['day'])
self.send(str(DDate(datetime.date(year=year, month=month, day=day))), data)
def main():
run_service(DiscordianDate)
if __name__ == '__main__':
main()
| + import datetime
from tenyksservice import TenyksService, run_service
from ddate.base import DDate
class DiscordianDate(TenyksService):
direct_only = True
irc_message_filters = {
+ 'date': [r'^(?i)(ddate|discordian) (?P<month>(.*)) (?P<day>(.*)) (?P<year>(.*))'],
'today': [r'^(?i)(ddate|discordian)']
}
def __init__(self, *args, **kwargs):
super(DiscordianDate, self).__init__(*args, **kwargs)
def handle_today(self, data, match):
self.send(str(DDate()), data)
+ def handle_date(self, data, match):
+ year = int(match.groupdict()['year'])
+ month = int(match.groupdict()['month'])
+ day = int(match.groupdict()['day'])
+
+ self.send(str(DDate(datetime.date(year=year, month=month, day=day))), data)
+
def main():
run_service(DiscordianDate)
if __name__ == '__main__':
main() |
fa42219c1e6763f3adfc1f6ede4080f769e476a6 | tests/test_mongo.py | tests/test_mongo.py |
from uuid import uuid4 as uuid
import pytest
pymongo = pytest.importorskip('pymongo')
from simplekv.db.mongo import MongoStore
from basic_store import BasicStore
class TestMongoDB(BasicStore):
@pytest.fixture
def db_name(self):
return '_simplekv_test_{}'.format(uuid())
@pytest.yield_fixture
def store(self, db_name):
conn = pymongo.MongoClient()
yield MongoStore(conn[db_name])
conn.drop_database(self.db_name)
|
from uuid import uuid4 as uuid
import pytest
pymongo = pytest.importorskip('pymongo')
from simplekv.db.mongo import MongoStore
from basic_store import BasicStore
class TestMongoDB(BasicStore):
@pytest.fixture
def db_name(self):
return '_simplekv_test_{}'.format(uuid())
@pytest.yield_fixture
def store(self, db_name):
conn = pymongo.MongoClient()
yield MongoStore(conn[db_name], 'simplekv-tests')
conn.drop_database(self.db_name)
| Add database table name to MongoStore tests. | Add database table name to MongoStore tests.
| Python | mit | fmarczin/simplekv,karteek/simplekv,mbr/simplekv,mbr/simplekv,fmarczin/simplekv,karteek/simplekv |
from uuid import uuid4 as uuid
import pytest
pymongo = pytest.importorskip('pymongo')
from simplekv.db.mongo import MongoStore
from basic_store import BasicStore
class TestMongoDB(BasicStore):
@pytest.fixture
def db_name(self):
return '_simplekv_test_{}'.format(uuid())
@pytest.yield_fixture
def store(self, db_name):
conn = pymongo.MongoClient()
- yield MongoStore(conn[db_name])
+ yield MongoStore(conn[db_name], 'simplekv-tests')
conn.drop_database(self.db_name)
| Add database table name to MongoStore tests. | ## Code Before:
from uuid import uuid4 as uuid
import pytest
pymongo = pytest.importorskip('pymongo')
from simplekv.db.mongo import MongoStore
from basic_store import BasicStore
class TestMongoDB(BasicStore):
@pytest.fixture
def db_name(self):
return '_simplekv_test_{}'.format(uuid())
@pytest.yield_fixture
def store(self, db_name):
conn = pymongo.MongoClient()
yield MongoStore(conn[db_name])
conn.drop_database(self.db_name)
## Instruction:
Add database table name to MongoStore tests.
## Code After:
from uuid import uuid4 as uuid
import pytest
pymongo = pytest.importorskip('pymongo')
from simplekv.db.mongo import MongoStore
from basic_store import BasicStore
class TestMongoDB(BasicStore):
@pytest.fixture
def db_name(self):
return '_simplekv_test_{}'.format(uuid())
@pytest.yield_fixture
def store(self, db_name):
conn = pymongo.MongoClient()
yield MongoStore(conn[db_name], 'simplekv-tests')
conn.drop_database(self.db_name)
|
from uuid import uuid4 as uuid
import pytest
pymongo = pytest.importorskip('pymongo')
from simplekv.db.mongo import MongoStore
from basic_store import BasicStore
class TestMongoDB(BasicStore):
@pytest.fixture
def db_name(self):
return '_simplekv_test_{}'.format(uuid())
@pytest.yield_fixture
def store(self, db_name):
conn = pymongo.MongoClient()
- yield MongoStore(conn[db_name])
+ yield MongoStore(conn[db_name], 'simplekv-tests')
? ++++++++++++++++++
conn.drop_database(self.db_name) |
220b6a9fee0f307d4de1e48b29093812f7dd10ec | var/spack/repos/builtin/packages/m4/package.py | var/spack/repos/builtin/packages/m4/package.py | from spack import *
class M4(Package):
"""GNU M4 is an implementation of the traditional Unix macro processor."""
homepage = "https://www.gnu.org/software/m4/m4.html"
url = "ftp://ftp.gnu.org/gnu/m4/m4-1.4.17.tar.gz"
version('1.4.17', 'a5e9954b1dae036762f7b13673a2cf76')
depends_on('libsigsegv')
def install(self, spec, prefix):
configure("--prefix=%s" % prefix)
make()
make("install")
| from spack import *
class M4(Package):
"""GNU M4 is an implementation of the traditional Unix macro processor."""
homepage = "https://www.gnu.org/software/m4/m4.html"
url = "ftp://ftp.gnu.org/gnu/m4/m4-1.4.17.tar.gz"
version('1.4.17', 'a5e9954b1dae036762f7b13673a2cf76')
variant('sigsegv', default=True, description="Build the libsigsegv dependency")
depends_on('libsigsegv', when='+sigsegv')
def install(self, spec, prefix):
configure("--prefix=%s" % prefix)
make()
make("install")
| Make libsigsegv an optional dependency | Make libsigsegv an optional dependency
| Python | lgpl-2.1 | lgarren/spack,mfherbst/spack,LLNL/spack,TheTimmy/spack,EmreAtes/spack,LLNL/spack,tmerrick1/spack,krafczyk/spack,TheTimmy/spack,TheTimmy/spack,lgarren/spack,skosukhin/spack,matthiasdiener/spack,TheTimmy/spack,mfherbst/spack,skosukhin/spack,krafczyk/spack,lgarren/spack,mfherbst/spack,matthiasdiener/spack,matthiasdiener/spack,mfherbst/spack,krafczyk/spack,iulian787/spack,iulian787/spack,matthiasdiener/spack,LLNL/spack,LLNL/spack,tmerrick1/spack,lgarren/spack,EmreAtes/spack,EmreAtes/spack,mfherbst/spack,lgarren/spack,LLNL/spack,TheTimmy/spack,iulian787/spack,krafczyk/spack,EmreAtes/spack,iulian787/spack,tmerrick1/spack,skosukhin/spack,krafczyk/spack,iulian787/spack,skosukhin/spack,tmerrick1/spack,tmerrick1/spack,skosukhin/spack,EmreAtes/spack,matthiasdiener/spack | from spack import *
class M4(Package):
"""GNU M4 is an implementation of the traditional Unix macro processor."""
homepage = "https://www.gnu.org/software/m4/m4.html"
url = "ftp://ftp.gnu.org/gnu/m4/m4-1.4.17.tar.gz"
version('1.4.17', 'a5e9954b1dae036762f7b13673a2cf76')
+ variant('sigsegv', default=True, description="Build the libsigsegv dependency")
+
- depends_on('libsigsegv')
+ depends_on('libsigsegv', when='+sigsegv')
def install(self, spec, prefix):
configure("--prefix=%s" % prefix)
make()
make("install")
| Make libsigsegv an optional dependency | ## Code Before:
from spack import *
class M4(Package):
"""GNU M4 is an implementation of the traditional Unix macro processor."""
homepage = "https://www.gnu.org/software/m4/m4.html"
url = "ftp://ftp.gnu.org/gnu/m4/m4-1.4.17.tar.gz"
version('1.4.17', 'a5e9954b1dae036762f7b13673a2cf76')
depends_on('libsigsegv')
def install(self, spec, prefix):
configure("--prefix=%s" % prefix)
make()
make("install")
## Instruction:
Make libsigsegv an optional dependency
## Code After:
from spack import *
class M4(Package):
"""GNU M4 is an implementation of the traditional Unix macro processor."""
homepage = "https://www.gnu.org/software/m4/m4.html"
url = "ftp://ftp.gnu.org/gnu/m4/m4-1.4.17.tar.gz"
version('1.4.17', 'a5e9954b1dae036762f7b13673a2cf76')
variant('sigsegv', default=True, description="Build the libsigsegv dependency")
depends_on('libsigsegv', when='+sigsegv')
def install(self, spec, prefix):
configure("--prefix=%s" % prefix)
make()
make("install")
| from spack import *
class M4(Package):
"""GNU M4 is an implementation of the traditional Unix macro processor."""
homepage = "https://www.gnu.org/software/m4/m4.html"
url = "ftp://ftp.gnu.org/gnu/m4/m4-1.4.17.tar.gz"
version('1.4.17', 'a5e9954b1dae036762f7b13673a2cf76')
+ variant('sigsegv', default=True, description="Build the libsigsegv dependency")
+
- depends_on('libsigsegv')
+ depends_on('libsigsegv', when='+sigsegv')
? +++++++++++++++++
def install(self, spec, prefix):
configure("--prefix=%s" % prefix)
make()
make("install") |
2cb73ac018287ab77b380c31166ec4fc6fd99f5e | performanceplatform/collector/gcloud/__init__.py | performanceplatform/collector/gcloud/__init__.py | from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
from dshelpers import download_url
from performanceplatform.collector.gcloud.core import (
nuke_local_database, save_raw_data, aggregate_and_save,
push_aggregates)
from performanceplatform.collector.gcloud.sales_parser import (
get_latest_csv_url)
from performanceplatform.collector.write import DataSet
INDEX_URL = ('https://digitalmarketplace.blog.gov.uk'
'/sales-accreditation-information/')
def main(credentials, data_set_config, query, options, start_at, end_at,
filename=None):
nuke_local_database()
if filename is not None:
with open(filename, 'r') as f:
save_raw_data(f)
else:
save_raw_data(download_url(get_latest_csv_url(INDEX_URL)))
aggregate_and_save()
data_set = DataSet.from_config(data_set_config)
push_aggregates(data_set)
| from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
from dshelpers import download_url
from performanceplatform.collector.gcloud.core import (
nuke_local_database, save_raw_data, aggregate_and_save,
push_aggregates)
from performanceplatform.collector.gcloud.sales_parser import (
get_latest_csv_url)
from performanceplatform.collector.write import DataSet
INDEX_URL = ('https://digitalmarketplace.blog.gov.uk'
'/sales-accreditation-information/')
def main(credentials, data_set_config, query, options, start_at, end_at,
filename=None):
nuke_local_database()
if filename is not None:
with open(filename, 'r') as f:
save_raw_data(f)
else:
save_raw_data(download_url(get_latest_csv_url(INDEX_URL)))
aggregate_and_save()
data_set = DataSet.from_config(data_set_config)
data_set.empty_data_set()
push_aggregates(data_set)
| Make the G-Cloud collector empty the data set | Make the G-Cloud collector empty the data set
https://www.pivotaltracker.com/story/show/72073020
[Delivers #72073020]
| Python | mit | alphagov/performanceplatform-collector,alphagov/performanceplatform-collector,alphagov/performanceplatform-collector | from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
from dshelpers import download_url
from performanceplatform.collector.gcloud.core import (
nuke_local_database, save_raw_data, aggregate_and_save,
push_aggregates)
from performanceplatform.collector.gcloud.sales_parser import (
get_latest_csv_url)
from performanceplatform.collector.write import DataSet
INDEX_URL = ('https://digitalmarketplace.blog.gov.uk'
'/sales-accreditation-information/')
def main(credentials, data_set_config, query, options, start_at, end_at,
filename=None):
nuke_local_database()
if filename is not None:
with open(filename, 'r') as f:
save_raw_data(f)
else:
save_raw_data(download_url(get_latest_csv_url(INDEX_URL)))
aggregate_and_save()
data_set = DataSet.from_config(data_set_config)
+ data_set.empty_data_set()
push_aggregates(data_set)
| Make the G-Cloud collector empty the data set | ## Code Before:
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
from dshelpers import download_url
from performanceplatform.collector.gcloud.core import (
nuke_local_database, save_raw_data, aggregate_and_save,
push_aggregates)
from performanceplatform.collector.gcloud.sales_parser import (
get_latest_csv_url)
from performanceplatform.collector.write import DataSet
INDEX_URL = ('https://digitalmarketplace.blog.gov.uk'
'/sales-accreditation-information/')
def main(credentials, data_set_config, query, options, start_at, end_at,
filename=None):
nuke_local_database()
if filename is not None:
with open(filename, 'r') as f:
save_raw_data(f)
else:
save_raw_data(download_url(get_latest_csv_url(INDEX_URL)))
aggregate_and_save()
data_set = DataSet.from_config(data_set_config)
push_aggregates(data_set)
## Instruction:
Make the G-Cloud collector empty the data set
## Code After:
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
from dshelpers import download_url
from performanceplatform.collector.gcloud.core import (
nuke_local_database, save_raw_data, aggregate_and_save,
push_aggregates)
from performanceplatform.collector.gcloud.sales_parser import (
get_latest_csv_url)
from performanceplatform.collector.write import DataSet
INDEX_URL = ('https://digitalmarketplace.blog.gov.uk'
'/sales-accreditation-information/')
def main(credentials, data_set_config, query, options, start_at, end_at,
filename=None):
nuke_local_database()
if filename is not None:
with open(filename, 'r') as f:
save_raw_data(f)
else:
save_raw_data(download_url(get_latest_csv_url(INDEX_URL)))
aggregate_and_save()
data_set = DataSet.from_config(data_set_config)
data_set.empty_data_set()
push_aggregates(data_set)
| from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
from dshelpers import download_url
from performanceplatform.collector.gcloud.core import (
nuke_local_database, save_raw_data, aggregate_and_save,
push_aggregates)
from performanceplatform.collector.gcloud.sales_parser import (
get_latest_csv_url)
from performanceplatform.collector.write import DataSet
INDEX_URL = ('https://digitalmarketplace.blog.gov.uk'
'/sales-accreditation-information/')
def main(credentials, data_set_config, query, options, start_at, end_at,
filename=None):
nuke_local_database()
if filename is not None:
with open(filename, 'r') as f:
save_raw_data(f)
else:
save_raw_data(download_url(get_latest_csv_url(INDEX_URL)))
aggregate_and_save()
data_set = DataSet.from_config(data_set_config)
+ data_set.empty_data_set()
push_aggregates(data_set) |
f1b78e050a2b4e8e648e6570c1d2e8688f104899 | bin/pylama/lint/extensions.py | bin/pylama/lint/extensions.py | """Load extensions."""
import os
import sys
CURDIR = os.path.abspath(os.path.dirname(__file__))
sys.path.insert(0, os.path.join(CURDIR, '..', '..', 'deps'))
LINTERS = {}
try:
from pylama.lint.pylama_mccabe import Linter
LINTERS['mccabe'] = Linter()
except ImportError:
pass
try:
from pylama.lint.pylama_pydocstyle import Linter
LINTERS['pep257'] = Linter() # for compatibility
LINTERS['pydocstyle'] = Linter()
except ImportError:
pass
try:
from pylama.lint.pylama_pycodestyle import Linter
LINTERS['pycodestyle'] = Linter() # for compability
LINTERS['pep8'] = Linter() # for compability
except ImportError:
pass
try:
from pylama.lint.pylama_pyflakes import Linter
LINTERS['pyflakes'] = Linter()
except ImportError:
pass
try:
from pylama_pylint import Linter
LINTERS['pylint'] = Linter()
except ImportError:
pass
from pkg_resources import iter_entry_points
for entry in iter_entry_points('pylama.linter'):
if entry.name not in LINTERS:
try:
LINTERS[entry.name] = entry.load()()
except ImportError:
pass
# pylama:ignore=E0611
| """Load extensions."""
import os
import sys
CURDIR = os.path.abspath(os.path.dirname(__file__))
sys.path.insert(0, os.path.join(CURDIR, '..', '..', 'deps'))
LINTERS = {}
try:
from pylama.lint.pylama_mccabe import Linter
LINTERS['mccabe'] = Linter()
except ImportError:
pass
try:
from pylama.lint.pylama_pydocstyle import Linter
LINTERS['pep257'] = Linter() # for compatibility
LINTERS['pydocstyle'] = Linter()
except ImportError:
pass
try:
from pylama.lint.pylama_pycodestyle import Linter
LINTERS['pycodestyle'] = Linter() # for compability
LINTERS['pep8'] = Linter() # for compability
except ImportError:
pass
try:
from pylama.lint.pylama_pyflakes import Linter
LINTERS['pyflakes'] = Linter()
except ImportError:
pass
try:
from pylama.lint.pylama_pylint import Linter
LINTERS['pylint'] = Linter()
except ImportError:
pass
from pkg_resources import iter_entry_points
for entry in iter_entry_points('pylama.linter'):
if entry.name not in LINTERS:
try:
LINTERS[entry.name] = entry.load()()
except ImportError:
pass
# pylama:ignore=E0611
| Fix import Linter from pylam_pylint | Fix import Linter from pylam_pylint
| Python | mit | AtomLinter/linter-pylama | """Load extensions."""
import os
import sys
CURDIR = os.path.abspath(os.path.dirname(__file__))
sys.path.insert(0, os.path.join(CURDIR, '..', '..', 'deps'))
LINTERS = {}
try:
from pylama.lint.pylama_mccabe import Linter
LINTERS['mccabe'] = Linter()
except ImportError:
pass
try:
from pylama.lint.pylama_pydocstyle import Linter
LINTERS['pep257'] = Linter() # for compatibility
LINTERS['pydocstyle'] = Linter()
except ImportError:
pass
try:
from pylama.lint.pylama_pycodestyle import Linter
LINTERS['pycodestyle'] = Linter() # for compability
LINTERS['pep8'] = Linter() # for compability
except ImportError:
pass
try:
from pylama.lint.pylama_pyflakes import Linter
LINTERS['pyflakes'] = Linter()
except ImportError:
pass
try:
- from pylama_pylint import Linter
+ from pylama.lint.pylama_pylint import Linter
LINTERS['pylint'] = Linter()
except ImportError:
pass
from pkg_resources import iter_entry_points
for entry in iter_entry_points('pylama.linter'):
if entry.name not in LINTERS:
try:
LINTERS[entry.name] = entry.load()()
except ImportError:
pass
# pylama:ignore=E0611
| Fix import Linter from pylam_pylint | ## Code Before:
"""Load extensions."""
import os
import sys
CURDIR = os.path.abspath(os.path.dirname(__file__))
sys.path.insert(0, os.path.join(CURDIR, '..', '..', 'deps'))
LINTERS = {}
try:
from pylama.lint.pylama_mccabe import Linter
LINTERS['mccabe'] = Linter()
except ImportError:
pass
try:
from pylama.lint.pylama_pydocstyle import Linter
LINTERS['pep257'] = Linter() # for compatibility
LINTERS['pydocstyle'] = Linter()
except ImportError:
pass
try:
from pylama.lint.pylama_pycodestyle import Linter
LINTERS['pycodestyle'] = Linter() # for compability
LINTERS['pep8'] = Linter() # for compability
except ImportError:
pass
try:
from pylama.lint.pylama_pyflakes import Linter
LINTERS['pyflakes'] = Linter()
except ImportError:
pass
try:
from pylama_pylint import Linter
LINTERS['pylint'] = Linter()
except ImportError:
pass
from pkg_resources import iter_entry_points
for entry in iter_entry_points('pylama.linter'):
if entry.name not in LINTERS:
try:
LINTERS[entry.name] = entry.load()()
except ImportError:
pass
# pylama:ignore=E0611
## Instruction:
Fix import Linter from pylam_pylint
## Code After:
"""Load extensions."""
import os
import sys
CURDIR = os.path.abspath(os.path.dirname(__file__))
sys.path.insert(0, os.path.join(CURDIR, '..', '..', 'deps'))
LINTERS = {}
try:
from pylama.lint.pylama_mccabe import Linter
LINTERS['mccabe'] = Linter()
except ImportError:
pass
try:
from pylama.lint.pylama_pydocstyle import Linter
LINTERS['pep257'] = Linter() # for compatibility
LINTERS['pydocstyle'] = Linter()
except ImportError:
pass
try:
from pylama.lint.pylama_pycodestyle import Linter
LINTERS['pycodestyle'] = Linter() # for compability
LINTERS['pep8'] = Linter() # for compability
except ImportError:
pass
try:
from pylama.lint.pylama_pyflakes import Linter
LINTERS['pyflakes'] = Linter()
except ImportError:
pass
try:
from pylama.lint.pylama_pylint import Linter
LINTERS['pylint'] = Linter()
except ImportError:
pass
from pkg_resources import iter_entry_points
for entry in iter_entry_points('pylama.linter'):
if entry.name not in LINTERS:
try:
LINTERS[entry.name] = entry.load()()
except ImportError:
pass
# pylama:ignore=E0611
| """Load extensions."""
import os
import sys
CURDIR = os.path.abspath(os.path.dirname(__file__))
sys.path.insert(0, os.path.join(CURDIR, '..', '..', 'deps'))
LINTERS = {}
try:
from pylama.lint.pylama_mccabe import Linter
LINTERS['mccabe'] = Linter()
except ImportError:
pass
try:
from pylama.lint.pylama_pydocstyle import Linter
LINTERS['pep257'] = Linter() # for compatibility
LINTERS['pydocstyle'] = Linter()
except ImportError:
pass
try:
from pylama.lint.pylama_pycodestyle import Linter
LINTERS['pycodestyle'] = Linter() # for compability
LINTERS['pep8'] = Linter() # for compability
except ImportError:
pass
try:
from pylama.lint.pylama_pyflakes import Linter
LINTERS['pyflakes'] = Linter()
except ImportError:
pass
try:
- from pylama_pylint import Linter
+ from pylama.lint.pylama_pylint import Linter
? ++++++++++++
LINTERS['pylint'] = Linter()
except ImportError:
pass
from pkg_resources import iter_entry_points
for entry in iter_entry_points('pylama.linter'):
if entry.name not in LINTERS:
try:
LINTERS[entry.name] = entry.load()()
except ImportError:
pass
# pylama:ignore=E0611 |
3a9568b4d4de969b1e2031e8d2d3cdd7bd56824f | zerver/migrations/0237_rename_zulip_realm_to_zulipinternal.py | zerver/migrations/0237_rename_zulip_realm_to_zulipinternal.py | from django.conf import settings
from django.db import migrations
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
def rename_zulip_realm_to_zulipinternal(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
if not settings.PRODUCTION:
return
Realm = apps.get_model('zerver', 'Realm')
UserProfile = apps.get_model('zerver', 'UserProfile')
if Realm.objects.count() == 0:
# Database not yet populated, do nothing:
return
if Realm.objects.filter(string_id="zulipinternal").exists():
return
internal_realm = Realm.objects.get(string_id="zulip")
# For safety, as a sanity check, verify that "internal_realm" is indeed the realm for system bots:
welcome_bot = UserProfile.objects.get(email="welcome-bot@zulip.com")
assert welcome_bot.realm.id == internal_realm.id
internal_realm.string_id = "zulipinternal"
internal_realm.name = "System use only"
internal_realm.save()
class Migration(migrations.Migration):
dependencies = [
('zerver', '0236_remove_illegal_characters_email_full'),
]
operations = [
migrations.RunPython(rename_zulip_realm_to_zulipinternal)
]
| from django.conf import settings
from django.db import migrations
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
def rename_zulip_realm_to_zulipinternal(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
if not settings.PRODUCTION:
return
Realm = apps.get_model('zerver', 'Realm')
UserProfile = apps.get_model('zerver', 'UserProfile')
if Realm.objects.count() == 0:
# Database not yet populated, do nothing:
return
if Realm.objects.filter(string_id="zulipinternal").exists():
return
if not Realm.objects.filter(string_id="zulip").exists():
# If the user renamed the `zulip` system bot realm (or deleted
# it), there's nothing for us to do.
return
internal_realm = Realm.objects.get(string_id="zulip")
# For safety, as a sanity check, verify that "internal_realm" is indeed the realm for system bots:
welcome_bot = UserProfile.objects.get(email="welcome-bot@zulip.com")
assert welcome_bot.realm.id == internal_realm.id
internal_realm.string_id = "zulipinternal"
internal_realm.name = "System use only"
internal_realm.save()
class Migration(migrations.Migration):
dependencies = [
('zerver', '0236_remove_illegal_characters_email_full'),
]
operations = [
migrations.RunPython(rename_zulip_realm_to_zulipinternal)
]
| Fix zulipinternal migration corner case. | migrations: Fix zulipinternal migration corner case.
It's theoretically possible to have configured a Zulip server where
the system bots live in the same realm as normal users (and may have
in fact been the default in early Zulip releases? Unclear.). We
should handle these without the migration intended to clean up naming
for the system bot realm crashing.
Fixes #13660.
| Python | apache-2.0 | brainwane/zulip,andersk/zulip,hackerkid/zulip,synicalsyntax/zulip,andersk/zulip,hackerkid/zulip,punchagan/zulip,shubhamdhama/zulip,showell/zulip,zulip/zulip,synicalsyntax/zulip,kou/zulip,rht/zulip,showell/zulip,brainwane/zulip,punchagan/zulip,shubhamdhama/zulip,hackerkid/zulip,andersk/zulip,kou/zulip,brainwane/zulip,brainwane/zulip,andersk/zulip,showell/zulip,shubhamdhama/zulip,kou/zulip,punchagan/zulip,zulip/zulip,kou/zulip,showell/zulip,brainwane/zulip,eeshangarg/zulip,timabbott/zulip,eeshangarg/zulip,hackerkid/zulip,shubhamdhama/zulip,zulip/zulip,timabbott/zulip,brainwane/zulip,eeshangarg/zulip,rht/zulip,zulip/zulip,timabbott/zulip,rht/zulip,synicalsyntax/zulip,andersk/zulip,showell/zulip,shubhamdhama/zulip,rht/zulip,hackerkid/zulip,rht/zulip,hackerkid/zulip,eeshangarg/zulip,kou/zulip,synicalsyntax/zulip,brainwane/zulip,shubhamdhama/zulip,eeshangarg/zulip,andersk/zulip,rht/zulip,timabbott/zulip,punchagan/zulip,showell/zulip,eeshangarg/zulip,synicalsyntax/zulip,punchagan/zulip,timabbott/zulip,zulip/zulip,andersk/zulip,punchagan/zulip,zulip/zulip,hackerkid/zulip,timabbott/zulip,synicalsyntax/zulip,zulip/zulip,showell/zulip,eeshangarg/zulip,kou/zulip,punchagan/zulip,synicalsyntax/zulip,rht/zulip,kou/zulip,timabbott/zulip,shubhamdhama/zulip | from django.conf import settings
from django.db import migrations
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
def rename_zulip_realm_to_zulipinternal(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
if not settings.PRODUCTION:
return
Realm = apps.get_model('zerver', 'Realm')
UserProfile = apps.get_model('zerver', 'UserProfile')
if Realm.objects.count() == 0:
# Database not yet populated, do nothing:
return
if Realm.objects.filter(string_id="zulipinternal").exists():
+ return
+ if not Realm.objects.filter(string_id="zulip").exists():
+ # If the user renamed the `zulip` system bot realm (or deleted
+ # it), there's nothing for us to do.
return
internal_realm = Realm.objects.get(string_id="zulip")
# For safety, as a sanity check, verify that "internal_realm" is indeed the realm for system bots:
welcome_bot = UserProfile.objects.get(email="welcome-bot@zulip.com")
assert welcome_bot.realm.id == internal_realm.id
internal_realm.string_id = "zulipinternal"
internal_realm.name = "System use only"
internal_realm.save()
class Migration(migrations.Migration):
dependencies = [
('zerver', '0236_remove_illegal_characters_email_full'),
]
operations = [
migrations.RunPython(rename_zulip_realm_to_zulipinternal)
]
| Fix zulipinternal migration corner case. | ## Code Before:
from django.conf import settings
from django.db import migrations
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
def rename_zulip_realm_to_zulipinternal(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
if not settings.PRODUCTION:
return
Realm = apps.get_model('zerver', 'Realm')
UserProfile = apps.get_model('zerver', 'UserProfile')
if Realm.objects.count() == 0:
# Database not yet populated, do nothing:
return
if Realm.objects.filter(string_id="zulipinternal").exists():
return
internal_realm = Realm.objects.get(string_id="zulip")
# For safety, as a sanity check, verify that "internal_realm" is indeed the realm for system bots:
welcome_bot = UserProfile.objects.get(email="welcome-bot@zulip.com")
assert welcome_bot.realm.id == internal_realm.id
internal_realm.string_id = "zulipinternal"
internal_realm.name = "System use only"
internal_realm.save()
class Migration(migrations.Migration):
dependencies = [
('zerver', '0236_remove_illegal_characters_email_full'),
]
operations = [
migrations.RunPython(rename_zulip_realm_to_zulipinternal)
]
## Instruction:
Fix zulipinternal migration corner case.
## Code After:
from django.conf import settings
from django.db import migrations
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
def rename_zulip_realm_to_zulipinternal(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
if not settings.PRODUCTION:
return
Realm = apps.get_model('zerver', 'Realm')
UserProfile = apps.get_model('zerver', 'UserProfile')
if Realm.objects.count() == 0:
# Database not yet populated, do nothing:
return
if Realm.objects.filter(string_id="zulipinternal").exists():
return
if not Realm.objects.filter(string_id="zulip").exists():
# If the user renamed the `zulip` system bot realm (or deleted
# it), there's nothing for us to do.
return
internal_realm = Realm.objects.get(string_id="zulip")
# For safety, as a sanity check, verify that "internal_realm" is indeed the realm for system bots:
welcome_bot = UserProfile.objects.get(email="welcome-bot@zulip.com")
assert welcome_bot.realm.id == internal_realm.id
internal_realm.string_id = "zulipinternal"
internal_realm.name = "System use only"
internal_realm.save()
class Migration(migrations.Migration):
dependencies = [
('zerver', '0236_remove_illegal_characters_email_full'),
]
operations = [
migrations.RunPython(rename_zulip_realm_to_zulipinternal)
]
| from django.conf import settings
from django.db import migrations
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
def rename_zulip_realm_to_zulipinternal(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
if not settings.PRODUCTION:
return
Realm = apps.get_model('zerver', 'Realm')
UserProfile = apps.get_model('zerver', 'UserProfile')
if Realm.objects.count() == 0:
# Database not yet populated, do nothing:
return
if Realm.objects.filter(string_id="zulipinternal").exists():
+ return
+ if not Realm.objects.filter(string_id="zulip").exists():
+ # If the user renamed the `zulip` system bot realm (or deleted
+ # it), there's nothing for us to do.
return
internal_realm = Realm.objects.get(string_id="zulip")
# For safety, as a sanity check, verify that "internal_realm" is indeed the realm for system bots:
welcome_bot = UserProfile.objects.get(email="welcome-bot@zulip.com")
assert welcome_bot.realm.id == internal_realm.id
internal_realm.string_id = "zulipinternal"
internal_realm.name = "System use only"
internal_realm.save()
class Migration(migrations.Migration):
dependencies = [
('zerver', '0236_remove_illegal_characters_email_full'),
]
operations = [
migrations.RunPython(rename_zulip_realm_to_zulipinternal)
] |
ad4b6663a2de08fddc0ebef8a08e1f405c0cb80a | pkgcmp/cli.py | pkgcmp/cli.py | '''
Parse CLI options
'''
# Import python libs
import os
import copy
import argparse
# Import pkgcmp libs
import pkgcmp.scan
# Import third party libs
import yaml
DEFAULTS = {'cachedir': '/var/cache/pkgcmp'}
def parse():
'''
Parse!!
'''
parser = argparse.ArgumentParser(description='The pkgcmp map generator')
parser.add_argument(
'--cachedir',
dest='cachedir',
default=None,
help='The location to store all the files while working')
parser.add_argument(
'--config',
dest='config',
default='/etc/pkgcmp/pkgcmp',
help='The location of the pkgcmp config file')
opts = parser.parse_args().__dict__
conf = config(opts['config'])
for key in opts:
if opts[key] is not None:
conf[key] = opts[key]
return conf
def config(cfn):
'''
Read in the config file
'''
ret = copy.copy(DEFAULTS)
if os.path.isfile(cfn):
with open(cfn, 'r') as cfp:
conf = yaml.safe_load(cfp)
if isinstance(conf, dict):
ret.update(conf)
return ret
class PkgCmp:
'''
Build and run the application
'''
def __init__(self):
self.opts = parse()
self.scan = pkgcmp.scan.Scanner(self.opts)
def run(self):
self.scan.run()
| '''
Parse CLI options
'''
# Import python libs
import os
import copy
import argparse
# Import pkgcmp libs
import pkgcmp.scan
# Import third party libs
import yaml
DEFAULTS = {'cachedir': '/var/cache/pkgcmp',
'extension_modules': ''}
def parse():
'''
Parse!!
'''
parser = argparse.ArgumentParser(description='The pkgcmp map generator')
parser.add_argument(
'--cachedir',
dest='cachedir',
default=None,
help='The location to store all the files while working')
parser.add_argument(
'--config',
dest='config',
default='/etc/pkgcmp/pkgcmp',
help='The location of the pkgcmp config file')
opts = parser.parse_args().__dict__
conf = config(opts['config'])
for key in opts:
if opts[key] is not None:
conf[key] = opts[key]
return conf
def config(cfn):
'''
Read in the config file
'''
ret = copy.copy(DEFAULTS)
if os.path.isfile(cfn):
with open(cfn, 'r') as cfp:
conf = yaml.safe_load(cfp)
if isinstance(conf, dict):
ret.update(conf)
return ret
class PkgCmp:
'''
Build and run the application
'''
def __init__(self):
self.opts = parse()
self.scan = pkgcmp.scan.Scanner(self.opts)
def run(self):
self.scan.run()
| Add extension_modueles to the default configuration | Add extension_modueles to the default configuration
| Python | apache-2.0 | SS-RD/pkgcmp | '''
Parse CLI options
'''
# Import python libs
import os
import copy
import argparse
# Import pkgcmp libs
import pkgcmp.scan
# Import third party libs
import yaml
- DEFAULTS = {'cachedir': '/var/cache/pkgcmp'}
+ DEFAULTS = {'cachedir': '/var/cache/pkgcmp',
+ 'extension_modules': ''}
def parse():
'''
Parse!!
'''
parser = argparse.ArgumentParser(description='The pkgcmp map generator')
parser.add_argument(
'--cachedir',
dest='cachedir',
default=None,
help='The location to store all the files while working')
parser.add_argument(
'--config',
dest='config',
default='/etc/pkgcmp/pkgcmp',
help='The location of the pkgcmp config file')
opts = parser.parse_args().__dict__
conf = config(opts['config'])
for key in opts:
if opts[key] is not None:
conf[key] = opts[key]
return conf
def config(cfn):
'''
Read in the config file
'''
ret = copy.copy(DEFAULTS)
if os.path.isfile(cfn):
with open(cfn, 'r') as cfp:
conf = yaml.safe_load(cfp)
if isinstance(conf, dict):
ret.update(conf)
return ret
class PkgCmp:
'''
Build and run the application
'''
def __init__(self):
self.opts = parse()
self.scan = pkgcmp.scan.Scanner(self.opts)
def run(self):
self.scan.run()
| Add extension_modueles to the default configuration | ## Code Before:
'''
Parse CLI options
'''
# Import python libs
import os
import copy
import argparse
# Import pkgcmp libs
import pkgcmp.scan
# Import third party libs
import yaml
DEFAULTS = {'cachedir': '/var/cache/pkgcmp'}
def parse():
'''
Parse!!
'''
parser = argparse.ArgumentParser(description='The pkgcmp map generator')
parser.add_argument(
'--cachedir',
dest='cachedir',
default=None,
help='The location to store all the files while working')
parser.add_argument(
'--config',
dest='config',
default='/etc/pkgcmp/pkgcmp',
help='The location of the pkgcmp config file')
opts = parser.parse_args().__dict__
conf = config(opts['config'])
for key in opts:
if opts[key] is not None:
conf[key] = opts[key]
return conf
def config(cfn):
'''
Read in the config file
'''
ret = copy.copy(DEFAULTS)
if os.path.isfile(cfn):
with open(cfn, 'r') as cfp:
conf = yaml.safe_load(cfp)
if isinstance(conf, dict):
ret.update(conf)
return ret
class PkgCmp:
'''
Build and run the application
'''
def __init__(self):
self.opts = parse()
self.scan = pkgcmp.scan.Scanner(self.opts)
def run(self):
self.scan.run()
## Instruction:
Add extension_modueles to the default configuration
## Code After:
'''
Parse CLI options
'''
# Import python libs
import os
import copy
import argparse
# Import pkgcmp libs
import pkgcmp.scan
# Import third party libs
import yaml
DEFAULTS = {'cachedir': '/var/cache/pkgcmp',
'extension_modules': ''}
def parse():
'''
Parse!!
'''
parser = argparse.ArgumentParser(description='The pkgcmp map generator')
parser.add_argument(
'--cachedir',
dest='cachedir',
default=None,
help='The location to store all the files while working')
parser.add_argument(
'--config',
dest='config',
default='/etc/pkgcmp/pkgcmp',
help='The location of the pkgcmp config file')
opts = parser.parse_args().__dict__
conf = config(opts['config'])
for key in opts:
if opts[key] is not None:
conf[key] = opts[key]
return conf
def config(cfn):
'''
Read in the config file
'''
ret = copy.copy(DEFAULTS)
if os.path.isfile(cfn):
with open(cfn, 'r') as cfp:
conf = yaml.safe_load(cfp)
if isinstance(conf, dict):
ret.update(conf)
return ret
class PkgCmp:
'''
Build and run the application
'''
def __init__(self):
self.opts = parse()
self.scan = pkgcmp.scan.Scanner(self.opts)
def run(self):
self.scan.run()
| '''
Parse CLI options
'''
# Import python libs
import os
import copy
import argparse
# Import pkgcmp libs
import pkgcmp.scan
# Import third party libs
import yaml
- DEFAULTS = {'cachedir': '/var/cache/pkgcmp'}
? ^
+ DEFAULTS = {'cachedir': '/var/cache/pkgcmp',
? ^
+ 'extension_modules': ''}
def parse():
'''
Parse!!
'''
parser = argparse.ArgumentParser(description='The pkgcmp map generator')
parser.add_argument(
'--cachedir',
dest='cachedir',
default=None,
help='The location to store all the files while working')
parser.add_argument(
'--config',
dest='config',
default='/etc/pkgcmp/pkgcmp',
help='The location of the pkgcmp config file')
opts = parser.parse_args().__dict__
conf = config(opts['config'])
for key in opts:
if opts[key] is not None:
conf[key] = opts[key]
return conf
def config(cfn):
'''
Read in the config file
'''
ret = copy.copy(DEFAULTS)
if os.path.isfile(cfn):
with open(cfn, 'r') as cfp:
conf = yaml.safe_load(cfp)
if isinstance(conf, dict):
ret.update(conf)
return ret
class PkgCmp:
'''
Build and run the application
'''
def __init__(self):
self.opts = parse()
self.scan = pkgcmp.scan.Scanner(self.opts)
def run(self):
self.scan.run() |
8d7862a7045fbb52ce3a2499766ffa1ffef284af | tests/settings.py | tests/settings.py | from moztrap.settings.default import *
DEFAULT_FILE_STORAGE = "tests.storage.MemoryStorage"
ALLOW_ANONYMOUS_ACCESS = False
SITE_URL = "http://localhost:80"
USE_BROWSERID = True
| from moztrap.settings.default import *
DEFAULT_FILE_STORAGE = "tests.storage.MemoryStorage"
ALLOW_ANONYMOUS_ACCESS = False
SITE_URL = "http://localhost:80"
USE_BROWSERID = True
PASSWORD_HASHERS = ['django.contrib.auth.hashers.UnsaltedMD5PasswordHasher']
| Use faster password hashing in tests. | Use faster password hashing in tests.
| Python | bsd-2-clause | mccarrmb/moztrap,bobsilverberg/moztrap,mozilla/moztrap,mccarrmb/moztrap,shinglyu/moztrap,mccarrmb/moztrap,shinglyu/moztrap,mccarrmb/moztrap,shinglyu/moztrap,mccarrmb/moztrap,bobsilverberg/moztrap,mozilla/moztrap,bobsilverberg/moztrap,shinglyu/moztrap,mozilla/moztrap,shinglyu/moztrap,bobsilverberg/moztrap,mozilla/moztrap,mozilla/moztrap | from moztrap.settings.default import *
DEFAULT_FILE_STORAGE = "tests.storage.MemoryStorage"
ALLOW_ANONYMOUS_ACCESS = False
SITE_URL = "http://localhost:80"
USE_BROWSERID = True
+ PASSWORD_HASHERS = ['django.contrib.auth.hashers.UnsaltedMD5PasswordHasher']
+ | Use faster password hashing in tests. | ## Code Before:
from moztrap.settings.default import *
DEFAULT_FILE_STORAGE = "tests.storage.MemoryStorage"
ALLOW_ANONYMOUS_ACCESS = False
SITE_URL = "http://localhost:80"
USE_BROWSERID = True
## Instruction:
Use faster password hashing in tests.
## Code After:
from moztrap.settings.default import *
DEFAULT_FILE_STORAGE = "tests.storage.MemoryStorage"
ALLOW_ANONYMOUS_ACCESS = False
SITE_URL = "http://localhost:80"
USE_BROWSERID = True
PASSWORD_HASHERS = ['django.contrib.auth.hashers.UnsaltedMD5PasswordHasher']
| from moztrap.settings.default import *
DEFAULT_FILE_STORAGE = "tests.storage.MemoryStorage"
ALLOW_ANONYMOUS_ACCESS = False
SITE_URL = "http://localhost:80"
USE_BROWSERID = True
+
+ PASSWORD_HASHERS = ['django.contrib.auth.hashers.UnsaltedMD5PasswordHasher'] |
2cecc2e197e4a4089e29b350179103e323136268 | ddb_ngsflow/variation/sv/itdseek.py | ddb_ngsflow/variation/sv/itdseek.py |
from ddb_ngsflow import pipeline
def run_flt3_itdseek(job, config, name, samples):
"""Run ITDseek without a matched normal sample
:param config: The configuration dictionary.
:type config: dict.
:param name: sample name.
:type name: str.
:param samples: The samples configuration dictionary.
:type config: dict.
:returns: str -- The output vcf file name.
"""
itdseek_vcf = "{}.flt3.itdseek.vcf".format(name)
itdseek_logfile = "{}.flt3.itdseek.log".format(name)
itdseek_command = ["{}".format(config['itdseek']['bin']),
"{}.rg.sorted.bam".format(name),
"{}".format(config['reference']),
"{}".format(config['samtools-0.19']['bin']),
">",
"{}".format(itdseek_vcf)]
job.fileStore.logToMaster("ITDSeek Command: {}\n".format(itdseek_command))
pipeline.run_and_log_command(" ".join(itdseek_command), itdseek_logfile)
return itdseek_vcf
|
from ddb_ngsflow import pipeline
def run_flt3_itdseek(job, config, name):
"""Run ITDseek without a matched normal sample
:param config: The configuration dictionary.
:type config: dict.
:param name: sample name.
:type name: str.
:returns: str -- The output vcf file name.
"""
itdseek_vcf = "{}.flt3.itdseek.vcf".format(name)
itdseek_logfile = "{}.flt3.itdseek.log".format(name)
itdseek_command = ["{}".format(config['itdseek']['bin']),
"{}.rg.sorted.bam".format(name),
"{}".format(config['reference']),
"{}".format(config['samtools-0.19']['bin']),
">",
"{}".format(itdseek_vcf)]
job.fileStore.logToMaster("ITDSeek Command: {}\n".format(itdseek_command))
pipeline.run_and_log_command(" ".join(itdseek_command), itdseek_logfile)
return itdseek_vcf
| Remove unneeded samples config passing | Remove unneeded samples config passing
| Python | mit | dgaston/ddb-ngsflow,dgaston/ddbio-ngsflow |
from ddb_ngsflow import pipeline
- def run_flt3_itdseek(job, config, name, samples):
+ def run_flt3_itdseek(job, config, name):
"""Run ITDseek without a matched normal sample
:param config: The configuration dictionary.
:type config: dict.
:param name: sample name.
:type name: str.
- :param samples: The samples configuration dictionary.
- :type config: dict.
:returns: str -- The output vcf file name.
"""
itdseek_vcf = "{}.flt3.itdseek.vcf".format(name)
itdseek_logfile = "{}.flt3.itdseek.log".format(name)
itdseek_command = ["{}".format(config['itdseek']['bin']),
"{}.rg.sorted.bam".format(name),
"{}".format(config['reference']),
"{}".format(config['samtools-0.19']['bin']),
">",
"{}".format(itdseek_vcf)]
job.fileStore.logToMaster("ITDSeek Command: {}\n".format(itdseek_command))
pipeline.run_and_log_command(" ".join(itdseek_command), itdseek_logfile)
return itdseek_vcf
| Remove unneeded samples config passing | ## Code Before:
from ddb_ngsflow import pipeline
def run_flt3_itdseek(job, config, name, samples):
"""Run ITDseek without a matched normal sample
:param config: The configuration dictionary.
:type config: dict.
:param name: sample name.
:type name: str.
:param samples: The samples configuration dictionary.
:type config: dict.
:returns: str -- The output vcf file name.
"""
itdseek_vcf = "{}.flt3.itdseek.vcf".format(name)
itdseek_logfile = "{}.flt3.itdseek.log".format(name)
itdseek_command = ["{}".format(config['itdseek']['bin']),
"{}.rg.sorted.bam".format(name),
"{}".format(config['reference']),
"{}".format(config['samtools-0.19']['bin']),
">",
"{}".format(itdseek_vcf)]
job.fileStore.logToMaster("ITDSeek Command: {}\n".format(itdseek_command))
pipeline.run_and_log_command(" ".join(itdseek_command), itdseek_logfile)
return itdseek_vcf
## Instruction:
Remove unneeded samples config passing
## Code After:
from ddb_ngsflow import pipeline
def run_flt3_itdseek(job, config, name):
"""Run ITDseek without a matched normal sample
:param config: The configuration dictionary.
:type config: dict.
:param name: sample name.
:type name: str.
:returns: str -- The output vcf file name.
"""
itdseek_vcf = "{}.flt3.itdseek.vcf".format(name)
itdseek_logfile = "{}.flt3.itdseek.log".format(name)
itdseek_command = ["{}".format(config['itdseek']['bin']),
"{}.rg.sorted.bam".format(name),
"{}".format(config['reference']),
"{}".format(config['samtools-0.19']['bin']),
">",
"{}".format(itdseek_vcf)]
job.fileStore.logToMaster("ITDSeek Command: {}\n".format(itdseek_command))
pipeline.run_and_log_command(" ".join(itdseek_command), itdseek_logfile)
return itdseek_vcf
|
from ddb_ngsflow import pipeline
- def run_flt3_itdseek(job, config, name, samples):
? ---------
+ def run_flt3_itdseek(job, config, name):
"""Run ITDseek without a matched normal sample
:param config: The configuration dictionary.
:type config: dict.
:param name: sample name.
:type name: str.
- :param samples: The samples configuration dictionary.
- :type config: dict.
:returns: str -- The output vcf file name.
"""
itdseek_vcf = "{}.flt3.itdseek.vcf".format(name)
itdseek_logfile = "{}.flt3.itdseek.log".format(name)
itdseek_command = ["{}".format(config['itdseek']['bin']),
"{}.rg.sorted.bam".format(name),
"{}".format(config['reference']),
"{}".format(config['samtools-0.19']['bin']),
">",
"{}".format(itdseek_vcf)]
job.fileStore.logToMaster("ITDSeek Command: {}\n".format(itdseek_command))
pipeline.run_and_log_command(" ".join(itdseek_command), itdseek_logfile)
return itdseek_vcf |
f80febf88c3f045493e75efc788d88058f021f0f | merge_sort.py | merge_sort.py |
def merge_sort(lyst):
buf = [len(lyst)]
_merge_sort(lyst, buf, 0, len(lyst)-1)
def _merge_sort(lyst, buf, low, high):
if low < high:
middle = (low + high) // 2
_merge_sort(lyst, buf, low, middle)
_merge_sort(lyst, buf, middle+1, high)
merge(lyst, buf, low, middle, high)
def merge(lyst, buf, low, middle, high):
i1 = low
i2 = middle + 1
for i in range(low, high):
if i1 > middle:
buf[i] = lyst[i2]
i2 += 1
elif i2 > high:
buf[i] = lyst[i1]
i1 += 1
elif lyst[i1] < lyst[i2]:
buf[i] = lyst[i]
i1 += 1
else:
buf[i] = lyst[i2]
i2 += 1
for i in range(low, high):
lyst[i] = buf[i]
|
def merge_sort(lyst):
buf = [None for x in range(len(lyst))]
_merge_sort(lyst, buf, 0, len(lyst)-1)
def _merge_sort(lyst, buf, low, high):
if low < high:
middle = (low + high) // 2
_merge_sort(lyst, buf, low, middle)
_merge_sort(lyst, buf, middle+1, high)
merge(lyst, buf, low, middle, high)
def merge(lyst, buf, low, middle, high):
i1 = low
i2 = middle + 1
for i in range(low, high+1):
if i1 > middle:
buf[i] = lyst[i2]
i2 += 1
elif i2 > high:
buf[i] = lyst[i1]
i1 += 1
elif lyst[i1] < lyst[i2]:
buf[i] = lyst[i]
i1 += 1
else:
buf[i] = lyst[i2]
i2 += 1
for i in range(low, high+1):
lyst[i] = buf[i]
| Fix initial buf variable to act as an array | Fix initial buf variable to act as an array
| Python | mit | nbeck90/data_structures_2 |
def merge_sort(lyst):
- buf = [len(lyst)]
+ buf = [None for x in range(len(lyst))]
_merge_sort(lyst, buf, 0, len(lyst)-1)
def _merge_sort(lyst, buf, low, high):
if low < high:
middle = (low + high) // 2
_merge_sort(lyst, buf, low, middle)
_merge_sort(lyst, buf, middle+1, high)
merge(lyst, buf, low, middle, high)
def merge(lyst, buf, low, middle, high):
i1 = low
i2 = middle + 1
- for i in range(low, high):
+ for i in range(low, high+1):
if i1 > middle:
buf[i] = lyst[i2]
i2 += 1
elif i2 > high:
buf[i] = lyst[i1]
i1 += 1
elif lyst[i1] < lyst[i2]:
buf[i] = lyst[i]
i1 += 1
else:
buf[i] = lyst[i2]
i2 += 1
- for i in range(low, high):
+ for i in range(low, high+1):
lyst[i] = buf[i]
| Fix initial buf variable to act as an array | ## Code Before:
def merge_sort(lyst):
buf = [len(lyst)]
_merge_sort(lyst, buf, 0, len(lyst)-1)
def _merge_sort(lyst, buf, low, high):
if low < high:
middle = (low + high) // 2
_merge_sort(lyst, buf, low, middle)
_merge_sort(lyst, buf, middle+1, high)
merge(lyst, buf, low, middle, high)
def merge(lyst, buf, low, middle, high):
i1 = low
i2 = middle + 1
for i in range(low, high):
if i1 > middle:
buf[i] = lyst[i2]
i2 += 1
elif i2 > high:
buf[i] = lyst[i1]
i1 += 1
elif lyst[i1] < lyst[i2]:
buf[i] = lyst[i]
i1 += 1
else:
buf[i] = lyst[i2]
i2 += 1
for i in range(low, high):
lyst[i] = buf[i]
## Instruction:
Fix initial buf variable to act as an array
## Code After:
def merge_sort(lyst):
buf = [None for x in range(len(lyst))]
_merge_sort(lyst, buf, 0, len(lyst)-1)
def _merge_sort(lyst, buf, low, high):
if low < high:
middle = (low + high) // 2
_merge_sort(lyst, buf, low, middle)
_merge_sort(lyst, buf, middle+1, high)
merge(lyst, buf, low, middle, high)
def merge(lyst, buf, low, middle, high):
i1 = low
i2 = middle + 1
for i in range(low, high+1):
if i1 > middle:
buf[i] = lyst[i2]
i2 += 1
elif i2 > high:
buf[i] = lyst[i1]
i1 += 1
elif lyst[i1] < lyst[i2]:
buf[i] = lyst[i]
i1 += 1
else:
buf[i] = lyst[i2]
i2 += 1
for i in range(low, high+1):
lyst[i] = buf[i]
|
def merge_sort(lyst):
- buf = [len(lyst)]
+ buf = [None for x in range(len(lyst))]
_merge_sort(lyst, buf, 0, len(lyst)-1)
def _merge_sort(lyst, buf, low, high):
if low < high:
middle = (low + high) // 2
_merge_sort(lyst, buf, low, middle)
_merge_sort(lyst, buf, middle+1, high)
merge(lyst, buf, low, middle, high)
def merge(lyst, buf, low, middle, high):
i1 = low
i2 = middle + 1
- for i in range(low, high):
+ for i in range(low, high+1):
? ++
if i1 > middle:
buf[i] = lyst[i2]
i2 += 1
elif i2 > high:
buf[i] = lyst[i1]
i1 += 1
elif lyst[i1] < lyst[i2]:
buf[i] = lyst[i]
i1 += 1
else:
buf[i] = lyst[i2]
i2 += 1
- for i in range(low, high):
+ for i in range(low, high+1):
? ++
lyst[i] = buf[i] |
243feb2fe194ad00f59c6ff22ac41989fe0978d1 | bots.sample/number-jokes/__init__.py | bots.sample/number-jokes/__init__.py | import random
from botfriend.bot import TextGeneratorBot
class ExampleBot(TextGeneratorBot):
def generate_text(self):
"""Tell a joke about numbers."""
num = random.randint(1,10)
arguments = dict(
num=num,
plus_1=num+1,
plus_3=num+3
)
setup = "Why is %(num)d afraid of %(plus_1)d? "
punchline = "Because %(plus_1)d ate %(plus_3)d!"
return (setup + punchline) % arguments
Bot = ExampleBot
| import random
from botfriend.bot import TextGeneratorBot
class NumberJokes(TextGeneratorBot):
def generate_text(self):
"""Tell a joke about numbers."""
num = random.randint(1,10)
arguments = dict(
num=num,
plus_1=num+1,
plus_3=num+3
)
setup = "Why is %(num)d afraid of %(plus_1)d? "
punchline = "Because %(plus_1)d ate %(plus_3)d!"
return (setup + punchline) % arguments
Bot = NumberJokes
| Change number-jokes to match the tutorial. | Change number-jokes to match the tutorial.
| Python | mit | leonardr/botfriend | import random
from botfriend.bot import TextGeneratorBot
- class ExampleBot(TextGeneratorBot):
+ class NumberJokes(TextGeneratorBot):
def generate_text(self):
"""Tell a joke about numbers."""
num = random.randint(1,10)
arguments = dict(
num=num,
plus_1=num+1,
plus_3=num+3
)
setup = "Why is %(num)d afraid of %(plus_1)d? "
punchline = "Because %(plus_1)d ate %(plus_3)d!"
return (setup + punchline) % arguments
- Bot = ExampleBot
+ Bot = NumberJokes
| Change number-jokes to match the tutorial. | ## Code Before:
import random
from botfriend.bot import TextGeneratorBot
class ExampleBot(TextGeneratorBot):
def generate_text(self):
"""Tell a joke about numbers."""
num = random.randint(1,10)
arguments = dict(
num=num,
plus_1=num+1,
plus_3=num+3
)
setup = "Why is %(num)d afraid of %(plus_1)d? "
punchline = "Because %(plus_1)d ate %(plus_3)d!"
return (setup + punchline) % arguments
Bot = ExampleBot
## Instruction:
Change number-jokes to match the tutorial.
## Code After:
import random
from botfriend.bot import TextGeneratorBot
class NumberJokes(TextGeneratorBot):
def generate_text(self):
"""Tell a joke about numbers."""
num = random.randint(1,10)
arguments = dict(
num=num,
plus_1=num+1,
plus_3=num+3
)
setup = "Why is %(num)d afraid of %(plus_1)d? "
punchline = "Because %(plus_1)d ate %(plus_3)d!"
return (setup + punchline) % arguments
Bot = NumberJokes
| import random
from botfriend.bot import TextGeneratorBot
- class ExampleBot(TextGeneratorBot):
? ^^^ ^^ ^ ^
+ class NumberJokes(TextGeneratorBot):
? ^^ ^ ^^ ^^^
def generate_text(self):
"""Tell a joke about numbers."""
num = random.randint(1,10)
arguments = dict(
num=num,
plus_1=num+1,
plus_3=num+3
)
setup = "Why is %(num)d afraid of %(plus_1)d? "
punchline = "Because %(plus_1)d ate %(plus_3)d!"
return (setup + punchline) % arguments
- Bot = ExampleBot
+ Bot = NumberJokes |
8b09bc6854075f43bf408169a743d023f60fbe0b | telemetry/telemetry/page/actions/navigate.py | telemetry/telemetry/page/actions/navigate.py |
from telemetry.page.actions import page_action
class NavigateAction(page_action.PageAction):
def __init__(self, attributes=None):
super(NavigateAction, self).__init__(attributes)
def RunAction(self, page, tab):
if page.is_file:
target_side_url = tab.browser.http_server.UrlOf(page.file_path_url)
else:
target_side_url = page.url
tab.Navigate(target_side_url, page.script_to_evaluate_on_commit)
tab.WaitForDocumentReadyStateToBeInteractiveOrBetter()
|
from telemetry.page.actions import page_action
class NavigateAction(page_action.PageAction):
def __init__(self, attributes=None):
super(NavigateAction, self).__init__(attributes)
def RunAction(self, page, tab):
if page.is_file:
target_side_url = tab.browser.http_server.UrlOf(page.file_path_url)
else:
target_side_url = page.url
if hasattr(self, 'timeout_seconds') and self.timeout_seconds:
tab.Navigate(target_side_url,
page.script_to_evaluate_on_commit,
self.timeout_seconds)
else:
tab.Navigate(target_side_url, page.script_to_evaluate_on_commit)
tab.WaitForDocumentReadyStateToBeInteractiveOrBetter()
| Add a timeout attr to NavigateAction. | Add a timeout attr to NavigateAction.
BUG=320748
Review URL: https://codereview.chromium.org/202483006
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@257922 0039d316-1c4b-4281-b951-d872f2087c98
| Python | bsd-3-clause | catapult-project/catapult,catapult-project/catapult,SummerLW/Perf-Insight-Report,sahiljain/catapult,benschmaus/catapult,benschmaus/catapult,catapult-project/catapult,catapult-project/catapult-csm,catapult-project/catapult,catapult-project/catapult,catapult-project/catapult-csm,benschmaus/catapult,catapult-project/catapult-csm,catapult-project/catapult,sahiljain/catapult,SummerLW/Perf-Insight-Report,catapult-project/catapult-csm,catapult-project/catapult-csm,SummerLW/Perf-Insight-Report,SummerLW/Perf-Insight-Report,catapult-project/catapult-csm,benschmaus/catapult,sahiljain/catapult,SummerLW/Perf-Insight-Report,catapult-project/catapult,catapult-project/catapult-csm,sahiljain/catapult,sahiljain/catapult,benschmaus/catapult,SummerLW/Perf-Insight-Report,benschmaus/catapult,sahiljain/catapult,benschmaus/catapult |
from telemetry.page.actions import page_action
class NavigateAction(page_action.PageAction):
def __init__(self, attributes=None):
super(NavigateAction, self).__init__(attributes)
def RunAction(self, page, tab):
if page.is_file:
target_side_url = tab.browser.http_server.UrlOf(page.file_path_url)
else:
target_side_url = page.url
+ if hasattr(self, 'timeout_seconds') and self.timeout_seconds:
+ tab.Navigate(target_side_url,
+ page.script_to_evaluate_on_commit,
+ self.timeout_seconds)
+ else:
- tab.Navigate(target_side_url, page.script_to_evaluate_on_commit)
+ tab.Navigate(target_side_url, page.script_to_evaluate_on_commit)
tab.WaitForDocumentReadyStateToBeInteractiveOrBetter()
| Add a timeout attr to NavigateAction. | ## Code Before:
from telemetry.page.actions import page_action
class NavigateAction(page_action.PageAction):
def __init__(self, attributes=None):
super(NavigateAction, self).__init__(attributes)
def RunAction(self, page, tab):
if page.is_file:
target_side_url = tab.browser.http_server.UrlOf(page.file_path_url)
else:
target_side_url = page.url
tab.Navigate(target_side_url, page.script_to_evaluate_on_commit)
tab.WaitForDocumentReadyStateToBeInteractiveOrBetter()
## Instruction:
Add a timeout attr to NavigateAction.
## Code After:
from telemetry.page.actions import page_action
class NavigateAction(page_action.PageAction):
def __init__(self, attributes=None):
super(NavigateAction, self).__init__(attributes)
def RunAction(self, page, tab):
if page.is_file:
target_side_url = tab.browser.http_server.UrlOf(page.file_path_url)
else:
target_side_url = page.url
if hasattr(self, 'timeout_seconds') and self.timeout_seconds:
tab.Navigate(target_side_url,
page.script_to_evaluate_on_commit,
self.timeout_seconds)
else:
tab.Navigate(target_side_url, page.script_to_evaluate_on_commit)
tab.WaitForDocumentReadyStateToBeInteractiveOrBetter()
|
from telemetry.page.actions import page_action
class NavigateAction(page_action.PageAction):
def __init__(self, attributes=None):
super(NavigateAction, self).__init__(attributes)
def RunAction(self, page, tab):
if page.is_file:
target_side_url = tab.browser.http_server.UrlOf(page.file_path_url)
else:
target_side_url = page.url
+ if hasattr(self, 'timeout_seconds') and self.timeout_seconds:
+ tab.Navigate(target_side_url,
+ page.script_to_evaluate_on_commit,
+ self.timeout_seconds)
+ else:
- tab.Navigate(target_side_url, page.script_to_evaluate_on_commit)
+ tab.Navigate(target_side_url, page.script_to_evaluate_on_commit)
? ++
tab.WaitForDocumentReadyStateToBeInteractiveOrBetter() |
09ec6e4611a763e823a5e3d15fb233a0132fd06b | imagersite/imagersite/tests.py | imagersite/imagersite/tests.py | from django.test import Client, TestCase
from django.contrib.auth.models import User
HOME = '/'
REGISTER = '/accounts/register/'
LOGIN = '/login'
LOGOUT = '/logout'
class UnauthenticatedUser(TestCase):
"""Create unauth user for testing."""
def setUp(self):
"""Setup unauth user."""
client = Client()
self.home = client.get(HOME)
self.login = client.get(LOGIN)
self.logout = client.get(LOGOUT)
self.register = client.get(REGISTER)
def test_no_user_in_db(self):
"""No user i db."""
self.assertFalse(User.objects.count())
def test_homepage(self):
"""Test homepage can be reached."""
self.assertEqual(self.home.status_code, 200)
def test_login(self):
"""Test login cna be reached."""
self.assertEqual(self.login.status_code, 200)
def test_logout(self):
"""Test logout can be reached."""
self.assertEqual(self.logout.status_code, 200)
def test_register(self):
"""Test register can be reached."""
self.assertEqual(self.register.status_code, 200)
| """Tests for project level urls and views."""
from __future__ import unicode_literals
from django.contrib.staticfiles import finders
from django.test import Client, TestCase
from django.contrib.auth.models import User
HOME = '/'
REGISTER = '/accounts/register/'
LOGIN = '/login'
LOGOUT = '/logout'
DEFAULT_IMAGE = finders.find('static/imagersite/images/default-image.jpg')
class UnauthenticatedUser(TestCase):
"""Create unauth user for testing."""
def setUp(self):
"""Setup unauth user."""
client = Client()
self.home = client.get(HOME)
self.login = client.get(LOGIN)
self.logout = client.get(LOGOUT)
self.register = client.get(REGISTER)
def test_no_user_in_db(self):
"""No user i db."""
self.assertFalse(User.objects.count())
def test_homepage(self):
"""Test homepage can be reached."""
self.assertEqual(self.home.status_code, 200)
def test_login(self):
"""Test login cna be reached."""
self.assertEqual(self.login.status_code, 200)
def test_logout(self):
"""Test logout can be reached."""
self.assertEqual(self.logout.status_code, 200)
def test_register(self):
"""Test register can be reached."""
self.assertEqual(self.register.status_code, 200)
def test_default_image(self):
"""Test default image shows up."""
img_path = self.home.context['image']
self.assertEqual(img_path, DEFAULT_IMAGE)
| Add passing test for default image | Add passing test for default image
| Python | mit | SeleniumK/django-imager,SeleniumK/django-imager,SeleniumK/django-imager | + """Tests for project level urls and views."""
+ from __future__ import unicode_literals
+ from django.contrib.staticfiles import finders
from django.test import Client, TestCase
from django.contrib.auth.models import User
HOME = '/'
REGISTER = '/accounts/register/'
LOGIN = '/login'
LOGOUT = '/logout'
+ DEFAULT_IMAGE = finders.find('static/imagersite/images/default-image.jpg')
class UnauthenticatedUser(TestCase):
"""Create unauth user for testing."""
def setUp(self):
"""Setup unauth user."""
client = Client()
self.home = client.get(HOME)
self.login = client.get(LOGIN)
self.logout = client.get(LOGOUT)
self.register = client.get(REGISTER)
def test_no_user_in_db(self):
"""No user i db."""
self.assertFalse(User.objects.count())
def test_homepage(self):
"""Test homepage can be reached."""
self.assertEqual(self.home.status_code, 200)
def test_login(self):
"""Test login cna be reached."""
self.assertEqual(self.login.status_code, 200)
def test_logout(self):
"""Test logout can be reached."""
self.assertEqual(self.logout.status_code, 200)
def test_register(self):
"""Test register can be reached."""
self.assertEqual(self.register.status_code, 200)
+ def test_default_image(self):
+ """Test default image shows up."""
+ img_path = self.home.context['image']
+ self.assertEqual(img_path, DEFAULT_IMAGE)
+ | Add passing test for default image | ## Code Before:
from django.test import Client, TestCase
from django.contrib.auth.models import User
HOME = '/'
REGISTER = '/accounts/register/'
LOGIN = '/login'
LOGOUT = '/logout'
class UnauthenticatedUser(TestCase):
"""Create unauth user for testing."""
def setUp(self):
"""Setup unauth user."""
client = Client()
self.home = client.get(HOME)
self.login = client.get(LOGIN)
self.logout = client.get(LOGOUT)
self.register = client.get(REGISTER)
def test_no_user_in_db(self):
"""No user i db."""
self.assertFalse(User.objects.count())
def test_homepage(self):
"""Test homepage can be reached."""
self.assertEqual(self.home.status_code, 200)
def test_login(self):
"""Test login cna be reached."""
self.assertEqual(self.login.status_code, 200)
def test_logout(self):
"""Test logout can be reached."""
self.assertEqual(self.logout.status_code, 200)
def test_register(self):
"""Test register can be reached."""
self.assertEqual(self.register.status_code, 200)
## Instruction:
Add passing test for default image
## Code After:
"""Tests for project level urls and views."""
from __future__ import unicode_literals
from django.contrib.staticfiles import finders
from django.test import Client, TestCase
from django.contrib.auth.models import User
HOME = '/'
REGISTER = '/accounts/register/'
LOGIN = '/login'
LOGOUT = '/logout'
DEFAULT_IMAGE = finders.find('static/imagersite/images/default-image.jpg')
class UnauthenticatedUser(TestCase):
"""Create unauth user for testing."""
def setUp(self):
"""Setup unauth user."""
client = Client()
self.home = client.get(HOME)
self.login = client.get(LOGIN)
self.logout = client.get(LOGOUT)
self.register = client.get(REGISTER)
def test_no_user_in_db(self):
"""No user i db."""
self.assertFalse(User.objects.count())
def test_homepage(self):
"""Test homepage can be reached."""
self.assertEqual(self.home.status_code, 200)
def test_login(self):
"""Test login cna be reached."""
self.assertEqual(self.login.status_code, 200)
def test_logout(self):
"""Test logout can be reached."""
self.assertEqual(self.logout.status_code, 200)
def test_register(self):
"""Test register can be reached."""
self.assertEqual(self.register.status_code, 200)
def test_default_image(self):
"""Test default image shows up."""
img_path = self.home.context['image']
self.assertEqual(img_path, DEFAULT_IMAGE)
| + """Tests for project level urls and views."""
+ from __future__ import unicode_literals
+ from django.contrib.staticfiles import finders
from django.test import Client, TestCase
from django.contrib.auth.models import User
HOME = '/'
REGISTER = '/accounts/register/'
LOGIN = '/login'
LOGOUT = '/logout'
+ DEFAULT_IMAGE = finders.find('static/imagersite/images/default-image.jpg')
class UnauthenticatedUser(TestCase):
"""Create unauth user for testing."""
def setUp(self):
"""Setup unauth user."""
client = Client()
self.home = client.get(HOME)
self.login = client.get(LOGIN)
self.logout = client.get(LOGOUT)
self.register = client.get(REGISTER)
def test_no_user_in_db(self):
"""No user i db."""
self.assertFalse(User.objects.count())
def test_homepage(self):
"""Test homepage can be reached."""
self.assertEqual(self.home.status_code, 200)
def test_login(self):
"""Test login cna be reached."""
self.assertEqual(self.login.status_code, 200)
def test_logout(self):
"""Test logout can be reached."""
self.assertEqual(self.logout.status_code, 200)
def test_register(self):
"""Test register can be reached."""
self.assertEqual(self.register.status_code, 200)
+
+ def test_default_image(self):
+ """Test default image shows up."""
+ img_path = self.home.context['image']
+ self.assertEqual(img_path, DEFAULT_IMAGE) |
b1c67321e5eec29b9fd91d728bd8e63382dc063a | src/keybar/conf/test.py | src/keybar/conf/test.py | from keybar.conf.base import *
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'keybar_test',
}
}
certificates_dir = os.path.join(BASE_DIR, 'tests', 'resources', 'certificates')
KEYBAR_SERVER_CERTIFICATE = os.path.join(certificates_dir, 'KEYBAR-intermediate-SERVER.cert')
KEYBAR_SERVER_KEY = os.path.join(certificates_dir, 'KEYBAR-intermediate-SERVER.key')
KEYBAR_CLIENT_CERTIFICATE = os.path.join(certificates_dir, 'KEYBAR-intermediate-CLIENT.cert')
KEYBAR_CLIENT_KEY = os.path.join(certificates_dir, 'KEYBAR-intermediate-CLIENT.key')
KEYBAR_CA_BUNDLE = os.path.join(certificates_dir, 'KEYBAR-ca-bundle.crt')
KEYBAR_VERIFY_CLIENT_CERTIFICATE = True
KEYBAR_DOMAIN = 'local.keybar.io'
KEYBAR_HOST = 'local.keybar.io:8443'
PASSWORD_HASHERS = (
'django.contrib.auth.hashers.MD5PasswordHasher',
)
CELERY_ALWAYS_EAGER = True
CELERY_EAGER_PROPAGATES_EXCEPTIONS = True
KEYBAR_HOST = 'local.keybar.io:9999'
KEYBAR_KDF_ITERATIONS = 100
| from keybar.conf.base import *
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'keybar_test',
}
}
certificates_dir = os.path.join(BASE_DIR, 'tests', 'resources', 'certificates')
KEYBAR_SERVER_CERTIFICATE = os.path.join(certificates_dir, 'KEYBAR-intermediate-SERVER.cert')
KEYBAR_SERVER_KEY = os.path.join(certificates_dir, 'KEYBAR-intermediate-SERVER.key')
KEYBAR_CLIENT_CERTIFICATE = os.path.join(certificates_dir, 'KEYBAR-intermediate-CLIENT.cert')
KEYBAR_CLIENT_KEY = os.path.join(certificates_dir, 'KEYBAR-intermediate-CLIENT.key')
KEYBAR_CA_BUNDLE = os.path.join(certificates_dir, 'KEYBAR-ca-bundle.crt')
KEYBAR_VERIFY_CLIENT_CERTIFICATE = True
KEYBAR_DOMAIN = 'local.keybar.io'
KEYBAR_HOST = 'local.keybar.io:9999'
PASSWORD_HASHERS = (
'django.contrib.auth.hashers.MD5PasswordHasher',
)
CELERY_ALWAYS_EAGER = True
CELERY_EAGER_PROPAGATES_EXCEPTIONS = True
KEYBAR_KDF_ITERATIONS = 100
| Remove duplicate keybar host value | Remove duplicate keybar host value
| Python | bsd-3-clause | keybar/keybar | from keybar.conf.base import *
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'keybar_test',
}
}
certificates_dir = os.path.join(BASE_DIR, 'tests', 'resources', 'certificates')
KEYBAR_SERVER_CERTIFICATE = os.path.join(certificates_dir, 'KEYBAR-intermediate-SERVER.cert')
KEYBAR_SERVER_KEY = os.path.join(certificates_dir, 'KEYBAR-intermediate-SERVER.key')
KEYBAR_CLIENT_CERTIFICATE = os.path.join(certificates_dir, 'KEYBAR-intermediate-CLIENT.cert')
KEYBAR_CLIENT_KEY = os.path.join(certificates_dir, 'KEYBAR-intermediate-CLIENT.key')
KEYBAR_CA_BUNDLE = os.path.join(certificates_dir, 'KEYBAR-ca-bundle.crt')
KEYBAR_VERIFY_CLIENT_CERTIFICATE = True
KEYBAR_DOMAIN = 'local.keybar.io'
- KEYBAR_HOST = 'local.keybar.io:8443'
+ KEYBAR_HOST = 'local.keybar.io:9999'
PASSWORD_HASHERS = (
'django.contrib.auth.hashers.MD5PasswordHasher',
)
CELERY_ALWAYS_EAGER = True
CELERY_EAGER_PROPAGATES_EXCEPTIONS = True
- KEYBAR_HOST = 'local.keybar.io:9999'
KEYBAR_KDF_ITERATIONS = 100
| Remove duplicate keybar host value | ## Code Before:
from keybar.conf.base import *
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'keybar_test',
}
}
certificates_dir = os.path.join(BASE_DIR, 'tests', 'resources', 'certificates')
KEYBAR_SERVER_CERTIFICATE = os.path.join(certificates_dir, 'KEYBAR-intermediate-SERVER.cert')
KEYBAR_SERVER_KEY = os.path.join(certificates_dir, 'KEYBAR-intermediate-SERVER.key')
KEYBAR_CLIENT_CERTIFICATE = os.path.join(certificates_dir, 'KEYBAR-intermediate-CLIENT.cert')
KEYBAR_CLIENT_KEY = os.path.join(certificates_dir, 'KEYBAR-intermediate-CLIENT.key')
KEYBAR_CA_BUNDLE = os.path.join(certificates_dir, 'KEYBAR-ca-bundle.crt')
KEYBAR_VERIFY_CLIENT_CERTIFICATE = True
KEYBAR_DOMAIN = 'local.keybar.io'
KEYBAR_HOST = 'local.keybar.io:8443'
PASSWORD_HASHERS = (
'django.contrib.auth.hashers.MD5PasswordHasher',
)
CELERY_ALWAYS_EAGER = True
CELERY_EAGER_PROPAGATES_EXCEPTIONS = True
KEYBAR_HOST = 'local.keybar.io:9999'
KEYBAR_KDF_ITERATIONS = 100
## Instruction:
Remove duplicate keybar host value
## Code After:
from keybar.conf.base import *
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'keybar_test',
}
}
certificates_dir = os.path.join(BASE_DIR, 'tests', 'resources', 'certificates')
KEYBAR_SERVER_CERTIFICATE = os.path.join(certificates_dir, 'KEYBAR-intermediate-SERVER.cert')
KEYBAR_SERVER_KEY = os.path.join(certificates_dir, 'KEYBAR-intermediate-SERVER.key')
KEYBAR_CLIENT_CERTIFICATE = os.path.join(certificates_dir, 'KEYBAR-intermediate-CLIENT.cert')
KEYBAR_CLIENT_KEY = os.path.join(certificates_dir, 'KEYBAR-intermediate-CLIENT.key')
KEYBAR_CA_BUNDLE = os.path.join(certificates_dir, 'KEYBAR-ca-bundle.crt')
KEYBAR_VERIFY_CLIENT_CERTIFICATE = True
KEYBAR_DOMAIN = 'local.keybar.io'
KEYBAR_HOST = 'local.keybar.io:9999'
PASSWORD_HASHERS = (
'django.contrib.auth.hashers.MD5PasswordHasher',
)
CELERY_ALWAYS_EAGER = True
CELERY_EAGER_PROPAGATES_EXCEPTIONS = True
KEYBAR_KDF_ITERATIONS = 100
| from keybar.conf.base import *
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'keybar_test',
}
}
certificates_dir = os.path.join(BASE_DIR, 'tests', 'resources', 'certificates')
KEYBAR_SERVER_CERTIFICATE = os.path.join(certificates_dir, 'KEYBAR-intermediate-SERVER.cert')
KEYBAR_SERVER_KEY = os.path.join(certificates_dir, 'KEYBAR-intermediate-SERVER.key')
KEYBAR_CLIENT_CERTIFICATE = os.path.join(certificates_dir, 'KEYBAR-intermediate-CLIENT.cert')
KEYBAR_CLIENT_KEY = os.path.join(certificates_dir, 'KEYBAR-intermediate-CLIENT.key')
KEYBAR_CA_BUNDLE = os.path.join(certificates_dir, 'KEYBAR-ca-bundle.crt')
KEYBAR_VERIFY_CLIENT_CERTIFICATE = True
KEYBAR_DOMAIN = 'local.keybar.io'
- KEYBAR_HOST = 'local.keybar.io:8443'
? ^^^^
+ KEYBAR_HOST = 'local.keybar.io:9999'
? ^^^^
PASSWORD_HASHERS = (
'django.contrib.auth.hashers.MD5PasswordHasher',
)
CELERY_ALWAYS_EAGER = True
CELERY_EAGER_PROPAGATES_EXCEPTIONS = True
- KEYBAR_HOST = 'local.keybar.io:9999'
KEYBAR_KDF_ITERATIONS = 100 |
11fdccbc4144c2b1e27d2b124596ce9122c365a2 | froide/problem/apps.py | froide/problem/apps.py | import json
from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
class ProblemConfig(AppConfig):
name = 'froide.problem'
verbose_name = _('Problems')
def ready(self):
from froide.account.export import registry
from . import signals # noqa
registry.register(export_user_data)
def export_user_data(user):
from .models import ProblemReport
problems = ProblemReport.objects.filter(
user=user
).select_related('message', 'message__request')
if not problems:
return
yield ('problem_reports.json', json.dumps([
{
'message': pb.message.get_absolute_domain_short_url(),
'timestamp': pb.timestamp.isoformat(),
'resolved': pb.resolved,
'kind': pb.kind,
'description': pb.description,
'resolution': pb.resolution,
'resolution_timestamp': (
pb.resolution_timestamp.isoformat()
if pb.resolution_timestamp else None
),
}
for pb in problems]).encode('utf-8')
)
| import json
from django.apps import AppConfig
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
class ProblemConfig(AppConfig):
name = 'froide.problem'
verbose_name = _('Problems')
def ready(self):
from froide.account.export import registry
from froide.account import account_merged
from froide.account.menu import menu_registry, MenuItem
from . import signals # noqa
registry.register(export_user_data)
account_merged.connect(merge_user)
def get_moderation_menu_item(request):
from froide.foirequest.auth import is_foirequest_moderator
if not (request.user.is_staff or is_foirequest_moderator(request)):
return None
return MenuItem(
section='after_settings', order=0,
url=reverse('problem-moderation'),
label=_('Moderation')
)
menu_registry.register(get_moderation_menu_item)
registry.register(export_user_data)
def merge_user(sender, old_user=None, new_user=None, **kwargs):
from .models import ProblemReport
ProblemReport.objects.filter(user=old_user).update(
user=new_user
)
ProblemReport.objects.filter(moderator=old_user).update(
moderator=new_user
)
def export_user_data(user):
from .models import ProblemReport
problems = ProblemReport.objects.filter(
user=user
).select_related('message', 'message__request')
if not problems:
return
yield ('problem_reports.json', json.dumps([
{
'message': pb.message.get_absolute_domain_short_url(),
'timestamp': pb.timestamp.isoformat(),
'resolved': pb.resolved,
'kind': pb.kind,
'description': pb.description,
'resolution': pb.resolution,
'resolution_timestamp': (
pb.resolution_timestamp.isoformat()
if pb.resolution_timestamp else None
),
}
for pb in problems]).encode('utf-8')
)
| Add user merging to problem, menu for moderation | Add user merging to problem, menu for moderation | Python | mit | fin/froide,fin/froide,stefanw/froide,stefanw/froide,stefanw/froide,fin/froide,stefanw/froide,fin/froide,stefanw/froide | import json
from django.apps import AppConfig
+ from django.urls import reverse
from django.utils.translation import gettext_lazy as _
class ProblemConfig(AppConfig):
name = 'froide.problem'
verbose_name = _('Problems')
def ready(self):
from froide.account.export import registry
+ from froide.account import account_merged
+ from froide.account.menu import menu_registry, MenuItem
from . import signals # noqa
registry.register(export_user_data)
+ account_merged.connect(merge_user)
+
+ def get_moderation_menu_item(request):
+ from froide.foirequest.auth import is_foirequest_moderator
+
+ if not (request.user.is_staff or is_foirequest_moderator(request)):
+ return None
+
+ return MenuItem(
+ section='after_settings', order=0,
+ url=reverse('problem-moderation'),
+ label=_('Moderation')
+ )
+
+ menu_registry.register(get_moderation_menu_item)
+ registry.register(export_user_data)
+
+
+ def merge_user(sender, old_user=None, new_user=None, **kwargs):
+ from .models import ProblemReport
+
+ ProblemReport.objects.filter(user=old_user).update(
+ user=new_user
+ )
+ ProblemReport.objects.filter(moderator=old_user).update(
+ moderator=new_user
+ )
def export_user_data(user):
from .models import ProblemReport
problems = ProblemReport.objects.filter(
user=user
).select_related('message', 'message__request')
if not problems:
return
yield ('problem_reports.json', json.dumps([
{
'message': pb.message.get_absolute_domain_short_url(),
'timestamp': pb.timestamp.isoformat(),
'resolved': pb.resolved,
'kind': pb.kind,
'description': pb.description,
'resolution': pb.resolution,
'resolution_timestamp': (
pb.resolution_timestamp.isoformat()
if pb.resolution_timestamp else None
),
}
for pb in problems]).encode('utf-8')
)
| Add user merging to problem, menu for moderation | ## Code Before:
import json
from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
class ProblemConfig(AppConfig):
name = 'froide.problem'
verbose_name = _('Problems')
def ready(self):
from froide.account.export import registry
from . import signals # noqa
registry.register(export_user_data)
def export_user_data(user):
from .models import ProblemReport
problems = ProblemReport.objects.filter(
user=user
).select_related('message', 'message__request')
if not problems:
return
yield ('problem_reports.json', json.dumps([
{
'message': pb.message.get_absolute_domain_short_url(),
'timestamp': pb.timestamp.isoformat(),
'resolved': pb.resolved,
'kind': pb.kind,
'description': pb.description,
'resolution': pb.resolution,
'resolution_timestamp': (
pb.resolution_timestamp.isoformat()
if pb.resolution_timestamp else None
),
}
for pb in problems]).encode('utf-8')
)
## Instruction:
Add user merging to problem, menu for moderation
## Code After:
import json
from django.apps import AppConfig
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
class ProblemConfig(AppConfig):
name = 'froide.problem'
verbose_name = _('Problems')
def ready(self):
from froide.account.export import registry
from froide.account import account_merged
from froide.account.menu import menu_registry, MenuItem
from . import signals # noqa
registry.register(export_user_data)
account_merged.connect(merge_user)
def get_moderation_menu_item(request):
from froide.foirequest.auth import is_foirequest_moderator
if not (request.user.is_staff or is_foirequest_moderator(request)):
return None
return MenuItem(
section='after_settings', order=0,
url=reverse('problem-moderation'),
label=_('Moderation')
)
menu_registry.register(get_moderation_menu_item)
registry.register(export_user_data)
def merge_user(sender, old_user=None, new_user=None, **kwargs):
from .models import ProblemReport
ProblemReport.objects.filter(user=old_user).update(
user=new_user
)
ProblemReport.objects.filter(moderator=old_user).update(
moderator=new_user
)
def export_user_data(user):
from .models import ProblemReport
problems = ProblemReport.objects.filter(
user=user
).select_related('message', 'message__request')
if not problems:
return
yield ('problem_reports.json', json.dumps([
{
'message': pb.message.get_absolute_domain_short_url(),
'timestamp': pb.timestamp.isoformat(),
'resolved': pb.resolved,
'kind': pb.kind,
'description': pb.description,
'resolution': pb.resolution,
'resolution_timestamp': (
pb.resolution_timestamp.isoformat()
if pb.resolution_timestamp else None
),
}
for pb in problems]).encode('utf-8')
)
| import json
from django.apps import AppConfig
+ from django.urls import reverse
from django.utils.translation import gettext_lazy as _
class ProblemConfig(AppConfig):
name = 'froide.problem'
verbose_name = _('Problems')
def ready(self):
from froide.account.export import registry
+ from froide.account import account_merged
+ from froide.account.menu import menu_registry, MenuItem
from . import signals # noqa
registry.register(export_user_data)
+ account_merged.connect(merge_user)
+
+ def get_moderation_menu_item(request):
+ from froide.foirequest.auth import is_foirequest_moderator
+
+ if not (request.user.is_staff or is_foirequest_moderator(request)):
+ return None
+
+ return MenuItem(
+ section='after_settings', order=0,
+ url=reverse('problem-moderation'),
+ label=_('Moderation')
+ )
+
+ menu_registry.register(get_moderation_menu_item)
+ registry.register(export_user_data)
+
+
+ def merge_user(sender, old_user=None, new_user=None, **kwargs):
+ from .models import ProblemReport
+
+ ProblemReport.objects.filter(user=old_user).update(
+ user=new_user
+ )
+ ProblemReport.objects.filter(moderator=old_user).update(
+ moderator=new_user
+ )
def export_user_data(user):
from .models import ProblemReport
problems = ProblemReport.objects.filter(
user=user
).select_related('message', 'message__request')
if not problems:
return
yield ('problem_reports.json', json.dumps([
{
'message': pb.message.get_absolute_domain_short_url(),
'timestamp': pb.timestamp.isoformat(),
'resolved': pb.resolved,
'kind': pb.kind,
'description': pb.description,
'resolution': pb.resolution,
'resolution_timestamp': (
pb.resolution_timestamp.isoformat()
if pb.resolution_timestamp else None
),
}
for pb in problems]).encode('utf-8')
) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.