commit
stringlengths 40
40
| old_file
stringlengths 4
118
| new_file
stringlengths 4
118
| old_contents
stringlengths 10
2.94k
| new_contents
stringlengths 21
3.18k
| subject
stringlengths 16
444
| message
stringlengths 17
2.63k
| lang
stringclasses 1
value | license
stringclasses 13
values | repos
stringlengths 5
43k
| ndiff
stringlengths 52
3.32k
| instruction
stringlengths 16
444
| content
stringlengths 133
4.32k
| fuzzy_diff
stringlengths 16
3.18k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
28f59d245d4695de5dbcfc0302f34c46234fd116
|
blackgate/executor_pools.py
|
blackgate/executor_pools.py
|
from blackgate.executor import QueueExecutor
from tornado.ioloop import IOLoop
class ExecutorPools(object):
class PoolFull(Exception):
pass
class ExecutionTimeout(Exception):
pass
class ExecutionFailure(Exception):
pass
def __init__(self):
self.pools = {}
def register_pool(self, group_key, max_size=1):
executor = QueueExecutor(pool_key=group_key, max_size=max_size)
IOLoop.current().spawn_callback(executor.consume)
self.pools[group_key] = executor
def get_executor(self, group_key):
if group_key not in self.pools:
raise Exception("Pool not registerd")
return self.pools[group_key]
|
from blackgate.executor import QueueExecutor
from tornado.ioloop import IOLoop
class ExecutorPools(object):
class PoolFull(Exception):
pass
class ExecutionTimeout(Exception):
pass
class ExecutionFailure(Exception):
pass
def __init__(self):
self.pools = {}
def register_pool(self, group_key, max_size=10, max_workers=10):
executor = QueueExecutor(pool_key=group_key, max_size=max_size, max_workers=max_workers)
IOLoop.current().spawn_callback(executor.consume)
self.pools[group_key] = executor
def get_executor(self, group_key):
if group_key not in self.pools:
raise Exception("Pool not registerd")
return self.pools[group_key]
|
Set max_workers the same as max_size.
|
Set max_workers the same as max_size.
|
Python
|
mit
|
soasme/blackgate
|
from blackgate.executor import QueueExecutor
from tornado.ioloop import IOLoop
class ExecutorPools(object):
class PoolFull(Exception):
pass
class ExecutionTimeout(Exception):
pass
class ExecutionFailure(Exception):
pass
def __init__(self):
self.pools = {}
- def register_pool(self, group_key, max_size=1):
+ def register_pool(self, group_key, max_size=10, max_workers=10):
- executor = QueueExecutor(pool_key=group_key, max_size=max_size)
+ executor = QueueExecutor(pool_key=group_key, max_size=max_size, max_workers=max_workers)
IOLoop.current().spawn_callback(executor.consume)
self.pools[group_key] = executor
def get_executor(self, group_key):
if group_key not in self.pools:
raise Exception("Pool not registerd")
return self.pools[group_key]
|
Set max_workers the same as max_size.
|
## Code Before:
from blackgate.executor import QueueExecutor
from tornado.ioloop import IOLoop
class ExecutorPools(object):
class PoolFull(Exception):
pass
class ExecutionTimeout(Exception):
pass
class ExecutionFailure(Exception):
pass
def __init__(self):
self.pools = {}
def register_pool(self, group_key, max_size=1):
executor = QueueExecutor(pool_key=group_key, max_size=max_size)
IOLoop.current().spawn_callback(executor.consume)
self.pools[group_key] = executor
def get_executor(self, group_key):
if group_key not in self.pools:
raise Exception("Pool not registerd")
return self.pools[group_key]
## Instruction:
Set max_workers the same as max_size.
## Code After:
from blackgate.executor import QueueExecutor
from tornado.ioloop import IOLoop
class ExecutorPools(object):
class PoolFull(Exception):
pass
class ExecutionTimeout(Exception):
pass
class ExecutionFailure(Exception):
pass
def __init__(self):
self.pools = {}
def register_pool(self, group_key, max_size=10, max_workers=10):
executor = QueueExecutor(pool_key=group_key, max_size=max_size, max_workers=max_workers)
IOLoop.current().spawn_callback(executor.consume)
self.pools[group_key] = executor
def get_executor(self, group_key):
if group_key not in self.pools:
raise Exception("Pool not registerd")
return self.pools[group_key]
|
# ... existing code ...
def register_pool(self, group_key, max_size=10, max_workers=10):
executor = QueueExecutor(pool_key=group_key, max_size=max_size, max_workers=max_workers)
IOLoop.current().spawn_callback(executor.consume)
# ... rest of the code ...
|
451a435ca051305517c79216d7ab9441939f4004
|
src/amr.py
|
src/amr.py
|
import dolfin as df
def amr(mesh, m, DirichletBoundary, g, d):
V = df.FunctionSpace(mesh, "CG", 1)
# Define boundary condition
bc = df.DirichletBC(V, g, DirichletBoundary())
# Define variational problem
u = df.Function(V)
v = df.TestFunction(V)
E = df.grad(u)
costheta = df.dot(m, E)
sigma = 1/(1 + costheta**2)
F = df.inner(sigma*df.grad(u), df.grad(v))*df.dx
# Compute solution
df.solve(F == 0, u, bc, solver_parameters={"newton_solver":
{"relative_tolerance": 1e-6}})
# Plot solution and solution gradient
df.plot(u, title="Solution")
df.plot(sigma*df.grad(u), title="Solution gradient")
df.interactive()
|
import dolfin as df
def amr(mesh, m, DirichletBoundary, g, d, s0=1, alpha=1):
V = df.FunctionSpace(mesh, "CG", 1)
# Define boundary condition
bc = df.DirichletBC(V, g, DirichletBoundary())
# Define variational problem
u = df.Function(V)
v = df.TestFunction(V)
E = -df.grad(u)
costheta = df.dot(m, E)
sigma = s0/(1 + alpha*costheta**2)
F = df.inner(sigma*df.grad(u), df.grad(v))*df.dx
# Compute solution
df.solve(F == 0, u, bc, solver_parameters={"newton_solver":
{"relative_tolerance": 1e-6}})
# Plot solution and solution gradient
df.plot(u, title="Solution")
df.plot(sigma*df.grad(u), title="Solution gradient")
df.interactive()
|
Add sigma0 and alpha AMR parameters to the function.
|
Add sigma0 and alpha AMR parameters to the function.
|
Python
|
bsd-2-clause
|
fangohr/fenics-anisotropic-magneto-resistance
|
import dolfin as df
- def amr(mesh, m, DirichletBoundary, g, d):
+ def amr(mesh, m, DirichletBoundary, g, d, s0=1, alpha=1):
V = df.FunctionSpace(mesh, "CG", 1)
# Define boundary condition
bc = df.DirichletBC(V, g, DirichletBoundary())
# Define variational problem
u = df.Function(V)
v = df.TestFunction(V)
- E = df.grad(u)
+ E = -df.grad(u)
costheta = df.dot(m, E)
- sigma = 1/(1 + costheta**2)
+ sigma = s0/(1 + alpha*costheta**2)
F = df.inner(sigma*df.grad(u), df.grad(v))*df.dx
# Compute solution
df.solve(F == 0, u, bc, solver_parameters={"newton_solver":
{"relative_tolerance": 1e-6}})
# Plot solution and solution gradient
df.plot(u, title="Solution")
df.plot(sigma*df.grad(u), title="Solution gradient")
df.interactive()
|
Add sigma0 and alpha AMR parameters to the function.
|
## Code Before:
import dolfin as df
def amr(mesh, m, DirichletBoundary, g, d):
V = df.FunctionSpace(mesh, "CG", 1)
# Define boundary condition
bc = df.DirichletBC(V, g, DirichletBoundary())
# Define variational problem
u = df.Function(V)
v = df.TestFunction(V)
E = df.grad(u)
costheta = df.dot(m, E)
sigma = 1/(1 + costheta**2)
F = df.inner(sigma*df.grad(u), df.grad(v))*df.dx
# Compute solution
df.solve(F == 0, u, bc, solver_parameters={"newton_solver":
{"relative_tolerance": 1e-6}})
# Plot solution and solution gradient
df.plot(u, title="Solution")
df.plot(sigma*df.grad(u), title="Solution gradient")
df.interactive()
## Instruction:
Add sigma0 and alpha AMR parameters to the function.
## Code After:
import dolfin as df
def amr(mesh, m, DirichletBoundary, g, d, s0=1, alpha=1):
V = df.FunctionSpace(mesh, "CG", 1)
# Define boundary condition
bc = df.DirichletBC(V, g, DirichletBoundary())
# Define variational problem
u = df.Function(V)
v = df.TestFunction(V)
E = -df.grad(u)
costheta = df.dot(m, E)
sigma = s0/(1 + alpha*costheta**2)
F = df.inner(sigma*df.grad(u), df.grad(v))*df.dx
# Compute solution
df.solve(F == 0, u, bc, solver_parameters={"newton_solver":
{"relative_tolerance": 1e-6}})
# Plot solution and solution gradient
df.plot(u, title="Solution")
df.plot(sigma*df.grad(u), title="Solution gradient")
df.interactive()
|
...
def amr(mesh, m, DirichletBoundary, g, d, s0=1, alpha=1):
V = df.FunctionSpace(mesh, "CG", 1)
...
v = df.TestFunction(V)
E = -df.grad(u)
costheta = df.dot(m, E)
sigma = s0/(1 + alpha*costheta**2)
F = df.inner(sigma*df.grad(u), df.grad(v))*df.dx
...
|
9d6c8eaa491d0988bf16633bbba9847350f57778
|
spacy/lang/norm_exceptions.py
|
spacy/lang/norm_exceptions.py
|
from __future__ import unicode_literals
# These exceptions are used to add NORM values based on a token's ORTH value.
# Individual languages can also add their own exceptions and overwrite them -
# for example, British vs. American spelling in English.
# Norms are only set if no alternative is provided in the tokenizer exceptions.
# Note that this does not change any other token attributes. Its main purpose
# is to normalise the word representations so that equivalent tokens receive
# similar representations. For example: $ and € are very different, but they're
# both currency symbols. By normalising currency symbols to $, all symbols are
# seen as similar, no matter how common they are in the training data.
BASE_NORMS = {
"'s": "'s",
"'S": "'s",
"’s": "'s",
"’S": "'s",
"’": "'",
"‘": "'",
"´": "'",
"`": "'",
"”": '"',
"“": '"',
"''": '"',
"``": '"',
"´´": '"',
"„": '"',
"»": '"',
"«": '"',
"…": "...",
"—": "-",
"–": "-",
"--": "-",
"---": "-",
"€": "$",
"£": "$",
"¥": "$",
"฿": "$",
"US$": "$",
"C$": "$",
"A$": "$"
}
|
from __future__ import unicode_literals
# These exceptions are used to add NORM values based on a token's ORTH value.
# Individual languages can also add their own exceptions and overwrite them -
# for example, British vs. American spelling in English.
# Norms are only set if no alternative is provided in the tokenizer exceptions.
# Note that this does not change any other token attributes. Its main purpose
# is to normalise the word representations so that equivalent tokens receive
# similar representations. For example: $ and € are very different, but they're
# both currency symbols. By normalising currency symbols to $, all symbols are
# seen as similar, no matter how common they are in the training data.
BASE_NORMS = {
"'s": "'s",
"'S": "'s",
"’s": "'s",
"’S": "'s",
"’": "'",
"‘": "'",
"´": "'",
"`": "'",
"”": '"',
"“": '"',
"''": '"',
"``": '"',
"´´": '"',
"„": '"',
"»": '"',
"«": '"',
"‘‘": '"',
"’’": '"',
"?": "?",
"!": "!",
",": ",",
";": ";",
":": ":",
"。": ".",
"।": ".",
"…": "...",
"—": "-",
"–": "-",
"--": "-",
"---": "-",
"——": "-",
"€": "$",
"£": "$",
"¥": "$",
"฿": "$",
"US$": "$",
"C$": "$",
"A$": "$"
}
|
Update base norm exceptions with more unicode characters
|
Update base norm exceptions with more unicode characters
e.g. unicode variations of punctuation used in Chinese
|
Python
|
mit
|
aikramer2/spaCy,aikramer2/spaCy,recognai/spaCy,explosion/spaCy,aikramer2/spaCy,recognai/spaCy,honnibal/spaCy,explosion/spaCy,recognai/spaCy,aikramer2/spaCy,explosion/spaCy,recognai/spaCy,aikramer2/spaCy,recognai/spaCy,spacy-io/spaCy,spacy-io/spaCy,honnibal/spaCy,explosion/spaCy,honnibal/spaCy,explosion/spaCy,spacy-io/spaCy,recognai/spaCy,spacy-io/spaCy,aikramer2/spaCy,spacy-io/spaCy,explosion/spaCy,spacy-io/spaCy,honnibal/spaCy
|
from __future__ import unicode_literals
# These exceptions are used to add NORM values based on a token's ORTH value.
# Individual languages can also add their own exceptions and overwrite them -
# for example, British vs. American spelling in English.
# Norms are only set if no alternative is provided in the tokenizer exceptions.
# Note that this does not change any other token attributes. Its main purpose
# is to normalise the word representations so that equivalent tokens receive
# similar representations. For example: $ and € are very different, but they're
# both currency symbols. By normalising currency symbols to $, all symbols are
# seen as similar, no matter how common they are in the training data.
BASE_NORMS = {
"'s": "'s",
"'S": "'s",
"’s": "'s",
"’S": "'s",
"’": "'",
"‘": "'",
"´": "'",
"`": "'",
"”": '"',
"“": '"',
"''": '"',
"``": '"',
"´´": '"',
"„": '"',
"»": '"',
"«": '"',
+ "‘‘": '"',
+ "’’": '"',
+ "?": "?",
+ "!": "!",
+ ",": ",",
+ ";": ";",
+ ":": ":",
+ "。": ".",
+ "।": ".",
"…": "...",
"—": "-",
"–": "-",
"--": "-",
"---": "-",
+ "——": "-",
"€": "$",
"£": "$",
"¥": "$",
"฿": "$",
"US$": "$",
"C$": "$",
"A$": "$"
}
|
Update base norm exceptions with more unicode characters
|
## Code Before:
from __future__ import unicode_literals
# These exceptions are used to add NORM values based on a token's ORTH value.
# Individual languages can also add their own exceptions and overwrite them -
# for example, British vs. American spelling in English.
# Norms are only set if no alternative is provided in the tokenizer exceptions.
# Note that this does not change any other token attributes. Its main purpose
# is to normalise the word representations so that equivalent tokens receive
# similar representations. For example: $ and € are very different, but they're
# both currency symbols. By normalising currency symbols to $, all symbols are
# seen as similar, no matter how common they are in the training data.
BASE_NORMS = {
"'s": "'s",
"'S": "'s",
"’s": "'s",
"’S": "'s",
"’": "'",
"‘": "'",
"´": "'",
"`": "'",
"”": '"',
"“": '"',
"''": '"',
"``": '"',
"´´": '"',
"„": '"',
"»": '"',
"«": '"',
"…": "...",
"—": "-",
"–": "-",
"--": "-",
"---": "-",
"€": "$",
"£": "$",
"¥": "$",
"฿": "$",
"US$": "$",
"C$": "$",
"A$": "$"
}
## Instruction:
Update base norm exceptions with more unicode characters
## Code After:
from __future__ import unicode_literals
# These exceptions are used to add NORM values based on a token's ORTH value.
# Individual languages can also add their own exceptions and overwrite them -
# for example, British vs. American spelling in English.
# Norms are only set if no alternative is provided in the tokenizer exceptions.
# Note that this does not change any other token attributes. Its main purpose
# is to normalise the word representations so that equivalent tokens receive
# similar representations. For example: $ and € are very different, but they're
# both currency symbols. By normalising currency symbols to $, all symbols are
# seen as similar, no matter how common they are in the training data.
BASE_NORMS = {
"'s": "'s",
"'S": "'s",
"’s": "'s",
"’S": "'s",
"’": "'",
"‘": "'",
"´": "'",
"`": "'",
"”": '"',
"“": '"',
"''": '"',
"``": '"',
"´´": '"',
"„": '"',
"»": '"',
"«": '"',
"‘‘": '"',
"’’": '"',
"?": "?",
"!": "!",
",": ",",
";": ";",
":": ":",
"。": ".",
"।": ".",
"…": "...",
"—": "-",
"–": "-",
"--": "-",
"---": "-",
"——": "-",
"€": "$",
"£": "$",
"¥": "$",
"฿": "$",
"US$": "$",
"C$": "$",
"A$": "$"
}
|
// ... existing code ...
"«": '"',
"‘‘": '"',
"’’": '"',
"?": "?",
"!": "!",
",": ",",
";": ";",
":": ":",
"。": ".",
"।": ".",
"…": "...",
// ... modified code ...
"---": "-",
"——": "-",
"€": "$",
// ... rest of the code ...
|
7ad3346759f53f57f233319e63361a0ed792535f
|
incrowd/notify/utils.py
|
incrowd/notify/utils.py
|
import logging
from notify.models import Notification
logger = logging.getLogger(__name__)
def ping_filter(message, users, sending_user, notify_text, notify_type,
notify_url=None):
for user in users:
if username_in_message(message, user.username):
# Create notification
if user == sending_user:
continue
note = Notification(
text='{} {}: {}'.format(
sending_user.username, notify_text, message),
user=user,
from_user=sending_user,
type=notify_type,
link=notify_url)
note.save()
logger.info("Created notification for user {} from {}"
.format(note))
return message
def username_in_message(message, username):
message = message.lower()
username = username.lower()
# Check if @username in message. Edge case for username at the end of
# the message.
if '@' + username + ' ' in message.lower():
return True
try:
return (message.index('@' + username) ==
len(message.lower()) - len('@' + username))
except ValueError:
return False
|
import logging
from notify.models import Notification
logger = logging.getLogger(__name__)
def ping_filter(message, users, sending_user, notify_text, notify_type,
notify_url=None):
for user in users:
if username_in_message(message, user.username):
# Create notification
if user == sending_user:
continue
note = Notification(
text='{} {}: {}'.format(
sending_user.username, notify_text, message),
user=user,
from_user=sending_user,
type=notify_type,
link=notify_url)
note.save()
logger.info("Created notification for user {} from {}"
.format(note.user, note.from_user))
return message
def username_in_message(message, username):
message = message.lower()
username = username.lower()
# Check if @username in message. Edge case for username at the end of
# the message.
if '@' + username + ' ' in message.lower():
return True
try:
return (message.index('@' + username) ==
len(message.lower()) - len('@' + username))
except ValueError:
return False
|
Fix pinging in chat throwing errors
|
Fix pinging in chat throwing errors
|
Python
|
apache-2.0
|
pcsforeducation/incrowd,pcsforeducation/incrowd,incrowdio/incrowd,incrowdio/incrowd,incrowdio/incrowd,pcsforeducation/incrowd,pcsforeducation/incrowd,incrowdio/incrowd
|
import logging
from notify.models import Notification
logger = logging.getLogger(__name__)
def ping_filter(message, users, sending_user, notify_text, notify_type,
notify_url=None):
for user in users:
if username_in_message(message, user.username):
# Create notification
if user == sending_user:
continue
note = Notification(
text='{} {}: {}'.format(
sending_user.username, notify_text, message),
user=user,
from_user=sending_user,
type=notify_type,
link=notify_url)
note.save()
logger.info("Created notification for user {} from {}"
- .format(note))
+ .format(note.user, note.from_user))
return message
def username_in_message(message, username):
message = message.lower()
username = username.lower()
# Check if @username in message. Edge case for username at the end of
# the message.
if '@' + username + ' ' in message.lower():
return True
try:
return (message.index('@' + username) ==
len(message.lower()) - len('@' + username))
except ValueError:
return False
+
|
Fix pinging in chat throwing errors
|
## Code Before:
import logging
from notify.models import Notification
logger = logging.getLogger(__name__)
def ping_filter(message, users, sending_user, notify_text, notify_type,
notify_url=None):
for user in users:
if username_in_message(message, user.username):
# Create notification
if user == sending_user:
continue
note = Notification(
text='{} {}: {}'.format(
sending_user.username, notify_text, message),
user=user,
from_user=sending_user,
type=notify_type,
link=notify_url)
note.save()
logger.info("Created notification for user {} from {}"
.format(note))
return message
def username_in_message(message, username):
message = message.lower()
username = username.lower()
# Check if @username in message. Edge case for username at the end of
# the message.
if '@' + username + ' ' in message.lower():
return True
try:
return (message.index('@' + username) ==
len(message.lower()) - len('@' + username))
except ValueError:
return False
## Instruction:
Fix pinging in chat throwing errors
## Code After:
import logging
from notify.models import Notification
logger = logging.getLogger(__name__)
def ping_filter(message, users, sending_user, notify_text, notify_type,
notify_url=None):
for user in users:
if username_in_message(message, user.username):
# Create notification
if user == sending_user:
continue
note = Notification(
text='{} {}: {}'.format(
sending_user.username, notify_text, message),
user=user,
from_user=sending_user,
type=notify_type,
link=notify_url)
note.save()
logger.info("Created notification for user {} from {}"
.format(note.user, note.from_user))
return message
def username_in_message(message, username):
message = message.lower()
username = username.lower()
# Check if @username in message. Edge case for username at the end of
# the message.
if '@' + username + ' ' in message.lower():
return True
try:
return (message.index('@' + username) ==
len(message.lower()) - len('@' + username))
except ValueError:
return False
|
// ... existing code ...
logger.info("Created notification for user {} from {}"
.format(note.user, note.from_user))
return message
// ... rest of the code ...
|
77f99f4862ded1b8493b5895e4f9d88a3bbf722b
|
source/globals/fieldtests.py
|
source/globals/fieldtests.py
|
import wx
## Tests if a wx control/instance is enabled
#
# Function for compatibility between wx versions
# \param enabled
# \b \e bool : Check if enabled or disabled
def FieldEnabled(field, enabled=True):
if wx.MAJOR_VERSION > 2:
return field.IsThisEnabled() == enabled
else:
return field.IsEnabled() == enabled
## Tests multiple fields
#
# \return
# \b \e bool : True if all fields are enabled
def FieldsEnabled(field_list):
if isinstance(field_list, (tuple, list)):
return FieldEnabled(field_list)
for F in field_list:
if not FieldEnabled(F):
return False
return True
|
import wx
## Tests if a wx control/instance is enabled/disabled
#
# Function for compatibility between wx versions
# \param field
# \b \e wx.Window : the wx control to check
# \param enabled
# \b \e bool : Check if enabled or disabled
# \return
# \b \e bool : True if field's enabled status is same as 'enabled'
def FieldEnabled(field, enabled=True):
if wx.MAJOR_VERSION > 2:
return field.IsThisEnabled() == enabled
else:
return field.IsEnabled() == enabled
## Tests if a wx control/instance is disabled
#
# \param field
# \b \e wx.Window : The wx field to check
# \return
# \b \e : True if field is disabled
def FieldDisabled(field):
return FieldEnabled(field, False)
## Tests multiple fields
#
# \return
# \b \e bool : True if all fields are enabled
def FieldsEnabled(field_list):
if isinstance(field_list, (tuple, list)):
return FieldEnabled(field_list)
for F in field_list:
if not FieldEnabled(F):
return False
return True
|
Add function FieldDisabled to test for disabled controls
|
Add function FieldDisabled to test for disabled controls
|
Python
|
mit
|
AntumDeluge/desktop_recorder,AntumDeluge/desktop_recorder
|
import wx
- ## Tests if a wx control/instance is enabled
+ ## Tests if a wx control/instance is enabled/disabled
#
# Function for compatibility between wx versions
+ # \param field
+ # \b \e wx.Window : the wx control to check
# \param enabled
# \b \e bool : Check if enabled or disabled
+ # \return
+ # \b \e bool : True if field's enabled status is same as 'enabled'
def FieldEnabled(field, enabled=True):
if wx.MAJOR_VERSION > 2:
return field.IsThisEnabled() == enabled
else:
return field.IsEnabled() == enabled
+
+
+ ## Tests if a wx control/instance is disabled
+ #
+ # \param field
+ # \b \e wx.Window : The wx field to check
+ # \return
+ # \b \e : True if field is disabled
+ def FieldDisabled(field):
+ return FieldEnabled(field, False)
## Tests multiple fields
#
# \return
# \b \e bool : True if all fields are enabled
def FieldsEnabled(field_list):
if isinstance(field_list, (tuple, list)):
return FieldEnabled(field_list)
for F in field_list:
if not FieldEnabled(F):
return False
return True
|
Add function FieldDisabled to test for disabled controls
|
## Code Before:
import wx
## Tests if a wx control/instance is enabled
#
# Function for compatibility between wx versions
# \param enabled
# \b \e bool : Check if enabled or disabled
def FieldEnabled(field, enabled=True):
if wx.MAJOR_VERSION > 2:
return field.IsThisEnabled() == enabled
else:
return field.IsEnabled() == enabled
## Tests multiple fields
#
# \return
# \b \e bool : True if all fields are enabled
def FieldsEnabled(field_list):
if isinstance(field_list, (tuple, list)):
return FieldEnabled(field_list)
for F in field_list:
if not FieldEnabled(F):
return False
return True
## Instruction:
Add function FieldDisabled to test for disabled controls
## Code After:
import wx
## Tests if a wx control/instance is enabled/disabled
#
# Function for compatibility between wx versions
# \param field
# \b \e wx.Window : the wx control to check
# \param enabled
# \b \e bool : Check if enabled or disabled
# \return
# \b \e bool : True if field's enabled status is same as 'enabled'
def FieldEnabled(field, enabled=True):
if wx.MAJOR_VERSION > 2:
return field.IsThisEnabled() == enabled
else:
return field.IsEnabled() == enabled
## Tests if a wx control/instance is disabled
#
# \param field
# \b \e wx.Window : The wx field to check
# \return
# \b \e : True if field is disabled
def FieldDisabled(field):
return FieldEnabled(field, False)
## Tests multiple fields
#
# \return
# \b \e bool : True if all fields are enabled
def FieldsEnabled(field_list):
if isinstance(field_list, (tuple, list)):
return FieldEnabled(field_list)
for F in field_list:
if not FieldEnabled(F):
return False
return True
|
// ... existing code ...
## Tests if a wx control/instance is enabled/disabled
#
// ... modified code ...
# Function for compatibility between wx versions
# \param field
# \b \e wx.Window : the wx control to check
# \param enabled
...
# \b \e bool : Check if enabled or disabled
# \return
# \b \e bool : True if field's enabled status is same as 'enabled'
def FieldEnabled(field, enabled=True):
...
return field.IsEnabled() == enabled
## Tests if a wx control/instance is disabled
#
# \param field
# \b \e wx.Window : The wx field to check
# \return
# \b \e : True if field is disabled
def FieldDisabled(field):
return FieldEnabled(field, False)
// ... rest of the code ...
|
78032531e9fe1ab99f6c0e021250754fe5375ab9
|
src/zeit/content/article/edit/browser/tests/test_sync.py
|
src/zeit/content/article/edit/browser/tests/test_sync.py
|
import zeit.content.article.edit.browser.testing
class Supertitle(zeit.content.article.edit.browser.testing.EditorTestCase):
supertitle = 'article-content-head.supertitle'
teaser_supertitle = 'teaser-supertitle.teaserSupertitle'
layer = zeit.content.article.testing.WEBDRIVER_LAYER
def setUp(self):
super(Supertitle, self).setUp()
self.open('/repository/online/2007/01/Somalia/@@checkout')
self.selenium.waitForElementPresent('id=%s' % self.teaser_supertitle)
def test_teaser_supertitle_is_copied_to_article_supertitle_if_empty(self):
s = self.selenium
self.eval('document.getElementById("%s").value = ""' % self.supertitle)
s.click('//a[@href="edit-form-teaser"]')
s.type('id=%s' % self.teaser_supertitle, 'super\t')
# XXX There's nothing asynchronous going on here, but with a direct
# assert, the test fails with "Element is no longer attached to the
# DOM" (at least on WS's machine).
s.waitForValue('id=%s' % self.supertitle, 'super')
|
import zeit.content.article.edit.browser.testing
import time
class Supertitle(zeit.content.article.edit.browser.testing.EditorTestCase):
supertitle = 'article-content-head.supertitle'
teaser_supertitle = 'teaser-supertitle.teaserSupertitle'
layer = zeit.content.article.testing.WEBDRIVER_LAYER
def setUp(self):
super(Supertitle, self).setUp()
self.open('/repository/online/2007/01/Somalia/@@checkout')
self.selenium.waitForElementPresent('id=%s' % self.teaser_supertitle)
def test_teaser_supertitle_is_copied_to_article_supertitle_if_empty(self):
s = self.selenium
self.eval('document.getElementById("%s").value = ""' % self.supertitle)
s.click('//a[@href="edit-form-teaser"]')
s.type('id=%s' % self.teaser_supertitle, 'super\t')
# We cannot use waitForValue, since the DOM element changes in-between
# but Selenium retrieves the element once and only checks the value
# repeatedly, thus leading to an error that DOM is no longer attached
for i in range(10):
try:
s.assertValue('id=%s' % self.supertitle, 'super')
break
except:
time.sleep(0.1)
continue
s.assertValue('id=%s' % self.supertitle, 'super')
|
Fix test that may break with DOM element no longer attached, since the DOM element in question is reloaded.
|
Fix test that may break with DOM element no longer attached, since the DOM element in question is reloaded.
|
Python
|
bsd-3-clause
|
ZeitOnline/zeit.content.article,ZeitOnline/zeit.content.article,ZeitOnline/zeit.content.article
|
import zeit.content.article.edit.browser.testing
+ import time
class Supertitle(zeit.content.article.edit.browser.testing.EditorTestCase):
supertitle = 'article-content-head.supertitle'
teaser_supertitle = 'teaser-supertitle.teaserSupertitle'
layer = zeit.content.article.testing.WEBDRIVER_LAYER
def setUp(self):
super(Supertitle, self).setUp()
self.open('/repository/online/2007/01/Somalia/@@checkout')
self.selenium.waitForElementPresent('id=%s' % self.teaser_supertitle)
def test_teaser_supertitle_is_copied_to_article_supertitle_if_empty(self):
s = self.selenium
self.eval('document.getElementById("%s").value = ""' % self.supertitle)
s.click('//a[@href="edit-form-teaser"]')
s.type('id=%s' % self.teaser_supertitle, 'super\t')
- # XXX There's nothing asynchronous going on here, but with a direct
- # assert, the test fails with "Element is no longer attached to the
- # DOM" (at least on WS's machine).
- s.waitForValue('id=%s' % self.supertitle, 'super')
+ # We cannot use waitForValue, since the DOM element changes in-between
+ # but Selenium retrieves the element once and only checks the value
+ # repeatedly, thus leading to an error that DOM is no longer attached
+ for i in range(10):
+ try:
+ s.assertValue('id=%s' % self.supertitle, 'super')
+ break
+ except:
+ time.sleep(0.1)
+ continue
+ s.assertValue('id=%s' % self.supertitle, 'super')
+
|
Fix test that may break with DOM element no longer attached, since the DOM element in question is reloaded.
|
## Code Before:
import zeit.content.article.edit.browser.testing
class Supertitle(zeit.content.article.edit.browser.testing.EditorTestCase):
supertitle = 'article-content-head.supertitle'
teaser_supertitle = 'teaser-supertitle.teaserSupertitle'
layer = zeit.content.article.testing.WEBDRIVER_LAYER
def setUp(self):
super(Supertitle, self).setUp()
self.open('/repository/online/2007/01/Somalia/@@checkout')
self.selenium.waitForElementPresent('id=%s' % self.teaser_supertitle)
def test_teaser_supertitle_is_copied_to_article_supertitle_if_empty(self):
s = self.selenium
self.eval('document.getElementById("%s").value = ""' % self.supertitle)
s.click('//a[@href="edit-form-teaser"]')
s.type('id=%s' % self.teaser_supertitle, 'super\t')
# XXX There's nothing asynchronous going on here, but with a direct
# assert, the test fails with "Element is no longer attached to the
# DOM" (at least on WS's machine).
s.waitForValue('id=%s' % self.supertitle, 'super')
## Instruction:
Fix test that may break with DOM element no longer attached, since the DOM element in question is reloaded.
## Code After:
import zeit.content.article.edit.browser.testing
import time
class Supertitle(zeit.content.article.edit.browser.testing.EditorTestCase):
supertitle = 'article-content-head.supertitle'
teaser_supertitle = 'teaser-supertitle.teaserSupertitle'
layer = zeit.content.article.testing.WEBDRIVER_LAYER
def setUp(self):
super(Supertitle, self).setUp()
self.open('/repository/online/2007/01/Somalia/@@checkout')
self.selenium.waitForElementPresent('id=%s' % self.teaser_supertitle)
def test_teaser_supertitle_is_copied_to_article_supertitle_if_empty(self):
s = self.selenium
self.eval('document.getElementById("%s").value = ""' % self.supertitle)
s.click('//a[@href="edit-form-teaser"]')
s.type('id=%s' % self.teaser_supertitle, 'super\t')
# We cannot use waitForValue, since the DOM element changes in-between
# but Selenium retrieves the element once and only checks the value
# repeatedly, thus leading to an error that DOM is no longer attached
for i in range(10):
try:
s.assertValue('id=%s' % self.supertitle, 'super')
break
except:
time.sleep(0.1)
continue
s.assertValue('id=%s' % self.supertitle, 'super')
|
...
import zeit.content.article.edit.browser.testing
import time
...
s.type('id=%s' % self.teaser_supertitle, 'super\t')
# We cannot use waitForValue, since the DOM element changes in-between
# but Selenium retrieves the element once and only checks the value
# repeatedly, thus leading to an error that DOM is no longer attached
for i in range(10):
try:
s.assertValue('id=%s' % self.supertitle, 'super')
break
except:
time.sleep(0.1)
continue
s.assertValue('id=%s' % self.supertitle, 'super')
...
|
0aee34bc19d43f2369a121da2f9cfff05225fdbc
|
comet/__init__.py
|
comet/__init__.py
|
__description__ = "VOEvent Broker"
__url__ = "http://comet.transientskp.org/"
__author__ = "John Swinbank"
__contact__ = "[email protected]"
__version__ = "2.1.0-pre"
|
__description__ = "VOEvent Broker"
__url__ = "http://comet.transientskp.org/"
__author__ = "John Swinbank"
__contact__ = "[email protected]"
__version__ = "2.1.0-pre"
import sys
if sys.version_info.major <= 2:
BINARY_TYPE = str
else:
BINARY_TYPE = bytes
|
Add alias to appropriate raw bytes for this Python.
|
Add alias to appropriate raw bytes for this Python.
|
Python
|
bsd-2-clause
|
jdswinbank/Comet,jdswinbank/Comet
|
__description__ = "VOEvent Broker"
__url__ = "http://comet.transientskp.org/"
__author__ = "John Swinbank"
__contact__ = "[email protected]"
__version__ = "2.1.0-pre"
+ import sys
+
+ if sys.version_info.major <= 2:
+ BINARY_TYPE = str
+ else:
+ BINARY_TYPE = bytes
+
|
Add alias to appropriate raw bytes for this Python.
|
## Code Before:
__description__ = "VOEvent Broker"
__url__ = "http://comet.transientskp.org/"
__author__ = "John Swinbank"
__contact__ = "[email protected]"
__version__ = "2.1.0-pre"
## Instruction:
Add alias to appropriate raw bytes for this Python.
## Code After:
__description__ = "VOEvent Broker"
__url__ = "http://comet.transientskp.org/"
__author__ = "John Swinbank"
__contact__ = "[email protected]"
__version__ = "2.1.0-pre"
import sys
if sys.version_info.major <= 2:
BINARY_TYPE = str
else:
BINARY_TYPE = bytes
|
...
__version__ = "2.1.0-pre"
import sys
if sys.version_info.major <= 2:
BINARY_TYPE = str
else:
BINARY_TYPE = bytes
...
|
9e148028300a46f9074b9f188dc04d87884c8905
|
rsr/headerbar.py
|
rsr/headerbar.py
|
from gi.repository import Gio, Gtk
from rsr.commands import commands
class HeaderBar(Gtk.HeaderBar):
def __init__(self, win):
super(HeaderBar, self).__init__()
self.win = win
self.set_show_close_button(True)
self.set_title('RunSQLRun')
self.set_subtitle('Database query tool')
self.pack_start(self._btn_from_command('app', 'neweditor'))
self.pack_start(self._btn_from_command('editor', 'run'))
btn = Gtk.Button()
icon = Gio.ThemedIcon(name="preferences-system-symbolic")
image = Gtk.Image.new_from_gicon(icon, Gtk.IconSize.BUTTON)
btn.add(image)
self.pack_end(btn)
def _btn_from_command(self, group, name):
btn = Gtk.Button()
btn.set_action_name('app.{}_{}'.format(group, name))
data = commands[group]['actions'][name]
icon = Gio.ThemedIcon(name=data['icon'])
image = Gtk.Image.new_from_gicon(icon, Gtk.IconSize.BUTTON)
btn.add(image)
btn.set_tooltip_text('{} [{}]'.format(
data['description'], data['shortcut']))
return btn
def on_button_add_clicked(self, *args):
self.win.docview.add_worksheet()
|
from gi.repository import Gio, Gtk
from rsr.commands import commands
class HeaderBar(Gtk.HeaderBar):
def __init__(self, win):
super(HeaderBar, self).__init__()
self.win = win
self.set_show_close_button(True)
self.set_title('RunSQLRun')
self.set_subtitle('Database query tool')
self.pack_start(self._btn_from_command('app', 'neweditor'))
self.pack_start(self._btn_from_command('editor', 'run'))
# btn = Gtk.Button()
# icon = Gio.ThemedIcon(name="preferences-system-symbolic")
# image = Gtk.Image.new_from_gicon(icon, Gtk.IconSize.BUTTON)
# btn.add(image)
# self.pack_end(btn)
def _btn_from_command(self, group, name):
btn = Gtk.Button()
btn.set_action_name('app.{}_{}'.format(group, name))
data = commands[group]['actions'][name]
icon = Gio.ThemedIcon(name=data['icon'])
image = Gtk.Image.new_from_gicon(icon, Gtk.IconSize.BUTTON)
btn.add(image)
btn.set_tooltip_text('{} [{}]'.format(
data['description'], data['shortcut']))
return btn
def on_button_add_clicked(self, *args):
self.win.docview.add_worksheet()
|
Hide preferences button for now.
|
Hide preferences button for now.
|
Python
|
mit
|
andialbrecht/runsqlrun
|
from gi.repository import Gio, Gtk
from rsr.commands import commands
class HeaderBar(Gtk.HeaderBar):
def __init__(self, win):
super(HeaderBar, self).__init__()
self.win = win
self.set_show_close_button(True)
self.set_title('RunSQLRun')
self.set_subtitle('Database query tool')
self.pack_start(self._btn_from_command('app', 'neweditor'))
self.pack_start(self._btn_from_command('editor', 'run'))
- btn = Gtk.Button()
+ # btn = Gtk.Button()
- icon = Gio.ThemedIcon(name="preferences-system-symbolic")
+ # icon = Gio.ThemedIcon(name="preferences-system-symbolic")
- image = Gtk.Image.new_from_gicon(icon, Gtk.IconSize.BUTTON)
+ # image = Gtk.Image.new_from_gicon(icon, Gtk.IconSize.BUTTON)
- btn.add(image)
+ # btn.add(image)
- self.pack_end(btn)
+ # self.pack_end(btn)
def _btn_from_command(self, group, name):
btn = Gtk.Button()
btn.set_action_name('app.{}_{}'.format(group, name))
data = commands[group]['actions'][name]
icon = Gio.ThemedIcon(name=data['icon'])
image = Gtk.Image.new_from_gicon(icon, Gtk.IconSize.BUTTON)
btn.add(image)
btn.set_tooltip_text('{} [{}]'.format(
data['description'], data['shortcut']))
return btn
def on_button_add_clicked(self, *args):
self.win.docview.add_worksheet()
|
Hide preferences button for now.
|
## Code Before:
from gi.repository import Gio, Gtk
from rsr.commands import commands
class HeaderBar(Gtk.HeaderBar):
def __init__(self, win):
super(HeaderBar, self).__init__()
self.win = win
self.set_show_close_button(True)
self.set_title('RunSQLRun')
self.set_subtitle('Database query tool')
self.pack_start(self._btn_from_command('app', 'neweditor'))
self.pack_start(self._btn_from_command('editor', 'run'))
btn = Gtk.Button()
icon = Gio.ThemedIcon(name="preferences-system-symbolic")
image = Gtk.Image.new_from_gicon(icon, Gtk.IconSize.BUTTON)
btn.add(image)
self.pack_end(btn)
def _btn_from_command(self, group, name):
btn = Gtk.Button()
btn.set_action_name('app.{}_{}'.format(group, name))
data = commands[group]['actions'][name]
icon = Gio.ThemedIcon(name=data['icon'])
image = Gtk.Image.new_from_gicon(icon, Gtk.IconSize.BUTTON)
btn.add(image)
btn.set_tooltip_text('{} [{}]'.format(
data['description'], data['shortcut']))
return btn
def on_button_add_clicked(self, *args):
self.win.docview.add_worksheet()
## Instruction:
Hide preferences button for now.
## Code After:
from gi.repository import Gio, Gtk
from rsr.commands import commands
class HeaderBar(Gtk.HeaderBar):
def __init__(self, win):
super(HeaderBar, self).__init__()
self.win = win
self.set_show_close_button(True)
self.set_title('RunSQLRun')
self.set_subtitle('Database query tool')
self.pack_start(self._btn_from_command('app', 'neweditor'))
self.pack_start(self._btn_from_command('editor', 'run'))
# btn = Gtk.Button()
# icon = Gio.ThemedIcon(name="preferences-system-symbolic")
# image = Gtk.Image.new_from_gicon(icon, Gtk.IconSize.BUTTON)
# btn.add(image)
# self.pack_end(btn)
def _btn_from_command(self, group, name):
btn = Gtk.Button()
btn.set_action_name('app.{}_{}'.format(group, name))
data = commands[group]['actions'][name]
icon = Gio.ThemedIcon(name=data['icon'])
image = Gtk.Image.new_from_gicon(icon, Gtk.IconSize.BUTTON)
btn.add(image)
btn.set_tooltip_text('{} [{}]'.format(
data['description'], data['shortcut']))
return btn
def on_button_add_clicked(self, *args):
self.win.docview.add_worksheet()
|
# ... existing code ...
# btn = Gtk.Button()
# icon = Gio.ThemedIcon(name="preferences-system-symbolic")
# image = Gtk.Image.new_from_gicon(icon, Gtk.IconSize.BUTTON)
# btn.add(image)
# self.pack_end(btn)
# ... rest of the code ...
|
b9a752c8f6ea7fd9ada1ec283b7aaaa2eaf4b271
|
src/gui/loggers_ui/urls.py
|
src/gui/loggers_ui/urls.py
|
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.MainPage.as_view(), name='index'),
url(r'^(?P<ses_id>[a-zA-Z0-9]+)/$', views.SessionPage.as_view(),
name='Session'),
url(r'^GlobalMap/$', views.GlobalMap.as_view(),
name='GlobalMap'),
url(r'^(?P<ses_id>[a-zA-Z0-9]+)/Map$', views.MapPage.as_view(),
name='Map'),
url(r'^(?P<ses_id>[a-zA-Z0-9]+)/download$', views.download_file,
name='ses_down'),
]
|
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.MainPage.as_view(), name='index'),
url(r'^GlobalMap/$', views.GlobalMap.as_view(),
name='GlobalMap'),
url(r'^(?P<ses_id>[a-zA-Z0-9]+)/$', views.SessionPage.as_view(),
name='Session'),
url(r'^(?P<ses_id>[a-zA-Z0-9]+)/Map$', views.MapPage.as_view(),
name='Map'),
url(r'^(?P<ses_id>[a-zA-Z0-9]+)/download$', views.download_file,
name='ses_down'),
]
|
Move global map url before session url.
|
gui: Move global map url before session url.
|
Python
|
mit
|
alberand/tserver,alberand/tserver,alberand/tserver,alberand/tserver
|
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.MainPage.as_view(), name='index'),
+ url(r'^GlobalMap/$', views.GlobalMap.as_view(),
+ name='GlobalMap'),
url(r'^(?P<ses_id>[a-zA-Z0-9]+)/$', views.SessionPage.as_view(),
name='Session'),
- url(r'^GlobalMap/$', views.GlobalMap.as_view(),
- name='GlobalMap'),
url(r'^(?P<ses_id>[a-zA-Z0-9]+)/Map$', views.MapPage.as_view(),
name='Map'),
url(r'^(?P<ses_id>[a-zA-Z0-9]+)/download$', views.download_file,
name='ses_down'),
]
|
Move global map url before session url.
|
## Code Before:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.MainPage.as_view(), name='index'),
url(r'^(?P<ses_id>[a-zA-Z0-9]+)/$', views.SessionPage.as_view(),
name='Session'),
url(r'^GlobalMap/$', views.GlobalMap.as_view(),
name='GlobalMap'),
url(r'^(?P<ses_id>[a-zA-Z0-9]+)/Map$', views.MapPage.as_view(),
name='Map'),
url(r'^(?P<ses_id>[a-zA-Z0-9]+)/download$', views.download_file,
name='ses_down'),
]
## Instruction:
Move global map url before session url.
## Code After:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.MainPage.as_view(), name='index'),
url(r'^GlobalMap/$', views.GlobalMap.as_view(),
name='GlobalMap'),
url(r'^(?P<ses_id>[a-zA-Z0-9]+)/$', views.SessionPage.as_view(),
name='Session'),
url(r'^(?P<ses_id>[a-zA-Z0-9]+)/Map$', views.MapPage.as_view(),
name='Map'),
url(r'^(?P<ses_id>[a-zA-Z0-9]+)/download$', views.download_file,
name='ses_down'),
]
|
// ... existing code ...
url(r'^$', views.MainPage.as_view(), name='index'),
url(r'^GlobalMap/$', views.GlobalMap.as_view(),
name='GlobalMap'),
url(r'^(?P<ses_id>[a-zA-Z0-9]+)/$', views.SessionPage.as_view(),
// ... modified code ...
name='Session'),
url(r'^(?P<ses_id>[a-zA-Z0-9]+)/Map$', views.MapPage.as_view(),
// ... rest of the code ...
|
6e8e7a067419166afd632aa63ecb743dd6c3a162
|
geokey_dataimports/tests/test_model_helpers.py
|
geokey_dataimports/tests/test_model_helpers.py
|
from io import BytesIO
from django.test import TestCase
from geokey_dataimports.helpers.model_helpers import import_from_csv
class ImportFromCSVTest(TestCase):
"""Tests to check that characters can be imported from CSV files.
Notes that these tests are probably not possible or relevant under Python 3.
"""
def test_import_csv_basic_chars(self):
"""Basic ASCII characters can be imported."""
mock_csv = BytesIO("abc,cde,efg\n123,456,789")
features = []
import_from_csv(features=features, fields=[], file=mock_csv)
print(features)
self.assertEquals(features[0]['properties'], {'cde': '456', 'abc': '123', 'efg': '789'})
def test_import_csv_non_ascii_chars(self):
"""Non-ASCII unicode characters can be imported."""
mock_csv = BytesIO("abc,àde,e£g\n¡23,45Ç,Æ8é")
features = []
import_from_csv(features=features, fields=[], file=mock_csv)
print(features)
self.assertEquals(features[0]['properties'], {'àde': '45Ç', 'abc': '¡23', 'e£g': 'Æ8é'})
|
from cStringIO import StringIO
from django.test import TestCase
from geokey_dataimports.helpers.model_helpers import import_from_csv
class ImportFromCSVTest(TestCase):
"""Tests to check that characters can be imported from CSV files.
Notes that these tests are probably not possible or relevant under Python 3.
"""
def test_import_csv_basic_chars(self):
"""Basic ASCII characters can be imported."""
input_dict = {u'abc': u'123', u'cde': u'456', u'efg': u'789'}
mock_csv = StringIO("abc,cde,efg\n123,456,789")
features = []
import_from_csv(features=features, fields=[], file_obj=mock_csv)
for k, v in input_dict.items():
self.assertEquals(v, features[0]['properties'][k])
def test_import_csv_non_ascii_chars(self):
"""Non-ASCII unicode characters can be imported."""
input_dict = {u'à': u'¡', u'£': u'Ç'}
mock_csv = StringIO("à,£\n¡,Ç")
features = []
import_from_csv(features=features, fields=[], file_obj=mock_csv)
for k, v in input_dict.items():
self.assertEquals(v, features[0]['properties'][k])
|
Simplify test data for easier comparison.
|
Simplify test data for easier comparison.
|
Python
|
mit
|
ExCiteS/geokey-dataimports,ExCiteS/geokey-dataimports,ExCiteS/geokey-dataimports
|
- from io import BytesIO
+ from cStringIO import StringIO
from django.test import TestCase
from geokey_dataimports.helpers.model_helpers import import_from_csv
class ImportFromCSVTest(TestCase):
"""Tests to check that characters can be imported from CSV files.
Notes that these tests are probably not possible or relevant under Python 3.
"""
def test_import_csv_basic_chars(self):
"""Basic ASCII characters can be imported."""
+ input_dict = {u'abc': u'123', u'cde': u'456', u'efg': u'789'}
- mock_csv = BytesIO("abc,cde,efg\n123,456,789")
+ mock_csv = StringIO("abc,cde,efg\n123,456,789")
features = []
- import_from_csv(features=features, fields=[], file=mock_csv)
+ import_from_csv(features=features, fields=[], file_obj=mock_csv)
- print(features)
- self.assertEquals(features[0]['properties'], {'cde': '456', 'abc': '123', 'efg': '789'})
+ for k, v in input_dict.items():
+ self.assertEquals(v, features[0]['properties'][k])
def test_import_csv_non_ascii_chars(self):
"""Non-ASCII unicode characters can be imported."""
- mock_csv = BytesIO("abc,àde,e£g\n¡23,45Ç,Æ8é")
+ input_dict = {u'à': u'¡', u'£': u'Ç'}
+ mock_csv = StringIO("à,£\n¡,Ç")
features = []
- import_from_csv(features=features, fields=[], file=mock_csv)
+ import_from_csv(features=features, fields=[], file_obj=mock_csv)
- print(features)
- self.assertEquals(features[0]['properties'], {'àde': '45Ç', 'abc': '¡23', 'e£g': 'Æ8é'})
+ for k, v in input_dict.items():
+ self.assertEquals(v, features[0]['properties'][k])
+
|
Simplify test data for easier comparison.
|
## Code Before:
from io import BytesIO
from django.test import TestCase
from geokey_dataimports.helpers.model_helpers import import_from_csv
class ImportFromCSVTest(TestCase):
"""Tests to check that characters can be imported from CSV files.
Notes that these tests are probably not possible or relevant under Python 3.
"""
def test_import_csv_basic_chars(self):
"""Basic ASCII characters can be imported."""
mock_csv = BytesIO("abc,cde,efg\n123,456,789")
features = []
import_from_csv(features=features, fields=[], file=mock_csv)
print(features)
self.assertEquals(features[0]['properties'], {'cde': '456', 'abc': '123', 'efg': '789'})
def test_import_csv_non_ascii_chars(self):
"""Non-ASCII unicode characters can be imported."""
mock_csv = BytesIO("abc,àde,e£g\n¡23,45Ç,Æ8é")
features = []
import_from_csv(features=features, fields=[], file=mock_csv)
print(features)
self.assertEquals(features[0]['properties'], {'àde': '45Ç', 'abc': '¡23', 'e£g': 'Æ8é'})
## Instruction:
Simplify test data for easier comparison.
## Code After:
from cStringIO import StringIO
from django.test import TestCase
from geokey_dataimports.helpers.model_helpers import import_from_csv
class ImportFromCSVTest(TestCase):
"""Tests to check that characters can be imported from CSV files.
Notes that these tests are probably not possible or relevant under Python 3.
"""
def test_import_csv_basic_chars(self):
"""Basic ASCII characters can be imported."""
input_dict = {u'abc': u'123', u'cde': u'456', u'efg': u'789'}
mock_csv = StringIO("abc,cde,efg\n123,456,789")
features = []
import_from_csv(features=features, fields=[], file_obj=mock_csv)
for k, v in input_dict.items():
self.assertEquals(v, features[0]['properties'][k])
def test_import_csv_non_ascii_chars(self):
"""Non-ASCII unicode characters can be imported."""
input_dict = {u'à': u'¡', u'£': u'Ç'}
mock_csv = StringIO("à,£\n¡,Ç")
features = []
import_from_csv(features=features, fields=[], file_obj=mock_csv)
for k, v in input_dict.items():
self.assertEquals(v, features[0]['properties'][k])
|
# ... existing code ...
from cStringIO import StringIO
from django.test import TestCase
# ... modified code ...
"""Basic ASCII characters can be imported."""
input_dict = {u'abc': u'123', u'cde': u'456', u'efg': u'789'}
mock_csv = StringIO("abc,cde,efg\n123,456,789")
features = []
import_from_csv(features=features, fields=[], file_obj=mock_csv)
for k, v in input_dict.items():
self.assertEquals(v, features[0]['properties'][k])
...
"""Non-ASCII unicode characters can be imported."""
input_dict = {u'à': u'¡', u'£': u'Ç'}
mock_csv = StringIO("à,£\n¡,Ç")
features = []
import_from_csv(features=features, fields=[], file_obj=mock_csv)
for k, v in input_dict.items():
self.assertEquals(v, features[0]['properties'][k])
# ... rest of the code ...
|
43905a102092bdd50de1f8997cd19cb617b348b3
|
tests/cart_tests.py
|
tests/cart_tests.py
|
import importlib
import os
import sys
import unittest
import code
import struct
code_path = os.path.dirname(__file__)
code_path = os.path.join(code_path, os.pardir)
sys.path.append(code_path)
import MOS6502
class TestCartHeaderParsing(unittest.TestCase):
def testMagic(self):
cpu = MOS6502.CPU()
cpu.loadRom("../smb1.nes")
self.assertEqual(cpu.rom != None, True)
def testRomBanks(self):
cpu = MOS6502.CPU()
cpu.loadRom("../smb1.nes")
self.assertEqual(cpu.rom.numRomBanks, 2)
self.assertEqual(cpu.rom.numVromBanks, 1)
if __name__ == '__main__':
unittest.main()
|
import importlib
import os
import sys
import unittest
import code
import struct
code_path = os.path.dirname(__file__)
code_path = os.path.join(code_path, os.pardir)
sys.path.append(code_path)
import MOS6502
class TestCartHeaderParsing(unittest.TestCase):
def testMagic(self):
cpu = MOS6502.CPU()
cpu.loadRom("../smb1.nes")
self.assertEqual(cpu.rom != None, True)
def testRomBanks(self):
cpu = MOS6502.CPU()
cpu.loadRom("../smb1.nes")
self.assertEqual(cpu.rom.numRomBanks, 2)
self.assertEqual(cpu.rom.numVromBanks, 1)
startAddr = cpu.ReadMemWord(cpu.reset)
firstByte = cpu.ReadMemory(startAddr)
self.assertEqual(firstByte, 0x78)
if __name__ == '__main__':
unittest.main()
|
Use the reset adder from the banks properly
|
Use the reset adder from the banks properly
|
Python
|
bsd-2-clause
|
pusscat/refNes
|
import importlib
import os
import sys
import unittest
import code
import struct
code_path = os.path.dirname(__file__)
code_path = os.path.join(code_path, os.pardir)
sys.path.append(code_path)
import MOS6502
class TestCartHeaderParsing(unittest.TestCase):
def testMagic(self):
cpu = MOS6502.CPU()
cpu.loadRom("../smb1.nes")
self.assertEqual(cpu.rom != None, True)
def testRomBanks(self):
cpu = MOS6502.CPU()
cpu.loadRom("../smb1.nes")
self.assertEqual(cpu.rom.numRomBanks, 2)
self.assertEqual(cpu.rom.numVromBanks, 1)
+ startAddr = cpu.ReadMemWord(cpu.reset)
+ firstByte = cpu.ReadMemory(startAddr)
+ self.assertEqual(firstByte, 0x78)
if __name__ == '__main__':
unittest.main()
|
Use the reset adder from the banks properly
|
## Code Before:
import importlib
import os
import sys
import unittest
import code
import struct
code_path = os.path.dirname(__file__)
code_path = os.path.join(code_path, os.pardir)
sys.path.append(code_path)
import MOS6502
class TestCartHeaderParsing(unittest.TestCase):
def testMagic(self):
cpu = MOS6502.CPU()
cpu.loadRom("../smb1.nes")
self.assertEqual(cpu.rom != None, True)
def testRomBanks(self):
cpu = MOS6502.CPU()
cpu.loadRom("../smb1.nes")
self.assertEqual(cpu.rom.numRomBanks, 2)
self.assertEqual(cpu.rom.numVromBanks, 1)
if __name__ == '__main__':
unittest.main()
## Instruction:
Use the reset adder from the banks properly
## Code After:
import importlib
import os
import sys
import unittest
import code
import struct
code_path = os.path.dirname(__file__)
code_path = os.path.join(code_path, os.pardir)
sys.path.append(code_path)
import MOS6502
class TestCartHeaderParsing(unittest.TestCase):
def testMagic(self):
cpu = MOS6502.CPU()
cpu.loadRom("../smb1.nes")
self.assertEqual(cpu.rom != None, True)
def testRomBanks(self):
cpu = MOS6502.CPU()
cpu.loadRom("../smb1.nes")
self.assertEqual(cpu.rom.numRomBanks, 2)
self.assertEqual(cpu.rom.numVromBanks, 1)
startAddr = cpu.ReadMemWord(cpu.reset)
firstByte = cpu.ReadMemory(startAddr)
self.assertEqual(firstByte, 0x78)
if __name__ == '__main__':
unittest.main()
|
...
startAddr = cpu.ReadMemWord(cpu.reset)
firstByte = cpu.ReadMemory(startAddr)
self.assertEqual(firstByte, 0x78)
...
|
c2ae6fb563b1ecc20b11ec6d693bad8a7f9e8945
|
scrapple/utils/exceptions.py
|
scrapple/utils/exceptions.py
|
import re
def handle_exceptions(args):
"""
Validates the arguments passed through the CLI commands.
:param args: The arguments passed in the CLI, parsed by the docopt module
:return: None
"""
projectname_re = re.compile(r'[^a-zA-Z0-9_]')
if args['genconfig']:
if args['--type'] not in ['scraper', 'crawler']:
raise Exception("--type has to be 'scraper' or 'crawler'")
if args['--selector'] not in ['xpath', 'css']:
raise Exception("--selector has to be 'xpath' or 'css'")
if args['generate'] or args['run']:
if args['--output_type'] not in ['json', 'csv']:
raise Exception("--output_type has to be 'json' or 'csv'")
if args['genconfig'] or args['generate'] or args['run']:
if projectname_re.search(args['<projectname>']) is not None:
raise Exception("<projectname> should consist of letters, digits or _")
return
|
import re
def handle_exceptions(args):
"""
Validates the arguments passed through the CLI commands.
:param args: The arguments passed in the CLI, parsed by the docopt module
:return: None
"""
projectname_re = re.compile(r'[^a-zA-Z0-9_]')
if args['genconfig']:
if args['--type'] not in ['scraper', 'crawler']:
raise Exception("--type has to be 'scraper' or 'crawler'")
if args['--selector'] not in ['xpath', 'css']:
raise Exception("--selector has to be 'xpath' or 'css'")
if args['generate'] or args['run']:
if args['--output_type'] not in ['json', 'csv']:
raise Exception("--output_type has to be 'json' or 'csv'")
if args['genconfig'] or args['generate'] or args['run']:
if projectname_re.search(args['<projectname>']) is not None:
raise Exception("<projectname> should consist of letters, digits or _")
if int(args['--levels']) < 1:
raise Exception("--levels should be greater than, or equal to 1")
return
|
Update exception handling for levels argument
|
Update exception handling for levels argument
|
Python
|
mit
|
scrappleapp/scrapple,AlexMathew/scrapple,AlexMathew/scrapple,scrappleapp/scrapple,AlexMathew/scrapple
|
import re
def handle_exceptions(args):
"""
Validates the arguments passed through the CLI commands.
:param args: The arguments passed in the CLI, parsed by the docopt module
:return: None
"""
projectname_re = re.compile(r'[^a-zA-Z0-9_]')
if args['genconfig']:
if args['--type'] not in ['scraper', 'crawler']:
raise Exception("--type has to be 'scraper' or 'crawler'")
if args['--selector'] not in ['xpath', 'css']:
raise Exception("--selector has to be 'xpath' or 'css'")
if args['generate'] or args['run']:
if args['--output_type'] not in ['json', 'csv']:
raise Exception("--output_type has to be 'json' or 'csv'")
if args['genconfig'] or args['generate'] or args['run']:
if projectname_re.search(args['<projectname>']) is not None:
raise Exception("<projectname> should consist of letters, digits or _")
+ if int(args['--levels']) < 1:
+ raise Exception("--levels should be greater than, or equal to 1")
return
|
Update exception handling for levels argument
|
## Code Before:
import re
def handle_exceptions(args):
"""
Validates the arguments passed through the CLI commands.
:param args: The arguments passed in the CLI, parsed by the docopt module
:return: None
"""
projectname_re = re.compile(r'[^a-zA-Z0-9_]')
if args['genconfig']:
if args['--type'] not in ['scraper', 'crawler']:
raise Exception("--type has to be 'scraper' or 'crawler'")
if args['--selector'] not in ['xpath', 'css']:
raise Exception("--selector has to be 'xpath' or 'css'")
if args['generate'] or args['run']:
if args['--output_type'] not in ['json', 'csv']:
raise Exception("--output_type has to be 'json' or 'csv'")
if args['genconfig'] or args['generate'] or args['run']:
if projectname_re.search(args['<projectname>']) is not None:
raise Exception("<projectname> should consist of letters, digits or _")
return
## Instruction:
Update exception handling for levels argument
## Code After:
import re
def handle_exceptions(args):
"""
Validates the arguments passed through the CLI commands.
:param args: The arguments passed in the CLI, parsed by the docopt module
:return: None
"""
projectname_re = re.compile(r'[^a-zA-Z0-9_]')
if args['genconfig']:
if args['--type'] not in ['scraper', 'crawler']:
raise Exception("--type has to be 'scraper' or 'crawler'")
if args['--selector'] not in ['xpath', 'css']:
raise Exception("--selector has to be 'xpath' or 'css'")
if args['generate'] or args['run']:
if args['--output_type'] not in ['json', 'csv']:
raise Exception("--output_type has to be 'json' or 'csv'")
if args['genconfig'] or args['generate'] or args['run']:
if projectname_re.search(args['<projectname>']) is not None:
raise Exception("<projectname> should consist of letters, digits or _")
if int(args['--levels']) < 1:
raise Exception("--levels should be greater than, or equal to 1")
return
|
// ... existing code ...
raise Exception("<projectname> should consist of letters, digits or _")
if int(args['--levels']) < 1:
raise Exception("--levels should be greater than, or equal to 1")
return
// ... rest of the code ...
|
92c024c2112573e4c4b2d1288b1ec3c7a40bc670
|
test/test_uploader.py
|
test/test_uploader.py
|
import boto3
from os import path
from lambda_uploader import uploader, config
from moto import mock_s3
EX_CONFIG = path.normpath(path.join(path.dirname(__file__),
'../test/configs'))
@mock_s3
def test_s3_upload():
mock_bucket = 'mybucket'
conn = boto3.resource('s3')
conn.create_bucket(Bucket=mock_bucket)
conf = config.Config(path.dirname(__file__),
config_file=path.join(EX_CONFIG, 'lambda.json'))
conf.set_s3(mock_bucket)
upldr = uploader.PackageUploader(conf, None)
upldr._upload_s3(path.join(path.dirname(__file__), 'dummyfile'))
|
import boto3
from os import path
from lambda_uploader import uploader, config
from moto import mock_s3
EX_CONFIG = path.normpath(path.join(path.dirname(__file__),
'../test/configs'))
@mock_s3
def test_s3_upload():
mock_bucket = 'mybucket'
conn = boto3.resource('s3')
conn.create_bucket(Bucket=mock_bucket)
conf = config.Config(path.dirname(__file__),
config_file=path.join(EX_CONFIG, 'lambda.json'))
conf.set_s3(mock_bucket)
upldr = uploader.PackageUploader(conf, None)
upldr._upload_s3(path.join(path.dirname(__file__), 'dummyfile'))
# fetch the contents back out, be sure we truly uploaded the dummyfile
retrieved_bucket = conn.Object(
mock_bucket,
conf.s3_package_name()
).get()['Body']
found_contents = str(retrieved_bucket.read()).rstrip()
assert found_contents == 'dummy data'
|
Add additional assertion that the file we uploaded is correct
|
Add additional assertion that the file we uploaded is correct
We should pull back down the S3 bucket file and be sure it's the same, proving we used the boto3 API correctly. We should probably, at some point, also upload a _real_ zip file and not just a plaintext file.
|
Python
|
apache-2.0
|
rackerlabs/lambda-uploader,dsouzajude/lambda-uploader
|
import boto3
from os import path
from lambda_uploader import uploader, config
from moto import mock_s3
EX_CONFIG = path.normpath(path.join(path.dirname(__file__),
'../test/configs'))
@mock_s3
def test_s3_upload():
mock_bucket = 'mybucket'
conn = boto3.resource('s3')
conn.create_bucket(Bucket=mock_bucket)
conf = config.Config(path.dirname(__file__),
config_file=path.join(EX_CONFIG, 'lambda.json'))
conf.set_s3(mock_bucket)
upldr = uploader.PackageUploader(conf, None)
upldr._upload_s3(path.join(path.dirname(__file__), 'dummyfile'))
+ # fetch the contents back out, be sure we truly uploaded the dummyfile
+ retrieved_bucket = conn.Object(
+ mock_bucket,
+ conf.s3_package_name()
+ ).get()['Body']
+ found_contents = str(retrieved_bucket.read()).rstrip()
+ assert found_contents == 'dummy data'
+
|
Add additional assertion that the file we uploaded is correct
|
## Code Before:
import boto3
from os import path
from lambda_uploader import uploader, config
from moto import mock_s3
EX_CONFIG = path.normpath(path.join(path.dirname(__file__),
'../test/configs'))
@mock_s3
def test_s3_upload():
mock_bucket = 'mybucket'
conn = boto3.resource('s3')
conn.create_bucket(Bucket=mock_bucket)
conf = config.Config(path.dirname(__file__),
config_file=path.join(EX_CONFIG, 'lambda.json'))
conf.set_s3(mock_bucket)
upldr = uploader.PackageUploader(conf, None)
upldr._upload_s3(path.join(path.dirname(__file__), 'dummyfile'))
## Instruction:
Add additional assertion that the file we uploaded is correct
## Code After:
import boto3
from os import path
from lambda_uploader import uploader, config
from moto import mock_s3
EX_CONFIG = path.normpath(path.join(path.dirname(__file__),
'../test/configs'))
@mock_s3
def test_s3_upload():
mock_bucket = 'mybucket'
conn = boto3.resource('s3')
conn.create_bucket(Bucket=mock_bucket)
conf = config.Config(path.dirname(__file__),
config_file=path.join(EX_CONFIG, 'lambda.json'))
conf.set_s3(mock_bucket)
upldr = uploader.PackageUploader(conf, None)
upldr._upload_s3(path.join(path.dirname(__file__), 'dummyfile'))
# fetch the contents back out, be sure we truly uploaded the dummyfile
retrieved_bucket = conn.Object(
mock_bucket,
conf.s3_package_name()
).get()['Body']
found_contents = str(retrieved_bucket.read()).rstrip()
assert found_contents == 'dummy data'
|
# ... existing code ...
upldr._upload_s3(path.join(path.dirname(__file__), 'dummyfile'))
# fetch the contents back out, be sure we truly uploaded the dummyfile
retrieved_bucket = conn.Object(
mock_bucket,
conf.s3_package_name()
).get()['Body']
found_contents = str(retrieved_bucket.read()).rstrip()
assert found_contents == 'dummy data'
# ... rest of the code ...
|
b6cfa50e127d3f74247ab148219ef6336e445cca
|
InvenTree/InvenTree/ready.py
|
InvenTree/InvenTree/ready.py
|
import sys
def canAppAccessDatabase():
"""
Returns True if the apps.py file can access database records.
There are some circumstances where we don't want the ready function in apps.py
to touch the database
"""
# If any of the following management commands are being executed,
# prevent custom "on load" code from running!
excluded_commands = [
'flush',
'loaddata',
'dumpdata',
'makemirations',
'migrate',
'check',
'dbbackup',
'mediabackup',
'dbrestore',
'mediarestore',
'shell',
'createsuperuser',
'wait_for_db',
'prerender',
'collectstatic',
'makemessages',
'compilemessages',
'test',
]
for cmd in excluded_commands:
if cmd in sys.argv:
return False
return True
|
import sys
def canAppAccessDatabase():
"""
Returns True if the apps.py file can access database records.
There are some circumstances where we don't want the ready function in apps.py
to touch the database
"""
# If any of the following management commands are being executed,
# prevent custom "on load" code from running!
excluded_commands = [
'flush',
'loaddata',
'dumpdata',
'makemirations',
'migrate',
'check',
'dbbackup',
'mediabackup',
'dbrestore',
'mediarestore',
'shell',
'createsuperuser',
'wait_for_db',
'prerender',
'collectstatic',
'makemessages',
'compilemessages',
]
for cmd in excluded_commands:
if cmd in sys.argv:
return False
return True
|
Allow data operations to run for 'test'
|
Allow data operations to run for 'test'
|
Python
|
mit
|
inventree/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree
|
import sys
def canAppAccessDatabase():
"""
Returns True if the apps.py file can access database records.
There are some circumstances where we don't want the ready function in apps.py
to touch the database
"""
# If any of the following management commands are being executed,
# prevent custom "on load" code from running!
excluded_commands = [
'flush',
'loaddata',
'dumpdata',
'makemirations',
'migrate',
'check',
'dbbackup',
'mediabackup',
'dbrestore',
'mediarestore',
'shell',
'createsuperuser',
'wait_for_db',
'prerender',
'collectstatic',
'makemessages',
'compilemessages',
- 'test',
]
for cmd in excluded_commands:
if cmd in sys.argv:
return False
return True
|
Allow data operations to run for 'test'
|
## Code Before:
import sys
def canAppAccessDatabase():
"""
Returns True if the apps.py file can access database records.
There are some circumstances where we don't want the ready function in apps.py
to touch the database
"""
# If any of the following management commands are being executed,
# prevent custom "on load" code from running!
excluded_commands = [
'flush',
'loaddata',
'dumpdata',
'makemirations',
'migrate',
'check',
'dbbackup',
'mediabackup',
'dbrestore',
'mediarestore',
'shell',
'createsuperuser',
'wait_for_db',
'prerender',
'collectstatic',
'makemessages',
'compilemessages',
'test',
]
for cmd in excluded_commands:
if cmd in sys.argv:
return False
return True
## Instruction:
Allow data operations to run for 'test'
## Code After:
import sys
def canAppAccessDatabase():
"""
Returns True if the apps.py file can access database records.
There are some circumstances where we don't want the ready function in apps.py
to touch the database
"""
# If any of the following management commands are being executed,
# prevent custom "on load" code from running!
excluded_commands = [
'flush',
'loaddata',
'dumpdata',
'makemirations',
'migrate',
'check',
'dbbackup',
'mediabackup',
'dbrestore',
'mediarestore',
'shell',
'createsuperuser',
'wait_for_db',
'prerender',
'collectstatic',
'makemessages',
'compilemessages',
]
for cmd in excluded_commands:
if cmd in sys.argv:
return False
return True
|
...
'compilemessages',
]
...
|
d921858302f8bba715a7f4e63eaec68dfe04927a
|
app/grandchallenge/workstations/context_processors.py
|
app/grandchallenge/workstations/context_processors.py
|
from grandchallenge.workstations.models import Session
def workstation_session(request):
""" Adds workstation_session. request.user must be set """
s = None
if not request.user.is_anonymous:
s = (
Session.objects.filter(creator=request.user)
.exclude(status__in=[Session.QUEUED, Session.STOPPED])
.order_by("-created")
.select_related("workstation_image__workstation")
.first()
)
return {"workstation_session": s}
|
from grandchallenge.workstations.models import Session
def workstation_session(request):
""" Adds workstation_session. request.user must be set """
s = None
try:
if not request.user.is_anonymous:
s = (
Session.objects.filter(creator=request.user)
.exclude(status__in=[Session.QUEUED, Session.STOPPED])
.order_by("-created")
.select_related("workstation_image__workstation")
.first()
)
except AttributeError:
# No user
pass
return {"workstation_session": s}
|
Handle no user at all
|
Handle no user at all
|
Python
|
apache-2.0
|
comic/comic-django,comic/comic-django,comic/comic-django,comic/comic-django,comic/comic-django
|
from grandchallenge.workstations.models import Session
def workstation_session(request):
""" Adds workstation_session. request.user must be set """
s = None
+ try:
- if not request.user.is_anonymous:
+ if not request.user.is_anonymous:
- s = (
+ s = (
- Session.objects.filter(creator=request.user)
+ Session.objects.filter(creator=request.user)
- .exclude(status__in=[Session.QUEUED, Session.STOPPED])
+ .exclude(status__in=[Session.QUEUED, Session.STOPPED])
- .order_by("-created")
+ .order_by("-created")
- .select_related("workstation_image__workstation")
+ .select_related("workstation_image__workstation")
- .first()
+ .first()
- )
+ )
+ except AttributeError:
+ # No user
+ pass
return {"workstation_session": s}
|
Handle no user at all
|
## Code Before:
from grandchallenge.workstations.models import Session
def workstation_session(request):
""" Adds workstation_session. request.user must be set """
s = None
if not request.user.is_anonymous:
s = (
Session.objects.filter(creator=request.user)
.exclude(status__in=[Session.QUEUED, Session.STOPPED])
.order_by("-created")
.select_related("workstation_image__workstation")
.first()
)
return {"workstation_session": s}
## Instruction:
Handle no user at all
## Code After:
from grandchallenge.workstations.models import Session
def workstation_session(request):
""" Adds workstation_session. request.user must be set """
s = None
try:
if not request.user.is_anonymous:
s = (
Session.objects.filter(creator=request.user)
.exclude(status__in=[Session.QUEUED, Session.STOPPED])
.order_by("-created")
.select_related("workstation_image__workstation")
.first()
)
except AttributeError:
# No user
pass
return {"workstation_session": s}
|
...
try:
if not request.user.is_anonymous:
s = (
Session.objects.filter(creator=request.user)
.exclude(status__in=[Session.QUEUED, Session.STOPPED])
.order_by("-created")
.select_related("workstation_image__workstation")
.first()
)
except AttributeError:
# No user
pass
...
|
6ad77e5a9cdbe63ca706bd7c7d3aebb7a34e4cc5
|
mopidy/__init__.py
|
mopidy/__init__.py
|
from __future__ import absolute_import, print_function, unicode_literals
import platform
import sys
import warnings
compatible_py2 = (2, 7) <= sys.version_info < (3,)
compatible_py3 = (3, 7) <= sys.version_info
if not (compatible_py2 or compatible_py3):
sys.exit(
'ERROR: Mopidy requires Python 2.7 or >=3.7, but found %s.' %
platform.python_version())
warnings.filterwarnings('ignore', 'could not open display')
__version__ = '3.0.0a2'
|
from __future__ import absolute_import, print_function, unicode_literals
import platform
import sys
import warnings
if not sys.version_info >= (3, 7):
sys.exit(
'ERROR: Mopidy requires Python >= 3.7, but found %s.' %
platform.python_version())
warnings.filterwarnings('ignore', 'could not open display')
__version__ = '3.0.0a2'
|
Exit if imported on Python 2
|
Exit if imported on Python 2
|
Python
|
apache-2.0
|
kingosticks/mopidy,adamcik/mopidy,jcass77/mopidy,jodal/mopidy,mopidy/mopidy,kingosticks/mopidy,mopidy/mopidy,adamcik/mopidy,jcass77/mopidy,kingosticks/mopidy,jodal/mopidy,jodal/mopidy,mopidy/mopidy,jcass77/mopidy,adamcik/mopidy
|
from __future__ import absolute_import, print_function, unicode_literals
import platform
import sys
import warnings
+ if not sys.version_info >= (3, 7):
- compatible_py2 = (2, 7) <= sys.version_info < (3,)
- compatible_py3 = (3, 7) <= sys.version_info
-
- if not (compatible_py2 or compatible_py3):
sys.exit(
- 'ERROR: Mopidy requires Python 2.7 or >=3.7, but found %s.' %
+ 'ERROR: Mopidy requires Python >= 3.7, but found %s.' %
platform.python_version())
warnings.filterwarnings('ignore', 'could not open display')
__version__ = '3.0.0a2'
|
Exit if imported on Python 2
|
## Code Before:
from __future__ import absolute_import, print_function, unicode_literals
import platform
import sys
import warnings
compatible_py2 = (2, 7) <= sys.version_info < (3,)
compatible_py3 = (3, 7) <= sys.version_info
if not (compatible_py2 or compatible_py3):
sys.exit(
'ERROR: Mopidy requires Python 2.7 or >=3.7, but found %s.' %
platform.python_version())
warnings.filterwarnings('ignore', 'could not open display')
__version__ = '3.0.0a2'
## Instruction:
Exit if imported on Python 2
## Code After:
from __future__ import absolute_import, print_function, unicode_literals
import platform
import sys
import warnings
if not sys.version_info >= (3, 7):
sys.exit(
'ERROR: Mopidy requires Python >= 3.7, but found %s.' %
platform.python_version())
warnings.filterwarnings('ignore', 'could not open display')
__version__ = '3.0.0a2'
|
// ... existing code ...
if not sys.version_info >= (3, 7):
sys.exit(
'ERROR: Mopidy requires Python >= 3.7, but found %s.' %
platform.python_version())
// ... rest of the code ...
|
09225071761ae059c46393d41180b6c37d1b3edc
|
portal/models/locale.py
|
portal/models/locale.py
|
from .coding import Coding
from .lazy import lazyprop
from ..system_uri import IETF_LANGUAGE_TAG
class LocaleConstants(object):
"""Attributes for built in locales
Additions may be defined in persistence files, base values defined
within for easy access and testing
"""
def __iter__(self):
for attr in dir(self):
if attr.startswith('_'):
continue
yield getattr(self, attr)
@lazyprop
def AmericanEnglish(self):
Coding(
system=IETF_LANGUAGE_TAG, code='en_US',
display='American English').add_if_not_found(True)
@lazyprop
def AustralianEnglish(self):
Coding(
system=IETF_LANGUAGE_TAG, code='en_AU',
display='Australian English').add_if_not_found(True)
|
from .coding import Coding
from .lazy import lazyprop
from ..system_uri import IETF_LANGUAGE_TAG
class LocaleConstants(object):
"""Attributes for built in locales
Additions may be defined in persistence files, base values defined
within for easy access and testing
"""
def __iter__(self):
for attr in dir(self):
if attr.startswith('_'):
continue
yield getattr(self, attr)
@lazyprop
def AmericanEnglish(self):
return Coding(
system=IETF_LANGUAGE_TAG, code='en_US',
display='American English').add_if_not_found(True)
@lazyprop
def AustralianEnglish(self):
return Coding(
system=IETF_LANGUAGE_TAG, code='en_AU',
display='Australian English').add_if_not_found(True)
|
Correct coding error - need to return coding from property function or it'll cache None.
|
Correct coding error - need to return coding from property function or it'll cache None.
|
Python
|
bsd-3-clause
|
uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal
|
from .coding import Coding
from .lazy import lazyprop
from ..system_uri import IETF_LANGUAGE_TAG
class LocaleConstants(object):
"""Attributes for built in locales
Additions may be defined in persistence files, base values defined
within for easy access and testing
"""
-
def __iter__(self):
for attr in dir(self):
if attr.startswith('_'):
continue
yield getattr(self, attr)
@lazyprop
def AmericanEnglish(self):
- Coding(
+ return Coding(
system=IETF_LANGUAGE_TAG, code='en_US',
display='American English').add_if_not_found(True)
@lazyprop
def AustralianEnglish(self):
- Coding(
+ return Coding(
system=IETF_LANGUAGE_TAG, code='en_AU',
display='Australian English').add_if_not_found(True)
|
Correct coding error - need to return coding from property function or it'll cache None.
|
## Code Before:
from .coding import Coding
from .lazy import lazyprop
from ..system_uri import IETF_LANGUAGE_TAG
class LocaleConstants(object):
"""Attributes for built in locales
Additions may be defined in persistence files, base values defined
within for easy access and testing
"""
def __iter__(self):
for attr in dir(self):
if attr.startswith('_'):
continue
yield getattr(self, attr)
@lazyprop
def AmericanEnglish(self):
Coding(
system=IETF_LANGUAGE_TAG, code='en_US',
display='American English').add_if_not_found(True)
@lazyprop
def AustralianEnglish(self):
Coding(
system=IETF_LANGUAGE_TAG, code='en_AU',
display='Australian English').add_if_not_found(True)
## Instruction:
Correct coding error - need to return coding from property function or it'll cache None.
## Code After:
from .coding import Coding
from .lazy import lazyprop
from ..system_uri import IETF_LANGUAGE_TAG
class LocaleConstants(object):
"""Attributes for built in locales
Additions may be defined in persistence files, base values defined
within for easy access and testing
"""
def __iter__(self):
for attr in dir(self):
if attr.startswith('_'):
continue
yield getattr(self, attr)
@lazyprop
def AmericanEnglish(self):
return Coding(
system=IETF_LANGUAGE_TAG, code='en_US',
display='American English').add_if_not_found(True)
@lazyprop
def AustralianEnglish(self):
return Coding(
system=IETF_LANGUAGE_TAG, code='en_AU',
display='Australian English').add_if_not_found(True)
|
// ... existing code ...
"""
def __iter__(self):
// ... modified code ...
def AmericanEnglish(self):
return Coding(
system=IETF_LANGUAGE_TAG, code='en_US',
...
def AustralianEnglish(self):
return Coding(
system=IETF_LANGUAGE_TAG, code='en_AU',
// ... rest of the code ...
|
c4dae009a376f5ce4f707595c860e6d92f9953ea
|
web/webViews/dockletrequest.py
|
web/webViews/dockletrequest.py
|
import requests
from flask import abort, session
from webViews.log import logger
endpoint = "http://0.0.0.0:9000"
class dockletRequest():
@classmethod
def post(self, url = '/', data = {}):
#try:
data = dict(data)
data['token'] = session['token']
logger.info ("Docklet Request: user = %s data = %s, url = %s"%(session['username'], data, url))
result = requests.post(endpoint + url, data = data).json()
if (result.get('success', None) == "false" and (result.get('reason', None) == "Unauthorized Action" or result.get('Unauthorized', None) == 'True')):
abort(401)
logger.info ("Docklet Response: user = %s result = %s, url = %s"%(session['username'], result, url))
return result
#except:
#abort(500)
@classmethod
def unauthorizedpost(self, url = '/', data = None):
logger.info("Docklet Unauthorized Request: data = %s, url = %s" % (data, url))
result = requests.post(endpoint + url, data = data).json()
logger.info("Docklet Unauthorized Response: result = %s, url = %s"%(result, url))
return result
|
import requests
from flask import abort, session
from webViews.log import logger
endpoint = "http://0.0.0.0:9000"
class dockletRequest():
@classmethod
def post(self, url = '/', data = {}):
#try:
data = dict(data)
data['token'] = session['token']
logger.info ("Docklet Request: user = %s data = %s, url = %s"%(session['username'], data, url))
result = requests.post(endpoint + url, data = data).json()
if (result.get('success', None) == "false" and (result.get('reason', None) == "Unauthorized Action" or result.get('Unauthorized', None) == 'True')):
abort(401)
logger.info ("Docklet Response: user = %s result = %s, url = %s"%(session['username'], result, url))
return result
#except:
#abort(500)
@classmethod
def unauthorizedpost(self, url = '/', data = None):
data = dict(data)
data_log = {'user': data.get('user', 'external')}
logger.info("Docklet Unauthorized Request: data = %s, url = %s" % (data_log, url))
result = requests.post(endpoint + url, data = data).json()
logger.info("Docklet Unauthorized Response: result = %s, url = %s"%(result, url))
return result
|
Fix a bug that will lead to error when external_login() is called
|
Fix a bug that will lead to error when external_login() is called
|
Python
|
bsd-3-clause
|
FirmlyReality/docklet,scorpionis/docklet,caodg/docklet,caodg/docklet,scorpionis/docklet,caodg/docklet,FirmlyReality/docklet,caodg/docklet,FirmlyReality/docklet,FirmlyReality/docklet
|
import requests
from flask import abort, session
from webViews.log import logger
endpoint = "http://0.0.0.0:9000"
class dockletRequest():
@classmethod
def post(self, url = '/', data = {}):
#try:
data = dict(data)
data['token'] = session['token']
logger.info ("Docklet Request: user = %s data = %s, url = %s"%(session['username'], data, url))
result = requests.post(endpoint + url, data = data).json()
if (result.get('success', None) == "false" and (result.get('reason', None) == "Unauthorized Action" or result.get('Unauthorized', None) == 'True')):
abort(401)
logger.info ("Docklet Response: user = %s result = %s, url = %s"%(session['username'], result, url))
return result
#except:
#abort(500)
@classmethod
def unauthorizedpost(self, url = '/', data = None):
+ data = dict(data)
+ data_log = {'user': data.get('user', 'external')}
- logger.info("Docklet Unauthorized Request: data = %s, url = %s" % (data, url))
+ logger.info("Docklet Unauthorized Request: data = %s, url = %s" % (data_log, url))
result = requests.post(endpoint + url, data = data).json()
logger.info("Docklet Unauthorized Response: result = %s, url = %s"%(result, url))
return result
|
Fix a bug that will lead to error when external_login() is called
|
## Code Before:
import requests
from flask import abort, session
from webViews.log import logger
endpoint = "http://0.0.0.0:9000"
class dockletRequest():
@classmethod
def post(self, url = '/', data = {}):
#try:
data = dict(data)
data['token'] = session['token']
logger.info ("Docklet Request: user = %s data = %s, url = %s"%(session['username'], data, url))
result = requests.post(endpoint + url, data = data).json()
if (result.get('success', None) == "false" and (result.get('reason', None) == "Unauthorized Action" or result.get('Unauthorized', None) == 'True')):
abort(401)
logger.info ("Docklet Response: user = %s result = %s, url = %s"%(session['username'], result, url))
return result
#except:
#abort(500)
@classmethod
def unauthorizedpost(self, url = '/', data = None):
logger.info("Docklet Unauthorized Request: data = %s, url = %s" % (data, url))
result = requests.post(endpoint + url, data = data).json()
logger.info("Docklet Unauthorized Response: result = %s, url = %s"%(result, url))
return result
## Instruction:
Fix a bug that will lead to error when external_login() is called
## Code After:
import requests
from flask import abort, session
from webViews.log import logger
endpoint = "http://0.0.0.0:9000"
class dockletRequest():
@classmethod
def post(self, url = '/', data = {}):
#try:
data = dict(data)
data['token'] = session['token']
logger.info ("Docklet Request: user = %s data = %s, url = %s"%(session['username'], data, url))
result = requests.post(endpoint + url, data = data).json()
if (result.get('success', None) == "false" and (result.get('reason', None) == "Unauthorized Action" or result.get('Unauthorized', None) == 'True')):
abort(401)
logger.info ("Docklet Response: user = %s result = %s, url = %s"%(session['username'], result, url))
return result
#except:
#abort(500)
@classmethod
def unauthorizedpost(self, url = '/', data = None):
data = dict(data)
data_log = {'user': data.get('user', 'external')}
logger.info("Docklet Unauthorized Request: data = %s, url = %s" % (data_log, url))
result = requests.post(endpoint + url, data = data).json()
logger.info("Docklet Unauthorized Response: result = %s, url = %s"%(result, url))
return result
|
# ... existing code ...
def unauthorizedpost(self, url = '/', data = None):
data = dict(data)
data_log = {'user': data.get('user', 'external')}
logger.info("Docklet Unauthorized Request: data = %s, url = %s" % (data_log, url))
result = requests.post(endpoint + url, data = data).json()
# ... rest of the code ...
|
0749c47bb280230ae5b1e2cda23773d3b10b2491
|
redis_check.py
|
redis_check.py
|
import sys
import redis
import redis.exceptions
host = sys.argv[1]
host = host.strip('\r\n')
port = 6379
timeout = 5
try:
db = redis.StrictRedis(host=host, port=port, socket_timeout=timeout)
i = db.info()
ver = i.get('redis_version')
siz = db.dbsize()
print('[+] {0}:{1} - {2}({3})'.format(host, port, ver, siz))
except redis.exceptions.ResponseError as e:
print('[+] {0}:{1} - {2}'.format(host, port, e))
except redis.exceptions.ConnectionError:
print('[-] {0}:{1} - Connection Error'.format(host, port))
except redis.exceptions.TimeoutError:
print('[-] {0}:{1} - Timeout'.format(host, port))
except redis.exceptions.InvalidResponse:
print('[-] {0}:{1} - Invalid Response'.format(host, port))
|
import sys
import redis
import redis.exceptions
host = sys.argv[1]
host = host.strip('\r\n')
port = 6379
timeout = 5
try:
db = redis.StrictRedis(host=host, port=port, socket_timeout=timeout)
i = db.info()
ver = i.get('redis_version')
siz = db.dbsize()
print('[+] {0}:{1}:{2}'.format(host, ver, siz))
except redis.exceptions.ResponseError as e:
print('[+] {0}::{1}'.format(host, e))
except redis.exceptions.ConnectionError:
print('[-] {0}::Connection Error'.format(host))
except redis.exceptions.TimeoutError:
print('[-] {0}::Timeout'.format(host))
except redis.exceptions.InvalidResponse:
print('[-] {0}::Invalid Response'.format(host))
|
Make output easier to parse with cli tools.
|
Make output easier to parse with cli tools.
|
Python
|
bsd-3-clause
|
averagesecurityguy/research
|
import sys
import redis
import redis.exceptions
host = sys.argv[1]
host = host.strip('\r\n')
port = 6379
timeout = 5
try:
db = redis.StrictRedis(host=host, port=port, socket_timeout=timeout)
i = db.info()
ver = i.get('redis_version')
siz = db.dbsize()
- print('[+] {0}:{1} - {2}({3})'.format(host, port, ver, siz))
+ print('[+] {0}:{1}:{2}'.format(host, ver, siz))
except redis.exceptions.ResponseError as e:
- print('[+] {0}:{1} - {2}'.format(host, port, e))
+ print('[+] {0}::{1}'.format(host, e))
except redis.exceptions.ConnectionError:
- print('[-] {0}:{1} - Connection Error'.format(host, port))
+ print('[-] {0}::Connection Error'.format(host))
except redis.exceptions.TimeoutError:
- print('[-] {0}:{1} - Timeout'.format(host, port))
+ print('[-] {0}::Timeout'.format(host))
except redis.exceptions.InvalidResponse:
- print('[-] {0}:{1} - Invalid Response'.format(host, port))
+ print('[-] {0}::Invalid Response'.format(host))
|
Make output easier to parse with cli tools.
|
## Code Before:
import sys
import redis
import redis.exceptions
host = sys.argv[1]
host = host.strip('\r\n')
port = 6379
timeout = 5
try:
db = redis.StrictRedis(host=host, port=port, socket_timeout=timeout)
i = db.info()
ver = i.get('redis_version')
siz = db.dbsize()
print('[+] {0}:{1} - {2}({3})'.format(host, port, ver, siz))
except redis.exceptions.ResponseError as e:
print('[+] {0}:{1} - {2}'.format(host, port, e))
except redis.exceptions.ConnectionError:
print('[-] {0}:{1} - Connection Error'.format(host, port))
except redis.exceptions.TimeoutError:
print('[-] {0}:{1} - Timeout'.format(host, port))
except redis.exceptions.InvalidResponse:
print('[-] {0}:{1} - Invalid Response'.format(host, port))
## Instruction:
Make output easier to parse with cli tools.
## Code After:
import sys
import redis
import redis.exceptions
host = sys.argv[1]
host = host.strip('\r\n')
port = 6379
timeout = 5
try:
db = redis.StrictRedis(host=host, port=port, socket_timeout=timeout)
i = db.info()
ver = i.get('redis_version')
siz = db.dbsize()
print('[+] {0}:{1}:{2}'.format(host, ver, siz))
except redis.exceptions.ResponseError as e:
print('[+] {0}::{1}'.format(host, e))
except redis.exceptions.ConnectionError:
print('[-] {0}::Connection Error'.format(host))
except redis.exceptions.TimeoutError:
print('[-] {0}::Timeout'.format(host))
except redis.exceptions.InvalidResponse:
print('[-] {0}::Invalid Response'.format(host))
|
# ... existing code ...
print('[+] {0}:{1}:{2}'.format(host, ver, siz))
# ... modified code ...
except redis.exceptions.ResponseError as e:
print('[+] {0}::{1}'.format(host, e))
...
except redis.exceptions.ConnectionError:
print('[-] {0}::Connection Error'.format(host))
...
except redis.exceptions.TimeoutError:
print('[-] {0}::Timeout'.format(host))
...
except redis.exceptions.InvalidResponse:
print('[-] {0}::Invalid Response'.format(host))
# ... rest of the code ...
|
1e8ecd09ce6dc44c4955f8bb2f81aa65232ad9a0
|
multi_schema/management/commands/loaddata.py
|
multi_schema/management/commands/loaddata.py
|
from django.core.management.commands import loaddata
from django.core.management.base import CommandError
from django.db import DatabaseError
from optparse import make_option
from ...models import Schema, template_schema
class Command(loaddata.Command):
option_list = loaddata.Command.option_list + (
make_option('--schema', action='store', dest='schema',
help='Specify which schema to load schema-aware models to',
default='__template__',
),
)
def handle(self, *app_labels, **options):
schema_name = options.get('schema')
if schema_name == '__template__':
# Hmm, we don't want to accidentally write data to this, so
# we should raise an exception if we are going to be
# writing any schema-aware objects.
schema = None
else:
try:
schema = Schema.objects.get(schema=options.get('schema'))
except Schema.DoesNotExist:
raise CommandError('No Schema found named "%s"' % schema_name)
schema.activate()
super(Command, self).handle(*app_labels, **options)
if schema:
schema.deactivate()
|
from django.core.management.commands import loaddata
from django.core.management.base import CommandError
from django.db import DatabaseError
from optparse import make_option
from ...models import Schema, template_schema
class Command(loaddata.Command):
option_list = loaddata.Command.option_list + (
make_option('--schema', action='store', dest='schema',
help='Specify which schema to load schema-aware models to',
default='__template__',
),
)
def handle(self, *app_labels, **options):
schema_name = options.get('schema')
if schema_name == '__template__':
# Hmm, we don't want to accidentally write data to this, so
# we should raise an exception if we are going to be
# writing any schema-aware objects.
schema = None
else:
try:
schema = Schema.objects.get(schema=options.get('schema'))
except Schema.DoesNotExist:
raise CommandError('No Schema found named "%s"' % schema_name)
schema.activate()
super(Command, self).handle(*app_labels, **options)
if schema:
schema.deactivate()
for schema in Schema.objects.all():
schema.create_schema()
|
Fix indenting. Create any schemas that were just loaded.
|
Fix indenting.
Create any schemas that were just loaded.
|
Python
|
bsd-3-clause
|
luzfcb/django-boardinghouse,luzfcb/django-boardinghouse,luzfcb/django-boardinghouse
|
from django.core.management.commands import loaddata
from django.core.management.base import CommandError
from django.db import DatabaseError
from optparse import make_option
from ...models import Schema, template_schema
class Command(loaddata.Command):
option_list = loaddata.Command.option_list + (
make_option('--schema', action='store', dest='schema',
help='Specify which schema to load schema-aware models to',
default='__template__',
),
)
def handle(self, *app_labels, **options):
schema_name = options.get('schema')
if schema_name == '__template__':
# Hmm, we don't want to accidentally write data to this, so
# we should raise an exception if we are going to be
# writing any schema-aware objects.
schema = None
else:
try:
schema = Schema.objects.get(schema=options.get('schema'))
except Schema.DoesNotExist:
raise CommandError('No Schema found named "%s"' % schema_name)
schema.activate()
- super(Command, self).handle(*app_labels, **options)
+ super(Command, self).handle(*app_labels, **options)
if schema:
schema.deactivate()
+
+
+ for schema in Schema.objects.all():
+ schema.create_schema()
|
Fix indenting. Create any schemas that were just loaded.
|
## Code Before:
from django.core.management.commands import loaddata
from django.core.management.base import CommandError
from django.db import DatabaseError
from optparse import make_option
from ...models import Schema, template_schema
class Command(loaddata.Command):
option_list = loaddata.Command.option_list + (
make_option('--schema', action='store', dest='schema',
help='Specify which schema to load schema-aware models to',
default='__template__',
),
)
def handle(self, *app_labels, **options):
schema_name = options.get('schema')
if schema_name == '__template__':
# Hmm, we don't want to accidentally write data to this, so
# we should raise an exception if we are going to be
# writing any schema-aware objects.
schema = None
else:
try:
schema = Schema.objects.get(schema=options.get('schema'))
except Schema.DoesNotExist:
raise CommandError('No Schema found named "%s"' % schema_name)
schema.activate()
super(Command, self).handle(*app_labels, **options)
if schema:
schema.deactivate()
## Instruction:
Fix indenting. Create any schemas that were just loaded.
## Code After:
from django.core.management.commands import loaddata
from django.core.management.base import CommandError
from django.db import DatabaseError
from optparse import make_option
from ...models import Schema, template_schema
class Command(loaddata.Command):
option_list = loaddata.Command.option_list + (
make_option('--schema', action='store', dest='schema',
help='Specify which schema to load schema-aware models to',
default='__template__',
),
)
def handle(self, *app_labels, **options):
schema_name = options.get('schema')
if schema_name == '__template__':
# Hmm, we don't want to accidentally write data to this, so
# we should raise an exception if we are going to be
# writing any schema-aware objects.
schema = None
else:
try:
schema = Schema.objects.get(schema=options.get('schema'))
except Schema.DoesNotExist:
raise CommandError('No Schema found named "%s"' % schema_name)
schema.activate()
super(Command, self).handle(*app_labels, **options)
if schema:
schema.deactivate()
for schema in Schema.objects.all():
schema.create_schema()
|
...
super(Command, self).handle(*app_labels, **options)
...
schema.deactivate()
for schema in Schema.objects.all():
schema.create_schema()
...
|
f80b080f62b450531007f58849019fd18c75c25f
|
stacker/blueprints/rds/postgres.py
|
stacker/blueprints/rds/postgres.py
|
from stacker.blueprints.rds import base
class PostgresMixin(object):
def engine(self):
return "postgres"
def get_engine_versions(self):
return ['9.3.1', '9.3.2', '9.3.3', '9.3.5', '9.3.6', '9.4.1']
def get_db_families(self):
return ["postgres9.3", "postgres9.4"]
class MasterInstance(PostgresMixin, base.MasterInstance):
pass
class ReadReplica(PostgresMixin, base.ReadReplica):
pass
|
from stacker.blueprints.rds import base
class PostgresMixin(object):
def engine(self):
return "postgres"
def get_engine_versions(self):
return ['9.3.1', '9.3.2', '9.3.3', '9.3.5', '9.3.6', '9.3.9',
'9.3.10', '9.4.1', '9.4.4', '9.4.5']
def get_db_families(self):
return ["postgres9.3", "postgres9.4"]
class MasterInstance(PostgresMixin, base.MasterInstance):
pass
class ReadReplica(PostgresMixin, base.ReadReplica):
pass
|
Add new versions of Postgres
|
Add new versions of Postgres
|
Python
|
bsd-2-clause
|
mhahn/stacker,remind101/stacker,mhahn/stacker,remind101/stacker
|
from stacker.blueprints.rds import base
class PostgresMixin(object):
def engine(self):
return "postgres"
def get_engine_versions(self):
- return ['9.3.1', '9.3.2', '9.3.3', '9.3.5', '9.3.6', '9.4.1']
+ return ['9.3.1', '9.3.2', '9.3.3', '9.3.5', '9.3.6', '9.3.9',
+ '9.3.10', '9.4.1', '9.4.4', '9.4.5']
def get_db_families(self):
return ["postgres9.3", "postgres9.4"]
class MasterInstance(PostgresMixin, base.MasterInstance):
pass
class ReadReplica(PostgresMixin, base.ReadReplica):
pass
|
Add new versions of Postgres
|
## Code Before:
from stacker.blueprints.rds import base
class PostgresMixin(object):
def engine(self):
return "postgres"
def get_engine_versions(self):
return ['9.3.1', '9.3.2', '9.3.3', '9.3.5', '9.3.6', '9.4.1']
def get_db_families(self):
return ["postgres9.3", "postgres9.4"]
class MasterInstance(PostgresMixin, base.MasterInstance):
pass
class ReadReplica(PostgresMixin, base.ReadReplica):
pass
## Instruction:
Add new versions of Postgres
## Code After:
from stacker.blueprints.rds import base
class PostgresMixin(object):
def engine(self):
return "postgres"
def get_engine_versions(self):
return ['9.3.1', '9.3.2', '9.3.3', '9.3.5', '9.3.6', '9.3.9',
'9.3.10', '9.4.1', '9.4.4', '9.4.5']
def get_db_families(self):
return ["postgres9.3", "postgres9.4"]
class MasterInstance(PostgresMixin, base.MasterInstance):
pass
class ReadReplica(PostgresMixin, base.ReadReplica):
pass
|
...
def get_engine_versions(self):
return ['9.3.1', '9.3.2', '9.3.3', '9.3.5', '9.3.6', '9.3.9',
'9.3.10', '9.4.1', '9.4.4', '9.4.5']
...
|
ba983dea1e20409d403a86d62c300ea3d257b58a
|
parserscripts/phage.py
|
parserscripts/phage.py
|
import re
class Phage:
supported_databases = {
# European Nucleotide Archive phage database
"ENA": r"^gi\|[0-9]+\|ref\|([^\|]+)\|\ ([^,]+)[^$]*$",
# National Center for Biotechnology Information phage database
"NCBI": r"^ENA\|([^\|]+)\|[^\ ]+\ ([^,]+)[^$]*$",
# Actinobacteriophage Database
"AD": r"^([^\ ]+)\ [^,]*,[^,]*,\ Cluster\ ([^$]+)$"
}
def __init__(self, raw_text, phage_finder):
self.raw = raw_text.strip()
self.refseq = None
self.name = None
self.db = None
self._parse_phage(raw_text, phage_finder)
def _parse_phage(self, raw_text, phage_finder):
for db, regex in Phage.supported_databases.items():
match = re.search(regex, raw_text)
if match is not None:
if db is not "AD":
self.name = match.group(2)
self.refseq = match.group(1)
else:
short_name = match.group(1)
cluster = match.group(2)
self.name = "Mycobacteriophage " + short_name
self.refseq = phage_finder.find_by_phage(short_name,
cluster)
self.db = db
|
import re
class Phage:
SUPPORTED_DATABASES = {
# European Nucleotide Archive phage database
"ENA": r"^gi\|[0-9]+\|ref\|([^\|]+)\|\ ([^,]+)[^$]*$",
# National Center for Biotechnology Information phage database
"NCBI": r"^ENA\|([^\|]+)\|[^\ ]+\ ([^,]+)[^$]*$",
# Actinobacteriophage Database
"AD": r"^([^\ ]+)\ [^,]*,[^,]*,\ Cluster\ ([^$]+)$"
}
def __init__(self, raw_text, phage_finder):
self.raw = raw_text.strip()
self.refseq = None
self.name = None
self.db = None
self._parse_phage(raw_text, phage_finder)
def _parse_phage(self, raw_text, phage_finder):
for db, regex in Phage.SUPPORTED_DATABASES.items():
match = re.search(regex, raw_text)
if match is not None:
if db is not "AD":
self.name = match.group(2)
self.refseq = match.group(1)
else:
short_name = match.group(1)
cluster = match.group(2)
self.name = "Mycobacteriophage " + short_name
self.refseq = phage_finder.find_by_phage(short_name,
cluster)
self.db = db
|
Rename to follow constant naming conventions
|
Rename to follow constant naming conventions
|
Python
|
mit
|
mbonsma/phageParser,mbonsma/phageParser,phageParser/phageParser,mbonsma/phageParser,phageParser/phageParser,goyalsid/phageParser,goyalsid/phageParser,phageParser/phageParser,phageParser/phageParser,mbonsma/phageParser,goyalsid/phageParser
|
import re
class Phage:
- supported_databases = {
+ SUPPORTED_DATABASES = {
# European Nucleotide Archive phage database
"ENA": r"^gi\|[0-9]+\|ref\|([^\|]+)\|\ ([^,]+)[^$]*$",
# National Center for Biotechnology Information phage database
"NCBI": r"^ENA\|([^\|]+)\|[^\ ]+\ ([^,]+)[^$]*$",
# Actinobacteriophage Database
"AD": r"^([^\ ]+)\ [^,]*,[^,]*,\ Cluster\ ([^$]+)$"
}
def __init__(self, raw_text, phage_finder):
self.raw = raw_text.strip()
self.refseq = None
self.name = None
self.db = None
self._parse_phage(raw_text, phage_finder)
def _parse_phage(self, raw_text, phage_finder):
- for db, regex in Phage.supported_databases.items():
+ for db, regex in Phage.SUPPORTED_DATABASES.items():
match = re.search(regex, raw_text)
if match is not None:
if db is not "AD":
self.name = match.group(2)
self.refseq = match.group(1)
else:
short_name = match.group(1)
cluster = match.group(2)
self.name = "Mycobacteriophage " + short_name
self.refseq = phage_finder.find_by_phage(short_name,
cluster)
self.db = db
|
Rename to follow constant naming conventions
|
## Code Before:
import re
class Phage:
supported_databases = {
# European Nucleotide Archive phage database
"ENA": r"^gi\|[0-9]+\|ref\|([^\|]+)\|\ ([^,]+)[^$]*$",
# National Center for Biotechnology Information phage database
"NCBI": r"^ENA\|([^\|]+)\|[^\ ]+\ ([^,]+)[^$]*$",
# Actinobacteriophage Database
"AD": r"^([^\ ]+)\ [^,]*,[^,]*,\ Cluster\ ([^$]+)$"
}
def __init__(self, raw_text, phage_finder):
self.raw = raw_text.strip()
self.refseq = None
self.name = None
self.db = None
self._parse_phage(raw_text, phage_finder)
def _parse_phage(self, raw_text, phage_finder):
for db, regex in Phage.supported_databases.items():
match = re.search(regex, raw_text)
if match is not None:
if db is not "AD":
self.name = match.group(2)
self.refseq = match.group(1)
else:
short_name = match.group(1)
cluster = match.group(2)
self.name = "Mycobacteriophage " + short_name
self.refseq = phage_finder.find_by_phage(short_name,
cluster)
self.db = db
## Instruction:
Rename to follow constant naming conventions
## Code After:
import re
class Phage:
SUPPORTED_DATABASES = {
# European Nucleotide Archive phage database
"ENA": r"^gi\|[0-9]+\|ref\|([^\|]+)\|\ ([^,]+)[^$]*$",
# National Center for Biotechnology Information phage database
"NCBI": r"^ENA\|([^\|]+)\|[^\ ]+\ ([^,]+)[^$]*$",
# Actinobacteriophage Database
"AD": r"^([^\ ]+)\ [^,]*,[^,]*,\ Cluster\ ([^$]+)$"
}
def __init__(self, raw_text, phage_finder):
self.raw = raw_text.strip()
self.refseq = None
self.name = None
self.db = None
self._parse_phage(raw_text, phage_finder)
def _parse_phage(self, raw_text, phage_finder):
for db, regex in Phage.SUPPORTED_DATABASES.items():
match = re.search(regex, raw_text)
if match is not None:
if db is not "AD":
self.name = match.group(2)
self.refseq = match.group(1)
else:
short_name = match.group(1)
cluster = match.group(2)
self.name = "Mycobacteriophage " + short_name
self.refseq = phage_finder.find_by_phage(short_name,
cluster)
self.db = db
|
// ... existing code ...
class Phage:
SUPPORTED_DATABASES = {
# European Nucleotide Archive phage database
// ... modified code ...
def _parse_phage(self, raw_text, phage_finder):
for db, regex in Phage.SUPPORTED_DATABASES.items():
match = re.search(regex, raw_text)
// ... rest of the code ...
|
fd48211548c8c2d5daec0994155ddb7e8d226882
|
tests/test_anki_sync.py
|
tests/test_anki_sync.py
|
import pytest
import os
import rememberberry
from rememberscript import RememberMachine, FileStorage
from rememberberry.testing import tmp_data_path, assert_replies, get_isolated_story
@pytest.mark.asyncio
@tmp_data_path('/tmp/data/', delete=True)
async def test_anki_account():
storage = FileStorage()
m, storage = get_isolated_story('login_anki', storage)
await assert_replies(m.reply(''), 'What is your Anki username?')
await assert_replies(m.reply('ajshdkajhsdkajshd'), 'And now the password')
await assert_replies(m.reply('jkdhskjhgdksjhg'),
'Authentication with ankiweb failed, try again?',
'What is your Anki username?')
await assert_replies(m.reply('[email protected]'), 'And now the password')
await assert_replies(m.reply('ankitest'),
'Authentication worked, now I\'ll try to sync your account',
'Syncing anki database',
'Syncing media files (this may take a while)',
'Syncing done',
'Great, you\'re all synced up!',
'enter init')
|
import pytest
import os
import rememberberry
from rememberscript import RememberMachine, FileStorage
from rememberberry.testing import tmp_data_path, assert_replies, get_isolated_story
@pytest.mark.asyncio
@tmp_data_path('/tmp/data/', delete=True)
async def test_anki_account():
storage = FileStorage()
storage['username'] = 'alice'
m, storage = get_isolated_story('login_anki', storage)
await assert_replies(m.reply(''), 'What is your Anki username?')
await assert_replies(m.reply('ajshdkajhsdkajshd'), 'And now the password')
await assert_replies(m.reply('jkdhskjhgdksjhg'),
'Authentication with ankiweb failed, try again?',
'What is your Anki username?')
await assert_replies(m.reply('[email protected]'), 'And now the password')
await assert_replies(m.reply('ankitest'),
'Authentication worked, now I\'ll try to sync your account',
'Syncing anki database',
'Syncing media files (this may take a while)',
'Syncing done',
'Great, you\'re all synced up!',
'enter init')
|
Fix missing username in test
|
Fix missing username in test
|
Python
|
agpl-3.0
|
rememberberry/rememberberry-server,rememberberry/rememberberry-server
|
import pytest
import os
import rememberberry
from rememberscript import RememberMachine, FileStorage
from rememberberry.testing import tmp_data_path, assert_replies, get_isolated_story
@pytest.mark.asyncio
@tmp_data_path('/tmp/data/', delete=True)
async def test_anki_account():
storage = FileStorage()
+ storage['username'] = 'alice'
m, storage = get_isolated_story('login_anki', storage)
await assert_replies(m.reply(''), 'What is your Anki username?')
await assert_replies(m.reply('ajshdkajhsdkajshd'), 'And now the password')
await assert_replies(m.reply('jkdhskjhgdksjhg'),
'Authentication with ankiweb failed, try again?',
'What is your Anki username?')
await assert_replies(m.reply('[email protected]'), 'And now the password')
await assert_replies(m.reply('ankitest'),
'Authentication worked, now I\'ll try to sync your account',
'Syncing anki database',
'Syncing media files (this may take a while)',
'Syncing done',
'Great, you\'re all synced up!',
'enter init')
|
Fix missing username in test
|
## Code Before:
import pytest
import os
import rememberberry
from rememberscript import RememberMachine, FileStorage
from rememberberry.testing import tmp_data_path, assert_replies, get_isolated_story
@pytest.mark.asyncio
@tmp_data_path('/tmp/data/', delete=True)
async def test_anki_account():
storage = FileStorage()
m, storage = get_isolated_story('login_anki', storage)
await assert_replies(m.reply(''), 'What is your Anki username?')
await assert_replies(m.reply('ajshdkajhsdkajshd'), 'And now the password')
await assert_replies(m.reply('jkdhskjhgdksjhg'),
'Authentication with ankiweb failed, try again?',
'What is your Anki username?')
await assert_replies(m.reply('[email protected]'), 'And now the password')
await assert_replies(m.reply('ankitest'),
'Authentication worked, now I\'ll try to sync your account',
'Syncing anki database',
'Syncing media files (this may take a while)',
'Syncing done',
'Great, you\'re all synced up!',
'enter init')
## Instruction:
Fix missing username in test
## Code After:
import pytest
import os
import rememberberry
from rememberscript import RememberMachine, FileStorage
from rememberberry.testing import tmp_data_path, assert_replies, get_isolated_story
@pytest.mark.asyncio
@tmp_data_path('/tmp/data/', delete=True)
async def test_anki_account():
storage = FileStorage()
storage['username'] = 'alice'
m, storage = get_isolated_story('login_anki', storage)
await assert_replies(m.reply(''), 'What is your Anki username?')
await assert_replies(m.reply('ajshdkajhsdkajshd'), 'And now the password')
await assert_replies(m.reply('jkdhskjhgdksjhg'),
'Authentication with ankiweb failed, try again?',
'What is your Anki username?')
await assert_replies(m.reply('[email protected]'), 'And now the password')
await assert_replies(m.reply('ankitest'),
'Authentication worked, now I\'ll try to sync your account',
'Syncing anki database',
'Syncing media files (this may take a while)',
'Syncing done',
'Great, you\'re all synced up!',
'enter init')
|
# ... existing code ...
storage = FileStorage()
storage['username'] = 'alice'
m, storage = get_isolated_story('login_anki', storage)
# ... rest of the code ...
|
94b37ba0abacbff53da342574b61c87810f6a5d4
|
bulletin/tools/plugins/forms/job.py
|
bulletin/tools/plugins/forms/job.py
|
from datetimewidget.widgets import DateTimeWidget
from django.forms import ModelForm
from form_utils.widgets import ImageWidget
from ..models import Job
job_field_labels = {
'image': 'Image (10Mb Limit)',
'url': 'URL'
}
job_help_texts = {
'url': 'Provide a full url, e.g., "http://www.example.com/page.html"'
}
class JobSubmitForm(ModelForm):
class Meta:
model = Job
fields = ['title',
'url',
'organization',
'image']
labels = {
}
labels = job_field_labels
help_texts = job_help_texts
class JobUpdateForm(ModelForm):
class Meta:
model = Job
fields = ['title',
'url',
'organization',
'image',
'approved',
'include_in_newsletter',
'pub_date']
widgets = {
'pub_date': DateTimeWidget(usel10n=True, bootstrap_version=3),
'image': ImageWidget(),
}
labels = job_field_labels
help_texts = job_help_texts
|
from datetimewidget.widgets import DateTimeWidget
from django.forms import ModelForm
from form_utils.widgets import ImageWidget
from ..models import Job
job_field_labels = {
'image': 'Image (10Mb Limit)',
'url': 'URL'
}
job_help_texts = {
'url': 'Provide a full url, e.g., "http://www.example.com/page.html"'
}
field_widgets = {
'image': ImageWidget(attrs={'required': 'required'})
}
class JobSubmitForm(ModelForm):
class Meta:
model = Job
fields = ['title',
'url',
'organization',
'image']
labels = job_field_labels
help_texts = job_help_texts
widgets = field_widgets
class JobUpdateForm(ModelForm):
class Meta:
model = Job
fields = ['title',
'url',
'organization',
'image',
'approved',
'include_in_newsletter',
'pub_date']
widgets = {
'pub_date': DateTimeWidget(usel10n=True, bootstrap_version=3),
'image': ImageWidget(),
}
labels = job_field_labels
help_texts = job_help_texts
|
Make image required on Job submit form.
|
Make image required on Job submit form.
|
Python
|
mit
|
AASHE/django-bulletin,AASHE/django-bulletin,AASHE/django-bulletin
|
from datetimewidget.widgets import DateTimeWidget
from django.forms import ModelForm
from form_utils.widgets import ImageWidget
from ..models import Job
job_field_labels = {
'image': 'Image (10Mb Limit)',
'url': 'URL'
}
job_help_texts = {
'url': 'Provide a full url, e.g., "http://www.example.com/page.html"'
}
+ field_widgets = {
+ 'image': ImageWidget(attrs={'required': 'required'})
+ }
+
class JobSubmitForm(ModelForm):
class Meta:
model = Job
fields = ['title',
'url',
'organization',
'image']
- labels = {
-
- }
labels = job_field_labels
help_texts = job_help_texts
+ widgets = field_widgets
class JobUpdateForm(ModelForm):
class Meta:
model = Job
fields = ['title',
'url',
'organization',
'image',
'approved',
'include_in_newsletter',
'pub_date']
widgets = {
'pub_date': DateTimeWidget(usel10n=True, bootstrap_version=3),
'image': ImageWidget(),
}
labels = job_field_labels
help_texts = job_help_texts
|
Make image required on Job submit form.
|
## Code Before:
from datetimewidget.widgets import DateTimeWidget
from django.forms import ModelForm
from form_utils.widgets import ImageWidget
from ..models import Job
job_field_labels = {
'image': 'Image (10Mb Limit)',
'url': 'URL'
}
job_help_texts = {
'url': 'Provide a full url, e.g., "http://www.example.com/page.html"'
}
class JobSubmitForm(ModelForm):
class Meta:
model = Job
fields = ['title',
'url',
'organization',
'image']
labels = {
}
labels = job_field_labels
help_texts = job_help_texts
class JobUpdateForm(ModelForm):
class Meta:
model = Job
fields = ['title',
'url',
'organization',
'image',
'approved',
'include_in_newsletter',
'pub_date']
widgets = {
'pub_date': DateTimeWidget(usel10n=True, bootstrap_version=3),
'image': ImageWidget(),
}
labels = job_field_labels
help_texts = job_help_texts
## Instruction:
Make image required on Job submit form.
## Code After:
from datetimewidget.widgets import DateTimeWidget
from django.forms import ModelForm
from form_utils.widgets import ImageWidget
from ..models import Job
job_field_labels = {
'image': 'Image (10Mb Limit)',
'url': 'URL'
}
job_help_texts = {
'url': 'Provide a full url, e.g., "http://www.example.com/page.html"'
}
field_widgets = {
'image': ImageWidget(attrs={'required': 'required'})
}
class JobSubmitForm(ModelForm):
class Meta:
model = Job
fields = ['title',
'url',
'organization',
'image']
labels = job_field_labels
help_texts = job_help_texts
widgets = field_widgets
class JobUpdateForm(ModelForm):
class Meta:
model = Job
fields = ['title',
'url',
'organization',
'image',
'approved',
'include_in_newsletter',
'pub_date']
widgets = {
'pub_date': DateTimeWidget(usel10n=True, bootstrap_version=3),
'image': ImageWidget(),
}
labels = job_field_labels
help_texts = job_help_texts
|
...
field_widgets = {
'image': ImageWidget(attrs={'required': 'required'})
}
...
'image']
labels = job_field_labels
...
help_texts = job_help_texts
widgets = field_widgets
...
|
9616ba8659aab6b60d95ea7e07699e258fb436e6
|
openprovider/modules/__init__.py
|
openprovider/modules/__init__.py
|
import lxml
E = lxml.objectify.ElementMaker(annotate=False)
from openprovider.modules import customer
from openprovider.modules import domain
from openprovider.modules import extension
from openprovider.modules import financial
from openprovider.modules import nameserver
from openprovider.modules import nsgroup
from openprovider.modules import reseller
from openprovider.modules import ssl
|
import lxml
E = lxml.objectify.ElementMaker(annotate=False)
def OE(element, value, transform=lambda x: x):
"""
Create an Optional Element.
Returns an Element as ElementMaker would, unless value is None. Optionally the value can be
transformed through a function.
>>> OE('elem', None)
None
>>> lxml.etree.tostring(OE('elem', 'value'))
<elem>value</elem>
>>> lxml.etree.tostring(OE('elem', True, int))
<elem>1</elem>
"""
return E(element, transform(value)) if value is not None else None
from openprovider.modules import customer
from openprovider.modules import domain
from openprovider.modules import extension
from openprovider.modules import financial
from openprovider.modules import nameserver
from openprovider.modules import nsgroup
from openprovider.modules import reseller
from openprovider.modules import ssl
|
Implement an Optional Element function
|
Implement an Optional Element function
|
Python
|
mit
|
AntagonistHQ/openprovider.py
|
import lxml
E = lxml.objectify.ElementMaker(annotate=False)
+
+
+ def OE(element, value, transform=lambda x: x):
+ """
+ Create an Optional Element.
+
+ Returns an Element as ElementMaker would, unless value is None. Optionally the value can be
+ transformed through a function.
+
+ >>> OE('elem', None)
+ None
+
+ >>> lxml.etree.tostring(OE('elem', 'value'))
+ <elem>value</elem>
+
+ >>> lxml.etree.tostring(OE('elem', True, int))
+ <elem>1</elem>
+ """
+ return E(element, transform(value)) if value is not None else None
+
from openprovider.modules import customer
from openprovider.modules import domain
from openprovider.modules import extension
from openprovider.modules import financial
from openprovider.modules import nameserver
from openprovider.modules import nsgroup
from openprovider.modules import reseller
from openprovider.modules import ssl
|
Implement an Optional Element function
|
## Code Before:
import lxml
E = lxml.objectify.ElementMaker(annotate=False)
from openprovider.modules import customer
from openprovider.modules import domain
from openprovider.modules import extension
from openprovider.modules import financial
from openprovider.modules import nameserver
from openprovider.modules import nsgroup
from openprovider.modules import reseller
from openprovider.modules import ssl
## Instruction:
Implement an Optional Element function
## Code After:
import lxml
E = lxml.objectify.ElementMaker(annotate=False)
def OE(element, value, transform=lambda x: x):
"""
Create an Optional Element.
Returns an Element as ElementMaker would, unless value is None. Optionally the value can be
transformed through a function.
>>> OE('elem', None)
None
>>> lxml.etree.tostring(OE('elem', 'value'))
<elem>value</elem>
>>> lxml.etree.tostring(OE('elem', True, int))
<elem>1</elem>
"""
return E(element, transform(value)) if value is not None else None
from openprovider.modules import customer
from openprovider.modules import domain
from openprovider.modules import extension
from openprovider.modules import financial
from openprovider.modules import nameserver
from openprovider.modules import nsgroup
from openprovider.modules import reseller
from openprovider.modules import ssl
|
# ... existing code ...
E = lxml.objectify.ElementMaker(annotate=False)
def OE(element, value, transform=lambda x: x):
"""
Create an Optional Element.
Returns an Element as ElementMaker would, unless value is None. Optionally the value can be
transformed through a function.
>>> OE('elem', None)
None
>>> lxml.etree.tostring(OE('elem', 'value'))
<elem>value</elem>
>>> lxml.etree.tostring(OE('elem', True, int))
<elem>1</elem>
"""
return E(element, transform(value)) if value is not None else None
# ... rest of the code ...
|
46972788b2f4c3b3ac79e2d2fb9b8dd6a3834148
|
src/yunohost/utils/error.py
|
src/yunohost/utils/error.py
|
from moulinette.core import MoulinetteError
from moulinette import m18n
class YunohostError(MoulinetteError):
"""Yunohost base exception"""
def __init__(self, key, __raw_msg__=False, *args, **kwargs):
if __raw_msg__:
msg = key
else:
msg = m18n.n(key, *args, **kwargs)
super(YunohostError, self).__init__(msg, __raw_msg__=True)
|
from moulinette.core import MoulinetteError
from moulinette import m18n
class YunohostError(MoulinetteError):
"""
Yunohost base exception
The (only?) main difference with MoulinetteError being that keys
are translated via m18n.n (namespace) instead of m18n.g (global?)
"""
def __init__(self, key, __raw_msg__=False, *args, **kwargs):
if __raw_msg__:
msg = key
else:
msg = m18n.n(key, *args, **kwargs)
super(YunohostError, self).__init__(msg, __raw_msg__=True)
|
Add comment about the motivation behind YunohostError
|
Add comment about the motivation behind YunohostError
|
Python
|
agpl-3.0
|
YunoHost/yunohost,YunoHost/yunohost,YunoHost/moulinette-yunohost,YunoHost/moulinette-yunohost,YunoHost/yunohost,YunoHost/moulinette-yunohost,YunoHost/yunohost,YunoHost/moulinette-yunohost,YunoHost/moulinette-yunohost
|
from moulinette.core import MoulinetteError
from moulinette import m18n
class YunohostError(MoulinetteError):
+ """
- """Yunohost base exception"""
+ Yunohost base exception
+
+ The (only?) main difference with MoulinetteError being that keys
+ are translated via m18n.n (namespace) instead of m18n.g (global?)
+ """
def __init__(self, key, __raw_msg__=False, *args, **kwargs):
if __raw_msg__:
msg = key
else:
msg = m18n.n(key, *args, **kwargs)
super(YunohostError, self).__init__(msg, __raw_msg__=True)
|
Add comment about the motivation behind YunohostError
|
## Code Before:
from moulinette.core import MoulinetteError
from moulinette import m18n
class YunohostError(MoulinetteError):
"""Yunohost base exception"""
def __init__(self, key, __raw_msg__=False, *args, **kwargs):
if __raw_msg__:
msg = key
else:
msg = m18n.n(key, *args, **kwargs)
super(YunohostError, self).__init__(msg, __raw_msg__=True)
## Instruction:
Add comment about the motivation behind YunohostError
## Code After:
from moulinette.core import MoulinetteError
from moulinette import m18n
class YunohostError(MoulinetteError):
"""
Yunohost base exception
The (only?) main difference with MoulinetteError being that keys
are translated via m18n.n (namespace) instead of m18n.g (global?)
"""
def __init__(self, key, __raw_msg__=False, *args, **kwargs):
if __raw_msg__:
msg = key
else:
msg = m18n.n(key, *args, **kwargs)
super(YunohostError, self).__init__(msg, __raw_msg__=True)
|
# ... existing code ...
class YunohostError(MoulinetteError):
"""
Yunohost base exception
The (only?) main difference with MoulinetteError being that keys
are translated via m18n.n (namespace) instead of m18n.g (global?)
"""
def __init__(self, key, __raw_msg__=False, *args, **kwargs):
# ... rest of the code ...
|
c4e791ea6175fbefce0ef0671051936a27fc9684
|
tests/vec_test.py
|
tests/vec_test.py
|
"""Tests for vectors."""
from sympy import sympify
from drudge import Vec
def test_vecs_has_basic_properties():
"""Tests the basic properties of vector instances."""
base = Vec('v')
v_ab = Vec('v', indices=['a', 'b'])
v_ab_1 = base['a', 'b']
v_ab_2 = (base['a'])['b']
indices_ref = (sympify('a'), sympify('b'))
hash_ref = hash(v_ab)
str_ref = 'v[a, b]'
repr_ref = "Vec('v', (a, b))"
for i in [v_ab, v_ab_1, v_ab_2]:
assert i.label == base.label
assert i.base == base
assert i.indices == indices_ref
assert hash(i) == hash_ref
assert i == v_ab
assert str(i) == str_ref
assert repr(i) == repr_ref
|
"""Tests for vectors."""
import pytest
from sympy import sympify
from drudge import Vec
def test_vecs_has_basic_properties():
"""Tests the basic properties of vector instances."""
base = Vec('v')
v_ab = Vec('v', indices=['a', 'b'])
v_ab_1 = base['a', 'b']
v_ab_2 = (base['a'])['b']
indices_ref = (sympify('a'), sympify('b'))
hash_ref = hash(v_ab)
str_ref = 'v[a, b]'
repr_ref = "Vec('v', (a, b))"
for i in [v_ab, v_ab_1, v_ab_2]:
assert i.label == base.label
assert i.base == base
assert i.indices == indices_ref
assert hash(i) == hash_ref
assert i == v_ab
assert str(i) == str_ref
assert repr(i) == repr_ref
# Vectors should not be sympified.
with pytest.raises(TypeError):
sympify(i)
|
Add tests for disabled sympification of vectors
|
Add tests for disabled sympification of vectors
|
Python
|
mit
|
tschijnmo/drudge,tschijnmo/drudge,tschijnmo/drudge
|
"""Tests for vectors."""
+
+ import pytest
from sympy import sympify
from drudge import Vec
def test_vecs_has_basic_properties():
"""Tests the basic properties of vector instances."""
base = Vec('v')
v_ab = Vec('v', indices=['a', 'b'])
v_ab_1 = base['a', 'b']
v_ab_2 = (base['a'])['b']
indices_ref = (sympify('a'), sympify('b'))
hash_ref = hash(v_ab)
str_ref = 'v[a, b]'
repr_ref = "Vec('v', (a, b))"
for i in [v_ab, v_ab_1, v_ab_2]:
assert i.label == base.label
assert i.base == base
assert i.indices == indices_ref
assert hash(i) == hash_ref
assert i == v_ab
assert str(i) == str_ref
assert repr(i) == repr_ref
+ # Vectors should not be sympified.
+ with pytest.raises(TypeError):
+ sympify(i)
+
|
Add tests for disabled sympification of vectors
|
## Code Before:
"""Tests for vectors."""
from sympy import sympify
from drudge import Vec
def test_vecs_has_basic_properties():
"""Tests the basic properties of vector instances."""
base = Vec('v')
v_ab = Vec('v', indices=['a', 'b'])
v_ab_1 = base['a', 'b']
v_ab_2 = (base['a'])['b']
indices_ref = (sympify('a'), sympify('b'))
hash_ref = hash(v_ab)
str_ref = 'v[a, b]'
repr_ref = "Vec('v', (a, b))"
for i in [v_ab, v_ab_1, v_ab_2]:
assert i.label == base.label
assert i.base == base
assert i.indices == indices_ref
assert hash(i) == hash_ref
assert i == v_ab
assert str(i) == str_ref
assert repr(i) == repr_ref
## Instruction:
Add tests for disabled sympification of vectors
## Code After:
"""Tests for vectors."""
import pytest
from sympy import sympify
from drudge import Vec
def test_vecs_has_basic_properties():
"""Tests the basic properties of vector instances."""
base = Vec('v')
v_ab = Vec('v', indices=['a', 'b'])
v_ab_1 = base['a', 'b']
v_ab_2 = (base['a'])['b']
indices_ref = (sympify('a'), sympify('b'))
hash_ref = hash(v_ab)
str_ref = 'v[a, b]'
repr_ref = "Vec('v', (a, b))"
for i in [v_ab, v_ab_1, v_ab_2]:
assert i.label == base.label
assert i.base == base
assert i.indices == indices_ref
assert hash(i) == hash_ref
assert i == v_ab
assert str(i) == str_ref
assert repr(i) == repr_ref
# Vectors should not be sympified.
with pytest.raises(TypeError):
sympify(i)
|
// ... existing code ...
"""Tests for vectors."""
import pytest
// ... modified code ...
assert repr(i) == repr_ref
# Vectors should not be sympified.
with pytest.raises(TypeError):
sympify(i)
// ... rest of the code ...
|
a91a2d3468cb3bfc7fdc686327770365321ef102
|
qa_app/challenges.py
|
qa_app/challenges.py
|
from flask import Blueprint, render_template
from flask_login import login_required
challenges = Blueprint('challenges', __name__)
@challenges.route('/challenges', methods=['GET'])
@login_required
def challenges_view():
return render_template('challenges.html', page="Challenges")
|
import requests
from flask import Blueprint, render_template, jsonify
from flask_login import login_required
challenges = Blueprint('challenges', __name__)
@challenges.route('/challenges', methods=['GET'])
@login_required
def challenges_view():
return render_template('challenges.html', page="Challenges")
@challenges.route('/exercises', methods=['GET'])
@login_required
def api_exercises():
exercises = requests.get("http://localhost:8000/").json()
result = {
"exercises":
[]
}
for current in exercises['exercises']:
result['exercises'].append({
"name": current.get('name', 'unknown'),
"category": current.get('answers')[0].split(".")[1],
"solved": 0,
"cost": 100
})
return jsonify(result)
|
Implement demo 'exercises' api method.
|
Implement demo 'exercises' api method.
|
Python
|
apache-2.0
|
molecul/qa_app_flask,molecul/qa_app_flask,molecul/qa_app_flask
|
+ import requests
+
- from flask import Blueprint, render_template
+ from flask import Blueprint, render_template, jsonify
from flask_login import login_required
challenges = Blueprint('challenges', __name__)
@challenges.route('/challenges', methods=['GET'])
@login_required
def challenges_view():
return render_template('challenges.html', page="Challenges")
+
+ @challenges.route('/exercises', methods=['GET'])
+ @login_required
+ def api_exercises():
+ exercises = requests.get("http://localhost:8000/").json()
+ result = {
+ "exercises":
+ []
+ }
+ for current in exercises['exercises']:
+ result['exercises'].append({
+ "name": current.get('name', 'unknown'),
+ "category": current.get('answers')[0].split(".")[1],
+ "solved": 0,
+ "cost": 100
+ })
+ return jsonify(result)
+
|
Implement demo 'exercises' api method.
|
## Code Before:
from flask import Blueprint, render_template
from flask_login import login_required
challenges = Blueprint('challenges', __name__)
@challenges.route('/challenges', methods=['GET'])
@login_required
def challenges_view():
return render_template('challenges.html', page="Challenges")
## Instruction:
Implement demo 'exercises' api method.
## Code After:
import requests
from flask import Blueprint, render_template, jsonify
from flask_login import login_required
challenges = Blueprint('challenges', __name__)
@challenges.route('/challenges', methods=['GET'])
@login_required
def challenges_view():
return render_template('challenges.html', page="Challenges")
@challenges.route('/exercises', methods=['GET'])
@login_required
def api_exercises():
exercises = requests.get("http://localhost:8000/").json()
result = {
"exercises":
[]
}
for current in exercises['exercises']:
result['exercises'].append({
"name": current.get('name', 'unknown'),
"category": current.get('answers')[0].split(".")[1],
"solved": 0,
"cost": 100
})
return jsonify(result)
|
# ... existing code ...
import requests
from flask import Blueprint, render_template, jsonify
from flask_login import login_required
# ... modified code ...
return render_template('challenges.html', page="Challenges")
@challenges.route('/exercises', methods=['GET'])
@login_required
def api_exercises():
exercises = requests.get("http://localhost:8000/").json()
result = {
"exercises":
[]
}
for current in exercises['exercises']:
result['exercises'].append({
"name": current.get('name', 'unknown'),
"category": current.get('answers')[0].split(".")[1],
"solved": 0,
"cost": 100
})
return jsonify(result)
# ... rest of the code ...
|
d07bf029b7ba9b5ef1f494d119a2eca004c1818a
|
tests/basics/list_slice_3arg.py
|
tests/basics/list_slice_3arg.py
|
x = list(range(10))
print(x[::-1])
print(x[::2])
print(x[::-2])
|
x = list(range(10))
print(x[::-1])
print(x[::2])
print(x[::-2])
x = list(range(9))
print(x[::-1])
print(x[::2])
print(x[::-2])
|
Add small testcase for 3-arg slices.
|
tests: Add small testcase for 3-arg slices.
|
Python
|
mit
|
neilh10/micropython,danicampora/micropython,tuc-osg/micropython,noahchense/micropython,ahotam/micropython,alex-march/micropython,SungEun-Steve-Kim/test-mp,suda/micropython,SungEun-Steve-Kim/test-mp,noahwilliamsson/micropython,neilh10/micropython,aethaniel/micropython,noahwilliamsson/micropython,chrisdearman/micropython,redbear/micropython,AriZuu/micropython,praemdonck/micropython,ceramos/micropython,firstval/micropython,rubencabrera/micropython,selste/micropython,pozetroninc/micropython,galenhz/micropython,omtinez/micropython,dmazzella/micropython,turbinenreiter/micropython,vriera/micropython,toolmacher/micropython,kostyll/micropython,hiway/micropython,SungEun-Steve-Kim/test-mp,ernesto-g/micropython,xyb/micropython,ernesto-g/micropython,dxxb/micropython,kostyll/micropython,vitiral/micropython,PappaPeppar/micropython,dmazzella/micropython,TDAbboud/micropython,matthewelse/micropython,lbattraw/micropython,xyb/micropython,stonegithubs/micropython,orionrobots/micropython,kerneltask/micropython,ChuckM/micropython,selste/micropython,omtinez/micropython,rubencabrera/micropython,xuxiaoxin/micropython,alex-march/micropython,xhat/micropython,jlillest/micropython,kostyll/micropython,cloudformdesign/micropython,infinnovation/micropython,blazewicz/micropython,deshipu/micropython,hosaka/micropython,feilongfl/micropython,henriknelson/micropython,adafruit/micropython,Peetz0r/micropython-esp32,mgyenik/micropython,hiway/micropython,Vogtinator/micropython,alex-robbins/micropython,mianos/micropython,martinribelotta/micropython,jmarcelino/pycom-micropython,pfalcon/micropython,pramasoul/micropython,HenrikSolver/micropython,skybird6672/micropython,suda/micropython,kostyll/micropython,pfalcon/micropython,puuu/micropython,tralamazza/micropython,blazewicz/micropython,ruffy91/micropython,Timmenem/micropython,heisewangluo/micropython,Timmenem/micropython,xuxiaoxin/micropython,jmarcelino/pycom-micropython,pfalcon/micropython,oopy/micropython,puuu/micropython,adafruit/circuitpython,tdautc19841202/micropython,torwag/micropython,paul-xxx/micropython,KISSMonX/micropython,suda/micropython,PappaPeppar/micropython,skybird6672/micropython,orionrobots/micropython,dxxb/micropython,skybird6672/micropython,lbattraw/micropython,alex-robbins/micropython,xuxiaoxin/micropython,drrk/micropython,cloudformdesign/micropython,slzatz/micropython,ruffy91/micropython,danicampora/micropython,heisewangluo/micropython,SungEun-Steve-Kim/test-mp,emfcamp/micropython,ericsnowcurrently/micropython,hosaka/micropython,ahotam/micropython,MrSurly/micropython-esp32,misterdanb/micropython,xuxiaoxin/micropython,lowRISC/micropython,xyb/micropython,deshipu/micropython,cwyark/micropython,jimkmc/micropython,trezor/micropython,supergis/micropython,kostyll/micropython,deshipu/micropython,jmarcelino/pycom-micropython,mgyenik/micropython,AriZuu/micropython,praemdonck/micropython,ganshun666/micropython,rubencabrera/micropython,trezor/micropython,vitiral/micropython,danicampora/micropython,EcmaXp/micropython,ceramos/micropython,TDAbboud/micropython,micropython/micropython-esp32,orionrobots/micropython,lbattraw/micropython,supergis/micropython,galenhz/micropython,redbear/micropython,toolmacher/micropython,ceramos/micropython,cnoviello/micropython,paul-xxx/micropython,dhylands/micropython,EcmaXp/micropython,tralamazza/micropython,Vogtinator/micropython,rubencabrera/micropython,noahwilliamsson/micropython,bvernoux/micropython,hosaka/micropython,mhoffma/micropython,selste/micropython,heisewangluo/micropython,xhat/micropython,warner83/micropython,methoxid/micropystat,vitiral/micropython,supergis/micropython,praemdonck/micropython,utopiaprince/micropython,noahchense/micropython,tdautc19841202/micropython,oopy/micropython,pozetroninc/micropython,torwag/micropython,deshipu/micropython,HenrikSolver/micropython,feilongfl/micropython,ganshun666/micropython,swegener/micropython,torwag/micropython,aethaniel/micropython,EcmaXp/micropython,oopy/micropython,swegener/micropython,xhat/micropython,tdautc19841202/micropython,heisewangluo/micropython,tdautc19841202/micropython,deshipu/micropython,ryannathans/micropython,paul-xxx/micropython,danicampora/micropython,toolmacher/micropython,ryannathans/micropython,blazewicz/micropython,galenhz/micropython,xhat/micropython,hosaka/micropython,noahwilliamsson/micropython,mgyenik/micropython,toolmacher/micropython,mpalomer/micropython,xyb/micropython,ChuckM/micropython,Timmenem/micropython,supergis/micropython,ernesto-g/micropython,misterdanb/micropython,MrSurly/micropython-esp32,ryannathans/micropython,swegener/micropython,KISSMonX/micropython,vriera/micropython,alex-robbins/micropython,matthewelse/micropython,danicampora/micropython,mgyenik/micropython,KISSMonX/micropython,suda/micropython,tuc-osg/micropython,warner83/micropython,blazewicz/micropython,slzatz/micropython,mhoffma/micropython,AriZuu/micropython,dxxb/micropython,Vogtinator/micropython,drrk/micropython,tuc-osg/micropython,tuc-osg/micropython,cnoviello/micropython,tobbad/micropython,jimkmc/micropython,blmorris/micropython,alex-march/micropython,adamkh/micropython,heisewangluo/micropython,adamkh/micropython,cloudformdesign/micropython,pramasoul/micropython,firstval/micropython,stonegithubs/micropython,torwag/micropython,ChuckM/micropython,Peetz0r/micropython-esp32,ganshun666/micropython,MrSurly/micropython,AriZuu/micropython,methoxid/micropystat,swegener/micropython,adafruit/circuitpython,skybird6672/micropython,blazewicz/micropython,ceramos/micropython,Timmenem/micropython,neilh10/micropython,mhoffma/micropython,paul-xxx/micropython,emfcamp/micropython,EcmaXp/micropython,neilh10/micropython,lbattraw/micropython,Peetz0r/micropython-esp32,infinnovation/micropython,galenhz/micropython,kerneltask/micropython,cnoviello/micropython,feilongfl/micropython,toolmacher/micropython,emfcamp/micropython,EcmaXp/micropython,praemdonck/micropython,alex-robbins/micropython,matthewelse/micropython,utopiaprince/micropython,vriera/micropython,adafruit/micropython,micropython/micropython-esp32,blmorris/micropython,stonegithubs/micropython,ericsnowcurrently/micropython,lowRISC/micropython,emfcamp/micropython,tdautc19841202/micropython,dhylands/micropython,bvernoux/micropython,dinau/micropython,oopy/micropython,PappaPeppar/micropython,MrSurly/micropython,alex-march/micropython,warner83/micropython,aethaniel/micropython,TDAbboud/micropython,Timmenem/micropython,aethaniel/micropython,SungEun-Steve-Kim/test-mp,dxxb/micropython,mianos/micropython,ernesto-g/micropython,jlillest/micropython,trezor/micropython,tobbad/micropython,redbear/micropython,cnoviello/micropython,xuxiaoxin/micropython,HenrikSolver/micropython,redbear/micropython,omtinez/micropython,hiway/micropython,SHA2017-badge/micropython-esp32,ganshun666/micropython,blmorris/micropython,dinau/micropython,emfcamp/micropython,cnoviello/micropython,ryannathans/micropython,kerneltask/micropython,redbear/micropython,infinnovation/micropython,adafruit/micropython,henriknelson/micropython,ericsnowcurrently/micropython,paul-xxx/micropython,kerneltask/micropython,misterdanb/micropython,jlillest/micropython,pramasoul/micropython,vriera/micropython,noahwilliamsson/micropython,ceramos/micropython,dinau/micropython,dmazzella/micropython,swegener/micropython,ernesto-g/micropython,mgyenik/micropython,mpalomer/micropython,ahotam/micropython,skybird6672/micropython,noahchense/micropython,ahotam/micropython,pfalcon/micropython,mhoffma/micropython,blmorris/micropython,xyb/micropython,micropython/micropython-esp32,dinau/micropython,noahchense/micropython,lbattraw/micropython,puuu/micropython,jmarcelino/pycom-micropython,misterdanb/micropython,turbinenreiter/micropython,matthewelse/micropython,martinribelotta/micropython,tobbad/micropython,warner83/micropython,adamkh/micropython,tobbad/micropython,alex-march/micropython,bvernoux/micropython,slzatz/micropython,ruffy91/micropython,adafruit/micropython,chrisdearman/micropython,SHA2017-badge/micropython-esp32,praemdonck/micropython,mianos/micropython,mpalomer/micropython,MrSurly/micropython-esp32,HenrikSolver/micropython,feilongfl/micropython,turbinenreiter/micropython,torwag/micropython,jlillest/micropython,drrk/micropython,henriknelson/micropython,alex-robbins/micropython,firstval/micropython,AriZuu/micropython,SHA2017-badge/micropython-esp32,cwyark/micropython,puuu/micropython,orionrobots/micropython,pramasoul/micropython,martinribelotta/micropython,feilongfl/micropython,adafruit/circuitpython,TDAbboud/micropython,mhoffma/micropython,hosaka/micropython,MrSurly/micropython-esp32,TDAbboud/micropython,puuu/micropython,firstval/micropython,misterdanb/micropython,Peetz0r/micropython-esp32,utopiaprince/micropython,pozetroninc/micropython,lowRISC/micropython,infinnovation/micropython,mianos/micropython,trezor/micropython,drrk/micropython,dinau/micropython,neilh10/micropython,adafruit/circuitpython,PappaPeppar/micropython,micropython/micropython-esp32,HenrikSolver/micropython,adafruit/circuitpython,mianos/micropython,methoxid/micropystat,adafruit/micropython,jimkmc/micropython,chrisdearman/micropython,Vogtinator/micropython,cwyark/micropython,ericsnowcurrently/micropython,utopiaprince/micropython,chrisdearman/micropython,MrSurly/micropython,slzatz/micropython,henriknelson/micropython,aethaniel/micropython,blmorris/micropython,MrSurly/micropython,matthewelse/micropython,cwyark/micropython,dhylands/micropython,kerneltask/micropython,vitiral/micropython,selste/micropython,ahotam/micropython,vitiral/micropython,suda/micropython,orionrobots/micropython,ChuckM/micropython,dxxb/micropython,cloudformdesign/micropython,mpalomer/micropython,adamkh/micropython,adafruit/circuitpython,chrisdearman/micropython,supergis/micropython,jlillest/micropython,stonegithubs/micropython,selste/micropython,trezor/micropython,ruffy91/micropython,jimkmc/micropython,xhat/micropython,mpalomer/micropython,pfalcon/micropython,cwyark/micropython,tobbad/micropython,micropython/micropython-esp32,MrSurly/micropython,omtinez/micropython,pozetroninc/micropython,ruffy91/micropython,infinnovation/micropython,SHA2017-badge/micropython-esp32,omtinez/micropython,dhylands/micropython,oopy/micropython,adamkh/micropython,martinribelotta/micropython,ChuckM/micropython,bvernoux/micropython,henriknelson/micropython,Peetz0r/micropython-esp32,turbinenreiter/micropython,matthewelse/micropython,KISSMonX/micropython,methoxid/micropystat,dhylands/micropython,dmazzella/micropython,PappaPeppar/micropython,jmarcelino/pycom-micropython,firstval/micropython,hiway/micropython,ryannathans/micropython,lowRISC/micropython,tralamazza/micropython,lowRISC/micropython,vriera/micropython,turbinenreiter/micropython,warner83/micropython,utopiaprince/micropython,pozetroninc/micropython,drrk/micropython,bvernoux/micropython,martinribelotta/micropython,ganshun666/micropython,rubencabrera/micropython,MrSurly/micropython-esp32,galenhz/micropython,noahchense/micropython,cloudformdesign/micropython,tuc-osg/micropython,SHA2017-badge/micropython-esp32,KISSMonX/micropython,methoxid/micropystat,pramasoul/micropython,Vogtinator/micropython,hiway/micropython,ericsnowcurrently/micropython,slzatz/micropython,stonegithubs/micropython,tralamazza/micropython,jimkmc/micropython
|
x = list(range(10))
print(x[::-1])
print(x[::2])
print(x[::-2])
+ x = list(range(9))
+ print(x[::-1])
+ print(x[::2])
+ print(x[::-2])
+
|
Add small testcase for 3-arg slices.
|
## Code Before:
x = list(range(10))
print(x[::-1])
print(x[::2])
print(x[::-2])
## Instruction:
Add small testcase for 3-arg slices.
## Code After:
x = list(range(10))
print(x[::-1])
print(x[::2])
print(x[::-2])
x = list(range(9))
print(x[::-1])
print(x[::2])
print(x[::-2])
|
# ... existing code ...
print(x[::-2])
x = list(range(9))
print(x[::-1])
print(x[::2])
print(x[::-2])
# ... rest of the code ...
|
762ba71537cebac83970fbfb19725054b127191b
|
__init__.py
|
__init__.py
|
from .blendergltf import *
|
if 'loaded' in locals():
import imp
imp.reload(blendergltf)
from .blendergltf import *
else:
loaded = True
from .blendergltf import *
|
Improve reloading of the module
|
Improve reloading of the module
|
Python
|
apache-2.0
|
Kupoman/blendergltf,lukesanantonio/blendergltf
|
+ if 'loaded' in locals():
+ import imp
+ imp.reload(blendergltf)
- from .blendergltf import *
+ from .blendergltf import *
+ else:
+ loaded = True
+ from .blendergltf import *
|
Improve reloading of the module
|
## Code Before:
from .blendergltf import *
## Instruction:
Improve reloading of the module
## Code After:
if 'loaded' in locals():
import imp
imp.reload(blendergltf)
from .blendergltf import *
else:
loaded = True
from .blendergltf import *
|
...
if 'loaded' in locals():
import imp
imp.reload(blendergltf)
from .blendergltf import *
else:
loaded = True
from .blendergltf import *
...
|
13ec50a7e2187edb03174ed4a9dbf8767f4c6ad4
|
version.py
|
version.py
|
major = 0
minor=0
patch=0
branch="dev"
timestamp=1376412824.91
|
major = 0
minor=0
patch=8
branch="master"
timestamp=1376412892.53
|
Tag commit for v0.0.8-master generated by gitmake.py
|
Tag commit for v0.0.8-master generated by gitmake.py
|
Python
|
mit
|
ryansturmer/gitmake
|
major = 0
minor=0
- patch=0
+ patch=8
- branch="dev"
+ branch="master"
- timestamp=1376412824.91
+ timestamp=1376412892.53
|
Tag commit for v0.0.8-master generated by gitmake.py
|
## Code Before:
major = 0
minor=0
patch=0
branch="dev"
timestamp=1376412824.91
## Instruction:
Tag commit for v0.0.8-master generated by gitmake.py
## Code After:
major = 0
minor=0
patch=8
branch="master"
timestamp=1376412892.53
|
// ... existing code ...
minor=0
patch=8
branch="master"
timestamp=1376412892.53
// ... rest of the code ...
|
b0b1be44c64ed48c15f9e796b90a21e7e4597df8
|
jsrn/encoding.py
|
jsrn/encoding.py
|
import json
import registration
import resources
class JSRNEncoder(json.JSONEncoder):
"""
Encoder for JSRN resources.
"""
def default(self, o):
if isinstance(o, resources.Resource):
state = o.__getstate__()
state['$'] = o._meta.resource_name
return state
return super(JSRNEncoder, self)
def build_object_graph(obj, resource_name=None):
if isinstance(obj, dict):
if not resource_name:
resource_name = obj.pop("$", None)
if resource_name:
resource_type = registration.get_resource(resource_name)
if resource_type:
new_resource = resource_type()
new_resource.__setstate__(obj)
return new_resource
else:
raise TypeError("Unknown resource: %s" % resource_name)
if isinstance(obj, list):
return [build_object_graph(o, resource_name) for o in obj]
return obj
|
import json
import resources
class JSRNEncoder(json.JSONEncoder):
"""
Encoder for JSRN resources.
"""
def default(self, o):
if isinstance(o, resources.Resource):
obj = {f.name: f.to_json(f.value_from_object(o)) for f in o._meta.fields}
obj[resources.RESOURCE_TYPE_FIELD] = o._meta.resource_name
return obj
return super(JSRNEncoder, self)
def build_object_graph(obj, resource_name=None):
"""
From the decoded JSON structure, generate an object graph.
:raises ValidationError: During building of the object graph and issues discovered are raised as a ValidationError.
"""
if isinstance(obj, dict):
return resources.create_resource_from_dict(obj, resource_name)
if isinstance(obj, list):
return [build_object_graph(o, resource_name) for o in obj]
return obj
|
Add extra documentation, remove use of __setstate__ and __getstate__ methods.
|
Add extra documentation, remove use of __setstate__ and __getstate__ methods.
|
Python
|
bsd-3-clause
|
timsavage/jsrn,timsavage/jsrn
|
import json
- import registration
import resources
class JSRNEncoder(json.JSONEncoder):
"""
Encoder for JSRN resources.
"""
def default(self, o):
if isinstance(o, resources.Resource):
- state = o.__getstate__()
- state['$'] = o._meta.resource_name
+ obj = {f.name: f.to_json(f.value_from_object(o)) for f in o._meta.fields}
+ obj[resources.RESOURCE_TYPE_FIELD] = o._meta.resource_name
- return state
+ return obj
return super(JSRNEncoder, self)
def build_object_graph(obj, resource_name=None):
+ """
+ From the decoded JSON structure, generate an object graph.
+
+ :raises ValidationError: During building of the object graph and issues discovered are raised as a ValidationError.
+ """
+
if isinstance(obj, dict):
+ return resources.create_resource_from_dict(obj, resource_name)
- if not resource_name:
- resource_name = obj.pop("$", None)
- if resource_name:
- resource_type = registration.get_resource(resource_name)
- if resource_type:
- new_resource = resource_type()
- new_resource.__setstate__(obj)
- return new_resource
- else:
- raise TypeError("Unknown resource: %s" % resource_name)
if isinstance(obj, list):
return [build_object_graph(o, resource_name) for o in obj]
return obj
|
Add extra documentation, remove use of __setstate__ and __getstate__ methods.
|
## Code Before:
import json
import registration
import resources
class JSRNEncoder(json.JSONEncoder):
"""
Encoder for JSRN resources.
"""
def default(self, o):
if isinstance(o, resources.Resource):
state = o.__getstate__()
state['$'] = o._meta.resource_name
return state
return super(JSRNEncoder, self)
def build_object_graph(obj, resource_name=None):
if isinstance(obj, dict):
if not resource_name:
resource_name = obj.pop("$", None)
if resource_name:
resource_type = registration.get_resource(resource_name)
if resource_type:
new_resource = resource_type()
new_resource.__setstate__(obj)
return new_resource
else:
raise TypeError("Unknown resource: %s" % resource_name)
if isinstance(obj, list):
return [build_object_graph(o, resource_name) for o in obj]
return obj
## Instruction:
Add extra documentation, remove use of __setstate__ and __getstate__ methods.
## Code After:
import json
import resources
class JSRNEncoder(json.JSONEncoder):
"""
Encoder for JSRN resources.
"""
def default(self, o):
if isinstance(o, resources.Resource):
obj = {f.name: f.to_json(f.value_from_object(o)) for f in o._meta.fields}
obj[resources.RESOURCE_TYPE_FIELD] = o._meta.resource_name
return obj
return super(JSRNEncoder, self)
def build_object_graph(obj, resource_name=None):
"""
From the decoded JSON structure, generate an object graph.
:raises ValidationError: During building of the object graph and issues discovered are raised as a ValidationError.
"""
if isinstance(obj, dict):
return resources.create_resource_from_dict(obj, resource_name)
if isinstance(obj, list):
return [build_object_graph(o, resource_name) for o in obj]
return obj
|
// ... existing code ...
import json
import resources
// ... modified code ...
if isinstance(o, resources.Resource):
obj = {f.name: f.to_json(f.value_from_object(o)) for f in o._meta.fields}
obj[resources.RESOURCE_TYPE_FIELD] = o._meta.resource_name
return obj
return super(JSRNEncoder, self)
...
def build_object_graph(obj, resource_name=None):
"""
From the decoded JSON structure, generate an object graph.
:raises ValidationError: During building of the object graph and issues discovered are raised as a ValidationError.
"""
if isinstance(obj, dict):
return resources.create_resource_from_dict(obj, resource_name)
// ... rest of the code ...
|
3c25f2802f70a16869e93fb301428c31452c00f0
|
plyer/platforms/macosx/uniqueid.py
|
plyer/platforms/macosx/uniqueid.py
|
from subprocess import Popen, PIPE
from plyer.facades import UniqueID
from plyer.utils import whereis_exe
from os import environ
class OSXUniqueID(UniqueID):
def _get_uid(self):
old_lang = environ.get('LANG')
environ['LANG'] = 'C'
ioreg_process = Popen(["ioreg", "-l"], stdout=PIPE)
grep_process = Popen(["grep", "IOPlatformSerialNumber"],
stdin=ioreg_process.stdout, stdout=PIPE)
ioreg_process.stdout.close()
output = grep_process.communicate()[0]
environ['LANG'] = old_lang
if output:
return output.split()[3][1:-1]
else:
return None
def instance():
import sys
if whereis_exe('ioreg'):
return OSXUniqueID()
sys.stderr.write("ioreg not found.")
return UniqueID()
|
from subprocess import Popen, PIPE
from plyer.facades import UniqueID
from plyer.utils import whereis_exe
from os import environ
class OSXUniqueID(UniqueID):
def _get_uid(self):
old_lang = environ.get('LANG')
environ['LANG'] = 'C'
ioreg_process = Popen(["ioreg", "-l"], stdout=PIPE)
grep_process = Popen(["grep", "IOPlatformSerialNumber"],
stdin=ioreg_process.stdout, stdout=PIPE)
ioreg_process.stdout.close()
output = grep_process.communicate()[0]
if old_lang is None:
environ.pop('LANG')
else:
environ['LANG'] = old_lang
if output:
return output.split()[3][1:-1]
else:
return None
def instance():
import sys
if whereis_exe('ioreg'):
return OSXUniqueID()
sys.stderr.write("ioreg not found.")
return UniqueID()
|
Fix TypeError if `LANG` is not set in on osx
|
Fix TypeError if `LANG` is not set in on osx
In macosx.uniqueid, `$LANG` is retrieved with `old_lang = environ.get('LANG')`. This means that if `LANG` is not set, `old_lang` will be none. When plyer later tries to restore the original value of lang, `putenv` will complain that we're not supplying a string. I've corrected this by popping the inserted `LANG` value if `old_lang` is none.
|
Python
|
mit
|
kivy/plyer,kived/plyer,KeyWeeUsr/plyer,johnbolia/plyer,johnbolia/plyer,kivy/plyer,KeyWeeUsr/plyer,kived/plyer,KeyWeeUsr/plyer,kivy/plyer
|
from subprocess import Popen, PIPE
from plyer.facades import UniqueID
from plyer.utils import whereis_exe
from os import environ
class OSXUniqueID(UniqueID):
def _get_uid(self):
old_lang = environ.get('LANG')
environ['LANG'] = 'C'
ioreg_process = Popen(["ioreg", "-l"], stdout=PIPE)
grep_process = Popen(["grep", "IOPlatformSerialNumber"],
stdin=ioreg_process.stdout, stdout=PIPE)
ioreg_process.stdout.close()
output = grep_process.communicate()[0]
+ if old_lang is None:
+ environ.pop('LANG')
+ else:
- environ['LANG'] = old_lang
+ environ['LANG'] = old_lang
+
if output:
return output.split()[3][1:-1]
else:
return None
def instance():
import sys
if whereis_exe('ioreg'):
return OSXUniqueID()
sys.stderr.write("ioreg not found.")
return UniqueID()
|
Fix TypeError if `LANG` is not set in on osx
|
## Code Before:
from subprocess import Popen, PIPE
from plyer.facades import UniqueID
from plyer.utils import whereis_exe
from os import environ
class OSXUniqueID(UniqueID):
def _get_uid(self):
old_lang = environ.get('LANG')
environ['LANG'] = 'C'
ioreg_process = Popen(["ioreg", "-l"], stdout=PIPE)
grep_process = Popen(["grep", "IOPlatformSerialNumber"],
stdin=ioreg_process.stdout, stdout=PIPE)
ioreg_process.stdout.close()
output = grep_process.communicate()[0]
environ['LANG'] = old_lang
if output:
return output.split()[3][1:-1]
else:
return None
def instance():
import sys
if whereis_exe('ioreg'):
return OSXUniqueID()
sys.stderr.write("ioreg not found.")
return UniqueID()
## Instruction:
Fix TypeError if `LANG` is not set in on osx
## Code After:
from subprocess import Popen, PIPE
from plyer.facades import UniqueID
from plyer.utils import whereis_exe
from os import environ
class OSXUniqueID(UniqueID):
def _get_uid(self):
old_lang = environ.get('LANG')
environ['LANG'] = 'C'
ioreg_process = Popen(["ioreg", "-l"], stdout=PIPE)
grep_process = Popen(["grep", "IOPlatformSerialNumber"],
stdin=ioreg_process.stdout, stdout=PIPE)
ioreg_process.stdout.close()
output = grep_process.communicate()[0]
if old_lang is None:
environ.pop('LANG')
else:
environ['LANG'] = old_lang
if output:
return output.split()[3][1:-1]
else:
return None
def instance():
import sys
if whereis_exe('ioreg'):
return OSXUniqueID()
sys.stderr.write("ioreg not found.")
return UniqueID()
|
// ... existing code ...
if old_lang is None:
environ.pop('LANG')
else:
environ['LANG'] = old_lang
// ... rest of the code ...
|
121bcbfc873ce45667ec67bc6f22387b43f3aa52
|
openfisca_web_ui/uuidhelpers.py
|
openfisca_web_ui/uuidhelpers.py
|
"""Helpers to handle uuid"""
import uuid
def generate_uuid():
return unicode(uuid.uuid4()).replace('-', '')
|
"""Helpers to handle uuid"""
import uuid
def generate_uuid():
return unicode(uuid.uuid4().hex)
|
Use uuid.hex instead of reinventing it.
|
Use uuid.hex instead of reinventing it.
|
Python
|
agpl-3.0
|
openfisca/openfisca-web-ui,openfisca/openfisca-web-ui,openfisca/openfisca-web-ui
|
"""Helpers to handle uuid"""
import uuid
def generate_uuid():
- return unicode(uuid.uuid4()).replace('-', '')
+ return unicode(uuid.uuid4().hex)
|
Use uuid.hex instead of reinventing it.
|
## Code Before:
"""Helpers to handle uuid"""
import uuid
def generate_uuid():
return unicode(uuid.uuid4()).replace('-', '')
## Instruction:
Use uuid.hex instead of reinventing it.
## Code After:
"""Helpers to handle uuid"""
import uuid
def generate_uuid():
return unicode(uuid.uuid4().hex)
|
// ... existing code ...
def generate_uuid():
return unicode(uuid.uuid4().hex)
// ... rest of the code ...
|
a69bd95c2e732f22aac555884904bbe7d9d0a1b9
|
src/dynamic_fixtures/management/commands/load_dynamic_fixtures.py
|
src/dynamic_fixtures/management/commands/load_dynamic_fixtures.py
|
from django.core.management.base import BaseCommand
from dynamic_fixtures.fixtures.runner import LoadFixtureRunner
class Command(BaseCommand):
help_text = 'Load fixtures while keeping dependencies in mind.'
args = '[app_label] [fixture_name]'
def handle(self, *args, **options):
runner = LoadFixtureRunner()
nodes = None
if len(args) == 1:
nodes = runner.get_app_nodes(app_label=args[0])
elif len(args) == 2:
nodes = runner.get_fixture_node(app_label=args[0],
fixture_prefix=args[1])
fixture_count = runner.load_fixtures(
nodes=nodes,
progress_callback=self.progress_callback
)
self.stdout.write('Loaded {} fixtures'.format(fixture_count))
def progress_callback(self, action, node):
if action == 'load_start':
self.stdout.write('Loading fixture {}.{}...'.format(*node),
ending='')
self.stdout.flush()
elif action == 'load_success':
self.stdout.write('SUCCESS')
|
from django.core.management.base import BaseCommand
from dynamic_fixtures.fixtures.runner import LoadFixtureRunner
class Command(BaseCommand):
help_text = 'Load fixtures while keeping dependencies in mind.'
args = '[app_label] [fixture_name]'
def add_arguments(self, parser):
parser.add_argument('app_label', type=str)
parser.add_argument('fixture_name', default=None, nargs='?', type=str)
def handle(self, *args, **options):
runner = LoadFixtureRunner()
nodes = None
if len(args) == 0:
if options['fixture_name'] is None:
args = (options['app_label'], )
else:
args = (options['app_label'], options['fixture_name'])
if len(args) == 1:
nodes = runner.get_app_nodes(app_label=args[0])
elif len(args) == 2:
nodes = runner.get_fixture_node(app_label=args[0],
fixture_prefix=args[1])
fixture_count = runner.load_fixtures(
nodes=nodes,
progress_callback=self.progress_callback
)
self.stdout.write('Loaded {} fixtures'.format(fixture_count))
def progress_callback(self, action, node):
if action == 'load_start':
self.stdout.write('Loading fixture {}.{}...'.format(*node),
ending='')
self.stdout.flush()
elif action == 'load_success':
self.stdout.write('SUCCESS')
|
Fix Command compatibility with Django>= 1.8
|
Fix Command compatibility with Django>= 1.8
|
Python
|
mit
|
Peter-Slump/django-factory-boy-fixtures,Peter-Slump/django-dynamic-fixtures
|
from django.core.management.base import BaseCommand
from dynamic_fixtures.fixtures.runner import LoadFixtureRunner
class Command(BaseCommand):
help_text = 'Load fixtures while keeping dependencies in mind.'
args = '[app_label] [fixture_name]'
+ def add_arguments(self, parser):
+ parser.add_argument('app_label', type=str)
+ parser.add_argument('fixture_name', default=None, nargs='?', type=str)
+
def handle(self, *args, **options):
runner = LoadFixtureRunner()
nodes = None
+
+ if len(args) == 0:
+ if options['fixture_name'] is None:
+ args = (options['app_label'], )
+ else:
+ args = (options['app_label'], options['fixture_name'])
+
if len(args) == 1:
nodes = runner.get_app_nodes(app_label=args[0])
elif len(args) == 2:
nodes = runner.get_fixture_node(app_label=args[0],
fixture_prefix=args[1])
fixture_count = runner.load_fixtures(
nodes=nodes,
progress_callback=self.progress_callback
)
self.stdout.write('Loaded {} fixtures'.format(fixture_count))
def progress_callback(self, action, node):
if action == 'load_start':
self.stdout.write('Loading fixture {}.{}...'.format(*node),
ending='')
self.stdout.flush()
elif action == 'load_success':
self.stdout.write('SUCCESS')
|
Fix Command compatibility with Django>= 1.8
|
## Code Before:
from django.core.management.base import BaseCommand
from dynamic_fixtures.fixtures.runner import LoadFixtureRunner
class Command(BaseCommand):
help_text = 'Load fixtures while keeping dependencies in mind.'
args = '[app_label] [fixture_name]'
def handle(self, *args, **options):
runner = LoadFixtureRunner()
nodes = None
if len(args) == 1:
nodes = runner.get_app_nodes(app_label=args[0])
elif len(args) == 2:
nodes = runner.get_fixture_node(app_label=args[0],
fixture_prefix=args[1])
fixture_count = runner.load_fixtures(
nodes=nodes,
progress_callback=self.progress_callback
)
self.stdout.write('Loaded {} fixtures'.format(fixture_count))
def progress_callback(self, action, node):
if action == 'load_start':
self.stdout.write('Loading fixture {}.{}...'.format(*node),
ending='')
self.stdout.flush()
elif action == 'load_success':
self.stdout.write('SUCCESS')
## Instruction:
Fix Command compatibility with Django>= 1.8
## Code After:
from django.core.management.base import BaseCommand
from dynamic_fixtures.fixtures.runner import LoadFixtureRunner
class Command(BaseCommand):
help_text = 'Load fixtures while keeping dependencies in mind.'
args = '[app_label] [fixture_name]'
def add_arguments(self, parser):
parser.add_argument('app_label', type=str)
parser.add_argument('fixture_name', default=None, nargs='?', type=str)
def handle(self, *args, **options):
runner = LoadFixtureRunner()
nodes = None
if len(args) == 0:
if options['fixture_name'] is None:
args = (options['app_label'], )
else:
args = (options['app_label'], options['fixture_name'])
if len(args) == 1:
nodes = runner.get_app_nodes(app_label=args[0])
elif len(args) == 2:
nodes = runner.get_fixture_node(app_label=args[0],
fixture_prefix=args[1])
fixture_count = runner.load_fixtures(
nodes=nodes,
progress_callback=self.progress_callback
)
self.stdout.write('Loaded {} fixtures'.format(fixture_count))
def progress_callback(self, action, node):
if action == 'load_start':
self.stdout.write('Loading fixture {}.{}...'.format(*node),
ending='')
self.stdout.flush()
elif action == 'load_success':
self.stdout.write('SUCCESS')
|
...
def add_arguments(self, parser):
parser.add_argument('app_label', type=str)
parser.add_argument('fixture_name', default=None, nargs='?', type=str)
def handle(self, *args, **options):
...
nodes = None
if len(args) == 0:
if options['fixture_name'] is None:
args = (options['app_label'], )
else:
args = (options['app_label'], options['fixture_name'])
if len(args) == 1:
...
|
442f0df33b91fced038e2c497e6c03e0f82f55b2
|
qtpy/QtTest.py
|
qtpy/QtTest.py
|
from qtpy import PYQT5, PYQT4, PYSIDE, PythonQtError
if PYQT5:
from PyQt5.QtTest import QTest
elif PYQT4:
from PyQt4.QtTest import QTest as OldQTest
class QTest(OldQTest):
@staticmethod
def qWaitForWindowActive(QWidget):
OldQTest.qWaitForWindowShown(QWidget)
elif PYSIDE:
raise ImportError('QtTest support is incomplete for PySide')
else:
raise PythonQtError('No Qt bindings could be found')
|
from qtpy import PYQT5, PYQT4, PYSIDE, PythonQtError
if PYQT5:
from PyQt5.QtTest import QTest
elif PYQT4:
from PyQt4.QtTest import QTest as OldQTest
class QTest(OldQTest):
@staticmethod
def qWaitForWindowActive(QWidget):
OldQTest.qWaitForWindowShown(QWidget)
elif PYSIDE:
from PySide.QtTest import QTest
else:
raise PythonQtError('No Qt bindings could be found')
|
Add support for QTest with PySide
|
Add support for QTest with PySide
|
Python
|
mit
|
spyder-ide/qtpy,davvid/qtpy,goanpeca/qtpy,davvid/qtpy,goanpeca/qtpy
|
from qtpy import PYQT5, PYQT4, PYSIDE, PythonQtError
if PYQT5:
from PyQt5.QtTest import QTest
elif PYQT4:
from PyQt4.QtTest import QTest as OldQTest
class QTest(OldQTest):
@staticmethod
def qWaitForWindowActive(QWidget):
OldQTest.qWaitForWindowShown(QWidget)
elif PYSIDE:
- raise ImportError('QtTest support is incomplete for PySide')
+ from PySide.QtTest import QTest
else:
raise PythonQtError('No Qt bindings could be found')
|
Add support for QTest with PySide
|
## Code Before:
from qtpy import PYQT5, PYQT4, PYSIDE, PythonQtError
if PYQT5:
from PyQt5.QtTest import QTest
elif PYQT4:
from PyQt4.QtTest import QTest as OldQTest
class QTest(OldQTest):
@staticmethod
def qWaitForWindowActive(QWidget):
OldQTest.qWaitForWindowShown(QWidget)
elif PYSIDE:
raise ImportError('QtTest support is incomplete for PySide')
else:
raise PythonQtError('No Qt bindings could be found')
## Instruction:
Add support for QTest with PySide
## Code After:
from qtpy import PYQT5, PYQT4, PYSIDE, PythonQtError
if PYQT5:
from PyQt5.QtTest import QTest
elif PYQT4:
from PyQt4.QtTest import QTest as OldQTest
class QTest(OldQTest):
@staticmethod
def qWaitForWindowActive(QWidget):
OldQTest.qWaitForWindowShown(QWidget)
elif PYSIDE:
from PySide.QtTest import QTest
else:
raise PythonQtError('No Qt bindings could be found')
|
# ... existing code ...
elif PYSIDE:
from PySide.QtTest import QTest
else:
# ... rest of the code ...
|
a2627a5e0fc68be04af50259e1fd504be389aeb1
|
kino/utils/config.py
|
kino/utils/config.py
|
from utils.data_handler import DataHandler
class Config(object):
class __Config:
def __init__(self):
self.data_handler = DataHandler()
self.fname = "config.json"
config = self.__read_config()
self.kino = config["kino"]
self.github = config["github"]
def __read_config(self):
return self.data_handler.read_file(self.fname)
instance = None
def __init__(self):
if not Config.instance:
Config.instance = Config.__Config()
def __getattr__(self, name):
return getattr(self.instance, name)
|
from utils.data_handler import DataHandler
class Config(object):
class __Config:
def __init__(self):
self.data_handler = DataHandler()
self.fname = "config.json"
config = self.__read_config()
self.kino = config["kino"]
self.github = config["github"]
self.weather = config["weather"]
def __read_config(self):
return self.data_handler.read_file(self.fname)
instance = None
def __init__(self):
if not Config.instance:
Config.instance = Config.__Config()
def __getattr__(self, name):
return getattr(self.instance, name)
|
Add Config weather - (DARKSKY API KEY, HOME, WORK_PLACE
|
Add Config weather - (DARKSKY API KEY, HOME, WORK_PLACE
|
Python
|
mit
|
DongjunLee/kino-bot
|
from utils.data_handler import DataHandler
class Config(object):
class __Config:
def __init__(self):
self.data_handler = DataHandler()
self.fname = "config.json"
config = self.__read_config()
self.kino = config["kino"]
self.github = config["github"]
+ self.weather = config["weather"]
def __read_config(self):
return self.data_handler.read_file(self.fname)
instance = None
def __init__(self):
if not Config.instance:
Config.instance = Config.__Config()
def __getattr__(self, name):
return getattr(self.instance, name)
|
Add Config weather - (DARKSKY API KEY, HOME, WORK_PLACE
|
## Code Before:
from utils.data_handler import DataHandler
class Config(object):
class __Config:
def __init__(self):
self.data_handler = DataHandler()
self.fname = "config.json"
config = self.__read_config()
self.kino = config["kino"]
self.github = config["github"]
def __read_config(self):
return self.data_handler.read_file(self.fname)
instance = None
def __init__(self):
if not Config.instance:
Config.instance = Config.__Config()
def __getattr__(self, name):
return getattr(self.instance, name)
## Instruction:
Add Config weather - (DARKSKY API KEY, HOME, WORK_PLACE
## Code After:
from utils.data_handler import DataHandler
class Config(object):
class __Config:
def __init__(self):
self.data_handler = DataHandler()
self.fname = "config.json"
config = self.__read_config()
self.kino = config["kino"]
self.github = config["github"]
self.weather = config["weather"]
def __read_config(self):
return self.data_handler.read_file(self.fname)
instance = None
def __init__(self):
if not Config.instance:
Config.instance = Config.__Config()
def __getattr__(self, name):
return getattr(self.instance, name)
|
// ... existing code ...
self.github = config["github"]
self.weather = config["weather"]
// ... rest of the code ...
|
dec2222cde98b395aac303af4e005937f4085b89
|
src/ggrc_workflows/migrations/versions/20140804203436_32221e9f330c_remove_prohibitive_foreign_key_.py
|
src/ggrc_workflows/migrations/versions/20140804203436_32221e9f330c_remove_prohibitive_foreign_key_.py
|
# revision identifiers, used by Alembic.
revision = '32221e9f330c'
down_revision = '235b7b9989be'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.drop_constraint(
'cycle_task_group_object_tasks_ibfk_4',
table_name='cycle_task_group_object_tasks',
type_='foreignkey'
)
op.drop_constraint(
'cycle_task_group_objects_ibfk_4',
table_name='cycle_task_group_objects',
type_='foreignkey'
)
def downgrade():
pass
|
# revision identifiers, used by Alembic.
revision = '32221e9f330c'
down_revision = '235b7b9989be'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.drop_constraint(
'uq_t_workflows', table_name='workflows', type_='unique')
op.drop_constraint(
'uq_t_task_groups', table_name='task_groups', type_='unique')
op.drop_constraint(
'cycle_task_group_object_tasks_ibfk_4',
table_name='cycle_task_group_object_tasks',
type_='foreignkey'
)
op.drop_constraint(
'cycle_task_group_objects_ibfk_4',
table_name='cycle_task_group_objects',
type_='foreignkey'
)
def downgrade():
pass
|
Remove uniqueness constraints on Workflow and TaskGroup
|
Remove uniqueness constraints on Workflow and TaskGroup
* Titles need not be unique anymore
|
Python
|
apache-2.0
|
vladan-m/ggrc-core,hyperNURb/ggrc-core,NejcZupec/ggrc-core,prasannav7/ggrc-core,plamut/ggrc-core,AleksNeStu/ggrc-core,hyperNURb/ggrc-core,vladan-m/ggrc-core,plamut/ggrc-core,hasanalom/ggrc-core,prasannav7/ggrc-core,jmakov/ggrc-core,VinnieJohns/ggrc-core,vladan-m/ggrc-core,prasannav7/ggrc-core,plamut/ggrc-core,NejcZupec/ggrc-core,AleksNeStu/ggrc-core,vladan-m/ggrc-core,AleksNeStu/ggrc-core,hasanalom/ggrc-core,uskudnik/ggrc-core,j0gurt/ggrc-core,edofic/ggrc-core,hyperNURb/ggrc-core,andrei-karalionak/ggrc-core,josthkko/ggrc-core,josthkko/ggrc-core,AleksNeStu/ggrc-core,VinnieJohns/ggrc-core,kr41/ggrc-core,hasanalom/ggrc-core,uskudnik/ggrc-core,j0gurt/ggrc-core,jmakov/ggrc-core,jmakov/ggrc-core,josthkko/ggrc-core,kr41/ggrc-core,edofic/ggrc-core,andrei-karalionak/ggrc-core,VinnieJohns/ggrc-core,edofic/ggrc-core,uskudnik/ggrc-core,jmakov/ggrc-core,prasannav7/ggrc-core,vladan-m/ggrc-core,edofic/ggrc-core,hyperNURb/ggrc-core,VinnieJohns/ggrc-core,selahssea/ggrc-core,jmakov/ggrc-core,NejcZupec/ggrc-core,selahssea/ggrc-core,uskudnik/ggrc-core,j0gurt/ggrc-core,kr41/ggrc-core,j0gurt/ggrc-core,hyperNURb/ggrc-core,uskudnik/ggrc-core,josthkko/ggrc-core,selahssea/ggrc-core,plamut/ggrc-core,selahssea/ggrc-core,andrei-karalionak/ggrc-core,hasanalom/ggrc-core,hasanalom/ggrc-core,kr41/ggrc-core,andrei-karalionak/ggrc-core,NejcZupec/ggrc-core
|
# revision identifiers, used by Alembic.
revision = '32221e9f330c'
down_revision = '235b7b9989be'
from alembic import op
import sqlalchemy as sa
def upgrade():
+ op.drop_constraint(
+ 'uq_t_workflows', table_name='workflows', type_='unique')
+ op.drop_constraint(
+ 'uq_t_task_groups', table_name='task_groups', type_='unique')
op.drop_constraint(
'cycle_task_group_object_tasks_ibfk_4',
table_name='cycle_task_group_object_tasks',
type_='foreignkey'
)
op.drop_constraint(
'cycle_task_group_objects_ibfk_4',
table_name='cycle_task_group_objects',
type_='foreignkey'
)
def downgrade():
pass
|
Remove uniqueness constraints on Workflow and TaskGroup
|
## Code Before:
# revision identifiers, used by Alembic.
revision = '32221e9f330c'
down_revision = '235b7b9989be'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.drop_constraint(
'cycle_task_group_object_tasks_ibfk_4',
table_name='cycle_task_group_object_tasks',
type_='foreignkey'
)
op.drop_constraint(
'cycle_task_group_objects_ibfk_4',
table_name='cycle_task_group_objects',
type_='foreignkey'
)
def downgrade():
pass
## Instruction:
Remove uniqueness constraints on Workflow and TaskGroup
## Code After:
# revision identifiers, used by Alembic.
revision = '32221e9f330c'
down_revision = '235b7b9989be'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.drop_constraint(
'uq_t_workflows', table_name='workflows', type_='unique')
op.drop_constraint(
'uq_t_task_groups', table_name='task_groups', type_='unique')
op.drop_constraint(
'cycle_task_group_object_tasks_ibfk_4',
table_name='cycle_task_group_object_tasks',
type_='foreignkey'
)
op.drop_constraint(
'cycle_task_group_objects_ibfk_4',
table_name='cycle_task_group_objects',
type_='foreignkey'
)
def downgrade():
pass
|
...
def upgrade():
op.drop_constraint(
'uq_t_workflows', table_name='workflows', type_='unique')
op.drop_constraint(
'uq_t_task_groups', table_name='task_groups', type_='unique')
op.drop_constraint(
...
|
3d7459f7b1d40bb94a64d3f08d41942feabf4c12
|
manager/jobs/migrations/0003_auto_20200723_0219.py
|
manager/jobs/migrations/0003_auto_20200723_0219.py
|
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('jobs', '0002_auto_20200708_2203'),
]
operations = [
migrations.AlterField(
model_name='job',
name='id',
field=models.BigAutoField(help_text='An autoincrementing integer to allow selecting jobs in the order they were created.', primary_key=True, serialize=False),
),
migrations.AlterField(
model_name='job',
name='method',
field=models.CharField(choices=[('parallel', 'parallel'), ('series', 'series'), ('chain', 'chain'), ('clean', 'clean'), ('archive', 'archive'), ('pull', 'pull'), ('push', 'push'), ('decode', 'decode'), ('encode', 'encode'), ('convert', 'convert'), ('compile', 'compile'), ('build', 'build'), ('execute', 'execute'), ('session', 'session'), ('sleep', 'sleep')], help_text='The job method.', max_length=32),
),
]
|
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('jobs', '0002_auto_20200708_2203'),
]
operations = [
migrations.RemoveField(
model_name='job',
name='id',
),
migrations.AddField(
model_name='job',
name='id',
field=models.BigAutoField(help_text='An autoincrementing integer to allow selecting jobs in the order they were created.', primary_key=True, serialize=False),
),
migrations.AlterField(
model_name='job',
name='method',
field=models.CharField(choices=[('parallel', 'parallel'), ('series', 'series'), ('chain', 'chain'), ('clean', 'clean'), ('archive', 'archive'), ('pull', 'pull'), ('push', 'push'), ('decode', 'decode'), ('encode', 'encode'), ('convert', 'convert'), ('compile', 'compile'), ('build', 'build'), ('execute', 'execute'), ('session', 'session'), ('sleep', 'sleep')], help_text='The job method.', max_length=32),
),
]
|
Allow migration to run on Postgres
|
chore(Jobs): Allow migration to run on Postgres
|
Python
|
apache-2.0
|
stencila/hub,stencila/hub,stencila/hub,stencila/hub,stencila/hub
|
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('jobs', '0002_auto_20200708_2203'),
]
operations = [
+ migrations.RemoveField(
+ model_name='job',
+ name='id',
+ ),
- migrations.AlterField(
+ migrations.AddField(
model_name='job',
name='id',
field=models.BigAutoField(help_text='An autoincrementing integer to allow selecting jobs in the order they were created.', primary_key=True, serialize=False),
),
migrations.AlterField(
model_name='job',
name='method',
field=models.CharField(choices=[('parallel', 'parallel'), ('series', 'series'), ('chain', 'chain'), ('clean', 'clean'), ('archive', 'archive'), ('pull', 'pull'), ('push', 'push'), ('decode', 'decode'), ('encode', 'encode'), ('convert', 'convert'), ('compile', 'compile'), ('build', 'build'), ('execute', 'execute'), ('session', 'session'), ('sleep', 'sleep')], help_text='The job method.', max_length=32),
),
]
|
Allow migration to run on Postgres
|
## Code Before:
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('jobs', '0002_auto_20200708_2203'),
]
operations = [
migrations.AlterField(
model_name='job',
name='id',
field=models.BigAutoField(help_text='An autoincrementing integer to allow selecting jobs in the order they were created.', primary_key=True, serialize=False),
),
migrations.AlterField(
model_name='job',
name='method',
field=models.CharField(choices=[('parallel', 'parallel'), ('series', 'series'), ('chain', 'chain'), ('clean', 'clean'), ('archive', 'archive'), ('pull', 'pull'), ('push', 'push'), ('decode', 'decode'), ('encode', 'encode'), ('convert', 'convert'), ('compile', 'compile'), ('build', 'build'), ('execute', 'execute'), ('session', 'session'), ('sleep', 'sleep')], help_text='The job method.', max_length=32),
),
]
## Instruction:
Allow migration to run on Postgres
## Code After:
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('jobs', '0002_auto_20200708_2203'),
]
operations = [
migrations.RemoveField(
model_name='job',
name='id',
),
migrations.AddField(
model_name='job',
name='id',
field=models.BigAutoField(help_text='An autoincrementing integer to allow selecting jobs in the order they were created.', primary_key=True, serialize=False),
),
migrations.AlterField(
model_name='job',
name='method',
field=models.CharField(choices=[('parallel', 'parallel'), ('series', 'series'), ('chain', 'chain'), ('clean', 'clean'), ('archive', 'archive'), ('pull', 'pull'), ('push', 'push'), ('decode', 'decode'), ('encode', 'encode'), ('convert', 'convert'), ('compile', 'compile'), ('build', 'build'), ('execute', 'execute'), ('session', 'session'), ('sleep', 'sleep')], help_text='The job method.', max_length=32),
),
]
|
// ... existing code ...
operations = [
migrations.RemoveField(
model_name='job',
name='id',
),
migrations.AddField(
model_name='job',
// ... rest of the code ...
|
b26ce5b5ff778208314bfd21014f88ee24917d7a
|
ideas/views.py
|
ideas/views.py
|
from .models import Idea
from .serializers import IdeaSerializer
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
@api_view(['GET',])
def idea_list(request):
if request.method == 'GET':
ideas = Idea.objects.all()
serializer = IdeaSerializer(ideas, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
@api_view(['GET',])
def results(request):
if request.method == 'GET':
ideas_ordered = Idea.objects.order_by('-votes')
serializer = IdeaSerializer(ideas_ordered, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
@api_view(['POST',])
def vote(request):
if request.method == 'POST':
idea = Idea.objects.get(pk=request.data)
idea.votes += 1
idea.save()
serializer = IdeaSerializer(idea)
return Response(serializer.data, status=status.HTTP_200_OK)
|
from .models import Idea
from .serializers import IdeaSerializer
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
@api_view(['GET',])
def idea_list(request):
if request.method == 'GET':
ideas = Idea.objects.all()
serializer = IdeaSerializer(ideas, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
@api_view(['GET',])
def idea(request, pk):
if request.method == 'GET':
idea = Idea.objects.get(pk=pk)
serializer = IdeaSerializer(idea)
return Response(serializer.data, status=status.HTTP_200_OK)
@api_view(['GET',])
def results(request):
if request.method == 'GET':
ideas_ordered = Idea.objects.order_by('-votes')
serializer = IdeaSerializer(ideas_ordered, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
@api_view(['POST',])
def vote(request, pk):
if request.method == 'POST':
idea = Idea.objects.get(pk=pk)
idea.votes += 1
idea.save()
serializer = IdeaSerializer(idea)
return Response(serializer.data, status=status.HTTP_200_OK)
|
Add GET for idea and refactor vote
|
Add GET for idea and refactor vote
|
Python
|
mit
|
neosergio/vote_hackatrix_backend
|
from .models import Idea
from .serializers import IdeaSerializer
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
@api_view(['GET',])
def idea_list(request):
if request.method == 'GET':
ideas = Idea.objects.all()
serializer = IdeaSerializer(ideas, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
@api_view(['GET',])
+ def idea(request, pk):
+ if request.method == 'GET':
+ idea = Idea.objects.get(pk=pk)
+ serializer = IdeaSerializer(idea)
+ return Response(serializer.data, status=status.HTTP_200_OK)
+
+ @api_view(['GET',])
def results(request):
if request.method == 'GET':
ideas_ordered = Idea.objects.order_by('-votes')
serializer = IdeaSerializer(ideas_ordered, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
@api_view(['POST',])
- def vote(request):
+ def vote(request, pk):
if request.method == 'POST':
- idea = Idea.objects.get(pk=request.data)
+ idea = Idea.objects.get(pk=pk)
idea.votes += 1
idea.save()
serializer = IdeaSerializer(idea)
return Response(serializer.data, status=status.HTTP_200_OK)
|
Add GET for idea and refactor vote
|
## Code Before:
from .models import Idea
from .serializers import IdeaSerializer
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
@api_view(['GET',])
def idea_list(request):
if request.method == 'GET':
ideas = Idea.objects.all()
serializer = IdeaSerializer(ideas, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
@api_view(['GET',])
def results(request):
if request.method == 'GET':
ideas_ordered = Idea.objects.order_by('-votes')
serializer = IdeaSerializer(ideas_ordered, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
@api_view(['POST',])
def vote(request):
if request.method == 'POST':
idea = Idea.objects.get(pk=request.data)
idea.votes += 1
idea.save()
serializer = IdeaSerializer(idea)
return Response(serializer.data, status=status.HTTP_200_OK)
## Instruction:
Add GET for idea and refactor vote
## Code After:
from .models import Idea
from .serializers import IdeaSerializer
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
@api_view(['GET',])
def idea_list(request):
if request.method == 'GET':
ideas = Idea.objects.all()
serializer = IdeaSerializer(ideas, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
@api_view(['GET',])
def idea(request, pk):
if request.method == 'GET':
idea = Idea.objects.get(pk=pk)
serializer = IdeaSerializer(idea)
return Response(serializer.data, status=status.HTTP_200_OK)
@api_view(['GET',])
def results(request):
if request.method == 'GET':
ideas_ordered = Idea.objects.order_by('-votes')
serializer = IdeaSerializer(ideas_ordered, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
@api_view(['POST',])
def vote(request, pk):
if request.method == 'POST':
idea = Idea.objects.get(pk=pk)
idea.votes += 1
idea.save()
serializer = IdeaSerializer(idea)
return Response(serializer.data, status=status.HTTP_200_OK)
|
# ... existing code ...
@api_view(['GET',])
def idea(request, pk):
if request.method == 'GET':
idea = Idea.objects.get(pk=pk)
serializer = IdeaSerializer(idea)
return Response(serializer.data, status=status.HTTP_200_OK)
@api_view(['GET',])
def results(request):
# ... modified code ...
@api_view(['POST',])
def vote(request, pk):
if request.method == 'POST':
idea = Idea.objects.get(pk=pk)
idea.votes += 1
# ... rest of the code ...
|
6cd1c7a95ca4162643b6d52f4bb82596178fde22
|
gaphor/UML/__init__.py
|
gaphor/UML/__init__.py
|
from gaphor.UML.uml2 import * # noqa: isort:skip
from gaphor.UML.presentation import Presentation # noqa: isort:skip
import gaphor.UML.uml2overrides # noqa: isort:skip
from gaphor.UML.elementfactory import ElementFactory # noqa: isort:skip
from gaphor.UML import modelfactory as model # noqa: isort:skip
from gaphor.UML.umlfmt import format
from gaphor.UML.umllex import parse
|
from gaphor.UML.uml2 import * # noqa: isort:skip
from gaphor.UML.presentation import Presentation # noqa: isort:skip
from gaphor.UML.elementfactory import ElementFactory # noqa: isort:skip
from gaphor.UML import modelfactory as model # noqa: isort:skip
from gaphor.UML.umlfmt import format
from gaphor.UML.umllex import parse
import gaphor.UML.uml2overrides # noqa: isort:skip
|
Reorder imports in UML module
|
Reorder imports in UML module
|
Python
|
lgpl-2.1
|
amolenaar/gaphor,amolenaar/gaphor
|
from gaphor.UML.uml2 import * # noqa: isort:skip
from gaphor.UML.presentation import Presentation # noqa: isort:skip
- import gaphor.UML.uml2overrides # noqa: isort:skip
from gaphor.UML.elementfactory import ElementFactory # noqa: isort:skip
from gaphor.UML import modelfactory as model # noqa: isort:skip
from gaphor.UML.umlfmt import format
from gaphor.UML.umllex import parse
+ import gaphor.UML.uml2overrides # noqa: isort:skip
+
|
Reorder imports in UML module
|
## Code Before:
from gaphor.UML.uml2 import * # noqa: isort:skip
from gaphor.UML.presentation import Presentation # noqa: isort:skip
import gaphor.UML.uml2overrides # noqa: isort:skip
from gaphor.UML.elementfactory import ElementFactory # noqa: isort:skip
from gaphor.UML import modelfactory as model # noqa: isort:skip
from gaphor.UML.umlfmt import format
from gaphor.UML.umllex import parse
## Instruction:
Reorder imports in UML module
## Code After:
from gaphor.UML.uml2 import * # noqa: isort:skip
from gaphor.UML.presentation import Presentation # noqa: isort:skip
from gaphor.UML.elementfactory import ElementFactory # noqa: isort:skip
from gaphor.UML import modelfactory as model # noqa: isort:skip
from gaphor.UML.umlfmt import format
from gaphor.UML.umllex import parse
import gaphor.UML.uml2overrides # noqa: isort:skip
|
// ... existing code ...
from gaphor.UML.presentation import Presentation # noqa: isort:skip
from gaphor.UML.elementfactory import ElementFactory # noqa: isort:skip
// ... modified code ...
from gaphor.UML.umllex import parse
import gaphor.UML.uml2overrides # noqa: isort:skip
// ... rest of the code ...
|
f4807197cb48da72a88a0b12c950902614f4b9f6
|
celery_bungiesearch/tasks/bulkdelete.py
|
celery_bungiesearch/tasks/bulkdelete.py
|
from .celerybungie import CeleryBungieTask
from bungiesearch import Bungiesearch
from bungiesearch.utils import update_index
class BulkDeleteTask(CeleryBungieTask):
def run(self, model, instances, **kwargs):
settings = Bungiesearch.BUNGIE.get('SIGNALS', {})
buffer_size = settings.get('BUFFER_SIZE', 100)
update_index(instances, model.__name__, action='delete', bulk_size=buffer_size)
|
from .celerybungie import CeleryBungieTask
from bungiesearch import Bungiesearch
from bungiesearch.utils import update_index
from elasticsearch import TransportError
class BulkDeleteTask(CeleryBungieTask):
def run(self, model, instances, **kwargs):
settings = Bungiesearch.BUNGIE.get('SIGNALS', {})
buffer_size = settings.get('BUFFER_SIZE', 100)
try:
update_index(instances, model.__name__, action='delete', bulk_size=buffer_size)
except TransportError as e:
if e.status_code == 404:
return
raise
|
Add error handling code to bulk delete
|
Add error handling code to bulk delete
|
Python
|
mit
|
afrancis13/celery-bungiesearch
|
from .celerybungie import CeleryBungieTask
from bungiesearch import Bungiesearch
from bungiesearch.utils import update_index
+
+ from elasticsearch import TransportError
class BulkDeleteTask(CeleryBungieTask):
def run(self, model, instances, **kwargs):
settings = Bungiesearch.BUNGIE.get('SIGNALS', {})
buffer_size = settings.get('BUFFER_SIZE', 100)
- update_index(instances, model.__name__, action='delete', bulk_size=buffer_size)
+ try:
+ update_index(instances, model.__name__, action='delete', bulk_size=buffer_size)
+ except TransportError as e:
+ if e.status_code == 404:
+ return
+ raise
+
|
Add error handling code to bulk delete
|
## Code Before:
from .celerybungie import CeleryBungieTask
from bungiesearch import Bungiesearch
from bungiesearch.utils import update_index
class BulkDeleteTask(CeleryBungieTask):
def run(self, model, instances, **kwargs):
settings = Bungiesearch.BUNGIE.get('SIGNALS', {})
buffer_size = settings.get('BUFFER_SIZE', 100)
update_index(instances, model.__name__, action='delete', bulk_size=buffer_size)
## Instruction:
Add error handling code to bulk delete
## Code After:
from .celerybungie import CeleryBungieTask
from bungiesearch import Bungiesearch
from bungiesearch.utils import update_index
from elasticsearch import TransportError
class BulkDeleteTask(CeleryBungieTask):
def run(self, model, instances, **kwargs):
settings = Bungiesearch.BUNGIE.get('SIGNALS', {})
buffer_size = settings.get('BUFFER_SIZE', 100)
try:
update_index(instances, model.__name__, action='delete', bulk_size=buffer_size)
except TransportError as e:
if e.status_code == 404:
return
raise
|
# ... existing code ...
from bungiesearch.utils import update_index
from elasticsearch import TransportError
# ... modified code ...
buffer_size = settings.get('BUFFER_SIZE', 100)
try:
update_index(instances, model.__name__, action='delete', bulk_size=buffer_size)
except TransportError as e:
if e.status_code == 404:
return
raise
# ... rest of the code ...
|
9b8a223dc45f133851fac2df564c2c058aafdf91
|
scripts/index.py
|
scripts/index.py
|
from collections import defaultdict
from pathlib import Path
import re
from string import Template
import sys
def tree():
return defaultdict(tree)
root = tree()
for src in Path('content').glob('**/README.org'):
path = re.sub(r'^content/(.*)/README.org$', r'\1', str(src))
segments = path.split('/')
node = root
for s in segments:
node = node[s]
def walk(node, parent='.', level=0):
elems = sorted((k, v) for k, v in node.items())
for name, subs in elems:
indent = ' ' * level
path = f'{parent}/{name}'
link = f'[[{path}][{name}]]'
yield f'{indent}- {link}'
yield from walk(subs, path, level + 1)
with open('README.org') as f:
head = f.read()
with open('templates/index.org') as f:
template = Template(f.read())
index = '\n'.join(walk(root))
body = template.safe_substitute(index=index)
TARGET = sys.argv[1]
content = '\n'.join([head, body])
with open(TARGET, 'w') as f:
f.write(content)
|
from collections import defaultdict
from pathlib import Path
from string import Template
import sys
def tree():
return defaultdict(tree)
root = tree()
for src in Path('content').glob('**/README.org'):
segments = src.parts[1:-1]
node = root
for s in segments:
node = node[s]
def walk(node, parent='.', level=0):
elems = sorted((k, v) for k, v in node.items())
for name, subs in elems:
indent = ' ' * level
path = f'{parent}/{name}'
link = f'[[{path}][{name}]]'
yield f'{indent}- {link}'
yield from walk(subs, path, level + 1)
with open('README.org') as f:
head = f.read()
with open('templates/index.org') as f:
template = Template(f.read())
index = '\n'.join(walk(root))
body = template.safe_substitute(index=index)
TARGET = sys.argv[1]
content = '\n'.join([head, body])
with open(TARGET, 'w') as f:
f.write(content)
|
Use pathlib for path segmentation
|
Use pathlib for path segmentation
|
Python
|
mit
|
yeonghoey/notes,yeonghoey/yeonghoey,yeonghoey/yeonghoey,yeonghoey/yeonghoey,yeonghoey/yeonghoey
|
from collections import defaultdict
from pathlib import Path
- import re
from string import Template
import sys
def tree():
return defaultdict(tree)
root = tree()
for src in Path('content').glob('**/README.org'):
+ segments = src.parts[1:-1]
- path = re.sub(r'^content/(.*)/README.org$', r'\1', str(src))
- segments = path.split('/')
node = root
for s in segments:
node = node[s]
def walk(node, parent='.', level=0):
elems = sorted((k, v) for k, v in node.items())
for name, subs in elems:
indent = ' ' * level
path = f'{parent}/{name}'
link = f'[[{path}][{name}]]'
yield f'{indent}- {link}'
yield from walk(subs, path, level + 1)
with open('README.org') as f:
head = f.read()
with open('templates/index.org') as f:
template = Template(f.read())
index = '\n'.join(walk(root))
body = template.safe_substitute(index=index)
TARGET = sys.argv[1]
content = '\n'.join([head, body])
with open(TARGET, 'w') as f:
f.write(content)
|
Use pathlib for path segmentation
|
## Code Before:
from collections import defaultdict
from pathlib import Path
import re
from string import Template
import sys
def tree():
return defaultdict(tree)
root = tree()
for src in Path('content').glob('**/README.org'):
path = re.sub(r'^content/(.*)/README.org$', r'\1', str(src))
segments = path.split('/')
node = root
for s in segments:
node = node[s]
def walk(node, parent='.', level=0):
elems = sorted((k, v) for k, v in node.items())
for name, subs in elems:
indent = ' ' * level
path = f'{parent}/{name}'
link = f'[[{path}][{name}]]'
yield f'{indent}- {link}'
yield from walk(subs, path, level + 1)
with open('README.org') as f:
head = f.read()
with open('templates/index.org') as f:
template = Template(f.read())
index = '\n'.join(walk(root))
body = template.safe_substitute(index=index)
TARGET = sys.argv[1]
content = '\n'.join([head, body])
with open(TARGET, 'w') as f:
f.write(content)
## Instruction:
Use pathlib for path segmentation
## Code After:
from collections import defaultdict
from pathlib import Path
from string import Template
import sys
def tree():
return defaultdict(tree)
root = tree()
for src in Path('content').glob('**/README.org'):
segments = src.parts[1:-1]
node = root
for s in segments:
node = node[s]
def walk(node, parent='.', level=0):
elems = sorted((k, v) for k, v in node.items())
for name, subs in elems:
indent = ' ' * level
path = f'{parent}/{name}'
link = f'[[{path}][{name}]]'
yield f'{indent}- {link}'
yield from walk(subs, path, level + 1)
with open('README.org') as f:
head = f.read()
with open('templates/index.org') as f:
template = Template(f.read())
index = '\n'.join(walk(root))
body = template.safe_substitute(index=index)
TARGET = sys.argv[1]
content = '\n'.join([head, body])
with open(TARGET, 'w') as f:
f.write(content)
|
# ... existing code ...
from pathlib import Path
from string import Template
# ... modified code ...
for src in Path('content').glob('**/README.org'):
segments = src.parts[1:-1]
node = root
# ... rest of the code ...
|
1ade5cef22e162ce07edb6d94859268727da4949
|
agile.py
|
agile.py
|
import requests
import xml.etree.ElementTree as ET
from credentials import app_key, user_key, corp_id, report_id
base_url = 'https://prod3.agileticketing.net/api/reporting.svc/xml/render'
date = '&DatePicker=thisweek'
report = '&MembershipMultiPicker=130&filename=memberactivity.xml'
url = '{}{}{}{}{}{}{}'.format(base_url, app_key, user_key, corp_id, report_id,
date, report)
# r = requests.get(url)
# text = r.text
# xml = text[3:]
# root = ET.fromstring(xml)
tree = ET.parse('data.xml')
root = tree.getroot()
members = root[1]
collections = members[3]
details = collections[0]
first_name = details[2].text
# print(first_name)
for name in root.iter('{Membership_MemberList_Extract}FirstName'):
print(name.text)
for name in root.iter():
print(name.tag)
|
import requests
import xml.etree.ElementTree as ET
from credentials import app_key, user_key, corp_id, report_id
base_url = 'https://prod3.agileticketing.net/api/reporting.svc/xml/render'
date = '&DatePicker=thisweek'
report = '&MembershipMultiPicker=130&filename=memberactivity.xml'
url = '{}{}{}{}{}{}{}'.format(base_url, app_key, user_key, corp_id, report_id,
date, report)
# r = requests.get(url)
# text = r.text
# xml = text[3:]
# root = ET.fromstring(xml)
tree = ET.parse('data.xml')
root = tree.getroot()
members = root[1]
collection = members[3]
summary = root[0].attrib
record_count = int(summary['Record_Count'])
members = []
def append_contacts(collection):
'''Populates the contact and address dictionaries and then appends them to
a contacts list.
Arguments:
contacts = The list the dictionary will be appended to.
'''
contact = {}
address = {}
contact['email_addresses'] = [collection[7].text]
contact['first_name'] = collection[2].text.title()
contact['last_name'] = collection[4].text.title()
contact['home_phone'] = collection[19][0].attrib
contact['custom_field 1'] = collection[26].text
contact['addresses'] = [address]
address['line1'] = collection[9].text
address['line2'] = collection[10].text
address['city'] = collection[11].text.title()
address['state_code'] = collection[12].text
address['postal_code'] = collection[13].text
members.append(contact)
for count in range(record_count):
append_contacts(collection[count])
print(members)
|
Create dict out of member info and append to list
|
Create dict out of member info and append to list
append_members() work identically to append_contacts(). A for loop is
also needed to loop over every member entry in the XML file.
|
Python
|
mit
|
deadlyraptor/reels
|
import requests
import xml.etree.ElementTree as ET
from credentials import app_key, user_key, corp_id, report_id
base_url = 'https://prod3.agileticketing.net/api/reporting.svc/xml/render'
date = '&DatePicker=thisweek'
report = '&MembershipMultiPicker=130&filename=memberactivity.xml'
url = '{}{}{}{}{}{}{}'.format(base_url, app_key, user_key, corp_id, report_id,
date, report)
# r = requests.get(url)
# text = r.text
# xml = text[3:]
# root = ET.fromstring(xml)
tree = ET.parse('data.xml')
root = tree.getroot()
members = root[1]
- collections = members[3]
+ collection = members[3]
- details = collections[0]
+ summary = root[0].attrib
+ record_count = int(summary['Record_Count'])
+ members = []
- first_name = details[2].text
- # print(first_name)
- for name in root.iter('{Membership_MemberList_Extract}FirstName'):
- print(name.text)
- for name in root.iter():
- print(name.tag)
+ def append_contacts(collection):
+ '''Populates the contact and address dictionaries and then appends them to
+ a contacts list.
+ Arguments:
+ contacts = The list the dictionary will be appended to.
+ '''
+ contact = {}
+ address = {}
+
+ contact['email_addresses'] = [collection[7].text]
+ contact['first_name'] = collection[2].text.title()
+ contact['last_name'] = collection[4].text.title()
+ contact['home_phone'] = collection[19][0].attrib
+ contact['custom_field 1'] = collection[26].text
+
+ contact['addresses'] = [address]
+
+ address['line1'] = collection[9].text
+ address['line2'] = collection[10].text
+ address['city'] = collection[11].text.title()
+ address['state_code'] = collection[12].text
+ address['postal_code'] = collection[13].text
+
+ members.append(contact)
+
+ for count in range(record_count):
+ append_contacts(collection[count])
+
+ print(members)
+
|
Create dict out of member info and append to list
|
## Code Before:
import requests
import xml.etree.ElementTree as ET
from credentials import app_key, user_key, corp_id, report_id
base_url = 'https://prod3.agileticketing.net/api/reporting.svc/xml/render'
date = '&DatePicker=thisweek'
report = '&MembershipMultiPicker=130&filename=memberactivity.xml'
url = '{}{}{}{}{}{}{}'.format(base_url, app_key, user_key, corp_id, report_id,
date, report)
# r = requests.get(url)
# text = r.text
# xml = text[3:]
# root = ET.fromstring(xml)
tree = ET.parse('data.xml')
root = tree.getroot()
members = root[1]
collections = members[3]
details = collections[0]
first_name = details[2].text
# print(first_name)
for name in root.iter('{Membership_MemberList_Extract}FirstName'):
print(name.text)
for name in root.iter():
print(name.tag)
## Instruction:
Create dict out of member info and append to list
## Code After:
import requests
import xml.etree.ElementTree as ET
from credentials import app_key, user_key, corp_id, report_id
base_url = 'https://prod3.agileticketing.net/api/reporting.svc/xml/render'
date = '&DatePicker=thisweek'
report = '&MembershipMultiPicker=130&filename=memberactivity.xml'
url = '{}{}{}{}{}{}{}'.format(base_url, app_key, user_key, corp_id, report_id,
date, report)
# r = requests.get(url)
# text = r.text
# xml = text[3:]
# root = ET.fromstring(xml)
tree = ET.parse('data.xml')
root = tree.getroot()
members = root[1]
collection = members[3]
summary = root[0].attrib
record_count = int(summary['Record_Count'])
members = []
def append_contacts(collection):
'''Populates the contact and address dictionaries and then appends them to
a contacts list.
Arguments:
contacts = The list the dictionary will be appended to.
'''
contact = {}
address = {}
contact['email_addresses'] = [collection[7].text]
contact['first_name'] = collection[2].text.title()
contact['last_name'] = collection[4].text.title()
contact['home_phone'] = collection[19][0].attrib
contact['custom_field 1'] = collection[26].text
contact['addresses'] = [address]
address['line1'] = collection[9].text
address['line2'] = collection[10].text
address['city'] = collection[11].text.title()
address['state_code'] = collection[12].text
address['postal_code'] = collection[13].text
members.append(contact)
for count in range(record_count):
append_contacts(collection[count])
print(members)
|
...
members = root[1]
collection = members[3]
summary = root[0].attrib
record_count = int(summary['Record_Count'])
members = []
def append_contacts(collection):
'''Populates the contact and address dictionaries and then appends them to
a contacts list.
Arguments:
contacts = The list the dictionary will be appended to.
'''
contact = {}
address = {}
contact['email_addresses'] = [collection[7].text]
contact['first_name'] = collection[2].text.title()
contact['last_name'] = collection[4].text.title()
contact['home_phone'] = collection[19][0].attrib
contact['custom_field 1'] = collection[26].text
contact['addresses'] = [address]
address['line1'] = collection[9].text
address['line2'] = collection[10].text
address['city'] = collection[11].text.title()
address['state_code'] = collection[12].text
address['postal_code'] = collection[13].text
members.append(contact)
for count in range(record_count):
append_contacts(collection[count])
print(members)
...
|
a9059f075bc1bb48422a3aba564a38071b1acf9f
|
selectable/forms/base.py
|
selectable/forms/base.py
|
from django import forms
from django.conf import settings
__all__ = ('BaseLookupForm', )
class BaseLookupForm(forms.Form):
term = forms.CharField(required=False)
limit = forms.IntegerField(required=False, min_value=1)
def clean_limit(self):
"Ensure given limit is less than default if defined"
limit = self.cleaned_data.get('limit', None)
if (settings.SELECTABLE_MAX_LIMIT is not None and
(not limit or limit > settings.SELECTABLE_MAX_LIMIT)):
limit = settings.SELECTABLE_MAX_LIMIT
return limit
|
from django import forms
from django.conf import settings
__all__ = ('BaseLookupForm', )
class BaseLookupForm(forms.Form):
term = forms.CharField(required=False)
limit = forms.IntegerField(required=False, min_value=1)
page = forms.IntegerField(required=False, min_value=1)
def clean_limit(self):
"Ensure given limit is less than default if defined"
limit = self.cleaned_data.get('limit', None)
if (settings.SELECTABLE_MAX_LIMIT is not None and
(not limit or limit > settings.SELECTABLE_MAX_LIMIT)):
limit = settings.SELECTABLE_MAX_LIMIT
return limit
def clean_page(self):
"Return the first page if no page or invalid number is given."
return self.cleaned_data.get('page', 1) or 1
|
Move page cleaning logic to the form.
|
Move page cleaning logic to the form.
--HG--
branch : result-refactor
|
Python
|
bsd-2-clause
|
mlavin/django-selectable,makinacorpus/django-selectable,affan2/django-selectable,affan2/django-selectable,mlavin/django-selectable,affan2/django-selectable,mlavin/django-selectable,makinacorpus/django-selectable
|
from django import forms
from django.conf import settings
__all__ = ('BaseLookupForm', )
class BaseLookupForm(forms.Form):
term = forms.CharField(required=False)
limit = forms.IntegerField(required=False, min_value=1)
+ page = forms.IntegerField(required=False, min_value=1)
def clean_limit(self):
"Ensure given limit is less than default if defined"
limit = self.cleaned_data.get('limit', None)
if (settings.SELECTABLE_MAX_LIMIT is not None and
(not limit or limit > settings.SELECTABLE_MAX_LIMIT)):
limit = settings.SELECTABLE_MAX_LIMIT
return limit
+ def clean_page(self):
+ "Return the first page if no page or invalid number is given."
+ return self.cleaned_data.get('page', 1) or 1
+
|
Move page cleaning logic to the form.
|
## Code Before:
from django import forms
from django.conf import settings
__all__ = ('BaseLookupForm', )
class BaseLookupForm(forms.Form):
term = forms.CharField(required=False)
limit = forms.IntegerField(required=False, min_value=1)
def clean_limit(self):
"Ensure given limit is less than default if defined"
limit = self.cleaned_data.get('limit', None)
if (settings.SELECTABLE_MAX_LIMIT is not None and
(not limit or limit > settings.SELECTABLE_MAX_LIMIT)):
limit = settings.SELECTABLE_MAX_LIMIT
return limit
## Instruction:
Move page cleaning logic to the form.
## Code After:
from django import forms
from django.conf import settings
__all__ = ('BaseLookupForm', )
class BaseLookupForm(forms.Form):
term = forms.CharField(required=False)
limit = forms.IntegerField(required=False, min_value=1)
page = forms.IntegerField(required=False, min_value=1)
def clean_limit(self):
"Ensure given limit is less than default if defined"
limit = self.cleaned_data.get('limit', None)
if (settings.SELECTABLE_MAX_LIMIT is not None and
(not limit or limit > settings.SELECTABLE_MAX_LIMIT)):
limit = settings.SELECTABLE_MAX_LIMIT
return limit
def clean_page(self):
"Return the first page if no page or invalid number is given."
return self.cleaned_data.get('page', 1) or 1
|
# ... existing code ...
limit = forms.IntegerField(required=False, min_value=1)
page = forms.IntegerField(required=False, min_value=1)
# ... modified code ...
return limit
def clean_page(self):
"Return the first page if no page or invalid number is given."
return self.cleaned_data.get('page', 1) or 1
# ... rest of the code ...
|
216294a0ea36c2fbabb43c31ce4fde3a9eee4bf3
|
anchor/models.py
|
anchor/models.py
|
from datetime import datetime
from dateutil import tz
from dateutil.relativedelta import relativedelta
UTC = tz.tzutc()
class Region:
def __init__(self, data):
self.name = data.get('name').title()
self.abbreviation = data.get('abbreviation').upper()
self.active = bool(data.get('active'))
class Account:
def __init__(self, data):
self.account_number = data.get('account_number')
self.cache_expiration = self.set_expiration()
self.host_servers = data.get('host_servers')
self.public_zones = data.get('public_zones')
self.region = data.get('region').lower()
self.servers = data.get('servers')
self.lookup_type = data.get('lookup_type')
def set_expiration(self):
return datetime.now(UTC) + relativedelta(days=1)
|
from datetime import datetime
from dateutil import tz
from dateutil.relativedelta import relativedelta
UTC = tz.tzutc()
class Region:
def __init__(self, data):
self.name = data.get('name').title()
self.abbreviation = data.get('abbreviation').upper()
self.active = bool(data.get('active'))
class Account:
def __init__(self, data):
self.account_number = data.get('account_number')
self.cache_expiration = self.set_expiration()
self.host_servers = data.get('host_servers')
self.public_zones = data.get('public_zones')
self.region = data.get('region').lower()
self.servers = data.get('servers')
self.volumes = data.get('volumes')
self.cbs_hosts = data.get('cbs_hosts')
self.lookup_type = data.get('lookup_type')
def set_expiration(self):
return datetime.now(UTC) + relativedelta(days=1)
|
Update model for CBS host and volume information
|
Update model for CBS host and volume information
|
Python
|
apache-2.0
|
oldarmyc/anchor,oldarmyc/anchor,oldarmyc/anchor
|
from datetime import datetime
from dateutil import tz
from dateutil.relativedelta import relativedelta
UTC = tz.tzutc()
class Region:
def __init__(self, data):
self.name = data.get('name').title()
self.abbreviation = data.get('abbreviation').upper()
self.active = bool(data.get('active'))
class Account:
def __init__(self, data):
self.account_number = data.get('account_number')
self.cache_expiration = self.set_expiration()
self.host_servers = data.get('host_servers')
self.public_zones = data.get('public_zones')
self.region = data.get('region').lower()
self.servers = data.get('servers')
+ self.volumes = data.get('volumes')
+ self.cbs_hosts = data.get('cbs_hosts')
self.lookup_type = data.get('lookup_type')
def set_expiration(self):
return datetime.now(UTC) + relativedelta(days=1)
|
Update model for CBS host and volume information
|
## Code Before:
from datetime import datetime
from dateutil import tz
from dateutil.relativedelta import relativedelta
UTC = tz.tzutc()
class Region:
def __init__(self, data):
self.name = data.get('name').title()
self.abbreviation = data.get('abbreviation').upper()
self.active = bool(data.get('active'))
class Account:
def __init__(self, data):
self.account_number = data.get('account_number')
self.cache_expiration = self.set_expiration()
self.host_servers = data.get('host_servers')
self.public_zones = data.get('public_zones')
self.region = data.get('region').lower()
self.servers = data.get('servers')
self.lookup_type = data.get('lookup_type')
def set_expiration(self):
return datetime.now(UTC) + relativedelta(days=1)
## Instruction:
Update model for CBS host and volume information
## Code After:
from datetime import datetime
from dateutil import tz
from dateutil.relativedelta import relativedelta
UTC = tz.tzutc()
class Region:
def __init__(self, data):
self.name = data.get('name').title()
self.abbreviation = data.get('abbreviation').upper()
self.active = bool(data.get('active'))
class Account:
def __init__(self, data):
self.account_number = data.get('account_number')
self.cache_expiration = self.set_expiration()
self.host_servers = data.get('host_servers')
self.public_zones = data.get('public_zones')
self.region = data.get('region').lower()
self.servers = data.get('servers')
self.volumes = data.get('volumes')
self.cbs_hosts = data.get('cbs_hosts')
self.lookup_type = data.get('lookup_type')
def set_expiration(self):
return datetime.now(UTC) + relativedelta(days=1)
|
...
self.servers = data.get('servers')
self.volumes = data.get('volumes')
self.cbs_hosts = data.get('cbs_hosts')
self.lookup_type = data.get('lookup_type')
...
|
150dad224dd985762714b73e9a91d084efb11e06
|
ob_pipelines/sample.py
|
ob_pipelines/sample.py
|
import os
from luigi import Parameter
from ob_airtable import get_record_by_name, get_record
AIRTABLE_EXPT_TABLE = 'Genomics%20Expt'
AIRTABLE_SAMPLE_TABLE = 'Genomics%20Sample'
S3_BUCKET = os.environ.get('S3_BUCKET')
def get_samples(expt_id):
expt = get_record_by_name(expt_id, AIRTABLE_EXPT_TABLE)
sample_keys = expt['fields']['Genomics samples']
for sample_key in sample_keys:
sample = get_record(sample_key, AIRTABLE_SAMPLE_TABLE)
yield sample['fields']['Name']
class Sample(object):
sample_id = Parameter()
@property
def sample(self):
if not hasattr(self, '_sample'):
self._sample = get_record_by_name(self.sample_id, AIRTABLE_SAMPLE_TABLE)['fields']
return self._sample
@property
def sample_folder(self):
return '{expt}/{sample}'.format(
bucket=S3_BUCKET,
expt = self.experiment['Name'],
sample=self.sample_id)
@property
def experiment(self):
if not hasattr(self, '_experiment'):
expt_key = self.sample['Experiment'][0]
self._experiment = get_record(expt_key, AIRTABLE_EXPT_TABLE)['fields']
return self._experiment
|
import os
from luigi import Parameter
from ob_airtable import AirtableClient
AIRTABLE_EXPT_TABLE = 'Genomics%20Expt'
AIRTABLE_SAMPLE_TABLE = 'Genomics%20Sample'
S3_BUCKET = os.environ.get('S3_BUCKET')
client = AirtableClient()
def get_samples(expt_id):
expt = client.get_record_by_name(expt_id, AIRTABLE_EXPT_TABLE)
sample_keys = expt['fields']['Genomics samples']
for sample_key in sample_keys:
sample = client.get_record(sample_key, AIRTABLE_SAMPLE_TABLE)
yield sample['fields']['Name']
class Sample(object):
sample_id = Parameter()
@property
def sample(self):
if not hasattr(self, '_sample'):
self._sample = client.get_record_by_name(self.sample_id, AIRTABLE_SAMPLE_TABLE)['fields']
return self._sample
@property
def sample_folder(self):
return '{expt}/{sample}'.format(
bucket=S3_BUCKET,
expt = self.experiment['Name'],
sample=self.sample_id)
@property
def experiment(self):
if not hasattr(self, '_experiment'):
expt_key = self.sample['Experiment'][0]
self._experiment = client.get_record(expt_key, AIRTABLE_EXPT_TABLE)['fields']
return self._experiment
|
Update to match changes in ob-airtable
|
Update to match changes in ob-airtable
|
Python
|
apache-2.0
|
outlierbio/ob-pipelines,outlierbio/ob-pipelines,outlierbio/ob-pipelines
|
import os
from luigi import Parameter
- from ob_airtable import get_record_by_name, get_record
+ from ob_airtable import AirtableClient
AIRTABLE_EXPT_TABLE = 'Genomics%20Expt'
AIRTABLE_SAMPLE_TABLE = 'Genomics%20Sample'
S3_BUCKET = os.environ.get('S3_BUCKET')
+ client = AirtableClient()
def get_samples(expt_id):
- expt = get_record_by_name(expt_id, AIRTABLE_EXPT_TABLE)
+ expt = client.get_record_by_name(expt_id, AIRTABLE_EXPT_TABLE)
sample_keys = expt['fields']['Genomics samples']
for sample_key in sample_keys:
- sample = get_record(sample_key, AIRTABLE_SAMPLE_TABLE)
+ sample = client.get_record(sample_key, AIRTABLE_SAMPLE_TABLE)
yield sample['fields']['Name']
class Sample(object):
sample_id = Parameter()
@property
def sample(self):
if not hasattr(self, '_sample'):
- self._sample = get_record_by_name(self.sample_id, AIRTABLE_SAMPLE_TABLE)['fields']
+ self._sample = client.get_record_by_name(self.sample_id, AIRTABLE_SAMPLE_TABLE)['fields']
return self._sample
@property
def sample_folder(self):
return '{expt}/{sample}'.format(
bucket=S3_BUCKET,
expt = self.experiment['Name'],
sample=self.sample_id)
@property
def experiment(self):
if not hasattr(self, '_experiment'):
expt_key = self.sample['Experiment'][0]
- self._experiment = get_record(expt_key, AIRTABLE_EXPT_TABLE)['fields']
+ self._experiment = client.get_record(expt_key, AIRTABLE_EXPT_TABLE)['fields']
return self._experiment
|
Update to match changes in ob-airtable
|
## Code Before:
import os
from luigi import Parameter
from ob_airtable import get_record_by_name, get_record
AIRTABLE_EXPT_TABLE = 'Genomics%20Expt'
AIRTABLE_SAMPLE_TABLE = 'Genomics%20Sample'
S3_BUCKET = os.environ.get('S3_BUCKET')
def get_samples(expt_id):
expt = get_record_by_name(expt_id, AIRTABLE_EXPT_TABLE)
sample_keys = expt['fields']['Genomics samples']
for sample_key in sample_keys:
sample = get_record(sample_key, AIRTABLE_SAMPLE_TABLE)
yield sample['fields']['Name']
class Sample(object):
sample_id = Parameter()
@property
def sample(self):
if not hasattr(self, '_sample'):
self._sample = get_record_by_name(self.sample_id, AIRTABLE_SAMPLE_TABLE)['fields']
return self._sample
@property
def sample_folder(self):
return '{expt}/{sample}'.format(
bucket=S3_BUCKET,
expt = self.experiment['Name'],
sample=self.sample_id)
@property
def experiment(self):
if not hasattr(self, '_experiment'):
expt_key = self.sample['Experiment'][0]
self._experiment = get_record(expt_key, AIRTABLE_EXPT_TABLE)['fields']
return self._experiment
## Instruction:
Update to match changes in ob-airtable
## Code After:
import os
from luigi import Parameter
from ob_airtable import AirtableClient
AIRTABLE_EXPT_TABLE = 'Genomics%20Expt'
AIRTABLE_SAMPLE_TABLE = 'Genomics%20Sample'
S3_BUCKET = os.environ.get('S3_BUCKET')
client = AirtableClient()
def get_samples(expt_id):
expt = client.get_record_by_name(expt_id, AIRTABLE_EXPT_TABLE)
sample_keys = expt['fields']['Genomics samples']
for sample_key in sample_keys:
sample = client.get_record(sample_key, AIRTABLE_SAMPLE_TABLE)
yield sample['fields']['Name']
class Sample(object):
sample_id = Parameter()
@property
def sample(self):
if not hasattr(self, '_sample'):
self._sample = client.get_record_by_name(self.sample_id, AIRTABLE_SAMPLE_TABLE)['fields']
return self._sample
@property
def sample_folder(self):
return '{expt}/{sample}'.format(
bucket=S3_BUCKET,
expt = self.experiment['Name'],
sample=self.sample_id)
@property
def experiment(self):
if not hasattr(self, '_experiment'):
expt_key = self.sample['Experiment'][0]
self._experiment = client.get_record(expt_key, AIRTABLE_EXPT_TABLE)['fields']
return self._experiment
|
# ... existing code ...
from luigi import Parameter
from ob_airtable import AirtableClient
# ... modified code ...
client = AirtableClient()
...
def get_samples(expt_id):
expt = client.get_record_by_name(expt_id, AIRTABLE_EXPT_TABLE)
sample_keys = expt['fields']['Genomics samples']
...
for sample_key in sample_keys:
sample = client.get_record(sample_key, AIRTABLE_SAMPLE_TABLE)
yield sample['fields']['Name']
...
if not hasattr(self, '_sample'):
self._sample = client.get_record_by_name(self.sample_id, AIRTABLE_SAMPLE_TABLE)['fields']
return self._sample
...
expt_key = self.sample['Experiment'][0]
self._experiment = client.get_record(expt_key, AIRTABLE_EXPT_TABLE)['fields']
return self._experiment
# ... rest of the code ...
|
aa86dfda0b92ac99c86053db7fb43bd8cecccc83
|
kpi/interfaces/sync_backend_media.py
|
kpi/interfaces/sync_backend_media.py
|
class SyncBackendMediaInterface:
"""
This interface defines required properties and methods
of objects passed to deployment back-end class on media synchronization.
"""
@property
def backend_data_value(self):
raise NotImplementedError('This property should be implemented in '
'subclasses')
@property
def backend_uniqid(self):
raise NotImplementedError('This property should be implemented in '
'subclasses')
def delete(self, **kwargs):
raise NotImplementedError('This method should be implemented in '
'subclasses')
@property
def deleted_at(self):
raise NotImplementedError('This property should be implemented in '
'subclasses')
@property
def filename(self):
raise NotImplementedError('This property should be implemented in '
'subclasses')
@property
def hash(self):
raise NotImplementedError('This property should be implemented in '
'subclasses')
@property
def is_remote_url(self):
raise NotImplementedError('This property should be implemented in '
'subclasses')
@property
def mimetype(self):
raise NotImplementedError('This property should be implemented in '
'subclasses')
|
from kpi.exceptions import AbstractMethodError, AbstractPropertyError
class SyncBackendMediaInterface:
"""
This interface defines required properties and methods
of objects passed to deployment back-end class on media synchronization.
"""
@property
def backend_data_value(self):
raise AbstractPropertyError
@property
def backend_uniqid(self):
raise AbstractPropertyError
def delete(self, **kwargs):
raise AbstractMethodError
@property
def deleted_at(self):
raise AbstractPropertyError
@property
def filename(self):
raise AbstractPropertyError
@property
def hash(self):
raise AbstractPropertyError
@property
def is_remote_url(self):
raise AbstractPropertyError
@property
def mimetype(self):
raise AbstractPropertyError
|
Use new exceptions: AbstractMethodError, AbstractPropertyError
|
Use new exceptions: AbstractMethodError, AbstractPropertyError
|
Python
|
agpl-3.0
|
kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi
|
+ from kpi.exceptions import AbstractMethodError, AbstractPropertyError
+
class SyncBackendMediaInterface:
"""
This interface defines required properties and methods
of objects passed to deployment back-end class on media synchronization.
"""
@property
def backend_data_value(self):
+ raise AbstractPropertyError
- raise NotImplementedError('This property should be implemented in '
- 'subclasses')
@property
def backend_uniqid(self):
+ raise AbstractPropertyError
- raise NotImplementedError('This property should be implemented in '
- 'subclasses')
def delete(self, **kwargs):
+ raise AbstractMethodError
- raise NotImplementedError('This method should be implemented in '
- 'subclasses')
@property
def deleted_at(self):
+ raise AbstractPropertyError
- raise NotImplementedError('This property should be implemented in '
- 'subclasses')
@property
def filename(self):
+ raise AbstractPropertyError
- raise NotImplementedError('This property should be implemented in '
- 'subclasses')
@property
def hash(self):
+ raise AbstractPropertyError
- raise NotImplementedError('This property should be implemented in '
- 'subclasses')
@property
def is_remote_url(self):
+ raise AbstractPropertyError
- raise NotImplementedError('This property should be implemented in '
- 'subclasses')
@property
def mimetype(self):
+ raise AbstractPropertyError
- raise NotImplementedError('This property should be implemented in '
- 'subclasses')
|
Use new exceptions: AbstractMethodError, AbstractPropertyError
|
## Code Before:
class SyncBackendMediaInterface:
"""
This interface defines required properties and methods
of objects passed to deployment back-end class on media synchronization.
"""
@property
def backend_data_value(self):
raise NotImplementedError('This property should be implemented in '
'subclasses')
@property
def backend_uniqid(self):
raise NotImplementedError('This property should be implemented in '
'subclasses')
def delete(self, **kwargs):
raise NotImplementedError('This method should be implemented in '
'subclasses')
@property
def deleted_at(self):
raise NotImplementedError('This property should be implemented in '
'subclasses')
@property
def filename(self):
raise NotImplementedError('This property should be implemented in '
'subclasses')
@property
def hash(self):
raise NotImplementedError('This property should be implemented in '
'subclasses')
@property
def is_remote_url(self):
raise NotImplementedError('This property should be implemented in '
'subclasses')
@property
def mimetype(self):
raise NotImplementedError('This property should be implemented in '
'subclasses')
## Instruction:
Use new exceptions: AbstractMethodError, AbstractPropertyError
## Code After:
from kpi.exceptions import AbstractMethodError, AbstractPropertyError
class SyncBackendMediaInterface:
"""
This interface defines required properties and methods
of objects passed to deployment back-end class on media synchronization.
"""
@property
def backend_data_value(self):
raise AbstractPropertyError
@property
def backend_uniqid(self):
raise AbstractPropertyError
def delete(self, **kwargs):
raise AbstractMethodError
@property
def deleted_at(self):
raise AbstractPropertyError
@property
def filename(self):
raise AbstractPropertyError
@property
def hash(self):
raise AbstractPropertyError
@property
def is_remote_url(self):
raise AbstractPropertyError
@property
def mimetype(self):
raise AbstractPropertyError
|
# ... existing code ...
from kpi.exceptions import AbstractMethodError, AbstractPropertyError
# ... modified code ...
def backend_data_value(self):
raise AbstractPropertyError
...
def backend_uniqid(self):
raise AbstractPropertyError
...
def delete(self, **kwargs):
raise AbstractMethodError
...
def deleted_at(self):
raise AbstractPropertyError
...
def filename(self):
raise AbstractPropertyError
...
def hash(self):
raise AbstractPropertyError
...
def is_remote_url(self):
raise AbstractPropertyError
...
def mimetype(self):
raise AbstractPropertyError
# ... rest of the code ...
|
330c90c9bc8b4c6d8df4d15f503e9a483513e5db
|
install/setup_pi_box.py
|
install/setup_pi_box.py
|
import os
import sys
import shutil
if not os.path.exists('/opt/Pi-Box'):
os.makedirs('/opt/Pi-Box')
shutil.copy('./main.py', '/opt/Pi-Box')
if not os.path.exists('/opt/Pi-Box/dropbox.txt'):
print('Dropbox token file (dropbox.txt) not found.')
print('Authorize Pi-Box and obtain the token file: blah, blah, blah')
print('Save the file in: /opt/Pi-Box')
print('Run the installation script again: ./install.sh')
sys.exit()
print("Example Pi Box path: /home/username/my-pi-box")
pi_box_directory = raw_input("Pi Box path: ")
if not os.path.isdir(pi_box_directory):
os.makedirs(pi_box_directory)
with open('./install/pi-box-conf-template.txt', 'r') as f:
upstart_template = f.read()
with open('/etc/init/pi-box.conf', 'w+') as f:
f.write(upstart_template.format(pi_box_directory))
|
import os
import sys
import shutil
if not os.path.exists('/opt/Pi-Box'):
os.makedirs('/opt/Pi-Box')
shutil.copy('./main.py', '/opt/Pi-Box')
if not os.path.exists('/opt/Pi-Box/dropbox.txt'):
print('Authorize Pi-Box and obtain the token file: http://raspberry-pi-box.herokuapp.com/')
print('Copy Dropbox token file (dropbox.txt) to: /opt/Pi-Box.')
print('Run the installation script again: ./install.sh')
sys.exit()
print("Example Pi Box path: /home/username/my-pi-box")
pi_box_directory = raw_input("Pi Box path: ")
if not os.path.isdir(pi_box_directory):
os.makedirs(pi_box_directory)
with open('./install/pi-box-conf-template.txt', 'r') as f:
upstart_template = f.read()
with open('/etc/init/pi-box.conf', 'w+') as f:
f.write(upstart_template.format(pi_box_directory))
|
Add URL to setup script
|
Add URL to setup script
|
Python
|
mit
|
projectweekend/Pi-Box,projectweekend/Pi-Box
|
import os
import sys
import shutil
if not os.path.exists('/opt/Pi-Box'):
os.makedirs('/opt/Pi-Box')
shutil.copy('./main.py', '/opt/Pi-Box')
if not os.path.exists('/opt/Pi-Box/dropbox.txt'):
+ print('Authorize Pi-Box and obtain the token file: http://raspberry-pi-box.herokuapp.com/')
- print('Dropbox token file (dropbox.txt) not found.')
+ print('Copy Dropbox token file (dropbox.txt) to: /opt/Pi-Box.')
- print('Authorize Pi-Box and obtain the token file: blah, blah, blah')
- print('Save the file in: /opt/Pi-Box')
print('Run the installation script again: ./install.sh')
sys.exit()
print("Example Pi Box path: /home/username/my-pi-box")
pi_box_directory = raw_input("Pi Box path: ")
if not os.path.isdir(pi_box_directory):
os.makedirs(pi_box_directory)
with open('./install/pi-box-conf-template.txt', 'r') as f:
upstart_template = f.read()
with open('/etc/init/pi-box.conf', 'w+') as f:
f.write(upstart_template.format(pi_box_directory))
|
Add URL to setup script
|
## Code Before:
import os
import sys
import shutil
if not os.path.exists('/opt/Pi-Box'):
os.makedirs('/opt/Pi-Box')
shutil.copy('./main.py', '/opt/Pi-Box')
if not os.path.exists('/opt/Pi-Box/dropbox.txt'):
print('Dropbox token file (dropbox.txt) not found.')
print('Authorize Pi-Box and obtain the token file: blah, blah, blah')
print('Save the file in: /opt/Pi-Box')
print('Run the installation script again: ./install.sh')
sys.exit()
print("Example Pi Box path: /home/username/my-pi-box")
pi_box_directory = raw_input("Pi Box path: ")
if not os.path.isdir(pi_box_directory):
os.makedirs(pi_box_directory)
with open('./install/pi-box-conf-template.txt', 'r') as f:
upstart_template = f.read()
with open('/etc/init/pi-box.conf', 'w+') as f:
f.write(upstart_template.format(pi_box_directory))
## Instruction:
Add URL to setup script
## Code After:
import os
import sys
import shutil
if not os.path.exists('/opt/Pi-Box'):
os.makedirs('/opt/Pi-Box')
shutil.copy('./main.py', '/opt/Pi-Box')
if not os.path.exists('/opt/Pi-Box/dropbox.txt'):
print('Authorize Pi-Box and obtain the token file: http://raspberry-pi-box.herokuapp.com/')
print('Copy Dropbox token file (dropbox.txt) to: /opt/Pi-Box.')
print('Run the installation script again: ./install.sh')
sys.exit()
print("Example Pi Box path: /home/username/my-pi-box")
pi_box_directory = raw_input("Pi Box path: ")
if not os.path.isdir(pi_box_directory):
os.makedirs(pi_box_directory)
with open('./install/pi-box-conf-template.txt', 'r') as f:
upstart_template = f.read()
with open('/etc/init/pi-box.conf', 'w+') as f:
f.write(upstart_template.format(pi_box_directory))
|
# ... existing code ...
if not os.path.exists('/opt/Pi-Box/dropbox.txt'):
print('Authorize Pi-Box and obtain the token file: http://raspberry-pi-box.herokuapp.com/')
print('Copy Dropbox token file (dropbox.txt) to: /opt/Pi-Box.')
print('Run the installation script again: ./install.sh')
# ... rest of the code ...
|
080637c99898082d38b306ef73983552b263e628
|
inbox/ignition.py
|
inbox/ignition.py
|
from sqlalchemy import create_engine
from inbox.sqlalchemy_ext.util import ForceStrictMode
from inbox.config import db_uri, config
DB_POOL_SIZE = config.get_required('DB_POOL_SIZE')
def main_engine(pool_size=DB_POOL_SIZE, max_overflow=5):
engine = create_engine(db_uri(),
listeners=[ForceStrictMode()],
isolation_level='READ COMMITTED',
echo=False,
pool_size=pool_size,
max_overflow=max_overflow,
connect_args={'charset': 'utf8mb4'})
return engine
def init_db():
""" Make the tables.
This is called only from bin/create-db, which is run during setup.
Previously we allowed this to run everytime on startup, which broke some
alembic revisions by creating new tables before a migration was run.
From now on, we should ony be creating tables+columns via SQLalchemy *once*
and all subscequent changes done via migration scripts.
"""
from inbox.models.base import MailSyncBase
engine = main_engine(pool_size=1)
MailSyncBase.metadata.create_all(engine)
|
from sqlalchemy import create_engine
from inbox.sqlalchemy_ext.util import ForceStrictMode
from inbox.config import db_uri, config
DB_POOL_SIZE = config.get_required('DB_POOL_SIZE')
def main_engine(pool_size=DB_POOL_SIZE, max_overflow=5):
engine = create_engine(db_uri(),
listeners=[ForceStrictMode()],
isolation_level='READ COMMITTED',
echo=False,
pool_size=pool_size,
pool_recycle=3600,
max_overflow=max_overflow,
connect_args={'charset': 'utf8mb4'})
return engine
def init_db():
""" Make the tables.
This is called only from bin/create-db, which is run during setup.
Previously we allowed this to run everytime on startup, which broke some
alembic revisions by creating new tables before a migration was run.
From now on, we should ony be creating tables+columns via SQLalchemy *once*
and all subscequent changes done via migration scripts.
"""
from inbox.models.base import MailSyncBase
engine = main_engine(pool_size=1)
MailSyncBase.metadata.create_all(engine)
|
Set pool_recycle to deal with MySQL closing idle connections.
|
Set pool_recycle to deal with MySQL closing idle connections.
See http://docs.sqlalchemy.org/en/latest/dialects/mysql.html#connection-timeouts
Cherry-picking this onto master so it definitely gets deployed.
|
Python
|
agpl-3.0
|
Eagles2F/sync-engine,Eagles2F/sync-engine,ErinCall/sync-engine,ErinCall/sync-engine,ErinCall/sync-engine,PriviPK/privipk-sync-engine,closeio/nylas,Eagles2F/sync-engine,wakermahmud/sync-engine,Eagles2F/sync-engine,wakermahmud/sync-engine,jobscore/sync-engine,jobscore/sync-engine,Eagles2F/sync-engine,wakermahmud/sync-engine,PriviPK/privipk-sync-engine,jobscore/sync-engine,jobscore/sync-engine,ErinCall/sync-engine,wakermahmud/sync-engine,PriviPK/privipk-sync-engine,PriviPK/privipk-sync-engine,closeio/nylas,nylas/sync-engine,nylas/sync-engine,wakermahmud/sync-engine,EthanBlackburn/sync-engine,EthanBlackburn/sync-engine,nylas/sync-engine,PriviPK/privipk-sync-engine,EthanBlackburn/sync-engine,gale320/sync-engine,EthanBlackburn/sync-engine,gale320/sync-engine,ErinCall/sync-engine,gale320/sync-engine,closeio/nylas,EthanBlackburn/sync-engine,nylas/sync-engine,gale320/sync-engine,closeio/nylas,gale320/sync-engine
|
from sqlalchemy import create_engine
from inbox.sqlalchemy_ext.util import ForceStrictMode
from inbox.config import db_uri, config
DB_POOL_SIZE = config.get_required('DB_POOL_SIZE')
def main_engine(pool_size=DB_POOL_SIZE, max_overflow=5):
engine = create_engine(db_uri(),
listeners=[ForceStrictMode()],
isolation_level='READ COMMITTED',
echo=False,
pool_size=pool_size,
+ pool_recycle=3600,
max_overflow=max_overflow,
connect_args={'charset': 'utf8mb4'})
return engine
def init_db():
""" Make the tables.
This is called only from bin/create-db, which is run during setup.
Previously we allowed this to run everytime on startup, which broke some
alembic revisions by creating new tables before a migration was run.
From now on, we should ony be creating tables+columns via SQLalchemy *once*
and all subscequent changes done via migration scripts.
"""
from inbox.models.base import MailSyncBase
engine = main_engine(pool_size=1)
MailSyncBase.metadata.create_all(engine)
|
Set pool_recycle to deal with MySQL closing idle connections.
|
## Code Before:
from sqlalchemy import create_engine
from inbox.sqlalchemy_ext.util import ForceStrictMode
from inbox.config import db_uri, config
DB_POOL_SIZE = config.get_required('DB_POOL_SIZE')
def main_engine(pool_size=DB_POOL_SIZE, max_overflow=5):
engine = create_engine(db_uri(),
listeners=[ForceStrictMode()],
isolation_level='READ COMMITTED',
echo=False,
pool_size=pool_size,
max_overflow=max_overflow,
connect_args={'charset': 'utf8mb4'})
return engine
def init_db():
""" Make the tables.
This is called only from bin/create-db, which is run during setup.
Previously we allowed this to run everytime on startup, which broke some
alembic revisions by creating new tables before a migration was run.
From now on, we should ony be creating tables+columns via SQLalchemy *once*
and all subscequent changes done via migration scripts.
"""
from inbox.models.base import MailSyncBase
engine = main_engine(pool_size=1)
MailSyncBase.metadata.create_all(engine)
## Instruction:
Set pool_recycle to deal with MySQL closing idle connections.
## Code After:
from sqlalchemy import create_engine
from inbox.sqlalchemy_ext.util import ForceStrictMode
from inbox.config import db_uri, config
DB_POOL_SIZE = config.get_required('DB_POOL_SIZE')
def main_engine(pool_size=DB_POOL_SIZE, max_overflow=5):
engine = create_engine(db_uri(),
listeners=[ForceStrictMode()],
isolation_level='READ COMMITTED',
echo=False,
pool_size=pool_size,
pool_recycle=3600,
max_overflow=max_overflow,
connect_args={'charset': 'utf8mb4'})
return engine
def init_db():
""" Make the tables.
This is called only from bin/create-db, which is run during setup.
Previously we allowed this to run everytime on startup, which broke some
alembic revisions by creating new tables before a migration was run.
From now on, we should ony be creating tables+columns via SQLalchemy *once*
and all subscequent changes done via migration scripts.
"""
from inbox.models.base import MailSyncBase
engine = main_engine(pool_size=1)
MailSyncBase.metadata.create_all(engine)
|
# ... existing code ...
pool_size=pool_size,
pool_recycle=3600,
max_overflow=max_overflow,
# ... rest of the code ...
|
b352c3e1f5e8812d29f2e8a1bca807bea5da8cc4
|
test/test_hx_launcher.py
|
test/test_hx_launcher.py
|
import pytest_twisted
from hendrix.ux import main
from hendrix.options import HendrixOptionParser
def test_no_arguments_gives_help_text(mocker):
class MockFile(object):
@classmethod
def write(cls, whatever):
cls.things_written = whatever
class MockStdOut(object):
@classmethod
def write(cls, whatever):
HendrixOptionParser.print_help(MockFile)
assert MockFile.things_written == whatever
mocker.patch('sys.stdout', new=MockStdOut)
main([])
|
from hendrix.options import HendrixOptionParser
from hendrix.ux import main
def test_no_arguments_gives_help_text(mocker):
class MockFile(object):
@classmethod
def write(cls, whatever):
cls.things_written = whatever
class MockStdOut(object):
@classmethod
def write(cls, whatever):
HendrixOptionParser.print_help(MockFile)
assert MockFile.things_written == whatever
mocker.patch('sys.stdout', new=MockStdOut)
main([])
|
Test for the hx launcher.
|
Test for the hx launcher.
|
Python
|
mit
|
hangarunderground/hendrix,hendrix/hendrix,hangarunderground/hendrix,hendrix/hendrix,jMyles/hendrix,hendrix/hendrix,jMyles/hendrix,hangarunderground/hendrix,hangarunderground/hendrix,jMyles/hendrix
|
+ from hendrix.options import HendrixOptionParser
- import pytest_twisted
-
from hendrix.ux import main
- from hendrix.options import HendrixOptionParser
def test_no_arguments_gives_help_text(mocker):
-
class MockFile(object):
@classmethod
def write(cls, whatever):
cls.things_written = whatever
class MockStdOut(object):
@classmethod
def write(cls, whatever):
HendrixOptionParser.print_help(MockFile)
assert MockFile.things_written == whatever
mocker.patch('sys.stdout', new=MockStdOut)
main([])
|
Test for the hx launcher.
|
## Code Before:
import pytest_twisted
from hendrix.ux import main
from hendrix.options import HendrixOptionParser
def test_no_arguments_gives_help_text(mocker):
class MockFile(object):
@classmethod
def write(cls, whatever):
cls.things_written = whatever
class MockStdOut(object):
@classmethod
def write(cls, whatever):
HendrixOptionParser.print_help(MockFile)
assert MockFile.things_written == whatever
mocker.patch('sys.stdout', new=MockStdOut)
main([])
## Instruction:
Test for the hx launcher.
## Code After:
from hendrix.options import HendrixOptionParser
from hendrix.ux import main
def test_no_arguments_gives_help_text(mocker):
class MockFile(object):
@classmethod
def write(cls, whatever):
cls.things_written = whatever
class MockStdOut(object):
@classmethod
def write(cls, whatever):
HendrixOptionParser.print_help(MockFile)
assert MockFile.things_written == whatever
mocker.patch('sys.stdout', new=MockStdOut)
main([])
|
...
from hendrix.options import HendrixOptionParser
from hendrix.ux import main
...
def test_no_arguments_gives_help_text(mocker):
class MockFile(object):
...
|
05c057b44460eea6f6fe4a3dd891038d65e6d781
|
naxos/naxos/settings/secretKeyGen.py
|
naxos/naxos/settings/secretKeyGen.py
|
try:
SECRET_KEY
except NameError:
from os.path import join
from .base import BASE_DIR
SECRET_FILE = join(BASE_DIR, 'secret.txt')
try:
SECRET_KEY = open(SECRET_FILE).read().strip()
except IOError:
try:
import random
SECRET_KEY = ''.join([random.SystemRandom().choice(
'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)')
for i in range(50)])
secret = open(SECRET_FILE, 'w')
secret.write(SECRET_KEY)
secret.close()
except IOError:
Exception('Please create a {:s} file with random characters \
to generate your secret key!'.format(SECRET_FILE))
|
try:
SECRET_KEY
except NameError:
from os.path import join
from .base import BASE_DIR
SECRET_FILE = join(BASE_DIR, 'secret.txt')
try:
with open(SECRET_FILE) as f:
SECRET_KEY = f.read().strip()
except IOError:
try:
import random
SECRET_KEY = ''.join([random.SystemRandom().choice(
'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)')
for i in range(50)])
secret = open(SECRET_FILE, 'w')
secret.write(SECRET_KEY)
secret.close()
except IOError:
Exception('Please create a {:s} file with random characters \
to generate your secret key!'.format(SECRET_FILE))
|
Fix not closed file warning
|
fix: Fix not closed file warning
|
Python
|
apache-2.0
|
maur1th/naxos,maur1th/naxos,maur1th/naxos,maur1th/naxos
|
try:
SECRET_KEY
except NameError:
from os.path import join
from .base import BASE_DIR
SECRET_FILE = join(BASE_DIR, 'secret.txt')
try:
+ with open(SECRET_FILE) as f:
- SECRET_KEY = open(SECRET_FILE).read().strip()
+ SECRET_KEY = f.read().strip()
except IOError:
try:
import random
SECRET_KEY = ''.join([random.SystemRandom().choice(
'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)')
for i in range(50)])
secret = open(SECRET_FILE, 'w')
secret.write(SECRET_KEY)
secret.close()
except IOError:
Exception('Please create a {:s} file with random characters \
to generate your secret key!'.format(SECRET_FILE))
|
Fix not closed file warning
|
## Code Before:
try:
SECRET_KEY
except NameError:
from os.path import join
from .base import BASE_DIR
SECRET_FILE = join(BASE_DIR, 'secret.txt')
try:
SECRET_KEY = open(SECRET_FILE).read().strip()
except IOError:
try:
import random
SECRET_KEY = ''.join([random.SystemRandom().choice(
'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)')
for i in range(50)])
secret = open(SECRET_FILE, 'w')
secret.write(SECRET_KEY)
secret.close()
except IOError:
Exception('Please create a {:s} file with random characters \
to generate your secret key!'.format(SECRET_FILE))
## Instruction:
Fix not closed file warning
## Code After:
try:
SECRET_KEY
except NameError:
from os.path import join
from .base import BASE_DIR
SECRET_FILE = join(BASE_DIR, 'secret.txt')
try:
with open(SECRET_FILE) as f:
SECRET_KEY = f.read().strip()
except IOError:
try:
import random
SECRET_KEY = ''.join([random.SystemRandom().choice(
'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)')
for i in range(50)])
secret = open(SECRET_FILE, 'w')
secret.write(SECRET_KEY)
secret.close()
except IOError:
Exception('Please create a {:s} file with random characters \
to generate your secret key!'.format(SECRET_FILE))
|
...
try:
with open(SECRET_FILE) as f:
SECRET_KEY = f.read().strip()
except IOError:
...
|
fc6042cf57752ca139c52889ec5e00c02b618d0d
|
setup.py
|
setup.py
|
from distutils.core import setup, Command
class PyTest(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
import sys
import subprocess
errno = subprocess.call([sys.executable, 'runtests.py'])
raise SystemExit(errno)
with open('README.rst') as file:
long_description = file.read()
setup(
name='webpay',
packages=['webpay'],
version='0.1.0',
author='webpay',
author_email='[email protected]',
url='https://github.com/webpay/webpay-python',
description='WebPay Python bindings',
cmdclass={'test': PyTest},
long_description=long_description,
classifiers=[
'Development Status :: 4 - Beta',
'Operating System :: OS Independent',
'License :: OSI Approved :: MIT License',
'Intended Audience :: Developers',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: Implementation :: CPython',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Software Development :: Libraries :: Python Modules'
],
requires=[
'requests (== 2.0.1)'
]
)
|
from distutils.core import setup, Command
class PyTest(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
import sys
import subprocess
errno = subprocess.call([sys.executable, 'runtests.py'])
raise SystemExit(errno)
with open('README.rst') as file:
long_description = file.read()
setup(
name='webpay',
packages=['webpay', 'webpay.api', 'webpay.model'],
version='0.1.0',
author='webpay',
author_email='[email protected]',
url='https://github.com/webpay/webpay-python',
description='WebPay Python bindings',
cmdclass={'test': PyTest},
long_description=long_description,
classifiers=[
'Development Status :: 4 - Beta',
'Operating System :: OS Independent',
'License :: OSI Approved :: MIT License',
'Intended Audience :: Developers',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: Implementation :: CPython',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Software Development :: Libraries :: Python Modules'
],
requires=[
'requests (== 2.0.1)'
]
)
|
Add api and model to packages
|
Add api and model to packages
|
Python
|
mit
|
yamaneko1212/webpay-python
|
from distutils.core import setup, Command
class PyTest(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
import sys
import subprocess
errno = subprocess.call([sys.executable, 'runtests.py'])
raise SystemExit(errno)
with open('README.rst') as file:
long_description = file.read()
setup(
name='webpay',
- packages=['webpay'],
+ packages=['webpay', 'webpay.api', 'webpay.model'],
version='0.1.0',
author='webpay',
author_email='[email protected]',
url='https://github.com/webpay/webpay-python',
description='WebPay Python bindings',
cmdclass={'test': PyTest},
long_description=long_description,
classifiers=[
'Development Status :: 4 - Beta',
'Operating System :: OS Independent',
'License :: OSI Approved :: MIT License',
'Intended Audience :: Developers',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: Implementation :: CPython',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Software Development :: Libraries :: Python Modules'
],
requires=[
'requests (== 2.0.1)'
]
)
|
Add api and model to packages
|
## Code Before:
from distutils.core import setup, Command
class PyTest(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
import sys
import subprocess
errno = subprocess.call([sys.executable, 'runtests.py'])
raise SystemExit(errno)
with open('README.rst') as file:
long_description = file.read()
setup(
name='webpay',
packages=['webpay'],
version='0.1.0',
author='webpay',
author_email='[email protected]',
url='https://github.com/webpay/webpay-python',
description='WebPay Python bindings',
cmdclass={'test': PyTest},
long_description=long_description,
classifiers=[
'Development Status :: 4 - Beta',
'Operating System :: OS Independent',
'License :: OSI Approved :: MIT License',
'Intended Audience :: Developers',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: Implementation :: CPython',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Software Development :: Libraries :: Python Modules'
],
requires=[
'requests (== 2.0.1)'
]
)
## Instruction:
Add api and model to packages
## Code After:
from distutils.core import setup, Command
class PyTest(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
import sys
import subprocess
errno = subprocess.call([sys.executable, 'runtests.py'])
raise SystemExit(errno)
with open('README.rst') as file:
long_description = file.read()
setup(
name='webpay',
packages=['webpay', 'webpay.api', 'webpay.model'],
version='0.1.0',
author='webpay',
author_email='[email protected]',
url='https://github.com/webpay/webpay-python',
description='WebPay Python bindings',
cmdclass={'test': PyTest},
long_description=long_description,
classifiers=[
'Development Status :: 4 - Beta',
'Operating System :: OS Independent',
'License :: OSI Approved :: MIT License',
'Intended Audience :: Developers',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: Implementation :: CPython',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Software Development :: Libraries :: Python Modules'
],
requires=[
'requests (== 2.0.1)'
]
)
|
...
name='webpay',
packages=['webpay', 'webpay.api', 'webpay.model'],
version='0.1.0',
...
|
28353efe2802059c1da8b1c81b157dc6e773032e
|
salt/modules/monit.py
|
salt/modules/monit.py
|
'''
Salt module to manage monit
'''
def version():
'''
List monit version
Cli Example::
salt '*' monit.version
'''
cmd = 'monit -V'
res = __salt__['cmd.run'](cmd)
return res.split("\n")[0]
def status():
'''
Monit status
CLI Example::
salt '*' monit.status
'''
cmd = 'monit status'
res = __salt__['cmd.run'](cmd)
return res.split("\n")
def start():
'''
Starts monit
CLI Example::
salt '*' monit.start
*Note need to add check to insure its running*
`ps ax | grep monit | grep -v grep or something`
'''
cmd = 'monit'
res = __salt__['cmd.run'](cmd)
return "Monit started"
def stop():
'''
Stop monit
CLI Example::
salt '*' monit.stop
*Note Needs check as above*
'''
def _is_bsd():
return True if __grains__['os'] == 'FreeBSD' else False
if _is_bsd():
cmd = "/usr/local/etc/rc.d/monit stop"
else:
cmd = "/etc/init.d/monit stop"
res = __salt__['cmd.run'](cmd)
return "Monit Stopped"
def monitor_all():
'''
Initializing all monit modules.
'''
cmd = 'monit monitor all'
res = __salt__['cmd.run'](cmd)
if res:
return "All Services initaialized"
return "Issue starting monitoring on all services"
def unmonitor_all():
'''
unmonitor all services.
'''
cmd = 'monit unmonitor all'
res = __salt__['cmd.run'](cmd)
if res:
return "All Services unmonitored"
return "Issue unmonitoring all services"
|
'''
Monit service module. This module will create a monit type
service watcher.
'''
import os
def start(name):
'''
CLI Example::
salt '*' monit.start <service name>
'''
cmd = "monit start {0}".format(name)
return not __salt__['cmd.retcode'](cmd)
def stop(name):
'''
Stops service via monit
CLI Example::
salt '*' monit.stop <service name>
'''
cmd = "monit stop {0}".format(name)
return not __salt__['cmd.retcode'](cmd)
def restart(name):
'''
Restart service via monit
CLI Example::
salt '*' monit.restart <service name>
'''
cmd = "monit restart {0}".format(name)
return not __salt__['cmd.retcode'](cmd)
|
Check to see if we are going donw the right path
|
Check to see if we are going donw the right path
|
Python
|
apache-2.0
|
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
|
'''
- Salt module to manage monit
+ Monit service module. This module will create a monit type
+ service watcher.
'''
- def version():
+ import os
+
+ def start(name):
'''
- List monit version
+
+ CLI Example::
+ salt '*' monit.start <service name>
+ '''
+ cmd = "monit start {0}".format(name)
- Cli Example::
-
- salt '*' monit.version
- '''
-
- cmd = 'monit -V'
- res = __salt__['cmd.run'](cmd)
+ return not __salt__['cmd.retcode'](cmd)
- return res.split("\n")[0]
- def status():
+ def stop(name):
'''
- Monit status
+ Stops service via monit
CLI Example::
- salt '*' monit.status
+ salt '*' monit.stop <service name>
'''
+ cmd = "monit stop {0}".format(name)
- cmd = 'monit status'
- res = __salt__['cmd.run'](cmd)
- return res.split("\n")
+ return not __salt__['cmd.retcode'](cmd)
+
+
- def start():
+ def restart(name):
'''
- Starts monit
+ Restart service via monit
CLI Example::
- salt '*' monit.start
+ salt '*' monit.restart <service name>
- *Note need to add check to insure its running*
- `ps ax | grep monit | grep -v grep or something`
'''
- cmd = 'monit'
+ cmd = "monit restart {0}".format(name)
+
- res = __salt__['cmd.run'](cmd)
+ return not __salt__['cmd.retcode'](cmd)
- return "Monit started"
- def stop():
- '''
- Stop monit
-
- CLI Example::
-
- salt '*' monit.stop
- *Note Needs check as above*
- '''
- def _is_bsd():
- return True if __grains__['os'] == 'FreeBSD' else False
-
- if _is_bsd():
- cmd = "/usr/local/etc/rc.d/monit stop"
- else:
- cmd = "/etc/init.d/monit stop"
- res = __salt__['cmd.run'](cmd)
- return "Monit Stopped"
-
-
- def monitor_all():
- '''
- Initializing all monit modules.
- '''
- cmd = 'monit monitor all'
- res = __salt__['cmd.run'](cmd)
- if res:
- return "All Services initaialized"
- return "Issue starting monitoring on all services"
-
-
- def unmonitor_all():
- '''
- unmonitor all services.
- '''
- cmd = 'monit unmonitor all'
- res = __salt__['cmd.run'](cmd)
- if res:
- return "All Services unmonitored"
- return "Issue unmonitoring all services"
-
|
Check to see if we are going donw the right path
|
## Code Before:
'''
Salt module to manage monit
'''
def version():
'''
List monit version
Cli Example::
salt '*' monit.version
'''
cmd = 'monit -V'
res = __salt__['cmd.run'](cmd)
return res.split("\n")[0]
def status():
'''
Monit status
CLI Example::
salt '*' monit.status
'''
cmd = 'monit status'
res = __salt__['cmd.run'](cmd)
return res.split("\n")
def start():
'''
Starts monit
CLI Example::
salt '*' monit.start
*Note need to add check to insure its running*
`ps ax | grep monit | grep -v grep or something`
'''
cmd = 'monit'
res = __salt__['cmd.run'](cmd)
return "Monit started"
def stop():
'''
Stop monit
CLI Example::
salt '*' monit.stop
*Note Needs check as above*
'''
def _is_bsd():
return True if __grains__['os'] == 'FreeBSD' else False
if _is_bsd():
cmd = "/usr/local/etc/rc.d/monit stop"
else:
cmd = "/etc/init.d/monit stop"
res = __salt__['cmd.run'](cmd)
return "Monit Stopped"
def monitor_all():
'''
Initializing all monit modules.
'''
cmd = 'monit monitor all'
res = __salt__['cmd.run'](cmd)
if res:
return "All Services initaialized"
return "Issue starting monitoring on all services"
def unmonitor_all():
'''
unmonitor all services.
'''
cmd = 'monit unmonitor all'
res = __salt__['cmd.run'](cmd)
if res:
return "All Services unmonitored"
return "Issue unmonitoring all services"
## Instruction:
Check to see if we are going donw the right path
## Code After:
'''
Monit service module. This module will create a monit type
service watcher.
'''
import os
def start(name):
'''
CLI Example::
salt '*' monit.start <service name>
'''
cmd = "monit start {0}".format(name)
return not __salt__['cmd.retcode'](cmd)
def stop(name):
'''
Stops service via monit
CLI Example::
salt '*' monit.stop <service name>
'''
cmd = "monit stop {0}".format(name)
return not __salt__['cmd.retcode'](cmd)
def restart(name):
'''
Restart service via monit
CLI Example::
salt '*' monit.restart <service name>
'''
cmd = "monit restart {0}".format(name)
return not __salt__['cmd.retcode'](cmd)
|
...
'''
Monit service module. This module will create a monit type
service watcher.
'''
...
import os
def start(name):
'''
CLI Example::
salt '*' monit.start <service name>
'''
cmd = "monit start {0}".format(name)
return not __salt__['cmd.retcode'](cmd)
...
def stop(name):
'''
Stops service via monit
...
salt '*' monit.stop <service name>
'''
cmd = "monit stop {0}".format(name)
...
return not __salt__['cmd.retcode'](cmd)
def restart(name):
'''
Restart service via monit
...
salt '*' monit.restart <service name>
'''
cmd = "monit restart {0}".format(name)
return not __salt__['cmd.retcode'](cmd)
...
|
7cf58ed386028a616c2083364d3f5c92e0c0ade3
|
examples/hello_world/hello_world.py
|
examples/hello_world/hello_world.py
|
# Third Party Libs
from flask import Flask
from flask_hal import HAL, document
app = Flask(__name__)
HAL(app) # Initialise HAL
@app.route('/foo')
def foo():
d = document.Document(data={
'foo': 'bar'
})
return d.to_json()
if __name__ == "__main__":
app.run()
|
# Third Party Libs
from flask import Flask
from flask_hal import HAL, document
app = Flask(__name__)
HAL(app) # Initialise HAL
@app.route('/hello')
def foo():
return document.Document(data={
'message': 'Hello World'
})
if __name__ == "__main__":
app.run()
|
Update to hello world example
|
Update to hello world example
|
Python
|
unlicense
|
thisissoon/Flask-HAL,thisissoon/Flask-HAL
|
# Third Party Libs
from flask import Flask
from flask_hal import HAL, document
app = Flask(__name__)
HAL(app) # Initialise HAL
- @app.route('/foo')
+ @app.route('/hello')
def foo():
- d = document.Document(data={
+ return document.Document(data={
- 'foo': 'bar'
+ 'message': 'Hello World'
})
- return d.to_json()
if __name__ == "__main__":
app.run()
|
Update to hello world example
|
## Code Before:
# Third Party Libs
from flask import Flask
from flask_hal import HAL, document
app = Flask(__name__)
HAL(app) # Initialise HAL
@app.route('/foo')
def foo():
d = document.Document(data={
'foo': 'bar'
})
return d.to_json()
if __name__ == "__main__":
app.run()
## Instruction:
Update to hello world example
## Code After:
# Third Party Libs
from flask import Flask
from flask_hal import HAL, document
app = Flask(__name__)
HAL(app) # Initialise HAL
@app.route('/hello')
def foo():
return document.Document(data={
'message': 'Hello World'
})
if __name__ == "__main__":
app.run()
|
# ... existing code ...
@app.route('/hello')
def foo():
return document.Document(data={
'message': 'Hello World'
})
# ... modified code ...
# ... rest of the code ...
|
86678fce3817388641db3d0f4002b3f8d409377d
|
pdcupdater/tests/handler_tests/test_kerberos_auth.py
|
pdcupdater/tests/handler_tests/test_kerberos_auth.py
|
import pytest
import requests_kerberos
from mock import patch, Mock
import pdcupdater.utils
from test.test_support import EnvironmentVarGuard
import os
class TestKerberosAuthentication(object):
@patch('os.path.exists', return_value=True)
@patch('requests_kerberos.HTTPKerberosAuth')
@patch('requests.get')
def test_get_token(self, requests_get, kerb_auth, os_path):
self.url = 'https://pdc.fedoraproject.org/rest_api/v1/'
set_env=patch.dict(os.environ,{'KRB5_CLIENT_KTNAME': '/etc/foo.keytab'})
requests_rv = Mock()
requests_rv.json.return_value = {"token": "12345"}
requests_get.return_value = requests_rv
set_env.start()
rv = pdcupdater.utils.get_token(self.url,
'/etc/foo.keytab')
set_env.stop()
assert rv == '12345'
|
import os
from mock import patch, Mock
import pdcupdater.utils
class TestKerberosAuthentication(object):
@patch('os.path.exists', return_value=True)
@patch('requests_kerberos.HTTPKerberosAuth')
@patch('requests.get')
def test_get_token(self, requests_get, kerb_auth, os_path):
self.url = 'https://pdc.fedoraproject.org/rest_api/v1/'
set_env = patch.dict(
os.environ, {'KRB5_CLIENT_KTNAME': '/etc/foo.keytab'})
requests_rv = Mock()
requests_rv.json.return_value = {"token": "12345"}
requests_get.return_value = requests_rv
set_env.start()
rv = pdcupdater.utils.get_token(self.url, '/etc/foo.keytab')
set_env.stop()
assert rv == '12345'
|
Remove invalid imports for TestKerberosAuthentication and fix its styling
|
Remove invalid imports for TestKerberosAuthentication and fix its styling
|
Python
|
lgpl-2.1
|
fedora-infra/pdc-updater
|
- import pytest
- import requests_kerberos
- from mock import patch, Mock
- import pdcupdater.utils
- from test.test_support import EnvironmentVarGuard
import os
+ from mock import patch, Mock
+
+ import pdcupdater.utils
+
+
class TestKerberosAuthentication(object):
+ @patch('os.path.exists', return_value=True)
+ @patch('requests_kerberos.HTTPKerberosAuth')
+ @patch('requests.get')
+ def test_get_token(self, requests_get, kerb_auth, os_path):
+ self.url = 'https://pdc.fedoraproject.org/rest_api/v1/'
+ set_env = patch.dict(
+ os.environ, {'KRB5_CLIENT_KTNAME': '/etc/foo.keytab'})
+ requests_rv = Mock()
+ requests_rv.json.return_value = {"token": "12345"}
+ requests_get.return_value = requests_rv
+ set_env.start()
+ rv = pdcupdater.utils.get_token(self.url, '/etc/foo.keytab')
+ set_env.stop()
+ assert rv == '12345'
- @patch('os.path.exists', return_value=True)
- @patch('requests_kerberos.HTTPKerberosAuth')
- @patch('requests.get')
- def test_get_token(self, requests_get, kerb_auth, os_path):
- self.url = 'https://pdc.fedoraproject.org/rest_api/v1/'
- set_env=patch.dict(os.environ,{'KRB5_CLIENT_KTNAME': '/etc/foo.keytab'})
- requests_rv = Mock()
- requests_rv.json.return_value = {"token": "12345"}
- requests_get.return_value = requests_rv
- set_env.start()
- rv = pdcupdater.utils.get_token(self.url,
- '/etc/foo.keytab')
- set_env.stop()
- assert rv == '12345'
-
|
Remove invalid imports for TestKerberosAuthentication and fix its styling
|
## Code Before:
import pytest
import requests_kerberos
from mock import patch, Mock
import pdcupdater.utils
from test.test_support import EnvironmentVarGuard
import os
class TestKerberosAuthentication(object):
@patch('os.path.exists', return_value=True)
@patch('requests_kerberos.HTTPKerberosAuth')
@patch('requests.get')
def test_get_token(self, requests_get, kerb_auth, os_path):
self.url = 'https://pdc.fedoraproject.org/rest_api/v1/'
set_env=patch.dict(os.environ,{'KRB5_CLIENT_KTNAME': '/etc/foo.keytab'})
requests_rv = Mock()
requests_rv.json.return_value = {"token": "12345"}
requests_get.return_value = requests_rv
set_env.start()
rv = pdcupdater.utils.get_token(self.url,
'/etc/foo.keytab')
set_env.stop()
assert rv == '12345'
## Instruction:
Remove invalid imports for TestKerberosAuthentication and fix its styling
## Code After:
import os
from mock import patch, Mock
import pdcupdater.utils
class TestKerberosAuthentication(object):
@patch('os.path.exists', return_value=True)
@patch('requests_kerberos.HTTPKerberosAuth')
@patch('requests.get')
def test_get_token(self, requests_get, kerb_auth, os_path):
self.url = 'https://pdc.fedoraproject.org/rest_api/v1/'
set_env = patch.dict(
os.environ, {'KRB5_CLIENT_KTNAME': '/etc/foo.keytab'})
requests_rv = Mock()
requests_rv.json.return_value = {"token": "12345"}
requests_get.return_value = requests_rv
set_env.start()
rv = pdcupdater.utils.get_token(self.url, '/etc/foo.keytab')
set_env.stop()
assert rv == '12345'
|
...
import os
...
from mock import patch, Mock
import pdcupdater.utils
class TestKerberosAuthentication(object):
@patch('os.path.exists', return_value=True)
@patch('requests_kerberos.HTTPKerberosAuth')
@patch('requests.get')
def test_get_token(self, requests_get, kerb_auth, os_path):
self.url = 'https://pdc.fedoraproject.org/rest_api/v1/'
set_env = patch.dict(
os.environ, {'KRB5_CLIENT_KTNAME': '/etc/foo.keytab'})
requests_rv = Mock()
requests_rv.json.return_value = {"token": "12345"}
requests_get.return_value = requests_rv
set_env.start()
rv = pdcupdater.utils.get_token(self.url, '/etc/foo.keytab')
set_env.stop()
assert rv == '12345'
...
|
896f7b82eb1c84538a94e65d8ff55282e36c6818
|
squadron/exthandlers/__init__.py
|
squadron/exthandlers/__init__.py
|
from .dir import ext_dir
from .makegit import ext_git
from .download import ext_download
from .template import ext_template
extension_handles = {
'dir':ext_dir,
'git':ext_git,
'download':ext_download,
'virtualenv',ext_virtualenv,
'tpl':ext_template
}
|
from .dir import ext_dir
from .makegit import ext_git
from .download import ext_download
from .template import ext_template
from .virtualenv import ext_virtualenv
extension_handles = {
'dir':ext_dir,
'git':ext_git,
'download':ext_download,
'virtualenv':ext_virtualenv,
'tpl':ext_template
}
|
Fix broken tests because of virtualenv handler
|
Fix broken tests because of virtualenv handler
|
Python
|
mit
|
gosquadron/squadron,gosquadron/squadron
|
from .dir import ext_dir
from .makegit import ext_git
from .download import ext_download
from .template import ext_template
+ from .virtualenv import ext_virtualenv
extension_handles = {
'dir':ext_dir,
'git':ext_git,
'download':ext_download,
- 'virtualenv',ext_virtualenv,
+ 'virtualenv':ext_virtualenv,
'tpl':ext_template
}
|
Fix broken tests because of virtualenv handler
|
## Code Before:
from .dir import ext_dir
from .makegit import ext_git
from .download import ext_download
from .template import ext_template
extension_handles = {
'dir':ext_dir,
'git':ext_git,
'download':ext_download,
'virtualenv',ext_virtualenv,
'tpl':ext_template
}
## Instruction:
Fix broken tests because of virtualenv handler
## Code After:
from .dir import ext_dir
from .makegit import ext_git
from .download import ext_download
from .template import ext_template
from .virtualenv import ext_virtualenv
extension_handles = {
'dir':ext_dir,
'git':ext_git,
'download':ext_download,
'virtualenv':ext_virtualenv,
'tpl':ext_template
}
|
// ... existing code ...
from .template import ext_template
from .virtualenv import ext_virtualenv
// ... modified code ...
'download':ext_download,
'virtualenv':ext_virtualenv,
'tpl':ext_template
// ... rest of the code ...
|
8c6ff33c8a034c2eecf5f2244811c86acf96120a
|
tools/apollo/list_organisms.py
|
tools/apollo/list_organisms.py
|
from __future__ import print_function
import argparse
import json
from webapollo import AssertUser, WAAuth, WebApolloInstance, accessible_organisms, PasswordGenerator
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='List all organisms available in an Apollo instance')
WAAuth(parser)
parser.add_argument('email', help='User Email')
args = parser.parse_args()
wa = WebApolloInstance(args.apollo, args.username, args.password)
try:
gx_user = AssertUser(wa.users.loadUsers(email=args.email))
except Exception:
returnData = wa.users.createUser(args.email, args.email, args.email, PasswordGenerator(12), role='user', addToHistory=True)
gx_user = AssertUser(wa.users.loadUsers(email=args.email))
all_orgs = wa.organisms.findAllOrganisms()
orgs = accessible_organisms(gx_user, all_orgs)
print(json.dumps(orgs, indent=2))
|
from __future__ import print_function
import argparse
import json
from webapollo import AssertUser, WAAuth, WebApolloInstance, accessible_organisms, PasswordGenerator
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='List all organisms available in an Apollo instance')
WAAuth(parser)
parser.add_argument('email', help='User Email')
args = parser.parse_args()
wa = WebApolloInstance(args.apollo, args.username, args.password)
try:
gx_user = AssertUser(wa.users.loadUsers(email=args.email))
except Exception:
returnData = wa.users.createUser(args.email, args.email, args.email, PasswordGenerator(12), role='user', addToHistory=True)
gx_user = AssertUser(wa.users.loadUsers(email=args.email))
all_orgs = wa.organisms.findAllOrganisms()
try:
orgs = accessible_organisms(gx_user, all_orgs)
except Exception:
orgs = []
print(json.dumps(orgs, indent=2))
|
Add try-catch if no organism allowed
|
Add try-catch if no organism allowed
|
Python
|
mit
|
galaxy-genome-annotation/galaxy-tools,galaxy-genome-annotation/galaxy-tools
|
from __future__ import print_function
import argparse
import json
from webapollo import AssertUser, WAAuth, WebApolloInstance, accessible_organisms, PasswordGenerator
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='List all organisms available in an Apollo instance')
WAAuth(parser)
parser.add_argument('email', help='User Email')
args = parser.parse_args()
wa = WebApolloInstance(args.apollo, args.username, args.password)
try:
gx_user = AssertUser(wa.users.loadUsers(email=args.email))
except Exception:
returnData = wa.users.createUser(args.email, args.email, args.email, PasswordGenerator(12), role='user', addToHistory=True)
gx_user = AssertUser(wa.users.loadUsers(email=args.email))
all_orgs = wa.organisms.findAllOrganisms()
+ try:
- orgs = accessible_organisms(gx_user, all_orgs)
+ orgs = accessible_organisms(gx_user, all_orgs)
+ except Exception:
+ orgs = []
print(json.dumps(orgs, indent=2))
|
Add try-catch if no organism allowed
|
## Code Before:
from __future__ import print_function
import argparse
import json
from webapollo import AssertUser, WAAuth, WebApolloInstance, accessible_organisms, PasswordGenerator
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='List all organisms available in an Apollo instance')
WAAuth(parser)
parser.add_argument('email', help='User Email')
args = parser.parse_args()
wa = WebApolloInstance(args.apollo, args.username, args.password)
try:
gx_user = AssertUser(wa.users.loadUsers(email=args.email))
except Exception:
returnData = wa.users.createUser(args.email, args.email, args.email, PasswordGenerator(12), role='user', addToHistory=True)
gx_user = AssertUser(wa.users.loadUsers(email=args.email))
all_orgs = wa.organisms.findAllOrganisms()
orgs = accessible_organisms(gx_user, all_orgs)
print(json.dumps(orgs, indent=2))
## Instruction:
Add try-catch if no organism allowed
## Code After:
from __future__ import print_function
import argparse
import json
from webapollo import AssertUser, WAAuth, WebApolloInstance, accessible_organisms, PasswordGenerator
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='List all organisms available in an Apollo instance')
WAAuth(parser)
parser.add_argument('email', help='User Email')
args = parser.parse_args()
wa = WebApolloInstance(args.apollo, args.username, args.password)
try:
gx_user = AssertUser(wa.users.loadUsers(email=args.email))
except Exception:
returnData = wa.users.createUser(args.email, args.email, args.email, PasswordGenerator(12), role='user', addToHistory=True)
gx_user = AssertUser(wa.users.loadUsers(email=args.email))
all_orgs = wa.organisms.findAllOrganisms()
try:
orgs = accessible_organisms(gx_user, all_orgs)
except Exception:
orgs = []
print(json.dumps(orgs, indent=2))
|
// ... existing code ...
try:
orgs = accessible_organisms(gx_user, all_orgs)
except Exception:
orgs = []
// ... rest of the code ...
|
d6f13599f47ff4b4926d07d79962d3fff36ab6c4
|
gradebook/__init__.py
|
gradebook/__init__.py
|
from collections import OrderedDict
import os
import sys
import json
try:
gb_home = os.environ["GB_HOME"]
except KeyError:
raise RuntimeError("Please set the environment variable GB_HOME")
repo_dir = os.path.join(gb_home, 'repos')
data_dir = os.path.join(gb_home, 'data')
log_dir = os.path.join(gb_home, 'log')
grade_file = 'grades.json'
instructor_home = os.path.join(repo_dir, 'instructor', 'assignments')
student_grades = grade_file
class_grades = os.path.join(data_dir, grade_file)
config_file = os.path.join(data_dir, 'config.json')
class_log = os.path.join(log_dir, 'grade.log')
def get_grades(filename=class_grades):
try:
with open(filename) as infile:
grades = json.load(infile, object_pairs_hook=OrderedDict)
except:
print("Trouble loading " + filename)
sys.exit(1)
return grades
def save_grades(content, filename):
with open(filename, 'w') as outfile:
json.dump(content, outfile, indent=4)
grades = get_grades()
|
from collections import OrderedDict
import os
import sys
import json
try:
gb_home = os.environ["GB_HOME"]
except KeyError:
raise RuntimeError("Please set the environment variable GB_HOME")
repo_dir = os.path.join(gb_home, 'repos')
data_dir = os.path.join(gb_home, 'data')
log_dir = os.path.join(gb_home, 'log')
grade_file = 'grades.json'
instructor_home = os.path.join(repo_dir, 'instructor', 'assignments')
student_grades = grade_file
class_grades = os.path.join(data_dir, grade_file)
config_file = os.path.join(data_dir, 'config.json')
csv_file = os.path.join(data_home, 'grades.csv')
class_log = os.path.join(log_dir, 'grade.log')
def get_grades(filename=class_grades):
try:
with open(filename) as infile:
grades = json.load(infile, object_pairs_hook=OrderedDict)
except:
print("Trouble loading " + filename)
sys.exit(1)
return grades
def save_grades(content, filename):
with open(filename, 'w') as outfile:
json.dump(content, outfile, indent=4)
grades = get_grades()
|
Add placeholder for CSV file
|
Add placeholder for CSV file
|
Python
|
bsd-2-clause
|
jarrodmillman/gradebook
|
from collections import OrderedDict
import os
import sys
import json
try:
gb_home = os.environ["GB_HOME"]
except KeyError:
raise RuntimeError("Please set the environment variable GB_HOME")
repo_dir = os.path.join(gb_home, 'repos')
data_dir = os.path.join(gb_home, 'data')
log_dir = os.path.join(gb_home, 'log')
grade_file = 'grades.json'
instructor_home = os.path.join(repo_dir, 'instructor', 'assignments')
student_grades = grade_file
class_grades = os.path.join(data_dir, grade_file)
config_file = os.path.join(data_dir, 'config.json')
+ csv_file = os.path.join(data_home, 'grades.csv')
class_log = os.path.join(log_dir, 'grade.log')
def get_grades(filename=class_grades):
try:
with open(filename) as infile:
grades = json.load(infile, object_pairs_hook=OrderedDict)
except:
print("Trouble loading " + filename)
sys.exit(1)
return grades
def save_grades(content, filename):
with open(filename, 'w') as outfile:
json.dump(content, outfile, indent=4)
grades = get_grades()
|
Add placeholder for CSV file
|
## Code Before:
from collections import OrderedDict
import os
import sys
import json
try:
gb_home = os.environ["GB_HOME"]
except KeyError:
raise RuntimeError("Please set the environment variable GB_HOME")
repo_dir = os.path.join(gb_home, 'repos')
data_dir = os.path.join(gb_home, 'data')
log_dir = os.path.join(gb_home, 'log')
grade_file = 'grades.json'
instructor_home = os.path.join(repo_dir, 'instructor', 'assignments')
student_grades = grade_file
class_grades = os.path.join(data_dir, grade_file)
config_file = os.path.join(data_dir, 'config.json')
class_log = os.path.join(log_dir, 'grade.log')
def get_grades(filename=class_grades):
try:
with open(filename) as infile:
grades = json.load(infile, object_pairs_hook=OrderedDict)
except:
print("Trouble loading " + filename)
sys.exit(1)
return grades
def save_grades(content, filename):
with open(filename, 'w') as outfile:
json.dump(content, outfile, indent=4)
grades = get_grades()
## Instruction:
Add placeholder for CSV file
## Code After:
from collections import OrderedDict
import os
import sys
import json
try:
gb_home = os.environ["GB_HOME"]
except KeyError:
raise RuntimeError("Please set the environment variable GB_HOME")
repo_dir = os.path.join(gb_home, 'repos')
data_dir = os.path.join(gb_home, 'data')
log_dir = os.path.join(gb_home, 'log')
grade_file = 'grades.json'
instructor_home = os.path.join(repo_dir, 'instructor', 'assignments')
student_grades = grade_file
class_grades = os.path.join(data_dir, grade_file)
config_file = os.path.join(data_dir, 'config.json')
csv_file = os.path.join(data_home, 'grades.csv')
class_log = os.path.join(log_dir, 'grade.log')
def get_grades(filename=class_grades):
try:
with open(filename) as infile:
grades = json.load(infile, object_pairs_hook=OrderedDict)
except:
print("Trouble loading " + filename)
sys.exit(1)
return grades
def save_grades(content, filename):
with open(filename, 'w') as outfile:
json.dump(content, outfile, indent=4)
grades = get_grades()
|
// ... existing code ...
config_file = os.path.join(data_dir, 'config.json')
csv_file = os.path.join(data_home, 'grades.csv')
// ... rest of the code ...
|
b785fdc041a41f06c10e08d1e4e4b2bd4a5e5f90
|
tests/test_uploader.py
|
tests/test_uploader.py
|
"""Tests for the uploader module"""
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from builtins import open
from future import standard_library
standard_library.install_aliases()
from os.path import join
from datapackage import DataPackage
from pytest import fixture
from json import loads
from gobble.config import ASSETS_DIR
from gobble.uploader import Uploader
from gobble.user import User
@fixture
def user():
return User()
@fixture
def package():
filepath = join(ASSETS_DIR, 'mexican-budget-samples', 'datapackage.json')
return DataPackage(filepath)
# noinspection PyShadowingNames
def test_build_payloads(user, package):
uploader = Uploader(user, package)
expected = join(ASSETS_DIR, 'mexican-budget-samples', 'payload.json')
with open(expected) as json:
assert uploader.payload == loads(json.read())
|
"""Tests for the uploader module"""
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from datapackage import DataPackage
from future import standard_library
from gobble.user import User
standard_library.install_aliases()
from json import loads
from io import open
from gobble.uploader import Uploader
# noinspection PyUnresolvedReferences
from tests.fixtures import (dummy_requests,
ROOT_DIR,
PACKAGE_FILE,
UPLOADER_PAYLOAD)
# noinspection PyShadowingNames
def test_build_payloads(dummy_requests):
with dummy_requests:
user = User()
package = DataPackage(PACKAGE_FILE)
uploader = Uploader(user, package)
with open(UPLOADER_PAYLOAD) as json:
assert uploader.payload == loads(json.read())
|
Refactor uploader tests to use the fixture module.
|
Refactor uploader tests to use the fixture module.
|
Python
|
mit
|
openspending/gobble
|
"""Tests for the uploader module"""
+
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
- from builtins import open
+ from datapackage import DataPackage
from future import standard_library
+
+ from gobble.user import User
standard_library.install_aliases()
- from os.path import join
- from datapackage import DataPackage
- from pytest import fixture
from json import loads
+ from io import open
- from gobble.config import ASSETS_DIR
from gobble.uploader import Uploader
+ # noinspection PyUnresolvedReferences
+ from tests.fixtures import (dummy_requests,
+ ROOT_DIR,
+ PACKAGE_FILE,
+ UPLOADER_PAYLOAD)
- from gobble.user import User
-
-
- @fixture
- def user():
- return User()
-
-
- @fixture
- def package():
- filepath = join(ASSETS_DIR, 'mexican-budget-samples', 'datapackage.json')
- return DataPackage(filepath)
# noinspection PyShadowingNames
- def test_build_payloads(user, package):
+ def test_build_payloads(dummy_requests):
+ with dummy_requests:
+ user = User()
+ package = DataPackage(PACKAGE_FILE)
- uploader = Uploader(user, package)
+ uploader = Uploader(user, package)
+ with open(UPLOADER_PAYLOAD) as json:
- expected = join(ASSETS_DIR, 'mexican-budget-samples', 'payload.json')
- with open(expected) as json:
- assert uploader.payload == loads(json.read())
+ assert uploader.payload == loads(json.read())
|
Refactor uploader tests to use the fixture module.
|
## Code Before:
"""Tests for the uploader module"""
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from builtins import open
from future import standard_library
standard_library.install_aliases()
from os.path import join
from datapackage import DataPackage
from pytest import fixture
from json import loads
from gobble.config import ASSETS_DIR
from gobble.uploader import Uploader
from gobble.user import User
@fixture
def user():
return User()
@fixture
def package():
filepath = join(ASSETS_DIR, 'mexican-budget-samples', 'datapackage.json')
return DataPackage(filepath)
# noinspection PyShadowingNames
def test_build_payloads(user, package):
uploader = Uploader(user, package)
expected = join(ASSETS_DIR, 'mexican-budget-samples', 'payload.json')
with open(expected) as json:
assert uploader.payload == loads(json.read())
## Instruction:
Refactor uploader tests to use the fixture module.
## Code After:
"""Tests for the uploader module"""
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from datapackage import DataPackage
from future import standard_library
from gobble.user import User
standard_library.install_aliases()
from json import loads
from io import open
from gobble.uploader import Uploader
# noinspection PyUnresolvedReferences
from tests.fixtures import (dummy_requests,
ROOT_DIR,
PACKAGE_FILE,
UPLOADER_PAYLOAD)
# noinspection PyShadowingNames
def test_build_payloads(dummy_requests):
with dummy_requests:
user = User()
package = DataPackage(PACKAGE_FILE)
uploader = Uploader(user, package)
with open(UPLOADER_PAYLOAD) as json:
assert uploader.payload == loads(json.read())
|
// ... existing code ...
"""Tests for the uploader module"""
from __future__ import unicode_literals
// ... modified code ...
from __future__ import absolute_import
from datapackage import DataPackage
from future import standard_library
from gobble.user import User
...
from json import loads
from io import open
from gobble.uploader import Uploader
# noinspection PyUnresolvedReferences
from tests.fixtures import (dummy_requests,
ROOT_DIR,
PACKAGE_FILE,
UPLOADER_PAYLOAD)
...
# noinspection PyShadowingNames
def test_build_payloads(dummy_requests):
with dummy_requests:
user = User()
package = DataPackage(PACKAGE_FILE)
uploader = Uploader(user, package)
with open(UPLOADER_PAYLOAD) as json:
assert uploader.payload == loads(json.read())
// ... rest of the code ...
|
8e45eb77394ad47579f5726e8f2e63794b8e10c5
|
farnsworth/wsgi.py
|
farnsworth/wsgi.py
|
import os
# We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks
# if running multiple sites in the same mod_wsgi process. To fix this, use
# mod_wsgi daemon mode with each site in its own daemon process, or use
# os.environ["DJANGO_SETTINGS_MODULE"] = "farnsworth.settings"
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "farnsworth.settings")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
|
import os
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
# We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks
# if running multiple sites in the same mod_wsgi process. To fix this, use
# mod_wsgi daemon mode with each site in its own daemon process, or use
# os.environ["DJANGO_SETTINGS_MODULE"] = "farnsworth.settings"
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "farnsworth.settings")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
|
Fix python-path when WSGIPythonPath is not defined
|
Fix python-path when WSGIPythonPath is not defined
|
Python
|
bsd-2-clause
|
knagra/farnsworth,knagra/farnsworth,knagra/farnsworth,knagra/farnsworth
|
import os
+ import sys
+ sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
# We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks
# if running multiple sites in the same mod_wsgi process. To fix this, use
# mod_wsgi daemon mode with each site in its own daemon process, or use
# os.environ["DJANGO_SETTINGS_MODULE"] = "farnsworth.settings"
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "farnsworth.settings")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
|
Fix python-path when WSGIPythonPath is not defined
|
## Code Before:
import os
# We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks
# if running multiple sites in the same mod_wsgi process. To fix this, use
# mod_wsgi daemon mode with each site in its own daemon process, or use
# os.environ["DJANGO_SETTINGS_MODULE"] = "farnsworth.settings"
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "farnsworth.settings")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
## Instruction:
Fix python-path when WSGIPythonPath is not defined
## Code After:
import os
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
# We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks
# if running multiple sites in the same mod_wsgi process. To fix this, use
# mod_wsgi daemon mode with each site in its own daemon process, or use
# os.environ["DJANGO_SETTINGS_MODULE"] = "farnsworth.settings"
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "farnsworth.settings")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
|
// ... existing code ...
import os
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
// ... rest of the code ...
|
904db705daf24d68fcc9ac6010b55b93c7dc4544
|
txircd/modules/core/accounts.py
|
txircd/modules/core/accounts.py
|
from twisted.plugin import IPlugin
from txircd.module_interface import IModuleData, ModuleData
from txircd.utils import ircLower
from zope.interface import implements
class Accounts(ModuleData):
implements(IPlugin, IModuleData)
name = "Accounts"
core = True
def actions(self):
return [ ("usercansetmetadata", 10, self.denyMetadataSet) ]
def denyMetadataSet(self, key):
if ircLower(key) == "account":
return False
return None
accounts = Accounts()
|
from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.module_interface import IModuleData, ModuleData
from txircd.utils import ircLower
from zope.interface import implements
# Numerics and names are taken from the IRCv3.1 SASL specification at http://ircv3.net/specs/extensions/sasl-3.1.html
irc.RPL_LOGGEDIN = "900"
irc.RPL_LOGGEDOUT = "901"
class Accounts(ModuleData):
implements(IPlugin, IModuleData)
name = "Accounts"
core = True
def actions(self):
return [ ("usercansetmetadata", 10, self.denyMetadataSet),
("usermetadataupdate", 10, self.sendLoginNumeric) ]
def denyMetadataSet(self, key):
if ircLower(key) == "account":
return False
return None
def sendLoginNumeric(self, user, key, oldValue, value, visibility, setByUser, fromServer):
if key == "account":
if value is None:
user.sendMessage(irc.RPL_LOGGEDOUT, user.hostmask(), "You are now logged out")
else:
user.sendMessage(irc.RPL_LOGGEDIN, user.hostmask(), value, "You are now logged in as {}".format(value))
accounts = Accounts()
|
Add automatic sending of 900/901 numerics for account status
|
Add automatic sending of 900/901 numerics for account status
|
Python
|
bsd-3-clause
|
Heufneutje/txircd,ElementalAlchemist/txircd
|
from twisted.plugin import IPlugin
+ from twisted.words.protocols import irc
from txircd.module_interface import IModuleData, ModuleData
from txircd.utils import ircLower
from zope.interface import implements
+
+ # Numerics and names are taken from the IRCv3.1 SASL specification at http://ircv3.net/specs/extensions/sasl-3.1.html
+ irc.RPL_LOGGEDIN = "900"
+ irc.RPL_LOGGEDOUT = "901"
class Accounts(ModuleData):
implements(IPlugin, IModuleData)
name = "Accounts"
core = True
def actions(self):
- return [ ("usercansetmetadata", 10, self.denyMetadataSet) ]
+ return [ ("usercansetmetadata", 10, self.denyMetadataSet),
+ ("usermetadataupdate", 10, self.sendLoginNumeric) ]
def denyMetadataSet(self, key):
if ircLower(key) == "account":
return False
return None
+
+ def sendLoginNumeric(self, user, key, oldValue, value, visibility, setByUser, fromServer):
+ if key == "account":
+ if value is None:
+ user.sendMessage(irc.RPL_LOGGEDOUT, user.hostmask(), "You are now logged out")
+ else:
+ user.sendMessage(irc.RPL_LOGGEDIN, user.hostmask(), value, "You are now logged in as {}".format(value))
accounts = Accounts()
|
Add automatic sending of 900/901 numerics for account status
|
## Code Before:
from twisted.plugin import IPlugin
from txircd.module_interface import IModuleData, ModuleData
from txircd.utils import ircLower
from zope.interface import implements
class Accounts(ModuleData):
implements(IPlugin, IModuleData)
name = "Accounts"
core = True
def actions(self):
return [ ("usercansetmetadata", 10, self.denyMetadataSet) ]
def denyMetadataSet(self, key):
if ircLower(key) == "account":
return False
return None
accounts = Accounts()
## Instruction:
Add automatic sending of 900/901 numerics for account status
## Code After:
from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.module_interface import IModuleData, ModuleData
from txircd.utils import ircLower
from zope.interface import implements
# Numerics and names are taken from the IRCv3.1 SASL specification at http://ircv3.net/specs/extensions/sasl-3.1.html
irc.RPL_LOGGEDIN = "900"
irc.RPL_LOGGEDOUT = "901"
class Accounts(ModuleData):
implements(IPlugin, IModuleData)
name = "Accounts"
core = True
def actions(self):
return [ ("usercansetmetadata", 10, self.denyMetadataSet),
("usermetadataupdate", 10, self.sendLoginNumeric) ]
def denyMetadataSet(self, key):
if ircLower(key) == "account":
return False
return None
def sendLoginNumeric(self, user, key, oldValue, value, visibility, setByUser, fromServer):
if key == "account":
if value is None:
user.sendMessage(irc.RPL_LOGGEDOUT, user.hostmask(), "You are now logged out")
else:
user.sendMessage(irc.RPL_LOGGEDIN, user.hostmask(), value, "You are now logged in as {}".format(value))
accounts = Accounts()
|
...
from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.module_interface import IModuleData, ModuleData
...
from zope.interface import implements
# Numerics and names are taken from the IRCv3.1 SASL specification at http://ircv3.net/specs/extensions/sasl-3.1.html
irc.RPL_LOGGEDIN = "900"
irc.RPL_LOGGEDOUT = "901"
...
def actions(self):
return [ ("usercansetmetadata", 10, self.denyMetadataSet),
("usermetadataupdate", 10, self.sendLoginNumeric) ]
...
return None
def sendLoginNumeric(self, user, key, oldValue, value, visibility, setByUser, fromServer):
if key == "account":
if value is None:
user.sendMessage(irc.RPL_LOGGEDOUT, user.hostmask(), "You are now logged out")
else:
user.sendMessage(irc.RPL_LOGGEDIN, user.hostmask(), value, "You are now logged in as {}".format(value))
...
|
9f97f232a23dab38736e487bd69377b977dff752
|
candidates/tests/test_feeds.py
|
candidates/tests/test_feeds.py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django_webtest import WebTest
from .auth import TestUserMixin
from ..models import LoggedAction
class TestFeeds(TestUserMixin, WebTest):
def setUp(self):
self.action1 = LoggedAction.objects.create(
user=self.user,
action_type='person-create',
ip_address='127.0.0.1',
person_id='9876',
popit_person_new_version='1234567890abcdef',
source='Just for tests...',
)
self.action2 = LoggedAction.objects.create(
user=self.user,
action_type='candidacy-delete',
ip_address='127.0.0.1',
person_id='1234',
popit_person_new_version='987654321',
source='Something with unicode in it…',
)
def test_unicode(self):
response = self.app.get('/feeds/changes.xml')
self.assertTrue("Just for tests..." in response)
self.assertTrue("Something with unicode in it…" in response)
def tearDown(self):
self.action2.delete()
self.action1.delete()
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django_webtest import WebTest
from popolo.models import Person
from .auth import TestUserMixin
from ..models import LoggedAction
class TestFeeds(TestUserMixin, WebTest):
def setUp(self):
self.person1 = Person.objects.create(
name='Test Person1'
)
self.person2 = Person.objects.create(
name='Test Person2'
)
self.action1 = LoggedAction.objects.create(
user=self.user,
action_type='person-create',
ip_address='127.0.0.1',
person=self.person1,
popit_person_new_version='1234567890abcdef',
source='Just for tests...',
)
self.action2 = LoggedAction.objects.create(
user=self.user,
action_type='candidacy-delete',
ip_address='127.0.0.1',
person=self.person2,
popit_person_new_version='987654321',
source='Something with unicode in it…',
)
def test_unicode(self):
response = self.app.get('/feeds/changes.xml')
self.assertTrue("Just for tests..." in response)
self.assertTrue("Something with unicode in it…" in response)
def tearDown(self):
self.action2.delete()
self.action1.delete()
self.person2.delete()
self.person1.delete()
|
Update feed tests to use a person object when creating LoggedAction
|
Update feed tests to use a person object when creating LoggedAction
Otherwise the notification signal attached to LoggedAction for the
alerts throws an error as it expects a Person to exist
|
Python
|
agpl-3.0
|
DemocracyClub/yournextrepresentative,mysociety/yournextrepresentative,neavouli/yournextrepresentative,neavouli/yournextrepresentative,mysociety/yournextrepresentative,mysociety/yournextrepresentative,DemocracyClub/yournextrepresentative,mysociety/yournextmp-popit,mysociety/yournextmp-popit,mysociety/yournextmp-popit,neavouli/yournextrepresentative,neavouli/yournextrepresentative,DemocracyClub/yournextrepresentative,mysociety/yournextrepresentative,mysociety/yournextrepresentative,mysociety/yournextmp-popit,mysociety/yournextmp-popit,neavouli/yournextrepresentative
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django_webtest import WebTest
+ from popolo.models import Person
from .auth import TestUserMixin
from ..models import LoggedAction
class TestFeeds(TestUserMixin, WebTest):
def setUp(self):
+ self.person1 = Person.objects.create(
+ name='Test Person1'
+ )
+ self.person2 = Person.objects.create(
+ name='Test Person2'
+ )
self.action1 = LoggedAction.objects.create(
user=self.user,
action_type='person-create',
ip_address='127.0.0.1',
- person_id='9876',
+ person=self.person1,
popit_person_new_version='1234567890abcdef',
source='Just for tests...',
)
self.action2 = LoggedAction.objects.create(
user=self.user,
action_type='candidacy-delete',
ip_address='127.0.0.1',
- person_id='1234',
+ person=self.person2,
popit_person_new_version='987654321',
source='Something with unicode in it…',
)
def test_unicode(self):
response = self.app.get('/feeds/changes.xml')
self.assertTrue("Just for tests..." in response)
self.assertTrue("Something with unicode in it…" in response)
def tearDown(self):
self.action2.delete()
self.action1.delete()
+ self.person2.delete()
+ self.person1.delete()
|
Update feed tests to use a person object when creating LoggedAction
|
## Code Before:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django_webtest import WebTest
from .auth import TestUserMixin
from ..models import LoggedAction
class TestFeeds(TestUserMixin, WebTest):
def setUp(self):
self.action1 = LoggedAction.objects.create(
user=self.user,
action_type='person-create',
ip_address='127.0.0.1',
person_id='9876',
popit_person_new_version='1234567890abcdef',
source='Just for tests...',
)
self.action2 = LoggedAction.objects.create(
user=self.user,
action_type='candidacy-delete',
ip_address='127.0.0.1',
person_id='1234',
popit_person_new_version='987654321',
source='Something with unicode in it…',
)
def test_unicode(self):
response = self.app.get('/feeds/changes.xml')
self.assertTrue("Just for tests..." in response)
self.assertTrue("Something with unicode in it…" in response)
def tearDown(self):
self.action2.delete()
self.action1.delete()
## Instruction:
Update feed tests to use a person object when creating LoggedAction
## Code After:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django_webtest import WebTest
from popolo.models import Person
from .auth import TestUserMixin
from ..models import LoggedAction
class TestFeeds(TestUserMixin, WebTest):
def setUp(self):
self.person1 = Person.objects.create(
name='Test Person1'
)
self.person2 = Person.objects.create(
name='Test Person2'
)
self.action1 = LoggedAction.objects.create(
user=self.user,
action_type='person-create',
ip_address='127.0.0.1',
person=self.person1,
popit_person_new_version='1234567890abcdef',
source='Just for tests...',
)
self.action2 = LoggedAction.objects.create(
user=self.user,
action_type='candidacy-delete',
ip_address='127.0.0.1',
person=self.person2,
popit_person_new_version='987654321',
source='Something with unicode in it…',
)
def test_unicode(self):
response = self.app.get('/feeds/changes.xml')
self.assertTrue("Just for tests..." in response)
self.assertTrue("Something with unicode in it…" in response)
def tearDown(self):
self.action2.delete()
self.action1.delete()
self.person2.delete()
self.person1.delete()
|
...
from popolo.models import Person
from .auth import TestUserMixin
...
def setUp(self):
self.person1 = Person.objects.create(
name='Test Person1'
)
self.person2 = Person.objects.create(
name='Test Person2'
)
self.action1 = LoggedAction.objects.create(
...
ip_address='127.0.0.1',
person=self.person1,
popit_person_new_version='1234567890abcdef',
...
ip_address='127.0.0.1',
person=self.person2,
popit_person_new_version='987654321',
...
self.action1.delete()
self.person2.delete()
self.person1.delete()
...
|
6d37cb94c13c26ae82bc3b67a7ff03c2a032d7fc
|
test/test_message.py
|
test/test_message.py
|
import quopri
from daemail.message import DraftMessage
TEXT = 'àéîøü'
def test_quopri_text():
msg = DraftMessage()
msg.addtext(TEXT)
blob = msg.compile()
assert isinstance(blob, bytes)
assert TEXT.encode('utf-8') not in blob
assert quopri.encodestring(TEXT.encode('utf-8')) in blob
def test_quopri_multipart():
msg = DraftMessage()
msg.addtext(TEXT)
msg.addmimeblob(b'\0\0\0\0', 'application/octet-stream', 'null.dat')
blob = msg.compile()
assert isinstance(blob, bytes)
assert TEXT.encode('utf-8') not in blob
assert quopri.encodestring(TEXT.encode('utf-8')) in blob
|
from base64 import b64encode
import quopri
from daemail.message import DraftMessage
TEXT = 'àéîøü\n'
# Something in the email module implicitly adds a newline to the body text if
# one isn't present, so we need to include one here lest the base64 encodings
# not match up.
TEXT_ENC = TEXT.encode('utf-8')
def test_7bit_text():
msg = DraftMessage()
msg.addtext(TEXT)
blob = msg.compile()
assert isinstance(blob, bytes)
assert TEXT_ENC not in blob
assert quopri.encodestring(TEXT_ENC) in blob or b64encode(TEXT_ENC) in blob
def test_7bit_multipart():
msg = DraftMessage()
msg.addtext(TEXT)
msg.addmimeblob(b'\0\0\0\0', 'application/octet-stream', 'null.dat')
blob = msg.compile()
assert isinstance(blob, bytes)
assert TEXT_ENC not in blob
assert quopri.encodestring(TEXT_ENC) in blob or b64encode(TEXT_ENC) in blob
|
Make tests forwards-compatible with new email API
|
Make tests forwards-compatible with new email API
|
Python
|
mit
|
jwodder/daemail
|
+ from base64 import b64encode
import quopri
from daemail.message import DraftMessage
- TEXT = 'àéîøü'
+ TEXT = 'àéîøü\n'
+ # Something in the email module implicitly adds a newline to the body text if
+ # one isn't present, so we need to include one here lest the base64 encodings
+ # not match up.
+ TEXT_ENC = TEXT.encode('utf-8')
- def test_quopri_text():
+ def test_7bit_text():
msg = DraftMessage()
msg.addtext(TEXT)
blob = msg.compile()
assert isinstance(blob, bytes)
- assert TEXT.encode('utf-8') not in blob
- assert quopri.encodestring(TEXT.encode('utf-8')) in blob
+ assert TEXT_ENC not in blob
+ assert quopri.encodestring(TEXT_ENC) in blob or b64encode(TEXT_ENC) in blob
- def test_quopri_multipart():
+ def test_7bit_multipart():
msg = DraftMessage()
msg.addtext(TEXT)
msg.addmimeblob(b'\0\0\0\0', 'application/octet-stream', 'null.dat')
blob = msg.compile()
assert isinstance(blob, bytes)
- assert TEXT.encode('utf-8') not in blob
- assert quopri.encodestring(TEXT.encode('utf-8')) in blob
+ assert TEXT_ENC not in blob
+ assert quopri.encodestring(TEXT_ENC) in blob or b64encode(TEXT_ENC) in blob
|
Make tests forwards-compatible with new email API
|
## Code Before:
import quopri
from daemail.message import DraftMessage
TEXT = 'àéîøü'
def test_quopri_text():
msg = DraftMessage()
msg.addtext(TEXT)
blob = msg.compile()
assert isinstance(blob, bytes)
assert TEXT.encode('utf-8') not in blob
assert quopri.encodestring(TEXT.encode('utf-8')) in blob
def test_quopri_multipart():
msg = DraftMessage()
msg.addtext(TEXT)
msg.addmimeblob(b'\0\0\0\0', 'application/octet-stream', 'null.dat')
blob = msg.compile()
assert isinstance(blob, bytes)
assert TEXT.encode('utf-8') not in blob
assert quopri.encodestring(TEXT.encode('utf-8')) in blob
## Instruction:
Make tests forwards-compatible with new email API
## Code After:
from base64 import b64encode
import quopri
from daemail.message import DraftMessage
TEXT = 'àéîøü\n'
# Something in the email module implicitly adds a newline to the body text if
# one isn't present, so we need to include one here lest the base64 encodings
# not match up.
TEXT_ENC = TEXT.encode('utf-8')
def test_7bit_text():
msg = DraftMessage()
msg.addtext(TEXT)
blob = msg.compile()
assert isinstance(blob, bytes)
assert TEXT_ENC not in blob
assert quopri.encodestring(TEXT_ENC) in blob or b64encode(TEXT_ENC) in blob
def test_7bit_multipart():
msg = DraftMessage()
msg.addtext(TEXT)
msg.addmimeblob(b'\0\0\0\0', 'application/octet-stream', 'null.dat')
blob = msg.compile()
assert isinstance(blob, bytes)
assert TEXT_ENC not in blob
assert quopri.encodestring(TEXT_ENC) in blob or b64encode(TEXT_ENC) in blob
|
// ... existing code ...
from base64 import b64encode
import quopri
// ... modified code ...
TEXT = 'àéîøü\n'
# Something in the email module implicitly adds a newline to the body text if
# one isn't present, so we need to include one here lest the base64 encodings
# not match up.
TEXT_ENC = TEXT.encode('utf-8')
def test_7bit_text():
msg = DraftMessage()
...
assert isinstance(blob, bytes)
assert TEXT_ENC not in blob
assert quopri.encodestring(TEXT_ENC) in blob or b64encode(TEXT_ENC) in blob
def test_7bit_multipart():
msg = DraftMessage()
...
assert isinstance(blob, bytes)
assert TEXT_ENC not in blob
assert quopri.encodestring(TEXT_ENC) in blob or b64encode(TEXT_ENC) in blob
// ... rest of the code ...
|
db6b869eae416e72fa30b1d7271b0ed1d7dc1a55
|
sqlalchemy_json/__init__.py
|
sqlalchemy_json/__init__.py
|
from sqlalchemy.ext.mutable import (
Mutable,
MutableDict)
from sqlalchemy_utils.types.json import JSONType
from . track import (
TrackedDict,
TrackedList)
__all__ = 'MutableJson', 'NestedMutableJson'
class NestedMutableDict(TrackedDict, Mutable):
@classmethod
def coerce(cls, key, value):
if isinstance(value, cls):
return value
if isinstance(value, dict):
return cls(value)
return super(cls).coerce(key, value)
class NestedMutableList(TrackedList, Mutable):
@classmethod
def coerce(cls, key, value):
if isinstance(value, cls):
return value
if isinstance(value, list):
return cls(value)
return super(cls).coerce(key, value)
class NestedMutable(Mutable):
"""SQLAlchemy `mutable` extension with nested change tracking."""
@classmethod
def coerce(cls, key, value):
"""Convert plain dictionary to NestedMutable."""
if isinstance(value, cls):
return value
if isinstance(value, dict):
return NestedMutableDict.coerce(key, value)
if isinstance(value, list):
return NestedMutableList.coerce(key, value)
return super(cls).coerce(key, value)
class MutableJson(JSONType):
"""JSON type for SQLAlchemy with change tracking at top level."""
class NestedMutableJson(JSONType):
"""JSON type for SQLAlchemy with nested change tracking."""
MutableDict.associate_with(MutableJson)
NestedMutable.associate_with(NestedMutableJson)
|
from sqlalchemy.ext.mutable import (
Mutable,
MutableDict)
from sqlalchemy_utils.types.json import JSONType
from . track import (
TrackedDict,
TrackedList)
__all__ = 'MutableJson', 'NestedMutableJson'
class NestedMutableDict(TrackedDict, Mutable):
@classmethod
def coerce(cls, key, value):
if isinstance(value, cls):
return value
if isinstance(value, dict):
return cls(value)
return super(cls).coerce(key, value)
class NestedMutableList(TrackedList, Mutable):
@classmethod
def coerce(cls, key, value):
if isinstance(value, cls):
return value
if isinstance(value, list):
return cls(value)
return super(cls).coerce(key, value)
class NestedMutable(Mutable):
"""SQLAlchemy `mutable` extension with nested change tracking."""
@classmethod
def coerce(cls, key, value):
"""Convert plain dictionary to NestedMutable."""
if value is None:
return value
if isinstance(value, cls):
return value
if isinstance(value, dict):
return NestedMutableDict.coerce(key, value)
if isinstance(value, list):
return NestedMutableList.coerce(key, value)
return super(cls).coerce(key, value)
class MutableJson(JSONType):
"""JSON type for SQLAlchemy with change tracking at top level."""
class NestedMutableJson(JSONType):
"""JSON type for SQLAlchemy with nested change tracking."""
MutableDict.associate_with(MutableJson)
NestedMutable.associate_with(NestedMutableJson)
|
Fix error when setting JSON value to be `None`
|
Fix error when setting JSON value to be `None`
Previously this would raise an attribute error as `None` does not
have the `coerce` attribute.
|
Python
|
bsd-2-clause
|
edelooff/sqlalchemy-json
|
from sqlalchemy.ext.mutable import (
Mutable,
MutableDict)
from sqlalchemy_utils.types.json import JSONType
from . track import (
TrackedDict,
TrackedList)
__all__ = 'MutableJson', 'NestedMutableJson'
class NestedMutableDict(TrackedDict, Mutable):
@classmethod
def coerce(cls, key, value):
if isinstance(value, cls):
return value
if isinstance(value, dict):
return cls(value)
return super(cls).coerce(key, value)
class NestedMutableList(TrackedList, Mutable):
@classmethod
def coerce(cls, key, value):
if isinstance(value, cls):
return value
if isinstance(value, list):
return cls(value)
return super(cls).coerce(key, value)
class NestedMutable(Mutable):
"""SQLAlchemy `mutable` extension with nested change tracking."""
@classmethod
def coerce(cls, key, value):
"""Convert plain dictionary to NestedMutable."""
+ if value is None:
+ return value
if isinstance(value, cls):
return value
if isinstance(value, dict):
return NestedMutableDict.coerce(key, value)
if isinstance(value, list):
return NestedMutableList.coerce(key, value)
return super(cls).coerce(key, value)
class MutableJson(JSONType):
"""JSON type for SQLAlchemy with change tracking at top level."""
class NestedMutableJson(JSONType):
"""JSON type for SQLAlchemy with nested change tracking."""
MutableDict.associate_with(MutableJson)
NestedMutable.associate_with(NestedMutableJson)
|
Fix error when setting JSON value to be `None`
|
## Code Before:
from sqlalchemy.ext.mutable import (
Mutable,
MutableDict)
from sqlalchemy_utils.types.json import JSONType
from . track import (
TrackedDict,
TrackedList)
__all__ = 'MutableJson', 'NestedMutableJson'
class NestedMutableDict(TrackedDict, Mutable):
@classmethod
def coerce(cls, key, value):
if isinstance(value, cls):
return value
if isinstance(value, dict):
return cls(value)
return super(cls).coerce(key, value)
class NestedMutableList(TrackedList, Mutable):
@classmethod
def coerce(cls, key, value):
if isinstance(value, cls):
return value
if isinstance(value, list):
return cls(value)
return super(cls).coerce(key, value)
class NestedMutable(Mutable):
"""SQLAlchemy `mutable` extension with nested change tracking."""
@classmethod
def coerce(cls, key, value):
"""Convert plain dictionary to NestedMutable."""
if isinstance(value, cls):
return value
if isinstance(value, dict):
return NestedMutableDict.coerce(key, value)
if isinstance(value, list):
return NestedMutableList.coerce(key, value)
return super(cls).coerce(key, value)
class MutableJson(JSONType):
"""JSON type for SQLAlchemy with change tracking at top level."""
class NestedMutableJson(JSONType):
"""JSON type for SQLAlchemy with nested change tracking."""
MutableDict.associate_with(MutableJson)
NestedMutable.associate_with(NestedMutableJson)
## Instruction:
Fix error when setting JSON value to be `None`
## Code After:
from sqlalchemy.ext.mutable import (
Mutable,
MutableDict)
from sqlalchemy_utils.types.json import JSONType
from . track import (
TrackedDict,
TrackedList)
__all__ = 'MutableJson', 'NestedMutableJson'
class NestedMutableDict(TrackedDict, Mutable):
@classmethod
def coerce(cls, key, value):
if isinstance(value, cls):
return value
if isinstance(value, dict):
return cls(value)
return super(cls).coerce(key, value)
class NestedMutableList(TrackedList, Mutable):
@classmethod
def coerce(cls, key, value):
if isinstance(value, cls):
return value
if isinstance(value, list):
return cls(value)
return super(cls).coerce(key, value)
class NestedMutable(Mutable):
"""SQLAlchemy `mutable` extension with nested change tracking."""
@classmethod
def coerce(cls, key, value):
"""Convert plain dictionary to NestedMutable."""
if value is None:
return value
if isinstance(value, cls):
return value
if isinstance(value, dict):
return NestedMutableDict.coerce(key, value)
if isinstance(value, list):
return NestedMutableList.coerce(key, value)
return super(cls).coerce(key, value)
class MutableJson(JSONType):
"""JSON type for SQLAlchemy with change tracking at top level."""
class NestedMutableJson(JSONType):
"""JSON type for SQLAlchemy with nested change tracking."""
MutableDict.associate_with(MutableJson)
NestedMutable.associate_with(NestedMutableJson)
|
...
"""Convert plain dictionary to NestedMutable."""
if value is None:
return value
if isinstance(value, cls):
...
|
3ec71d3925a3551f6f25fc25e827c88caaff1fdd
|
tests/integration/test_redirection_external.py
|
tests/integration/test_redirection_external.py
|
"""Check external REDIRECTIONS"""
import pytest
from nikola import __main__
from .helper import append_config, cd
from .test_demo_build import prepare_demo_site
from .test_empty_build import ( # NOQA
test_archive_exists,
test_avoid_double_slash_in_rss,
test_check_files,
test_check_links,
test_index_in_sitemap,
)
@pytest.fixture(scope="module")
def build(target_dir):
"""Fill the site with demo content and build it."""
prepare_demo_site(target_dir)
append_config(
target_dir,
"""
REDIRECTIONS = [ ("external.html", "http://www.example.com/"), ]
""",
)
with cd(target_dir):
__main__.main(["build"])
|
"""Check external REDIRECTIONS"""
import os
import pytest
from nikola import __main__
from .helper import append_config, cd
from .test_demo_build import prepare_demo_site
from .test_empty_build import ( # NOQA
test_archive_exists,
test_avoid_double_slash_in_rss,
test_check_files,
test_check_links,
test_index_in_sitemap,
)
def test_external_redirection(build, output_dir):
ext_link = os.path.join(output_dir, 'external.html')
assert os.path.exists(ext_link)
with open(ext_link) as ext_link_fd:
ext_link_content = ext_link_fd.read()
redirect_tag = '<meta http-equiv="refresh" content="0; url=http://www.example.com/">'
assert redirect_tag in ext_link_content
@pytest.fixture(scope="module")
def build(target_dir):
"""Fill the site with demo content and build it."""
prepare_demo_site(target_dir)
append_config(
target_dir,
"""
REDIRECTIONS = [ ("external.html", "http://www.example.com/"), ]
""",
)
with cd(target_dir):
__main__.main(["build"])
|
Add test for external redirection.
|
Add test for external redirection.
|
Python
|
mit
|
okin/nikola,okin/nikola,okin/nikola,getnikola/nikola,getnikola/nikola,getnikola/nikola,okin/nikola,getnikola/nikola
|
"""Check external REDIRECTIONS"""
+
+ import os
import pytest
from nikola import __main__
from .helper import append_config, cd
from .test_demo_build import prepare_demo_site
from .test_empty_build import ( # NOQA
test_archive_exists,
test_avoid_double_slash_in_rss,
test_check_files,
test_check_links,
test_index_in_sitemap,
)
+
+
+ def test_external_redirection(build, output_dir):
+ ext_link = os.path.join(output_dir, 'external.html')
+
+ assert os.path.exists(ext_link)
+ with open(ext_link) as ext_link_fd:
+ ext_link_content = ext_link_fd.read()
+
+ redirect_tag = '<meta http-equiv="refresh" content="0; url=http://www.example.com/">'
+ assert redirect_tag in ext_link_content
@pytest.fixture(scope="module")
def build(target_dir):
"""Fill the site with demo content and build it."""
prepare_demo_site(target_dir)
append_config(
target_dir,
"""
REDIRECTIONS = [ ("external.html", "http://www.example.com/"), ]
""",
)
with cd(target_dir):
__main__.main(["build"])
|
Add test for external redirection.
|
## Code Before:
"""Check external REDIRECTIONS"""
import pytest
from nikola import __main__
from .helper import append_config, cd
from .test_demo_build import prepare_demo_site
from .test_empty_build import ( # NOQA
test_archive_exists,
test_avoid_double_slash_in_rss,
test_check_files,
test_check_links,
test_index_in_sitemap,
)
@pytest.fixture(scope="module")
def build(target_dir):
"""Fill the site with demo content and build it."""
prepare_demo_site(target_dir)
append_config(
target_dir,
"""
REDIRECTIONS = [ ("external.html", "http://www.example.com/"), ]
""",
)
with cd(target_dir):
__main__.main(["build"])
## Instruction:
Add test for external redirection.
## Code After:
"""Check external REDIRECTIONS"""
import os
import pytest
from nikola import __main__
from .helper import append_config, cd
from .test_demo_build import prepare_demo_site
from .test_empty_build import ( # NOQA
test_archive_exists,
test_avoid_double_slash_in_rss,
test_check_files,
test_check_links,
test_index_in_sitemap,
)
def test_external_redirection(build, output_dir):
ext_link = os.path.join(output_dir, 'external.html')
assert os.path.exists(ext_link)
with open(ext_link) as ext_link_fd:
ext_link_content = ext_link_fd.read()
redirect_tag = '<meta http-equiv="refresh" content="0; url=http://www.example.com/">'
assert redirect_tag in ext_link_content
@pytest.fixture(scope="module")
def build(target_dir):
"""Fill the site with demo content and build it."""
prepare_demo_site(target_dir)
append_config(
target_dir,
"""
REDIRECTIONS = [ ("external.html", "http://www.example.com/"), ]
""",
)
with cd(target_dir):
__main__.main(["build"])
|
// ... existing code ...
"""Check external REDIRECTIONS"""
import os
// ... modified code ...
def test_external_redirection(build, output_dir):
ext_link = os.path.join(output_dir, 'external.html')
assert os.path.exists(ext_link)
with open(ext_link) as ext_link_fd:
ext_link_content = ext_link_fd.read()
redirect_tag = '<meta http-equiv="refresh" content="0; url=http://www.example.com/">'
assert redirect_tag in ext_link_content
@pytest.fixture(scope="module")
// ... rest of the code ...
|
456de4b1184780b9179ee9e6572a3f62cf22550a
|
tests/test_tools/simple_project.py
|
tests/test_tools/simple_project.py
|
project_1_yaml = {
'common': {
'sources': ['sources/main.cpp'],
'includes': ['includes/header1.h'],
'target': ['mbed-lpc1768']
}
}
projects_1_yaml = {
'projects': {
'project_1' : ['test_workspace/project_1.yaml']
},
}
|
project_1_yaml = {
'common': {
'sources': ['sources/main.cpp'],
'includes': ['includes/header1.h'],
'target': ['mbed-lpc1768'],
'linker_file': ['linker_script'],
}
}
projects_1_yaml = {
'projects': {
'project_1' : ['test_workspace/project_1.yaml']
},
}
|
Test - add linker script for tools project
|
Test - add linker script for tools project
|
Python
|
apache-2.0
|
molejar/project_generator,hwfwgrp/project_generator,0xc0170/project_generator,sarahmarshy/project_generator,ohagendorf/project_generator,project-generator/project_generator
|
project_1_yaml = {
'common': {
'sources': ['sources/main.cpp'],
'includes': ['includes/header1.h'],
- 'target': ['mbed-lpc1768']
+ 'target': ['mbed-lpc1768'],
+ 'linker_file': ['linker_script'],
}
}
projects_1_yaml = {
'projects': {
'project_1' : ['test_workspace/project_1.yaml']
},
}
|
Test - add linker script for tools project
|
## Code Before:
project_1_yaml = {
'common': {
'sources': ['sources/main.cpp'],
'includes': ['includes/header1.h'],
'target': ['mbed-lpc1768']
}
}
projects_1_yaml = {
'projects': {
'project_1' : ['test_workspace/project_1.yaml']
},
}
## Instruction:
Test - add linker script for tools project
## Code After:
project_1_yaml = {
'common': {
'sources': ['sources/main.cpp'],
'includes': ['includes/header1.h'],
'target': ['mbed-lpc1768'],
'linker_file': ['linker_script'],
}
}
projects_1_yaml = {
'projects': {
'project_1' : ['test_workspace/project_1.yaml']
},
}
|
...
'includes': ['includes/header1.h'],
'target': ['mbed-lpc1768'],
'linker_file': ['linker_script'],
}
...
|
221d672368f8989508aaf5b36f6a4f9f5bd5425a
|
winthrop/books/migrations/0008_add-digital-edition.py
|
winthrop/books/migrations/0008_add-digital-edition.py
|
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('djiffy', '0002_add-digital-edition'),
('books', '0007_title-length'),
]
operations = [
migrations.AlterModelOptions(
name='book',
options={'ordering': ['title']},
),
migrations.AddField(
model_name='book',
name='digital_edition',
field=models.ForeignKey(blank=True, null=True, default=None, help_text='Digitized edition of this book, if available', on_delete=django.db.models.deletion.CASCADE, to='djiffy.Manifest'),
preserve_default=False,
),
]
|
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('djiffy', '0001_initial'),
('books', '0007_title-length'),
]
operations = [
migrations.AlterModelOptions(
name='book',
options={'ordering': ['title']},
),
migrations.AddField(
model_name='book',
name='digital_edition',
field=models.ForeignKey(blank=True, help_text='Digitized edition of this book, if available', null=True, on_delete=django.db.models.deletion.CASCADE, to='djiffy.Manifest'),
),
]
|
Fix migration so it works with actual existing djiffy migrations
|
Fix migration so it works with actual existing djiffy migrations
|
Python
|
apache-2.0
|
Princeton-CDH/winthrop-django,Princeton-CDH/winthrop-django,Princeton-CDH/winthrop-django
|
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
- ('djiffy', '0002_add-digital-edition'),
+ ('djiffy', '0001_initial'),
('books', '0007_title-length'),
]
operations = [
migrations.AlterModelOptions(
name='book',
options={'ordering': ['title']},
),
migrations.AddField(
model_name='book',
name='digital_edition',
- field=models.ForeignKey(blank=True, null=True, default=None, help_text='Digitized edition of this book, if available', on_delete=django.db.models.deletion.CASCADE, to='djiffy.Manifest'),
+ field=models.ForeignKey(blank=True, help_text='Digitized edition of this book, if available', null=True, on_delete=django.db.models.deletion.CASCADE, to='djiffy.Manifest'),
- preserve_default=False,
),
]
|
Fix migration so it works with actual existing djiffy migrations
|
## Code Before:
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('djiffy', '0002_add-digital-edition'),
('books', '0007_title-length'),
]
operations = [
migrations.AlterModelOptions(
name='book',
options={'ordering': ['title']},
),
migrations.AddField(
model_name='book',
name='digital_edition',
field=models.ForeignKey(blank=True, null=True, default=None, help_text='Digitized edition of this book, if available', on_delete=django.db.models.deletion.CASCADE, to='djiffy.Manifest'),
preserve_default=False,
),
]
## Instruction:
Fix migration so it works with actual existing djiffy migrations
## Code After:
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('djiffy', '0001_initial'),
('books', '0007_title-length'),
]
operations = [
migrations.AlterModelOptions(
name='book',
options={'ordering': ['title']},
),
migrations.AddField(
model_name='book',
name='digital_edition',
field=models.ForeignKey(blank=True, help_text='Digitized edition of this book, if available', null=True, on_delete=django.db.models.deletion.CASCADE, to='djiffy.Manifest'),
),
]
|
...
dependencies = [
('djiffy', '0001_initial'),
('books', '0007_title-length'),
...
name='digital_edition',
field=models.ForeignKey(blank=True, help_text='Digitized edition of this book, if available', null=True, on_delete=django.db.models.deletion.CASCADE, to='djiffy.Manifest'),
),
...
|
e4e930587e6ad145dbdbf1f742b942d63bf645a2
|
wandb/git_repo.py
|
wandb/git_repo.py
|
from git import Repo, exc
import os
class GitRepo(object):
def __init__(self, root=None, remote="origin", lazy=True):
self.remote_name = remote
self.root = root
self._repo = None
if not lazy:
self.repo
@property
def repo(self):
if self._repo is None:
if self.remote_name is None:
self._repo = False
else:
try:
self._repo = Repo(self.root or os.getcwd(), search_parent_directories=True)
except exc.InvalidGitRepositoryError:
self._repo = False
return self._repo
@property
def enabled(self):
return self.repo
@property
def dirty(self):
return self.repo.is_dirty()
@property
def last_commit(self):
if not self.repo:
return None
return self.repo.head.commit.hexsha
@property
def remote(self):
if not self.repo:
return None
try:
return self.repo.remotes[self.remote_name]
except IndexError:
return None
@property
def remote_url(self):
if not self.remote:
return None
return self.remote.url
def tag(self, name, message):
return self.repo.create_tag("wandb/"+name, message=message, force=True)
def push(self, name):
if self.remote:
return self.remote.push("wandb/"+name, force=True)
|
from git import Repo, exc
import os
class GitRepo(object):
def __init__(self, root=None, remote="origin", lazy=True):
self.remote_name = remote
self.root = root
self._repo = None
if not lazy:
self.repo
@property
def repo(self):
if self._repo is None:
if self.remote_name is None:
self._repo = False
else:
try:
self._repo = Repo(self.root or os.getcwd(), search_parent_directories=True)
except exc.InvalidGitRepositoryError:
self._repo = False
return self._repo
@property
def enabled(self):
return self.repo
@property
def dirty(self):
return self.repo.is_dirty()
@property
def last_commit(self):
if not self.repo:
return None
return self.repo.head.commit.hexsha
@property
def remote(self):
if not self.repo:
return None
try:
return self.repo.remotes[self.remote_name]
except IndexError:
return None
@property
def remote_url(self):
if not self.remote:
return None
return self.remote.url
def tag(self, name, message):
try:
return self.repo.create_tag("wandb/"+name, message=message, force=True)
except GitCommandError:
print("Failed to tag repository.")
return None
def push(self, name):
if self.remote:
return self.remote.push("wandb/"+name, force=True)
|
Handle no git user configured
|
Handle no git user configured
|
Python
|
mit
|
wandb/client,wandb/client,wandb/client
|
from git import Repo, exc
import os
class GitRepo(object):
def __init__(self, root=None, remote="origin", lazy=True):
self.remote_name = remote
self.root = root
self._repo = None
if not lazy:
self.repo
@property
def repo(self):
if self._repo is None:
if self.remote_name is None:
self._repo = False
else:
try:
self._repo = Repo(self.root or os.getcwd(), search_parent_directories=True)
except exc.InvalidGitRepositoryError:
self._repo = False
return self._repo
@property
def enabled(self):
return self.repo
@property
def dirty(self):
return self.repo.is_dirty()
@property
def last_commit(self):
if not self.repo:
return None
return self.repo.head.commit.hexsha
@property
def remote(self):
if not self.repo:
return None
try:
return self.repo.remotes[self.remote_name]
except IndexError:
return None
@property
def remote_url(self):
if not self.remote:
return None
return self.remote.url
def tag(self, name, message):
+ try:
- return self.repo.create_tag("wandb/"+name, message=message, force=True)
+ return self.repo.create_tag("wandb/"+name, message=message, force=True)
+ except GitCommandError:
+ print("Failed to tag repository.")
+ return None
def push(self, name):
if self.remote:
return self.remote.push("wandb/"+name, force=True)
|
Handle no git user configured
|
## Code Before:
from git import Repo, exc
import os
class GitRepo(object):
def __init__(self, root=None, remote="origin", lazy=True):
self.remote_name = remote
self.root = root
self._repo = None
if not lazy:
self.repo
@property
def repo(self):
if self._repo is None:
if self.remote_name is None:
self._repo = False
else:
try:
self._repo = Repo(self.root or os.getcwd(), search_parent_directories=True)
except exc.InvalidGitRepositoryError:
self._repo = False
return self._repo
@property
def enabled(self):
return self.repo
@property
def dirty(self):
return self.repo.is_dirty()
@property
def last_commit(self):
if not self.repo:
return None
return self.repo.head.commit.hexsha
@property
def remote(self):
if not self.repo:
return None
try:
return self.repo.remotes[self.remote_name]
except IndexError:
return None
@property
def remote_url(self):
if not self.remote:
return None
return self.remote.url
def tag(self, name, message):
return self.repo.create_tag("wandb/"+name, message=message, force=True)
def push(self, name):
if self.remote:
return self.remote.push("wandb/"+name, force=True)
## Instruction:
Handle no git user configured
## Code After:
from git import Repo, exc
import os
class GitRepo(object):
def __init__(self, root=None, remote="origin", lazy=True):
self.remote_name = remote
self.root = root
self._repo = None
if not lazy:
self.repo
@property
def repo(self):
if self._repo is None:
if self.remote_name is None:
self._repo = False
else:
try:
self._repo = Repo(self.root or os.getcwd(), search_parent_directories=True)
except exc.InvalidGitRepositoryError:
self._repo = False
return self._repo
@property
def enabled(self):
return self.repo
@property
def dirty(self):
return self.repo.is_dirty()
@property
def last_commit(self):
if not self.repo:
return None
return self.repo.head.commit.hexsha
@property
def remote(self):
if not self.repo:
return None
try:
return self.repo.remotes[self.remote_name]
except IndexError:
return None
@property
def remote_url(self):
if not self.remote:
return None
return self.remote.url
def tag(self, name, message):
try:
return self.repo.create_tag("wandb/"+name, message=message, force=True)
except GitCommandError:
print("Failed to tag repository.")
return None
def push(self, name):
if self.remote:
return self.remote.push("wandb/"+name, force=True)
|
...
def tag(self, name, message):
try:
return self.repo.create_tag("wandb/"+name, message=message, force=True)
except GitCommandError:
print("Failed to tag repository.")
return None
...
|
38365839856658bcf870e286a27f0de784a255a2
|
test/tools/lldb-mi/TestMiLibraryLoaded.py
|
test/tools/lldb-mi/TestMiLibraryLoaded.py
|
import lldbmi_testcase
from lldbtest import *
import unittest2
class MiLibraryLoadedTestCase(lldbmi_testcase.MiTestCaseBase):
mydir = TestBase.compute_mydir(__file__)
@lldbmi_test
@expectedFailureWindows("llvm.org/pr22274: need a pexpect replacement for windows")
@skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
def test_lldbmi_library_loaded(self):
"""Test that 'lldb-mi --interpreter' shows the =library-loaded notifications."""
self.spawnLldbMi(args = None)
# Load executable
self.runCmd("-file-exec-and-symbols %s" % self.myexe)
self.expect("\^done")
# Test =library-loaded
import os
path = os.path.join(os.getcwd(), self.myexe)
symbols_path = os.path.join(path + ".dSYM", "Contents", "Resources", "DWARF", self.myexe)
self.expect("=library-loaded,id=\"%s\",target-name=\"%s\",host-name=\"%s\",symbols-loaded=\"1\",symbols-path=\"%s\",loaded_addr=\"-\"" % (path, path, path, symbols_path),
exactly = True)
if __name__ == '__main__':
unittest2.main()
|
import lldbmi_testcase
from lldbtest import *
import unittest2
class MiLibraryLoadedTestCase(lldbmi_testcase.MiTestCaseBase):
mydir = TestBase.compute_mydir(__file__)
@lldbmi_test
@expectedFailureWindows("llvm.org/pr22274: need a pexpect replacement for windows")
@skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
def test_lldbmi_library_loaded(self):
"""Test that 'lldb-mi --interpreter' shows the =library-loaded notifications."""
self.spawnLldbMi(args = None)
# Load executable
self.runCmd("-file-exec-and-symbols %s" % self.myexe)
self.expect("\^done")
# Test =library-loaded
import os
path = os.path.join(os.getcwd(), self.myexe)
symbols_path = os.path.join(path + ".dSYM", "Contents", "Resources", "DWARF", self.myexe)
self.expect([
"=library-loaded,id=\"%s\",target-name=\"%s\",host-name=\"%s\",symbols-loaded=\"1\",symbols-path=\"%s\",loaded_addr=\"-\"" % (path, path, path, symbols_path),
"=library-loaded,id=\"%s\",target-name=\"%s\",host-name=\"%s\",symbols-loaded=\"0\",loaded_addr=\"-\"" % (path, path, path)
], exactly = True)
if __name__ == '__main__':
unittest2.main()
|
Fix MiLibraryLoadedTestCase.test_lldbmi_library_loaded test on Linux (MI)
|
Fix MiLibraryLoadedTestCase.test_lldbmi_library_loaded test on Linux (MI)
git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@236229 91177308-0d34-0410-b5e6-96231b3b80d8
|
Python
|
apache-2.0
|
apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,llvm-mirror/lldb,apple/swift-lldb
|
import lldbmi_testcase
from lldbtest import *
import unittest2
class MiLibraryLoadedTestCase(lldbmi_testcase.MiTestCaseBase):
mydir = TestBase.compute_mydir(__file__)
@lldbmi_test
@expectedFailureWindows("llvm.org/pr22274: need a pexpect replacement for windows")
@skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
def test_lldbmi_library_loaded(self):
"""Test that 'lldb-mi --interpreter' shows the =library-loaded notifications."""
self.spawnLldbMi(args = None)
# Load executable
self.runCmd("-file-exec-and-symbols %s" % self.myexe)
self.expect("\^done")
# Test =library-loaded
import os
path = os.path.join(os.getcwd(), self.myexe)
symbols_path = os.path.join(path + ".dSYM", "Contents", "Resources", "DWARF", self.myexe)
+ self.expect([
- self.expect("=library-loaded,id=\"%s\",target-name=\"%s\",host-name=\"%s\",symbols-loaded=\"1\",symbols-path=\"%s\",loaded_addr=\"-\"" % (path, path, path, symbols_path),
+ "=library-loaded,id=\"%s\",target-name=\"%s\",host-name=\"%s\",symbols-loaded=\"1\",symbols-path=\"%s\",loaded_addr=\"-\"" % (path, path, path, symbols_path),
+ "=library-loaded,id=\"%s\",target-name=\"%s\",host-name=\"%s\",symbols-loaded=\"0\",loaded_addr=\"-\"" % (path, path, path)
- exactly = True)
+ ], exactly = True)
if __name__ == '__main__':
unittest2.main()
|
Fix MiLibraryLoadedTestCase.test_lldbmi_library_loaded test on Linux (MI)
|
## Code Before:
import lldbmi_testcase
from lldbtest import *
import unittest2
class MiLibraryLoadedTestCase(lldbmi_testcase.MiTestCaseBase):
mydir = TestBase.compute_mydir(__file__)
@lldbmi_test
@expectedFailureWindows("llvm.org/pr22274: need a pexpect replacement for windows")
@skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
def test_lldbmi_library_loaded(self):
"""Test that 'lldb-mi --interpreter' shows the =library-loaded notifications."""
self.spawnLldbMi(args = None)
# Load executable
self.runCmd("-file-exec-and-symbols %s" % self.myexe)
self.expect("\^done")
# Test =library-loaded
import os
path = os.path.join(os.getcwd(), self.myexe)
symbols_path = os.path.join(path + ".dSYM", "Contents", "Resources", "DWARF", self.myexe)
self.expect("=library-loaded,id=\"%s\",target-name=\"%s\",host-name=\"%s\",symbols-loaded=\"1\",symbols-path=\"%s\",loaded_addr=\"-\"" % (path, path, path, symbols_path),
exactly = True)
if __name__ == '__main__':
unittest2.main()
## Instruction:
Fix MiLibraryLoadedTestCase.test_lldbmi_library_loaded test on Linux (MI)
## Code After:
import lldbmi_testcase
from lldbtest import *
import unittest2
class MiLibraryLoadedTestCase(lldbmi_testcase.MiTestCaseBase):
mydir = TestBase.compute_mydir(__file__)
@lldbmi_test
@expectedFailureWindows("llvm.org/pr22274: need a pexpect replacement for windows")
@skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
def test_lldbmi_library_loaded(self):
"""Test that 'lldb-mi --interpreter' shows the =library-loaded notifications."""
self.spawnLldbMi(args = None)
# Load executable
self.runCmd("-file-exec-and-symbols %s" % self.myexe)
self.expect("\^done")
# Test =library-loaded
import os
path = os.path.join(os.getcwd(), self.myexe)
symbols_path = os.path.join(path + ".dSYM", "Contents", "Resources", "DWARF", self.myexe)
self.expect([
"=library-loaded,id=\"%s\",target-name=\"%s\",host-name=\"%s\",symbols-loaded=\"1\",symbols-path=\"%s\",loaded_addr=\"-\"" % (path, path, path, symbols_path),
"=library-loaded,id=\"%s\",target-name=\"%s\",host-name=\"%s\",symbols-loaded=\"0\",loaded_addr=\"-\"" % (path, path, path)
], exactly = True)
if __name__ == '__main__':
unittest2.main()
|
// ... existing code ...
symbols_path = os.path.join(path + ".dSYM", "Contents", "Resources", "DWARF", self.myexe)
self.expect([
"=library-loaded,id=\"%s\",target-name=\"%s\",host-name=\"%s\",symbols-loaded=\"1\",symbols-path=\"%s\",loaded_addr=\"-\"" % (path, path, path, symbols_path),
"=library-loaded,id=\"%s\",target-name=\"%s\",host-name=\"%s\",symbols-loaded=\"0\",loaded_addr=\"-\"" % (path, path, path)
], exactly = True)
// ... rest of the code ...
|
91b3891078b889db98d3832f0c06e465a86e52ef
|
django_tenants/staticfiles/storage.py
|
django_tenants/staticfiles/storage.py
|
import os
from django.contrib.staticfiles.storage import StaticFilesStorage
from django_tenants.files.storages import TenantStorageMixin
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
class TenantStaticFilesStorage(TenantStorageMixin, StaticFilesStorage):
"""
Implementation that extends core Django's StaticFilesStorage.
"""
def __init__(self, location=None, base_url=None, *args, **kwargs):
super(TenantStaticFilesStorage, self).__init__(location, base_url, *args, **kwargs)
if hasattr(settings, "MULTITENANT_RELATIVE_STATIC_ROOT"):
self.location = os.path.join(self.location, settings.MULTITENANT_RELATIVE_STATIC_ROOT)
def path(self, name):
"""
if not hasattr(settings, "MULTITENANT_RELATIVE_STATIC_ROOT") or \
not settings.MULTITENANT_RELATIVE_STATIC_ROOT:
raise ImproperlyConfigured("You're using the TenantStaticFilesStorage "
"without having set the MULTITENANT_RELATIVE_STATIC_ROOT "
"setting to a filesystem path.")
"""
return super(TenantStaticFilesStorage, self).path(name)
|
import os
from django.contrib.staticfiles.storage import StaticFilesStorage
from django_tenants.files.storages import TenantStorageMixin
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
class TenantStaticFilesStorage(TenantStorageMixin, StaticFilesStorage):
"""
Implementation that extends core Django's StaticFilesStorage.
"""
def __init__(self, location=None, base_url=None, *args, **kwargs):
super(TenantStaticFilesStorage, self).__init__(location, base_url, *args, **kwargs)
if hasattr(settings, "MULTITENANT_RELATIVE_STATIC_ROOT"):
self.location = os.path.join(self.location, settings.MULTITENANT_RELATIVE_STATIC_ROOT)
"""
def path(self, name):
if not hasattr(settings, "MULTITENANT_RELATIVE_STATIC_ROOT") or \
not settings.MULTITENANT_RELATIVE_STATIC_ROOT:
raise ImproperlyConfigured("You're using the TenantStaticFilesStorage "
"without having set the MULTITENANT_RELATIVE_STATIC_ROOT "
"setting to a filesystem path.")
return super(TenantStaticFilesStorage, self).path(name)
"""
|
Fix regression in path handling of TenantStaticFileStorage.
|
Fix regression in path handling of TenantStaticFileStorage.
Fixes #197.
|
Python
|
mit
|
tomturner/django-tenants,tomturner/django-tenants,tomturner/django-tenants
|
import os
from django.contrib.staticfiles.storage import StaticFilesStorage
from django_tenants.files.storages import TenantStorageMixin
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
class TenantStaticFilesStorage(TenantStorageMixin, StaticFilesStorage):
"""
Implementation that extends core Django's StaticFilesStorage.
"""
def __init__(self, location=None, base_url=None, *args, **kwargs):
super(TenantStaticFilesStorage, self).__init__(location, base_url, *args, **kwargs)
if hasattr(settings, "MULTITENANT_RELATIVE_STATIC_ROOT"):
self.location = os.path.join(self.location, settings.MULTITENANT_RELATIVE_STATIC_ROOT)
+ """
def path(self, name):
- """
if not hasattr(settings, "MULTITENANT_RELATIVE_STATIC_ROOT") or \
not settings.MULTITENANT_RELATIVE_STATIC_ROOT:
raise ImproperlyConfigured("You're using the TenantStaticFilesStorage "
"without having set the MULTITENANT_RELATIVE_STATIC_ROOT "
"setting to a filesystem path.")
- """
return super(TenantStaticFilesStorage, self).path(name)
+ """
|
Fix regression in path handling of TenantStaticFileStorage.
|
## Code Before:
import os
from django.contrib.staticfiles.storage import StaticFilesStorage
from django_tenants.files.storages import TenantStorageMixin
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
class TenantStaticFilesStorage(TenantStorageMixin, StaticFilesStorage):
"""
Implementation that extends core Django's StaticFilesStorage.
"""
def __init__(self, location=None, base_url=None, *args, **kwargs):
super(TenantStaticFilesStorage, self).__init__(location, base_url, *args, **kwargs)
if hasattr(settings, "MULTITENANT_RELATIVE_STATIC_ROOT"):
self.location = os.path.join(self.location, settings.MULTITENANT_RELATIVE_STATIC_ROOT)
def path(self, name):
"""
if not hasattr(settings, "MULTITENANT_RELATIVE_STATIC_ROOT") or \
not settings.MULTITENANT_RELATIVE_STATIC_ROOT:
raise ImproperlyConfigured("You're using the TenantStaticFilesStorage "
"without having set the MULTITENANT_RELATIVE_STATIC_ROOT "
"setting to a filesystem path.")
"""
return super(TenantStaticFilesStorage, self).path(name)
## Instruction:
Fix regression in path handling of TenantStaticFileStorage.
## Code After:
import os
from django.contrib.staticfiles.storage import StaticFilesStorage
from django_tenants.files.storages import TenantStorageMixin
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
class TenantStaticFilesStorage(TenantStorageMixin, StaticFilesStorage):
"""
Implementation that extends core Django's StaticFilesStorage.
"""
def __init__(self, location=None, base_url=None, *args, **kwargs):
super(TenantStaticFilesStorage, self).__init__(location, base_url, *args, **kwargs)
if hasattr(settings, "MULTITENANT_RELATIVE_STATIC_ROOT"):
self.location = os.path.join(self.location, settings.MULTITENANT_RELATIVE_STATIC_ROOT)
"""
def path(self, name):
if not hasattr(settings, "MULTITENANT_RELATIVE_STATIC_ROOT") or \
not settings.MULTITENANT_RELATIVE_STATIC_ROOT:
raise ImproperlyConfigured("You're using the TenantStaticFilesStorage "
"without having set the MULTITENANT_RELATIVE_STATIC_ROOT "
"setting to a filesystem path.")
return super(TenantStaticFilesStorage, self).path(name)
"""
|
# ... existing code ...
"""
def path(self, name):
if not hasattr(settings, "MULTITENANT_RELATIVE_STATIC_ROOT") or \
# ... modified code ...
"setting to a filesystem path.")
return super(TenantStaticFilesStorage, self).path(name)
"""
# ... rest of the code ...
|
853bfc4d010f6c80bef6878a356df73a60f09596
|
test_config.py
|
test_config.py
|
import tempfile
import shutil
import os
from voltgrid import ConfigManager
def test_config_manager():
c = ConfigManager('voltgrid.conf.example')
c.write_envs()
def test_config_is_empty():
with tempfile.NamedTemporaryFile() as tmp_f:
c = ConfigManager(tmp_f.name)
def test_config_not_exist():
c = ConfigManager('does-not-exist')
def test_git_config():
git_url = '[email protected]:voltgrid/voltgrid-pie.git'
os.environ['GIT_URL'] = git_url
c = ConfigManager()
assert(c.git_url == git_url)
|
import tempfile
import shutil
import os
from voltgrid import ConfigManager
VG_CFG = 'voltgrid.conf.example'
def test_config_manager():
c = ConfigManager(VG_CFG)
c.write_envs()
def test_config_is_empty():
with tempfile.NamedTemporaryFile() as tmp_f:
c = ConfigManager(tmp_f.name)
def test_config_not_exist():
c = ConfigManager('does-not-exist')
def test_git_config():
git_url = '[email protected]:voltgrid/voltgrid-pie.git'
os.environ['GIT_URL'] = git_url
c = ConfigManager(VG_CFG)
assert(c.git_url == git_url)
|
Fix test loading wrong config
|
Fix test loading wrong config
|
Python
|
bsd-3-clause
|
voltgrid/voltgrid-pie
|
import tempfile
import shutil
import os
from voltgrid import ConfigManager
+ VG_CFG = 'voltgrid.conf.example'
+
def test_config_manager():
- c = ConfigManager('voltgrid.conf.example')
+ c = ConfigManager(VG_CFG)
c.write_envs()
def test_config_is_empty():
with tempfile.NamedTemporaryFile() as tmp_f:
c = ConfigManager(tmp_f.name)
def test_config_not_exist():
c = ConfigManager('does-not-exist')
def test_git_config():
git_url = '[email protected]:voltgrid/voltgrid-pie.git'
os.environ['GIT_URL'] = git_url
- c = ConfigManager()
+ c = ConfigManager(VG_CFG)
assert(c.git_url == git_url)
|
Fix test loading wrong config
|
## Code Before:
import tempfile
import shutil
import os
from voltgrid import ConfigManager
def test_config_manager():
c = ConfigManager('voltgrid.conf.example')
c.write_envs()
def test_config_is_empty():
with tempfile.NamedTemporaryFile() as tmp_f:
c = ConfigManager(tmp_f.name)
def test_config_not_exist():
c = ConfigManager('does-not-exist')
def test_git_config():
git_url = '[email protected]:voltgrid/voltgrid-pie.git'
os.environ['GIT_URL'] = git_url
c = ConfigManager()
assert(c.git_url == git_url)
## Instruction:
Fix test loading wrong config
## Code After:
import tempfile
import shutil
import os
from voltgrid import ConfigManager
VG_CFG = 'voltgrid.conf.example'
def test_config_manager():
c = ConfigManager(VG_CFG)
c.write_envs()
def test_config_is_empty():
with tempfile.NamedTemporaryFile() as tmp_f:
c = ConfigManager(tmp_f.name)
def test_config_not_exist():
c = ConfigManager('does-not-exist')
def test_git_config():
git_url = '[email protected]:voltgrid/voltgrid-pie.git'
os.environ['GIT_URL'] = git_url
c = ConfigManager(VG_CFG)
assert(c.git_url == git_url)
|
...
VG_CFG = 'voltgrid.conf.example'
...
def test_config_manager():
c = ConfigManager(VG_CFG)
c.write_envs()
...
os.environ['GIT_URL'] = git_url
c = ConfigManager(VG_CFG)
assert(c.git_url == git_url)
...
|
441f950efac0197e73fa46cf423793f28402f532
|
yaml_storage.py
|
yaml_storage.py
|
import yaml
import sys
from tinydb.storages import Storage
class YAMLStorage(Storage):
def __init__(self, filename): # (1)
self.filename = filename
def read(self):
with open(self.filename) as handle:
try:
data = yaml.safe_load(handle.read()) # (2)
return data
except yaml.YAMLError:
return None # (3)
def write(self, data):
with open(self.filename, 'w') as handle:
yaml.dump(yaml.safe_load(str(data)), handle)
def close(self): # (4)
pass
|
import yaml
import sys
from tinydb.database import Document
from tinydb.storages import Storage, touch
def represent_doc(dumper, data):
# Represent `Document` objects as their dict's string representation
# which PyYAML understands
return dumper.represent_data(dict(data))
yaml.add_representer(Document, represent_doc)
class YAMLStorage(Storage):
def __init__(self, filename):
self.filename = filename
touch(filename, False)
def read(self):
with open(self.filename) as handle:
data = yaml.safe_load(handle.read())
return data
def write(self, data):
with open(self.filename, 'w') as handle:
yaml.dump(data, handle)
def close(self):
pass
|
Fix YAMLStorage as per TinyDB doc changes
|
Fix YAMLStorage as per TinyDB doc changes
|
Python
|
mit
|
msembinelli/mpm
|
import yaml
import sys
+ from tinydb.database import Document
- from tinydb.storages import Storage
+ from tinydb.storages import Storage, touch
+
+ def represent_doc(dumper, data):
+ # Represent `Document` objects as their dict's string representation
+ # which PyYAML understands
+ return dumper.represent_data(dict(data))
+
+ yaml.add_representer(Document, represent_doc)
class YAMLStorage(Storage):
- def __init__(self, filename): # (1)
+ def __init__(self, filename):
self.filename = filename
+ touch(filename, False)
def read(self):
with open(self.filename) as handle:
- try:
- data = yaml.safe_load(handle.read()) # (2)
+ data = yaml.safe_load(handle.read())
- return data
+ return data
- except yaml.YAMLError:
- return None # (3)
def write(self, data):
with open(self.filename, 'w') as handle:
- yaml.dump(yaml.safe_load(str(data)), handle)
+ yaml.dump(data, handle)
- def close(self): # (4)
+ def close(self):
pass
|
Fix YAMLStorage as per TinyDB doc changes
|
## Code Before:
import yaml
import sys
from tinydb.storages import Storage
class YAMLStorage(Storage):
def __init__(self, filename): # (1)
self.filename = filename
def read(self):
with open(self.filename) as handle:
try:
data = yaml.safe_load(handle.read()) # (2)
return data
except yaml.YAMLError:
return None # (3)
def write(self, data):
with open(self.filename, 'w') as handle:
yaml.dump(yaml.safe_load(str(data)), handle)
def close(self): # (4)
pass
## Instruction:
Fix YAMLStorage as per TinyDB doc changes
## Code After:
import yaml
import sys
from tinydb.database import Document
from tinydb.storages import Storage, touch
def represent_doc(dumper, data):
# Represent `Document` objects as their dict's string representation
# which PyYAML understands
return dumper.represent_data(dict(data))
yaml.add_representer(Document, represent_doc)
class YAMLStorage(Storage):
def __init__(self, filename):
self.filename = filename
touch(filename, False)
def read(self):
with open(self.filename) as handle:
data = yaml.safe_load(handle.read())
return data
def write(self, data):
with open(self.filename, 'w') as handle:
yaml.dump(data, handle)
def close(self):
pass
|
...
import sys
from tinydb.database import Document
from tinydb.storages import Storage, touch
def represent_doc(dumper, data):
# Represent `Document` objects as their dict's string representation
# which PyYAML understands
return dumper.represent_data(dict(data))
yaml.add_representer(Document, represent_doc)
...
class YAMLStorage(Storage):
def __init__(self, filename):
self.filename = filename
touch(filename, False)
...
with open(self.filename) as handle:
data = yaml.safe_load(handle.read())
return data
...
with open(self.filename, 'w') as handle:
yaml.dump(data, handle)
def close(self):
pass
...
|
72ce164a461987f7b9d35ac9a2b3a36386b7f8c9
|
ui/Interactor.py
|
ui/Interactor.py
|
class Interactor(object):
"""
Interactor
"""
def __init__(self):
super(Interactor, self).__init__()
def AddObserver(self, obj, eventName, callbackFunction):
"""
Creates a callback and stores the callback so that later
on the callbacks can be properly cleaned up.
"""
if not hasattr(self, "_callbacks"):
self._callbacks = []
callback = obj.AddObserver(eventName, callbackFunction)
self._callbacks.append((obj, callback))
def cleanUpCallbacks(self):
"""
Cleans up the vtkCallBacks
"""
if not hasattr(self, "_callbacks"):
return
for obj, callback in self._callbacks:
obj.RemoveObserver(callback)
self._callbacks = []
|
class Interactor(object):
"""
Interactor
"""
def __init__(self):
super(Interactor, self).__init__()
def AddObserver(self, obj, eventName, callbackFunction, priority=None):
"""
Creates a callback and stores the callback so that later
on the callbacks can be properly cleaned up.
"""
if not hasattr(self, "_callbacks"):
self._callbacks = []
if priority is not None:
callback = obj.AddObserver(eventName, callbackFunction, priority)
else:
callback = obj.AddObserver(eventName, callbackFunction)
self._callbacks.append((obj, callback))
def cleanUpCallbacks(self):
"""
Cleans up the vtkCallBacks
"""
if not hasattr(self, "_callbacks"):
return
for obj, callback in self._callbacks:
obj.RemoveObserver(callback)
self._callbacks = []
|
Add possibility of passing priority for adding an observer
|
Add possibility of passing priority for adding an observer
|
Python
|
mit
|
berendkleinhaneveld/Registrationshop,berendkleinhaneveld/Registrationshop
|
class Interactor(object):
"""
Interactor
"""
def __init__(self):
super(Interactor, self).__init__()
- def AddObserver(self, obj, eventName, callbackFunction):
+ def AddObserver(self, obj, eventName, callbackFunction, priority=None):
"""
Creates a callback and stores the callback so that later
on the callbacks can be properly cleaned up.
"""
if not hasattr(self, "_callbacks"):
self._callbacks = []
+ if priority is not None:
+ callback = obj.AddObserver(eventName, callbackFunction, priority)
+ else:
- callback = obj.AddObserver(eventName, callbackFunction)
+ callback = obj.AddObserver(eventName, callbackFunction)
self._callbacks.append((obj, callback))
def cleanUpCallbacks(self):
"""
Cleans up the vtkCallBacks
"""
if not hasattr(self, "_callbacks"):
return
for obj, callback in self._callbacks:
obj.RemoveObserver(callback)
self._callbacks = []
|
Add possibility of passing priority for adding an observer
|
## Code Before:
class Interactor(object):
"""
Interactor
"""
def __init__(self):
super(Interactor, self).__init__()
def AddObserver(self, obj, eventName, callbackFunction):
"""
Creates a callback and stores the callback so that later
on the callbacks can be properly cleaned up.
"""
if not hasattr(self, "_callbacks"):
self._callbacks = []
callback = obj.AddObserver(eventName, callbackFunction)
self._callbacks.append((obj, callback))
def cleanUpCallbacks(self):
"""
Cleans up the vtkCallBacks
"""
if not hasattr(self, "_callbacks"):
return
for obj, callback in self._callbacks:
obj.RemoveObserver(callback)
self._callbacks = []
## Instruction:
Add possibility of passing priority for adding an observer
## Code After:
class Interactor(object):
"""
Interactor
"""
def __init__(self):
super(Interactor, self).__init__()
def AddObserver(self, obj, eventName, callbackFunction, priority=None):
"""
Creates a callback and stores the callback so that later
on the callbacks can be properly cleaned up.
"""
if not hasattr(self, "_callbacks"):
self._callbacks = []
if priority is not None:
callback = obj.AddObserver(eventName, callbackFunction, priority)
else:
callback = obj.AddObserver(eventName, callbackFunction)
self._callbacks.append((obj, callback))
def cleanUpCallbacks(self):
"""
Cleans up the vtkCallBacks
"""
if not hasattr(self, "_callbacks"):
return
for obj, callback in self._callbacks:
obj.RemoveObserver(callback)
self._callbacks = []
|
// ... existing code ...
def AddObserver(self, obj, eventName, callbackFunction, priority=None):
"""
// ... modified code ...
if priority is not None:
callback = obj.AddObserver(eventName, callbackFunction, priority)
else:
callback = obj.AddObserver(eventName, callbackFunction)
self._callbacks.append((obj, callback))
// ... rest of the code ...
|
187026ce695dee79c4897c0e8e014bb208de5a83
|
gaia_tools/load/__init__.py
|
gaia_tools/load/__init__.py
|
import os, os.path
import astropy.io.ascii
from gaia_tools.load import path, download
def galah(dr=1):
filePath, ReadMePath= path.galahPath(dr=dr)
if not os.path.exists(filePath):
download.galah(dr=dr)
data= astropy.io.ascii.read(filePath,readme=ReadMePath)
return data
|
import os, os.path
import numpy
import astropy.io.ascii
from gaia_tools.load import path, download
def galah(dr=1):
filePath, ReadMePath= path.galahPath(dr=dr)
if not os.path.exists(filePath):
download.galah(dr=dr)
data= astropy.io.ascii.read(filePath,readme=ReadMePath)
data['RA']._fill_value= numpy.array([-9999.99])
data['dec']._fill_value= numpy.array([-9999.99])
return data
|
Set fill value of GALAH RA and Dec explicitly
|
Set fill value of GALAH RA and Dec explicitly
|
Python
|
mit
|
jobovy/gaia_tools
|
import os, os.path
+ import numpy
import astropy.io.ascii
from gaia_tools.load import path, download
def galah(dr=1):
filePath, ReadMePath= path.galahPath(dr=dr)
if not os.path.exists(filePath):
download.galah(dr=dr)
data= astropy.io.ascii.read(filePath,readme=ReadMePath)
+ data['RA']._fill_value= numpy.array([-9999.99])
+ data['dec']._fill_value= numpy.array([-9999.99])
return data
|
Set fill value of GALAH RA and Dec explicitly
|
## Code Before:
import os, os.path
import astropy.io.ascii
from gaia_tools.load import path, download
def galah(dr=1):
filePath, ReadMePath= path.galahPath(dr=dr)
if not os.path.exists(filePath):
download.galah(dr=dr)
data= astropy.io.ascii.read(filePath,readme=ReadMePath)
return data
## Instruction:
Set fill value of GALAH RA and Dec explicitly
## Code After:
import os, os.path
import numpy
import astropy.io.ascii
from gaia_tools.load import path, download
def galah(dr=1):
filePath, ReadMePath= path.galahPath(dr=dr)
if not os.path.exists(filePath):
download.galah(dr=dr)
data= astropy.io.ascii.read(filePath,readme=ReadMePath)
data['RA']._fill_value= numpy.array([-9999.99])
data['dec']._fill_value= numpy.array([-9999.99])
return data
|
...
import os, os.path
import numpy
import astropy.io.ascii
...
data= astropy.io.ascii.read(filePath,readme=ReadMePath)
data['RA']._fill_value= numpy.array([-9999.99])
data['dec']._fill_value= numpy.array([-9999.99])
return data
...
|
e81e25f1d97ef4f141e392bda736aaa6a37aadf5
|
chatbot/botui.py
|
chatbot/botui.py
|
import numpy as np
import os
import sys
import tensorflow as tf
from settings import PROJECT_ROOT
from chatbot.tokenizeddata import TokenizedData
from chatbot.botpredictor import BotPredictor
def bot_ui():
data_file = os.path.join(PROJECT_ROOT, 'Data', 'Corpus', 'basic_conv.txt')
td = TokenizedData(seq_length=10, data_file=data_file)
res_dir = os.path.join(PROJECT_ROOT, 'Data', 'Result')
with tf.Session() as sess:
predictor = BotPredictor(sess, td, res_dir, 'basic')
# Waiting from standard input.
sys.stdout.write("> ")
sys.stdout.flush()
sentence = sys.stdin.readline()
while sentence:
dec_outputs = predictor.predict(sentence)
word_ids = []
for out in dec_outputs:
word_ids.append(np.argmax(out))
print(td.word_ids_to_str(word_ids))
print("> ", end="")
sys.stdout.flush()
sentence = sys.stdin.readline()
if __name__ == "__main__":
bot_ui()
|
import numpy as np
import os
import sys
import tensorflow as tf
from settings import PROJECT_ROOT
from chatbot.tokenizeddata import TokenizedData
from chatbot.botpredictor import BotPredictor
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
def bot_ui():
dict_file = os.path.join(PROJECT_ROOT, 'Data', 'Result', 'dicts.pickle')
td = TokenizedData(seq_length=10, dict_file=dict_file)
res_dir = os.path.join(PROJECT_ROOT, 'Data', 'Result')
with tf.Session() as sess:
predictor = BotPredictor(sess, td, res_dir, 'basic')
print("Welcome to Chat with ChatLearner!")
print("Type exit and press enter to end the conversation.")
# Waiting from standard input.
sys.stdout.write("> ")
sys.stdout.flush()
sentence = sys.stdin.readline()
while sentence:
if sentence.strip() == 'exit':
print("Thank you for using ChatLearner. Bye.")
break
dec_outputs = predictor.predict(sentence)
word_ids = []
for out in dec_outputs:
word_ids.append(np.argmax(out))
print(td.word_ids_to_str(word_ids))
print("> ", end="")
sys.stdout.flush()
sentence = sys.stdin.readline()
if __name__ == "__main__":
bot_ui()
|
Optimize the UI and allow the user to exit the program smoothly.
|
Optimize the UI and allow the user to exit the program smoothly.
|
Python
|
apache-2.0
|
bshao001/ChatLearner,bshao001/ChatLearner,bshao001/ChatLearner,bshao001/ChatLearner
|
import numpy as np
import os
import sys
import tensorflow as tf
from settings import PROJECT_ROOT
from chatbot.tokenizeddata import TokenizedData
from chatbot.botpredictor import BotPredictor
+ os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
def bot_ui():
- data_file = os.path.join(PROJECT_ROOT, 'Data', 'Corpus', 'basic_conv.txt')
+ dict_file = os.path.join(PROJECT_ROOT, 'Data', 'Result', 'dicts.pickle')
- td = TokenizedData(seq_length=10, data_file=data_file)
+ td = TokenizedData(seq_length=10, dict_file=dict_file)
res_dir = os.path.join(PROJECT_ROOT, 'Data', 'Result')
with tf.Session() as sess:
predictor = BotPredictor(sess, td, res_dir, 'basic')
+ print("Welcome to Chat with ChatLearner!")
+ print("Type exit and press enter to end the conversation.")
# Waiting from standard input.
sys.stdout.write("> ")
sys.stdout.flush()
sentence = sys.stdin.readline()
while sentence:
+ if sentence.strip() == 'exit':
+ print("Thank you for using ChatLearner. Bye.")
+ break
+
dec_outputs = predictor.predict(sentence)
word_ids = []
for out in dec_outputs:
word_ids.append(np.argmax(out))
print(td.word_ids_to_str(word_ids))
print("> ", end="")
sys.stdout.flush()
sentence = sys.stdin.readline()
if __name__ == "__main__":
bot_ui()
|
Optimize the UI and allow the user to exit the program smoothly.
|
## Code Before:
import numpy as np
import os
import sys
import tensorflow as tf
from settings import PROJECT_ROOT
from chatbot.tokenizeddata import TokenizedData
from chatbot.botpredictor import BotPredictor
def bot_ui():
data_file = os.path.join(PROJECT_ROOT, 'Data', 'Corpus', 'basic_conv.txt')
td = TokenizedData(seq_length=10, data_file=data_file)
res_dir = os.path.join(PROJECT_ROOT, 'Data', 'Result')
with tf.Session() as sess:
predictor = BotPredictor(sess, td, res_dir, 'basic')
# Waiting from standard input.
sys.stdout.write("> ")
sys.stdout.flush()
sentence = sys.stdin.readline()
while sentence:
dec_outputs = predictor.predict(sentence)
word_ids = []
for out in dec_outputs:
word_ids.append(np.argmax(out))
print(td.word_ids_to_str(word_ids))
print("> ", end="")
sys.stdout.flush()
sentence = sys.stdin.readline()
if __name__ == "__main__":
bot_ui()
## Instruction:
Optimize the UI and allow the user to exit the program smoothly.
## Code After:
import numpy as np
import os
import sys
import tensorflow as tf
from settings import PROJECT_ROOT
from chatbot.tokenizeddata import TokenizedData
from chatbot.botpredictor import BotPredictor
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
def bot_ui():
dict_file = os.path.join(PROJECT_ROOT, 'Data', 'Result', 'dicts.pickle')
td = TokenizedData(seq_length=10, dict_file=dict_file)
res_dir = os.path.join(PROJECT_ROOT, 'Data', 'Result')
with tf.Session() as sess:
predictor = BotPredictor(sess, td, res_dir, 'basic')
print("Welcome to Chat with ChatLearner!")
print("Type exit and press enter to end the conversation.")
# Waiting from standard input.
sys.stdout.write("> ")
sys.stdout.flush()
sentence = sys.stdin.readline()
while sentence:
if sentence.strip() == 'exit':
print("Thank you for using ChatLearner. Bye.")
break
dec_outputs = predictor.predict(sentence)
word_ids = []
for out in dec_outputs:
word_ids.append(np.argmax(out))
print(td.word_ids_to_str(word_ids))
print("> ", end="")
sys.stdout.flush()
sentence = sys.stdin.readline()
if __name__ == "__main__":
bot_ui()
|
# ... existing code ...
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
# ... modified code ...
def bot_ui():
dict_file = os.path.join(PROJECT_ROOT, 'Data', 'Result', 'dicts.pickle')
td = TokenizedData(seq_length=10, dict_file=dict_file)
...
print("Welcome to Chat with ChatLearner!")
print("Type exit and press enter to end the conversation.")
# Waiting from standard input.
...
while sentence:
if sentence.strip() == 'exit':
print("Thank you for using ChatLearner. Bye.")
break
dec_outputs = predictor.predict(sentence)
# ... rest of the code ...
|
dd8176f26addcf36419f1723448ab1e3ae8d0e89
|
metashare/repository/search_fields.py
|
metashare/repository/search_fields.py
|
from haystack.exceptions import SearchFieldError
from haystack.indexes import SearchField, CharField, MultiValueField
class LabeledField(SearchField):
"""
A kind of mixin class for creating `SearchField`s with a label.
"""
def __init__(self, label, **kwargs):
if label is None:
raise SearchFieldError("'{0}' fields must have a label." \
.format(self.__class__.__name__))
self.label = label
super(LabeledField, self).__init__(**kwargs)
class LabeledCharField(LabeledField, CharField):
"""
A `CharField` with a label.
"""
pass
class LabeledMultiValueField(LabeledField, MultiValueField):
"""
A `MultiValueField` with a label.
"""
pass
|
from haystack.exceptions import SearchFieldError
from haystack.indexes import SearchField, CharField, MultiValueField
class LabeledField(SearchField):
"""
A kind of mixin class for creating `SearchField`s with a label.
"""
def __init__(self, label, facet_id, parent_id, **kwargs):
if label is None:
raise SearchFieldError("'{0}' fields must have a label." \
.format(self.__class__.__name__))
self.label = label
self.facet_id = facet_id
self.parent_id = parent_id
super(LabeledField, self).__init__(**kwargs)
class LabeledCharField(LabeledField, CharField):
"""
A `CharField` with a label.
"""
pass
class LabeledMultiValueField(LabeledField, MultiValueField):
"""
A `MultiValueField` with a label.
"""
pass
|
Order facets and add sub facet feature
|
Order facets and add sub facet feature
|
Python
|
bsd-3-clause
|
MiltosD/CEF-ELRC,JuliBakagianni/CEF-ELRC,MiltosD/CEFELRC,zeehio/META-SHARE,MiltosD/CEF-ELRC,JuliBakagianni/CEF-ELRC,MiltosD/CEFELRC,MiltosD/CEF-ELRC,JuliBakagianni/META-SHARE,MiltosD/CEFELRC,JuliBakagianni/CEF-ELRC,MiltosD/CEFELRC,zeehio/META-SHARE,zeehio/META-SHARE,MiltosD/CEF-ELRC,JuliBakagianni/CEF-ELRC,zeehio/META-SHARE,MiltosD/CEF-ELRC,MiltosD/CEFELRC,JuliBakagianni/CEF-ELRC,JuliBakagianni/CEF-ELRC,JuliBakagianni/META-SHARE,zeehio/META-SHARE,MiltosD/CEF-ELRC,JuliBakagianni/META-SHARE,JuliBakagianni/META-SHARE,zeehio/META-SHARE,MiltosD/CEFELRC,JuliBakagianni/CEF-ELRC,MiltosD/CEFELRC,JuliBakagianni/META-SHARE,JuliBakagianni/META-SHARE,zeehio/META-SHARE,MiltosD/CEF-ELRC,JuliBakagianni/META-SHARE
|
from haystack.exceptions import SearchFieldError
from haystack.indexes import SearchField, CharField, MultiValueField
class LabeledField(SearchField):
"""
A kind of mixin class for creating `SearchField`s with a label.
"""
- def __init__(self, label, **kwargs):
+ def __init__(self, label, facet_id, parent_id, **kwargs):
if label is None:
raise SearchFieldError("'{0}' fields must have a label." \
.format(self.__class__.__name__))
self.label = label
+ self.facet_id = facet_id
+ self.parent_id = parent_id
super(LabeledField, self).__init__(**kwargs)
class LabeledCharField(LabeledField, CharField):
"""
A `CharField` with a label.
"""
pass
class LabeledMultiValueField(LabeledField, MultiValueField):
"""
A `MultiValueField` with a label.
"""
pass
|
Order facets and add sub facet feature
|
## Code Before:
from haystack.exceptions import SearchFieldError
from haystack.indexes import SearchField, CharField, MultiValueField
class LabeledField(SearchField):
"""
A kind of mixin class for creating `SearchField`s with a label.
"""
def __init__(self, label, **kwargs):
if label is None:
raise SearchFieldError("'{0}' fields must have a label." \
.format(self.__class__.__name__))
self.label = label
super(LabeledField, self).__init__(**kwargs)
class LabeledCharField(LabeledField, CharField):
"""
A `CharField` with a label.
"""
pass
class LabeledMultiValueField(LabeledField, MultiValueField):
"""
A `MultiValueField` with a label.
"""
pass
## Instruction:
Order facets and add sub facet feature
## Code After:
from haystack.exceptions import SearchFieldError
from haystack.indexes import SearchField, CharField, MultiValueField
class LabeledField(SearchField):
"""
A kind of mixin class for creating `SearchField`s with a label.
"""
def __init__(self, label, facet_id, parent_id, **kwargs):
if label is None:
raise SearchFieldError("'{0}' fields must have a label." \
.format(self.__class__.__name__))
self.label = label
self.facet_id = facet_id
self.parent_id = parent_id
super(LabeledField, self).__init__(**kwargs)
class LabeledCharField(LabeledField, CharField):
"""
A `CharField` with a label.
"""
pass
class LabeledMultiValueField(LabeledField, MultiValueField):
"""
A `MultiValueField` with a label.
"""
pass
|
// ... existing code ...
"""
def __init__(self, label, facet_id, parent_id, **kwargs):
if label is None:
// ... modified code ...
self.label = label
self.facet_id = facet_id
self.parent_id = parent_id
super(LabeledField, self).__init__(**kwargs)
// ... rest of the code ...
|
b72c9a26c00ca31966be3ae8b529e9272d300290
|
__main__.py
|
__main__.py
|
import sys
import argparse
from . import parse
from . import compile
from . import runtime
from .interactive import Interactive
class Interactive (Interactive):
def __init__(self, args):
super().__init__()
self.args = args
self.single = sys.stdin.isatty() or args.print
def displayhook(self, value):
self.args.print and print(value)
return super().displayhook(value)
def traceback(self, trace):
# When running in non-interactive mode, strip the first 4 lines.
# These correspond to stuff in this module.
return super().traceback(trace)[4 * (not sys.stdin.isatty()):]
def compile(self, code):
q = parse.r.compile_command(code)
q = q if q is None else compile.r(q, name='<module>', single=self.single)
return q
def run(self, ns):
q = parse.r(sys.stdin.read(), sys.stdin.name)
q = compile.r(q, name='<module>', single=self.single)
return self.eval(q, ns)
parser = argparse.ArgumentParser()
parser.add_argument('-p', '--print', action='store_true', help='when compiling, make the top-level code print its evaluation result in addition to returning it (does not affect REPL)')
parser.add_argument('file', nargs='?', help='files to parse/compile', type=argparse.FileType())
parser.add_argument('arguments', nargs='*', help='additional arguments')
args = parser.parse_args()
sys.argv = [args.file.name if args.file else '-'] + args.arguments
sys.stdin = args.file or sys.stdin
Interactive(args).shell(__name__)
|
import sys
import argparse
from . import parse
from . import compile
from . import runtime
from .interactive import Interactive
class Interactive (Interactive):
def __init__(self, args):
super().__init__()
self.args = args
def traceback(self, trace):
# When running in non-interactive mode, strip the first 4 lines.
# These correspond to stuff in this module.
return super().traceback(trace)[4 * (not sys.stdin.isatty()):]
def compile(self, code):
q = parse.r.compile_command(code)
q = q if q is None else compile.r(q, name='<module>', single=True)
return q
def run(self, ns):
q = parse.r(sys.stdin.read(), sys.stdin.name)
q = compile.r(q, name='<module>')
return self.eval(q, ns)
parser = argparse.ArgumentParser()
parser.add_argument('file', nargs='?', help='files to parse/compile', type=argparse.FileType())
parser.add_argument('arguments', nargs='*', help='additional arguments')
args = parser.parse_args()
sys.argv = [args.file.name if args.file else '-'] + args.arguments
sys.stdin = args.file or sys.stdin
Interactive(args).shell(__name__)
|
Remove the -p command-line option.
|
Remove the -p command-line option.
It's pretty useless anyway. Use instead.
|
Python
|
mit
|
pyos/dg
|
import sys
import argparse
from . import parse
from . import compile
from . import runtime
from .interactive import Interactive
class Interactive (Interactive):
def __init__(self, args):
super().__init__()
- self.args = args
+ self.args = args
- self.single = sys.stdin.isatty() or args.print
-
- def displayhook(self, value):
-
- self.args.print and print(value)
- return super().displayhook(value)
def traceback(self, trace):
# When running in non-interactive mode, strip the first 4 lines.
# These correspond to stuff in this module.
return super().traceback(trace)[4 * (not sys.stdin.isatty()):]
def compile(self, code):
q = parse.r.compile_command(code)
- q = q if q is None else compile.r(q, name='<module>', single=self.single)
+ q = q if q is None else compile.r(q, name='<module>', single=True)
return q
def run(self, ns):
q = parse.r(sys.stdin.read(), sys.stdin.name)
- q = compile.r(q, name='<module>', single=self.single)
+ q = compile.r(q, name='<module>')
return self.eval(q, ns)
parser = argparse.ArgumentParser()
- parser.add_argument('-p', '--print', action='store_true', help='when compiling, make the top-level code print its evaluation result in addition to returning it (does not affect REPL)')
parser.add_argument('file', nargs='?', help='files to parse/compile', type=argparse.FileType())
parser.add_argument('arguments', nargs='*', help='additional arguments')
args = parser.parse_args()
sys.argv = [args.file.name if args.file else '-'] + args.arguments
sys.stdin = args.file or sys.stdin
Interactive(args).shell(__name__)
|
Remove the -p command-line option.
|
## Code Before:
import sys
import argparse
from . import parse
from . import compile
from . import runtime
from .interactive import Interactive
class Interactive (Interactive):
def __init__(self, args):
super().__init__()
self.args = args
self.single = sys.stdin.isatty() or args.print
def displayhook(self, value):
self.args.print and print(value)
return super().displayhook(value)
def traceback(self, trace):
# When running in non-interactive mode, strip the first 4 lines.
# These correspond to stuff in this module.
return super().traceback(trace)[4 * (not sys.stdin.isatty()):]
def compile(self, code):
q = parse.r.compile_command(code)
q = q if q is None else compile.r(q, name='<module>', single=self.single)
return q
def run(self, ns):
q = parse.r(sys.stdin.read(), sys.stdin.name)
q = compile.r(q, name='<module>', single=self.single)
return self.eval(q, ns)
parser = argparse.ArgumentParser()
parser.add_argument('-p', '--print', action='store_true', help='when compiling, make the top-level code print its evaluation result in addition to returning it (does not affect REPL)')
parser.add_argument('file', nargs='?', help='files to parse/compile', type=argparse.FileType())
parser.add_argument('arguments', nargs='*', help='additional arguments')
args = parser.parse_args()
sys.argv = [args.file.name if args.file else '-'] + args.arguments
sys.stdin = args.file or sys.stdin
Interactive(args).shell(__name__)
## Instruction:
Remove the -p command-line option.
## Code After:
import sys
import argparse
from . import parse
from . import compile
from . import runtime
from .interactive import Interactive
class Interactive (Interactive):
def __init__(self, args):
super().__init__()
self.args = args
def traceback(self, trace):
# When running in non-interactive mode, strip the first 4 lines.
# These correspond to stuff in this module.
return super().traceback(trace)[4 * (not sys.stdin.isatty()):]
def compile(self, code):
q = parse.r.compile_command(code)
q = q if q is None else compile.r(q, name='<module>', single=True)
return q
def run(self, ns):
q = parse.r(sys.stdin.read(), sys.stdin.name)
q = compile.r(q, name='<module>')
return self.eval(q, ns)
parser = argparse.ArgumentParser()
parser.add_argument('file', nargs='?', help='files to parse/compile', type=argparse.FileType())
parser.add_argument('arguments', nargs='*', help='additional arguments')
args = parser.parse_args()
sys.argv = [args.file.name if args.file else '-'] + args.arguments
sys.stdin = args.file or sys.stdin
Interactive(args).shell(__name__)
|
# ... existing code ...
self.args = args
# ... modified code ...
q = parse.r.compile_command(code)
q = q if q is None else compile.r(q, name='<module>', single=True)
return q
...
q = parse.r(sys.stdin.read(), sys.stdin.name)
q = compile.r(q, name='<module>')
return self.eval(q, ns)
...
parser = argparse.ArgumentParser()
parser.add_argument('file', nargs='?', help='files to parse/compile', type=argparse.FileType())
# ... rest of the code ...
|
4dfbe6ea079b32644c9086351f911ce1a2b2b0e1
|
easy_maps/geocode.py
|
easy_maps/geocode.py
|
from __future__ import absolute_import
from django.utils.encoding import smart_str
from geopy import geocoders
from geopy.exc import GeocoderServiceError
class Error(Exception):
pass
def google_v3(address):
"""
Given an address, return ``(computed_address, (latitude, longitude))``
tuple using Google Geocoding API v3.
"""
try:
g = geocoders.GoogleV3()
address = smart_str(address)
return g.geocode(address, exactly_one=False)[0]
except (UnboundLocalError, ValueError, GeocoderServiceError) as e:
raise Error(e)
|
from __future__ import absolute_import
from django.utils.encoding import smart_str
from geopy import geocoders
from geopy.exc import GeocoderServiceError
class Error(Exception):
pass
def google_v3(address):
"""
Given an address, return ``(computed_address, (latitude, longitude))``
tuple using Google Geocoding API v3.
"""
try:
g = geocoders.GoogleV3()
address = smart_str(address)
results = g.geocode(address, exactly_one=False)
if results is not None:
return results[0]
raise Error('No results found')
except (UnboundLocalError, ValueError, GeocoderServiceError) as e:
raise Error(e)
|
Resolve the 500 error when google send a no results info
|
Resolve the 500 error when google send a no results info
|
Python
|
mit
|
duixteam/django-easy-maps,kmike/django-easy-maps,Gonzasestopal/django-easy-maps,kmike/django-easy-maps,bashu/django-easy-maps,bashu/django-easy-maps,Gonzasestopal/django-easy-maps
|
from __future__ import absolute_import
from django.utils.encoding import smart_str
from geopy import geocoders
from geopy.exc import GeocoderServiceError
+
class Error(Exception):
pass
def google_v3(address):
"""
Given an address, return ``(computed_address, (latitude, longitude))``
tuple using Google Geocoding API v3.
"""
try:
g = geocoders.GoogleV3()
address = smart_str(address)
- return g.geocode(address, exactly_one=False)[0]
+ results = g.geocode(address, exactly_one=False)
+ if results is not None:
+ return results[0]
+ raise Error('No results found')
except (UnboundLocalError, ValueError, GeocoderServiceError) as e:
raise Error(e)
|
Resolve the 500 error when google send a no results info
|
## Code Before:
from __future__ import absolute_import
from django.utils.encoding import smart_str
from geopy import geocoders
from geopy.exc import GeocoderServiceError
class Error(Exception):
pass
def google_v3(address):
"""
Given an address, return ``(computed_address, (latitude, longitude))``
tuple using Google Geocoding API v3.
"""
try:
g = geocoders.GoogleV3()
address = smart_str(address)
return g.geocode(address, exactly_one=False)[0]
except (UnboundLocalError, ValueError, GeocoderServiceError) as e:
raise Error(e)
## Instruction:
Resolve the 500 error when google send a no results info
## Code After:
from __future__ import absolute_import
from django.utils.encoding import smart_str
from geopy import geocoders
from geopy.exc import GeocoderServiceError
class Error(Exception):
pass
def google_v3(address):
"""
Given an address, return ``(computed_address, (latitude, longitude))``
tuple using Google Geocoding API v3.
"""
try:
g = geocoders.GoogleV3()
address = smart_str(address)
results = g.geocode(address, exactly_one=False)
if results is not None:
return results[0]
raise Error('No results found')
except (UnboundLocalError, ValueError, GeocoderServiceError) as e:
raise Error(e)
|
...
from geopy.exc import GeocoderServiceError
...
address = smart_str(address)
results = g.geocode(address, exactly_one=False)
if results is not None:
return results[0]
raise Error('No results found')
except (UnboundLocalError, ValueError, GeocoderServiceError) as e:
...
|
d705c4ffbe60a11a0cde55f5caa2324349366bab
|
irctest/optional_extensions.py
|
irctest/optional_extensions.py
|
import unittest
import operator
import itertools
class NotImplementedByController(unittest.SkipTest, NotImplementedError):
def __str__(self):
return 'Not implemented by controller: {}'.format(self.args[0])
class OptionalExtensionNotSupported(unittest.SkipTest):
def __str__(self):
return 'Unsupported extension: {}'.format(self.args[0])
class OptionalSaslMechanismNotSupported(unittest.SkipTest):
def __str__(self):
return 'Unsupported SASL mechanism: {}'.format(self.args[0])
class OptionalityReportingTextTestRunner(unittest.TextTestRunner):
"""Small wrapper around unittest.TextTestRunner that reports the
number of tests that were skipped because the software does not support
an optional feature."""
def run(self, test):
result = super().run(test)
if result.skipped:
print()
print('Some tests were skipped because the following optional'
'specifications/mechanisms are not supported:')
msg_to_tests = itertools.groupby(result.skipped,
key=operator.itemgetter(1))
for (msg, tests) in sorted(msg_to_tests):
print('\t{} ({} test(s))'.format(msg, sum(1 for x in tests)))
return result
|
import unittest
import operator
import collections
class NotImplementedByController(unittest.SkipTest, NotImplementedError):
def __str__(self):
return 'Not implemented by controller: {}'.format(self.args[0])
class OptionalExtensionNotSupported(unittest.SkipTest):
def __str__(self):
return 'Unsupported extension: {}'.format(self.args[0])
class OptionalSaslMechanismNotSupported(unittest.SkipTest):
def __str__(self):
return 'Unsupported SASL mechanism: {}'.format(self.args[0])
class OptionalityReportingTextTestRunner(unittest.TextTestRunner):
"""Small wrapper around unittest.TextTestRunner that reports the
number of tests that were skipped because the software does not support
an optional feature."""
def run(self, test):
result = super().run(test)
if result.skipped:
print()
print('Some tests were skipped because the following optional '
'specifications/mechanisms are not supported:')
msg_to_count = collections.defaultdict(lambda: 0)
for (test, msg) in result.skipped:
msg_to_count[msg] += 1
for (msg, count) in sorted(msg_to_count.items()):
print('\t{} ({} test(s))'.format(msg, count))
return result
|
Fix output of skipped tests.
|
Fix output of skipped tests.
|
Python
|
mit
|
ProgVal/irctest
|
import unittest
import operator
- import itertools
+ import collections
class NotImplementedByController(unittest.SkipTest, NotImplementedError):
def __str__(self):
return 'Not implemented by controller: {}'.format(self.args[0])
class OptionalExtensionNotSupported(unittest.SkipTest):
def __str__(self):
return 'Unsupported extension: {}'.format(self.args[0])
class OptionalSaslMechanismNotSupported(unittest.SkipTest):
def __str__(self):
return 'Unsupported SASL mechanism: {}'.format(self.args[0])
class OptionalityReportingTextTestRunner(unittest.TextTestRunner):
"""Small wrapper around unittest.TextTestRunner that reports the
number of tests that were skipped because the software does not support
an optional feature."""
def run(self, test):
result = super().run(test)
if result.skipped:
print()
- print('Some tests were skipped because the following optional'
+ print('Some tests were skipped because the following optional '
'specifications/mechanisms are not supported:')
- msg_to_tests = itertools.groupby(result.skipped,
- key=operator.itemgetter(1))
+ msg_to_count = collections.defaultdict(lambda: 0)
+ for (test, msg) in result.skipped:
+ msg_to_count[msg] += 1
- for (msg, tests) in sorted(msg_to_tests):
+ for (msg, count) in sorted(msg_to_count.items()):
- print('\t{} ({} test(s))'.format(msg, sum(1 for x in tests)))
+ print('\t{} ({} test(s))'.format(msg, count))
return result
|
Fix output of skipped tests.
|
## Code Before:
import unittest
import operator
import itertools
class NotImplementedByController(unittest.SkipTest, NotImplementedError):
def __str__(self):
return 'Not implemented by controller: {}'.format(self.args[0])
class OptionalExtensionNotSupported(unittest.SkipTest):
def __str__(self):
return 'Unsupported extension: {}'.format(self.args[0])
class OptionalSaslMechanismNotSupported(unittest.SkipTest):
def __str__(self):
return 'Unsupported SASL mechanism: {}'.format(self.args[0])
class OptionalityReportingTextTestRunner(unittest.TextTestRunner):
"""Small wrapper around unittest.TextTestRunner that reports the
number of tests that were skipped because the software does not support
an optional feature."""
def run(self, test):
result = super().run(test)
if result.skipped:
print()
print('Some tests were skipped because the following optional'
'specifications/mechanisms are not supported:')
msg_to_tests = itertools.groupby(result.skipped,
key=operator.itemgetter(1))
for (msg, tests) in sorted(msg_to_tests):
print('\t{} ({} test(s))'.format(msg, sum(1 for x in tests)))
return result
## Instruction:
Fix output of skipped tests.
## Code After:
import unittest
import operator
import collections
class NotImplementedByController(unittest.SkipTest, NotImplementedError):
def __str__(self):
return 'Not implemented by controller: {}'.format(self.args[0])
class OptionalExtensionNotSupported(unittest.SkipTest):
def __str__(self):
return 'Unsupported extension: {}'.format(self.args[0])
class OptionalSaslMechanismNotSupported(unittest.SkipTest):
def __str__(self):
return 'Unsupported SASL mechanism: {}'.format(self.args[0])
class OptionalityReportingTextTestRunner(unittest.TextTestRunner):
"""Small wrapper around unittest.TextTestRunner that reports the
number of tests that were skipped because the software does not support
an optional feature."""
def run(self, test):
result = super().run(test)
if result.skipped:
print()
print('Some tests were skipped because the following optional '
'specifications/mechanisms are not supported:')
msg_to_count = collections.defaultdict(lambda: 0)
for (test, msg) in result.skipped:
msg_to_count[msg] += 1
for (msg, count) in sorted(msg_to_count.items()):
print('\t{} ({} test(s))'.format(msg, count))
return result
|
...
import operator
import collections
...
print()
print('Some tests were skipped because the following optional '
'specifications/mechanisms are not supported:')
msg_to_count = collections.defaultdict(lambda: 0)
for (test, msg) in result.skipped:
msg_to_count[msg] += 1
for (msg, count) in sorted(msg_to_count.items()):
print('\t{} ({} test(s))'.format(msg, count))
return result
...
|
eb2f720d53ea4ff3450e78a30e1cdb53cd3357bb
|
tests/render/texture/runtest.py
|
tests/render/texture/runtest.py
|
import sys
sys.path.insert(0, '../..')
import test_harness
test_harness.register_render_test('render_texture', ['main.cpp'],
'2ec4cc681873bc5978617e347d46f3b38230a3a0',
targets=['emulator'])
test_harness.execute_tests()
|
import sys
sys.path.insert(0, '../..')
import test_harness
test_harness.register_render_test('render_texture', ['main.cpp'],
'feb853e1a54d4ba2ce394142ea6119d5e401a60b',
targets=['emulator'])
test_harness.execute_tests()
|
Fix failing test caused by new toolchain
|
Fix failing test caused by new toolchain
The challenge with floating point values in tests is that the value can
change slightly based on the order of operations, which can legally
be affected by optimizations. The results aren't visible (often just
1 ULP), but the tests validate exact bit patterns.
This test would be more robust if it did a comparison with the target image
and allowed some small amount of variability. Currently it computes a SHA
checksum of the framebuffer.
Updated the checksum for the new toolchain.
|
Python
|
apache-2.0
|
jbush001/NyuziProcessor,jbush001/NyuziProcessor,jbush001/NyuziProcessor,jbush001/NyuziProcessor,jbush001/NyuziProcessor,jbush001/NyuziProcessor
|
import sys
sys.path.insert(0, '../..')
import test_harness
test_harness.register_render_test('render_texture', ['main.cpp'],
- '2ec4cc681873bc5978617e347d46f3b38230a3a0',
+ 'feb853e1a54d4ba2ce394142ea6119d5e401a60b',
targets=['emulator'])
test_harness.execute_tests()
|
Fix failing test caused by new toolchain
|
## Code Before:
import sys
sys.path.insert(0, '../..')
import test_harness
test_harness.register_render_test('render_texture', ['main.cpp'],
'2ec4cc681873bc5978617e347d46f3b38230a3a0',
targets=['emulator'])
test_harness.execute_tests()
## Instruction:
Fix failing test caused by new toolchain
## Code After:
import sys
sys.path.insert(0, '../..')
import test_harness
test_harness.register_render_test('render_texture', ['main.cpp'],
'feb853e1a54d4ba2ce394142ea6119d5e401a60b',
targets=['emulator'])
test_harness.execute_tests()
|
# ... existing code ...
test_harness.register_render_test('render_texture', ['main.cpp'],
'feb853e1a54d4ba2ce394142ea6119d5e401a60b',
targets=['emulator'])
# ... rest of the code ...
|
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'
|
# ... existing code ...
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(
# ... rest of the code ...
|
4636c2deb451c284ffdfc44c744cf025a9f87377
|
scribeui_pyramid/modules/plugins/__init__.py
|
scribeui_pyramid/modules/plugins/__init__.py
|
import imp #For plugins
import sys
import traceback
import logging
import os #For plugins
log = logging.getLogger(__name__)
pluginsList = []
def includeme(config):
global pluginsList
plugins = load_plugins()
for name, plugin in plugins.iteritems():
config.include("..plugins."+name)
pluginsList.append(name)
#===============================
# Plugin load code
#===============================
def load_plugins():
plugins = {}
path = os.path.abspath(os.path.dirname(__file__))
for filename in os.listdir(path):
if os.path.isdir(os.path.join(path, filename)) and os.path.isfile(os.path.join(path, filename, '__init__.py')):
try:
f, pluginPath, descr = imp.find_module(filename, [path])
pluginName = os.path.basename(pluginPath)
plugins[pluginName] = imp.load_module(filename, f, pluginName, descr)
except ImportError:
log.error('There was an error with the '+filename+' plugin:')
traceback.print_exc(file=sys.stdout)
return plugins
|
import imp #For plugins
import sys
import traceback
import logging
import os #For plugins
log = logging.getLogger(__name__)
pluginsList = []
def includeme(config):
global pluginsList
plugins = load_plugins()
for name, plugin in plugins.iteritems():
config.include("..plugins."+name)
pluginsList.append(name)
#===============================
# Plugin load code
#===============================
def load_plugins():
plugins = {}
path = os.path.abspath(os.path.dirname(__file__))
for filename in os.listdir(path):
tmp_path = path
if os.path.isdir(os.path.join(tmp_path, filename)) and os.path.isfile(os.path.join(tmp_path, filename, '__init__.py')):
try:
f, pluginPath, descr = imp.find_module(filename, [tmp_path])
pluginName = os.path.basename(pluginPath)
plugins[pluginName] = imp.load_module(filename, f, pluginName, descr)
except ImportError:
log.error('There was an error with the '+filename+' plugin:')
traceback.print_exc(file=sys.stdout)
return plugins
|
Fix load_plugin loop loading only one plugin
|
Fix load_plugin loop loading only one plugin
|
Python
|
mit
|
mapgears/scribeui,mapgears/scribeui,mapgears/scribeui,mapgears/scribeui,mapgears/scribeui,mapgears/scribeui
|
import imp #For plugins
import sys
import traceback
import logging
import os #For plugins
log = logging.getLogger(__name__)
pluginsList = []
def includeme(config):
global pluginsList
plugins = load_plugins()
for name, plugin in plugins.iteritems():
config.include("..plugins."+name)
pluginsList.append(name)
#===============================
# Plugin load code
#===============================
def load_plugins():
plugins = {}
path = os.path.abspath(os.path.dirname(__file__))
for filename in os.listdir(path):
+ tmp_path = path
- if os.path.isdir(os.path.join(path, filename)) and os.path.isfile(os.path.join(path, filename, '__init__.py')):
+ if os.path.isdir(os.path.join(tmp_path, filename)) and os.path.isfile(os.path.join(tmp_path, filename, '__init__.py')):
try:
- f, pluginPath, descr = imp.find_module(filename, [path])
+ f, pluginPath, descr = imp.find_module(filename, [tmp_path])
pluginName = os.path.basename(pluginPath)
plugins[pluginName] = imp.load_module(filename, f, pluginName, descr)
except ImportError:
log.error('There was an error with the '+filename+' plugin:')
traceback.print_exc(file=sys.stdout)
return plugins
|
Fix load_plugin loop loading only one plugin
|
## Code Before:
import imp #For plugins
import sys
import traceback
import logging
import os #For plugins
log = logging.getLogger(__name__)
pluginsList = []
def includeme(config):
global pluginsList
plugins = load_plugins()
for name, plugin in plugins.iteritems():
config.include("..plugins."+name)
pluginsList.append(name)
#===============================
# Plugin load code
#===============================
def load_plugins():
plugins = {}
path = os.path.abspath(os.path.dirname(__file__))
for filename in os.listdir(path):
if os.path.isdir(os.path.join(path, filename)) and os.path.isfile(os.path.join(path, filename, '__init__.py')):
try:
f, pluginPath, descr = imp.find_module(filename, [path])
pluginName = os.path.basename(pluginPath)
plugins[pluginName] = imp.load_module(filename, f, pluginName, descr)
except ImportError:
log.error('There was an error with the '+filename+' plugin:')
traceback.print_exc(file=sys.stdout)
return plugins
## Instruction:
Fix load_plugin loop loading only one plugin
## Code After:
import imp #For plugins
import sys
import traceback
import logging
import os #For plugins
log = logging.getLogger(__name__)
pluginsList = []
def includeme(config):
global pluginsList
plugins = load_plugins()
for name, plugin in plugins.iteritems():
config.include("..plugins."+name)
pluginsList.append(name)
#===============================
# Plugin load code
#===============================
def load_plugins():
plugins = {}
path = os.path.abspath(os.path.dirname(__file__))
for filename in os.listdir(path):
tmp_path = path
if os.path.isdir(os.path.join(tmp_path, filename)) and os.path.isfile(os.path.join(tmp_path, filename, '__init__.py')):
try:
f, pluginPath, descr = imp.find_module(filename, [tmp_path])
pluginName = os.path.basename(pluginPath)
plugins[pluginName] = imp.load_module(filename, f, pluginName, descr)
except ImportError:
log.error('There was an error with the '+filename+' plugin:')
traceback.print_exc(file=sys.stdout)
return plugins
|
// ... existing code ...
for filename in os.listdir(path):
tmp_path = path
if os.path.isdir(os.path.join(tmp_path, filename)) and os.path.isfile(os.path.join(tmp_path, filename, '__init__.py')):
try:
f, pluginPath, descr = imp.find_module(filename, [tmp_path])
pluginName = os.path.basename(pluginPath)
// ... rest of the code ...
|
32f38eb01c3a203ae35d70b485fcee7b13f1acde
|
tests/help_generation_test.py
|
tests/help_generation_test.py
|
"""Test that we can generate help for PKB."""
import os
import unittest
from perfkitbenchmarker import flags
# Import pkb to add all flag definitions to flags.FLAGS.
from perfkitbenchmarker import pkb # NOQA
class HelpTest(unittest.TestCase):
def testHelp(self):
# Test that help generation finishes without errors
flags.FLAGS.GetHelp()
class HelpXMLTest(unittest.TestCase):
def testHelpXML(self):
with open(os.devnull, 'w') as out:
flags.FLAGS.WriteHelpInXMLFormat(outfile=out)
if __name__ == '__main__':
unittest.main()
|
"""Test that we can generate help for PKB."""
import os
import unittest
from perfkitbenchmarker import flags
# Import pkb to add all flag definitions to flags.FLAGS.
from perfkitbenchmarker import pkb # NOQA
class HelpTest(unittest.TestCase):
def testHelp(self):
# Test that help generation finishes without errors
if hasattr(flags.FLAGS, 'get_help'):
flags.FLAGS.get_help()
else:
flags.FLAGS.GetHelp()
class HelpXMLTest(unittest.TestCase):
def testHelpXML(self):
with open(os.devnull, 'w') as out:
flags.FLAGS.WriteHelpInXMLFormat(outfile=out)
if __name__ == '__main__':
unittest.main()
|
Call FLAGS.get_help if it's available.
|
Call FLAGS.get_help if it's available.
|
Python
|
apache-2.0
|
GoogleCloudPlatform/PerfKitBenchmarker,GoogleCloudPlatform/PerfKitBenchmarker,meteorfox/PerfKitBenchmarker,GoogleCloudPlatform/PerfKitBenchmarker,GoogleCloudPlatform/PerfKitBenchmarker,meteorfox/PerfKitBenchmarker
|
"""Test that we can generate help for PKB."""
import os
import unittest
from perfkitbenchmarker import flags
# Import pkb to add all flag definitions to flags.FLAGS.
from perfkitbenchmarker import pkb # NOQA
class HelpTest(unittest.TestCase):
def testHelp(self):
# Test that help generation finishes without errors
+ if hasattr(flags.FLAGS, 'get_help'):
+ flags.FLAGS.get_help()
+ else:
- flags.FLAGS.GetHelp()
+ flags.FLAGS.GetHelp()
class HelpXMLTest(unittest.TestCase):
def testHelpXML(self):
with open(os.devnull, 'w') as out:
flags.FLAGS.WriteHelpInXMLFormat(outfile=out)
if __name__ == '__main__':
unittest.main()
|
Call FLAGS.get_help if it's available.
|
## Code Before:
"""Test that we can generate help for PKB."""
import os
import unittest
from perfkitbenchmarker import flags
# Import pkb to add all flag definitions to flags.FLAGS.
from perfkitbenchmarker import pkb # NOQA
class HelpTest(unittest.TestCase):
def testHelp(self):
# Test that help generation finishes without errors
flags.FLAGS.GetHelp()
class HelpXMLTest(unittest.TestCase):
def testHelpXML(self):
with open(os.devnull, 'w') as out:
flags.FLAGS.WriteHelpInXMLFormat(outfile=out)
if __name__ == '__main__':
unittest.main()
## Instruction:
Call FLAGS.get_help if it's available.
## Code After:
"""Test that we can generate help for PKB."""
import os
import unittest
from perfkitbenchmarker import flags
# Import pkb to add all flag definitions to flags.FLAGS.
from perfkitbenchmarker import pkb # NOQA
class HelpTest(unittest.TestCase):
def testHelp(self):
# Test that help generation finishes without errors
if hasattr(flags.FLAGS, 'get_help'):
flags.FLAGS.get_help()
else:
flags.FLAGS.GetHelp()
class HelpXMLTest(unittest.TestCase):
def testHelpXML(self):
with open(os.devnull, 'w') as out:
flags.FLAGS.WriteHelpInXMLFormat(outfile=out)
if __name__ == '__main__':
unittest.main()
|
...
# Test that help generation finishes without errors
if hasattr(flags.FLAGS, 'get_help'):
flags.FLAGS.get_help()
else:
flags.FLAGS.GetHelp()
...
|
f3cd06721efaf3045d09f2d3c2c067e01b27953a
|
tests/som_test.py
|
tests/som_test.py
|
import unittest
from parameterized import parameterized
from som.vm.universe import Universe
class SomTest(unittest.TestCase):
@parameterized.expand([
("ClassStructure",),
("Array" ,),
("Block" ,),
("ClassLoading" ,),
("Closure" ,),
("Coercion" ,),
("CompilerReturn",),
("Double" ,),
("DoesNotUnderstand",),
("Empty" ,),
("Global" ,),
("Hash" ,),
("Integer" ,),
("Preliminary" ,),
("Reflection" ,),
("SelfBlock" ,),
("Set",),
("SpecialSelectors",),
("Super" ,),
("String" ,),
("Symbol" ,),
("System" ,),
("Vector" ,)])
def test_som_test(self, test_name):
args = ["-cp", "Smalltalk", "TestSuite/TestHarness.som", test_name]
u = Universe(True)
u.interpret(args)
self.assertEquals(0, u.last_exit_code())
import sys
if 'pytest' in sys.modules:
# hack to make pytest not to collect the unexpanded test method
delattr(SomTest, "test_som_test")
|
import unittest
from parameterized import parameterized
from som.vm.universe import Universe
class SomTest(unittest.TestCase):
@parameterized.expand([
("Array" ,),
("Block" ,),
("ClassLoading" ,),
("ClassStructure",),
("Closure" ,),
("Coercion" ,),
("CompilerReturn",),
("DoesNotUnderstand",),
("Double" ,),
("Empty" ,),
("Global" ,),
("Hash" ,),
("Integer" ,),
("Preliminary" ,),
("Reflection" ,),
("SelfBlock" ,),
("SpecialSelectors",),
("Super" ,),
("Set",),
("String" ,),
("Symbol" ,),
("System" ,),
("Vector" ,)])
def test_som_test(self, test_name):
args = ["-cp", "Smalltalk", "TestSuite/TestHarness.som", test_name]
u = Universe(True)
u.interpret(args)
self.assertEquals(0, u.last_exit_code())
import sys
if 'pytest' in sys.modules:
# hack to make pytest not to collect the unexpanded test method
delattr(SomTest, "test_som_test")
|
Sort tests, to verify they are complete
|
Sort tests, to verify they are complete
Signed-off-by: Stefan Marr <[email protected]>
|
Python
|
mit
|
SOM-st/PySOM,SOM-st/RPySOM,SOM-st/RTruffleSOM,SOM-st/RPySOM,smarr/PySOM,smarr/PySOM,smarr/RTruffleSOM,SOM-st/RTruffleSOM,smarr/RTruffleSOM,SOM-st/PySOM
|
import unittest
from parameterized import parameterized
from som.vm.universe import Universe
class SomTest(unittest.TestCase):
@parameterized.expand([
- ("ClassStructure",),
("Array" ,),
("Block" ,),
("ClassLoading" ,),
+ ("ClassStructure",),
("Closure" ,),
("Coercion" ,),
("CompilerReturn",),
+ ("DoesNotUnderstand",),
("Double" ,),
- ("DoesNotUnderstand",),
("Empty" ,),
("Global" ,),
("Hash" ,),
("Integer" ,),
("Preliminary" ,),
("Reflection" ,),
("SelfBlock" ,),
- ("Set",),
("SpecialSelectors",),
("Super" ,),
+ ("Set",),
("String" ,),
("Symbol" ,),
("System" ,),
("Vector" ,)])
def test_som_test(self, test_name):
args = ["-cp", "Smalltalk", "TestSuite/TestHarness.som", test_name]
u = Universe(True)
u.interpret(args)
self.assertEquals(0, u.last_exit_code())
import sys
if 'pytest' in sys.modules:
# hack to make pytest not to collect the unexpanded test method
delattr(SomTest, "test_som_test")
|
Sort tests, to verify they are complete
|
## Code Before:
import unittest
from parameterized import parameterized
from som.vm.universe import Universe
class SomTest(unittest.TestCase):
@parameterized.expand([
("ClassStructure",),
("Array" ,),
("Block" ,),
("ClassLoading" ,),
("Closure" ,),
("Coercion" ,),
("CompilerReturn",),
("Double" ,),
("DoesNotUnderstand",),
("Empty" ,),
("Global" ,),
("Hash" ,),
("Integer" ,),
("Preliminary" ,),
("Reflection" ,),
("SelfBlock" ,),
("Set",),
("SpecialSelectors",),
("Super" ,),
("String" ,),
("Symbol" ,),
("System" ,),
("Vector" ,)])
def test_som_test(self, test_name):
args = ["-cp", "Smalltalk", "TestSuite/TestHarness.som", test_name]
u = Universe(True)
u.interpret(args)
self.assertEquals(0, u.last_exit_code())
import sys
if 'pytest' in sys.modules:
# hack to make pytest not to collect the unexpanded test method
delattr(SomTest, "test_som_test")
## Instruction:
Sort tests, to verify they are complete
## Code After:
import unittest
from parameterized import parameterized
from som.vm.universe import Universe
class SomTest(unittest.TestCase):
@parameterized.expand([
("Array" ,),
("Block" ,),
("ClassLoading" ,),
("ClassStructure",),
("Closure" ,),
("Coercion" ,),
("CompilerReturn",),
("DoesNotUnderstand",),
("Double" ,),
("Empty" ,),
("Global" ,),
("Hash" ,),
("Integer" ,),
("Preliminary" ,),
("Reflection" ,),
("SelfBlock" ,),
("SpecialSelectors",),
("Super" ,),
("Set",),
("String" ,),
("Symbol" ,),
("System" ,),
("Vector" ,)])
def test_som_test(self, test_name):
args = ["-cp", "Smalltalk", "TestSuite/TestHarness.som", test_name]
u = Universe(True)
u.interpret(args)
self.assertEquals(0, u.last_exit_code())
import sys
if 'pytest' in sys.modules:
# hack to make pytest not to collect the unexpanded test method
delattr(SomTest, "test_som_test")
|
# ... existing code ...
@parameterized.expand([
("Array" ,),
# ... modified code ...
("ClassLoading" ,),
("ClassStructure",),
...
("CompilerReturn",),
("DoesNotUnderstand",),
("Double" ,),
...
("SelfBlock" ,),
("SpecialSelectors",),
...
("Set",),
("String" ,),
# ... rest of the code ...
|
1eb6f65e40fccb3cea4b35374e7ddc25dd574dfa
|
examples/test/test_scratchnet.py
|
examples/test/test_scratchnet.py
|
import unittest
import pexpect
class testScratchNet( unittest.TestCase ):
opts = [ "1 packets transmitted, 1 received, 0% packet loss", pexpect.EOF ]
def pingTest( self, name ):
"Verify that no ping packets were dropped"
p = pexpect.spawn( 'python -m %s' % name )
index = p.expect( self.opts )
self.assertEqual( index, 0 )
def testPingKernel( self ):
self.pingTest( 'mininet.examples.scratchnet' )
def testPingUser( self ):
self.pingTest( 'mininet.examples.scratchnetuser' )
if __name__ == '__main__':
unittest.main()
|
import unittest
import pexpect
class testScratchNet( unittest.TestCase ):
opts = [ "1 packets transmitted, 1 received, 0% packet loss", pexpect.EOF ]
def pingTest( self, name ):
"Verify that no ping packets were dropped"
p = pexpect.spawn( 'python -m %s' % name )
index = p.expect( self.opts, timeout=120 )
self.assertEqual( index, 0 )
def testPingKernel( self ):
self.pingTest( 'mininet.examples.scratchnet' )
def testPingUser( self ):
self.pingTest( 'mininet.examples.scratchnetuser' )
if __name__ == '__main__':
unittest.main()
|
Increase scratchnet timeout to see if it's just slow.
|
Increase scratchnet timeout to see if it's just slow.
|
Python
|
bsd-3-clause
|
mininet/mininet,mininet/mininet,mininet/mininet
|
import unittest
import pexpect
class testScratchNet( unittest.TestCase ):
opts = [ "1 packets transmitted, 1 received, 0% packet loss", pexpect.EOF ]
def pingTest( self, name ):
"Verify that no ping packets were dropped"
p = pexpect.spawn( 'python -m %s' % name )
- index = p.expect( self.opts )
+ index = p.expect( self.opts, timeout=120 )
self.assertEqual( index, 0 )
def testPingKernel( self ):
self.pingTest( 'mininet.examples.scratchnet' )
def testPingUser( self ):
self.pingTest( 'mininet.examples.scratchnetuser' )
if __name__ == '__main__':
unittest.main()
|
Increase scratchnet timeout to see if it's just slow.
|
## Code Before:
import unittest
import pexpect
class testScratchNet( unittest.TestCase ):
opts = [ "1 packets transmitted, 1 received, 0% packet loss", pexpect.EOF ]
def pingTest( self, name ):
"Verify that no ping packets were dropped"
p = pexpect.spawn( 'python -m %s' % name )
index = p.expect( self.opts )
self.assertEqual( index, 0 )
def testPingKernel( self ):
self.pingTest( 'mininet.examples.scratchnet' )
def testPingUser( self ):
self.pingTest( 'mininet.examples.scratchnetuser' )
if __name__ == '__main__':
unittest.main()
## Instruction:
Increase scratchnet timeout to see if it's just slow.
## Code After:
import unittest
import pexpect
class testScratchNet( unittest.TestCase ):
opts = [ "1 packets transmitted, 1 received, 0% packet loss", pexpect.EOF ]
def pingTest( self, name ):
"Verify that no ping packets were dropped"
p = pexpect.spawn( 'python -m %s' % name )
index = p.expect( self.opts, timeout=120 )
self.assertEqual( index, 0 )
def testPingKernel( self ):
self.pingTest( 'mininet.examples.scratchnet' )
def testPingUser( self ):
self.pingTest( 'mininet.examples.scratchnetuser' )
if __name__ == '__main__':
unittest.main()
|
...
p = pexpect.spawn( 'python -m %s' % name )
index = p.expect( self.opts, timeout=120 )
self.assertEqual( index, 0 )
...
|
badda02f6cc81a8c5670b6f53e67009a3cb8b66f
|
rmake/core/constants.py
|
rmake/core/constants.py
|
JOB_OK = 200
JOB_FAILED = 400
# Status codes for a task
TASK_OK = 200
TASK_FAILED = 400
TASK_NOT_ASSIGNABLE = 401
# "ok" code for WorkerInfo.getScore() -- when can this task be assigned?
A_NOW = 0
A_LATER = 1
A_NEVER = 2
A_WRONG_ZONE = 3
|
JOB_OK = 200
# Generic failure. Core failure codes will be in the range 450-499 and 550-599.
# All others are reserved for plugins.
JOB_FAILED = 450
# Status codes for a task
TASK_OK = 200
# See above note about core failure codes.
TASK_FAILED = 450
TASK_NOT_ASSIGNABLE = 451
# "ok" code for WorkerInfo.getScore() -- when can this task be assigned?
A_NOW = 0
A_LATER = 1
A_NEVER = 2
A_WRONG_ZONE = 3
|
Relocate core status codes to the 450-499 range
|
Relocate core status codes to the 450-499 range
|
Python
|
apache-2.0
|
sassoftware/rmake3,sassoftware/rmake3,sassoftware/rmake3
|
JOB_OK = 200
+ # Generic failure. Core failure codes will be in the range 450-499 and 550-599.
+ # All others are reserved for plugins.
- JOB_FAILED = 400
+ JOB_FAILED = 450
# Status codes for a task
TASK_OK = 200
+ # See above note about core failure codes.
- TASK_FAILED = 400
+ TASK_FAILED = 450
- TASK_NOT_ASSIGNABLE = 401
+ TASK_NOT_ASSIGNABLE = 451
# "ok" code for WorkerInfo.getScore() -- when can this task be assigned?
A_NOW = 0
A_LATER = 1
A_NEVER = 2
A_WRONG_ZONE = 3
|
Relocate core status codes to the 450-499 range
|
## Code Before:
JOB_OK = 200
JOB_FAILED = 400
# Status codes for a task
TASK_OK = 200
TASK_FAILED = 400
TASK_NOT_ASSIGNABLE = 401
# "ok" code for WorkerInfo.getScore() -- when can this task be assigned?
A_NOW = 0
A_LATER = 1
A_NEVER = 2
A_WRONG_ZONE = 3
## Instruction:
Relocate core status codes to the 450-499 range
## Code After:
JOB_OK = 200
# Generic failure. Core failure codes will be in the range 450-499 and 550-599.
# All others are reserved for plugins.
JOB_FAILED = 450
# Status codes for a task
TASK_OK = 200
# See above note about core failure codes.
TASK_FAILED = 450
TASK_NOT_ASSIGNABLE = 451
# "ok" code for WorkerInfo.getScore() -- when can this task be assigned?
A_NOW = 0
A_LATER = 1
A_NEVER = 2
A_WRONG_ZONE = 3
|
...
JOB_OK = 200
# Generic failure. Core failure codes will be in the range 450-499 and 550-599.
# All others are reserved for plugins.
JOB_FAILED = 450
...
TASK_OK = 200
# See above note about core failure codes.
TASK_FAILED = 450
TASK_NOT_ASSIGNABLE = 451
...
|
9d2d41f8450f6f3735b8ff9a0041f9bf5d80e5ec
|
config/template.py
|
config/template.py
|
DB_USER = ''
DB_HOST = ''
DB_PASSWORD = ''
DB_NAME = ''
|
DB_USER = ''
DB_HOST = ''
DB_PASSWORD = ''
DB_NAME = ''
TWILIO_NUMBERS = ['']
|
Allow for representative view display with sample configuration
|
Allow for representative view display with sample configuration
|
Python
|
mit
|
PeterTheOne/ueberwachungspaket.at,PeterTheOne/ueberwachungspaket.at,PeterTheOne/ueberwachungspaket.at
|
DB_USER = ''
DB_HOST = ''
DB_PASSWORD = ''
DB_NAME = ''
+ TWILIO_NUMBERS = ['']
+
|
Allow for representative view display with sample configuration
|
## Code Before:
DB_USER = ''
DB_HOST = ''
DB_PASSWORD = ''
DB_NAME = ''
## Instruction:
Allow for representative view display with sample configuration
## Code After:
DB_USER = ''
DB_HOST = ''
DB_PASSWORD = ''
DB_NAME = ''
TWILIO_NUMBERS = ['']
|
# ... existing code ...
DB_NAME = ''
TWILIO_NUMBERS = ['']
# ... rest of the code ...
|
6c54fc230e8c889a2351f20b524382a5c6e29d1c
|
examples/apps.py
|
examples/apps.py
|
import os
import sys
from pysuru import TsuruClient
TSURU_TARGET = os.environ.get('TSURU_TARGET', None)
TSURU_TOKEN = os.environ.get('TSURU_TOKEN', None)
if not TSURU_TARGET or not TSURU_TOKEN:
print('You must set TSURU_TARGET and TSURU_TOKEN.')
sys.exit(1)
api = TsuruClient(TSURU_TARGET, TSURU_TOKEN)
# List all apps that this token has access to
for app in api.apps:
print(app.name)
# Update one specific app
api.apps.update('my-awesome-app', {'description': 'My awesome app'})
# Get information for one app
app = App.get('my-awesome-app')
print('%s: %s' % (app.name, app.description))
# List all services instances for app
for service in app.services:
print('Service: %s' % service.name)
|
import os
import sys
from pysuru import TsuruClient
TSURU_TARGET = os.environ.get('TSURU_TARGET', None)
TSURU_TOKEN = os.environ.get('TSURU_TOKEN', None)
if not TSURU_TARGET or not TSURU_TOKEN:
print('You must set TSURU_TARGET and TSURU_TOKEN env variables.')
sys.exit(1)
# Creating TsuruClient instance
tsuru = TsuruClient(TSURU_TARGET, TSURU_TOKEN)
# List all apps that this user has access to
for app in tsuru.apps.list():
print('App: {}'.format(app.name))
# Get information for one app
app = tsuru.apps.get('my-awesome-app')
print('{app.name}: {app.description}'.format(app=app))
# Update specific app
tsuru.apps.update('my-awesome-app', {'description': 'My new awesome description'})
|
Update examples to match docs
|
Update examples to match docs
Use the interface defined in the docs in the examples scripts.
|
Python
|
mit
|
rcmachado/pysuru
|
import os
import sys
from pysuru import TsuruClient
TSURU_TARGET = os.environ.get('TSURU_TARGET', None)
TSURU_TOKEN = os.environ.get('TSURU_TOKEN', None)
if not TSURU_TARGET or not TSURU_TOKEN:
- print('You must set TSURU_TARGET and TSURU_TOKEN.')
+ print('You must set TSURU_TARGET and TSURU_TOKEN env variables.')
sys.exit(1)
+ # Creating TsuruClient instance
- api = TsuruClient(TSURU_TARGET, TSURU_TOKEN)
+ tsuru = TsuruClient(TSURU_TARGET, TSURU_TOKEN)
- # List all apps that this token has access to
+ # List all apps that this user has access to
+ for app in tsuru.apps.list():
+ print('App: {}'.format(app.name))
- for app in api.apps:
- print(app.name)
-
- # Update one specific app
- api.apps.update('my-awesome-app', {'description': 'My awesome app'})
# Get information for one app
- app = App.get('my-awesome-app')
+ app = tsuru.apps.get('my-awesome-app')
- print('%s: %s' % (app.name, app.description))
+ print('{app.name}: {app.description}'.format(app=app))
+ # Update specific app
+ tsuru.apps.update('my-awesome-app', {'description': 'My new awesome description'})
- # List all services instances for app
- for service in app.services:
- print('Service: %s' % service.name)
|
Update examples to match docs
|
## Code Before:
import os
import sys
from pysuru import TsuruClient
TSURU_TARGET = os.environ.get('TSURU_TARGET', None)
TSURU_TOKEN = os.environ.get('TSURU_TOKEN', None)
if not TSURU_TARGET or not TSURU_TOKEN:
print('You must set TSURU_TARGET and TSURU_TOKEN.')
sys.exit(1)
api = TsuruClient(TSURU_TARGET, TSURU_TOKEN)
# List all apps that this token has access to
for app in api.apps:
print(app.name)
# Update one specific app
api.apps.update('my-awesome-app', {'description': 'My awesome app'})
# Get information for one app
app = App.get('my-awesome-app')
print('%s: %s' % (app.name, app.description))
# List all services instances for app
for service in app.services:
print('Service: %s' % service.name)
## Instruction:
Update examples to match docs
## Code After:
import os
import sys
from pysuru import TsuruClient
TSURU_TARGET = os.environ.get('TSURU_TARGET', None)
TSURU_TOKEN = os.environ.get('TSURU_TOKEN', None)
if not TSURU_TARGET or not TSURU_TOKEN:
print('You must set TSURU_TARGET and TSURU_TOKEN env variables.')
sys.exit(1)
# Creating TsuruClient instance
tsuru = TsuruClient(TSURU_TARGET, TSURU_TOKEN)
# List all apps that this user has access to
for app in tsuru.apps.list():
print('App: {}'.format(app.name))
# Get information for one app
app = tsuru.apps.get('my-awesome-app')
print('{app.name}: {app.description}'.format(app=app))
# Update specific app
tsuru.apps.update('my-awesome-app', {'description': 'My new awesome description'})
|
// ... existing code ...
if not TSURU_TARGET or not TSURU_TOKEN:
print('You must set TSURU_TARGET and TSURU_TOKEN env variables.')
sys.exit(1)
// ... modified code ...
# Creating TsuruClient instance
tsuru = TsuruClient(TSURU_TARGET, TSURU_TOKEN)
# List all apps that this user has access to
for app in tsuru.apps.list():
print('App: {}'.format(app.name))
...
# Get information for one app
app = tsuru.apps.get('my-awesome-app')
print('{app.name}: {app.description}'.format(app=app))
# Update specific app
tsuru.apps.update('my-awesome-app', {'description': 'My new awesome description'})
// ... rest of the code ...
|
31a4253288637070f50a398cd80250176e785a19
|
rnacentral_pipeline/cli/genes.py
|
rnacentral_pipeline/cli/genes.py
|
import click
from rnacentral_pipeline.rnacentral.genes import build, write
@click.group("genes")
def cli():
"""
A group of commands dealing with building genes.
"""
pass
@cli.command("build")
@click.option("--format", type=click.Choice(write.Format.names(), case_sensitive=False))
@click.argument("data_file", type=click.File("r"))
@click.argument("output", type=click.File("w"))
def build_genes(data_file, output, format=None):
"""
Build the genes for the given data file. This assumes that the file is
already split into reasonable chunks.
"""
data = build.from_json(data_file)
write.write(data, write.Format.from_name(format), output)
|
import click
from rnacentral_pipeline.rnacentral.genes import build, write
@click.group("genes")
def cli():
"""
A group of commands dealing with building genes.
"""
pass
@cli.command("build")
@click.option(
"--format",
default="csv",
type=click.Choice(write.Format.names(), case_sensitive=False),
)
@click.argument("data_file", type=click.File("r"))
@click.argument("output", type=click.File("w"))
def build_genes(data_file, output, format=None):
"""
Build the genes for the given data file. The file can contain all data for a
specific assembly.
"""
data = build.from_json(data_file)
write.write(data, write.Format.from_name(format), output)
|
Clean up CLI a bit
|
Clean up CLI a bit
Default arguments are useful.
|
Python
|
apache-2.0
|
RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline
|
import click
from rnacentral_pipeline.rnacentral.genes import build, write
@click.group("genes")
def cli():
"""
A group of commands dealing with building genes.
"""
pass
@cli.command("build")
+ @click.option(
+ "--format",
+ default="csv",
- @click.option("--format", type=click.Choice(write.Format.names(), case_sensitive=False))
+ type=click.Choice(write.Format.names(), case_sensitive=False),
+ )
@click.argument("data_file", type=click.File("r"))
@click.argument("output", type=click.File("w"))
def build_genes(data_file, output, format=None):
"""
- Build the genes for the given data file. This assumes that the file is
- already split into reasonable chunks.
+ Build the genes for the given data file. The file can contain all data for a
+ specific assembly.
"""
data = build.from_json(data_file)
write.write(data, write.Format.from_name(format), output)
|
Clean up CLI a bit
|
## Code Before:
import click
from rnacentral_pipeline.rnacentral.genes import build, write
@click.group("genes")
def cli():
"""
A group of commands dealing with building genes.
"""
pass
@cli.command("build")
@click.option("--format", type=click.Choice(write.Format.names(), case_sensitive=False))
@click.argument("data_file", type=click.File("r"))
@click.argument("output", type=click.File("w"))
def build_genes(data_file, output, format=None):
"""
Build the genes for the given data file. This assumes that the file is
already split into reasonable chunks.
"""
data = build.from_json(data_file)
write.write(data, write.Format.from_name(format), output)
## Instruction:
Clean up CLI a bit
## Code After:
import click
from rnacentral_pipeline.rnacentral.genes import build, write
@click.group("genes")
def cli():
"""
A group of commands dealing with building genes.
"""
pass
@cli.command("build")
@click.option(
"--format",
default="csv",
type=click.Choice(write.Format.names(), case_sensitive=False),
)
@click.argument("data_file", type=click.File("r"))
@click.argument("output", type=click.File("w"))
def build_genes(data_file, output, format=None):
"""
Build the genes for the given data file. The file can contain all data for a
specific assembly.
"""
data = build.from_json(data_file)
write.write(data, write.Format.from_name(format), output)
|
...
@cli.command("build")
@click.option(
"--format",
default="csv",
type=click.Choice(write.Format.names(), case_sensitive=False),
)
@click.argument("data_file", type=click.File("r"))
...
"""
Build the genes for the given data file. The file can contain all data for a
specific assembly.
"""
...
|
8bd3b1eb25d2207e33cd8970ac2cf739c983e191
|
properties/__init__.py
|
properties/__init__.py
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from .base import (
HasProperties,
Instance,
List,
Union,
)
from .basic import (
Bool,
Color,
Complex,
DateTime,
Float,
GettableProperty,
Integer,
Property,
String,
StringChoice,
Uuid,
)
from .math import (
Array,
Vector2,
Vector2Array,
Vector3,
Vector3Array,
)
from .images import (
ImagePNG
)
from .utils import defaults, filter_props, undefined
from .handlers import observer, validator
from . import task
__version__ = '0.2.3'
__author__ = '3point Science'
__license__ = 'MIT'
__copyright__ = 'Copyright 2016 3point Science,'
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from .base import (
HasProperties,
Instance,
List,
Union,
)
from .basic import (
Bool,
Color,
Complex,
DateTime,
Float,
GettableProperty,
Integer,
Property,
String,
StringChoice,
Uuid,
)
# Attempt to import image classes. Requires:
# >> pip install properties[image]
# or
# >> pip install properties[full]
try:
from .images import (
ImagePNG
)
except ImportError:
pass
# Attempt to import math/array classes. Requires:
# >> pip install properties[math]
# or
# >> pip install properties[full]
try:
from .math import (
Array,
Vector2,
Vector2Array,
Vector3,
Vector3Array,
)
except ImportError:
pass
from .utils import defaults, filter_props, undefined
from .handlers import observer, validator
from . import task
__version__ = '0.2.3'
__author__ = '3point Science'
__license__ = 'MIT'
__copyright__ = 'Copyright 2016 3point Science,'
|
Modify init to only import available modules
|
Modify init to only import available modules
|
Python
|
mit
|
aranzgeo/properties,3ptscience/properties
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from .base import (
HasProperties,
Instance,
List,
Union,
)
+
from .basic import (
Bool,
Color,
Complex,
DateTime,
Float,
GettableProperty,
Integer,
Property,
String,
StringChoice,
Uuid,
)
+
+ # Attempt to import image classes. Requires:
+ # >> pip install properties[image]
+ # or
+ # >> pip install properties[full]
+ try:
- from .math import (
- Array,
- Vector2,
- Vector2Array,
- Vector3,
- Vector3Array,
- )
- from .images import (
+ from .images import (
- ImagePNG
+ ImagePNG
- )
+ )
+ except ImportError:
+ pass
+
+ # Attempt to import math/array classes. Requires:
+ # >> pip install properties[math]
+ # or
+ # >> pip install properties[full]
+ try:
+ from .math import (
+ Array,
+ Vector2,
+ Vector2Array,
+ Vector3,
+ Vector3Array,
+ )
+ except ImportError:
+ pass
+
from .utils import defaults, filter_props, undefined
from .handlers import observer, validator
from . import task
__version__ = '0.2.3'
__author__ = '3point Science'
__license__ = 'MIT'
__copyright__ = 'Copyright 2016 3point Science,'
|
Modify init to only import available modules
|
## Code Before:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from .base import (
HasProperties,
Instance,
List,
Union,
)
from .basic import (
Bool,
Color,
Complex,
DateTime,
Float,
GettableProperty,
Integer,
Property,
String,
StringChoice,
Uuid,
)
from .math import (
Array,
Vector2,
Vector2Array,
Vector3,
Vector3Array,
)
from .images import (
ImagePNG
)
from .utils import defaults, filter_props, undefined
from .handlers import observer, validator
from . import task
__version__ = '0.2.3'
__author__ = '3point Science'
__license__ = 'MIT'
__copyright__ = 'Copyright 2016 3point Science,'
## Instruction:
Modify init to only import available modules
## Code After:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from .base import (
HasProperties,
Instance,
List,
Union,
)
from .basic import (
Bool,
Color,
Complex,
DateTime,
Float,
GettableProperty,
Integer,
Property,
String,
StringChoice,
Uuid,
)
# Attempt to import image classes. Requires:
# >> pip install properties[image]
# or
# >> pip install properties[full]
try:
from .images import (
ImagePNG
)
except ImportError:
pass
# Attempt to import math/array classes. Requires:
# >> pip install properties[math]
# or
# >> pip install properties[full]
try:
from .math import (
Array,
Vector2,
Vector2Array,
Vector3,
Vector3Array,
)
except ImportError:
pass
from .utils import defaults, filter_props, undefined
from .handlers import observer, validator
from . import task
__version__ = '0.2.3'
__author__ = '3point Science'
__license__ = 'MIT'
__copyright__ = 'Copyright 2016 3point Science,'
|
// ... existing code ...
)
from .basic import (
// ... modified code ...
)
# Attempt to import image classes. Requires:
# >> pip install properties[image]
# or
# >> pip install properties[full]
try:
from .images import (
ImagePNG
)
except ImportError:
pass
# Attempt to import math/array classes. Requires:
# >> pip install properties[math]
# or
# >> pip install properties[full]
try:
from .math import (
Array,
Vector2,
Vector2Array,
Vector3,
Vector3Array,
)
except ImportError:
pass
from .utils import defaults, filter_props, undefined
// ... rest of the code ...
|
3436b94a4c69b843c65f6ddf6756c18ca540c090
|
linked-list/is-list-palindrome.py
|
linked-list/is-list-palindrome.py
|
class Node(object): # define constructor
def __init__(self, value):
self.value = value
self.next = None
def is_list_palindrome(l):
if not l.value or not l.next.value:
return True
def create_nodes(l):
root = Node(-1)
current_node = root
for value in l:
current_node.next = Node(value)
current_node = current_node.next
return root.next
|
class Node(object): # define constructor
def __init__(self, value):
self.value = value
self.next = None
def is_list_palindrome(l):
if not l.value or not l.next.value:
return True
fake_head = Node(None)
fake_head.next = l
fast_node = fake_head
slow_node = fake_head
while fast_node.next and fast_node.next.next:
fast_node = fast_node.next.next
slow_node = slow_node.next
def create_nodes(l):
root = Node(-1)
current_node = root
for value in l:
current_node.next = Node(value)
current_node = current_node.next
return root.next
is_list_palindrome(create_nodes([1, 2, 3, 4]))
|
Create fast node that is twice the speed of slow node to get to center of list
|
Create fast node that is twice the speed of slow node to get to center of list
|
Python
|
mit
|
derekmpham/interview-prep,derekmpham/interview-prep
|
class Node(object): # define constructor
def __init__(self, value):
self.value = value
self.next = None
def is_list_palindrome(l):
if not l.value or not l.next.value:
return True
+ fake_head = Node(None)
+ fake_head.next = l
+ fast_node = fake_head
+ slow_node = fake_head
+
+ while fast_node.next and fast_node.next.next:
+ fast_node = fast_node.next.next
+ slow_node = slow_node.next
+
def create_nodes(l):
root = Node(-1)
current_node = root
for value in l:
current_node.next = Node(value)
current_node = current_node.next
return root.next
+
+
+ is_list_palindrome(create_nodes([1, 2, 3, 4]))
+
|
Create fast node that is twice the speed of slow node to get to center of list
|
## Code Before:
class Node(object): # define constructor
def __init__(self, value):
self.value = value
self.next = None
def is_list_palindrome(l):
if not l.value or not l.next.value:
return True
def create_nodes(l):
root = Node(-1)
current_node = root
for value in l:
current_node.next = Node(value)
current_node = current_node.next
return root.next
## Instruction:
Create fast node that is twice the speed of slow node to get to center of list
## Code After:
class Node(object): # define constructor
def __init__(self, value):
self.value = value
self.next = None
def is_list_palindrome(l):
if not l.value or not l.next.value:
return True
fake_head = Node(None)
fake_head.next = l
fast_node = fake_head
slow_node = fake_head
while fast_node.next and fast_node.next.next:
fast_node = fast_node.next.next
slow_node = slow_node.next
def create_nodes(l):
root = Node(-1)
current_node = root
for value in l:
current_node.next = Node(value)
current_node = current_node.next
return root.next
is_list_palindrome(create_nodes([1, 2, 3, 4]))
|
...
fake_head = Node(None)
fake_head.next = l
fast_node = fake_head
slow_node = fake_head
while fast_node.next and fast_node.next.next:
fast_node = fast_node.next.next
slow_node = slow_node.next
def create_nodes(l):
...
return root.next
is_list_palindrome(create_nodes([1, 2, 3, 4]))
...
|
bb2c92732ee7cf834d937025a03c87d7ee5bc343
|
tests/modules/test_traffic.py
|
tests/modules/test_traffic.py
|
import mock
import unittest
import tests.mocks as mocks
from bumblebee.modules.traffic import Module
class TestTrafficModule(unittest.TestCase):
def setUp(self):
mocks.setup_test(self, Module)
def test_default_format(self):
self.assertEqual(self.module._format, "{:.2f}")
def test_get_minwidth_str(self):
# default value (two digits after dot)
self.assertEqual(self.module.get_minwidth_str(), "1000.00MB")
# integer value
self.module._format = "{:.0f}"
self.assertEqual(self.module.get_minwidth_str(), "1000MB")
# just one digit after dot
self.module._format = "{:.1f}"
self.assertEqual(self.module.get_minwidth_str(), "1000.0MB")
|
import mock
import unittest
import tests.mocks as mocks
from bumblebee.modules.traffic import Module
class TestTrafficModule(unittest.TestCase):
def setUp(self):
mocks.setup_test(self, Module)
def test_default_format(self):
self.assertEqual(self.module._format, "{:.2f}")
def test_get_minwidth_str(self):
# default value (two digits after dot)
self.assertEqual(self.module.get_minwidth_str(), "1000.00KiB/s")
# integer value
self.module._format = "{:.0f}"
self.assertEqual(self.module.get_minwidth_str(), "1000KiB/s")
# just one digit after dot
self.module._format = "{:.1f}"
self.assertEqual(self.module.get_minwidth_str(), "1000.0KiB/s")
|
Fix tests for module traffic
|
[tests/traffic] Fix tests for module traffic
|
Python
|
mit
|
tobi-wan-kenobi/bumblebee-status,tobi-wan-kenobi/bumblebee-status
|
import mock
import unittest
import tests.mocks as mocks
from bumblebee.modules.traffic import Module
class TestTrafficModule(unittest.TestCase):
def setUp(self):
mocks.setup_test(self, Module)
def test_default_format(self):
self.assertEqual(self.module._format, "{:.2f}")
def test_get_minwidth_str(self):
# default value (two digits after dot)
- self.assertEqual(self.module.get_minwidth_str(), "1000.00MB")
+ self.assertEqual(self.module.get_minwidth_str(), "1000.00KiB/s")
# integer value
self.module._format = "{:.0f}"
- self.assertEqual(self.module.get_minwidth_str(), "1000MB")
+ self.assertEqual(self.module.get_minwidth_str(), "1000KiB/s")
# just one digit after dot
self.module._format = "{:.1f}"
- self.assertEqual(self.module.get_minwidth_str(), "1000.0MB")
+ self.assertEqual(self.module.get_minwidth_str(), "1000.0KiB/s")
|
Fix tests for module traffic
|
## Code Before:
import mock
import unittest
import tests.mocks as mocks
from bumblebee.modules.traffic import Module
class TestTrafficModule(unittest.TestCase):
def setUp(self):
mocks.setup_test(self, Module)
def test_default_format(self):
self.assertEqual(self.module._format, "{:.2f}")
def test_get_minwidth_str(self):
# default value (two digits after dot)
self.assertEqual(self.module.get_minwidth_str(), "1000.00MB")
# integer value
self.module._format = "{:.0f}"
self.assertEqual(self.module.get_minwidth_str(), "1000MB")
# just one digit after dot
self.module._format = "{:.1f}"
self.assertEqual(self.module.get_minwidth_str(), "1000.0MB")
## Instruction:
Fix tests for module traffic
## Code After:
import mock
import unittest
import tests.mocks as mocks
from bumblebee.modules.traffic import Module
class TestTrafficModule(unittest.TestCase):
def setUp(self):
mocks.setup_test(self, Module)
def test_default_format(self):
self.assertEqual(self.module._format, "{:.2f}")
def test_get_minwidth_str(self):
# default value (two digits after dot)
self.assertEqual(self.module.get_minwidth_str(), "1000.00KiB/s")
# integer value
self.module._format = "{:.0f}"
self.assertEqual(self.module.get_minwidth_str(), "1000KiB/s")
# just one digit after dot
self.module._format = "{:.1f}"
self.assertEqual(self.module.get_minwidth_str(), "1000.0KiB/s")
|
...
# default value (two digits after dot)
self.assertEqual(self.module.get_minwidth_str(), "1000.00KiB/s")
# integer value
...
self.module._format = "{:.0f}"
self.assertEqual(self.module.get_minwidth_str(), "1000KiB/s")
# just one digit after dot
...
self.module._format = "{:.1f}"
self.assertEqual(self.module.get_minwidth_str(), "1000.0KiB/s")
...
|
55b7b07986590c4ab519fcda3c973c87ad23596b
|
flask_admin/model/typefmt.py
|
flask_admin/model/typefmt.py
|
from jinja2 import Markup
def null_formatter(value):
"""
Return `NULL` as the string for `None` value
:param value:
Value to check
"""
return Markup('<i>NULL</i>')
def empty_formatter(value):
"""
Return empty string for `None` value
:param value:
Value to check
"""
return ''
def bool_formatter(value):
"""
Return check icon if value is `True` or empty string otherwise.
:param value:
Value to check
"""
return Markup('<i class="icon-ok"></i>' if value else '')
DEFAULT_FORMATTERS = {
type(None): empty_formatter,
bool: bool_formatter
}
|
from jinja2 import Markup
def null_formatter(value):
"""
Return `NULL` as the string for `None` value
:param value:
Value to check
"""
return Markup('<i>NULL</i>')
def empty_formatter(value):
"""
Return empty string for `None` value
:param value:
Value to check
"""
return ''
def bool_formatter(value):
"""
Return check icon if value is `True` or empty string otherwise.
:param value:
Value to check
"""
return Markup('<i class="icon-ok"></i>' if value else '')
def list_formatter(values):
"""
Return string with comma separated values
:param values:
Value to check
"""
return u', '.join(values)
DEFAULT_FORMATTERS = {
type(None): empty_formatter,
bool: bool_formatter,
list: list_formatter,
}
|
Add extra type formatter for `list` type
|
Add extra type formatter for `list` type
|
Python
|
bsd-3-clause
|
mrjoes/flask-admin,janusnic/flask-admin,Kha/flask-admin,wuxiangfeng/flask-admin,litnimax/flask-admin,HermasT/flask-admin,quokkaproject/flask-admin,Kha/flask-admin,flabe81/flask-admin,porduna/flask-admin,Junnplus/flask-admin,ibushong/test-repo,janusnic/flask-admin,jschneier/flask-admin,closeio/flask-admin,chase-seibert/flask-admin,litnimax/flask-admin,ArtemSerga/flask-admin,flask-admin/flask-admin,NickWoodhams/flask-admin,LennartP/flask-admin,late-warrior/flask-admin,likaiguo/flask-admin,iurisilvio/flask-admin,mikelambert/flask-admin,jamesbeebop/flask-admin,quokkaproject/flask-admin,mrjoes/flask-admin,pawl/flask-admin,jschneier/flask-admin,toddetzel/flask-admin,rochacbruno/flask-admin,ArtemSerga/flask-admin,Junnplus/flask-admin,torotil/flask-admin,ondoheer/flask-admin,plaes/flask-admin,AlmogCohen/flask-admin,plaes/flask-admin,wangjun/flask-admin,dxmo/flask-admin,jmagnusson/flask-admin,marrybird/flask-admin,torotil/flask-admin,wuxiangfeng/flask-admin,CoolCloud/flask-admin,toddetzel/flask-admin,lifei/flask-admin,ondoheer/flask-admin,phantomxc/flask-admin,mikelambert/flask-admin,mrjoes/flask-admin,petrus-jvrensburg/flask-admin,CoolCloud/flask-admin,wangjun/flask-admin,iurisilvio/flask-admin,petrus-jvrensburg/flask-admin,lifei/flask-admin,mikelambert/flask-admin,sfermigier/flask-admin,radioprotector/flask-admin,wuxiangfeng/flask-admin,petrus-jvrensburg/flask-admin,iurisilvio/flask-admin,likaiguo/flask-admin,jschneier/flask-admin,litnimax/flask-admin,flask-admin/flask-admin,petrus-jvrensburg/flask-admin,plaes/flask-admin,ibushong/test-repo,flask-admin/flask-admin,torotil/flask-admin,radioprotector/flask-admin,rochacbruno/flask-admin,wuxiangfeng/flask-admin,HermasT/flask-admin,LennartP/flask-admin,marrybird/flask-admin,dxmo/flask-admin,flask-admin/flask-admin,phantomxc/flask-admin,LennartP/flask-admin,chase-seibert/flask-admin,plaes/flask-admin,marrybird/flask-admin,mikelambert/flask-admin,wangjun/flask-admin,ArtemSerga/flask-admin,AlmogCohen/flask-admin,AlmogCohen/flask-admin,ondoheer/flask-admin,closeio/flask-admin,rochacbruno/flask-admin,flabe81/flask-admin,AlmogCohen/flask-admin,lifei/flask-admin,jmagnusson/flask-admin,mrjoes/flask-admin,pawl/flask-admin,torotil/flask-admin,likaiguo/flask-admin,HermasT/flask-admin,flabe81/flask-admin,porduna/flask-admin,iurisilvio/flask-admin,NickWoodhams/flask-admin,late-warrior/flask-admin,porduna/flask-admin,radioprotector/flask-admin,chase-seibert/flask-admin,CoolCloud/flask-admin,toddetzel/flask-admin,betterlife/flask-admin,betterlife/flask-admin,lifei/flask-admin,porduna/flask-admin,quokkaproject/flask-admin,rochacbruno/flask-admin,jschneier/flask-admin,late-warrior/flask-admin,pawl/flask-admin,toddetzel/flask-admin,phantomxc/flask-admin,late-warrior/flask-admin,wangjun/flask-admin,ondoheer/flask-admin,ibushong/test-repo,jmagnusson/flask-admin,CoolCloud/flask-admin,closeio/flask-admin,ArtemSerga/flask-admin,jamesbeebop/flask-admin,janusnic/flask-admin,marrybird/flask-admin,jamesbeebop/flask-admin,LennartP/flask-admin,phantomxc/flask-admin,Kha/flask-admin,radioprotector/flask-admin,flabe81/flask-admin,betterlife/flask-admin,sfermigier/flask-admin,jamesbeebop/flask-admin,closeio/flask-admin,Kha/flask-admin,Junnplus/flask-admin,Junnplus/flask-admin,ibushong/test-repo,dxmo/flask-admin,NickWoodhams/flask-admin,NickWoodhams/flask-admin,quokkaproject/flask-admin,sfermigier/flask-admin,likaiguo/flask-admin,HermasT/flask-admin,litnimax/flask-admin,jmagnusson/flask-admin,dxmo/flask-admin,betterlife/flask-admin,chase-seibert/flask-admin,janusnic/flask-admin
|
from jinja2 import Markup
def null_formatter(value):
"""
Return `NULL` as the string for `None` value
:param value:
Value to check
"""
return Markup('<i>NULL</i>')
def empty_formatter(value):
"""
Return empty string for `None` value
:param value:
Value to check
"""
return ''
def bool_formatter(value):
"""
Return check icon if value is `True` or empty string otherwise.
:param value:
Value to check
"""
return Markup('<i class="icon-ok"></i>' if value else '')
+ def list_formatter(values):
+ """
+ Return string with comma separated values
+
+ :param values:
+ Value to check
+ """
+ return u', '.join(values)
+
+
DEFAULT_FORMATTERS = {
type(None): empty_formatter,
- bool: bool_formatter
+ bool: bool_formatter,
+ list: list_formatter,
}
|
Add extra type formatter for `list` type
|
## Code Before:
from jinja2 import Markup
def null_formatter(value):
"""
Return `NULL` as the string for `None` value
:param value:
Value to check
"""
return Markup('<i>NULL</i>')
def empty_formatter(value):
"""
Return empty string for `None` value
:param value:
Value to check
"""
return ''
def bool_formatter(value):
"""
Return check icon if value is `True` or empty string otherwise.
:param value:
Value to check
"""
return Markup('<i class="icon-ok"></i>' if value else '')
DEFAULT_FORMATTERS = {
type(None): empty_formatter,
bool: bool_formatter
}
## Instruction:
Add extra type formatter for `list` type
## Code After:
from jinja2 import Markup
def null_formatter(value):
"""
Return `NULL` as the string for `None` value
:param value:
Value to check
"""
return Markup('<i>NULL</i>')
def empty_formatter(value):
"""
Return empty string for `None` value
:param value:
Value to check
"""
return ''
def bool_formatter(value):
"""
Return check icon if value is `True` or empty string otherwise.
:param value:
Value to check
"""
return Markup('<i class="icon-ok"></i>' if value else '')
def list_formatter(values):
"""
Return string with comma separated values
:param values:
Value to check
"""
return u', '.join(values)
DEFAULT_FORMATTERS = {
type(None): empty_formatter,
bool: bool_formatter,
list: list_formatter,
}
|
# ... existing code ...
def list_formatter(values):
"""
Return string with comma separated values
:param values:
Value to check
"""
return u', '.join(values)
DEFAULT_FORMATTERS = {
# ... modified code ...
type(None): empty_formatter,
bool: bool_formatter,
list: list_formatter,
}
# ... rest of the code ...
|
c9d30e8873233adc84a6a7ed24423202e6538709
|
kindergarten-garden/kindergarten_garden.py
|
kindergarten-garden/kindergarten_garden.py
|
CHILDREN = ["Alice", "Bob", "Charlie", "David", "Eve", "Fred",
"Ginny", "Harriet", "Ileana", "Joseph", "Kincaid", "Larry"]
PLANTS = {"C": "Clover", "G": "Grass", "R": "Radishes", "V": "Violets"}
class Garden(object):
def __init__(self, garden, students=CHILDREN):
self.students = sorted(students)
rows = garden.split()
patches = [rows[0][i:i+2] + rows[1][i:i+2]
for i in range(0,2*len(self.students),2)]
self._garden = {s: [PLANTS[ch] for ch in p]
for s, p in zip(self.students, patches)}
def plants(self, student):
return self._garden[student]
|
CHILDREN = ["Alice", "Bob", "Charlie", "David", "Eve", "Fred",
"Ginny", "Harriet", "Ileana", "Joseph", "Kincaid", "Larry"]
PLANTS = {"C": "Clover", "G": "Grass", "R": "Radishes", "V": "Violets"}
class Garden(object):
def __init__(self, garden, students=CHILDREN):
self.students = sorted(students)
row1, row2 = garden.split()
patches = [row1[i:i+2] + row2[i:i+2]
for i in range(0,2*len(self.students),2)]
self._garden = {s: [PLANTS[ch] for ch in p]
for s, p in zip(self.students, patches)}
def plants(self, student):
return self._garden[student]
|
Use unpacking for simpler code
|
Use unpacking for simpler code
|
Python
|
agpl-3.0
|
CubicComet/exercism-python-solutions
|
CHILDREN = ["Alice", "Bob", "Charlie", "David", "Eve", "Fred",
"Ginny", "Harriet", "Ileana", "Joseph", "Kincaid", "Larry"]
PLANTS = {"C": "Clover", "G": "Grass", "R": "Radishes", "V": "Violets"}
class Garden(object):
def __init__(self, garden, students=CHILDREN):
self.students = sorted(students)
- rows = garden.split()
+ row1, row2 = garden.split()
- patches = [rows[0][i:i+2] + rows[1][i:i+2]
+ patches = [row1[i:i+2] + row2[i:i+2]
for i in range(0,2*len(self.students),2)]
self._garden = {s: [PLANTS[ch] for ch in p]
for s, p in zip(self.students, patches)}
def plants(self, student):
return self._garden[student]
|
Use unpacking for simpler code
|
## Code Before:
CHILDREN = ["Alice", "Bob", "Charlie", "David", "Eve", "Fred",
"Ginny", "Harriet", "Ileana", "Joseph", "Kincaid", "Larry"]
PLANTS = {"C": "Clover", "G": "Grass", "R": "Radishes", "V": "Violets"}
class Garden(object):
def __init__(self, garden, students=CHILDREN):
self.students = sorted(students)
rows = garden.split()
patches = [rows[0][i:i+2] + rows[1][i:i+2]
for i in range(0,2*len(self.students),2)]
self._garden = {s: [PLANTS[ch] for ch in p]
for s, p in zip(self.students, patches)}
def plants(self, student):
return self._garden[student]
## Instruction:
Use unpacking for simpler code
## Code After:
CHILDREN = ["Alice", "Bob", "Charlie", "David", "Eve", "Fred",
"Ginny", "Harriet", "Ileana", "Joseph", "Kincaid", "Larry"]
PLANTS = {"C": "Clover", "G": "Grass", "R": "Radishes", "V": "Violets"}
class Garden(object):
def __init__(self, garden, students=CHILDREN):
self.students = sorted(students)
row1, row2 = garden.split()
patches = [row1[i:i+2] + row2[i:i+2]
for i in range(0,2*len(self.students),2)]
self._garden = {s: [PLANTS[ch] for ch in p]
for s, p in zip(self.students, patches)}
def plants(self, student):
return self._garden[student]
|
# ... existing code ...
self.students = sorted(students)
row1, row2 = garden.split()
patches = [row1[i:i+2] + row2[i:i+2]
for i in range(0,2*len(self.students),2)]
# ... rest of the code ...
|
e93789084c03b2a566835006d6d5adaee3d4bbe6
|
silk/globals.py
|
silk/globals.py
|
__all__ = []
try:
from silk.webdoc import css, html, node
__all__.extend(('css', 'html', 'node'))
except ImportError:
pass
try:
from silk.webdb import (
AuthenticationError, BoolColumn, Column, DB, DataColumn,
DateTimeColumn, FloatColumn, IntColumn, RecordError, ReferenceColumn,
RowidColumn, SQLSyntaxError, StrColumn, Table, UnknownDriver, connect
)
__all__.extend((
'AuthenticationError', 'BoolColumn', 'Column', 'DB', 'DataColumn',
'DateTimeColumn', 'FloatColumn', 'IntColumn', 'RecordError',
'ReferenceColumn', 'RowidColumn', 'SQLSyntaxError', 'StrColumn',
'Table', 'UnknownDriver', 'connect'
))
except ImportError:
pass
try:
from silk.webreq import (
B64Document, BaseRouter, Document, FormData, HTTP, Header, HeaderList,
PathRouter, Query, Redirect, Response, TextView, URI
)
__all__.extend((
'B64Document', 'BaseRouter', 'Document', 'FormData', 'HTTP', 'Header',
'HeaderList', 'PathRouter', 'Query', 'Redirect', 'Response',
'TextView', 'URI'
))
except ImportError:
pass
|
__all__ = []
try:
from silk.webdoc import css, html, node
__all__ += ['css', 'html', 'node']
except ImportError:
pass
try:
from silk.webdb import (
AuthenticationError, BoolColumn, Column, DB, DataColumn,
DateTimeColumn, FloatColumn, IntColumn, RecordError, ReferenceColumn,
RowidColumn, SQLSyntaxError, StrColumn, Table, UnknownDriver, connect
)
__all__ += [
'AuthenticationError', 'BoolColumn', 'Column', 'DB', 'DataColumn',
'DateTimeColumn', 'FloatColumn', 'IntColumn', 'RecordError',
'ReferenceColumn', 'RowidColumn', 'SQLSyntaxError', 'StrColumn',
'Table', 'UnknownDriver', 'connect'
]
except ImportError:
pass
try:
from silk.webreq import (
B64Document, BaseRouter, Document, FormData, HTTP, Header, HeaderList,
PathRouter, Query, Redirect, Response, TextView, URI
)
__all__ += [
'B64Document', 'BaseRouter', 'Document', 'FormData', 'HTTP', 'Header',
'HeaderList', 'PathRouter', 'Query', 'Redirect', 'Response',
'TextView', 'URI'
]
except ImportError:
pass
|
Use += to modify __all__, to appease flake8
|
Use += to modify __all__, to appease flake8
|
Python
|
bsd-3-clause
|
orbnauticus/silk
|
__all__ = []
try:
from silk.webdoc import css, html, node
- __all__.extend(('css', 'html', 'node'))
+ __all__ += ['css', 'html', 'node']
except ImportError:
pass
try:
from silk.webdb import (
AuthenticationError, BoolColumn, Column, DB, DataColumn,
DateTimeColumn, FloatColumn, IntColumn, RecordError, ReferenceColumn,
RowidColumn, SQLSyntaxError, StrColumn, Table, UnknownDriver, connect
)
- __all__.extend((
+ __all__ += [
'AuthenticationError', 'BoolColumn', 'Column', 'DB', 'DataColumn',
'DateTimeColumn', 'FloatColumn', 'IntColumn', 'RecordError',
'ReferenceColumn', 'RowidColumn', 'SQLSyntaxError', 'StrColumn',
'Table', 'UnknownDriver', 'connect'
- ))
+ ]
except ImportError:
pass
try:
from silk.webreq import (
B64Document, BaseRouter, Document, FormData, HTTP, Header, HeaderList,
PathRouter, Query, Redirect, Response, TextView, URI
)
- __all__.extend((
+ __all__ += [
'B64Document', 'BaseRouter', 'Document', 'FormData', 'HTTP', 'Header',
'HeaderList', 'PathRouter', 'Query', 'Redirect', 'Response',
'TextView', 'URI'
- ))
+ ]
except ImportError:
pass
|
Use += to modify __all__, to appease flake8
|
## Code Before:
__all__ = []
try:
from silk.webdoc import css, html, node
__all__.extend(('css', 'html', 'node'))
except ImportError:
pass
try:
from silk.webdb import (
AuthenticationError, BoolColumn, Column, DB, DataColumn,
DateTimeColumn, FloatColumn, IntColumn, RecordError, ReferenceColumn,
RowidColumn, SQLSyntaxError, StrColumn, Table, UnknownDriver, connect
)
__all__.extend((
'AuthenticationError', 'BoolColumn', 'Column', 'DB', 'DataColumn',
'DateTimeColumn', 'FloatColumn', 'IntColumn', 'RecordError',
'ReferenceColumn', 'RowidColumn', 'SQLSyntaxError', 'StrColumn',
'Table', 'UnknownDriver', 'connect'
))
except ImportError:
pass
try:
from silk.webreq import (
B64Document, BaseRouter, Document, FormData, HTTP, Header, HeaderList,
PathRouter, Query, Redirect, Response, TextView, URI
)
__all__.extend((
'B64Document', 'BaseRouter', 'Document', 'FormData', 'HTTP', 'Header',
'HeaderList', 'PathRouter', 'Query', 'Redirect', 'Response',
'TextView', 'URI'
))
except ImportError:
pass
## Instruction:
Use += to modify __all__, to appease flake8
## Code After:
__all__ = []
try:
from silk.webdoc import css, html, node
__all__ += ['css', 'html', 'node']
except ImportError:
pass
try:
from silk.webdb import (
AuthenticationError, BoolColumn, Column, DB, DataColumn,
DateTimeColumn, FloatColumn, IntColumn, RecordError, ReferenceColumn,
RowidColumn, SQLSyntaxError, StrColumn, Table, UnknownDriver, connect
)
__all__ += [
'AuthenticationError', 'BoolColumn', 'Column', 'DB', 'DataColumn',
'DateTimeColumn', 'FloatColumn', 'IntColumn', 'RecordError',
'ReferenceColumn', 'RowidColumn', 'SQLSyntaxError', 'StrColumn',
'Table', 'UnknownDriver', 'connect'
]
except ImportError:
pass
try:
from silk.webreq import (
B64Document, BaseRouter, Document, FormData, HTTP, Header, HeaderList,
PathRouter, Query, Redirect, Response, TextView, URI
)
__all__ += [
'B64Document', 'BaseRouter', 'Document', 'FormData', 'HTTP', 'Header',
'HeaderList', 'PathRouter', 'Query', 'Redirect', 'Response',
'TextView', 'URI'
]
except ImportError:
pass
|
# ... existing code ...
from silk.webdoc import css, html, node
__all__ += ['css', 'html', 'node']
except ImportError:
# ... modified code ...
)
__all__ += [
'AuthenticationError', 'BoolColumn', 'Column', 'DB', 'DataColumn',
...
'Table', 'UnknownDriver', 'connect'
]
except ImportError:
...
__all__ += [
'B64Document', 'BaseRouter', 'Document', 'FormData', 'HTTP', 'Header',
...
'TextView', 'URI'
]
except ImportError:
# ... rest of the code ...
|
67c1855f75a3c29bc650c193235576f6b591c805
|
payment_redsys/__manifest__.py
|
payment_redsys/__manifest__.py
|
{
"name": "Pasarela de pago Redsys",
"category": "Payment Acquirer",
"summary": "Payment Acquirer: Redsys Implementation",
"version": "14.0.2.0.0",
"author": "Tecnativa," "Odoo Community Association (OCA)",
"website": "https://github.com/OCA/l10n-spain",
"depends": ["payment", "website_sale"],
"external_dependencies": {"python": ["Crypto.Cipher.DES3"]},
"data": [
"views/redsys.xml",
"views/payment_acquirer.xml",
"views/payment_redsys_templates.xml",
"data/payment_redsys.xml",
],
"license": "AGPL-3",
"installable": True,
}
|
{
"name": "Pasarela de pago Redsys",
"category": "Payment Acquirer",
"summary": "Payment Acquirer: Redsys Implementation",
"version": "14.0.2.0.0",
"author": "Tecnativa," "Odoo Community Association (OCA)",
"website": "https://github.com/OCA/l10n-spain",
"depends": ["payment", "website_sale"],
"external_dependencies": {"python": ["pycrypto"]},
"data": [
"views/redsys.xml",
"views/payment_acquirer.xml",
"views/payment_redsys_templates.xml",
"data/payment_redsys.xml",
],
"license": "AGPL-3",
"installable": True,
}
|
Put real package on pypi
|
[IMP] payment_redsys: Put real package on pypi
|
Python
|
agpl-3.0
|
cubells/l10n-spain,cubells/l10n-spain,cubells/l10n-spain
|
{
"name": "Pasarela de pago Redsys",
"category": "Payment Acquirer",
"summary": "Payment Acquirer: Redsys Implementation",
"version": "14.0.2.0.0",
"author": "Tecnativa," "Odoo Community Association (OCA)",
"website": "https://github.com/OCA/l10n-spain",
"depends": ["payment", "website_sale"],
- "external_dependencies": {"python": ["Crypto.Cipher.DES3"]},
+ "external_dependencies": {"python": ["pycrypto"]},
"data": [
"views/redsys.xml",
"views/payment_acquirer.xml",
"views/payment_redsys_templates.xml",
"data/payment_redsys.xml",
],
"license": "AGPL-3",
"installable": True,
}
|
Put real package on pypi
|
## Code Before:
{
"name": "Pasarela de pago Redsys",
"category": "Payment Acquirer",
"summary": "Payment Acquirer: Redsys Implementation",
"version": "14.0.2.0.0",
"author": "Tecnativa," "Odoo Community Association (OCA)",
"website": "https://github.com/OCA/l10n-spain",
"depends": ["payment", "website_sale"],
"external_dependencies": {"python": ["Crypto.Cipher.DES3"]},
"data": [
"views/redsys.xml",
"views/payment_acquirer.xml",
"views/payment_redsys_templates.xml",
"data/payment_redsys.xml",
],
"license": "AGPL-3",
"installable": True,
}
## Instruction:
Put real package on pypi
## Code After:
{
"name": "Pasarela de pago Redsys",
"category": "Payment Acquirer",
"summary": "Payment Acquirer: Redsys Implementation",
"version": "14.0.2.0.0",
"author": "Tecnativa," "Odoo Community Association (OCA)",
"website": "https://github.com/OCA/l10n-spain",
"depends": ["payment", "website_sale"],
"external_dependencies": {"python": ["pycrypto"]},
"data": [
"views/redsys.xml",
"views/payment_acquirer.xml",
"views/payment_redsys_templates.xml",
"data/payment_redsys.xml",
],
"license": "AGPL-3",
"installable": True,
}
|
# ... existing code ...
"depends": ["payment", "website_sale"],
"external_dependencies": {"python": ["pycrypto"]},
"data": [
# ... rest of the code ...
|
e743bcddbc53d51142f3e1277919a3f65afaad90
|
tests/conftest.py
|
tests/conftest.py
|
import base64
import betamax
import os
credentials = [os.environ.get('GH_USER', 'foo').encode(),
os.environ.get('GH_PASSWORD', 'bar').encode()]
with betamax.Betamax.configure() as config:
config.cassette_library_dir = 'tests/cassettes'
record_mode = 'never' if os.environ.get('TRAVIS_GH3') else 'once'
print('Record mode: {0}'.format(record_mode))
config.default_cassette_options['record_mode'] = record_mode
config.define_cassette_placeholder(
'<AUTH_TOKEN>',
os.environ.get('GH_AUTH', 'x' * 20)
)
config.define_cassette_placeholder(
'<BASIC_AUTH>',
base64.b64encode(b':'.join(credentials)).decode()
)
|
import base64
import betamax
import os
credentials = [os.environ.get('GH_USER', 'foo').encode(),
os.environ.get('GH_PASSWORD', 'bar').encode()]
with betamax.Betamax.configure() as config:
config.cassette_library_dir = 'tests/cassettes'
record_mode = 'never' if os.environ.get('TRAVIS_GH3') else 'once'
config.default_cassette_options['record_mode'] = record_mode
config.define_cassette_placeholder(
'<AUTH_TOKEN>',
os.environ.get('GH_AUTH', 'x' * 20)
)
config.define_cassette_placeholder(
'<BASIC_AUTH>',
base64.b64encode(b':'.join(credentials)).decode()
)
|
Revert "For travis, let us print the mode"
|
Revert "For travis, let us print the mode"
This reverts commit 0c8e9c36219214cf08b33c0ff1812e6cefa53353.
|
Python
|
bsd-3-clause
|
sigmavirus24/github3.py,agamdua/github3.py,christophelec/github3.py,jim-minter/github3.py,ueg1990/github3.py,degustaf/github3.py,balloob/github3.py,h4ck3rm1k3/github3.py,icio/github3.py,wbrefvem/github3.py,krxsky/github3.py,itsmemattchung/github3.py
|
import base64
import betamax
import os
credentials = [os.environ.get('GH_USER', 'foo').encode(),
os.environ.get('GH_PASSWORD', 'bar').encode()]
with betamax.Betamax.configure() as config:
config.cassette_library_dir = 'tests/cassettes'
record_mode = 'never' if os.environ.get('TRAVIS_GH3') else 'once'
- print('Record mode: {0}'.format(record_mode))
config.default_cassette_options['record_mode'] = record_mode
config.define_cassette_placeholder(
'<AUTH_TOKEN>',
os.environ.get('GH_AUTH', 'x' * 20)
)
config.define_cassette_placeholder(
'<BASIC_AUTH>',
base64.b64encode(b':'.join(credentials)).decode()
)
|
Revert "For travis, let us print the mode"
|
## Code Before:
import base64
import betamax
import os
credentials = [os.environ.get('GH_USER', 'foo').encode(),
os.environ.get('GH_PASSWORD', 'bar').encode()]
with betamax.Betamax.configure() as config:
config.cassette_library_dir = 'tests/cassettes'
record_mode = 'never' if os.environ.get('TRAVIS_GH3') else 'once'
print('Record mode: {0}'.format(record_mode))
config.default_cassette_options['record_mode'] = record_mode
config.define_cassette_placeholder(
'<AUTH_TOKEN>',
os.environ.get('GH_AUTH', 'x' * 20)
)
config.define_cassette_placeholder(
'<BASIC_AUTH>',
base64.b64encode(b':'.join(credentials)).decode()
)
## Instruction:
Revert "For travis, let us print the mode"
## Code After:
import base64
import betamax
import os
credentials = [os.environ.get('GH_USER', 'foo').encode(),
os.environ.get('GH_PASSWORD', 'bar').encode()]
with betamax.Betamax.configure() as config:
config.cassette_library_dir = 'tests/cassettes'
record_mode = 'never' if os.environ.get('TRAVIS_GH3') else 'once'
config.default_cassette_options['record_mode'] = record_mode
config.define_cassette_placeholder(
'<AUTH_TOKEN>',
os.environ.get('GH_AUTH', 'x' * 20)
)
config.define_cassette_placeholder(
'<BASIC_AUTH>',
base64.b64encode(b':'.join(credentials)).decode()
)
|
...
record_mode = 'never' if os.environ.get('TRAVIS_GH3') else 'once'
...
|
62d7924f6f5097845a21408e975cae1dfff01c1c
|
android/app/src/main/assets/python/enamlnative/widgets/analog_clock.py
|
android/app/src/main/assets/python/enamlnative/widgets/analog_clock.py
|
'''
Copyright (c) 2017, Jairus Martin.
Distributed under the terms of the MIT License.
The full license is in the file COPYING.txt, distributed with this software.
Created on May 20, 2017
@author: jrm
'''
from atom.api import (
Typed, ForwardTyped, Unicode, observe
)
from enaml.core.declarative import d_
from .text_view import TextView, ProxyTextView
class ProxyAnalogClock(ProxyTextView):
""" The abstract definition of a proxy AnalogClock object.
"""
#: A reference to the Label declaration.
declaration = ForwardTyped(lambda: AnalogClock)
class AnalogClock(TextView):
""" A simple control for displaying an AnalogClock
"""
#: A reference to the proxy object.
proxy = Typed(ProxyAnalogClock)
|
'''
Copyright (c) 2017, Jairus Martin.
Distributed under the terms of the MIT License.
The full license is in the file COPYING.txt, distributed with this software.
Created on May 20, 2017
@author: jrm
'''
from atom.api import (
Typed, ForwardTyped, Unicode, observe
)
from enaml.core.declarative import d_
from .view import View, ProxyView
class ProxyAnalogClock(ProxyView):
""" The abstract definition of a proxy AnalogClock object.
"""
#: A reference to the Label declaration.
declaration = ForwardTyped(lambda: AnalogClock)
class AnalogClock(View):
""" A simple control for displaying an AnalogClock
"""
#: A reference to the proxy object.
proxy = Typed(ProxyAnalogClock)
|
Use correct parent class for clock
|
Use correct parent class for clock
|
Python
|
mit
|
codelv/enaml-native,codelv/enaml-native,codelv/enaml-native,codelv/enaml-native
|
'''
Copyright (c) 2017, Jairus Martin.
Distributed under the terms of the MIT License.
The full license is in the file COPYING.txt, distributed with this software.
Created on May 20, 2017
@author: jrm
'''
from atom.api import (
Typed, ForwardTyped, Unicode, observe
)
from enaml.core.declarative import d_
- from .text_view import TextView, ProxyTextView
+ from .view import View, ProxyView
- class ProxyAnalogClock(ProxyTextView):
+ class ProxyAnalogClock(ProxyView):
""" The abstract definition of a proxy AnalogClock object.
"""
#: A reference to the Label declaration.
declaration = ForwardTyped(lambda: AnalogClock)
- class AnalogClock(TextView):
+ class AnalogClock(View):
""" A simple control for displaying an AnalogClock
"""
#: A reference to the proxy object.
proxy = Typed(ProxyAnalogClock)
|
Use correct parent class for clock
|
## Code Before:
'''
Copyright (c) 2017, Jairus Martin.
Distributed under the terms of the MIT License.
The full license is in the file COPYING.txt, distributed with this software.
Created on May 20, 2017
@author: jrm
'''
from atom.api import (
Typed, ForwardTyped, Unicode, observe
)
from enaml.core.declarative import d_
from .text_view import TextView, ProxyTextView
class ProxyAnalogClock(ProxyTextView):
""" The abstract definition of a proxy AnalogClock object.
"""
#: A reference to the Label declaration.
declaration = ForwardTyped(lambda: AnalogClock)
class AnalogClock(TextView):
""" A simple control for displaying an AnalogClock
"""
#: A reference to the proxy object.
proxy = Typed(ProxyAnalogClock)
## Instruction:
Use correct parent class for clock
## Code After:
'''
Copyright (c) 2017, Jairus Martin.
Distributed under the terms of the MIT License.
The full license is in the file COPYING.txt, distributed with this software.
Created on May 20, 2017
@author: jrm
'''
from atom.api import (
Typed, ForwardTyped, Unicode, observe
)
from enaml.core.declarative import d_
from .view import View, ProxyView
class ProxyAnalogClock(ProxyView):
""" The abstract definition of a proxy AnalogClock object.
"""
#: A reference to the Label declaration.
declaration = ForwardTyped(lambda: AnalogClock)
class AnalogClock(View):
""" A simple control for displaying an AnalogClock
"""
#: A reference to the proxy object.
proxy = Typed(ProxyAnalogClock)
|
// ... existing code ...
from .view import View, ProxyView
// ... modified code ...
class ProxyAnalogClock(ProxyView):
""" The abstract definition of a proxy AnalogClock object.
...
class AnalogClock(View):
""" A simple control for displaying an AnalogClock
// ... rest of the code ...
|
dcd36fab023ac2530cbfa17449e3ce8f61ad6bdc
|
ssl-cert-parse.py
|
ssl-cert-parse.py
|
import datetime
import ssl
import OpenSSL
def GetCert(SiteName, Port):
return ssl.get_server_certificate((SiteName, Port))
def ParseCert(CertRaw):
Cert = OpenSSL.crypto.load_certificate(
OpenSSL.crypto.FILETYPE_PEM, CertRaw)
print(str(Cert.get_subject())[18:-2])
print(datetime.datetime.strptime(str(Cert.get_notBefore())[2:-1],
'%Y%m%d%H%M%SZ'))
print(datetime.datetime.strptime(str(Cert.get_notAfter())[2:-1],
'%Y%m%d%H%M%SZ'))
print(str(Cert.get_issuer())[18:-2])
CertRaw = GetCert('some.domain.tld', 443)
print(CertRaw)
ParseCert(CertRaw)
|
import datetime
import ssl
import OpenSSL
def GetCert(SiteName, Port):
return ssl.get_server_certificate((SiteName, Port))
def ParseCert(CertRaw):
Cert = OpenSSL.crypto.load_certificate(
OpenSSL.crypto.FILETYPE_PEM, CertRaw)
CertSubject = str(Cert.get_subject())[18:-2]
CertStartDate = datetime.datetime.strptime(str(Cert.get_notBefore())[2:-1],
'%Y%m%d%H%M%SZ')
CertEndDate = datetime.datetime.strptime(str(Cert.get_notAfter())[2:-1],
'%Y%m%d%H%M%SZ')
CertIssuer = str(Cert.get_issuer())[18:-2]
return {'CertSubject': CertIssuer, 'CertStartDate': CertStartDate,
'CertEndDate': CertEndDate, 'CertIssuer': CertIssuer}
CertRaw = GetCert('some.domain.tld', 443)
print(CertRaw)
Out = ParseCert(CertRaw)
print(Out)
print(Out['CertSubject'])
print(Out['CertStartDate'])
|
Fix ParseCert() function, add variables, add a return statement
|
Fix ParseCert() function, add variables, add a return statement
|
Python
|
apache-2.0
|
ivuk/ssl-cert-parse
|
import datetime
import ssl
import OpenSSL
def GetCert(SiteName, Port):
return ssl.get_server_certificate((SiteName, Port))
def ParseCert(CertRaw):
Cert = OpenSSL.crypto.load_certificate(
OpenSSL.crypto.FILETYPE_PEM, CertRaw)
+
- print(str(Cert.get_subject())[18:-2])
+ CertSubject = str(Cert.get_subject())[18:-2]
- print(datetime.datetime.strptime(str(Cert.get_notBefore())[2:-1],
+ CertStartDate = datetime.datetime.strptime(str(Cert.get_notBefore())[2:-1],
- '%Y%m%d%H%M%SZ'))
+ '%Y%m%d%H%M%SZ')
- print(datetime.datetime.strptime(str(Cert.get_notAfter())[2:-1],
+ CertEndDate = datetime.datetime.strptime(str(Cert.get_notAfter())[2:-1],
- '%Y%m%d%H%M%SZ'))
+ '%Y%m%d%H%M%SZ')
- print(str(Cert.get_issuer())[18:-2])
+ CertIssuer = str(Cert.get_issuer())[18:-2]
+
+ return {'CertSubject': CertIssuer, 'CertStartDate': CertStartDate,
+ 'CertEndDate': CertEndDate, 'CertIssuer': CertIssuer}
CertRaw = GetCert('some.domain.tld', 443)
+
print(CertRaw)
- ParseCert(CertRaw)
+ Out = ParseCert(CertRaw)
+ print(Out)
+ print(Out['CertSubject'])
+ print(Out['CertStartDate'])
+
|
Fix ParseCert() function, add variables, add a return statement
|
## Code Before:
import datetime
import ssl
import OpenSSL
def GetCert(SiteName, Port):
return ssl.get_server_certificate((SiteName, Port))
def ParseCert(CertRaw):
Cert = OpenSSL.crypto.load_certificate(
OpenSSL.crypto.FILETYPE_PEM, CertRaw)
print(str(Cert.get_subject())[18:-2])
print(datetime.datetime.strptime(str(Cert.get_notBefore())[2:-1],
'%Y%m%d%H%M%SZ'))
print(datetime.datetime.strptime(str(Cert.get_notAfter())[2:-1],
'%Y%m%d%H%M%SZ'))
print(str(Cert.get_issuer())[18:-2])
CertRaw = GetCert('some.domain.tld', 443)
print(CertRaw)
ParseCert(CertRaw)
## Instruction:
Fix ParseCert() function, add variables, add a return statement
## Code After:
import datetime
import ssl
import OpenSSL
def GetCert(SiteName, Port):
return ssl.get_server_certificate((SiteName, Port))
def ParseCert(CertRaw):
Cert = OpenSSL.crypto.load_certificate(
OpenSSL.crypto.FILETYPE_PEM, CertRaw)
CertSubject = str(Cert.get_subject())[18:-2]
CertStartDate = datetime.datetime.strptime(str(Cert.get_notBefore())[2:-1],
'%Y%m%d%H%M%SZ')
CertEndDate = datetime.datetime.strptime(str(Cert.get_notAfter())[2:-1],
'%Y%m%d%H%M%SZ')
CertIssuer = str(Cert.get_issuer())[18:-2]
return {'CertSubject': CertIssuer, 'CertStartDate': CertStartDate,
'CertEndDate': CertEndDate, 'CertIssuer': CertIssuer}
CertRaw = GetCert('some.domain.tld', 443)
print(CertRaw)
Out = ParseCert(CertRaw)
print(Out)
print(Out['CertSubject'])
print(Out['CertStartDate'])
|
// ... existing code ...
OpenSSL.crypto.FILETYPE_PEM, CertRaw)
CertSubject = str(Cert.get_subject())[18:-2]
CertStartDate = datetime.datetime.strptime(str(Cert.get_notBefore())[2:-1],
'%Y%m%d%H%M%SZ')
CertEndDate = datetime.datetime.strptime(str(Cert.get_notAfter())[2:-1],
'%Y%m%d%H%M%SZ')
CertIssuer = str(Cert.get_issuer())[18:-2]
return {'CertSubject': CertIssuer, 'CertStartDate': CertStartDate,
'CertEndDate': CertEndDate, 'CertIssuer': CertIssuer}
// ... modified code ...
CertRaw = GetCert('some.domain.tld', 443)
print(CertRaw)
Out = ParseCert(CertRaw)
print(Out)
print(Out['CertSubject'])
print(Out['CertStartDate'])
// ... rest of the code ...
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.